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 { ...@@ -27,7 +27,7 @@ import {
import { BaseServerSpan } from '../../server/lib/trace/constants' with { 'turbopack-transition': 'next-server-utility' } 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 { stripFlightHeaders } from '../../server/app-render/strip-flight-headers' with { 'turbopack-transition': 'next-server-utility' }
import { import {
hasInvalidFlightRouterStateHeader, isInvalidFlightRouterStateError,
parseRequestHeaders, parseRequestHeaders,
type ParsedRequestHeaders, type ParsedRequestHeaders,
} from '../../server/route-modules/app-page/parse-request-headers' with { 'turbopack-transition': 'next-server-utility' } } from '../../server/route-modules/app-page/parse-request-headers' with { 'turbopack-transition': 'next-server-utility' }
...@@ -778,22 +778,6 @@ export function createAppPageEntrypoint({ ...@@ -778,22 +778,6 @@ export function createAppPageEntrypoint({
stripFlightHeaders(req.headers) 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 = { const ComponentMod = {
...entryBase, ...entryBase,
tree, tree,
...@@ -1871,23 +1855,43 @@ export function createAppPageEntrypoint({ ...@@ -1871,23 +1855,43 @@ export function createAppPageEntrypoint({
throw new NoFallbackError() throw new NoFallbackError()
} }
const cacheEntry = await routeModule.handleResponse({ let cacheEntry: Awaited<ReturnType<typeof routeModule.handleResponse>>
cacheKey: ssgCacheKey, try {
responseGenerator: (c) => cacheEntry = await routeModule.handleResponse({
responseGenerator({ cacheKey: ssgCacheKey,
span, responseGenerator: (c) =>
...c, responseGenerator({
}), span,
routeKind: RouteKind.APP_PAGE, ...c,
isOnDemandRevalidate, }),
isRoutePPREnabled, routeKind: RouteKind.APP_PAGE,
req, isOnDemandRevalidate,
nextConfig, isRoutePPREnabled,
previewProps, req,
prerenderManifest, nextConfig,
waitUntil: ctx.waitUntil, previewProps,
isMinimalMode, 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 (cacheEntry !== null && 'error' in cacheEntry) {
if (res.headersSent || res.writableEnded) { if (res.headersSent || res.writableEnded) {
......
...@@ -39,7 +39,7 @@ import { toNodeOutgoingHttpHeaders } from '../../server/web/utils' ...@@ -39,7 +39,7 @@ import { toNodeOutgoingHttpHeaders } from '../../server/web/utils'
import type { RequestMeta } from '../../server/request-meta' import type { RequestMeta } from '../../server/request-meta'
import { createDevRenderContext } from '../../server/route-modules/app-page/dev-render-context' import { createDevRenderContext } from '../../server/route-modules/app-page/dev-render-context'
import { import {
hasInvalidFlightRouterStateHeader, isInvalidFlightRouterStateError,
parseRequestHeaders, parseRequestHeaders,
type ParsedRequestHeaders, type ParsedRequestHeaders,
} from '../../server/route-modules/app-page/parse-request-headers' } from '../../server/route-modules/app-page/parse-request-headers'
...@@ -408,6 +408,23 @@ async function requestHandler( ...@@ -408,6 +408,23 @@ async function requestHandler(
if (!closeController.isClosed) { if (!closeController.isClosed) {
closeController.dispatchClose() 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 const silenceLog = false
await pageRouteModule.onRequestError( await pageRouteModule.onRequestError(
baseReq, baseReq,
...@@ -425,26 +442,6 @@ async function requestHandler( ...@@ -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() const tracer = getTracer()
return tracer.withPropagatedContext(req.headers, () => return tracer.withPropagatedContext(req.headers, () =>
......
...@@ -2,6 +2,35 @@ import type { FlightRouterState } from '../../shared/lib/app-router-types' ...@@ -2,6 +2,35 @@ import type { FlightRouterState } from '../../shared/lib/app-router-types'
import { flightRouterStateSchema } from './types' import { flightRouterStateSchema } from './types'
import { assert } from 'next/dist/compiled/superstruct' 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( export function parseAndValidateFlightRouterState(
stateHeader: string | string[] stateHeader: string | string[]
): FlightRouterState ): FlightRouterState
...@@ -18,7 +47,7 @@ export function parseAndValidateFlightRouterState( ...@@ -18,7 +47,7 @@ export function parseAndValidateFlightRouterState(
return undefined return undefined
} }
if (Array.isArray(stateHeader)) { if (Array.isArray(stateHeader)) {
throw new Error( throw new InvalidFlightRouterStateError(
'Multiple router state headers were sent. This is not allowed.' 'Multiple router state headers were sent. This is not allowed.'
) )
} }
...@@ -29,7 +58,9 @@ export function parseAndValidateFlightRouterState( ...@@ -29,7 +58,9 @@ export function parseAndValidateFlightRouterState(
// This is around 2,000 nested or parallel route segment states: // This is around 2,000 nested or parallel route segment states:
// '{"children":["",{}]}'.length === 20. // '{"children":["",{}]}'.length === 20.
if (stateHeader.length > 20 * 2000) { 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 { try {
...@@ -37,6 +68,8 @@ export function parseAndValidateFlightRouterState( ...@@ -37,6 +68,8 @@ export function parseAndValidateFlightRouterState(
assert(state, flightRouterStateSchema) assert(state, flightRouterStateSchema)
return state return state
} catch { } 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 type { IncomingHttpHeaders } from 'http'
import { import {
hasInvalidFlightRouterStateHeader, isInvalidFlightRouterStateError,
parseRequestHeaders, parseRequestHeaders,
} from './parse-request-headers' } 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( const validTree = encodeURIComponent(
JSON.stringify([ JSON.stringify([
...@@ -32,6 +51,8 @@ const legacyTree = encodeURIComponent( ...@@ -32,6 +51,8 @@ const legacyTree = encodeURIComponent(
]) ])
) )
const options = { isRoutePPREnabled: false, previewModeId: undefined }
function rscHeaders( function rscHeaders(
stateTree: string | string[] | undefined, stateTree: string | string[] | undefined,
extra: IncomingHttpHeaders = {} extra: IncomingHttpHeaders = {}
...@@ -39,59 +60,103 @@ function rscHeaders( ...@@ -39,59 +60,103 @@ function rscHeaders(
return { rsc: '1', 'next-router-state-tree': stateTree, ...extra } return { rsc: '1', 'next-router-state-tree': stateTree, ...extra }
} }
describe('hasInvalidFlightRouterStateHeader', () => { function getParseError(headers: IncomingHttpHeaders, opts = options) {
const options = { isRoutePPREnabled: false } 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( expect(
hasInvalidFlightRouterStateHeader(rscHeaders(validTree), options) parseRequestHeaders(rscHeaders(validTree), options).flightRouterState
).toBe(false) ).toEqual(JSON.parse(decodeURIComponent(validTree)))
expect(parseSpy).toHaveBeenCalledTimes(1)
}) })
it('accepts a missing header', () => { it('accepts a missing header', () => {
expect(hasInvalidFlightRouterStateHeader({ rsc: '1' }, options)).toBe(false) expect(
parseRequestHeaders({ rsc: '1' }, options).flightRouterState
).toBeUndefined()
}) })
it.each([ it.each([
['a header from an older Next.js version', legacyTree], [
['malformed JSON', '%5B'], 'a header from an older Next.js version',
['a schema mismatch', encodeURIComponent(JSON.stringify(['', '']))], legacyTree,
['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)], ],
['a header sent multiple times', [validTree, validTree]], [
])('rejects %s', (_, stateTree) => { 'malformed JSON',
expect( '%5B',
hasInvalidFlightRouterStateHeader(rscHeaders(stateTree), options) 'The router state header was sent but could not be parsed.',
).toBe(true) ],
[
'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', () => { it('ignores the header on non-RSC requests', () => {
expect( expect(
hasInvalidFlightRouterStateHeader( parseRequestHeaders({ 'next-router-state-tree': legacyTree }, options)
{ 'next-router-state-tree': legacyTree }, .flightRouterState
options ).toBeUndefined()
) expect(parseSpy).not.toHaveBeenCalled()
).toBe(false)
}) })
it('ignores the header on prefetches of PPR-enabled routes', () => { it('ignores the header on prefetches of PPR-enabled routes', () => {
const headers = rscHeaders(legacyTree, { 'next-router-prefetch': '1' }) const headers = rscHeaders(legacyTree, { 'next-router-prefetch': '1' })
expect( expect(
hasInvalidFlightRouterStateHeader(headers, { isRoutePPREnabled: true }) parseRequestHeaders(headers, { ...options, isRoutePPREnabled: true })
).toBe(false) .flightRouterState
expect( ).toBeUndefined()
hasInvalidFlightRouterStateHeader(headers, { isRoutePPREnabled: false }) expect(parseSpy).not.toHaveBeenCalled()
).toBe(true) expect(isInvalidFlightRouterStateError(getParseError(headers))).toBe(true)
}) })
})
it('agrees with parseRequestHeaders', () => { describe('isInvalidFlightRouterStateError', () => {
const parseOptions = { isRoutePPREnabled: false, previewModeId: undefined } 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( it.each([
parseRequestHeaders(rscHeaders(validTree), parseOptions).flightRouterState ['an ordinary error', new Error('The router state header was too large.')],
).toBeDefined() ['an error with another code', Object.assign(new Error(), { code: 'X' })],
expect(() => ['a string', 'NEXT_INVALID_FLIGHT_ROUTER_STATE'],
parseRequestHeaders(rscHeaders(legacyTree), parseOptions) ['null', null],
).toThrow('The router state header was sent but could not be parsed.') ['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 ...@@ -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 { parseAndValidateFlightRouterState } from '../../app-render/parse-and-validate-flight-router-state'
import { getPreviouslyRevalidatedTags } from '../../server-utils' 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 { interface ParseRequestHeadersOptions {
readonly isRoutePPREnabled: boolean readonly isRoutePPREnabled: boolean
readonly previewModeId: string | undefined readonly previewModeId: string | undefined
...@@ -49,57 +53,6 @@ export interface ParsedRequestHeaders { ...@@ -49,57 +53,6 @@ export interface ParsedRequestHeaders {
readonly htmlRequestId: string | undefined 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( export function parseRequestHeaders(
headers: IncomingHttpHeaders, headers: IncomingHttpHeaders,
options: ParseRequestHeadersOptions options: ParseRequestHeadersOptions
...@@ -132,14 +85,10 @@ export function parseRequestHeaders( ...@@ -132,14 +85,10 @@ export function parseRequestHeaders(
const isHmrRefresh = headers[NEXT_HMR_REFRESH_HEADER] !== undefined const isHmrRefresh = headers[NEXT_HMR_REFRESH_HEADER] !== undefined
// Request handlers reject invalid headers with a 400 before rendering (see const shouldProvideFlightRouterState =
// `hasInvalidFlightRouterStateHeader`), so this only throws for callers that isRSCRequest && (!isPrefetchRequest || !options.isRoutePPREnabled)
// don't perform that check.
const flightRouterState = shouldProvideFlightRouterState( const flightRouterState = shouldProvideFlightRouterState
isRSCRequest,
isPrefetchRequest,
options.isRoutePPREnabled
)
? parseAndValidateFlightRouterState(headers[NEXT_ROUTER_STATE_TREE_HEADER]) ? parseAndValidateFlightRouterState(headers[NEXT_ROUTER_STATE_TREE_HEADER])
: undefined : 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