bitwarden-estensione-browser/libs/auth/src/common/services/login-strategies/login-strategy.service.spec.ts

Ignoring revisions in .git-blame-ignore-revs. Click here to bypass and see the normal blame view.

228 lines
9.2 KiB
TypeScript
Raw Normal View History

import { MockProxy, mock } from "jest-mock-extended";
import { ApiService } from "@bitwarden/common/abstractions/api.service";
import { PolicyService } from "@bitwarden/common/admin-console/abstractions/policy/policy.service.abstraction";
import { DeviceTrustServiceAbstraction } from "@bitwarden/common/auth/abstractions/device-trust.service.abstraction";
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 { TwoFactorProviderType } from "@bitwarden/common/auth/enums/two-factor-provider-type";
import { AuthResult } from "@bitwarden/common/auth/models/domain/auth-result";
import { TokenTwoFactorRequest } from "@bitwarden/common/auth/models/request/identity-token/token-two-factor.request";
import { IdentityTokenResponse } from "@bitwarden/common/auth/models/response/identity-token.response";
import { IdentityTwoFactorResponse } from "@bitwarden/common/auth/models/response/identity-two-factor.response";
[PM-5362] Add MP Service (attempt #2) (#8619) * create mp and kdf service * update mp service interface to not rely on active user * rename observable methods * update crypto service with new MP service * add master password service to login strategies - make fake service for easier testing - fix crypto service tests * update auth service and finish strategies * auth request refactors * more service refactors and constructor updates * setMasterKey refactors * remove master key methods from crypto service * remove master key and hash from state service * missed fixes * create migrations and fix references * fix master key imports * default force set password reason to none * add password reset reason observable factory to service * remove kdf changes and migrate only disk data * update migration number * fix sync service deps * use disk for force set password state * fix desktop migration * fix sso test * fix tests * fix more tests * fix even more tests * fix even more tests * fix cli * remove kdf service abstraction * add missing deps for browser * fix merge conflicts * clear reset password reason on lock or logout * fix tests * fix other tests * add jsdocs to abstraction * use state provider in crypto service * inverse master password service factory * add clearOn to master password service * add parameter validation to master password service * add component level userId * add missed userId * migrate key hash * fix login strategy service * delete crypto master key from account * migrate master key encrypted user key * rename key hash to master key hash * use mp service for getMasterKeyEncryptedUserKey * fix tests * fix user key decryption logic * add clear methods to mp service * fix circular dep and encryption issue * fix test * remove extra account service call * use EncString in state provider * fix tests * return to using encrypted string for serialization
2024-04-10 02:50:20 +02:00
import { FakeMasterPasswordService } from "@bitwarden/common/auth/services/master-password/fake-master-password.service";
import { BillingAccountProfileStateService } from "@bitwarden/common/billing/abstractions/account/billing-account-profile-state.service";
import { AppIdService } from "@bitwarden/common/platform/abstractions/app-id.service";
import { CryptoService } from "@bitwarden/common/platform/abstractions/crypto.service";
import { EncryptService } from "@bitwarden/common/platform/abstractions/encrypt.service";
import { EnvironmentService } from "@bitwarden/common/platform/abstractions/environment.service";
import { I18nService } from "@bitwarden/common/platform/abstractions/i18n.service";
import { LogService } from "@bitwarden/common/platform/abstractions/log.service";
import { MessagingService } from "@bitwarden/common/platform/abstractions/messaging.service";
import { PlatformUtilsService } from "@bitwarden/common/platform/abstractions/platform-utils.service";
import { StateService } from "@bitwarden/common/platform/abstractions/state.service";
import { KdfType } from "@bitwarden/common/platform/enums";
[PM-5362] Add MP Service (attempt #2) (#8619) * create mp and kdf service * update mp service interface to not rely on active user * rename observable methods * update crypto service with new MP service * add master password service to login strategies - make fake service for easier testing - fix crypto service tests * update auth service and finish strategies * auth request refactors * more service refactors and constructor updates * setMasterKey refactors * remove master key methods from crypto service * remove master key and hash from state service * missed fixes * create migrations and fix references * fix master key imports * default force set password reason to none * add password reset reason observable factory to service * remove kdf changes and migrate only disk data * update migration number * fix sync service deps * use disk for force set password state * fix desktop migration * fix sso test * fix tests * fix more tests * fix even more tests * fix even more tests * fix cli * remove kdf service abstraction * add missing deps for browser * fix merge conflicts * clear reset password reason on lock or logout * fix tests * fix other tests * add jsdocs to abstraction * use state provider in crypto service * inverse master password service factory * add clearOn to master password service * add parameter validation to master password service * add component level userId * add missed userId * migrate key hash * fix login strategy service * delete crypto master key from account * migrate master key encrypted user key * rename key hash to master key hash * use mp service for getMasterKeyEncryptedUserKey * fix tests * fix user key decryption logic * add clear methods to mp service * fix circular dep and encryption issue * fix test * remove extra account service call * use EncString in state provider * fix tests * return to using encrypted string for serialization
2024-04-10 02:50:20 +02:00
import {
FakeAccountService,
FakeGlobalState,
FakeGlobalStateProvider,
mockAccountServiceWith,
} from "@bitwarden/common/spec";
import { PasswordStrengthServiceAbstraction } from "@bitwarden/common/tools/password-strength";
[PM-5362] Add MP Service (attempt #2) (#8619) * create mp and kdf service * update mp service interface to not rely on active user * rename observable methods * update crypto service with new MP service * add master password service to login strategies - make fake service for easier testing - fix crypto service tests * update auth service and finish strategies * auth request refactors * more service refactors and constructor updates * setMasterKey refactors * remove master key methods from crypto service * remove master key and hash from state service * missed fixes * create migrations and fix references * fix master key imports * default force set password reason to none * add password reset reason observable factory to service * remove kdf changes and migrate only disk data * update migration number * fix sync service deps * use disk for force set password state * fix desktop migration * fix sso test * fix tests * fix more tests * fix even more tests * fix even more tests * fix cli * remove kdf service abstraction * add missing deps for browser * fix merge conflicts * clear reset password reason on lock or logout * fix tests * fix other tests * add jsdocs to abstraction * use state provider in crypto service * inverse master password service factory * add clearOn to master password service * add parameter validation to master password service * add component level userId * add missed userId * migrate key hash * fix login strategy service * delete crypto master key from account * migrate master key encrypted user key * rename key hash to master key hash * use mp service for getMasterKeyEncryptedUserKey * fix tests * fix user key decryption logic * add clear methods to mp service * fix circular dep and encryption issue * fix test * remove extra account service call * use EncString in state provider * fix tests * return to using encrypted string for serialization
2024-04-10 02:50:20 +02:00
import { UserId } from "@bitwarden/common/types/guid";
[PM-5404, PM-3518] Migrate user decryption options to new service (#7344) * create new user decryption options service * rename new service to user decryption options * add hasMasterPassword to user decryption options service * migrate device trust service to new user decryption options service * add migration for user-decryption-options * migrate sync service and calls to trust-device-service * rename abstraction file * migrate two factor component * migrate two factor spec * migrate sso component * migrate set-password component * migrate base login decryption component * migrate organization options component * fix component imports * add missing imports - remove state service calls - add update user decryption options method * remove acct decryption options from account * lint * fix tests and linting * fix browser * fix desktop * add user decryption options service to cli * remove default value from migration * bump migration number * fix merge conflict * fix vault timeout settings * fix cli * more fixes * add user decryption options service to deps of vault timeout settings service * update login strategy service with user decryption options * remove early return from sync bandaid for user decryption options * move user decryption options service to lib/auth * move user decryption options to libs/auth * fix reference * fix browser * check user decryption options after 2fa check * update migration and revert tsconfig changes * add more documentation * clear user decryption options on logout * fix tests by creating helper for user decryption options * fix tests * pr feedback * fix factory * update migration * add tests * update missed migration num in test
2024-03-21 01:33:57 +01:00
import {
AuthRequestServiceAbstraction,
InternalUserDecryptionOptionsServiceAbstraction,
} from "../../abstractions";
import { PasswordLoginCredentials } from "../../models";
[PM-5404, PM-3518] Migrate user decryption options to new service (#7344) * create new user decryption options service * rename new service to user decryption options * add hasMasterPassword to user decryption options service * migrate device trust service to new user decryption options service * add migration for user-decryption-options * migrate sync service and calls to trust-device-service * rename abstraction file * migrate two factor component * migrate two factor spec * migrate sso component * migrate set-password component * migrate base login decryption component * migrate organization options component * fix component imports * add missing imports - remove state service calls - add update user decryption options method * remove acct decryption options from account * lint * fix tests and linting * fix browser * fix desktop * add user decryption options service to cli * remove default value from migration * bump migration number * fix merge conflict * fix vault timeout settings * fix cli * more fixes * add user decryption options service to deps of vault timeout settings service * update login strategy service with user decryption options * remove early return from sync bandaid for user decryption options * move user decryption options service to lib/auth * move user decryption options to libs/auth * fix reference * fix browser * check user decryption options after 2fa check * update migration and revert tsconfig changes * add more documentation * clear user decryption options on logout * fix tests by creating helper for user decryption options * fix tests * pr feedback * fix factory * update migration * add tests * update missed migration num in test
2024-03-21 01:33:57 +01:00
import { UserDecryptionOptionsService } from "../user-decryption-options/user-decryption-options.service";
import { LoginStrategyService } from "./login-strategy.service";
import { CACHE_EXPIRATION_KEY } from "./login-strategy.state";
describe("LoginStrategyService", () => {
let sut: LoginStrategyService;
[PM-5362] Add MP Service (attempt #2) (#8619) * create mp and kdf service * update mp service interface to not rely on active user * rename observable methods * update crypto service with new MP service * add master password service to login strategies - make fake service for easier testing - fix crypto service tests * update auth service and finish strategies * auth request refactors * more service refactors and constructor updates * setMasterKey refactors * remove master key methods from crypto service * remove master key and hash from state service * missed fixes * create migrations and fix references * fix master key imports * default force set password reason to none * add password reset reason observable factory to service * remove kdf changes and migrate only disk data * update migration number * fix sync service deps * use disk for force set password state * fix desktop migration * fix sso test * fix tests * fix more tests * fix even more tests * fix even more tests * fix cli * remove kdf service abstraction * add missing deps for browser * fix merge conflicts * clear reset password reason on lock or logout * fix tests * fix other tests * add jsdocs to abstraction * use state provider in crypto service * inverse master password service factory * add clearOn to master password service * add parameter validation to master password service * add component level userId * add missed userId * migrate key hash * fix login strategy service * delete crypto master key from account * migrate master key encrypted user key * rename key hash to master key hash * use mp service for getMasterKeyEncryptedUserKey * fix tests * fix user key decryption logic * add clear methods to mp service * fix circular dep and encryption issue * fix test * remove extra account service call * use EncString in state provider * fix tests * return to using encrypted string for serialization
2024-04-10 02:50:20 +02:00
let accountService: FakeAccountService;
let masterPasswordService: FakeMasterPasswordService;
let cryptoService: MockProxy<CryptoService>;
let apiService: MockProxy<ApiService>;
let tokenService: MockProxy<TokenService>;
let appIdService: MockProxy<AppIdService>;
let platformUtilsService: MockProxy<PlatformUtilsService>;
let messagingService: MockProxy<MessagingService>;
let logService: MockProxy<LogService>;
let keyConnectorService: MockProxy<KeyConnectorService>;
let environmentService: MockProxy<EnvironmentService>;
let stateService: MockProxy<StateService>;
let twoFactorService: MockProxy<TwoFactorService>;
let i18nService: MockProxy<I18nService>;
let encryptService: MockProxy<EncryptService>;
let passwordStrengthService: MockProxy<PasswordStrengthServiceAbstraction>;
let policyService: MockProxy<PolicyService>;
let deviceTrustService: MockProxy<DeviceTrustServiceAbstraction>;
let authRequestService: MockProxy<AuthRequestServiceAbstraction>;
[PM-5404, PM-3518] Migrate user decryption options to new service (#7344) * create new user decryption options service * rename new service to user decryption options * add hasMasterPassword to user decryption options service * migrate device trust service to new user decryption options service * add migration for user-decryption-options * migrate sync service and calls to trust-device-service * rename abstraction file * migrate two factor component * migrate two factor spec * migrate sso component * migrate set-password component * migrate base login decryption component * migrate organization options component * fix component imports * add missing imports - remove state service calls - add update user decryption options method * remove acct decryption options from account * lint * fix tests and linting * fix browser * fix desktop * add user decryption options service to cli * remove default value from migration * bump migration number * fix merge conflict * fix vault timeout settings * fix cli * more fixes * add user decryption options service to deps of vault timeout settings service * update login strategy service with user decryption options * remove early return from sync bandaid for user decryption options * move user decryption options service to lib/auth * move user decryption options to libs/auth * fix reference * fix browser * check user decryption options after 2fa check * update migration and revert tsconfig changes * add more documentation * clear user decryption options on logout * fix tests by creating helper for user decryption options * fix tests * pr feedback * fix factory * update migration * add tests * update missed migration num in test
2024-03-21 01:33:57 +01:00
let userDecryptionOptionsService: MockProxy<InternalUserDecryptionOptionsServiceAbstraction>;
let billingAccountProfileStateService: MockProxy<BillingAccountProfileStateService>;
let stateProvider: FakeGlobalStateProvider;
let loginStrategyCacheExpirationState: FakeGlobalState<Date | null>;
[PM-5362] Add MP Service (attempt #2) (#8619) * create mp and kdf service * update mp service interface to not rely on active user * rename observable methods * update crypto service with new MP service * add master password service to login strategies - make fake service for easier testing - fix crypto service tests * update auth service and finish strategies * auth request refactors * more service refactors and constructor updates * setMasterKey refactors * remove master key methods from crypto service * remove master key and hash from state service * missed fixes * create migrations and fix references * fix master key imports * default force set password reason to none * add password reset reason observable factory to service * remove kdf changes and migrate only disk data * update migration number * fix sync service deps * use disk for force set password state * fix desktop migration * fix sso test * fix tests * fix more tests * fix even more tests * fix even more tests * fix cli * remove kdf service abstraction * add missing deps for browser * fix merge conflicts * clear reset password reason on lock or logout * fix tests * fix other tests * add jsdocs to abstraction * use state provider in crypto service * inverse master password service factory * add clearOn to master password service * add parameter validation to master password service * add component level userId * add missed userId * migrate key hash * fix login strategy service * delete crypto master key from account * migrate master key encrypted user key * rename key hash to master key hash * use mp service for getMasterKeyEncryptedUserKey * fix tests * fix user key decryption logic * add clear methods to mp service * fix circular dep and encryption issue * fix test * remove extra account service call * use EncString in state provider * fix tests * return to using encrypted string for serialization
2024-04-10 02:50:20 +02:00
const userId = "USER_ID" as UserId;
beforeEach(() => {
[PM-5362] Add MP Service (attempt #2) (#8619) * create mp and kdf service * update mp service interface to not rely on active user * rename observable methods * update crypto service with new MP service * add master password service to login strategies - make fake service for easier testing - fix crypto service tests * update auth service and finish strategies * auth request refactors * more service refactors and constructor updates * setMasterKey refactors * remove master key methods from crypto service * remove master key and hash from state service * missed fixes * create migrations and fix references * fix master key imports * default force set password reason to none * add password reset reason observable factory to service * remove kdf changes and migrate only disk data * update migration number * fix sync service deps * use disk for force set password state * fix desktop migration * fix sso test * fix tests * fix more tests * fix even more tests * fix even more tests * fix cli * remove kdf service abstraction * add missing deps for browser * fix merge conflicts * clear reset password reason on lock or logout * fix tests * fix other tests * add jsdocs to abstraction * use state provider in crypto service * inverse master password service factory * add clearOn to master password service * add parameter validation to master password service * add component level userId * add missed userId * migrate key hash * fix login strategy service * delete crypto master key from account * migrate master key encrypted user key * rename key hash to master key hash * use mp service for getMasterKeyEncryptedUserKey * fix tests * fix user key decryption logic * add clear methods to mp service * fix circular dep and encryption issue * fix test * remove extra account service call * use EncString in state provider * fix tests * return to using encrypted string for serialization
2024-04-10 02:50:20 +02:00
accountService = mockAccountServiceWith(userId);
masterPasswordService = new FakeMasterPasswordService();
cryptoService = mock<CryptoService>();
apiService = mock<ApiService>();
tokenService = mock<TokenService>();
appIdService = mock<AppIdService>();
platformUtilsService = mock<PlatformUtilsService>();
messagingService = mock<MessagingService>();
logService = mock<LogService>();
keyConnectorService = mock<KeyConnectorService>();
environmentService = mock<EnvironmentService>();
stateService = mock<StateService>();
twoFactorService = mock<TwoFactorService>();
i18nService = mock<I18nService>();
encryptService = mock<EncryptService>();
passwordStrengthService = mock<PasswordStrengthServiceAbstraction>();
policyService = mock<PolicyService>();
deviceTrustService = mock<DeviceTrustServiceAbstraction>();
authRequestService = mock<AuthRequestServiceAbstraction>();
[PM-5404, PM-3518] Migrate user decryption options to new service (#7344) * create new user decryption options service * rename new service to user decryption options * add hasMasterPassword to user decryption options service * migrate device trust service to new user decryption options service * add migration for user-decryption-options * migrate sync service and calls to trust-device-service * rename abstraction file * migrate two factor component * migrate two factor spec * migrate sso component * migrate set-password component * migrate base login decryption component * migrate organization options component * fix component imports * add missing imports - remove state service calls - add update user decryption options method * remove acct decryption options from account * lint * fix tests and linting * fix browser * fix desktop * add user decryption options service to cli * remove default value from migration * bump migration number * fix merge conflict * fix vault timeout settings * fix cli * more fixes * add user decryption options service to deps of vault timeout settings service * update login strategy service with user decryption options * remove early return from sync bandaid for user decryption options * move user decryption options service to lib/auth * move user decryption options to libs/auth * fix reference * fix browser * check user decryption options after 2fa check * update migration and revert tsconfig changes * add more documentation * clear user decryption options on logout * fix tests by creating helper for user decryption options * fix tests * pr feedback * fix factory * update migration * add tests * update missed migration num in test
2024-03-21 01:33:57 +01:00
userDecryptionOptionsService = mock<UserDecryptionOptionsService>();
billingAccountProfileStateService = mock<BillingAccountProfileStateService>();
stateProvider = new FakeGlobalStateProvider();
sut = new LoginStrategyService(
[PM-5362] Add MP Service (attempt #2) (#8619) * create mp and kdf service * update mp service interface to not rely on active user * rename observable methods * update crypto service with new MP service * add master password service to login strategies - make fake service for easier testing - fix crypto service tests * update auth service and finish strategies * auth request refactors * more service refactors and constructor updates * setMasterKey refactors * remove master key methods from crypto service * remove master key and hash from state service * missed fixes * create migrations and fix references * fix master key imports * default force set password reason to none * add password reset reason observable factory to service * remove kdf changes and migrate only disk data * update migration number * fix sync service deps * use disk for force set password state * fix desktop migration * fix sso test * fix tests * fix more tests * fix even more tests * fix even more tests * fix cli * remove kdf service abstraction * add missing deps for browser * fix merge conflicts * clear reset password reason on lock or logout * fix tests * fix other tests * add jsdocs to abstraction * use state provider in crypto service * inverse master password service factory * add clearOn to master password service * add parameter validation to master password service * add component level userId * add missed userId * migrate key hash * fix login strategy service * delete crypto master key from account * migrate master key encrypted user key * rename key hash to master key hash * use mp service for getMasterKeyEncryptedUserKey * fix tests * fix user key decryption logic * add clear methods to mp service * fix circular dep and encryption issue * fix test * remove extra account service call * use EncString in state provider * fix tests * return to using encrypted string for serialization
2024-04-10 02:50:20 +02:00
accountService,
masterPasswordService,
cryptoService,
apiService,
tokenService,
appIdService,
platformUtilsService,
messagingService,
logService,
keyConnectorService,
environmentService,
stateService,
twoFactorService,
i18nService,
encryptService,
passwordStrengthService,
policyService,
deviceTrustService,
authRequestService,
[PM-5404, PM-3518] Migrate user decryption options to new service (#7344) * create new user decryption options service * rename new service to user decryption options * add hasMasterPassword to user decryption options service * migrate device trust service to new user decryption options service * add migration for user-decryption-options * migrate sync service and calls to trust-device-service * rename abstraction file * migrate two factor component * migrate two factor spec * migrate sso component * migrate set-password component * migrate base login decryption component * migrate organization options component * fix component imports * add missing imports - remove state service calls - add update user decryption options method * remove acct decryption options from account * lint * fix tests and linting * fix browser * fix desktop * add user decryption options service to cli * remove default value from migration * bump migration number * fix merge conflict * fix vault timeout settings * fix cli * more fixes * add user decryption options service to deps of vault timeout settings service * update login strategy service with user decryption options * remove early return from sync bandaid for user decryption options * move user decryption options service to lib/auth * move user decryption options to libs/auth * fix reference * fix browser * check user decryption options after 2fa check * update migration and revert tsconfig changes * add more documentation * clear user decryption options on logout * fix tests by creating helper for user decryption options * fix tests * pr feedback * fix factory * update migration * add tests * update missed migration num in test
2024-03-21 01:33:57 +01:00
userDecryptionOptionsService,
stateProvider,
billingAccountProfileStateService,
);
loginStrategyCacheExpirationState = stateProvider.getFake(CACHE_EXPIRATION_KEY);
});
it("should return an AuthResult on successful login", async () => {
const credentials = new PasswordLoginCredentials("EMAIL", "MASTER_PASSWORD");
apiService.postIdentityToken.mockResolvedValue(
new IdentityTokenResponse({
ForcePasswordReset: false,
Kdf: KdfType.Argon2id,
Key: "KEY",
PrivateKey: "PRIVATE_KEY",
ResetMasterPassword: false,
access_token: "ACCESS_TOKEN",
expires_in: 3600,
refresh_token: "REFRESH_TOKEN",
scope: "api offline_access",
token_type: "Bearer",
}),
);
Auth/PM-5263 - TokenService State Provider Migration (#7975) * PM-5263 - Token Service state migration - (1) Got key and state definitions setup (2) Ported over core state service getTimeoutBasedStorageOptions method logic into local determineStorageLocation method (3) Updated majority of methods to use state provider state * PM-5263 - StateSvc - add TODO to remove timeoutBasedStorageOptions + other state methods after migration code complete. * PM-5263 - TokenSvc - ClearToken method - (1) Update signature to remove user id as it wasn't used and it simplifies the new state provider implementation (2) Convert away from state svc to state provider state. * PM-5263 - TokenService - update deps - WIP on circular dep issues. * PM-5263 - To resolve circular dep issues between VaultTimeoutSettingsSvc and TokenService: (1) For writes, require callers to pass in vault timeout data (2) For reads, we can just check both locations. This approach has 1 less state call than the previous implementation and is safe as long as the clear logic properly works and is executed anytime a user changes their vault timeout action (lock or log out) & vault timeout (numeric value) * PM-5263 - VaultTimeoutSettingsSvc - Set token calls now updated to include vault timeout info. * PM-5263 - Update API Service - add state service and look up vault timeout details and pass to token service when setting token info. * PM-5263 - TokenService - update service dependencies. * PM-5263 - TokenService - Add new getAccessTokenByUserId method for state service use case. * PM-5263 - StateSvc - remove migrated methods and try to replace all usages of getAccessToken. WIP * PM-5263 - TokenSvc Migration - start on migrator * PM-5263 - (1) TokenSvc - Build new clearAccessTokenByUserId which is required by state service (2) TokenSvc - Update getToken to take an optional userId to handle another state service case (3) Add some documentation to TokenSvc abstraction. * PM-5263 - StateService - finish updating all calls within the state service which accessed token service state directly with calls to the new token service methods instead. * PM-5263 - TokenSvc Abstraction - Add more docs * PM-5263 - TokenSvc abstraction - more doc tweaks * PM-5263 - Web state service - add new token service dependency. * PM-5263 - User API Key Login Strategy - Update to pull vault timeout action and vault timeout from state service in order to pass to new token service endpoints for setting API key client id and secret. * PM-5263 - (1) Remove TokenSvc owned state from account (2) StateSvc - remove account scaffold logic for clearing removed account data. The same functionality will exist in the state provider framework via lifecycle hooks cleaning up this data and users getting initialized with null data by default. * PM-5263 - Add token service dependency to state service (WIP - desktop deps not working) * PM-5263 - Update services module on desktop and browser to add token svc dependency * PM-5263 - API service factory - add state service factory dependency that I missed initially to get browser building. * PM-5263 - TokenSvc - getToken/setToken/decodeToken --> 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 <git@mgibson.dev> * 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 <jlf0dev@users.noreply.github.com> * 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<any> and replace with promise<void> * 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 <jfink@bitwarden.com> * Update libs/auth/src/common/login-strategies/password-login.strategy.ts Co-authored-by: Jake Fink <jfink@bitwarden.com> * 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 <git@mgibson.dev> Co-authored-by: Jake Fink <jlf0dev@users.noreply.github.com> Co-authored-by: Justin Baur <19896123+justindbaur@users.noreply.github.com> Co-authored-by: Jake Fink <jfink@bitwarden.com>
2024-03-15 16:50:04 +01:00
tokenService.decodeAccessToken.calledWith("ACCESS_TOKEN").mockResolvedValue({
sub: "USER_ID",
name: "NAME",
email: "EMAIL",
premium: false,
});
const result = await sut.logIn(credentials);
expect(result).toBeInstanceOf(AuthResult);
});
it("should return an AuthResult on successful 2fa login", async () => {
const credentials = new PasswordLoginCredentials("EMAIL", "MASTER_PASSWORD");
apiService.postIdentityToken.mockResolvedValueOnce(
new IdentityTwoFactorResponse({
TwoFactorProviders: ["0"],
TwoFactorProviders2: { 0: null },
error: "invalid_grant",
error_description: "Two factor required.",
email: undefined,
ssoEmail2faSessionToken: undefined,
}),
);
await sut.logIn(credentials);
const twoFactorToken = new TokenTwoFactorRequest(
TwoFactorProviderType.Authenticator,
"TWO_FACTOR_TOKEN",
true,
);
apiService.postIdentityToken.mockResolvedValue(
new IdentityTokenResponse({
ForcePasswordReset: false,
Kdf: KdfType.Argon2id,
Key: "KEY",
PrivateKey: "PRIVATE_KEY",
ResetMasterPassword: false,
access_token: "ACCESS_TOKEN",
expires_in: 3600,
refresh_token: "REFRESH_TOKEN",
scope: "api offline_access",
token_type: "Bearer",
}),
);
Auth/PM-5263 - TokenService State Provider Migration (#7975) * PM-5263 - Token Service state migration - (1) Got key and state definitions setup (2) Ported over core state service getTimeoutBasedStorageOptions method logic into local determineStorageLocation method (3) Updated majority of methods to use state provider state * PM-5263 - StateSvc - add TODO to remove timeoutBasedStorageOptions + other state methods after migration code complete. * PM-5263 - TokenSvc - ClearToken method - (1) Update signature to remove user id as it wasn't used and it simplifies the new state provider implementation (2) Convert away from state svc to state provider state. * PM-5263 - TokenService - update deps - WIP on circular dep issues. * PM-5263 - To resolve circular dep issues between VaultTimeoutSettingsSvc and TokenService: (1) For writes, require callers to pass in vault timeout data (2) For reads, we can just check both locations. This approach has 1 less state call than the previous implementation and is safe as long as the clear logic properly works and is executed anytime a user changes their vault timeout action (lock or log out) & vault timeout (numeric value) * PM-5263 - VaultTimeoutSettingsSvc - Set token calls now updated to include vault timeout info. * PM-5263 - Update API Service - add state service and look up vault timeout details and pass to token service when setting token info. * PM-5263 - TokenService - update service dependencies. * PM-5263 - TokenService - Add new getAccessTokenByUserId method for state service use case. * PM-5263 - StateSvc - remove migrated methods and try to replace all usages of getAccessToken. WIP * PM-5263 - TokenSvc Migration - start on migrator * PM-5263 - (1) TokenSvc - Build new clearAccessTokenByUserId which is required by state service (2) TokenSvc - Update getToken to take an optional userId to handle another state service case (3) Add some documentation to TokenSvc abstraction. * PM-5263 - StateService - finish updating all calls within the state service which accessed token service state directly with calls to the new token service methods instead. * PM-5263 - TokenSvc Abstraction - Add more docs * PM-5263 - TokenSvc abstraction - more doc tweaks * PM-5263 - Web state service - add new token service dependency. * PM-5263 - User API Key Login Strategy - Update to pull vault timeout action and vault timeout from state service in order to pass to new token service endpoints for setting API key client id and secret. * PM-5263 - (1) Remove TokenSvc owned state from account (2) StateSvc - remove account scaffold logic for clearing removed account data. The same functionality will exist in the state provider framework via lifecycle hooks cleaning up this data and users getting initialized with null data by default. * PM-5263 - Add token service dependency to state service (WIP - desktop deps not working) * PM-5263 - Update services module on desktop and browser to add token svc dependency * PM-5263 - API service factory - add state service factory dependency that I missed initially to get browser building. * PM-5263 - TokenSvc - getToken/setToken/decodeToken --> 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 <git@mgibson.dev> * 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 <jlf0dev@users.noreply.github.com> * 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<any> and replace with promise<void> * 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 <jfink@bitwarden.com> * Update libs/auth/src/common/login-strategies/password-login.strategy.ts Co-authored-by: Jake Fink <jfink@bitwarden.com> * 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 <git@mgibson.dev> Co-authored-by: Jake Fink <jlf0dev@users.noreply.github.com> Co-authored-by: Justin Baur <19896123+justindbaur@users.noreply.github.com> Co-authored-by: Jake Fink <jfink@bitwarden.com>
2024-03-15 16:50:04 +01:00
tokenService.decodeAccessToken.calledWith("ACCESS_TOKEN").mockResolvedValue({
sub: "USER_ID",
name: "NAME",
email: "EMAIL",
premium: false,
});
const result = await sut.logInTwoFactor(twoFactorToken, "CAPTCHA");
expect(result).toBeInstanceOf(AuthResult);
});
it("should clear the cache if more than 2 mins have passed since expiration date", async () => {
const credentials = new PasswordLoginCredentials("EMAIL", "MASTER_PASSWORD");
apiService.postIdentityToken.mockResolvedValue(
new IdentityTwoFactorResponse({
TwoFactorProviders: ["0"],
TwoFactorProviders2: { 0: null },
error: "invalid_grant",
error_description: "Two factor required.",
email: undefined,
ssoEmail2faSessionToken: undefined,
}),
);
await sut.logIn(credentials);
loginStrategyCacheExpirationState.stateSubject.next(new Date(Date.now() - 1000 * 60 * 5));
const twoFactorToken = new TokenTwoFactorRequest(
TwoFactorProviderType.Authenticator,
"TWO_FACTOR_TOKEN",
true,
);
await expect(sut.logInTwoFactor(twoFactorToken, "CAPTCHA")).rejects.toThrow();
});
});