Unverified Commit 65c832c8 authored by Josh Story's avatar Josh Story Committed by GitHub

Return client errors for unrecognized Server Actions (#98123)

## Summary

- return `400 Bad Request` when a Server Action reference ID does not
match the expected format
- return `409 Conflict` when a well-formed action ID is unavailable in
the current deployment, including deployment skew
- apply the same classification to IDs from the `Next-Action` header and
multipart MPA forms, including direct and bound actions in Node and Edge
runtimes
- return generic text bodies matching the client error category, without
exposing action-ID details
- derive marked forwarded-action responses from the original action ID
so an unexpected or mixed-version worker response cannot change the
client error semantics

Fetch actions previously had dedicated 404 handling, while equivalent
MPA form submissions fell through to the generic error path and returned
500. This removes that transport-dependent behavior and distinguishes
malformed or scanning traffic from legitimate stale clients without
treating either case as a missing page or an internal server failure.

## Verification

- `pnpm test-dev-turbo
test/e2e/app-dir/actions-unrecognized/actions-unrecognized.test.ts`
- `pnpm test-dev-turbo test/e2e/app-dir/actions/app-action.test.ts -t
'forward.*action'`
- `pnpm test-start-turbo
test/e2e/app-dir/actions-unrecognized/actions-unrecognized.test.ts`
- `pnpm test-dev-webpack
test/e2e/app-dir/actions-unrecognized/actions-unrecognized.test.ts`
- `pnpm test-dev-turbo
test/e2e/app-dir/no-server-actions/no-server-actions.test.ts`

<!-- NEXT_JS_LLM -->
parent 0eb4d7d5
......@@ -94,6 +94,16 @@ function hasServerActions() {
)
}
function getUnrecognizedActionStatusCode(actionId: string | null): 400 | 409 {
return actionId !== null && !mightBeServerReferenceId(actionId) ? 400 : 409
}
function getUnrecognizedActionResponseBody(statusCode: 400 | 409): string {
return statusCode === 400
? 'Invalid Server Action request.'
: 'Server Action unavailable.'
}
function nodeHeadersToRecord(
headers: IncomingHttpHeaders | OutgoingHttpHeaders
) {
......@@ -212,7 +222,8 @@ async function createForwardedActionResponse(
res: BaseNextResponse,
host: Host,
workerPathname: string,
basePath: string
basePath: string,
actionId: string
) {
if (!host) {
throw new Error(
......@@ -306,8 +317,14 @@ async function createForwardedActionResponse(
if (response.headers.get(NEXT_ACTION_NOT_FOUND_HEADER) === '1') {
res.setHeader(NEXT_ACTION_NOT_FOUND_HEADER, '1')
res.setHeader('content-type', 'text/plain')
res.statusCode = 404
return RenderResult.fromStatic('Server action not found.', 'text/plain')
// The marker denotes an unavailable action. Derive the status from the
// requested ID so mixed-version workers cannot change its semantics.
const statusCode = getUnrecognizedActionStatusCode(actionId)
res.statusCode = statusCode
return RenderResult.fromStatic(
getUnrecognizedActionResponseBody(statusCode),
'text/plain'
)
}
} catch (err) {
// we couldn't stream the forwarded response, so we'll just return an empty response
......@@ -610,7 +627,10 @@ export async function handleAction({
isPossibleServerAction,
} = getServerActionRequestMetadata(req)
const handleUnrecognizedFetchAction = (err: unknown): HandleActionResult => {
const handleUnrecognizedAction = (
err: unknown,
statusCode: 400 | 409
): HandleActionResult => {
// If the deployment doesn't have skew protection, this is expected to occasionally happen,
// so we use a warning instead of an error.
console.warn(err)
......@@ -621,10 +641,13 @@ export async function handleAction({
// (i.e. without needing to invoke a lambda)
res.setHeader(NEXT_ACTION_NOT_FOUND_HEADER, '1')
res.setHeader('content-type', 'text/plain')
res.statusCode = 404
res.statusCode = statusCode
return {
type: 'done',
result: RenderResult.fromStatic('Server action not found.', 'text/plain'),
result: RenderResult.fromStatic(
getUnrecognizedActionResponseBody(statusCode),
'text/plain'
),
}
}
......@@ -648,13 +671,16 @@ export async function handleAction({
}
}
// If the app has no server actions at all, we can 404 early.
// If the app has no server actions at all, we can reject the request early.
if (!hasServerActions()) {
const error =
actionId !== null && !mightBeServerReferenceId(actionId)
? getInvalidServerReferenceIdError(actionId)
: getActionNotFoundError(actionId)
return handleUnrecognizedFetchAction(error)
return handleUnrecognizedAction(
error,
getUnrecognizedActionStatusCode(actionId)
)
}
let temporaryReferences: TemporaryReferenceSet | undefined
......@@ -780,7 +806,8 @@ export async function handleAction({
res,
host,
forwardedWorker,
ctx.renderOpts.basePath
ctx.renderOpts.basePath,
actionId
),
}
}
......@@ -868,7 +895,10 @@ export async function handleAction({
try {
actionModId = getActionModIdOrError(actionId, serverModuleMap)
} catch (err) {
return handleUnrecognizedFetchAction(err)
return handleUnrecognizedAction(
err,
getUnrecognizedActionStatusCode(actionId)
)
}
boundActionArguments = await decodeReply<unknown[]>(
......@@ -879,12 +909,15 @@ export async function handleAction({
} else {
// Multipart POST, but not a fetch action.
// Potentially an MPA action, we have to try decoding it to check.
if (areAllActionIdsValid(formData, serverModuleMap) === false) {
// TODO: This can be from skew or manipulated input. We should handle this case
// more gracefully but this preserves the prior behavior where decodeAction would throw instead.
throw new Error(
`Failed to find Server Action. This request might be from an older or newer deployment.\nRead more: https://nextjs.org/docs/messages/failed-to-find-server-action`
)
try {
if (!areAllActionIdsValid(formData, serverModuleMap)) {
return handleUnrecognizedAction(
new Error('Invalid Server Actions request.'),
400
)
}
} catch (err) {
return handleUnrecognizedAction(err, 409)
}
const action = await decodeAction(formData, serverModuleMap)
......@@ -932,7 +965,10 @@ export async function handleAction({
try {
actionModId = getActionModIdOrError(actionId, serverModuleMap)
} catch (err) {
return handleUnrecognizedFetchAction(err)
return handleUnrecognizedAction(
err,
getUnrecognizedActionStatusCode(actionId)
)
}
// A fetch action with a non-multipart body.
......@@ -1029,7 +1065,10 @@ export async function handleAction({
try {
actionModId = getActionModIdOrError(actionId, serverModuleMap)
} catch (err) {
return handleUnrecognizedFetchAction(err)
return handleUnrecognizedAction(
err,
getUnrecognizedActionStatusCode(actionId)
)
}
const busboy = (
......@@ -1086,12 +1125,15 @@ export async function handleAction({
throw err
}
if (areAllActionIdsValid(formData, serverModuleMap) === false) {
// TODO: This can be from skew or manipulated input. We should handle this case
// more gracefully but this preserves the prior behavior where decodeAction would throw instead.
throw new Error(
`Failed to find Server Action. This request might be from an older or newer deployment.\nRead more: https://nextjs.org/docs/messages/failed-to-find-server-action`
)
try {
if (!areAllActionIdsValid(formData, serverModuleMap)) {
return handleUnrecognizedAction(
new Error('Invalid Server Actions request.'),
400
)
}
} catch (err) {
return handleUnrecognizedAction(err, 409)
}
// TODO: Refactor so it is harder to accidentally decode an action before you have validated that the
......@@ -1141,7 +1183,10 @@ export async function handleAction({
try {
actionModId = getActionModIdOrError(actionId, serverModuleMap)
} catch (err) {
return handleUnrecognizedFetchAction(err)
return handleUnrecognizedAction(
err,
getUnrecognizedActionStatusCode(actionId)
)
}
// A fetch action with a non-multipart body.
......@@ -1497,8 +1542,8 @@ function areAllActionIdsValid(
): boolean {
let seenActionRefs = 0
let hasAtLeastOneAction = false
// Before we attempt to decode the payload for a possible MPA action, assert that all
// action IDs are valid IDs. If not we should disregard the payload
// Before we attempt to decode the payload for a possible MPA action, assert
// that all action IDs are valid IDs.
for (let key of mpaFormData.keys()) {
if (!key.startsWith($ACTION_)) {
// not a relevant field
......@@ -1545,7 +1590,7 @@ const ACTION_DESCRIPTOR_ID_PREFIX = '{"id":"'
function isInvalidStringActionDescriptor(
actionDescriptor: string,
serverModuleMap: ServerModuleMap
): unknown {
): boolean {
if (actionDescriptor.startsWith(ACTION_DESCRIPTOR_ID_PREFIX) === false) {
return true
}
......
......@@ -6,7 +6,7 @@ import { outdent } from 'outdent'
describe('unrecognized server actions', () => {
const unrecognizedActionId = '0'.repeat(42)
const { next, isNextDeploy, isNextDev } = nextTestSetup({
const { next, isNextDeploy } = nextTestSetup({
files: __dirname,
})
......@@ -42,6 +42,7 @@ describe('unrecognized server actions', () => {
{
idType: 'malformed',
actionId: '123',
expectedStatus: 400,
expectedError: outdent`
The Server Reference ID did not match the expected format. Received "123".
Read more: https://nextjs.org/docs/messages/failed-to-find-server-action
......@@ -50,6 +51,7 @@ describe('unrecognized server actions', () => {
{
idType: 'plausible but missing',
actionId: unrecognizedActionId,
expectedStatus: 409,
expectedError: outdent`
Failed to find Server Action "${unrecognizedActionId}". This request might be from an older or newer deployment.
Read more: https://nextjs.org/docs/messages/failed-to-find-server-action
......@@ -62,12 +64,13 @@ describe('unrecognized server actions', () => {
// We should still surface a diagnosable error instead of a TypeError.
idType: 'well-known property name',
actionId: 'toString',
expectedStatus: 400,
expectedError: outdent`
The Server Reference ID did not match the expected format. Received "toString".
Read more: https://nextjs.org/docs/messages/failed-to-find-server-action
`,
},
])('with a $idType id', ({ actionId, expectedError }) => {
])('with a $idType id', ({ actionId, expectedStatus, expectedError }) => {
it.each([
{
// encodeReply encodes simple args as plaintext.
......@@ -87,7 +90,7 @@ describe('unrecognized server actions', () => {
},
},
])(
'should 404 when POSTing a server action to a nonexistent page: $name',
'should reject a server action POST to a nonexistent page: $name',
async ({ request: { contentType, body } }) => {
const res = await next.fetch('/non-existent-route', {
method: 'POST',
......@@ -99,7 +102,7 @@ describe('unrecognized server actions', () => {
body,
})
expect(res.status).toBe(404)
expect(res.status).toBe(expectedStatus)
const cliOutput = getLogs()
expect(cliOutput).not.toContain('TypeError')
......@@ -129,6 +132,48 @@ describe('unrecognized server actions', () => {
describe.each(['nodejs', 'edge'])(
'should error and log a warning when submitting a server action with an unrecognized ID - %s',
(runtime) => {
it.each([
{
description: 'a malformed ID',
actionId: '123',
expectedStatus: 400,
expectedBody: 'Invalid Server Action request.',
expectedError: 'Invalid Server Actions request.',
},
{
description: 'a plausible but missing ID',
actionId: unrecognizedActionId,
expectedStatus: 409,
expectedBody: 'Server Action unavailable.',
expectedError: outdent`
Failed to find Server Action "${unrecognizedActionId}". This request might be from an older or newer deployment.
Read more: https://nextjs.org/docs/messages/failed-to-find-server-action
`,
},
])(
'should reject an MPA action with $description',
async ({ actionId, expectedStatus, expectedBody, expectedError }) => {
const boundary = '----nextjs-test-boundary'
const body = `--${boundary}\r\nContent-Disposition: form-data; name="$ACTION_ID_${actionId}"\r\n\r\n\r\n--${boundary}--\r\n`
const response = await next.fetch(`/${runtime}/unrecognized-action`, {
method: 'POST',
headers: {
'content-type': `multipart/form-data; boundary=${boundary}`,
},
body,
})
expect(response.status).toBe(expectedStatus)
expect(response.headers.get('content-type')).toStartWith('text/plain')
expect(await response.text()).toBe(expectedBody)
if (!isNextDeploy) {
await retry(async () => expect(getLogs()).toInclude(expectedError))
}
}
)
const testUnrecognizedActionSubmission = async ({
formId,
disableJavaScript,
......@@ -156,7 +201,7 @@ describe('unrecognized server actions', () => {
if (!disableJavaScript) {
// A fetch action, sent via the router.
expect(response.status()).toBe(404)
expect(response.status()).toBe(409)
// NOTE: we cannot validate the response text, because playwright hangs on `response.text()` for some reason.
expect(response.headers()['content-type']).toStartWith('text/plain')
......@@ -165,7 +210,7 @@ describe('unrecognized server actions', () => {
/Error boundary: Server Action ".+?" was not found on the server\./
)
// We responded with a 404, but we shouldn't trigger a not-found (either a custom or a default one)
// We responded with a 409, but we shouldn't trigger a not-found (either a custom or a default one)
expect(await browser.elementByCss('body').text()).not.toContain(
'Not found'
)
......@@ -183,39 +228,18 @@ describe('unrecognized server actions', () => {
}
} else {
// An MPA action, sent without JS.
expect(response.status()).toBe(409)
expect(response.headers()['content-type']).toStartWith('text/plain')
expect(await browser.elementByCss('body').text()).toBe(
'Server Action unavailable.'
)
// FIXME: When deployed, the request is logged as a 500, but returns a 405.
// We also don't seem to display the error page correctly
if (!isNextDeploy) {
// FIXME: Currently, an unrecognized id in an MPA action results in a 500.
// This is not ideal, and ignores all nested `error.js` files, only showing the topmost one.
expect(response.status()).toBe(500)
if (isNextDev) {
expect(response.headers()['content-type']).toStartWith(
'text/html'
)
} else {
const responseText = await response.text()
expect(responseText).toBe('Internal Server Error')
expect(response.headers()['content-type']).toStartWith(
'text/plain'
)
}
// In dev, the 500 page doesn't have any SSR'd html, so it won't show anything without JS.
if (!isNextDev) {
expect(await browser.elementByCss('body').text()).toContain(
'Internal Server Error'
)
}
if (!isNextDeploy) {
await retry(async () =>
expect(getLogs()).toInclude(
`Error: Failed to find Server Action "${unrecognizedActionId}". This request might be from an older or newer deployment`
)
await retry(async () =>
expect(getLogs()).toInclude(
`Error: Failed to find Server Action "${unrecognizedActionId}". This request might be from an older or newer deployment`
)
}
)
}
}
}
......
......@@ -11,17 +11,19 @@ describe('app-dir - no server actions', () => {
{
description: 'a malformed id',
actionId: 'abc123',
expectedStatus: 400,
expectedError:
'The Server Reference ID did not match the expected format. Received "abc123".\nRead more: https://nextjs.org/docs/messages/failed-to-find-server-action',
},
{
description: 'a plausible but missing id',
actionId: missingActionId,
expectedStatus: 409,
expectedError: `Failed to find Server Action "${missingActionId}". This request might be from an older or newer deployment.\nRead more: https://nextjs.org/docs/messages/failed-to-find-server-action`,
},
])(
'should error when triggering a fetch action with $description on an app with no server actions',
async ({ actionId, expectedError }) => {
async ({ actionId, expectedStatus, expectedError }) => {
const res = await next.fetch('/', {
method: 'POST',
headers: {
......@@ -29,7 +31,7 @@ describe('app-dir - no server actions', () => {
},
})
expect(res.status).toBe(404)
expect(res.status).toBe(expectedStatus)
expect(res.headers.get('x-nextjs-action-not-found')).toBe('1')
// Runtime logs and custom headers are not forwarded to the client when deployed.
......@@ -52,7 +54,7 @@ describe('app-dir - no server actions', () => {
body: formData,
})
expect(res.status).toBe(404)
expect(res.status).toBe(409)
expect(res.headers.get('x-nextjs-action-not-found')).toBe('1')
// Runtime logs are not available when deployed.
......
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