"""Lambda function module.""" import os import common_config import sns # noqa import util # noqa from constants import common from constants import general from constants import error def validate_size(size): """Validate file size. Args: size (int): S3 file size Returns: bool: validation result """ return size <= general.MAX_ALLOWED_FILE_SIZE def validate_extension(extension): """Validate file extension. Args: extension (str): S3 file extension Returns: bool: validation result """ return extension.lower() in general.ALLOWED_FILE_EXTENSIONS def validate_path(key): """Validate file path. Args: key (str): S3 file key Returns: bool: validation result """ head, tail = os.path.split(key) return head == common_config.S3_BUCKET_FOLDER def validate_file(s3_object): """Validate file attributes. Args: s3_object (dict): Attributes of the file (s3.object) Returns: str: Error message or empty string (in case of success) """ if not validate_path(s3_object['key']): return error.INVALID_PATH_MSG if not validate_size(s3_object['size']): return error.INVALID_SIZE_MSG parsed_attrs = util.parse_file_key(s3_object['key']) if not parsed_attrs: return error.INVALID_NAME_MSG if not validate_extension(parsed_attrs['extension']): return error.INVALID_EXTENSION_MSG return '' def handler(event, context): """Lambda entry point.""" if common_config.IGNORE_ALL_EVENTS is not None: common_config.logger.warning(common.IGNORE_MESSAGE) return s3_object = event['Records'][0]['s3']['object'] key = s3_object.get('key') common_config.logger.info( 'Starting verification process for {}'.format(key)) validation_result = validate_file(s3_object) message = { 's3_event': event, 'attachment_attrs': util.parse_file_key(s3_object['key']) } if validation_result: error_message = 'Verification error: {} {}'.format( key, validation_result) common_config.logger.info(error_message) message.update({ 'status': 'ERROR', 'detailed': error_message}) sns.send_notification( common_config.SNS_ARN_FAIL, message) else: common_config.logger.info('Verification successfully finished.') sns.send_notification( common_config.SNS_ARN_SUCCESS, message)