Skip to content

Commit

Permalink
fix(s3): use bucket's region in urlForObject()
Browse files Browse the repository at this point in the history
This commit updates urlForObject() to use the bucket's region
instead of the stack's region when constructing the returned
URL.

Refs: aws#14149
  • Loading branch information
cjihrig committed Apr 22, 2021
1 parent fbc297a commit ef0b169
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 2 deletions.
2 changes: 1 addition & 1 deletion packages/@aws-cdk/aws-s3/lib/bucket.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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);
}
Expand Down
21 changes: 20 additions & 1 deletion packages/@aws-cdk/aws-s3/test/bucket.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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': {
Expand Down Expand Up @@ -1678,6 +1683,20 @@ describe('bucket', () => {
],
},
},
'RegionBucketURL': {
'Value': {
'Fn::Join': [
'',
[
'https://s3.us-west-2.',
{
'Ref': 'AWS::URLSuffix',
},
'/explicit-region-bucket',
],
],
},
},
},
});

Expand Down Expand Up @@ -2453,4 +2472,4 @@ describe('bucket', () => {
autoDeleteObjects: true,
})).toThrow(/Cannot use \'autoDeleteObjects\' property on a bucket without setting removal policy to \'DESTROY\'/);
});
});
});

0 comments on commit ef0b169

Please sign in to comment.