예제 #1
0
 def test_sam_injects_policy(self, sample_app):
     function = models.LambdaFunction(
         resource_name='foo',
         function_name='app-dev-foo',
         environment_variables={},
         runtime='python27',
         handler='app.app',
         tags={'foo': 'bar'},
         timeout=120,
         memory_size=128,
         deployment_package=models.DeploymentPackage(filename='foo.zip'),
         role=models.ManagedIAMRole(
             resource_name='role',
             role_name='app-role',
             trust_policy={},
             policy=models.AutoGenIAMPolicy(document={'iam': 'policy'}),
         ))
     template = self.template_gen.generate_sam_template([function])
     cfn_resource = list(template['Resources'].values())[0]
     assert cfn_resource == {
         'Type': 'AWS::Serverless::Function',
         'Properties': {
             'CodeUri': 'foo.zip',
             'Handler': 'app.app',
             'MemorySize': 128,
             'Role': {
                 'Fn::GetAtt': ['Role', 'Arn']
             },
             'Runtime': 'python27',
             'Tags': {
                 'foo': 'bar'
             },
             'Timeout': 120
         },
     }
예제 #2
0
 def _create_role_reference(self, config, stage_name, function_name):
     # type: (Config, str, str) -> models.IAMRole
     # First option, the user doesn't want us to manage
     # the role at all.
     if not config.manage_iam_role:
         # We've already validated the iam_role_arn is provided
         # if manage_iam_role is set to False.
         return models.PreCreatedIAMRole(role_arn=config.iam_role_arn, )
     policy = models.IAMPolicy(document=models.Placeholder.BUILD_STAGE)
     if not config.autogen_policy:
         resource_name = '%s_role' % function_name
         role_name = '%s-%s-%s' % (config.app_name, stage_name,
                                   function_name)
         if config.iam_policy_file is not None:
             filename = os.path.join(config.project_dir, '.chalice',
                                     config.iam_policy_file)
         else:
             filename = os.path.join(config.project_dir, '.chalice',
                                     'policy-%s.json' % stage_name)
         policy = models.FileBasedIAMPolicy(
             filename=filename, document=models.Placeholder.BUILD_STAGE)
     else:
         resource_name = 'default-role'
         role_name = '%s-%s' % (config.app_name, stage_name)
         policy = models.AutoGenIAMPolicy(
             document=models.Placeholder.BUILD_STAGE)
     return models.ManagedIAMRole(
         resource_name=resource_name,
         role_name=role_name,
         trust_policy=LAMBDA_TRUST_POLICY,
         policy=policy,
     )
예제 #3
0
 def test_can_update_managed_role(self):
     role = models.ManagedIAMRole(
         resource_name='resource_name',
         role_name='myrole',
         trust_policy={},
         policy=models.AutoGenIAMPolicy(document={'role': 'policy'}),
     )
     self.remote_state.declare_resource_exists(role, role_arn='myrole:arn')
     plan = self.determine_plan(role)
     assert plan[0] == models.StoreValue(name='myrole_role_arn',
                                         value='myrole:arn')
     self.assert_apicall_equals(
         plan[1],
         models.APICall(
             method_name='put_role_policy',
             params={
                 'role_name': 'myrole',
                 'policy_name': 'myrole',
                 'policy_document': {
                     'role': 'policy'
                 }
             },
         ))
     assert plan[-2].variable_name == 'myrole_role_arn'
     assert plan[-1].value == 'myrole'
     assert list(self.last_plan.messages.values()) == [
         'Updating policy for IAM role: myrole\n'
     ]
예제 #4
0
 def test_can_plan_for_iam_role_creation(self):
     self.remote_state.declare_no_resources_exists()
     resource = models.ManagedIAMRole(
         resource_name='default-role',
         role_name='myrole',
         trust_policy={'trust': 'policy'},
         policy=models.AutoGenIAMPolicy(document={'iam': 'policy'}),
     )
     plan = self.determine_plan(resource)
     expected = models.APICall(
         method_name='create_role',
         params={
             'name': 'myrole',
             'trust_policy': {
                 'trust': 'policy'
             },
             'policy': {
                 'iam': 'policy'
             }
         },
     )
     self.assert_apicall_equals(plan[0], expected)
     assert list(self.last_plan.messages.values()) == [
         'Creating IAM role: myrole\n'
     ]
예제 #5
0
    def test_invokes_policy_generator(self):
        generator = mock.Mock(spec=AppPolicyGenerator)
        generator.generate_policy.return_value = {'policy': 'doc'}
        policy = models.AutoGenIAMPolicy(models.Placeholder.BUILD_STAGE)
        config = Config.create()

        p = self.create_policy_generator(generator)
        p.handle(config, policy)

        assert policy.document == {'policy': 'doc'}
예제 #6
0
    def test_no_policy_generated_if_exists(self):
        generator = mock.Mock(spec=AppPolicyGenerator)
        generator.generate_policy.return_value = {'policy': 'new'}
        policy = models.AutoGenIAMPolicy(document={'policy': 'original'})
        config = Config.create()

        p = self.create_policy_generator(generator)
        p.handle(config, policy)

        assert policy.document == {'policy': 'original'}
        assert not generator.generate_policy.called
예제 #7
0
    def test_vpc_policy_inject_if_needed(self):
        generator = mock.Mock(spec=AppPolicyGenerator)
        generator.generate_policy.return_value = {'Statement': []}
        policy = models.AutoGenIAMPolicy(
            document=models.Placeholder.BUILD_STAGE,
            traits=set([models.RoleTraits.VPC_NEEDED]),
        )
        config = Config.create()

        p = self.create_policy_generator(generator)
        p.handle(config, policy)

        assert policy.document['Statement'][0] == VPC_ATTACH_POLICY
예제 #8
0
    def test_vpc_trait_added_when_vpc_configured(self, sample_app_lambda_only):
        @sample_app_lambda_only.lambda_function()
        def foo(event, context):
            pass

        builder = ApplicationGraphBuilder()
        config = self.create_config(sample_app_lambda_only,
                                    autogen_policy=True,
                                    security_group_ids=['sg1', 'sg2'],
                                    subnet_ids=['sn1', 'sn2'])
        application = builder.build(config, stage_name='dev')

        policy = application.resources[0].role.policy
        assert policy == models.AutoGenIAMPolicy(
            document=models.Placeholder.BUILD_STAGE,
            traits=set([models.RoleTraits.VPC_NEEDED]),
        )
예제 #9
0
 def test_autogen_policy_for_function(self, sample_app_lambda_only):
     # This test is just a sanity test that verifies all the params
     # for an ManagedIAMRole.  The various combinations for role
     # configuration is all tested via RoleTestCase.
     config = self.create_config(sample_app_lambda_only,
                                 autogen_policy=True)
     builder = ApplicationGraphBuilder()
     application = builder.build(config, stage_name='dev')
     function = application.resources[0]
     role = function.role
     # We should have linked a ManagedIAMRole
     assert isinstance(role, models.ManagedIAMRole)
     assert role == models.ManagedIAMRole(
         resource_name='default-role',
         role_name='lambda-only-dev',
         trust_policy=LAMBDA_TRUST_POLICY,
         policy=models.AutoGenIAMPolicy(models.Placeholder.BUILD_STAGE),
     )
예제 #10
0
 def test_managed_iam_role(self):
     role = models.ManagedIAMRole(
         resource_name='default_role',
         role_name='app-dev',
         trust_policy=LAMBDA_TRUST_POLICY,
         policy=models.AutoGenIAMPolicy(document={'iam': 'policy'}),
     )
     template = self.template_gen.generate_sam_template([role])
     resources = template['Resources']
     assert len(resources) == 1
     cfn_role = resources['DefaultRole']
     assert cfn_role['Type'] == 'AWS::IAM::Role'
     assert cfn_role['Properties']['Policies'] == [
         {'PolicyName': 'DefaultRolePolicy',
          'PolicyDocument': {'iam': 'policy'}}
     ]
     # Ensure the RoleName is not in the resource properties
     # so we don't require CAPABILITY_NAMED_IAM.
     assert 'RoleName' not in cfn_role['Properties']
예제 #11
0
 def test_dynamically_lookup_iam_role(self):
     remote_state = RemoteState(
         self.client,
         DeployedResources(
             {'resources': [{
                 'name': 'rest_api',
                 'rest_api_id': 'foo'
             }]}))
     resource = models.ManagedIAMRole(
         resource_name='default-role',
         role_name='myrole',
         trust_policy={'trust': 'policy'},
         policy=models.AutoGenIAMPolicy(document={'iam': 'policy'}),
     )
     self.client.get_role_arn_for_name.return_value = 'my-role-arn'
     values = remote_state.resource_deployed_values(resource)
     assert values == {
         'name': 'default-role',
         'resource_type': 'iam_role',
         'role_arn': 'my-role-arn',
         'role_name': 'myrole'
     }