diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index e8509e134ef..8e442b65757 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -83,6 +83,9 @@ jobs: - name: Run lint run: yarn run lint --quiet + - name: Run SSR response lifecycle tests + run: yarn run test:ssr-response-lifecycle + - name: Check for circular dependencies run: yarn run check-circ-deps diff --git a/package.json b/package.json index 565c0510999..52f413fcebd 100644 --- a/package.json +++ b/package.json @@ -5,6 +5,7 @@ "ng": "ng", "config:watch": "nodemon", "test:rest": "ts-node --project ./tsconfig.ts-node.json scripts/test-rest.ts", + "test:ssr-response-lifecycle": "node --test scripts/test-ssr-response-lifecycle.js", "start": "yarn run start:prod", "start:dev": "nodemon --exec \"cross-env NODE_ENV=development yarn run serve\"", "start:prod": "yarn run build:prod && cross-env NODE_ENV=production yarn run serve:ssr", diff --git a/scripts/test-ssr-response-lifecycle.js b/scripts/test-ssr-response-lifecycle.js new file mode 100644 index 00000000000..297e7b03502 --- /dev/null +++ b/scripts/test-ssr-response-lifecycle.js @@ -0,0 +1,324 @@ +const assert = require('node:assert/strict'); +const { once } = require('node:events'); +const { readFileSync } = require('node:fs'); +const { test } = require('node:test'); +const { setTimeout: sleep } = require('node:timers/promises'); +const vm = require('node:vm'); +const express = require('express'); +const LRUCache = require('lru-cache'); +const { resolve } = require('node:path'); +const ts = require('typescript'); + +process.env.TS_NODE_PROJECT = 'tsconfig.ts-node.json'; +process.env.TS_NODE_COMPILER_OPTIONS = JSON.stringify({ module: 'commonjs', moduleResolution: 'node' }); +require('ts-node/register/transpile-only'); + +// Execute the actual server functions without booting Angular or reading a production config. +function loadServerFunctions(cache, render, errors, mount = '/', foreground = false) { + const source = ts.createSourceFile('server.ts', readFileSync('server.ts', 'utf8'), ts.ScriptTarget.Latest, true); + const names = new Set(['serverSideRender', 'cacheCheck', 'checkCacheForRequest', + 'saveToCache', 'hasNotSucceeded', 'retrieveHeaders', 'isUserAuthenticated', 'botCacheEnabled', 'anonymousCacheEnabled']); + const functions = source.statements.filter(statement => ts.isFunctionDeclaration(statement) && names.has(statement.name?.text)); + assert.equal(functions.length, names.size); + const warnings = []; + const context = { + URL, botCache: cache, + anonymousCache: undefined, + cacheCounters: { bot: { hits: 0, misses: 0 }, anonymous: { hits: 0, misses: 0 } }, + environment: { + universal: { preboot: true }, ui: { baseUrl: 'http://localhost' }, + rest: { baseUrl: 'http://backend' }, + cache: { serverSide: { botCache: { max: 3 }, anonymousCache: { max: 0 }, headers: ['Link'] } }, + }, + indexHtml: resolve('src/index.html'), REST_BASE_URL: 'http://backend', + APP_BASE_HREF: 'base', REQUEST: 'request', RESPONSE: 'response', APP_CONFIG: 'config', + TOKENITEM: 'token', LANG_COOKIE: 'dsLanguage', isbot: () => true, hasValue: value => value != null, hasNoValue: value => value == null, + console: { log() {}, warn(message) { warnings.push(message); } }, + }; + Object.assign(context, require('../src/backend/ssr-response-context.ts')); + vm.createContext(context); + const keySource = ts.createSourceFile('key.ts', readFileSync('src/app/shared/ssr-cache-key.util.ts', 'utf8'), ts.ScriptTarget.Latest, true); + const keyFunction = keySource.statements.find(statement => ts.isFunctionDeclaration(statement) && statement.name.text === 'getSsrCacheKey'); + vm.runInContext(ts.transpileModule(functions.map(fn => fn.getText(source)).join('\n') + '\n' + keyFunction.getText(keySource).replace('export ', ''), { + compilerOptions: { target: ts.ScriptTarget.ES2022, module: ts.ModuleKind.CommonJS }, + }).outputText, context); + const app = express(); + app.locals.renderWarnings = warnings; + app.engine('html', (path, options, callback) => { + Promise.resolve(render({ providers: [ + { provide: 'response', useValue: options.req.res }, + { provide: 'request', useValue: options.req }, + ] })).then(html => { + try { callback(null, html); } catch (error) { errors.push(error); } + }, error => { + try { callback(error); } catch (failure) { errors.push(failure); } + }); + }); + const router = express.Router(); + router.use((req, res, next) => { + req.cookies = {}; + req.headers.host = '127.0.0.1'; + app.locals.originalRequest = req; + if (foreground) { context.serverSideRender(req, res); return; } + context.cacheCheck(req, res, error => { + if (error === 'router') { next('router'); } else { errors.push(error); } + }); + }); + app.use(mount, router); + return app; +} + +test('stale cache refresh owns an independent response and saves fresh headers after client response ends', async () => { + const cache = new LRUCache({ max: 3, ttl: 1, allowStale: true }); + cache.set(JSON.stringify(['http', '127.0.0.1', undefined, '/cached']), { page: 'stale', headers: { Link: 'old' } }); + await sleep(10); + let finishRender; + let renderResponse; + let renderRequest; + const errors = []; + const app = loadServerFunctions(cache, options => { + renderResponse = options.providers.find(provider => provider.provide === 'response').useValue; + renderRequest = options.providers.find(provider => provider.provide === 'request').useValue; + return new Promise(resolve => { finishRender = resolve; }); + }, errors, '/ui'); + const server = app.listen(0, '127.0.0.1'); + await once(server, 'listening'); + try { + const response = await fetch(`http://127.0.0.1:${server.address().port}/ui/cached`); + assert.equal(await response.text(), 'stale'); + assert.equal(response.headers.get('Link'), 'old'); + assert.equal(renderResponse.headersSent, false, 'background response must remain writable'); + assert.equal(renderRequest.res, renderResponse, 'cache save must read the rendered response'); + assert.equal(renderRequest.url, '/cached'); + assert.equal(app.locals.originalRequest.url, '/ui/cached', 'Express restored the mounted URL on the visitor request'); + renderResponse.setHeader('Link', 'fresh'); + finishRender('fresh html'); + await sleep(10); + assert.equal(cache.peek(JSON.stringify(['http', '127.0.0.1', undefined, '/cached']))?.page, 'fresh html'); + assert.equal(cache.peek(JSON.stringify(['http', '127.0.0.1', undefined, '/cached']))?.headers.Link, 'fresh'); + assert.deepEqual(errors, []); + } finally { + await new Promise(resolve => server.close(resolve)); + } +}); + + +test('background render redirects cannot redirect the visitor or enter the cache', async () => { + const cache = new LRUCache({ max: 3, ttl: 1, allowStale: true }); + cache.set(JSON.stringify(['http', '127.0.0.1', undefined, '/cached']), { page: 'stale' }); + await sleep(10); + let finishRender; + let renderResponse; + const errors = []; + const app = loadServerFunctions(cache, options => { + renderResponse = options.providers.find(provider => provider.provide === 'response').useValue; + return new Promise(resolve => { finishRender = resolve; }); + }, errors); + const server = app.listen(0, '127.0.0.1'); + await once(server, 'listening'); + try { + const response = await fetch(`http://127.0.0.1:${server.address().port}/cached`); + assert.equal(await response.text(), 'stale'); + renderResponse.redirect(302, '/different'); + finishRender('redirect page'); + await sleep(10); + assert.equal(response.status, 200); + assert.equal(response.headers.get('Location'), null); + assert.equal(cache.peek(JSON.stringify(['http', '127.0.0.1', undefined, '/cached'])), undefined); + assert.deepEqual(errors, []); + } finally { + await new Promise(resolve => server.close(resolve)); + } +}); + +test('background rendering failures do not call the completed client error pipeline', async () => { + const cache = new LRUCache({ max: 3, ttl: 1, allowStale: true }); + cache.set(JSON.stringify(['http', '127.0.0.1', undefined, '/cached']), { page: 'stale' }); + await sleep(10); + let failRender; + const errors = []; + const app = loadServerFunctions(cache, () => new Promise((resolve, reject) => { failRender = reject; }), errors); + const server = app.listen(0, '127.0.0.1'); + await once(server, 'listening'); + try { + const response = await fetch(`http://127.0.0.1:${server.address().port}/cached`); + assert.equal(await response.text(), 'stale'); + failRender(new Error('render failed')); + await sleep(10); + assert.equal(cache.peek(JSON.stringify(['http', '127.0.0.1', undefined, '/cached'])), undefined); + assert.deepEqual(errors, []); + } finally { + await new Promise(resolve => server.close(resolve)); + } +}); + +function loadClass(path, name, context) { + const source = ts.createSourceFile(path, readFileSync(path, 'utf8'), ts.ScriptTarget.Latest, true); + const declaration = source.statements.find(statement => ts.isClassDeclaration(statement) && statement.name?.text === name); + assert.ok(declaration, name); + const sandbox = { + exports: {}, Component: () => target => target, Injectable: () => target => target, + Inject: () => () => undefined, Optional: () => () => undefined, + ...context, + }; + vm.createContext(sandbox); + vm.runInContext(ts.transpileModule(declaration.getText(source), { + compilerOptions: { target: ts.ScriptTarget.ES2022, module: ts.ModuleKind.CommonJS, experimentalDecorators: true }, + }).outputText, sandbox); + return sandbox.exports[name]; +} + +for (const metadata of ['ready', 'pending', 'invalid-header']) { +test(`download redirects with optional signposting ${metadata}`, async () => { + const { Subject, of, combineLatest } = require('rxjs'); + const operators = require('rxjs/operators'); + const warnings = []; + const context = { + console: { warn: message => warnings.push(message) }, + ...operators, Observable: Object, of, observableOf: of, observableCombineLatest: combineLatest, + inject: () => ({}), Subject, environment: { signpostingEnabled: true }, PLATFORM_ID: {}, + AsyncPipe: {}, TranslateModule: {}, isPlatformServer: platform => platform === 'server', + takeUntilDestroyed: () => source => source, + getRemoteDataPayload: () => operators.map(data => data.payload), + redirectOn4xx: () => source => source, + hasValue: value => value != null, isNotEmpty: value => value != null && value !== '', + FeatureID: { CanDownload: 'download' }, getForbiddenRoute: () => '/forbidden', + }; + const ResponseService = loadClass('src/app/core/services/server-response.service.ts', 'ServerResponseService', { RESPONSE: {}, console: { warn: message => warnings.push(message) } }); + const RedirectService = loadClass('src/app/core/services/server-hard-redirect.service.ts', 'ServerHardRedirectService', { + APP_CONFIG: {}, REQUEST: {}, RESPONSE: {}, HardRedirectService: class {}, + isNotEmpty: context.isNotEmpty, environment: { ui: { baseUrl: 'https://ui.example' } }, console, + }); + const DownloadComponent = loadClass('src/app/bitstream-page/bitstream-download-page/bitstream-download-page.component.ts', 'BitstreamDownloadPageComponent', context); + const links = new Subject(); + const authorization = new Subject(); + let requestStarted; + const started = new Promise(resolve => { requestStarted = resolve; }); + const app = express(); + let pendingResponse; + app.get('/download', (req, res) => { + pendingResponse = res; + const bitstream = { _links: { content: { href: 'https://backend.example/content' } } }; + const route = { queryParams: of({}), data: of({ bitstream: { payload: bitstream } }), params: of({ id: 'test' }) }; + const component = new DownloadComponent(route, {}, { isAuthorized: () => authorization }, + { isAuthenticated: () => of(false) }, {}, + new RedirectService({ rest: { baseUrl: 'https://backend.example' } }, req, res), {}, {}, + { getLinks: () => links }, new ResponseService(res), 'server'); + component.ngOnInit(); + requestStarted(); + }); + const server = app.listen(0, '127.0.0.1'); + await once(server, 'listening'); + try { + const fetching = fetch(`http://127.0.0.1:${server.address().port}/download`, { redirect: 'manual' }); + await started; + assert.ok(pendingResponse); + assert.equal(pendingResponse.headersSent, false, 'authorization is not ready'); + if (metadata !== 'pending') { + links.next([{ href: metadata === 'invalid-header' ? 'https://example.org/\r\ninvalid' : 'https://example.org/item', rel: 'item' }]); + } + authorization.next(true); + const response = await fetching; + assert.equal(response.status, 302); + assert.equal(response.headers.get('Location'), 'https://backend.example/content'); + assert.equal(response.headers.get('Link'), metadata === 'ready' ? ' ; rel="item" ' : null); + await response.text(); + assert.equal(links.observers.length, 0, 'optional request unsubscribed in the decision turn'); + links.next([{ href: 'https://late.example/item', rel: 'item' }]); + assert.deepEqual(warnings, metadata === 'invalid-header' + ? ['Unable to load signposting links for the download response.'] : [], + 'late metadata must not attempt a committed response write'); + } finally { + await new Promise(resolve => server.close(resolve)); + } +}); + +} + +test('background 404 results cannot replace the successful cached visitor response or enter cache', async () => { + const cache = new LRUCache({ max: 3, ttl: 1, allowStale: true }); + cache.set(JSON.stringify(['http', '127.0.0.1', undefined, '/cached']), { page: 'stale' }); + await sleep(10); + let finishRender; + let renderResponse; + const errors = []; + const app = loadServerFunctions(cache, options => { + renderResponse = options.providers.find(provider => provider.provide === 'response').useValue; + return new Promise(resolve => { finishRender = resolve; }); + }, errors); + const server = app.listen(0, '127.0.0.1'); + await once(server, 'listening'); + try { + const response = await fetch(`http://127.0.0.1:${server.address().port}/cached`); + assert.equal(await response.text(), 'stale'); + renderResponse.statusCode = 404; + finishRender('not found'); + await sleep(10); + assert.equal(response.status, 200); + assert.equal(cache.peek(JSON.stringify(['http', '127.0.0.1', undefined, '/cached'])), undefined); + assert.deepEqual(errors, []); + } finally { + await new Promise(resolve => server.close(resolve)); + } +}); + +test('completed foreground redirect is not overwritten by the later SSR callback', async () => { + const cache = new LRUCache({ max: 3, ttl: 1000 }); + let finishRender; + let renderResponse; + let started; + const rendering = new Promise(resolve => { started = resolve; }); + const errors = []; + const app = loadServerFunctions(cache, options => { + renderResponse = options.providers.find(provider => provider.provide === 'response').useValue; + started(); + return new Promise(resolve => { finishRender = resolve; }); + }, errors, '/', true); + const server = app.listen(0, '127.0.0.1'); + await once(server, 'listening'); + try { + const fetching = fetch(`http://127.0.0.1:${server.address().port}/download`, { redirect: 'manual' }); + await rendering; + renderResponse.redirect(302, '/target'); + const response = await fetching; + await response.text(); + finishRender('later rendered page'); + await sleep(10); + assert.equal(response.status, 302); + assert.deepEqual(errors, []); + assert.equal(cache.size, 0); + } finally { + await new Promise(resolve => server.close(resolve)); + } +}); + +test('rendering errors after a foreground redirect remain visible without another response write', async () => { + const cache = new LRUCache({ max: 3, ttl: 1000 }); + let failRender; + let renderResponse; + let started; + const rendering = new Promise(resolve => { started = resolve; }); + const errors = []; + const app = loadServerFunctions(cache, options => { + renderResponse = options.providers.find(provider => provider.provide === 'response').useValue; + started(); + return new Promise((resolve, reject) => { failRender = reject; }); + }, errors, '/', true); + const server = app.listen(0, '127.0.0.1'); + await once(server, 'listening'); + try { + const fetching = fetch(`http://127.0.0.1:${server.address().port}/download`, { redirect: 'manual' }); + await rendering; + renderResponse.redirect(302, '/target'); + const response = await fetching; + await response.text(); + failRender(new Error('render failed')); + await sleep(10); + assert.equal(response.status, 302); + assert.deepEqual(errors, []); + assert.deepEqual(app.locals.renderWarnings, ['Server-side rendering failed after the response was committed.']); + assert.equal(cache.size, 0); + } finally { + await new Promise(resolve => server.close(resolve)); + } +}); diff --git a/server.ts b/server.ts index 2b3b65150bf..6faaedd7d5e 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 { createSsrRefreshContext } from './src/backend/ssr-response-context'; import { getSsrCacheKey } from './src/app/shared/ssr-cache-key.util'; import { SsrExcludePatterns } from './src/config/universal-config.interface'; @@ -275,6 +276,14 @@ function serverSideRender(req, res, sendToUser: boolean = true) { originUrl: environment.ui.baseUrl, requestUrl: req.originalUrl, }, (err, data) => { + if (res.headersSent && hasValue(err)) { + console.warn('Server-side rendering failed after the response was committed.'); + } + // If headers were already sent, then do nothing else, it is probably a + // redirect response + if (res.headersSent) { + return; + } if (hasNoValue(err) && hasValue(data)) { // Replace REST URL with UI URL if (environment.universal.replaceRestUrl && REST_BASE_URL !== environment.rest.baseUrl) { @@ -450,7 +459,8 @@ function checkCacheForRequest(cacheName: string, cache: LRU, req, r // Update cached copy by rerendering server-side // NOTE: In this scenario the currently cached copy will be returned to the current user. // This re-render is peformed behind the scenes to update cached copy for next user. - serverSideRender(req, res, false); + const background = createSsrRefreshContext(req, res); + serverSideRender(background.request, background.response, false); } } else { if (environment.cache.serverSide.debug) { console.log(`CACHE MISS FOR ${key} in ${cacheName} cache.`); } diff --git a/src/app/bitstream-page/bitstream-download-page/bitstream-download-page.component.spec.ts b/src/app/bitstream-page/bitstream-download-page/bitstream-download-page.component.spec.ts index 59261e56d28..eee4f102451 100644 --- a/src/app/bitstream-page/bitstream-download-page/bitstream-download-page.component.spec.ts +++ b/src/app/bitstream-page/bitstream-download-page/bitstream-download-page.component.spec.ts @@ -1,7 +1,7 @@ import { ComponentFixture, TestBed, waitForAsync } from '@angular/core/testing'; import { AuthService } from '../../core/auth/auth.service'; import { FileService } from '../../core/shared/file.service'; -import { of as observableOf } from 'rxjs'; +import { EMPTY, of as observableOf, Subject, throwError } from 'rxjs'; import { Bitstream } from '../../core/shared/bitstream.model'; import { BitstreamDownloadPageComponent } from './bitstream-download-page.component'; import { AuthorizationDataService } from '../../core/data/feature-authorization/authorization-data.service'; @@ -189,4 +189,110 @@ describe('BitstreamDownloadPageComponent', () => { }); }); }); + describe('when signposting responds after download authorization', () => { + let links$: Subject; + + beforeEach(waitForAsync(() => { + init(); + links$ = new Subject(); + signpostingDataService.getLinks.and.returnValue(links$); + initTestbed(); + })); + + beforeEach(() => { + fixture = TestBed.createComponent(BitstreamDownloadPageComponent); + component = fixture.componentInstance; + fixture.detectChanges(); + }); + + it('should not wait for optional signposting before redirecting', () => { + expect(hardRedirectService.redirect).toHaveBeenCalledWith('content-url-with-headers'); + }); + + it('should cancel pending optional signposting at the redirect decision', () => { + expect(links$.observers.length).toBe(0); + }); + + it('should ignore signposting that arrives after redirecting', () => { + links$.next([mocklink]); + expect(serverResponseService.setHeader).not.toHaveBeenCalled(); + expect(hardRedirectService.redirect).toHaveBeenCalledTimes(1); + }); + + it('should redirect without a Link header if signposting is empty or malformed', () => { + links$.next(null); + expect(serverResponseService.setHeader).not.toHaveBeenCalled(); + expect(hardRedirectService.redirect).toHaveBeenCalledWith('content-url-with-headers'); + }); + + it('should ignore optional signposting errors after redirecting', () => { + const warning = spyOn(console, 'warn'); + links$.error(new Error('signposting unavailable')); + expect(serverResponseService.setHeader).not.toHaveBeenCalled(); + expect(hardRedirectService.redirect).toHaveBeenCalledWith('content-url-with-headers'); + expect(warning).not.toHaveBeenCalled(); + }); + + it('should request download authorization while signposting is pending', () => { + expect(authorizationService.isAuthorized).toHaveBeenCalled(); + expect(fileService.retrieveFileDownloadLink).toHaveBeenCalled(); + expect(hardRedirectService.redirect).toHaveBeenCalled(); + }); + + }); + + [ + { name: 'malformed', response: () => observableOf(null), warns: false }, + { name: 'failed', response: () => throwError(() => new Error('optional metadata failed')), warns: true }, + { name: 'empty', response: () => EMPTY, warns: false }, + { name: 'a null link entry', response: () => observableOf([null]), warns: true }, + { name: 'an invalid header', response: () => observableOf([mocklink]), warns: true }, + ].forEach(scenario => { + describe(`when optional signposting is ${scenario.name} before authorization completes`, () => { + beforeEach(waitForAsync(() => { + init(); + signpostingDataService.getLinks.and.returnValue(scenario.response()); + initTestbed(); + })); + + it('should omit Link and still redirect', () => { + const warning = spyOn(console, 'warn'); + if (scenario.name === 'an invalid header') { + serverResponseService.setHeader.and.throwError('Invalid character in header content'); + } + fixture = TestBed.createComponent(BitstreamDownloadPageComponent); + fixture.detectChanges(); + expect(serverResponseService.setHeader.calls.count()).toBe(scenario.name === 'an invalid header' ? 1 : 0); + expect(hardRedirectService.redirect).toHaveBeenCalledWith('content-url-with-headers'); + expect(warning.calls.count()).toBe(scenario.warns ? 1 : 0); + }); + }); + }); + + describe('when destroyed before download authorization completes', () => { + let authorization$: Subject; + let links$: Subject; + + beforeEach(waitForAsync(() => { + init(); + authorization$ = new Subject(); + links$ = new Subject(); + (authorizationService.isAuthorized as jasmine.Spy).and.returnValue(authorization$); + signpostingDataService.getLinks.and.returnValue(links$); + initTestbed(); + })); + + it('should unsubscribe pending metadata and authorization without late side effects', () => { + fixture = TestBed.createComponent(BitstreamDownloadPageComponent); + fixture.detectChanges(); + fixture.destroy(); + authorization$.next(true); + links$.next([mocklink]); + expect(authorization$.observers.length).toBe(0); + expect(links$.observers.length).toBe(0); + expect(serverResponseService.setHeader).not.toHaveBeenCalled(); + expect(hardRedirectService.redirect).not.toHaveBeenCalled(); + }); + }); + }); diff --git a/src/app/bitstream-page/bitstream-download-page/bitstream-download-page.component.ts b/src/app/bitstream-page/bitstream-download-page/bitstream-download-page.component.ts index 700c6f162c2..2b64594ee9e 100644 --- a/src/app/bitstream-page/bitstream-download-page/bitstream-download-page.component.ts +++ b/src/app/bitstream-page/bitstream-download-page/bitstream-download-page.component.ts @@ -1,5 +1,5 @@ -import { Component, Inject, OnInit, PLATFORM_ID } from '@angular/core'; -import { filter, map, switchMap, take } from 'rxjs/operators'; +import { Component, Inject, OnDestroy, OnInit, PLATFORM_ID } from '@angular/core'; +import { catchError, filter, map, startWith, switchMap, take, takeUntil, tap, withLatestFrom } from 'rxjs/operators'; import { ActivatedRoute, Router } from '@angular/router'; import { hasValue, isNotEmpty } from '../../shared/empty.util'; import { getRemoteDataPayload } from '../../core/shared/operators'; @@ -7,7 +7,7 @@ import { Bitstream } from '../../core/shared/bitstream.model'; import { AuthorizationDataService } from '../../core/data/feature-authorization/authorization-data.service'; import { FeatureID } from '../../core/data/feature-authorization/feature-id'; import { AuthService } from '../../core/auth/auth.service'; -import { combineLatest as observableCombineLatest, Observable, of as observableOf } from 'rxjs'; +import { combineLatest as observableCombineLatest, Observable, of as observableOf, Subject } from 'rxjs'; import { FileService } from '../../core/shared/file.service'; import { HardRedirectService } from '../../core/services/hard-redirect.service'; import { getForbiddenRoute } from '../../app-routing-paths'; @@ -27,11 +27,13 @@ import { environment } from '../../../environments/environment'; /** * Page component for downloading a bitstream */ -export class BitstreamDownloadPageComponent implements OnInit { +export class BitstreamDownloadPageComponent implements OnInit, OnDestroy { bitstream$: Observable; bitstreamRD$: Observable>; + private readonly destroy$ = new Subject(); + constructor( private route: ActivatedRoute, protected router: Router, @@ -45,7 +47,6 @@ export class BitstreamDownloadPageComponent implements OnInit { private responseService: ServerResponseService, @Inject(PLATFORM_ID) protected platformId: string ) { - this.initPageLinks(); } back(): void { @@ -62,7 +63,7 @@ export class BitstreamDownloadPageComponent implements OnInit { getRemoteDataPayload() ); - this.bitstream$.pipe( + const download$ = this.bitstream$.pipe( switchMap((bitstream: Bitstream) => { const isAuthorized$ = this.authorizationService.isAuthorized(FeatureID.CanDownload, isNotEmpty(bitstream) ? bitstream.self : undefined); const isLoggedIn$ = this.auth.isAuthenticated(); @@ -82,6 +83,13 @@ export class BitstreamDownloadPageComponent implements OnInit { return [[isAuthorized, isLoggedIn, bitstream, '']]; } }) + ); + + download$.pipe( + withLatestFrom(this.initPageLinks().pipe(startWith(undefined))), + take(1), + map(([download]) => download), + takeUntil(this.destroy$) ).subscribe(([isAuthorized, isLoggedIn, bitstream, fileLink]: [boolean, boolean, Bitstream, string]) => { if (isAuthorized && isLoggedIn && isNotEmpty(fileLink)) { this.hardRedirectService.redirect(fileLink); @@ -101,22 +109,31 @@ export class BitstreamDownloadPageComponent implements OnInit { * * @private */ - private initPageLinks(): void { - if (!environment.signpostingEnabled) { - return; + private initPageLinks(): Observable { + if (!environment.signpostingEnabled || !isPlatformServer(this.platformId)) { + return observableOf(undefined); } - if (isPlatformServer(this.platformId)) { - this.route.params.subscribe(params => { - this.signpostingDataService.getLinks(params.id).pipe(take(1)).subscribe((signpostingLinks: SignpostingLink[]) => { - let links = ''; - - signpostingLinks.forEach((link: SignpostingLink) => { - links = links + (isNotEmpty(links) ? ', ' : '') + `<${link.href}> ; rel="${link.rel}"` + (isNotEmpty(link.type) ? ` ; type="${link.type}" ` : ' '); - }); - + return this.route.params.pipe( + take(1), + switchMap(params => this.signpostingDataService.getLinks(params.id).pipe(take(1))), + tap((signpostingLinks: SignpostingLink[]) => { + const links = (Array.isArray(signpostingLinks) ? signpostingLinks : []).map((link: SignpostingLink) => + `<${link.href}> ; rel="${link.rel}"` + (isNotEmpty(link.type) ? ` ; type="${link.type}" ` : ' ') + ).join(', '); + if (isNotEmpty(links)) { this.responseService.setHeader('Link', links); - }); - }); - } + } + }), + map(() => undefined), + catchError(() => { + console.warn('Unable to load signposting links for the download response.'); + return observableOf(undefined); + }) + ); + } + + ngOnDestroy(): void { + this.destroy$.next(); + this.destroy$.complete(); } } diff --git a/src/app/core/services/server-response.service.spec.ts b/src/app/core/services/server-response.service.spec.ts new file mode 100644 index 00000000000..a40262d9f01 --- /dev/null +++ b/src/app/core/services/server-response.service.spec.ts @@ -0,0 +1,36 @@ +import { ServerResponseService } from './server-response.service'; + +describe('ServerResponseService', () => { + it('should preserve headers and status after the response has been committed', () => { + const response = jasmine.createSpyObj('response', ['setHeader']); + response.headersSent = true; + response.statusCode = 302; + response.statusMessage = 'Found'; + const service = new ServerResponseService(response); + const warning = spyOn(console, 'warn'); + service.setHeader('Link', ''); + service.setStatus(200, 'OK'); + expect(response.setHeader).not.toHaveBeenCalled(); + expect(response.statusCode).toBe(302); + expect(response.statusMessage).toBe('Found'); + expect(warning).toHaveBeenCalledTimes(1); + expect(warning).toHaveBeenCalledWith('Server response already committed; skipping subsequent header/status updates.'); + }); + + it('should set headers and status before commitment', () => { + const response = jasmine.createSpyObj('response', ['setHeader']); + response.headersSent = false; + const service = new ServerResponseService(response); + service.setHeader('Link', ''); + service.setStatus(404, 'Not Found'); + expect(response.setHeader).toHaveBeenCalledWith('Link', ''); + expect(response.statusCode).toBe(404); + expect(response.statusMessage).toBe('Not Found'); + }); + + it('should be safe in the browser without a server response', () => { + const service = new ServerResponseService(null); + expect(() => service.setHeader('Link', '')).not.toThrow(); + expect(service.setStatus(200)).toBe(service); + }); +}); diff --git a/src/app/core/services/server-response.service.ts b/src/app/core/services/server-response.service.ts index 0b193d536c9..815746b2eed 100644 --- a/src/app/core/services/server-response.service.ts +++ b/src/app/core/services/server-response.service.ts @@ -10,6 +10,8 @@ import { Response } from 'express'; export class ServerResponseService { private response: Response; + private warnedAboutCommittedResponse = false; + constructor(@Optional() @Inject(RESPONSE) response: any) { this.response = response; } @@ -21,7 +23,7 @@ export class ServerResponseService { * @param message */ setStatus(code: number, message?: string): this { - if (this.response) { + if (this.canModifyResponse()) { this.response.statusCode = code; if (message) { this.response.statusMessage = message; @@ -73,8 +75,23 @@ export class ServerResponseService { * @param content */ setHeader(header: string, content: string) { - if (this.response) { + if (this.canModifyResponse()) { this.response.setHeader(header, content); } } + + private canModifyResponse(): boolean { + if (!this.response) { + return false; + } + if (this.response.headersSent) { + if (!this.warnedAboutCommittedResponse) { + console.warn('Server response already committed; skipping subsequent header/status updates.'); + this.warnedAboutCommittedResponse = true; + } + return false; + } + return true; + } + } diff --git a/src/app/menu.resolver.spec.ts b/src/app/menu.resolver.spec.ts index 12d5efa24e1..521853a1b8f 100644 --- a/src/app/menu.resolver.spec.ts +++ b/src/app/menu.resolver.spec.ts @@ -1,7 +1,7 @@ import { TestBed, waitForAsync } from '@angular/core/testing'; import { MenuResolver } from './menu.resolver'; -import { of as observableOf } from 'rxjs'; +import { BehaviorSubject, of as observableOf } from 'rxjs'; import { FeatureID } from './core/data/feature-authorization/feature-id'; import { TranslateModule } from '@ngx-translate/core'; import { NoopAnimationsModule } from '@angular/platform-browser/animations'; @@ -423,4 +423,19 @@ describe('MenuResolver', () => { }); }); }); + ['Import', 'Export'].forEach(action => { + it(`should not request protected ${action.toLowerCase()} scripts before administrator authorization`, () => { + const authorized$ = new BehaviorSubject(false); + authorizationService.isAuthorized.and.returnValue(authorized$); + scriptService.scriptWithNameExistsAndCanExecute.calls.reset(); + resolver[`create${action}MenuSections`](); + expect(scriptService.scriptWithNameExistsAndCanExecute).not.toHaveBeenCalled(); + authorized$.next(true); + expect(scriptService.scriptWithNameExistsAndCanExecute).toHaveBeenCalledTimes(1); + expect(menuService.addSection).toHaveBeenCalledWith(MenuID.ADMIN, jasmine.objectContaining({ + id: action.toLowerCase(), visible: true + })); + }); + }); + }); diff --git a/src/app/menu.resolver.ts b/src/app/menu.resolver.ts index 53d5669eb15..ca82f3503ff 100644 --- a/src/app/menu.resolver.ts +++ b/src/app/menu.resolver.ts @@ -12,7 +12,7 @@ import { RemoteData } from './core/data/remote-data'; import { TextMenuItemModel } from './shared/menu/menu-item/models/text.model'; import { BrowseService } from './core/browse/browse.service'; import { MenuService } from './shared/menu/menu.service'; -import { filter, find, map, mergeMap, take } from 'rxjs/operators'; +import { filter, find, map, mergeMap, switchMap, take } from 'rxjs/operators'; import { hasValue } from './shared/empty.util'; import { FeatureID } from './core/data/feature-authorization/feature-id'; import { @@ -479,11 +479,11 @@ export class MenuResolver implements Resolve { ]; menuList.forEach((menuSection) => this.menuService.addSection(MenuID.ADMIN, menuSection)); - observableCombineLatest([ - this.authorizationService.isAuthorized(FeatureID.AdministratorOf), - this.scriptDataService.scriptWithNameExistsAndCanExecute(METADATA_EXPORT_SCRIPT_NAME) - ]).pipe( - filter(([authorized, metadataExportScriptExists]: boolean[]) => authorized && metadataExportScriptExists), + this.authorizationService.isAuthorized(FeatureID.AdministratorOf).pipe( + switchMap((authorized: boolean) => authorized + ? this.scriptDataService.scriptWithNameExistsAndCanExecute(METADATA_EXPORT_SCRIPT_NAME) + : observableOf(false)), + filter((scriptExists: boolean) => scriptExists), take(1) ).subscribe(() => { // Hides the export menu for unauthorised people @@ -540,11 +540,11 @@ export class MenuResolver implements Resolve { const menuList = []; menuList.forEach((menuSection) => this.menuService.addSection(MenuID.ADMIN, menuSection)); - observableCombineLatest([ - this.authorizationService.isAuthorized(FeatureID.AdministratorOf), - this.scriptDataService.scriptWithNameExistsAndCanExecute(METADATA_IMPORT_SCRIPT_NAME) - ]).pipe( - filter(([authorized, metadataImportScriptExists]: boolean[]) => authorized && metadataImportScriptExists), + this.authorizationService.isAuthorized(FeatureID.AdministratorOf).pipe( + switchMap((authorized: boolean) => authorized + ? this.scriptDataService.scriptWithNameExistsAndCanExecute(METADATA_IMPORT_SCRIPT_NAME) + : observableOf(false)), + filter((scriptExists: boolean) => scriptExists), take(1) ).subscribe(() => { // Hides the import menu for unauthorised people diff --git a/src/backend/ssr-response-context.ts b/src/backend/ssr-response-context.ts new file mode 100644 index 00000000000..d30a19006ad --- /dev/null +++ b/src/backend/ssr-response-context.ts @@ -0,0 +1,21 @@ +import { ServerResponse } from 'node:http'; + +import type { + Request, + Response, +} from 'express'; + +/** + * Give a background render its own response, without a socket to the visitor. + * Express response methods still need their application prototype and a request. + * The request is a read-only metadata snapshot; its body, socket and event handlers + * belong to the original request and must not be consumed by background rendering. + */ +export function createSsrRefreshContext(req: Request, res: Response): { request: Request; response: Response } { + const request = Object.assign(Object.create(Object.getPrototypeOf(req)), req) as Request; + const response = new ServerResponse(request) as unknown as Response; + Object.setPrototypeOf(response, Object.getPrototypeOf(res)); + Object.assign(response, { locals: {}, req: request }); + request.res = response; + return { request, response }; +}