Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions cdk/.gitignore
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
*.js
!jest.config.js
!lib/constructs/cf-lambda-furl-service/cf-function/*.js
*.d.ts
node_modules

Expand Down
39 changes: 39 additions & 0 deletions cdk/lib/constructs/cf-lambda-furl-service/cf-function/cache-key.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
// CloudFront Functions JS 2.0
// Combines Next.js RSC-related headers into a single hashed cache key header
// to prevent cache poisoning between HTML and RSC flight responses.
//
// Next.js App Router sets Vary: rsc, next-router-state-tree, next-router-prefetch,
// next-router-segment-prefetch (and next-url for interception routes).
// CloudFront ignores Vary and requires explicit cache key configuration,
// but its Cache Policy has a 10-header limit. This function hashes all
// RSC headers into one header to stay within the limit.
async function handler(event) {
var h = event.request.headers;
var parts = [
'rsc',
'next-router-prefetch',
'next-router-state-tree',
'next-router-segment-prefetch',
'next-url',
];
var key = '';
for (var i = 0; i < parts.length; i++) {
if (h[parts[i]]) {
key += parts[i] + '=' + h[parts[i]].value + ';';
}
}
if (key) {
// FNV-1a hash (32-bit). Cryptographic strength is unnecessary;
// we only need distinct cache keys for distinct header combinations.
// See: https://en.wikipedia.org/wiki/Fowler%E2%80%93Noll%E2%80%93Vo_hash_function
var FNV_OFFSET_BASIS = 2166136261;
var FNV_PRIME = 16777619;
var hash = FNV_OFFSET_BASIS;
for (var j = 0; j < key.length; j++) {
hash ^= key.charCodeAt(j);
hash = (hash * FNV_PRIME) | 0;
}
event.request.headers['x-nextjs-cache-key'] = { value: String(hash >>> 0) };
}
return event.request;
}
22 changes: 22 additions & 0 deletions cdk/lib/constructs/cf-lambda-furl-service/service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,11 +8,16 @@ import {
CachePolicy,
CacheQueryStringBehavior,
Distribution,
Function as CfFunction,
FunctionCode as CfFunctionCode,
FunctionEventType,
FunctionRuntime,
LambdaEdgeEventType,
OriginRequestPolicy,
SecurityPolicyProtocol,
} from 'aws-cdk-lib/aws-cloudfront';
import { FunctionUrlOrigin } from 'aws-cdk-lib/aws-cloudfront-origins';
import * as path from 'path';
import { StringParameter } from 'aws-cdk-lib/aws-ssm';
import { ARecord, IHostedZone, RecordTarget } from 'aws-cdk-lib/aws-route53';
import { CloudFrontTarget } from 'aws-cdk-lib/aws-route53-targets';
Expand Down Expand Up @@ -89,20 +94,37 @@ export class CloudFrontLambdaFunctionUrlService extends Construct {
'X-HTTP-Method-Override',
'X-HTTP-Method',
'X-Method-Override',
// Hashed Next.js RSC headers set by the CloudFront Function below.
// See cf-function/cache-key.js for details.
'x-nextjs-cache-key',
),
defaultTtl: Duration.seconds(0),
cookieBehavior: CacheCookieBehavior.all(),
enableAcceptEncodingBrotli: true,
enableAcceptEncodingGzip: true,
});

// CloudFront Function to hash Next.js RSC headers into a single cache key header.
// This prevents cache poisoning between HTML and RSC flight responses while
// staying within CloudFront's 10-header limit on Cache Policies.
const cacheKeyFunction = new CfFunction(this, 'CacheKeyFunction', {
runtime: FunctionRuntime.JS_2_0,
code: CfFunctionCode.fromFile({ filePath: path.join(__dirname, 'cf-function', 'cache-key.js') }),
});

const distribution = new Distribution(this, 'Resource', {
comment: `CloudFront for ${serviceName}`,
defaultBehavior: {
origin,
cachePolicy,
allowedMethods: AllowedMethods.ALLOW_ALL,
originRequestPolicy: OriginRequestPolicy.ALL_VIEWER_EXCEPT_HOST_HEADER,
functionAssociations: [
{
function: cacheKeyFunction,
eventType: FunctionEventType.VIEWER_REQUEST,
},
],
edgeLambdas: [
{
functionVersion: signPayloadHandler.versionArn(this),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2980,6 +2980,17 @@ service iptables save",
"Ref": "WebappSharedCachePolicy14FEE4A0",
},
"Compress": true,
"FunctionAssociations": [
{
"EventType": "viewer-request",
"FunctionARN": {
"Fn::GetAtt": [
"WebappCacheKeyFunction6C227CE2",
"FunctionARN",
],
},
},
],
"LambdaFunctionAssociations": [
{
"EventType": "origin-request",
Expand Down Expand Up @@ -3200,6 +3211,57 @@ service iptables save",
"Type": "AWS::ECR::Repository",
"UpdateReplacePolicy": "Delete",
},
"WebappCacheKeyFunction6C227CE2": {
"Properties": {
"AutoPublish": true,
"FunctionCode": "// CloudFront Functions JS 2.0
// Combines Next.js RSC-related headers into a single hashed cache key header
// to prevent cache poisoning between HTML and RSC flight responses.
//
// Next.js App Router sets Vary: rsc, next-router-state-tree, next-router-prefetch,
// next-router-segment-prefetch (and next-url for interception routes).
// CloudFront ignores Vary and requires explicit cache key configuration,
// but its Cache Policy has a 10-header limit. This function hashes all
// RSC headers into one header to stay within the limit.
async function handler(event) {
var h = event.request.headers;
var parts = [
'rsc',
'next-router-prefetch',
'next-router-state-tree',
'next-router-segment-prefetch',
'next-url',
];
var key = '';
for (var i = 0; i < parts.length; i++) {
if (h[parts[i]]) {
key += parts[i] + '=' + h[parts[i]].value + ';';
}
}
if (key) {
// FNV-1a hash (32-bit). Cryptographic strength is unnecessary;
// we only need distinct cache keys for distinct header combinations.
// See: https://en.wikipedia.org/wiki/Fowler%E2%80%93Noll%E2%80%93Vo_hash_function
var FNV_OFFSET_BASIS = 2166136261;
var FNV_PRIME = 16777619;
var hash = FNV_OFFSET_BASIS;
for (var j = 0; j < key.length; j++) {
hash ^= key.charCodeAt(j);
hash = (hash * FNV_PRIME) | 0;
}
event.request.headers['x-nextjs-cache-key'] = { value: String(hash >>> 0) };
}
return event.request;
}
",
"FunctionConfig": {
"Comment": "us-west-2ServerlessWebappCacheKeyFunction86D1ABE9",
"Runtime": "cloudfront-js-2.0",
},
"Name": "us-west-2ServerlessWebappCacheKeyFunction86D1ABE9",
},
"Type": "AWS::CloudFront::Function",
},
"WebappCloudFrontInvalidation588CF152": {
"DeletionPolicy": "Delete",
"DependsOn": [
Expand Down Expand Up @@ -4094,6 +4156,7 @@ service iptables save",
"X-HTTP-Method-Override",
"X-HTTP-Method",
"X-Method-Override",
"x-nextjs-cache-key",
],
},
"QueryStringsConfig": {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2815,6 +2815,17 @@ service iptables save",
"Ref": "WebappSharedCachePolicy14FEE4A0",
},
"Compress": true,
"FunctionAssociations": [
{
"EventType": "viewer-request",
"FunctionARN": {
"Fn::GetAtt": [
"WebappCacheKeyFunction6C227CE2",
"FunctionARN",
],
},
},
],
"LambdaFunctionAssociations": [
{
"EventType": "origin-request",
Expand Down Expand Up @@ -3045,6 +3056,57 @@ service iptables save",
"Type": "AWS::ECR::Repository",
"UpdateReplacePolicy": "Delete",
},
"WebappCacheKeyFunction6C227CE2": {
"Properties": {
"AutoPublish": true,
"FunctionCode": "// CloudFront Functions JS 2.0
// Combines Next.js RSC-related headers into a single hashed cache key header
// to prevent cache poisoning between HTML and RSC flight responses.
//
// Next.js App Router sets Vary: rsc, next-router-state-tree, next-router-prefetch,
// next-router-segment-prefetch (and next-url for interception routes).
// CloudFront ignores Vary and requires explicit cache key configuration,
// but its Cache Policy has a 10-header limit. This function hashes all
// RSC headers into one header to stay within the limit.
async function handler(event) {
var h = event.request.headers;
var parts = [
'rsc',
'next-router-prefetch',
'next-router-state-tree',
'next-router-segment-prefetch',
'next-url',
];
var key = '';
for (var i = 0; i < parts.length; i++) {
if (h[parts[i]]) {
key += parts[i] + '=' + h[parts[i]].value + ';';
}
}
if (key) {
// FNV-1a hash (32-bit). Cryptographic strength is unnecessary;
// we only need distinct cache keys for distinct header combinations.
// See: https://en.wikipedia.org/wiki/Fowler%E2%80%93Noll%E2%80%93Vo_hash_function
var FNV_OFFSET_BASIS = 2166136261;
var FNV_PRIME = 16777619;
var hash = FNV_OFFSET_BASIS;
for (var j = 0; j < key.length; j++) {
hash ^= key.charCodeAt(j);
hash = (hash * FNV_PRIME) | 0;
}
event.request.headers['x-nextjs-cache-key'] = { value: String(hash >>> 0) };
}
return event.request;
}
",
"FunctionConfig": {
"Comment": "us-west-2ServerlessWebappCacheKeyFunction86D1ABE9",
"Runtime": "cloudfront-js-2.0",
},
"Name": "us-west-2ServerlessWebappCacheKeyFunction86D1ABE9",
},
"Type": "AWS::CloudFront::Function",
},
"WebappCloudFrontInvalidation588CF152": {
"DeletionPolicy": "Delete",
"DependsOn": [
Expand Down Expand Up @@ -3918,6 +3980,7 @@ service iptables save",
"X-HTTP-Method-Override",
"X-HTTP-Method",
"X-Method-Override",
"x-nextjs-cache-key",
],
},
"QueryStringsConfig": {
Expand Down
Loading