diff --git a/server.ts b/server.ts index b3db6fff540..bfba79a9476 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'; /* @@ -363,14 +364,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); } else if (anonymousCacheEnabled() && !isUserAuthenticated(req)) { cachedCopy = checkCacheForRequest('anonymous', anonymousCache, req, res); @@ -413,7 +414,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); @@ -437,18 +438,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). @@ -461,9 +450,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]); +} diff --git a/src/app/static-page/static-page.component.spec.ts b/src/app/static-page/static-page.component.spec.ts index 0d3df7afec0..51eb4cc894d 100644 --- a/src/app/static-page/static-page.component.spec.ts +++ b/src/app/static-page/static-page.component.spec.ts @@ -83,4 +83,12 @@ describe('StaticPageComponent', () => { expect(responseService.setNotFound).toHaveBeenCalled(); expect(component.contentState).toBe('not-found'); }); + + it('should not request a file name that leaves static-files once decoded', async () => { + (TestBed.inject(Router) as unknown as RouterMock).setRoute('/static/..%2Findex'); + await component.ngOnInit(); + expect(htmlContentService.fetchHtmlContent).not.toHaveBeenCalled(); + expect(responseService.setNotFound).toHaveBeenCalled(); + expect(component.contentState).toBe('not-found'); + }); }); diff --git a/src/app/static-page/static-page.component.ts b/src/app/static-page/static-page.component.ts index 8710fdb3110..d755b8c5c66 100644 --- a/src/app/static-page/static-page.component.ts +++ b/src/app/static-page/static-page.component.ts @@ -36,6 +36,12 @@ export class StaticPageComponent implements OnInit { let url = ''; // Fetch html file name from the url path. `static/some_file.html` this.htmlFileName = this.getHtmlFileName(); + if (isNotEmpty(this.htmlFileName) && !this.isPlainFileName(this.htmlFileName)) { + this.responseService.setNotFound(); + this.contentState = 'not-found'; + this.changeDetector.detectChanges(); + return; + } // Get current language let language = this.localeService.getCurrentLanguageCode(); @@ -138,6 +144,19 @@ export class StaticPageComponent implements OnInit { window.location.href = absoluteUrl.href; } + /** + * 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 { + // Malformed percent-encoding: nothing to load. + return false; + } + } + /** * Load file name from the URL - `static/FILE_NAME.html` * @private