diff --git a/packages/angular/ssr/src/utils/ng.ts b/packages/angular/ssr/src/utils/ng.ts index 4ae3a7f4ed0f..8c05a3a1432a 100644 --- a/packages/angular/ssr/src/utils/ng.ts +++ b/packages/angular/ssr/src/utils/ng.ts @@ -24,7 +24,13 @@ import { } from '@angular/platform-server'; import { ActivatedRoute, Router } from '@angular/router'; import { Console } from '../console'; -import { addTrailingSlash, joinUrlParts, stripIndexHtmlFromURL, stripTrailingSlash } from './url'; +import { + addTrailingSlash, + collapseLeadingSlashes, + joinUrlParts, + stripIndexHtmlFromURL, + stripTrailingSlash, +} from './url'; /** * Represents the bootstrap mechanism for an Angular application. @@ -133,7 +139,10 @@ export async function renderAngular( const urlToRenderString = constructSerializedUrl(router, urlToRender, requestPrefix); if (urlToRenderString !== finalUrl) { - redirectTo = [pathname, search, hash].join(''); + // The pathname is used as-is to preserve its encoding, as re-serializing it can alter it. + // Its leading slashes are collapsed because a pathname is allowed to start with `//`, + // which as a `Location` value is a protocol-relative URL pointing to another origin. + redirectTo = [collapseLeadingSlashes(pathname), search, hash].join(''); } } diff --git a/packages/angular/ssr/src/utils/redirect.ts b/packages/angular/ssr/src/utils/redirect.ts index b67f53265c17..0349c80874f6 100644 --- a/packages/angular/ssr/src/utils/redirect.ts +++ b/packages/angular/ssr/src/utils/redirect.ts @@ -6,6 +6,8 @@ * found in the LICENSE file at https://angular.dev/license */ +import { addLeadingSlash, collapseLeadingSlashes } from './url'; + /** * An set of HTTP status codes that are considered valid for redirect responses. */ @@ -26,7 +28,9 @@ export function isValidRedirectResponseCode(code: number): boolean { /** * Creates an HTTP redirect response with a specified location and status code. * - * @param location - The URL to which the response should redirect. + * @param location - The path to which the response should redirect. It is normalized to an + * absolute path, as a `Location` value is resolved against the request URL and + * must therefore not be able to point to another origin. * @param status - The HTTP status code for the redirection. Defaults to 302 (Found). * See: https://developer.mozilla.org/en-US/docs/Web/API/Response/redirect_static#status * @param headers - Additional headers to include in the response. @@ -44,6 +48,18 @@ export function createRedirectResponse( ); } + // A `Location` value is resolved against the request URL. Only a path that starts with a single + // slash is guaranteed to resolve to the current origin: two leading slashes make it a + // protocol-relative URL, and a missing leading slash can make it an absolute URL. + const normalizedLocation = addLeadingSlash(collapseLeadingSlashes(location)); + if (ngDevMode && normalizedLocation !== location) { + // eslint-disable-next-line no-console + console.warn( + `Location "${location}" is not an absolute path and was rewritten to "${normalizedLocation}" ` + + `to keep the redirect on the current origin.`, + ); + } + const resHeaders = headers instanceof Headers ? headers : new Headers(headers); if (ngDevMode && resHeaders.has('location')) { // eslint-disable-next-line no-console @@ -64,7 +80,7 @@ export function createRedirectResponse( } resHeaders.set('Vary', [...varySet].join(', ')); - resHeaders.set('Location', location); + resHeaders.set('Location', normalizedLocation); return new Response(null, { status, diff --git a/packages/angular/ssr/src/utils/url.ts b/packages/angular/ssr/src/utils/url.ts index d5e7c9ac2814..b082f9588879 100644 --- a/packages/angular/ssr/src/utils/url.ts +++ b/packages/angular/ssr/src/utils/url.ts @@ -78,6 +78,53 @@ export function addTrailingSlash(url: string): string { return url.at(-1) === '/' ? url : `${url}/`; } +/** + * Characters that cannot be left at the start of a path, because a client parsing the path as a + * URL would read them as the start of an authority. + * + * `/` and `\` are the two authority delimiters. Tab, line feed and carriage return are included + * because the WHATWG URL parser removes them from its input *before* parsing it, so they do not + * separate the delimiters around them: `/\t/example.com` is parsed as `//example.com`. + */ +const AUTHORITY_DELIMITERS: ReadonlySet = new Set(['/', '\\', '\t', '\n', '\r']); + +/** + * Collapses the leading slashes of a URL path into a single slash. + * + * A path that starts with two or more slashes or backslashes is parsed as a protocol-relative + * URL (for example, `//example.com` resolves to `https://example.com`), which points to a + * different origin. Collapsing the leading slashes keeps the path relative to the current origin. + * + * Characters that the URL parser strips are collapsed along with the slashes, as a path is + * resolved by the client and not by this function: leaving them in place would let + * `/\t/example.com` be parsed as `//example.com` after the collapse has run. + * + * @param pathname - The URL path to collapse the leading slashes of. + * @returns The URL path with at most one leading slash. + * + * @example + * ```js + * collapseLeadingSlashes('//example.com'); // '/example.com' + * collapseLeadingSlashes('/\\example.com'); // '/example.com' + * collapseLeadingSlashes('/\t/example.com'); // '/example.com' + * collapseLeadingSlashes('/path'); // '/path' + * ``` + */ +export function collapseLeadingSlashes(pathname: string): string { + // Use a "Pointer" to avoid intermediate slices + let start = 0; + while (start < pathname.length && AUTHORITY_DELIMITERS.has(pathname[start])) { + start++; + } + + // Nothing to collapse when the path already starts with at most one forward slash. + if (start === 0 || (start === 1 && pathname[0] === '/')) { + return pathname; + } + + return `/${pathname.slice(start)}`; +} + /** * Joins URL parts into a single URL string. * diff --git a/packages/angular/ssr/test/app_spec.ts b/packages/angular/ssr/test/app_spec.ts index 56f4c6fd7b24..0759f7d86c2c 100644 --- a/packages/angular/ssr/test/app_spec.ts +++ b/packages/angular/ssr/test/app_spec.ts @@ -435,6 +435,92 @@ describe('AngularServerApp', () => { expect(response?.status).toBe(302); }); + describe('protocol-relative redirects', () => { + /** + * Installs a route tree where the first URL segment is a parameter with a wildcard child. + * This allows the router to match a URL such as `/.;/(//example.com)`, which the router + * serializes with an empty leading segment. + */ + function setupWildcardChildManifest(): AngularServerApp { + setAngularAppTestingManifest( + [ + { + path: ':slug', + children: [{ path: '**', component: HomeComponent }], + }, + ], + [{ path: '**', renderMode: RenderMode.Server }], + ); + + return new AngularServerApp(); + } + + afterEach(() => { + setupManifest(); + }); + + it('should not redirect to another origin when the final URL has an empty leading segment', async () => { + const customApp = setupWildcardChildManifest(); + const response = await customApp.handle( + new Request('http://localhost/.;/(//example.com)'), + ); + + expect(response?.status).toBe(302); + expect(response?.headers.get('location')).toBe('/example.com'); + }); + + it('should keep the query string and userinfo on the current origin', async () => { + const customApp = setupWildcardChildManifest(); + const response = await customApp.handle( + new Request('http://localhost/.;/(//user@example.com:8080/login)?session=abc'), + ); + + expect(response?.status).toBe(302); + expect(response?.headers.get('location')).toBe( + '/user@example.com:8080/login?session=abc', + ); + }); + + it('should not redirect again when the redirect location is requested', async () => { + const customApp = setupWildcardChildManifest(); + const response = await customApp.handle(new Request('http://localhost/example.com')); + + expect(response?.status).toBe(200); + expect(await response?.text()).toContain('Home works'); + }); + + it('should not redirect to another origin for any X-Forwarded-Prefix', async () => { + // `AngularAppEngine` rejects these headers before they reach here, but it is not the + // only caller: the development server drives `AngularServerApp` directly through + // `ɵgetOrCreateAngularServerApp`, without that validation. + const prefixes = [ + '//evil.test', + '///evil.test', + '/\\evil.test', + '\\\\evil.test', + // A tab is a legal header value character, and the URL parser removes it before + // parsing, so these describe the same protocol-relative URL as the ones above. + '/\t/evil.test', + '/\t\\evil.test', + '\t//evil.test', + '/\t\t/evil.test', + ]; + + for (const prefix of prefixes) { + const response = await app.handle( + new Request('http://localhost/redirect', { + headers: { 'X-Forwarded-Prefix': prefix }, + }), + ); + + const location = response?.headers.get('location') ?? ''; + expect(new URL(location, 'http://localhost').origin) + .withContext(`X-Forwarded-Prefix: ${JSON.stringify(prefix)} -> ${location}`) + .toBe('http://localhost'); + } + }); + }); + it('should work with complex and encoded URLs', async () => { const urls = [ 'http://localhost/home?email=xyz%40xyz.com', diff --git a/packages/angular/ssr/test/utils/redirect_spec.ts b/packages/angular/ssr/test/utils/redirect_spec.ts index 4d0b94a87798..1468826d5fc3 100644 --- a/packages/angular/ssr/test/utils/redirect_spec.ts +++ b/packages/angular/ssr/test/utils/redirect_spec.ts @@ -46,6 +46,86 @@ describe('Redirect Utils', () => { expect(response.headers.get('Vary')).toBe('X-Forwarded-Prefix, Host'); }); + it('should normalize the Location header to an absolute path', () => { + const locations = { + '//example.com': '/example.com', + '///example.com': '/example.com', + '/\\example.com': '/example.com', + '\\\\example.com': '/example.com', + // A tab, line feed or carriage return is removed by the URL parser before it parses, so + // one between the slashes still yields a protocol-relative URL unless it is collapsed too. + '/\t/example.com': '/example.com', + '/\t\\example.com': '/example.com', + '\t//example.com': '/example.com', + '/\n/example.com': '/example.com', + '/\r/example.com': '/example.com', + 'https://example.com/path': '/https://example.com/path', + '': '/', + }; + + for (const [location, expected] of Object.entries(locations)) { + const response = createRedirectResponse(location); + expect(response.headers.get('Location')) + .withContext(`Location: "${location}"`) + .toBe(expected); + } + }); + + it('should never emit a Location header that resolves to another origin', () => { + const origin = 'https://example.com'; + + // The guarantee is about every string, so the inputs are generated rather than listed: a + // hand-written list only covers the escapes that were thought of when it was written. + // These are the characters that can begin an authority once a client parses the value, + // either directly or because the URL parser removes them first. + const separators = ['/', '\\', '\t', '\n', '\r', ' ', '.', ';', '@', '%2f', '%5c', '%09']; + const locations = new Set([ + 'https://evil.test/path', + 'evil.test:8080/path', + 'javascript:alert(1)', + '', + ]); + + for (const first of separators) { + for (const second of separators) { + for (const third of separators) { + locations.add(`${first}${second}${third}evil.test`); + } + } + } + + const escapes: string[] = []; + for (const location of locations) { + let emitted: string | null; + try { + emitted = createRedirectResponse(location).headers.get('Location'); + } catch { + // A value the Headers layer rejects, such as one containing a line feed, can never be + // emitted in the first place. + continue; + } + + if (new URL(emitted ?? '', origin).origin !== origin) { + escapes.push(`${JSON.stringify(location)} -> ${JSON.stringify(emitted)}`); + } + } + + expect(escapes) + .withContext(`Locations that left the origin: ${escapes.join(', ')}`) + .toEqual([]); + }); + + it('should warn if the Location is rewritten in dev mode', () => { + // @ts-expect-error accessing global + globalThis.ngDevMode = true; + const warnSpy = spyOn(console, 'warn'); + createRedirectResponse('//example.com'); + expect(warnSpy).toHaveBeenCalledWith( + 'Location "//example.com" is not an absolute path and was rewritten to "/example.com" ' + + 'to keep the redirect on the current origin.', + ); + }); + it('should warn if Location header is provided in extra headers in dev mode', () => { // @ts-expect-error accessing global globalThis.ngDevMode = true; diff --git a/packages/angular/ssr/test/utils/url_spec.ts b/packages/angular/ssr/test/utils/url_spec.ts index a108c7ff1df6..d51cbe4c8267 100644 --- a/packages/angular/ssr/test/utils/url_spec.ts +++ b/packages/angular/ssr/test/utils/url_spec.ts @@ -10,6 +10,7 @@ import { addLeadingSlash, addTrailingSlash, buildPathWithParams, + collapseLeadingSlashes, joinUrlParts, stripIndexHtmlFromURL, stripLeadingSlash, @@ -84,6 +85,56 @@ describe('URL Utils', () => { }); }); + describe('collapseLeadingSlashes', () => { + it('should collapse multiple leading slashes into a single slash', () => { + expect(collapseLeadingSlashes('//example.com')).toBe('/example.com'); + expect(collapseLeadingSlashes('///example.com')).toBe('/example.com'); + }); + + it('should replace leading backslashes with a single slash', () => { + expect(collapseLeadingSlashes('\\example.com')).toBe('/example.com'); + expect(collapseLeadingSlashes('\\\\example.com')).toBe('/example.com'); + expect(collapseLeadingSlashes('/\\example.com')).toBe('/example.com'); + expect(collapseLeadingSlashes('\\/example.com')).toBe('/example.com'); + }); + + it('should collapse characters the URL parser removes along with the slashes', () => { + // The WHATWG URL parser removes tab, line feed and carriage return from its input before + // parsing it, so these all describe the same protocol-relative URL as `//example.com`. + expect(collapseLeadingSlashes('/\t/example.com')).toBe('/example.com'); + expect(collapseLeadingSlashes('/\n/example.com')).toBe('/example.com'); + expect(collapseLeadingSlashes('/\r/example.com')).toBe('/example.com'); + expect(collapseLeadingSlashes('\t//example.com')).toBe('/example.com'); + expect(collapseLeadingSlashes('/\t\\example.com')).toBe('/example.com'); + expect(collapseLeadingSlashes('/\t\t/example.com')).toBe('/example.com'); + }); + + it('should not modify a path with a single leading slash', () => { + expect(collapseLeadingSlashes('/path/to/resource')).toBe('/path/to/resource'); + }); + + it('should preserve a removable character that is not leading', () => { + // Once a path segment has started, a later tab cannot reopen an authority. + expect(collapseLeadingSlashes('/path/\t/to')).toBe('/path/\t/to'); + }); + + it('should not modify a path without a leading slash', () => { + expect(collapseLeadingSlashes('path/to/resource')).toBe('path/to/resource'); + }); + + it('should preserve slashes that are not leading', () => { + expect(collapseLeadingSlashes('/path//to///resource')).toBe('/path//to///resource'); + }); + + it('should handle a path containing only slashes', () => { + expect(collapseLeadingSlashes('//')).toBe('/'); + }); + + it('should handle an empty path', () => { + expect(collapseLeadingSlashes('')).toBe(''); + }); + }); + describe('joinUrlParts', () => { it('should join multiple URL parts with normalized slashes', () => { expect(joinUrlParts('', 'path/', '/to/resource')).toBe('/path/to/resource');