Skip to content

Commit

Permalink
Fix for readonly headers lambda@edge (#433)
Browse files Browse the repository at this point in the history
* fix for readonly headers cloudfront lambda@edge

* Create flat-coats-train.md
  • Loading branch information
conico974 authored Jun 9, 2024
1 parent 22e80d7 commit bc26e9a
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 3 deletions.
5 changes: 5 additions & 0 deletions .changeset/flat-coats-train.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"open-next": patch
---

Fix for readonly headers lambda@edge
22 changes: 19 additions & 3 deletions packages/open-next/src/converters/aws-cloudfront.ts
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,19 @@ const CloudFrontBlacklistedHeaders = [
"x-real-ip",
];

// Read-only headers, see: https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/edge-function-restrictions-all.html#function-restrictions-read-only-headers
// We should only remove these headers when directly responding in lambda@edge, not for the external middleware
const cloudfrontReadOnlyHeaders = [
"accept-encoding",
"content-length",
"if-modified-since",
"if-none-match",
"if-range",
"if-unmodified-since",
"transfer-encoding",
"via",
];

function normalizeCloudFrontRequestEventHeaders(
rawHeaders: CloudFrontHeaders,
): Record<string, string> {
Expand Down Expand Up @@ -97,14 +110,17 @@ type MiddlewareEvent = {

function convertToCloudfrontHeaders(
headers: Record<string, OutgoingHttpHeader>,
directResponse?: boolean,
) {
const cloudfrontHeaders: CloudFrontHeaders = {};
Object.entries(headers)
.filter(
([key]) =>
!CloudFrontBlacklistedHeaders.some((header) =>
typeof header === "string" ? header === key : header.test(key),
),
) &&
// Only remove read-only headers when directly responding in lambda@edge
(directResponse ? !cloudfrontReadOnlyHeaders.includes(key) : true),
)
.forEach(([key, value]) => {
if (key === "set-cookie") {
Expand Down Expand Up @@ -146,7 +162,7 @@ async function convertToCloudFrontRequestResult(
const cloudfrontResult = {
status: externalResult.statusCode.toString(),
statusDescription: "OK",
headers: convertToCloudfrontHeaders(externalResult.headers),
headers: convertToCloudfrontHeaders(externalResult.headers, true),
bodyEncoding: externalResult.isBase64Encoded
? ("base64" as const)
: ("text" as const),
Expand Down Expand Up @@ -195,7 +211,7 @@ async function convertToCloudFrontRequestResult(
const response: CloudFrontRequestResult = {
status: result.statusCode.toString(),
statusDescription: "OK",
headers: convertToCloudfrontHeaders(responseHeaders),
headers: convertToCloudfrontHeaders(responseHeaders, true),
bodyEncoding: result.isBase64Encoded ? "base64" : "text",
body: result.body,
};
Expand Down

0 comments on commit bc26e9a

Please sign in to comment.