Skip to content
Merged
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
160 changes: 156 additions & 4 deletions src/app/static-page/static-page.component.spec.ts
Original file line number Diff line number Diff line change
@@ -1,15 +1,19 @@
import { TestBed } from '@angular/core/testing';
import { ComponentFixture, TestBed } from '@angular/core/testing';

import { StaticPageComponent } from './static-page.component';
import { HtmlContentService } from '../shared/html-content.service';
import { Router } from '@angular/router';
import { RouterMock } from '../shared/mocks/router.mock';
import { TranslateModule } from '@ngx-translate/core';
import { of } from 'rxjs';
import { Observable, of, throwError } from 'rxjs';
import { APP_CONFIG } from '../../config/app-config.interface';
import { environment } from '../../environments/environment';
import { ClarinSafeHtmlPipe } from '../shared/utils/clarin-safehtml.pipe';
import { ServerResponseService } from '../core/services/server-response.service';
import { ConfigurationDataService } from '../core/data/configuration-data.service';
import { ConfigurationProperty } from '../core/shared/configuration-property.model';
import { RemoteData } from '../core/data/remote-data';
import { createFailedRemoteDataObject$, createSuccessfulRemoteDataObject$ } from '../shared/remote-data.utils';

describe('StaticPageComponent', () => {
function createDeferred<T>() {
Expand All @@ -26,13 +30,22 @@ describe('StaticPageComponent', () => {
html: string | undefined,
restBase?: string,
contentPromise?: Promise<string | undefined>,
route: string = '/static/test-file.html'
route: string = '/static/test-file.html',
configProperties: { [name: string]: string[] } = {}
) {
const htmlContentService = jasmine.createSpyObj('htmlContentService', {
fetchHtmlContent: of(html),
getHmtlContentByPathAndLocale: contentPromise ?? Promise.resolve(html)
});

// Unknown properties fail with 404, like a property the backend doesn't expose
const configurationService = jasmine.createSpyObj('configurationService', ['findByPropertyName']);
configurationService.findByPropertyName.and.callFake((name: string): Observable<RemoteData<ConfigurationProperty>> =>
Object.prototype.hasOwnProperty.call(configProperties, name)
? createSuccessfulRemoteDataObject$(Object.assign(new ConfigurationProperty(), { name, values: configProperties[name] }))
: createFailedRemoteDataObject$('No such configuration property', 404)
);

const responseService = jasmine.createSpyObj('responseService', {
setNotFound: null
});
Expand Down Expand Up @@ -61,13 +74,14 @@ describe('StaticPageComponent', () => {
{ provide: HtmlContentService, useValue: htmlContentService },
{ provide: Router, useValue: router },
{ provide: ServerResponseService, useValue: responseService },
{ provide: ConfigurationDataService, useValue: configurationService },
{ provide: APP_CONFIG, useValue: appConfig }
]
}).compileComponents();

const fixture = TestBed.createComponent(StaticPageComponent);
const component = fixture.componentInstance;
return { fixture, component, htmlContentService, responseService };
return { fixture, component, htmlContentService, responseService, configurationService };
}

function createLinkEvent(href: string, useNestedTarget = false): Event {
Expand Down Expand Up @@ -167,6 +181,144 @@ describe('StaticPageComponent', () => {
expect(component.htmlContent.value).toBe(otherHtml);
});

describe('variable interpolation', () => {
const allPlaceholdersHtml = '<p>Welcome to ${dspace.name}, provided by ${description.institution}, ' +
'located at ${description.location}.</p><p>Laws of ${description.country}, court of ${description.city}.</p>';
const allProperties = {
'dspace.name': ['Test Repository'],
'description.institution': ['Test Institute'],
'description.location': ['Test Street 1', '100 00 Test City'],
'description.city': ['Test City'],
'description.country': ['Test Country'],
};

function setupInterpolationTest(html: string, configProperties: { [name: string]: string[] } = {}, restBase?: string) {
return setupTest(html, restBase, undefined, '/static/test-file.html', configProperties);
}

async function render(fixture: ComponentFixture<StaticPageComponent>) {
fixture.detectChanges();
await fixture.whenStable();
fixture.detectChanges();
}

let warnSpy: jasmine.Spy;

beforeEach(() => {
warnSpy = spyOn(console, 'warn');
});

it('should replace all placeholders with backend configuration properties', async () => {
const { fixture, component } = await setupInterpolationTest(allPlaceholdersHtml, allProperties);
await render(fixture);

expect(component.htmlContent.value).toBe('<p>Welcome to Test Repository, provided by Test Institute, ' +
'located at Test Street 1, 100 00 Test City.</p><p>Laws of Test Country, court of Test City.</p>');
expect(warnSpy).not.toHaveBeenCalled();
});

it('should join a value the backend split on commas', async () => {
// How the backend returns `dspace.name = A (B), C, D`
const { fixture, component } = await setupInterpolationTest('<p>${dspace.name}</p>', {
'dspace.name': ['LINDAT/CLARIAH-CZ digital library at the Institute of Formal and Applied Linguistics (ÚFAL)',
'Faculty of Mathematics and Physics', 'Charles University'],
});
await render(fixture);

expect(component.htmlContent.value).toBe('<p>LINDAT/CLARIAH-CZ digital library at the Institute of Formal and Applied ' +
'Linguistics (ÚFAL), Faculty of Mathematics and Physics, Charles University</p>');
});

it('should request each property once', async () => {
const { fixture, configurationService } = await setupInterpolationTest('<p>${dspace.name} ${dspace.name} ${description.city}</p>', allProperties);
await render(fixture);

expect(configurationService.findByPropertyName).toHaveBeenCalledTimes(2);
expect(configurationService.findByPropertyName).toHaveBeenCalledWith('dspace.name');
expect(configurationService.findByPropertyName).toHaveBeenCalledWith('description.city');
});

it('should not request any property when the page has no placeholders', async () => {
const html = '<p>No placeholders here</p>';
const { fixture, component, configurationService } = await setupInterpolationTest(html, allProperties);
await render(fixture);

expect(component.htmlContent.value).toBe(html);
expect(configurationService.findByPropertyName).not.toHaveBeenCalled();
expect(warnSpy).not.toHaveBeenCalled();
});

it('should leave an unknown or unexposed placeholder literal and warn once', async () => {
const { fixture, component } = await setupInterpolationTest('<p>${dspace.name} ${foo.bar}</p>', allProperties);
await render(fixture);

expect(component.htmlContent.value).toBe('<p>Test Repository ${foo.bar}</p>');
expect(warnSpy).toHaveBeenCalledOnceWith('Static page: unresolved variables', ['foo.bar']);
});

it('should treat an empty value as missing', async () => {
const { fixture, component } = await setupInterpolationTest('<p>${dspace.name} ${description.city}</p>',
{ 'dspace.name': [''], 'description.city': [] });
await render(fixture);

expect(component.htmlContent.value).toBe('<p>${dspace.name} ${description.city}</p>');
expect(warnSpy).toHaveBeenCalledOnceWith('Static page: unresolved variables', ['dspace.name', 'description.city']);
});

it('should still show the page when a property request errors', async () => {
const { fixture, component, configurationService, responseService } = await setupInterpolationTest('<p>${dspace.name}</p>');
configurationService.findByPropertyName.and.returnValue(throwError(() => new Error('backend down')));
await render(fixture);

expect(component.contentState).toBe('found');
expect(component.htmlContent.value).toBe('<p>${dspace.name}</p>');
expect(responseService.setNotFound).not.toHaveBeenCalled();
expect(warnSpy).toHaveBeenCalledOnceWith('Static page: unresolved variables', ['dspace.name']);
});

it('should HTML-escape values', async () => {
const { fixture, component } = await setupInterpolationTest('<p id="target">${dspace.name}</p>', { 'dspace.name': ['A & <b>B</b>'] });
await render(fixture);

expect(component.htmlContent.value).toBe('<p id="target">A &amp; &lt;b&gt;B&lt;/b&gt;</p>');
const target = fixture.nativeElement.querySelector('#target');
expect(target.querySelector('b')).toBeNull();
expect(target.textContent).toBe('A & <b>B</b>');
});

it('should insert values containing replacement patterns literally', async () => {
const { fixture, component } = await setupInterpolationTest(
'<p id="target">${dspace.name}|${description.city}</p>',
{ 'dspace.name': ['a$&b'], 'description.city': ['c$1$`$\'d'] }
);
await render(fixture);

expect(fixture.nativeElement.querySelector('#target').textContent).toBe('a$&b|c$1$`$\'d');
expect(component.htmlContent.value).not.toContain('${');
});

it('should not touch other placeholder syntaxes', async () => {
const html = '<p>$dspace.name {{\'x\' | translate}} $ {dspace.name}</p>';
const { fixture, component, configurationService } = await setupInterpolationTest(html, allProperties);
await render(fixture);

expect(component.htmlContent.value).toBe(html);
expect(configurationService.findByPropertyName).not.toHaveBeenCalled();
});

it('should apply both the OAI link rewrite and variable interpolation', async () => {
const { fixture, component } = await setupInterpolationTest(
'<a href="/server/oai/request?verb=Identify">${dspace.name}</a>',
allProperties,
'https://api.example.org/repository/server'
);
await render(fixture);

expect(component.htmlContent.value)
.toBe('<a href="https://api.example.org/repository/server/oai/request?verb=Identify">Test Repository</a>');
});
});

describe('contentState behavior', () => {
it('should initialize contentState to "loading"', async () => {
const { component } = await setupTest('<div>test</div>');
Expand Down
49 changes: 48 additions & 1 deletion src/app/static-page/static-page.component.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,14 @@
import { ChangeDetectorRef, Component, Inject, OnInit } from '@angular/core';
import { HtmlContentService } from '../shared/html-content.service';
import { BehaviorSubject } from 'rxjs';
import { BehaviorSubject, firstValueFrom } from 'rxjs';
import { Router } from '@angular/router';
import { isEmpty } from '../shared/empty.util';
import { STATIC_PAGE_PATH } from './static-page-routing-paths';
import { APP_CONFIG, AppConfig } from '../../config/app-config.interface';
import { ServerResponseService } from '../core/services/server-response.service';
import { ConfigurationDataService } from '../core/data/configuration-data.service';
import { getFirstCompletedRemoteData } from '../core/shared/operators';
import escapeHtml from 'lodash/escape';

/**
* Component which load and show static files from the `static-files` folder.
Expand All @@ -25,6 +28,7 @@ export class StaticPageComponent implements OnInit {
private router: Router,
private responseService: ServerResponseService,
private changeDetector: ChangeDetectorRef,
private configurationService: ConfigurationDataService,
@Inject(APP_CONFIG) protected appConfig?: AppConfig) { }

async ngOnInit(): Promise<void> {
Expand All @@ -40,6 +44,7 @@ export class StaticPageComponent implements OnInit {
const restBase = this.appConfig?.rest?.baseUrl;
const oaiUrl = restBase ? restBase.replace(/\/+$/, '') + '/oai' : '/server/oai';
htmlContent = htmlContent.replace(/href="\/server\/oai/gi, 'href="' + oaiUrl);
htmlContent = await this.interpolateVariables(htmlContent);

this.htmlContent.next(htmlContent);
this.contentState = 'found';
Expand Down Expand Up @@ -85,6 +90,48 @@ export class StaticPageComponent implements OnInit {
this.redirectToRelativeLink(staticPageBaseUrl, href);
}

/**
* Replace `${key}` placeholders with the value of the backend configuration property `key`, e.g. `${dspace.name}`.
* The property must be listed in `rest.properties.exposed` on the backend.
* Values are HTML-escaped. A property that is not exposed, not set, empty, or fails to load leaves the placeholder unchanged.
* @param html static page content
* @private
*/
private async interpolateVariables(html: string): Promise<string> {
const keys = [...new Set((html.match(/\$\{[\w.-]+\}/g) ?? []).map((placeholder) => placeholder.slice(2, -1)))];
if (keys.length === 0) {
return html;
}
const loaded = await Promise.all(keys.map((key) => this.getConfigValue(key)));
const values = new Map(keys.map((key, i) => [key, loaded[i]]));
const missing = keys.filter((key) => values.get(key) === undefined);
if (missing.length > 0) {
console.warn('Static page: unresolved variables', missing);
}
// Function replacer: `$&`, `$'` etc. in values are inserted literally, not as replacement patterns.
return html.replace(/\$\{([\w.-]+)\}/g, (match: string, key: string) => {
const value = values.get(key);
return value === undefined ? match : escapeHtml(value);
});
}

/**
* Load a configuration property from the backend.
* @param key property name
* @returns the property value, or `undefined` if it is missing, empty, or fails to load
* @private
*/
private async getConfigValue(key: string): Promise<string | undefined> {
try {
const response = await firstValueFrom(this.configurationService.findByPropertyName(key).pipe(getFirstCompletedRemoteData()));
// The backend splits a value on commas into several values; join them back.
const value = response.hasSucceeded ? response.payload?.values?.join(', ').trim() : undefined;
return isEmpty(value) ? undefined : value;
} catch (error) {
return undefined;
}
}

private getNamespacePrefix(): string {
const nameSpace = this.appConfig?.ui?.nameSpace ?? '/';
return nameSpace === '/' ? '' : nameSpace.replace(/\/$/, '');
Expand Down
4 changes: 2 additions & 2 deletions src/static-files/terms-of-service.html
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ <h2 id="ufal-point-faq">CLARIN Terms of Service (v1.0)</h2>

<h3>Preamble</h3>

<p>Welcome to ${dspace.name}. This repository service is provided to you by ${lr.description.institution}, located at ${lr.description.location}, hereinafter referred to as CLARIN Centre. The mission of CLARIN is to provide as wide access as possible to language research materials and tools around Europe. To archive this goal, we set some ground rules in this document. By accessing or using, and in consideration of the CLARIN Services provided to you, you agree to abide by the Terms of Use below, which can be updated or modified according to article 9.</p>
<p>Welcome to ${dspace.name}. This repository service is provided to you by ${description.institution}, located at ${description.location}, hereinafter referred to as CLARIN Centre. The mission of CLARIN is to provide as wide access as possible to language research materials and tools around Europe. To archive this goal, we set some ground rules in this document. By accessing or using, and in consideration of the CLARIN Services provided to you, you agree to abide by the Terms of Use below, which can be updated or modified according to article 9.</p>

<h3>1. Governing Terms</h3>

Expand Down Expand Up @@ -134,7 +134,7 @@ <h3>5. Availability of Services</h3>
<h3>6. Governing Law and Entire Agreement</h3>

<p>
These Terms are governed by the laws of ${lr.description.country} without regard to the rules of conflict of law that may cause the laws of another jurisdiction to apply. The User agrees to the sole and exclusive jurisdiction and venue of the ${lr.description.city} District Court of Law in the event of any dispute of any kind arising from or relating to the CLARIN Services, or the User’s use or review of it. However, CLARIN has the right to use the laws of another jurisdiction to get injunctive measures against the misuse of the CLARIN Service.
These Terms are governed by the laws of ${description.country} without regard to the rules of conflict of law that may cause the laws of another jurisdiction to apply. The User agrees to the sole and exclusive jurisdiction and venue of the ${description.city} District Court of Law in the event of any dispute of any kind arising from or relating to the CLARIN Services, or the User’s use or review of it. However, CLARIN has the right to use the laws of another jurisdiction to get injunctive measures against the misuse of the CLARIN Service.
</p>

<p>
Expand Down
Loading