From ef0b1691da3a980fb189f724ee592f3474a38766 Mon Sep 17 00:00:00 2001 From: cjihrig Date: Wed, 21 Apr 2021 20:47:27 -0400 Subject: [PATCH] fix(s3): use bucket's region in urlForObject() This commit updates urlForObject() to use the bucket's region instead of the stack's region when constructing the returned URL. Refs: https://github.com/aws/aws-cdk/issues/14149 --- packages/@aws-cdk/aws-s3/lib/bucket.ts | 2 +- packages/@aws-cdk/aws-s3/test/bucket.test.ts | 21 +++++++++++++++++++- 2 files changed, 21 insertions(+), 2 deletions(-) diff --git a/packages/@aws-cdk/aws-s3/lib/bucket.ts b/packages/@aws-cdk/aws-s3/lib/bucket.ts index 969378942c33e..002435a234c0c 100644 --- a/packages/@aws-cdk/aws-s3/lib/bucket.ts +++ b/packages/@aws-cdk/aws-s3/lib/bucket.ts @@ -530,7 +530,7 @@ abstract class BucketBase extends Resource implements IBucket { */ public urlForObject(key?: string): string { const stack = Stack.of(this); - const prefix = `https://s3.${stack.region}.${stack.urlSuffix}/`; + const prefix = `https://s3.${this.env.region}.${stack.urlSuffix}/`; if (typeof key !== 'string') { return this.urlJoin(prefix, this.bucketName); } diff --git a/packages/@aws-cdk/aws-s3/test/bucket.test.ts b/packages/@aws-cdk/aws-s3/test/bucket.test.ts index fa8157fd9d1fd..95a8cf377dfc6 100644 --- a/packages/@aws-cdk/aws-s3/test/bucket.test.ts +++ b/packages/@aws-cdk/aws-s3/test/bucket.test.ts @@ -1599,10 +1599,15 @@ describe('bucket', () => { test('urlForObject returns a token with the S3 URL of the token', () => { const stack = new cdk.Stack(); const bucket = new s3.Bucket(stack, 'MyBucket'); + const bucketWithRegion = s3.Bucket.fromBucketAttributes(stack, 'RegionalBucket', { + bucketArn: 'arn:aws:s3:::explicit-region-bucket', + region: 'us-west-2', + }); new cdk.CfnOutput(stack, 'BucketURL', { value: bucket.urlForObject() }); new cdk.CfnOutput(stack, 'MyFileURL', { value: bucket.urlForObject('my/file.txt') }); new cdk.CfnOutput(stack, 'YourFileURL', { value: bucket.urlForObject('/your/file.txt') }); // "/" is optional + new cdk.CfnOutput(stack, 'RegionBucketURL', { value: bucketWithRegion.urlForObject() }); expect(stack).toMatchTemplate({ 'Resources': { @@ -1678,6 +1683,20 @@ describe('bucket', () => { ], }, }, + 'RegionBucketURL': { + 'Value': { + 'Fn::Join': [ + '', + [ + 'https://s3.us-west-2.', + { + 'Ref': 'AWS::URLSuffix', + }, + '/explicit-region-bucket', + ], + ], + }, + }, }, }); @@ -2453,4 +2472,4 @@ describe('bucket', () => { autoDeleteObjects: true, })).toThrow(/Cannot use \'autoDeleteObjects\' property on a bucket without setting removal policy to \'DESTROY\'/); }); -}); \ No newline at end of file +});