Skip to content

Commit 78a40a9

Browse files
committed
fix(@angular/ssr): reject recursive SSR requests before rendering
Consume `ɵisSsrRequest` and `ɵSSR_REQUEST_HEADER` from `@angular/platform-server` (introduced in angular/angular#72226) to reject incoming requests that were sent by an Angular application while rendering on the server: - Guard cold-start `ServerRouter.from()` extraction (`!this.router && !this.manifest.routes`) in `AngularServerApp.handle()` to avoid deadlocking on the in-flight route extraction promise. - Reject static redirects in `AngularServerApp.handle()`, locale redirects in `AngularAppEngine.redirectBasedOnAcceptLanguage()`, and server-side rendering in `AngularServerApp.handleRendering()` (including on-demand rendering of prerendered routes when `allowStaticRouteRender` is enabled), while continuing to return `null` for non-Angular routes and serving static prerendered/CSR responses without rendering. - Return `404 Not Found` with `Cache-Control: no-store` (avoiding CDNs like CloudFront caching `400` responses despite `no-store` without triggering 5xx outlier ejection) and log a dev-only warning so loops are observable during development. Closes angular/angular#72223
1 parent 0a61cbc commit 78a40a9

6 files changed

Lines changed: 394 additions & 0 deletions

File tree

‎packages/angular/ssr/src/app-engine.ts‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@ import { Hooks } from './hooks';
1111
import { getPotentialLocaleIdFromUrl, getPreferredLocale } from './i18n';
1212
import { EntryPointExports, getAngularAppEngineManifest } from './manifest';
1313
import { createRedirectResponse } from './utils/redirect';
14+
import { createSsrRequestResponse, isSsrRequest } from './utils/ssr-request';
1415
import { joinUrlParts } from './utils/url';
1516
import {
1617
getFirstHeaderValue,
@@ -212,6 +213,10 @@ export class AngularAppEngine {
212213
if (preferredLocale) {
213214
const subPath = supportedLocales[preferredLocale];
214215
if (subPath !== undefined) {
216+
if (isSsrRequest(request)) {
217+
return createSsrRequestResponse(request);
218+
}
219+
215220
const prefix = getFirstHeaderValue(request.headers.get('X-Forwarded-Prefix')) ?? '';
216221

217222
return createRedirectResponse(

‎packages/angular/ssr/src/app.ts‎

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,7 @@ import { ServerRouter } from './routes/router';
2424
import { AngularBootstrap, renderAngular } from './utils/ng';
2525
import { promiseWithAbort } from './utils/promise';
2626
import { createRedirectResponse } from './utils/redirect';
27+
import { createSsrRequestResponse, isSsrRequest } from './utils/ssr-request';
2728
import { buildUrlWithParams, joinUrlParts, stripLeadingSlash } from './utils/url';
2829
import { getFirstHeaderValue } from './utils/validation';
2930

@@ -159,6 +160,12 @@ export class AngularServerApp {
159160
return null;
160161
}
161162

163+
if (!this.router && !this.manifest.routes && isSsrRequest(request)) {
164+
// Avoid triggering or awaiting route extraction (which bootstraps the app and may
165+
// deadlock on the in-flight extraction promise) for requests sent during SSR.
166+
return createSsrRequestResponse(request);
167+
}
168+
162169
this.router ??= await ServerRouter.from(this.manifest, url);
163170
const matchedRoute = this.router.match(url);
164171

@@ -170,6 +177,10 @@ export class AngularServerApp {
170177
const { redirectTo, relativeRedirect, status, renderMode, headers } = matchedRoute;
171178

172179
if (redirectTo !== undefined) {
180+
if (isSsrRequest(request)) {
181+
return createSsrRequestResponse(request);
182+
}
183+
173184
const location = joinUrlParts(
174185
getFirstHeaderValue(request.headers.get('X-Forwarded-Prefix')) ?? '',
175186
buildUrlWithParams(redirectTo, url.pathname, relativeRedirect ? undefined : url.search),
@@ -271,6 +282,12 @@ export class AngularServerApp {
271282
return null;
272283
}
273284

285+
if (renderMode !== RenderMode.Client && isSsrRequest(request)) {
286+
// The application sent this request to its own host while it was rendered on the server.
287+
// Rendering it could render a page that sends the same request again, without bound.
288+
return createSsrRequestResponse(request);
289+
}
290+
274291
const url = new URL(request.url);
275292
const platformProviders: StaticProvider[] = [];
276293

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
/**
2+
* @license
3+
* Copyright Google LLC All Rights Reserved.
4+
*
5+
* Use of this source code is governed by an MIT-style license that can be
6+
* found in the LICENSE file at https://angular.dev/license
7+
*/
8+
9+
import {
10+
ɵSSR_REQUEST_HEADER as SSR_REQUEST_HEADER,
11+
ɵisSsrRequest as isSsrRequest,
12+
} from '@angular/platform-server';
13+
14+
export { SSR_REQUEST_HEADER, isSsrRequest };
15+
16+
/**
17+
* Creates a non-cached response for an incoming request that carries the
18+
* {@link SSR_REQUEST_HEADER} header, indicating it was sent by an Angular application
19+
* while rendering on the server.
20+
*
21+
* A `404 Not Found` status with `Cache-Control: no-store` is returned instead of `400`
22+
* because some CDNs (such as CloudFront) ignore `Cache-Control: no-store` on `400`
23+
* responses and cache them by default, whereas `404` honors `no-store` without
24+
* triggering 5xx outlier ejection.
25+
*
26+
* @param request - The incoming recursive SSR `Request`.
27+
* @returns A `Response` object with a `404` status code and `Cache-Control: no-store`.
28+
*/
29+
export function createSsrRequestResponse(request: Request): Response {
30+
if (typeof ngDevMode === 'undefined' || ngDevMode) {
31+
// eslint-disable-next-line no-console
32+
console.warn(
33+
`Refusing to handle request for "${request.url}" because it carries the ` +
34+
`"${SSR_REQUEST_HEADER}" header, indicating it was sent while rendering on the server.`,
35+
);
36+
}
37+
38+
return new Response('Requests sent while rendering on the server are not rendered.', {
39+
status: 404,
40+
statusText: 'Not Found',
41+
headers: {
42+
'Content-Type': 'text/plain',
43+
'Cache-Control': 'no-store',
44+
},
45+
});
46+
}

‎packages/angular/ssr/test/app-engine_spec.ts‎

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@ import { destroyAngularServerApp, getOrCreateAngularServerApp } from '../src/app
1616
import { AngularAppEngine } from '../src/app-engine';
1717
import { setAngularAppEngineManifest } from '../src/manifest';
1818
import { RenderMode } from '../src/routes/route-config';
19+
import { SSR_REQUEST_HEADER } from '../src/utils/ssr-request';
1920
import { setAngularAppTestingManifest } from './testing-utils';
2021

2122
@Component({
@@ -235,6 +236,28 @@ describe('AngularAppEngine', () => {
235236
const response = await appEngine.handle(request);
236237
expect(response).toBeNull();
237238
});
239+
240+
it('should return a non-cached 404 instead of redirecting on "/" for recursive SSR requests', async () => {
241+
spyOn(console, 'warn');
242+
const request = new Request('https://example.com', {
243+
headers: {
244+
'Accept-Language': 'it',
245+
[SSR_REQUEST_HEADER]: '1',
246+
},
247+
});
248+
const response = await appEngine.handle(request);
249+
expect(response?.status).toBe(404);
250+
expect(response?.headers.get('Location')).toBeNull();
251+
expect(response?.headers.get('Cache-Control')).toBe('no-store');
252+
});
253+
254+
it('should still return null for unknown paths carrying the SSR request header', async () => {
255+
const request = new Request('https://example.com/unknown/page', {
256+
headers: { [SSR_REQUEST_HEADER]: '1' },
257+
});
258+
const response = await appEngine.handle(request);
259+
expect(response).toBeNull();
260+
});
238261
});
239262
});
240263

0 commit comments

Comments
 (0)