diff --git a/src/app/static-page/static-page.component.spec.ts b/src/app/static-page/static-page.component.spec.ts index f62bf4a1756..7feafe91c75 100644 --- a/src/app/static-page/static-page.component.spec.ts +++ b/src/app/static-page/static-page.component.spec.ts @@ -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() { @@ -26,13 +30,22 @@ describe('StaticPageComponent', () => { html: string | undefined, restBase?: string, contentPromise?: Promise, - 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> => + 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 }); @@ -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 { @@ -167,6 +181,144 @@ describe('StaticPageComponent', () => { expect(component.htmlContent.value).toBe(otherHtml); }); + describe('variable interpolation', () => { + const allPlaceholdersHtml = '

Welcome to ${dspace.name}, provided by ${description.institution}, ' + + 'located at ${description.location}.

Laws of ${description.country}, court of ${description.city}.

'; + 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) { + 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('

Welcome to Test Repository, provided by Test Institute, ' + + 'located at Test Street 1, 100 00 Test City.

Laws of Test Country, court of Test City.

'); + 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('

${dspace.name}

', { + '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('

LINDAT/CLARIAH-CZ digital library at the Institute of Formal and Applied ' + + 'Linguistics (ÚFAL), Faculty of Mathematics and Physics, Charles University

'); + }); + + it('should request each property once', async () => { + const { fixture, configurationService } = await setupInterpolationTest('

${dspace.name} ${dspace.name} ${description.city}

', 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 = '

No placeholders here

'; + 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('

${dspace.name} ${foo.bar}

', allProperties); + await render(fixture); + + expect(component.htmlContent.value).toBe('

Test Repository ${foo.bar}

'); + expect(warnSpy).toHaveBeenCalledOnceWith('Static page: unresolved variables', ['foo.bar']); + }); + + it('should treat an empty value as missing', async () => { + const { fixture, component } = await setupInterpolationTest('

${dspace.name} ${description.city}

', + { 'dspace.name': [''], 'description.city': [] }); + await render(fixture); + + expect(component.htmlContent.value).toBe('

${dspace.name} ${description.city}

'); + 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('

${dspace.name}

'); + configurationService.findByPropertyName.and.returnValue(throwError(() => new Error('backend down'))); + await render(fixture); + + expect(component.contentState).toBe('found'); + expect(component.htmlContent.value).toBe('

${dspace.name}

'); + 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('

${dspace.name}

', { 'dspace.name': ['A & B'] }); + await render(fixture); + + expect(component.htmlContent.value).toBe('

A & <b>B</b>

'); + const target = fixture.nativeElement.querySelector('#target'); + expect(target.querySelector('b')).toBeNull(); + expect(target.textContent).toBe('A & B'); + }); + + it('should insert values containing replacement patterns literally', async () => { + const { fixture, component } = await setupInterpolationTest( + '

${dspace.name}|${description.city}

', + { '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 = '

$dspace.name {{\'x\' | translate}} $ {dspace.name}

'; + 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( + '${dspace.name}', + allProperties, + 'https://api.example.org/repository/server' + ); + await render(fixture); + + expect(component.htmlContent.value) + .toBe('Test Repository'); + }); + }); + describe('contentState behavior', () => { it('should initialize contentState to "loading"', async () => { const { component } = await setupTest('
test
'); diff --git a/src/app/static-page/static-page.component.ts b/src/app/static-page/static-page.component.ts index 6ca77bf955c..d0e10e19104 100644 --- a/src/app/static-page/static-page.component.ts +++ b/src/app/static-page/static-page.component.ts @@ -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. @@ -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 { @@ -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'; @@ -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 { + 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 { + 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(/\/$/, ''); diff --git a/src/static-files/terms-of-service.html b/src/static-files/terms-of-service.html index dd699238b15..47db90066c1 100644 --- a/src/static-files/terms-of-service.html +++ b/src/static-files/terms-of-service.html @@ -7,7 +7,7 @@

CLARIN Terms of Service (v1.0)

Preamble

-

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.

+

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.

1. Governing Terms

@@ -134,7 +134,7 @@

5. Availability of Services

6. Governing Law and Entire Agreement

- 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.