Commit 39e2ed99 authored by Zack Tanner's avatar Zack Tanner

Backport Next.js changes to v15.2.7 (#26)

* remove urlencoded server action handling (#14)

* remove urlencoded server action handling

* urlencoded POSTs should still flow through action handler

* bailout early for urlencoded

* tweak handling to 404 in feetch action case

* error when there are no server actions (#15)

* remove custom error

* remove dev gate

* error when there are no server actions

* gate against dev

* Check whether action ids are valid before parsing (#16)

* Check whether action ids are valid before parsing

In an effort to narrow access to parsing methods Next.js now prequalifies MPA form parsing by ensuring there are only valid action IDs as part of the submission. This is not meant to be a strong line of defense against malicious payloads since action IDs are not private and are for many apps relatively easy to acquire. It does however provide some limited narrowing of code paths so that action decoding only happens for plausible actions

Additionally all other branches that use next-action header now consistently check the header before proceeding with parsing. This is also a perf improvement.

* fix test assertion

---------
Co-authored-by: 's avatarZack Tanner <1939140+ztanner@users.noreply.github.com>

* fix test

---------
Co-authored-by: 's avatarJosh Story <story@hey.com>
parent 25ba2c26
...@@ -659,5 +659,7 @@ ...@@ -659,5 +659,7 @@
"658": "Pass `Infinity` instead of `false` if you want to cache on the server forever without checking with the origin.", "658": "Pass `Infinity` instead of `false` if you want to cache on the server forever without checking with the origin.",
"659": "SSG should not return an image cache value", "659": "SSG should not return an image cache value",
"660": "Rspack support is only available in Next.js canary.", "660": "Rspack support is only available in Next.js canary.",
"661": "Build failed because of %s errors" "661": "Build failed because of %s errors",
"662": "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",
"663": "Failed to find Server Action%s. This request might be from an older or newer deployment. %s\\nRead more: https://nextjs.org/docs/messages/failed-to-find-server-action"
} }
...@@ -4,6 +4,7 @@ import type { RequestStore } from '../app-render/work-unit-async-storage.externa ...@@ -4,6 +4,7 @@ import type { RequestStore } from '../app-render/work-unit-async-storage.externa
import type { AppRenderContext, GenerateFlight } from './app-render' import type { AppRenderContext, GenerateFlight } from './app-render'
import type { AppPageModule } from '../route-modules/app-page/module' import type { AppPageModule } from '../route-modules/app-page/module'
import type { BaseNextRequest, BaseNextResponse } from '../base-http' import type { BaseNextRequest, BaseNextResponse } from '../base-http'
import type { ActionManifest } from '../../build/webpack/plugins/flight-client-entry-plugin'
import { import {
RSC_HEADER, RSC_HEADER,
...@@ -49,13 +50,14 @@ import { synchronizeMutableCookies } from '../async-storage/request-store' ...@@ -49,13 +50,14 @@ import { synchronizeMutableCookies } from '../async-storage/request-store'
import type { TemporaryReferenceSet } from 'react-server-dom-webpack/server.edge' import type { TemporaryReferenceSet } from 'react-server-dom-webpack/server.edge'
import { workUnitAsyncStorage } from '../app-render/work-unit-async-storage.external' import { workUnitAsyncStorage } from '../app-render/work-unit-async-storage.external'
function formDataFromSearchQueryString(query: string) { /**
const searchParams = new URLSearchParams(query) * Checks if the app has any server actions defined in any runtime.
const formData = new FormData() */
for (const [key, value] of searchParams) { function hasServerActions(manifest: ActionManifest) {
formData.append(key, value) return (
} Object.keys(manifest.node).length > 0 ||
return formData Object.keys(manifest.edge).length > 0
)
} }
function nodeHeadersToRecord( function nodeHeadersToRecord(
...@@ -495,6 +497,29 @@ export async function handleAction({ ...@@ -495,6 +497,29 @@ export async function handleAction({
return return
} }
// We don't currently support URL encoded actions, so we bail out early.
// Depending on if it's a fetch action or an MPA, we return a different response.
if (isURLEncodedAction) {
if (isFetchAction) {
return {
type: 'not-found',
}
} else {
// This is an MPA action, so we return
return
}
}
// If the app has no server actions at all, we can 404 early.
if (!hasServerActions(serverActionsManifest)) {
const error = getActionNotFoundError(actionId)
console.warn(error)
return {
type: 'not-found',
}
}
if (workStore.isStaticGeneration) { if (workStore.isStaticGeneration) {
throw new Error( throw new Error(
"Invariant: server actions can't be handled during static rendering" "Invariant: server actions can't be handled during static rendering"
...@@ -667,12 +692,30 @@ export async function handleAction({ ...@@ -667,12 +692,30 @@ export async function handleAction({
// TODO-APP: Add streaming support // TODO-APP: Add streaming support
const formData = await req.request.formData() const formData = await req.request.formData()
if (isFetchAction) { if (isFetchAction) {
try {
actionModId = getActionModIdOrError(actionId, serverModuleMap)
} catch (err) {
console.warn(err)
return {
type: 'not-found',
}
}
boundActionArguments = await decodeReply( boundActionArguments = await decodeReply(
formData, formData,
serverModuleMap, serverModuleMap,
{ temporaryReferences } { temporaryReferences }
) )
} else { } else {
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`
)
}
const action = await decodeAction(formData, serverModuleMap) const action = await decodeAction(formData, serverModuleMap)
if (typeof action === 'function') { if (typeof action === 'function') {
// Only warn if it's a server action, otherwise skip for other post requests // Only warn if it's a server action, otherwise skip for other post requests
...@@ -720,21 +763,12 @@ export async function handleAction({ ...@@ -720,21 +763,12 @@ export async function handleAction({
const actionData = Buffer.concat(chunks).toString('utf-8') const actionData = Buffer.concat(chunks).toString('utf-8')
if (isURLEncodedAction) {
const formData = formDataFromSearchQueryString(actionData)
boundActionArguments = await decodeReply(
formData,
serverModuleMap,
{ temporaryReferences }
)
} else {
boundActionArguments = await decodeReply( boundActionArguments = await decodeReply(
actionData, actionData,
serverModuleMap, serverModuleMap,
{ temporaryReferences } { temporaryReferences }
) )
} }
}
} else if ( } else if (
// The type check here ensures that `req` is correctly typed, and the // The type check here ensures that `req` is correctly typed, and the
// environment variable check provides dead code elimination. // environment variable check provides dead code elimination.
...@@ -792,6 +826,16 @@ export async function handleAction({ ...@@ -792,6 +826,16 @@ export async function handleAction({
if (isMultipartAction) { if (isMultipartAction) {
if (isFetchAction) { if (isFetchAction) {
try {
actionModId = getActionModIdOrError(actionId, serverModuleMap)
} catch (err) {
console.warn(err)
return {
type: 'not-found',
}
}
const busboy = (require('busboy') as typeof import('busboy'))({ const busboy = (require('busboy') as typeof import('busboy'))({
defParamCharset: 'utf8', defParamCharset: 'utf8',
headers: req.headers, headers: req.headers,
...@@ -828,6 +872,17 @@ export async function handleAction({ ...@@ -828,6 +872,17 @@ export async function handleAction({
duplex: 'half', duplex: 'half',
}) })
const formData = await fakeRequest.formData() const formData = await fakeRequest.formData()
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`
)
}
// TODO: Refactor so it is harder to accidentally decode an action before you have validated that the
// action referred to is available.
const action = await decodeAction(formData, serverModuleMap) const action = await decodeAction(formData, serverModuleMap)
if (typeof action === 'function') { if (typeof action === 'function') {
// Only warn if it's a server action, otherwise skip for other post requests // Only warn if it's a server action, otherwise skip for other post requests
...@@ -869,21 +924,12 @@ export async function handleAction({ ...@@ -869,21 +924,12 @@ export async function handleAction({
const actionData = Buffer.concat(chunks).toString('utf-8') const actionData = Buffer.concat(chunks).toString('utf-8')
if (isURLEncodedAction) {
const formData = formDataFromSearchQueryString(actionData)
boundActionArguments = await decodeReply(
formData,
serverModuleMap,
{ temporaryReferences }
)
} else {
boundActionArguments = await decodeReply( boundActionArguments = await decodeReply(
actionData, actionData,
serverModuleMap, serverModuleMap,
{ temporaryReferences } { temporaryReferences }
) )
} }
}
} else { } else {
throw new Error('Invariant: Unknown request type.') throw new Error('Invariant: Unknown request type.')
} }
...@@ -1074,10 +1120,121 @@ function getActionModIdOrError( ...@@ -1074,10 +1120,121 @@ function getActionModIdOrError(
return actionModId return actionModId
} catch (err) { } catch (err) {
throw new Error( throw getActionNotFoundError(actionId, err as Error)
`Failed to find Server Action "${actionId}". This request might be from an older or newer deployment. ${ }
}
function getActionNotFoundError(actionId: string | null, err?: Error): Error {
return new Error(
`Failed to find Server Action${actionId ? ` "${actionId}"` : ''}. This request might be from an older or newer deployment. ${
err instanceof Error ? `Original error: ${err.message}` : '' err instanceof Error ? `Original error: ${err.message}` : ''
}\nRead more: https://nextjs.org/docs/messages/failed-to-find-server-action` }\nRead more: https://nextjs.org/docs/messages/failed-to-find-server-action`
) )
}
const $ACTION_ = '$ACTION_'
const $ACTION_REF_ = '$ACTION_REF_'
const $ACTION_ID_ = '$ACTION_ID_'
const ACTION_ID_EXPECTED_LENGTH = 42
/**
* This function mirrors logic inside React's decodeAction and should be kept in sync with that.
* It pre-parses the FormData to ensure that any action IDs referred to are actual action IDs for
* this Next.js application.
*/
function areAllActionIdsValid(
mpaFormData: FormData,
serverModuleMap: ServerModuleMap
): boolean {
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
for (let key of mpaFormData.keys()) {
if (!key.startsWith($ACTION_)) {
// not a relevant field
continue
}
if (key.startsWith($ACTION_ID_)) {
// No Bound args case
if (isInvalidActionIdFieldName(key, serverModuleMap)) {
return false
}
hasAtLeastOneAction = true
} else if (key.startsWith($ACTION_REF_)) {
// Bound args case
const actionDescriptorField =
$ACTION_ + key.slice($ACTION_REF_.length) + ':0'
const actionFields = mpaFormData.getAll(actionDescriptorField)
if (actionFields.length !== 1) {
return false
}
const actionField = actionFields[0]
if (typeof actionField !== 'string') {
return false
}
if (isInvalidStringActionDescriptor(actionField, serverModuleMap)) {
return false
}
hasAtLeastOneAction = true
}
}
return hasAtLeastOneAction
}
const ACTION_DESCRIPTOR_ID_PREFIX = '{"id":"'
function isInvalidStringActionDescriptor(
actionDescriptor: string,
serverModuleMap: ServerModuleMap
): unknown {
if (actionDescriptor.startsWith(ACTION_DESCRIPTOR_ID_PREFIX) === false) {
return true
}
const from = ACTION_DESCRIPTOR_ID_PREFIX.length
const to = from + ACTION_ID_EXPECTED_LENGTH
// We expect actionDescriptor to be '{"id":"<actionId>",...}'
const actionId = actionDescriptor.slice(from, to)
if (
actionId.length !== ACTION_ID_EXPECTED_LENGTH ||
actionDescriptor[to] !== '"'
) {
return true
}
const entry = serverModuleMap[actionId]
if (entry == null) {
return true
} }
return false
}
function isInvalidActionIdFieldName(
actionIdFieldName: string,
serverModuleMap: ServerModuleMap
): boolean {
// The field name must always start with $ACTION_ID_ but since it is
// the id is extracted from the key of the field we have already validated
// this before entering this function
if (
actionIdFieldName.length !==
$ACTION_ID_.length + ACTION_ID_EXPECTED_LENGTH
) {
// this field name has too few or too many characters
return true
}
const actionId = actionIdFieldName.slice($ACTION_ID_.length)
const entry = serverModuleMap[actionId]
if (entry == null) {
return true
}
return false
} }
...@@ -23,6 +23,9 @@ export function getServerActionRequestMetadata( ...@@ -23,6 +23,9 @@ export function getServerActionRequestMetadata(
contentType = req.headers['content-type'] ?? null contentType = req.headers['content-type'] ?? null
} }
// We don't actually support URL encoded actions, and the action handler will bail out if it sees one.
// But we still want it to flow through to the action handler, to prevent changes in behavior when a regular
// page component tries to handle a POST.
const isURLEncodedAction = Boolean( const isURLEncodedAction = Boolean(
req.method === 'POST' && contentType === 'application/x-www-form-urlencoded' req.method === 'POST' && contentType === 'application/x-www-form-urlencoded'
) )
......
...@@ -801,7 +801,6 @@ describe('app-dir action handling', () => { ...@@ -801,7 +801,6 @@ describe('app-dir action handling', () => {
await next.fetch('/server', { await next.fetch('/server', {
method: 'POST', method: 'POST',
headers: { headers: {
'content-type': 'application/x-www-form-urlencoded',
'next-action': 'abc123', 'next-action': 'abc123',
}, },
body: 'foo=bar', body: 'foo=bar',
......
export default function Layout({ children }: { children: React.ReactNode }) {
return (
<html>
<body>{children}</body>
</html>
)
}
export default function Page() {
return <p>Hello World</p>
}
import { nextTestSetup } from 'e2e-utils'
describe('app-dir - no server actions', () => {
const { next } = nextTestSetup({
files: __dirname,
})
it('should log when triggering a fetch action on an app with no server actions', async () => {
await next.fetch('/', {
method: 'POST',
headers: {
'Next-Action': 'abc123',
},
})
expect(next.cliOutput).toContain(
'Failed to find Server Action "abc123". This request might be from an older or newer deployment.'
)
})
it('should log when triggering an MPA action on an app with no server actions', async () => {
const formData = new FormData()
formData.append('test', 'value')
await next.fetch('/', {
method: 'POST',
headers: {
'Content-Type': 'multipart/form-data',
},
// @ts-expect-error: node-fetch types don't seem to like FormData
body: formData,
})
expect(next.cliOutput).toContain(
'Failed to find Server Action. This request might be from an older or newer deployment.'
)
})
})
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