CDK 将策略添加到自定义创建的 SES 验证电子邮件

CDK Add Policy to Custom Created SES Verified Email

使用 AWS SDK,我可以创建一个 SES 验证的电子邮件地址。但是我如何创建一个策略来授予 SendEmail 和 SendRawEmail 对电子邮件的权限(就像在控制台中一样)?我的理解是 AwsCustomResource 策略属性向创建资源的 Lambda 函数授予权限,而不是向创建的资源本身授予权限。

const customResource = new cr.AwsCustomResource(this, 'VerifyEmailIdentity', {
    onCreate: {
        service: 'SES',
        action: 'verifyEmailIdentity',
        parameters: {
            EmailAddress: cognitoEmailAddress,
        },
        physicalResourceId: cr.PhysicalResourceId.of(`verify-${cognitoEmailAddress}`)
    },
    onDelete: {
        service: 'SES',
        action: 'deleteIdentity',
        parameters: {
            Identity: cognitoEmailAddress
        }
    },
    policy: cr.AwsCustomResourcePolicy.fromStatements([
        new iam.PolicyStatement({
            effect: iam.Effect.ALLOW,
            actions: ['ses:VerifyEmailIdentity', 'ses:DeleteIdentity'],
            resources: ['*']
        })
    ])
});

添加以下调用 SES putIdentityPolicy 的附加代码,允许(例如)将 Cognito 服务发送到 SendEmail 和 SendRawEmail。

import * as cr from '@aws-cdk/custom-resources';
import * as iam from '@aws-cdk/aws-iam';

const cognitoEmailAddress = 'myemail@mydomain.com';
const cognitoEmailAddressArn = `arn:aws:ses:${myRegion}:${myAccount}:identity/${cognitoEmailAddress}`;

const policy = {
    Version: '2008-10-17',
    Statement: [
        {
            Sid: 'stmt1621717794524',
            Effect: 'Allow',
            Principal: {
                Service: 'cognito-idp.amazonaws.com'
            },
            Action: [
                'ses:SendEmail',
                'ses:SendRawEmail'
            ],
            Resource: cognitoEmailAddressArn
        }
    ]
};

new cr.AwsCustomResource(this, 'PutIdentityPolicy', {
    onCreate: {
        service: 'SES',
        action: 'putIdentityPolicy',
        parameters: {
            Identity: cognitoEmailAddress,
            Policy: JSON.stringify(policy),
            PolicyName: 'CognitoSESEmail'
        },
        physicalResourceId: cr.PhysicalResourceId.of(`policy-${cognitoEmailAddress}`)
    },
    onDelete: {
        service: 'SES',
        action: 'deleteIdentityPolicy',
        parameters: {
            Identity: cognitoEmailAddress,
            PolicyName: 'CognitoSESEmail'
        }
    },
    // There is a policy bug in the CDK for custom resources: https://github.com/aws/aws-cdk/issues/4533
    // Use the following policy workaround. 
    policy: cr.AwsCustomResourcePolicy.fromStatements([
        new iam.PolicyStatement({
            effect: iam.Effect.ALLOW,
            actions: ['ses:PutIdentityPolicy', 'ses:DeleteIdentityPolicy'],
            resources: ['*']
        })
    ])
});