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

Apply page method guards and 404 status in entrypoint handlers

Adapters invoke the app-page and pages entrypoint handlers directly, so the
OPTIONS (400) and static-page (405) method guards and the 404 status for the
not-found page, which only lived in BaseServer, were skipped: OPTIONS on a
dynamic page rendered it in full and returned 200. Mirror those checks in the
handlers so every adapter gets them.
Co-authored-by: 's avatarTobias Koppers <1365881+sokra@users.noreply.github.com>
parent 44525146
......@@ -342,6 +342,19 @@ export function createAppPageEntrypoint({
return null
}
// Mirrors `BaseServer`, which treats both the not-found route and a `/404`
// page as the 404 page.
const is404Page =
normalizedSrcPage === UNDERSCORE_NOT_FOUND_ROUTE ||
normalizedSrcPage === '/404'
// Ensure the 404 status when the 404 page is invoked directly (e.g. by an
// adapter). This mirrors `BaseServer`, which sets it before invoking this
// handler.
if (is404Page && !isRSCRequest) {
res.statusCode = 404
}
/**
* If the route being rendered is an app page, and the ppr feature has been
* enabled, then the given route _could_ support PPR.
......@@ -440,6 +453,42 @@ export function createAppPageEntrypoint({
addRequestMeta(req, 'postponed', postponed)
}
// Method guards. These mirror the ones in `BaseServer` so that adapters
// that invoke this handler directly (without `NextServer`) reject the same
// requests before anything is rendered.
if (req.method !== 'GET' && req.method !== 'HEAD') {
// Static pages only support GET and HEAD. Server actions and resume
// requests can use other methods.
const isStaticPage =
Boolean(req.headers['x-now-route-matches']) ||
(!routeModule.isDev &&
Boolean(prerenderManifest.routes[normalizedSrcPage]))
// Like `BaseServer`, the 404 and 500 pages are exempt. (`BaseServer` also
// exempts `/_error`, which only exists in the Pages Router.)
if (
isStaticPage &&
!isPossibleServerAction &&
typeof getRequestMeta(req, 'postponed') !== 'string' &&
!is404Page &&
normalizedSrcPage !== '/500'
) {
res.statusCode = 405
res.setHeader('Allow', ['GET', 'HEAD'])
res.end('Method Not Allowed')
ctx.waitUntil?.(Promise.resolve())
return null
}
// An OPTIONS request to a page handler is invalid.
if (req.method === 'OPTIONS' && !is404Page) {
res.statusCode = 400
res.end()
ctx.waitUntil?.(Promise.resolve())
return null
}
}
// When enabled, this will allow the use of the `?__nextppronly` query to
// enable debugging of the static shell.
const hasDebugStaticShellQuery =
......
......@@ -43,6 +43,7 @@ import { isBot } from '../../../shared/lib/router/utils/is-bot'
import { addPathPrefix } from '../../../shared/lib/router/utils/add-path-prefix'
import { removeTrailingSlash } from '../../../shared/lib/router/utils/remove-trailing-slash'
import { isRouteCacheOwner } from '../../lib/route-cache-key'
import { getIsPossibleServerAction } from '../../lib/server-action-request-meta'
import type { PagesRouteModule } from './module.compiled'
import type {
GetServerSideProps,
......@@ -180,10 +181,57 @@ export const getHandler = ({
let isNextDataRequest =
prepareResult.isNextDataRequest && (hasStaticProps || hasServerProps)
const method = req.method || 'GET'
const is404Page = srcPage === '/404'
const is500Page = srcPage === '/500'
const isErrorPage = srcPage === '/_error'
// The guards below mirror the ones in `BaseServer` so that adapters that
// invoke this handler directly (without `NextServer`) get the same
// responses, before any data fetching or rendering happens.
// Ensure the 404 status when the 404 page is invoked directly.
if (is404Page && !isNextDataRequest) {
res.statusCode = 404
}
if (method !== 'GET' && method !== 'HEAD') {
// Static pages only support GET and HEAD.
const isStaticPage =
hasStaticProps ||
Boolean(req.headers['x-now-route-matches']) ||
(!routeModule.isDev && Boolean(prerenderManifest.routes[srcPage]))
if (
isStaticPage &&
!getIsPossibleServerAction(req) &&
typeof getRequestMeta(req, 'postponed') !== 'string' &&
!is404Page &&
!is500Page &&
!isErrorPage
) {
res.statusCode = 405
res.setHeader('Allow', ['GET', 'HEAD'])
res.end('Method Not Allowed')
ctx.waitUntil?.(Promise.resolve())
return
}
// An OPTIONS request to a page handler is invalid. The 404 page (also
// when rendered through `_error`) is exempt.
if (
method === 'OPTIONS' &&
!is404Page &&
!(isErrorPage && res.statusCode === 404)
) {
res.statusCode = 400
res.end()
ctx.waitUntil?.(Promise.resolve())
return
}
}
if (!routeModule.isDev && !isDraftMode && hasStaticProps) {
cacheKey = `${locale ? `/${locale}` : ''}${
(srcPage === '/' || resolvedPathname === '/') && locale
......@@ -255,8 +303,6 @@ export const getHandler = ({
routerServerContext?.isWrappedByNextServer
)
const method = req.method || 'GET'
const resolvedUrl = formatUrl({
pathname: nextConfig.trailingSlash
? `${encodedResolvedPathname}${!encodedResolvedPathname.endsWith('/') && parsedUrl.pathname?.endsWith('/') ? '/' : ''}`
......
// Mimics how deployment platforms invoke a build output through an adapter.
// It reads the outputs passed to the adapter's `onBuildComplete` and calls the
// `handler` export of one Node.js output's entrypoint directly, with
// minimal-mode request metadata. No NextServer is involved, so any request
// validation has to happen in the entrypoint itself.
//
// The entrypoint is loaded from its build location rather than from a copy of
// its traced assets: this suite is about the handler's behavior, not about
// output tracing.
//
// Usage: node adapter-launcher.js <outputs key>:<pathname>
// e.g. node adapter-launcher.js appPages:/dynamic
//
// Request headers used by the test:
// - `x-test-request-id`: echoed in a log line once the handler has finished,
// so the test can wait for all logs produced by the request.
// - `x-test-preset-status`: emulates callers that set the status before
// invoking an error page.
const fs = require('fs')
const http = require('http')
const path = require('path')
const outputId = process.argv[2]
const separator = outputId.indexOf(':')
const outputsKey = outputId.slice(0, separator)
const pathname = outputId.slice(separator + 1)
const { outputs, projectDir, repoRoot } = JSON.parse(
fs.readFileSync(path.join(process.cwd(), 'build-complete.json'), 'utf8')
)
const output = outputs[outputsKey].find(
(item) => item.pathname === pathname && item.runtime === 'nodejs'
)
if (!output) {
throw new Error(`No Node.js output found for ${outputId}`)
}
process.chdir(repoRoot)
const relativeProjectDir = path.relative(repoRoot, projectDir) || '.'
require('next/dist/build/adapter/setup-node-env.external')
const { handler } = require(output.filePath)
http
.createServer((req, res) => {
const presetStatus = req.headers['x-test-preset-status']
if (typeof presetStatus === 'string') {
res.statusCode = Number(presetStatus)
}
Promise.resolve()
.then(() =>
handler(req, res, {
waitUntil: undefined,
requestMeta: {
minimalMode: true,
relativeProjectDir,
initURL: `https://localhost${req.url}`,
},
})
)
.catch((err) => {
console.error('handler error', err)
if (!res.writableEnded) {
res.statusCode = 500
res.end('internal error')
}
})
.finally(() => {
console.log(`__request-done__ ${req.headers['x-test-request-id']}`)
})
})
.listen(Number(process.env.PORT), () =>
console.log(`adapter launcher ready: ${outputId}`)
)
import { spawn, type ChildProcess } from 'child_process'
import path from 'path'
import { nextTestSetup } from 'e2e-utils'
import { findPort, retry } from 'next-test-utils'
// Adapters invoke the entrypoint `handler` of each build output directly,
// without NextServer. The method guards and not-found status that NextServer
// applies must also be applied by the entrypoints themselves.
//
// This suite controls the local build lifecycle directly, which deployment tests cannot reproduce.
// @force-gate !deploy
describe('adapter-page-method-guards', () => {
const { next } = nextTestSetup({
files: __dirname,
skipStart: true,
})
// One launcher (deployed function) per build output, keyed by
// `<outputs key>:<pathname>` as passed to `onBuildComplete`.
const outputIds = [
'appPages:/dynamic',
'appPages:/static',
'appPages:/500',
'appPages:/_not-found',
'appRoutes:/route-handler',
'pages:/ssr',
'pages:/ssg',
'pages:/404',
'pages:/_error',
'pagesApi:/api/hello',
]
const launchers = new Map<
string,
{ process: ChildProcess; port: number; output: { value: string } }
>()
let requestCount = 0
beforeAll(async () => {
await next.build()
for (const outputId of outputIds) {
const port = await findPort()
const output = { value: '' }
const child = spawn(
'node',
[path.join(next.testDir, 'adapter-launcher.js'), outputId],
{
cwd: next.testDir,
env: { ...process.env, PORT: String(port), NODE_ENV: 'production' },
stdio: 'pipe',
}
)
child.stdout?.on('data', (chunk) => (output.value += chunk))
child.stderr?.on('data', (chunk) => (output.value += chunk))
launchers.set(outputId, { process: child, port, output })
}
for (const [outputId, { output }] of launchers) {
await retry(async () => {
expect(output.value).toContain(`adapter launcher ready: ${outputId}`)
})
}
})
afterAll(() => {
for (const { process } of launchers.values()) {
process.kill()
}
})
/**
* Invokes the handler of a build output through its launcher and returns the
* response together with the logs written while handling the request.
*/
async function invoke(
outputId: string,
pathname: string,
init: { method?: string; headers?: Record<string, string> } = {}
) {
const launcher = launchers.get(outputId)
if (!launcher) {
throw new Error(`No launcher for ${outputId}`)
}
const { port, output } = launcher
const requestId = String(++requestCount)
const start = output.value.length
const res = await fetch(`http://localhost:${port}${pathname}`, {
method: init.method ?? 'GET',
headers: { 'x-test-request-id': requestId, ...init.headers },
})
const body = await res.text()
// The launcher logs this after the handler has finished, on the same
// stream as the logs written while handling the request.
await retry(async () => {
expect(output.value.slice(start)).toContain(
`__request-done__ ${requestId}\n`
)
})
return { res, body, logs: output.value.slice(start) }
}
describe('OPTIONS on dynamic pages', () => {
it('rejects OPTIONS on an app dynamic page without rendering', async () => {
const { res, body, logs } = await invoke(
'appPages:/dynamic',
'/dynamic',
{
method: 'OPTIONS',
}
)
expect(res.status).toBe(400)
expect(body).toBe('')
expect(logs).not.toContain('__app-dynamic-rendered__')
expect(logs).not.toContain('__app-dynamic-metadata__')
})
it('still renders GET on an app dynamic page', async () => {
const { res, body, logs } = await invoke('appPages:/dynamic', '/dynamic')
expect(res.status).toBe(200)
expect(body).toContain('app dynamic page')
// Confirms that the logs asserted absent above are observable.
expect(logs).toContain('__app-dynamic-rendered__')
expect(logs).toContain('__app-dynamic-metadata__')
})
it('does not add method validation for other methods on an app dynamic page', async () => {
const { res, body } = await invoke('appPages:/dynamic', '/dynamic', {
method: 'PUT',
})
expect(res.status).toBe(200)
expect(body).toContain('app dynamic page')
})
it('rejects OPTIONS on a pages SSR page without running getServerSideProps', async () => {
const { res, body, logs } = await invoke('pages:/ssr', '/ssr', {
method: 'OPTIONS',
})
expect(res.status).toBe(400)
expect(body).toBe('')
expect(logs).not.toContain('__pages-ssr-gssp__')
})
it('still renders GET on a pages SSR page', async () => {
const { res, body, logs } = await invoke('pages:/ssr', '/ssr')
expect(res.status).toBe(200)
expect(body).toContain('pages ssr page')
expect(logs).toContain('__pages-ssr-gssp__')
})
})
describe('non-GET/HEAD on static pages', () => {
it.each([
['appPages:/static', '/static'],
['pages:/ssg', '/ssg'],
])('returns 405 for %s', async (outputKey, pathname) => {
for (const method of ['OPTIONS', 'POST']) {
const { res, body } = await invoke(outputKey, pathname, { method })
expect({ method, status: res.status }).toEqual({ method, status: 405 })
expect(res.headers.get('allow')).toBe('GET, HEAD')
expect(body).toBe('Method Not Allowed')
}
})
it('does not reject a server action POST on a static app page with 405', async () => {
const { res } = await invoke('appPages:/static', '/static', {
method: 'POST',
headers: {
'next-action': 'does-not-exist',
'content-type': 'text/plain;charset=UTF-8',
},
})
expect(res.status).not.toBe(405)
})
it('does not return 405 for a static app /500 page, like NextServer', async () => {
const { res } = await invoke('appPages:/500', '/500', { method: 'POST' })
expect(res.status).not.toBe(405)
})
it('still rejects OPTIONS on a static app /500 page', async () => {
const { res, body } = await invoke('appPages:/500', '/500', {
method: 'OPTIONS',
})
expect(res.status).toBe(400)
expect(body).toBe('')
})
})
describe('not-found pages', () => {
it.each(['GET', 'OPTIONS'])(
'returns 404 for the app not-found entrypoint (%s)',
async (method) => {
const { res, body } = await invoke(
'appPages:/_not-found',
'/does-not-exist',
{ method, headers: { accept: 'text/html' } }
)
expect(res.status).toBe(404)
expect(body).toContain('custom not found page')
}
)
it.each(['GET', 'OPTIONS'])(
'returns 404 for the pages /404 entrypoint (%s)',
async (method) => {
const { res, body } = await invoke('pages:/404', '/does-not-exist', {
method,
headers: { accept: 'text/html' },
})
expect(res.status).toBe(404)
expect(body).toContain('pages custom 404')
}
)
it('does not reject OPTIONS for pages /_error rendered with a 404 status', async () => {
const { res } = await invoke('pages:/_error', '/does-not-exist', {
method: 'OPTIONS',
headers: { accept: 'text/html', 'x-test-preset-status': '404' },
})
expect(res.status).toBe(404)
})
})
describe('routes that handle OPTIONS themselves', () => {
it('auto-implements OPTIONS for app route handlers', async () => {
const { res } = await invoke(
'appRoutes:/route-handler',
'/route-handler',
{
method: 'OPTIONS',
}
)
expect(res.status).toBe(204)
})
it('passes OPTIONS through to pages API routes', async () => {
const { res, body } = await invoke('pagesApi:/api/hello', '/api/hello', {
method: 'OPTIONS',
})
expect(res.status).toBe(200)
expect(JSON.parse(body)).toEqual({ method: 'OPTIONS' })
})
})
})
// The dynamic root `not-found.tsx` would otherwise make this page dynamic too.
export const dynamic = 'force-static'
export default function Page() {
return <p>app 500 page</p>
}
export const dynamic = 'force-dynamic'
export async function generateMetadata() {
console.log('__app-dynamic-metadata__')
return { title: 'app dynamic' }
}
export default async function Page() {
console.log('__app-dynamic-rendered__')
return <p>app dynamic page</p>
}
import type { ReactNode } from 'react'
export default function Root({ children }: { children: ReactNode }) {
return (
<html>
<body>{children}</body>
</html>
)
}
import { headers } from 'next/headers'
// Reading request headers makes the not-found page dynamic, so it is rendered
// by the `/_not-found` entrypoint on demand instead of a static 404.html.
export default async function NotFound() {
await headers()
return <h1>custom not found page</h1>
}
export const dynamic = 'force-dynamic'
export async function GET() {
return Response.json({ ok: true })
}
// The dynamic root `not-found.tsx` would otherwise make this page dynamic too.
export const dynamic = 'force-static'
async function action() {
'use server'
console.log('__app-static-action__')
}
export default function Page() {
return (
<form action={action}>
<p>app static page</p>
<button type="submit">submit</button>
</form>
)
}
import { createRequire } from 'module'
const require = createRequire(import.meta.url)
/** @type {import('next').NextConfig} */
const nextConfig = {
adapterPath: require.resolve('./test-adapter.mjs'),
}
export default nextConfig
export default function Custom404() {
return <p>pages custom 404</p>
}
import type { NextApiRequest, NextApiResponse } from 'next'
export default function handler(req: NextApiRequest, res: NextApiResponse) {
res.status(200).json({ method: req.method })
}
export async function getStaticProps() {
return { props: {}, revalidate: 60 }
}
export default function Page() {
return <p>pages ssg page</p>
}
export async function getServerSideProps() {
console.log('__pages-ssr-gssp__')
return { props: {} }
}
export default function Page() {
return <p>pages ssr page</p>
}
import fs from 'fs/promises'
/** @type {import('next').NextAdapter} */
const adapter = {
name: 'test-adapter',
async onBuildComplete(ctx) {
await fs.writeFile(
new URL('build-complete.json', import.meta.url),
JSON.stringify(ctx)
)
},
}
export default adapter
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