Unverified Commit adacbfbe authored by vercel-fleet-prod[bot]'s avatar vercel-fleet-prod[bot] Committed by GitHub

Map router state parse errors to 400 without a second parse

Remove the up-front router state validation so each request parses the header once, as before. Invalid headers now throw a marked error from the parser, which the Node and Edge handlers answer with a 400 instead of reporting it as a server error.
Co-authored-by: 's avatarTobias Koppers <1365881+sokra@users.noreply.github.com>
parent 038e61df
......@@ -27,7 +27,7 @@ import {
import { BaseServerSpan } from '../../server/lib/trace/constants' with { 'turbopack-transition': 'next-server-utility' }
import { stripFlightHeaders } from '../../server/app-render/strip-flight-headers' with { 'turbopack-transition': 'next-server-utility' }
import {
hasInvalidFlightRouterStateHeader,
isInvalidFlightRouterStateError,
parseRequestHeaders,
type ParsedRequestHeaders,
} from '../../server/route-modules/app-page/parse-request-headers' with { 'turbopack-transition': 'next-server-utility' }
......@@ -778,22 +778,6 @@ export function createAppPageEntrypoint({
stripFlightHeaders(req.headers)
}
// A router state header that can't be accepted is invalid client input
// (e.g. a tab still running a previous build after a deployment). Reject it
// before rendering instead of failing the render with a 500. The client
// router falls back to a document navigation for non-OK responses.
if (hasInvalidFlightRouterStateHeader(req.headers, { isRoutePPREnabled })) {
res.statusCode = 400
res.setHeader(
'Cache-Control',
'private, no-cache, no-store, max-age=0, must-revalidate'
)
res.setHeader('Content-Type', 'text/plain; charset=utf-8')
res.end('Bad Request')
ctx.waitUntil?.(Promise.resolve())
return null
}
const ComponentMod = {
...entryBase,
tree,
......@@ -1871,23 +1855,43 @@ export function createAppPageEntrypoint({
throw new NoFallbackError()
}
const cacheEntry = await routeModule.handleResponse({
cacheKey: ssgCacheKey,
responseGenerator: (c) =>
responseGenerator({
span,
...c,
}),
routeKind: RouteKind.APP_PAGE,
isOnDemandRevalidate,
isRoutePPREnabled,
req,
nextConfig,
previewProps,
prerenderManifest,
waitUntil: ctx.waitUntil,
isMinimalMode,
})
let cacheEntry: Awaited<ReturnType<typeof routeModule.handleResponse>>
try {
cacheEntry = await routeModule.handleResponse({
cacheKey: ssgCacheKey,
responseGenerator: (c) =>
responseGenerator({
span,
...c,
}),
routeKind: RouteKind.APP_PAGE,
isOnDemandRevalidate,
isRoutePPREnabled,
req,
nextConfig,
previewProps,
prerenderManifest,
waitUntil: ctx.waitUntil,
isMinimalMode,
})
} catch (err) {
// The render parses the router state header before it starts. A header
// that can't be accepted is invalid client input (e.g. a tab still
// running a previous build after a deployment), not a server error, so
// answer with a 400 instead of reporting it. The client router falls
// back to a document navigation for non-OK responses.
if (isInvalidFlightRouterStateError(err) && !res.headersSent) {
res.statusCode = 400
res.setHeader(
'Cache-Control',
'private, no-cache, no-store, max-age=0, must-revalidate'
)
res.setHeader('Content-Type', 'text/plain; charset=utf-8')
res.end('Bad Request')
return null
}
throw err
}
if (cacheEntry !== null && 'error' in cacheEntry) {
if (res.headersSent || res.writableEnded) {
......
......@@ -39,7 +39,7 @@ import { toNodeOutgoingHttpHeaders } from '../../server/web/utils'
import type { RequestMeta } from '../../server/request-meta'
import { createDevRenderContext } from '../../server/route-modules/app-page/dev-render-context'
import {
hasInvalidFlightRouterStateHeader,
isInvalidFlightRouterStateError,
parseRequestHeaders,
type ParsedRequestHeaders,
} from '../../server/route-modules/app-page/parse-request-headers'
......@@ -408,6 +408,23 @@ async function requestHandler(
if (!closeController.isClosed) {
closeController.dispatchClose()
}
// The router state header is parsed before the render starts. A header
// that can't be accepted is invalid client input (e.g. a tab still
// running a previous build after a deployment), not a server error, so
// answer with a 400 instead of reporting it. The client router falls back
// to a document navigation for non-OK responses.
if (isInvalidFlightRouterStateError(err)) {
return new Response('Bad Request', {
status: 400,
headers: {
'Cache-Control':
'private, no-cache, no-store, max-age=0, must-revalidate',
'Content-Type': 'text/plain; charset=utf-8',
},
})
}
const silenceLog = false
await pageRouteModule.onRequestError(
baseReq,
......@@ -425,26 +442,6 @@ async function requestHandler(
}
}
// A router state header that can't be accepted is invalid client input
// (e.g. a tab still running a previous build after a deployment). Reject it
// before rendering instead of failing the render with a 500. The client
// router falls back to a document navigation for non-OK responses.
if (
hasInvalidFlightRouterStateHeader(baseReq.headers, {
isRoutePPREnabled:
renderContextBase.renderOpts.experimental.isRoutePPREnabled === true,
})
) {
return new Response('Bad Request', {
status: 400,
headers: {
'Cache-Control':
'private, no-cache, no-store, max-age=0, must-revalidate',
'Content-Type': 'text/plain; charset=utf-8',
},
})
}
const tracer = getTracer()
return tracer.withPropagatedContext(req.headers, () =>
......
......@@ -2,6 +2,35 @@ import type { FlightRouterState } from '../../shared/lib/app-router-types'
import { flightRouterStateSchema } from './types'
import { assert } from 'next/dist/compiled/superstruct'
const INVALID_FLIGHT_ROUTER_STATE_ERROR_CODE =
'NEXT_INVALID_FLIGHT_ROUTER_STATE'
/**
* Thrown when the router state header can't be accepted. This is invalid
* client input (e.g. a tab still running a previous build after a deployment),
* so request handlers respond with a 400 instead of treating it as a server
* error.
*/
class InvalidFlightRouterStateError extends Error {
readonly code = INVALID_FLIGHT_ROUTER_STATE_ERROR_CODE
}
/**
* Checks for an `InvalidFlightRouterStateError` by its code rather than with
* `instanceof`, because the error may be thrown and caught by different
* bundle layers.
*/
export function isInvalidFlightRouterStateError(
err: unknown
): err is InvalidFlightRouterStateError {
return (
typeof err === 'object' &&
err !== null &&
'code' in err &&
err.code === INVALID_FLIGHT_ROUTER_STATE_ERROR_CODE
)
}
export function parseAndValidateFlightRouterState(
stateHeader: string | string[]
): FlightRouterState
......@@ -18,7 +47,7 @@ export function parseAndValidateFlightRouterState(
return undefined
}
if (Array.isArray(stateHeader)) {
throw new Error(
throw new InvalidFlightRouterStateError(
'Multiple router state headers were sent. This is not allowed.'
)
}
......@@ -29,7 +58,9 @@ export function parseAndValidateFlightRouterState(
// This is around 2,000 nested or parallel route segment states:
// '{"children":["",{}]}'.length === 20.
if (stateHeader.length > 20 * 2000) {
throw new Error('The router state header was too large.')
throw new InvalidFlightRouterStateError(
'The router state header was too large.'
)
}
try {
......@@ -37,6 +68,8 @@ export function parseAndValidateFlightRouterState(
assert(state, flightRouterStateSchema)
return state
} catch {
throw new Error('The router state header was sent but could not be parsed.')
throw new InvalidFlightRouterStateError(
'The router state header was sent but could not be parsed.'
)
}
}
import type { IncomingHttpHeaders } from 'http'
import {
hasInvalidFlightRouterStateHeader,
isInvalidFlightRouterStateError,
parseRequestHeaders,
} from './parse-request-headers'
import { parseAndValidateFlightRouterState } from '../../app-render/parse-and-validate-flight-router-state'
jest.mock('../../app-render/parse-and-validate-flight-router-state', () => {
const actual = jest.requireActual(
'../../app-render/parse-and-validate-flight-router-state'
)
return {
...actual,
parseAndValidateFlightRouterState: jest.fn(
actual.parseAndValidateFlightRouterState
),
}
})
const parseSpy = jest.mocked(parseAndValidateFlightRouterState)
beforeEach(() => {
parseSpy.mockClear()
})
const validTree = encodeURIComponent(
JSON.stringify([
......@@ -32,6 +51,8 @@ const legacyTree = encodeURIComponent(
])
)
const options = { isRoutePPREnabled: false, previewModeId: undefined }
function rscHeaders(
stateTree: string | string[] | undefined,
extra: IncomingHttpHeaders = {}
......@@ -39,59 +60,103 @@ function rscHeaders(
return { rsc: '1', 'next-router-state-tree': stateTree, ...extra }
}
describe('hasInvalidFlightRouterStateHeader', () => {
const options = { isRoutePPREnabled: false }
function getParseError(headers: IncomingHttpHeaders, opts = options) {
try {
parseRequestHeaders(headers, opts)
} catch (err) {
return err
}
throw new Error('Expected parseRequestHeaders to throw')
}
it('accepts a valid header', () => {
describe('parseRequestHeaders router state', () => {
it('parses a valid header once', () => {
expect(
hasInvalidFlightRouterStateHeader(rscHeaders(validTree), options)
).toBe(false)
parseRequestHeaders(rscHeaders(validTree), options).flightRouterState
).toEqual(JSON.parse(decodeURIComponent(validTree)))
expect(parseSpy).toHaveBeenCalledTimes(1)
})
it('accepts a missing header', () => {
expect(hasInvalidFlightRouterStateHeader({ rsc: '1' }, options)).toBe(false)
expect(
parseRequestHeaders({ rsc: '1' }, options).flightRouterState
).toBeUndefined()
})
it.each([
['a header from an older Next.js version', legacyTree],
['malformed JSON', '%5B'],
['a schema mismatch', encodeURIComponent(JSON.stringify(['', '']))],
['a malformed URI encoding', '%E0%A4%A'],
['a header that is too large', 'a'.repeat(20 * 2000 + 1)],
['a header sent multiple times', [validTree, validTree]],
])('rejects %s', (_, stateTree) => {
expect(
hasInvalidFlightRouterStateHeader(rscHeaders(stateTree), options)
).toBe(true)
[
'a header from an older Next.js version',
legacyTree,
'The router state header was sent but could not be parsed.',
],
[
'malformed JSON',
'%5B',
'The router state header was sent but could not be parsed.',
],
[
'a schema mismatch',
encodeURIComponent(JSON.stringify(['', ''])),
'The router state header was sent but could not be parsed.',
],
[
'a malformed URI encoding',
'%E0%A4%A',
'The router state header was sent but could not be parsed.',
],
[
'a header that is too large',
'a'.repeat(20 * 2000 + 1),
'The router state header was too large.',
],
[
'a header sent multiple times',
[validTree, validTree],
'Multiple router state headers were sent. This is not allowed.',
],
])('rejects %s as invalid client input', (_, stateTree, message) => {
const err = getParseError(rscHeaders(stateTree))
expect(isInvalidFlightRouterStateError(err)).toBe(true)
expect((err as Error).message).toBe(message)
expect(parseSpy).toHaveBeenCalledTimes(1)
})
it('ignores the header on non-RSC requests', () => {
expect(
hasInvalidFlightRouterStateHeader(
{ 'next-router-state-tree': legacyTree },
options
)
).toBe(false)
parseRequestHeaders({ 'next-router-state-tree': legacyTree }, options)
.flightRouterState
).toBeUndefined()
expect(parseSpy).not.toHaveBeenCalled()
})
it('ignores the header on prefetches of PPR-enabled routes', () => {
const headers = rscHeaders(legacyTree, { 'next-router-prefetch': '1' })
expect(
hasInvalidFlightRouterStateHeader(headers, { isRoutePPREnabled: true })
).toBe(false)
expect(
hasInvalidFlightRouterStateHeader(headers, { isRoutePPREnabled: false })
).toBe(true)
parseRequestHeaders(headers, { ...options, isRoutePPREnabled: true })
.flightRouterState
).toBeUndefined()
expect(parseSpy).not.toHaveBeenCalled()
expect(isInvalidFlightRouterStateError(getParseError(headers))).toBe(true)
})
})
it('agrees with parseRequestHeaders', () => {
const parseOptions = { isRoutePPREnabled: false, previewModeId: undefined }
describe('isInvalidFlightRouterStateError', () => {
it('recognizes the error by its code, not its class', () => {
// Errors may be thrown and caught by different bundle layers, each with
// its own copy of the error class.
const err = Object.assign(new Error('x'), {
code: 'NEXT_INVALID_FLIGHT_ROUTER_STATE',
})
expect(isInvalidFlightRouterStateError(err)).toBe(true)
})
expect(
parseRequestHeaders(rscHeaders(validTree), parseOptions).flightRouterState
).toBeDefined()
expect(() =>
parseRequestHeaders(rscHeaders(legacyTree), parseOptions)
).toThrow('The router state header was sent but could not be parsed.')
it.each([
['an ordinary error', new Error('The router state header was too large.')],
['an error with another code', Object.assign(new Error(), { code: 'X' })],
['a string', 'NEXT_INVALID_FLIGHT_ROUTER_STATE'],
['null', null],
['undefined', undefined],
])('is false for %s', (_, value) => {
expect(isInvalidFlightRouterStateError(value)).toBe(false)
})
})
......@@ -19,6 +19,10 @@ import { getScriptNonceFromHeaders } from '../../app-render/get-script-nonce-fro
import { parseAndValidateFlightRouterState } from '../../app-render/parse-and-validate-flight-router-state'
import { getPreviouslyRevalidatedTags } from '../../server-utils'
// Request handlers use this to answer an invalid router state header, which
// `parseRequestHeaders` throws for, with a 400.
export { isInvalidFlightRouterStateError } from '../../app-render/parse-and-validate-flight-router-state'
interface ParseRequestHeadersOptions {
readonly isRoutePPREnabled: boolean
readonly previewModeId: string | undefined
......@@ -49,57 +53,6 @@ export interface ParsedRequestHeaders {
readonly htmlRequestId: string | undefined
}
/**
* Whether the router state header is read for this request. Prefetches of
* PPR-enabled routes don't depend on the client's router state.
*/
function shouldProvideFlightRouterState(
isRSCRequest: boolean,
isPrefetchRequest: boolean,
isRoutePPREnabled: boolean
): boolean {
return isRSCRequest && (!isPrefetchRequest || !isRoutePPREnabled)
}
/**
* Returns true when the request carries a router state header that would be
* used for rendering but can't be accepted (sent more than once, too large,
* unparseable, or not matching the expected schema, e.g. because it was sent
* by a client still running an older build after a deployment).
*
* This is invalid client input, so request handlers use this to respond with
* a 400 before rendering instead of failing the render with a 500.
*/
export function hasInvalidFlightRouterStateHeader(
headers: IncomingHttpHeaders,
options: Pick<ParseRequestHeadersOptions, 'isRoutePPREnabled'>
): boolean {
const stateHeader = headers[NEXT_ROUTER_STATE_TREE_HEADER]
if (stateHeader === undefined) {
return false
}
const isRSCRequest = isRSCRequestHeader(headers[RSC_HEADER])
const isPrefetchRequest =
isRSCRequest && headers[NEXT_ROUTER_PREFETCH_HEADER] === '1'
if (
!shouldProvideFlightRouterState(
isRSCRequest,
isPrefetchRequest,
options.isRoutePPREnabled
)
) {
return false
}
try {
parseAndValidateFlightRouterState(stateHeader)
return false
} catch {
return true
}
}
export function parseRequestHeaders(
headers: IncomingHttpHeaders,
options: ParseRequestHeadersOptions
......@@ -132,14 +85,10 @@ export function parseRequestHeaders(
const isHmrRefresh = headers[NEXT_HMR_REFRESH_HEADER] !== undefined
// Request handlers reject invalid headers with a 400 before rendering (see
// `hasInvalidFlightRouterStateHeader`), so this only throws for callers that
// don't perform that check.
const flightRouterState = shouldProvideFlightRouterState(
isRSCRequest,
isPrefetchRequest,
options.isRoutePPREnabled
)
const shouldProvideFlightRouterState =
isRSCRequest && (!isPrefetchRequest || !options.isRoutePPREnabled)
const flightRouterState = shouldProvideFlightRouterState
? parseAndValidateFlightRouterState(headers[NEXT_ROUTER_STATE_TREE_HEADER])
: undefined
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment