Unverified Commit 1caa5808 authored by Balázs Orbán's avatar Balázs Orbán Committed by GitHub

fix: correctly set `x-forwarded-*` in Middleware (#57815)

### What?

Follow-up of #56797

While working on this, I noticed that some logic around stripping internal headers was duplicated, so I did some cleanup too.

### Why?

In #56797 we set these headers, but it only affected Route Handlers, Middleware is still missing them, which is a regression introduced in #52492

(Related: https://github.com/vercel/next-learn/issues/252)

### How?

Move to set these headers up to `base-server.ts` so they are present in Middleware too.

> Note: All headers are set with `??=` to respect the original value if set (with other words, only add these headers if they aren't set yet)

Closes NEXT-
Fixes #52266
parent f2efb502
...@@ -127,6 +127,7 @@ import getRouteFromAssetPath from '../shared/lib/router/utils/get-route-from-ass ...@@ -127,6 +127,7 @@ import getRouteFromAssetPath from '../shared/lib/router/utils/get-route-from-ass
import { stripInternalHeaders } from './internal-utils' import { stripInternalHeaders } from './internal-utils'
import { RSCPathnameNormalizer } from './future/normalizers/request/rsc' import { RSCPathnameNormalizer } from './future/normalizers/request/rsc'
import { PostponedPathnameNormalizer } from './future/normalizers/request/postponed' import { PostponedPathnameNormalizer } from './future/normalizers/request/postponed'
import type { TLSSocket } from 'tls'
export type FindComponentsResult = { export type FindComponentsResult = {
components: LoadComponentsReturnType components: LoadComponentsReturnType
...@@ -894,6 +895,15 @@ export default abstract class Server<ServerOptions extends Options = Options> { ...@@ -894,6 +895,15 @@ export default abstract class Server<ServerOptions extends Options = Options> {
} }
} }
req.headers['x-forwarded-host'] ??= `${this.hostname}:${this.port}`
req.headers['x-forwarded-port'] ??= this.port?.toString()
const { originalRequest } = req as NodeNextRequest
req.headers['x-forwarded-proto'] ??= (originalRequest.socket as TLSSocket)
?.encrypted
? 'https'
: 'http'
req.headers['x-forwarded-for'] ??= originalRequest.socket?.remoteAddress
this.attachRequestMeta(req, parsedUrl) this.attachRequestMeta(req, parsedUrl)
const domainLocale = this.i18nProvider?.detectDomainLocale( const domainLocale = this.i18nProvider?.detectDomainLocale(
......
...@@ -2,6 +2,7 @@ import type { IncomingHttpHeaders } from 'http' ...@@ -2,6 +2,7 @@ import type { IncomingHttpHeaders } from 'http'
import type { NextParsedUrlQuery } from './request-meta' import type { NextParsedUrlQuery } from './request-meta'
import { NEXT_RSC_UNION_QUERY } from '../client/components/app-router-headers' import { NEXT_RSC_UNION_QUERY } from '../client/components/app-router-headers'
import { INTERNAL_HEADERS } from '../shared/lib/constants'
const INTERNAL_QUERY_NAMES = [ const INTERNAL_QUERY_NAMES = [
'__nextFallback', '__nextFallback',
...@@ -39,19 +40,6 @@ export function stripInternalSearchParams<T extends string | URL>( ...@@ -39,19 +40,6 @@ export function stripInternalSearchParams<T extends string | URL>(
return (isStringUrl ? instance.toString() : instance) as T return (isStringUrl ? instance.toString() : instance) as T
} }
/**
* Headers that are set by the Next.js server and should be stripped from the
* request headers going to the user's application.
*/
const INTERNAL_HEADERS = [
'x-invoke-path',
'x-invoke-status',
'x-invoke-error',
'x-invoke-query',
'x-invoke-output',
'x-middleware-invoke',
] as const
/** /**
* Strip internal headers from the request headers. * Strip internal headers from the request headers.
* *
......
...@@ -37,13 +37,15 @@ export class MockedRequest extends Stream.Readable implements IncomingMessage { ...@@ -37,13 +37,15 @@ export class MockedRequest extends Stream.Readable implements IncomingMessage {
private bodyReadable?: Stream.Readable private bodyReadable?: Stream.Readable
// If we don't actually have a socket, we'll just use a mock one that // If we don't actually have a socket, we'll just use a mock one that
// always returns false for the `encrypted` property. // always returns false for the `encrypted` property and undefined for the
// `remoteAddress` property.
public socket: Socket = new Proxy<TLSSocket>({} as TLSSocket, { public socket: Socket = new Proxy<TLSSocket>({} as TLSSocket, {
get: (_target, prop) => { get: (_target, prop) => {
if (prop !== 'encrypted') { if (prop !== 'encrypted' && prop !== 'remoteAddress') {
throw new Error('Method not implemented') throw new Error('Method not implemented')
} }
if (prop === 'remoteAddress') return undefined
// For this mock request, always ensure we just respond with the encrypted // For this mock request, always ensure we just respond with the encrypted
// set to false to ensure there's no odd leakages. // set to false to ensure there's no odd leakages.
return false return false
......
...@@ -32,7 +32,6 @@ import { ...@@ -32,7 +32,6 @@ import {
PERMANENT_REDIRECT_STATUS, PERMANENT_REDIRECT_STATUS,
} from '../../shared/lib/constants' } from '../../shared/lib/constants'
import { DevBundlerService } from './dev-bundler-service' import { DevBundlerService } from './dev-bundler-service'
import type { TLSSocket } from 'tls'
const debug = setupDebug('next:router-server:main') const debug = setupDebug('next:router-server:main')
...@@ -225,17 +224,6 @@ export async function initialize(opts: { ...@@ -225,17 +224,6 @@ export async function initialize(opts: {
'x-middleware-invoke': '', 'x-middleware-invoke': '',
'x-invoke-path': invokePath, 'x-invoke-path': invokePath,
'x-invoke-query': encodeURIComponent(JSON.stringify(parsedUrl.query)), 'x-invoke-query': encodeURIComponent(JSON.stringify(parsedUrl.query)),
'x-forwarded-host':
req.headers['x-forwarded-host'] ?? req.headers.host ?? opts.hostname,
'x-forwarded-port':
req.headers['x-forwarded-port'] ?? opts.port.toString(),
'x-forwarded-proto':
req.headers['x-forwarded-proto'] ??
(req.socket as TLSSocket).encrypted
? 'https'
: 'http',
'x-forwarded-for':
req.headers['x-forwarded-for'] ?? req.socket.remoteAddress,
...(additionalInvokeHeaders || {}), ...(additionalInvokeHeaders || {}),
} }
Object.assign(req.headers, invokeHeaders) Object.assign(req.headers, invokeHeaders)
......
...@@ -24,11 +24,13 @@ export async function proxyRequest( ...@@ -24,11 +24,13 @@ export async function proxyRequest(
target, target,
changeOrigin: true, changeOrigin: true,
ignorePath: true, ignorePath: true,
xfwd: true,
ws: true, ws: true,
// we limit proxy requests to 30s by default, in development // we limit proxy requests to 30s by default, in development
// we don't time out WebSocket requests to allow proxying // we don't time out WebSocket requests to allow proxying
proxyTimeout: proxyTimeout === null ? undefined : proxyTimeout || 30_000, proxyTimeout: proxyTimeout === null ? undefined : proxyTimeout || 30_000,
headers: {
'x-forwarded-host': req.headers.host || '',
},
}) })
await new Promise((proxyResolve, proxyReject) => { await new Promise((proxyResolve, proxyReject) => {
......
import type { TLSSocket } from 'tls'
import type { FsOutput } from './filesystem' import type { FsOutput } from './filesystem'
import type { IncomingMessage, ServerResponse } from 'http' import type { IncomingMessage, ServerResponse } from 'http'
import type { NextConfigComplete } from '../../config-shared' import type { NextConfigComplete } from '../../config-shared'
...@@ -38,6 +37,7 @@ import { ...@@ -38,6 +37,7 @@ import {
prepareDestination, prepareDestination,
} from '../../../shared/lib/router/utils/prepare-destination' } from '../../../shared/lib/router/utils/prepare-destination'
import { createRequestResponseMocks } from '../mock-request' import { createRequestResponseMocks } from '../mock-request'
import type { TLSSocket } from 'tls'
const debug = setupDebug('next:router-server:resolve-routes') const debug = setupDebug('next:router-server:resolve-routes')
......
...@@ -2,7 +2,6 @@ import './node-environment' ...@@ -2,7 +2,6 @@ import './node-environment'
import './require-hook' import './require-hook'
import './node-polyfill-crypto' import './node-polyfill-crypto'
import type { TLSSocket } from 'tls'
import type { CacheFs } from '../shared/lib/utils' import type { CacheFs } from '../shared/lib/utils'
import { import {
DecodeError, DecodeError,
...@@ -41,7 +40,6 @@ import { ...@@ -41,7 +40,6 @@ import {
SERVER_DIRECTORY, SERVER_DIRECTORY,
NEXT_FONT_MANIFEST, NEXT_FONT_MANIFEST,
PHASE_PRODUCTION_BUILD, PHASE_PRODUCTION_BUILD,
INTERNAL_HEADERS,
} from '../shared/lib/constants' } from '../shared/lib/constants'
import { findDir } from '../lib/find-pages-dir' import { findDir } from '../lib/find-pages-dir'
import { NodeNextRequest, NodeNextResponse } from './base-http/node' import { NodeNextRequest, NodeNextResponse } from './base-http/node'
...@@ -1616,10 +1614,6 @@ export default class NextNodeServer extends BaseServer { ...@@ -1616,10 +1614,6 @@ export default class NextNodeServer extends BaseServer {
> >
let bubblingResult = false let bubblingResult = false
for (const key of INTERNAL_HEADERS) {
delete req.headers[key]
}
// Strip the internal headers. // Strip the internal headers.
this.stripInternalHeaders(req) this.stripInternalHeaders(req)
...@@ -1746,11 +1740,8 @@ export default class NextNodeServer extends BaseServer { ...@@ -1746,11 +1740,8 @@ export default class NextNodeServer extends BaseServer {
parsedUrl: NextUrlWithParsedQuery, parsedUrl: NextUrlWithParsedQuery,
isUpgradeReq?: boolean isUpgradeReq?: boolean
) { ) {
const protocol = // Injected in base-server.ts
((req as NodeNextRequest).originalRequest?.socket as TLSSocket) const protocol = req.headers['x-forwarded-proto'] as 'https' | 'http'
?.encrypted || req.headers['x-forwarded-proto']?.includes('https')
? 'https'
: 'http'
// When there are hostname and port we build an absolute URL // When there are hostname and port we build an absolute URL
const initUrl = const initUrl =
......
...@@ -11,11 +11,7 @@ import { waitUntilSymbol } from './spec-extension/fetch-event' ...@@ -11,11 +11,7 @@ import { waitUntilSymbol } from './spec-extension/fetch-event'
import { NextURL } from './next-url' import { NextURL } from './next-url'
import { stripInternalSearchParams } from '../internal-utils' import { stripInternalSearchParams } from '../internal-utils'
import { normalizeRscURL } from '../../shared/lib/router/utils/app-paths' import { normalizeRscURL } from '../../shared/lib/router/utils/app-paths'
import { import { FLIGHT_PARAMETERS } from '../../client/components/app-router-headers'
NEXT_ROUTER_PREFETCH,
NEXT_ROUTER_STATE_TREE,
RSC,
} from '../../client/components/app-router-headers'
import { NEXT_QUERY_PARAM_PREFIX } from '../../lib/constants' import { NEXT_QUERY_PARAM_PREFIX } from '../../lib/constants'
import { ensureInstrumentationRegistered } from './globals' import { ensureInstrumentationRegistered } from './globals'
import { RequestAsyncStorageWrapper } from '../async-storage/request-async-storage-wrapper' import { RequestAsyncStorageWrapper } from '../async-storage/request-async-storage-wrapper'
...@@ -47,12 +43,6 @@ class NextRequestHint extends NextRequest { ...@@ -47,12 +43,6 @@ class NextRequestHint extends NextRequest {
} }
} }
const FLIGHT_PARAMETERS = [
[RSC],
[NEXT_ROUTER_STATE_TREE],
[NEXT_ROUTER_PREFETCH],
] as const
export type AdapterOptions = { export type AdapterOptions = {
handler: NextMiddleware handler: NextMiddleware
page: string page: string
......
...@@ -10,11 +10,16 @@ export const COMPILER_NAMES = { ...@@ -10,11 +10,16 @@ export const COMPILER_NAMES = {
edgeServer: 'edge-server', edgeServer: 'edge-server',
} as const } as const
/**
* Headers that are set by the Next.js server and should be stripped from the
* request headers going to the user's application.
*/
export const INTERNAL_HEADERS = [ export const INTERNAL_HEADERS = [
'x-invoke-path',
'x-invoke-status',
'x-invoke-error', 'x-invoke-error',
'x-invoke-output',
'x-invoke-path',
'x-invoke-query', 'x-invoke-query',
'x-invoke-status',
'x-middleware-invoke', 'x-middleware-invoke',
] as const ] as const
......
import { NextResponse } from 'next/server'
export function middleware(req: Request) {
return NextResponse.next({
headers: {
'middleware-x-forwarded-host':
req.headers.get('x-forwarded-host') ?? 'wrong',
'middleware-x-forwarded-port':
req.headers.get('x-forwarded-port') ?? 'wrong',
'middleware-x-forwarded-proto':
req.headers.get('x-forwarded-proto') ?? 'wrong',
},
})
}
...@@ -8,6 +8,10 @@ createNextDescribe('x-forwarded-headers', { files: __dirname }, ({ next }) => { ...@@ -8,6 +8,10 @@ createNextDescribe('x-forwarded-headers', { files: __dirname }, ({ next }) => {
expect(headers['x-forwarded-host']).toBe(url.host) expect(headers['x-forwarded-host']).toBe(url.host)
expect(headers['x-forwarded-port']).toBe(url.port) expect(headers['x-forwarded-port']).toBe(url.port)
expect(headers['x-forwarded-proto']).toBe(url.protocol.replace(':', '')) expect(headers['x-forwarded-proto']).toBe(url.protocol.replace(':', ''))
console.log(headers) expect(headers['middleware-x-forwarded-host']).toBe(url.host)
expect(headers['middleware-x-forwarded-port']).toBe(url.port)
expect(headers['middleware-x-forwarded-proto']).toBe(
url.protocol.replace(':', '')
)
}) })
}) })
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