"""Lambda sanitise-rds-data function module.""" from lambdacommon.common_config import logger import sentry_sdk from sentry_sdk.integrations.aws_lambda import AwsLambdaIntegration import config from src.logic import database from src.logic import mysql from src.logic import postgresql from src.logic import secrets if config.SENTRY_DSN: sentry_sdk.init( dsn=config.SENTRY_DSN, environment=config.ENVIRONMENT, integrations=[AwsLambdaIntegration(timeout_warning=True)] ) def _get_engine_logic(engine): """Return the sanitisation logic module for the given database engine. The engine is the value reported by RDS (e.g. mysql, aurora-mysql, postgres, aurora-postgresql). MySQL and PostgreSQL logic modules expose the same copy_users() and run_scripts() interface. """ if engine is None: raise UnsupportedEngine( 'No engine provided in event; cannot select sanitisation logic') if 'mysql' in engine: return mysql if 'postgres' in engine: return postgresql raise UnsupportedEngine(f'Unsupported database engine: {engine}') def handler(event, context): """Lambda entry point.""" try: scripts_dir = event.get('scripts_dir') engine = event.get('engine') logic = _get_engine_logic(engine) logger.info(f'Using {engine} sanitisation logic') users_source_db_name = event['users_source_db']['name'] users_source_db_type = event['users_source_db']['type'] target_db_name = event['target_db']['name'] target_db_type = event['target_db']['type'] logger.info( f'Resetting master credentials for {users_source_db_name}, ' f'type: {users_source_db_type}') source_db_credentials = database.reset_rds_master_credentials( users_source_db_name, users_source_db_type, wait=False) logger.info( f'Resetting master credentials for {target_db_name}, ' f'type: {target_db_type}') target_db_credentials = database.reset_rds_master_credentials( target_db_name, target_db_type, wait=False) database.wait_for_pending_modifications( users_source_db_name, users_source_db_type) database.wait_for_pending_modifications( target_db_name, target_db_type) role_passwords = secrets.get_role_passwords(target_db_name) logger.info( f'Copying users from {users_source_db_name} to {target_db_name}') users_created = logic.copy_users( source_db_credentials, target_db_credentials, role_passwords) if scripts_dir: logger.info(f'Running sanitisation scripts from {scripts_dir}') scripts_run = logic.run_scripts(target_db_credentials, scripts_dir) else: logger.info( 'Not running sanitisation scripts as no scripts_dir provided.') scripts_run = 0 return { 'scripts_run': scripts_run, 'users_created': users_created } except Exception as e: logger.exception(str(e)) raise e class UnsupportedEngine(Exception): """Exception raised when the database engine is not supported.""" pass