Skip to content
Open
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
2 changes: 1 addition & 1 deletion packages/angular/ssr/node/src/request.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
2 changes: 1 addition & 1 deletion packages/angular/ssr/node/test/request_spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
8 changes: 2 additions & 6 deletions packages/angular/ssr/src/app-engine.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
2 changes: 1 addition & 1 deletion packages/angular/ssr/src/app.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
221 changes: 221 additions & 0 deletions packages/angular/ssr/src/utils/headers.ts
Original file line number Diff line number Diff line change
@@ -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();
}
Comment thread
alan-agius4 marked this conversation as resolved.
Resolved

/**
* 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<string>,
): 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<string>` of normalized header names.
*/
export function normalizeTrustProxyHeaders(
trustProxyHeaders: boolean | readonly string[] | undefined,
): ReadonlySet<string> {
if (!trustProxyHeaders) {
return new Set();
}

if (trustProxyHeaders === true) {
return new Set([TRUST_ALL_PROXY_HEADERS]);
}

const normalizedTrustedProxyHeaders = new Set<string>();
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<string, string> {
if (!headerValue) {
return {};
}

const params: Record<string, string> = {};
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<string, string>,
): void {
if (!hasValue) {
return;
}

const trimmedKey = key.trim().toLowerCase();
if (trimmedKey) {
params[trimmedKey] = value;
}
}
2 changes: 1 addition & 1 deletion packages/angular/ssr/src/utils/ng.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
Loading