From 06843121450899ecf0390ca4efaff6c9a6fe0f75 Mon Sep 17 00:00:00 2001 From: Erika <3019731+Princesseuh@users.noreply.github.com> Date: Mon, 15 Apr 2024 05:06:30 -0400 Subject: [PATCH] fix(assets): Forward headers from the original request to the internal request to the image (#10775) --- .changeset/rich-spoons-fold.md | 5 +++++ packages/astro/src/assets/endpoint/generic.ts | 14 +++++++++----- 2 files changed, 14 insertions(+), 5 deletions(-) create mode 100644 .changeset/rich-spoons-fold.md diff --git a/.changeset/rich-spoons-fold.md b/.changeset/rich-spoons-fold.md new file mode 100644 index 000000000000..217562a24ce8 --- /dev/null +++ b/.changeset/rich-spoons-fold.md @@ -0,0 +1,5 @@ +--- +"astro": patch +--- + +Fixes assets endpoint in serverless returning 404 in certain situations where the website might be under a protected route diff --git a/packages/astro/src/assets/endpoint/generic.ts b/packages/astro/src/assets/endpoint/generic.ts index 22b15446da75..5c51f6575534 100644 --- a/packages/astro/src/assets/endpoint/generic.ts +++ b/packages/astro/src/assets/endpoint/generic.ts @@ -7,9 +7,12 @@ import { isRemoteAllowed } from '../utils/remotePattern.js'; // @ts-expect-error import { imageConfig } from 'astro:assets'; -async function loadRemoteImage(src: URL) { +async function loadRemoteImage(src: URL, headers: Headers) { try { - const res = await fetch(src); + const res = await fetch(src, { + // Forward all headers from the original request + headers, + }); if (!res.ok) { return undefined; @@ -41,15 +44,16 @@ export const GET: APIRoute = async ({ request }) => { let inputBuffer: ArrayBuffer | undefined = undefined; - const sourceUrl = isRemotePath(transform.src) + const isRemoteImage = isRemotePath(transform.src); + const sourceUrl = isRemoteImage ? new URL(transform.src) : new URL(transform.src, url.origin); - if (isRemotePath(transform.src) && isRemoteAllowed(transform.src, imageConfig) === false) { + if (isRemoteImage && isRemoteAllowed(transform.src, imageConfig) === false) { return new Response('Forbidden', { status: 403 }); } - inputBuffer = await loadRemoteImage(sourceUrl); + inputBuffer = await loadRemoteImage(sourceUrl, isRemoteImage ? new Headers() : request.headers); if (!inputBuffer) { return new Response('Not Found', { status: 404 });