Skip to content
Merged
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
5 changes: 5 additions & 0 deletions .changeset/ripe-bottles-fetch.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'astro': patch
---

Fixes internal Astro headers leaking from direct `pages()` handler responses
13 changes: 3 additions & 10 deletions packages/astro/src/core/app/prepare-response.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,9 @@
import { INTERNAL_RESPONSE_HEADERS, responseSentSymbol } from '../constants.js';
import { responseSentSymbol } from '../constants.js';
import { getSetCookiesFromResponse } from '../cookies/index.js';

/**
* Strips internal-only headers from the response before sending it to the
* user agent, and optionally appends cookies written via `Astro.cookie.set()`
* to the `Set-Cookie` header.
* Appends cookies written via `Astro.cookie.set()` to the `Set-Cookie` header
* and marks the response as sent.
*
* This is a pure function with no dependencies on the app; it is shared by
* `AstroHandler` and the various error handlers.
Expand All @@ -13,12 +12,6 @@ export function prepareResponse(
response: Response,
{ addCookieHeader }: { addCookieHeader: boolean },
): void {
for (const headerName of INTERNAL_RESPONSE_HEADERS) {
if (response.headers.has(headerName)) {
response.headers.delete(headerName);
}
}

if (addCookieHeader) {
for (const setCookieHeaderValue of getSetCookiesFromResponse(response)) {
response.headers.append('set-cookie', setCookieHeaderValue);
Expand Down
52 changes: 0 additions & 52 deletions packages/astro/src/core/constants.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,58 +3,6 @@ export const ASTRO_VERSION = process.env.PACKAGE_VERSION ?? 'development';

export const ASTRO_GENERATOR = `Astro v${ASTRO_VERSION}`;

/**
* The name for the header used to help rerouting behavior.
* When set to "no", astro will NOT try to reroute an error response to the corresponding error page, which is the default behavior that can sometimes lead to loops.
*
* ```ts
* const response = new Response("keep this content as-is", {
* status: 404,
* headers: {
* // note that using a variable name as the key of an object needs to be wrapped in square brackets in javascript
* // without them, the header name will be interpreted as "REROUTE_DIRECTIVE_HEADER" instead of "X-Astro-Reroute"
* [REROUTE_DIRECTIVE_HEADER]: 'no',
* }
* })
* ```
* Alternatively...
* ```ts
* response.headers.set(REROUTE_DIRECTIVE_HEADER, 'no');
* ```
*/
export const REROUTE_DIRECTIVE_HEADER = 'X-Astro-Reroute';

/**
* Header and value that are attached to a Response object when a **user rewrite** occurs.
*
* This metadata is used to determine the origin of a Response. If a rewrite has occurred, it should be prioritised over other logic.
*/
export const REWRITE_DIRECTIVE_HEADER_KEY = 'X-Astro-Rewrite';

export const REWRITE_DIRECTIVE_HEADER_VALUE = 'yes';

/**
* This header is set by the no-op Astro middleware.
*/
export const NOOP_MIDDLEWARE_HEADER = 'X-Astro-Noop';

/**
* The name for the header used to help i18n middleware, which only needs to act on "page" and "fallback" route types.
*/
export const ROUTE_TYPE_HEADER = 'X-Astro-Route-Type';

/**
* Internal headers that should be stripped from the response before
* sending it to the user agent. Add new internal headers here so
* `prepareResponse` removes them automatically.
*/
export const INTERNAL_RESPONSE_HEADERS = [
REROUTE_DIRECTIVE_HEADER,
REWRITE_DIRECTIVE_HEADER_KEY,
NOOP_MIDDLEWARE_HEADER,
ROUTE_TYPE_HEADER,
] as const;

/**
* Set by internal handlers (e.g. PagesHandler) to signal that a
* response should be replaced with the corresponding error page.
Expand Down
9 changes: 9 additions & 0 deletions packages/astro/src/core/fetch/fetch-state.ts
Original file line number Diff line number Diff line change
Expand Up @@ -193,6 +193,10 @@ export class FetchState implements AstroFetchState {
clientAddress: string | undefined;
/** Whether this is a partial render (container API). */
partial: boolean | undefined;
/** Internal metadata about the current response route type. */
responseRouteType: 'page' | 'fallback' | undefined;
/** Internal flag to prevent rerouting this response to an error page. */
skipErrorReroute = false;
Comment on lines +196 to +199

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nice!!!

/** Whether to inject CSP meta tags. */
shouldInjectCspMetaTags: boolean | undefined;
/** Request-scoped locals object, shared with user middleware. */
Expand Down Expand Up @@ -1124,4 +1128,9 @@ export class FetchState implements AstroFetchState {
this.actionApiContext = null;
this.apiContext = null;
}

resetResponseMetadata(): void {
this.responseRouteType = undefined;
this.skipErrorReroute = false;
}
}
21 changes: 7 additions & 14 deletions packages/astro/src/core/i18n/handler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@ import { I18nRouter, type I18nRouterContext } from '../../i18n/router.js';
import { PipelineFeatures } from '../base-pipeline.js';
import type { SSRManifest } from '../app/types.js';
import { shouldAppendForwardSlash } from '../build/util.js';
import { REROUTE_DIRECTIVE_HEADER, ROUTE_TYPE_HEADER } from '../constants.js';
import type { FetchState } from '../fetch/fetch-state.js';

/**
Expand Down Expand Up @@ -59,34 +58,28 @@ export class I18n {
async finalize(state: FetchState, response: Response): Promise<Response> {
state.pipeline.usedFeatures |= PipelineFeatures.i18n;
const i18n = this.#i18n;
const typeHeader = response.headers.get(ROUTE_TYPE_HEADER);
// We don't need this header anymore, and we shouldn't pass downstream to users.
if (typeHeader) {
response.headers.delete(ROUTE_TYPE_HEADER);
}

// This is a case where we are internally rendering a 404/500, so we
// need to bypass checks that were done already.
const isReroute = response.headers.get(REROUTE_DIRECTIVE_HEADER);
if (isReroute === 'no' && typeof i18n.fallback === 'undefined') {
if (state.skipErrorReroute && typeof i18n.fallback === 'undefined') {
return response;
}

// If the route we're processing is not a page, then we ignore it
if (typeHeader !== 'page' && typeHeader !== 'fallback') {
if (state.responseRouteType !== 'page' && state.responseRouteType !== 'fallback') {
return response;
}

const url = new URL(state.request.url);
const currentLocale = state.computeCurrentLocale();
const isPrerendered = state.routeData!.prerender;

// Build context for router (typeHeader is guaranteed to be 'page' | 'fallback' here)
// Build context for router (responseRouteType is guaranteed to be 'page' | 'fallback' here)
const routerContext: I18nRouterContext = {
currentLocale,
currentDomain: url.hostname,
routeType: typeHeader as 'page' | 'fallback',
isReroute: isReroute === 'yes',
routeType: state.responseRouteType,
isReroute: false,
};

// Step 1: Apply routing strategy
Expand All @@ -113,7 +106,7 @@ export class I18n {
status: 404,
headers: response.headers,
});
prerenderedRes.headers.set(REROUTE_DIRECTIVE_HEADER, 'no');
state.skipErrorReroute = true;
if (routeDecision.location) {
prerenderedRes.headers.set('Location', routeDecision.location);
}
Expand All @@ -137,7 +130,7 @@ export class I18n {
// The fallback sentinel (X-Astro-Route-Type: fallback, status 500) signals
// that the render pipeline couldn't find this page in the current locale.
// Treat it as a 404 so computeFallbackRoute will apply fallback logic.
const effectiveStatus = typeHeader === 'fallback' ? 404 : response.status;
const effectiveStatus = state.responseRouteType === 'fallback' ? 404 : response.status;
const fallbackDecision = computeFallbackRoute({
pathname: url.pathname,
responseStatus: effectiveStatus,
Expand Down
2 changes: 0 additions & 2 deletions packages/astro/src/core/middleware/noop-middleware.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,6 @@
import type { MiddlewareHandler } from '../../types/public/common.js';
import { NOOP_MIDDLEWARE_HEADER } from '../constants.js';

export const NOOP_MIDDLEWARE_FN: MiddlewareHandler = async (_ctx, next) => {
const response = await next();
response.headers.set(NOOP_MIDDLEWARE_HEADER, 'true');
return response;
};
24 changes: 9 additions & 15 deletions packages/astro/src/core/pages/handler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,7 @@ import { renderPage } from '../../runtime/server/index.js';
import type { APIContext } from '../../types/public/context.js';
import type { FetchState } from '../fetch/fetch-state.js';
import type { Pipeline } from '../base-pipeline.js';
import {
ASTRO_ERROR_HEADER,
REROUTE_DIRECTIVE_HEADER,
REWRITE_DIRECTIVE_HEADER_KEY,
REWRITE_DIRECTIVE_HEADER_VALUE,
ROUTE_TYPE_HEADER,
} from '../constants.js';
import { ASTRO_ERROR_HEADER } from '../constants.js';
import { getCookiesFromResponse } from '../cookies/response.js';

// Shared empty-slots object so we don't allocate `{}` on every render for
Expand Down Expand Up @@ -39,6 +33,7 @@ export class PagesHandler {
async handle(state: FetchState, ctx: APIContext): Promise<Response> {
const pipeline = this.#pipeline;
const { logger, streaming } = pipeline;
state.resetResponseMetadata();

let response: Response;

Expand All @@ -50,6 +45,7 @@ export class PagesHandler {
ctx,
state.routeData!.prerender,
logger,
state,
);
break;
}
Expand All @@ -58,14 +54,14 @@ export class PagesHandler {
const actionApiContext = state.getActionAPIContext();
const result = await state.createResult(componentInstance!, actionApiContext);
try {
response = await renderPage(
response = await renderPage(
result,
componentInstance?.default as any,
props,
state.slots ?? EMPTY_SLOTS,
streaming,
state.routeData!,
);
);
} catch (e) {
// If there is an error in the page's frontmatter or instantiation of the RenderTemplate fails midway,
// we signal to the rest of the internals that we can ignore the results of existing renders and avoid kicking off more of them.
Expand All @@ -74,21 +70,19 @@ export class PagesHandler {
}

// Signal to the i18n middleware to maybe act on this response
response.headers.set(ROUTE_TYPE_HEADER, 'page');
state.responseRouteType = 'page';
// Signal to the error-page-rerouting infra to let this response pass through to avoid loops
if (state.routeData!.route === '/404' || state.routeData!.route === '/500') {
response.headers.set(REROUTE_DIRECTIVE_HEADER, 'no');
}
if (state.isRewriting) {
response.headers.set(REWRITE_DIRECTIVE_HEADER_KEY, REWRITE_DIRECTIVE_HEADER_VALUE);
state.skipErrorReroute = true;
}
break;
}
case 'redirect': {
return new Response(null, { status: 404, headers: { [ASTRO_ERROR_HEADER]: 'true' } });
}
case 'fallback': {
return new Response(null, { status: 500, headers: { [ROUTE_TYPE_HEADER]: 'fallback' } });
state.responseRouteType = 'fallback';
return new Response(null, { status: 500 });
}
}
// We need to merge the cookies from the response back into the cookies
Expand Down
12 changes: 3 additions & 9 deletions packages/astro/src/core/routing/handler.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,6 @@
import { ActionHandler } from '../../actions/handler.js';
import type { APIContext } from '../../types/public/context.js';
import {
REROUTABLE_STATUS_CODES,
REROUTE_DIRECTIVE_HEADER,
REWRITE_DIRECTIVE_HEADER_KEY,
} from '../constants.js';
import { REROUTABLE_STATUS_CODES } from '../constants.js';
import { TrailingSlashHandler } from './trailing-slash-handler.js';
import { CacheHandler, provideCache } from '../cache/handler.js';
import { I18n } from '../i18n/handler.js';
Expand Down Expand Up @@ -159,13 +155,11 @@ export class AstroHandler {
response = await this.#cacheHandler.handle(state, runPipeline);
}

const isRewrite = response.headers.has(REWRITE_DIRECTIVE_HEADER_KEY);

this.#app.logThisRequest({
pathname,
method: request.method,
statusCode: response.status,
isRewrite,
isRewrite: state.isRewriting,
timeStart: state.timeStart,
});
} catch (err: any) {
Expand All @@ -186,7 +180,7 @@ export class AstroHandler {
// If the body isn't null, that means the user sets the 404 status
// but uses the current route to handle the 404
response.body === null &&
response.headers.get(REROUTE_DIRECTIVE_HEADER) !== 'no'
!state.skipErrorReroute
) {
return this.#app.renderError(request, {
...state.renderOptions,
Expand Down
14 changes: 5 additions & 9 deletions packages/astro/src/i18n/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import {
import type { RoutingStrategies } from '../core/app/common.js';
import type { SSRManifest } from '../core/app/types.js';
import { shouldAppendForwardSlash } from '../core/build/util.js';
import { REROUTE_DIRECTIVE_HEADER } from '../core/constants.js';
import { getFetchStateFromAPIContext } from '../core/fetch/fetch-state.js';
import { i18nNoLocaleFoundInPath, MissingLocale } from '../core/errors/errors-data.js';
import { AstroError } from '../core/errors/index.js';
import type { AstroConfig, Locales, ValidRedirectStatus } from '../types/public/config.js';
Expand Down Expand Up @@ -331,10 +331,9 @@ export function redirectToDefaultLocale({
// NOTE: public function exported to the users via `astro:i18n` module
export function notFound({ base, locales, fallback }: MiddlewarePayload) {
return function (context: APIContext, response?: Response): Response | undefined {
if (
response?.headers.get(REROUTE_DIRECTIVE_HEADER) === 'no' &&
typeof fallback === 'undefined'
) {
const fetchState = getFetchStateFromAPIContext(context);

if (fetchState.skipErrorReroute && typeof fallback === 'undefined') {
return response;
}

Expand All @@ -344,18 +343,15 @@ export function notFound({ base, locales, fallback }: MiddlewarePayload) {
// - the URL doesn't contain a locale
const isRoot = url.pathname === base + '/' || url.pathname === base;
if (!(isRoot || pathHasLocale(url.pathname, locales))) {
fetchState.skipErrorReroute = true;
if (response) {
response.headers.set(REROUTE_DIRECTIVE_HEADER, 'no');
return new Response(response.body, {
status: 404,
headers: response.headers,
});
} else {
return new Response(null, {
status: 404,
headers: {
[REROUTE_DIRECTIVE_HEADER]: 'no',
},
});
}
}
Expand Down
22 changes: 5 additions & 17 deletions packages/astro/src/runtime/server/endpoint.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
import colors from 'piccolore';
import { REROUTABLE_STATUS_CODES, REROUTE_DIRECTIVE_HEADER } from '../../core/constants.js';
import { REROUTABLE_STATUS_CODES } from '../../core/constants.js';
import { AstroError } from '../../core/errors/errors.js';
import { EndpointDidNotReturnAResponse } from '../../core/errors/errors-data.js';
import type { FetchState } from '../../core/fetch/fetch-state.js';
import type { AstroLogger } from '../../core/logger/core.js';
import type { APIRoute } from '../../types/public/common.js';
import type { APIContext } from '../../types/public/context.js';
Expand All @@ -14,6 +15,7 @@ export async function renderEndpoint(
context: APIContext,
isPrerendered: boolean,
logger: AstroLogger,
state?: FetchState,
) {
const { request, url } = context;

Expand Down Expand Up @@ -58,28 +60,14 @@ export async function renderEndpoint(
}

let response = await handler.call(mod, context);

if (!response || response instanceof Response === false) {
throw new AstroError(EndpointDidNotReturnAResponse);
}

// Endpoints explicitly returning 404 or 500 response status should
// NOT be subject to rerouting to 404.astro or 500.astro.
if (REROUTABLE_STATUS_CODES.includes(response.status)) {
try {
response.headers.set(REROUTE_DIRECTIVE_HEADER, 'no');
} catch (err) {
// In some cases the response may have immutable headers
// This is the case if, for example, the user directly returns a `fetch` response
// There's no clean way to check if the headers are immutable, so we just catch the error
// Note that response.clone() still has immutable headers!
if ((err as Error).message?.includes('immutable')) {
response = new Response(response.body, response);
response.headers.set(REROUTE_DIRECTIVE_HEADER, 'no');
} else {
throw err;
}
}
if (state && REROUTABLE_STATUS_CODES.includes(response.status)) {
state.skipErrorReroute = true;
}

if (method === 'HEAD') {
Expand Down
Loading
Loading