Skip to content

Commit

Permalink
fix(cloudfront): trim autogenerated cache policy name (#18953)
Browse files Browse the repository at this point in the history
Closes #18918

----

*By submitting this pull request, I confirm that my contribution is made under the terms of the Apache-2.0 license*
  • Loading branch information
robertd committed Feb 22, 2022
1 parent 5b92cc3 commit c7394c9
Show file tree
Hide file tree
Showing 3 changed files with 14 additions and 4 deletions.
9 changes: 7 additions & 2 deletions packages/@aws-cdk/aws-cloudfront/lib/cache-policy.ts
Expand Up @@ -129,9 +129,14 @@ export class CachePolicy extends Resource implements ICachePolicy {
physicalName: props.cachePolicyName,
});

const cachePolicyName = props.cachePolicyName ?? `${Names.uniqueId(this)}-${Stack.of(this).region}`;
const cachePolicyName = props.cachePolicyName ?? `${Names.uniqueId(this).slice(0, 110)}-${Stack.of(this).region}`;

if (!Token.isUnresolved(cachePolicyName) && !cachePolicyName.match(/^[\w-]+$/i)) {
throw new Error(`'cachePolicyName' can only include '-', '_', and alphanumeric characters, got: '${props.cachePolicyName}'`);
throw new Error(`'cachePolicyName' can only include '-', '_', and alphanumeric characters, got: '${cachePolicyName}'`);
}

if (cachePolicyName.length > 128) {
throw new Error(`'cachePolicyName' cannot be longer than 128 characters, got: '${cachePolicyName.length}'`);
}

const minTtl = (props.minTtl ?? Duration.seconds(0)).toSeconds();
Expand Down
2 changes: 1 addition & 1 deletion packages/@aws-cdk/aws-cloudfront/lib/distribution.ts
Expand Up @@ -285,7 +285,7 @@ export class Distribution extends Resource implements IDistribution {
// Comments have an undocumented limit of 128 characters
const trimmedComment =
props.comment && props.comment.length > 128
? `${props.comment.substr(0, 128 - 3)}...`
? `${props.comment.slice(0, 128 - 3)}...`
: props.comment;

const distribution = new CfnDistribution(this, 'Resource', {
Expand Down
7 changes: 6 additions & 1 deletion packages/@aws-cdk/aws-cloudfront/test/cache-policy.test.ts
Expand Up @@ -85,7 +85,12 @@ describe('CachePolicy', () => {
});
});

test('throws if given a cachePolicyName with invalid characters', () => {
test('throws on long policy names over 128 characters', () => {
const errorMessage = /'cachePolicyName' cannot be longer than 128 characters/;
expect(() => new CachePolicy(stack, 'CachePolicy1', { cachePolicyName: 'FooBarBaz'.repeat(15) })).toThrow(errorMessage);
});

test('throws if cachePolicyName contains invalid characters', () => {
const errorMessage = /'cachePolicyName' can only include '-', '_', and alphanumeric characters/;
expect(() => new CachePolicy(stack, 'CachePolicy1', { cachePolicyName: 'My Policy' })).toThrow(errorMessage);
expect(() => new CachePolicy(stack, 'CachePolicy2', { cachePolicyName: 'MyPolicy!' })).toThrow(errorMessage);
Expand Down

0 comments on commit c7394c9

Please sign in to comment.