From 27bdc3dc624b80145c66d00eb88b27fd185721a2 Mon Sep 17 00:00:00 2001 From: Alan Agius <17563226+alan-agius4@users.noreply.github.com> Date: Thu, 26 Nov 2026 09:04:19 +0000 Subject: [PATCH] =?UTF-8?q?refactor(@angular/ssr):=20reuse=20=C9=B5isHostA?= =?UTF-8?q?llowed=20from=20@angular/platform-server?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Replace the duplicate local `isHostAllowed` implementation in `@angular/ssr` with `ɵisHostAllowed` from `@angular/platform-server` so host allowlist matching stays consistent across both packages. Extract the framework-independent HTTP/proxy header helpers into `src/utils/headers.ts` so `node/src/request.ts` and its pure-Node unit tests do not pull in `@angular/platform-server`. --- packages/angular/ssr/node/src/request.ts | 2 +- .../angular/ssr/node/test/request_spec.ts | 2 +- packages/angular/ssr/src/app-engine.ts | 8 +- packages/angular/ssr/src/app.ts | 2 +- packages/angular/ssr/src/utils/headers.ts | 221 ++++++++++++++++ packages/angular/ssr/src/utils/ng.ts | 2 +- packages/angular/ssr/src/utils/validation.ts | 240 +----------------- .../angular/ssr/test/utils/validation_spec.ts | 11 +- 8 files changed, 236 insertions(+), 252 deletions(-) create mode 100644 packages/angular/ssr/src/utils/headers.ts diff --git a/packages/angular/ssr/node/src/request.ts b/packages/angular/ssr/node/src/request.ts index 4f604b6a9d0e..99135547128a 100644 --- a/packages/angular/ssr/node/src/request.ts +++ b/packages/angular/ssr/node/src/request.ts @@ -13,7 +13,7 @@ import { isProxyHeaderAllowed, normalizeTrustProxyHeaders, parseForwardedHeader, -} from '../../src/utils/validation'; +} from '../../src/utils/headers'; /** * A set containing all the pseudo-headers defined in the HTTP/2 specification. diff --git a/packages/angular/ssr/node/test/request_spec.ts b/packages/angular/ssr/node/test/request_spec.ts index 8d5b55ee39ae..c172f0c5beb9 100644 --- a/packages/angular/ssr/node/test/request_spec.ts +++ b/packages/angular/ssr/node/test/request_spec.ts @@ -8,7 +8,7 @@ import { IncomingMessage } from 'node:http'; import { Socket } from 'node:net'; -import { normalizeTrustProxyHeaders } from '../../src/utils/validation'; +import { normalizeTrustProxyHeaders } from '../../src/utils/headers'; import { createRequestUrl } from '../src/request'; // Helper to create a mock request object for testing. diff --git a/packages/angular/ssr/src/app-engine.ts b/packages/angular/ssr/src/app-engine.ts index 8afa2bbad822..ef216c7bc859 100644 --- a/packages/angular/ssr/src/app-engine.ts +++ b/packages/angular/ssr/src/app-engine.ts @@ -10,14 +10,10 @@ import type { AngularServerApp, getOrCreateAngularServerApp } from './app'; import { Hooks } from './hooks'; import { getPotentialLocaleIdFromUrl, getPreferredLocale } from './i18n'; import { EntryPointExports, getAngularAppEngineManifest } from './manifest'; +import { getFirstHeaderValue, normalizeTrustProxyHeaders } from './utils/headers'; import { createRedirectResponse } from './utils/redirect'; import { joinUrlParts } from './utils/url'; -import { - getFirstHeaderValue, - normalizeTrustProxyHeaders, - sanitizeRequestHeaders, - validateRequest, -} from './utils/validation'; +import { sanitizeRequestHeaders, validateRequest } from './utils/validation'; /** * Options for the Angular server application engine. diff --git a/packages/angular/ssr/src/app.ts b/packages/angular/ssr/src/app.ts index fdf13108e95b..3122e0f54085 100644 --- a/packages/angular/ssr/src/app.ts +++ b/packages/angular/ssr/src/app.ts @@ -21,11 +21,11 @@ import { getAngularAppManifest } from './manifest'; import { RenderMode } from './routes/route-config'; import { RouteTreeNodeMetadata } from './routes/route-tree'; import { ServerRouter } from './routes/router'; +import { getFirstHeaderValue } from './utils/headers'; import { AngularBootstrap, renderAngular } from './utils/ng'; import { promiseWithAbort } from './utils/promise'; import { createRedirectResponse } from './utils/redirect'; import { buildUrlWithParams, joinUrlParts, stripLeadingSlash } from './utils/url'; -import { getFirstHeaderValue } from './utils/validation'; /** * A set of well-known URLs that are not handled by Angular. diff --git a/packages/angular/ssr/src/utils/headers.ts b/packages/angular/ssr/src/utils/headers.ts new file mode 100644 index 000000000000..830e29c014e3 --- /dev/null +++ b/packages/angular/ssr/src/utils/headers.ts @@ -0,0 +1,221 @@ +/** + * @license + * Copyright Google LLC All Rights Reserved. + * + * Use of this source code is governed by an MIT-style license that can be + * found in the LICENSE file at https://angular.dev/license + */ + +/** + * Internal sentinel string representing a wildcard rule to trust all proxy headers. + */ +const TRUST_ALL_PROXY_HEADERS = '*'; + +/** + * Extracts the first value from a multi-value header string. + * + * @param value - A string or an array of strings representing the header values. + * If it's a string, values are expected to be comma-separated. + * @returns The first trimmed value from the multi-value header, or `undefined` if the input is invalid or empty. + * + * @example + * ```typescript + * getFirstHeaderValue("value1, value2, value3"); // "value1" + * getFirstHeaderValue(["value1", "value2"]); // "value1" + * getFirstHeaderValue(undefined); // undefined + * ``` + */ +export function getFirstHeaderValue( + value: string | string[] | undefined | null, +): string | undefined { + return value?.toString().split(',', 1)[0]?.trim(); +} + +/** + * Checks if a specific proxy header is allowed. + * + * @param headerName - The name of the proxy header to check. + * @param trustProxyHeaders - A set of allowed proxy headers. + * @returns `true` if the header is allowed, `false` otherwise. + */ +export function isProxyHeaderAllowed( + headerName: string, + trustProxyHeaders: ReadonlySet, +): boolean { + return ( + trustProxyHeaders.has(TRUST_ALL_PROXY_HEADERS) || + trustProxyHeaders.has(headerName.toLowerCase()) + ); +} + +/** + * Normalizes the `trustProxyHeaders` option to a consistent representation. + * @param trustProxyHeaders The input `trustProxyHeaders` value. + * @returns A `Set` of normalized header names. + */ +export function normalizeTrustProxyHeaders( + trustProxyHeaders: boolean | readonly string[] | undefined, +): ReadonlySet { + if (!trustProxyHeaders) { + return new Set(); + } + + if (trustProxyHeaders === true) { + return new Set([TRUST_ALL_PROXY_HEADERS]); + } + + const normalizedTrustedProxyHeaders = new Set(); + for (const header of trustProxyHeaders) { + const lowerHeader = header.toLowerCase(); + if (lowerHeader === TRUST_ALL_PROXY_HEADERS) { + throw new Error( + `"${TRUST_ALL_PROXY_HEADERS}" is not allowed as a value for the "trustProxyHeaders" option.`, + ); + } + const isValid = lowerHeader === 'forwarded' || lowerHeader.startsWith('x-forwarded-'); + if (!isValid) { + throw new Error( + `"${header}" is not a valid proxy header. Trusted proxy headers must be "forwarded" or start with "x-forwarded-".`, + ); + } + normalizedTrustedProxyHeaders.add(lowerHeader); + } + + return normalizedTrustedProxyHeaders; +} + +/** + * Parses the standard `Forwarded` header (RFC 7239). + * It extracts the parameters from the first (leftmost) element in the header. + * + * @param headerValue - The value of the `Forwarded` header. + * @returns A record of lowercase parameter names to their values. + */ +export function parseForwardedHeader( + headerValue: string | null | undefined, +): Record { + if (!headerValue) { + return {}; + } + + const params: Record = {}; + let inQuotes = false; + let escaped = false; + let currentKey = ''; + let currentValue = ''; + let isParsingValue = false; + let isKeyEnded = false; + let isParsingValueEnded = false; + + for (const char of headerValue) { + if (escaped) { + escaped = false; + if (isParsingValue) { + currentValue += char; + } else { + currentKey += char; + } + continue; + } + + if (char === '\\') { + if (inQuotes) { + escaped = true; + } else if (isParsingValue) { + currentValue += char; + } else { + currentKey += char; + } + continue; + } + + if (char === '"') { + inQuotes = !inQuotes; + continue; + } + + if (inQuotes) { + if (isParsingValue) { + currentValue += char; + } else { + currentKey += char; + } + continue; + } + + if (char === ',') { + addParam(currentKey, currentValue, isParsingValue, params); + break; + } + + if (char === ';') { + addParam(currentKey, currentValue, isParsingValue, params); + currentKey = ''; + currentValue = ''; + isParsingValue = false; + isKeyEnded = false; + isParsingValueEnded = false; + continue; + } + + if (char === '=') { + if (!isParsingValue) { + isParsingValue = true; + } else { + currentValue += char; + } + continue; + } + + if (char === ' ' || char === '\t') { + if (isParsingValue) { + if (currentValue.length > 0) { + isParsingValueEnded = true; + } + } else if (currentKey.length > 0) { + isKeyEnded = true; + } + continue; + } + + if (isParsingValue) { + if (!isParsingValueEnded) { + currentValue += char; + } + } else if (isKeyEnded) { + currentKey = char; + isKeyEnded = false; + } else { + currentKey += char; + } + } + + if (currentKey || currentValue || isParsingValue) { + addParam(currentKey, currentValue, isParsingValue, params); + } + + return params; +} + +/** + * Helper function to add a parameter to the params object. + * @param key - The key to add. + * @param value - The value to add. + * @param hasValue - Whether the parameter has a value. + * @param params - The params object to add the parameter to. + */ +function addParam( + key: string, + value: string, + hasValue: boolean, + params: Record, +): void { + if (!hasValue) { + return; + } + + const trimmedKey = key.trim().toLowerCase(); + if (trimmedKey) { + params[trimmedKey] = value; + } +} diff --git a/packages/angular/ssr/src/utils/ng.ts b/packages/angular/ssr/src/utils/ng.ts index 11f2111af0a7..93564d424c9f 100644 --- a/packages/angular/ssr/src/utils/ng.ts +++ b/packages/angular/ssr/src/utils/ng.ts @@ -24,8 +24,8 @@ import { } from '@angular/platform-server'; import { ActivatedRoute, Router } from '@angular/router'; import { Console } from '../console'; +import { getFirstHeaderValue } from './headers'; import { addTrailingSlash, joinUrlParts, stripIndexHtmlFromURL, stripTrailingSlash } from './url'; -import { getFirstHeaderValue } from './validation'; /** * Represents the bootstrap mechanism for an Angular application. diff --git a/packages/angular/ssr/src/utils/validation.ts b/packages/angular/ssr/src/utils/validation.ts index 73e6c712d80b..78556b9efbe3 100644 --- a/packages/angular/ssr/src/utils/validation.ts +++ b/packages/angular/ssr/src/utils/validation.ts @@ -6,10 +6,8 @@ * found in the LICENSE file at https://angular.dev/license */ -/** - * Internal sentinel string representing a wildcard rule to trust all proxy headers. - */ -const TRUST_ALL_PROXY_HEADERS = '*'; +import { ɵisHostAllowed as isHostAllowed } from '@angular/platform-server'; +import { getFirstHeaderValue, isProxyHeaderAllowed, parseForwardedHeader } from './headers'; /** * The set of headers that should be validated for host header injection attacks. @@ -32,26 +30,6 @@ const VALID_PROTO_REGEX = /^https?$/i; */ const VALID_PREFIX_REGEX = /^\/([a-z0-9_-]+\/)*[a-z0-9_-]*$/i; -/** - * Extracts the first value from a multi-value header string. - * - * @param value - A string or an array of strings representing the header values. - * If it's a string, values are expected to be comma-separated. - * @returns The first trimmed value from the multi-value header, or `undefined` if the input is invalid or empty. - * - * @example - * ```typescript - * getFirstHeaderValue("value1, value2, value3"); // "value1" - * getFirstHeaderValue(["value1", "value2"]); // "value1" - * getFirstHeaderValue(undefined); // undefined - * ``` - */ -export function getFirstHeaderValue( - value: string | string[] | undefined | null, -): string | undefined { - return value?.toString().split(',', 1)[0]?.trim(); -} - /** * Validates a request. * @@ -153,31 +131,6 @@ function verifyHostAllowed( } } -/** - * Checks if the hostname is allowed. - * @param hostname - The hostname to check. - * @param allowedHosts - A set of allowed hostnames. - * @returns `true` if the hostname is allowed, `false` otherwise. - */ -function isHostAllowed(hostname: string, allowedHosts: ReadonlySet): boolean { - if (allowedHosts.has('*') || allowedHosts.has(hostname)) { - return true; - } - - for (const allowedHost of allowedHosts) { - if (!allowedHost.startsWith('*.')) { - continue; - } - - const domain = allowedHost.slice(1); - if (hostname.endsWith(domain)) { - return true; - } - } - - return false; -} - /** * Validates the headers of an incoming request. * @@ -228,192 +181,3 @@ function validateHeaders( ); } } - -/** - * Checks if a specific proxy header is allowed. - * - * @param headerName - The name of the proxy header to check. - * @param trustProxyHeaders - A set of allowed proxy headers. - * @returns `true` if the header is allowed, `false` otherwise. - */ -export function isProxyHeaderAllowed( - headerName: string, - trustProxyHeaders: ReadonlySet, -): boolean { - return ( - trustProxyHeaders.has(TRUST_ALL_PROXY_HEADERS) || - trustProxyHeaders.has(headerName.toLowerCase()) - ); -} - -/** - * Normalizes the `trustProxyHeaders` option to a consistent representation. - * @param trustProxyHeaders The input `trustProxyHeaders` value. - * @returns A `Set` of normalized header names. - */ -export function normalizeTrustProxyHeaders( - trustProxyHeaders: boolean | readonly string[] | undefined, -): ReadonlySet { - if (!trustProxyHeaders) { - return new Set(); - } - - if (trustProxyHeaders === true) { - return new Set([TRUST_ALL_PROXY_HEADERS]); - } - - const normalizedTrustedProxyHeaders = new Set(); - for (const header of trustProxyHeaders) { - const lowerHeader = header.toLowerCase(); - if (lowerHeader === TRUST_ALL_PROXY_HEADERS) { - throw new Error( - `"${TRUST_ALL_PROXY_HEADERS}" is not allowed as a value for the "trustProxyHeaders" option.`, - ); - } - const isValid = lowerHeader === 'forwarded' || lowerHeader.startsWith('x-forwarded-'); - if (!isValid) { - throw new Error( - `"${header}" is not a valid proxy header. Trusted proxy headers must be "forwarded" or start with "x-forwarded-".`, - ); - } - normalizedTrustedProxyHeaders.add(lowerHeader); - } - - return normalizedTrustedProxyHeaders; -} - -/** - * Parses the standard `Forwarded` header (RFC 7239). - * It extracts the parameters from the first (leftmost) element in the header. - * - * @param headerValue - The value of the `Forwarded` header. - * @returns A record of lowercase parameter names to their values. - */ -export function parseForwardedHeader( - headerValue: string | null | undefined, -): Record { - if (!headerValue) { - return {}; - } - - const params: Record = {}; - let inQuotes = false; - let escaped = false; - let currentKey = ''; - let currentValue = ''; - let isParsingValue = false; - let isKeyEnded = false; - let isParsingValueEnded = false; - - for (const char of headerValue) { - if (escaped) { - escaped = false; - if (isParsingValue) { - currentValue += char; - } else { - currentKey += char; - } - continue; - } - - if (char === '\\') { - if (inQuotes) { - escaped = true; - } else if (isParsingValue) { - currentValue += char; - } else { - currentKey += char; - } - continue; - } - - if (char === '"') { - inQuotes = !inQuotes; - continue; - } - - if (inQuotes) { - if (isParsingValue) { - currentValue += char; - } else { - currentKey += char; - } - continue; - } - - if (char === ',') { - addParam(currentKey, currentValue, isParsingValue, params); - break; - } - - if (char === ';') { - addParam(currentKey, currentValue, isParsingValue, params); - currentKey = ''; - currentValue = ''; - isParsingValue = false; - isKeyEnded = false; - isParsingValueEnded = false; - continue; - } - - if (char === '=') { - if (!isParsingValue) { - isParsingValue = true; - } else { - currentValue += char; - } - continue; - } - - if (char === ' ' || char === '\t') { - if (isParsingValue) { - if (currentValue.length > 0) { - isParsingValueEnded = true; - } - } else if (currentKey.length > 0) { - isKeyEnded = true; - } - continue; - } - - if (isParsingValue) { - if (!isParsingValueEnded) { - currentValue += char; - } - } else if (isKeyEnded) { - currentKey = char; - isKeyEnded = false; - } else { - currentKey += char; - } - } - - if (currentKey || currentValue || isParsingValue) { - addParam(currentKey, currentValue, isParsingValue, params); - } - - return params; -} - -/** - * Helper function to add a parameter to the params object. - * @param key - The key to add. - * @param value - The value to add. - * @param hasValue - Whether the parameter has a value. - * @param params - The params object to add the parameter to. - */ -function addParam( - key: string, - value: string, - hasValue: boolean, - params: Record, -): void { - if (!hasValue) { - return; - } - - const trimmedKey = key.trim().toLowerCase(); - if (trimmedKey) { - params[trimmedKey] = value; - } -} diff --git a/packages/angular/ssr/test/utils/validation_spec.ts b/packages/angular/ssr/test/utils/validation_spec.ts index c9986a9bd73a..1685971fed4a 100644 --- a/packages/angular/ssr/test/utils/validation_spec.ts +++ b/packages/angular/ssr/test/utils/validation_spec.ts @@ -6,14 +6,17 @@ * found in the LICENSE file at https://angular.dev/license */ +// The compiler is needed as tests are in JIT. +/* eslint-disable import/no-unassigned-import */ +import '@angular/compiler'; +/* eslint-enable import/no-unassigned-import */ + import { getFirstHeaderValue, normalizeTrustProxyHeaders, parseForwardedHeader, - sanitizeRequestHeaders, - validateRequest, - validateUrl, -} from '../../src/utils/validation'; +} from '../../src/utils/headers'; +import { sanitizeRequestHeaders, validateRequest, validateUrl } from '../../src/utils/validation'; describe('Validation Utils', () => { describe('getFirstHeaderValue', () => {