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

Reject invalid router state headers with 400

Stale clients can send router state in an older schema after a deployment. Validate the header before rendering so invalid client input returns 400 without being reported as a server error. Add regression coverage for Node and Edge runtimes, valid requests, document requests, and static pages.
Co-authored-by: 's avatarTobias Koppers <1365881+sokra@users.noreply.github.com>
parent c58836ae
...@@ -27,6 +27,7 @@ import { ...@@ -27,6 +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,
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' }
...@@ -777,6 +778,22 @@ export function createAppPageEntrypoint({ ...@@ -777,6 +778,22 @@ 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,
......
...@@ -39,6 +39,7 @@ import { toNodeOutgoingHttpHeaders } from '../../server/web/utils' ...@@ -39,6 +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,
parseRequestHeaders, parseRequestHeaders,
type ParsedRequestHeaders, type ParsedRequestHeaders,
} from '../../server/route-modules/app-page/parse-request-headers' } from '../../server/route-modules/app-page/parse-request-headers'
...@@ -424,6 +425,26 @@ async function requestHandler( ...@@ -424,6 +425,26 @@ 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, () =>
......
import type { IncomingHttpHeaders } from 'http'
import {
hasInvalidFlightRouterStateHeader,
parseRequestHeaders,
} from './parse-request-headers'
const validTree = encodeURIComponent(
JSON.stringify([
'',
{
children: [['slug', 'foo', 'd', null], { children: ['__PAGE__', {}] }],
},
])
)
// Next.js 15 encoded dynamic segments as a 3-tuple and sent a boolean
// `isRootLayout` flag at index 4.
const legacyTree = encodeURIComponent(
JSON.stringify([
'',
{
children: [
['slug', 'foo', 'd'],
{ children: ['__PAGE__', {}] },
null,
null,
],
},
null,
null,
true,
])
)
function rscHeaders(
stateTree: string | string[] | undefined,
extra: IncomingHttpHeaders = {}
): IncomingHttpHeaders {
return { rsc: '1', 'next-router-state-tree': stateTree, ...extra }
}
describe('hasInvalidFlightRouterStateHeader', () => {
const options = { isRoutePPREnabled: false }
it('accepts a valid header', () => {
expect(
hasInvalidFlightRouterStateHeader(rscHeaders(validTree), options)
).toBe(false)
})
it('accepts a missing header', () => {
expect(hasInvalidFlightRouterStateHeader({ rsc: '1' }, options)).toBe(false)
})
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)
})
it('ignores the header on non-RSC requests', () => {
expect(
hasInvalidFlightRouterStateHeader(
{ 'next-router-state-tree': legacyTree },
options
)
).toBe(false)
})
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)
})
it('agrees with parseRequestHeaders', () => {
const parseOptions = { isRoutePPREnabled: false, previewModeId: undefined }
expect(
parseRequestHeaders(rscHeaders(validTree), parseOptions).flightRouterState
).toBeDefined()
expect(() =>
parseRequestHeaders(rscHeaders(legacyTree), parseOptions)
).toThrow('The router state header was sent but could not be parsed.')
})
})
...@@ -49,6 +49,57 @@ export interface ParsedRequestHeaders { ...@@ -49,6 +49,57 @@ 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
...@@ -81,10 +132,14 @@ export function parseRequestHeaders( ...@@ -81,10 +132,14 @@ export function parseRequestHeaders(
const isHmrRefresh = headers[NEXT_HMR_REFRESH_HEADER] !== undefined const isHmrRefresh = headers[NEXT_HMR_REFRESH_HEADER] !== undefined
const shouldProvideFlightRouterState = // Request handlers reject invalid headers with a 400 before rendering (see
isRSCRequest && (!isPrefetchRequest || !options.isRoutePPREnabled) // `hasInvalidFlightRouterStateHeader`), so this only throws for callers that
// 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
......
export default async function SlugPage({ params }) {
const { slug } = await params
return <h1>{slug}</h1>
}
// Ensures that the flight requests are always handled by the server.
export const dynamic = 'force-dynamic'
export const runtime = 'edge'
export default async function EdgeSlugPage({ params }) {
const { slug } = await params
return <h1>{slug}</h1>
}
export default function StaticPage() {
return <h1>Static</h1>
}
...@@ -4,12 +4,59 @@ import { ...@@ -4,12 +4,59 @@ import {
computeLegacyCacheBustingSearchParam, computeLegacyCacheBustingSearchParam,
} from 'next/dist/shared/lib/router/utils/cache-busting-search-param' } from 'next/dist/shared/lib/router/utils/cache-busting-search-param'
// Builds a router state tree for `/<prefix...>/<slug>`, where `<slug>` is a
// dynamic `[slug]` segment.
function createStateTree(
prefixSegments: string[],
slug: string,
{ legacy }: { legacy: boolean }
): string {
// Next.js 15 encoded dynamic segments as a 3-tuple and sent a boolean
// `isRootLayout` flag at index 4. Tabs that are still running an older
// build send this shape after a deployment.
let tree: unknown[] = legacy
? [['slug', slug, 'd'], { children: ['__PAGE__', {}] }, null, null]
: [['slug', slug, 'd', null], { children: ['__PAGE__', {}] }]
for (const segment of [...prefixSegments].reverse()) {
tree = [segment, { children: tree }]
}
const root = legacy
? ['', { children: tree }, null, null, true]
: ['', { children: tree }]
return encodeURIComponent(JSON.stringify(root))
}
async function fetchWithRouterState(
next: ReturnType<typeof nextTestSetup>['next'],
pathname: string,
stateTree: string,
{ rsc = true }: { rsc?: boolean } = {}
) {
const url = new URL(pathname, 'http://localhost')
const cacheBustingParam = await computeCacheBustingSearchParam(
undefined,
undefined,
stateTree,
undefined
)
if (cacheBustingParam) {
url.searchParams.set('_rsc', cacheBustingParam)
}
return next.fetch(url.pathname + url.search, {
headers: rsc
? { rsc: '1', 'next-router-state-tree': stateTree }
: { 'next-router-state-tree': stateTree },
})
}
describe('app dir - validation', () => { describe('app dir - validation', () => {
const { next } = nextTestSetup({ const { next, isNextDev } = nextTestSetup({
files: __dirname, files: __dirname,
}) })
it('should error when passing invalid router state tree', async () => { it('should reject an invalid router state tree with a 400', async () => {
const stateTree1 = JSON.stringify(['', '']) const stateTree1 = JSON.stringify(['', ''])
const stateTree2 = JSON.stringify(['', {}]) const stateTree2 = JSON.stringify(['', {}])
...@@ -48,12 +95,75 @@ describe('app dir - validation', () => { ...@@ -48,12 +95,75 @@ describe('app dir - validation', () => {
} }
const res = await next.fetch(url1.toString(), { headers: headers1 }) const res = await next.fetch(url1.toString(), { headers: headers1 })
expect(res.status).toBe(500) expect(res.status).toBe(400)
expect(res.headers.get('cache-control')).toBe(
'private, no-cache, no-store, max-age=0, must-revalidate'
)
expect(await res.text()).toBe('Bad Request')
const res2 = await next.fetch(url2.toString(), { headers: headers2 }) const res2 = await next.fetch(url2.toString(), { headers: headers2 })
expect(res2.status).toBe(200) expect(res2.status).toBe(200)
}) })
describe.each([
{ runtime: 'nodejs', prefixSegments: [] },
{ runtime: 'edge', prefixSegments: ['edge'] },
])('$runtime runtime', ({ prefixSegments }) => {
const pathname = `/${[...prefixSegments, 'foo'].join('/')}`
it('should reject a router state tree sent by an older Next.js version with a 400', async () => {
const outputIndex = next.cliOutput.length
const res = await fetchWithRouterState(
next,
pathname,
createStateTree(prefixSegments, 'foo', { legacy: true })
)
expect(res.status).toBe(400)
expect(res.headers.get('cache-control')).toBe(
'private, no-cache, no-store, max-age=0, must-revalidate'
)
expect(await res.text()).toBe('Bad Request')
// Invalid client input is not a server error.
expect(next.cliOutput.slice(outputIndex)).not.toContain(
'The router state header was sent but could not be parsed'
)
})
it('should accept a valid router state tree', async () => {
const res = await fetchWithRouterState(
next,
pathname,
createStateTree(prefixSegments, 'foo', { legacy: false })
)
expect(res.status).toBe(200)
})
})
it('should accept an RSC request without a router state tree', async () => {
const res = await next.fetch('/foo', { headers: { rsc: '1' } })
expect(res.status).toBe(200)
})
it('should ignore an invalid router state tree on a document request', async () => {
const res = await fetchWithRouterState(
next,
'/foo',
createStateTree([], 'foo', { legacy: true }),
{ rsc: false }
)
expect(res.status).toBe(200)
})
it('should only validate the router state tree when a static page renders it', async () => {
const res = await fetchWithRouterState(next, '/static', '%5B')
// Production servers strip Flight headers to serve the prebuilt static
// response, so they never read the router state. Development renders it.
expect(res.status).toBe(isNextDev ? 400 : 200)
})
it('should generate distinct cache-busting params for known colliding RSC variants', async () => { it('should generate distinct cache-busting params for known colliding RSC variants', async () => {
const stateTree = '%5B%22%22%2C%7B%7D%5D' const stateTree = '%5B%22%22%2C%7B%7D%5D'
......
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