Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 15 additions & 0 deletions src/app/core/auth/auth.service.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand Down Expand Up @@ -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();
Expand Down
10 changes: 10 additions & 0 deletions src/app/core/auth/auth.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -86,6 +86,7 @@ import {
getRedirectUrl,
isAuthenticated,
isAuthenticatedLoaded,
isAuthenticationBlocking,
isIdle,
isTokenRefreshing,
} from './selectors';
Expand Down Expand Up @@ -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<boolean> {
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).
Expand Down
Original file line number Diff line number Diff line change
@@ -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';
Expand All @@ -26,6 +28,7 @@ describe('AuthorizationDataService', () => {
let service: AuthorizationDataService;
let siteService: SiteDataService;
let objectCache;
let authService;

let site: Site;
let ePerson: EPerson;
Expand All @@ -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(() => {
Expand All @@ -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);
});

Expand Down Expand Up @@ -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');
});
});
});
});
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand All @@ -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';

/**
Expand All @@ -59,6 +69,7 @@ export class AuthorizationDataService extends BaseDataService<Authorization> imp
protected objectCache: ObjectCacheService,
protected halService: HALEndpointService,
protected siteService: SiteDataService,
protected authService: AuthService,
) {
super('authorizations', requestService, rdbService, objectCache, halService);

Expand All @@ -85,6 +96,70 @@ export class AuthorizationDataService extends BaseDataService<Authorization> imp
* requested after the response becomes stale
*/
isAuthorized(featureId?: FeatureID, objectUrl?: string, ePersonUuid?: string, useCachedVersionIfAvailable = true, reRequestOnStale = true): Observable<boolean> {
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<boolean> {
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<string>) => 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<Authorization[]> {
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<Authorization>) => {
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<Authorization>) => [...authorizations, ...page.page], []),
);
}
Comment thread
bram-atmire marked this conversation as resolved.
Resolved

/**
* 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<boolean> {
return this.searchByObject(featureId, objectUrl, ePersonUuid, {}, useCachedVersionIfAvailable, reRequestOnStale, followLink('feature')).pipe(
getFirstCompletedRemoteData(),
map((authorizationRD) => {
Expand Down
45 changes: 44 additions & 1 deletion src/app/core/data/feature-authorization/authorization-utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand Down Expand Up @@ -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<RemoteData<PaginatedList<Authorization>>>): Observable<PaginatedList<Authorization>> =>
source.pipe(
getFirstCompletedRemoteData(),
map((response: RemoteData<PaginatedList<Authorization>>) => {
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<Authorization[]>): Observable<Set<string>> =>
source.pipe(
switchMap((authorizations: Authorization[]) => {
const features$ = (authorizations || [])
.filter((authorization: Authorization) => hasValue(authorization.feature))
.map((authorization: Authorization) => authorization.feature.pipe(
getFirstCompletedRemoteData(),
map((featureRD: RemoteData<Feature>) => {
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))),
);
Loading
Loading