Skip to content

Commit b66bc5a

Browse files
committed
fix(@angular/ssr): do not render requests sent while rendering on the server
Requests that an application sends to its own host while it is rendered on the server now carry an `x-angular-ssr-request` header. The server answers them with a 400 response instead of rendering them, which could repeat the same request without bound. Fixes #34789
1 parent 0a61cbc commit b66bc5a

4 files changed

Lines changed: 187 additions & 0 deletions

File tree

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

Lines changed: 7 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 { SSR_REQUEST_HEADER, createSsrRequestResponse } from './utils/ssr-request';
2728
import { buildUrlWithParams, joinUrlParts, stripLeadingSlash } from './utils/url';
2829
import { getFirstHeaderValue } from './utils/validation';
2930

@@ -317,6 +318,12 @@ export class AngularServerApp {
317318
return new Response(html, responseInit);
318319
}
319320

321+
if (request.headers.has(SSR_REQUEST_HEADER)) {
322+
// The application sent this request to its own host while it was rendered on the server.
323+
// Rendering it could render a page that sends the same request again, without bound.
324+
return createSsrRequestResponse();
325+
}
326+
320327
if (locale !== undefined) {
321328
platformProviders.push({
322329
provide: LOCALE_ID,

‎packages/angular/ssr/src/routes/route-config.ts‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@
66
* found in the LICENSE file at https://angular.dev/license
77
*/
88

9+
import { ɵHTTP_ROOT_INTERCEPTOR_FNS as HTTP_ROOT_INTERCEPTOR_FNS } from '@angular/common/http';
910
import {
1011
EnvironmentProviders,
1112
InjectionToken,
@@ -17,6 +18,7 @@ import {
1718
} from '@angular/core';
1819
import { provideServerRendering as provideServerRenderingPlatformServer } from '@angular/platform-server';
1920
import { type DefaultExport, ROUTES, type Route } from '@angular/router';
21+
import { ssrRequestInterceptorFn } from '../utils/ssr-request';
2022

2123
/**
2224
* The internal path used for the app shell route.
@@ -448,6 +450,8 @@ export function provideServerRendering(
448450

449451
const providers: (Provider | EnvironmentProviders)[] = [
450452
provideServerRenderingPlatformServer(options),
453+
// Registered after the platform server providers, so that relative URLs are already resolved.
454+
{ provide: HTTP_ROOT_INTERCEPTOR_FNS, useValue: ssrRequestInterceptorFn, multi: true },
451455
];
452456

453457
let hasAppShell = false;
Lines changed: 65 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,65 @@
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 { PlatformLocation } from '@angular/common';
10+
import type { HttpInterceptorFn } from '@angular/common/http';
11+
import { inject } from '@angular/core';
12+
13+
/**
14+
* The header added to the HTTP requests that an application sends to its own host while it is
15+
* rendered on the server. The server does not render requests that carry it.
16+
*/
17+
export const SSR_REQUEST_HEADER = 'x-angular-ssr-request';
18+
19+
/**
20+
* Adds the {@link SSR_REQUEST_HEADER} header to the requests sent to the host of the page being
21+
* rendered. Such a request could otherwise be rendered as a page that sends the same request again,
22+
* without bound.
23+
*
24+
* Host names are compared rather than origins: behind a proxy that terminates TLS, the page is
25+
* rendered for `http:` while the application may call its public `https:` URL.
26+
*
27+
* This interceptor must run after the `@angular/platform-server` interceptor that resolves relative
28+
* URLs. Requests that are not sent through the `HttpClient` interceptors are not marked.
29+
*/
30+
export const ssrRequestInterceptorFn: HttpInterceptorFn = (request, next) => {
31+
const { href, hostname } = inject(PlatformLocation);
32+
if (!URL.canParse(href)) {
33+
// The URL of the page is unknown, so requests sent to its host cannot be recognized.
34+
return next(request);
35+
}
36+
37+
// URLs that cannot be parsed are marked too: some HTTP clients still send a request for them.
38+
if (
39+
URL.canParse(request.urlWithParams, href) &&
40+
new URL(request.urlWithParams, href).hostname !== hostname
41+
) {
42+
return next(request);
43+
}
44+
45+
return next(request.clone({ setHeaders: { [SSR_REQUEST_HEADER]: '1' } }));
46+
};
47+
48+
/**
49+
* Creates the response to a request that the application sent to its own host while it was
50+
* rendered on the server. The request is not rendered. The response is only meaningful to the
51+
* render that sent the request, so it does not include the headers configured for the route and
52+
* must not be stored.
53+
*
54+
* @returns A `Response` object with a 400 status code.
55+
*/
56+
export function createSsrRequestResponse(): Response {
57+
return new Response('Requests sent while rendering on the server are not rendered.', {
58+
status: 400,
59+
statusText: 'Bad Request',
60+
headers: {
61+
'Content-Type': 'text/plain',
62+
'Cache-Control': 'no-store',
63+
},
64+
});
65+
}

‎packages/angular/ssr/test/app_spec.ts‎

Lines changed: 111 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@ import '@angular/compiler';
1212
/* eslint-enable import/no-unassigned-import */
1313

1414
import { APP_BASE_HREF } from '@angular/common';
15+
import { HttpClient, provideHttpClient } from '@angular/common/http';
1516
import {
1617
Component,
1718
DestroyRef,
@@ -20,12 +21,14 @@ import {
2021
REQUEST,
2122
RESPONSE_INIT,
2223
inject,
24+
signal,
2325
} from '@angular/core';
2426
import { ActivatedRoute, CanActivateFn, Router } from '@angular/router';
2527
import { setTimeout } from 'node:timers/promises';
2628
import { AngularServerApp } from '../src/app';
2729
import { Hooks } from '../src/hooks';
2830
import { RenderMode } from '../src/routes/route-config';
31+
import { SSR_REQUEST_HEADER } from '../src/utils/ssr-request';
2932
import { setAngularAppTestingManifest } from './testing-utils';
3033

3134
describe('AngularServerApp', () => {
@@ -818,5 +821,113 @@ describe('AngularServerApp', () => {
818821
});
819822
});
820823
});
824+
825+
describe('requests sent while rendering on the server', () => {
826+
@Component({
827+
selector: 'app-request',
828+
template: `{{ response() }}`,
829+
})
830+
class RequestComponent {
831+
protected readonly response = signal('');
832+
833+
constructor() {
834+
inject(HttpClient)
835+
.get(inject(ActivatedRoute).snapshot.data['url'], { responseType: 'text' })
836+
.subscribe({
837+
next: (value) => this.response.set(value),
838+
error: () => this.response.set('Request failed'),
839+
});
840+
}
841+
}
842+
843+
/** Creates an application whose pages request the given URL while they are rendered. */
844+
function createAppRequesting(url: string): AngularServerApp {
845+
setAngularAppTestingManifest(
846+
[{ path: '**', component: RequestComponent, data: { url } }],
847+
[{ path: '**', renderMode: RenderMode.Server }],
848+
undefined,
849+
undefined,
850+
undefined,
851+
undefined,
852+
[provideHttpClient()],
853+
);
854+
855+
return new AngularServerApp();
856+
}
857+
858+
beforeEach(() => {
859+
setupManifest();
860+
});
861+
862+
it('should return a 400 response that is not stored for routes requested while rendering', async () => {
863+
const response = await app.handle(
864+
new Request('http://localhost/page-with-headers', {
865+
headers: { [SSR_REQUEST_HEADER]: '' },
866+
}),
867+
);
868+
869+
expect(response?.status).toBe(400);
870+
expect(Object.fromEntries(response?.headers.entries() ?? [])).toEqual({
871+
'cache-control': 'no-store',
872+
'content-type': 'text/plain',
873+
});
874+
});
875+
876+
it('should serve prerendered pages, redirects and client-side rendered routes requested while rendering', async () => {
877+
const headers = { [SSR_REQUEST_HEADER]: '1' };
878+
879+
const redirect = await app.handle(new Request('http://localhost/redirect', { headers }));
880+
expect(redirect?.headers.get('location')).toBe('/home');
881+
882+
const prerendered = await app.handle(new Request('http://localhost/home-ssg', { headers }));
883+
expect(await prerendered?.text()).toContain('Home SSG works');
884+
885+
const clientSide = await app.handle(new Request('http://localhost/home-csr', { headers }));
886+
expect(await clientSide?.text()).toContain('<title>CSR page</title>');
887+
});
888+
889+
it('should not render the requests that a page sends to its own host', async () => {
890+
const requestingApp = createAppRequesting('/api');
891+
let requestCount = 0;
892+
let requestStatus: number | undefined;
893+
spyOn(globalThis, 'fetch').and.callFake(async (input, init) => {
894+
// Stop the loop that renders the page again for each of its own requests.
895+
if (++requestCount > 5) {
896+
return new Response(null, { status: 508 });
897+
}
898+
899+
const response =
900+
(await requestingApp.handle(new Request(input, init))) ??
901+
new Response(null, { status: 404 });
902+
requestStatus = response.status;
903+
904+
return response;
905+
});
906+
907+
const response = await requestingApp.handle(new Request('http://localhost/page'));
908+
expect(await response?.text()).toContain('Request failed');
909+
expect(requestCount).toBe(1);
910+
expect(requestStatus).toBe(400);
911+
});
912+
913+
it(`should add the '${SSR_REQUEST_HEADER}' header only to requests sent to the host of the page`, async () => {
914+
const fetchSpy = spyOn(globalThis, 'fetch').and.callFake(
915+
async () => new Response('Request works'),
916+
);
917+
918+
for (const url of ['http://example.com/api', 'https://localhost:8443/api']) {
919+
const response = await createAppRequesting(url).handle(
920+
new Request('http://localhost/page'),
921+
);
922+
expect(await response?.text()).toContain('Request works');
923+
}
924+
925+
const requests = fetchSpy.calls.allArgs().map(([input, init]) => new Request(input, init));
926+
expect(requests.map(({ url, headers }) => [url, headers.has(SSR_REQUEST_HEADER)])).toEqual([
927+
['http://example.com/api', false],
928+
['https://localhost:8443/api', true],
929+
]);
930+
});
931+
});
821932
});
822933
});

0 commit comments

Comments
 (0)