diff --git a/packages/@aws-cdk/aws-cloudfront/lib/cache-policy.ts b/packages/@aws-cdk/aws-cloudfront/lib/cache-policy.ts index 533ccbd5d78b9..e870a538fc887 100644 --- a/packages/@aws-cdk/aws-cloudfront/lib/cache-policy.ts +++ b/packages/@aws-cdk/aws-cloudfront/lib/cache-policy.ts @@ -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(); diff --git a/packages/@aws-cdk/aws-cloudfront/lib/distribution.ts b/packages/@aws-cdk/aws-cloudfront/lib/distribution.ts index c593edd9efec7..bd9fb1cb50202 100644 --- a/packages/@aws-cdk/aws-cloudfront/lib/distribution.ts +++ b/packages/@aws-cdk/aws-cloudfront/lib/distribution.ts @@ -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', { diff --git a/packages/@aws-cdk/aws-cloudfront/test/cache-policy.test.ts b/packages/@aws-cdk/aws-cloudfront/test/cache-policy.test.ts index 47e9b0ee46fb9..2abeffd3cc39b 100644 --- a/packages/@aws-cdk/aws-cloudfront/test/cache-policy.test.ts +++ b/packages/@aws-cdk/aws-cloudfront/test/cache-policy.test.ts @@ -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);