Skip to content

Commit

Permalink
Add cross-account KMS key grant
Browse files Browse the repository at this point in the history
This adds support for detecting when the KMS key is cross-account and not add the ViaServicePrincipal as per the documentation here: https://docs.aws.amazon.com/secretsmanager/latest/userguide/auth-and-access_examples_cross.html
  • Loading branch information
pergardebrink committed Dec 17, 2023
1 parent 9ab50d9 commit 76ff0b8
Show file tree
Hide file tree
Showing 3 changed files with 351 additions and 68 deletions.
55 changes: 26 additions & 29 deletions packages/aws-cdk-lib/aws-lambda/test/params-and-secrets.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -433,6 +433,32 @@ describe('params and secrets', () => {
Ref: 'SecretA720EF05',
},
},
{
Action: 'kms:Decrypt',
Condition: {
StringEquals: {
'kms:ViaService': {
'Fn::Join': [
'',
[
'secretsmanager.',
{
Ref: 'AWS::Region',
},
'.amazonaws.com',
],
],
},
},
},
Effect: 'Allow',
Resource: {
'Fn::GetAtt': [
'Key961B73FD',
'Arn',
],
},
},
],
Version: '2012-10-17',
},
Expand Down Expand Up @@ -555,35 +581,6 @@ describe('params and secrets', () => {
},
Resource: '*',
},
{
Action: 'kms:Decrypt',
Condition: {
StringEquals: {
'kms:ViaService': {
'Fn::Join': [
'',
[
'secretsmanager.',
{
Ref: 'AWS::Region',
},
'.amazonaws.com',
],
],
},
},
},
Effect: 'Allow',
Principal: {
AWS: {
'Fn::GetAtt': [
'FunctionServiceRole675BB04A',
'Arn',
],
},
},
Resource: '*',
},
]),
},
});
Expand Down
8 changes: 2 additions & 6 deletions packages/aws-cdk-lib/aws-secretsmanager/lib/secret.ts
Original file line number Diff line number Diff line change
Expand Up @@ -381,9 +381,7 @@ abstract class SecretBase extends Resource implements ISecret {

if (this.encryptionKey) {
// @see https://docs.aws.amazon.com/kms/latest/developerguide/services-secrets-manager.html
this.encryptionKey.grantDecrypt(
new kms.ViaServicePrincipal(`secretsmanager.${Stack.of(this).region}.amazonaws.com`, grantee.grantPrincipal),
);
this.encryptionKey.grantDecrypt(new kms.ViaServicePrincipal(`secretsmanager.${Stack.of(this).region}.amazonaws.com`, grantee.grantPrincipal));
}

const crossAccount = Token.compareStrings(Stack.of(this).account, grantee.grantPrincipal.principalAccount || '');
Expand All @@ -407,9 +405,7 @@ abstract class SecretBase extends Resource implements ISecret {

if (this.encryptionKey) {
// See https://docs.aws.amazon.com/kms/latest/developerguide/services-secrets-manager.html
this.encryptionKey.grantEncrypt(
new kms.ViaServicePrincipal(`secretsmanager.${Stack.of(this).region}.amazonaws.com`, grantee.grantPrincipal),
);
this.encryptionKey.grantEncrypt(new kms.ViaServicePrincipal(`secretsmanager.${Stack.of(this).region}.amazonaws.com`, grantee.grantPrincipal));
}

// Throw if secret is not imported and it's shared cross account and no KMS key is provided
Expand Down
Loading

0 comments on commit 76ff0b8

Please sign in to comment.