Skip to content

Commit bc26e9a

Browse files
authored
Fix for readonly headers lambda@edge (#433)
* fix for readonly headers cloudfront lambda@edge * Create flat-coats-train.md
1 parent 22e80d7 commit bc26e9a

File tree

2 files changed

+24
-3
lines changed

2 files changed

+24
-3
lines changed

.changeset/flat-coats-train.md

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
"open-next": patch
3+
---
4+
5+
Fix for readonly headers lambda@edge

packages/open-next/src/converters/aws-cloudfront.ts

Lines changed: 19 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -50,6 +50,19 @@ const CloudFrontBlacklistedHeaders = [
5050
"x-real-ip",
5151
];
5252

53+
// Read-only headers, see: https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/edge-function-restrictions-all.html#function-restrictions-read-only-headers
54+
// We should only remove these headers when directly responding in lambda@edge, not for the external middleware
55+
const cloudfrontReadOnlyHeaders = [
56+
"accept-encoding",
57+
"content-length",
58+
"if-modified-since",
59+
"if-none-match",
60+
"if-range",
61+
"if-unmodified-since",
62+
"transfer-encoding",
63+
"via",
64+
];
65+
5366
function normalizeCloudFrontRequestEventHeaders(
5467
rawHeaders: CloudFrontHeaders,
5568
): Record<string, string> {
@@ -97,14 +110,17 @@ type MiddlewareEvent = {
97110

98111
function convertToCloudfrontHeaders(
99112
headers: Record<string, OutgoingHttpHeader>,
113+
directResponse?: boolean,
100114
) {
101115
const cloudfrontHeaders: CloudFrontHeaders = {};
102116
Object.entries(headers)
103117
.filter(
104118
([key]) =>
105119
!CloudFrontBlacklistedHeaders.some((header) =>
106120
typeof header === "string" ? header === key : header.test(key),
107-
),
121+
) &&
122+
// Only remove read-only headers when directly responding in lambda@edge
123+
(directResponse ? !cloudfrontReadOnlyHeaders.includes(key) : true),
108124
)
109125
.forEach(([key, value]) => {
110126
if (key === "set-cookie") {
@@ -146,7 +162,7 @@ async function convertToCloudFrontRequestResult(
146162
const cloudfrontResult = {
147163
status: externalResult.statusCode.toString(),
148164
statusDescription: "OK",
149-
headers: convertToCloudfrontHeaders(externalResult.headers),
165+
headers: convertToCloudfrontHeaders(externalResult.headers, true),
150166
bodyEncoding: externalResult.isBase64Encoded
151167
? ("base64" as const)
152168
: ("text" as const),
@@ -195,7 +211,7 @@ async function convertToCloudFrontRequestResult(
195211
const response: CloudFrontRequestResult = {
196212
status: result.statusCode.toString(),
197213
statusDescription: "OK",
198-
headers: convertToCloudfrontHeaders(responseHeaders),
214+
headers: convertToCloudfrontHeaders(responseHeaders, true),
199215
bodyEncoding: result.isBase64Encoded ? "base64" : "text",
200216
body: result.body,
201217
};

0 commit comments

Comments
 (0)