def handler(event, context): if event['RequestType'] == 'Delete': return custom_resource_response.success_response({'Arn': ''}, '') props = properties.load(event, { 'ConfigurationBucket': properties.String(), 'ConfigurationKey': properties.String(), 'LogicalPoolName': properties.String(), 'RoleType': properties.String(default=""), 'Path': properties.String(), 'AssumeRolePolicyDocument': properties.Dictionary() }) stack_manager = stack_info.StackInfoManager() stack = stack_manager.get_stack_info(event['StackId']) identity_client = identity_pool.get_identity_client() cognito_pool_info = aws_utils.get_cognito_pool_from_file(props.ConfigurationBucket, props.ConfigurationKey, props.LogicalPoolName, stack) arn = '' if cognito_pool_info: response = identity_client.get_identity_pool_roles(IdentityPoolId=cognito_pool_info['PhysicalResourceId']) arn = response.get("Roles", {}).get(props.RoleType, "") else: name = "{}{}Role".format(stack.stack_name, event['LogicalResourceId']) arn=create_role(name, props) return custom_resource_response.success_response({'Arn': arn}, arn)
def test_with_non_dict(self): target = properties.Dictionary() with self.assertRaises(properties.ValidationError) as e: value = target('Test', 'string') self.assertIn('Test', e.exception.message)
def test_with_None_and_no_default(self): target = properties.Dictionary() with self.assertRaises(properties.ValidationError) as e: value = target('Test', None) self.assertIn('Test', e.exception.message)
def handler(event, context): props = properties.load(event, { 'Input': properties.Dictionary(), }) stack_name = aws_utils.get_stack_name_from_stack_arn(event['StackId']) physical_resource_id = stack_name + '-' + event['LogicalResourceId'] output = _process_dict(props.Input) return custom_resource_response.success_response(output, physical_resource_id)
def handler(event, context): """Entry point for the Custom::CognitoIdPoolSharedRole resource handler.""" stack_id = event['StackId'] if event['RequestType'] == 'Delete': return custom_resource_response.success_response({'Arn': ''}, '') props = properties.load( event, { 'ConfigurationBucket': properties.String(), 'ConfigurationKey': properties.String(), 'LogicalPoolName': properties.String(), 'RoleType': properties.String(default=""), 'Path': properties.String(), 'AssumeRolePolicyDocument': properties.Dictionary() }) stack_manager = stack_info.StackInfoManager() stack = stack_manager.get_stack_info(stack_id) identity_client = identity_pool.get_identity_client() cognito_pool_info = aws_utils.get_cognito_pool_from_file( props.ConfigurationBucket, props.ConfigurationKey, props.LogicalPoolName, stack) arn = '' if cognito_pool_info: response = identity_client.get_identity_pool_roles( IdentityPoolId=cognito_pool_info['PhysicalResourceId']) arn = response.get("Roles", {}).get(props.RoleType, "") else: # Set up resource tags for all resources created tags = [{ "Key": constant.PROJECT_NAME_TAG, "Value": stack.project_stack.project_name }, { "Key": constant.STACK_ID_TAG, "Value": stack_id }] name = "{}{}Role".format(stack.stack_name, event['LogicalResourceId']) arn = _create_role(name, props, tags) return custom_resource_response.success_response({'Arn': arn}, arn)
do_not_log_args=['body']) API_GATEWAY_SERVICE_NAME = 'apigateway.amazonaws.com' STAGE_NAME = 'api' PROPERTY_SCHEMA = { 'ConfigurationBucket': properties.String(), 'ConfigurationKey': properties.String(), 'CacheClusterEnabled': properties.Boolean(default=False), 'CacheClusterSize': properties.String(default='0.5'), 'SwaggerSettings': properties.Dictionary(default={}), 'MethodSettings': properties.Object( default={}, schema={ '*': properties.Object( default={}, # path, can be * schema={ '*': properties.Object( default={}, # method, can be * schema={ 'cacheDataEncrypted': properties.Boolean(default=False), 'cacheTtlInSeconds':
# These are mostly Lambda configuration properties and should follow existing names and restrictions _handler_properties_configuration = { 'MemorySize': properties.Integer(default=_default_lambda_memory), # MB: Must be a multiple of 64MB as per Lambda spec 'Timeout': properties.Integer(default=_default_lambda_timeout), # Seconds: Must be between 3-900 as per Lambda spec } # Schema for ArnHandler or FunctionHandlers for core resource types _handler_schema = { 'Function': properties.String(""), 'HandlerFunctionConfiguration': properties.Object(default={}, schema=_handler_properties_configuration), 'PolicyStatement': properties.ObjectOrListOfObject(default=[], schema={ 'Sid': properties.String(""), 'Action': properties.StringOrListOfString(), 'Resource': properties.StringOrListOfString(default=[]), 'Effect': properties.String(), 'Condition': properties.Dictionary(default={}) }) } # Schema for the CoreResourceTypes custom CloudFormation resources. # Note: LambdaConfiguration and LambdaTimeout are globally applied to all custom resource Lambdas. To change Memory and Timeout for a given Lambda # use a HandlerFunctionConfiguration which overrides the global lambda configs # # Note: Need to define expected fields here to avoid "Property is not supported" failures during definition validation _schema = { 'LambdaConfiguration': properties.Dictionary(default={}), 'LambdaTimeout': properties.Integer(default=_default_lambda_timeout), 'Definitions': properties.Object(default=None, schema={ '*': properties.Object(default={}, schema={ 'PermissionMetadata': properties.Object(default={}, schema={ 'RestrictActions': properties.StringOrListOfString(default=[]),
def handler(event, context): """Entry point for the Custom::CognitoUserPool resource handler.""" stack_id = event['StackId'] props = properties.load( event, { 'ClientApps': properties.StringOrListOfString(), 'ExplicitAuthFlows': properties.StringOrListOfString(default=[]), 'RefreshTokenValidity': properties.String('30'), 'ConfigurationKey': properties.String( ), # this is only here to force the resource handler to execute on each update to the deployment 'LambdaConfig': properties.Dictionary({}), 'PoolName': properties.String(), 'Groups': properties.ObjectOrListOfObject( default=[], schema={ 'Name': properties.String(), 'Description': properties.String(''), 'Role': properties.String(), 'Precedence': properties.String('99') }), 'AllowAdminCreateUserOnly': properties.String('') }) # give the identity pool a unique name per stack stack_manager = stack_info.StackInfoManager() stack = stack_manager.get_stack_info(stack_id) stack_name = stack.stack_name pool_name = props.PoolName.replace('-', ' ') pool_name = stack_name + pool_name cognito_idp_client = user_pool.get_idp_client() pool_id = custom_resource_utils.get_embedded_physical_id( event.get('PhysicalResourceId')) found_pool = user_pool.get_user_pool(pool_id) # Set up tags for all resources created tags = { constant.PROJECT_NAME_TAG: stack.project_stack.project_name, constant.STACK_ID_TAG: stack_id } request_type = event['RequestType'] if request_type == 'Delete': if found_pool is not None: cognito_idp_client.delete_user_pool(UserPoolId=pool_id) data = {} else: # if the pool exists just update it, otherwise create a new one mfa_config = 'OFF' # MFA is currently unsupported by Lumberyard # Users are automatically prompted to verify these things. # At least one auto-verified thing (email or phone) is required to allow password recovery. auto_verified_attributes = ['email'] client_app_data = {} lambda_config = props.LambdaConfig user_pool.validate_identity_metadata(stack_manager, stack_id, event['LogicalResourceId'], props.ClientApps) admin_create_user_config = __get_admin_create_user_config( props.AllowAdminCreateUserOnly) print(json.dumps(admin_create_user_config)) if found_pool is not None: # Update response = cognito_idp_client.update_user_pool( UserPoolId=pool_id, MfaConfiguration=mfa_config, AutoVerifiedAttributes=auto_verified_attributes, LambdaConfig=lambda_config, AdminCreateUserConfig=admin_create_user_config, UserPoolTags=tags) existing_client_apps = user_pool.get_client_apps(pool_id) client_app_data = update_client_apps(pool_id, props.ClientApps, existing_client_apps, False, props.ExplicitAuthFlows, props.RefreshTokenValidity) response = cognito_idp_client.list_groups(UserPoolId=pool_id) found_groups = {} for actual_group in response['Groups']: group_name = actual_group['GroupName'] for requested_group in props.Groups: # does the group exist in the resource template if group_name == requested_group.Name: found_groups.update({group_name: True}) break # delete the group as it is no longer in the resource template if group_name not in found_groups: cognito_idp_client.delete_group( GroupName=actual_group['GroupName'], UserPoolId=pool_id) print("Found groups=>{}".format(json.dumps(found_groups))) # iterate the groups defined in the user pool resource template for group in props.Groups: # update the group as it is currently a group in the user pool group_definition = __generate_group_definition(pool_id, group) print("Group '{}' is defined by {}".format( group.Name, json.dumps(group_definition))) if group.Name in found_groups: cognito_idp_client.update_group(**group_definition) else: # group is a new group on the user pool cognito_idp_client.create_group(**group_definition) else: # Create response = cognito_idp_client.create_user_pool( PoolName=pool_name, MfaConfiguration=mfa_config, AutoVerifiedAttributes=auto_verified_attributes, LambdaConfig=lambda_config, AdminCreateUserConfig=admin_create_user_config, UserPoolTags=tags) pool_id = response['UserPool']['Id'] print('User pool creation response: {}'.format(response)) for group in props.Groups: group_definition = __generate_group_definition(pool_id, group) print("Group '{}' is defined by {}".format( group.Name, json.dumps(group_definition))) cognito_idp_client.create_group(**group_definition) client_app_data = update_client_apps(pool_id, props.ClientApps, [], False, props.ExplicitAuthFlows, props.RefreshTokenValidity) updated_resources = { stack_id: { event['LogicalResourceId']: { 'physical_id': pool_id, 'client_apps': { client_app['ClientName']: { 'client_id': client_app['ClientId'] } for client_app in client_app_data['Created'] + client_app_data['Updated'] } } } } identity_pool.update_cognito_identity_providers( stack_manager, stack_id, pool_id, updated_resources) data = { 'UserPoolName': pool_name, 'UserPoolId': pool_id, 'ClientApps': client_app_data, } physical_resource_id = pool_id return custom_resource_response.success_response(data, physical_resource_id)
from botocore.exceptions import ClientError from cgf_service_directory import ServiceDirectory cfg = botocore.config.Config(read_timeout=70, connect_timeout=70) s3 = aws_utils.ClientWrapper(boto3.client('s3', config = cfg)) api_gateway = aws_utils.ClientWrapper(boto3.client('apigateway', config = cfg), do_not_log_args=['body']) API_GATEWAY_SERVICE_NAME = 'apigateway.amazonaws.com' STAGE_NAME = 'api' PROPERTY_SCHEMA = { 'ConfigurationBucket': properties.String(), 'ConfigurationKey': properties.String(), 'CacheClusterEnabled': properties.Boolean( default = False ), 'CacheClusterSize': properties.String( default = '0.5' ), 'SwaggerSettings': properties.Dictionary( default={} ), 'MethodSettings': properties.Object( default={}, schema={ '*': properties.Object( default={}, # path, can be * schema={ '*': properties.Object( default={}, # method, can be * schema={ 'cacheDataEncrypted': properties.Boolean( default = False ), 'cacheTtlInSeconds': properties.Integer( default = 300 ), 'cachingEnabled': properties.Boolean( default = False ), 'dataTraceEnabled': properties.Boolean( default = False ), 'loggingLevel': properties.String( default='OFF' ), 'metricsEnabled': properties.Boolean( default = False ), 'throttlingBurstLimit': properties.Integer( default = 500 ), 'throttlingRateLimit': properties.Integer( default = 1000 ), }
def test_with_None_and_default(self): target = properties.Dictionary(default={'a': 2}) value = target('Test', None) self.assertEqual(value, {'a': 2})
def test_with_dict_and_no_default(self): target = properties.Dictionary() value = target('Test', {'a': 1}) self.assertEqual(value, {'a': 1})
# Schema for ArnHandler or FunctionHandlers for core resource types _handler_schema = { 'Function': properties.String(""), 'HandlerFunctionConfiguration': properties.Object(default={}, schema=_handler_properties_configuration), 'PolicyStatement': properties.ObjectOrListOfObject( default=[], schema={ 'Sid': properties.String(""), 'Action': properties.StringOrListOfString(), 'Resource': properties.StringOrListOfString(default=[]), 'Effect': properties.String(), 'Condition': properties.Dictionary(default={}) }) } # Schema for the CoreResourceTypes custom CloudFormation resources. # Note: LambdaConfiguration and LambdaTimeout are globally applied to all custom resource Lambdas. To change Memory and Timeout for a given Lambda # use a HandlerFunctionConfiguration which overrides the global lambda configs # # Note: Need to define expected fields here to avoid "Property is not supported" failures during definition validation _schema = { 'LambdaConfiguration': properties.Dictionary(default={}), 'LambdaTimeout': properties.Integer(default=_default_lambda_timeout), 'Definitions': properties.Object(