diff --git a/goldens/public-api/angular/ssr/index.api.md b/goldens/public-api/angular/ssr/index.api.md index 852187d5290b..c8aa105b5426 100644 --- a/goldens/public-api/angular/ssr/index.api.md +++ b/goldens/public-api/angular/ssr/index.api.md @@ -22,6 +22,7 @@ export class AngularAppEngine { // @public export interface AngularAppEngineOptions { allowedHosts?: readonly string[]; + excludedPathPrefixes?: readonly string[]; trustProxyHeaders?: boolean | readonly string[]; } diff --git a/packages/angular/ssr/src/app-engine.ts b/packages/angular/ssr/src/app-engine.ts index ef216c7bc859..83a35e58b707 100644 --- a/packages/angular/ssr/src/app-engine.ts +++ b/packages/angular/ssr/src/app-engine.ts @@ -42,6 +42,26 @@ export interface AngularAppEngineOptions { * @default false */ trustProxyHeaders?: boolean | readonly string[]; + + /** + * Path prefixes that Angular never handles, such as the path of an API that another server + * serves. A request whose path starts with one of them, or whose path within the application + * does, is left to the next handler, which must answer it: `handle` resolves to `null` without + * rendering, even when a catch-all route would match. + * + * @remarks + * A relative URL that the application requests while it is rendered on the server is resolved + * against its base href. When the request that is rendered reached the server directly, the + * request for the relative URL reaches this server too, instead of the server that serves the + * path behind a reverse proxy. The path within the application is the path without the base + * href and the locale. A document without a `` element resolves relative URLs against the + * path of the page, which a prefix cannot match, so request the API with URLs that start with + * `/` in that case. + * + * @example `['/api']` leaves `/api`, `/api/users` and, under the locale `en`, `/en/api/users` + * to the next handler, but not `/apiary` or `/docs/api`. + */ + excludedPathPrefixes?: readonly string[]; } /** @@ -103,6 +123,23 @@ export class AngularAppEngine { */ private readonly trustProxyHeaders: ReadonlySet; + /** + * Path prefixes that Angular never handles, normalized and decoded, without a trailing slash. + */ + private readonly excludedPathPrefixes: readonly string[]; + + /** + * The base path of the application, without a trailing slash. + */ + private readonly normalizedBasePath = this.manifest.basePath.replace(/\/$/, ''); + + /** + * The path prefixes of the locales of the application, such as `/en`. + */ + private readonly localePrefixes: readonly string[] = Object.values(this.manifest.supportedLocales) + .filter((subPath) => !!subPath) + .map((subPath) => '/' + subPath); + /** * A cache that holds entry points, keyed by their potential locale string. */ @@ -115,6 +152,23 @@ export class AngularAppEngine { constructor(options?: AngularAppEngineOptions) { this.allowedHosts = this.getAllowedHosts(options); this.trustProxyHeaders = normalizeTrustProxyHeaders(options?.trustProxyHeaders); + this.excludedPathPrefixes = (options?.excludedPathPrefixes ?? []).map((prefix) => { + // Compared with the decoded path of a request URL, which the URL parser normalizes. + const { pathname, search, hash } = new URL(prefix, 'http://localhost'); + if ( + !prefix.startsWith('/') || + prefix.startsWith('//') || + search || + hash || + pathname === '/' + ) { + throw new Error( + `The excluded path prefix "${prefix}" must be a path that starts with "/" and is not "/".`, + ); + } + + return decodePath(pathname.endsWith('/') ? pathname.slice(0, -1) : pathname); + }); } private getAllowedHosts(options: AngularAppEngineOptions | undefined): ReadonlySet { @@ -168,6 +222,10 @@ export class AngularAppEngine { return this.handleValidationError(securedRequest.url, error as Error); } + if (this.isExcludedPath(securedRequest)) { + return null; + } + const serverApp = await this.getAngularServerAppForRequest(securedRequest); if (serverApp) { return serverApp.handle(securedRequest, requestContext); @@ -181,6 +239,36 @@ export class AngularAppEngine { return null; } + /** + * Checks whether the path of a request is one that Angular never handles. + * + * @param request The incoming request. + * @returns `true` if the path, or the path within the application, starts with one of the + * excluded path prefixes. + */ + private isExcludedPath(request: Request): boolean { + if (this.excludedPathPrefixes.length === 0) { + return false; + } + + const pathname = decodePath(new URL(request.url).pathname); + + // The relative URLs of the application resolve below its base href, which ends with the locale + // of a localized application. + let appPath = stripPathPrefix(pathname, this.normalizedBasePath); + for (const localePrefix of this.localePrefixes) { + const withoutLocale = stripPathPrefix(appPath, localePrefix); + if (withoutLocale !== appPath) { + appPath = withoutLocale; + break; + } + } + + return this.excludedPathPrefixes.some((prefix) => + [pathname, appPath].some((path) => path === prefix || path.startsWith(prefix + '/')), + ); + } + /** * Handles requests for the base path when i18n is enabled. * Redirects the user to a locale-specific path based on the `Accept-Language` header. @@ -324,3 +412,41 @@ export class AngularAppEngine { }); } } + +/** + * Removes a leading path from a path. + * + * @param path The path. + * @param prefix The leading path, without a trailing slash. + * @returns The rest of the path, or the path itself if it does not start with the prefix. + */ +function stripPathPrefix(path: string, prefix: string): string { + if (!prefix) { + return path; + } + + return path === prefix ? '/' : path.startsWith(prefix + '/') ? path.slice(prefix.length) : path; +} + +/** + * Decodes each segment of a path, so that a path compares equal however a client encoded it. + * + * @param path The path. + * @returns The path with decoded segments. A segment that is not validly encoded is kept as it is. + */ +function decodePath(path: string): string { + if (!path.includes('%')) { + return path; + } + + return path + .split('/') + .map((segment) => { + try { + return decodeURIComponent(segment); + } catch { + return segment; + } + }) + .join('/'); +} diff --git a/packages/angular/ssr/test/app-engine_spec.ts b/packages/angular/ssr/test/app-engine_spec.ts index db03015b85f1..b6a2bff06c17 100644 --- a/packages/angular/ssr/test/app-engine_spec.ts +++ b/packages/angular/ssr/test/app-engine_spec.ts @@ -14,7 +14,7 @@ import '@angular/compiler'; import { Component, REQUEST, inject } from '@angular/core'; import { destroyAngularServerApp, getOrCreateAngularServerApp } from '../src/app'; import { AngularAppEngine } from '../src/app-engine'; -import { setAngularAppEngineManifest } from '../src/manifest'; +import { EntryPointExports, setAngularAppEngineManifest } from '../src/manifest'; import { RenderMode } from '../src/routes/route-config'; import { setAngularAppTestingManifest } from './testing-utils'; @@ -354,6 +354,167 @@ describe('AngularAppEngine', () => { }); }); + describe('Excluded path prefixes', () => { + beforeAll(() => { + @Component({ + selector: 'app-page', + template: `Page works`, + }) + class PageComponent {} + + @Component({ + selector: 'app-not-found', + template: `Not found`, + }) + class NotFoundComponent {} + + setAngularAppEngineManifest({ + allowedHosts: ['example.com'], + entryPoints: { + '': async () => { + setAngularAppTestingManifest( + [ + { path: 'home', component: PageComponent }, + { path: '**', component: NotFoundComponent }, + ], + [{ path: '**', renderMode: RenderMode.Server }], + ); + + return { + ɵgetOrCreateAngularServerApp: getOrCreateAngularServerApp, + ɵdestroyAngularServerApp: destroyAngularServerApp, + }; + }, + }, + basePath: '/', + supportedLocales: { 'en-US': '' }, + }); + + appEngine = new AngularAppEngine({ excludedPathPrefixes: ['/api', '/auth/'] }); + }); + + it('should return null for a path below an excluded prefix that a catch-all route matches', async () => { + for (const path of [ + '/api', + '/api/', + '/api/config?x=1', + '/%61pi/config', + '/api/%E0', + '/auth', + '/auth/me', + ]) { + const response = await appEngine.handle(new Request(`https://example.com${path}`)); + expect(response).withContext(path).toBeNull(); + } + }); + + it('should render a path that does not start with an excluded prefix', async () => { + for (const path of ['/apiary', '/auth-me', '/docs/api', '/docs/api/x']) { + const response = await appEngine.handle(new Request(`https://example.com${path}`)); + expect(await response?.text()) + .withContext(path) + .toContain('Not found'); + } + }); + + it('should render other paths', async () => { + const response = await appEngine.handle(new Request('https://example.com/home')); + expect(await response?.text()).toContain('Page works'); + }); + + it('should validate the host before it excludes a path', async () => { + spyOn(console, 'error'); + const response = await appEngine.handle(new Request('https://evil.com/api/config')); + expect(response?.status).toBe(400); + }); + + it('should not accept a value that is not a path below the root', () => { + for (const prefix of ['api', '/', '//api', '/api?x=1', '/api#x']) { + expect(() => new AngularAppEngine({ excludedPathPrefixes: [prefix] })) + .withContext(prefix) + .toThrowError(/must be a path/); + } + }); + + it('should compare paths however a client encodes them', async () => { + for (const [excluded, path] of [ + ['/datos/año', '/datos/a%C3%B1o/config'], + ['/datos/a%C3%B1o', '/datos/año/config'], + ['/datos/a%c3%b1o', '/datos/a%C3%B1o/config'], + // A client that escapes characters that the URL parser leaves as they are. + ["/it's", '/it%27s/config'], + ]) { + const engine = new AngularAppEngine({ excludedPathPrefixes: [excluded] }); + const response = await engine.handle(new Request(`https://example.com${path}`)); + expect(response).withContext(`${excluded} ${path}`).toBeNull(); + } + }); + }); + + describe('Excluded path prefixes below the base href', () => { + /** Sets up an application whose catch-all route renders every path below its base href. */ + function setUp(basePath: string, supportedLocales: Record): void { + @Component({ + selector: 'app-any', + template: `Any page`, + }) + class AnyComponent {} + + const entryPoints: Record Promise> = {}; + for (const subPath of Object.values(supportedLocales)) { + entryPoints[subPath] = async () => { + setAngularAppTestingManifest( + [{ path: '**', component: AnyComponent }], + [{ path: '**', renderMode: RenderMode.Server }], + [basePath.replace(/\/$/, ''), subPath, ''].join('/').replace(/\/+/g, '/'), + ); + + return { + ɵgetOrCreateAngularServerApp: getOrCreateAngularServerApp, + ɵdestroyAngularServerApp: destroyAngularServerApp, + }; + }; + } + + setAngularAppEngineManifest({ + allowedHosts: ['example.com'], + entryPoints, + basePath, + supportedLocales, + }); + } + + afterEach(() => { + destroyAngularServerApp(); + }); + + it('should exclude a prefix of the path within the application under a base href', async () => { + setUp('/b', { 'en-US': '' }); + for (const prefix of ['/api', '/b/api']) { + const engine = new AngularAppEngine({ excludedPathPrefixes: [prefix] }); + const excluded = await engine.handle(new Request('https://example.com/b/api/config')); + expect(excluded).withContext(prefix).toBeNull(); + + const rendered = await engine.handle(new Request('https://example.com/b/apiary')); + expect(await rendered?.text()) + .withContext(prefix) + .toContain('Any page'); + } + }); + + it('should exclude a prefix of the path within a localized application', async () => { + setUp('/', { 'en': 'en', 'es': 'es' }); + const engine = new AngularAppEngine({ excludedPathPrefixes: ['/api'] }); + for (const path of ['/en/api/config', '/es/api', '/api/config']) { + const response = await engine.handle(new Request(`https://example.com${path}`)); + expect(response).withContext(path).toBeNull(); + } + + const rendered = await engine.handle(new Request('https://example.com/en/home')); + expect(await rendered?.text()).toContain('Any page'); + }); + }); + describe('Invalid host headers', () => { let consoleErrorSpy: jasmine.Spy;