From 16bbddf0e7f5923bd657447de15cfc8238fb867f Mon Sep 17 00:00:00 2001 From: Cesar Gonzalez Date: Thu, 14 Mar 2024 15:29:37 -0500 Subject: [PATCH 01/16] [PM-6575] Collection of page details might error when getting text content from field sibilings (#8169) --- .../src/autofill/services/collect-autofill-content.service.ts | 3 +++ 1 file changed, 3 insertions(+) diff --git a/apps/browser/src/autofill/services/collect-autofill-content.service.ts b/apps/browser/src/autofill/services/collect-autofill-content.service.ts index f623e0f6c98d..1de801a2c2c5 100644 --- a/apps/browser/src/autofill/services/collect-autofill-content.service.ts +++ b/apps/browser/src/autofill/services/collect-autofill-content.service.ts @@ -755,6 +755,9 @@ class CollectAutofillContentService implements CollectAutofillContentServiceInte // Prioritize capturing text content from elements rather than nodes. currentElement = currentElement.parentElement || currentElement.parentNode; + if (!currentElement) { + return textContentItems; + } let siblingElement = nodeIsElement(currentElement) ? currentElement.previousElementSibling From 4f8fa57b9dc939528fefd16ee060451133f2e5b5 Mon Sep 17 00:00:00 2001 From: Jonathan Prusik Date: Thu, 14 Mar 2024 16:34:07 -0400 Subject: [PATCH 02/16] fix default value for autoCopyTotp (#8287) --- .../common/src/autofill/services/autofill-settings.service.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/libs/common/src/autofill/services/autofill-settings.service.ts b/libs/common/src/autofill/services/autofill-settings.service.ts index 41452c536ca5..49d6dc40de35 100644 --- a/libs/common/src/autofill/services/autofill-settings.service.ts +++ b/libs/common/src/autofill/services/autofill-settings.service.ts @@ -42,7 +42,7 @@ const AUTOFILL_ON_PAGE_LOAD_POLICY_TOAST_HAS_DISPLAYED = new KeyDefinition( ); const AUTO_COPY_TOTP = new KeyDefinition(AUTOFILL_SETTINGS_DISK, "autoCopyTotp", { - deserializer: (value: boolean) => value ?? false, + deserializer: (value: boolean) => value ?? true, }); const INLINE_MENU_VISIBILITY = new KeyDefinition( @@ -144,7 +144,7 @@ export class AutofillSettingsService implements AutofillSettingsServiceAbstracti ); this.autoCopyTotpState = this.stateProvider.getActive(AUTO_COPY_TOTP); - this.autoCopyTotp$ = this.autoCopyTotpState.state$.pipe(map((x) => x ?? false)); + this.autoCopyTotp$ = this.autoCopyTotpState.state$.pipe(map((x) => x ?? true)); this.inlineMenuVisibilityState = this.stateProvider.getGlobal(INLINE_MENU_VISIBILITY); this.inlineMenuVisibility$ = this.inlineMenuVisibilityState.state$.pipe( From 1d76e80afbdc62741667012ae8ef526c7e236ae3 Mon Sep 17 00:00:00 2001 From: Justin Baur <19896123+justindbaur@users.noreply.github.com> Date: Thu, 14 Mar 2024 16:38:22 -0500 Subject: [PATCH 03/16] Refactor State Providers (#8273) * Delete A Lot Of Code * Fix Tests * Create SingleUserState Provider Once * Update Manual Instantiations * Fix Service Factory * Delete More * Delete Unused `updatePromise` * `postStorageSave` -> `doStorageSave` * Update Comment * Fix jslib-services --- .../browser/src/background/main.background.ts | 3 +- .../active-user-state-provider.factory.ts | 16 +- apps/cli/src/bw.ts | 3 +- apps/desktop/src/main.ts | 13 +- .../src/services/jslib-services.module.ts | 2 +- .../services/environment.service.spec.ts | 12 +- ...default-active-user-state.provider.spec.ts | 12 +- .../default-active-user-state.provider.ts | 44 ++--- .../default-active-user-state.spec.ts | 47 +++-- .../default-active-user-state.ts | 173 +++--------------- .../implementations/default-global-state.ts | 116 +----------- .../default-single-user-state.ts | 111 ++--------- .../specific-state.provider.spec.ts | 34 ++-- .../state/implementations/state-base.ts | 109 +++++++++++ 14 files changed, 241 insertions(+), 454 deletions(-) create mode 100644 libs/common/src/platform/state/implementations/state-base.ts diff --git a/apps/browser/src/background/main.background.ts b/apps/browser/src/background/main.background.ts index fd2208fe3c8d..e0dd4e579165 100644 --- a/apps/browser/src/background/main.background.ts +++ b/apps/browser/src/background/main.background.ts @@ -409,8 +409,7 @@ export default class MainBackground { ); this.activeUserStateProvider = new DefaultActiveUserStateProvider( this.accountService, - storageServiceProvider, - stateEventRegistrarService, + this.singleUserStateProvider, ); this.derivedStateProvider = new BackgroundDerivedStateProvider( this.memoryStorageForStateProviders, diff --git a/apps/browser/src/platform/background/service-factories/active-user-state-provider.factory.ts b/apps/browser/src/platform/background/service-factories/active-user-state-provider.factory.ts index 6dafd2952e03..ff46ca84e8c3 100644 --- a/apps/browser/src/platform/background/service-factories/active-user-state-provider.factory.ts +++ b/apps/browser/src/platform/background/service-factories/active-user-state-provider.factory.ts @@ -9,20 +9,15 @@ import { import { CachedServices, FactoryOptions, factory } from "./factory-options"; import { - StateEventRegistrarServiceInitOptions, - stateEventRegistrarServiceFactory, -} from "./state-event-registrar-service.factory"; -import { - StorageServiceProviderInitOptions, - storageServiceProviderFactory, -} from "./storage-service-provider.factory"; + SingleUserStateProviderInitOptions, + singleUserStateProviderFactory, +} from "./single-user-state-provider.factory"; type ActiveUserStateProviderFactory = FactoryOptions; export type ActiveUserStateProviderInitOptions = ActiveUserStateProviderFactory & AccountServiceInitOptions & - StorageServiceProviderInitOptions & - StateEventRegistrarServiceInitOptions; + SingleUserStateProviderInitOptions; export async function activeUserStateProviderFactory( cache: { activeUserStateProvider?: ActiveUserStateProvider } & CachedServices, @@ -35,8 +30,7 @@ export async function activeUserStateProviderFactory( async () => new DefaultActiveUserStateProvider( await accountServiceFactory(cache, opts), - await storageServiceProviderFactory(cache, opts), - await stateEventRegistrarServiceFactory(cache, opts), + await singleUserStateProviderFactory(cache, opts), ), ); } diff --git a/apps/cli/src/bw.ts b/apps/cli/src/bw.ts index 1e624de1b15e..f312c0c37e4c 100644 --- a/apps/cli/src/bw.ts +++ b/apps/cli/src/bw.ts @@ -294,8 +294,7 @@ export class Main { this.activeUserStateProvider = new DefaultActiveUserStateProvider( this.accountService, - storageServiceProvider, - stateEventRegistrarService, + this.singleUserStateProvider, ); this.derivedStateProvider = new DefaultDerivedStateProvider( diff --git a/apps/desktop/src/main.ts b/apps/desktop/src/main.ts index e2c8f9c0ad33..80dfa04c274a 100644 --- a/apps/desktop/src/main.ts +++ b/apps/desktop/src/main.ts @@ -124,13 +124,14 @@ export class Main { storageServiceProvider, ); + const singleUserStateProvider = new DefaultSingleUserStateProvider( + storageServiceProvider, + stateEventRegistrarService, + ); + const stateProvider = new DefaultStateProvider( - new DefaultActiveUserStateProvider( - accountService, - storageServiceProvider, - stateEventRegistrarService, - ), - new DefaultSingleUserStateProvider(storageServiceProvider, stateEventRegistrarService), + new DefaultActiveUserStateProvider(accountService, singleUserStateProvider), + singleUserStateProvider, globalStateProvider, new DefaultDerivedStateProvider(this.memoryStorageForStateProviders), ); diff --git a/libs/angular/src/services/jslib-services.module.ts b/libs/angular/src/services/jslib-services.module.ts index 7aecdccbea32..c5ab77e77b5b 100644 --- a/libs/angular/src/services/jslib-services.module.ts +++ b/libs/angular/src/services/jslib-services.module.ts @@ -954,7 +954,7 @@ const typesafeProviders: Array = [ safeProvider({ provide: ActiveUserStateProvider, useClass: DefaultActiveUserStateProvider, - deps: [AccountServiceAbstraction, StorageServiceProvider, StateEventRegistrarService], + deps: [AccountServiceAbstraction, SingleUserStateProvider], }), safeProvider({ provide: SingleUserStateProvider, diff --git a/libs/common/src/platform/services/environment.service.spec.ts b/libs/common/src/platform/services/environment.service.spec.ts index c55489599459..1454ada72404 100644 --- a/libs/common/src/platform/services/environment.service.spec.ts +++ b/libs/common/src/platform/services/environment.service.spec.ts @@ -45,13 +45,13 @@ describe("EnvironmentService", () => { storageServiceProvider = new StorageServiceProvider(diskStorageService, memoryStorageService); accountService = mockAccountServiceWith(undefined); + const singleUserStateProvider = new DefaultSingleUserStateProvider( + storageServiceProvider, + stateEventRegistrarService, + ); stateProvider = new DefaultStateProvider( - new DefaultActiveUserStateProvider( - accountService, - storageServiceProvider, - stateEventRegistrarService, - ), - new DefaultSingleUserStateProvider(storageServiceProvider, stateEventRegistrarService), + new DefaultActiveUserStateProvider(accountService, singleUserStateProvider), + singleUserStateProvider, new DefaultGlobalStateProvider(storageServiceProvider), new DefaultDerivedStateProvider(memoryStorageService), ); diff --git a/libs/common/src/platform/state/implementations/default-active-user-state.provider.spec.ts b/libs/common/src/platform/state/implementations/default-active-user-state.provider.spec.ts index 023001854928..c1cc15a176f7 100644 --- a/libs/common/src/platform/state/implementations/default-active-user-state.provider.spec.ts +++ b/libs/common/src/platform/state/implementations/default-active-user-state.provider.spec.ts @@ -3,14 +3,12 @@ import { mock } from "jest-mock-extended"; import { mockAccountServiceWith, trackEmissions } from "../../../../spec"; import { AuthenticationStatus } from "../../../auth/enums/authentication-status"; import { UserId } from "../../../types/guid"; -import { StorageServiceProvider } from "../../services/storage-service.provider"; -import { StateEventRegistrarService } from "../state-event-registrar.service"; +import { SingleUserStateProvider } from "../user-state.provider"; import { DefaultActiveUserStateProvider } from "./default-active-user-state.provider"; describe("DefaultActiveUserStateProvider", () => { - const storageServiceProvider = mock(); - const stateEventRegistrarService = mock(); + const singleUserStateProvider = mock(); const userId = "userId" as UserId; const accountInfo = { id: userId, @@ -22,11 +20,7 @@ describe("DefaultActiveUserStateProvider", () => { let sut: DefaultActiveUserStateProvider; beforeEach(() => { - sut = new DefaultActiveUserStateProvider( - accountService, - storageServiceProvider, - stateEventRegistrarService, - ); + sut = new DefaultActiveUserStateProvider(accountService, singleUserStateProvider); }); afterEach(() => { diff --git a/libs/common/src/platform/state/implementations/default-active-user-state.provider.ts b/libs/common/src/platform/state/implementations/default-active-user-state.provider.ts index 268b22e51979..3c12477b798d 100644 --- a/libs/common/src/platform/state/implementations/default-active-user-state.provider.ts +++ b/libs/common/src/platform/state/implementations/default-active-user-state.provider.ts @@ -1,56 +1,40 @@ -import { Observable, map } from "rxjs"; +import { Observable, distinctUntilChanged, map } from "rxjs"; import { AccountService } from "../../../auth/abstractions/account.service"; import { UserId } from "../../../types/guid"; -import { StorageServiceProvider } from "../../services/storage-service.provider"; import { KeyDefinition } from "../key-definition"; -import { StateEventRegistrarService } from "../state-event-registrar.service"; import { UserKeyDefinition, isUserKeyDefinition } from "../user-key-definition"; import { ActiveUserState } from "../user-state"; -import { ActiveUserStateProvider } from "../user-state.provider"; +import { ActiveUserStateProvider, SingleUserStateProvider } from "../user-state.provider"; import { DefaultActiveUserState } from "./default-active-user-state"; export class DefaultActiveUserStateProvider implements ActiveUserStateProvider { - private cache: Record> = {}; - activeUserId$: Observable; constructor( private readonly accountService: AccountService, - private readonly storageServiceProvider: StorageServiceProvider, - private readonly stateEventRegistrarService: StateEventRegistrarService, + private readonly singleUserStateProvider: SingleUserStateProvider, ) { - this.activeUserId$ = this.accountService.activeAccount$.pipe(map((account) => account?.id)); + this.activeUserId$ = this.accountService.activeAccount$.pipe( + map((account) => account?.id), + // To avoid going to storage when we don't need to, only get updates when there is a true change. + distinctUntilChanged((a, b) => (a == null || b == null ? a == b : a === b)), // Treat null and undefined as equal + ); } get(keyDefinition: KeyDefinition | UserKeyDefinition): ActiveUserState { if (!isUserKeyDefinition(keyDefinition)) { keyDefinition = UserKeyDefinition.fromBaseKeyDefinition(keyDefinition); } - const [location, storageService] = this.storageServiceProvider.get( - keyDefinition.stateDefinition.defaultStorageLocation, - keyDefinition.stateDefinition.storageLocationOverrides, - ); - const cacheKey = this.buildCacheKey(location, keyDefinition); - const existingUserState = this.cache[cacheKey]; - if (existingUserState != null) { - // I have to cast out of the unknown generic but this should be safe if rules - // around domain token are made - return existingUserState as ActiveUserState; - } - const newUserState = new DefaultActiveUserState( + // All other providers cache the creation of their corresponding `State` objects, this instance + // doesn't need to do that since it calls `SingleUserStateProvider` it will go through their caching + // layer, because of that, the creation of this instance is quite simple and not worth caching. + return new DefaultActiveUserState( keyDefinition, - this.accountService, - storageService, - this.stateEventRegistrarService, + this.activeUserId$, + this.singleUserStateProvider, ); - this.cache[cacheKey] = newUserState; - return newUserState; - } - - private buildCacheKey(location: string, keyDefinition: UserKeyDefinition) { - return `${location}_${keyDefinition.fullName}`; } } diff --git a/libs/common/src/platform/state/implementations/default-active-user-state.spec.ts b/libs/common/src/platform/state/implementations/default-active-user-state.spec.ts index feb9530987b6..6e01b615d7bf 100644 --- a/libs/common/src/platform/state/implementations/default-active-user-state.spec.ts +++ b/libs/common/src/platform/state/implementations/default-active-user-state.spec.ts @@ -3,19 +3,21 @@ * @jest-environment ../shared/test.environment.ts */ import { any, mock } from "jest-mock-extended"; -import { BehaviorSubject, firstValueFrom, of, timeout } from "rxjs"; +import { BehaviorSubject, firstValueFrom, map, of, timeout } from "rxjs"; import { Jsonify } from "type-fest"; import { awaitAsync, trackEmissions } from "../../../../spec"; import { FakeStorageService } from "../../../../spec/fake-storage.service"; -import { AccountInfo, AccountService } from "../../../auth/abstractions/account.service"; +import { AccountInfo } from "../../../auth/abstractions/account.service"; import { AuthenticationStatus } from "../../../auth/enums/authentication-status"; import { UserId } from "../../../types/guid"; +import { StorageServiceProvider } from "../../services/storage-service.provider"; import { StateDefinition } from "../state-definition"; import { StateEventRegistrarService } from "../state-event-registrar.service"; import { UserKeyDefinition } from "../user-key-definition"; import { DefaultActiveUserState } from "./default-active-user-state"; +import { DefaultSingleUserStateProvider } from "./default-single-user-state.provider"; class TestState { date: Date; @@ -41,25 +43,37 @@ const testKeyDefinition = new UserKeyDefinition(testStateDefinition, }); describe("DefaultActiveUserState", () => { - const accountService = mock(); let diskStorageService: FakeStorageService; + const storageServiceProvider = mock(); const stateEventRegistrarService = mock(); let activeAccountSubject: BehaviorSubject<{ id: UserId } & AccountInfo>; + + let singleUserStateProvider: DefaultSingleUserStateProvider; + let userState: DefaultActiveUserState; beforeEach(() => { + diskStorageService = new FakeStorageService(); + storageServiceProvider.get.mockReturnValue(["disk", diskStorageService]); + + singleUserStateProvider = new DefaultSingleUserStateProvider( + storageServiceProvider, + stateEventRegistrarService, + ); + activeAccountSubject = new BehaviorSubject<{ id: UserId } & AccountInfo>(undefined); - accountService.activeAccount$ = activeAccountSubject; - diskStorageService = new FakeStorageService(); userState = new DefaultActiveUserState( testKeyDefinition, - accountService, - diskStorageService, - stateEventRegistrarService, + activeAccountSubject.asObservable().pipe(map((a) => a?.id)), + singleUserStateProvider, ); }); + afterEach(() => { + jest.resetAllMocks(); + }); + const makeUserId = (id: string) => { return id != null ? (`00000000-0000-1000-a000-00000000000${id}` as UserId) : undefined; }; @@ -223,7 +237,16 @@ describe("DefaultActiveUserState", () => { await changeActiveUser("1"); // This should always return a value right await - const value = await firstValueFrom(userState.state$); + const value = await firstValueFrom( + userState.state$.pipe( + timeout({ + first: 20, + with: () => { + throw new Error("Did not emit data from newly active user."); + }, + }), + ), + ); expect(value).toEqual(user1Data); // Make it such that there is no active user @@ -392,9 +415,7 @@ describe("DefaultActiveUserState", () => { await changeActiveUser(undefined); // Act - // FIXME: Verify that this floating promise is intentional. If it is, add an explanatory comment and ensure there is proper error handling. - // eslint-disable-next-line @typescript-eslint/no-floating-promises - expect(async () => await userState.update(() => null)).rejects.toThrow( + await expect(async () => await userState.update(() => null)).rejects.toThrow( "No active user at this time.", ); }); @@ -563,7 +584,7 @@ describe("DefaultActiveUserState", () => { }); it("does not await updates if the active user changes", async () => { - const initialUserId = (await firstValueFrom(accountService.activeAccount$)).id; + const initialUserId = (await firstValueFrom(activeAccountSubject)).id; expect(initialUserId).toBe(userId); trackEmissions(userState.state$); await awaitAsync(); // storage updates are behind a promise diff --git a/libs/common/src/platform/state/implementations/default-active-user-state.ts b/libs/common/src/platform/state/implementations/default-active-user-state.ts index ae656d836e26..ee90204b617e 100644 --- a/libs/common/src/platform/state/implementations/default-active-user-state.ts +++ b/libs/common/src/platform/state/implementations/default-active-user-state.ts @@ -1,118 +1,27 @@ -import { - Observable, - map, - switchMap, - firstValueFrom, - filter, - timeout, - merge, - share, - ReplaySubject, - timer, - tap, - throwError, - distinctUntilChanged, - withLatestFrom, -} from "rxjs"; +import { Observable, map, switchMap, firstValueFrom, timeout, throwError, NEVER } from "rxjs"; -import { AccountService } from "../../../auth/abstractions/account.service"; import { UserId } from "../../../types/guid"; -import { - AbstractStorageService, - ObservableStorageService, -} from "../../abstractions/storage.service"; -import { StateEventRegistrarService } from "../state-event-registrar.service"; -import { StateUpdateOptions, populateOptionsWithDefault } from "../state-update-options"; +import { StateUpdateOptions } from "../state-update-options"; import { UserKeyDefinition } from "../user-key-definition"; import { ActiveUserState, CombinedState, activeMarker } from "../user-state"; - -import { getStoredValue } from "./util"; - -const FAKE = Symbol("fake"); +import { SingleUserStateProvider } from "../user-state.provider"; export class DefaultActiveUserState implements ActiveUserState { [activeMarker]: true; - private updatePromise: Promise<[UserId, T]> | null = null; - - private activeUserId$: Observable; - combinedState$: Observable>; state$: Observable; constructor( protected keyDefinition: UserKeyDefinition, - private accountService: AccountService, - private chosenStorageLocation: AbstractStorageService & ObservableStorageService, - private stateEventRegistrarService: StateEventRegistrarService, + private activeUserId$: Observable, + private singleUserStateProvider: SingleUserStateProvider, ) { - this.activeUserId$ = this.accountService.activeAccount$.pipe( - // We only care about the UserId but we do want to know about no user as well. - map((a) => a?.id), - // To avoid going to storage when we don't need to, only get updates when there is a true change. - distinctUntilChanged((a, b) => (a == null || b == null ? a == b : a === b)), // Treat null and undefined as equal - ); - - const userChangeAndInitial$ = this.activeUserId$.pipe( - // If the user has changed, we no longer need to lock an update call - // since that call will be for a user that is no longer active. - tap(() => (this.updatePromise = null)), - switchMap(async (userId) => { - // We've switched or started off with no active user. So, - // emit a fake value so that we can fill our share buffer. - if (userId == null) { - return FAKE; - } - - const fullKey = this.keyDefinition.buildKey(userId); - const data = await getStoredValue( - fullKey, - this.chosenStorageLocation, - this.keyDefinition.deserializer, - ); - return [userId, data] as CombinedState; - }), - ); - - const latestStorage$ = this.chosenStorageLocation.updates$.pipe( - // Use withLatestFrom so that we do NOT emit when activeUserId changes because that - // is taken care of above, but we do want to have the latest user id - // when we get a storage update so we can filter the full key - withLatestFrom( - this.activeUserId$.pipe( - // Null userId is already taken care of through the userChange observable above - filter((u) => u != null), - // Take the userId and build the fullKey that we can now create - map((userId) => [userId, this.keyDefinition.buildKey(userId)] as const), - ), + this.combinedState$ = this.activeUserId$.pipe( + switchMap((userId) => + userId != null + ? this.singleUserStateProvider.get(userId, this.keyDefinition).combinedState$ + : NEVER, ), - // Filter to only storage updates that pertain to our key - filter(([storageUpdate, [_userId, fullKey]]) => storageUpdate.key === fullKey), - switchMap(async ([storageUpdate, [userId, fullKey]]) => { - // We can shortcut on updateType of "remove" - // and just emit null. - if (storageUpdate.updateType === "remove") { - return [userId, null] as CombinedState; - } - - return [ - userId, - await getStoredValue( - fullKey, - this.chosenStorageLocation, - this.keyDefinition.deserializer, - ), - ] as CombinedState; - }), - ); - - this.combinedState$ = merge(userChangeAndInitial$, latestStorage$).pipe( - share({ - connector: () => new ReplaySubject | typeof FAKE>(1), - resetOnRefCountZero: () => timer(this.keyDefinition.cleanupDelayMs), - }), - // Filter out FAKE AFTER the share so that we can fill the ReplaySubjects - // buffer with something and avoid emitting when there is no active user. - filter>((d) => d !== (FAKE as unknown)), ); // State should just be combined state without the user id @@ -123,52 +32,17 @@ export class DefaultActiveUserState implements ActiveUserState { configureState: (state: T, dependency: TCombine) => T, options: StateUpdateOptions = {}, ): Promise<[UserId, T]> { - options = populateOptionsWithDefault(options); - try { - if (this.updatePromise != null) { - await this.updatePromise; - } - this.updatePromise = this.internalUpdate(configureState, options); - const [userId, newState] = await this.updatePromise; - return [userId, newState]; - } finally { - this.updatePromise = null; - } - } - - private async internalUpdate( - configureState: (state: T, dependency: TCombine) => T, - options: StateUpdateOptions, - ): Promise<[UserId, T]> { - const [userId, key, currentState] = await this.getStateForUpdate(); - const combinedDependencies = - options.combineLatestWith != null - ? await firstValueFrom(options.combineLatestWith.pipe(timeout(options.msTimeout))) - : null; - - if (!options.shouldUpdate(currentState, combinedDependencies)) { - return [userId, currentState]; - } - - const newState = configureState(currentState, combinedDependencies); - await this.saveToStorage(key, newState); - if (newState != null && currentState == null) { - // Only register this state as something clearable on the first time it saves something - // worth deleting. This is helpful in making sure there is less of a race to adding events. - await this.stateEventRegistrarService.registerEvents(this.keyDefinition); - } - return [userId, newState]; - } - - /** For use in update methods, does not wait for update to complete before yielding state. - * The expectation is that that await is already done - */ - protected async getStateForUpdate() { const userId = await firstValueFrom( this.activeUserId$.pipe( timeout({ first: 1000, - with: () => throwError(() => new Error("Timeout while retrieving active user.")), + with: () => + throwError( + () => + new Error( + `Timeout while retrieving active user for key ${this.keyDefinition.fullName}.`, + ), + ), }), ), ); @@ -177,15 +51,12 @@ export class DefaultActiveUserState implements ActiveUserState { `Error storing ${this.keyDefinition.fullName} for the active user: No active user at this time.`, ); } - const fullKey = this.keyDefinition.buildKey(userId); + return [ userId, - fullKey, - await getStoredValue(fullKey, this.chosenStorageLocation, this.keyDefinition.deserializer), - ] as const; - } - - protected saveToStorage(key: string, data: T): Promise { - return this.chosenStorageLocation.save(key, data); + await this.singleUserStateProvider + .get(userId, this.keyDefinition) + .update(configureState, options), + ]; } } diff --git a/libs/common/src/platform/state/implementations/default-global-state.ts b/libs/common/src/platform/state/implementations/default-global-state.ts index db296194077b..f44d5e26c6e0 100644 --- a/libs/common/src/platform/state/implementations/default-global-state.ts +++ b/libs/common/src/platform/state/implementations/default-global-state.ts @@ -1,120 +1,20 @@ -import { - Observable, - ReplaySubject, - defer, - filter, - firstValueFrom, - merge, - share, - switchMap, - timeout, - timer, -} from "rxjs"; - import { AbstractStorageService, ObservableStorageService, } from "../../abstractions/storage.service"; import { GlobalState } from "../global-state"; import { KeyDefinition, globalKeyBuilder } from "../key-definition"; -import { StateUpdateOptions, populateOptionsWithDefault } from "../state-update-options"; - -import { getStoredValue } from "./util"; -export class DefaultGlobalState implements GlobalState { - private storageKey: string; - private updatePromise: Promise | null = null; - - readonly state$: Observable; +import { StateBase } from "./state-base"; +export class DefaultGlobalState + extends StateBase> + implements GlobalState +{ constructor( - private keyDefinition: KeyDefinition, - private chosenLocation: AbstractStorageService & ObservableStorageService, + keyDefinition: KeyDefinition, + chosenLocation: AbstractStorageService & ObservableStorageService, ) { - this.storageKey = globalKeyBuilder(this.keyDefinition); - const initialStorageGet$ = defer(() => { - return getStoredValue(this.storageKey, this.chosenLocation, this.keyDefinition.deserializer); - }); - - const latestStorage$ = this.chosenLocation.updates$.pipe( - filter((s) => s.key === this.storageKey), - switchMap(async (storageUpdate) => { - if (storageUpdate.updateType === "remove") { - return null; - } - - return await getStoredValue( - this.storageKey, - this.chosenLocation, - this.keyDefinition.deserializer, - ); - }), - ); - - this.state$ = merge(initialStorageGet$, latestStorage$).pipe( - share({ - connector: () => new ReplaySubject(1), - resetOnRefCountZero: () => timer(this.keyDefinition.cleanupDelayMs), - }), - ); - } - - async update( - configureState: (state: T, dependency: TCombine) => T, - options: StateUpdateOptions = {}, - ): Promise { - options = populateOptionsWithDefault(options); - if (this.updatePromise != null) { - await this.updatePromise; - } - - try { - this.updatePromise = this.internalUpdate(configureState, options); - const newState = await this.updatePromise; - return newState; - } finally { - this.updatePromise = null; - } - } - - private async internalUpdate( - configureState: (state: T, dependency: TCombine) => T, - options: StateUpdateOptions, - ): Promise { - const currentState = await this.getStateForUpdate(); - const combinedDependencies = - options.combineLatestWith != null - ? await firstValueFrom(options.combineLatestWith.pipe(timeout(options.msTimeout))) - : null; - - if (!options.shouldUpdate(currentState, combinedDependencies)) { - return currentState; - } - - const newState = configureState(currentState, combinedDependencies); - await this.chosenLocation.save(this.storageKey, newState); - return newState; - } - - /** For use in update methods, does not wait for update to complete before yielding state. - * The expectation is that that await is already done - */ - private async getStateForUpdate() { - return await getStoredValue( - this.storageKey, - this.chosenLocation, - this.keyDefinition.deserializer, - ); - } - - async getFromState(): Promise { - if (this.updatePromise != null) { - return await this.updatePromise; - } - return await getStoredValue( - this.storageKey, - this.chosenLocation, - this.keyDefinition.deserializer, - ); + super(globalKeyBuilder(keyDefinition), chosenLocation, keyDefinition); } } diff --git a/libs/common/src/platform/state/implementations/default-single-user-state.ts b/libs/common/src/platform/state/implementations/default-single-user-state.ts index b01e0958b5c0..fc25e0afbc50 100644 --- a/libs/common/src/platform/state/implementations/default-single-user-state.ts +++ b/libs/common/src/platform/state/implementations/default-single-user-state.ts @@ -1,17 +1,4 @@ -import { - Observable, - ReplaySubject, - combineLatest, - defer, - filter, - firstValueFrom, - merge, - of, - share, - switchMap, - timeout, - timer, -} from "rxjs"; +import { Observable, combineLatest, of } from "rxjs"; import { UserId } from "../../../types/guid"; import { @@ -19,105 +6,31 @@ import { ObservableStorageService, } from "../../abstractions/storage.service"; import { StateEventRegistrarService } from "../state-event-registrar.service"; -import { StateUpdateOptions, populateOptionsWithDefault } from "../state-update-options"; import { UserKeyDefinition } from "../user-key-definition"; import { CombinedState, SingleUserState } from "../user-state"; -import { getStoredValue } from "./util"; - -export class DefaultSingleUserState implements SingleUserState { - private storageKey: string; - private updatePromise: Promise | null = null; +import { StateBase } from "./state-base"; - readonly state$: Observable; +export class DefaultSingleUserState + extends StateBase> + implements SingleUserState +{ readonly combinedState$: Observable>; constructor( readonly userId: UserId, - private keyDefinition: UserKeyDefinition, - private chosenLocation: AbstractStorageService & ObservableStorageService, + keyDefinition: UserKeyDefinition, + chosenLocation: AbstractStorageService & ObservableStorageService, private stateEventRegistrarService: StateEventRegistrarService, ) { - this.storageKey = this.keyDefinition.buildKey(this.userId); - const initialStorageGet$ = defer(() => { - return getStoredValue(this.storageKey, this.chosenLocation, this.keyDefinition.deserializer); - }); - - const latestStorage$ = chosenLocation.updates$.pipe( - filter((s) => s.key === this.storageKey), - switchMap(async (storageUpdate) => { - if (storageUpdate.updateType === "remove") { - return null; - } - - return await getStoredValue( - this.storageKey, - this.chosenLocation, - this.keyDefinition.deserializer, - ); - }), - ); - - this.state$ = merge(initialStorageGet$, latestStorage$).pipe( - share({ - connector: () => new ReplaySubject(1), - resetOnRefCountZero: () => timer(this.keyDefinition.cleanupDelayMs), - }), - ); - + super(keyDefinition.buildKey(userId), chosenLocation, keyDefinition); this.combinedState$ = combineLatest([of(userId), this.state$]); } - async update( - configureState: (state: T, dependency: TCombine) => T, - options: StateUpdateOptions = {}, - ): Promise { - options = populateOptionsWithDefault(options); - if (this.updatePromise != null) { - await this.updatePromise; - } - - try { - this.updatePromise = this.internalUpdate(configureState, options); - const newState = await this.updatePromise; - return newState; - } finally { - this.updatePromise = null; - } - } - - private async internalUpdate( - configureState: (state: T, dependency: TCombine) => T, - options: StateUpdateOptions, - ): Promise { - const currentState = await this.getStateForUpdate(); - const combinedDependencies = - options.combineLatestWith != null - ? await firstValueFrom(options.combineLatestWith.pipe(timeout(options.msTimeout))) - : null; - - if (!options.shouldUpdate(currentState, combinedDependencies)) { - return currentState; - } - - const newState = configureState(currentState, combinedDependencies); - await this.chosenLocation.save(this.storageKey, newState); - if (newState != null && currentState == null) { - // Only register this state as something clearable on the first time it saves something - // worth deleting. This is helpful in making sure there is less of a race to adding events. + protected override async doStorageSave(newState: T, oldState: T): Promise { + await super.doStorageSave(newState, oldState); + if (newState != null && oldState == null) { await this.stateEventRegistrarService.registerEvents(this.keyDefinition); } - return newState; - } - - /** For use in update methods, does not wait for update to complete before yielding state. - * The expectation is that that await is already done - */ - private async getStateForUpdate() { - return await getStoredValue( - this.storageKey, - this.chosenLocation, - this.keyDefinition.deserializer, - ); } } diff --git a/libs/common/src/platform/state/implementations/specific-state.provider.spec.ts b/libs/common/src/platform/state/implementations/specific-state.provider.spec.ts index f3e5ef7f6104..da41908935b6 100644 --- a/libs/common/src/platform/state/implementations/specific-state.provider.spec.ts +++ b/libs/common/src/platform/state/implementations/specific-state.provider.spec.ts @@ -34,11 +34,7 @@ describe("Specific State Providers", () => { storageServiceProvider, stateEventRegistrarService, ); - activeSut = new DefaultActiveUserStateProvider( - mockAccountServiceWith(null), - storageServiceProvider, - stateEventRegistrarService, - ); + activeSut = new DefaultActiveUserStateProvider(mockAccountServiceWith(null), singleSut); globalSut = new DefaultGlobalStateProvider(storageServiceProvider); }); @@ -67,21 +63,25 @@ describe("Specific State Providers", () => { }, ); - describe.each([ + const globalAndSingle = [ + { + getMethod: (keyDefinition: KeyDefinition) => globalSut.get(keyDefinition), + expectedInstance: DefaultGlobalState, + }, { // Use a static user id so that it has the same signature as the rest and then write special tests // handling differing user id getMethod: (keyDefinition: KeyDefinition) => singleSut.get(fakeUser1, keyDefinition), expectedInstance: DefaultSingleUserState, }, + ]; + + describe.each([ { getMethod: (keyDefinition: KeyDefinition) => activeSut.get(keyDefinition), expectedInstance: DefaultActiveUserState, }, - { - getMethod: (keyDefinition: KeyDefinition) => globalSut.get(keyDefinition), - expectedInstance: DefaultGlobalState, - }, + ...globalAndSingle, ])("common behavior %s", ({ getMethod, expectedInstance }) => { it("returns expected instance", () => { const state = getMethod(fakeDiskKeyDefinition); @@ -90,12 +90,6 @@ describe("Specific State Providers", () => { expect(state).toBeInstanceOf(expectedInstance); }); - it("returns cached instance on repeated request", () => { - const stateFirst = getMethod(fakeDiskKeyDefinition); - const stateCached = getMethod(fakeDiskKeyDefinition); - expect(stateFirst).toStrictEqual(stateCached); - }); - it("returns different instances when the storage location differs", () => { const stateDisk = getMethod(fakeDiskKeyDefinition); const stateMemory = getMethod(fakeMemoryKeyDefinition); @@ -115,6 +109,14 @@ describe("Specific State Providers", () => { }); }); + describe.each(globalAndSingle)("Global And Single Behavior", ({ getMethod }) => { + it("returns cached instance on repeated request", () => { + const stateFirst = getMethod(fakeDiskKeyDefinition); + const stateCached = getMethod(fakeDiskKeyDefinition); + expect(stateFirst).toStrictEqual(stateCached); + }); + }); + describe("DefaultSingleUserStateProvider only behavior", () => { const fakeUser2 = "00000000-0000-1000-a000-000000000002" as UserId; diff --git a/libs/common/src/platform/state/implementations/state-base.ts b/libs/common/src/platform/state/implementations/state-base.ts new file mode 100644 index 000000000000..c09771033cc9 --- /dev/null +++ b/libs/common/src/platform/state/implementations/state-base.ts @@ -0,0 +1,109 @@ +import { + Observable, + ReplaySubject, + defer, + filter, + firstValueFrom, + merge, + share, + switchMap, + timeout, + timer, +} from "rxjs"; +import { Jsonify } from "type-fest"; + +import { StorageKey } from "../../../types/state"; +import { + AbstractStorageService, + ObservableStorageService, +} from "../../abstractions/storage.service"; +import { StateUpdateOptions, populateOptionsWithDefault } from "../state-update-options"; + +import { getStoredValue } from "./util"; + +// The parts of a KeyDefinition this class cares about to make it work +type KeyDefinitionRequirements = { + deserializer: (jsonState: Jsonify) => T; + cleanupDelayMs: number; +}; + +export abstract class StateBase> { + private updatePromise: Promise; + + readonly state$: Observable; + + constructor( + protected readonly key: StorageKey, + protected readonly storageService: AbstractStorageService & ObservableStorageService, + protected readonly keyDefinition: KeyDef, + ) { + const storageUpdate$ = storageService.updates$.pipe( + filter((storageUpdate) => storageUpdate.key === key), + switchMap(async (storageUpdate) => { + if (storageUpdate.updateType === "remove") { + return null; + } + + return await getStoredValue(key, storageService, keyDefinition.deserializer); + }), + ); + + this.state$ = merge( + defer(() => getStoredValue(key, storageService, keyDefinition.deserializer)), + storageUpdate$, + ).pipe( + share({ + connector: () => new ReplaySubject(1), + resetOnRefCountZero: () => timer(keyDefinition.cleanupDelayMs), + }), + ); + } + + async update( + configureState: (state: T, dependency: TCombine) => T, + options: StateUpdateOptions = {}, + ): Promise { + options = populateOptionsWithDefault(options); + if (this.updatePromise != null) { + await this.updatePromise; + } + + try { + this.updatePromise = this.internalUpdate(configureState, options); + const newState = await this.updatePromise; + return newState; + } finally { + this.updatePromise = null; + } + } + + private async internalUpdate( + configureState: (state: T, dependency: TCombine) => T, + options: StateUpdateOptions, + ): Promise { + const currentState = await this.getStateForUpdate(); + const combinedDependencies = + options.combineLatestWith != null + ? await firstValueFrom(options.combineLatestWith.pipe(timeout(options.msTimeout))) + : null; + + if (!options.shouldUpdate(currentState, combinedDependencies)) { + return currentState; + } + + const newState = configureState(currentState, combinedDependencies); + await this.doStorageSave(newState, currentState); + return newState; + } + + protected async doStorageSave(newState: T, oldState: T) { + await this.storageService.save(this.key, newState); + } + + /** For use in update methods, does not wait for update to complete before yielding state. + * The expectation is that that await is already done + */ + private async getStateForUpdate() { + return await getStoredValue(this.key, this.storageService, this.keyDefinition.deserializer); + } +} From 550684262300c200d6bcaf4ff958e5955f060c9b Mon Sep 17 00:00:00 2001 From: Thomas Rittson <31796059+eliykat@users.noreply.github.com> Date: Fri, 15 Mar 2024 09:33:15 +1000 Subject: [PATCH 04/16] [AC-2171] Member modal - limit admin access - editing self (#8299) * If editing your own member modal, you cannot add new collections or groups * Update forms to prevent this * Add helper text * Delete unused api method --- .../member-dialog.component.html | 13 ++++- .../member-dialog/member-dialog.component.ts | 48 +++++++++++++++++-- .../access-selector.component.html | 2 +- .../access-selector.component.ts | 5 ++ apps/web/src/locales/en/messages.json | 6 +++ .../organization-user.service.ts | 13 ----- .../organization-user/requests/index.ts | 1 - ...organization-user-update-groups.request.ts | 3 -- ...rganization-user.service.implementation.ts | 15 ------ 9 files changed, 67 insertions(+), 39 deletions(-) delete mode 100644 libs/common/src/admin-console/abstractions/organization-user/requests/organization-user-update-groups.request.ts diff --git a/apps/web/src/app/admin-console/organizations/members/components/member-dialog/member-dialog.component.html b/apps/web/src/app/admin-console/organizations/members/components/member-dialog/member-dialog.component.html index 46d8c6a8671d..95febbd3c5e1 100644 --- a/apps/web/src/app/admin-console/organizations/members/components/member-dialog/member-dialog.component.html +++ b/apps/web/src/app/admin-console/organizations/members/components/member-dialog/member-dialog.component.html @@ -399,7 +399,11 @@

- {{ "groupAccessUserDesc" | i18n }} + {{ + (restrictedAccess$ | async) + ? ("restrictedGroupAccess" | i18n) + : ("groupAccessUserDesc" | i18n) + }}
[selectorLabelText]="'selectGroups' | i18n" [emptySelectionText]="'noGroupsAdded' | i18n" [flexibleCollectionsEnabled]="organization.flexibleCollections" + [hideMultiSelect]="restrictedAccess$ | async" >
-
+
+ {{ "restrictedCollectionAccess" | i18n }} +
+
{{ "userPermissionOverrideHelper" | i18n }}
@@ -441,6 +449,7 @@

[selectorLabelText]="'selectCollections' | i18n" [emptySelectionText]="'noCollectionsAdded' | i18n" [flexibleCollectionsEnabled]="organization.flexibleCollections" + [hideMultiSelect]="restrictedAccess$ | async" > diff --git a/apps/web/src/app/admin-console/organizations/members/components/member-dialog/member-dialog.component.ts b/apps/web/src/app/admin-console/organizations/members/components/member-dialog/member-dialog.component.ts index 4d6442e89889..38ddf013c08a 100644 --- a/apps/web/src/app/admin-console/organizations/members/components/member-dialog/member-dialog.component.ts +++ b/apps/web/src/app/admin-console/organizations/members/components/member-dialog/member-dialog.component.ts @@ -4,6 +4,7 @@ import { FormBuilder, Validators } from "@angular/forms"; import { combineLatest, firstValueFrom, + map, Observable, of, shareReplay, @@ -20,7 +21,9 @@ import { } from "@bitwarden/common/admin-console/enums"; import { PermissionsApi } from "@bitwarden/common/admin-console/models/api/permissions.api"; import { Organization } from "@bitwarden/common/admin-console/models/domain/organization"; +import { AccountService } from "@bitwarden/common/auth/abstractions/account.service"; import { ProductType } from "@bitwarden/common/enums"; +import { FeatureFlag } from "@bitwarden/common/enums/feature-flag.enum"; import { ConfigServiceAbstraction } from "@bitwarden/common/platform/abstractions/config/config.service.abstraction"; import { I18nService } from "@bitwarden/common/platform/abstractions/i18n.service"; import { PlatformUtilsService } from "@bitwarden/common/platform/abstractions/platform-utils.service"; @@ -99,6 +102,8 @@ export class MemberDialogComponent implements OnDestroy { groups: [[] as AccessItemValue[]], }); + protected restrictedAccess$: Observable; + protected permissionsGroup = this.formBuilder.group({ manageAssignedCollectionsGroup: this.formBuilder.group>({ manageAssignedCollections: false, @@ -144,6 +149,7 @@ export class MemberDialogComponent implements OnDestroy { private organizationUserService: OrganizationUserService, private dialogService: DialogService, private configService: ConfigServiceAbstraction, + private accountService: AccountService, organizationService: OrganizationService, ) { this.organization$ = organizationService @@ -162,12 +168,42 @@ export class MemberDialogComponent implements OnDestroy { ), ); + const userDetails$ = this.params.organizationUserId + ? this.userService.get(this.params.organizationId, this.params.organizationUserId) + : of(null); + + // The orgUser cannot manage their own Group assignments if collection access is restricted + // TODO: fix disabled state of access-selector rows so that any controls are hidden + this.restrictedAccess$ = combineLatest([ + this.organization$, + userDetails$, + this.accountService.activeAccount$, + this.configService.getFeatureFlag$(FeatureFlag.FlexibleCollectionsV1), + ]).pipe( + map( + ([organization, userDetails, activeAccount, flexibleCollectionsV1Enabled]) => + // Feature flag conditionals + flexibleCollectionsV1Enabled && + organization.flexibleCollections && + // Business logic conditionals + userDetails.userId == activeAccount.id && + !organization.allowAdminAccessToAllCollectionItems, + ), + shareReplay({ refCount: true, bufferSize: 1 }), + ); + + this.restrictedAccess$.pipe(takeUntil(this.destroy$)).subscribe((restrictedAccess) => { + if (restrictedAccess) { + this.formGroup.controls.groups.disable(); + } else { + this.formGroup.controls.groups.enable(); + } + }); + combineLatest({ organization: this.organization$, collections: this.collectionAdminService.getAll(this.params.organizationId), - userDetails: this.params.organizationUserId - ? this.userService.get(this.params.organizationId, this.params.organizationUserId) - : of(null), + userDetails: userDetails$, groups: groups$, }) .pipe(takeUntil(this.destroy$)) @@ -369,7 +405,11 @@ export class MemberDialogComponent implements OnDestroy { userView.collections = this.formGroup.value.access .filter((v) => v.type === AccessItemType.Collection) .map(convertToSelectionView); - userView.groups = this.formGroup.value.groups.map((m) => m.id); + + userView.groups = (await firstValueFrom(this.restrictedAccess$)) + ? null + : this.formGroup.value.groups.map((m) => m.id); + userView.accessSecretsManager = this.formGroup.value.accessSecretsManager; if (this.editMode) { diff --git a/apps/web/src/app/admin-console/organizations/shared/components/access-selector/access-selector.component.html b/apps/web/src/app/admin-console/organizations/shared/components/access-selector/access-selector.component.html index 5a22b7b22875..16a24781dfaa 100644 --- a/apps/web/src/app/admin-console/organizations/shared/components/access-selector/access-selector.component.html +++ b/apps/web/src/app/admin-console/organizations/shared/components/access-selector/access-selector.component.html @@ -1,6 +1,6 @@ -
+
{{ "permission" | i18n }} getAccessToken/setAccessToken/decodeAccessToken * PM-5263 - TokenSvc State Provider Migrator - WIP - update expected acct type to match actual account * PM-5263 - TokenService - clearToken renamed to clearTokens * PM-5263 - CLI - NodeApiService - add state service dep to get CLI building. * PM-5263 - StateDefinitions - use unique state definition names * PM-5263 - StateSvc - remove getTimeoutBasedStorageOptions as no longer used. * PM-5263 - TokenSvc - Add TODO for figuring out how to store tokens in secure storage. * PM-5263 - StateSvc - remove get/set 2FA token - references migrated later. * PM-5263 - TODO: figure out if using same key definition names is an issue * PM-5263 - TokenServiceStateProviderMigrator written * PM-5263 - TokenServiceStateProviderMigrator - (1) Don't update legacy account if we only added a new state in state provider for 2FA token (2) Use for loop for easier debugging * PM-5263 - TokenServiceStateProviderMigrator test - WIP - migration testing mostly complete and passing. Rollback logic TODO. * PM-5263 - TokenServiceStateProviderMigrator - Add rollback logic to restore 2FA token from users to global. * PM-5263 - TokenServiceStateProviderMigrator - Refactor rollback to only set account once as not necessary to set it every time. * PM-5263 - TokenServiceStateProviderMigrator tests - test all rollback scenarios * PM-5263 - Remove TODO as don't need unique key def names as long as state def keys are unique. * PM-5263 - TokenSvc - update clearAccessTokenByUserId to use proper state provider helper method to set state. * PM-5263 - Revert accidentally committing settings.json changes. * PM-5263 - TokenSvc - update all 2FA token methods to require email so we can user specifically scope 2FA tokens while still storing them in global storage. * PM-5263 - Update all token service 2FA set / get / clear methods to pass in email. * PM-5263 - JslibServices module - add missed login service to login strategy svc deps. * PM-5263 - VaultTimeoutSettingsService - setVaultTimeoutOptions - rename token to accesToken for clarity. * PM-5263 - (1) TokenSvc - remove getAccessTokenByUserId and force consumers to use getAccessToken w/ optional user id to keep interface small (2) TokenSvc - attempt to implement secure storage on platforms that support it for access & refresh token storage (3) StateSvc - replace usage of getAccessTokenByUserId with getAccessToken * PM-5263 - TokenSvc - add platform utils and secure storage svc deps * PM-5263 - TODO: figure out what to do with broken migration * PM-5263 - TODO: update tests in light of latest 2FA token changes. * PM-5263 - TokenSvc - clean up TODO * PM-5263 - We should have tests for the token service. * PM-5263 - TokenSvc - setAccessToken - If platform supports secure storage and we are saving an access token, remove the access token from memory and disk to fully migrate to secure storage. * PM-5263 - TokenSvc - getAccessToken - Update logic to look at memory and disk first always and secure storage last to support the secure storage migration * PM-5263 - TokenSvc - setAccesToken - if user id null on a secure storage supporting platform, throw error. * PM-5263 - TokenService - (1) Refresh token now stored in secure storage (2) Refresh token set now private as we require a user id to store it in secure storage and we can use the setTokens method to enforce always setting the access token and refresh token together in order to extract a user id from the refresh token. (3) setTokens clientIdClientSecret param now optional * PM-5263 - TokenServiceStateProviderMigrator - update migration to take global but user scoped 2FA token storage changes into account. * PM-5263 - Remove old migration as it references state we are removing. Bump min version. Co-authored-by: Matt Gibson * PM-5263 - TokenService - 2FA token methods now backed by global state record which maps email to individual tokens. * PM-5263 - WIP on Token Svc migrator and test updates based on new 2FA token storage changes. * PM-5263 - TokenSvc - (1) Add jira tickets to clean up state migration (2) Add state to track secure storage migration to improve # of reads to get data * PM-5263 - StateDef - consolidate name of token domain state defs per feedback from Justin + update migration tests * PM-5263 - TokenSvc - fix error message and add TODO * PM-5263 - Update token service migration + tests to pass after all 2FA token changes. * PM-5263 - Fix all login strategy tests which were failing due to token state provider changes + the addition of the loginService as a dependency in the base login strategy. * PM-5263 - Register TokenService state provider migration with migrator * PM-5263 - TokenSvc state migration - set tokens after initializing account * PM-5263 - TokenService changes - WIP - convert from ActiveUserStateProvider to just SingleUserStateProvider to avoid future circ dependency issues. Co-authored-by: Jake Fink * PM-5263 - TokenSvc - create getSecureStorageOptions for centralizing all logic for getting data out of SecureStorage. * PM-5263 - TokenSvc - (1) Refactor determineStorageLocation to also determine secure storage - created a TokenStorageLocation string enum to remove magic strings (2) Refactor setAccessToken to use switch (3) Refactor clearAccessTokenByUserId to clear all locations and not early return on secure storage b/c we only use secure storage if disk is the location but I don't want to require vault timeout data for this method. * PM-5263 - TokenSvc - getDataFromSecureStorage - Refactor to be more generic for easier re-use * PM-5263 - TokenSvc - Convert refresh token methods to use single user state and require user ids * PM-5263 - VaultTimeoutSettingsSvc - get user id and pass to access and refresh token methods. * PM-5263 - TokenSvc - refactor save secure storage logic into private helper. * PM-5263 - Base Login Strategy - per discussion with Justin, move save of tokens to before account initialization as we can always derive the user id from the access token. This will ensure that the account is initialized with the proper authN status. * PM-5263 - TokenSvc - latest refactor - update all methods to accept optional userId now as we can read active user id from global state provider without using activeUserStateProvider (thus, avoiding a circular dep and having to have every method accept in a mandatory user id). * PM-5263 - VaultTimeoutSettingsService - remove user id from token calls * PM-5263 - TokenSvc - update all places we instantiate token service to properly pass in new deps. * PM-5263 - TokenSvc migration is now 27th instead of 23rd. * PM-5263 - Browser - MainContextMenuHandler - Update service options to include PlatformUtilsServiceInitOptions as the TokenService requires that and the TokenService is now injected on the StateService * PM-5263 - TokenSvc migration test - update rollback tests to start with correct current version * PM-5263 - Create token service test file - WIP * PM-5263 - TokenSvc - tests WIP - instantiates working. * PM-5263 - TokenSvc - set2FAToken - use null coalesce to ensure record is instantiated for new users before setting data on it. * PM-5263 - TokenService tests - WIP - 2FA token tests. * PM-5263 - Worked with Justin to resolve desktop circular dependency issue by adding SUPPORTS_SECURE_STORAGE injection token instead of injecting PlatformUtilsService directly into TokenService. Co-authored-by: Justin Baur <19896123+justindbaur@users.noreply.github.com> * PM-5263 - TokenSvc tests - WIP - (1) Update TokenSvc instantiation to use new supportsSecureStorage (2) Test TwoFactorToken methods * PM-5263 - Fix SUPPORTS_SECURE_STORAGE injection token to properly call supportsSecureStorage message * PM-5263 - Token state testing * PM-5263 - TokenState fix name of describe * PM-5263 - TokenService - export TokenStorageLocation for use in tests. * PM-5263 - TokenSvc Tests WIP * PM-5263 - TokenSvc tests - access token logic mostly completed. * PM-5263 - TokenSvc Tests - more WIP - finish testing access token methods. * PM-5263 - TokenSvc WIP - another clear access token test. * PM-5263 - TokenSvc tests - WIP - SetTokens tested. * PM-5263 - Tweak test name * PM-5263 - TokenSvc tests - remove unnecessary describe around 2FA token methods. * PM-5263 - TokenSvc.clearAccessTokenByUserId renamed to just clearAccessToken * PM-5263 - TokenSvc - refactor clearTokens logic and implement individual clear logic which doesn't require vault timeout setting information. * PM-5263 - TokenSvc - Replace all places we have vaultTimeout: number with vaultTimeout: number | null to be accurate. * PM-5263 - TokenSvc.clearTokens - add check for user id; throw if not found * PM-5263 - TokenService - test clearTokens * PM-5263 - TokenSvc Tests - setRefreshToken tested * PM-5263 - TokenSvc tests - getRefreshToken tested + added a new getAccessToken test * PM-5263 - TokenSvc - ClearRefreshToken scenarios tested. * PM-5263 - TokenSvc.clearRefreshToken tests - fix copy pasta * PM-5263 - TokenSvc tests - (1) Fix mistakes in refresh token testing (2) Test setClientId for all scenarios * PM-5263 - TokenSvc tests - (1) Add some getClientId tests (2) clarify lack of awaits * PM-5263 - TokenSvc Tests - WIP - getClientId && clearClientId * PM-5263 - TokenService - getClientSecret - fix error message * PM-5263 - TokenService tests - test all client secret methods * PM-5263 - Update TokenSvc migration to 30th migration * PM-5263 - TokenService - update all tests to initialize data to undefined now that fake state provider supports faking data based on specific key definitions. * PM-5263 - (1) TokenSvc.decodeAccessToken - update static method's error handling (2) TokenSvc tests - test all decodeAccessToken scenarios * PM-5263 - TokenSvc - (1) Add DecodedAccessToken type (2) Refactor getTokenExpirationDate logic to use new type and make proper type checks for numbers for exp claim values. * PM-5263 - TokenSvc tests - test getTokenExpirationDate method. * PM-5263 - TokenSvc - (1) Update DecodedAccessToken docs (2) Tweak naming in tokenSecondsRemaining * PM-5263 - TokenSvc abstraction - add jsdoc for tokenSecondsRemaining * PM-5263 - TokenSvc tests - test tokenSecondsRemaining * PM-5263 - TokenSvc - DecodedAccessToken type - update sstamp info * PM-5263 - TokenService - fix flaky tokenSecondsRemaining tests by locking time * PM-5263 - TokenSvc Tests - Test tokenNeedsRefresh * PM-5263 - (1) TokenSvc - Refactor getUserId to add extra safety (2) TokenSvc tests - test getUserId * PM-5263 - (1) TokenSvc - refactor getUserIdFromAccessToken to handle decoding errors (2) TokenSvc tests - test getUserIdFromAccessToken * PM-5263 - (1) TokenSvc - Refactor getEmail to handle decoding errors + check for specific, expected type (2) TokenSvc tests - test getEmail * PM-5263 - TokenSvc tests - clean up comment * PM-5263 - (1) TokenSvc - getEmailVerified - refactor (2) TokenSvc tests - add getEmailVerified tests * PM-5263 - (1) TokenSvc - refactor getName (2) TokenSvc tests - test getName * PM-5263 - (1) TokenSvc - refactor getIssuer (2) TokenSvc tests - test getIssuer * PM-5263 - TokenSvc - remove unnecessary "as type" statements now that we have a decoded access token type * PM-5263 - (1) TokenSvc - refactor getIsExternal (2) TokenSvc Tests - test getIsExternal * PM-5263 - TokenSvc abstraction - tune up rest of docs. * PM-5263 - TokenSvc - clean up promise and replace with promise * PM-5263 - TokenSvc abstraction - more docs. * PM-5263 - Clean up TODO as I've tested every method in token svc. * PM-5263 - (1) Extract JWT decode logic into auth owned utility function out of the token service (2) Update TokenService decode logic to use new utility function (3) Update LastPassDirectImportService + vault.ts to use new utility function and remove token service dependency. (4) Update tests + migrate tests to new utility test file. * PM-5263 - Rename decodeJwtTokenToJson to decode-jwt-token-to-json to meet lint rules excluding capitals * PM-5263 - TokenSvc + tests - fix all get methods to return undefined like they did before instead of throwing an error if a user id isn't provided. * PM-5263 - Services.module - add missing token service dep * PM-5263 - Update token svc migrations to be 32nd migration * PM-5263 - Popup - Services.module - Remove token service as it no longer requires a background service due to the migration to state provider. The service definition in jslib-services module is enough. * PM-5263 - BaseLoginStrategy - Extract email out of getTwoFactorToken method call for easier debugging. * PM-5263 - Login Comp - Set email into memory on login service so that base login strategy can access user email for looking up 2FA token stored in global state. * PM-5263 - (1) LoginComp - remove loginSvc.setEmail call as no longer necessary + introduced issues w/ popup and background in browser extension (2) AuthReq & Password login strategies now just pass in email to buildTwoFactor method. * PM-5263 - SsoLoginSvc + abstraction - Add key definition and get/set methods for saving user email in session storage so it persists across the SSO redirect. * PM-5263 - Base Login Strategy - BuildTwoFactor - only try to get 2FA token if we have an email to look up their token * PM-5263 - Remove LoginService dependency from LoginStrategyService * PM-5263 - (1) Save off user email when they click enterprise SSO on all clients in login comp (2) Retrieve it and pass it into login strategy in SSO comp * PM-5263 - (1) TokenSvc - update 2FA token methods to be more safe in case user removes record from local storage (2) Add test cases + missing clearTwoFactorToken tests * PM-5263 - Browser SSO login - save user email for browser SSO process * PM-5263 - Finish removing login service from login strategy tests. * PM-5263 - More removals of the login service from the login strategy tests. * PM-5263 - Main.ts - platformUtilsSvc no longer used in TokenSvc so remove it from desktop main.ts * PM-5263 - Fix failing login strategy service tests * PM-5263 - Bump token svc migration values to migration 35 after merging in main * PM-5263 - Bump token svc migration version * PM-5263 - TokenService.clearTwoFactorToken - use delete instead of setting values to null per discussion with Justin Co-authored-by: Justin Baur <19896123+justindbaur@users.noreply.github.com> * PM-5263 - TokenSvc + decode JWT token tests - anonymize my information Co-authored-by: Justin Baur <19896123+justindbaur@users.noreply.github.com> * PM-5263 - TokenSvc tests - update clear token tests based on actual deletion * PM-5263 - Add docs per PR feedback * PM-5263 - (1) Move ownership of clearing two factor token on rejection from server to base login strategy (2) Each login strategy that supports remember 2FA logic now persists user entered email in its data (3) Base login strategy processTwoFactorResponse now clears 2FA token (4) Updated base login strategy tests to affirm the clearing of the 2FA token * Update libs/auth/src/common/login-strategies/login.strategy.ts Co-authored-by: Jake Fink * Update libs/auth/src/common/login-strategies/password-login.strategy.ts Co-authored-by: Jake Fink * PM-5263 - Login Strategy - per PR feedback, add jsdoc comments to each method I've touched for this PR. * PM-5263 - (1) TokenSvc - adjust setTokens, setAccessToken, setRefreshToken, and clearRefreshToken based on PR feedback to remove optional user ids where possible and improve public interface (2) TokenSvc Abstraction - update docs and abstractions based on removed user ids and changed logic (3) TokenSvc tests - update tests to add new test cases, remove no longer relevant ones, and update test names. * PM-5263 - Bump migrations again --------- Co-authored-by: Matt Gibson Co-authored-by: Jake Fink Co-authored-by: Justin Baur <19896123+justindbaur@users.noreply.github.com> Co-authored-by: Jake Fink --- .../token-service.factory.ts | 32 +- .../browser/src/auth/popup/login.component.ts | 2 + .../browser/main-context-menu-handler.ts | 5 + .../browser/src/background/main.background.ts | 26 +- .../service-factories/api-service.factory.ts | 5 +- .../state-service.factory.ts | 6 + .../services/browser-state.service.spec.ts | 4 + .../services/browser-state.service.ts | 3 + .../src/popup/services/services.module.ts | 4 +- apps/cli/src/auth/commands/login.command.ts | 1 + apps/cli/src/bw.ts | 10 +- .../src/platform/services/node-api.service.ts | 3 + .../src/app/services/services.module.ts | 15 +- apps/desktop/src/main.ts | 20 +- .../electron-platform-utils.service.ts | 4 +- apps/web/src/app/core/state/state.service.ts | 3 + .../src/auth/components/login.component.ts | 4 + .../src/auth/components/sso.component.ts | 3 + libs/angular/src/services/injection-tokens.ts | 1 + .../src/services/jslib-services.module.ts | 16 +- libs/auth/src/common/index.ts | 1 + .../auth-request-login.strategy.spec.ts | 2 +- .../auth-request-login.strategy.ts | 2 +- .../login-strategies/login.strategy.spec.ts | 22 +- .../common/login-strategies/login.strategy.ts | 84 +- .../password-login.strategy.spec.ts | 2 +- .../password-login.strategy.ts | 7 +- .../sso-login.strategy.spec.ts | 2 +- .../login-strategies/sso-login.strategy.ts | 9 +- .../user-api-login.strategy.spec.ts | 20 +- .../user-api-login.strategy.ts | 17 +- .../webauthn-login.strategy.spec.ts | 2 +- .../common/models/domain/login-credentials.ts | 5 + .../login-strategy.service.spec.ts | 4 +- .../decode-jwt-token-to-json.utility.spec.ts | 90 + .../decode-jwt-token-to-json.utility.ts | 32 + libs/auth/src/common/utilities/index.ts | 1 + .../sso-login.service.abstraction.ts | 14 + .../src/auth/abstractions/token.service.ts | 213 +- .../src/auth/services/sso-login.service.ts | 20 +- .../src/auth/services/token.service.spec.ts | 2237 +++++++++++++++++ .../common/src/auth/services/token.service.ts | 771 +++++- .../src/auth/services/token.state.spec.ts | 64 + libs/common/src/auth/services/token.state.ts | 65 + .../platform/abstractions/state.service.ts | 11 +- .../src/platform/models/domain/account.ts | 4 - .../src/platform/services/state.service.ts | 96 +- .../src/platform/state/state-definitions.ts | 5 + libs/common/src/services/api.service.ts | 26 +- .../vault-timeout-settings.service.ts | 13 +- libs/common/src/state-migrations/migrate.ts | 10 +- .../migrations/3-fix-premium.spec.ts | 111 - .../migrations/3-fix-premium.ts | 48 - ...igrate-token-svc-to-state-provider.spec.ts | 258 ++ .../38-migrate-token-svc-to-state-provider.ts | 231 ++ .../lastpass-direct-import.service.ts | 4 +- .../src/importers/lastpass/access/vault.ts | 9 +- 57 files changed, 4242 insertions(+), 437 deletions(-) create mode 100644 libs/auth/src/common/utilities/decode-jwt-token-to-json.utility.spec.ts create mode 100644 libs/auth/src/common/utilities/decode-jwt-token-to-json.utility.ts create mode 100644 libs/auth/src/common/utilities/index.ts create mode 100644 libs/common/src/auth/services/token.service.spec.ts create mode 100644 libs/common/src/auth/services/token.state.spec.ts create mode 100644 libs/common/src/auth/services/token.state.ts delete mode 100644 libs/common/src/state-migrations/migrations/3-fix-premium.spec.ts delete mode 100644 libs/common/src/state-migrations/migrations/3-fix-premium.ts create mode 100644 libs/common/src/state-migrations/migrations/38-migrate-token-svc-to-state-provider.spec.ts create mode 100644 libs/common/src/state-migrations/migrations/38-migrate-token-svc-to-state-provider.ts diff --git a/apps/browser/src/auth/background/service-factories/token-service.factory.ts b/apps/browser/src/auth/background/service-factories/token-service.factory.ts index 476b8e2d7858..25c30460f06d 100644 --- a/apps/browser/src/auth/background/service-factories/token-service.factory.ts +++ b/apps/browser/src/auth/background/service-factories/token-service.factory.ts @@ -7,13 +7,29 @@ import { factory, } from "../../../platform/background/service-factories/factory-options"; import { - stateServiceFactory, - StateServiceInitOptions, -} from "../../../platform/background/service-factories/state-service.factory"; + GlobalStateProviderInitOptions, + globalStateProviderFactory, +} from "../../../platform/background/service-factories/global-state-provider.factory"; +import { + PlatformUtilsServiceInitOptions, + platformUtilsServiceFactory, +} from "../../../platform/background/service-factories/platform-utils-service.factory"; +import { + SingleUserStateProviderInitOptions, + singleUserStateProviderFactory, +} from "../../../platform/background/service-factories/single-user-state-provider.factory"; +import { + SecureStorageServiceInitOptions, + secureStorageServiceFactory, +} from "../../../platform/background/service-factories/storage-service.factory"; type TokenServiceFactoryOptions = FactoryOptions; -export type TokenServiceInitOptions = TokenServiceFactoryOptions & StateServiceInitOptions; +export type TokenServiceInitOptions = TokenServiceFactoryOptions & + SingleUserStateProviderInitOptions & + GlobalStateProviderInitOptions & + PlatformUtilsServiceInitOptions & + SecureStorageServiceInitOptions; export function tokenServiceFactory( cache: { tokenService?: AbstractTokenService } & CachedServices, @@ -23,6 +39,12 @@ export function tokenServiceFactory( cache, "tokenService", opts, - async () => new TokenService(await stateServiceFactory(cache, opts)), + async () => + new TokenService( + await singleUserStateProviderFactory(cache, opts), + await globalStateProviderFactory(cache, opts), + (await platformUtilsServiceFactory(cache, opts)).supportsSecureStorage(), + await secureStorageServiceFactory(cache, opts), + ), ); } diff --git a/apps/browser/src/auth/popup/login.component.ts b/apps/browser/src/auth/popup/login.component.ts index 857dae663067..c1dd9526589b 100644 --- a/apps/browser/src/auth/popup/login.component.ts +++ b/apps/browser/src/auth/popup/login.component.ts @@ -91,6 +91,8 @@ export class LoginComponent extends BaseLoginComponent { } async launchSsoBrowser() { + // Save off email for SSO + await this.ssoLoginService.setSsoEmail(this.formGroup.value.email); await this.loginService.saveEmailSettings(); // Generate necessary sso params const passwordOptions: any = { diff --git a/apps/browser/src/autofill/browser/main-context-menu-handler.ts b/apps/browser/src/autofill/browser/main-context-menu-handler.ts index 998b5c7258b6..b7e26be4a9c4 100644 --- a/apps/browser/src/autofill/browser/main-context-menu-handler.ts +++ b/apps/browser/src/autofill/browser/main-context-menu-handler.ts @@ -184,6 +184,11 @@ export class MainContextMenuHandler { stateServiceOptions: { stateFactory: stateFactory, }, + platformUtilsServiceOptions: { + clipboardWriteCallback: () => Promise.resolve(), + biometricCallback: () => Promise.resolve(false), + win: self, + }, }; return new MainContextMenuHandler( diff --git a/apps/browser/src/background/main.background.ts b/apps/browser/src/background/main.background.ts index 34a5f9e1fd89..23f415fc4182 100644 --- a/apps/browser/src/background/main.background.ts +++ b/apps/browser/src/background/main.background.ts @@ -427,6 +427,21 @@ export default class MainBackground { ); this.biometricStateService = new DefaultBiometricStateService(this.stateProvider); + this.userNotificationSettingsService = new UserNotificationSettingsService(this.stateProvider); + this.platformUtilsService = new BackgroundPlatformUtilsService( + this.messagingService, + (clipboardValue, clearMs) => this.clearClipboard(clipboardValue, clearMs), + async () => this.biometricUnlock(), + self, + ); + + this.tokenService = new TokenService( + this.singleUserStateProvider, + this.globalStateProvider, + this.platformUtilsService.supportsSecureStorage(), + this.secureStorageService, + ); + const migrationRunner = new MigrationRunner( this.storageService, this.logService, @@ -441,15 +456,9 @@ export default class MainBackground { new StateFactory(GlobalState, Account), this.accountService, this.environmentService, + this.tokenService, migrationRunner, ); - this.userNotificationSettingsService = new UserNotificationSettingsService(this.stateProvider); - this.platformUtilsService = new BackgroundPlatformUtilsService( - this.messagingService, - (clipboardValue, clearMs) => this.clearClipboard(clipboardValue, clearMs), - async () => this.biometricUnlock(), - self, - ); const themeStateService = new DefaultThemeStateService(this.globalStateProvider); @@ -465,13 +474,14 @@ export default class MainBackground { this.stateProvider, this.biometricStateService, ); - this.tokenService = new TokenService(this.stateService); + this.appIdService = new AppIdService(this.globalStateProvider); this.apiService = new ApiService( this.tokenService, this.platformUtilsService, this.environmentService, this.appIdService, + this.stateService, (expired: boolean) => this.logout(expired), ); this.domainSettingsService = new DefaultDomainSettingsService(this.stateProvider); diff --git a/apps/browser/src/platform/background/service-factories/api-service.factory.ts b/apps/browser/src/platform/background/service-factories/api-service.factory.ts index 649fe1f7fe69..57cd50044136 100644 --- a/apps/browser/src/platform/background/service-factories/api-service.factory.ts +++ b/apps/browser/src/platform/background/service-factories/api-service.factory.ts @@ -20,6 +20,7 @@ import { PlatformUtilsServiceInitOptions, platformUtilsServiceFactory, } from "./platform-utils-service.factory"; +import { stateServiceFactory, StateServiceInitOptions } from "./state-service.factory"; type ApiServiceFactoryOptions = FactoryOptions & { apiServiceOptions: { @@ -32,7 +33,8 @@ export type ApiServiceInitOptions = ApiServiceFactoryOptions & TokenServiceInitOptions & PlatformUtilsServiceInitOptions & EnvironmentServiceInitOptions & - AppIdServiceInitOptions; + AppIdServiceInitOptions & + StateServiceInitOptions; export function apiServiceFactory( cache: { apiService?: AbstractApiService } & CachedServices, @@ -48,6 +50,7 @@ export function apiServiceFactory( await platformUtilsServiceFactory(cache, opts), await environmentServiceFactory(cache, opts), await appIdServiceFactory(cache, opts), + await stateServiceFactory(cache, opts), opts.apiServiceOptions.logoutCallback, opts.apiServiceOptions.customUserAgent, ), diff --git a/apps/browser/src/platform/background/service-factories/state-service.factory.ts b/apps/browser/src/platform/background/service-factories/state-service.factory.ts index 8bcb65a3209f..20a9ac074a70 100644 --- a/apps/browser/src/platform/background/service-factories/state-service.factory.ts +++ b/apps/browser/src/platform/background/service-factories/state-service.factory.ts @@ -5,6 +5,10 @@ import { accountServiceFactory, AccountServiceInitOptions, } from "../../../auth/background/service-factories/account-service.factory"; +import { + tokenServiceFactory, + TokenServiceInitOptions, +} from "../../../auth/background/service-factories/token-service.factory"; import { Account } from "../../../models/account"; import { BrowserStateService } from "../../services/browser-state.service"; @@ -38,6 +42,7 @@ export type StateServiceInitOptions = StateServiceFactoryOptions & LogServiceInitOptions & AccountServiceInitOptions & EnvironmentServiceInitOptions & + TokenServiceInitOptions & MigrationRunnerInitOptions; export async function stateServiceFactory( @@ -57,6 +62,7 @@ export async function stateServiceFactory( opts.stateServiceOptions.stateFactory, await accountServiceFactory(cache, opts), await environmentServiceFactory(cache, opts), + await tokenServiceFactory(cache, opts), await migrationRunnerFactory(cache, opts), opts.stateServiceOptions.useAccountCache, ), diff --git a/apps/browser/src/platform/services/browser-state.service.spec.ts b/apps/browser/src/platform/services/browser-state.service.spec.ts index b5d1b9c38a0f..3069b8f1749b 100644 --- a/apps/browser/src/platform/services/browser-state.service.spec.ts +++ b/apps/browser/src/platform/services/browser-state.service.spec.ts @@ -1,5 +1,6 @@ import { mock, MockProxy } from "jest-mock-extended"; +import { TokenService } from "@bitwarden/common/auth/abstractions/token.service"; import { EnvironmentService } from "@bitwarden/common/platform/abstractions/environment.service"; import { LogService } from "@bitwarden/common/platform/abstractions/log.service"; import { @@ -32,6 +33,7 @@ describe("Browser State Service", () => { let stateFactory: MockProxy>; let useAccountCache: boolean; let environmentService: MockProxy; + let tokenService: MockProxy; let migrationRunner: MockProxy; let state: State; @@ -46,6 +48,7 @@ describe("Browser State Service", () => { logService = mock(); stateFactory = mock(); environmentService = mock(); + tokenService = mock(); migrationRunner = mock(); // turn off account cache for tests useAccountCache = false; @@ -77,6 +80,7 @@ describe("Browser State Service", () => { stateFactory, accountService, environmentService, + tokenService, migrationRunner, useAccountCache, ); diff --git a/apps/browser/src/platform/services/browser-state.service.ts b/apps/browser/src/platform/services/browser-state.service.ts index c544915e26cf..f7ee74be2179 100644 --- a/apps/browser/src/platform/services/browser-state.service.ts +++ b/apps/browser/src/platform/services/browser-state.service.ts @@ -1,6 +1,7 @@ import { BehaviorSubject } from "rxjs"; import { AccountService } from "@bitwarden/common/auth/abstractions/account.service"; +import { TokenService } from "@bitwarden/common/auth/abstractions/token.service"; import { EnvironmentService } from "@bitwarden/common/platform/abstractions/environment.service"; import { LogService } from "@bitwarden/common/platform/abstractions/log.service"; import { @@ -45,6 +46,7 @@ export class BrowserStateService stateFactory: StateFactory, accountService: AccountService, environmentService: EnvironmentService, + tokenService: TokenService, migrationRunner: MigrationRunner, useAccountCache = true, ) { @@ -56,6 +58,7 @@ export class BrowserStateService stateFactory, accountService, environmentService, + tokenService, migrationRunner, useAccountCache, ); diff --git a/apps/browser/src/popup/services/services.module.ts b/apps/browser/src/popup/services/services.module.ts index 5f97b5788249..0e9cee5c671c 100644 --- a/apps/browser/src/popup/services/services.module.ts +++ b/apps/browser/src/popup/services/services.module.ts @@ -233,7 +233,6 @@ function getBgService(service: keyof MainBackground) { deps: [], }, { provide: TotpService, useFactory: getBgService("totpService"), deps: [] }, - { provide: TokenService, useFactory: getBgService("tokenService"), deps: [] }, { provide: I18nServiceAbstraction, useFactory: (globalStateProvider: GlobalStateProvider) => { @@ -445,6 +444,7 @@ function getBgService(service: keyof MainBackground) { logService: LogServiceAbstraction, accountService: AccountServiceAbstraction, environmentService: EnvironmentService, + tokenService: TokenService, migrationRunner: MigrationRunner, ) => { return new BrowserStateService( @@ -455,6 +455,7 @@ function getBgService(service: keyof MainBackground) { new StateFactory(GlobalState, Account), accountService, environmentService, + tokenService, migrationRunner, ); }, @@ -465,6 +466,7 @@ function getBgService(service: keyof MainBackground) { LogServiceAbstraction, AccountServiceAbstraction, EnvironmentService, + TokenService, MigrationRunner, ], }, diff --git a/apps/cli/src/auth/commands/login.command.ts b/apps/cli/src/auth/commands/login.command.ts index 75e6479dc048..97c0974ac666 100644 --- a/apps/cli/src/auth/commands/login.command.ts +++ b/apps/cli/src/auth/commands/login.command.ts @@ -203,6 +203,7 @@ export class LoginCommand { ssoCodeVerifier, this.ssoRedirectUri, orgIdentifier, + undefined, // email to look up 2FA token not required as CLI can't remember 2FA token twoFactor, ), ); diff --git a/apps/cli/src/bw.ts b/apps/cli/src/bw.ts index f312c0c37e4c..8e3b60e270f7 100644 --- a/apps/cli/src/bw.ts +++ b/apps/cli/src/bw.ts @@ -310,6 +310,13 @@ export class Main { this.environmentService = new EnvironmentService(this.stateProvider, this.accountService); + this.tokenService = new TokenService( + this.singleUserStateProvider, + this.globalStateProvider, + this.platformUtilsService.supportsSecureStorage(), + this.secureStorageService, + ); + const migrationRunner = new MigrationRunner( this.storageService, this.logService, @@ -324,6 +331,7 @@ export class Main { new StateFactory(GlobalState, Account), this.accountService, this.environmentService, + this.tokenService, migrationRunner, ); @@ -341,7 +349,6 @@ export class Main { ); this.appIdService = new AppIdService(this.globalStateProvider); - this.tokenService = new TokenService(this.stateService); const customUserAgent = "Bitwarden_CLI/" + @@ -354,6 +361,7 @@ export class Main { this.platformUtilsService, this.environmentService, this.appIdService, + this.stateService, async (expired: boolean) => await this.logout(), customUserAgent, ); diff --git a/apps/cli/src/platform/services/node-api.service.ts b/apps/cli/src/platform/services/node-api.service.ts index d95e9d7d85e9..9099fd276038 100644 --- a/apps/cli/src/platform/services/node-api.service.ts +++ b/apps/cli/src/platform/services/node-api.service.ts @@ -6,6 +6,7 @@ import { TokenService } from "@bitwarden/common/auth/abstractions/token.service" import { AppIdService } from "@bitwarden/common/platform/abstractions/app-id.service"; import { EnvironmentService } from "@bitwarden/common/platform/abstractions/environment.service"; import { PlatformUtilsService } from "@bitwarden/common/platform/abstractions/platform-utils.service"; +import { StateService } from "@bitwarden/common/platform/abstractions/state.service"; import { ApiService } from "@bitwarden/common/services/api.service"; (global as any).fetch = fe.default; @@ -20,6 +21,7 @@ export class NodeApiService extends ApiService { platformUtilsService: PlatformUtilsService, environmentService: EnvironmentService, appIdService: AppIdService, + stateService: StateService, logoutCallback: (expired: boolean) => Promise, customUserAgent: string = null, ) { @@ -28,6 +30,7 @@ export class NodeApiService extends ApiService { platformUtilsService, environmentService, appIdService, + stateService, logoutCallback, customUserAgent, ); diff --git a/apps/desktop/src/app/services/services.module.ts b/apps/desktop/src/app/services/services.module.ts index 2b103b8d715d..3a8457da7a6b 100644 --- a/apps/desktop/src/app/services/services.module.ts +++ b/apps/desktop/src/app/services/services.module.ts @@ -10,6 +10,7 @@ import { OBSERVABLE_MEMORY_STORAGE, OBSERVABLE_DISK_STORAGE, WINDOW, + SUPPORTS_SECURE_STORAGE, SYSTEM_THEME_OBSERVABLE, } from "@bitwarden/angular/services/injection-tokens"; import { JslibServicesModule } from "@bitwarden/angular/services/jslib-services.module"; @@ -18,6 +19,7 @@ import { PolicyService as PolicyServiceAbstraction } from "@bitwarden/common/adm import { AccountService as AccountServiceAbstraction } from "@bitwarden/common/auth/abstractions/account.service"; import { AuthService as AuthServiceAbstraction } from "@bitwarden/common/auth/abstractions/auth.service"; import { LoginService as LoginServiceAbstraction } from "@bitwarden/common/auth/abstractions/login.service"; +import { TokenService } from "@bitwarden/common/auth/abstractions/token.service"; import { LoginService } from "@bitwarden/common/auth/services/login.service"; import { AutofillSettingsServiceAbstraction } from "@bitwarden/common/autofill/services/autofill-settings.service"; import { BroadcasterService as BroadcasterServiceAbstraction } from "@bitwarden/common/platform/abstractions/broadcaster.service"; @@ -54,7 +56,10 @@ import { LoginGuard } from "../../auth/guards/login.guard"; import { Account } from "../../models/account"; import { ElectronCryptoService } from "../../platform/services/electron-crypto.service"; import { ElectronLogRendererService } from "../../platform/services/electron-log.renderer.service"; -import { ElectronPlatformUtilsService } from "../../platform/services/electron-platform-utils.service"; +import { + ELECTRON_SUPPORTS_SECURE_STORAGE, + ElectronPlatformUtilsService, +} from "../../platform/services/electron-platform-utils.service"; import { ElectronRendererMessagingService } from "../../platform/services/electron-renderer-messaging.service"; import { ElectronRendererSecureStorageService } from "../../platform/services/electron-renderer-secure-storage.service"; import { ElectronRendererStorageService } from "../../platform/services/electron-renderer-storage.service"; @@ -101,6 +106,13 @@ const RELOAD_CALLBACK = new InjectionToken<() => any>("RELOAD_CALLBACK"); useClass: ElectronPlatformUtilsService, deps: [I18nServiceAbstraction, MessagingServiceAbstraction], }, + { + // We manually override the value of SUPPORTS_SECURE_STORAGE here to avoid + // the TokenService having to inject the PlatformUtilsService which introduces a + // circular dependency on Desktop only. + provide: SUPPORTS_SECURE_STORAGE, + useValue: ELECTRON_SUPPORTS_SECURE_STORAGE, + }, { provide: I18nServiceAbstraction, useClass: I18nRendererService, @@ -140,6 +152,7 @@ const RELOAD_CALLBACK = new InjectionToken<() => any>("RELOAD_CALLBACK"); STATE_FACTORY, AccountServiceAbstraction, EnvironmentService, + TokenService, MigrationRunner, STATE_SERVICE_USE_CACHE, ], diff --git a/apps/desktop/src/main.ts b/apps/desktop/src/main.ts index 80dfa04c274a..0b92fab894eb 100644 --- a/apps/desktop/src/main.ts +++ b/apps/desktop/src/main.ts @@ -2,7 +2,9 @@ import * as path from "path"; import { app } from "electron"; +import { TokenService as TokenServiceAbstraction } from "@bitwarden/common/auth/abstractions/token.service"; import { AccountServiceImplementation } from "@bitwarden/common/auth/services/account.service"; +import { TokenService } from "@bitwarden/common/auth/services/token.service"; import { StateService } from "@bitwarden/common/platform/abstractions/state.service"; import { DefaultBiometricStateService } from "@bitwarden/common/platform/biometrics/biometric-state.service"; import { StateFactory } from "@bitwarden/common/platform/factories/state-factory"; @@ -36,6 +38,7 @@ import { ClipboardMain } from "./platform/main/clipboard.main"; import { DesktopCredentialStorageListener } from "./platform/main/desktop-credential-storage-listener"; import { MainCryptoFunctionService } from "./platform/main/main-crypto-function.service"; import { ElectronLogMainService } from "./platform/services/electron-log.main.service"; +import { ELECTRON_SUPPORTS_SECURE_STORAGE } from "./platform/services/electron-platform-utils.service"; import { ElectronStateService } from "./platform/services/electron-state.service"; import { ElectronStorageService } from "./platform/services/electron-storage.service"; import { I18nMainService } from "./platform/services/i18n.main.service"; @@ -53,6 +56,7 @@ export class Main { mainCryptoFunctionService: MainCryptoFunctionService; desktopCredentialStorageListener: DesktopCredentialStorageListener; migrationRunner: MigrationRunner; + tokenService: TokenServiceAbstraction; windowMain: WindowMain; messagingMain: MessagingMain; @@ -129,8 +133,13 @@ export class Main { stateEventRegistrarService, ); + const activeUserStateProvider = new DefaultActiveUserStateProvider( + accountService, + singleUserStateProvider, + ); + const stateProvider = new DefaultStateProvider( - new DefaultActiveUserStateProvider(accountService, singleUserStateProvider), + activeUserStateProvider, singleUserStateProvider, globalStateProvider, new DefaultDerivedStateProvider(this.memoryStorageForStateProviders), @@ -138,6 +147,13 @@ export class Main { this.environmentService = new EnvironmentService(stateProvider, accountService); + this.tokenService = new TokenService( + singleUserStateProvider, + globalStateProvider, + ELECTRON_SUPPORTS_SECURE_STORAGE, + this.storageService, + ); + this.migrationRunner = new MigrationRunner( this.storageService, this.logService, @@ -155,6 +171,7 @@ export class Main { new StateFactory(GlobalState, Account), accountService, // will not broadcast logouts. This is a hack until we can remove messaging dependency this.environmentService, + this.tokenService, this.migrationRunner, false, // Do not use disk caching because this will get out of sync with the renderer service ); @@ -176,6 +193,7 @@ export class Main { this.messagingService = new ElectronMainMessagingService(this.windowMain, (message) => { this.messagingMain.onMessage(message); }); + this.powerMonitorMain = new PowerMonitorMain(this.messagingService); this.menuMain = new MenuMain( this.i18nService, diff --git a/apps/desktop/src/platform/services/electron-platform-utils.service.ts b/apps/desktop/src/platform/services/electron-platform-utils.service.ts index 5f117ba678c2..2d50712dfb68 100644 --- a/apps/desktop/src/platform/services/electron-platform-utils.service.ts +++ b/apps/desktop/src/platform/services/electron-platform-utils.service.ts @@ -8,6 +8,8 @@ import { import { ClipboardWriteMessage } from "../types/clipboard"; +export const ELECTRON_SUPPORTS_SECURE_STORAGE = true; + export class ElectronPlatformUtilsService implements PlatformUtilsService { constructor( protected i18nService: I18nService, @@ -142,7 +144,7 @@ export class ElectronPlatformUtilsService implements PlatformUtilsService { } supportsSecureStorage(): boolean { - return true; + return ELECTRON_SUPPORTS_SECURE_STORAGE; } getAutofillKeyboardShortcut(): Promise { diff --git a/apps/web/src/app/core/state/state.service.ts b/apps/web/src/app/core/state/state.service.ts index 1ad3bd25c317..a80384d17987 100644 --- a/apps/web/src/app/core/state/state.service.ts +++ b/apps/web/src/app/core/state/state.service.ts @@ -7,6 +7,7 @@ import { STATE_SERVICE_USE_CACHE, } from "@bitwarden/angular/services/injection-tokens"; import { AccountService } from "@bitwarden/common/auth/abstractions/account.service"; +import { TokenService } from "@bitwarden/common/auth/abstractions/token.service"; import { EnvironmentService } from "@bitwarden/common/platform/abstractions/environment.service"; import { LogService } from "@bitwarden/common/platform/abstractions/log.service"; import { @@ -33,6 +34,7 @@ export class StateService extends BaseStateService { @Inject(STATE_FACTORY) stateFactory: StateFactory, accountService: AccountService, environmentService: EnvironmentService, + tokenService: TokenService, migrationRunner: MigrationRunner, @Inject(STATE_SERVICE_USE_CACHE) useAccountCache = true, ) { @@ -44,6 +46,7 @@ export class StateService extends BaseStateService { stateFactory, accountService, environmentService, + tokenService, migrationRunner, useAccountCache, ); diff --git a/libs/angular/src/auth/components/login.component.ts b/libs/angular/src/auth/components/login.component.ts index 8314bdb2dcc6..0ed1fd1dfe82 100644 --- a/libs/angular/src/auth/components/login.component.ts +++ b/libs/angular/src/auth/components/login.component.ts @@ -149,6 +149,7 @@ export class LoginComponent extends CaptchaProtectedComponent implements OnInit, this.captchaToken, null, ); + this.formPromise = this.loginStrategyService.logIn(credentials); const response = await this.formPromise; this.setFormValues(); @@ -302,6 +303,9 @@ export class LoginComponent extends CaptchaProtectedComponent implements OnInit, async saveEmailSettings() { this.setFormValues(); await this.loginService.saveEmailSettings(); + + // Save off email for SSO + await this.ssoLoginService.setSsoEmail(this.formGroup.value.email); } // Legacy accounts used the master key to encrypt data. Migration is required diff --git a/libs/angular/src/auth/components/sso.component.ts b/libs/angular/src/auth/components/sso.component.ts index 2f50288f048c..a5a08f9aefab 100644 --- a/libs/angular/src/auth/components/sso.component.ts +++ b/libs/angular/src/auth/components/sso.component.ts @@ -182,11 +182,14 @@ export class SsoComponent { private async logIn(code: string, codeVerifier: string, orgSsoIdentifier: string): Promise { this.loggingIn = true; try { + const email = await this.ssoLoginService.getSsoEmail(); + const credentials = new SsoLoginCredentials( code, codeVerifier, this.redirectUri, orgSsoIdentifier, + email, ); this.formPromise = this.loginStrategyService.logIn(credentials); const authResult = await this.formPromise; diff --git a/libs/angular/src/services/injection-tokens.ts b/libs/angular/src/services/injection-tokens.ts index 50aafc232605..7d39078797e7 100644 --- a/libs/angular/src/services/injection-tokens.ts +++ b/libs/angular/src/services/injection-tokens.ts @@ -42,6 +42,7 @@ export const LOGOUT_CALLBACK = new SafeInjectionToken< export const LOCKED_CALLBACK = new SafeInjectionToken<(userId?: string) => Promise>( "LOCKED_CALLBACK", ); +export const SUPPORTS_SECURE_STORAGE = new SafeInjectionToken("SUPPORTS_SECURE_STORAGE"); export const LOCALES_DIRECTORY = new SafeInjectionToken("LOCALES_DIRECTORY"); export const SYSTEM_LANGUAGE = new SafeInjectionToken("SYSTEM_LANGUAGE"); export const LOG_MAC_FAILURES = new SafeInjectionToken("LOG_MAC_FAILURES"); diff --git a/libs/angular/src/services/jslib-services.module.ts b/libs/angular/src/services/jslib-services.module.ts index c5ab77e77b5b..58d614bb9cc3 100644 --- a/libs/angular/src/services/jslib-services.module.ts +++ b/libs/angular/src/services/jslib-services.module.ts @@ -250,6 +250,7 @@ import { SECURE_STORAGE, STATE_FACTORY, STATE_SERVICE_USE_CACHE, + SUPPORTS_SECURE_STORAGE, SYSTEM_LANGUAGE, SYSTEM_THEME_OBSERVABLE, WINDOW, @@ -272,6 +273,12 @@ const typesafeProviders: Array = [ useFactory: (i18nService: I18nServiceAbstraction) => i18nService.translationLocale, deps: [I18nServiceAbstraction], }), + safeProvider({ + provide: SUPPORTS_SECURE_STORAGE, + useFactory: (platformUtilsService: PlatformUtilsServiceAbstraction) => + platformUtilsService.supportsSecureStorage(), + deps: [PlatformUtilsServiceAbstraction], + }), safeProvider({ provide: LOCALES_DIRECTORY, useValue: "./locales", @@ -475,7 +482,12 @@ const typesafeProviders: Array = [ safeProvider({ provide: TokenServiceAbstraction, useClass: TokenService, - deps: [StateServiceAbstraction], + deps: [ + SingleUserStateProvider, + GlobalStateProvider, + SUPPORTS_SECURE_STORAGE, + AbstractStorageService, + ], }), safeProvider({ provide: KeyGenerationServiceAbstraction, @@ -519,6 +531,7 @@ const typesafeProviders: Array = [ PlatformUtilsServiceAbstraction, EnvironmentServiceAbstraction, AppIdServiceAbstraction, + StateServiceAbstraction, LOGOUT_CALLBACK, ], }), @@ -621,6 +634,7 @@ const typesafeProviders: Array = [ STATE_FACTORY, AccountServiceAbstraction, EnvironmentServiceAbstraction, + TokenServiceAbstraction, MigrationRunner, STATE_SERVICE_USE_CACHE, ], diff --git a/libs/auth/src/common/index.ts b/libs/auth/src/common/index.ts index f70f8be2153e..936666e1a818 100644 --- a/libs/auth/src/common/index.ts +++ b/libs/auth/src/common/index.ts @@ -4,3 +4,4 @@ export * from "./abstractions"; export * from "./models"; export * from "./services"; +export * from "./utilities"; diff --git a/libs/auth/src/common/login-strategies/auth-request-login.strategy.spec.ts b/libs/auth/src/common/login-strategies/auth-request-login.strategy.spec.ts index dd046195aae9..6a045a8f623f 100644 --- a/libs/auth/src/common/login-strategies/auth-request-login.strategy.spec.ts +++ b/libs/auth/src/common/login-strategies/auth-request-login.strategy.spec.ts @@ -67,7 +67,7 @@ describe("AuthRequestLoginStrategy", () => { tokenService.getTwoFactorToken.mockResolvedValue(null); appIdService.getAppId.mockResolvedValue(deviceId); - tokenService.decodeToken.mockResolvedValue({}); + tokenService.decodeAccessToken.mockResolvedValue({}); authRequestLoginStrategy = new AuthRequestLoginStrategy( cache, diff --git a/libs/auth/src/common/login-strategies/auth-request-login.strategy.ts b/libs/auth/src/common/login-strategies/auth-request-login.strategy.ts index acf21219c206..01a2c970776c 100644 --- a/libs/auth/src/common/login-strategies/auth-request-login.strategy.ts +++ b/libs/auth/src/common/login-strategies/auth-request-login.strategy.ts @@ -79,7 +79,7 @@ export class AuthRequestLoginStrategy extends LoginStrategy { credentials.email, credentials.accessCode, null, - await this.buildTwoFactor(credentials.twoFactor), + await this.buildTwoFactor(credentials.twoFactor, credentials.email), await this.buildDeviceRequest(), ); data.tokenRequest.setAuthRequestAccessCode(credentials.authRequestId); diff --git a/libs/auth/src/common/login-strategies/login.strategy.spec.ts b/libs/auth/src/common/login-strategies/login.strategy.spec.ts index 5771cb2543f6..a9938bd39c4f 100644 --- a/libs/auth/src/common/login-strategies/login.strategy.spec.ts +++ b/libs/auth/src/common/login-strategies/login.strategy.spec.ts @@ -14,6 +14,7 @@ import { IdentityTokenResponse } from "@bitwarden/common/auth/models/response/id import { IdentityTwoFactorResponse } from "@bitwarden/common/auth/models/response/identity-two-factor.response"; import { MasterPasswordPolicyResponse } from "@bitwarden/common/auth/models/response/master-password-policy.response"; import { IUserDecryptionOptionsServerResponse } from "@bitwarden/common/auth/models/response/user-decryption-options/user-decryption-options.response"; +import { VaultTimeoutAction } from "@bitwarden/common/enums/vault-timeout-action.enum"; import { AppIdService } from "@bitwarden/common/platform/abstractions/app-id.service"; import { CryptoService } from "@bitwarden/common/platform/abstractions/crypto.service"; import { LogService } from "@bitwarden/common/platform/abstractions/log.service"; @@ -123,11 +124,12 @@ describe("LoginStrategy", () => { logService = mock(); stateService = mock(); twoFactorService = mock(); + policyService = mock(); passwordStrengthService = mock(); appIdService.getAppId.mockResolvedValue(deviceId); - tokenService.decodeToken.calledWith(accessToken).mockResolvedValue(decodedToken); + tokenService.decodeAccessToken.calledWith(accessToken).mockResolvedValue(decodedToken); // The base class is abstract so we test it via PasswordLoginStrategy passwordLoginStrategy = new PasswordLoginStrategy( @@ -167,8 +169,21 @@ describe("LoginStrategy", () => { const idTokenResponse = identityTokenResponseFactory(); apiService.postIdentityToken.mockResolvedValue(idTokenResponse); + const mockVaultTimeoutAction = VaultTimeoutAction.Lock; + const mockVaultTimeout = 1000; + + stateService.getVaultTimeoutAction.mockResolvedValue(mockVaultTimeoutAction); + stateService.getVaultTimeout.mockResolvedValue(mockVaultTimeout); + await passwordLoginStrategy.logIn(credentials); + expect(tokenService.setTokens).toHaveBeenCalledWith( + accessToken, + refreshToken, + mockVaultTimeoutAction, + mockVaultTimeout, + ); + expect(stateService.addAccount).toHaveBeenCalledWith( new Account({ profile: { @@ -184,10 +199,6 @@ describe("LoginStrategy", () => { }, tokens: { ...new AccountTokens(), - ...{ - accessToken: accessToken, - refreshToken: refreshToken, - }, }, keys: new AccountKeys(), decryptionOptions: AccountDecryptionOptions.fromResponse(idTokenResponse), @@ -299,6 +310,7 @@ describe("LoginStrategy", () => { expect(stateService.addAccount).not.toHaveBeenCalled(); expect(messagingService.send).not.toHaveBeenCalled(); + expect(tokenService.clearTwoFactorToken).toHaveBeenCalled(); const expected = new AuthResult(); expected.twoFactorProviders = new Map(); diff --git a/libs/auth/src/common/login-strategies/login.strategy.ts b/libs/auth/src/common/login-strategies/login.strategy.ts index e6ff1c68a38c..c6d441af2367 100644 --- a/libs/auth/src/common/login-strategies/login.strategy.ts +++ b/libs/auth/src/common/login-strategies/login.strategy.ts @@ -16,6 +16,7 @@ import { IdentityCaptchaResponse } from "@bitwarden/common/auth/models/response/ import { IdentityTokenResponse } from "@bitwarden/common/auth/models/response/identity-token.response"; import { IdentityTwoFactorResponse } from "@bitwarden/common/auth/models/response/identity-two-factor.response"; import { ClientType } from "@bitwarden/common/enums"; +import { VaultTimeoutAction } from "@bitwarden/common/enums/vault-timeout-action.enum"; import { KeysRequest } from "@bitwarden/common/models/request/keys.request"; import { AppIdService } from "@bitwarden/common/platform/abstractions/app-id.service"; import { CryptoService } from "@bitwarden/common/platform/abstractions/crypto.service"; @@ -49,6 +50,9 @@ export abstract class LoginStrategyData { | SsoTokenRequest | WebAuthnLoginTokenRequest; captchaBypassToken?: string; + + /** User's entered email obtained pre-login. */ + abstract userEnteredEmail?: string; } export abstract class LoginStrategy { @@ -110,21 +114,47 @@ export abstract class LoginStrategy { return new DeviceRequest(appId, this.platformUtilsService); } - protected async buildTwoFactor(userProvidedTwoFactor?: TokenTwoFactorRequest) { + /** + * Builds the TokenTwoFactorRequest to be used within other login strategies token requests + * to the server. + * If the user provided a 2FA token in an already created TokenTwoFactorRequest, it will be used. + * If not, and the user has previously remembered a 2FA token, it will be used. + * If neither of these are true, an empty TokenTwoFactorRequest will be returned. + * @param userProvidedTwoFactor - optional - The 2FA token request provided by the caller + * @param email - optional - ensure that email is provided for any login strategies that support remember 2FA functionality + * @returns a promise which resolves to a TokenTwoFactorRequest to be sent to the server + */ + protected async buildTwoFactor( + userProvidedTwoFactor?: TokenTwoFactorRequest, + email?: string, + ): Promise { if (userProvidedTwoFactor != null) { return userProvidedTwoFactor; } - const storedTwoFactorToken = await this.tokenService.getTwoFactorToken(); - if (storedTwoFactorToken != null) { - return new TokenTwoFactorRequest(TwoFactorProviderType.Remember, storedTwoFactorToken, false); + if (email) { + const storedTwoFactorToken = await this.tokenService.getTwoFactorToken(email); + if (storedTwoFactorToken != null) { + return new TokenTwoFactorRequest( + TwoFactorProviderType.Remember, + storedTwoFactorToken, + false, + ); + } } return new TokenTwoFactorRequest(); } - protected async saveAccountInformation(tokenResponse: IdentityTokenResponse) { - const accountInformation = await this.tokenService.decodeToken(tokenResponse.accessToken); + /** + * Initializes the account with information from the IdTokenResponse after successful login. + * It also sets the access token and refresh token in the token service. + * + * @param {IdentityTokenResponse} tokenResponse - The response from the server containing the identity token. + * @returns {Promise} - A promise that resolves when the account information has been successfully saved. + */ + protected async saveAccountInformation(tokenResponse: IdentityTokenResponse): Promise { + const accountInformation = await this.tokenService.decodeAccessToken(tokenResponse.accessToken); // Must persist existing device key if it exists for trusted device decryption to work // However, we must provide a user id so that the device key can be retrieved @@ -141,6 +171,18 @@ export abstract class LoginStrategy { // If you don't persist existing admin auth requests on login, they will get deleted. const adminAuthRequest = await this.stateService.getAdminAuthRequest({ userId }); + const vaultTimeoutAction = await this.stateService.getVaultTimeoutAction(); + const vaultTimeout = await this.stateService.getVaultTimeout(); + + // set access token and refresh token before account initialization so authN status can be accurate + // User id will be derived from the access token. + await this.tokenService.setTokens( + tokenResponse.accessToken, + tokenResponse.refreshToken, + vaultTimeoutAction as VaultTimeoutAction, + vaultTimeout, + ); + await this.stateService.addAccount( new Account({ profile: { @@ -158,10 +200,6 @@ export abstract class LoginStrategy { }, tokens: { ...new AccountTokens(), - ...{ - accessToken: tokenResponse.accessToken, - refreshToken: tokenResponse.refreshToken, - }, }, keys: accountKeys, decryptionOptions: AccountDecryptionOptions.fromResponse(tokenResponse), @@ -193,7 +231,10 @@ export abstract class LoginStrategy { await this.saveAccountInformation(response); if (response.twoFactorToken != null) { - await this.tokenService.setTwoFactorToken(response); + // note: we can read email from access token b/c it was saved in saveAccountInformation + const userEmail = await this.tokenService.getEmail(); + + await this.tokenService.setTwoFactorToken(userEmail, response.twoFactorToken); } await this.setMasterKey(response); @@ -226,7 +267,18 @@ export abstract class LoginStrategy { } } + /** + * Handles the response from the server when a 2FA is required. + * It clears any existing 2FA token, as it's no longer valid, and sets up the necessary data for the 2FA process. + * + * @param {IdentityTwoFactorResponse} response - The response from the server indicating that 2FA is required. + * @returns {Promise} - A promise that resolves to an AuthResult object + */ private async processTwoFactorResponse(response: IdentityTwoFactorResponse): Promise { + // If we get a 2FA required response, then we should clear the 2FA token + // just in case as it is no longer valid. + await this.clearTwoFactorToken(); + const result = new AuthResult(); result.twoFactorProviders = response.twoFactorProviders2; @@ -237,6 +289,16 @@ export abstract class LoginStrategy { return result; } + /** + * Clears the 2FA token from the token service using the user's email if it exists + */ + private async clearTwoFactorToken() { + const email = this.cache.value.userEnteredEmail; + if (email) { + await this.tokenService.clearTwoFactorToken(email); + } + } + private async processCaptchaResponse(response: IdentityCaptchaResponse): Promise { const result = new AuthResult(); result.captchaSiteKey = response.siteKey; diff --git a/libs/auth/src/common/login-strategies/password-login.strategy.spec.ts b/libs/auth/src/common/login-strategies/password-login.strategy.spec.ts index 77ef6792ba05..1ab908ac9e0f 100644 --- a/libs/auth/src/common/login-strategies/password-login.strategy.spec.ts +++ b/libs/auth/src/common/login-strategies/password-login.strategy.spec.ts @@ -81,7 +81,7 @@ describe("PasswordLoginStrategy", () => { passwordStrengthService = mock(); appIdService.getAppId.mockResolvedValue(deviceId); - tokenService.decodeToken.mockResolvedValue({}); + tokenService.decodeAccessToken.mockResolvedValue({}); loginStrategyService.makePreloginKey.mockResolvedValue(masterKey); diff --git a/libs/auth/src/common/login-strategies/password-login.strategy.ts b/libs/auth/src/common/login-strategies/password-login.strategy.ts index c12eb28204ba..2c99c243e07c 100644 --- a/libs/auth/src/common/login-strategies/password-login.strategy.ts +++ b/libs/auth/src/common/login-strategies/password-login.strategy.ts @@ -32,6 +32,10 @@ import { LoginStrategy, LoginStrategyData } from "./login.strategy"; export class PasswordLoginStrategyData implements LoginStrategyData { tokenRequest: PasswordTokenRequest; + + /** User's entered email obtained pre-login. Always present in MP login. */ + userEnteredEmail: string; + captchaBypassToken?: string; /** * The local version of the user's master key hash @@ -105,6 +109,7 @@ export class PasswordLoginStrategy extends LoginStrategy { const data = new PasswordLoginStrategyData(); data.masterKey = await this.loginStrategyService.makePreloginKey(masterPassword, email); + data.userEnteredEmail = email; // Hash the password early (before authentication) so we don't persist it in memory in plaintext data.localMasterKeyHash = await this.cryptoService.hashMasterKey( @@ -118,7 +123,7 @@ export class PasswordLoginStrategy extends LoginStrategy { email, masterKeyHash, captchaToken, - await this.buildTwoFactor(twoFactor), + await this.buildTwoFactor(twoFactor, email), await this.buildDeviceRequest(), ); diff --git a/libs/auth/src/common/login-strategies/sso-login.strategy.spec.ts b/libs/auth/src/common/login-strategies/sso-login.strategy.spec.ts index b6cf6db58a0f..9946a6141f72 100644 --- a/libs/auth/src/common/login-strategies/sso-login.strategy.spec.ts +++ b/libs/auth/src/common/login-strategies/sso-login.strategy.spec.ts @@ -71,7 +71,7 @@ describe("SsoLoginStrategy", () => { tokenService.getTwoFactorToken.mockResolvedValue(null); appIdService.getAppId.mockResolvedValue(deviceId); - tokenService.decodeToken.mockResolvedValue({}); + tokenService.decodeAccessToken.mockResolvedValue({}); ssoLoginStrategy = new SsoLoginStrategy( null, diff --git a/libs/auth/src/common/login-strategies/sso-login.strategy.ts b/libs/auth/src/common/login-strategies/sso-login.strategy.ts index a5ef92220480..6b88a92f7013 100644 --- a/libs/auth/src/common/login-strategies/sso-login.strategy.ts +++ b/libs/auth/src/common/login-strategies/sso-login.strategy.ts @@ -29,6 +29,10 @@ import { LoginStrategyData, LoginStrategy } from "./login.strategy"; export class SsoLoginStrategyData implements LoginStrategyData { captchaBypassToken: string; tokenRequest: SsoTokenRequest; + /** + * User's entered email obtained pre-login. Present in most SSO flows, but not CLI + SSO Flow. + */ + userEnteredEmail?: string; /** * User email address. Only available after authentication. */ @@ -105,11 +109,14 @@ export class SsoLoginStrategy extends LoginStrategy { async logIn(credentials: SsoLoginCredentials) { const data = new SsoLoginStrategyData(); data.orgId = credentials.orgId; + + data.userEnteredEmail = credentials.email; + data.tokenRequest = new SsoTokenRequest( credentials.code, credentials.codeVerifier, credentials.redirectUrl, - await this.buildTwoFactor(credentials.twoFactor), + await this.buildTwoFactor(credentials.twoFactor, credentials.email), await this.buildDeviceRequest(), ); diff --git a/libs/auth/src/common/login-strategies/user-api-login.strategy.spec.ts b/libs/auth/src/common/login-strategies/user-api-login.strategy.spec.ts index d50d2883c763..da856a282eb0 100644 --- a/libs/auth/src/common/login-strategies/user-api-login.strategy.spec.ts +++ b/libs/auth/src/common/login-strategies/user-api-login.strategy.spec.ts @@ -4,6 +4,7 @@ import { ApiService } from "@bitwarden/common/abstractions/api.service"; import { KeyConnectorService } from "@bitwarden/common/auth/abstractions/key-connector.service"; import { TokenService } from "@bitwarden/common/auth/abstractions/token.service"; import { TwoFactorService } from "@bitwarden/common/auth/abstractions/two-factor.service"; +import { VaultTimeoutAction } from "@bitwarden/common/enums/vault-timeout-action.enum"; import { AppIdService } from "@bitwarden/common/platform/abstractions/app-id.service"; import { CryptoService } from "@bitwarden/common/platform/abstractions/crypto.service"; import { EnvironmentService } from "@bitwarden/common/platform/abstractions/environment.service"; @@ -59,7 +60,7 @@ describe("UserApiLoginStrategy", () => { appIdService.getAppId.mockResolvedValue(deviceId); tokenService.getTwoFactorToken.mockResolvedValue(null); - tokenService.decodeToken.mockResolvedValue({}); + tokenService.decodeAccessToken.mockResolvedValue({}); apiLogInStrategy = new UserApiLoginStrategy( cache, @@ -101,10 +102,23 @@ describe("UserApiLoginStrategy", () => { it("sets the local environment after a successful login", async () => { apiService.postIdentityToken.mockResolvedValue(identityTokenResponseFactory()); + const mockVaultTimeoutAction = VaultTimeoutAction.Lock; + const mockVaultTimeout = 60; + stateService.getVaultTimeoutAction.mockResolvedValue(mockVaultTimeoutAction); + stateService.getVaultTimeout.mockResolvedValue(mockVaultTimeout); + await apiLogInStrategy.logIn(credentials); - expect(stateService.setApiKeyClientId).toHaveBeenCalledWith(apiClientId); - expect(stateService.setApiKeyClientSecret).toHaveBeenCalledWith(apiClientSecret); + expect(tokenService.setClientId).toHaveBeenCalledWith( + apiClientId, + mockVaultTimeoutAction, + mockVaultTimeout, + ); + expect(tokenService.setClientSecret).toHaveBeenCalledWith( + apiClientSecret, + mockVaultTimeoutAction, + mockVaultTimeout, + ); expect(stateService.addAccount).toHaveBeenCalled(); }); diff --git a/libs/auth/src/common/login-strategies/user-api-login.strategy.ts b/libs/auth/src/common/login-strategies/user-api-login.strategy.ts index a26fb41ae967..68916b6e8e18 100644 --- a/libs/auth/src/common/login-strategies/user-api-login.strategy.ts +++ b/libs/auth/src/common/login-strategies/user-api-login.strategy.ts @@ -7,6 +7,7 @@ import { TokenService } from "@bitwarden/common/auth/abstractions/token.service" import { TwoFactorService } from "@bitwarden/common/auth/abstractions/two-factor.service"; import { UserApiTokenRequest } from "@bitwarden/common/auth/models/request/identity-token/user-api-token.request"; import { IdentityTokenResponse } from "@bitwarden/common/auth/models/response/identity-token.response"; +import { VaultTimeoutAction } from "@bitwarden/common/enums/vault-timeout-action.enum"; import { AppIdService } from "@bitwarden/common/platform/abstractions/app-id.service"; import { CryptoService } from "@bitwarden/common/platform/abstractions/crypto.service"; import { EnvironmentService } from "@bitwarden/common/platform/abstractions/environment.service"; @@ -104,9 +105,21 @@ export class UserApiLoginStrategy extends LoginStrategy { protected async saveAccountInformation(tokenResponse: IdentityTokenResponse) { await super.saveAccountInformation(tokenResponse); + const vaultTimeout = await this.stateService.getVaultTimeout(); + const vaultTimeoutAction = await this.stateService.getVaultTimeoutAction(); + const tokenRequest = this.cache.value.tokenRequest; - await this.stateService.setApiKeyClientId(tokenRequest.clientId); - await this.stateService.setApiKeyClientSecret(tokenRequest.clientSecret); + + await this.tokenService.setClientId( + tokenRequest.clientId, + vaultTimeoutAction as VaultTimeoutAction, + vaultTimeout, + ); + await this.tokenService.setClientSecret( + tokenRequest.clientSecret, + vaultTimeoutAction as VaultTimeoutAction, + vaultTimeout, + ); } exportCache(): CacheData { diff --git a/libs/auth/src/common/login-strategies/webauthn-login.strategy.spec.ts b/libs/auth/src/common/login-strategies/webauthn-login.strategy.spec.ts index 17933a3dcb6c..b7a56e623083 100644 --- a/libs/auth/src/common/login-strategies/webauthn-login.strategy.spec.ts +++ b/libs/auth/src/common/login-strategies/webauthn-login.strategy.spec.ts @@ -71,7 +71,7 @@ describe("WebAuthnLoginStrategy", () => { tokenService.getTwoFactorToken.mockResolvedValue(null); appIdService.getAppId.mockResolvedValue(deviceId); - tokenService.decodeToken.mockResolvedValue({}); + tokenService.decodeAccessToken.mockResolvedValue({}); webAuthnLoginStrategy = new WebAuthnLoginStrategy( cache, diff --git a/libs/auth/src/common/models/domain/login-credentials.ts b/libs/auth/src/common/models/domain/login-credentials.ts index a56d8e00970b..bfe01aea20f5 100644 --- a/libs/auth/src/common/models/domain/login-credentials.ts +++ b/libs/auth/src/common/models/domain/login-credentials.ts @@ -25,6 +25,11 @@ export class SsoLoginCredentials { public codeVerifier: string, public redirectUrl: string, public orgId: string, + /** + * Optional email address for SSO login. + * Used for looking up 2FA token on clients that support remembering 2FA token. + */ + public email?: string, public twoFactor?: TokenTwoFactorRequest, ) {} } diff --git a/libs/auth/src/common/services/login-strategies/login-strategy.service.spec.ts b/libs/auth/src/common/services/login-strategies/login-strategy.service.spec.ts index 21509eb83c65..2304dc4d3393 100644 --- a/libs/auth/src/common/services/login-strategies/login-strategy.service.spec.ts +++ b/libs/auth/src/common/services/login-strategies/login-strategy.service.spec.ts @@ -114,7 +114,7 @@ describe("LoginStrategyService", () => { token_type: "Bearer", }), ); - tokenService.decodeToken.calledWith("ACCESS_TOKEN").mockResolvedValue({ + tokenService.decodeAccessToken.calledWith("ACCESS_TOKEN").mockResolvedValue({ sub: "USER_ID", name: "NAME", email: "EMAIL", @@ -161,7 +161,7 @@ describe("LoginStrategyService", () => { }), ); - tokenService.decodeToken.calledWith("ACCESS_TOKEN").mockResolvedValue({ + tokenService.decodeAccessToken.calledWith("ACCESS_TOKEN").mockResolvedValue({ sub: "USER_ID", name: "NAME", email: "EMAIL", diff --git a/libs/auth/src/common/utilities/decode-jwt-token-to-json.utility.spec.ts b/libs/auth/src/common/utilities/decode-jwt-token-to-json.utility.spec.ts new file mode 100644 index 000000000000..84778b82f887 --- /dev/null +++ b/libs/auth/src/common/utilities/decode-jwt-token-to-json.utility.spec.ts @@ -0,0 +1,90 @@ +import { DecodedAccessToken } from "@bitwarden/common/auth/services/token.service"; +import { Utils } from "@bitwarden/common/platform/misc/utils"; + +import { decodeJwtTokenToJson } from "./decode-jwt-token-to-json.utility"; + +describe("decodeJwtTokenToJson", () => { + const accessTokenJwt = + "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJodHRwOi8vbG9jYWxob3N0IiwibmJmIjoxNzA5MzI0MTExLCJpYXQiOjE3MDkzMjQxMTEsImV4cCI6MTcwOTMyNzcxMSwic2NvcGUiOlsiYXBpIiwib2ZmbGluZV9hY2Nlc3MiXSwiYW1yIjpbIkFwcGxpY2F0aW9uIl0sImNsaWVudF9pZCI6IndlYiIsInN1YiI6ImVjZTcwYTEzLTcyMTYtNDNjNC05OTc3LWIxMDMwMTQ2ZTFlNyIsImF1dGhfdGltZSI6MTcwOTMyNDEwNCwiaWRwIjoiYml0d2FyZGVuIiwicHJlbWl1bSI6ZmFsc2UsImVtYWlsIjoiZXhhbXBsZUBiaXR3YXJkZW4uY29tIiwiZW1haWxfdmVyaWZpZWQiOmZhbHNlLCJzc3RhbXAiOiJHWTdKQU82NENLS1RLQkI2WkVBVVlMMldPUVU3QVNUMiIsIm5hbWUiOiJUZXN0IFVzZXIiLCJvcmdvd25lciI6WyI5MmI0OTkwOC1iNTE0LTQ1YTgtYmFkYi1iMTAzMDE0OGZlNTMiLCIzOGVkZTMyMi1iNGI0LTRiZDgtOWUwOS1iMTA3MDExMmRjMTEiLCJiMmQwNzAyOC1hNTgzLTRjM2UtOGQ2MC1iMTA3MDExOThjMjkiLCJiZjkzNGJhMi0wZmQ0LTQ5ZjItYTk1ZS1iMTA3MDExZmM5ZTYiLCJjMGI3Zjc1ZC0wMTVmLTQyYzktYjNhNi1iMTA4MDE3NjA3Y2EiXSwiZGV2aWNlIjoiNGI4NzIzNjctMGRhNi00MWEwLWFkY2ItNzdmMmZlZWZjNGY0IiwianRpIjoiNzUxNjFCRTQxMzFGRjVBMkRFNTExQjhDNEUyRkY4OUEifQ.n7roP8sSbfwcYdvRxZNZds27IK32TW6anorE6BORx_Q"; + + const accessTokenDecoded: DecodedAccessToken = { + iss: "http://localhost", + nbf: 1709324111, + iat: 1709324111, + exp: 1709327711, + scope: ["api", "offline_access"], + amr: ["Application"], + client_id: "web", + sub: "ece70a13-7216-43c4-9977-b1030146e1e7", // user id + auth_time: 1709324104, + idp: "bitwarden", + premium: false, + email: "example@bitwarden.com", + email_verified: false, + sstamp: "GY7JAO64CKKTKBB6ZEAUYL2WOQU7AST2", + name: "Test User", + orgowner: [ + "92b49908-b514-45a8-badb-b1030148fe53", + "38ede322-b4b4-4bd8-9e09-b1070112dc11", + "b2d07028-a583-4c3e-8d60-b10701198c29", + "bf934ba2-0fd4-49f2-a95e-b107011fc9e6", + "c0b7f75d-015f-42c9-b3a6-b108017607ca", + ], + device: "4b872367-0da6-41a0-adcb-77f2feefc4f4", + jti: "75161BE4131FF5A2DE511B8C4E2FF89A", + }; + + it("should decode the JWT token", () => { + // Act + const result = decodeJwtTokenToJson(accessTokenJwt); + + // Assert + expect(result).toEqual(accessTokenDecoded); + }); + + it("should throw an error if the JWT token is null", () => { + // Act && Assert + expect(() => decodeJwtTokenToJson(null)).toThrow("JWT token not found"); + }); + + it("should throw an error if the JWT token is missing 3 parts", () => { + // Act && Assert + expect(() => decodeJwtTokenToJson("invalidToken")).toThrow("JWT must have 3 parts"); + }); + + it("should throw an error if the JWT token payload contains invalid JSON", () => { + // Arrange: Create a token with a valid format but with a payload that's valid Base64 but not valid JSON + const header = btoa(JSON.stringify({ alg: "none" })); + // Create a Base64-encoded string which fails to parse as JSON + const payload = btoa("invalid JSON"); + const signature = "signature"; + const malformedToken = `${header}.${payload}.${signature}`; + + // Act & Assert + expect(() => decodeJwtTokenToJson(malformedToken)).toThrow( + "Cannot parse the token's payload into JSON", + ); + }); + + it("should throw an error if the JWT token cannot be decoded", () => { + // Arrange: Create a token with a valid format + const header = btoa(JSON.stringify({ alg: "none" })); + const payload = "invalidPayloadBecauseWeWillMockTheFailure"; + const signature = "signature"; + const malformedToken = `${header}.${payload}.${signature}`; + + // Mock Utils.fromUrlB64ToUtf8 to throw an error for this specific payload + jest.spyOn(Utils, "fromUrlB64ToUtf8").mockImplementation((input) => { + if (input === payload) { + throw new Error("Mock error"); + } + return input; // Default behavior for other inputs + }); + + // Act & Assert + expect(() => decodeJwtTokenToJson(malformedToken)).toThrow("Cannot decode the token"); + + // Restore original function so other tests are not affected + jest.restoreAllMocks(); + }); +}); diff --git a/libs/auth/src/common/utilities/decode-jwt-token-to-json.utility.ts b/libs/auth/src/common/utilities/decode-jwt-token-to-json.utility.ts new file mode 100644 index 000000000000..717e80b110df --- /dev/null +++ b/libs/auth/src/common/utilities/decode-jwt-token-to-json.utility.ts @@ -0,0 +1,32 @@ +import { Utils } from "@bitwarden/common/platform/misc/utils"; + +export function decodeJwtTokenToJson(jwtToken: string): any { + if (jwtToken == null) { + throw new Error("JWT token not found"); + } + + const parts = jwtToken.split("."); + if (parts.length !== 3) { + throw new Error("JWT must have 3 parts"); + } + + // JWT has 3 parts: header, payload, signature separated by '.' + // So, grab the payload to decode + const encodedPayload = parts[1]; + + let decodedPayloadJSON: string; + try { + // Attempt to decode from URL-safe Base64 to UTF-8 + decodedPayloadJSON = Utils.fromUrlB64ToUtf8(encodedPayload); + } catch (decodingError) { + throw new Error("Cannot decode the token"); + } + + try { + // Attempt to parse the JSON payload + const decodedToken = JSON.parse(decodedPayloadJSON); + return decodedToken; + } catch (jsonError) { + throw new Error("Cannot parse the token's payload into JSON"); + } +} diff --git a/libs/auth/src/common/utilities/index.ts b/libs/auth/src/common/utilities/index.ts new file mode 100644 index 000000000000..0309e37f3942 --- /dev/null +++ b/libs/auth/src/common/utilities/index.ts @@ -0,0 +1 @@ +export * from "./decode-jwt-token-to-json.utility"; diff --git a/libs/common/src/auth/abstractions/sso-login.service.abstraction.ts b/libs/common/src/auth/abstractions/sso-login.service.abstraction.ts index 4d73810320d4..c964c8809c33 100644 --- a/libs/common/src/auth/abstractions/sso-login.service.abstraction.ts +++ b/libs/common/src/auth/abstractions/sso-login.service.abstraction.ts @@ -54,6 +54,20 @@ export abstract class SsoLoginServiceAbstraction { * Do not use this value outside of the SSO login flow. */ setOrganizationSsoIdentifier: (organizationIdentifier: string) => Promise; + /** + * Gets the user's email. + * Note: This should only be used during the SSO flow to identify the user that is attempting to log in. + * @returns The user's email. + */ + getSsoEmail: () => Promise; + /** + * Sets the user's email. + * Note: This should only be used during the SSO flow to identify the user that is attempting to log in. + * @param email The user's email. + * @returns A promise that resolves when the email has been set. + * + */ + setSsoEmail: (email: string) => Promise; /** * Gets the value of the active user's organization sso identifier. * diff --git a/libs/common/src/auth/abstractions/token.service.ts b/libs/common/src/auth/abstractions/token.service.ts index 88e6d489b328..d2358314d79e 100644 --- a/libs/common/src/auth/abstractions/token.service.ts +++ b/libs/common/src/auth/abstractions/token.service.ts @@ -1,31 +1,208 @@ -import { IdentityTokenResponse } from "../models/response/identity-token.response"; +import { VaultTimeoutAction } from "../../enums/vault-timeout-action.enum"; +import { UserId } from "../../types/guid"; +import { DecodedAccessToken } from "../services/token.service"; export abstract class TokenService { + /** + * Sets the access token, refresh token, API Key Client ID, and API Key Client Secret in memory or disk + * based on the given vaultTimeoutAction and vaultTimeout and the derived access token user id. + * Note: for platforms that support secure storage, the access & refresh tokens are stored in secure storage instead of on disk. + * Note 2: this method also enforces always setting the access token and the refresh token together as + * we can retrieve the user id required to set the refresh token from the access token for efficiency. + * @param accessToken The access token to set. + * @param refreshToken The refresh token to set. + * @param clientIdClientSecret The API Key Client ID and Client Secret to set. + * @param vaultTimeoutAction The action to take when the vault times out. + * @param vaultTimeout The timeout for the vault. + * @returns A promise that resolves when the tokens have been set. + */ setTokens: ( accessToken: string, refreshToken: string, - clientIdClientSecret: [string, string], - ) => Promise; - setToken: (token: string) => Promise; - getToken: () => Promise; - setRefreshToken: (refreshToken: string) => Promise; - getRefreshToken: () => Promise; - setClientId: (clientId: string) => Promise; - getClientId: () => Promise; - setClientSecret: (clientSecret: string) => Promise; - getClientSecret: () => Promise; - setTwoFactorToken: (tokenResponse: IdentityTokenResponse) => Promise; - getTwoFactorToken: () => Promise; - clearTwoFactorToken: () => Promise; - clearToken: (userId?: string) => Promise; - decodeToken: (token?: string) => Promise; - getTokenExpirationDate: () => Promise; + vaultTimeoutAction: VaultTimeoutAction, + vaultTimeout: number | null, + clientIdClientSecret?: [string, string], + ) => Promise; + + /** + * Clears the access token, refresh token, API Key Client ID, and API Key Client Secret out of memory, disk, and secure storage if supported. + * @param userId The optional user id to clear the tokens for; if not provided, the active user id is used. + * @returns A promise that resolves when the tokens have been cleared. + */ + clearTokens: (userId?: UserId) => Promise; + + /** + * Sets the access token in memory or disk based on the given vaultTimeoutAction and vaultTimeout + * and the user id read off the access token + * Note: for platforms that support secure storage, the access & refresh tokens are stored in secure storage instead of on disk. + * @param accessToken The access token to set. + * @param vaultTimeoutAction The action to take when the vault times out. + * @param vaultTimeout The timeout for the vault. + * @returns A promise that resolves when the access token has been set. + */ + setAccessToken: ( + accessToken: string, + vaultTimeoutAction: VaultTimeoutAction, + vaultTimeout: number | null, + ) => Promise; + + // TODO: revisit having this public clear method approach once the state service is fully deprecated. + /** + * Clears the access token for the given user id out of memory, disk, and secure storage if supported. + * @param userId The optional user id to clear the access token for; if not provided, the active user id is used. + * @returns A promise that resolves when the access token has been cleared. + * + * Note: This method is required so that the StateService doesn't have to inject the VaultTimeoutSettingsService to + * pass in the vaultTimeoutAction and vaultTimeout. + * This avoids a circular dependency between the StateService, TokenService, and VaultTimeoutSettingsService. + */ + clearAccessToken: (userId?: UserId) => Promise; + + /** + * Gets the access token + * @param userId - The optional user id to get the access token for; if not provided, the active user is used. + * @returns A promise that resolves with the access token or undefined. + */ + getAccessToken: (userId?: UserId) => Promise; + + /** + * Gets the refresh token. + * @param userId - The optional user id to get the refresh token for; if not provided, the active user is used. + * @returns A promise that resolves with the refresh token or undefined. + */ + getRefreshToken: (userId?: UserId) => Promise; + + /** + * Sets the API Key Client ID for the active user id in memory or disk based on the given vaultTimeoutAction and vaultTimeout. + * @param clientId The API Key Client ID to set. + * @param vaultTimeoutAction The action to take when the vault times out. + * @param vaultTimeout The timeout for the vault. + * @returns A promise that resolves when the API Key Client ID has been set. + */ + setClientId: ( + clientId: string, + vaultTimeoutAction: VaultTimeoutAction, + vaultTimeout: number | null, + userId?: UserId, + ) => Promise; + + /** + * Gets the API Key Client ID for the active user. + * @returns A promise that resolves with the API Key Client ID or undefined + */ + getClientId: (userId?: UserId) => Promise; + + /** + * Sets the API Key Client Secret for the active user id in memory or disk based on the given vaultTimeoutAction and vaultTimeout. + * @param clientSecret The API Key Client Secret to set. + * @param vaultTimeoutAction The action to take when the vault times out. + * @param vaultTimeout The timeout for the vault. + * @returns A promise that resolves when the API Key Client Secret has been set. + */ + setClientSecret: ( + clientSecret: string, + vaultTimeoutAction: VaultTimeoutAction, + vaultTimeout: number | null, + userId?: UserId, + ) => Promise; + + /** + * Gets the API Key Client Secret for the active user. + * @returns A promise that resolves with the API Key Client Secret or undefined + */ + getClientSecret: (userId?: UserId) => Promise; + + /** + * Sets the two factor token for the given email in global state. + * The two factor token is set when the user checks "remember me" when completing two factor + * authentication and it is used to bypass two factor authentication for a period of time. + * @param email The email to set the two factor token for. + * @param twoFactorToken The two factor token to set. + * @returns A promise that resolves when the two factor token has been set. + */ + setTwoFactorToken: (email: string, twoFactorToken: string) => Promise; + + /** + * Gets the two factor token for the given email. + * @param email The email to get the two factor token for. + * @returns A promise that resolves with the two factor token for the given email or null if it isn't found. + */ + getTwoFactorToken: (email: string) => Promise; + + /** + * Clears the two factor token for the given email out of global state. + * @param email The email to clear the two factor token for. + * @returns A promise that resolves when the two factor token has been cleared. + */ + clearTwoFactorToken: (email: string) => Promise; + + /** + * Decodes the access token. + * @param token The access token to decode. + * @returns A promise that resolves with the decoded access token. + */ + decodeAccessToken: (token?: string) => Promise; + + /** + * Gets the expiration date for the access token. Returns if token can't be decoded or has no expiration + * @returns A promise that resolves with the expiration date for the access token. + */ + getTokenExpirationDate: () => Promise; + + /** + * Calculates the adjusted time in seconds until the access token expires, considering an optional offset. + * + * @param {number} [offsetSeconds=0] Optional seconds to subtract from the remaining time, + * creating a buffer before actual expiration. Useful for preemptive actions + * before token expiry. A value of 0 or omitting this parameter calculates time + * based on the actual expiration. + * @returns {Promise} Promise resolving to the adjusted seconds remaining. + */ tokenSecondsRemaining: (offsetSeconds?: number) => Promise; + + /** + * Checks if the access token needs to be refreshed. + * @param {number} [minutes=5] - Optional number of minutes before the access token expires to consider refreshing it. + * @returns A promise that resolves with a boolean indicating if the access token needs to be refreshed. + */ tokenNeedsRefresh: (minutes?: number) => Promise; - getUserId: () => Promise; + + /** + * Gets the user id for the active user from the access token. + * @returns A promise that resolves with the user id for the active user. + * @deprecated Use AccountService.activeAccount$ instead. + */ + getUserId: () => Promise; + + /** + * Gets the email for the active user from the access token. + * @returns A promise that resolves with the email for the active user. + * @deprecated Use AccountService.activeAccount$ instead. + */ getEmail: () => Promise; + + /** + * Gets the email verified status for the active user from the access token. + * @returns A promise that resolves with the email verified status for the active user. + */ getEmailVerified: () => Promise; + + /** + * Gets the name for the active user from the access token. + * @returns A promise that resolves with the name for the active user. + * @deprecated Use AccountService.activeAccount$ instead. + */ getName: () => Promise; + + /** + * Gets the issuer for the active user from the access token. + * @returns A promise that resolves with the issuer for the active user. + */ getIssuer: () => Promise; + + /** + * Gets whether or not the user authenticated via an external mechanism. + * @returns A promise that resolves with a boolean representing the user's external authN status. + */ getIsExternal: () => Promise; } diff --git a/libs/common/src/auth/services/sso-login.service.ts b/libs/common/src/auth/services/sso-login.service.ts index e693de44fc07..99640e1c6c60 100644 --- a/libs/common/src/auth/services/sso-login.service.ts +++ b/libs/common/src/auth/services/sso-login.service.ts @@ -7,6 +7,7 @@ import { SSO_DISK, StateProvider, } from "../../platform/state"; +import { SsoLoginServiceAbstraction } from "../abstractions/sso-login.service.abstraction"; /** * Uses disk storage so that the code verifier can be persisted across sso redirects. @@ -33,16 +34,25 @@ const ORGANIZATION_SSO_IDENTIFIER = new KeyDefinition( }, ); -export class SsoLoginService { +/** + * Uses disk storage so that the user's email can be persisted across sso redirects. + */ +const SSO_EMAIL = new KeyDefinition(SSO_DISK, "ssoEmail", { + deserializer: (state) => state, +}); + +export class SsoLoginService implements SsoLoginServiceAbstraction { private codeVerifierState: GlobalState; private ssoState: GlobalState; private orgSsoIdentifierState: GlobalState; + private ssoEmailState: GlobalState; private activeUserOrgSsoIdentifierState: ActiveUserState; constructor(private stateProvider: StateProvider) { this.codeVerifierState = this.stateProvider.getGlobal(CODE_VERIFIER); this.ssoState = this.stateProvider.getGlobal(SSO_STATE); this.orgSsoIdentifierState = this.stateProvider.getGlobal(ORGANIZATION_SSO_IDENTIFIER); + this.ssoEmailState = this.stateProvider.getGlobal(SSO_EMAIL); this.activeUserOrgSsoIdentifierState = this.stateProvider.getActive( ORGANIZATION_SSO_IDENTIFIER, ); @@ -72,6 +82,14 @@ export class SsoLoginService { await this.orgSsoIdentifierState.update((_) => organizationIdentifier); } + getSsoEmail(): Promise { + return firstValueFrom(this.ssoEmailState.state$); + } + + async setSsoEmail(email: string): Promise { + await this.ssoEmailState.update((_) => email); + } + getActiveUserOrganizationSsoIdentifier(): Promise { return firstValueFrom(this.activeUserOrgSsoIdentifierState.state$); } diff --git a/libs/common/src/auth/services/token.service.spec.ts b/libs/common/src/auth/services/token.service.spec.ts new file mode 100644 index 000000000000..a7b953f92806 --- /dev/null +++ b/libs/common/src/auth/services/token.service.spec.ts @@ -0,0 +1,2237 @@ +import { mock } from "jest-mock-extended"; + +import { FakeSingleUserStateProvider, FakeGlobalStateProvider } from "../../../spec"; +import { VaultTimeoutAction } from "../../enums/vault-timeout-action.enum"; +import { AbstractStorageService } from "../../platform/abstractions/storage.service"; +import { StorageLocation } from "../../platform/enums"; +import { StorageOptions } from "../../platform/models/domain/storage-options"; +import { UserId } from "../../types/guid"; + +import { ACCOUNT_ACTIVE_ACCOUNT_ID } from "./account.service"; +import { DecodedAccessToken, TokenService } from "./token.service"; +import { + ACCESS_TOKEN_DISK, + ACCESS_TOKEN_MEMORY, + ACCESS_TOKEN_MIGRATED_TO_SECURE_STORAGE, + API_KEY_CLIENT_ID_DISK, + API_KEY_CLIENT_ID_MEMORY, + API_KEY_CLIENT_SECRET_DISK, + API_KEY_CLIENT_SECRET_MEMORY, + EMAIL_TWO_FACTOR_TOKEN_RECORD_DISK_LOCAL, + REFRESH_TOKEN_DISK, + REFRESH_TOKEN_MEMORY, + REFRESH_TOKEN_MIGRATED_TO_SECURE_STORAGE, +} from "./token.state"; + +describe("TokenService", () => { + let tokenService: TokenService; + let singleUserStateProvider: FakeSingleUserStateProvider; + let globalStateProvider: FakeGlobalStateProvider; + + const secureStorageService = mock(); + + const memoryVaultTimeoutAction = VaultTimeoutAction.LogOut; + const memoryVaultTimeout = 30; + + const diskVaultTimeoutAction = VaultTimeoutAction.Lock; + const diskVaultTimeout: number = null; + + const accessTokenJwt = + "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJodHRwOi8vbG9jYWxob3N0IiwibmJmIjoxNzA5MzI0MTExLCJpYXQiOjE3MDkzMjQxMTEsImV4cCI6MTcwOTMyNzcxMSwic2NvcGUiOlsiYXBpIiwib2ZmbGluZV9hY2Nlc3MiXSwiYW1yIjpbIkFwcGxpY2F0aW9uIl0sImNsaWVudF9pZCI6IndlYiIsInN1YiI6ImVjZTcwYTEzLTcyMTYtNDNjNC05OTc3LWIxMDMwMTQ2ZTFlNyIsImF1dGhfdGltZSI6MTcwOTMyNDEwNCwiaWRwIjoiYml0d2FyZGVuIiwicHJlbWl1bSI6ZmFsc2UsImVtYWlsIjoiZXhhbXBsZUBiaXR3YXJkZW4uY29tIiwiZW1haWxfdmVyaWZpZWQiOmZhbHNlLCJzc3RhbXAiOiJHWTdKQU82NENLS1RLQkI2WkVBVVlMMldPUVU3QVNUMiIsIm5hbWUiOiJUZXN0IFVzZXIiLCJvcmdvd25lciI6WyI5MmI0OTkwOC1iNTE0LTQ1YTgtYmFkYi1iMTAzMDE0OGZlNTMiLCIzOGVkZTMyMi1iNGI0LTRiZDgtOWUwOS1iMTA3MDExMmRjMTEiLCJiMmQwNzAyOC1hNTgzLTRjM2UtOGQ2MC1iMTA3MDExOThjMjkiLCJiZjkzNGJhMi0wZmQ0LTQ5ZjItYTk1ZS1iMTA3MDExZmM5ZTYiLCJjMGI3Zjc1ZC0wMTVmLTQyYzktYjNhNi1iMTA4MDE3NjA3Y2EiXSwiZGV2aWNlIjoiNGI4NzIzNjctMGRhNi00MWEwLWFkY2ItNzdmMmZlZWZjNGY0IiwianRpIjoiNzUxNjFCRTQxMzFGRjVBMkRFNTExQjhDNEUyRkY4OUEifQ.n7roP8sSbfwcYdvRxZNZds27IK32TW6anorE6BORx_Q"; + + const accessTokenDecoded: DecodedAccessToken = { + iss: "http://localhost", + nbf: 1709324111, + iat: 1709324111, + exp: 1709327711, + scope: ["api", "offline_access"], + amr: ["Application"], + client_id: "web", + sub: "ece70a13-7216-43c4-9977-b1030146e1e7", // user id + auth_time: 1709324104, + idp: "bitwarden", + premium: false, + email: "example@bitwarden.com", + email_verified: false, + sstamp: "GY7JAO64CKKTKBB6ZEAUYL2WOQU7AST2", + name: "Test User", + orgowner: [ + "92b49908-b514-45a8-badb-b1030148fe53", + "38ede322-b4b4-4bd8-9e09-b1070112dc11", + "b2d07028-a583-4c3e-8d60-b10701198c29", + "bf934ba2-0fd4-49f2-a95e-b107011fc9e6", + "c0b7f75d-015f-42c9-b3a6-b108017607ca", + ], + device: "4b872367-0da6-41a0-adcb-77f2feefc4f4", + jti: "75161BE4131FF5A2DE511B8C4E2FF89A", + }; + + const userIdFromAccessToken: UserId = accessTokenDecoded.sub as UserId; + + const secureStorageOptions: StorageOptions = { + storageLocation: StorageLocation.Disk, + useSecureStorage: true, + userId: userIdFromAccessToken, + }; + + beforeEach(() => { + jest.clearAllMocks(); + + singleUserStateProvider = new FakeSingleUserStateProvider(); + globalStateProvider = new FakeGlobalStateProvider(); + + const supportsSecureStorage = false; // default to false; tests will override as needed + tokenService = createTokenService(supportsSecureStorage); + }); + + it("instantiates", () => { + expect(tokenService).not.toBeFalsy(); + }); + + describe("Access Token methods", () => { + const accessTokenPartialSecureStorageKey = `_accessToken`; + const accessTokenSecureStorageKey = `${userIdFromAccessToken}${accessTokenPartialSecureStorageKey}`; + + describe("setAccessToken", () => { + it("should throw an error if the access token is null", async () => { + // Act + const result = tokenService.setAccessToken(null, VaultTimeoutAction.Lock, null); + // Assert + await expect(result).rejects.toThrow("Access token is required."); + }); + + it("should throw an error if an invalid token is passed in", async () => { + // Act + const result = tokenService.setAccessToken("invalidToken", VaultTimeoutAction.Lock, null); + // Assert + await expect(result).rejects.toThrow("JWT must have 3 parts"); + }); + + it("should not throw an error as long as the token is valid", async () => { + // Act + const result = tokenService.setAccessToken(accessTokenJwt, VaultTimeoutAction.Lock, null); + // Assert + await expect(result).resolves.not.toThrow(); + }); + + describe("Memory storage tests", () => { + it("should set the access token in memory", async () => { + // Act + await tokenService.setAccessToken( + accessTokenJwt, + memoryVaultTimeoutAction, + memoryVaultTimeout, + ); + // Assert + expect( + singleUserStateProvider.getFake(userIdFromAccessToken, ACCESS_TOKEN_MEMORY).nextMock, + ).toHaveBeenCalledWith(accessTokenJwt); + }); + }); + + describe("Disk storage tests (secure storage not supported on platform)", () => { + it("should set the access token in disk", async () => { + // Act + await tokenService.setAccessToken( + accessTokenJwt, + diskVaultTimeoutAction, + diskVaultTimeout, + ); + // Assert + expect( + singleUserStateProvider.getFake(userIdFromAccessToken, ACCESS_TOKEN_DISK).nextMock, + ).toHaveBeenCalledWith(accessTokenJwt); + }); + }); + + describe("Disk storage tests (secure storage supported on platform)", () => { + beforeEach(() => { + const supportsSecureStorage = true; + tokenService = createTokenService(supportsSecureStorage); + }); + + it("should set the access token in secure storage, null out data on disk or in memory, and set a flag to indicate the token has been migrated", async () => { + // Arrange: + + // For testing purposes, let's assume that the access token is already in disk and memory + singleUserStateProvider + .getFake(userIdFromAccessToken, ACCESS_TOKEN_DISK) + .stateSubject.next([userIdFromAccessToken, accessTokenJwt]); + + singleUserStateProvider + .getFake(userIdFromAccessToken, ACCESS_TOKEN_MEMORY) + .stateSubject.next([userIdFromAccessToken, accessTokenJwt]); + + // Act + await tokenService.setAccessToken( + accessTokenJwt, + diskVaultTimeoutAction, + diskVaultTimeout, + ); + // Assert + + // assert that the access token was set in secure storage + expect(secureStorageService.save).toHaveBeenCalledWith( + accessTokenSecureStorageKey, + accessTokenJwt, + secureStorageOptions, + ); + + // assert data was migrated out of disk and memory + flag was set + expect( + singleUserStateProvider.getFake(userIdFromAccessToken, ACCESS_TOKEN_DISK).nextMock, + ).toHaveBeenCalledWith(null); + expect( + singleUserStateProvider.getFake(userIdFromAccessToken, ACCESS_TOKEN_MEMORY).nextMock, + ).toHaveBeenCalledWith(null); + + expect( + singleUserStateProvider.getFake( + userIdFromAccessToken, + ACCESS_TOKEN_MIGRATED_TO_SECURE_STORAGE, + ).nextMock, + ).toHaveBeenCalledWith(true); + }); + }); + }); + + describe("getAccessToken", () => { + it("should return undefined if no user id is provided and there is no active user in global state", async () => { + // Act + const result = await tokenService.getAccessToken(); + // Assert + expect(result).toBeUndefined(); + }); + + it("should return null if no access token is found in memory, disk, or secure storage", async () => { + // Arrange + globalStateProvider + .getFake(ACCOUNT_ACTIVE_ACCOUNT_ID) + .stateSubject.next(userIdFromAccessToken); + + // Act + const result = await tokenService.getAccessToken(); + // Assert + expect(result).toBeNull(); + }); + + describe("Memory storage tests", () => { + it("should get the access token from memory with no user id specified (uses global active user)", async () => { + // Arrange + singleUserStateProvider + .getFake(userIdFromAccessToken, ACCESS_TOKEN_MEMORY) + .stateSubject.next([userIdFromAccessToken, accessTokenJwt]); + + // set disk to undefined + singleUserStateProvider + .getFake(userIdFromAccessToken, ACCESS_TOKEN_DISK) + .stateSubject.next([userIdFromAccessToken, undefined]); + + // Need to have global active id set to the user id + globalStateProvider + .getFake(ACCOUNT_ACTIVE_ACCOUNT_ID) + .stateSubject.next(userIdFromAccessToken); + + // Act + const result = await tokenService.getAccessToken(); + + // Assert + expect(result).toEqual(accessTokenJwt); + }); + + it("should get the access token from memory for the specified user id", async () => { + // Arrange + singleUserStateProvider + .getFake(userIdFromAccessToken, ACCESS_TOKEN_MEMORY) + .stateSubject.next([userIdFromAccessToken, accessTokenJwt]); + + // set disk to undefined + singleUserStateProvider + .getFake(userIdFromAccessToken, ACCESS_TOKEN_DISK) + .stateSubject.next([userIdFromAccessToken, undefined]); + + // Act + const result = await tokenService.getAccessToken(userIdFromAccessToken); + // Assert + expect(result).toEqual(accessTokenJwt); + }); + }); + + describe("Disk storage tests (secure storage not supported on platform)", () => { + it("should get the access token from disk with no user id specified", async () => { + // Arrange + singleUserStateProvider + .getFake(userIdFromAccessToken, ACCESS_TOKEN_MEMORY) + .stateSubject.next([userIdFromAccessToken, undefined]); + + singleUserStateProvider + .getFake(userIdFromAccessToken, ACCESS_TOKEN_DISK) + .stateSubject.next([userIdFromAccessToken, accessTokenJwt]); + + // Need to have global active id set to the user id + globalStateProvider + .getFake(ACCOUNT_ACTIVE_ACCOUNT_ID) + .stateSubject.next(userIdFromAccessToken); + + // Act + const result = await tokenService.getAccessToken(); + // Assert + expect(result).toEqual(accessTokenJwt); + }); + + it("should get the access token from disk for the specified user id", async () => { + // Arrange + singleUserStateProvider + .getFake(userIdFromAccessToken, ACCESS_TOKEN_MEMORY) + .stateSubject.next([userIdFromAccessToken, undefined]); + + singleUserStateProvider + .getFake(userIdFromAccessToken, ACCESS_TOKEN_DISK) + .stateSubject.next([userIdFromAccessToken, accessTokenJwt]); + + // Act + const result = await tokenService.getAccessToken(userIdFromAccessToken); + // Assert + expect(result).toEqual(accessTokenJwt); + }); + }); + + describe("Disk storage tests (secure storage supported on platform)", () => { + beforeEach(() => { + const supportsSecureStorage = true; + tokenService = createTokenService(supportsSecureStorage); + }); + + it("should get the access token from secure storage when no user id is specified and the migration flag is set to true", async () => { + // Arrange + singleUserStateProvider + .getFake(userIdFromAccessToken, ACCESS_TOKEN_MEMORY) + .stateSubject.next([userIdFromAccessToken, undefined]); + + singleUserStateProvider + .getFake(userIdFromAccessToken, ACCESS_TOKEN_DISK) + .stateSubject.next([userIdFromAccessToken, undefined]); + + secureStorageService.get.mockResolvedValue(accessTokenJwt); + + // Need to have global active id set to the user id + globalStateProvider + .getFake(ACCOUNT_ACTIVE_ACCOUNT_ID) + .stateSubject.next(userIdFromAccessToken); + + // set access token migration flag to true + singleUserStateProvider + .getFake(userIdFromAccessToken, ACCESS_TOKEN_MIGRATED_TO_SECURE_STORAGE) + .stateSubject.next([userIdFromAccessToken, true]); + + // Act + const result = await tokenService.getAccessToken(); + // Assert + expect(result).toEqual(accessTokenJwt); + }); + + it("should get the access token from secure storage when user id is specified and the migration flag set to true", async () => { + // Arrange + + singleUserStateProvider + .getFake(userIdFromAccessToken, ACCESS_TOKEN_MEMORY) + .stateSubject.next([userIdFromAccessToken, undefined]); + + singleUserStateProvider + .getFake(userIdFromAccessToken, ACCESS_TOKEN_DISK) + .stateSubject.next([userIdFromAccessToken, undefined]); + + secureStorageService.get.mockResolvedValue(accessTokenJwt); + + // set access token migration flag to true + singleUserStateProvider + .getFake(userIdFromAccessToken, ACCESS_TOKEN_MIGRATED_TO_SECURE_STORAGE) + .stateSubject.next([userIdFromAccessToken, true]); + + // Act + const result = await tokenService.getAccessToken(userIdFromAccessToken); + // Assert + expect(result).toEqual(accessTokenJwt); + }); + + it("should fallback and get the access token from disk when user id is specified and the migration flag is set to false even if the platform supports secure storage", async () => { + // Arrange + singleUserStateProvider + .getFake(userIdFromAccessToken, ACCESS_TOKEN_MEMORY) + .stateSubject.next([userIdFromAccessToken, undefined]); + + singleUserStateProvider + .getFake(userIdFromAccessToken, ACCESS_TOKEN_DISK) + .stateSubject.next([userIdFromAccessToken, accessTokenJwt]); + + // set access token migration flag to false + singleUserStateProvider + .getFake(userIdFromAccessToken, ACCESS_TOKEN_MIGRATED_TO_SECURE_STORAGE) + .stateSubject.next([userIdFromAccessToken, false]); + + // Act + const result = await tokenService.getAccessToken(userIdFromAccessToken); + + // Assert + expect(result).toEqual(accessTokenJwt); + + // assert that secure storage was not called + expect(secureStorageService.get).not.toHaveBeenCalled(); + }); + + it("should fallback and get the access token from disk when no user id is specified and the migration flag is set to false even if the platform supports secure storage", async () => { + // Arrange + singleUserStateProvider + .getFake(userIdFromAccessToken, ACCESS_TOKEN_MEMORY) + .stateSubject.next([userIdFromAccessToken, undefined]); + + singleUserStateProvider + .getFake(userIdFromAccessToken, ACCESS_TOKEN_DISK) + .stateSubject.next([userIdFromAccessToken, accessTokenJwt]); + + // Need to have global active id set to the user id + globalStateProvider + .getFake(ACCOUNT_ACTIVE_ACCOUNT_ID) + .stateSubject.next(userIdFromAccessToken); + + // set access token migration flag to false + singleUserStateProvider + .getFake(userIdFromAccessToken, ACCESS_TOKEN_MIGRATED_TO_SECURE_STORAGE) + .stateSubject.next([userIdFromAccessToken, false]); + + // Act + const result = await tokenService.getAccessToken(); + + // Assert + expect(result).toEqual(accessTokenJwt); + + // assert that secure storage was not called + expect(secureStorageService.get).not.toHaveBeenCalled(); + }); + }); + }); + + describe("clearAccessToken", () => { + it("should throw an error if no user id is provided and there is no active user in global state", async () => { + // Act + // note: don't await here because we want to test the error + const result = tokenService.clearAccessToken(); + // Assert + await expect(result).rejects.toThrow("User id not found. Cannot clear access token."); + }); + + describe("Secure storage enabled", () => { + beforeEach(() => { + const supportsSecureStorage = true; + tokenService = createTokenService(supportsSecureStorage); + }); + + it("should clear the access token from all storage locations for the specified user id", async () => { + // Arrange + singleUserStateProvider + .getFake(userIdFromAccessToken, ACCESS_TOKEN_MEMORY) + .stateSubject.next([userIdFromAccessToken, accessTokenJwt]); + + singleUserStateProvider + .getFake(userIdFromAccessToken, ACCESS_TOKEN_DISK) + .stateSubject.next([userIdFromAccessToken, accessTokenJwt]); + + // Act + await tokenService.clearAccessToken(userIdFromAccessToken); + + // Assert + expect( + singleUserStateProvider.getFake(userIdFromAccessToken, ACCESS_TOKEN_MEMORY).nextMock, + ).toHaveBeenCalledWith(null); + expect( + singleUserStateProvider.getFake(userIdFromAccessToken, ACCESS_TOKEN_DISK).nextMock, + ).toHaveBeenCalledWith(null); + + expect(secureStorageService.remove).toHaveBeenCalledWith( + accessTokenSecureStorageKey, + secureStorageOptions, + ); + }); + + it("should clear the access token from all storage locations for the global active user", async () => { + // Arrange + singleUserStateProvider + .getFake(userIdFromAccessToken, ACCESS_TOKEN_MEMORY) + .stateSubject.next([userIdFromAccessToken, accessTokenJwt]); + + singleUserStateProvider + .getFake(userIdFromAccessToken, ACCESS_TOKEN_DISK) + .stateSubject.next([userIdFromAccessToken, accessTokenJwt]); + + // Need to have global active id set to the user id + globalStateProvider + .getFake(ACCOUNT_ACTIVE_ACCOUNT_ID) + .stateSubject.next(userIdFromAccessToken); + + // Act + await tokenService.clearAccessToken(); + + // Assert + expect( + singleUserStateProvider.getFake(userIdFromAccessToken, ACCESS_TOKEN_MEMORY).nextMock, + ).toHaveBeenCalledWith(null); + expect( + singleUserStateProvider.getFake(userIdFromAccessToken, ACCESS_TOKEN_DISK).nextMock, + ).toHaveBeenCalledWith(null); + + expect(secureStorageService.remove).toHaveBeenCalledWith( + accessTokenSecureStorageKey, + secureStorageOptions, + ); + }); + }); + }); + + describe("decodeAccessToken", () => { + it("should throw an error if no access token provided or retrieved from state", async () => { + // Access + tokenService.getAccessToken = jest.fn().mockResolvedValue(null); + + // Act + // note: don't await here because we want to test the error + const result = tokenService.decodeAccessToken(); + // Assert + await expect(result).rejects.toThrow("Access token not found."); + }); + + it("should decode the access token", async () => { + // Arrange + tokenService.getAccessToken = jest.fn().mockResolvedValue(accessTokenJwt); + + // Act + const result = await tokenService.decodeAccessToken(); + + // Assert + expect(result).toEqual(accessTokenDecoded); + }); + }); + + describe("Data methods", () => { + describe("getTokenExpirationDate", () => { + it("should throw an error if the access token cannot be decoded", async () => { + // Arrange + tokenService.decodeAccessToken = jest.fn().mockRejectedValue(new Error("Mock error")); + + // Act + // note: don't await here because we want to test the error + const result = tokenService.getTokenExpirationDate(); + // Assert + await expect(result).rejects.toThrow("Failed to decode access token: Mock error"); + }); + + it("should return null if the decoded access token is null", async () => { + // Arrange + tokenService.decodeAccessToken = jest.fn().mockResolvedValue(null); + + // Act + const result = await tokenService.getTokenExpirationDate(); + + // Assert + expect(result).toBeNull(); + }); + + it("should return null if the decoded access token does not have an expiration date", async () => { + // Arrange + const accessTokenDecodedWithoutExp = { ...accessTokenDecoded }; + delete accessTokenDecodedWithoutExp.exp; + tokenService.decodeAccessToken = jest + .fn() + .mockResolvedValue(accessTokenDecodedWithoutExp); + + // Act + const result = await tokenService.getTokenExpirationDate(); + + // Assert + expect(result).toBeNull(); + }); + + it("should return null if the decoded access token has an non numeric expiration date", async () => { + // Arrange + const accessTokenDecodedWithNonNumericExp = { ...accessTokenDecoded, exp: "non-numeric" }; + tokenService.decodeAccessToken = jest + .fn() + .mockResolvedValue(accessTokenDecodedWithNonNumericExp); + + // Act + const result = await tokenService.getTokenExpirationDate(); + + // Assert + expect(result).toBeNull(); + }); + + it("should return the expiration date of the access token", async () => { + // Arrange + tokenService.decodeAccessToken = jest.fn().mockResolvedValue(accessTokenDecoded); + + // Act + const result = await tokenService.getTokenExpirationDate(); + + // Assert + expect(result).toEqual(new Date(accessTokenDecoded.exp * 1000)); + }); + }); + + describe("tokenSecondsRemaining", () => { + it("should return 0 if the tokenExpirationDate is null", async () => { + // Arrange + tokenService.getTokenExpirationDate = jest.fn().mockResolvedValue(null); + + // Act + const result = await tokenService.tokenSecondsRemaining(); + + // Assert + expect(result).toEqual(0); + }); + + it("should return the number of seconds remaining until the token expires", async () => { + // Arrange + // Lock the time to ensure a consistent test environment + // otherwise we have flaky issues with set system time date and the Date.now() call. + const fixedCurrentTime = new Date("2024-03-06T00:00:00Z"); + jest.useFakeTimers().setSystemTime(fixedCurrentTime); + + const nowInSeconds = Math.floor(Date.now() / 1000); + const expirationInSeconds = nowInSeconds + 3600; // token expires in 1 hr + const expectedSecondsRemaining = expirationInSeconds - nowInSeconds; + + const expirationDate = new Date(0); + expirationDate.setUTCSeconds(expirationInSeconds); + tokenService.getTokenExpirationDate = jest.fn().mockResolvedValue(expirationDate); + + // Act + const result = await tokenService.tokenSecondsRemaining(); + + // Assert + expect(result).toEqual(expectedSecondsRemaining); + + // Reset the timers to be the real ones + jest.useRealTimers(); + }); + + it("should return the number of seconds remaining until the token expires, considering an offset", async () => { + // Arrange + // Lock the time to ensure a consistent test environment + // otherwise we have flaky issues with set system time date and the Date.now() call. + const fixedCurrentTime = new Date("2024-03-06T00:00:00Z"); + jest.useFakeTimers().setSystemTime(fixedCurrentTime); + + const nowInSeconds = Math.floor(Date.now() / 1000); + const offsetSeconds = 300; // 5 minute offset + const expirationInSeconds = nowInSeconds + 3600; // token expires in 1 hr + const expectedSecondsRemaining = expirationInSeconds - nowInSeconds - offsetSeconds; // Adjust for offset + + const expirationDate = new Date(0); + expirationDate.setUTCSeconds(expirationInSeconds); + tokenService.getTokenExpirationDate = jest.fn().mockResolvedValue(expirationDate); + + // Act + const result = await tokenService.tokenSecondsRemaining(offsetSeconds); + + // Assert + expect(result).toEqual(expectedSecondsRemaining); + + // Reset the timers to be the real ones + jest.useRealTimers(); + }); + }); + + describe("tokenNeedsRefresh", () => { + it("should return true if token is within the default refresh threshold (5 min)", async () => { + // Arrange + const tokenSecondsRemaining = 60; + tokenService.tokenSecondsRemaining = jest.fn().mockResolvedValue(tokenSecondsRemaining); + + // Act + const result = await tokenService.tokenNeedsRefresh(); + + // Assert + expect(result).toEqual(true); + }); + + it("should return false if token is outside the default refresh threshold (5 min)", async () => { + // Arrange + const tokenSecondsRemaining = 600; + tokenService.tokenSecondsRemaining = jest.fn().mockResolvedValue(tokenSecondsRemaining); + + // Act + const result = await tokenService.tokenNeedsRefresh(); + + // Assert + expect(result).toEqual(false); + }); + + it("should return true if token is within the specified refresh threshold", async () => { + // Arrange + const tokenSecondsRemaining = 60; + tokenService.tokenSecondsRemaining = jest.fn().mockResolvedValue(tokenSecondsRemaining); + + // Act + const result = await tokenService.tokenNeedsRefresh(2); + + // Assert + expect(result).toEqual(true); + }); + + it("should return false if token is outside the specified refresh threshold", async () => { + // Arrange + const tokenSecondsRemaining = 600; + tokenService.tokenSecondsRemaining = jest.fn().mockResolvedValue(tokenSecondsRemaining); + + // Act + const result = await tokenService.tokenNeedsRefresh(5); + + // Assert + expect(result).toEqual(false); + }); + }); + + describe("getUserId", () => { + it("should throw an error if the access token cannot be decoded", async () => { + // Arrange + tokenService.decodeAccessToken = jest.fn().mockRejectedValue(new Error("Mock error")); + + // Act + // note: don't await here because we want to test the error + const result = tokenService.getUserId(); + // Assert + await expect(result).rejects.toThrow("Failed to decode access token: Mock error"); + }); + + it("should throw an error if the decoded access token is null", async () => { + // Arrange + tokenService.decodeAccessToken = jest.fn().mockResolvedValue(null); + + // Act + // note: don't await here because we want to test the error + const result = tokenService.getUserId(); + // Assert + await expect(result).rejects.toThrow("No user id found"); + }); + + it("should throw an error if the decoded access token has a non-string user id", async () => { + // Arrange + const accessTokenDecodedWithNonStringSub = { ...accessTokenDecoded, sub: 123 }; + tokenService.decodeAccessToken = jest + .fn() + .mockResolvedValue(accessTokenDecodedWithNonStringSub); + + // Act + // note: don't await here because we want to test the error + const result = tokenService.getUserId(); + // Assert + await expect(result).rejects.toThrow("No user id found"); + }); + + it("should return the user id from the decoded access token", async () => { + // Arrange + tokenService.decodeAccessToken = jest.fn().mockResolvedValue(accessTokenDecoded); + + // Act + const result = await tokenService.getUserId(); + + // Assert + expect(result).toEqual(userIdFromAccessToken); + }); + }); + + describe("getUserIdFromAccessToken", () => { + it("should throw an error if the access token cannot be decoded", async () => { + // Arrange + tokenService.decodeAccessToken = jest.fn().mockRejectedValue(new Error("Mock error")); + + // Act + // note: don't await here because we want to test the error + const result = (tokenService as any).getUserIdFromAccessToken(accessTokenJwt); + // Assert + await expect(result).rejects.toThrow("Failed to decode access token: Mock error"); + }); + + it("should throw an error if the decoded access token is null", async () => { + // Arrange + tokenService.decodeAccessToken = jest.fn().mockResolvedValue(null); + + // Act + // note: don't await here because we want to test the error + const result = (tokenService as any).getUserIdFromAccessToken(accessTokenJwt); + // Assert + await expect(result).rejects.toThrow("No user id found"); + }); + + it("should throw an error if the decoded access token has a non-string user id", async () => { + // Arrange + const accessTokenDecodedWithNonStringSub = { ...accessTokenDecoded, sub: 123 }; + tokenService.decodeAccessToken = jest + .fn() + .mockResolvedValue(accessTokenDecodedWithNonStringSub); + + // Act + // note: don't await here because we want to test the error + const result = (tokenService as any).getUserIdFromAccessToken(accessTokenJwt); + // Assert + await expect(result).rejects.toThrow("No user id found"); + }); + + it("should return the user id from the decoded access token", async () => { + // Arrange + tokenService.decodeAccessToken = jest.fn().mockResolvedValue(accessTokenDecoded); + + // Act + const result = await (tokenService as any).getUserIdFromAccessToken(accessTokenJwt); + + // Assert + expect(result).toEqual(userIdFromAccessToken); + }); + }); + + describe("getEmail", () => { + it("should throw an error if the access token cannot be decoded", async () => { + // Arrange + tokenService.decodeAccessToken = jest.fn().mockRejectedValue(new Error("Mock error")); + + // Act + // note: don't await here because we want to test the error + const result = tokenService.getEmail(); + // Assert + await expect(result).rejects.toThrow("Failed to decode access token: Mock error"); + }); + + it("should throw an error if the decoded access token is null", async () => { + // Arrange + tokenService.decodeAccessToken = jest.fn().mockResolvedValue(null); + + // Act + // note: don't await here because we want to test the error + const result = tokenService.getEmail(); + // Assert + await expect(result).rejects.toThrow("No email found"); + }); + + it("should throw an error if the decoded access token has a non-string email", async () => { + // Arrange + const accessTokenDecodedWithNonStringEmail = { ...accessTokenDecoded, email: 123 }; + tokenService.decodeAccessToken = jest + .fn() + .mockResolvedValue(accessTokenDecodedWithNonStringEmail); + + // Act + // note: don't await here because we want to test the error + const result = tokenService.getEmail(); + // Assert + await expect(result).rejects.toThrow("No email found"); + }); + + it("should return the email from the decoded access token", async () => { + // Arrange + tokenService.decodeAccessToken = jest.fn().mockResolvedValue(accessTokenDecoded); + + // Act + const result = await tokenService.getEmail(); + + // Assert + expect(result).toEqual(accessTokenDecoded.email); + }); + }); + + describe("getEmailVerified", () => { + it("should throw an error if the access token cannot be decoded", async () => { + // Arrange + tokenService.decodeAccessToken = jest.fn().mockRejectedValue(new Error("Mock error")); + + // Act + // note: don't await here because we want to test the error + const result = tokenService.getEmailVerified(); + // Assert + await expect(result).rejects.toThrow("Failed to decode access token: Mock error"); + }); + + it("should throw an error if the decoded access token is null", async () => { + // Arrange + tokenService.decodeAccessToken = jest.fn().mockResolvedValue(null); + + // Act + // note: don't await here because we want to test the error + const result = tokenService.getEmailVerified(); + // Assert + await expect(result).rejects.toThrow("No email verification found"); + }); + + it("should throw an error if the decoded access token has a non-boolean email_verified", async () => { + // Arrange + const accessTokenDecodedWithNonBooleanEmailVerified = { + ...accessTokenDecoded, + email_verified: 123, + }; + tokenService.decodeAccessToken = jest + .fn() + .mockResolvedValue(accessTokenDecodedWithNonBooleanEmailVerified); + + // Act + // note: don't await here because we want to test the error + const result = tokenService.getEmailVerified(); + // Assert + await expect(result).rejects.toThrow("No email verification found"); + }); + + it("should return the email_verified from the decoded access token", async () => { + // Arrange + tokenService.decodeAccessToken = jest.fn().mockResolvedValue(accessTokenDecoded); + + // Act + const result = await tokenService.getEmailVerified(); + + // Assert + expect(result).toEqual(accessTokenDecoded.email_verified); + }); + }); + + describe("getName", () => { + it("should throw an error if the access token cannot be decoded", async () => { + // Arrange + tokenService.decodeAccessToken = jest.fn().mockRejectedValue(new Error("Mock error")); + + // Act + // note: don't await here because we want to test the error + const result = tokenService.getName(); + // Assert + await expect(result).rejects.toThrow("Failed to decode access token: Mock error"); + }); + + it("should return null if the decoded access token is null", async () => { + // Arrange + tokenService.decodeAccessToken = jest.fn().mockResolvedValue(null); + + // Act + const result = await tokenService.getName(); + + // Assert + expect(result).toBeNull(); + }); + + it("should return null if the decoded access token has a non-string name", async () => { + // Arrange + const accessTokenDecodedWithNonStringName = { ...accessTokenDecoded, name: 123 }; + tokenService.decodeAccessToken = jest + .fn() + .mockResolvedValue(accessTokenDecodedWithNonStringName); + + // Act + const result = await tokenService.getName(); + + // Assert + expect(result).toBeNull(); + }); + + it("should return the name from the decoded access token", async () => { + // Arrange + tokenService.decodeAccessToken = jest.fn().mockResolvedValue(accessTokenDecoded); + + // Act + const result = await tokenService.getName(); + + // Assert + expect(result).toEqual(accessTokenDecoded.name); + }); + }); + + describe("getIssuer", () => { + it("should throw an error if the access token cannot be decoded", async () => { + // Arrange + tokenService.decodeAccessToken = jest.fn().mockRejectedValue(new Error("Mock error")); + + // Act + // note: don't await here because we want to test the error + const result = tokenService.getIssuer(); + // Assert + await expect(result).rejects.toThrow("Failed to decode access token: Mock error"); + }); + + it("should throw an error if the decoded access token is null", async () => { + // Arrange + tokenService.decodeAccessToken = jest.fn().mockResolvedValue(null); + + // Act + // note: don't await here because we want to test the error + const result = tokenService.getIssuer(); + // Assert + await expect(result).rejects.toThrow("No issuer found"); + }); + + it("should throw an error if the decoded access token has a non-string iss", async () => { + // Arrange + const accessTokenDecodedWithNonStringIss = { ...accessTokenDecoded, iss: 123 }; + tokenService.decodeAccessToken = jest + .fn() + .mockResolvedValue(accessTokenDecodedWithNonStringIss); + + // Act + // note: don't await here because we want to test the error + const result = tokenService.getIssuer(); + // Assert + await expect(result).rejects.toThrow("No issuer found"); + }); + + it("should return the issuer from the decoded access token", async () => { + // Arrange + tokenService.decodeAccessToken = jest.fn().mockResolvedValue(accessTokenDecoded); + + // Act + const result = await tokenService.getIssuer(); + + // Assert + expect(result).toEqual(accessTokenDecoded.iss); + }); + }); + + describe("getIsExternal", () => { + it("should throw an error if the access token cannot be decoded", async () => { + // Arrange + tokenService.decodeAccessToken = jest.fn().mockRejectedValue(new Error("Mock error")); + + // Act + // note: don't await here because we want to test the error + const result = tokenService.getIsExternal(); + // Assert + await expect(result).rejects.toThrow("Failed to decode access token: Mock error"); + }); + + it("should return false if the amr (Authentication Method Reference) claim does not contain 'external'", async () => { + // Arrange + const accessTokenDecodedWithoutExternalAmr = { + ...accessTokenDecoded, + amr: ["not-external"], + }; + tokenService.decodeAccessToken = jest + .fn() + .mockResolvedValue(accessTokenDecodedWithoutExternalAmr); + + // Act + const result = await tokenService.getIsExternal(); + + // Assert + expect(result).toEqual(false); + }); + + it("should return true if the amr (Authentication Method Reference) claim contains 'external'", async () => { + // Arrange + const accessTokenDecodedWithExternalAmr = { + ...accessTokenDecoded, + amr: ["external"], + }; + tokenService.decodeAccessToken = jest + .fn() + .mockResolvedValue(accessTokenDecodedWithExternalAmr); + + // Act + const result = await tokenService.getIsExternal(); + + // Assert + expect(result).toEqual(true); + }); + }); + }); + }); + + describe("Refresh Token methods", () => { + const refreshToken = "refreshToken"; + const refreshTokenPartialSecureStorageKey = `_refreshToken`; + const refreshTokenSecureStorageKey = `${userIdFromAccessToken}${refreshTokenPartialSecureStorageKey}`; + + describe("setRefreshToken", () => { + it("should throw an error if no user id is provided", async () => { + // Act + // note: don't await here because we want to test the error + const result = (tokenService as any).setRefreshToken( + refreshToken, + VaultTimeoutAction.Lock, + null, + ); + // Assert + await expect(result).rejects.toThrow("User id not found. Cannot save refresh token."); + }); + + describe("Memory storage tests", () => { + it("should set the refresh token in memory for the specified user id", async () => { + // Act + await (tokenService as any).setRefreshToken( + refreshToken, + memoryVaultTimeoutAction, + memoryVaultTimeout, + userIdFromAccessToken, + ); + + // Assert + expect( + singleUserStateProvider.getFake(userIdFromAccessToken, REFRESH_TOKEN_MEMORY).nextMock, + ).toHaveBeenCalledWith(refreshToken); + }); + }); + + describe("Disk storage tests (secure storage not supported on platform)", () => { + it("should set the refresh token in disk for the specified user id", async () => { + // Act + await (tokenService as any).setRefreshToken( + refreshToken, + diskVaultTimeoutAction, + diskVaultTimeout, + userIdFromAccessToken, + ); + + // Assert + expect( + singleUserStateProvider.getFake(userIdFromAccessToken, REFRESH_TOKEN_DISK).nextMock, + ).toHaveBeenCalledWith(refreshToken); + }); + }); + + describe("Disk storage tests (secure storage supported on platform)", () => { + beforeEach(() => { + const supportsSecureStorage = true; + tokenService = createTokenService(supportsSecureStorage); + }); + + it("should set the refresh token in secure storage, null out data on disk or in memory, and set a flag to indicate the token has been migrated for the specified user id", async () => { + // Arrange: + // For testing purposes, let's assume that the token is already in disk and memory + singleUserStateProvider + .getFake(userIdFromAccessToken, REFRESH_TOKEN_DISK) + .stateSubject.next([userIdFromAccessToken, refreshToken]); + + singleUserStateProvider + .getFake(userIdFromAccessToken, REFRESH_TOKEN_MEMORY) + .stateSubject.next([userIdFromAccessToken, refreshToken]); + + // Act + await (tokenService as any).setRefreshToken( + refreshToken, + diskVaultTimeoutAction, + diskVaultTimeout, + userIdFromAccessToken, + ); + // Assert + + // assert that the refresh token was set in secure storage + expect(secureStorageService.save).toHaveBeenCalledWith( + refreshTokenSecureStorageKey, + refreshToken, + secureStorageOptions, + ); + + // assert data was migrated out of disk and memory + flag was set + expect( + singleUserStateProvider.getFake(userIdFromAccessToken, REFRESH_TOKEN_DISK).nextMock, + ).toHaveBeenCalledWith(null); + expect( + singleUserStateProvider.getFake(userIdFromAccessToken, REFRESH_TOKEN_MEMORY).nextMock, + ).toHaveBeenCalledWith(null); + + expect( + singleUserStateProvider.getFake( + userIdFromAccessToken, + REFRESH_TOKEN_MIGRATED_TO_SECURE_STORAGE, + ).nextMock, + ).toHaveBeenCalledWith(true); + }); + }); + }); + + describe("getRefreshToken", () => { + it("should return undefined if no user id is provided and there is no active user in global state", async () => { + // Act + const result = await (tokenService as any).getRefreshToken(); + // Assert + expect(result).toBeUndefined(); + }); + + it("should return null if no refresh token is found in memory, disk, or secure storage", async () => { + // Arrange + globalStateProvider + .getFake(ACCOUNT_ACTIVE_ACCOUNT_ID) + .stateSubject.next(userIdFromAccessToken); + + // Act + const result = await (tokenService as any).getRefreshToken(); + // Assert + expect(result).toBeNull(); + }); + + describe("Memory storage tests", () => { + it("should get the refresh token from memory with no user id specified (uses global active user)", async () => { + // Arrange + singleUserStateProvider + .getFake(userIdFromAccessToken, REFRESH_TOKEN_MEMORY) + .stateSubject.next([userIdFromAccessToken, refreshToken]); + + singleUserStateProvider + .getFake(userIdFromAccessToken, REFRESH_TOKEN_DISK) + .stateSubject.next([userIdFromAccessToken, undefined]); + + // Need to have global active id set to the user id + globalStateProvider + .getFake(ACCOUNT_ACTIVE_ACCOUNT_ID) + .stateSubject.next(userIdFromAccessToken); + + // Act + const result = await tokenService.getRefreshToken(); + + // Assert + expect(result).toEqual(refreshToken); + }); + + it("should get the refresh token from memory for the specified user id", async () => { + // Arrange + singleUserStateProvider + .getFake(userIdFromAccessToken, REFRESH_TOKEN_MEMORY) + .stateSubject.next([userIdFromAccessToken, refreshToken]); + + singleUserStateProvider + .getFake(userIdFromAccessToken, REFRESH_TOKEN_DISK) + .stateSubject.next([userIdFromAccessToken, undefined]); + + // Act + const result = await tokenService.getRefreshToken(userIdFromAccessToken); + // Assert + expect(result).toEqual(refreshToken); + }); + }); + + describe("Disk storage tests (secure storage not supported on platform)", () => { + it("should get the refresh token from disk with no user id specified", async () => { + // Arrange + singleUserStateProvider + .getFake(userIdFromAccessToken, REFRESH_TOKEN_MEMORY) + .stateSubject.next([userIdFromAccessToken, undefined]); + + singleUserStateProvider + .getFake(userIdFromAccessToken, REFRESH_TOKEN_DISK) + .stateSubject.next([userIdFromAccessToken, refreshToken]); + + // Need to have global active id set to the user id + globalStateProvider + .getFake(ACCOUNT_ACTIVE_ACCOUNT_ID) + .stateSubject.next(userIdFromAccessToken); + + // Act + const result = await tokenService.getRefreshToken(); + // Assert + expect(result).toEqual(refreshToken); + }); + + it("should get the refresh token from disk for the specified user id", async () => { + // Arrange + singleUserStateProvider + .getFake(userIdFromAccessToken, REFRESH_TOKEN_MEMORY) + .stateSubject.next([userIdFromAccessToken, undefined]); + + singleUserStateProvider + .getFake(userIdFromAccessToken, REFRESH_TOKEN_DISK) + .stateSubject.next([userIdFromAccessToken, refreshToken]); + + // Act + const result = await tokenService.getRefreshToken(userIdFromAccessToken); + // Assert + expect(result).toEqual(refreshToken); + }); + }); + + describe("Disk storage tests (secure storage supported on platform)", () => { + beforeEach(() => { + const supportsSecureStorage = true; + tokenService = createTokenService(supportsSecureStorage); + }); + + it("should get the refresh token from secure storage when no user id is specified and the migration flag is set to true", async () => { + // Arrange + singleUserStateProvider + .getFake(userIdFromAccessToken, REFRESH_TOKEN_MEMORY) + .stateSubject.next([userIdFromAccessToken, undefined]); + + singleUserStateProvider + .getFake(userIdFromAccessToken, REFRESH_TOKEN_DISK) + .stateSubject.next([userIdFromAccessToken, undefined]); + + secureStorageService.get.mockResolvedValue(refreshToken); + + // Need to have global active id set to the user id + globalStateProvider + .getFake(ACCOUNT_ACTIVE_ACCOUNT_ID) + .stateSubject.next(userIdFromAccessToken); + + // set access token migration flag to true + singleUserStateProvider + .getFake(userIdFromAccessToken, REFRESH_TOKEN_MIGRATED_TO_SECURE_STORAGE) + .stateSubject.next([userIdFromAccessToken, true]); + + // Act + const result = await tokenService.getRefreshToken(); + // Assert + expect(result).toEqual(refreshToken); + }); + + it("should get the refresh token from secure storage when user id is specified and the migration flag set to true", async () => { + // Arrange + + singleUserStateProvider + .getFake(userIdFromAccessToken, REFRESH_TOKEN_MEMORY) + .stateSubject.next([userIdFromAccessToken, undefined]); + + singleUserStateProvider + .getFake(userIdFromAccessToken, REFRESH_TOKEN_DISK) + .stateSubject.next([userIdFromAccessToken, undefined]); + + secureStorageService.get.mockResolvedValue(refreshToken); + + // set access token migration flag to true + singleUserStateProvider + .getFake(userIdFromAccessToken, REFRESH_TOKEN_MIGRATED_TO_SECURE_STORAGE) + .stateSubject.next([userIdFromAccessToken, true]); + + // Act + const result = await tokenService.getRefreshToken(userIdFromAccessToken); + // Assert + expect(result).toEqual(refreshToken); + }); + + it("should fallback and get the refresh token from disk when user id is specified and the migration flag is set to false even if the platform supports secure storage", async () => { + // Arrange + singleUserStateProvider + .getFake(userIdFromAccessToken, REFRESH_TOKEN_MEMORY) + .stateSubject.next([userIdFromAccessToken, undefined]); + + singleUserStateProvider + .getFake(userIdFromAccessToken, REFRESH_TOKEN_DISK) + .stateSubject.next([userIdFromAccessToken, refreshToken]); + + // set refresh token migration flag to false + singleUserStateProvider + .getFake(userIdFromAccessToken, REFRESH_TOKEN_MIGRATED_TO_SECURE_STORAGE) + .stateSubject.next([userIdFromAccessToken, false]); + + // Act + const result = await tokenService.getRefreshToken(userIdFromAccessToken); + + // Assert + expect(result).toEqual(refreshToken); + + // assert that secure storage was not called + expect(secureStorageService.get).not.toHaveBeenCalled(); + }); + + it("should fallback and get the refresh token from disk when no user id is specified and the migration flag is set to false even if the platform supports secure storage", async () => { + // Arrange + singleUserStateProvider + .getFake(userIdFromAccessToken, REFRESH_TOKEN_MEMORY) + .stateSubject.next([userIdFromAccessToken, undefined]); + + singleUserStateProvider + .getFake(userIdFromAccessToken, REFRESH_TOKEN_DISK) + .stateSubject.next([userIdFromAccessToken, refreshToken]); + + // Need to have global active id set to the user id + globalStateProvider + .getFake(ACCOUNT_ACTIVE_ACCOUNT_ID) + .stateSubject.next(userIdFromAccessToken); + + // set access token migration flag to false + singleUserStateProvider + .getFake(userIdFromAccessToken, REFRESH_TOKEN_MIGRATED_TO_SECURE_STORAGE) + .stateSubject.next([userIdFromAccessToken, false]); + + // Act + const result = await tokenService.getRefreshToken(); + + // Assert + expect(result).toEqual(refreshToken); + + // assert that secure storage was not called + expect(secureStorageService.get).not.toHaveBeenCalled(); + }); + }); + }); + + describe("clearRefreshToken", () => { + it("should throw an error if no user id is provided", async () => { + // Act + // note: don't await here because we want to test the error + const result = (tokenService as any).clearRefreshToken(); + // Assert + await expect(result).rejects.toThrow("User id not found. Cannot clear refresh token."); + }); + + describe("Secure storage enabled", () => { + beforeEach(() => { + const supportsSecureStorage = true; + tokenService = createTokenService(supportsSecureStorage); + }); + + it("should clear the refresh token from all storage locations for the specified user id", async () => { + // Arrange + singleUserStateProvider + .getFake(userIdFromAccessToken, REFRESH_TOKEN_MEMORY) + .stateSubject.next([userIdFromAccessToken, refreshToken]); + + singleUserStateProvider + .getFake(userIdFromAccessToken, REFRESH_TOKEN_DISK) + .stateSubject.next([userIdFromAccessToken, refreshToken]); + + // Act + await (tokenService as any).clearRefreshToken(userIdFromAccessToken); + + // Assert + expect( + singleUserStateProvider.getFake(userIdFromAccessToken, REFRESH_TOKEN_MEMORY).nextMock, + ).toHaveBeenCalledWith(null); + expect( + singleUserStateProvider.getFake(userIdFromAccessToken, REFRESH_TOKEN_DISK).nextMock, + ).toHaveBeenCalledWith(null); + + expect(secureStorageService.remove).toHaveBeenCalledWith( + refreshTokenSecureStorageKey, + secureStorageOptions, + ); + }); + }); + }); + }); + + describe("Client Id methods", () => { + const clientId = "clientId"; + + describe("setClientId", () => { + it("should throw an error if no user id is provided and there is no active user in global state", async () => { + // Act + // note: don't await here because we want to test the error + const result = tokenService.setClientId(clientId, VaultTimeoutAction.Lock, null); + // Assert + await expect(result).rejects.toThrow("User id not found. Cannot save client id."); + }); + + describe("Memory storage tests", () => { + it("should set the client id in memory when there is an active user in global state", async () => { + // Arrange + globalStateProvider + .getFake(ACCOUNT_ACTIVE_ACCOUNT_ID) + .stateSubject.next(userIdFromAccessToken); + + // Act + await tokenService.setClientId(clientId, memoryVaultTimeoutAction, memoryVaultTimeout); + + // Assert + expect( + singleUserStateProvider.getFake(userIdFromAccessToken, API_KEY_CLIENT_ID_MEMORY) + .nextMock, + ).toHaveBeenCalledWith(clientId); + }); + + it("should set the client id in memory for the specified user id", async () => { + // Act + await tokenService.setClientId( + clientId, + memoryVaultTimeoutAction, + memoryVaultTimeout, + userIdFromAccessToken, + ); + + // Assert + expect( + singleUserStateProvider.getFake(userIdFromAccessToken, API_KEY_CLIENT_ID_MEMORY) + .nextMock, + ).toHaveBeenCalledWith(clientId); + }); + }); + + describe("Disk storage tests", () => { + it("should set the client id in disk when there is an active user in global state", async () => { + // Arrange + globalStateProvider + .getFake(ACCOUNT_ACTIVE_ACCOUNT_ID) + .stateSubject.next(userIdFromAccessToken); + + // Act + await tokenService.setClientId(clientId, diskVaultTimeoutAction, diskVaultTimeout); + + // Assert + expect( + singleUserStateProvider.getFake(userIdFromAccessToken, API_KEY_CLIENT_ID_DISK).nextMock, + ).toHaveBeenCalledWith(clientId); + }); + + it("should set the client id in disk for the specified user id", async () => { + // Act + await tokenService.setClientId( + clientId, + diskVaultTimeoutAction, + diskVaultTimeout, + userIdFromAccessToken, + ); + + // Assert + expect( + singleUserStateProvider.getFake(userIdFromAccessToken, API_KEY_CLIENT_ID_DISK).nextMock, + ).toHaveBeenCalledWith(clientId); + }); + }); + }); + + describe("getClientId", () => { + it("should return undefined if no user id is provided and there is no active user in global state", async () => { + // Act + const result = await tokenService.getClientId(); + // Assert + expect(result).toBeUndefined(); + }); + + it("should return null if no client id is found in memory or disk", async () => { + // Arrange + globalStateProvider + .getFake(ACCOUNT_ACTIVE_ACCOUNT_ID) + .stateSubject.next(userIdFromAccessToken); + + // Act + const result = await tokenService.getClientId(); + // Assert + expect(result).toBeNull(); + }); + + describe("Memory storage tests", () => { + it("should get the client id from memory with no user id specified (uses global active user)", async () => { + // Arrange + singleUserStateProvider + .getFake(userIdFromAccessToken, API_KEY_CLIENT_ID_MEMORY) + .stateSubject.next([userIdFromAccessToken, clientId]); + + // set disk to undefined + singleUserStateProvider + .getFake(userIdFromAccessToken, API_KEY_CLIENT_ID_DISK) + .stateSubject.next([userIdFromAccessToken, undefined]); + + // Need to have global active id set to the user id + globalStateProvider + .getFake(ACCOUNT_ACTIVE_ACCOUNT_ID) + .stateSubject.next(userIdFromAccessToken); + + // Act + const result = await tokenService.getClientId(); + + // Assert + expect(result).toEqual(clientId); + }); + + it("should get the client id from memory for the specified user id", async () => { + // Arrange + singleUserStateProvider + .getFake(userIdFromAccessToken, API_KEY_CLIENT_ID_MEMORY) + .stateSubject.next([userIdFromAccessToken, clientId]); + + // set disk to undefined + singleUserStateProvider + .getFake(userIdFromAccessToken, API_KEY_CLIENT_ID_DISK) + .stateSubject.next([userIdFromAccessToken, undefined]); + + // Act + const result = await tokenService.getClientId(userIdFromAccessToken); + // Assert + expect(result).toEqual(clientId); + }); + }); + + describe("Disk storage tests", () => { + it("should get the client id from disk with no user id specified", async () => { + // Arrange + singleUserStateProvider + .getFake(userIdFromAccessToken, API_KEY_CLIENT_ID_MEMORY) + .stateSubject.next([userIdFromAccessToken, undefined]); + + singleUserStateProvider + .getFake(userIdFromAccessToken, API_KEY_CLIENT_ID_DISK) + .stateSubject.next([userIdFromAccessToken, clientId]); + + // Need to have global active id set to the user id + globalStateProvider + .getFake(ACCOUNT_ACTIVE_ACCOUNT_ID) + .stateSubject.next(userIdFromAccessToken); + + // Act + const result = await tokenService.getClientId(); + // Assert + expect(result).toEqual(clientId); + }); + + it("should get the client id from disk for the specified user id", async () => { + // Arrange + singleUserStateProvider + .getFake(userIdFromAccessToken, API_KEY_CLIENT_ID_MEMORY) + .stateSubject.next([userIdFromAccessToken, undefined]); + + singleUserStateProvider + .getFake(userIdFromAccessToken, API_KEY_CLIENT_ID_DISK) + .stateSubject.next([userIdFromAccessToken, clientId]); + + // Act + const result = await tokenService.getClientId(userIdFromAccessToken); + // Assert + expect(result).toEqual(clientId); + }); + }); + }); + + describe("clearClientId", () => { + it("should throw an error if no user id is provided and there is no active user in global state", async () => { + // Act + // note: don't await here because we want to test the error + const result = (tokenService as any).clearClientId(); + // Assert + await expect(result).rejects.toThrow("User id not found. Cannot clear client id."); + }); + + it("should clear the client id from memory and disk for the specified user id", async () => { + // Arrange + singleUserStateProvider + .getFake(userIdFromAccessToken, API_KEY_CLIENT_ID_MEMORY) + .stateSubject.next([userIdFromAccessToken, clientId]); + + singleUserStateProvider + .getFake(userIdFromAccessToken, API_KEY_CLIENT_ID_DISK) + .stateSubject.next([userIdFromAccessToken, clientId]); + + // Act + await (tokenService as any).clearClientId(userIdFromAccessToken); + + // Assert + expect( + singleUserStateProvider.getFake(userIdFromAccessToken, API_KEY_CLIENT_ID_MEMORY).nextMock, + ).toHaveBeenCalledWith(null); + expect( + singleUserStateProvider.getFake(userIdFromAccessToken, API_KEY_CLIENT_ID_DISK).nextMock, + ).toHaveBeenCalledWith(null); + }); + + it("should clear the client id from memory and disk for the global active user", async () => { + // Arrange + singleUserStateProvider + .getFake(userIdFromAccessToken, API_KEY_CLIENT_ID_MEMORY) + .stateSubject.next([userIdFromAccessToken, clientId]); + + singleUserStateProvider + .getFake(userIdFromAccessToken, API_KEY_CLIENT_ID_DISK) + .stateSubject.next([userIdFromAccessToken, clientId]); + + // Need to have global active id set to the user id + globalStateProvider + .getFake(ACCOUNT_ACTIVE_ACCOUNT_ID) + .stateSubject.next(userIdFromAccessToken); + + // Act + await (tokenService as any).clearClientId(); + + // Assert + expect( + singleUserStateProvider.getFake(userIdFromAccessToken, API_KEY_CLIENT_ID_MEMORY).nextMock, + ).toHaveBeenCalledWith(null); + expect( + singleUserStateProvider.getFake(userIdFromAccessToken, API_KEY_CLIENT_ID_DISK).nextMock, + ).toHaveBeenCalledWith(null); + }); + }); + }); + + describe("Client Secret methods", () => { + const clientSecret = "clientSecret"; + + describe("setClientSecret", () => { + it("should throw an error if no user id is provided and there is no active user in global state", async () => { + // Act + // note: don't await here because we want to test the error + const result = tokenService.setClientSecret(clientSecret, VaultTimeoutAction.Lock, null); + // Assert + await expect(result).rejects.toThrow("User id not found. Cannot save client secret."); + }); + + describe("Memory storage tests", () => { + it("should set the client secret in memory when there is an active user in global state", async () => { + // Arrange + globalStateProvider + .getFake(ACCOUNT_ACTIVE_ACCOUNT_ID) + .stateSubject.next(userIdFromAccessToken); + + // Act + await tokenService.setClientSecret( + clientSecret, + memoryVaultTimeoutAction, + memoryVaultTimeout, + ); + + // Assert + expect( + singleUserStateProvider.getFake(userIdFromAccessToken, API_KEY_CLIENT_SECRET_MEMORY) + .nextMock, + ).toHaveBeenCalledWith(clientSecret); + }); + + it("should set the client secret in memory for the specified user id", async () => { + // Act + await tokenService.setClientSecret( + clientSecret, + memoryVaultTimeoutAction, + memoryVaultTimeout, + userIdFromAccessToken, + ); + + // Assert + expect( + singleUserStateProvider.getFake(userIdFromAccessToken, API_KEY_CLIENT_SECRET_MEMORY) + .nextMock, + ).toHaveBeenCalledWith(clientSecret); + }); + }); + + describe("Disk storage tests", () => { + it("should set the client secret in disk when there is an active user in global state", async () => { + // Arrange + globalStateProvider + .getFake(ACCOUNT_ACTIVE_ACCOUNT_ID) + .stateSubject.next(userIdFromAccessToken); + + // Act + await tokenService.setClientSecret( + clientSecret, + diskVaultTimeoutAction, + diskVaultTimeout, + ); + + // Assert + expect( + singleUserStateProvider.getFake(userIdFromAccessToken, API_KEY_CLIENT_SECRET_DISK) + .nextMock, + ).toHaveBeenCalledWith(clientSecret); + }); + + it("should set the client secret in disk for the specified user id", async () => { + // Act + await tokenService.setClientSecret( + clientSecret, + diskVaultTimeoutAction, + diskVaultTimeout, + userIdFromAccessToken, + ); + + // Assert + expect( + singleUserStateProvider.getFake(userIdFromAccessToken, API_KEY_CLIENT_SECRET_DISK) + .nextMock, + ).toHaveBeenCalledWith(clientSecret); + }); + }); + }); + + describe("getClientSecret", () => { + it("should return undefined if no user id is provided and there is no active user in global state", async () => { + // Act + const result = await tokenService.getClientSecret(); + // Assert + expect(result).toBeUndefined(); + }); + + it("should return null if no client secret is found in memory or disk", async () => { + // Arrange + globalStateProvider + .getFake(ACCOUNT_ACTIVE_ACCOUNT_ID) + .stateSubject.next(userIdFromAccessToken); + + // Act + const result = await tokenService.getClientSecret(); + // Assert + expect(result).toBeNull(); + }); + + describe("Memory storage tests", () => { + it("should get the client secret from memory with no user id specified (uses global active user)", async () => { + // Arrange + singleUserStateProvider + .getFake(userIdFromAccessToken, API_KEY_CLIENT_SECRET_MEMORY) + .stateSubject.next([userIdFromAccessToken, clientSecret]); + + // set disk to undefined + singleUserStateProvider + .getFake(userIdFromAccessToken, API_KEY_CLIENT_SECRET_DISK) + .stateSubject.next([userIdFromAccessToken, undefined]); + + // Need to have global active id set to the user id + globalStateProvider + .getFake(ACCOUNT_ACTIVE_ACCOUNT_ID) + .stateSubject.next(userIdFromAccessToken); + + // Act + const result = await tokenService.getClientSecret(); + + // Assert + expect(result).toEqual(clientSecret); + }); + + it("should get the client secret from memory for the specified user id", async () => { + // Arrange + singleUserStateProvider + .getFake(userIdFromAccessToken, API_KEY_CLIENT_SECRET_MEMORY) + .stateSubject.next([userIdFromAccessToken, clientSecret]); + + // set disk to undefined + singleUserStateProvider + .getFake(userIdFromAccessToken, API_KEY_CLIENT_SECRET_DISK) + .stateSubject.next([userIdFromAccessToken, undefined]); + + // Act + const result = await tokenService.getClientSecret(userIdFromAccessToken); + // Assert + expect(result).toEqual(clientSecret); + }); + }); + + describe("Disk storage tests", () => { + it("should get the client secret from disk with no user id specified", async () => { + // Arrange + singleUserStateProvider + .getFake(userIdFromAccessToken, API_KEY_CLIENT_SECRET_MEMORY) + .stateSubject.next([userIdFromAccessToken, undefined]); + + singleUserStateProvider + .getFake(userIdFromAccessToken, API_KEY_CLIENT_SECRET_DISK) + .stateSubject.next([userIdFromAccessToken, clientSecret]); + + // Need to have global active id set to the user id + globalStateProvider + .getFake(ACCOUNT_ACTIVE_ACCOUNT_ID) + .stateSubject.next(userIdFromAccessToken); + + // Act + const result = await tokenService.getClientSecret(); + // Assert + expect(result).toEqual(clientSecret); + }); + + it("should get the client secret from disk for the specified user id", async () => { + // Arrange + singleUserStateProvider + .getFake(userIdFromAccessToken, API_KEY_CLIENT_SECRET_MEMORY) + .stateSubject.next([userIdFromAccessToken, undefined]); + + singleUserStateProvider + .getFake(userIdFromAccessToken, API_KEY_CLIENT_SECRET_DISK) + .stateSubject.next([userIdFromAccessToken, clientSecret]); + + // Act + const result = await tokenService.getClientSecret(userIdFromAccessToken); + // Assert + expect(result).toEqual(clientSecret); + }); + }); + }); + + describe("clearClientSecret", () => { + it("should throw an error if no user id is provided and there is no active user in global state", async () => { + // Act + // note: don't await here because we want to test the error + const result = (tokenService as any).clearClientSecret(); + // Assert + await expect(result).rejects.toThrow("User id not found. Cannot clear client secret."); + }); + + it("should clear the client secret from memory and disk for the specified user id", async () => { + // Arrange + singleUserStateProvider + .getFake(userIdFromAccessToken, API_KEY_CLIENT_SECRET_MEMORY) + .stateSubject.next([userIdFromAccessToken, clientSecret]); + + singleUserStateProvider + .getFake(userIdFromAccessToken, API_KEY_CLIENT_SECRET_DISK) + .stateSubject.next([userIdFromAccessToken, clientSecret]); + + // Act + await (tokenService as any).clearClientSecret(userIdFromAccessToken); + + // Assert + expect( + singleUserStateProvider.getFake(userIdFromAccessToken, API_KEY_CLIENT_SECRET_MEMORY) + .nextMock, + ).toHaveBeenCalledWith(null); + expect( + singleUserStateProvider.getFake(userIdFromAccessToken, API_KEY_CLIENT_SECRET_DISK) + .nextMock, + ).toHaveBeenCalledWith(null); + }); + + it("should clear the client secret from memory and disk for the global active user", async () => { + // Arrange + singleUserStateProvider + .getFake(userIdFromAccessToken, API_KEY_CLIENT_SECRET_MEMORY) + .stateSubject.next([userIdFromAccessToken, clientSecret]); + + singleUserStateProvider + .getFake(userIdFromAccessToken, API_KEY_CLIENT_SECRET_DISK) + .stateSubject.next([userIdFromAccessToken, clientSecret]); + + // Need to have global active id set to the user id + globalStateProvider + .getFake(ACCOUNT_ACTIVE_ACCOUNT_ID) + .stateSubject.next(userIdFromAccessToken); + + // Act + await (tokenService as any).clearClientSecret(); + + // Assert + expect( + singleUserStateProvider.getFake(userIdFromAccessToken, API_KEY_CLIENT_SECRET_MEMORY) + .nextMock, + ).toHaveBeenCalledWith(null); + expect( + singleUserStateProvider.getFake(userIdFromAccessToken, API_KEY_CLIENT_SECRET_DISK) + .nextMock, + ).toHaveBeenCalledWith(null); + }); + }); + }); + + describe("setTokens", () => { + it("should call to set all passed in tokens after deriving user id from the access token", async () => { + // Arrange + const refreshToken = "refreshToken"; + // specific vault timeout actions and vault timeouts don't change this test so values don't matter. + const vaultTimeoutAction = VaultTimeoutAction.Lock; + const vaultTimeout = 30; + const clientId = "clientId"; + const clientSecret = "clientSecret"; + + (tokenService as any)._setAccessToken = jest.fn(); + // any hack allows for mocking private method. + (tokenService as any).setRefreshToken = jest.fn(); + tokenService.setClientId = jest.fn(); + tokenService.setClientSecret = jest.fn(); + + // Act + // Note: passing a valid access token so that a valid user id can be determined from the access token + await tokenService.setTokens(accessTokenJwt, refreshToken, vaultTimeoutAction, vaultTimeout, [ + clientId, + clientSecret, + ]); + + // Assert + expect((tokenService as any)._setAccessToken).toHaveBeenCalledWith( + accessTokenJwt, + vaultTimeoutAction, + vaultTimeout, + userIdFromAccessToken, + ); + + // any hack allows for testing private methods + expect((tokenService as any).setRefreshToken).toHaveBeenCalledWith( + refreshToken, + vaultTimeoutAction, + vaultTimeout, + userIdFromAccessToken, + ); + + expect(tokenService.setClientId).toHaveBeenCalledWith( + clientId, + vaultTimeoutAction, + vaultTimeout, + userIdFromAccessToken, + ); + expect(tokenService.setClientSecret).toHaveBeenCalledWith( + clientSecret, + vaultTimeoutAction, + vaultTimeout, + userIdFromAccessToken, + ); + }); + + it("should not try to set client id and client secret if they are not passed in", async () => { + // Arrange + const refreshToken = "refreshToken"; + const vaultTimeoutAction = VaultTimeoutAction.Lock; + const vaultTimeout = 30; + + (tokenService as any)._setAccessToken = jest.fn(); + (tokenService as any).setRefreshToken = jest.fn(); + tokenService.setClientId = jest.fn(); + tokenService.setClientSecret = jest.fn(); + + // Act + await tokenService.setTokens(accessTokenJwt, refreshToken, vaultTimeoutAction, vaultTimeout); + + // Assert + expect((tokenService as any)._setAccessToken).toHaveBeenCalledWith( + accessTokenJwt, + vaultTimeoutAction, + vaultTimeout, + userIdFromAccessToken, + ); + + // any hack allows for testing private methods + expect((tokenService as any).setRefreshToken).toHaveBeenCalledWith( + refreshToken, + vaultTimeoutAction, + vaultTimeout, + userIdFromAccessToken, + ); + + expect(tokenService.setClientId).not.toHaveBeenCalled(); + expect(tokenService.setClientSecret).not.toHaveBeenCalled(); + }); + + it("should throw an error if the access token is invalid", async () => { + // Arrange + const accessToken = "invalidToken"; + const refreshToken = "refreshToken"; + const vaultTimeoutAction = VaultTimeoutAction.Lock; + const vaultTimeout = 30; + + // Act + const result = tokenService.setTokens( + accessToken, + refreshToken, + vaultTimeoutAction, + vaultTimeout, + ); + + // Assert + await expect(result).rejects.toThrow("JWT must have 3 parts"); + }); + + it("should throw an error if the access token is missing", async () => { + // Arrange + const accessToken: string = null; + const refreshToken = "refreshToken"; + const vaultTimeoutAction = VaultTimeoutAction.Lock; + const vaultTimeout = 30; + + // Act + const result = tokenService.setTokens( + accessToken, + refreshToken, + vaultTimeoutAction, + vaultTimeout, + ); + + // Assert + await expect(result).rejects.toThrow("Access token and refresh token are required."); + }); + + it("should throw an error if the refresh token is missing", async () => { + // Arrange + const accessToken = "accessToken"; + const refreshToken: string = null; + const vaultTimeoutAction = VaultTimeoutAction.Lock; + const vaultTimeout = 30; + + // Act + const result = tokenService.setTokens( + accessToken, + refreshToken, + vaultTimeoutAction, + vaultTimeout, + ); + + // Assert + await expect(result).rejects.toThrow("Access token and refresh token are required."); + }); + }); + + describe("clearTokens", () => { + it("should call to clear all tokens for the specified user id", async () => { + // Arrange + const userId = "userId" as UserId; + + tokenService.clearAccessToken = jest.fn(); + (tokenService as any).clearRefreshToken = jest.fn(); + (tokenService as any).clearClientId = jest.fn(); + (tokenService as any).clearClientSecret = jest.fn(); + + // Act + + await tokenService.clearTokens(userId); + + // Assert + + expect(tokenService.clearAccessToken).toHaveBeenCalledWith(userId); + expect((tokenService as any).clearRefreshToken).toHaveBeenCalledWith(userId); + expect((tokenService as any).clearClientId).toHaveBeenCalledWith(userId); + expect((tokenService as any).clearClientSecret).toHaveBeenCalledWith(userId); + }); + + it("should call to clear all tokens for the active user id", async () => { + // Arrange + const userId = "userId" as UserId; + + globalStateProvider.getFake(ACCOUNT_ACTIVE_ACCOUNT_ID).stateSubject.next(userId); + + tokenService.clearAccessToken = jest.fn(); + (tokenService as any).clearRefreshToken = jest.fn(); + (tokenService as any).clearClientId = jest.fn(); + (tokenService as any).clearClientSecret = jest.fn(); + + // Act + + await tokenService.clearTokens(); + + // Assert + + expect(tokenService.clearAccessToken).toHaveBeenCalledWith(userId); + expect((tokenService as any).clearRefreshToken).toHaveBeenCalledWith(userId); + expect((tokenService as any).clearClientId).toHaveBeenCalledWith(userId); + expect((tokenService as any).clearClientSecret).toHaveBeenCalledWith(userId); + }); + + it("should not call to clear all tokens if no user id is provided and there is no active user in global state", async () => { + // Arrange + tokenService.clearAccessToken = jest.fn(); + (tokenService as any).clearRefreshToken = jest.fn(); + (tokenService as any).clearClientId = jest.fn(); + (tokenService as any).clearClientSecret = jest.fn(); + + // Act + + const result = tokenService.clearTokens(); + + // Assert + await expect(result).rejects.toThrow("User id not found. Cannot clear tokens."); + }); + }); + + describe("Two Factor Token methods", () => { + describe("setTwoFactorToken", () => { + it("should set the email and two factor token when there hasn't been a previous record (initializing the record)", async () => { + // Arrange + const email = "testUser@email.com"; + const twoFactorToken = "twoFactorTokenForTestUser"; + // Act + await tokenService.setTwoFactorToken(email, twoFactorToken); + // Assert + expect( + globalStateProvider.getFake(EMAIL_TWO_FACTOR_TOKEN_RECORD_DISK_LOCAL).nextMock, + ).toHaveBeenCalledWith({ [email]: twoFactorToken }); + }); + + it("should set the email and two factor token when there is an initialized value already (updating the existing record)", async () => { + // Arrange + const email = "testUser@email.com"; + const twoFactorToken = "twoFactorTokenForTestUser"; + const initialTwoFactorTokenRecord: Record = { + otherUser: "otherUserTwoFactorToken", + }; + + globalStateProvider + .getFake(EMAIL_TWO_FACTOR_TOKEN_RECORD_DISK_LOCAL) + .stateSubject.next(initialTwoFactorTokenRecord); + + // Act + await tokenService.setTwoFactorToken(email, twoFactorToken); + + // Assert + expect( + globalStateProvider.getFake(EMAIL_TWO_FACTOR_TOKEN_RECORD_DISK_LOCAL).nextMock, + ).toHaveBeenCalledWith({ [email]: twoFactorToken, ...initialTwoFactorTokenRecord }); + }); + }); + + describe("getTwoFactorToken", () => { + it("should return the two factor token for the given email", async () => { + // Arrange + const email = "testUser"; + const twoFactorToken = "twoFactorTokenForTestUser"; + const initialTwoFactorTokenRecord: Record = { + [email]: twoFactorToken, + }; + + globalStateProvider + .getFake(EMAIL_TWO_FACTOR_TOKEN_RECORD_DISK_LOCAL) + .stateSubject.next(initialTwoFactorTokenRecord); + + // Act + const result = await tokenService.getTwoFactorToken(email); + + // Assert + expect(result).toEqual(twoFactorToken); + }); + + it("should not return the two factor token for an email that doesn't exist", async () => { + // Arrange + const email = "testUser"; + const initialTwoFactorTokenRecord: Record = { + otherUser: "twoFactorTokenForOtherUser", + }; + + globalStateProvider + .getFake(EMAIL_TWO_FACTOR_TOKEN_RECORD_DISK_LOCAL) + .stateSubject.next(initialTwoFactorTokenRecord); + + // Act + const result = await tokenService.getTwoFactorToken(email); + + // Assert + expect(result).toEqual(undefined); + }); + + it("should return null if there is no two factor token record", async () => { + // Arrange + globalStateProvider + .getFake(EMAIL_TWO_FACTOR_TOKEN_RECORD_DISK_LOCAL) + .stateSubject.next(null); + + // Act + const result = await tokenService.getTwoFactorToken("testUser"); + + // Assert + expect(result).toEqual(null); + }); + }); + + describe("clearTwoFactorToken", () => { + it("should clear the two factor token for the given email when a record exists", async () => { + // Arrange + const email = "testUser"; + const twoFactorToken = "twoFactorTokenForTestUser"; + const initialTwoFactorTokenRecord: Record = { + [email]: twoFactorToken, + }; + + globalStateProvider + .getFake(EMAIL_TWO_FACTOR_TOKEN_RECORD_DISK_LOCAL) + .stateSubject.next(initialTwoFactorTokenRecord); + + // Act + await tokenService.clearTwoFactorToken(email); + + // Assert + expect( + globalStateProvider.getFake(EMAIL_TWO_FACTOR_TOKEN_RECORD_DISK_LOCAL).nextMock, + ).toHaveBeenCalledWith({}); + }); + + it("should initialize the record if it doesn't exist and delete the value", async () => { + // Arrange + const email = "testUser"; + + // Act + await tokenService.clearTwoFactorToken(email); + + // Assert + expect( + globalStateProvider.getFake(EMAIL_TWO_FACTOR_TOKEN_RECORD_DISK_LOCAL).nextMock, + ).toHaveBeenCalledWith({}); + }); + }); + }); + + // Helpers + function createTokenService(supportsSecureStorage: boolean) { + return new TokenService( + singleUserStateProvider, + globalStateProvider, + supportsSecureStorage, + secureStorageService, + ); + } +}); diff --git a/libs/common/src/auth/services/token.service.ts b/libs/common/src/auth/services/token.service.ts index b112c7b57d65..4e9722614edf 100644 --- a/libs/common/src/auth/services/token.service.ts +++ b/libs/common/src/auth/services/token.service.ts @@ -1,125 +1,629 @@ -import { StateService } from "../../platform/abstractions/state.service"; -import { Utils } from "../../platform/misc/utils"; +import { firstValueFrom } from "rxjs"; + +import { decodeJwtTokenToJson } from "@bitwarden/auth/common"; + +import { VaultTimeoutAction } from "../../enums/vault-timeout-action.enum"; +import { AbstractStorageService } from "../../platform/abstractions/storage.service"; +import { StorageLocation } from "../../platform/enums"; +import { StorageOptions } from "../../platform/models/domain/storage-options"; +import { + GlobalState, + GlobalStateProvider, + KeyDefinition, + SingleUserStateProvider, +} from "../../platform/state"; +import { UserId } from "../../types/guid"; import { TokenService as TokenServiceAbstraction } from "../abstractions/token.service"; -import { IdentityTokenResponse } from "../models/response/identity-token.response"; + +import { ACCOUNT_ACTIVE_ACCOUNT_ID } from "./account.service"; +import { + ACCESS_TOKEN_DISK, + ACCESS_TOKEN_MEMORY, + ACCESS_TOKEN_MIGRATED_TO_SECURE_STORAGE, + API_KEY_CLIENT_ID_DISK, + API_KEY_CLIENT_ID_MEMORY, + API_KEY_CLIENT_SECRET_DISK, + API_KEY_CLIENT_SECRET_MEMORY, + EMAIL_TWO_FACTOR_TOKEN_RECORD_DISK_LOCAL, + REFRESH_TOKEN_DISK, + REFRESH_TOKEN_MEMORY, + REFRESH_TOKEN_MIGRATED_TO_SECURE_STORAGE, +} from "./token.state"; + +export enum TokenStorageLocation { + Disk = "disk", + SecureStorage = "secureStorage", + Memory = "memory", +} + +/** + * Type representing the structure of a standard Bitwarden decoded access token. + * src: https://datatracker.ietf.org/doc/html/rfc7519#section-4.1 + * Note: all claims are technically optional so we must verify their existence before using them. + * Note 2: NumericDate is a number representing a date in seconds since the Unix epoch. + */ +export type DecodedAccessToken = { + /** Issuer - the issuer of the token, typically the URL of the authentication server */ + iss?: string; + + /** Not Before - a timestamp defining when the token starts being valid */ + nbf?: number; + + /** Issued At - a timestamp of when the token was issued */ + iat?: number; + + /** Expiration Time - a NumericDate timestamp of when the token will expire */ + exp?: number; + + /** Scope - the scope of the access request, such as the permissions the token grants */ + scope?: string[]; + + /** Authentication Method Reference - the methods used in the authentication */ + amr?: string[]; + + /** Client ID - the identifier for the client that requested the token */ + client_id?: string; + + /** Subject - the unique identifier for the user */ + sub?: string; + + /** Authentication Time - a timestamp of when the user authentication occurred */ + auth_time?: number; + + /** Identity Provider - the system or service that authenticated the user */ + idp?: string; + + /** Premium - a boolean flag indicating whether the account is premium */ + premium?: boolean; + + /** Email - the user's email address */ + email?: string; + + /** Email Verified - a boolean flag indicating whether the user's email address has been verified */ + email_verified?: boolean; + + /** + * Security Stamp - a unique identifier which invalidates the access token if it changes in the db + * (typically after critical account changes like a password change) + */ + sstamp?: string; + + /** Name - the name of the user */ + name?: string; + + /** Organization Owners - a list of organization owner identifiers */ + orgowner?: string[]; + + /** Device - the identifier of the device used */ + device?: string; + + /** JWT ID - a unique identifier for the JWT */ + jti?: string; +}; export class TokenService implements TokenServiceAbstraction { - static decodeToken(token: string): Promise { - if (token == null) { - throw new Error("Token not provided."); - } + private readonly accessTokenSecureStorageKey: string = "_accessToken"; - const parts = token.split("."); - if (parts.length !== 3) { - throw new Error("JWT must have 3 parts"); - } + private readonly refreshTokenSecureStorageKey: string = "_refreshToken"; - const decoded = Utils.fromUrlB64ToUtf8(parts[1]); - if (decoded == null) { - throw new Error("Cannot decode the token"); - } + private emailTwoFactorTokenRecordGlobalState: GlobalState>; + + private activeUserIdGlobalState: GlobalState; - const decodedToken = JSON.parse(decoded); - return decodedToken; + constructor( + // Note: we cannot use ActiveStateProvider because if we ever want to inject + // this service into the AccountService, we will make a circular dependency + private singleUserStateProvider: SingleUserStateProvider, + private globalStateProvider: GlobalStateProvider, + private readonly platformSupportsSecureStorage: boolean, + private secureStorageService: AbstractStorageService, + ) { + this.initializeState(); } - constructor(private stateService: StateService) {} + private initializeState(): void { + this.emailTwoFactorTokenRecordGlobalState = this.globalStateProvider.get( + EMAIL_TWO_FACTOR_TOKEN_RECORD_DISK_LOCAL, + ); + + this.activeUserIdGlobalState = this.globalStateProvider.get(ACCOUNT_ACTIVE_ACCOUNT_ID); + } async setTokens( accessToken: string, refreshToken: string, - clientIdClientSecret: [string, string], - ): Promise { - await this.setToken(accessToken); - await this.setRefreshToken(refreshToken); + vaultTimeoutAction: VaultTimeoutAction, + vaultTimeout: number | null, + clientIdClientSecret?: [string, string], + ): Promise { + if (!accessToken || !refreshToken) { + throw new Error("Access token and refresh token are required."); + } + + // get user id the access token + const userId: UserId = await this.getUserIdFromAccessToken(accessToken); + + if (!userId) { + throw new Error("User id not found. Cannot set tokens."); + } + + await this._setAccessToken(accessToken, vaultTimeoutAction, vaultTimeout, userId); + await this.setRefreshToken(refreshToken, vaultTimeoutAction, vaultTimeout, userId); if (clientIdClientSecret != null) { - await this.setClientId(clientIdClientSecret[0]); - await this.setClientSecret(clientIdClientSecret[1]); + await this.setClientId(clientIdClientSecret[0], vaultTimeoutAction, vaultTimeout, userId); + await this.setClientSecret(clientIdClientSecret[1], vaultTimeoutAction, vaultTimeout, userId); + } + } + + /** + * Internal helper for set access token which always requires user id. + * This is useful because setTokens always will have a user id from the access token whereas + * the public setAccessToken method does not. + */ + private async _setAccessToken( + accessToken: string, + vaultTimeoutAction: VaultTimeoutAction, + vaultTimeout: number | null, + userId: UserId, + ): Promise { + const storageLocation = await this.determineStorageLocation( + vaultTimeoutAction, + vaultTimeout, + true, + ); + + switch (storageLocation) { + case TokenStorageLocation.SecureStorage: + await this.saveStringToSecureStorage(userId, this.accessTokenSecureStorageKey, accessToken); + + // TODO: PM-6408 - https://bitwarden.atlassian.net/browse/PM-6408 + // 2024-02-20: Remove access token from memory and disk so that we migrate to secure storage over time. + // Remove these 2 calls to remove the access token from memory and disk after 3 releases. + + await this.singleUserStateProvider.get(userId, ACCESS_TOKEN_DISK).update((_) => null); + await this.singleUserStateProvider.get(userId, ACCESS_TOKEN_MEMORY).update((_) => null); + + // Set flag to indicate that the access token has been migrated to secure storage (don't remove this) + await this.setAccessTokenMigratedToSecureStorage(userId); + + return; + case TokenStorageLocation.Disk: + await this.singleUserStateProvider + .get(userId, ACCESS_TOKEN_DISK) + .update((_) => accessToken); + return; + case TokenStorageLocation.Memory: + await this.singleUserStateProvider + .get(userId, ACCESS_TOKEN_MEMORY) + .update((_) => accessToken); + return; + } + } + + async setAccessToken( + accessToken: string, + vaultTimeoutAction: VaultTimeoutAction, + vaultTimeout: number | null, + ): Promise { + if (!accessToken) { + throw new Error("Access token is required."); + } + const userId: UserId = await this.getUserIdFromAccessToken(accessToken); + + // If we don't have a user id, we can't save the value + if (!userId) { + throw new Error("User id not found. Cannot save access token."); + } + + await this._setAccessToken(accessToken, vaultTimeoutAction, vaultTimeout, userId); + } + + async clearAccessToken(userId?: UserId): Promise { + userId ??= await firstValueFrom(this.activeUserIdGlobalState.state$); + + // If we don't have a user id, we can't clear the value + if (!userId) { + throw new Error("User id not found. Cannot clear access token."); + } + + // TODO: re-eval this once we get shared key definitions for vault timeout and vault timeout action data. + // we can't determine storage location w/out vaultTimeoutAction and vaultTimeout + // but we can simply clear all locations to avoid the need to require those parameters + + if (this.platformSupportsSecureStorage) { + await this.secureStorageService.remove( + `${userId}${this.accessTokenSecureStorageKey}`, + this.getSecureStorageOptions(userId), + ); + } + + // Platform doesn't support secure storage, so use state provider implementation + await this.singleUserStateProvider.get(userId, ACCESS_TOKEN_DISK).update((_) => null); + await this.singleUserStateProvider.get(userId, ACCESS_TOKEN_MEMORY).update((_) => null); + } + + async getAccessToken(userId?: UserId): Promise { + userId ??= await firstValueFrom(this.activeUserIdGlobalState.state$); + + if (!userId) { + return undefined; + } + + const accessTokenMigratedToSecureStorage = + await this.getAccessTokenMigratedToSecureStorage(userId); + if (this.platformSupportsSecureStorage && accessTokenMigratedToSecureStorage) { + return await this.getStringFromSecureStorage(userId, this.accessTokenSecureStorageKey); + } + + // Try to get the access token from memory + const accessTokenMemory = await this.getStateValueByUserIdAndKeyDef( + userId, + ACCESS_TOKEN_MEMORY, + ); + + if (accessTokenMemory != null) { + return accessTokenMemory; + } + + // If memory is null, read from disk + return await this.getStateValueByUserIdAndKeyDef(userId, ACCESS_TOKEN_DISK); + } + + private async getAccessTokenMigratedToSecureStorage(userId: UserId): Promise { + return await firstValueFrom( + this.singleUserStateProvider.get(userId, ACCESS_TOKEN_MIGRATED_TO_SECURE_STORAGE).state$, + ); + } + + private async setAccessTokenMigratedToSecureStorage(userId: UserId): Promise { + await this.singleUserStateProvider + .get(userId, ACCESS_TOKEN_MIGRATED_TO_SECURE_STORAGE) + .update((_) => true); + } + + // Private because we only ever set the refresh token when also setting the access token + // and we need the user id from the access token to save to secure storage + private async setRefreshToken( + refreshToken: string, + vaultTimeoutAction: VaultTimeoutAction, + vaultTimeout: number | null, + userId: UserId, + ): Promise { + // If we don't have a user id, we can't save the value + if (!userId) { + throw new Error("User id not found. Cannot save refresh token."); + } + + const storageLocation = await this.determineStorageLocation( + vaultTimeoutAction, + vaultTimeout, + true, + ); + + switch (storageLocation) { + case TokenStorageLocation.SecureStorage: + await this.saveStringToSecureStorage( + userId, + this.refreshTokenSecureStorageKey, + refreshToken, + ); + + // TODO: PM-6408 - https://bitwarden.atlassian.net/browse/PM-6408 + // 2024-02-20: Remove refresh token from memory and disk so that we migrate to secure storage over time. + // Remove these 2 calls to remove the refresh token from memory and disk after 3 releases. + await this.singleUserStateProvider.get(userId, REFRESH_TOKEN_DISK).update((_) => null); + await this.singleUserStateProvider.get(userId, REFRESH_TOKEN_MEMORY).update((_) => null); + + // Set flag to indicate that the refresh token has been migrated to secure storage (don't remove this) + await this.setRefreshTokenMigratedToSecureStorage(userId); + + return; + + case TokenStorageLocation.Disk: + await this.singleUserStateProvider + .get(userId, REFRESH_TOKEN_DISK) + .update((_) => refreshToken); + return; + + case TokenStorageLocation.Memory: + await this.singleUserStateProvider + .get(userId, REFRESH_TOKEN_MEMORY) + .update((_) => refreshToken); + return; + } + } + + async getRefreshToken(userId?: UserId): Promise { + userId ??= await firstValueFrom(this.activeUserIdGlobalState.state$); + + if (!userId) { + return undefined; + } + + const refreshTokenMigratedToSecureStorage = + await this.getRefreshTokenMigratedToSecureStorage(userId); + if (this.platformSupportsSecureStorage && refreshTokenMigratedToSecureStorage) { + return await this.getStringFromSecureStorage(userId, this.refreshTokenSecureStorageKey); + } + + // pre-secure storage migration: + // Always read memory first b/c faster + const refreshTokenMemory = await this.getStateValueByUserIdAndKeyDef( + userId, + REFRESH_TOKEN_MEMORY, + ); + + if (refreshTokenMemory != null) { + return refreshTokenMemory; } + + // if memory is null, read from disk + const refreshTokenDisk = await this.getStateValueByUserIdAndKeyDef(userId, REFRESH_TOKEN_DISK); + + if (refreshTokenDisk != null) { + return refreshTokenDisk; + } + + return null; } - async setClientId(clientId: string): Promise { - return await this.stateService.setApiKeyClientId(clientId); + private async clearRefreshToken(userId: UserId): Promise { + // If we don't have a user id, we can't clear the value + if (!userId) { + throw new Error("User id not found. Cannot clear refresh token."); + } + + // TODO: re-eval this once we get shared key definitions for vault timeout and vault timeout action data. + // we can't determine storage location w/out vaultTimeoutAction and vaultTimeout + // but we can simply clear all locations to avoid the need to require those parameters + + if (this.platformSupportsSecureStorage) { + await this.secureStorageService.remove( + `${userId}${this.refreshTokenSecureStorageKey}`, + this.getSecureStorageOptions(userId), + ); + } + + // Platform doesn't support secure storage, so use state provider implementation + await this.singleUserStateProvider.get(userId, REFRESH_TOKEN_MEMORY).update((_) => null); + await this.singleUserStateProvider.get(userId, REFRESH_TOKEN_DISK).update((_) => null); } - async getClientId(): Promise { - return await this.stateService.getApiKeyClientId(); + private async getRefreshTokenMigratedToSecureStorage(userId: UserId): Promise { + return await firstValueFrom( + this.singleUserStateProvider.get(userId, REFRESH_TOKEN_MIGRATED_TO_SECURE_STORAGE).state$, + ); } - async setClientSecret(clientSecret: string): Promise { - return await this.stateService.setApiKeyClientSecret(clientSecret); + private async setRefreshTokenMigratedToSecureStorage(userId: UserId): Promise { + await this.singleUserStateProvider + .get(userId, REFRESH_TOKEN_MIGRATED_TO_SECURE_STORAGE) + .update((_) => true); } - async getClientSecret(): Promise { - return await this.stateService.getApiKeyClientSecret(); + async setClientId( + clientId: string, + vaultTimeoutAction: VaultTimeoutAction, + vaultTimeout: number | null, + userId?: UserId, + ): Promise { + userId ??= await firstValueFrom(this.activeUserIdGlobalState.state$); + + // If we don't have a user id, we can't save the value + if (!userId) { + throw new Error("User id not found. Cannot save client id."); + } + + const storageLocation = await this.determineStorageLocation( + vaultTimeoutAction, + vaultTimeout, + false, + ); + + if (storageLocation === TokenStorageLocation.Disk) { + await this.singleUserStateProvider + .get(userId, API_KEY_CLIENT_ID_DISK) + .update((_) => clientId); + } else if (storageLocation === TokenStorageLocation.Memory) { + await this.singleUserStateProvider + .get(userId, API_KEY_CLIENT_ID_MEMORY) + .update((_) => clientId); + } } - async setToken(token: string): Promise { - await this.stateService.setAccessToken(token); + async getClientId(userId?: UserId): Promise { + userId ??= await firstValueFrom(this.activeUserIdGlobalState.state$); + + if (!userId) { + return undefined; + } + + // Always read memory first b/c faster + const apiKeyClientIdMemory = await this.getStateValueByUserIdAndKeyDef( + userId, + API_KEY_CLIENT_ID_MEMORY, + ); + + if (apiKeyClientIdMemory != null) { + return apiKeyClientIdMemory; + } + + // if memory is null, read from disk + return await this.getStateValueByUserIdAndKeyDef(userId, API_KEY_CLIENT_ID_DISK); } - async getToken(): Promise { - return await this.stateService.getAccessToken(); + private async clearClientId(userId?: UserId): Promise { + userId ??= await firstValueFrom(this.activeUserIdGlobalState.state$); + + // If we don't have a user id, we can't clear the value + if (!userId) { + throw new Error("User id not found. Cannot clear client id."); + } + + // TODO: re-eval this once we get shared key definitions for vault timeout and vault timeout action data. + // we can't determine storage location w/out vaultTimeoutAction and vaultTimeout + // but we can simply clear both locations to avoid the need to require those parameters + + // Platform doesn't support secure storage, so use state provider implementation + await this.singleUserStateProvider.get(userId, API_KEY_CLIENT_ID_MEMORY).update((_) => null); + await this.singleUserStateProvider.get(userId, API_KEY_CLIENT_ID_DISK).update((_) => null); } - async setRefreshToken(refreshToken: string): Promise { - return await this.stateService.setRefreshToken(refreshToken); + async setClientSecret( + clientSecret: string, + vaultTimeoutAction: VaultTimeoutAction, + vaultTimeout: number | null, + userId?: UserId, + ): Promise { + userId ??= await firstValueFrom(this.activeUserIdGlobalState.state$); + + if (!userId) { + throw new Error("User id not found. Cannot save client secret."); + } + + const storageLocation = await this.determineStorageLocation( + vaultTimeoutAction, + vaultTimeout, + false, + ); + + if (storageLocation === TokenStorageLocation.Disk) { + await this.singleUserStateProvider + .get(userId, API_KEY_CLIENT_SECRET_DISK) + .update((_) => clientSecret); + } else if (storageLocation === TokenStorageLocation.Memory) { + await this.singleUserStateProvider + .get(userId, API_KEY_CLIENT_SECRET_MEMORY) + .update((_) => clientSecret); + } } - async getRefreshToken(): Promise { - return await this.stateService.getRefreshToken(); + async getClientSecret(userId?: UserId): Promise { + userId ??= await firstValueFrom(this.activeUserIdGlobalState.state$); + + if (!userId) { + return undefined; + } + + // Always read memory first b/c faster + const apiKeyClientSecretMemory = await this.getStateValueByUserIdAndKeyDef( + userId, + API_KEY_CLIENT_SECRET_MEMORY, + ); + + if (apiKeyClientSecretMemory != null) { + return apiKeyClientSecretMemory; + } + + // if memory is null, read from disk + return await this.getStateValueByUserIdAndKeyDef(userId, API_KEY_CLIENT_SECRET_DISK); } - async setTwoFactorToken(tokenResponse: IdentityTokenResponse): Promise { - return await this.stateService.setTwoFactorToken(tokenResponse.twoFactorToken); + private async clearClientSecret(userId?: UserId): Promise { + userId ??= await firstValueFrom(this.activeUserIdGlobalState.state$); + + // If we don't have a user id, we can't clear the value + if (!userId) { + throw new Error("User id not found. Cannot clear client secret."); + } + + // TODO: re-eval this once we get shared key definitions for vault timeout and vault timeout action data. + // we can't determine storage location w/out vaultTimeoutAction and vaultTimeout + // but we can simply clear both locations to avoid the need to require those parameters + + // Platform doesn't support secure storage, so use state provider implementation + await this.singleUserStateProvider + .get(userId, API_KEY_CLIENT_SECRET_MEMORY) + .update((_) => null); + await this.singleUserStateProvider.get(userId, API_KEY_CLIENT_SECRET_DISK).update((_) => null); } - async getTwoFactorToken(): Promise { - return await this.stateService.getTwoFactorToken(); + async setTwoFactorToken(email: string, twoFactorToken: string): Promise { + await this.emailTwoFactorTokenRecordGlobalState.update((emailTwoFactorTokenRecord) => { + emailTwoFactorTokenRecord ??= {}; + + emailTwoFactorTokenRecord[email] = twoFactorToken; + return emailTwoFactorTokenRecord; + }); } - async clearTwoFactorToken(): Promise { - return await this.stateService.setTwoFactorToken(null); + async getTwoFactorToken(email: string): Promise { + const emailTwoFactorTokenRecord: Record = await firstValueFrom( + this.emailTwoFactorTokenRecordGlobalState.state$, + ); + + if (!emailTwoFactorTokenRecord) { + return null; + } + + return emailTwoFactorTokenRecord[email]; } - async clearToken(userId?: string): Promise { - await this.stateService.setAccessToken(null, { userId: userId }); - await this.stateService.setRefreshToken(null, { userId: userId }); - await this.stateService.setApiKeyClientId(null, { userId: userId }); - await this.stateService.setApiKeyClientSecret(null, { userId: userId }); + async clearTwoFactorToken(email: string): Promise { + await this.emailTwoFactorTokenRecordGlobalState.update((emailTwoFactorTokenRecord) => { + emailTwoFactorTokenRecord ??= {}; + delete emailTwoFactorTokenRecord[email]; + return emailTwoFactorTokenRecord; + }); + } + + async clearTokens(userId?: UserId): Promise { + userId ??= await firstValueFrom(this.activeUserIdGlobalState.state$); + + if (!userId) { + throw new Error("User id not found. Cannot clear tokens."); + } + + await Promise.all([ + this.clearAccessToken(userId), + this.clearRefreshToken(userId), + this.clearClientId(userId), + this.clearClientSecret(userId), + ]); } // jwthelper methods // ref https://github.com/auth0/angular-jwt/blob/master/src/angularJwt/services/jwt.js - async decodeToken(token?: string): Promise { - token = token ?? (await this.stateService.getAccessToken()); + async decodeAccessToken(token?: string): Promise { + token = token ?? (await this.getAccessToken()); if (token == null) { - throw new Error("Token not found."); + throw new Error("Access token not found."); } - return TokenService.decodeToken(token); + return decodeJwtTokenToJson(token) as DecodedAccessToken; } - async getTokenExpirationDate(): Promise { - const decoded = await this.decodeToken(); - if (typeof decoded.exp === "undefined") { + // TODO: PM-6678- tech debt - consider consolidating the return types of all these access + // token data retrieval methods to return null if something goes wrong instead of throwing an error. + + async getTokenExpirationDate(): Promise { + let decoded: DecodedAccessToken; + try { + decoded = await this.decodeAccessToken(); + } catch (error) { + throw new Error("Failed to decode access token: " + error.message); + } + + // per RFC, exp claim is optional but if it exists, it should be a number + if (!decoded || typeof decoded.exp !== "number") { return null; } - const d = new Date(0); // The 0 here is the key, which sets the date to the epoch - d.setUTCSeconds(decoded.exp); - return d; + // The 0 in Date(0) is the key; it sets the date to the epoch + const expirationDate = new Date(0); + expirationDate.setUTCSeconds(decoded.exp); + return expirationDate; } async tokenSecondsRemaining(offsetSeconds = 0): Promise { - const d = await this.getTokenExpirationDate(); - if (d == null) { + const date = await this.getTokenExpirationDate(); + if (date == null) { return 0; } - const msRemaining = d.valueOf() - (new Date().valueOf() + offsetSeconds * 1000); + const msRemaining = date.valueOf() - (new Date().valueOf() + offsetSeconds * 1000); return Math.round(msRemaining / 1000); } @@ -128,54 +632,159 @@ export class TokenService implements TokenServiceAbstraction { return sRemaining < 60 * minutes; } - async getUserId(): Promise { - const decoded = await this.decodeToken(); - if (typeof decoded.sub === "undefined") { + async getUserId(): Promise { + let decoded: DecodedAccessToken; + try { + decoded = await this.decodeAccessToken(); + } catch (error) { + throw new Error("Failed to decode access token: " + error.message); + } + + if (!decoded || typeof decoded.sub !== "string") { + throw new Error("No user id found"); + } + + return decoded.sub as UserId; + } + + private async getUserIdFromAccessToken(accessToken: string): Promise { + let decoded: DecodedAccessToken; + try { + decoded = await this.decodeAccessToken(accessToken); + } catch (error) { + throw new Error("Failed to decode access token: " + error.message); + } + + if (!decoded || typeof decoded.sub !== "string") { throw new Error("No user id found"); } - return decoded.sub as string; + return decoded.sub as UserId; } async getEmail(): Promise { - const decoded = await this.decodeToken(); - if (typeof decoded.email === "undefined") { + let decoded: DecodedAccessToken; + try { + decoded = await this.decodeAccessToken(); + } catch (error) { + throw new Error("Failed to decode access token: " + error.message); + } + + if (!decoded || typeof decoded.email !== "string") { throw new Error("No email found"); } - return decoded.email as string; + return decoded.email; } async getEmailVerified(): Promise { - const decoded = await this.decodeToken(); - if (typeof decoded.email_verified === "undefined") { + let decoded: DecodedAccessToken; + try { + decoded = await this.decodeAccessToken(); + } catch (error) { + throw new Error("Failed to decode access token: " + error.message); + } + + if (!decoded || typeof decoded.email_verified !== "boolean") { throw new Error("No email verification found"); } - return decoded.email_verified as boolean; + return decoded.email_verified; } async getName(): Promise { - const decoded = await this.decodeToken(); - if (typeof decoded.name === "undefined") { + let decoded: DecodedAccessToken; + try { + decoded = await this.decodeAccessToken(); + } catch (error) { + throw new Error("Failed to decode access token: " + error.message); + } + + if (!decoded || typeof decoded.name !== "string") { return null; } - return decoded.name as string; + return decoded.name; } async getIssuer(): Promise { - const decoded = await this.decodeToken(); - if (typeof decoded.iss === "undefined") { + let decoded: DecodedAccessToken; + try { + decoded = await this.decodeAccessToken(); + } catch (error) { + throw new Error("Failed to decode access token: " + error.message); + } + + if (!decoded || typeof decoded.iss !== "string") { throw new Error("No issuer found"); } - return decoded.iss as string; + return decoded.iss; } async getIsExternal(): Promise { - const decoded = await this.decodeToken(); + let decoded: DecodedAccessToken; + try { + decoded = await this.decodeAccessToken(); + } catch (error) { + throw new Error("Failed to decode access token: " + error.message); + } return Array.isArray(decoded.amr) && decoded.amr.includes("external"); } + + private async getStateValueByUserIdAndKeyDef( + userId: UserId, + storageLocation: KeyDefinition, + ): Promise { + // read from single user state provider + return await firstValueFrom(this.singleUserStateProvider.get(userId, storageLocation).state$); + } + + private async determineStorageLocation( + vaultTimeoutAction: VaultTimeoutAction, + vaultTimeout: number | null, + useSecureStorage: boolean, + ): Promise { + if (vaultTimeoutAction === VaultTimeoutAction.LogOut && vaultTimeout != null) { + return TokenStorageLocation.Memory; + } else { + if (useSecureStorage && this.platformSupportsSecureStorage) { + return TokenStorageLocation.SecureStorage; + } + + return TokenStorageLocation.Disk; + } + } + + private async saveStringToSecureStorage( + userId: UserId, + storageKey: string, + value: string, + ): Promise { + await this.secureStorageService.save( + `${userId}${storageKey}`, + value, + this.getSecureStorageOptions(userId), + ); + } + + private async getStringFromSecureStorage( + userId: UserId, + storageKey: string, + ): Promise { + // If we have a user ID, read from secure storage. + return await this.secureStorageService.get( + `${userId}${storageKey}`, + this.getSecureStorageOptions(userId), + ); + } + + private getSecureStorageOptions(userId: UserId): StorageOptions { + return { + storageLocation: StorageLocation.Disk, + useSecureStorage: true, + userId: userId, + }; + } } diff --git a/libs/common/src/auth/services/token.state.spec.ts b/libs/common/src/auth/services/token.state.spec.ts new file mode 100644 index 000000000000..f4089a73fb47 --- /dev/null +++ b/libs/common/src/auth/services/token.state.spec.ts @@ -0,0 +1,64 @@ +import { KeyDefinition } from "../../platform/state"; + +import { + ACCESS_TOKEN_DISK, + ACCESS_TOKEN_MEMORY, + ACCESS_TOKEN_MIGRATED_TO_SECURE_STORAGE, + API_KEY_CLIENT_ID_DISK, + API_KEY_CLIENT_ID_MEMORY, + API_KEY_CLIENT_SECRET_DISK, + API_KEY_CLIENT_SECRET_MEMORY, + EMAIL_TWO_FACTOR_TOKEN_RECORD_DISK_LOCAL, + REFRESH_TOKEN_DISK, + REFRESH_TOKEN_MEMORY, + REFRESH_TOKEN_MIGRATED_TO_SECURE_STORAGE, +} from "./token.state"; + +describe.each([ + [ACCESS_TOKEN_DISK, "accessTokenDisk"], + [ACCESS_TOKEN_MEMORY, "accessTokenMemory"], + [ACCESS_TOKEN_MIGRATED_TO_SECURE_STORAGE, true], + [REFRESH_TOKEN_DISK, "refreshTokenDisk"], + [REFRESH_TOKEN_MEMORY, "refreshTokenMemory"], + [REFRESH_TOKEN_MIGRATED_TO_SECURE_STORAGE, true], + [EMAIL_TWO_FACTOR_TOKEN_RECORD_DISK_LOCAL, { user: "token" }], + [API_KEY_CLIENT_ID_DISK, "apiKeyClientIdDisk"], + [API_KEY_CLIENT_ID_MEMORY, "apiKeyClientIdMemory"], + [API_KEY_CLIENT_SECRET_DISK, "apiKeyClientSecretDisk"], + [API_KEY_CLIENT_SECRET_MEMORY, "apiKeyClientSecretMemory"], +])( + "deserializes state key definitions", + ( + keyDefinition: + | KeyDefinition + | KeyDefinition + | KeyDefinition>, + state: string | boolean | Record, + ) => { + function getTypeDescription(value: any): string { + if (isRecord(value)) { + return "Record"; + } else if (Array.isArray(value)) { + return "array"; + } else if (value === null) { + return "null"; + } + + // Fallback for primitive types + return typeof value; + } + + function isRecord(value: any): value is Record { + return typeof value === "object" && value !== null && !Array.isArray(value); + } + + function testDeserialization(keyDefinition: KeyDefinition, state: T) { + const deserialized = keyDefinition.deserializer(JSON.parse(JSON.stringify(state))); + expect(deserialized).toEqual(state); + } + + it(`should deserialize state for KeyDefinition<${getTypeDescription(state)}>: "${keyDefinition.key}"`, () => { + testDeserialization(keyDefinition, state); + }); + }, +); diff --git a/libs/common/src/auth/services/token.state.ts b/libs/common/src/auth/services/token.state.ts new file mode 100644 index 000000000000..022f56f7aa55 --- /dev/null +++ b/libs/common/src/auth/services/token.state.ts @@ -0,0 +1,65 @@ +import { KeyDefinition, TOKEN_DISK, TOKEN_DISK_LOCAL, TOKEN_MEMORY } from "../../platform/state"; + +export const ACCESS_TOKEN_DISK = new KeyDefinition(TOKEN_DISK, "accessToken", { + deserializer: (accessToken) => accessToken, +}); + +export const ACCESS_TOKEN_MEMORY = new KeyDefinition(TOKEN_MEMORY, "accessToken", { + deserializer: (accessToken) => accessToken, +}); + +export const ACCESS_TOKEN_MIGRATED_TO_SECURE_STORAGE = new KeyDefinition( + TOKEN_DISK, + "accessTokenMigratedToSecureStorage", + { + deserializer: (accessTokenMigratedToSecureStorage) => accessTokenMigratedToSecureStorage, + }, +); + +export const REFRESH_TOKEN_DISK = new KeyDefinition(TOKEN_DISK, "refreshToken", { + deserializer: (refreshToken) => refreshToken, +}); + +export const REFRESH_TOKEN_MEMORY = new KeyDefinition(TOKEN_MEMORY, "refreshToken", { + deserializer: (refreshToken) => refreshToken, +}); + +export const REFRESH_TOKEN_MIGRATED_TO_SECURE_STORAGE = new KeyDefinition( + TOKEN_DISK, + "refreshTokenMigratedToSecureStorage", + { + deserializer: (refreshTokenMigratedToSecureStorage) => refreshTokenMigratedToSecureStorage, + }, +); + +export const EMAIL_TWO_FACTOR_TOKEN_RECORD_DISK_LOCAL = KeyDefinition.record( + TOKEN_DISK_LOCAL, + "emailTwoFactorTokenRecord", + { + deserializer: (emailTwoFactorTokenRecord) => emailTwoFactorTokenRecord, + }, +); + +export const API_KEY_CLIENT_ID_DISK = new KeyDefinition(TOKEN_DISK, "apiKeyClientId", { + deserializer: (apiKeyClientId) => apiKeyClientId, +}); + +export const API_KEY_CLIENT_ID_MEMORY = new KeyDefinition(TOKEN_MEMORY, "apiKeyClientId", { + deserializer: (apiKeyClientId) => apiKeyClientId, +}); + +export const API_KEY_CLIENT_SECRET_DISK = new KeyDefinition( + TOKEN_DISK, + "apiKeyClientSecret", + { + deserializer: (apiKeyClientSecret) => apiKeyClientSecret, + }, +); + +export const API_KEY_CLIENT_SECRET_MEMORY = new KeyDefinition( + TOKEN_MEMORY, + "apiKeyClientSecret", + { + deserializer: (apiKeyClientSecret) => apiKeyClientSecret, + }, +); diff --git a/libs/common/src/platform/abstractions/state.service.ts b/libs/common/src/platform/abstractions/state.service.ts index 3fc65e4acf1e..938720daaae5 100644 --- a/libs/common/src/platform/abstractions/state.service.ts +++ b/libs/common/src/platform/abstractions/state.service.ts @@ -52,16 +52,11 @@ export abstract class StateService { clean: (options?: StorageOptions) => Promise; init: (initOptions?: InitOptions) => Promise; - getAccessToken: (options?: StorageOptions) => Promise; - setAccessToken: (value: string, options?: StorageOptions) => Promise; getAddEditCipherInfo: (options?: StorageOptions) => Promise; setAddEditCipherInfo: (value: AddEditCipherInfo, options?: StorageOptions) => Promise; getAlwaysShowDock: (options?: StorageOptions) => Promise; setAlwaysShowDock: (value: boolean, options?: StorageOptions) => Promise; - getApiKeyClientId: (options?: StorageOptions) => Promise; - setApiKeyClientId: (value: string, options?: StorageOptions) => Promise; - getApiKeyClientSecret: (options?: StorageOptions) => Promise; - setApiKeyClientSecret: (value: string, options?: StorageOptions) => Promise; + getAutoConfirmFingerPrints: (options?: StorageOptions) => Promise; setAutoConfirmFingerprints: (value: boolean, options?: StorageOptions) => Promise; getBiometricFingerprintValidated: (options?: StorageOptions) => Promise; @@ -332,14 +327,10 @@ export abstract class StateService { * Sets the user's Pin, encrypted by the user key */ setProtectedPin: (value: string, options?: StorageOptions) => Promise; - getRefreshToken: (options?: StorageOptions) => Promise; - setRefreshToken: (value: string, options?: StorageOptions) => Promise; getRememberedEmail: (options?: StorageOptions) => Promise; setRememberedEmail: (value: string, options?: StorageOptions) => Promise; getSecurityStamp: (options?: StorageOptions) => Promise; setSecurityStamp: (value: string, options?: StorageOptions) => Promise; - getTwoFactorToken: (options?: StorageOptions) => Promise; - setTwoFactorToken: (value: string, options?: StorageOptions) => Promise; getUserId: (options?: StorageOptions) => Promise; getUsesKeyConnector: (options?: StorageOptions) => Promise; setUsesKeyConnector: (value: boolean, options?: StorageOptions) => Promise; diff --git a/libs/common/src/platform/models/domain/account.ts b/libs/common/src/platform/models/domain/account.ts index 0c85307032d5..edb8f87d2541 100644 --- a/libs/common/src/platform/models/domain/account.ts +++ b/libs/common/src/platform/models/domain/account.ts @@ -112,7 +112,6 @@ export class AccountKeys { masterKeyEncryptedUserKey?: string; deviceKey?: ReturnType; publicKey?: Uint8Array; - apiKeyClientSecret?: string; /** @deprecated July 2023, left for migration purposes*/ cryptoMasterKey?: SymmetricCryptoKey; @@ -167,7 +166,6 @@ export class AccountKeys { } export class AccountProfile { - apiKeyClientId?: string; convertAccountToKeyConnector?: boolean; name?: string; email?: string; @@ -233,8 +231,6 @@ export class AccountSettings { } export class AccountTokens { - accessToken?: string; - refreshToken?: string; securityStamp?: string; static fromJSON(obj: Jsonify): AccountTokens { diff --git a/libs/common/src/platform/services/state.service.ts b/libs/common/src/platform/services/state.service.ts index 08c5350d06db..0ccd405dd133 100644 --- a/libs/common/src/platform/services/state.service.ts +++ b/libs/common/src/platform/services/state.service.ts @@ -3,12 +3,12 @@ import { Jsonify, JsonValue } from "type-fest"; import { OrganizationData } from "../../admin-console/models/data/organization.data"; import { AccountService } from "../../auth/abstractions/account.service"; +import { TokenService } from "../../auth/abstractions/token.service"; import { AuthenticationStatus } from "../../auth/enums/authentication-status"; import { AdminAuthRequestStorable } from "../../auth/models/domain/admin-auth-req-storable"; import { ForceSetPasswordReason } from "../../auth/models/domain/force-set-password-reason"; import { KdfConfig } from "../../auth/models/domain/kdf-config"; import { BiometricKey } from "../../auth/types/biometric-key"; -import { VaultTimeoutAction } from "../../enums/vault-timeout-action.enum"; import { EventData } from "../../models/data/event.data"; import { WindowState } from "../../models/domain/window-state"; import { GeneratorOptions } from "../../tools/generator/generator-options"; @@ -100,6 +100,7 @@ export class StateService< protected stateFactory: StateFactory, protected accountService: AccountService, protected environmentService: EnvironmentService, + protected tokenService: TokenService, private migrationRunner: MigrationRunner, protected useAccountCache: boolean = true, ) { @@ -190,7 +191,7 @@ export class StateService< // TODO: Temporary update to avoid routing all account status changes through account service for now. // The determination of state should be handled by the various services that control those values. - const token = await this.getAccessToken({ userId: userId }); + const token = await this.tokenService.getAccessToken(userId as UserId); const autoKey = await this.getUserKeyAutoUnlock({ userId: userId }); const accountStatus = token == null @@ -255,18 +256,6 @@ export class StateService< return currentUser as UserId; } - async getAccessToken(options?: StorageOptions): Promise { - options = await this.getTimeoutBasedStorageOptions(options); - return (await this.getAccount(options))?.tokens?.accessToken; - } - - async setAccessToken(value: string, options?: StorageOptions): Promise { - options = await this.getTimeoutBasedStorageOptions(options); - const account = await this.getAccount(options); - account.tokens.accessToken = value; - await this.saveAccount(account, options); - } - async getAddEditCipherInfo(options?: StorageOptions): Promise { const account = await this.getAccount( this.reconcileOptions(options, await this.defaultInMemoryOptions()), @@ -313,30 +302,6 @@ export class StateService< ); } - async getApiKeyClientId(options?: StorageOptions): Promise { - options = await this.getTimeoutBasedStorageOptions(options); - return (await this.getAccount(options))?.profile?.apiKeyClientId; - } - - async setApiKeyClientId(value: string, options?: StorageOptions): Promise { - options = await this.getTimeoutBasedStorageOptions(options); - const account = await this.getAccount(options); - account.profile.apiKeyClientId = value; - await this.saveAccount(account, options); - } - - async getApiKeyClientSecret(options?: StorageOptions): Promise { - options = await this.getTimeoutBasedStorageOptions(options); - return (await this.getAccount(options))?.keys?.apiKeyClientSecret; - } - - async setApiKeyClientSecret(value: string, options?: StorageOptions): Promise { - options = await this.getTimeoutBasedStorageOptions(options); - const account = await this.getAccount(options); - account.keys.apiKeyClientSecret = value; - await this.saveAccount(account, options); - } - async getAutoConfirmFingerPrints(options?: StorageOptions): Promise { return ( (await this.getAccount(this.reconcileOptions(options, await this.defaultOnDiskOptions()))) @@ -1356,7 +1321,10 @@ export class StateService< } async getIsAuthenticated(options?: StorageOptions): Promise { - return (await this.getAccessToken(options)) != null && (await this.getUserId(options)) != null; + return ( + (await this.tokenService.getAccessToken(options?.userId as UserId)) != null && + (await this.getUserId(options)) != null + ); } async getKdfConfig(options?: StorageOptions): Promise { @@ -1672,18 +1640,6 @@ export class StateService< ); } - async getRefreshToken(options?: StorageOptions): Promise { - options = await this.getTimeoutBasedStorageOptions(options); - return (await this.getAccount(options))?.tokens?.refreshToken; - } - - async setRefreshToken(value: string, options?: StorageOptions): Promise { - options = await this.getTimeoutBasedStorageOptions(options); - const account = await this.getAccount(options); - account.tokens.refreshToken = value; - await this.saveAccount(account, options); - } - async getRememberedEmail(options?: StorageOptions): Promise { return ( await this.getGlobals(this.reconcileOptions(options, await this.defaultOnDiskLocalOptions())) @@ -1718,23 +1674,6 @@ export class StateService< ); } - async getTwoFactorToken(options?: StorageOptions): Promise { - return ( - await this.getGlobals(this.reconcileOptions(options, await this.defaultOnDiskLocalOptions())) - )?.twoFactorToken; - } - - async setTwoFactorToken(value: string, options?: StorageOptions): Promise { - const globals = await this.getGlobals( - this.reconcileOptions(options, await this.defaultOnDiskLocalOptions()), - ); - globals.twoFactorToken = value; - await this.saveGlobals( - globals, - this.reconcileOptions(options, await this.defaultOnDiskLocalOptions()), - ); - } - async getUserId(options?: StorageOptions): Promise { return ( await this.getAccount(this.reconcileOptions(options, await this.defaultOnDiskOptions())) @@ -2041,15 +1980,6 @@ export class StateService< await this.storageService.remove(keys.tempAccountSettings); } - if ( - account.settings.vaultTimeoutAction === VaultTimeoutAction.LogOut && - account.settings.vaultTimeout != null - ) { - account.tokens.accessToken = null; - account.tokens.refreshToken = null; - account.profile.apiKeyClientId = null; - account.keys.apiKeyClientSecret = null; - } await this.saveAccount( account, this.reconcileOptions( @@ -2250,7 +2180,7 @@ export class StateService< } protected async deAuthenticateAccount(userId: string): Promise { - await this.setAccessToken(null, { userId: userId }); + await this.tokenService.clearAccessToken(userId as UserId); await this.setLastActive(null, { userId: userId }); await this.updateState(async (state) => { state.authenticatedAccounts = state.authenticatedAccounts.filter((id) => id !== userId); @@ -2293,16 +2223,6 @@ export class StateService< return newActiveUser; } - private async getTimeoutBasedStorageOptions(options?: StorageOptions): Promise { - const timeoutAction = await this.getVaultTimeoutAction({ userId: options?.userId }); - const timeout = await this.getVaultTimeout({ userId: options?.userId }); - const defaultOptions = - timeoutAction === VaultTimeoutAction.LogOut && timeout != null - ? await this.defaultInMemoryOptions() - : await this.defaultOnDiskOptions(); - return this.reconcileOptions(options, defaultOptions); - } - protected async saveSecureStorageKey( key: string, value: T, diff --git a/libs/common/src/platform/state/state-definitions.ts b/libs/common/src/platform/state/state-definitions.ts index 86b8dd051cb2..34b6bb097f04 100644 --- a/libs/common/src/platform/state/state-definitions.ts +++ b/libs/common/src/platform/state/state-definitions.ts @@ -28,6 +28,11 @@ export const PROVIDERS_DISK = new StateDefinition("providers", "disk"); export const ACCOUNT_MEMORY = new StateDefinition("account", "memory"); export const AVATAR_DISK = new StateDefinition("avatar", "disk", { web: "disk-local" }); export const SSO_DISK = new StateDefinition("ssoLogin", "disk"); +export const TOKEN_DISK = new StateDefinition("token", "disk"); +export const TOKEN_DISK_LOCAL = new StateDefinition("tokenDiskLocal", "disk", { + web: "disk-local", +}); +export const TOKEN_MEMORY = new StateDefinition("token", "memory"); export const LOGIN_STRATEGY_MEMORY = new StateDefinition("loginStrategy", "memory"); // Autofill diff --git a/libs/common/src/services/api.service.ts b/libs/common/src/services/api.service.ts index 336191f3abb5..869d45ebff14 100644 --- a/libs/common/src/services/api.service.ts +++ b/libs/common/src/services/api.service.ts @@ -93,6 +93,7 @@ import { SubscriptionResponse } from "../billing/models/response/subscription.re import { TaxInfoResponse } from "../billing/models/response/tax-info.response"; import { TaxRateResponse } from "../billing/models/response/tax-rate.response"; import { DeviceType } from "../enums"; +import { VaultTimeoutAction } from "../enums/vault-timeout-action.enum"; import { CollectionBulkDeleteRequest } from "../models/request/collection-bulk-delete.request"; import { DeleteRecoverRequest } from "../models/request/delete-recover.request"; import { EventRequest } from "../models/request/event.request"; @@ -116,6 +117,7 @@ import { UserKeyResponse } from "../models/response/user-key.response"; import { AppIdService } from "../platform/abstractions/app-id.service"; import { EnvironmentService } from "../platform/abstractions/environment.service"; import { PlatformUtilsService } from "../platform/abstractions/platform-utils.service"; +import { StateService } from "../platform/abstractions/state.service"; import { Utils } from "../platform/misc/utils"; import { AttachmentRequest } from "../vault/models/request/attachment.request"; import { CipherBulkDeleteRequest } from "../vault/models/request/cipher-bulk-delete.request"; @@ -154,6 +156,7 @@ export class ApiService implements ApiServiceAbstraction { private platformUtilsService: PlatformUtilsService, private environmentService: EnvironmentService, private appIdService: AppIdService, + private stateService: StateService, private logoutCallback: (expired: boolean) => Promise, private customUserAgent: string = null, ) { @@ -224,7 +227,6 @@ export class ApiService implements ApiServiceAbstraction { responseJson.TwoFactorProviders2 && Object.keys(responseJson.TwoFactorProviders2).length ) { - await this.tokenService.clearTwoFactorToken(); return new IdentityTwoFactorResponse(responseJson); } else if ( response.status === 400 && @@ -1578,10 +1580,10 @@ export class ApiService implements ApiServiceAbstraction { // Helpers async getActiveBearerToken(): Promise { - let accessToken = await this.tokenService.getToken(); + let accessToken = await this.tokenService.getAccessToken(); if (await this.tokenService.tokenNeedsRefresh()) { await this.doAuthRefresh(); - accessToken = await this.tokenService.getToken(); + accessToken = await this.tokenService.getAccessToken(); } return accessToken; } @@ -1749,7 +1751,7 @@ export class ApiService implements ApiServiceAbstraction { headers.set("User-Agent", this.customUserAgent); } - const decodedToken = await this.tokenService.decodeToken(); + const decodedToken = await this.tokenService.decodeAccessToken(); const response = await this.fetch( new Request(this.environmentService.getIdentityUrl() + "/connect/token", { body: this.qsStringify({ @@ -1767,10 +1769,15 @@ export class ApiService implements ApiServiceAbstraction { if (response.status === 200) { const responseJson = await response.json(); const tokenResponse = new IdentityTokenResponse(responseJson); + + const vaultTimeoutAction = await this.stateService.getVaultTimeoutAction(); + const vaultTimeout = await this.stateService.getVaultTimeout(); + await this.tokenService.setTokens( tokenResponse.accessToken, tokenResponse.refreshToken, - null, + vaultTimeoutAction as VaultTimeoutAction, + vaultTimeout, ); } else { const error = await this.handleError(response, true, true); @@ -1796,7 +1803,14 @@ export class ApiService implements ApiServiceAbstraction { throw new Error("Invalid response received when refreshing api token"); } - await this.tokenService.setToken(response.accessToken); + const vaultTimeoutAction = await this.stateService.getVaultTimeoutAction(); + const vaultTimeout = await this.stateService.getVaultTimeout(); + + await this.tokenService.setAccessToken( + response.accessToken, + vaultTimeoutAction as VaultTimeoutAction, + vaultTimeout, + ); } async send( diff --git a/libs/common/src/services/vault-timeout/vault-timeout-settings.service.ts b/libs/common/src/services/vault-timeout/vault-timeout-settings.service.ts index 0d0eb508cb2e..e8897d82b7d5 100644 --- a/libs/common/src/services/vault-timeout/vault-timeout-settings.service.ts +++ b/libs/common/src/services/vault-timeout/vault-timeout-settings.service.ts @@ -29,7 +29,7 @@ export class VaultTimeoutSettingsService implements VaultTimeoutSettingsServiceA async setVaultTimeoutOptions(timeout: number, action: VaultTimeoutAction): Promise { // We swap these tokens from being on disk for lock actions, and in memory for logout actions // Get them here to set them to their new location after changing the timeout action and clearing if needed - const token = await this.tokenService.getToken(); + const accessToken = await this.tokenService.getAccessToken(); const refreshToken = await this.tokenService.getRefreshToken(); const clientId = await this.tokenService.getClientId(); const clientSecret = await this.tokenService.getClientSecret(); @@ -37,21 +37,22 @@ export class VaultTimeoutSettingsService implements VaultTimeoutSettingsServiceA await this.stateService.setVaultTimeout(timeout); const currentAction = await this.stateService.getVaultTimeoutAction(); + if ( (timeout != null || timeout === 0) && action === VaultTimeoutAction.LogOut && action !== currentAction ) { // if we have a vault timeout and the action is log out, reset tokens - await this.tokenService.clearToken(); + await this.tokenService.clearTokens(); } await this.stateService.setVaultTimeoutAction(action); - await this.tokenService.setToken(token); - await this.tokenService.setRefreshToken(refreshToken); - await this.tokenService.setClientId(clientId); - await this.tokenService.setClientSecret(clientSecret); + await this.tokenService.setTokens(accessToken, refreshToken, action, timeout, [ + clientId, + clientSecret, + ]); await this.cryptoService.refreshAdditionalKeys(); } diff --git a/libs/common/src/state-migrations/migrate.ts b/libs/common/src/state-migrations/migrate.ts index 77a35ccb871f..798af3822091 100644 --- a/libs/common/src/state-migrations/migrate.ts +++ b/libs/common/src/state-migrations/migrate.ts @@ -24,7 +24,6 @@ import { RevertLastSyncMigrator } from "./migrations/26-revert-move-last-sync-to import { BadgeSettingsMigrator } from "./migrations/27-move-badge-settings-to-state-providers"; import { MoveBiometricUnlockToStateProviders } from "./migrations/28-move-biometric-unlock-to-state-providers"; import { UserNotificationSettingsKeyMigrator } from "./migrations/29-move-user-notification-settings-to-state-provider"; -import { FixPremiumMigrator } from "./migrations/3-fix-premium"; import { PolicyMigrator } from "./migrations/30-move-policy-state-to-state-provider"; import { EnableContextMenuMigrator } from "./migrations/31-move-enable-context-menu-to-autofill-settings-state-provider"; import { PreferredLanguageMigrator } from "./migrations/32-move-preferred-language"; @@ -33,6 +32,7 @@ import { DomainSettingsMigrator } from "./migrations/34-move-domain-settings-to- import { MoveThemeToStateProviderMigrator } from "./migrations/35-move-theme-to-state-providers"; import { VaultSettingsKeyMigrator } from "./migrations/36-move-show-card-and-identity-to-state-provider"; import { AvatarColorMigrator } from "./migrations/37-move-avatar-color-to-state-providers"; +import { TokenServiceStateProviderMigrator } from "./migrations/38-migrate-token-svc-to-state-provider"; import { RemoveEverBeenUnlockedMigrator } from "./migrations/4-remove-ever-been-unlocked"; import { AddKeyTypeToOrgKeysMigrator } from "./migrations/5-add-key-type-to-org-keys"; import { RemoveLegacyEtmKeyMigrator } from "./migrations/6-remove-legacy-etm-key"; @@ -41,14 +41,13 @@ import { MoveStateVersionMigrator } from "./migrations/8-move-state-version"; import { MoveBrowserSettingsToGlobal } from "./migrations/9-move-browser-settings-to-global"; import { MinVersionMigrator } from "./migrations/min-version"; -export const MIN_VERSION = 2; -export const CURRENT_VERSION = 37; +export const MIN_VERSION = 3; +export const CURRENT_VERSION = 38; export type MinVersion = typeof MIN_VERSION; export function createMigrationBuilder() { return MigrationBuilder.create() .with(MinVersionMigrator) - .with(FixPremiumMigrator, 2, 3) .with(RemoveEverBeenUnlockedMigrator, 3, 4) .with(AddKeyTypeToOrgKeysMigrator, 4, 5) .with(RemoveLegacyEtmKeyMigrator, 5, 6) @@ -82,7 +81,8 @@ export function createMigrationBuilder() { .with(DomainSettingsMigrator, 33, 34) .with(MoveThemeToStateProviderMigrator, 34, 35) .with(VaultSettingsKeyMigrator, 35, 36) - .with(AvatarColorMigrator, 36, CURRENT_VERSION); + .with(AvatarColorMigrator, 36, 37) + .with(TokenServiceStateProviderMigrator, 37, CURRENT_VERSION); } export async function currentVersion( diff --git a/libs/common/src/state-migrations/migrations/3-fix-premium.spec.ts b/libs/common/src/state-migrations/migrations/3-fix-premium.spec.ts deleted file mode 100644 index 1ef910d45691..000000000000 --- a/libs/common/src/state-migrations/migrations/3-fix-premium.spec.ts +++ /dev/null @@ -1,111 +0,0 @@ -import { MockProxy } from "jest-mock-extended"; - -// eslint-disable-next-line import/no-restricted-paths -- Used for testing migration, which requires import -import { TokenService } from "../../auth/services/token.service"; -import { MigrationHelper } from "../migration-helper"; -import { mockMigrationHelper } from "../migration-helper.spec"; - -import { FixPremiumMigrator } from "./3-fix-premium"; - -function migrateExampleJSON() { - return { - global: { - stateVersion: 2, - otherStuff: "otherStuff1", - }, - authenticatedAccounts: [ - "c493ed01-4e08-4e88-abc7-332f380ca760", - "23e61a5f-2ece-4f5e-b499-f0bc489482a9", - ], - "c493ed01-4e08-4e88-abc7-332f380ca760": { - profile: { - otherStuff: "otherStuff2", - hasPremiumPersonally: null as boolean, - }, - tokens: { - otherStuff: "otherStuff3", - accessToken: "accessToken", - }, - otherStuff: "otherStuff4", - }, - "23e61a5f-2ece-4f5e-b499-f0bc489482a9": { - profile: { - otherStuff: "otherStuff5", - hasPremiumPersonally: true, - }, - tokens: { - otherStuff: "otherStuff6", - accessToken: "accessToken", - }, - otherStuff: "otherStuff7", - }, - otherStuff: "otherStuff8", - }; -} - -jest.mock("../../auth/services/token.service", () => ({ - TokenService: { - decodeToken: jest.fn(), - }, -})); - -describe("FixPremiumMigrator", () => { - let helper: MockProxy; - let sut: FixPremiumMigrator; - const decodeTokenSpy = TokenService.decodeToken as jest.Mock; - - beforeEach(() => { - helper = mockMigrationHelper(migrateExampleJSON()); - sut = new FixPremiumMigrator(2, 3); - }); - - afterEach(() => { - jest.resetAllMocks(); - }); - - describe("migrate", () => { - it("should migrate hasPremiumPersonally", async () => { - decodeTokenSpy.mockResolvedValueOnce({ premium: true }); - await sut.migrate(helper); - - expect(helper.set).toHaveBeenCalledTimes(1); - expect(helper.set).toHaveBeenCalledWith("c493ed01-4e08-4e88-abc7-332f380ca760", { - profile: { - otherStuff: "otherStuff2", - hasPremiumPersonally: true, - }, - tokens: { - otherStuff: "otherStuff3", - accessToken: "accessToken", - }, - otherStuff: "otherStuff4", - }); - }); - - it("should not migrate if decode throws", async () => { - decodeTokenSpy.mockRejectedValueOnce(new Error("test")); - await sut.migrate(helper); - - expect(helper.set).not.toHaveBeenCalled(); - }); - - it("should not migrate if decode returns null", async () => { - decodeTokenSpy.mockResolvedValueOnce(null); - await sut.migrate(helper); - - expect(helper.set).not.toHaveBeenCalled(); - }); - }); - - describe("updateVersion", () => { - it("should update version", async () => { - await sut.updateVersion(helper, "up"); - - expect(helper.set).toHaveBeenCalledTimes(1); - expect(helper.set).toHaveBeenCalledWith("global", { - stateVersion: 3, - otherStuff: "otherStuff1", - }); - }); - }); -}); diff --git a/libs/common/src/state-migrations/migrations/3-fix-premium.ts b/libs/common/src/state-migrations/migrations/3-fix-premium.ts deleted file mode 100644 index b6c69a991686..000000000000 --- a/libs/common/src/state-migrations/migrations/3-fix-premium.ts +++ /dev/null @@ -1,48 +0,0 @@ -// eslint-disable-next-line import/no-restricted-paths -- Used for token decoding, which are valid for days. We want the latest -import { TokenService } from "../../auth/services/token.service"; -import { MigrationHelper } from "../migration-helper"; -import { Migrator, IRREVERSIBLE, Direction } from "../migrator"; - -type ExpectedAccountType = { - profile?: { hasPremiumPersonally?: boolean }; - tokens?: { accessToken?: string }; -}; - -export class FixPremiumMigrator extends Migrator<2, 3> { - async migrate(helper: MigrationHelper): Promise { - const accounts = await helper.getAccounts(); - - async function fixPremium(userId: string, account: ExpectedAccountType) { - if (account?.profile?.hasPremiumPersonally === null && account.tokens?.accessToken != null) { - let decodedToken: { premium: boolean }; - try { - decodedToken = await TokenService.decodeToken(account.tokens.accessToken); - } catch { - return; - } - - if (decodedToken?.premium == null) { - return; - } - - account.profile.hasPremiumPersonally = decodedToken?.premium; - return helper.set(userId, account); - } - } - - await Promise.all(accounts.map(({ userId, account }) => fixPremium(userId, account))); - } - - rollback(helper: MigrationHelper): Promise { - throw IRREVERSIBLE; - } - - // Override is necessary because default implementation assumes `stateVersion` at the root, but for this version - // it is nested inside a global object. - override async updateVersion(helper: MigrationHelper, direction: Direction): Promise { - const endVersion = direction === "up" ? this.toVersion : this.fromVersion; - helper.currentVersion = endVersion; - const global: Record = (await helper.get("global")) || {}; - await helper.set("global", { ...global, stateVersion: endVersion }); - } -} diff --git a/libs/common/src/state-migrations/migrations/38-migrate-token-svc-to-state-provider.spec.ts b/libs/common/src/state-migrations/migrations/38-migrate-token-svc-to-state-provider.spec.ts new file mode 100644 index 000000000000..a5243c261a56 --- /dev/null +++ b/libs/common/src/state-migrations/migrations/38-migrate-token-svc-to-state-provider.spec.ts @@ -0,0 +1,258 @@ +import { MockProxy, any } from "jest-mock-extended"; + +import { MigrationHelper } from "../migration-helper"; +import { mockMigrationHelper } from "../migration-helper.spec"; + +import { + EMAIL_TWO_FACTOR_TOKEN_RECORD_DISK_LOCAL, + ACCESS_TOKEN_DISK, + REFRESH_TOKEN_DISK, + API_KEY_CLIENT_ID_DISK, + API_KEY_CLIENT_SECRET_DISK, + TokenServiceStateProviderMigrator, +} from "./38-migrate-token-svc-to-state-provider"; + +// Represents data in state service pre-migration +function preMigrationJson() { + return { + global: { + twoFactorToken: "twoFactorToken", + otherStuff: "otherStuff1", + }, + authenticatedAccounts: ["user1", "user2", "user3"], + user1: { + tokens: { + accessToken: "accessToken", + refreshToken: "refreshToken", + otherStuff: "overStuff2", + }, + profile: { + apiKeyClientId: "apiKeyClientId", + email: "user1Email", + otherStuff: "overStuff3", + }, + keys: { + apiKeyClientSecret: "apiKeyClientSecret", + otherStuff: "overStuff4", + }, + otherStuff: "otherStuff5", + }, + user2: { + tokens: { + // no tokens to migrate + otherStuff: "overStuff2", + }, + profile: { + // no apiKeyClientId to migrate + otherStuff: "overStuff3", + email: "user2Email", + }, + keys: { + // no apiKeyClientSecret to migrate + otherStuff: "overStuff4", + }, + otherStuff: "otherStuff5", + }, + }; +} + +function rollbackJSON() { + return { + // User specific state provider data + // use pattern user_{userId}_{stateDefinitionName}_{keyDefinitionKey} for user data + + // User1 migrated data + user_user1_token_accessToken: "accessToken", + user_user1_token_refreshToken: "refreshToken", + user_user1_token_apiKeyClientId: "apiKeyClientId", + user_user1_token_apiKeyClientSecret: "apiKeyClientSecret", + + // User2 migrated data + user_user2_token_accessToken: null as any, + user_user2_token_refreshToken: null as any, + user_user2_token_apiKeyClientId: null as any, + user_user2_token_apiKeyClientSecret: null as any, + + // Global state provider data + // use pattern global_{stateDefinitionName}_{keyDefinitionKey} for global data + global_tokenDiskLocal_emailTwoFactorTokenRecord: { + user1Email: "twoFactorToken", + user2Email: "twoFactorToken", + }, + + global: { + // no longer has twoFactorToken + otherStuff: "otherStuff1", + }, + authenticatedAccounts: ["user1", "user2", "user3"], + user1: { + tokens: { + otherStuff: "overStuff2", + }, + profile: { + email: "user1Email", + otherStuff: "overStuff3", + }, + keys: { + otherStuff: "overStuff4", + }, + otherStuff: "otherStuff5", + }, + user2: { + tokens: { + otherStuff: "overStuff2", + }, + profile: { + email: "user2Email", + otherStuff: "overStuff3", + }, + keys: { + otherStuff: "overStuff4", + }, + otherStuff: "otherStuff5", + }, + }; +} + +describe("TokenServiceStateProviderMigrator", () => { + let helper: MockProxy; + let sut: TokenServiceStateProviderMigrator; + + describe("migrate", () => { + beforeEach(() => { + helper = mockMigrationHelper(preMigrationJson(), 37); + sut = new TokenServiceStateProviderMigrator(37, 38); + }); + + it("should remove state service data from all accounts that have it", async () => { + await sut.migrate(helper); + + expect(helper.set).toHaveBeenCalledWith("user1", { + tokens: { + otherStuff: "overStuff2", + }, + profile: { + email: "user1Email", + otherStuff: "overStuff3", + }, + keys: { + otherStuff: "overStuff4", + }, + otherStuff: "otherStuff5", + }); + + expect(helper.set).toHaveBeenCalledTimes(2); + expect(helper.set).not.toHaveBeenCalledWith("user2", any()); + expect(helper.set).not.toHaveBeenCalledWith("user3", any()); + }); + + it("should migrate data to state providers for defined accounts that have the data", async () => { + await sut.migrate(helper); + + // Two factor Token Migration + expect(helper.setToGlobal).toHaveBeenLastCalledWith( + EMAIL_TWO_FACTOR_TOKEN_RECORD_DISK_LOCAL, + { + user1Email: "twoFactorToken", + user2Email: "twoFactorToken", + }, + ); + expect(helper.setToGlobal).toHaveBeenCalledTimes(1); + + expect(helper.setToUser).toHaveBeenCalledWith("user1", ACCESS_TOKEN_DISK, "accessToken"); + expect(helper.setToUser).toHaveBeenCalledWith("user1", REFRESH_TOKEN_DISK, "refreshToken"); + expect(helper.setToUser).toHaveBeenCalledWith( + "user1", + API_KEY_CLIENT_ID_DISK, + "apiKeyClientId", + ); + expect(helper.setToUser).toHaveBeenCalledWith( + "user1", + API_KEY_CLIENT_SECRET_DISK, + "apiKeyClientSecret", + ); + + expect(helper.setToUser).not.toHaveBeenCalledWith("user2", ACCESS_TOKEN_DISK, any()); + expect(helper.setToUser).not.toHaveBeenCalledWith("user2", REFRESH_TOKEN_DISK, any()); + expect(helper.setToUser).not.toHaveBeenCalledWith("user2", API_KEY_CLIENT_ID_DISK, any()); + expect(helper.setToUser).not.toHaveBeenCalledWith("user2", API_KEY_CLIENT_SECRET_DISK, any()); + + // Expect that we didn't migrate anything to user 3 + + expect(helper.setToUser).not.toHaveBeenCalledWith("user3", ACCESS_TOKEN_DISK, any()); + expect(helper.setToUser).not.toHaveBeenCalledWith("user3", REFRESH_TOKEN_DISK, any()); + expect(helper.setToUser).not.toHaveBeenCalledWith("user3", API_KEY_CLIENT_ID_DISK, any()); + expect(helper.setToUser).not.toHaveBeenCalledWith("user3", API_KEY_CLIENT_SECRET_DISK, any()); + }); + }); + + describe("rollback", () => { + beforeEach(() => { + helper = mockMigrationHelper(rollbackJSON(), 38); + sut = new TokenServiceStateProviderMigrator(37, 38); + }); + + it("should null out newly migrated entries in state provider framework", async () => { + await sut.rollback(helper); + + expect(helper.setToGlobal).toHaveBeenCalledWith( + EMAIL_TWO_FACTOR_TOKEN_RECORD_DISK_LOCAL, + null, + ); + + expect(helper.setToUser).toHaveBeenCalledWith("user1", ACCESS_TOKEN_DISK, null); + expect(helper.setToUser).toHaveBeenCalledWith("user1", REFRESH_TOKEN_DISK, null); + expect(helper.setToUser).toHaveBeenCalledWith("user1", API_KEY_CLIENT_ID_DISK, null); + expect(helper.setToUser).toHaveBeenCalledWith("user1", API_KEY_CLIENT_SECRET_DISK, null); + + expect(helper.setToUser).toHaveBeenCalledWith("user2", ACCESS_TOKEN_DISK, null); + expect(helper.setToUser).toHaveBeenCalledWith("user2", REFRESH_TOKEN_DISK, null); + expect(helper.setToUser).toHaveBeenCalledWith("user2", API_KEY_CLIENT_ID_DISK, null); + expect(helper.setToUser).toHaveBeenCalledWith("user2", API_KEY_CLIENT_SECRET_DISK, null); + + expect(helper.setToUser).toHaveBeenCalledWith("user3", ACCESS_TOKEN_DISK, null); + expect(helper.setToUser).toHaveBeenCalledWith("user3", REFRESH_TOKEN_DISK, null); + expect(helper.setToUser).toHaveBeenCalledWith("user3", API_KEY_CLIENT_ID_DISK, null); + expect(helper.setToUser).toHaveBeenCalledWith("user3", API_KEY_CLIENT_SECRET_DISK, null); + }); + + it("should add back data to all accounts that had migrated data (only user 1)", async () => { + await sut.rollback(helper); + + expect(helper.set).toHaveBeenCalledWith("user1", { + tokens: { + accessToken: "accessToken", + refreshToken: "refreshToken", + otherStuff: "overStuff2", + }, + profile: { + apiKeyClientId: "apiKeyClientId", + email: "user1Email", + otherStuff: "overStuff3", + }, + keys: { + apiKeyClientSecret: "apiKeyClientSecret", + otherStuff: "overStuff4", + }, + otherStuff: "otherStuff5", + }); + }); + + it("should add back the global twoFactorToken", async () => { + await sut.rollback(helper); + + expect(helper.set).toHaveBeenCalledWith("global", { + twoFactorToken: "twoFactorToken", + otherStuff: "otherStuff1", + }); + }); + + it("should not add data back if data wasn't migrated or acct doesn't exist", async () => { + await sut.rollback(helper); + + // no data to add back for user2 (acct exists but no migrated data) and user3 (no acct) + expect(helper.set).not.toHaveBeenCalledWith("user2", any()); + expect(helper.set).not.toHaveBeenCalledWith("user3", any()); + }); + }); +}); diff --git a/libs/common/src/state-migrations/migrations/38-migrate-token-svc-to-state-provider.ts b/libs/common/src/state-migrations/migrations/38-migrate-token-svc-to-state-provider.ts new file mode 100644 index 000000000000..17753d21879f --- /dev/null +++ b/libs/common/src/state-migrations/migrations/38-migrate-token-svc-to-state-provider.ts @@ -0,0 +1,231 @@ +import { KeyDefinitionLike, MigrationHelper, StateDefinitionLike } from "../migration-helper"; +import { Migrator } from "../migrator"; + +// Types to represent data as it is stored in JSON +type ExpectedAccountType = { + tokens?: { + accessToken?: string; + refreshToken?: string; + }; + profile?: { + apiKeyClientId?: string; + email?: string; + }; + keys?: { + apiKeyClientSecret?: string; + }; +}; + +type ExpectedGlobalType = { + twoFactorToken?: string; +}; + +export const EMAIL_TWO_FACTOR_TOKEN_RECORD_DISK_LOCAL: KeyDefinitionLike = { + key: "emailTwoFactorTokenRecord", + stateDefinition: { + name: "tokenDiskLocal", + }, +}; + +const TOKEN_STATE_DEF_LIKE: StateDefinitionLike = { + name: "token", +}; + +export const ACCESS_TOKEN_DISK: KeyDefinitionLike = { + key: "accessToken", // matches KeyDefinition.key + stateDefinition: TOKEN_STATE_DEF_LIKE, +}; + +export const REFRESH_TOKEN_DISK: KeyDefinitionLike = { + key: "refreshToken", + stateDefinition: TOKEN_STATE_DEF_LIKE, +}; + +export const API_KEY_CLIENT_ID_DISK: KeyDefinitionLike = { + key: "apiKeyClientId", + stateDefinition: TOKEN_STATE_DEF_LIKE, +}; + +export const API_KEY_CLIENT_SECRET_DISK: KeyDefinitionLike = { + key: "apiKeyClientSecret", + stateDefinition: TOKEN_STATE_DEF_LIKE, +}; + +export class TokenServiceStateProviderMigrator extends Migrator<37, 38> { + async migrate(helper: MigrationHelper): Promise { + // Move global data + const globalData = await helper.get("global"); + + // Create new global record for 2FA token that we can accumulate data in + const emailTwoFactorTokenRecord = {}; + + const accounts = await helper.getAccounts(); + async function migrateAccount( + userId: string, + account: ExpectedAccountType | undefined, + globalTwoFactorToken: string | undefined, + emailTwoFactorTokenRecord: Record, + ): Promise { + let updatedAccount = false; + + // migrate 2FA token from global to user state + // Due to the existing implmentation, n users on the same device share the same global state value for 2FA token. + // So, we will just migrate it to all users to keep it valid for whichever was the user that set it previously. + // Note: don't bother migrating 2FA Token if user account or email is undefined + const email = account?.profile?.email; + if (globalTwoFactorToken != undefined && account != undefined && email != undefined) { + emailTwoFactorTokenRecord[email] = globalTwoFactorToken; + // Note: don't set updatedAccount to true here as we aren't updating + // the legacy user state, just migrating a global state to a new user state + } + + // Migrate access token + const existingAccessToken = account?.tokens?.accessToken; + + if (existingAccessToken != null) { + // Only migrate data that exists + await helper.setToUser(userId, ACCESS_TOKEN_DISK, existingAccessToken); + delete account.tokens.accessToken; + updatedAccount = true; + } + + // Migrate refresh token + const existingRefreshToken = account?.tokens?.refreshToken; + + if (existingRefreshToken != null) { + await helper.setToUser(userId, REFRESH_TOKEN_DISK, existingRefreshToken); + delete account.tokens.refreshToken; + updatedAccount = true; + } + + // Migrate API key client id + const existingApiKeyClientId = account?.profile?.apiKeyClientId; + + if (existingApiKeyClientId != null) { + await helper.setToUser(userId, API_KEY_CLIENT_ID_DISK, existingApiKeyClientId); + delete account.profile.apiKeyClientId; + updatedAccount = true; + } + + // Migrate API key client secret + const existingApiKeyClientSecret = account?.keys?.apiKeyClientSecret; + if (existingApiKeyClientSecret != null) { + await helper.setToUser(userId, API_KEY_CLIENT_SECRET_DISK, existingApiKeyClientSecret); + delete account.keys.apiKeyClientSecret; + updatedAccount = true; + } + + if (updatedAccount) { + // Save the migrated account only if it was updated + await helper.set(userId, account); + } + } + + await Promise.all([ + ...accounts.map(({ userId, account }) => + migrateAccount(userId, account, globalData?.twoFactorToken, emailTwoFactorTokenRecord), + ), + ]); + + // Save the global 2FA token record + await helper.setToGlobal(EMAIL_TWO_FACTOR_TOKEN_RECORD_DISK_LOCAL, emailTwoFactorTokenRecord); + + // Delete global data + delete globalData?.twoFactorToken; + await helper.set("global", globalData); + } + + async rollback(helper: MigrationHelper): Promise { + const accounts = await helper.getAccounts(); + + // Since we migrated the global 2FA token to all users, we need to rollback the 2FA token for all users + // but we only need to set it to the global state once + + // Go through accounts and find the first user that has a non-null email and 2FA token + let migratedTwoFactorToken: string | null = null; + for (const { account } of accounts) { + const email = account?.profile?.email; + if (email == null) { + continue; + } + const emailTwoFactorTokenRecord: Record = await helper.getFromGlobal( + EMAIL_TWO_FACTOR_TOKEN_RECORD_DISK_LOCAL, + ); + + migratedTwoFactorToken = emailTwoFactorTokenRecord[email]; + + if (migratedTwoFactorToken != null) { + break; + } + } + + if (migratedTwoFactorToken != null) { + let legacyGlobal = await helper.get("global"); + if (!legacyGlobal) { + legacyGlobal = {}; + } + legacyGlobal.twoFactorToken = migratedTwoFactorToken; + await helper.set("global", legacyGlobal); + } + + // delete global 2FA token record + await helper.setToGlobal(EMAIL_TWO_FACTOR_TOKEN_RECORD_DISK_LOCAL, null); + + async function rollbackAccount(userId: string, account: ExpectedAccountType): Promise { + let updatedLegacyAccount = false; + + // Rollback access token + const migratedAccessToken = await helper.getFromUser(userId, ACCESS_TOKEN_DISK); + + if (account?.tokens && migratedAccessToken != null) { + account.tokens.accessToken = migratedAccessToken; + updatedLegacyAccount = true; + } + + await helper.setToUser(userId, ACCESS_TOKEN_DISK, null); + + // Rollback refresh token + const migratedRefreshToken = await helper.getFromUser(userId, REFRESH_TOKEN_DISK); + + if (account?.tokens && migratedRefreshToken != null) { + account.tokens.refreshToken = migratedRefreshToken; + updatedLegacyAccount = true; + } + + await helper.setToUser(userId, REFRESH_TOKEN_DISK, null); + + // Rollback API key client id + + const migratedApiKeyClientId = await helper.getFromUser( + userId, + API_KEY_CLIENT_ID_DISK, + ); + + if (account?.profile && migratedApiKeyClientId != null) { + account.profile.apiKeyClientId = migratedApiKeyClientId; + updatedLegacyAccount = true; + } + + await helper.setToUser(userId, API_KEY_CLIENT_ID_DISK, null); + + // Rollback API key client secret + const migratedApiKeyClientSecret = await helper.getFromUser( + userId, + API_KEY_CLIENT_SECRET_DISK, + ); + + if (account?.keys && migratedApiKeyClientSecret != null) { + account.keys.apiKeyClientSecret = migratedApiKeyClientSecret; + updatedLegacyAccount = true; + } + + await helper.setToUser(userId, API_KEY_CLIENT_SECRET_DISK, null); + + if (updatedLegacyAccount) { + await helper.set(userId, account); + } + } + + await Promise.all([...accounts.map(({ userId, account }) => rollbackAccount(userId, account))]); + } +} diff --git a/libs/importer/src/components/lastpass/lastpass-direct-import.service.ts b/libs/importer/src/components/lastpass/lastpass-direct-import.service.ts index 4b002061e067..7d77bbbc868d 100644 --- a/libs/importer/src/components/lastpass/lastpass-direct-import.service.ts +++ b/libs/importer/src/components/lastpass/lastpass-direct-import.service.ts @@ -2,7 +2,6 @@ import { Injectable, NgZone } from "@angular/core"; import { OidcClient } from "oidc-client-ts"; import { Subject, firstValueFrom } from "rxjs"; -import { TokenService } from "@bitwarden/common/auth/abstractions/token.service"; import { ClientType } from "@bitwarden/common/enums"; import { AppIdService } from "@bitwarden/common/platform/abstractions/app-id.service"; import { BroadcasterService } from "@bitwarden/common/platform/abstractions/broadcaster.service"; @@ -32,7 +31,6 @@ export class LastPassDirectImportService { ssoImportCallback$ = this._ssoImportCallback$.asObservable(); constructor( - private tokenService: TokenService, private cryptoFunctionService: CryptoFunctionService, private environmentService: EnvironmentService, private appIdService: AppIdService, @@ -44,7 +42,7 @@ export class LastPassDirectImportService { private dialogService: DialogService, private i18nService: I18nService, ) { - this.vault = new Vault(this.cryptoFunctionService, this.tokenService); + this.vault = new Vault(this.cryptoFunctionService); /** TODO: remove this in favor of dedicated service */ this.broadcasterService.subscribe("LastPassDirectImportService", (message: any) => { diff --git a/libs/importer/src/importers/lastpass/access/vault.ts b/libs/importer/src/importers/lastpass/access/vault.ts index 814390f5c80c..13b8b62c1082 100644 --- a/libs/importer/src/importers/lastpass/access/vault.ts +++ b/libs/importer/src/importers/lastpass/access/vault.ts @@ -1,6 +1,6 @@ import * as papa from "papaparse"; -import { TokenService } from "@bitwarden/common/auth/abstractions/token.service"; +import { decodeJwtTokenToJson } from "@bitwarden/auth/common"; import { HttpStatusCode } from "@bitwarden/common/enums"; import { CryptoFunctionService } from "@bitwarden/common/platform/abstractions/crypto-function.service"; import { Utils } from "@bitwarden/common/platform/misc/utils"; @@ -24,10 +24,7 @@ export class Vault { private client: Client; private cryptoUtils: CryptoUtils; - constructor( - private cryptoFunctionService: CryptoFunctionService, - private tokenService: TokenService, - ) { + constructor(private cryptoFunctionService: CryptoFunctionService) { this.cryptoUtils = new CryptoUtils(cryptoFunctionService); const parser = new Parser(cryptoFunctionService, this.cryptoUtils); this.client = new Client(parser, this.cryptoUtils); @@ -212,7 +209,7 @@ export class Vault { } private async getK1FromAccessToken(federatedUser: FederatedUserContext, b64: boolean) { - const decodedAccessToken = await this.tokenService.decodeToken(federatedUser.accessToken); + const decodedAccessToken = decodeJwtTokenToJson(federatedUser.accessToken); const k1 = decodedAccessToken?.LastPassK1 as string; if (k1 != null) { return b64 ? Utils.fromB64ToArray(k1) : Utils.fromByteStringToArray(k1); From 65534a132375e2ba9a4b2fc637328ea4073585c5 Mon Sep 17 00:00:00 2001 From: aj-bw <81774843+aj-bw@users.noreply.github.com> Date: Fri, 15 Mar 2024 17:06:29 +0000 Subject: [PATCH 16/16] [AC-2304] added User Status check to revoke-restore as well as remove components (#8347) --- .../members/components/bulk/bulk-remove.component.ts | 5 ++++- .../members/components/bulk/bulk-restore-revoke.component.ts | 5 ++++- 2 files changed, 8 insertions(+), 2 deletions(-) diff --git a/apps/web/src/app/admin-console/organizations/members/components/bulk/bulk-remove.component.ts b/apps/web/src/app/admin-console/organizations/members/components/bulk/bulk-remove.component.ts index 506c556f1769..fdf499f0398f 100644 --- a/apps/web/src/app/admin-console/organizations/members/components/bulk/bulk-remove.component.ts +++ b/apps/web/src/app/admin-console/organizations/members/components/bulk/bulk-remove.component.ts @@ -2,6 +2,7 @@ import { Component, Input } from "@angular/core"; import { ApiService } from "@bitwarden/common/abstractions/api.service"; import { OrganizationUserService } from "@bitwarden/common/admin-console/abstractions/organization-user/organization-user.service"; +import { OrganizationUserStatusType } from "@bitwarden/common/admin-console/enums"; import { I18nService } from "@bitwarden/common/platform/abstractions/i18n.service"; import { BulkUserDetails } from "./bulk-status.component"; @@ -14,7 +15,9 @@ export class BulkRemoveComponent { @Input() organizationId: string; @Input() set users(value: BulkUserDetails[]) { this._users = value; - this.showNoMasterPasswordWarning = this._users.some((u) => u.hasMasterPassword === false); + this.showNoMasterPasswordWarning = this._users.some( + (u) => u.status > OrganizationUserStatusType.Invited && u.hasMasterPassword === false, + ); } get users(): BulkUserDetails[] { diff --git a/apps/web/src/app/admin-console/organizations/members/components/bulk/bulk-restore-revoke.component.ts b/apps/web/src/app/admin-console/organizations/members/components/bulk/bulk-restore-revoke.component.ts index 2b9ba67468cf..a2ab93dd0e13 100644 --- a/apps/web/src/app/admin-console/organizations/members/components/bulk/bulk-restore-revoke.component.ts +++ b/apps/web/src/app/admin-console/organizations/members/components/bulk/bulk-restore-revoke.component.ts @@ -2,6 +2,7 @@ import { DIALOG_DATA } from "@angular/cdk/dialog"; import { Component, Inject } from "@angular/core"; import { OrganizationUserService } from "@bitwarden/common/admin-console/abstractions/organization-user/organization-user.service"; +import { OrganizationUserStatusType } from "@bitwarden/common/admin-console/enums"; import { I18nService } from "@bitwarden/common/platform/abstractions/i18n.service"; import { DialogService } from "@bitwarden/components"; @@ -37,7 +38,9 @@ export class BulkRestoreRevokeComponent { this.isRevoking = data.isRevoking; this.organizationId = data.organizationId; this.users = data.users; - this.showNoMasterPasswordWarning = this.users.some((u) => u.hasMasterPassword === false); + this.showNoMasterPasswordWarning = this.users.some( + (u) => u.status > OrganizationUserStatusType.Invited && u.hasMasterPassword === false, + ); } get bulkTitle() {