diff --git a/angular.json b/angular.json index 47d1ed346a1..e8e320ab930 100644 --- a/angular.json +++ b/angular.json @@ -45,7 +45,10 @@ { "glob": "**/*", "input": "src/aai", - "output": "/aai" + "output": "/aai", + "ignore": [ + "**/*.spec.ts" + ] } ], "styles": [ diff --git a/src/aai/aai.js b/src/aai/aai.js index 72a3650c813..12653c1e1dd 100644 --- a/src/aai/aai.js +++ b/src/aai/aai.js @@ -32,7 +32,6 @@ var targetUrl = ''; var opts = jQuery.extend({}, this.defaults, options), defaultCallback = function(e) { - targetUrl = opts.target + '?redirectUrl='; // E.g. Redirect to Item page var redirectUrl = window.location.href; @@ -49,15 +48,10 @@ if (redirectUrlFromLogin != null && redirectUrlFromLogin !== '') { // Redirect from the login page with retrieved redirect URL - var baseUrl = window.location.origin + formatNamespace(namespace); - var redirectPath = ensureLeadingSlash(redirectUrlFromLogin); - - redirectUrl = baseUrl + redirectPath; + redirectUrl = shibbolethReturnUrl(redirectUrlFromLogin); } - // Encode the redirect URL - targetUrl += window.encodeURIComponent(redirectUrl); - window.location = opts.host + opts.port + '/Shibboleth.sso/Login?SAMLDS=1&target=' + targetUrl + '&entityID=' + window.encodeURIComponent(e.entityID); + window.location = shibbolethLoginUrl(opts, redirectUrl, e.entityID); }; //console.log(opts); if(!opts.target){ @@ -111,7 +105,7 @@ // jQuery('input#login').focus(); // Use cookie to toggle discojuice popup. setCookie('SHOW_DISCOJUICE_POPUP', false, 1) - window.location = window.location.origin + (namespace === '' ? namespace : '/' + namespace) + "/login?redirectUrl=" + window.location.href; + window.location = localLoginUrl(window.location.href); break; //case 'saml': default: @@ -135,6 +129,39 @@ } //if jQuery(selector) }; + // Exposed for tests. + this.localLoginUrl = localLoginUrl; + this.shibbolethReturnUrl = shibbolethReturnUrl; + this.shibbolethLoginUrl = shibbolethLoginUrl; + + /** + * Login page URL that returns to `pageUrl` after a local login. Encoded, so the query string of `pageUrl` stays in it. + */ + function localLoginUrl(pageUrl) { + return window.location.origin + formatNamespace(namespace) + '/login?redirectUrl=' + window.encodeURIComponent(pageUrl); + } + + /** + * Page to return to after a Shibboleth login, from the `redirectUrl` of the login page. + * A URL of this site (local login puts one there) is kept as it is, anything else is taken as a path in the app. + */ + function shibbolethReturnUrl(redirectUrlFromLogin) { + if (redirectUrlFromLogin.startsWith(window.location.origin + '/')) { + return redirectUrlFromLogin; + } + return window.location.origin + formatNamespace(namespace) + ensureLeadingSlash(redirectUrlFromLogin); + } + + /** + * Shibboleth login URL whose `target` (the backend) returns to `redirectUrl`. + * `redirectUrl` is encoded inside `target` and then `target` as a whole, so the query string of `redirectUrl` reaches the backend. + */ + function shibbolethLoginUrl(opts, redirectUrl, entityID) { + var target = opts.target + '?redirectUrl=' + window.encodeURIComponent(redirectUrl); + return opts.host + opts.port + '/Shibboleth.sso/Login?SAMLDS=1&target=' + window.encodeURIComponent(target) + + '&entityID=' + window.encodeURIComponent(entityID); + } + // Set a cookie function setCookie(name, value, daysToExpire) { var expirationDate = new Date(); diff --git a/src/aai/aai.spec.ts b/src/aai/aai.spec.ts new file mode 100644 index 00000000000..2e69c84cd7c --- /dev/null +++ b/src/aai/aai.spec.ts @@ -0,0 +1,59 @@ +import './aai.js'; + +import { DefaultUrlSerializer } from '@angular/router'; + +describe('aai.js', () => { + const aai = (window as any).aai; + + describe('localLoginUrl', () => { + const redirectUrlOf = (loginUrl: string): string => { + const url = new URL(loginUrl); + return new DefaultUrlSerializer().parse(url.pathname + url.search).queryParams.redirectUrl; + }; + + it('keeps the query string of the page the user came from', () => { + const page = 'http://localhost:4000/search?query=test&page=2'; + + expect(redirectUrlOf(aai.localLoginUrl(page))).toBe(page); + }); + + it('keeps the page stored by the auth guard when local login starts on the login page', () => { + const page = 'http://localhost:4000/login?redirectUrl=%2Fmydspace%3Fconfiguration%3Dworkflow'; + + expect(redirectUrlOf(aai.localLoginUrl(page))).toBe(page); + }); + }); + + describe('shibbolethReturnUrl', () => { + it('keeps a URL of this site, as local login puts it into the login URL', () => { + const page = window.location.origin + '/items/1?query=test'; + + expect(aai.shibbolethReturnUrl(page)).toBe(page); + }); + + it('turns a path into a URL of this site', () => { + // The karma page has , so no namespace goes in front of the path. + expect(aai.shibbolethReturnUrl('/mydspace')).toBe(window.location.origin + '/mydspace'); + }); + + it('keeps the return on this site when the URL is of another site', () => { + expect(aai.shibbolethReturnUrl('https://example.org/items/1').startsWith(window.location.origin + '/')).toBeTrue(); + }); + }); + + describe('shibbolethLoginUrl', () => { + const opts = { host: 'https://ui.example', port: '', target: 'https://ui.example/server/api/authn/shibboleth' }; + + it('gives the backend the whole redirectUrl, with its own query string', () => { + const page = 'https://ui.example/search?query=corpus&page=2'; + + const loginUrl = new URL(aai.shibbolethLoginUrl(opts, page, 'https://idp.example/idp')); + // The SP decodes `target` once and sends the user there; the backend then reads `redirectUrl` from it. + const target = new URL(loginUrl.searchParams.get('target')); + + expect(target.origin + target.pathname).toBe(opts.target); + expect(target.searchParams.get('redirectUrl')).toBe(page); + expect(loginUrl.searchParams.get('entityID')).toBe('https://idp.example/idp'); + }); + }); +}); diff --git a/src/app/core/auth/auth.service.spec.ts b/src/app/core/auth/auth.service.spec.ts index 1d17f17bade..158f7e77fd0 100644 --- a/src/app/core/auth/auth.service.spec.ts +++ b/src/app/core/auth/auth.service.spec.ts @@ -426,6 +426,16 @@ describe('AuthService test', () => { expect(hardRedirectService.redirect).toHaveBeenCalledWith(jasmine.stringMatching(new RegExp('reload/[0-9]*(?!\\?)$'))); }); + it('should send an expired session to the login page under the base href', () => { + const browserLocation = { href: '' }; + (authService as any)._window = { nativeWindow: { location: browserLocation } }; + + authService.redirectToLoginWhenTokenExpired(); + + // The browser resolves the new href against , e.g. /repository/ + expect(new URL(browserLocation.href, 'http://localhost:4000/repository/').href).toBe('http://localhost:4000/repository/login?expired=true'); + }); + describe('impersonate', () => { const userId = 'testUserId'; diff --git a/src/app/core/auth/auth.service.ts b/src/app/core/auth/auth.service.ts index 4a155920865..f812dec50ea 100644 --- a/src/app/core/auth/auth.service.ts +++ b/src/app/core/auth/auth.service.ts @@ -527,7 +527,8 @@ export class AuthService { const redirectUrl = LOGIN_ROUTE + '?expired=true'; if (this._window.nativeWindow.location) { // Hard redirect to login page, so that all state is definitely lost - this._window.nativeWindow.location.href = redirectUrl; + // Relative to , like the `reload/` URL in navigateToRedirectUrl. + this._window.nativeWindow.location.href = '.' + redirectUrl; } else { this.router.navigateByUrl(redirectUrl); } diff --git a/src/app/core/auth/server-auth.service.spec.ts b/src/app/core/auth/server-auth.service.spec.ts new file mode 100644 index 00000000000..578836f32f2 --- /dev/null +++ b/src/app/core/auth/server-auth.service.spec.ts @@ -0,0 +1,28 @@ +import { of } from 'rxjs'; + +import { AppConfig } from '../../../config/app-config.interface'; +import { ServerAuthService } from './server-auth.service'; + +describe('ServerAuthService', () => { + let response: { redirect: jasmine.Spy }; + + const createService = (nameSpace: string): ServerAuthService => { + response = { redirect: jasmine.createSpy('redirect') }; + const appConfig = { ui: { nameSpace } } as AppConfig; + // On the server there is no browser location, so the expired-session redirect is a 302. + const nativeWindowRef = { nativeWindow: {} } as any; + return new ServerAuthService({}, response, nativeWindowRef, null, null, null, null, null, of({}) as any, null, null, null, appConfig); + }; + + it('should send an expired session to the login page under the UI namespace', () => { + createService('/repository').redirectToLoginWhenTokenExpired(); + + expect(response.redirect).toHaveBeenCalledWith(302, '/repository/login?expired=true'); + }); + + it('should send an expired session to /login when the UI runs at the root', () => { + createService('/').redirectToLoginWhenTokenExpired(); + + expect(response.redirect).toHaveBeenCalledWith(302, '/login?expired=true'); + }); +}); diff --git a/src/app/core/auth/server-auth.service.ts b/src/app/core/auth/server-auth.service.ts index d287604c24d..68c6ed874f8 100644 --- a/src/app/core/auth/server-auth.service.ts +++ b/src/app/core/auth/server-auth.service.ts @@ -10,6 +10,10 @@ import { TranslateService } from '@ngx-translate/core'; import { Observable } from 'rxjs'; import { map } from 'rxjs/operators'; +import { + APP_CONFIG, + AppConfig, +} from '../../../config/app-config.interface'; import { REQUEST, RESPONSE, @@ -57,6 +61,7 @@ export class ServerAuthService extends AuthService { protected hardRedirectService: HardRedirectService, protected notificationService: NotificationsService, protected translateService: TranslateService, + @Inject(APP_CONFIG) protected appConfig: AppConfig, ) { super( _window, @@ -123,7 +128,8 @@ export class ServerAuthService extends AuthService { this._window.nativeWindow.location.href = redirectUrl; } else if (this.response) { if (!this.response._headerSent) { - this.response.redirect(302, redirectUrl); + // The browser resolves a 302 Location against the request path, not , so add the UI namespace. + this.response.redirect(302, this.appConfig.ui.nameSpace.replace(/\/$/, '') + redirectUrl); } } else { this.router.navigateByUrl(redirectUrl); diff --git a/src/app/login-page/login-page.component.spec.ts b/src/app/login-page/login-page.component.spec.ts index 50008a2f28f..fcab1189722 100644 --- a/src/app/login-page/login-page.component.spec.ts +++ b/src/app/login-page/login-page.component.spec.ts @@ -4,7 +4,11 @@ import { TestBed, waitForAsync, } from '@angular/core/testing'; -import { ActivatedRoute } from '@angular/router'; +import { + ActivatedRoute, + Params, + Router, +} from '@angular/router'; import { Store } from '@ngrx/store'; import { provideMockStore } from '@ngrx/store/testing'; import { TranslateModule } from '@ngx-translate/core'; @@ -16,12 +20,14 @@ import { XSRFService } from '../core/xsrf/xsrf.service'; import { AuthServiceMock } from '../shared/mocks/auth.service.mock'; import { ActivatedRouteStub } from '../shared/testing/active-router.stub'; import { EPersonMock } from '../shared/testing/eperson.mock'; +import { RouterStub } from '../shared/testing/router.stub'; import { LoginPageComponent } from './login-page.component'; describe('LoginPageComponent', () => { let comp: LoginPageComponent; let fixture: ComponentFixture; let authService: any; + let router: RouterStub; const mockUser = EPersonMock; const activatedRouteStub = Object.assign(new ActivatedRouteStub(), { @@ -39,7 +45,9 @@ describe('LoginPageComponent', () => { authService = Object.assign(new AuthServiceMock(), { isAuthenticated: jasmine.createSpy('isAuthenticated').and.returnValue(of(false)), getAuthenticatedUserFromStore: jasmine.createSpy('getAuthenticatedUserFromStore').and.returnValue(of(mockUser)), + getRedirectUrl: jasmine.createSpy('getRedirectUrl').and.returnValue(of(undefined)), }); + router = new RouterStub(); TestBed.configureTestingModule({ imports: [ @@ -49,9 +57,10 @@ describe('LoginPageComponent', () => { providers: [ { provide: ActivatedRoute, useValue: activatedRouteStub }, { provide: AuthService, useValue: authService }, + { provide: Router, useValue: router }, { provide: XSRFService, useValue: {} }, { provide: APP_DATA_SERVICES_MAP, useValue: {} }, - provideMockStore({}), + provideMockStore({ initialState: { core: { auth: { authenticated: false } } } }), ], schemas: [NO_ERRORS_SCHEMA], }).compileComponents(); @@ -95,4 +104,48 @@ describe('LoginPageComponent', () => { expect(comp.authenticatedUser).toBeNull(); }); }); + + // aai.js (DiscoJuice) takes the post-login target only from the `redirectUrl` query param of the page. + describe('redirectUrl query param', () => { + const initWith = (storedRedirectUrl: string, queryParams: Params = {}) => { + authService.getRedirectUrl.and.returnValue(of(storedRedirectUrl)); + (comp as any).route = { queryParams: of(queryParams), snapshot: { queryParams } }; + comp.ngOnInit(); + }; + + it('puts the page stored by the auth guard into the login URL', () => { + initWith('/mydspace'); + + expect(router.navigate).toHaveBeenCalledWith(['/login'], { + queryParams: { redirectUrl: '/mydspace' }, + queryParamsHandling: 'merge', + replaceUrl: true, + }); + }); + + it('keeps a redirectUrl that is already in the URL', () => { + initWith('/mydspace', { redirectUrl: 'http://localhost:4000/login?redirectUrl=/mydspace' }); + + expect(router.navigate).not.toHaveBeenCalled(); + }); + + it('keeps a stored URL with an access token out of the login URL', () => { + initWith('/bitstreams/123/download?accessToken=abc'); + + expect(router.navigate).not.toHaveBeenCalled(); + }); + + it('leaves the URL alone when no page is stored', () => { + initWith(undefined); + + expect(router.navigate).not.toHaveBeenCalled(); + }); + + it('does not navigate on the server', () => { + (comp as any).platformId = 'server'; + initWith('/mydspace'); + + expect(router.navigate).not.toHaveBeenCalled(); + }); + }); }); diff --git a/src/app/login-page/login-page.component.ts b/src/app/login-page/login-page.component.ts index 5868fe61b9f..d693159860b 100644 --- a/src/app/login-page/login-page.component.ts +++ b/src/app/login-page/login-page.component.ts @@ -1,10 +1,14 @@ +import { isPlatformBrowser } from '@angular/common'; import { Component, + Inject, OnDestroy, OnInit, + PLATFORM_ID, } from '@angular/core'; import { ActivatedRoute, + Router, RouterLink, } from '@angular/router'; import { Store } from '@ngrx/store'; @@ -27,7 +31,10 @@ import { AuthenticationSuccessAction, ResetAuthenticationMessagesAction, } from '../core/auth/auth.actions'; -import { AuthService } from '../core/auth/auth.service'; +import { + AuthService, + LOGIN_ROUTE, +} from '../core/auth/auth.service'; import { AuthTokenInfo } from '../core/auth/models/auth-token-info.model'; import { isAuthenticated } from '../core/auth/selectors'; import { EPerson } from '../core/eperson/models/eperson.model'; @@ -66,18 +73,25 @@ export class LoginPageComponent implements OnDestroy, OnInit { * Initialize instance variables * * @param {ActivatedRoute} route + * @param {Router} router * @param {Store} store * @param {AuthService} authService + * @param {object} platformId */ constructor(private route: ActivatedRoute, + private router: Router, private store: Store, - private authService: AuthService) {} + private authService: AuthService, + @Inject(PLATFORM_ID) private platformId: object) {} /** * Initialize instance variables */ ngOnInit() { this.initializeTheAuthenticationState(); + if (isPlatformBrowser(this.platformId)) { + this.showRedirectUrlInQueryParams(); + } const queryParamsObs = this.route.queryParams; const authenticated = this.store.select(isAuthenticated); @@ -103,6 +117,27 @@ export class LoginPageComponent implements OnDestroy, OnInit { })); } + /** + * Puts the stored post-login target (e.g. set by the auth guard) into the `redirectUrl` query param. + * The DiscoJuice scripts (aai.js) read it only from the URL: local login reloads the page, Shibboleth leaves the app. + * A URL with a request-a-copy `accessToken` stays only in the store, where the password login still reads it. + */ + private showRedirectUrlInQueryParams() { + if (isNotEmpty(this.route.snapshot.queryParams?.redirectUrl)) { + return; + } + this.subs.push(this.authService.getRedirectUrl().pipe(take(1)).subscribe((redirectUrl: string) => { + const hasAccessToken = new URLSearchParams(redirectUrl?.split('?')[1] ?? '').has('accessToken'); + if (isNotEmpty(redirectUrl) && !hasAccessToken) { + void this.router.navigate([LOGIN_ROUTE], { + queryParams: { redirectUrl }, + queryParamsHandling: 'merge', + replaceUrl: true, + }); + } + })); + } + /** * Resolves the authenticated user from the store, or null when nobody is logged in. */ diff --git a/src/app/shared/log-in/methods/password/log-in-password.component.spec.ts b/src/app/shared/log-in/methods/password/log-in-password.component.spec.ts index 55c9e3c75b2..c2d473e9a48 100644 --- a/src/app/shared/log-in/methods/password/log-in-password.component.spec.ts +++ b/src/app/shared/log-in/methods/password/log-in-password.component.spec.ts @@ -1,3 +1,4 @@ +import { APP_BASE_HREF } from '@angular/common'; import { CUSTOM_ELEMENTS_SCHEMA, PLATFORM_ID, @@ -107,6 +108,8 @@ describe('LogInPasswordComponent', () => { { provide: NotificationsService, useClass: NotificationsServiceStub }, { provide: ActivatedRoute, useValue: new ActivatedRouteStub() }, { provide: ThemeService, useValue: themeService }, + // The UI can run under a sub-path, e.g. /repository/ + { provide: APP_BASE_HREF, useValue: '/repository/' }, provideMockStore({ initialState }), ], schemas: [ @@ -204,12 +207,12 @@ describe('LogInPasswordComponent', () => { component.form.controls.password.setValue('password'); }); - it('redirects back to the redirectUrl page, reduced to an app-relative path', () => { + it('redirects back to the redirectUrl page, reduced to a router path', () => { setQueryParams({ redirectUrl: 'http://dev-6.pc:8603/repository/search' }); component.submit(); - expect(setRedirectUrlSpy).toHaveBeenCalledWith('/repository/search'); + expect(setRedirectUrlSpy).toHaveBeenCalledWith('/search'); expect(setRedirectUrlIfNotSetSpy).not.toHaveBeenCalled(); }); @@ -218,7 +221,7 @@ describe('LogInPasswordComponent', () => { component.submit(); - expect(setRedirectUrlSpy).toHaveBeenCalledWith('/repository/search?query=test'); + expect(setRedirectUrlSpy).toHaveBeenCalledWith('/search?query=test'); }); it('prefers a nested redirectUrl so the login page is not the redirect target', () => { @@ -228,15 +231,47 @@ describe('LogInPasswordComponent', () => { component.submit(); - expect(setRedirectUrlSpy).toHaveBeenCalledWith('/repository/items/1'); + expect(setRedirectUrlSpy).toHaveBeenCalledWith('/items/1'); + }); + + it('returns to the page the auth guard put into the login URL, after the DiscoJuice local-login reload', () => { + setQueryParams({ redirectUrl: 'http://localhost:4000/repository/login?redirectUrl=/mydspace' }); + + component.submit(); + + expect(setRedirectUrlSpy).toHaveBeenCalledWith('/mydspace'); + }); + + it('keeps the query string of the page the auth guard stored, when aai.js encodes the login URL', () => { + setQueryParams({ redirectUrl: 'http://localhost:4000/repository/login?redirectUrl=%2Fmydspace%3Fconfiguration%3Dworkflow' }); + + component.submit(); + + expect(setRedirectUrlSpy).toHaveBeenCalledWith('/mydspace?configuration=workflow'); }); it('passes through an already-relative redirectUrl unchanged', () => { - setQueryParams({ redirectUrl: '/repository/search' }); + setQueryParams({ redirectUrl: '/search' }); + + component.submit(); + + expect(setRedirectUrlSpy).toHaveBeenCalledWith('/search'); + }); + + it('targets the plain login route when the login started on the login page itself, so it ends on the home page', () => { + setQueryParams({ redirectUrl: 'http://localhost:4000/repository/login' }); + + component.submit(); + + expect(setRedirectUrlSpy).toHaveBeenCalledWith('/login'); + }); + + it('keeps the home page as the target, so a stored page does not win over it', () => { + setQueryParams({ redirectUrl: 'http://localhost:4000/repository/' }); component.submit(); - expect(setRedirectUrlSpy).toHaveBeenCalledWith('/repository/search'); + expect(setRedirectUrlSpy).toHaveBeenCalledWith('/'); }); it('falls back to setRedirectUrlIfNotSet("/") when no redirectUrl query param is present', () => { diff --git a/src/app/shared/log-in/methods/password/log-in-password.component.ts b/src/app/shared/log-in/methods/password/log-in-password.component.ts index d34772641f0..c33cca03d52 100644 --- a/src/app/shared/log-in/methods/password/log-in-password.component.ts +++ b/src/app/shared/log-in/methods/password/log-in-password.component.ts @@ -1,6 +1,7 @@ import { AsyncPipe, isPlatformBrowser, + Location, } from '@angular/common'; import { Component, @@ -166,6 +167,7 @@ export class LogInPasswordComponent implements OnInit, OnDestroy { protected configurationService: ConfigurationDataService, private notificationService: NotificationsService, private translateService: TranslateService, + private location: Location, ) { this.authMethod = injectedAuthMethodModel; } @@ -303,9 +305,13 @@ export class LogInPasswordComponent implements OnInit, OnDestroy { return this.toRelativePath(redirectUrl); } - /** Reduce a possibly-absolute URL to an app-relative path by dropping the scheme+host; relative values pass through. */ + /** + * Reduce a possibly-absolute URL to a router path by dropping the scheme+host and the base href (e.g. `/repository`). + * Without the base href a login page target is `/login`, which `AuthService.navigateToRedirectUrl` sends home. + * The home page itself normalizes to '', so it becomes `/`. + */ private toRelativePath(url: string): string { - return url.replace(/^https?:\/\/[^/]+/i, ''); + return this.location.normalize(url.replace(/^https?:\/\/[^/]+/i, '')) || '/'; } /**