Unverified Commit 24a617c2 authored by Shu Ding's avatar Shu Ding Committed by GitHub

Change allowed forwarded hosts to be allowed origins for Server Actions (#58023)

The allowlist should be origin domains that are allowed to send the
requests, not the list of forwarded hosts (i.e. reverse proxies).
parent f7b979c9
...@@ -28,7 +28,7 @@ export type EdgeSSRLoaderQuery = { ...@@ -28,7 +28,7 @@ export type EdgeSSRLoaderQuery = {
middlewareConfig: string middlewareConfig: string
serverActions?: { serverActions?: {
bodySizeLimit?: SizeLimit bodySizeLimit?: SizeLimit
allowedForwardedHosts?: string[] allowedOrigins?: string[]
} }
} }
......
...@@ -57,7 +57,7 @@ export function getRender({ ...@@ -57,7 +57,7 @@ export function getRender({
serverActionsManifest?: any serverActionsManifest?: any
serverActions?: { serverActions?: {
bodySizeLimit?: SizeLimit bodySizeLimit?: SizeLimit
allowedForwardedHosts?: string[] allowedOrigins?: string[]
} }
config: NextConfigComplete config: NextConfigComplete
buildId: string buildId: string
......
...@@ -79,7 +79,7 @@ const supportedTurbopackNextConfigOptions = [ ...@@ -79,7 +79,7 @@ const supportedTurbopackNextConfigOptions = [
'experimental.scrollRestoration', 'experimental.scrollRestoration',
'experimental.forceSwcTransforms', 'experimental.forceSwcTransforms',
'experimental.serverActions.bodySizeLimit', 'experimental.serverActions.bodySizeLimit',
'experimental.serverActions.allowedForwardedHosts', 'experimental.serverActions.allowedOrigins',
'experimental.memoryBasedWorkersCount', 'experimental.memoryBasedWorkersCount',
'experimental.clientRouterFilterRedirects', 'experimental.clientRouterFilterRedirects',
'experimental.webpackBuildWorker', 'experimental.webpackBuildWorker',
......
...@@ -257,7 +257,7 @@ export async function handleAction({ ...@@ -257,7 +257,7 @@ export async function handleAction({
requestStore: RequestStore requestStore: RequestStore
serverActions?: { serverActions?: {
bodySizeLimit?: SizeLimit bodySizeLimit?: SizeLimit
allowedForwardedHosts?: string[] allowedOrigins?: string[]
} }
ctx: AppRenderContext ctx: AppRenderContext
}): Promise< }): Promise<
...@@ -288,7 +288,7 @@ export async function handleAction({ ...@@ -288,7 +288,7 @@ export async function handleAction({
return return
} }
const originHostname = const originDomain =
typeof req.headers['origin'] === 'string' typeof req.headers['origin'] === 'string'
? new URL(req.headers['origin']).host ? new URL(req.headers['origin']).host
: undefined : undefined
...@@ -311,29 +311,28 @@ export async function handleAction({ ...@@ -311,29 +311,28 @@ export async function handleAction({
// This is to prevent CSRF attacks. If `x-forwarded-host` is set, we need to // This is to prevent CSRF attacks. If `x-forwarded-host` is set, we need to
// ensure that the request is coming from the same host. // ensure that the request is coming from the same host.
if (!originHostname) { if (!originDomain) {
// This might be an old browser that doesn't send `host` header. We ignore // This might be an old browser that doesn't send `host` header. We ignore
// this case. // this case.
console.warn( console.warn(
'Missing `origin` header from a forwarded Server Actions request.' 'Missing `origin` header from a forwarded Server Actions request.'
) )
} else if (!host || originHostname !== host.value) { } else if (!host || originDomain !== host.value) {
// If the customer sets a list of allowed hosts, we'll allow the request. // If the customer sets a list of allowed origins, we'll allow the request.
// These can be their reverse proxies or other safe hosts. // These are considered safe but might be different from forwarded host set
if ( // by the infra (i.e. reverse proxies).
host && if (serverActions?.allowedOrigins?.includes(originDomain)) {
typeof host.value === 'string' &&
serverActions?.allowedForwardedHosts?.includes(host.value)
) {
// Ignore it // Ignore it
} else { } else {
if (host) { if (host) {
// This is an attack. We should not proceed the action. // This seems to be an CSRF attack. We should not proceed the action.
console.error( console.error(
`\`${!host.type}\` header with value \`${limitUntrustedHeaderValueForLogs( `\`${
host.type
}\` header with value \`${limitUntrustedHeaderValueForLogs(
host.value host.value
)}\` does not match \`origin\` header with value \`${limitUntrustedHeaderValueForLogs( )}\` does not match \`origin\` header with value \`${limitUntrustedHeaderValueForLogs(
originHostname originDomain
)}\` from a forwarded Server Actions request. Aborting the action.` )}\` from a forwarded Server Actions request. Aborting the action.`
) )
} else { } else {
......
...@@ -134,9 +134,8 @@ export interface RenderOptsPartial { ...@@ -134,9 +134,8 @@ export interface RenderOptsPartial {
) => Promise<NextConfigComplete> ) => Promise<NextConfigComplete>
serverActions?: { serverActions?: {
bodySizeLimit?: SizeLimit bodySizeLimit?: SizeLimit
allowedForwardedHosts?: string[] allowedOrigins?: string[]
} }
allowedForwardedHosts?: string[]
params?: ParsedUrlQuery params?: ParsedUrlQuery
isPrefetch?: boolean isPrefetch?: boolean
experimental: { ppr: boolean } experimental: { ppr: boolean }
......
...@@ -250,7 +250,7 @@ type BaseRenderOpts = { ...@@ -250,7 +250,7 @@ type BaseRenderOpts = {
clientReferenceManifest?: ClientReferenceManifest clientReferenceManifest?: ClientReferenceManifest
serverActions?: { serverActions?: {
bodySizeLimit?: SizeLimit bodySizeLimit?: SizeLimit
allowedForwardedHosts?: string[] allowedOrigins?: string[]
} }
serverActionsManifest?: any serverActionsManifest?: any
nextFontManifest?: NextFontManifest nextFontManifest?: NextFontManifest
......
...@@ -254,10 +254,9 @@ export const configSchema: zod.ZodType<NextConfig> = z.lazy(() => ...@@ -254,10 +254,9 @@ export const configSchema: zod.ZodType<NextConfig> = z.lazy(() =>
serverActions: z serverActions: z
.object({ .object({
bodySizeLimit: zSizeLimit.optional(), bodySizeLimit: zSizeLimit.optional(),
allowedForwardedHosts: z.array(z.string()).optional(), allowedOrigins: z.array(z.string()).optional(),
}) })
.optional(), .optional(),
allowedForwardedHosts: z.array(z.string()).optional(),
// The original type was Record<string, any> // The original type was Record<string, any>
extensionAlias: z.record(z.string(), z.any()).optional(), extensionAlias: z.record(z.string(), z.any()).optional(),
externalDir: z.boolean().optional(), externalDir: z.boolean().optional(),
......
...@@ -309,11 +309,12 @@ export interface ExperimentalConfig { ...@@ -309,11 +309,12 @@ export interface ExperimentalConfig {
bodySizeLimit?: SizeLimit bodySizeLimit?: SizeLimit
/** /**
* Allowed domains that can bypass CSRF check. * Allowed origins that can bypass Server Action's CSRF check. This is helpful
* when you have reverse proxy in front of your app.
* @example * @example
* ["my-reverse-proxy.com"] * ["my-app.com"]
*/ */
allowedForwardedHosts?: string[] allowedOrigins?: string[]
} }
/** /**
......
...@@ -275,9 +275,8 @@ export type RenderOptsPartial = { ...@@ -275,9 +275,8 @@ export type RenderOptsPartial = {
serverComponents?: boolean serverComponents?: boolean
serverActions?: { serverActions?: {
bodySizeLimit?: SizeLimit bodySizeLimit?: SizeLimit
allowedForwardedHosts?: string[] allowedOrigins?: string[]
} }
allowedForwardedHosts?: string[]
customServer?: boolean customServer?: boolean
crossOrigin?: 'anonymous' | 'use-credentials' | '' | undefined crossOrigin?: 'anonymous' | 'use-credentials' | '' | undefined
images: ImageConfigComplete images: ImageConfigComplete
......
import { createNextDescribe } from 'e2e-utils'
import { check } from 'next-test-utils'
import { join } from 'path'
createNextDescribe(
'app-dir action allowed origins',
{
files: join(__dirname, 'safe-origins'),
skipDeployment: true,
dependencies: {
react: 'latest',
'react-dom': 'latest',
'server-only': 'latest',
},
// An arbitrary & random port.
forcedPort: '41831',
},
({ next }) => {
it('should pass if localhost is set as a safe origin', async function () {
const browser = await next.browser('/')
await browser.elementByCss('button').click()
await check(async () => {
return await browser.elementByCss('#res').text()
}, 'hi')
})
}
)
import { createNextDescribe } from 'e2e-utils' import { createNextDescribe } from 'e2e-utils'
import { check } from 'next-test-utils' import { check } from 'next-test-utils'
import { join } from 'path'
createNextDescribe( createNextDescribe(
'app-dir action allowed fowarding hosts', 'app-dir action disallowed origins',
{ {
files: __dirname, files: join(__dirname, 'unsafe-origins'),
skipDeployment: true, skipDeployment: true,
dependencies: { dependencies: {
react: 'latest', react: 'latest',
...@@ -13,10 +14,10 @@ createNextDescribe( ...@@ -13,10 +14,10 @@ createNextDescribe(
}, },
}, },
({ next }) => { ({ next }) => {
it('should error if setting an invalid x-forwarded-host header', async function () { // Origin should be localhost
const browser = await next.browser('/safe-hosts') it('should error if x-forwarded-host does not match the origin', async function () {
const browser = await next.browser('/')
await browser.eval(`window.__override_forwarded_host = 'bad.com'`)
await browser.elementByCss('button').click() await browser.elementByCss('button').click()
await check(async () => { await check(async () => {
...@@ -28,16 +29,5 @@ createNextDescribe( ...@@ -28,16 +29,5 @@ createNextDescribe(
: 'no' : 'no'
}, 'yes') }, 'yes')
}) })
it('should pass if using an allowed host', async function () {
const browser = await next.browser('/safe-hosts')
await browser.eval(`window.__override_forwarded_host = 'safe.com'`)
await browser.elementByCss('button').click()
await check(() => {
return browser.elementByCss('#res').text()
}, 'hi')
})
} }
) )
export default function RootLayout({ children }) {
return (
<html>
<head />
<body>{children}</body>
</html>
)
}
...@@ -7,12 +7,12 @@ if (typeof window !== 'undefined') { ...@@ -7,12 +7,12 @@ if (typeof window !== 'undefined') {
// hijack fetch // hijack fetch
const originalFetch = window.fetch const originalFetch = window.fetch
window.fetch = function (url, init) { window.fetch = function (url, init) {
if (window.__override_forwarded_host && init?.method === 'POST') { if (init?.method === 'POST') {
console.log('fetch', url, init) console.log('fetch', url, init)
// override forwarded host // override forwarded host
init.headers = init.headers || {} init.headers = init.headers || {}
init.headers['x-forwarded-host'] = window.__override_forwarded_host init.headers['x-forwarded-host'] = 'my-proxy.com'
} }
return originalFetch(url, init) return originalFetch(url, init)
......
/** @type {import('next').NextConfig} */
module.exports = {
productionBrowserSourceMaps: true,
logging: {
fetches: {},
},
experimental: {
serverActions: {
allowedOrigins: ['localhost:41831'],
},
},
}
'use server'
export async function log() {
return 'hi'
}
export default function RootLayout({ children }) {
return (
<html>
<head />
<body>{children}</body>
</html>
)
}
'use client'
import { useState } from 'react'
import { log } from './action'
if (typeof window !== 'undefined') {
// hijack fetch
const originalFetch = window.fetch
window.fetch = function (url, init) {
if (init?.method === 'POST') {
console.log('fetch', url, init)
// override forwarded host
init.headers = init.headers || {}
init.headers['x-forwarded-host'] = 'my-proxy.com'
}
return originalFetch(url, init)
}
}
export default function Page() {
const [res, setRes] = useState(null)
return (
<div>
<div id="res">{res}</div>
<button
onClick={async () => {
try {
setRes(await log())
} catch (err) {
setRes(err.message)
}
}}
>
fetch
</button>
</div>
)
}
/** @type {import('next').NextConfig} */
module.exports = {
productionBrowserSourceMaps: true,
logging: {
fetches: {},
},
}
...@@ -4,9 +4,4 @@ module.exports = { ...@@ -4,9 +4,4 @@ module.exports = {
logging: { logging: {
fetches: {}, fetches: {},
}, },
experimental: {
serverActions: {
allowedForwardedHosts: ['safe.com'],
},
},
} }
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