Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions .github/workflows/build.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down
324 changes: 324 additions & 0 deletions scripts/test-ssr-response-lifecycle.js

Large diffs are not rendered by default.

12 changes: 11 additions & 1 deletion server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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';

Expand Down Expand Up @@ -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) {
Expand Down Expand Up @@ -450,7 +459,8 @@ function checkCacheForRequest(cacheName: string, cache: LRU<string, any>, 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.`); }
Expand Down
Original file line number Diff line number Diff line change
@@ -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';
Expand Down Expand Up @@ -189,4 +189,110 @@ describe('BitstreamDownloadPageComponent', () => {
});
});
});
describe('when signposting responds after download authorization', () => {
let links$: Subject<any[]>;

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<boolean>;
let links$: Subject<any[]>;

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();
});
});

});
Original file line number Diff line number Diff line change
@@ -1,13 +1,13 @@
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';
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';
Expand All @@ -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<Bitstream>;
bitstreamRD$: Observable<RemoteData<Bitstream>>;

private readonly destroy$ = new Subject<void>();

constructor(
private route: ActivatedRoute,
protected router: Router,
Expand All @@ -45,7 +47,6 @@ export class BitstreamDownloadPageComponent implements OnInit {
private responseService: ServerResponseService,
@Inject(PLATFORM_ID) protected platformId: string
) {
this.initPageLinks();
}

back(): void {
Expand All @@ -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();
Expand All @@ -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);
Expand All @@ -101,22 +109,31 @@ export class BitstreamDownloadPageComponent implements OnInit {
*
* @private
*/
private initPageLinks(): void {
if (!environment.signpostingEnabled) {
return;
private initPageLinks(): Observable<void> {
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();
}
}
36 changes: 36 additions & 0 deletions src/app/core/services/server-response.service.spec.ts
Original file line number Diff line number Diff line change
@@ -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', '<https://example.org>');
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', '<https://example.org>');
service.setStatus(404, 'Not Found');
expect(response.setHeader).toHaveBeenCalledWith('Link', '<https://example.org>');
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', '<https://example.org>')).not.toThrow();
expect(service.setStatus(200)).toBe(service);
});
});
21 changes: 19 additions & 2 deletions src/app/core/services/server-response.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}
Expand All @@ -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;
Expand Down Expand Up @@ -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;
}

}
17 changes: 16 additions & 1 deletion src/app/menu.resolver.spec.ts
Original file line number Diff line number Diff line change
@@ -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';
Expand Down Expand Up @@ -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
}));
});
});

});
Loading
Loading