Skip to content

Commit

Permalink
fix(secretsmanager): cannot import secrets if ARN is a token
Browse files Browse the repository at this point in the history
The feature to support importing secrets by name (#10309) failed to handle
scenarios where the secret ARN is a token, due to parsing the ARN to retrieve
the secret name.

fixes #10520
  • Loading branch information
njlynch committed Sep 28, 2020
1 parent d68ce2f commit da10d74
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 1 deletion.
9 changes: 8 additions & 1 deletion packages/@aws-cdk/aws-secretsmanager/lib/secret.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import * as iam from '@aws-cdk/aws-iam';
import * as kms from '@aws-cdk/aws-kms';
import { Construct, IConstruct, IResource, RemovalPolicy, Resource, SecretValue, Stack } from '@aws-cdk/core';
import { Construct, Fn, IConstruct, IResource, RemovalPolicy, Resource, SecretValue, Stack, Token } from '@aws-cdk/core';
import { ResourcePolicy } from './policy';
import { RotationSchedule, RotationScheduleOptions } from './rotation-schedule';
import * as secretsmanager from './secretsmanager.generated';
Expand Down Expand Up @@ -596,6 +596,13 @@ export interface SecretStringGenerator {

/** Parses the secret name from the ARN. */
function parseSecretName(construct: IConstruct, secretArn: string) {
if (Token.isUnresolved(secretArn)) {
// Split the ARN by ':' to get the resource name;
// note that this returns the full secret name (vs the "friendly name" without the suffix)
// because there is no reasonable way to get the last index of the suffix delimiter ('-').
return Fn.select(6, Fn.split(':', secretArn));
}

const resourceName = Stack.of(construct).parseArn(secretArn).resourceName;
if (resourceName) {
// Secret resource names are in the format `${secretName}-${SecretsManager suffix}`
Expand Down
24 changes: 24 additions & 0 deletions packages/@aws-cdk/aws-secretsmanager/test/test.secret.ts
Original file line number Diff line number Diff line change
Expand Up @@ -482,6 +482,30 @@ export = {
test.done();
},

'import by secretArn supports tokens for ARNs'(test: Test) {
// GIVEN
const app = new cdk.App();
const stackA = new cdk.Stack(app, 'StackA');
const stackB = new cdk.Stack(app, 'StackB');
const secretA = new secretsmanager.Secret(stackA, 'SecretA');

// WHEN
const secretB = secretsmanager.Secret.fromSecretArn(stackB, 'SecretB', secretA.secretArn);
new cdk.CfnOutput(stackB, 'secretBSecretName', { value: secretB.secretName });

// THEN
test.equals(secretB.secretArn, secretA.secretArn);
expect(stackB).toMatch({
Outputs: {
secretBSecretName: {
Value: { 'Fn::Select': [6, { 'Fn::Split': [':', { 'Fn::ImportValue': 'StackA:ExportsOutputRefSecretA188F281703FC8A52' }] }] },
},
},
});

test.done();
},

'import by attributes'(test: Test) {
// GIVEN
const stack = new cdk.Stack();
Expand Down

0 comments on commit da10d74

Please sign in to comment.