From c7cae1cf45cd34959c9c15db35518fd437c39a30 Mon Sep 17 00:00:00 2001 From: jm Date: Tue, 27 Oct 2026 14:40:28 +0100 Subject: [PATCH 1/4] Load SSR static content from the configured UI origin, not the Host header During SSR, HtmlContentService built the static-file URL from the request protocol and Host header. A request with a spoofed Host made the server fetch /static-files/*.html from an attacker origin and render it unsanitized (dsSafeHtml); the SSR page caches, keyed by path only, could then serve that render to other visitors. Use the origin of the configured ui.baseUrl (the address the Node server listens on) instead and drop the now unused REQUEST injection. dspace-customers#1083, finding R22. --- src/app/shared/html-content.service.spec.ts | 19 +++++++++++++++++-- src/app/shared/html-content.service.ts | 15 ++++----------- 2 files changed, 21 insertions(+), 13 deletions(-) diff --git a/src/app/shared/html-content.service.spec.ts b/src/app/shared/html-content.service.spec.ts index dbc04dcf4e4..c3a902f52d5 100644 --- a/src/app/shared/html-content.service.spec.ts +++ b/src/app/shared/html-content.service.spec.ts @@ -1,5 +1,7 @@ import { fakeAsync, TestBed, tick } from '@angular/core/testing'; +import { PLATFORM_ID, Provider } from '@angular/core'; import { HttpClientTestingModule, HttpTestingController } from '@angular/common/http/testing'; +import { REQUEST } from '@nguniversal/express-engine/tokens'; import { firstValueFrom } from 'rxjs'; import { HtmlContentService } from './html-content.service'; @@ -19,7 +21,7 @@ describe('HtmlContentService', () => { let httpMock: HttpTestingController; let localeService: LocaleServiceStub; - function setup(nameSpace: string): void { + function setup(nameSpace: string, serverProviders: Provider[] = []): void { TestBed.configureTestingModule({ imports: [HttpClientTestingModule], providers: [ @@ -28,9 +30,10 @@ describe('HtmlContentService', () => { { provide: APP_CONFIG, useValue: { - ui: { nameSpace }, + ui: { nameSpace, baseUrl: `http://localhost:4000${nameSpace}` }, }, }, + ...serverProviders, ], }); @@ -112,6 +115,18 @@ describe('HtmlContentService', () => { expect(content).toBe('
English Content
'); })); + it('should fetch static content from the configured UI origin, not the request Host, during SSR', async () => { + setup('/repository', [ + { provide: PLATFORM_ID, useValue: 'server' }, + { provide: REQUEST, useValue: { protocol: 'https', get: () => 'attacker.example' } }, + ]); + + const promise = service.getHmtlContentByPathAndLocale('about'); + + httpMock.expectOne('http://localhost:4000/repository/static-files/about.html').flush('Trusted content'); + expect(await promise).toBe('Trusted content'); + }); + it('should return empty string from getHtmlContent when request fails', async () => { setup('/repository'); diff --git a/src/app/shared/html-content.service.ts b/src/app/shared/html-content.service.ts index 664eaf71e22..184da485480 100644 --- a/src/app/shared/html-content.service.ts +++ b/src/app/shared/html-content.service.ts @@ -1,5 +1,5 @@ import { isPlatformServer } from '@angular/common'; -import { Inject, Injectable, Optional, PLATFORM_ID } from '@angular/core'; +import { Inject, Injectable, PLATFORM_ID } from '@angular/core'; import { HttpClient, HttpResponse } from '@angular/common/http'; import { catchError } from 'rxjs/operators'; import { firstValueFrom, of as observableOf } from 'rxjs'; @@ -7,7 +7,6 @@ import { HTML_SUFFIX, STATIC_FILES_PROJECT_PATH } from '../static-page/static-pa import { isEmpty } from './empty.util'; import { LocaleService } from '../core/locale/locale.service'; import { APP_CONFIG, AppConfig } from '../../config/app-config.interface'; -import { REQUEST } from '@nguniversal/express-engine/tokens'; /** * Service for loading static `.html` files stored in the `/static-files` folder. @@ -18,7 +17,6 @@ export class HtmlContentService { private localeService: LocaleService, @Inject(APP_CONFIG) protected appConfig?: AppConfig, @Inject(PLATFORM_ID) private platformId?: object, - @Optional() @Inject(REQUEST) private request?: any, ) {} private getNamespacePrefix(): string { @@ -45,17 +43,12 @@ export class HtmlContentService { } private buildRuntimeUrl(path: string): string { - if (!isPlatformServer(this.platformId) || !this.request) { + if (!isPlatformServer(this.platformId)) { return path; } - const protocol = this.request.protocol; - const host = this.request.get?.('host'); - if (!protocol || !host) { - return path; - } - - return `${protocol}://${host}${path}`; + // The request Host header is client-controlled; SSR loads static HTML only from the configured UI origin. + return `${new URL(this.appConfig.ui.baseUrl).origin}${path}`; } getHtmlContent(url: string) { From 0b1428321127821ad4e34237ec5b05c087ebf798 Mon Sep 17 00:00:00 2001 From: jm Date: Tue, 27 Oct 2026 15:00:28 +0100 Subject: [PATCH 2/4] Key SSR page caches by origin and language, not only by path getCacheKey returned req.url, but an anonymous SSR render also depends on the request origin (protocol and Host header, e.g. citation_pdf_url via getCurrentOrigin) and on the dsLanguage cookie. A request with a forged Host or another language filled the bot and anonymous caches for everyone requesting that path. Move the key to getSsrCacheKey so it can be unit tested and include protocol, Host and the language cookie. The /reload check now reads req.url, because the key no longer starts with the path. dspace-customers#1083, finding R22. --- server.ts | 21 +++++---------------- src/app/shared/ssr-cache-key.util.spec.ts | 21 +++++++++++++++++++++ src/app/shared/ssr-cache-key.util.ts | 12 ++++++++++++ 3 files changed, 38 insertions(+), 16 deletions(-) create mode 100644 src/app/shared/ssr-cache-key.util.spec.ts create mode 100644 src/app/shared/ssr-cache-key.util.ts diff --git a/server.ts b/server.ts index e7b13aef522..cc0322f689f 100644 --- a/server.ts +++ b/server.ts @@ -55,6 +55,7 @@ import { APP_CONFIG, AppConfig } from './src/config/app-config.interface'; import { extendEnvironmentWithAppConfig } from './src/config/config.util'; import { logStartupMessage } from './startup-message'; import { TOKENITEM } from './src/app/core/auth/models/auth-token-info.model'; +import { getSsrCacheKey } from './src/app/shared/ssr-cache-key.util'; import { SsrExcludePatterns } from './src/config/universal-config.interface'; @@ -385,7 +386,7 @@ function anonymousCacheEnabled(): boolean { /** * Check if the currently requested page is in our server-side, in-memory cache. - * Caching is ONLY done for SSR requests. Pages are cached base on their path (e.g. /home or /search?query=test) + * Caching is ONLY done for SSR requests. Pages are cached by path, origin and language (see getSsrCacheKey) */ function cacheCheck(req, res, next) { // Cached copy of page (if found) @@ -435,7 +436,7 @@ function cacheCheck(req, res, next) { */ function checkCacheForRequest(cacheName: string, cache: LRU, req, res): any { // Get the cache key for this request - const key = getCacheKey(req); + const key = getSsrCacheKey(req); // Check if this page is in our cache let cachedCopy = cache.get(key); @@ -459,18 +460,6 @@ function checkCacheForRequest(cacheName: string, cache: LRU, req, r return cachedCopy; } -/** - * Create a cache key from the current request. - * The cache key is the URL path (NOTE: this key will also include any querystring params). - * E.g. "/home" or "/search?query=test" - * @param req current request - * @returns cache key to use for this page - */ -function getCacheKey(req): string { - // NOTE: this will return the URL path *without* any baseUrl - return req.url; -} - /** * Save page to server side cache(s), if enabled. If caching is not enabled or a user is authenticated, this is a noop * If multiple caches are enabled, the page will be saved to any caches where it does not yet exist (or is expired). @@ -483,9 +472,9 @@ function saveToCache(req, page: any) { // NOTE: It's not safe to save page data to the cache when a user is authenticated. In that situation, // the page may include sensitive or user-specific materials. As the cache is shared across all users, it can only contain public info. if (!isUserAuthenticated(req)) { - const key = getCacheKey(req); + const key = getSsrCacheKey(req); // Avoid caching "/reload/[random]" paths (these are hard refreshes after logout) - if (key.startsWith('/reload')) { return; } + if (req.url.startsWith('/reload')) { return; } // Avoid caching not successful responses (status code different from 2XX status) if (hasNotSucceeded(req.res.statusCode)) { return; } diff --git a/src/app/shared/ssr-cache-key.util.spec.ts b/src/app/shared/ssr-cache-key.util.spec.ts new file mode 100644 index 00000000000..7c8827fa197 --- /dev/null +++ b/src/app/shared/ssr-cache-key.util.spec.ts @@ -0,0 +1,21 @@ +import { Request } from 'express'; + +import { getSsrCacheKey } from './ssr-cache-key.util'; +import { LANG_COOKIE } from '../core/locale/locale.service'; + +describe('getSsrCacheKey', () => { + function request(protocol: string, host: string, cookies: Record = {}): Request { + return { url: '/static/about', protocol, get: () => host, cookies } as unknown as Request; + } + + it('should separate renders for different language cookies', () => { + expect(getSsrCacheKey(request('https', 'repo.example', { [LANG_COOKIE]: 'cs' }))) + .not.toEqual(getSsrCacheKey(request('https', 'repo.example', { [LANG_COOKIE]: 'en' }))); + }); + + it('should separate renders for different request origins', () => { + const key = getSsrCacheKey(request('https', 'repo.example')); + expect(getSsrCacheKey(request('https', 'attacker.example'))).not.toEqual(key); + expect(getSsrCacheKey(request('http', 'repo.example'))).not.toEqual(key); + }); +}); diff --git a/src/app/shared/ssr-cache-key.util.ts b/src/app/shared/ssr-cache-key.util.ts new file mode 100644 index 00000000000..4f05e1479c5 --- /dev/null +++ b/src/app/shared/ssr-cache-key.util.ts @@ -0,0 +1,12 @@ +import { Request } from 'express'; +import { LANG_COOKIE } from '../core/locale/locale.service'; + +/** + * Key of a server-side rendered page in the SSR page caches (see server.ts). + * Besides path and query, an anonymous render depends on the request origin (protocol and Host header, + * e.g. in `citation_pdf_url`) and on the language cookie, so they are part of the key. + * @param req current request + */ +export function getSsrCacheKey(req: Request): string { + return JSON.stringify([req.protocol, req.get('host'), req.cookies?.[LANG_COOKIE], req.url]); +} From 1a69f18114d7dba67a04a8024116a9d6de702c2f Mon Sep 17 00:00:00 2001 From: jm Date: Tue, 27 Oct 2026 15:16:03 +0100 Subject: [PATCH 3/4] Skip the SSR bot cache for authenticated requests cacheCheck read the bot cache for any bot user agent before checking for an authentication cookie, so an authenticated request with a bot user agent got the anonymous cached page instead of its own render. Read either cache only for anonymous requests; saveToCache already stores anonymous renders only. dspace-customers#1083, finding R22. --- server.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/server.ts b/server.ts index cc0322f689f..2b3b65150bf 100644 --- a/server.ts +++ b/server.ts @@ -392,8 +392,8 @@ function cacheCheck(req, res, next) { // Cached copy of page (if found) let cachedCopy; - // If the bot cache is enabled and this request looks like a bot, check the bot cache for a cached page. - if (botCacheEnabled() && isbot(req.get('user-agent'))) { + // If the bot cache is enabled and this request looks like an anonymous bot, check the bot cache for a cached page. + if (botCacheEnabled() && isbot(req.get('user-agent')) && !isUserAuthenticated(req)) { cachedCopy = checkCacheForRequest('bot', botCache, req, res); } else if (anonymousCacheEnabled() && !isUserAuthenticated(req)) { cachedCopy = checkCacheForRequest('anonymous', anonymousCache, req, res); From fb411c789dcef83a0379f73ea4667365cfb430d9 Mon Sep 17 00:00:00 2001 From: jm Date: Tue, 27 Oct 2026 15:16:03 +0100 Subject: [PATCH 4/4] Do not load static page names that leave static-files once decoded The static page file name comes from the URL. Express decodes the path before serving files, so /static/..%2Findex loaded the app's own index.html into the page. Return no content for a name that contains a path separator after decoding (the query part is ignored), which renders the existing 404. dspace-customers#1083, finding R22. --- src/app/shared/html-content.service.spec.ts | 9 +++++++++ src/app/shared/html-content.service.ts | 16 ++++++++++++++++ 2 files changed, 25 insertions(+) diff --git a/src/app/shared/html-content.service.spec.ts b/src/app/shared/html-content.service.spec.ts index c3a902f52d5..9f459638e2c 100644 --- a/src/app/shared/html-content.service.spec.ts +++ b/src/app/shared/html-content.service.spec.ts @@ -127,6 +127,15 @@ describe('HtmlContentService', () => { expect(await promise).toBe('Trusted content'); }); + it('should not request a file name that leaves static-files once decoded', async () => { + setup('/repository'); + + const promise = service.getHmtlContentByPathAndLocale('..%2Findex'); + + httpMock.expectNone(() => true); + expect(await promise).toBeUndefined(); + }); + it('should return empty string from getHtmlContent when request fails', async () => { setup('/repository'); diff --git a/src/app/shared/html-content.service.ts b/src/app/shared/html-content.service.ts index 184da485480..82d40ccfb7c 100644 --- a/src/app/shared/html-content.service.ts +++ b/src/app/shared/html-content.service.ts @@ -84,10 +84,26 @@ export class HtmlContentService { return undefined; } + /** + * Whether a file name taken from the URL is still one file name once the server decodes it, + * so it cannot address a file outside `static-files` (e.g. `..%2Findex`). A query part is ignored. + */ + private isPlainFileName(fileName: string): boolean { + try { + return !/[/\\]/.test(decodeURIComponent(fileName.split('?')[0])); + } catch { + // Missing name or malformed percent-encoding: nothing to load. + return false; + } + } + /** * Get the html file content as a string by the file name and the current locale. */ async getHmtlContentByPathAndLocale(fileName: string) { + if (!this.isPlainFileName(fileName)) { + return undefined; + } let url = ''; // Get current language let language = this.localeService.getCurrentLanguageCode();