Commit 385e8c28 authored by Zack Tanner's avatar Zack Tanner

Backport Next.js changes to v14.2.34 (#29)

* 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 7a2cf51e
...@@ -9,6 +9,7 @@ import type { SizeLimit } from '../../../types' ...@@ -9,6 +9,7 @@ import type { SizeLimit } from '../../../types'
import type { RequestStore } from '../../client/components/request-async-storage.external' import type { RequestStore } from '../../client/components/request-async-storage.external'
import type { AppRenderContext, GenerateFlight } from './app-render' import type { AppRenderContext, GenerateFlight } from './app-render'
import type { AppPageModule } from '../../server/future/route-modules/app-page/module' import type { AppPageModule } from '../../server/future/route-modules/app-page/module'
import type { ActionManifest } from '../../build/webpack/plugins/flight-client-entry-plugin'
import { import {
RSC_HEADER, RSC_HEADER,
...@@ -44,13 +45,14 @@ import { HeadersAdapter } from '../web/spec-extension/adapters/headers' ...@@ -44,13 +45,14 @@ import { HeadersAdapter } from '../web/spec-extension/adapters/headers'
import { fromNodeOutgoingHttpHeaders } from '../web/utils' import { fromNodeOutgoingHttpHeaders } from '../web/utils'
import { selectWorkerForForwarding } from './action-utils' import { selectWorkerForForwarding } from './action-utils'
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(
...@@ -412,6 +414,29 @@ export async function handleAction({ ...@@ -412,6 +414,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 (staticGenerationStore.isStaticGeneration) { if (staticGenerationStore.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"
...@@ -569,8 +594,26 @@ export async function handleAction({ ...@@ -569,8 +594,26 @@ export async function handleAction({
// TODO-APP: Add streaming support // TODO-APP: Add streaming support
const formData = await webRequest.request.formData() const formData = await webRequest.request.formData()
if (isFetchAction) { if (isFetchAction) {
try {
actionModId = getActionModIdOrError(actionId, serverModuleMap)
} catch (err) {
console.warn(err)
return {
type: 'not-found',
}
}
bound = await decodeReply(formData, serverModuleMap) bound = await decodeReply(formData, serverModuleMap)
} 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
...@@ -606,12 +649,7 @@ export async function handleAction({ ...@@ -606,12 +649,7 @@ export async function handleAction({
actionData += new TextDecoder().decode(value) actionData += new TextDecoder().decode(value)
} }
if (isURLEncodedAction) { bound = await decodeReply(actionData, serverModuleMap)
const formData = formDataFromSearchQueryString(actionData)
bound = await decodeReply(formData, serverModuleMap)
} else {
bound = await decodeReply(actionData, serverModuleMap)
}
} }
} else { } else {
// Use react-server-dom-webpack/server.node which supports streaming // Use react-server-dom-webpack/server.node which supports streaming
...@@ -624,6 +662,16 @@ export async function handleAction({ ...@@ -624,6 +662,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 readableLimit = serverActions?.bodySizeLimit ?? '1 MB' const readableLimit = serverActions?.bodySizeLimit ?? '1 MB'
const limit = require('next/dist/compiled/bytes').parse( const limit = require('next/dist/compiled/bytes').parse(
readableLimit readableLimit
...@@ -662,6 +710,17 @@ export async function handleAction({ ...@@ -662,6 +710,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
...@@ -705,12 +764,7 @@ To configure the body size limit for Server Actions, see: https://nextjs.org/doc ...@@ -705,12 +764,7 @@ To configure the body size limit for Server Actions, see: https://nextjs.org/doc
) )
} }
if (isURLEncodedAction) { bound = await decodeReply(actionData, serverModuleMap)
const formData = formDataFromSearchQueryString(actionData)
bound = await decodeReply(formData, serverModuleMap)
} else {
bound = await decodeReply(actionData, serverModuleMap)
}
} }
} }
...@@ -903,10 +957,123 @@ function getActionModIdOrError( ...@@ -903,10 +957,123 @@ 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. ${ }
err instanceof Error ? `Original error: ${err.message}` : '' }
}`
) 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}` : ''
}`
)
}
const $ACTION_ = '$ACTION_'
const $ACTION_REF_ = '$ACTION_REF_'
const $ACTION_ID_ = '$ACTION_ID_'
const ACTION_ID_EXPECTED_LENGTH = 40
/**
* 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'
) )
......
...@@ -519,7 +519,6 @@ createNextDescribe( ...@@ -519,7 +519,6 @@ createNextDescribe(
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