示例#1
0
    def test_with_empty_list(self):

        target = properties.ObjectOrListOfObject(
            schema={'prop': properties.String()})
        value = target('Test', [])

        self.assertEqual(len(value), 0)
示例#2
0
    def test_with_None_and_default_object(self):

        target = properties.ObjectOrListOfObject(
            schema={'prop': properties.String()}, default={'prop': 'value'})
        value = target('Test', None)

        self.assertEqual(len(value), 1)
        self.assertEqual(value[0].prop, 'value')
示例#3
0
    def test_with_invalid_object_in_list(self):

        target = properties.ObjectOrListOfObject(
            schema={'prop': properties.String()})

        with self.assertRaises(properties.ValidationError) as e:
            value = target('Test', [{'prop': 1234}])

        self.assertIn('Test', e.exception.message)
示例#4
0
    def test_with_None_and_no_default(self):

        target = properties.ObjectOrListOfObject(
            schema={'prop': properties.String()})

        with self.assertRaises(properties.ValidationError) as e:
            value = target('Test', None)

        self.assertIn('Test', e.exception.message)
示例#5
0
    def test_with_object_list(self):

        target = properties.ObjectOrListOfObject(
            schema={'prop': properties.String()})
        value = target('Test', [{'prop': 'value1'}, {'prop': 'value2'}])

        self.assertEqual(len(value), 2)
        self.assertEqual(value[0].prop, 'value1')
        self.assertEqual(value[1].prop, 'value2')
PROPERTIES_SCHEMA = {
    'ConfigurationBucket':
    properties.String(),
    'ConfigurationKey':
    properties.String(),
    'FunctionName':
    properties.String(),
    'Settings':
    properties.Object(default={}, schema={'*': properties.String()}),
    'Runtime':
    properties.String(),
    'Services':
    properties.ObjectOrListOfObject(default=[],
                                    schema={
                                        'InterfaceId':
                                        properties.String(),
                                        'Optional':
                                        properties.Boolean(default=False)
                                    }),
    'IgnoreAppendingSettingsToZip':
    properties.Boolean(default=False)
}


def handler(event, context):
    props = properties.load(event, PROPERTIES_SCHEMA)

    request_type = event['RequestType']
    stack_arn = event['StackId']
    logical_role_name = props.FunctionName
    stack_manager = stack_info.StackInfoManager()
# Schema for _handler_properties_configuration
# Set these values to increase memory and timeout values for a given custom resource Lambda
# 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={
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)
示例#9
0
        "Allow",
        'Action':
        ["logs:CreateLogGroup", "logs:CreateLogStream", "logs:PutLogEvents"],
        'Resource':
        "arn:aws:logs:*:*:*"
    }]
}

_handler_schema = {
    'Function':
    properties.String(""),
    'PolicyStatement':
    properties.ObjectOrListOfObject(
        default=[],
        schema={
            'Sid': properties.String(""),
            'Action': properties.StringOrListOfString(),
            'Resource': properties.StringOrListOfString(default=[]),
            'Effect': properties.String()
        })
}

_schema = {
    'LambdaConfiguration':
    properties.Dictionary(default={}),
    'LambdaTimeout':
    properties.Integer(default=10),
    'Definitions':
    properties.Object(
        default=None,
        schema={
            '*':