From ec77307c389773010832fb9e71425277eace9057 Mon Sep 17 00:00:00 2001 From: bram-atmire Date: Sun, 20 Sep 2026 20:22:50 +0200 Subject: [PATCH 1/6] Skip authenticated-only authorization checks for anonymous visitors An anonymous item render fires ~15 per-feature authorization checks, about ten of which ask about admin/edit/login-only capabilities an unauthenticated visitor can never hold. AuthorizationDataService.isAuthorized now answers false locally, without a REST call, for those features when no one is logged in, and waits for isAuthenticationLoaded() before deciding so authenticated users are never transiently treated as anonymous. Measured on a local DSpace 11 stack with OpenTelemetry tracing: an anonymous item render drops from 42 to 31 backend calls (15 to 5 authorization checks) and single-core SSR render throughput rises ~45%. Refs #6256, #3161 Co-authored-by: Claude Fable 5.1 --- .../authorization-data.service.spec.ts | 78 ++++++++++++++++++- .../authorization-data.service.ts | 54 +++++++++++++ .../item-select/item-select.component.spec.ts | 2 +- 3 files changed, 131 insertions(+), 3 deletions(-) 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..071b63bf1bf 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 @@ -26,6 +26,7 @@ describe('AuthorizationDataService', () => { let service: AuthorizationDataService; let siteService: SiteDataService; let objectCache; + let authService; let site: Site; let ePerson: EPerson; @@ -48,8 +49,12 @@ describe('AuthorizationDataService', () => { siteService = jasmine.createSpyObj('siteService', { find: of(site), }); + authService = jasmine.createSpyObj('authService', { + isAuthenticated: of(true), + isAuthenticationLoaded: of(true), + }); objectCache = getMockObjectCacheService(); - service = new AuthorizationDataService(requestService, undefined, objectCache, undefined, siteService); + service = new AuthorizationDataService(requestService, undefined, objectCache, undefined, siteService, authService); } beforeEach(() => { @@ -58,7 +63,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 +244,74 @@ describe('AuthorizationDataService', () => { }); }); }); + + describe('for an authenticated-only feature when the current user is anonymous', () => { + // canEditItem is in AUTHENTICATED_ONLY_FEATURES; an anonymous user can never have it. + beforeEach(() => { + authService.isAuthenticationLoaded.and.returnValue(of(true)); + authService.isAuthenticated.and.returnValue(of(false)); + spyOn(service, 'searchByObject'); + }); + + it('should short-circuit to false without any REST call', (done) => { + service.isAuthorized(FeatureID.CanEditItem).subscribe((result) => { + expect(result).toEqual(false); + expect(service.searchByObject).not.toHaveBeenCalled(); + done(); + }); + }); + }); + + describe('for an authenticated-only feature when the current user IS authenticated', () => { + beforeEach(() => { + authService.isAuthenticationLoaded.and.returnValue(of(true)); + authService.isAuthenticated.and.returnValue(of(true)); + spyOn(service, 'searchByObject').and.returnValue(createSuccessfulRemoteDataObject$(createPaginatedList(validPayload))); + }); + + it('should perform the normal check', (done) => { + service.isAuthorized(FeatureID.AdministratorOf).subscribe((result) => { + expect(service.searchByObject).toHaveBeenCalled(); + expect(result).toEqual(true); + done(); + }); + }); + }); + + describe('for a feature an anonymous user can legitimately have (e.g. canDownload)', () => { + beforeEach(() => { + authService.isAuthenticated.and.returnValue(of(false)); + authService.isAuthenticationLoaded.and.returnValue(of(true)); + spyOn(service, 'searchByObject').and.returnValue(createSuccessfulRemoteDataObject$(createPaginatedList(emptyPayload))); + }); + + it('should still be checked normally, not skipped', (done) => { + service.isAuthorized(FeatureID.CanDownload).subscribe(() => { + expect(service.searchByObject).toHaveBeenCalled(); + done(); + }); + }); + }); + + describe('for an authenticated-only feature before authentication has finished loading', () => { + beforeEach(() => { + // not loaded yet -> must wait, never decide off the transient "false" + authService.isAuthenticationLoaded.and.returnValue(of(false)); + authService.isAuthenticated.and.returnValue(of(false)); + spyOn(service, 'searchByObject'); + }); + + it('should not emit or call searchByObject until authentication is loaded', (done) => { + let emitted = false; + service.isAuthorized(FeatureID.CanEditItem).subscribe(() => { + emitted = true; + }); + setTimeout(() => { + expect(emitted).toEqual(false); + expect(service.searchByObject).not.toHaveBeenCalled(); + done(); + }, 50); + }); + }); }); }); 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..9d1f9d1d016 100644 --- a/src/app/core/data/feature-authorization/authorization-data.service.ts +++ b/src/app/core/data/feature-authorization/authorization-data.service.ts @@ -12,8 +12,10 @@ import { } from 'rxjs'; import { catchError, + filter, map, switchMap, + take, } from 'rxjs/operators'; import { dataService } from '../../cache/builders/build-decorators'; @@ -37,6 +39,7 @@ import { PaginatedList } from '../paginated-list.model'; import { RemoteData } from '../remote-data'; import { RequestService } from '../request.service'; import { SiteDataService } from '../site-data.service'; +import { AuthService } from '../../auth/auth.service'; import { AuthorizationSearchParams } from './authorization-search-params'; import { oneAuthorizationMatchesFeature } from './authorization-utils'; import { FeatureID } from './feature-id'; @@ -53,12 +56,35 @@ export class AuthorizationDataService extends BaseDataService imp private searchData: SearchDataImpl; + /** + * Features that can only ever be granted to an authenticated user. For an anonymous visitor + * these are always false, so they are answered locally without a REST call (avoiding a backend + * lookup that re-resolves the user's groups and resource policies). Kept deliberately + * conservative: the features an unauthenticated visitor can legitimately be granted - canDownload, + * canRequestACopy, epersonRegistration, epersonForgotPassword, canSendFeedback and + * canViewUsageStatistics - are intentionally NOT listed here and are always checked normally. + */ + private static readonly AUTHENTICATED_ONLY_FEATURES: Set = new Set([ + FeatureID.LoginOnBehalfOf, FeatureID.AdministratorOf, FeatureID.CanDelete, + FeatureID.CanEditMetadata, FeatureID.WithdrawItem, FeatureID.ReinstateItem, + FeatureID.CanManageGroups, FeatureID.CanManageGroup, FeatureID.IsCollectionAdmin, + FeatureID.IsCommunityAdmin, FeatureID.CanChangePassword, FeatureID.CanManageVersions, + FeatureID.CanManageBitstreamBundles, FeatureID.CanManageRelationships, + FeatureID.CanManageMappings, FeatureID.CanManagePolicies, FeatureID.CanMakePrivate, + FeatureID.CanMove, FeatureID.CanEditVersion, FeatureID.CanDeleteVersion, + FeatureID.CanCreateVersion, FeatureID.CanClaimItem, FeatureID.CanSynchronizeWithORCID, + FeatureID.CanSubmit, FeatureID.CanEditItem, FeatureID.CanRegisterDOI, + FeatureID.CanSubscribe, FeatureID.CanSeeQA, FeatureID.CoarNotifyEnabled, + FeatureID.CanReplaceBitstreamSubmitter, FeatureID.CanReplaceBitstreamAdmin, + ]); + constructor( protected requestService: RequestService, protected rdbService: RemoteDataBuildService, protected objectCache: ObjectCacheService, protected halService: HALEndpointService, protected siteService: SiteDataService, + protected authService: AuthService, ) { super('authorizations', requestService, rdbService, objectCache, halService); @@ -85,6 +111,34 @@ export class AuthorizationDataService extends BaseDataService imp * requested after the response becomes stale */ isAuthorized(featureId?: FeatureID, objectUrl?: string, ePersonUuid?: string, useCachedVersionIfAvailable = true, reRequestOnStale = true): Observable { + // Access load is dominated by unauthenticated traffic (crawlers and browser-impersonating + // scrapers). For those visitors an admin/edit/manage feature can never be granted, yet each + // check would otherwise trigger a REST call that re-resolves the user's groups and resource + // policies in the backend - a well-known source of excessive DB queries per page. So when we + // are checking the *current* user for a feature that only makes sense once logged in, answer + // "false" locally without any request whenever nobody is authenticated. + if (hasValue(featureId) && hasNoValue(ePersonUuid) && AuthorizationDataService.AUTHENTICATED_ONLY_FEATURES.has(featureId)) { + // Wait until authentication has finished loading before deciding. The auth store starts in an + // un-loaded state where "authenticated" reads false, so reading it too early could momentarily + // treat a genuinely logged-in user as anonymous and hide these controls from them. Only once + // authentication is loaded do we read the settled value: if still not authenticated, the answer + // is "false" locally with no REST call; otherwise we perform the normal check. + return this.authService.isAuthenticationLoaded().pipe( + filter((loaded: boolean) => loaded), + take(1), + switchMap(() => this.authService.isAuthenticated().pipe(take(1))), + switchMap((authenticated: boolean) => authenticated + ? this.checkAuthorization(featureId, objectUrl, ePersonUuid, useCachedVersionIfAvailable, reRequestOnStale) + : of(false)), + ); + } + return this.checkAuthorization(featureId, objectUrl, ePersonUuid, useCachedVersionIfAvailable, reRequestOnStale); + } + + /** + * 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/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: '', From 0a36bb02e847d8510d7af30f9a3c8363679ec1af Mon Sep 17 00:00:00 2001 From: bram-atmire Date: Sat, 26 Sep 2026 15:14:40 +0200 Subject: [PATCH 2/6] Batch anonymous authorization checks per object --- src/app/core/auth/auth.service.spec.ts | 15 ++ src/app/core/auth/auth.service.ts | 10 ++ .../authorization-data.service.spec.ts | 145 ++++++++++++------ .../authorization-data.service.ts | 87 ++++++----- 4 files changed, 171 insertions(+), 86 deletions(-) diff --git a/src/app/core/auth/auth.service.spec.ts b/src/app/core/auth/auth.service.spec.ts index 4c4efc2f62b..bc54c69ea0a 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 071b63bf1bf..2f89d667047 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'; @@ -51,7 +53,7 @@ describe('AuthorizationDataService', () => { }); authService = jasmine.createSpyObj('authService', { isAuthenticated: of(true), - isAuthenticationLoaded: of(true), + isAuthenticationReady: of(true), }); objectCache = getMockObjectCacheService(); service = new AuthorizationDataService(requestService, undefined, objectCache, undefined, siteService, authService); @@ -245,72 +247,119 @@ describe('AuthorizationDataService', () => { }); }); - describe('for an authenticated-only feature when the current user is anonymous', () => { - // canEditItem is in AUTHENTICATED_ONLY_FEATURES; an anonymous user can never have it. + describe('anonymous authorization batching', () => { + let search: jasmine.Spy; beforeEach(() => { - authService.isAuthenticationLoaded.and.returnValue(of(true)); authService.isAuthenticated.and.returnValue(of(false)); - spyOn(service, 'searchByObject'); + search = spyOn(service, 'searchByObject').and.returnValue(createSuccessfulRemoteDataObject$(createPaginatedList(validPayload))); }); - it('should short-circuit to false without any REST call', (done) => { - service.isAuthorized(FeatureID.CanEditItem).subscribe((result) => { - expect(result).toEqual(false); - expect(service.searchByObject).not.toHaveBeenCalled(); - done(); - }); + 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]); + 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()); }); - }); - describe('for an authenticated-only feature when the current user IS authenticated', () => { - beforeEach(() => { - authService.isAuthenticationLoaded.and.returnValue(of(true)); - authService.isAuthenticated.and.returnValue(of(true)); - spyOn(service, 'searchByObject').and.returnValue(createSuccessfulRemoteDataObject$(createPaginatedList(validPayload))); + 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()); }); - it('should perform the normal check', (done) => { - service.isAuthorized(FeatureID.AdministratorOf).subscribe((result) => { - expect(service.searchByObject).toHaveBeenCalled(); - expect(result).toEqual(true); - done(); + [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()); }); }); - }); - describe('for a feature an anonymous user can legitimately have (e.g. canDownload)', () => { - beforeEach(() => { - authService.isAuthenticated.and.returnValue(of(false)); - authService.isAuthenticationLoaded.and.returnValue(of(true)); - spyOn(service, 'searchByObject').and.returnValue(createSuccessfulRemoteDataObject$(createPaginatedList(emptyPayload))); + 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(); }); - it('should still be checked normally, not skipped', (done) => { - service.isAuthorized(FeatureID.CanDownload).subscribe(() => { - expect(service.searchByObject).toHaveBeenCalled(); - done(); + [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()); }); }); - }); - describe('for an authenticated-only feature before authentication has finished loading', () => { - beforeEach(() => { - // not loaded yet -> must wait, never decide off the transient "false" - authService.isAuthenticationLoaded.and.returnValue(of(false)); - authService.isAuthenticated.and.returnValue(of(false)); - spyOn(service, 'searchByObject'); + 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 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 not emit or call searchByObject until authentication is loaded', (done) => { - let emitted = false; - service.isAuthorized(FeatureID.CanEditItem).subscribe(() => { - emitted = true; + 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); }); - setTimeout(() => { - expect(emitted).toEqual(false); - expect(service.searchByObject).not.toHaveBeenCalled(); - done(); - }, 50); + }); + + 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 9d1f9d1d016..437f3e55f65 100644 --- a/src/app/core/data/feature-authorization/authorization-data.service.ts +++ b/src/app/core/data/feature-authorization/authorization-data.service.ts @@ -7,17 +7,22 @@ import { isNotEmpty, } from '@dspace/shared/utils/empty.util'; import { + defer, + 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'; @@ -39,7 +44,6 @@ import { PaginatedList } from '../paginated-list.model'; import { RemoteData } from '../remote-data'; import { RequestService } from '../request.service'; import { SiteDataService } from '../site-data.service'; -import { AuthService } from '../../auth/auth.service'; import { AuthorizationSearchParams } from './authorization-search-params'; import { oneAuthorizationMatchesFeature } from './authorization-utils'; import { FeatureID } from './feature-id'; @@ -56,28 +60,6 @@ export class AuthorizationDataService extends BaseDataService imp private searchData: SearchDataImpl; - /** - * Features that can only ever be granted to an authenticated user. For an anonymous visitor - * these are always false, so they are answered locally without a REST call (avoiding a backend - * lookup that re-resolves the user's groups and resource policies). Kept deliberately - * conservative: the features an unauthenticated visitor can legitimately be granted - canDownload, - * canRequestACopy, epersonRegistration, epersonForgotPassword, canSendFeedback and - * canViewUsageStatistics - are intentionally NOT listed here and are always checked normally. - */ - private static readonly AUTHENTICATED_ONLY_FEATURES: Set = new Set([ - FeatureID.LoginOnBehalfOf, FeatureID.AdministratorOf, FeatureID.CanDelete, - FeatureID.CanEditMetadata, FeatureID.WithdrawItem, FeatureID.ReinstateItem, - FeatureID.CanManageGroups, FeatureID.CanManageGroup, FeatureID.IsCollectionAdmin, - FeatureID.IsCommunityAdmin, FeatureID.CanChangePassword, FeatureID.CanManageVersions, - FeatureID.CanManageBitstreamBundles, FeatureID.CanManageRelationships, - FeatureID.CanManageMappings, FeatureID.CanManagePolicies, FeatureID.CanMakePrivate, - FeatureID.CanMove, FeatureID.CanEditVersion, FeatureID.CanDeleteVersion, - FeatureID.CanCreateVersion, FeatureID.CanClaimItem, FeatureID.CanSynchronizeWithORCID, - FeatureID.CanSubmit, FeatureID.CanEditItem, FeatureID.CanRegisterDOI, - FeatureID.CanSubscribe, FeatureID.CanSeeQA, FeatureID.CoarNotifyEnabled, - FeatureID.CanReplaceBitstreamSubmitter, FeatureID.CanReplaceBitstreamAdmin, - ]); - constructor( protected requestService: RequestService, protected rdbService: RemoteDataBuildService, @@ -111,30 +93,59 @@ export class AuthorizationDataService extends BaseDataService imp * requested after the response becomes stale */ isAuthorized(featureId?: FeatureID, objectUrl?: string, ePersonUuid?: string, useCachedVersionIfAvailable = true, reRequestOnStale = true): Observable { - // Access load is dominated by unauthenticated traffic (crawlers and browser-impersonating - // scrapers). For those visitors an admin/edit/manage feature can never be granted, yet each - // check would otherwise trigger a REST call that re-resolves the user's groups and resource - // policies in the backend - a well-known source of excessive DB queries per page. So when we - // are checking the *current* user for a feature that only makes sense once logged in, answer - // "false" locally without any request whenever nobody is authenticated. - if (hasValue(featureId) && hasNoValue(ePersonUuid) && AuthorizationDataService.AUTHENTICATED_ONLY_FEATURES.has(featureId)) { - // Wait until authentication has finished loading before deciding. The auth store starts in an - // un-loaded state where "authenticated" reads false, so reading it too early could momentarily - // treat a genuinely logged-in user as anonymous and hide these controls from them. Only once - // authentication is loaded do we read the settled value: if still not authenticated, the answer - // is "false" locally with no REST call; otherwise we perform the normal check. - return this.authService.isAuthenticationLoaded().pipe( - filter((loaded: boolean) => loaded), + 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) - : of(false)), + : 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. + * Follow every page before deciding a feature is absent. 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), + switchMap((url: string) => { + const readPage = (response$: Observable>>) => response$.pipe( + getFirstCompletedRemoteData(), + map((response) => { + if (!response.hasSucceeded || !Array.isArray(response.payload?.page)) { + throw new Error('Unable to retrieve object authorizations'); + } + return response.payload; + }), + ); + return defer(() => readPage(this.searchByObject(undefined, url, undefined, { elementsPerPage: 100 }, + useCachedVersionIfAvailable, reRequestOnStale, followLink('feature')))).pipe( + expand((page) => { + if (!page.next) { + return EMPTY; + } + const next$ = this.findListByHref(page.next, {}, useCachedVersionIfAvailable, reRequestOnStale, followLink('feature')); + this.addDependency(next$, of(url)); + return readPage(next$); + }), + reduce((authorizations, page) => [...authorizations, ...page.page], [] as Authorization[]), + oneAuthorizationMatchesFeature(featureId), + ); + }), + catchError(() => this.checkAuthorization(featureId, objectUrl, undefined, useCachedVersionIfAvailable, reRequestOnStale)), + ); + } + /** * Perform the actual authorization lookup for a single feature against the REST API. */ From 3a45c31e9f1d7429224b06b8547005d6b82fc6a4 Mon Sep 17 00:00:00 2001 From: bram-atmire Date: Fri, 2 Oct 2026 17:04:17 +0200 Subject: [PATCH 3/6] Avoid repeated anonymous authorization feature scans --- .../authorization-data.service.spec.ts | 3 +- .../authorization-data.service.ts | 49 ++++++++++++++----- .../authorization-utils.ts | 12 +++++ 3 files changed, 51 insertions(+), 13 deletions(-) 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 2f89d667047..40ec5947699 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 @@ -259,8 +259,7 @@ describe('AuthorizationDataService', () => { 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]); - expect(search.calls.count()).toBe(2); - expect(search.calls.argsFor(0)).toEqual(search.calls.argsFor(1)); + expect(search.calls.count()).toBe(1); expect(search).toHaveBeenCalledWith(undefined, 'item-url', undefined, { elementsPerPage: 100 }, true, true, jasmine.anything()); }); 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 437f3e55f65..a2fc697fc60 100644 --- a/src/app/core/data/feature-authorization/authorization-data.service.ts +++ b/src/app/core/data/feature-authorization/authorization-data.service.ts @@ -18,6 +18,7 @@ import { filter, map, reduce, + shareReplay, switchMap, take, } from 'rxjs/operators'; @@ -45,7 +46,7 @@ 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, oneAuthorizationMatchesFeature } from './authorization-utils'; import { FeatureID } from './feature-id'; /** @@ -59,6 +60,7 @@ export class AuthorizationDataService extends BaseDataService imp protected searchByObjectPath = 'object'; private searchData: SearchDataImpl; + private anonymousFeatureIds = new Map> }>(); constructor( protected requestService: RequestService, @@ -77,6 +79,7 @@ export class AuthorizationDataService extends BaseDataService imp * Set all authorization requests to stale */ invalidateAuthorizationsRequestCache() { + this.anonymousFeatureIds.clear(); this.requestService.setStaleByHrefSubstring(this.linkPath); } @@ -128,18 +131,42 @@ export class AuthorizationDataService extends BaseDataService imp return response.payload; }), ); - return defer(() => readPage(this.searchByObject(undefined, url, undefined, { elementsPerPage: 100 }, - useCachedVersionIfAvailable, reRequestOnStale, followLink('feature')))).pipe( - expand((page) => { - if (!page.next) { - return EMPTY; + const cacheKey = `${url}|${reRequestOnStale}`; + let cached = useCachedVersionIfAvailable ? this.anonymousFeatureIds.get(cacheKey) : undefined; + if (cached && cached.expiresAt <= Date.now()) { + this.anonymousFeatureIds.delete(cacheKey); + cached = undefined; + } + if (!cached) { + const features = defer(() => readPage(this.searchByObject(undefined, url, undefined, { elementsPerPage: 100 }, + useCachedVersionIfAvailable, reRequestOnStale, followLink('feature')))).pipe( + expand((page) => { + if (!page.next) { + return EMPTY; + } + const next$ = this.findListByHref(page.next, {}, useCachedVersionIfAvailable, reRequestOnStale, followLink('feature')); + this.addDependency(next$, of(url)); + return readPage(next$); + }), + reduce((authorizations, page) => [...authorizations, ...page.page], [] as Authorization[]), + authorizationFeatureIds, + shareReplay({ bufferSize: 1, refCount: false }), + ); + // BaseDataService may leave this unset, in which case RequestService uses its + // 15-minute default response lifetime as well. + cached = { expiresAt: Date.now() + (this.responseMsToLive ?? 15 * 60 * 1000), features }; + if (useCachedVersionIfAvailable) { + this.anonymousFeatureIds.set(cacheKey, cached); + } + } + return cached.features.pipe( + map((featureIds) => featureIds.has(featureId.valueOf())), + catchError(() => { + if (this.anonymousFeatureIds.get(cacheKey) === cached) { + this.anonymousFeatureIds.delete(cacheKey); } - const next$ = this.findListByHref(page.next, {}, useCachedVersionIfAvailable, reRequestOnStale, followLink('feature')); - this.addDependency(next$, of(url)); - return readPage(next$); + return this.checkAuthorization(featureId, url, undefined, useCachedVersionIfAvailable, reRequestOnStale); }), - reduce((authorizations, page) => [...authorizations, ...page.page], [] as Authorization[]), - oneAuthorizationMatchesFeature(featureId), ); }), catchError(() => this.checkAuthorization(featureId, objectUrl, undefined, useCachedVersionIfAvailable, reRequestOnStale)), diff --git a/src/app/core/data/feature-authorization/authorization-utils.ts b/src/app/core/data/feature-authorization/authorization-utils.ts index ee91c20058c..53886c5d4a5 100644 --- a/src/app/core/data/feature-authorization/authorization-utils.ts +++ b/src/app/core/data/feature-authorization/authorization-utils.ts @@ -93,3 +93,15 @@ export const oneAuthorizationMatchesFeature = (featureID: FeatureID) => }), map((features: Feature[]) => features.filter((feature: Feature) => feature.id === featureID.valueOf()).length > 0), ); + +/** Resolve the feature links once and retain their IDs for checking multiple features. */ +export const authorizationFeatureIds = (source: Observable): Observable> => + source.pipe( + switchMap((authorizations: Authorization[]) => { + const featureLinks = (authorizations || []) + .filter((authorization: Authorization) => hasValue(authorization.feature)) + .map((authorization: Authorization) => authorization.feature.pipe(getFirstSucceededRemoteDataPayload())); + return featureLinks.length ? observableCombineLatest(featureLinks) : of([]); + }), + map((features: Feature[]) => new Set(features.map((feature) => feature.id))), + ); From 0766e67b0d2ef272633c75b01e9c5994e4cdb30b Mon Sep 17 00:00:00 2001 From: bram-atmire Date: Mon, 5 Oct 2026 12:32:24 +0200 Subject: [PATCH 4/6] Fix authorization service import lint --- .../data/feature-authorization/authorization-data.service.ts | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) 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 a2fc697fc60..ea4c47fe632 100644 --- a/src/app/core/data/feature-authorization/authorization-data.service.ts +++ b/src/app/core/data/feature-authorization/authorization-data.service.ts @@ -46,7 +46,10 @@ import { RemoteData } from '../remote-data'; import { RequestService } from '../request.service'; import { SiteDataService } from '../site-data.service'; import { AuthorizationSearchParams } from './authorization-search-params'; -import { authorizationFeatureIds, oneAuthorizationMatchesFeature } from './authorization-utils'; +import { + authorizationFeatureIds, + oneAuthorizationMatchesFeature, +} from './authorization-utils'; import { FeatureID } from './feature-id'; /** From 833726f05e564a8d5b5d08a8bb4ce6dfe1b6d7dd Mon Sep 17 00:00:00 2001 From: bram-atmire Date: Fri, 9 Oct 2026 14:41:36 +0200 Subject: [PATCH 5/6] Stub AuthorizationDataService in FileSectionComponent spec The spec relied on the real AuthorizationDataService being created for FileDownloadLinkComponent. Now that the service depends on AuthService, that construction fails with a missing AuthRequestService provider, which the test runner also reports as a circular dependency. Provide the existing stub, as other component specs do. Assisted-by: Claude Code [claude-opus-5-5] --- .../file-section/file-section.component.spec.ts | 3 +++ 1 file changed, 3 insertions(+) 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() }, From 6f522621291da128ed407fb078b1651df6314f1d Mon Sep 17 00:00:00 2001 From: bram-atmire Date: Sat, 31 Oct 2026 10:13:40 +0100 Subject: [PATCH 6/6] Simplify anonymous authorization batching Remove the per-object feature ID memo. The request cache already deduplicates the identical unfiltered searches, and the memo's own expiry did not follow request-cache invalidation. Move pagination into findAllAuthorizationsForObject and handle every failure with a single fallback to the individual feature check. Resolving the feature links no longer waits for a successful response: a failed feature link now errors, triggering that fallback instead of leaving the check pending. Assisted-by: Claude Code [claude-opus-5-5] --- .../authorization-data.service.spec.ts | 16 +++- .../authorization-data.service.ts | 86 +++++++------------ .../authorization-utils.ts | 43 ++++++++-- 3 files changed, 85 insertions(+), 60 deletions(-) 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 40ec5947699..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 @@ -259,7 +259,9 @@ describe('AuthorizationDataService', () => { 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]); - expect(search.calls.count()).toBe(1); + // 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()); }); @@ -307,6 +309,18 @@ describe('AuthorizationDataService', () => { 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' }; 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 ea4c47fe632..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,7 +7,6 @@ import { isNotEmpty, } from '@dspace/shared/utils/empty.util'; import { - defer, EMPTY, Observable, of, @@ -18,7 +17,6 @@ import { filter, map, reduce, - shareReplay, switchMap, take, } from 'rxjs/operators'; @@ -48,6 +46,7 @@ import { SiteDataService } from '../site-data.service'; import { AuthorizationSearchParams } from './authorization-search-params'; import { authorizationFeatureIds, + getSucceededPageOrThrow, oneAuthorizationMatchesFeature, } from './authorization-utils'; import { FeatureID } from './feature-id'; @@ -63,7 +62,6 @@ export class AuthorizationDataService extends BaseDataService imp protected searchByObjectPath = 'object'; private searchData: SearchDataImpl; - private anonymousFeatureIds = new Map> }>(); constructor( protected requestService: RequestService, @@ -82,7 +80,6 @@ export class AuthorizationDataService extends BaseDataService imp * Set all authorization requests to stale */ invalidateAuthorizationsRequestCache() { - this.anonymousFeatureIds.clear(); this.requestService.setStaleByHrefSubstring(this.linkPath); } @@ -117,62 +114,45 @@ export class AuthorizationDataService extends BaseDataService imp * 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. - * Follow every page before deciding a feature is absent. A failed batch (including a custom - * feature throwing on the backend) falls back to the original individual feature check. + * 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), - switchMap((url: string) => { - const readPage = (response$: Observable>>) => response$.pipe( - getFirstCompletedRemoteData(), - map((response) => { - if (!response.hasSucceeded || !Array.isArray(response.payload?.page)) { - throw new Error('Unable to retrieve object authorizations'); - } - return response.payload; - }), - ); - const cacheKey = `${url}|${reRequestOnStale}`; - let cached = useCachedVersionIfAvailable ? this.anonymousFeatureIds.get(cacheKey) : undefined; - if (cached && cached.expiresAt <= Date.now()) { - this.anonymousFeatureIds.delete(cacheKey); - cached = undefined; - } - if (!cached) { - const features = defer(() => readPage(this.searchByObject(undefined, url, undefined, { elementsPerPage: 100 }, - useCachedVersionIfAvailable, reRequestOnStale, followLink('feature')))).pipe( - expand((page) => { - if (!page.next) { - return EMPTY; - } - const next$ = this.findListByHref(page.next, {}, useCachedVersionIfAvailable, reRequestOnStale, followLink('feature')); - this.addDependency(next$, of(url)); - return readPage(next$); - }), - reduce((authorizations, page) => [...authorizations, ...page.page], [] as Authorization[]), - authorizationFeatureIds, - shareReplay({ bufferSize: 1, refCount: false }), - ); - // BaseDataService may leave this unset, in which case RequestService uses its - // 15-minute default response lifetime as well. - cached = { expiresAt: Date.now() + (this.responseMsToLive ?? 15 * 60 * 1000), features }; - if (useCachedVersionIfAvailable) { - this.anonymousFeatureIds.set(cacheKey, cached); - } + // 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; } - return cached.features.pipe( - map((featureIds) => featureIds.has(featureId.valueOf())), - catchError(() => { - if (this.anonymousFeatureIds.get(cacheKey) === cached) { - this.anonymousFeatureIds.delete(cacheKey); - } - return this.checkAuthorization(featureId, url, undefined, useCachedVersionIfAvailable, reRequestOnStale); - }), - ); + const nextPage$ = this.findListByHref(page.next, {}, useCachedVersionIfAvailable, reRequestOnStale, followLink('feature')); + this.addDependency(nextPage$, of(url)); + return nextPage$.pipe(getSucceededPageOrThrow); }), - catchError(() => this.checkAuthorization(featureId, objectUrl, undefined, useCachedVersionIfAvailable, reRequestOnStale)), + // Combine the authorizations of all pages into one list + reduce((authorizations: Authorization[], page: PaginatedList) => [...authorizations, ...page.page], []), ); } diff --git a/src/app/core/data/feature-authorization/authorization-utils.ts b/src/app/core/data/feature-authorization/authorization-utils.ts index 53886c5d4a5..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'; @@ -94,14 +99,40 @@ export const oneAuthorizationMatchesFeature = (featureID: FeatureID) => map((features: Feature[]) => features.filter((feature: Feature) => feature.id === featureID.valueOf()).length > 0), ); -/** Resolve the feature links once and retain their IDs for checking multiple features. */ +/** + * 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 featureLinks = (authorizations || []) + const features$ = (authorizations || []) .filter((authorization: Authorization) => hasValue(authorization.feature)) - .map((authorization: Authorization) => authorization.feature.pipe(getFirstSucceededRemoteDataPayload())); - return featureLinks.length ? observableCombineLatest(featureLinks) : of([]); + .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.id))), + map((features: Feature[]) => new Set(features.map((feature: Feature) => feature.id))), );