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