Unverified Commit d43d57af authored by Zack Tanner's avatar Zack Tanner Committed by GitHub

Remove urlencoded action handling & harden action ID checks (#87082)

- Removes support for urlencoded actions
- Errors when a server action request is received in apps that have no
server actions
- validate action ID in MPA actions before proceeding

---------
Co-authored-by: 's avatarJosh Story <story@hey.com>
parent 8479550b
......@@ -970,5 +970,8 @@
"969": "Invariant: nextConfig couldn't be loaded",
"970": "process.env.NEXT_DEPLOYMENT_ID is missing but runtimeServerDeploymentId is enabled",
"971": "The NEXT_DEPLOYMENT_ID environment variable value \"%s\" does not match the provided deploymentId \"%s\" in the config.",
"972": "Failed to resolve pattern \"%s\": %s"
"972": "Failed to resolve pattern \"%s\": %s",
"973": "Server Actions are not enabled for this application. This request might be from an older or newer deployment.\nRead more: https://nextjs.org/docs/messages/failed-to-find-server-action",
"974": "Failed to find Server Action%s. This request might be from an older or newer deployment.\\nRead more: https://nextjs.org/docs/messages/failed-to-find-server-action",
"975": "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"
}
......@@ -53,6 +53,8 @@ import { fromNodeOutgoingHttpHeaders } from '../web/utils'
import {
selectWorkerForForwarding,
type ServerModuleMap,
getServerActionsManifest,
getServerModuleMap,
} from './manifests-singleton'
import { isNodeNextRequest, isWebNextRequest } from '../base-http/helpers'
import { RedirectStatusCode } from '../../client/components/redirect-status-code'
......@@ -63,19 +65,21 @@ import { InvariantError } from '../../shared/lib/invariant-error'
import { executeRevalidates } from '../revalidation-utils'
import { getRequestMeta } from '../request-meta'
import { setCacheBustingSearchParam } from '../../client/components/router-reducer/set-cache-busting-search-param'
import { getServerModuleMap } from './manifests-singleton'
import {
ActionDidNotRevalidate,
ActionDidRevalidateStaticAndDynamic,
} from '../../shared/lib/action-revalidation-kind'
function formDataFromSearchQueryString(query: string) {
const searchParams = new URLSearchParams(query)
const formData = new FormData()
for (const [key, value] of searchParams) {
formData.append(key, value)
}
return formData
/**
* Checks if the app has any server actions defined in any runtime.
*/
function hasServerActions() {
const serverActionsManifest = getServerActionsManifest()
return (
Object.keys(serverActionsManifest.node).length > 0 ||
Object.keys(serverActionsManifest.edge).length > 0
)
}
function nodeHeadersToRecord(
......@@ -539,12 +543,30 @@ export async function handleAction({
const {
actionId,
isURLEncodedAction,
isMultipartAction,
isFetchAction,
isURLEncodedAction,
isPossibleServerAction,
} = getServerActionRequestMetadata(req)
const handleUnrecognizedFetchAction = (err: unknown): 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)
// Return an empty response with a header that the client router will interpret.
// We don't need to waste time encoding a flight response, and using a blank body + header
// means that unrecognized actions can also be handled at the infra level
// (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
return {
type: 'done',
result: RenderResult.fromStatic('Server action not found.', 'text/plain'),
}
}
// If it can't be a Server Action, skip handling.
// Note that this can be a false positive -- any multipart/urlencoded POST can get us here,
// But won't know if it's an MPA action or not until we call `decodeAction` below.
......@@ -552,6 +574,24 @@ export async function handleAction({
return null
}
// 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 null
return null
}
}
// If the app has no server actions at all, we can 404 early.
if (!hasServerActions()) {
return handleUnrecognizedFetchAction(getActionNotFoundError(actionId))
}
if (workStore.isStaticGeneration) {
throw new Error(
"Invariant: server actions can't be handled during static rendering"
......@@ -670,24 +710,6 @@ export async function handleAction({
}
}
const handleUnrecognizedFetchAction = (err: unknown): 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)
// Return an empty response with a header that the client router will interpret.
// We don't need to waste time encoding a flight response, and using a blank body + header
// means that unrecognized actions can also be handled at the infra level
// (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
return {
type: 'done',
result: RenderResult.fromStatic('Server action not found.', 'text/plain'),
}
}
try {
return await actionAsyncStorage.run(
{ isAction: true },
......@@ -723,6 +745,13 @@ export async function handleAction({
const formData = await req.request.formData()
if (isFetchAction) {
// A fetch action with a multipart body.
try {
actionModId = getActionModIdOrError(actionId, serverModuleMap)
} catch (err) {
return handleUnrecognizedFetchAction(err)
}
boundActionArguments = await decodeReply(
formData,
serverModuleMap,
......@@ -731,6 +760,14 @@ 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`
)
}
const action = await decodeAction(formData, serverModuleMap)
if (typeof action === 'function') {
// an MPA action.
......@@ -796,20 +833,11 @@ export async function handleAction({
const actionData = Buffer.concat(chunks).toString('utf-8')
if (isURLEncodedAction) {
const formData = formDataFromSearchQueryString(actionData)
boundActionArguments = await decodeReply(
formData,
serverModuleMap,
{ temporaryReferences }
)
} else {
boundActionArguments = await decodeReply(
actionData,
serverModuleMap,
{ temporaryReferences }
)
}
boundActionArguments = await decodeReply(
actionData,
serverModuleMap,
{ temporaryReferences }
)
}
} else if (
// The type check here ensures that `req` is correctly typed, and the
......@@ -877,6 +905,12 @@ export async function handleAction({
if (isFetchAction) {
// A fetch action with a multipart body.
try {
actionModId = getActionModIdOrError(actionId, serverModuleMap)
} catch (err) {
return handleUnrecognizedFetchAction(err)
}
const busboy = (
require('next/dist/compiled/busboy') as typeof import('next/dist/compiled/busboy')
)({
......@@ -924,7 +958,19 @@ export async function handleAction({
}),
duplex: 'half',
})
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)
if (typeof action === 'function') {
// an MPA action.
......@@ -984,20 +1030,11 @@ export async function handleAction({
const actionData = Buffer.concat(chunks).toString('utf-8')
if (isURLEncodedAction) {
const formData = formDataFromSearchQueryString(actionData)
boundActionArguments = await decodeReply(
formData,
serverModuleMap,
{ temporaryReferences }
)
} else {
boundActionArguments = await decodeReply(
actionData,
serverModuleMap,
{ temporaryReferences }
)
}
boundActionArguments = await decodeReply(
actionData,
serverModuleMap,
{ temporaryReferences }
)
}
} else {
throw new Error('Invariant: Unknown request type.')
......@@ -1015,13 +1052,6 @@ export async function handleAction({
// / -> fire action -> POST / -> appRender1 -> modId for the action file
// /foo -> fire action -> POST /foo -> appRender2 -> modId for the action file
try {
actionModId =
actionModId ?? getActionModIdOrError(actionId, serverModuleMap)
} catch (err) {
return handleUnrecognizedFetchAction(err)
}
const actionMod = (await ComponentMod.__next_app__.require(
actionModId
)) as Record<string, (...args: unknown[]) => Promise<unknown>>
......@@ -1235,10 +1265,121 @@ function getActionModIdOrError(
const actionModId = serverModuleMap[actionId]?.id
if (!actionModId) {
throw new Error(
`Failed to find Server Action "${actionId}". This request might be from an older or newer deployment.\nRead more: https://nextjs.org/docs/messages/failed-to-find-server-action`
)
throw getActionNotFoundError(actionId)
}
return actionModId
}
function getActionNotFoundError(actionId: string | null): Error {
return new Error(
`Failed to find Server Action${actionId ? ` "${actionId}"` : ''}. This request might be from an older or newer deployment.\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(
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(
req.method === 'POST' && contentType === 'application/x-www-form-urlencoded'
)
......
......@@ -54,15 +54,6 @@ describe('unrecognized server actions', () => {
body: new FormData(),
},
},
{
// we never use urlencoded actions, but we currently have codepaths for it in `handleAction`,
// so might as well test them.
name: 'urlencoded',
request: {
contentType: 'application/x-www-form-urlencoded',
body: 'foo=bar',
},
},
])(
'should 404 when POSTing a server action with an unrecognized id to a nonexistent page: $name',
async ({ request: { contentType, body } }) => {
......@@ -91,6 +82,19 @@ describe('unrecognized server actions', () => {
)
}
it('should 404 when POSTing a urlencoded action to a nonexistent page', async () => {
const res = await next.fetch('/non-existent-route', {
method: 'POST',
headers: {
'next-action': '123',
'content-type': 'application/x-www-form-urlencoded',
},
body: 'foo=bar',
})
expect(res.status).toBe(404)
})
describe.each(['nodejs', 'edge'])(
'should error and log a warning when submitting a server action with an unrecognized ID - %s',
(runtime) => {
......@@ -178,10 +182,9 @@ describe('unrecognized server actions', () => {
}
if (!isNextDeploy) {
// FIXME: For an MPA action, the logs currently show the error thrown by React instead of our custom message with a link to a docs page.
await retry(async () =>
expect(getLogs()).toInclude(
`Error: Could not find the module "decafc0ffeebad01" in the React Server Manifest. This is probably a bug in the React Server Components bundler`
`Error: Failed to find Server Action. This request might be from an older or newer deployment`
)
)
}
......
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 404 when triggering a fetch action on an app with no server actions', async () => {
const res = await next.fetch('/', {
method: 'POST',
headers: {
'Next-Action': 'abc123',
},
})
expect(res.status).toBe(404)
expect(res.headers.get('x-nextjs-action-not-found')).toBe('1')
expect(next.cliOutput).toContain(
'Failed to find Server Action "abc123". This request might be from an older or newer deployment.\nRead more: https://nextjs.org/docs/messages/failed-to-find-server-action'
)
})
it('should 404 when triggering an MPA action on an app with no server actions', async () => {
const formData = new FormData()
formData.append('test', 'value')
const res = 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(res.status).toBe(404)
expect(res.headers.get('x-nextjs-action-not-found')).toBe('1')
expect(next.cliOutput).toContain(
'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'
)
})
})
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