diff --git a/src/app/core/auth/auth.service.spec.ts b/src/app/core/auth/auth.service.spec.ts index 98dffe3e509..d972d342b48 100644 --- a/src/app/core/auth/auth.service.spec.ts +++ b/src/app/core/auth/auth.service.spec.ts @@ -52,6 +52,8 @@ import { import { getMockTranslateService } from '../testing/translate.service.mock'; import { createSuccessfulRemoteDataObject$ } from '../utilities/remote-data.utils'; import { + CheckAuthenticationTokenAction, + RetrieveAuthMethodsSuccessAction, SetUserAsIdleAction, UnsetUserAsIdleAction, } from './auth.actions'; @@ -195,6 +197,19 @@ describe('AuthService test', () => { mockStore.setState(initialState); }); + it('should become ready after anonymous authentication initialization without a loaded flag', () => { + const pending = authReducer(undefined, new CheckAuthenticationTokenAction()); + mockStore.setState({ core: { auth: pending } } as any); + const results: boolean[] = []; + const subscription = authService.isAuthenticationReady().subscribe((ready) => results.push(ready)); + const anonymous = authReducer(pending, new RetrieveAuthMethodsSuccessAction([])); + expect(anonymous.loaded).toBeFalse(); + expect(anonymous.authenticated).toBeFalse(); + mockStore.setState({ core: { auth: anonymous } } as any); + expect(results).toEqual([false, true]); + subscription.unsubscribe(); + }); + it('should return the authentication status object when user credentials are correct', () => { authService.authenticate('user', 'password').subscribe((status: AuthStatus) => { expect(status).toBeDefined(); diff --git a/src/app/core/auth/auth.service.ts b/src/app/core/auth/auth.service.ts index a762c857626..bbaec730718 100644 --- a/src/app/core/auth/auth.service.ts +++ b/src/app/core/auth/auth.service.ts @@ -86,6 +86,7 @@ import { getRedirectUrl, isAuthenticated, isAuthenticatedLoaded, + isAuthenticationBlocking, isIdle, isTokenRefreshing, } from './selectors'; @@ -190,6 +191,15 @@ export class AuthService { return this.store.pipe(select(isAuthenticatedLoaded)); } + /** + * Whether authentication initialization has finished, including anonymous sessions. + * Uses the same readiness condition as application initialization; anonymous sessions + * can finish loading their authentication methods without setting the loaded flag. + */ + public isAuthenticationReady(): Observable { + return this.store.pipe(select(isAuthenticationBlocking), map((blocking) => blocking === false)); + } + /** * Used to set the external authentication status when authenticating via an * external authentication system (e.g. Shibboleth). diff --git a/src/app/core/data/feature-authorization/authorization-data.service.spec.ts b/src/app/core/data/feature-authorization/authorization-data.service.spec.ts index fb8a75815ed..615f2d71050 100644 --- a/src/app/core/data/feature-authorization/authorization-data.service.spec.ts +++ b/src/app/core/data/feature-authorization/authorization-data.service.spec.ts @@ -1,8 +1,10 @@ import { hasValue } from '@dspace/shared/utils/empty.util'; import { + BehaviorSubject, combineLatest as observableCombineLatest, Observable, of, + throwError, } from 'rxjs'; import { RequestParam } from '../../cache/models/request-param.model'; @@ -26,6 +28,7 @@ describe('AuthorizationDataService', () => { let service: AuthorizationDataService; let siteService: SiteDataService; let objectCache; + let authService; let site: Site; let ePerson: EPerson; @@ -48,8 +51,12 @@ describe('AuthorizationDataService', () => { siteService = jasmine.createSpyObj('siteService', { find: of(site), }); + authService = jasmine.createSpyObj('authService', { + isAuthenticated: of(true), + isAuthenticationReady: of(true), + }); objectCache = getMockObjectCacheService(); - service = new AuthorizationDataService(requestService, undefined, objectCache, undefined, siteService); + service = new AuthorizationDataService(requestService, undefined, objectCache, undefined, siteService, authService); } beforeEach(() => { @@ -58,7 +65,7 @@ describe('AuthorizationDataService', () => { }); describe('composition', () => { - const initService = () => new AuthorizationDataService(null, null, null, null, null); + const initService = () => new AuthorizationDataService(null, null, null, null, null, null); testSearchDataImplementation(initService); }); @@ -239,5 +246,134 @@ describe('AuthorizationDataService', () => { }); }); }); + + describe('anonymous authorization batching', () => { + let search: jasmine.Spy; + beforeEach(() => { + authService.isAuthenticated.and.returnValue(of(false)); + search = spyOn(service, 'searchByObject').and.returnValue(createSuccessfulRemoteDataObject$(createPaginatedList(validPayload))); + }); + + it('should use the same unfiltered object request for different anonymous features', () => { + const results = []; + service.isAuthorized(featureID, 'item-url').subscribe((value) => results.push(value)); + service.isAuthorized(FeatureID.CanCreateVersion, 'item-url').subscribe((value) => results.push(value)); + expect(results).toEqual([true, false]); + // Identical unfiltered searches, which the request cache serves with a single request + expect(search.calls.count()).toBe(2); + expect(search.calls.argsFor(0)).toEqual(search.calls.argsFor(1)); + expect(search).toHaveBeenCalledWith(undefined, 'item-url', undefined, { elementsPerPage: 100 }, true, true, jasmine.anything()); + }); + + it('should resolve the site URL for checks without an object', () => { + service.isAuthorized(featureID).subscribe((value) => expect(value).toBeTrue()); + expect(search).toHaveBeenCalledWith(undefined, site.self, undefined, { elementsPerPage: 100 }, true, true, jasmine.anything()); + }); + + [FeatureID.CanSeeQA, FeatureID.CoarNotifyEnabled, FeatureID.CanDownload, FeatureID.CanEditItem, + FeatureID.CanEditMetadata, FeatureID.CanManageRelationships, FeatureID.CanCreateVersion].forEach((feature) => { + it(`should preserve the backend result for ${feature}`, () => { + const grant = Object.assign(new Authorization(), { + feature: createSuccessfulRemoteDataObject$(Object.assign(new Feature(), { id: feature })), + }); + search.and.returnValue(createSuccessfulRemoteDataObject$(createPaginatedList([grant]))); + service.isAuthorized(feature).subscribe((result) => expect(result).toBeTrue()); + }); + }); + + it('should follow pagination before deciding a feature is absent', () => { + const first = createPaginatedList(invalidPayload); + first._links.next = { href: 'next-page' }; + search.and.returnValue(createSuccessfulRemoteDataObject$(first)); + const next = spyOn(service, 'findListByHref').and.returnValue(createSuccessfulRemoteDataObject$(createPaginatedList(validPayload))); + spyOn(service as any, 'addDependency'); + service.isAuthorized(featureID, 'item-url', undefined, false, false).subscribe((value) => expect(value).toBeTrue()); + expect(next).toHaveBeenCalledWith('next-page', {}, false, false, jasmine.anything()); + expect((service as any).addDependency).toHaveBeenCalled(); + }); + + [401, 403, 404, 500].forEach((status) => { + it(`should fall back to the individual check when the batch fails (${status})`, () => { + search.and.callFake((feature) => feature + ? createSuccessfulRemoteDataObject$(createPaginatedList(validPayload)) + : createFailedRemoteDataObject$('Batch failed', status)); + service.isAuthorized(featureID, 'item-url', undefined, false, false).subscribe((value) => expect(value).toBeTrue()); + expect(search).toHaveBeenCalledWith(featureID, 'item-url', undefined, {}, false, false, jasmine.anything()); + }); + }); + + it('should fall back on thrown errors', () => { + search.and.callFake((feature) => feature + ? createSuccessfulRemoteDataObject$(createPaginatedList(validPayload)) + : throwError(() => new Error('Batch failed'))); + service.isAuthorized(featureID).subscribe((value) => expect(value).toBeTrue()); + }); + + it('should fall back to the individual check when a feature cannot be retrieved', () => { + const brokenGrant = Object.assign(new Authorization(), { + feature: createFailedRemoteDataObject$('Feature failed', 500), + }); + search.and.callFake((feature) => createSuccessfulRemoteDataObject$( + createPaginatedList(feature ? validPayload : [brokenGrant]))); + const result = jasmine.createSpy('result'); + service.isAuthorized(featureID, 'item-url').subscribe(result); + expect(result).toHaveBeenCalledOnceWith(true); + expect(search).toHaveBeenCalledWith(featureID, 'item-url', undefined, {}, true, true, jasmine.anything()); + }); + + it('should discard partial grants if a later page fails', () => { + const first = createPaginatedList(validPayload); + first._links.next = { href: 'failed-page' }; + search.and.callFake((feature) => createSuccessfulRemoteDataObject$(feature ? createPaginatedList([]) : first)); + spyOn(service, 'findListByHref').and.returnValue(createFailedRemoteDataObject$('Failed', 500)); + spyOn(service as any, 'addDependency'); + service.isAuthorized(featureID).subscribe((value) => expect(value).toBeFalse()); + expect(search).toHaveBeenCalledTimes(2); + }); + + it('should retain individual checks for authenticated visitors', () => { + authService.isAuthenticated.and.returnValue(of(true)); + service.isAuthorized(featureID).subscribe((result) => expect(result).toBeTrue()); + expect(search).toHaveBeenCalledOnceWith(featureID, undefined, undefined, {}, true, true, jasmine.anything()); + }); + + it('should retain explicit EPerson requests and request cache options', () => { + service.isAuthorized(featureID, 'object-url', 'eperson-uuid', false, false).subscribe(); + expect(search).toHaveBeenCalledOnceWith(featureID, 'object-url', 'eperson-uuid', {}, false, false, jasmine.anything()); + }); + + it('should leave requests without a specific feature unchanged', () => { + search.and.returnValue(createSuccessfulRemoteDataObject$(createPaginatedList([]))); + service.isAuthorized().subscribe(); + expect(search).toHaveBeenCalledOnceWith(undefined, undefined, undefined, {}, true, true, jasmine.anything()); + }); + + [true, false].forEach((authenticated) => { + it(`should wait until authentication is ready (authenticated: ${authenticated})`, () => { + const ready$ = new BehaviorSubject(false); + const authenticated$ = new BehaviorSubject(false); + authService.isAuthenticationReady.and.returnValue(ready$); + authService.isAuthenticated.and.returnValue(authenticated$); + const result = jasmine.createSpy('result'); + service.isAuthorized(featureID, 'item-url').subscribe(result); + expect(result).not.toHaveBeenCalled(); + expect(search).not.toHaveBeenCalled(); + authenticated$.next(authenticated); + ready$.next(true); + expect(result).toHaveBeenCalledOnceWith(true); + expect(search.calls.mostRecent().args[0]).toEqual(authenticated ? featureID : undefined); + }); + }); + + it('should reconsider authentication on subsequent calls after login', () => { + service.isAuthorized(featureID, 'item-url').subscribe(); + authService.isAuthenticated.and.returnValue(of(true)); + service.invalidateAuthorizationsRequestCache(); + service.isAuthorized(featureID, 'item-url').subscribe(); + expect(search.calls.argsFor(0)[0]).toBeUndefined(); + expect(search.calls.argsFor(1)[0]).toBe(featureID); + expect(requestService.setStaleByHrefSubstring).toHaveBeenCalledWith('authorizations'); + }); + }); }); }); diff --git a/src/app/core/data/feature-authorization/authorization-data.service.ts b/src/app/core/data/feature-authorization/authorization-data.service.ts index afe0a4753de..ea23d81b275 100644 --- a/src/app/core/data/feature-authorization/authorization-data.service.ts +++ b/src/app/core/data/feature-authorization/authorization-data.service.ts @@ -7,15 +7,21 @@ import { isNotEmpty, } from '@dspace/shared/utils/empty.util'; import { + EMPTY, Observable, of, } from 'rxjs'; import { catchError, + expand, + filter, map, + reduce, switchMap, + take, } from 'rxjs/operators'; +import { AuthService } from '../../auth/auth.service'; import { dataService } from '../../cache/builders/build-decorators'; import { RemoteDataBuildService } from '../../cache/builders/remote-data-build.service'; import { RequestParam } from '../../cache/models/request-param.model'; @@ -38,7 +44,11 @@ import { RemoteData } from '../remote-data'; import { RequestService } from '../request.service'; import { SiteDataService } from '../site-data.service'; import { AuthorizationSearchParams } from './authorization-search-params'; -import { oneAuthorizationMatchesFeature } from './authorization-utils'; +import { + authorizationFeatureIds, + getSucceededPageOrThrow, + oneAuthorizationMatchesFeature, +} from './authorization-utils'; import { FeatureID } from './feature-id'; /** @@ -59,6 +69,7 @@ export class AuthorizationDataService extends BaseDataService imp protected objectCache: ObjectCacheService, protected halService: HALEndpointService, protected siteService: SiteDataService, + protected authService: AuthService, ) { super('authorizations', requestService, rdbService, objectCache, halService); @@ -85,6 +96,70 @@ export class AuthorizationDataService extends BaseDataService imp * requested after the response becomes stale */ isAuthorized(featureId?: FeatureID, objectUrl?: string, ePersonUuid?: string, useCachedVersionIfAvailable = true, reRequestOnStale = true): Observable { + if (hasValue(featureId) && hasNoValue(ePersonUuid)) { + // An unresolved authentication state must never be mistaken for an anonymous visitor. + return this.authService.isAuthenticationReady().pipe( + filter((ready: boolean) => ready), + take(1), + switchMap(() => this.authService.isAuthenticated().pipe(take(1))), + switchMap((authenticated: boolean) => authenticated + ? this.checkAuthorization(featureId, objectUrl, ePersonUuid, useCachedVersionIfAvailable, reRequestOnStale) + : this.checkAnonymousAuthorization(featureId, objectUrl, useCachedVersionIfAvailable, reRequestOnStale)), + ); + } + return this.checkAuthorization(featureId, objectUrl, ePersonUuid, useCachedVersionIfAvailable, reRequestOnStale); + } + + /** + * Anonymous feature checks for the same object share the existing unfiltered REST search. + * The request cache deduplicates pending requests and retains its normal expiry, dependency + * invalidation and SSR transfer behavior. No permissions are cached separately here. + * A failed batch (including a custom feature throwing on the backend) falls back to the + * original individual feature check. + */ + private checkAnonymousAuthorization(featureId: FeatureID, objectUrl: string, useCachedVersionIfAvailable: boolean, reRequestOnStale: boolean): Observable { + const objectUrl$ = hasValue(objectUrl) ? of(objectUrl) : this.siteService.find().pipe(map((site) => site.self)); + return objectUrl$.pipe( + take(1), + // Retrieve every authorization granted on the object, without a feature filter + switchMap((url: string) => this.findAllAuthorizationsForObject(url, useCachedVersionIfAvailable, reRequestOnStale)), + // Resolve the embedded feature of each authorization to its ID + authorizationFeatureIds, + // The requested feature is granted if its ID is among them + map((featureIds: Set) => featureIds.has(featureId.valueOf())), + // Any failure along the way: ask the backend about this single feature instead + catchError(() => this.checkAuthorization(featureId, objectUrl, undefined, useCachedVersionIfAvailable, reRequestOnStale)), + ); + } + + /** + * Retrieve all {@link Authorization}s granted on an object, following every page before + * completing, so that a feature is never considered absent because it is on a later page. + * Errors if any page fails. + */ + private findAllAuthorizationsForObject(url: string, useCachedVersionIfAvailable: boolean, reRequestOnStale: boolean): Observable { + const firstPage$ = this.searchByObject(undefined, url, undefined, { elementsPerPage: 100 }, + useCachedVersionIfAvailable, reRequestOnStale, followLink('feature')); + return firstPage$.pipe( + getSucceededPageOrThrow, + // Request the next page for as long as the current one links to it + expand((page: PaginatedList) => { + if (!page.next) { + return EMPTY; + } + const nextPage$ = this.findListByHref(page.next, {}, useCachedVersionIfAvailable, reRequestOnStale, followLink('feature')); + this.addDependency(nextPage$, of(url)); + return nextPage$.pipe(getSucceededPageOrThrow); + }), + // Combine the authorizations of all pages into one list + reduce((authorizations: Authorization[], page: PaginatedList) => [...authorizations, ...page.page], []), + ); + } + + /** + * Perform the actual authorization lookup for a single feature against the REST API. + */ + private checkAuthorization(featureId?: FeatureID, objectUrl?: string, ePersonUuid?: string, useCachedVersionIfAvailable = true, reRequestOnStale = true): Observable { return this.searchByObject(featureId, objectUrl, ePersonUuid, {}, useCachedVersionIfAvailable, reRequestOnStale, followLink('feature')).pipe( getFirstCompletedRemoteData(), map((authorizationRD) => { diff --git a/src/app/core/data/feature-authorization/authorization-utils.ts b/src/app/core/data/feature-authorization/authorization-utils.ts index ee91c20058c..61b5a4a5423 100644 --- a/src/app/core/data/feature-authorization/authorization-utils.ts +++ b/src/app/core/data/feature-authorization/authorization-utils.ts @@ -16,7 +16,12 @@ import { import { AuthService } from '../../auth/auth.service'; import { Authorization } from '../../shared/authorization.model'; import { Feature } from '../../shared/feature.model'; -import { getFirstSucceededRemoteDataPayload } from '../../shared/operators'; +import { + getFirstCompletedRemoteData, + getFirstSucceededRemoteDataPayload, +} from '../../shared/operators'; +import { PaginatedList } from '../paginated-list.model'; +import { RemoteData } from '../remote-data'; import { SiteDataService } from '../site-data.service'; import { AuthorizationSearchParams } from './authorization-search-params'; import { FeatureID } from './feature-id'; @@ -93,3 +98,41 @@ export const oneAuthorizationMatchesFeature = (featureID: FeatureID) => }), map((features: Feature[]) => features.filter((feature: Feature) => feature.id === featureID.valueOf()).length > 0), ); + +/** + * Operator emitting the payload of the first completed page of {@link Authorization}s. + * Errors instead if the request failed, so that callers can fall back to another check. + */ +export const getSucceededPageOrThrow = (source: Observable>>): Observable> => + source.pipe( + getFirstCompletedRemoteData(), + map((response: RemoteData>) => { + if (!response.hasSucceeded || !Array.isArray(response.payload?.page)) { + throw new Error('Unable to retrieve object authorizations'); + } + return response.payload; + }), + ); + +/** + * Operator resolving the {@link Feature} of each {@link Authorization} and emitting the set of their IDs. + * Errors if any feature cannot be retrieved, rather than waiting for one that never succeeds. + */ +export const authorizationFeatureIds = (source: Observable): Observable> => + source.pipe( + switchMap((authorizations: Authorization[]) => { + const features$ = (authorizations || []) + .filter((authorization: Authorization) => hasValue(authorization.feature)) + .map((authorization: Authorization) => authorization.feature.pipe( + getFirstCompletedRemoteData(), + map((featureRD: RemoteData) => { + if (!featureRD.hasSucceeded || hasNoValue(featureRD.payload)) { + throw new Error('Unable to retrieve authorization feature'); + } + return featureRD.payload; + }), + )); + return features$.length ? observableCombineLatest(features$) : of([]); + }), + map((features: Feature[]) => new Set(features.map((feature: Feature) => feature.id))), + ); diff --git a/src/app/item-page/simple/field-components/file-section/file-section.component.spec.ts b/src/app/item-page/simple/field-components/file-section/file-section.component.spec.ts index 09069ad1293..920d5f6c5d3 100644 --- a/src/app/item-page/simple/field-components/file-section/file-section.component.spec.ts +++ b/src/app/item-page/simple/field-components/file-section/file-section.component.spec.ts @@ -9,12 +9,14 @@ import { BrowserAnimationsModule } from '@angular/platform-browser/animations'; import { ActivatedRoute } from '@angular/router'; import { APP_CONFIG } from '@dspace/config/app-config.interface'; import { BitstreamDataService } from '@dspace/core/data/bitstream-data.service'; +import { AuthorizationDataService } from '@dspace/core/data/feature-authorization/authorization-data.service'; import { APP_DATA_SERVICES_MAP } from '@dspace/core/data-services-map-type'; import { LocaleService } from '@dspace/core/locale/locale.service'; import { NotificationsService } from '@dspace/core/notification-system/notifications.service'; import { Bitstream } from '@dspace/core/shared/bitstream.model'; import { PageInfo } from '@dspace/core/shared/page-info.model'; import { ActivatedRouteStub } from '@dspace/core/testing/active-router.stub'; +import { AuthorizationDataServiceStub } from '@dspace/core/testing/authorization-service.stub'; import { MockBitstreamFormat1 } from '@dspace/core/testing/item.mock'; import { NotificationsServiceStub } from '@dspace/core/testing/notifications-service.stub'; import { TranslateLoaderMock } from '@dspace/core/testing/translate-loader.mock'; @@ -91,6 +93,7 @@ describe('FileSectionComponent', () => { { provide: APP_DATA_SERVICES_MAP, useValue: {} }, { provide: XSRFService, useValue: {} }, { provide: BitstreamDataService, useValue: bitstreamDataService }, + { provide: AuthorizationDataService, useClass: AuthorizationDataServiceStub }, { provide: NotificationsService, useValue: new NotificationsServiceStub() }, { provide: APP_CONFIG, useValue: environment }, { provide: ThemeService, useValue: getMockThemeService() }, diff --git a/src/app/shared/object-select/item-select/item-select.component.spec.ts b/src/app/shared/object-select/item-select/item-select.component.spec.ts index 3d5d665e4c3..3a288a5ec47 100644 --- a/src/app/shared/object-select/item-select/item-select.component.spec.ts +++ b/src/app/shared/object-select/item-select/item-select.component.spec.ts @@ -79,7 +79,7 @@ describe('ItemSelectComponent', () => { paginationService = new PaginationServiceStub(mockPaginationOptions); - const authorizationDataService = new AuthorizationDataService(null, null, null, null, null); + const authorizationDataService = new AuthorizationDataService(null, null, null, null, null, null); const linkHeadService = jasmine.createSpyObj('linkHeadService', { addTag: '',