diff --git a/server.ts b/server.ts index 47e20ae5423..37301eb8631 100644 --- a/server.ts +++ b/server.ts @@ -68,6 +68,7 @@ import { SsrCacheStats, startSsrCacheStatsServer } from './src/backend/ssr-cache-stats'; +import { getSsrCacheKey } from './src/app/shared/ssr-cache-key.util'; /* * Set path for the browser application's dist folder @@ -465,14 +466,14 @@ 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) 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, next); } else if (anonymousCacheEnabled() && !isUserAuthenticated(req)) { cachedCopy = checkCacheForRequest('anonymous', anonymousCache, req, res, next); @@ -516,7 +517,7 @@ function cacheCheck(req, res, next) { */ function checkCacheForRequest(cacheName: 'bot' | 'anonymous', cache: LRUCache, req, res, next): any { // Get the cache key for this request - const key = getCacheKey(req); + const key = getSsrCacheKey(req); // Check if this page is in our cache const cachedCopy = cache.get(key); @@ -542,18 +543,6 @@ function checkCacheForRequest(cacheName: 'bot' | 'anonymous', cache: LRUCache { + let service: HtmlContentService; + let httpMock: HttpTestingController; + + beforeEach(() => { + TestBed.configureTestingModule({ + providers: [ + provideHttpClient(), + provideHttpClientTesting(), + { provide: PLATFORM_ID, useValue: 'browser' }, + { provide: LocaleService, useValue: { getCurrentLanguageCode: () => of('en') } }, + ], + }); + + service = TestBed.inject(HtmlContentService); + httpMock = TestBed.inject(HttpTestingController); + }); + + afterEach(() => { + httpMock.verify(); + }); + + it('should not request a file name that leaves static-files once decoded', async () => { + const promise = service.getHtmlContentByPathAndLocale('..%2Findex'); + + httpMock.expectNone(() => true); + expect(await promise).toBeUndefined(); + }); +}); diff --git a/src/app/shared/html-content.service.ts b/src/app/shared/html-content.service.ts index 0fb553d50fa..89edd260d91 100644 --- a/src/app/shared/html-content.service.ts +++ b/src/app/shared/html-content.service.ts @@ -42,6 +42,19 @@ export class HtmlContentService { return name.endsWith(HTML_SUFFIX) ? name : name + HTML_SUFFIX; } + /** + * 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; + } + } + private fetch(url: string) { return this.http.get(url, { responseType: 'text' }).pipe( map((body): HtmlContentResult => ({ found: true, body })), @@ -58,7 +71,7 @@ export class HtmlContentService { * and the content is loaded after hydration. */ async getHtmlContentByPathAndLocale(fileName: string): Promise { - if (!isPlatformBrowser(this.platformId)) { + if (!isPlatformBrowser(this.platformId) || !this.isPlainFileName(fileName)) { return undefined; } 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..031d5543530 --- /dev/null +++ b/src/app/shared/ssr-cache-key.util.spec.ts @@ -0,0 +1,21 @@ +import { Request } from 'express'; + +import { LANG_COOKIE } from '../core/locale/locale.service'; +import { getSsrCacheKey } from './ssr-cache-key.util'; + +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', 'other.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..d17aab24f3d --- /dev/null +++ b/src/app/shared/ssr-cache-key.util.ts @@ -0,0 +1,13 @@ +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) + * 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]); +}