示例#1
0
    def init_deploymentpipelines_permission(self, permission_config, permissions_by_account):
        """
        Iterates over each pipeline reference and adds its permission config
        to the map of permissions by account.
        """
        for resource in permission_config.resources:
            pipeline_ref = Reference(resource.pipeline)
            account_ref = 'paco.ref ' + '.'.join(pipeline_ref.parts) + '.configuration.account'
            account_ref = self.paco_ctx.get_ref(account_ref)
            account_name = self.paco_ctx.get_ref(account_ref + '.name')
            if permission_config not in permissions_by_account[account_name]:
                permissions_by_account[account_name].append(permission_config)


            # Initialize The network environments that we need access into
            pipeline_config = pipeline_ref.get_model_obj(self.paco_ctx.project)
            self.paco_ctx.get_controller(pipeline_ref.parts[0], model_obj=pipeline_config)

            # Some actions in the pipeline might be in different account so we must
            # iterate the pipeline stages and actions and add them too.
            for action_name in pipeline_config.source.keys():
                action = pipeline_config.source[action_name]
                account_name = None
                if action.type == 'CodeDeploy.Deploy':
                    asg_ref = Reference(action.auto_scaling_group)
                    asg_config = asg_ref.get_model_obj(self.paco_ctx.project)
                    account_name = self.paco_ctx.get_ref(asg_config.get_account().paco_ref + '.name')
                if account_name != None:
                    if permission_config not in permissions_by_account[account_name]:
                        permissions_by_account[account_name].append(permission_config)
    def init_deploymentpipelines_permission(self, permission_config,
                                            assume_role_res):
        if 'ManagedPolicyArns' not in assume_role_res.properties.keys():
            assume_role_res.properties['ManagedPolicyArns'] = []

        pipeline_list = []
        for resource in permission_config.resources:
            pipeline_ref = Reference(resource.pipeline)
            pipeline = pipeline_ref.get_model_obj(self.paco_ctx.project)
            account_ref = pipeline.configuration.account
            account_name = self.paco_ctx.get_ref(account_ref + '.name')
            if account_name == self.account_ctx.name:
                pipeline_arn = self.paco_ctx.get_ref(pipeline.paco_ref +
                                                     '.arn')
                pipeline_list.append({
                    'permission': resource.permission,
                    'pipeline': pipeline,
                    'pipeline_arn': pipeline_arn
                })

        self.deployment_pipeline_manaul_approval_permissions(
            pipeline_list, assume_role_res)
        self.deployment_pipeline_codepipeline_permissions(
            pipeline_list, assume_role_res)
        self.deployment_pipeline_codebuild_permissions(pipeline_list,
                                                       assume_role_res)
    def init_systemsmanagersession_permission(self, permission_config,
                                              assume_role_res):
        if 'ManagedPolicyArns' not in assume_role_res.properties.keys():
            assume_role_res.properties['ManagedPolicyArns'] = []

        resource_group_condition_list = []
        for resource in permission_config.resources:
            resource_ref = Reference(resource)
            # Initialize The network environments that we need access into
            resource_obj = resource_ref.get_model_obj(self.paco_ctx.project)
            if schemas.IResourceGroup.providedBy(resource_obj):
                resource_group_condition_list.append(
                    StringLike({
                        'ssm:resourceTag/Paco-Application-Group-Name':
                        resource_obj.name
                    }))

        if len(resource_group_condition_list) == 0:
            return

        statement_list = []
        statement_list.append(
            Statement(
                Sid='SessionManagerStartSession',
                Effect=Allow,
                Action=[
                    Action('ssm', 'StartSession'),
                ],
                Resource=[
                    'arn:aws:ec2:*:*:instance/*',
                    'arn:aws:ssm:*::document/AWS-StartPortForwardingSession'
                ],
                Condition=Condition(resource_group_condition_list)))
        statement_list.append(
            Statement(
                Sid='SessionManagerPortForward',
                Effect=Allow,
                Action=[
                    Action('ssm', 'StartSession'),
                ],
                Resource=[
                    'arn:aws:ssm:*::document/AWS-StartPortForwardingSession'
                ]))
        statement_list.append(
            Statement(Sid='SessionManagerTerminateSession',
                      Effect=Allow,
                      Action=[
                          Action('ssm', 'TerminateSession'),
                          Action('ssm', 'ResumeSession'),
                      ],
                      Resource=['arn:aws:ssm:*:*:session/${aws:username}-*']))
        managed_policy_res = troposphere.iam.ManagedPolicy(
            title=self.create_cfn_logical_id_join(["SystemsManagerSession"]),
            PolicyDocument=PolicyDocument(Version="2012-10-17",
                                          Statement=statement_list),
            Roles=[troposphere.Ref(assume_role_res)])
        self.template.add_resource(managed_policy_res)
示例#4
0
    def __init__(self, stack, paco_ctx):
        cip = stack.resource
        super().__init__(stack, paco_ctx, iam_capabilities=["CAPABILITY_IAM"])
        self.set_aws_name('CIP', self.resource_group_name, self.resource.name)

        self.init_template('Cognito Identity Pool')
        if not cip.is_enabled():
            return

        # Cognito Identity Pool
        cfn_export_dict = cip.cfn_export_dict
        if len(cip.identity_providers) > 0:
            idps = []
            up_client_params = {}
            up_params = {}
            for idp in cip.identity_providers:
                # replace <region> and <account> for refs in Services
                up_client_ref = Reference(idp.userpool_client)
                up_client_ref.set_account_name(self.account_ctx.get_name())
                up_client_ref.set_region(self.aws_region)
                userpool_client = up_client_ref.get_model_obj(self.paco_ctx.project)
                if up_client_ref.ref not in up_client_params:
                    up_client_name = self.create_cfn_logical_id(f'UserPoolClient{userpool_client.name}' + md5sum(str_data=up_client_ref.ref))
                    value = f'paco.ref {up_client_ref.ref }.id'
                    up_client_params[up_client_ref.ref] = self.create_cfn_parameter(
                        param_type='String',
                        name=up_client_name,
                        description=f'UserPool Client Id for {userpool_client.name}',
                        value=value,
                    )
                userpool = get_parent_by_interface(userpool_client, ICognitoUserPool)
                userpool_ref = userpool.paco_ref
                if userpool_ref not in up_params:
                    up_name = self.create_cfn_logical_id(f'UserPool{userpool.name}' + md5sum(str_data=userpool_ref))
                    up_params[userpool_ref] = self.create_cfn_parameter(
                        param_type='String',
                        name=up_name,
                        description=f'UserPool ProviderName for {userpool.name}',
                        value=userpool_ref + '.providername',
                    )
                idps.append({
                    "ClientId" : troposphere.Ref(up_client_params[up_client_ref.ref]),
                    "ProviderName" : troposphere.Ref(up_params[userpool_ref]),
                    "ServerSideTokenCheck" : idp.serverside_token_check,
                })
            cfn_export_dict['CognitoIdentityProviders'] = idps
        cip_resource = troposphere.cognito.IdentityPool.from_dict(
            'CognitoIdentityPool',
            cfn_export_dict
        )
        self.template.add_resource(cip_resource)

        # Outputs
        self.create_output(
            title=cip_resource.title + 'Id',
            description="Cognito Identity Pool Id",
            value=troposphere.Ref(cip_resource),
            ref=[cip.paco_ref_parts, cip.paco_ref_parts + ".id"],
        )

        # Roles
        roles_dict = {}

        unauthenticated_assume_role_policy = PolicyDocument(
            Statement=[
                Statement(
                    Effect=Allow,
                    Principal=Principal('Federated',"cognito-identity.amazonaws.com"),
                    Action=[Action('sts', 'AssumeRoleWithWebIdentity')],
                    Condition=Condition([
                        StringEquals({"cognito-identity.amazonaws.com:aud": troposphere.Ref(cip_resource)}),
                        ForAnyValueStringLike({"cognito-identity.amazonaws.com:amr": "unauthenticated"})
                    ]),
                ),
            ],
        )
        unauthenticated_role_resource = role_to_troposphere(
            cip.unauthenticated_role,
            'UnauthenticatedRole',
            assume_role_policy=unauthenticated_assume_role_policy,
        )
        if unauthenticated_role_resource != None:
            self.template.add_resource(unauthenticated_role_resource)
            roles_dict['unauthenticated'] = troposphere.GetAtt(unauthenticated_role_resource, "Arn")

        authenticated_assume_role_policy = PolicyDocument(
            Statement=[
                Statement(
                    Effect=Allow,
                    Principal=Principal('Federated',"cognito-identity.amazonaws.com"),
                    Action=[Action('sts', 'AssumeRoleWithWebIdentity')],
                    Condition=Condition([
                        StringEquals({"cognito-identity.amazonaws.com:aud": troposphere.Ref(cip_resource)}),
                        ForAnyValueStringLike({"cognito-identity.amazonaws.com:amr": "authenticated"})
                    ]),
                ),
            ],
        )
        authenticated_role_resource = role_to_troposphere(
            cip.authenticated_role,
            'AuthenticatedRole',
            assume_role_policy=authenticated_assume_role_policy
        )
        if authenticated_role_resource != None:
            self.template.add_resource(authenticated_role_resource)
            roles_dict['authenticated'] = troposphere.GetAtt(authenticated_role_resource, "Arn")

        # Identity Pool Role Attachment
        if roles_dict:
            iproleattachment_resource = troposphere.cognito.IdentityPoolRoleAttachment(
                title='IdentityPoolRoleAttachment',
                IdentityPoolId=troposphere.Ref(cip_resource),
                Roles=roles_dict,
            )
            self.template.add_resource(iproleattachment_resource)