Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add serverActions.allowedForwardedHosts option #57529

Merged
merged 9 commits into from
Nov 1, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -155,13 +155,7 @@ async fn wrap_edge_page(
// TODO(timneutkens): remove this
let is_server_component = true;

// let server_actions_body_size_limit =
// &next_config.experimental.server_actions.body_size_limit;
let server_actions_body_size_limit = next_config
.experimental
.server_actions
.as_ref()
.and_then(|sa| sa.body_size_limit.as_ref());
let server_actions = next_config.experimental.server_actions.as_ref();

let sri_enabled = !dev
&& next_config
Expand All @@ -184,7 +178,7 @@ async fn wrap_edge_page(
"nextConfig" => serde_json::to_string(next_config)?,
"isServerComponent" => serde_json::Value::Bool(is_server_component).to_string(),
"dev" => serde_json::Value::Bool(dev).to_string(),
"serverActionsBodySizeLimit" => serde_json::to_string(&server_actions_body_size_limit)?
"serverActions" => serde_json::to_string(&server_actions)?
},
indexmap! {
"incrementalCacheHandler" => None,
Expand Down
3 changes: 1 addition & 2 deletions packages/next/src/build/entries.ts
Original file line number Diff line number Diff line change
Expand Up @@ -417,8 +417,7 @@ export function getEdgeServerEntry(opts: {
middlewareConfig: Buffer.from(
JSON.stringify(opts.middlewareConfig || {})
).toString('base64'),
serverActionsBodySizeLimit:
opts.config.experimental.serverActions?.bodySizeLimit,
serverActions: opts.config.experimental.serverActions,
}

return {
Expand Down
8 changes: 3 additions & 5 deletions packages/next/src/build/templates/edge-ssr-app.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,12 +23,12 @@ const error500Mod = null
declare const sriEnabled: boolean
declare const isServerComponent: boolean
declare const dev: boolean
declare const serverActionsBodySizeLimit: any
declare const serverActions: any
declare const nextConfig: NextConfigComplete
// INJECT:sriEnabled
// INJECT:isServerComponent
// INJECT:dev
// INJECT:serverActionsBodySizeLimit
// INJECT:serverActions
// INJECT:nextConfig

const maybeJSONParse = (str?: string) => (str ? JSON.parse(str) : undefined)
Expand Down Expand Up @@ -58,9 +58,7 @@ const render = getRender({
reactLoadableManifest,
clientReferenceManifest: isServerComponent ? rscManifest : null,
serverActionsManifest: isServerComponent ? rscServerManifest : null,
serverActionsBodySizeLimit: isServerComponent
? serverActionsBodySizeLimit
: undefined,
serverActions: isServerComponent ? serverActions : undefined,
subresourceIntegrityManifest,
config: nextConfig,
buildId: 'VAR_BUILD_ID',
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,10 @@ export type EdgeSSRLoaderQuery = {
incrementalCacheHandlerPath?: string
preferredRegion: string | string[] | undefined
middlewareConfig: string
serverActionsBodySizeLimit?: SizeLimit
serverActions?: {
bodySizeLimit?: SizeLimit
allowedForwardedHosts?: string[]
}
}

/*
Expand Down Expand Up @@ -75,7 +78,7 @@ const edgeSSRLoader: webpack.LoaderDefinitionFunction<EdgeSSRLoaderQuery> =
incrementalCacheHandlerPath,
preferredRegion,
middlewareConfig: middlewareConfigBase64,
serverActionsBodySizeLimit,
serverActions,
} = this.getOptions()

const middlewareConfig: MiddlewareConfig = JSON.parse(
Expand Down Expand Up @@ -148,10 +151,10 @@ const edgeSSRLoader: webpack.LoaderDefinitionFunction<EdgeSSRLoaderQuery> =
nextConfig: stringifiedConfig,
isServerComponent: JSON.stringify(isServerComponent),
dev: JSON.stringify(dev),
serverActionsBodySizeLimit:
typeof serverActionsBodySizeLimit === 'undefined'
serverActions:
typeof serverActions === 'undefined'
? 'undefined'
: JSON.stringify(serverActionsBodySizeLimit),
: JSON.stringify(serverActions),
},
{
incrementalCacheHandler: incrementalCacheHandlerPath ?? null,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ export function getRender({
clientReferenceManifest,
subresourceIntegrityManifest,
serverActionsManifest,
serverActionsBodySizeLimit,
serverActions,
config,
buildId,
nextFontManifest,
Expand All @@ -55,7 +55,10 @@ export function getRender({
subresourceIntegrityManifest?: Record<string, string>
clientReferenceManifest?: ClientReferenceManifest
serverActionsManifest?: any
serverActionsBodySizeLimit?: SizeLimit
serverActions?: {
bodySizeLimit?: SizeLimit
allowedForwardedHosts?: string[]
}
config: NextConfigComplete
buildId: string
nextFontManifest: NextFontManifest
Expand Down Expand Up @@ -87,7 +90,7 @@ export function getRender({
supportsDynamicHTML: true,
disableOptimizedLoading: true,
serverActionsManifest,
serverActionsBodySizeLimit,
serverActions,
nextFontManifest,
},
renderToHTML,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -32,15 +32,13 @@ import {
import { traverseModules, forEachEntryModule } from '../utils'
import { normalizePathSep } from '../../../shared/lib/page-path/normalize-path-sep'
import { getProxiedPluginState } from '../../build-context'
import type { SizeLimit } from '../../../../types'
import semver from 'next/dist/compiled/semver'
import { generateRandomActionKeyRaw } from '../../../server/app-render/action-encryption-utils'

interface Options {
dev: boolean
appDir: string
isEdgeServer: boolean
serverActionsBodySizeLimit?: SizeLimit
}

const PLUGIN_NAME = 'FlightClientEntryPlugin'
Expand Down Expand Up @@ -160,14 +158,12 @@ export class FlightClientEntryPlugin {
dev: boolean
appDir: string
isEdgeServer: boolean
serverActionsBodySizeLimit?: SizeLimit
assetPrefix: string

constructor(options: Options) {
this.dev = options.dev
this.appDir = options.appDir
this.isEdgeServer = options.isEdgeServer
this.serverActionsBodySizeLimit = options.serverActionsBodySizeLimit
this.assetPrefix = !this.dev && !this.isEdgeServer ? '../' : ''
}

Expand Down
3 changes: 1 addition & 2 deletions packages/next/src/export/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -488,8 +488,7 @@ export async function exportAppImpl(
optimizeFonts: nextConfig.optimizeFonts as FontConfig,
largePageDataBytes: nextConfig.experimental.largePageDataBytes,
serverComponents: options.hasAppDir,
serverActionsBodySizeLimit:
nextConfig.experimental.serverActions?.bodySizeLimit,
serverActions: nextConfig.experimental.serverActions,
nextFontManifest: require(join(
distDir,
'server',
Expand Down
1 change: 1 addition & 0 deletions packages/next/src/lib/turbopack-warning.ts
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,7 @@ const supportedTurbopackNextConfigOptions = [
'experimental.scrollRestoration',
'experimental.forceSwcTransforms',
'experimental.serverActions.bodySizeLimit',
'experimental.serverActions.allowedForwardedHosts',
'experimental.memoryBasedWorkersCount',
'experimental.clientRouterFilterRedirects',
'experimental.webpackBuildWorker',
Expand Down
65 changes: 38 additions & 27 deletions packages/next/src/server/app-render/action-handler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -216,7 +216,7 @@ export async function handleAction({
generateFlight,
staticGenerationStore,
requestStore,
serverActionsBodySizeLimit,
serverActions,
ctx,
}: {
req: IncomingMessage
Expand All @@ -232,7 +232,10 @@ export async function handleAction({
generateFlight: GenerateFlight
staticGenerationStore: StaticGenerationStore
requestStore: RequestStore
serverActionsBodySizeLimit?: SizeLimit
serverActions?: {
bodySizeLimit?: SizeLimit
allowedForwardedHosts?: string[]
}
ctx: AppRenderContext
}): Promise<
| undefined
Expand Down Expand Up @@ -277,32 +280,41 @@ export async function handleAction({
'Missing `origin` header from a forwarded Server Actions request.'
)
} else if (!host || originHostname !== host) {
// This is an attack. We should not proceed the action.
console.error(
'`x-forwarded-host` and `host` headers do not match `origin` header from a forwarded Server Actions request. Aborting the action.'
)
// If the customer sets a list of allowed hosts, we'll allow the request.
// These can be their reverse proxies or other safe hosts.
if (
typeof host === 'string' &&
serverActions?.allowedForwardedHosts?.includes(host)
) {
// Ignore it
} else {
// This is an attack. We should not proceed the action.
console.error(
'`x-forwarded-host` and `host` headers do not match `origin` header from a forwarded Server Actions request. Aborting the action.'
)

const error = new Error('Invalid Server Actions request.')
const error = new Error('Invalid Server Actions request.')

if (isFetchAction) {
res.statusCode = 500
await Promise.all(staticGenerationStore.pendingRevalidates || [])
const promise = Promise.reject(error)
try {
await promise
} catch {}
if (isFetchAction) {
res.statusCode = 500
await Promise.all(staticGenerationStore.pendingRevalidates || [])
const promise = Promise.reject(error)
try {
await promise
} catch {}

return {
type: 'done',
result: await generateFlight(ctx, {
actionResult: promise,
// if the page was not revalidated, we can skip the rendering the flight tree
skipFlight: !staticGenerationStore.pathWasRevalidated,
}),
return {
type: 'done',
result: await generateFlight(ctx, {
actionResult: promise,
// if the page was not revalidated, we can skip the rendering the flight tree
skipFlight: !staticGenerationStore.pathWasRevalidated,
}),
}
}
}

throw error
throw error
}
}

// ensure we avoid caching server actions unexpectedly
Expand Down Expand Up @@ -421,15 +433,14 @@ export async function handleAction({

const actionData = Buffer.concat(chunks).toString('utf-8')

const limit = require('next/dist/compiled/bytes').parse(
serverActionsBodySizeLimit ?? '1mb'
)
const readableLimit = serverActions?.bodySizeLimit ?? '1 MB'
const limit = require('next/dist/compiled/bytes').parse(readableLimit)

if (actionData.length > limit) {
const { ApiError } = require('../api-utils')
throw new ApiError(
413,
`Body exceeded ${serverActionsBodySizeLimit} limit.
`Body exceeded ${readableLimit} limit.
To configure the body size limit for Server Actions, see: https://nextjs.org/docs/app/api-reference/server-actions#size-limitation`
)
}
Expand Down
4 changes: 2 additions & 2 deletions packages/next/src/server/app-render/app-render.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -409,7 +409,7 @@ async function renderToHTMLOrFlightImpl(
dev,
nextFontManifest,
supportsDynamicHTML,
serverActionsBodySizeLimit,
serverActions,
buildId,
appDirDevErrorLogger,
assetPrefix = '',
Expand Down Expand Up @@ -955,7 +955,7 @@ async function renderToHTMLOrFlightImpl(
generateFlight,
staticGenerationStore: staticGenerationStore,
requestStore: requestStore,
serverActionsBodySizeLimit,
serverActions,
ctx,
})

Expand Down
6 changes: 5 additions & 1 deletion packages/next/src/server/app-render/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -132,7 +132,11 @@ export interface RenderOptsPartial {
rawConfig?: boolean,
silent?: boolean
) => Promise<NextConfigComplete>
serverActionsBodySizeLimit?: SizeLimit
serverActions?: {
bodySizeLimit?: SizeLimit
allowedForwardedHosts?: string[]
}
allowedForwardedHosts?: string[]
params?: ParsedUrlQuery
isPrefetch?: boolean
ppr: boolean
Expand Down
8 changes: 5 additions & 3 deletions packages/next/src/server/base-server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -245,7 +245,10 @@ type BaseRenderOpts = {
supportsDynamicHTML?: boolean
isBot?: boolean
clientReferenceManifest?: ClientReferenceManifest
serverActionsBodySizeLimit?: SizeLimit
serverActions?: {
bodySizeLimit?: SizeLimit
allowedForwardedHosts?: string[]
}
serverActionsManifest?: any
nextFontManifest?: NextFontManifest
renderServerComponentData?: boolean
Expand Down Expand Up @@ -2106,8 +2109,7 @@ export default abstract class Server<ServerOptions extends Options = Options> {
incrementalCache,
isRevalidate: isSSG,
originalPathname: components.ComponentMod.originalPathname,
serverActionsBodySizeLimit:
this.nextConfig.experimental.serverActions?.bodySizeLimit,
serverActions: this.nextConfig.experimental.serverActions,
}
: {}),
isDataReq,
Expand Down
8 changes: 7 additions & 1 deletion packages/next/src/server/config-schema.ts
Original file line number Diff line number Diff line change
Expand Up @@ -251,7 +251,13 @@ export const configSchema: zod.ZodType<NextConfig> = z.lazy(() =>
disableOptimizedLoading: z.boolean().optional(),
disablePostcssPresetEnv: z.boolean().optional(),
esmExternals: z.union([z.boolean(), z.literal('loose')]).optional(),
serverActionsBodySizeLimit: zSizeLimit.optional(),
serverActions: z
.object({
bodySizeLimit: zSizeLimit.optional(),
allowedForwardedHosts: z.array(z.string()).optional(),
})
.optional(),
allowedForwardedHosts: z.array(z.string()).optional(),
// The original type was Record<string, any>
extensionAlias: z.record(z.string(), z.any()).optional(),
externalDir: z.boolean().optional(),
Expand Down
7 changes: 7 additions & 0 deletions packages/next/src/server/config-shared.ts
Original file line number Diff line number Diff line change
Expand Up @@ -307,6 +307,13 @@ export interface ExperimentalConfig {
* Allows adjusting body parser size limit for server actions.
*/
bodySizeLimit?: SizeLimit

/**
* Allowed domains that can bypass CSRF check.
* @example
* ["my-reverse-proxy.com"]
*/
allowedForwardedHosts?: string[]
}

/**
Expand Down
16 changes: 9 additions & 7 deletions packages/next/src/server/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -417,13 +417,15 @@ function assignDefaults(
}
}

// TODO: Remove this warning in Next.js 15
warnOptionHasBeenDeprecated(
result,
'experimental.serverActions',
'Server Actions are available by default now, `experimental.serverActions` option can be safely removed.',
silent
)
if (typeof result.experimental?.serverActions === 'boolean') {
// TODO: Remove this warning in Next.js 15
warnOptionHasBeenDeprecated(
result,
'experimental.serverActions',
'Server Actions are available by default now, `experimental.serverActions` option can be safely removed.',
silent
)
}

if (result.swcMinify === false) {
// TODO: Remove this warning in Next.js 15
Expand Down
6 changes: 5 additions & 1 deletion packages/next/src/server/render.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -273,7 +273,11 @@ export type RenderOptsPartial = {
isBot?: boolean
runtime?: ServerRuntime
serverComponents?: boolean
serverActionsBodySizeLimit?: SizeLimit
serverActions?: {
bodySizeLimit?: SizeLimit
allowedForwardedHosts?: string[]
}
allowedForwardedHosts?: string[]
customServer?: boolean
crossOrigin?: 'anonymous' | 'use-credentials' | '' | undefined
images: ImageConfigComplete
Expand Down
Loading
Loading