mirror of
https://github.com/bitwarden/browser
synced 2025-12-13 06:43:35 +00:00
Trusted Device Encryption feature (#5950)
* PM-1049 - Create first display draft of login-decryption-options base and web components (no data loading or user actions wired up yet; WIP) * PM-1049 - Update DeviceResponse to match latest properties on backend * PM-1049 - Add getDevices call to retrieve all user devices to API service * PM-1049 - WIP on figuring out login decryption options component requirements * PM-1049 - Add empty login decryption options to desktop * PM-1049 - Desktop - Update "Log in initiated" translation to be "Login Initiated" per figma and product request * PM-1049 - Desktop - login decryption options component html done * PM-1049 - Move login-decryption-options in web into own folder * PM-1049 - Browser - created html for login-decryption-options component * PM-1049 - Move newly created getDevices() method out of api.service into proper place in new devices-api.service. * PM-1049 -Comment cleanup and TODO added * PM-1049 - Comment cleanup and dependency cleanup across all login-decryption-options comps * PM-1049 - WIP of building out needed response and regular models for saving new UserDecryptionOptions on the Account in state. * PM-1049 - Update all User Decryption Options response and state models in light of the back end changes from a list to an object. Web building now with decryption options stored on state under the account successfully. Must now build out state service methods for retrieving / setting account decryption options for use elsewhere. * PM-1049 - State Service - setup setters / getters for UserDecryptionOptions off the account * PM-1049 - StateService - replace User with Acct for decryption options * PM-1049 - Create domain models vs using response models as response models have a response property w/ the full response nested underneath which we don't need to persist for the user decryption options stored on the account. * PM-1049 - AcctDecryptionOptions now persist across page refreshes of the login-initiated page to act similarly to refreshes on the lock screen. Accomplished via persisting AcctDecryptionOptions in local storage -- still cleared on logout. * PM-1049 - IdTokenResponse - only userDecryptionOptions if they exist on the response from the server; I saw a few instances where it did not. Wasn't able to replicate consistently, but I put this check here to be safe. * PM-1049 - Login Initiated route can only be accessed if user is AuthN w/ locked vault + TDE feature flag is on. * PM-1049 - LoginDecryptionOptions - (1) Wire up loading logic (2) Retrieve User Acct Decryption options to determine whether or not to show request admin approval btn and approve w/ MP (3) Write up future logic for requestAdminApproval (4) approveWithMasterPassword takes you to the lock screen to login. * PM-1049 - Apply same guards as in web to login-decryption-options in desktop & browser. * PM-1049 - (1) Updated dependencies in parent BaseLoginDecryptionOptionsComponent class + child components (2) Retrieve userEmail b/c needed for displaying which email the user is logging in with (3) Add log out functionality (4) Add comments regarding future implementation details for each login approval flow. * PM-1049 - Web/Browser/Desktop LoginDecryptionOptions - (1) Wire up approval buttons (2) Add conditional margins (3) Loading spinner added (4) Display userEmail + "not you" logout link * PM-1049 - Add TODOs for future changes needed as part of the Login Approval flows for TDE * PM-1049 - TODO: replace base component with business service * add new storage to replace MasterKey with UserSymKey * add storage for master key encrypted user symmetric key * Begin refactor of crypto service to support new key structure * remove provided key from getKeyForUserEncryption * add decryption with MasterKey method to crypto service * update makeKeyPair on crypto service to be generic * add type to parameter of setUserKey in abstraction of crypto service * add setUserSymKeyMasterKey so we can set the encrypted user sym key from server * update cli with new crypto service methods - decrypt user sym key and set when unlocking * separate the user key in memory from user keys in storage * add new memory concept to crypto service calls in cli * update auth service to use new crypto service * update register component in lib to use new crypto service * update register component again with more crypto service * update sync service to use new crypto service methods * update send service to use new crypto service methods * update folder service to use new crypto service methods * update cipher service to use new crypto service * update password generation service to use new crypto service * update vault timeout service with new crypto service * update collection service to use new crypto service * update emergency access components to use new crypto service methods * migrate login strategies to new key model - decrypt and set user symmetric key if Master Key is available - rename keys where applicable - update unit tests * migrate pin to use user's symmetric key instead of master key - set up new state - migrate on lock component - use new crypto service methods * update pin key when the user symmetric key is set - always set the protected pin so we can recreate pin key from user symmetric key - stop using EncryptionPair in account - use EncString for both pin key storage - update migration from old strategy on lock component * set user symmetric key on lock component - add missed key suffix types to crypto service methods * migrate auto key - add helper to internal crypto service method to migrate * remove additional keys in state service clean * clean up the old pin keys in more flows - in the case that the app is updated while logged in and the user changes their pin, this will clear the old pin keys * finish migrate auto key if needed - migrate whenever retrieved from storage - add back the user symmetric key toggle * migrate biometrics key - migrate only on retrieval * fix crypto calls for key connector and vault timeout settings * update change password components with new crypto service * update assortment of leftover old crypto service calls * update device-crypto service with new crypto service * remove old EncKey methods from crypto service * remove clearEncKey from crypto service * move crypto service jsdoc to abstraction * add org key type and new method to build a data enc key for orgs * fix typing of bulk confirm component * fix EncString serialization issues & various fixes Co-authored-by: Matt Gibson <MGibson1@users.noreply.github.com> * update account model with new keys serialization * migrate native messaging for biometrics to use new key model - support backwards compatibility - update safari web extension to send user key - add error handling * add early exit to native messaging flow for errors * improve error strings in crypto service * disable disk cache for browser due to bg script/popup race conditions * clear bio key when pin is migrated as bio is refreshed * share disk cache to fix syncing issues between contexts * check for ephemeral pin before process reload * remove state no longer needed and add JSDOC * fix linter * add new types to tests * remove cryptoMasterKeyB64 from account * fix tests imports * use master key for device approvals still * cleanup old TODOs, add missing crypto service parameters * fix cli crypto service calls * share disk cache between contexts on browser * Revert "share disk cache between contexts on browser" This reverts commit56a590c491. * use user sym key for account changing unlock verification * add tests to crypto service * rename 'user symmetric key' with 'user key' * remove userId from browser crypto service * updated EncKey to UserKey where applicable * jsdoc deprecate account properties * use encrypt service in crypto service * use encrypt service in crypto service * require key in validateUserKey * check storage for user key if missing in memory * change isPinLockSet to union type * move biometric check to electron crypto service * add secondary fallback name for bio key for safari * migrate master key if found * pass key to encrypt service * rename pinLock to pinEnabled * use org key or user key for encrypting attachments * refactor makeShareKey to be more clear its for orgs * rename retrieveUserKeyFromStorage * clear deprecated keys when setting new user key * fix cipher service test * options is nullable while setting user key * more crypto service refactors - check for auto key when getting user key - consolidate getUserKeyFromMemory and FromStorage methods - move bio key references out of base crypto service - update either pin key when setting user key instead of lock component - group deprecated methods - rename key legacy method * Feature/PM-1049 - TDEFflow 3 login decryption options - PR feedback changes (#5642) * PM-1049 - PR Feedback change - Browser - replace incorrect use of routerlink with manual attribute styling to keep anchor styling + tab focus while not having a router action race condition for the log out action to complete. * PM-1049 - PR Feedback - State Service changes - rename get/setAcctDecryptionOptions to get/setAccountDecryptionOptions * PM-1049 - PR Feedback changes - LoginDecryptionOptionsComp - Remove unncessary appA11yTitle directives as title / aria text would be identical to the displayed inner button text. * DeviceType - Create sets of device types which other components can reference to avoid having to manually define groups of device types. * PM-1049 - PR Feedback Changes - Update base-login-decryption-options component to leverage async piped observables per best practices. Updated all client templates to leverage new data streams. * PM-1049 - BaseLoginDecryptionOptionsComp - Add validation service for generic error handling * PM-1049 - DeviceResponse mistakenly had name as a number instead of a string * PM-1049 - First draft of creating observable based data store service for Devices so that the base login comp can leverage it instead of calling the devices API service directly (as it will be moved into the SDK in the future). * PM-1049 - Register new DevicesService on jslib-services module for use in components. * PM-1049 - Add new hasDevicesOfTypes call to devices data store svc + devices API service. * PM-1049 - BaseLoginDecryptionOptionsComp - wire up call to devicesService.hasDevicesOfTypes to replace getDevices() to avoid bringing down all trusted device information unnecessarily. * PM-1049 - LoginDecryptionOptionsComp - Web HTML - clean up loading state so it displays spinner centered properly. * PM-1049 - LoginDecryptionOptionsComp - Desktop HTML - Don't show login initiated title while page is loading to match other clients behavior. * PM-1049 - Devices Services - Update naming of hasDevicesOfTypes to match new name on back end + route change to getDevicesExistenseByTypes * PM-1049 - Device Response & View models - remove keys which are going to be deprecated on the base model * PM-1049 - DevicesService - devicesBSubject --> devicesSubject rename per PR feedback * PM-1049 - Devices Services - correct spelling of existence (*facepalm*) * PM-1049 - Update comment for clarity per PR feedback * PM-1049 - DevicesSvc - UserSymKey --> UserKey rename * PM-1049 - BaseLoginDecryptionOptions - replace user email source - get from stateService vs tokenService. * PM-1049 - BaseLoginDecryptionOptions - Remove uncessary check for userEmail as we will always have it here otherwise everything in the app is broken. * PM-1049 - BaseLoginDecryptionOptions - Finish cleaning up removal of user email from showReqAdminApprovalBtn$ stream * PM-1049 - LoginDecryptionOptionsComp - HTML revisions in web & browser to better space out buttons using tailwind or top margin to avoid need for multiple async pipes and shareReplay. * PM-1049 - DevicesService - of course all observables should have $ suffix. Facepalm. * PM-1049 - BaseLoginDecryptionOptionsComp - Update verbiage and style of destroy observable used for hooking into ngOnDestroy lifecycle to clean up all observables * PM-1049 - BaseLoginDecryptionOptions - PR feedback changes - refactor user email to have an underlying bSubject stream to ensure subscription/promise execution separately from the template async pipe subscribing to the stream. * PM-1049 - DevicesApiService - getDevicesExistenceByTypes - PR feedback - explicitly convert result to boolean instead of casting. * PM-1049 - BaseLoginDecryptionOptionsComp - Add ShareReplay for getAccountDecryptionOptions + context per PR feedback * PM-1049 - LoginDecryptionOptionsComp - Completely back away from template async pipe reactive approach as it caused massively increased complexity for little gain. Instead, just focus on reactively pulling asynchronously retrieved data and setting page loading state simply. This just works and is so much less overhead. + Add comments re flows of the component to be done later * PM-1049- Revert DevicesService implementation from smart data store cache service giant mess into simple, clean data passthrough service to avoid complexity and keep moving forward. YAGNI Co-authored-by: Andreas Coroiu <andreas@andreascoroiu.com> * PM-1049 - DeviceCryptoService - Add decryptUserKey method (WIP) * PM-1049 - AccountDecryptionOptions - add get helpers for checking for trusted device / key connector decryption option existence. * PM-1049 - SSO Login Strategy - added comments in setUserKey method for where we will probably be consuming device keys and determining if the device is trusted or not (i.e., if we can get a decrypted user sym key in memory) * PM-1049 - DeviceCryptoSvc.decryptUserKey - Update method to properly use state service device key retrieval + add TODO to figure out what to do if user has previously had a device key and has cleared their local cache (which will result in the device being untrusted now) * PM-1049 - SSO Login Strategy - add comment re future passkey login strategy support * PM-2759 - SSO & 2FA components updated with v0 of navigation logic to send users to LoginDecryptionOptions * PM-1049 - Account > AccountDecryptionOptions - can't create getter helper methods for determining if user has decryption options b/c of issues w/ account deserialization. Moving past b/c I can just easily check if the given options are not undefined. * PM-2759 - Add TODOs for deprecation of id token response resetMasterPassword logic and replacement with use of accountDecryptionOptions --------- Co-authored-by: Andreas Coroiu <andreas@andreascoroiu.com> * revert sharing disk cache between contexts * fix tests * add better tests to crypto service * add hack to get around duplicate instances of disk cache on browser * prevent duplicate cache deletes in browser * fix browser state service tests * Feature/PM-1212 - TDE - Approve with master password flow (#5706) * PM-1212 - StateSvc - Add getUserDeviceTrustChoice && setUserDeviceTrustChoice to persist user's choice in local storage in case of refresh on login approval screens (ex: lock) * PM-1212 - DeviceCryptoSvc - Add getUserDeviceTrustChoice && setUserDeviceTrustChoice as state service is lower level service for caching * PM-1212 - LoginDecryptionOptionsComp - Save result of rememberEmail checkbox into local storage via deviceCryptoService.setUserDeviceTrustChoice * PM-1212 - Lock component - after user key is set, check if user chose to establish trust, and if they did, then establish trust and reset choice. * PM-1212 - Update naming of methods per discussion with Jake + add comment explaining intended single use retrieval and need for resetting the value. * DeviceCryptoService - Refactor - decryptUserKey --> decryptUserKeyWithDeviceKey to match crypto service refactor naming convention * PM-1212 - Refactor State Service per PR feedback to store trustDeviceChoiceForDecryption on Account.settings b/c the temp setting is scoped to a user. * PM-2759 - SSO & 2FA Navigation to TDE Comp - Needs more work - Found scenarios on web with 2FA in which the expected navigation doesn't work. Adding TODO to assist in fixing * (1) Add Trust to DeviceCryptoService name (2) Move DeviceTrustCryptoService under auth folder * PM-1212 - Add tests for new getUserTrustDeviceChoiceForDecryption and setUserTrustDeviceChoiceForDecryption methods + TODOs for future tests. * PM-1212- Renaming / moving DeviceTrustCryptoService broke all the things - fixed all the client builds. * PM-1212- Copy doc comment to abstraction per PR feedback * PM-1212 - BaseLoginDecryptionOptions comp - remove unncessary cast to form control as apparently reactive forms now properly derives types. * [PM-1203] Replace MP confirmation with verification code (#5656) * [PM-1203] feat: ask for OTP if user does not have MP * [PM-1203] feat: add backwards compatibility for accounts/servers without decryption options * [PM-1203] feat: move hasMasterPassword to user-verification.service * [PM-1203] fix: remove duplicate implementation from crypto service * [PM-1203] fix: cli build * Tweak device trust crypto service implementation to match mobile late… (#5744) * Tweak device trust crypto service implementation to match mobile latest which results in more single responsibility methods * Update tests to match device trust crypto service implementation changes * update comment about state service * update pinLockType states and add jsdocs * add missed pinLockType changes * [PM-1033] Org invite user creation flow 1 (#5611) * [PM-1033] feat: basic redirection to login initiated * [PM-1033] feat: add ui for TDE enrollment * [PM-1033] feat: implement auto-enroll * [PM-1033] chore: add todo * [PM-1033] feat: add support in browser * [PM-1033] feat: add support for desktop * [PM-1033] feat: improve key check hack to allow regular accounts * [PM-1033] feat: init asymmetric account keys * [PM-1033] chore: temporary fix bug from merge * [PM-1033] feat: properly check if user can go ahead an auto-enroll * [PM-1033] feat: simplify approval required * [PM-1033] feat: rewrite using discrete states * [PM-1033] fix: clean-up and fix merge artifacts * [PM-1033] chore: clean up empty ng-container * [PM-1033] fix: new user identification logic * [PM-1033] feat: optimize data fetching * [PM-1033] feat: split user creating and reset enrollment * [PM-1033] fix: add missing loading false statement * [PM-1033] fix: navigation logic in sso component * [PM-1033] fix: add missing query param * [PM-1033] chore: rename to `ExistingUserUntrustedDevice` * PM-1033 - fix component templates to reference `ExistingUserUntrustedDevice` so clients can build --------- Co-authored-by: Jared Snider <jsnider@bitwarden.com> * remove extra partial key * set master key on lock component * rename key hash to password hash on crypto service * fix cli * rename enc user key setter in crypto service * Adds Events & Human Readable Messages (#5746) * [PM-1202] Hide the Master Password tab on Settings / Security (#5649) * [PM-1203] feat: ask for OTP if user does not have MP * [PM-1203] feat: get master password status from decryption options * [PM-1203] feat: add backwards compatibility for accounts/servers without decryption options * [PM-1203] feat: move hasMasterPassword to user-verification.service * fix merge issues * Change getUserTrustDeviceChoiceForDecryption / setUserTrustDeviceChoiceForDecryption to getShouldTrustDevice / setShouldTrustDevice (#5795) * Auth/[PM-1260] - Existing User - Login with Trusted Device (Flow 2) (#5775) * PM-1378 - Refactor - StateSvc.getDeviceKey() must actually convert JSON obj into instance of SymmetricCryptoKey * TODO: BaseLoginDecryptionOptionsComponent - verify new user check doesn't improperly pick up key connector users * PM-1260 - Add new encrypted keys to TrustedDeviceUserDecryptionOptionResponse * PM-1260 - DeviceTrustCryptoSvc - decryptUserKeyWithDeviceKey: (1) update method to optionally accept deviceKey (2) Return null user key when no device key exists (3) decryption of user key now works in the happy path * PM-1260 - LoginStrategy - SaveAcctInfo - Must persist device key on new account entity created from IdTokenResponse for TDE to work * PM-1260 - SSO Login Strategy - setUserKey refactor - (1) Refactor existing logic into trySetUserKeyForKeyConnector + setUserKeyMasterKey call and (2) new trySetUserKeyWithDeviceKey method for TDE * PM-1260 - Refactor DeviceTrustCryptoService.decryptUserKeyWithDeviceKey(...) - Add try catch around decryption attempts which removes device key (and trust) on decryption failure + warn. * PM-1260 - Account - Add deviceKey to fromJSON * TODO: add device key tests to account keys * TODO: figure out state service issues with getDeviceKey or if they are an issue w/ the account deserialization as a whole * PM-1260 - Add test suite for decryptUserKeyWithDeviceKey * PM-1260 - Add interfaces for server responses for UserDecryptionOptions to make testing easier without having to use the dreaded any type. * PM-1260 - SSOLoginStrategy - SetUserKey - Add check looking for key connector url on user decryption options + comment about future deprecation of tokenResponse.keyConnectorUrl * PM-1260 - SSO Login Strategy Spec file - Add test suite for TDE set user key logic * PM-1260 - BaseLoginStrategy - add test to verify device key persists on login * PM-1260 - StateService - verified that settings persist properly post SSO and it's just device keys we must manually instantiate into SymmetricCryptoKeys * PM-1260 - Remove comment about being unable to feature flag auth service / login strategy code due to circ deps as we don't need to worry about it b/c of the way we've written the new logic to be additive. * PM-1260 - DevicesApiServiceImplementation - Update constructor to properly use abstraction for API service * PM-1260 - Browser - AuthService - (1) Add new, required service factories for auth svc and (2) Update auth svc creation in main.background with new deps * PM-1260 - CLI - Update AuthSvc deps * PM-1260 - Address PR feedback to add clarity / match conventions * PM-1260 - Resolving more minor PR feedback * PM-1260 - DeviceTrustCryptoService - remove debug warn * PM-1378 - DeviceTrustCryptoSvc - TrustDevice - Fix bug where we only partially encrypted the user key with the device public key b/c I incorrectly passed userKey.encKey (32 bytes) instead of userKey.key (64 bytes) to the rsaEncrypt function which lead to an encryption type mismatch when decrypting the user's private key with the 32 byte decrypted user key obtained after TDE login. (Updated happy path test to prevent this from happening again) * PM-1260 - AccountKeys tests - add tests for deviceKey persistence and deserialization * PM-1260 - DeviceTrustCryptoSvc Test - tweak verbiage per feedback * PM-1260 - DeviceTrustCryptoSvc - Test verbiage tweak part 2 * Update apps/browser/src/background/service-factories/devices-api-service.factory.ts per PR feedback Co-authored-by: Justin Baur <19896123+justindbaur@users.noreply.github.com> --------- Co-authored-by: Justin Baur <19896123+justindbaur@users.noreply.github.com> * Defect - LockComp - After setting user key, must AWAIT retrieval of user's previous choice to have trusted the device or not. (#5804) * [PM-2928] [PM-2929] [PM-2930] Fixes for: [PM-1203] Replace MP confirmation with verification code (#5798) * [PM-2928] feat: hide change email if user doen't have MP * [PM-2929] feat: hide KDF settings if user doesn't have MP * [PM-2930] feat: remove MP copy * Removed self-hosted check from TDE SSO config. (#5837) * [PM-2998] Move Approving Device Check (#5822) * Switch to retrieving approving device from token response - Remove exist-by-types API call - Define `HasApprovingDevices` on TDE options * Update Naming * Update Test * Update Missing Names * [PM-2908] feat: show account created toast (#5810) * fix bug where we weren't passing MP on Restart to migrate method in lock * fix: buffer null error (#5856) * Auth/[pm-2759] - TDE - SSO and 2FA routing logic (#5829) * PM-2759 - SsoComp - (1) Temp remove all TDE routing logic (2) Refactor existing navigation logic via new component utility function navigateViaCallbackOrRoute * PM-2759 - SSO Component - Create test suite for logIn logic * PM-2759 - SsoComp Tests - add disclaimer regarding testing private methods and props * PM-1259 - SSO Comp - Refactor LogIn method to use functions for each navigation case for improved readability * PM-1259 - SSO Comp Tests - Add tests for error case during login + test for new handleLoginError logic * PM-2759 - SsoComp - Deprecate resetMasterPassword and replace with AccountDecryptionOptions logic + update tests * PM-2759 - SsoComp + tests - Add trusted device encryption first draft handling which has login success and force password reset handling * PM-2759 - Minor SsoComp comment and method name tweaks * PM-2759 - BaseTwoFactorComp - (1) Comment out TDE stuff for now (2) Add test suite (3) Replace global window in base comp constructor with angular injection token for window which follows best practices and allows for mocking so the comp can be unit tested * PM-2759 - Update child 2FA components to use angular injection token for window like base comp * PM-2759 - TwoFactorComp - Finish testing all logic in doSubmit * PM-2759 - TwoFactorComponent - Refactor DoSubmit method logic into multiple simple functions to make logic easier to follow * PM-2759 - Add newtrustedDeviceOption.hasManageResetPasswordPermission property to match server changes * PM-2759 - Flag AuthResult.resetMasterPassword property as deprecated * PM-2759 - SSO comp - TDE routing logic - User without MP and ResetPassword permission must set a MP * PM-2759 - Update Sso Comp tests to reflect additionally added TDE > MP set required logic (when user has no MP but they can reset other user passwords) * PM-2759 - SsoComp - Add comment explaining the happy paths better for TDE success navigation * PM-2759 - SsoComp - Refactor isTrustedDeviceEncEnabled logic into own method * PM-2759 - SsoComp - As the 2FA comp passes the org id through to each route, going to standardize on doing so across the board for now to avoid any tricky scenarios down the line where it is needed and it's not present * PM-2759 - SsoComp - Finish renaming orgIdFromState to orgIdentifier * PM-2759 - SsoComp - update tests for forcePasswordReset flows now passing orgIdentifier as query param * PM-2759 - SsoComp Tests - Export mockAcctDecryptionOpts permutations so we can share them across SsoComp and TwoFactorComp tests * PM-2759 - Refactor 2FA comp post login redirect logic to match SSO component + add TDE logic * PM-2759 - SsoComp - Refactor tests a bit for improved re-use * PM-2759 - Sso Comp tests - can't export consts from a spec file or the other spec files that import them will re-execute the whole test suite as a nested test suite. TIL. * PM-2759 - TwoFactorComp tests - All existing navigation scenarios + new TDE scenarios should now be tested. * PM-2759 - Web - 2FA comp - Fix build error b/c of renamed base comp prop (identifier --> orgIdentifier) * PM-2759 - Fix SsoLogin strategy tests b/c they were broken w/ the addition of the HasManageResetPasswordPermission prop to the TrustedDeviceOption interface * PM-2759 - Web TwoFactorComp - goAfterLogIn method must be an arrow function to inherit the parent base component scope so that important things like angular services can be defined. Web 2FA flow does not work without this being an arrow func. * PM-2759 - Fix typo * PM-2759 - SsoComp and TwoFactorComp tests - move service and other mocks into the top level before each to better ensure no crossover between test states per PR feedback * PM-2759 - SsoComp - add clarity by refactoring unclear comment * PM-2759 - SsoComp - Per excellent PR feedback, refactor if else statements to guard statements for better readability / design * PM-2759 - TwoFactorComp - Replace ifs with guard statements * PM-2759 - TwoFactorComp - add clarity to comment per PR feedback * PM-2759 - Replace use of jest.Mocked with MockProxy per PR feedback * PM-2759 - Use unknown over any per PR feedback * Bypass Master Password Reprompt if a user does not have a MP set (#5600) * Add a check for a master password in PasswordRepromptService.enabled() * Add tests for enabled() * Update state service method call * Use UserVerificationService to determine if a user has a master password * rename password hash to master key hash * fix cli build from key hash renaming * [PM-1339] Allow Rotating Device Keys (#5806) * Merge remote-tracking branch 'origin/feature/trusted-device-encryption' into Auth/pm-1339/rotate-device-keys * Implement Rotation of Current Device Keys - Detects if you are on a trusted device - Will rotate your keys of only this device - Allows you to still log in through SSO and decrypt your vault because the device is still trusted * Address PR Feedback * Move Files to Auth Ownership * fix: getOrgKeys returning null * [PM-3143] Trusted device encryption: Refactor reset enroll service (#5869) * create new reset enrollment service * refactor: login decryption options according to TODO * feat: add tests * PM-3143 - Add override to overriden methods --------- Co-authored-by: Jared Snider <jsnider@bitwarden.com> * generate a master key from master password if needed (#5870) * [PM-3120] fix: device key not being saved properly (#5882) * Auth/pm 1050/pm 1051/remaining tde approval flows (#5864) * fix: remove `Unauth guard` from `/login-with-device` * [PM-3101] Fix autofill items not working for users without a master password (#5885) * Add service factories for user verification services * Update autofill service to check for existence of master password for autofill * Update the context menu to check for existence of master password for autofill * context menu test fixes * [PM-3210] fix: use back navigation (#5907) * Removed buttons (#5935) * PM-2759 - Fix broken backwards compatibility for authResult.resetMast… (#5940) * PM-2759 - Fix broken backwards compatibility for authResult.resetMasterPassword * PM-2759 - Update TODO with specific tech debt task + target release date * TDE - State Svc - setDeviceKey should support setting null for future support of clearing device key. (#5942) * Check if a user has a mp before showing kdf warning (#5929) * [PM-1200] Unlock settings changes for accounts without master password - clients (#5894) * [PM-1200] chore: add comment for jake * [PM-1200] chore: rename to `vault-timeout` * [PM-1200] feat: initial version of `getAvailableVaultTimeoutActions` * [PM-1200] feat: implement `getAvailableVaultTimeoutActions` * [PM-1200] feat: change helper text if only logout is available * [PM-1200] feat: only show available timeout actions * [PM-1200] fix: add new service factories and dependencies * [PM-1200] fix: order of dependencies `UserVerificationService` is needed by `VaultTimeoutSettingsService` * [PM-1200] feat: add helper text if no lock method added * [PM-1200] refactor: simplify prev/new values when changing timeout and action * [PM-1200] feat: fetch timeout action from new observable * [PM-1200] refactor: make `getAvailableVaultTimeoutActions` private * [PM-1200] feat: add test cases for `vaultTimeoutAction$` * [PM-1200] feat: implement new timeout action logic * [PM-1200] feat: add dynamic lock options to browser * [PM-1200] feat: enable/disable action select * [PM-1200] feat: add support for biometrics * [PM-1200] feat: add helper text and disable unavailable options * [PM-1200] feat: update action on unlock method changes * [PM-1200] feat: update browser to use async pipe * [PM-1200] fix: element not updating * [PM-1200] feat: hide masterPassOnRestart pin option * [PM-1200] feat: hide change master password from browser settins * [PM-1200] feat: hide change master password from app menu * [PM-1200] feat: logout if lock is not supported * [PM-1200] feat: auto logout from lock screen if unlocking is not supported * [PM-1200] feat: remove lock button from web menus * Revert "[PM-1200] fix: element not updating" This reverts commit b27f425f48570d0d5dbc9dedb9797023fef64d8b. * Revert "[PM-1200] feat: update browser to use async pipe" This reverts commit 766c15bc3dbadcf7dcef3053b148e7874f8939ce. * [PM-1200] chore: add comment regarding detectorRef * [PM-1200] feat: remove lock now button from browser settings * [PM-1200] feat: add `userId` to unlock settings related methods * [PM-1200] feat: remove non-lockable accounts from menu * [PM-1200] fix: cli not building --------- Co-authored-by: Todd Martin <tmartin@bitwarden.com> Co-authored-by: Jared Snider <116684653+JaredSnider-Bitwarden@users.noreply.github.com> * [PM-3215][PM-3289] Create MasterKey from Password If Needed (#5931) * Create MasterKey from Password - Check if the MasterKey is stored or not - Create it if it's not * Add getOrDeriveKey Helper * Use Helper In More Places * Changed settings menu to be enabled whenever the account is not locked. (#5965) * [PM-3169] Login decryption options in extension popup (#5909) * [PM-3169] refactor: lock guard and add new redirect guard * [PM-3169] feat: implement fully rewritten routing * [PM-3169] feat: close SSO window * [PM-3169] feat: store sso org identifier in state * [PM-3169] fix: tests * [PM-3169] feat: get rid of unconventional patch method * PM-3169 - SSO & 2FA Comps - Update naming of new callback to match existing pattern + add tests for callback logic execution. * PM-3169 - Update LockGuard to have a special exception for allowing the TDE Login with MP flow * PM-3169 - Per discussion w/ Jake and Justin, rename login-initiated guard to be tde decryption required guard (more named for functionality vs specific route) * PM-3169 - Add some additional context to new redirect guard scenario * PM-3169 - Per PR feedback, replace all callback types with Promise<void> as the return values are not being used. * PM-3169 - StateSvc - Per PR feedback, update setUserSsoOrganizationIdentifier signature to explicitly use null instead of partial<string> which doesn't do anything * PM-3169 - Replace onSuccessfulLogin type to compile * PM-3169 - Add clarification comment for why we are not using a query param for persisting the org identifier * PM-3169 - Per discussion with Justin, only use memory for SsoOrgId as we don't need to persist it beyond that; tested and it worked on all 3 clients for new user TDE creation * PM-3169 - Add missing ssoIdentifierRequired translation to desktop and browser * PM-3169 - After discussing with Justin again, we realized that memory doesn't work on desktop if user refreshes app or closes and re-opens it so must use disk. * PM-3169 - Per PR feedback, remove hasEverHadUserKey logic as we can just leverage existing getUserKey method to check if we have a user key or not; tested all guards in browser and web with no issues * PM-3169 - Per design discussion with Danielle, move account created toast after successful account creation vs on load of page. --------- Co-authored-by: Jared Snider <116684653+JaredSnider-Bitwarden@users.noreply.github.com> Co-authored-by: Jared Snider <jsnider@bitwarden.com> * [PM-3314] Fixed missing MP prompt on lock component (#5966) * Updated lock component to handle no master password. * Added a comment. * Add Missing Slash (#5967) * Fix AdminAuthRequest Serialization on Desktop (#5970) - toJSON isn't being called by ElectronStorageService - Force it's conversion to JSON earlier so it happens for all storage methods * Fix issue where we were incorrectly calling setRememberEmailValues in the AdminAuthRequest state - no need to do this as the email is already saved to state. By calling this method, we would actually overwrite the already saved email with null as the user's choice to remember email wasn't persisted through SSO on the login service. (#5972) * PM-3329 - Restore everHadUserKey logic from PM-3169 which I incorrectly removed in order to fix routing logic so that user can lock and land on the lock screen properly (#5979) * PM-3210 - TDE - LoginWithDevice routing fix - Mirror PR #5950 in just simply providing a back action on click which works for all app generated scenarios (#5982) * PM-3332 - TDE - SsoLoginStrategy - For existing admin auth reqs, must… (#5980) * PM-3332 - TDE - SsoLoginStrategy - For existing admin auth reqs, must manually handle 404 error case to prevent app from hanging and clear the local state if the admin auth req in the DB has been purged; i.e., it should fail silently. * Add TODO for SSO Login Strategy tests * PM-3331 - TDE - Firefox - Browser extension - fix access denied error… (#5984) * PM-3331 - TDE - Firefox - Browser extension - fix access denied error on popup load which was caused by the canAccessFeature guard failing to lookup the TDE feature flag as the server config was returning null even after a successful server call as only returned the value if the user was unauthenticated for some reason * PM-3331 - After discussion with Andre, further refactor ConfigService logic to always return the latest information from the server so that requests for feature flag data will always get the most up to date information. * PM-3345 - TDE - Desktop - Biometrics setting submenu tweak - do not s… (#5988) * PM-3345 - TDE - Desktop - Biometrics setting submenu tweak - do not show require MP or PIN entry on restart if user doesn't have at least one of those options b/c otherwise user can get into a bad state where they cannot unlock * PM-3345 - TDE - Desktop - Settings comp - if user turns off PIN and Biometric is on + require PIN on restart is enabled then must turn that setting off to prevent bad user state * PM-3345 - Final tweak to logic * [PM-2852] Final merge from Key Migration branch to TDE Feature Branch (#5977) * [PM-3121] Added new copy with exclamation mark * [PM 3219] Fix key migration locking up the Desktop app (#5990) * Only check to migrate key on VaultTimeout startup * Remove desktop specific check * PM-3332 - LoginWithDevice - Add error handling logic around admin auth request retrieval similar to sso login strategy to prevent error state and allow re-creation of an admin auth request if it has been purged from the server for whatever reason. (#5991) * PM-3355 - TDE - Browser JIT Account Creation - Browser create user logic still had logic for simply closing the extension tab but as we no longer open the login decryption options in a tab we needed to update the logic here to navigate the user directly onto the vault. (#5993) * Add distinctUntilChanged to fix multiple value changes for biometrics firing (#5999) * Add optional chaining to master key (#6007) * PM-3369 - TDE - Persist user's choice to trust device to state when user ma… (#6000) * PM-3369 - Persist user's choice to trust device to state when user makes choice + persist previous choices out of state * PM-3369 - Must set trust device in state on load if it's never been set before * PM-3369 - Refactor BaseLoginDecOptions to properly set trust device choice in state on load * Update libs/angular/src/auth/components/base-login-decryption-options.component.ts Co-authored-by: Jake Fink <jfink@bitwarden.com> --------- Co-authored-by: Jake Fink <jfink@bitwarden.com> * Updated email change component to getOrDeriveMasterKey (#6009) * [PM-3330] Force Update to Lockable Accounts on PIN/Biometric Update (#6006) * Add Listener For Events that Need To Redraw the Menu * Send redrawMenu Message When Pin/Biometrics Updated * DeviceTrustCryptoService - don't worry about checking if a device should establish trust or not if the user doesn't have trusted device encryption on (#6010) * Auth / pm 3351 / TDE Login - Browser & Desktop vault sync issue fix (#6002) * PM-3351 - TDE Login on desktop and browser via SSO comp with no 2FA should trigger sync like standard onSuccessfulLogin process used to so user lands on vault with data. * PM-3351 - 2FA Comp - Refactor onSuccessfulLogin logic to only execute in the success path just like the SSO component + adding specific onSuccessfulLoginTde flow just like SSO comp. + removed unnecessary calls to loginService.clearValues(). Added browser & desktop definitions for onSuccessfulLoginTde which is just a fullSync kick off. * TODO * PM-3351 - remove await to restore code back to previous state without hang. * PM-3351 - 2FA Comp - Don't await onSuccessfulLoginTde b/c it causes a hang * PM-3351 - remove sso comp incorrect todo * PM-3351 - SsoComp - don't await onSuccessfulLoginTde for browsers sake * PM-3351 - SsoComp - remove awaits from onSuccessfulLoginTde and onSuccessfulLogin to avoid any hangs on desktop and browser * PM-3351 - Convert onSuccessfulLoginTde to promise<void> as its return is not used + refactor all to be consistent and clearly communciate that the sync won't be awaited. * PM-3351 - Convert onSuccessfulLogin to promise<void> and update all methods accordingly to more clearly indicate that the syncs and any other logic won't be awaited. * [PM-3356] Fallback to OTP When MasterPassword Hasn't Been Used (#6017) * Fallback to OTP When MasterPassword Hasn't Been Used * Update Test and Rename Method * Revert "DeviceTrustCryptoService - don't worry about checking if a device should establish trust or not if the user doesn't have trusted device encryption on (#6010)" (#6020) This reverts commit6ec22f9570. * PM-3390 - TDE - Redraw desktop after user creation to update isLocked checks and get menu to be enabled properly (#6018) * [PM-3383] Hide Change Password menu option for user with no MP (#6022) * Hide Change Master Password menu item on desktop when a user doesn't have a master password. * Renamed variable for consistency. * Updated to base logic on account. * Fixed menubar * Resolve merge errors in crypto service spec * Fixed autofill to use new method on userVerificationService (#6029) * PM-3456 - TDE Admin Auth Req Flow - FF dead object issue - The foreground popup must retrieve the long lived background services for the new TDE services (the AuthRequestCryptoService service fixes this issue, but the DeviceTrustCryptoService should have been added to services.module as well) (#6037) * skip auto key check when using biometrics on browser (#6041) * Added comments for backward compatibility removal. (#6039) * Updated warning message. (#6059) * Tde pr feedback (#6051) * move pin migration to the crypto service * refactor config service logic * refactor lock component load logic * rename key connector methods * add date to backwards compat todo * update backwards compat todo * don't specify defaults in redirectGuard * nit * add null & undefined check for userid before using the account * fix ui tests * add todo for tech debt * add todo comment * Fix storybook per PR feedback * Desktop & Browser - lock comp - add optional chaining check for focusable input - user can just have biometric and not have a MP or a PIN so must support that. * Main.background.ts - remove duplicate instantiations of the userVerificationApiService and userVerificationService which were added in two separate PRs * Per PR feedback - (1) Browser app routing module - fix incorrect import for redirect guard (2) Created index.ts file for auth guards to simplify imports and updated imports * Per PR feedback, (1) Update jslib-services.module to provide actual instance of VaultTimeoutService (2) Update init service to use concrete VaultTimeoutService vs abstraction. Co-authored-by: Matt Gibson <git@mgibson.dev> * Per PR feedback - update services module AuthRequestCryptoService and DeviceTrustCryptoService to use shorthand format. * Per PR feedback, add devicesService to main background and update services module to ensure the popup leverages the background devicesService --------- Co-authored-by: Jared Snider <jsnider@bitwarden.com> Co-authored-by: Matt Gibson <git@mgibson.dev> * Updated message keys for CrowdIn to pick them up. (#6066) * TDE PR Feedback resolutions round 2 (#6068) * Per PR feedback - main.background.ts - move userVerificationService and userVerificationApiService to correct location * Per PR feedback - JS lib services + vault timeout service updates - (1) Correctly type callbacks based on injection tokens (2) Update vault timeout service to have proper types based on injection tokens * Per PR Feedback - update web init service to inject actual VaultTimeoutService vs abstraction similar to what we did for desktop here:55a797d4ff* Per more feedback - revert incorrect changes to VaultTimeoutService based on existing injection token types for LOGOUT_CALLBACK and LOCKED_CALLBACK.. and instead update the injection token types themselves to match how they are being used. * Per PR feedback - in browser main.background.ts, inject concrete VaultTimeoutService instead of abstraction so we don't have to cast it anymore (matching web & desktop) --------- Co-authored-by: Jared Snider <jsnider@bitwarden.com> Co-authored-by: Jared Snider <116684653+JaredSnider-Bitwarden@users.noreply.github.com> Co-authored-by: Jacob Fink <jfink@bitwarden.com> Co-authored-by: Matt Gibson <MGibson1@users.noreply.github.com> Co-authored-by: Andreas Coroiu <andreas.coroiu@gmail.com> Co-authored-by: Andreas Coroiu <andreas@andreascoroiu.com> Co-authored-by: Andreas Coroiu <acoroiu@bitwarden.com> Co-authored-by: Justin Baur <19896123+justindbaur@users.noreply.github.com> Co-authored-by: André Bispo <abispo@bitwarden.com> Co-authored-by: Thomas Rittson <trittson@bitwarden.com> Co-authored-by: Vincent Salucci <vincesalucci21@gmail.com> Co-authored-by: Robyn MacCallum <robyntmaccallum@gmail.com> Co-authored-by: Jonathan Prusik <jprusik@classynemesis.com> Co-authored-by: Matt Gibson <git@mgibson.dev>
This commit is contained in:
@@ -0,0 +1,291 @@
|
||||
import { Directive, OnDestroy, OnInit } from "@angular/core";
|
||||
import { FormBuilder, FormControl } from "@angular/forms";
|
||||
import { ActivatedRoute, Router } from "@angular/router";
|
||||
import {
|
||||
firstValueFrom,
|
||||
switchMap,
|
||||
Subject,
|
||||
catchError,
|
||||
from,
|
||||
of,
|
||||
finalize,
|
||||
takeUntil,
|
||||
defer,
|
||||
throwError,
|
||||
} from "rxjs";
|
||||
|
||||
import { ApiService } from "@bitwarden/common/abstractions/api.service";
|
||||
import { DevicesServiceAbstraction } from "@bitwarden/common/abstractions/devices/devices.service.abstraction";
|
||||
import { OrganizationUserService } from "@bitwarden/common/abstractions/organization-user/organization-user.service";
|
||||
import { OrganizationApiServiceAbstraction } from "@bitwarden/common/admin-console/abstractions/organization/organization-api.service.abstraction";
|
||||
import { DeviceTrustCryptoServiceAbstraction } from "@bitwarden/common/auth/abstractions/device-trust-crypto.service.abstraction";
|
||||
import { LoginService } from "@bitwarden/common/auth/abstractions/login.service";
|
||||
import { PasswordResetEnrollmentServiceAbstraction } from "@bitwarden/common/auth/abstractions/password-reset-enrollment.service.abstraction";
|
||||
import { TokenService } from "@bitwarden/common/auth/abstractions/token.service";
|
||||
import { KeysRequest } from "@bitwarden/common/models/request/keys.request";
|
||||
import { CryptoService } from "@bitwarden/common/platform/abstractions/crypto.service";
|
||||
import { I18nService } from "@bitwarden/common/platform/abstractions/i18n.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 { ValidationService } from "@bitwarden/common/platform/abstractions/validation.service";
|
||||
import { AccountDecryptionOptions } from "@bitwarden/common/platform/models/domain/account";
|
||||
|
||||
enum State {
|
||||
NewUser,
|
||||
ExistingUserUntrustedDevice,
|
||||
}
|
||||
|
||||
type NewUserData = {
|
||||
readonly state: State.NewUser;
|
||||
readonly organizationId: string;
|
||||
readonly userEmail: string;
|
||||
};
|
||||
|
||||
type ExistingUserUntrustedDeviceData = {
|
||||
readonly state: State.ExistingUserUntrustedDevice;
|
||||
readonly showApproveFromOtherDeviceBtn: boolean;
|
||||
readonly showReqAdminApprovalBtn: boolean;
|
||||
readonly showApproveWithMasterPasswordBtn: boolean;
|
||||
readonly userEmail: string;
|
||||
};
|
||||
|
||||
type Data = NewUserData | ExistingUserUntrustedDeviceData;
|
||||
|
||||
@Directive()
|
||||
export class BaseLoginDecryptionOptionsComponent implements OnInit, OnDestroy {
|
||||
private destroy$ = new Subject<void>();
|
||||
|
||||
protected State = State;
|
||||
|
||||
protected data?: Data;
|
||||
protected loading = true;
|
||||
|
||||
// Remember device means for the user to trust the device
|
||||
rememberDeviceForm = this.formBuilder.group({
|
||||
rememberDevice: [true],
|
||||
});
|
||||
|
||||
get rememberDevice(): FormControl<boolean> {
|
||||
return this.rememberDeviceForm?.controls.rememberDevice;
|
||||
}
|
||||
|
||||
constructor(
|
||||
protected formBuilder: FormBuilder,
|
||||
protected devicesService: DevicesServiceAbstraction,
|
||||
protected stateService: StateService,
|
||||
protected router: Router,
|
||||
protected activatedRoute: ActivatedRoute,
|
||||
protected messagingService: MessagingService,
|
||||
protected tokenService: TokenService,
|
||||
protected loginService: LoginService,
|
||||
protected organizationApiService: OrganizationApiServiceAbstraction,
|
||||
protected cryptoService: CryptoService,
|
||||
protected organizationUserService: OrganizationUserService,
|
||||
protected apiService: ApiService,
|
||||
protected i18nService: I18nService,
|
||||
protected validationService: ValidationService,
|
||||
protected deviceTrustCryptoService: DeviceTrustCryptoServiceAbstraction,
|
||||
protected platformUtilsService: PlatformUtilsService,
|
||||
protected passwordResetEnrollmentService: PasswordResetEnrollmentServiceAbstraction
|
||||
) {}
|
||||
|
||||
async ngOnInit() {
|
||||
this.loading = true;
|
||||
|
||||
this.setupRememberDeviceValueChanges();
|
||||
|
||||
// Persist user choice from state if it exists
|
||||
await this.setRememberDeviceDefaultValue();
|
||||
|
||||
try {
|
||||
const accountDecryptionOptions: AccountDecryptionOptions =
|
||||
await this.stateService.getAccountDecryptionOptions();
|
||||
|
||||
// see sso-login.strategy - to determine if a user is new or not it just checks if there is a key on the token response..
|
||||
// can we check if they have a user key or master key in crypto service? Would that be sufficient?
|
||||
if (
|
||||
!accountDecryptionOptions?.trustedDeviceOption?.hasAdminApproval &&
|
||||
!accountDecryptionOptions?.hasMasterPassword
|
||||
) {
|
||||
// We are dealing with a new account if:
|
||||
// - User does not have admin approval (i.e. has not enrolled into admin reset)
|
||||
// - AND does not have a master password
|
||||
|
||||
this.loadNewUserData();
|
||||
} else {
|
||||
this.loadUntrustedDeviceData(accountDecryptionOptions);
|
||||
}
|
||||
|
||||
// Note: this is probably not a comprehensive write up of all scenarios:
|
||||
|
||||
// If the TDE feature flag is enabled and TDE is configured for the org that the user is a member of,
|
||||
// then new and existing users can be redirected here after completing the SSO flow (and 2FA if enabled).
|
||||
|
||||
// First we must determine user type (new or existing):
|
||||
|
||||
// New User
|
||||
// - present user with option to remember the device or not (trust the device)
|
||||
// - present a continue button to proceed to the vault
|
||||
// - loadNewUserData() --> will need to load enrollment status and user email address.
|
||||
|
||||
// Existing User
|
||||
// - Determine if user is an admin with access to account recovery in admin console
|
||||
// - Determine if user has a MP or not, if not, they must be redirected to set one (see PM-1035)
|
||||
// - Determine if device is trusted or not via device crypto service (method not yet written)
|
||||
// - If not trusted, present user with login decryption options (approve from other device, approve with master password, request admin approval)
|
||||
// - loadUntrustedDeviceData()
|
||||
} catch (err) {
|
||||
this.validationService.showError(err);
|
||||
}
|
||||
}
|
||||
|
||||
private async setRememberDeviceDefaultValue() {
|
||||
const rememberDeviceFromState = await this.deviceTrustCryptoService.getShouldTrustDevice();
|
||||
|
||||
const rememberDevice = rememberDeviceFromState ?? true;
|
||||
|
||||
this.rememberDevice.setValue(rememberDevice);
|
||||
}
|
||||
|
||||
private setupRememberDeviceValueChanges() {
|
||||
this.rememberDevice.valueChanges
|
||||
.pipe(
|
||||
switchMap((value) =>
|
||||
defer(() => this.deviceTrustCryptoService.setShouldTrustDevice(value))
|
||||
),
|
||||
takeUntil(this.destroy$)
|
||||
)
|
||||
.subscribe();
|
||||
}
|
||||
|
||||
async loadNewUserData() {
|
||||
const autoEnrollStatus$ = defer(() =>
|
||||
this.stateService.getUserSsoOrganizationIdentifier()
|
||||
).pipe(
|
||||
switchMap((organizationIdentifier) => {
|
||||
if (organizationIdentifier == undefined) {
|
||||
return throwError(() => new Error(this.i18nService.t("ssoIdentifierRequired")));
|
||||
}
|
||||
|
||||
return from(this.organizationApiService.getAutoEnrollStatus(organizationIdentifier));
|
||||
}),
|
||||
catchError((err: unknown) => {
|
||||
this.validationService.showError(err);
|
||||
return of(undefined);
|
||||
})
|
||||
);
|
||||
|
||||
const email$ = from(this.stateService.getEmail()).pipe(
|
||||
catchError((err: unknown) => {
|
||||
this.validationService.showError(err);
|
||||
return of(undefined);
|
||||
}),
|
||||
takeUntil(this.destroy$)
|
||||
);
|
||||
|
||||
const autoEnrollStatus = await firstValueFrom(autoEnrollStatus$);
|
||||
const email = await firstValueFrom(email$);
|
||||
|
||||
this.data = { state: State.NewUser, organizationId: autoEnrollStatus.id, userEmail: email };
|
||||
this.loading = false;
|
||||
}
|
||||
|
||||
loadUntrustedDeviceData(accountDecryptionOptions: AccountDecryptionOptions) {
|
||||
this.loading = true;
|
||||
|
||||
const email$ = from(this.stateService.getEmail()).pipe(
|
||||
catchError((err: unknown) => {
|
||||
this.validationService.showError(err);
|
||||
return of(undefined);
|
||||
}),
|
||||
takeUntil(this.destroy$)
|
||||
);
|
||||
|
||||
email$
|
||||
.pipe(
|
||||
takeUntil(this.destroy$),
|
||||
finalize(() => {
|
||||
this.loading = false;
|
||||
})
|
||||
)
|
||||
.subscribe((email) => {
|
||||
const showApproveFromOtherDeviceBtn =
|
||||
accountDecryptionOptions?.trustedDeviceOption?.hasLoginApprovingDevice || false;
|
||||
|
||||
const showReqAdminApprovalBtn =
|
||||
!!accountDecryptionOptions?.trustedDeviceOption?.hasAdminApproval || false;
|
||||
|
||||
const showApproveWithMasterPasswordBtn =
|
||||
accountDecryptionOptions?.hasMasterPassword || false;
|
||||
|
||||
const userEmail = email;
|
||||
|
||||
this.data = {
|
||||
state: State.ExistingUserUntrustedDevice,
|
||||
showApproveFromOtherDeviceBtn,
|
||||
showReqAdminApprovalBtn,
|
||||
showApproveWithMasterPasswordBtn,
|
||||
userEmail,
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
async approveFromOtherDevice() {
|
||||
if (this.data.state !== State.ExistingUserUntrustedDevice) {
|
||||
return;
|
||||
}
|
||||
|
||||
this.loginService.setEmail(this.data.userEmail);
|
||||
this.router.navigate(["/login-with-device"]);
|
||||
}
|
||||
|
||||
async requestAdminApproval() {
|
||||
this.loginService.setEmail(this.data.userEmail);
|
||||
this.router.navigate(["/admin-approval-requested"]);
|
||||
}
|
||||
|
||||
async approveWithMasterPassword() {
|
||||
this.router.navigate(["/lock"], { queryParams: { from: "login-initiated" } });
|
||||
}
|
||||
|
||||
async createUser() {
|
||||
if (this.data.state !== State.NewUser) {
|
||||
return;
|
||||
}
|
||||
|
||||
// this.loading to support clients without async-actions-support
|
||||
this.loading = true;
|
||||
try {
|
||||
const { publicKey, privateKey } = await this.cryptoService.initAccount();
|
||||
const keysRequest = new KeysRequest(publicKey, privateKey.encryptedString);
|
||||
await this.apiService.postAccountKeys(keysRequest);
|
||||
|
||||
this.platformUtilsService.showToast(
|
||||
"success",
|
||||
null,
|
||||
this.i18nService.t("accountSuccessfullyCreated")
|
||||
);
|
||||
|
||||
await this.passwordResetEnrollmentService.enroll(this.data.organizationId);
|
||||
|
||||
if (this.rememberDeviceForm.value.rememberDevice) {
|
||||
await this.deviceTrustCryptoService.trustDevice();
|
||||
}
|
||||
} catch (error) {
|
||||
this.validationService.showError(error);
|
||||
} finally {
|
||||
this.loading = false;
|
||||
}
|
||||
}
|
||||
|
||||
logOut() {
|
||||
this.loading = true; // to avoid an awkward delay in browser extension
|
||||
this.messagingService.send("logout");
|
||||
}
|
||||
|
||||
ngOnDestroy(): void {
|
||||
this.destroy$.next();
|
||||
this.destroy$.complete();
|
||||
}
|
||||
}
|
||||
@@ -12,7 +12,7 @@ import { PlatformUtilsService } from "@bitwarden/common/platform/abstractions/pl
|
||||
import { StateService } from "@bitwarden/common/platform/abstractions/state.service";
|
||||
import { Utils } from "@bitwarden/common/platform/misc/utils";
|
||||
import { EncString } from "@bitwarden/common/platform/models/domain/enc-string";
|
||||
import { SymmetricCryptoKey } from "@bitwarden/common/platform/models/domain/symmetric-crypto-key";
|
||||
import { MasterKey, UserKey } from "@bitwarden/common/platform/models/domain/symmetric-crypto-key";
|
||||
import { PasswordGenerationServiceAbstraction } from "@bitwarden/common/tools/generator/password";
|
||||
import { DialogService } from "@bitwarden/components";
|
||||
|
||||
@@ -79,23 +79,28 @@ export class ChangePasswordComponent implements OnInit, OnDestroy {
|
||||
if (this.kdfConfig == null) {
|
||||
this.kdfConfig = await this.stateService.getKdfConfig();
|
||||
}
|
||||
const key = await this.cryptoService.makeKey(
|
||||
|
||||
// Create new master key
|
||||
const newMasterKey = await this.cryptoService.makeMasterKey(
|
||||
this.masterPassword,
|
||||
email.trim().toLowerCase(),
|
||||
this.kdf,
|
||||
this.kdfConfig
|
||||
);
|
||||
const masterPasswordHash = await this.cryptoService.hashPassword(this.masterPassword, key);
|
||||
const newMasterKeyHash = await this.cryptoService.hashMasterKey(
|
||||
this.masterPassword,
|
||||
newMasterKey
|
||||
);
|
||||
|
||||
let encKey: [SymmetricCryptoKey, EncString] = null;
|
||||
const existingEncKey = await this.cryptoService.getEncKey();
|
||||
if (existingEncKey == null) {
|
||||
encKey = await this.cryptoService.makeEncKey(key);
|
||||
let newProtectedUserKey: [UserKey, EncString] = null;
|
||||
const userKey = await this.cryptoService.getUserKey();
|
||||
if (userKey == null) {
|
||||
newProtectedUserKey = await this.cryptoService.makeUserKey(newMasterKey);
|
||||
} else {
|
||||
encKey = await this.cryptoService.remakeEncKey(key);
|
||||
newProtectedUserKey = await this.cryptoService.encryptUserKeyWithMasterKey(newMasterKey);
|
||||
}
|
||||
|
||||
await this.performSubmitActions(masterPasswordHash, key, encKey);
|
||||
await this.performSubmitActions(newMasterKeyHash, newMasterKey, newProtectedUserKey);
|
||||
}
|
||||
|
||||
async setupSubmitActions(): Promise<boolean> {
|
||||
@@ -105,9 +110,9 @@ export class ChangePasswordComponent implements OnInit, OnDestroy {
|
||||
}
|
||||
|
||||
async performSubmitActions(
|
||||
masterPasswordHash: string,
|
||||
key: SymmetricCryptoKey,
|
||||
encKey: [SymmetricCryptoKey, EncString]
|
||||
newMasterKeyHash: string,
|
||||
newMasterKey: MasterKey,
|
||||
newUserKey: [UserKey, EncString]
|
||||
) {
|
||||
// Override in sub-class
|
||||
}
|
||||
|
||||
@@ -4,16 +4,18 @@ import { firstValueFrom, Subject } from "rxjs";
|
||||
import { concatMap, take, takeUntil } from "rxjs/operators";
|
||||
|
||||
import { ApiService } from "@bitwarden/common/abstractions/api.service";
|
||||
import { VaultTimeoutService } from "@bitwarden/common/abstractions/vaultTimeout/vaultTimeout.service";
|
||||
import { VaultTimeoutSettingsService } from "@bitwarden/common/abstractions/vaultTimeout/vaultTimeoutSettings.service";
|
||||
import { VaultTimeoutSettingsService } from "@bitwarden/common/abstractions/vault-timeout/vault-timeout-settings.service";
|
||||
import { VaultTimeoutService } from "@bitwarden/common/abstractions/vault-timeout/vault-timeout.service";
|
||||
import { PolicyApiServiceAbstraction } from "@bitwarden/common/admin-console/abstractions/policy/policy-api.service.abstraction";
|
||||
import { InternalPolicyService } from "@bitwarden/common/admin-console/abstractions/policy/policy.service.abstraction";
|
||||
import { MasterPasswordPolicyOptions } from "@bitwarden/common/admin-console/models/domain/master-password-policy-options";
|
||||
import { KeyConnectorService } from "@bitwarden/common/auth/abstractions/key-connector.service";
|
||||
import { DeviceTrustCryptoServiceAbstraction } from "@bitwarden/common/auth/abstractions/device-trust-crypto.service.abstraction";
|
||||
import { UserVerificationService } from "@bitwarden/common/auth/abstractions/user-verification/user-verification.service.abstraction";
|
||||
import { ForceResetPasswordReason } from "@bitwarden/common/auth/models/domain/force-reset-password-reason";
|
||||
import { SecretVerificationRequest } from "@bitwarden/common/auth/models/request/secret-verification.request";
|
||||
import { MasterPasswordPolicyResponse } from "@bitwarden/common/auth/models/response/master-password-policy.response";
|
||||
import { HashPurpose, KeySuffixOptions } from "@bitwarden/common/enums";
|
||||
import { VaultTimeoutAction } from "@bitwarden/common/enums/vault-timeout-action.enum";
|
||||
import { CryptoService } from "@bitwarden/common/platform/abstractions/crypto.service";
|
||||
import { EnvironmentService } from "@bitwarden/common/platform/abstractions/environment.service";
|
||||
import { I18nService } from "@bitwarden/common/platform/abstractions/i18n.service";
|
||||
@@ -23,7 +25,8 @@ import { PlatformUtilsService } from "@bitwarden/common/platform/abstractions/pl
|
||||
import { StateService } from "@bitwarden/common/platform/abstractions/state.service";
|
||||
import { Utils } from "@bitwarden/common/platform/misc/utils";
|
||||
import { EncString } from "@bitwarden/common/platform/models/domain/enc-string";
|
||||
import { SymmetricCryptoKey } from "@bitwarden/common/platform/models/domain/symmetric-crypto-key";
|
||||
import { UserKey } from "@bitwarden/common/platform/models/domain/symmetric-crypto-key";
|
||||
import { PinLockType } from "@bitwarden/common/services/vault-timeout/vault-timeout-settings.service";
|
||||
import { PasswordStrengthServiceAbstraction } from "@bitwarden/common/tools/password-strength";
|
||||
import { DialogService } from "@bitwarden/components";
|
||||
|
||||
@@ -33,20 +36,20 @@ export class LockComponent implements OnInit, OnDestroy {
|
||||
pin = "";
|
||||
showPassword = false;
|
||||
email: string;
|
||||
pinLock = false;
|
||||
pinEnabled = false;
|
||||
masterPasswordEnabled = false;
|
||||
webVaultHostname = "";
|
||||
formPromise: Promise<MasterPasswordPolicyResponse>;
|
||||
supportsBiometric: boolean;
|
||||
biometricLock: boolean;
|
||||
biometricText: string;
|
||||
hideInput: boolean;
|
||||
|
||||
protected successRoute = "vault";
|
||||
protected forcePasswordResetRoute = "update-temp-password";
|
||||
protected onSuccessfulSubmit: () => Promise<void>;
|
||||
|
||||
private invalidPinAttempts = 0;
|
||||
private pinSet: [boolean, boolean];
|
||||
private pinStatus: PinLockType;
|
||||
|
||||
private enforcedMasterPasswordOptions: MasterPasswordPolicyOptions = undefined;
|
||||
|
||||
@@ -64,12 +67,13 @@ export class LockComponent implements OnInit, OnDestroy {
|
||||
protected stateService: StateService,
|
||||
protected apiService: ApiService,
|
||||
protected logService: LogService,
|
||||
private keyConnectorService: KeyConnectorService,
|
||||
protected ngZone: NgZone,
|
||||
protected policyApiService: PolicyApiServiceAbstraction,
|
||||
protected policyService: InternalPolicyService,
|
||||
protected passwordStrengthService: PasswordStrengthServiceAbstraction,
|
||||
protected dialogService: DialogService
|
||||
protected dialogService: DialogService,
|
||||
protected deviceTrustCryptoService: DeviceTrustCryptoServiceAbstraction,
|
||||
protected userVerificationService: UserVerificationService
|
||||
) {}
|
||||
|
||||
async ngOnInit() {
|
||||
@@ -89,7 +93,7 @@ export class LockComponent implements OnInit, OnDestroy {
|
||||
}
|
||||
|
||||
async submit() {
|
||||
if (this.pinLock) {
|
||||
if (this.pinEnabled) {
|
||||
return await this.handlePinRequiredUnlock();
|
||||
}
|
||||
|
||||
@@ -114,18 +118,18 @@ export class LockComponent implements OnInit, OnDestroy {
|
||||
return;
|
||||
}
|
||||
|
||||
const success = (await this.cryptoService.getKey(KeySuffixOptions.Biometric)) != null;
|
||||
const userKey = await this.cryptoService.getUserKeyFromStorage(KeySuffixOptions.Biometric);
|
||||
|
||||
if (success) {
|
||||
await this.doContinue(false);
|
||||
if (userKey) {
|
||||
await this.setUserKeyAndContinue(userKey, false);
|
||||
}
|
||||
|
||||
return success;
|
||||
return !!userKey;
|
||||
}
|
||||
|
||||
togglePassword() {
|
||||
this.showPassword = !this.showPassword;
|
||||
const input = document.getElementById(this.pinLock ? "pin" : "masterPassword");
|
||||
const input = document.getElementById(this.pinEnabled ? "pin" : "masterPassword");
|
||||
if (this.ngZone.isStable) {
|
||||
input.focus();
|
||||
} else {
|
||||
@@ -151,25 +155,58 @@ export class LockComponent implements OnInit, OnDestroy {
|
||||
try {
|
||||
const kdf = await this.stateService.getKdfType();
|
||||
const kdfConfig = await this.stateService.getKdfConfig();
|
||||
if (this.pinSet[0]) {
|
||||
const key = await this.cryptoService.makeKeyFromPin(
|
||||
let userKeyPin: EncString;
|
||||
let oldPinKey: EncString;
|
||||
switch (this.pinStatus) {
|
||||
case "PERSISTANT": {
|
||||
userKeyPin = await this.stateService.getPinKeyEncryptedUserKey();
|
||||
const oldEncryptedPinKey = await this.stateService.getEncryptedPinProtected();
|
||||
oldPinKey = oldEncryptedPinKey ? new EncString(oldEncryptedPinKey) : undefined;
|
||||
break;
|
||||
}
|
||||
case "TRANSIENT": {
|
||||
userKeyPin = await this.stateService.getPinKeyEncryptedUserKeyEphemeral();
|
||||
oldPinKey = await this.stateService.getDecryptedPinProtected();
|
||||
break;
|
||||
}
|
||||
case "DISABLED": {
|
||||
throw new Error("Pin is disabled");
|
||||
}
|
||||
default: {
|
||||
const _exhaustiveCheck: never = this.pinStatus;
|
||||
return _exhaustiveCheck;
|
||||
}
|
||||
}
|
||||
|
||||
let userKey: UserKey;
|
||||
if (oldPinKey) {
|
||||
userKey = await this.cryptoService.decryptAndMigrateOldPinKey(
|
||||
this.pinStatus === "TRANSIENT",
|
||||
this.pin,
|
||||
this.email,
|
||||
kdf,
|
||||
kdfConfig,
|
||||
await this.stateService.getDecryptedPinProtected()
|
||||
oldPinKey
|
||||
);
|
||||
const encKey = await this.cryptoService.getEncKey(key);
|
||||
const protectedPin = await this.stateService.getProtectedPin();
|
||||
const decPin = await this.cryptoService.decryptToUtf8(new EncString(protectedPin), encKey);
|
||||
failed = decPin !== this.pin;
|
||||
if (!failed) {
|
||||
await this.setKeyAndContinue(key);
|
||||
}
|
||||
} else {
|
||||
const key = await this.cryptoService.makeKeyFromPin(this.pin, this.email, kdf, kdfConfig);
|
||||
failed = false;
|
||||
await this.setKeyAndContinue(key);
|
||||
userKey = await this.cryptoService.decryptUserKeyWithPin(
|
||||
this.pin,
|
||||
this.email,
|
||||
kdf,
|
||||
kdfConfig,
|
||||
userKeyPin
|
||||
);
|
||||
}
|
||||
|
||||
const protectedPin = await this.stateService.getProtectedPin();
|
||||
const decryptedPin = await this.cryptoService.decryptToUtf8(
|
||||
new EncString(protectedPin),
|
||||
userKey
|
||||
);
|
||||
failed = decryptedPin !== this.pin;
|
||||
|
||||
if (!failed) {
|
||||
await this.setUserKeyAndContinue(userKey);
|
||||
}
|
||||
} catch {
|
||||
failed = true;
|
||||
@@ -205,18 +242,28 @@ export class LockComponent implements OnInit, OnDestroy {
|
||||
const kdf = await this.stateService.getKdfType();
|
||||
const kdfConfig = await this.stateService.getKdfConfig();
|
||||
|
||||
const key = await this.cryptoService.makeKey(this.masterPassword, this.email, kdf, kdfConfig);
|
||||
const storedKeyHash = await this.cryptoService.getKeyHash();
|
||||
const masterKey = await this.cryptoService.makeMasterKey(
|
||||
this.masterPassword,
|
||||
this.email,
|
||||
kdf,
|
||||
kdfConfig
|
||||
);
|
||||
const storedPasswordHash = await this.cryptoService.getMasterKeyHash();
|
||||
|
||||
let passwordValid = false;
|
||||
|
||||
if (storedKeyHash != null) {
|
||||
passwordValid = await this.cryptoService.compareAndUpdateKeyHash(this.masterPassword, key);
|
||||
} else {
|
||||
const request = new SecretVerificationRequest();
|
||||
const serverKeyHash = await this.cryptoService.hashPassword(
|
||||
if (storedPasswordHash != null) {
|
||||
// Offline unlock possible
|
||||
passwordValid = await this.cryptoService.compareAndUpdateKeyHash(
|
||||
this.masterPassword,
|
||||
key,
|
||||
masterKey
|
||||
);
|
||||
} else {
|
||||
// Online only
|
||||
const request = new SecretVerificationRequest();
|
||||
const serverKeyHash = await this.cryptoService.hashMasterKey(
|
||||
this.masterPassword,
|
||||
masterKey,
|
||||
HashPurpose.ServerAuthorization
|
||||
);
|
||||
request.masterPasswordHash = serverKeyHash;
|
||||
@@ -225,14 +272,16 @@ export class LockComponent implements OnInit, OnDestroy {
|
||||
const response = await this.formPromise;
|
||||
this.enforcedMasterPasswordOptions = MasterPasswordPolicyOptions.fromResponse(response);
|
||||
passwordValid = true;
|
||||
const localKeyHash = await this.cryptoService.hashPassword(
|
||||
const localKeyHash = await this.cryptoService.hashMasterKey(
|
||||
this.masterPassword,
|
||||
key,
|
||||
masterKey,
|
||||
HashPurpose.LocalAuthorization
|
||||
);
|
||||
await this.cryptoService.setKeyHash(localKeyHash);
|
||||
await this.cryptoService.setMasterKeyHash(localKeyHash);
|
||||
} catch (e) {
|
||||
this.logService.error(e);
|
||||
} finally {
|
||||
this.formPromise = null;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -245,19 +294,18 @@ export class LockComponent implements OnInit, OnDestroy {
|
||||
return;
|
||||
}
|
||||
|
||||
if (this.pinSet[0]) {
|
||||
const protectedPin = await this.stateService.getProtectedPin();
|
||||
const encKey = await this.cryptoService.getEncKey(key);
|
||||
const decPin = await this.cryptoService.decryptToUtf8(new EncString(protectedPin), encKey);
|
||||
const pinKey = await this.cryptoService.makePinKey(decPin, this.email, kdf, kdfConfig);
|
||||
await this.stateService.setDecryptedPinProtected(
|
||||
await this.cryptoService.encrypt(key.key, pinKey)
|
||||
);
|
||||
}
|
||||
await this.setKeyAndContinue(key, true);
|
||||
const userKey = await this.cryptoService.decryptUserKeyWithMasterKey(masterKey);
|
||||
await this.cryptoService.setMasterKey(masterKey);
|
||||
await this.setUserKeyAndContinue(userKey, true);
|
||||
}
|
||||
private async setKeyAndContinue(key: SymmetricCryptoKey, evaluatePasswordAfterUnlock = false) {
|
||||
await this.cryptoService.setKey(key);
|
||||
|
||||
private async setUserKeyAndContinue(key: UserKey, evaluatePasswordAfterUnlock = false) {
|
||||
await this.cryptoService.setUserKey(key);
|
||||
|
||||
// Now that we have a decrypted user key in memory, we can check if we
|
||||
// need to establish trust on the current device
|
||||
await this.deviceTrustCryptoService.trustDeviceIfRequired();
|
||||
|
||||
await this.doContinue(evaluatePasswordAfterUnlock);
|
||||
}
|
||||
|
||||
@@ -295,24 +343,39 @@ export class LockComponent implements OnInit, OnDestroy {
|
||||
}
|
||||
|
||||
private async load() {
|
||||
this.pinSet = await this.vaultTimeoutSettingsService.isPinLockSet();
|
||||
this.pinLock =
|
||||
(this.pinSet[0] && (await this.stateService.getDecryptedPinProtected()) != null) ||
|
||||
this.pinSet[1];
|
||||
// TODO: Investigate PM-3515
|
||||
|
||||
// The loading of the lock component works as follows:
|
||||
// 1. First, is locking a valid timeout action? If not, we will log the user out.
|
||||
// 2. If locking IS a valid timeout action, we proceed to show the user the lock screen.
|
||||
// The user will be able to unlock as follows:
|
||||
// - If they have a PIN set, they will be presented with the PIN input
|
||||
// - If they have a master password and no PIN, they will be presented with the master password input
|
||||
// - If they have biometrics enabled, they will be presented with the biometric prompt
|
||||
|
||||
const availableVaultTimeoutActions = await firstValueFrom(
|
||||
this.vaultTimeoutSettingsService.availableVaultTimeoutActions$()
|
||||
);
|
||||
const supportsLock = availableVaultTimeoutActions.includes(VaultTimeoutAction.Lock);
|
||||
if (!supportsLock) {
|
||||
return await this.vaultTimeoutService.logOut();
|
||||
}
|
||||
|
||||
this.pinStatus = await this.vaultTimeoutSettingsService.isPinLockSet();
|
||||
|
||||
let ephemeralPinSet = await this.stateService.getPinKeyEncryptedUserKeyEphemeral();
|
||||
ephemeralPinSet ||= await this.stateService.getDecryptedPinProtected();
|
||||
this.pinEnabled =
|
||||
(this.pinStatus === "TRANSIENT" && !!ephemeralPinSet) || this.pinStatus === "PERSISTANT";
|
||||
this.masterPasswordEnabled = await this.userVerificationService.hasMasterPassword();
|
||||
|
||||
this.supportsBiometric = await this.platformUtilsService.supportsBiometric();
|
||||
this.biometricLock =
|
||||
(await this.vaultTimeoutSettingsService.isBiometricLockSet()) &&
|
||||
((await this.cryptoService.hasKeyStored(KeySuffixOptions.Biometric)) ||
|
||||
((await this.cryptoService.hasUserKeyStored(KeySuffixOptions.Biometric)) ||
|
||||
!this.platformUtilsService.supportsSecureStorage());
|
||||
this.biometricText = await this.stateService.getBiometricText();
|
||||
this.email = await this.stateService.getEmail();
|
||||
const usesKeyConnector = await this.keyConnectorService.getUsesKeyConnector();
|
||||
this.hideInput = usesKeyConnector && !this.pinLock;
|
||||
|
||||
// Users with key connector and without biometric or pin has no MP to unlock using
|
||||
if (usesKeyConnector && !(this.biometricLock || this.pinLock)) {
|
||||
await this.vaultTimeoutService.logOut();
|
||||
}
|
||||
|
||||
const webVaultUrl = this.environmentService.getWebVaultUrl();
|
||||
const vaultUrl =
|
||||
|
||||
@@ -1,16 +1,22 @@
|
||||
import { Directive, OnDestroy, OnInit } from "@angular/core";
|
||||
import { Router } from "@angular/router";
|
||||
import { IsActiveMatchOptions, Router } from "@angular/router";
|
||||
import { Subject, takeUntil } from "rxjs";
|
||||
|
||||
import { AnonymousHubService } from "@bitwarden/common/abstractions/anonymousHub.service";
|
||||
import { ApiService } from "@bitwarden/common/abstractions/api.service";
|
||||
import { AuthRequestCryptoServiceAbstraction } from "@bitwarden/common/auth/abstractions/auth-request-crypto.service.abstraction";
|
||||
import { AuthService } from "@bitwarden/common/auth/abstractions/auth.service";
|
||||
import { DeviceTrustCryptoServiceAbstraction } from "@bitwarden/common/auth/abstractions/device-trust-crypto.service.abstraction";
|
||||
import { LoginService } from "@bitwarden/common/auth/abstractions/login.service";
|
||||
import { AuthRequestType } from "@bitwarden/common/auth/enums/auth-request-type";
|
||||
import { AuthenticationStatus } from "@bitwarden/common/auth/enums/authentication-status";
|
||||
import { AdminAuthRequestStorable } from "@bitwarden/common/auth/models/domain/admin-auth-req-storable";
|
||||
import { AuthResult } from "@bitwarden/common/auth/models/domain/auth-result";
|
||||
import { ForceResetPasswordReason } from "@bitwarden/common/auth/models/domain/force-reset-password-reason";
|
||||
import { PasswordlessLogInCredentials } from "@bitwarden/common/auth/models/domain/log-in-credentials";
|
||||
import { PasswordlessCreateAuthRequest } from "@bitwarden/common/auth/models/request/passwordless-create-auth.request";
|
||||
import { AuthRequestResponse } from "@bitwarden/common/auth/models/response/auth-request.response";
|
||||
import { HttpStatusCode } from "@bitwarden/common/enums/http-status-code.enum";
|
||||
import { ErrorResponse } from "@bitwarden/common/models/response/error.response";
|
||||
import { AppIdService } from "@bitwarden/common/platform/abstractions/app-id.service";
|
||||
import { CryptoFunctionService } from "@bitwarden/common/platform/abstractions/crypto-function.service";
|
||||
@@ -22,17 +28,24 @@ import { PlatformUtilsService } from "@bitwarden/common/platform/abstractions/pl
|
||||
import { StateService } from "@bitwarden/common/platform/abstractions/state.service";
|
||||
import { ValidationService } from "@bitwarden/common/platform/abstractions/validation.service";
|
||||
import { Utils } from "@bitwarden/common/platform/misc/utils";
|
||||
import { SymmetricCryptoKey } from "@bitwarden/common/platform/models/domain/symmetric-crypto-key";
|
||||
import { PasswordGenerationServiceAbstraction } from "@bitwarden/common/tools/generator/password";
|
||||
|
||||
import { CaptchaProtectedComponent } from "./captcha-protected.component";
|
||||
|
||||
// TODO: consider renaming this component something like LoginViaAuthReqComponent
|
||||
|
||||
enum State {
|
||||
StandardAuthRequest,
|
||||
AdminAuthRequest,
|
||||
}
|
||||
|
||||
@Directive()
|
||||
export class LoginWithDeviceComponent
|
||||
extends CaptchaProtectedComponent
|
||||
implements OnInit, OnDestroy
|
||||
{
|
||||
private destroy$ = new Subject<void>();
|
||||
userAuthNStatus: AuthenticationStatus;
|
||||
email: string;
|
||||
showResendNotification = false;
|
||||
passwordlessRequest: PasswordlessCreateAuthRequest;
|
||||
@@ -42,12 +55,19 @@ export class LoginWithDeviceComponent
|
||||
onSuccessfulLoginNavigate: () => Promise<any>;
|
||||
onSuccessfulLoginForceResetNavigate: () => Promise<any>;
|
||||
|
||||
protected adminApprovalRoute = "admin-approval-requested";
|
||||
|
||||
protected StateEnum = State;
|
||||
protected state = State.StandardAuthRequest;
|
||||
|
||||
protected twoFactorRoute = "2fa";
|
||||
protected successRoute = "vault";
|
||||
protected forcePasswordResetRoute = "update-temp-password";
|
||||
private resendTimeout = 12000;
|
||||
private authRequestKeyPair: [publicKey: Uint8Array, privateKey: Uint8Array];
|
||||
|
||||
private authRequestKeyPair: { publicKey: Uint8Array; privateKey: Uint8Array };
|
||||
|
||||
// TODO: in future, go to child components and remove child constructors and let deps fall through to the super class
|
||||
constructor(
|
||||
protected router: Router,
|
||||
private cryptoService: CryptoService,
|
||||
@@ -63,10 +83,14 @@ export class LoginWithDeviceComponent
|
||||
private anonymousHubService: AnonymousHubService,
|
||||
private validationService: ValidationService,
|
||||
private stateService: StateService,
|
||||
private loginService: LoginService
|
||||
private loginService: LoginService,
|
||||
private deviceTrustCryptoService: DeviceTrustCryptoServiceAbstraction,
|
||||
private authReqCryptoService: AuthRequestCryptoServiceAbstraction
|
||||
) {
|
||||
super(environmentService, i18nService, platformUtilsService);
|
||||
|
||||
// TODO: I don't know why this is necessary.
|
||||
// Why would the existence of the email depend on the navigation?
|
||||
const navigation = this.router.getCurrentNavigation();
|
||||
if (navigation) {
|
||||
this.email = this.loginService.getEmail();
|
||||
@@ -77,25 +101,167 @@ export class LoginWithDeviceComponent
|
||||
.getPushNotificationObs$()
|
||||
.pipe(takeUntil(this.destroy$))
|
||||
.subscribe((id) => {
|
||||
this.confirmResponse(id);
|
||||
// Only fires on approval currently
|
||||
this.verifyAndHandleApprovedAuthReq(id);
|
||||
});
|
||||
}
|
||||
|
||||
async ngOnInit() {
|
||||
if (!this.email) {
|
||||
this.router.navigate(["/login"]);
|
||||
return;
|
||||
this.userAuthNStatus = await this.authService.getAuthStatus();
|
||||
|
||||
const matchOptions: IsActiveMatchOptions = {
|
||||
paths: "exact",
|
||||
queryParams: "ignored",
|
||||
fragment: "ignored",
|
||||
matrixParams: "ignored",
|
||||
};
|
||||
|
||||
if (this.router.isActive(this.adminApprovalRoute, matchOptions)) {
|
||||
this.state = State.AdminAuthRequest;
|
||||
}
|
||||
|
||||
if (this.state === State.AdminAuthRequest) {
|
||||
// Pull email from state for admin auth reqs b/c it is available
|
||||
// This also prevents it from being lost on refresh as the
|
||||
// login service email does not persist.
|
||||
this.email = await this.stateService.getEmail();
|
||||
|
||||
if (!this.email) {
|
||||
this.platformUtilsService.showToast("error", null, this.i18nService.t("userEmailMissing"));
|
||||
this.router.navigate(["/login-initiated"]);
|
||||
return;
|
||||
}
|
||||
|
||||
// We only allow a single admin approval request to be active at a time
|
||||
// so must check state to see if we have an existing one or not
|
||||
const adminAuthReqStorable = await this.stateService.getAdminAuthRequest();
|
||||
|
||||
if (adminAuthReqStorable) {
|
||||
await this.handleExistingAdminAuthRequest(adminAuthReqStorable);
|
||||
} else {
|
||||
// No existing admin auth request; so we need to create one
|
||||
await this.startPasswordlessLogin();
|
||||
}
|
||||
} else {
|
||||
// Standard auth request
|
||||
// TODO: evaluate if we can remove the setting of this.email in the constructor
|
||||
this.email = this.loginService.getEmail();
|
||||
|
||||
if (!this.email) {
|
||||
this.platformUtilsService.showToast("error", null, this.i18nService.t("userEmailMissing"));
|
||||
this.router.navigate(["/login"]);
|
||||
return;
|
||||
}
|
||||
|
||||
await this.startPasswordlessLogin();
|
||||
}
|
||||
}
|
||||
|
||||
ngOnDestroy(): void {
|
||||
this.destroy$.next();
|
||||
this.destroy$.complete();
|
||||
this.anonymousHubService.stopHubConnection();
|
||||
}
|
||||
|
||||
private async handleExistingAdminAuthRequest(adminAuthReqStorable: AdminAuthRequestStorable) {
|
||||
// Note: on login, the SSOLoginStrategy will also call to see an existing admin auth req
|
||||
// has been approved and handle it if so.
|
||||
|
||||
// Regardless, we always retrieve the auth request from the server verify and handle status changes here as well
|
||||
let adminAuthReqResponse: AuthRequestResponse;
|
||||
try {
|
||||
adminAuthReqResponse = await this.apiService.getAuthRequest(adminAuthReqStorable.id);
|
||||
} catch (error) {
|
||||
if (error instanceof ErrorResponse && error.statusCode === HttpStatusCode.NotFound) {
|
||||
return await this.handleExistingAdminAuthReqDeletedOrDenied();
|
||||
}
|
||||
}
|
||||
|
||||
// Request doesn't exist anymore
|
||||
if (!adminAuthReqResponse) {
|
||||
return await this.handleExistingAdminAuthReqDeletedOrDenied();
|
||||
}
|
||||
|
||||
// Re-derive the user's fingerprint phrase
|
||||
// It is important to not use the server's public key here as it could have been compromised via MITM
|
||||
const derivedPublicKeyArrayBuffer = await this.cryptoFunctionService.rsaExtractPublicKey(
|
||||
adminAuthReqStorable.privateKey
|
||||
);
|
||||
this.fingerprintPhrase = (
|
||||
await this.cryptoService.getFingerprint(this.email, derivedPublicKeyArrayBuffer)
|
||||
).join("-");
|
||||
|
||||
// Request denied
|
||||
if (adminAuthReqResponse.isAnswered && !adminAuthReqResponse.requestApproved) {
|
||||
return await this.handleExistingAdminAuthReqDeletedOrDenied();
|
||||
}
|
||||
|
||||
// Request approved
|
||||
if (adminAuthReqResponse.requestApproved) {
|
||||
return await this.handleApprovedAdminAuthRequest(
|
||||
adminAuthReqResponse,
|
||||
adminAuthReqStorable.privateKey
|
||||
);
|
||||
}
|
||||
|
||||
// Request still pending response from admin
|
||||
// So, create hub connection so that any approvals will be received via push notification
|
||||
this.anonymousHubService.createHubConnection(adminAuthReqStorable.id);
|
||||
}
|
||||
|
||||
private async handleExistingAdminAuthReqDeletedOrDenied() {
|
||||
// clear the admin auth request from state
|
||||
await this.stateService.setAdminAuthRequest(null);
|
||||
|
||||
// start new auth request
|
||||
this.startPasswordlessLogin();
|
||||
}
|
||||
|
||||
private async buildAuthRequest(authRequestType: AuthRequestType) {
|
||||
const authRequestKeyPairArray = await this.cryptoFunctionService.rsaGenerateKeyPair(2048);
|
||||
|
||||
this.authRequestKeyPair = {
|
||||
publicKey: authRequestKeyPairArray[0],
|
||||
privateKey: authRequestKeyPairArray[1],
|
||||
};
|
||||
|
||||
const deviceIdentifier = await this.appIdService.getAppId();
|
||||
const publicKey = Utils.fromBufferToB64(this.authRequestKeyPair.publicKey);
|
||||
const accessCode = await this.passwordGenerationService.generatePassword({ length: 25 });
|
||||
|
||||
this.fingerprintPhrase = (
|
||||
await this.cryptoService.getFingerprint(this.email, this.authRequestKeyPair.publicKey)
|
||||
).join("-");
|
||||
|
||||
this.passwordlessRequest = new PasswordlessCreateAuthRequest(
|
||||
this.email,
|
||||
deviceIdentifier,
|
||||
publicKey,
|
||||
authRequestType,
|
||||
accessCode
|
||||
);
|
||||
}
|
||||
|
||||
async startPasswordlessLogin() {
|
||||
this.showResendNotification = false;
|
||||
|
||||
try {
|
||||
await this.buildAuthRequest();
|
||||
const reqResponse = await this.apiService.postAuthRequest(this.passwordlessRequest);
|
||||
let reqResponse: AuthRequestResponse;
|
||||
|
||||
if (this.state === State.AdminAuthRequest) {
|
||||
await this.buildAuthRequest(AuthRequestType.AdminApproval);
|
||||
reqResponse = await this.apiService.postAdminAuthRequest(this.passwordlessRequest);
|
||||
|
||||
const adminAuthReqStorable = new AdminAuthRequestStorable({
|
||||
id: reqResponse.id,
|
||||
privateKey: this.authRequestKeyPair.privateKey,
|
||||
});
|
||||
|
||||
await this.stateService.setAdminAuthRequest(adminAuthReqStorable);
|
||||
} else {
|
||||
await this.buildAuthRequest(AuthRequestType.AuthenticateAndUnlock);
|
||||
reqResponse = await this.apiService.postAuthRequest(this.passwordlessRequest);
|
||||
}
|
||||
|
||||
if (reqResponse.id) {
|
||||
this.anonymousHubService.createHubConnection(reqResponse.id);
|
||||
@@ -109,52 +275,69 @@ export class LoginWithDeviceComponent
|
||||
}, this.resendTimeout);
|
||||
}
|
||||
|
||||
ngOnDestroy(): void {
|
||||
this.destroy$.next();
|
||||
this.destroy$.complete();
|
||||
this.anonymousHubService.stopHubConnection();
|
||||
}
|
||||
|
||||
private async confirmResponse(requestId: string) {
|
||||
private async verifyAndHandleApprovedAuthReq(requestId: string) {
|
||||
try {
|
||||
const response = await this.apiService.getAuthResponse(
|
||||
requestId,
|
||||
this.passwordlessRequest.accessCode
|
||||
);
|
||||
// Retrieve the auth request from server and verify it's approved
|
||||
let authReqResponse: AuthRequestResponse;
|
||||
|
||||
if (!response.requestApproved) {
|
||||
switch (this.state) {
|
||||
case State.StandardAuthRequest:
|
||||
// Unauthed - access code required for user verification
|
||||
authReqResponse = await this.apiService.getAuthResponse(
|
||||
requestId,
|
||||
this.passwordlessRequest.accessCode
|
||||
);
|
||||
break;
|
||||
|
||||
case State.AdminAuthRequest:
|
||||
// Authed - no access code required
|
||||
authReqResponse = await this.apiService.getAuthRequest(requestId);
|
||||
break;
|
||||
|
||||
default:
|
||||
break;
|
||||
}
|
||||
|
||||
if (!authReqResponse.requestApproved) {
|
||||
return;
|
||||
}
|
||||
|
||||
const credentials = await this.buildLoginCredentials(requestId, response);
|
||||
const loginResponse = await this.authService.logIn(credentials);
|
||||
// Approved so proceed:
|
||||
|
||||
if (loginResponse.requiresTwoFactor) {
|
||||
if (this.onSuccessfulLoginTwoFactorNavigate != null) {
|
||||
this.onSuccessfulLoginTwoFactorNavigate();
|
||||
} else {
|
||||
this.router.navigate([this.twoFactorRoute]);
|
||||
}
|
||||
} else if (loginResponse.forcePasswordReset != ForceResetPasswordReason.None) {
|
||||
if (this.onSuccessfulLoginForceResetNavigate != null) {
|
||||
this.onSuccessfulLoginForceResetNavigate();
|
||||
} else {
|
||||
this.router.navigate([this.forcePasswordResetRoute]);
|
||||
}
|
||||
} else {
|
||||
await this.setRememberEmailValues();
|
||||
if (this.onSuccessfulLogin != null) {
|
||||
this.onSuccessfulLogin();
|
||||
}
|
||||
if (this.onSuccessfulLoginNavigate != null) {
|
||||
this.onSuccessfulLoginNavigate();
|
||||
} else {
|
||||
this.router.navigate([this.successRoute]);
|
||||
}
|
||||
// 4 Scenarios to handle for approved auth requests:
|
||||
// Existing flow 1:
|
||||
// - Anon Login with Device > User is not AuthN > receives approval from device with pubKey(masterKey)
|
||||
// > decrypt masterKey > must authenticate > gets masterKey(userKey) > decrypt userKey and proceed to vault
|
||||
|
||||
// 3 new flows from TDE:
|
||||
// Flow 2:
|
||||
// - Post SSO > User is AuthN > SSO login strategy success sets masterKey(userKey) > receives approval from device with pubKey(masterKey)
|
||||
// > decrypt masterKey > decrypt userKey > establish trust if required > proceed to vault
|
||||
// Flow 3:
|
||||
// - Post SSO > User is AuthN > Receives approval from device with pubKey(userKey) > decrypt userKey > establish trust if required > proceed to vault
|
||||
// Flow 4:
|
||||
// - Anon Login with Device > User is not AuthN > receives approval from device with pubKey(userKey)
|
||||
// > decrypt userKey > must authenticate > set userKey > proceed to vault
|
||||
|
||||
// if user has authenticated via SSO
|
||||
if (this.userAuthNStatus === AuthenticationStatus.Locked) {
|
||||
return await this.handleApprovedAdminAuthRequest(
|
||||
authReqResponse,
|
||||
this.authRequestKeyPair.privateKey
|
||||
);
|
||||
}
|
||||
|
||||
// Flow 1 and 4:
|
||||
const loginAuthResult = await this.loginViaPasswordlessStrategy(requestId, authReqResponse);
|
||||
await this.handlePostLoginNavigation(loginAuthResult);
|
||||
} catch (error) {
|
||||
if (error instanceof ErrorResponse) {
|
||||
this.router.navigate(["/login"]);
|
||||
let errorRoute = "/login";
|
||||
if (this.state === State.AdminAuthRequest) {
|
||||
errorRoute = "/login-initiated";
|
||||
}
|
||||
|
||||
this.router.navigate([errorRoute]);
|
||||
this.validationService.showError(error);
|
||||
return;
|
||||
}
|
||||
@@ -163,6 +346,112 @@ export class LoginWithDeviceComponent
|
||||
}
|
||||
}
|
||||
|
||||
async handleApprovedAdminAuthRequest(
|
||||
adminAuthReqResponse: AuthRequestResponse,
|
||||
privateKey: ArrayBuffer
|
||||
) {
|
||||
// See verifyAndHandleApprovedAuthReq(...) for flow details
|
||||
// it's flow 2 or 3 based on presence of masterPasswordHash
|
||||
if (adminAuthReqResponse.masterPasswordHash) {
|
||||
// Flow 2: masterPasswordHash is not null
|
||||
// key is authRequestPublicKey(masterKey) + we have authRequestPublicKey(masterPasswordHash)
|
||||
await this.authReqCryptoService.setKeysAfterDecryptingSharedMasterKeyAndHash(
|
||||
adminAuthReqResponse,
|
||||
privateKey
|
||||
);
|
||||
} else {
|
||||
// Flow 3: masterPasswordHash is null
|
||||
// we can assume key is authRequestPublicKey(userKey) and we can just decrypt with userKey and proceed to vault
|
||||
await this.authReqCryptoService.setUserKeyAfterDecryptingSharedUserKey(
|
||||
adminAuthReqResponse,
|
||||
privateKey
|
||||
);
|
||||
}
|
||||
|
||||
// clear the admin auth request from state so it cannot be used again (it's a one time use)
|
||||
// TODO: this should eventually be enforced via deleting this on the server once it is used
|
||||
await this.stateService.setAdminAuthRequest(null);
|
||||
|
||||
this.platformUtilsService.showToast("success", null, this.i18nService.t("loginApproved"));
|
||||
|
||||
// Now that we have a decrypted user key in memory, we can check if we
|
||||
// need to establish trust on the current device
|
||||
await this.deviceTrustCryptoService.trustDeviceIfRequired();
|
||||
|
||||
// TODO: don't forget to use auto enrollment service everywhere we trust device
|
||||
|
||||
await this.handleSuccessfulLoginNavigation();
|
||||
}
|
||||
|
||||
// Authentication helper
|
||||
private async buildPasswordlessLoginCredentials(
|
||||
requestId: string,
|
||||
response: AuthRequestResponse
|
||||
): Promise<PasswordlessLogInCredentials> {
|
||||
// if masterPasswordHash has a value, we will always receive key as authRequestPublicKey(masterKey) + authRequestPublicKey(masterPasswordHash)
|
||||
// if masterPasswordHash is null, we will always receive key as authRequestPublicKey(userKey)
|
||||
if (response.masterPasswordHash) {
|
||||
const { masterKey, masterKeyHash } =
|
||||
await this.authReqCryptoService.decryptPubKeyEncryptedMasterKeyAndHash(
|
||||
response.key,
|
||||
response.masterPasswordHash,
|
||||
this.authRequestKeyPair.privateKey
|
||||
);
|
||||
|
||||
return new PasswordlessLogInCredentials(
|
||||
this.email,
|
||||
this.passwordlessRequest.accessCode,
|
||||
requestId,
|
||||
null, // no userKey
|
||||
masterKey,
|
||||
masterKeyHash
|
||||
);
|
||||
} else {
|
||||
const userKey = await this.authReqCryptoService.decryptPubKeyEncryptedUserKey(
|
||||
response.key,
|
||||
this.authRequestKeyPair.privateKey
|
||||
);
|
||||
return new PasswordlessLogInCredentials(
|
||||
this.email,
|
||||
this.passwordlessRequest.accessCode,
|
||||
requestId,
|
||||
userKey,
|
||||
null, // no masterKey
|
||||
null // no masterKeyHash
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
private async loginViaPasswordlessStrategy(
|
||||
requestId: string,
|
||||
authReqResponse: AuthRequestResponse
|
||||
): Promise<AuthResult> {
|
||||
// Note: credentials change based on if the authReqResponse.key is a encryptedMasterKey or UserKey
|
||||
const credentials = await this.buildPasswordlessLoginCredentials(requestId, authReqResponse);
|
||||
|
||||
// Note: keys are set by PasswordlessLogInStrategy success handling
|
||||
return await this.authService.logIn(credentials);
|
||||
}
|
||||
|
||||
// Routing logic
|
||||
private async handlePostLoginNavigation(loginResponse: AuthResult) {
|
||||
if (loginResponse.requiresTwoFactor) {
|
||||
if (this.onSuccessfulLoginTwoFactorNavigate != null) {
|
||||
this.onSuccessfulLoginTwoFactorNavigate();
|
||||
} else {
|
||||
this.router.navigate([this.twoFactorRoute]);
|
||||
}
|
||||
} else if (loginResponse.forcePasswordReset != ForceResetPasswordReason.None) {
|
||||
if (this.onSuccessfulLoginForceResetNavigate != null) {
|
||||
this.onSuccessfulLoginForceResetNavigate();
|
||||
} else {
|
||||
this.router.navigate([this.forcePasswordResetRoute]);
|
||||
}
|
||||
} else {
|
||||
await this.handleSuccessfulLoginNavigation();
|
||||
}
|
||||
}
|
||||
|
||||
async setRememberEmailValues() {
|
||||
const rememberEmail = this.loginService.getRememberEmail();
|
||||
const rememberedEmail = this.loginService.getEmail();
|
||||
@@ -170,43 +459,19 @@ export class LoginWithDeviceComponent
|
||||
this.loginService.clearValues();
|
||||
}
|
||||
|
||||
private async buildAuthRequest() {
|
||||
this.authRequestKeyPair = await this.cryptoFunctionService.rsaGenerateKeyPair(2048);
|
||||
const deviceIdentifier = await this.appIdService.getAppId();
|
||||
const publicKey = Utils.fromBufferToB64(this.authRequestKeyPair[0]);
|
||||
const accessCode = await this.passwordGenerationService.generatePassword({ length: 25 });
|
||||
private async handleSuccessfulLoginNavigation() {
|
||||
if (this.state === State.StandardAuthRequest) {
|
||||
// Only need to set remembered email on standard login with auth req flow
|
||||
await this.setRememberEmailValues();
|
||||
}
|
||||
|
||||
this.fingerprintPhrase = (
|
||||
await this.cryptoService.getFingerprint(this.email, this.authRequestKeyPair[0])
|
||||
).join("-");
|
||||
|
||||
this.passwordlessRequest = new PasswordlessCreateAuthRequest(
|
||||
this.email,
|
||||
deviceIdentifier,
|
||||
publicKey,
|
||||
AuthRequestType.AuthenticateAndUnlock,
|
||||
accessCode
|
||||
);
|
||||
}
|
||||
|
||||
private async buildLoginCredentials(
|
||||
requestId: string,
|
||||
response: AuthRequestResponse
|
||||
): Promise<PasswordlessLogInCredentials> {
|
||||
const decKey = await this.cryptoService.rsaDecrypt(response.key, this.authRequestKeyPair[1]);
|
||||
const decMasterPasswordHash = await this.cryptoService.rsaDecrypt(
|
||||
response.masterPasswordHash,
|
||||
this.authRequestKeyPair[1]
|
||||
);
|
||||
const key = new SymmetricCryptoKey(decKey);
|
||||
const localHashedPassword = Utils.fromBufferToUtf8(decMasterPasswordHash);
|
||||
|
||||
return new PasswordlessLogInCredentials(
|
||||
this.email,
|
||||
this.passwordlessRequest.accessCode,
|
||||
requestId,
|
||||
key,
|
||||
localHashedPassword
|
||||
);
|
||||
if (this.onSuccessfulLogin != null) {
|
||||
this.onSuccessfulLogin();
|
||||
}
|
||||
if (this.onSuccessfulLoginNavigate != null) {
|
||||
this.onSuccessfulLoginNavigate();
|
||||
} else {
|
||||
this.router.navigate([this.successRoute]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3,8 +3,8 @@ import { FormBuilder, Validators } from "@angular/forms";
|
||||
import { ActivatedRoute, Router } from "@angular/router";
|
||||
import { take } from "rxjs/operators";
|
||||
|
||||
import { DevicesApiServiceAbstraction } from "@bitwarden/common/abstractions/devices/devices-api.service.abstraction";
|
||||
import { AuthService } from "@bitwarden/common/auth/abstractions/auth.service";
|
||||
import { DevicesApiServiceAbstraction } from "@bitwarden/common/auth/abstractions/devices-api.service.abstraction";
|
||||
import { LoginService } from "@bitwarden/common/auth/abstractions/login.service";
|
||||
import { AuthResult } from "@bitwarden/common/auth/models/domain/auth-result";
|
||||
import { ForceResetPasswordReason } from "@bitwarden/common/auth/models/domain/force-reset-password-reason";
|
||||
|
||||
567
libs/angular/src/auth/components/sso.component.spec.ts
Normal file
567
libs/angular/src/auth/components/sso.component.spec.ts
Normal file
@@ -0,0 +1,567 @@
|
||||
import { Component } from "@angular/core";
|
||||
import { ComponentFixture, TestBed } from "@angular/core/testing";
|
||||
import { ActivatedRoute, Router } from "@angular/router";
|
||||
import { MockProxy, mock } from "jest-mock-extended";
|
||||
import { Observable, of } from "rxjs";
|
||||
|
||||
import { ApiService } from "@bitwarden/common/abstractions/api.service";
|
||||
import { AuthService } from "@bitwarden/common/auth/abstractions/auth.service";
|
||||
import { TwoFactorProviderType } from "@bitwarden/common/auth/enums/two-factor-provider-type";
|
||||
import { AuthResult } from "@bitwarden/common/auth/models/domain/auth-result";
|
||||
import { ForceResetPasswordReason } from "@bitwarden/common/auth/models/domain/force-reset-password-reason";
|
||||
import { KeyConnectorUserDecryptionOption } from "@bitwarden/common/auth/models/domain/user-decryption-options/key-connector-user-decryption-option";
|
||||
import { TrustedDeviceUserDecryptionOption } from "@bitwarden/common/auth/models/domain/user-decryption-options/trusted-device-user-decryption-option";
|
||||
import { ConfigServiceAbstraction } from "@bitwarden/common/platform/abstractions/config/config.service.abstraction";
|
||||
import { CryptoFunctionService } from "@bitwarden/common/platform/abstractions/crypto-function.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 { PlatformUtilsService } from "@bitwarden/common/platform/abstractions/platform-utils.service";
|
||||
import { StateService } from "@bitwarden/common/platform/abstractions/state.service";
|
||||
import { AccountDecryptionOptions } from "@bitwarden/common/platform/models/domain/account";
|
||||
import { PasswordGenerationServiceAbstraction } from "@bitwarden/common/tools/generator/password";
|
||||
|
||||
import { SsoComponent } from "./sso.component";
|
||||
// test component that extends the SsoComponent
|
||||
@Component({})
|
||||
class TestSsoComponent extends SsoComponent {}
|
||||
|
||||
interface SsoComponentProtected {
|
||||
twoFactorRoute: string;
|
||||
successRoute: string;
|
||||
trustedDeviceEncRoute: string;
|
||||
changePasswordRoute: string;
|
||||
forcePasswordResetRoute: string;
|
||||
logIn(code: string, codeVerifier: string, orgIdFromState: string): Promise<AuthResult>;
|
||||
handleLoginError(e: any): Promise<void>;
|
||||
}
|
||||
|
||||
// The ideal scenario would be to not have to test the protected / private methods of the SsoComponent
|
||||
// but that will require a refactor of the SsoComponent class which is out of scope for now.
|
||||
// This test suite allows us to be sure that the new Trusted Device encryption flows + mild refactors
|
||||
// of the SsoComponent don't break the existing post login flows.
|
||||
describe("SsoComponent", () => {
|
||||
let component: TestSsoComponent;
|
||||
let _component: SsoComponentProtected;
|
||||
let fixture: ComponentFixture<TestSsoComponent>;
|
||||
|
||||
// Mock Services
|
||||
let mockAuthService: MockProxy<AuthService>;
|
||||
let mockRouter: MockProxy<Router>;
|
||||
let mockI18nService: MockProxy<I18nService>;
|
||||
|
||||
let mockQueryParams: Observable<any>;
|
||||
let mockActivatedRoute: ActivatedRoute;
|
||||
|
||||
let mockStateService: MockProxy<StateService>;
|
||||
let mockPlatformUtilsService: MockProxy<PlatformUtilsService>;
|
||||
let mockApiService: MockProxy<ApiService>;
|
||||
let mockCryptoFunctionService: MockProxy<CryptoFunctionService>;
|
||||
let mockEnvironmentService: MockProxy<EnvironmentService>;
|
||||
let mockPasswordGenerationService: MockProxy<PasswordGenerationServiceAbstraction>;
|
||||
let mockLogService: MockProxy<LogService>;
|
||||
let mockConfigService: MockProxy<ConfigServiceAbstraction>;
|
||||
|
||||
// Mock authService.logIn params
|
||||
let code: string;
|
||||
let codeVerifier: string;
|
||||
let orgIdFromState: string;
|
||||
|
||||
// Mock component callbacks
|
||||
let mockOnSuccessfulLogin: jest.Mock;
|
||||
let mockOnSuccessfulLoginNavigate: jest.Mock;
|
||||
let mockOnSuccessfulLoginTwoFactorNavigate: jest.Mock;
|
||||
let mockOnSuccessfulLoginChangePasswordNavigate: jest.Mock;
|
||||
let mockOnSuccessfulLoginForceResetNavigate: jest.Mock;
|
||||
let mockOnSuccessfulLoginTdeNavigate: jest.Mock;
|
||||
|
||||
let mockAcctDecryptionOpts: {
|
||||
noMasterPassword: AccountDecryptionOptions;
|
||||
withMasterPassword: AccountDecryptionOptions;
|
||||
withMasterPasswordAndTrustedDevice: AccountDecryptionOptions;
|
||||
withMasterPasswordAndTrustedDeviceWithManageResetPassword: AccountDecryptionOptions;
|
||||
withMasterPasswordAndKeyConnector: AccountDecryptionOptions;
|
||||
noMasterPasswordWithTrustedDevice: AccountDecryptionOptions;
|
||||
noMasterPasswordWithTrustedDeviceWithManageResetPassword: AccountDecryptionOptions;
|
||||
noMasterPasswordWithKeyConnector: AccountDecryptionOptions;
|
||||
};
|
||||
|
||||
beforeEach(() => {
|
||||
// Mock Services
|
||||
mockAuthService = mock<AuthService>();
|
||||
mockRouter = mock<Router>();
|
||||
mockI18nService = mock<I18nService>();
|
||||
|
||||
// Default mockQueryParams
|
||||
mockQueryParams = of({ code: "code", state: "state" });
|
||||
// Create a custom mock for ActivatedRoute with mock queryParams
|
||||
mockActivatedRoute = {
|
||||
queryParams: mockQueryParams,
|
||||
} as any as ActivatedRoute;
|
||||
|
||||
mockStateService = mock<StateService>();
|
||||
mockPlatformUtilsService = mock<PlatformUtilsService>();
|
||||
mockApiService = mock<ApiService>();
|
||||
mockCryptoFunctionService = mock<CryptoFunctionService>();
|
||||
mockEnvironmentService = mock<EnvironmentService>();
|
||||
mockPasswordGenerationService = mock<PasswordGenerationServiceAbstraction>();
|
||||
mockLogService = mock<LogService>();
|
||||
mockConfigService = mock<ConfigServiceAbstraction>();
|
||||
|
||||
// Mock authService.logIn params
|
||||
code = "code";
|
||||
codeVerifier = "codeVerifier";
|
||||
orgIdFromState = "orgIdFromState";
|
||||
|
||||
// Mock component callbacks
|
||||
mockOnSuccessfulLogin = jest.fn();
|
||||
mockOnSuccessfulLoginNavigate = jest.fn();
|
||||
mockOnSuccessfulLoginTwoFactorNavigate = jest.fn();
|
||||
mockOnSuccessfulLoginChangePasswordNavigate = jest.fn();
|
||||
mockOnSuccessfulLoginForceResetNavigate = jest.fn();
|
||||
mockOnSuccessfulLoginTdeNavigate = jest.fn();
|
||||
|
||||
mockAcctDecryptionOpts = {
|
||||
noMasterPassword: new AccountDecryptionOptions({
|
||||
hasMasterPassword: false,
|
||||
trustedDeviceOption: undefined,
|
||||
keyConnectorOption: undefined,
|
||||
}),
|
||||
withMasterPassword: new AccountDecryptionOptions({
|
||||
hasMasterPassword: true,
|
||||
trustedDeviceOption: undefined,
|
||||
keyConnectorOption: undefined,
|
||||
}),
|
||||
withMasterPasswordAndTrustedDevice: new AccountDecryptionOptions({
|
||||
hasMasterPassword: true,
|
||||
trustedDeviceOption: new TrustedDeviceUserDecryptionOption(true, false, false),
|
||||
keyConnectorOption: undefined,
|
||||
}),
|
||||
withMasterPasswordAndTrustedDeviceWithManageResetPassword: new AccountDecryptionOptions({
|
||||
hasMasterPassword: true,
|
||||
trustedDeviceOption: new TrustedDeviceUserDecryptionOption(true, false, true),
|
||||
keyConnectorOption: undefined,
|
||||
}),
|
||||
withMasterPasswordAndKeyConnector: new AccountDecryptionOptions({
|
||||
hasMasterPassword: true,
|
||||
trustedDeviceOption: undefined,
|
||||
keyConnectorOption: new KeyConnectorUserDecryptionOption("http://example.com"),
|
||||
}),
|
||||
noMasterPasswordWithTrustedDevice: new AccountDecryptionOptions({
|
||||
hasMasterPassword: false,
|
||||
trustedDeviceOption: new TrustedDeviceUserDecryptionOption(true, false, false),
|
||||
keyConnectorOption: undefined,
|
||||
}),
|
||||
noMasterPasswordWithTrustedDeviceWithManageResetPassword: new AccountDecryptionOptions({
|
||||
hasMasterPassword: false,
|
||||
trustedDeviceOption: new TrustedDeviceUserDecryptionOption(true, false, true),
|
||||
keyConnectorOption: undefined,
|
||||
}),
|
||||
noMasterPasswordWithKeyConnector: new AccountDecryptionOptions({
|
||||
hasMasterPassword: false,
|
||||
trustedDeviceOption: undefined,
|
||||
keyConnectorOption: new KeyConnectorUserDecryptionOption("http://example.com"),
|
||||
}),
|
||||
};
|
||||
|
||||
TestBed.configureTestingModule({
|
||||
declarations: [TestSsoComponent],
|
||||
providers: [
|
||||
{ provide: AuthService, useValue: mockAuthService },
|
||||
{ provide: Router, useValue: mockRouter },
|
||||
{ provide: I18nService, useValue: mockI18nService },
|
||||
{ provide: ActivatedRoute, useValue: mockActivatedRoute },
|
||||
{ provide: StateService, useValue: mockStateService },
|
||||
{ provide: PlatformUtilsService, useValue: mockPlatformUtilsService },
|
||||
|
||||
{ provide: ApiService, useValue: mockApiService },
|
||||
{ provide: CryptoFunctionService, useValue: mockCryptoFunctionService },
|
||||
{ provide: EnvironmentService, useValue: mockEnvironmentService },
|
||||
{ provide: PasswordGenerationServiceAbstraction, useValue: mockPasswordGenerationService },
|
||||
|
||||
{ provide: LogService, useValue: mockLogService },
|
||||
{ provide: ConfigServiceAbstraction, useValue: mockConfigService },
|
||||
],
|
||||
});
|
||||
|
||||
fixture = TestBed.createComponent(TestSsoComponent);
|
||||
component = fixture.componentInstance;
|
||||
_component = component as any;
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
// Reset all mocks after each test
|
||||
jest.resetAllMocks();
|
||||
});
|
||||
|
||||
it("should create", () => {
|
||||
expect(component).toBeTruthy();
|
||||
});
|
||||
|
||||
describe("navigateViaCallbackOrRoute(...)", () => {
|
||||
it("calls the provided callback when callback is defined", async () => {
|
||||
const callback = jest.fn().mockResolvedValue(null);
|
||||
const commands = ["some", "route"];
|
||||
|
||||
await (component as any).navigateViaCallbackOrRoute(callback, commands);
|
||||
|
||||
expect(callback).toHaveBeenCalledTimes(1);
|
||||
expect(mockRouter.navigate).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("calls router.navigate when callback is not defined", async () => {
|
||||
const commands = ["some", "route"];
|
||||
|
||||
await (component as any).navigateViaCallbackOrRoute(undefined, commands);
|
||||
|
||||
expect(mockRouter.navigate).toHaveBeenCalledTimes(1);
|
||||
expect(mockRouter.navigate).toHaveBeenCalledWith(commands, undefined);
|
||||
});
|
||||
});
|
||||
|
||||
describe("logIn(...)", () => {
|
||||
describe("2FA scenarios", () => {
|
||||
beforeEach(() => {
|
||||
const authResult = new AuthResult();
|
||||
authResult.twoFactorProviders = new Map([[TwoFactorProviderType.Authenticator, {}]]);
|
||||
|
||||
// use standard user with MP because this test is not concerned with password reset.
|
||||
mockStateService.getAccountDecryptionOptions.mockResolvedValue(
|
||||
mockAcctDecryptionOpts.withMasterPassword
|
||||
);
|
||||
|
||||
mockAuthService.logIn.mockResolvedValue(authResult);
|
||||
});
|
||||
|
||||
it("calls authService.logIn and navigates to the component's defined 2FA route when the auth result requires 2FA and onSuccessfulLoginTwoFactorNavigate is not defined", async () => {
|
||||
await _component.logIn(code, codeVerifier, orgIdFromState);
|
||||
expect(mockAuthService.logIn).toHaveBeenCalledTimes(1);
|
||||
|
||||
expect(mockOnSuccessfulLoginTwoFactorNavigate).not.toHaveBeenCalled();
|
||||
|
||||
expect(mockRouter.navigate).toHaveBeenCalledTimes(1);
|
||||
expect(mockRouter.navigate).toHaveBeenCalledWith([_component.twoFactorRoute], {
|
||||
queryParams: {
|
||||
identifier: orgIdFromState,
|
||||
sso: "true",
|
||||
},
|
||||
});
|
||||
|
||||
expect(mockLogService.error).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("calls onSuccessfulLoginTwoFactorNavigate instead of router.navigate when response.requiresTwoFactor is true and the callback is defined", async () => {
|
||||
mockOnSuccessfulLoginTwoFactorNavigate = jest.fn().mockResolvedValue(null);
|
||||
component.onSuccessfulLoginTwoFactorNavigate = mockOnSuccessfulLoginTwoFactorNavigate;
|
||||
|
||||
await _component.logIn(code, codeVerifier, orgIdFromState);
|
||||
|
||||
expect(mockAuthService.logIn).toHaveBeenCalledTimes(1);
|
||||
expect(mockOnSuccessfulLoginTwoFactorNavigate).toHaveBeenCalledTimes(1);
|
||||
expect(mockRouter.navigate).not.toHaveBeenCalled();
|
||||
expect(mockLogService.error).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
// Shared test helpers
|
||||
const testChangePasswordOnSuccessfulLogin = () => {
|
||||
it("navigates to the component's defined change password route when onSuccessfulLoginChangePasswordNavigate callback is undefined", async () => {
|
||||
await _component.logIn(code, codeVerifier, orgIdFromState);
|
||||
expect(mockAuthService.logIn).toHaveBeenCalledTimes(1);
|
||||
|
||||
expect(mockOnSuccessfulLoginChangePasswordNavigate).not.toHaveBeenCalled();
|
||||
|
||||
expect(mockRouter.navigate).toHaveBeenCalledTimes(1);
|
||||
expect(mockRouter.navigate).toHaveBeenCalledWith([_component.changePasswordRoute], {
|
||||
queryParams: {
|
||||
identifier: orgIdFromState,
|
||||
},
|
||||
});
|
||||
|
||||
expect(mockLogService.error).not.toHaveBeenCalled();
|
||||
});
|
||||
};
|
||||
|
||||
const testOnSuccessfulLoginChangePasswordNavigate = () => {
|
||||
it("calls onSuccessfulLoginChangePasswordNavigate instead of router.navigate when the callback is defined", async () => {
|
||||
mockOnSuccessfulLoginChangePasswordNavigate = jest.fn().mockResolvedValue(null);
|
||||
component.onSuccessfulLoginChangePasswordNavigate =
|
||||
mockOnSuccessfulLoginChangePasswordNavigate;
|
||||
|
||||
await _component.logIn(code, codeVerifier, orgIdFromState);
|
||||
|
||||
expect(mockAuthService.logIn).toHaveBeenCalledTimes(1);
|
||||
expect(mockOnSuccessfulLoginChangePasswordNavigate).toHaveBeenCalledTimes(1);
|
||||
expect(mockRouter.navigate).not.toHaveBeenCalled();
|
||||
expect(mockLogService.error).not.toHaveBeenCalled();
|
||||
});
|
||||
};
|
||||
|
||||
const testForceResetOnSuccessfulLogin = (reasonString: string) => {
|
||||
it(`navigates to the component's defined forcePasswordResetRoute when response.forcePasswordReset is ${reasonString}`, async () => {
|
||||
await _component.logIn(code, codeVerifier, orgIdFromState);
|
||||
|
||||
expect(mockAuthService.logIn).toHaveBeenCalledTimes(1);
|
||||
|
||||
expect(mockOnSuccessfulLoginForceResetNavigate).not.toHaveBeenCalled();
|
||||
|
||||
expect(mockRouter.navigate).toHaveBeenCalledTimes(1);
|
||||
expect(mockRouter.navigate).toHaveBeenCalledWith([_component.forcePasswordResetRoute], {
|
||||
queryParams: {
|
||||
identifier: orgIdFromState,
|
||||
},
|
||||
});
|
||||
expect(mockLogService.error).not.toHaveBeenCalled();
|
||||
});
|
||||
};
|
||||
|
||||
const testOnSuccessfulLoginForceResetNavigate = (reasonString: string) => {
|
||||
it(`calls onSuccessfulLoginForceResetNavigate instead of router.navigate when response.forcePasswordReset is ${reasonString} and the callback is defined`, async () => {
|
||||
mockOnSuccessfulLoginForceResetNavigate = jest.fn().mockResolvedValue(null);
|
||||
component.onSuccessfulLoginForceResetNavigate = mockOnSuccessfulLoginForceResetNavigate;
|
||||
|
||||
await _component.logIn(code, codeVerifier, orgIdFromState);
|
||||
|
||||
expect(mockAuthService.logIn).toHaveBeenCalledTimes(1);
|
||||
expect(mockOnSuccessfulLoginForceResetNavigate).toHaveBeenCalledTimes(1);
|
||||
expect(mockRouter.navigate).not.toHaveBeenCalled();
|
||||
expect(mockLogService.error).not.toHaveBeenCalled();
|
||||
});
|
||||
};
|
||||
|
||||
describe("Trusted Device Encryption scenarios", () => {
|
||||
beforeEach(() => {
|
||||
mockConfigService.getFeatureFlagBool.mockResolvedValue(true); // TDE enabled
|
||||
});
|
||||
|
||||
describe("Given Trusted Device Encryption is enabled and user needs to set a master password", () => {
|
||||
let authResult;
|
||||
beforeEach(() => {
|
||||
mockStateService.getAccountDecryptionOptions.mockResolvedValue(
|
||||
mockAcctDecryptionOpts.noMasterPasswordWithTrustedDeviceWithManageResetPassword
|
||||
);
|
||||
|
||||
authResult = new AuthResult();
|
||||
mockAuthService.logIn.mockResolvedValue(authResult);
|
||||
});
|
||||
|
||||
testChangePasswordOnSuccessfulLogin();
|
||||
testOnSuccessfulLoginChangePasswordNavigate();
|
||||
});
|
||||
|
||||
describe("Given Trusted Device Encryption is enabled, user doesn't need to set a MP, and forcePasswordReset is required", () => {
|
||||
[
|
||||
ForceResetPasswordReason.AdminForcePasswordReset,
|
||||
ForceResetPasswordReason.WeakMasterPassword,
|
||||
].forEach((forceResetPasswordReason) => {
|
||||
const reasonString = ForceResetPasswordReason[forceResetPasswordReason];
|
||||
let authResult;
|
||||
beforeEach(() => {
|
||||
mockStateService.getAccountDecryptionOptions.mockResolvedValue(
|
||||
mockAcctDecryptionOpts.withMasterPasswordAndTrustedDevice
|
||||
);
|
||||
|
||||
authResult = new AuthResult();
|
||||
authResult.forcePasswordReset = ForceResetPasswordReason.AdminForcePasswordReset;
|
||||
mockAuthService.logIn.mockResolvedValue(authResult);
|
||||
});
|
||||
|
||||
testForceResetOnSuccessfulLogin(reasonString);
|
||||
testOnSuccessfulLoginForceResetNavigate(reasonString);
|
||||
});
|
||||
});
|
||||
|
||||
describe("Given Trusted Device Encryption is enabled, user doesn't need to set a MP, and forcePasswordReset is not required", () => {
|
||||
let authResult;
|
||||
beforeEach(() => {
|
||||
mockStateService.getAccountDecryptionOptions.mockResolvedValue(
|
||||
mockAcctDecryptionOpts.withMasterPasswordAndTrustedDevice
|
||||
);
|
||||
|
||||
authResult = new AuthResult();
|
||||
authResult.forcePasswordReset = ForceResetPasswordReason.None;
|
||||
mockAuthService.logIn.mockResolvedValue(authResult);
|
||||
});
|
||||
|
||||
it("navigates to the component's defined trusted device encryption route when login is successful and no callback is defined", async () => {
|
||||
await _component.logIn(code, codeVerifier, orgIdFromState);
|
||||
|
||||
expect(mockAuthService.logIn).toHaveBeenCalledTimes(1);
|
||||
expect(mockRouter.navigate).toHaveBeenCalledTimes(1);
|
||||
expect(mockRouter.navigate).toHaveBeenCalledWith(
|
||||
[_component.trustedDeviceEncRoute],
|
||||
undefined
|
||||
);
|
||||
expect(mockLogService.error).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("calls onSuccessfulLoginTdeNavigate instead of router.navigate when the callback is defined", async () => {
|
||||
mockOnSuccessfulLoginTdeNavigate = jest.fn().mockResolvedValue(null);
|
||||
component.onSuccessfulLoginTdeNavigate = mockOnSuccessfulLoginTdeNavigate;
|
||||
|
||||
await _component.logIn(code, codeVerifier, orgIdFromState);
|
||||
|
||||
expect(mockAuthService.logIn).toHaveBeenCalledTimes(1);
|
||||
|
||||
expect(mockOnSuccessfulLoginTdeNavigate).toHaveBeenCalledTimes(1);
|
||||
|
||||
expect(mockRouter.navigate).not.toHaveBeenCalled();
|
||||
expect(mockLogService.error).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("Set Master Password scenarios", () => {
|
||||
beforeEach(() => {
|
||||
const authResult = new AuthResult();
|
||||
mockAuthService.logIn.mockResolvedValue(authResult);
|
||||
});
|
||||
|
||||
describe("Given user needs to set a master password", () => {
|
||||
beforeEach(() => {
|
||||
// Only need to test the case where the user has no master password to test the primary change mp flow here
|
||||
mockStateService.getAccountDecryptionOptions.mockResolvedValue(
|
||||
mockAcctDecryptionOpts.noMasterPassword
|
||||
);
|
||||
});
|
||||
|
||||
testChangePasswordOnSuccessfulLogin();
|
||||
testOnSuccessfulLoginChangePasswordNavigate();
|
||||
});
|
||||
|
||||
it("does not navigate to the change password route when the user has key connector even if user has no master password", async () => {
|
||||
mockStateService.getAccountDecryptionOptions.mockResolvedValue(
|
||||
mockAcctDecryptionOpts.noMasterPasswordWithKeyConnector
|
||||
);
|
||||
|
||||
await _component.logIn(code, codeVerifier, orgIdFromState);
|
||||
expect(mockAuthService.logIn).toHaveBeenCalledTimes(1);
|
||||
|
||||
expect(mockOnSuccessfulLoginChangePasswordNavigate).not.toHaveBeenCalled();
|
||||
expect(mockRouter.navigate).not.toHaveBeenCalledWith([_component.changePasswordRoute], {
|
||||
queryParams: {
|
||||
identifier: orgIdFromState,
|
||||
},
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("Force Master Password Reset scenarios", () => {
|
||||
[
|
||||
ForceResetPasswordReason.AdminForcePasswordReset,
|
||||
ForceResetPasswordReason.WeakMasterPassword,
|
||||
].forEach((forceResetPasswordReason) => {
|
||||
const reasonString = ForceResetPasswordReason[forceResetPasswordReason];
|
||||
|
||||
beforeEach(() => {
|
||||
// use standard user with MP because this test is not concerned with password reset.
|
||||
mockStateService.getAccountDecryptionOptions.mockResolvedValue(
|
||||
mockAcctDecryptionOpts.withMasterPassword
|
||||
);
|
||||
|
||||
const authResult = new AuthResult();
|
||||
authResult.forcePasswordReset = forceResetPasswordReason;
|
||||
mockAuthService.logIn.mockResolvedValue(authResult);
|
||||
});
|
||||
|
||||
testForceResetOnSuccessfulLogin(reasonString);
|
||||
testOnSuccessfulLoginForceResetNavigate(reasonString);
|
||||
});
|
||||
});
|
||||
|
||||
describe("Success scenarios", () => {
|
||||
beforeEach(() => {
|
||||
const authResult = new AuthResult();
|
||||
authResult.twoFactorProviders = null;
|
||||
// use standard user with MP because this test is not concerned with password reset.
|
||||
mockStateService.getAccountDecryptionOptions.mockResolvedValue(
|
||||
mockAcctDecryptionOpts.withMasterPassword
|
||||
);
|
||||
authResult.forcePasswordReset = ForceResetPasswordReason.None;
|
||||
mockAuthService.logIn.mockResolvedValue(authResult);
|
||||
});
|
||||
|
||||
it("calls authService.logIn and navigates to the component's defined success route when the login is successful", async () => {
|
||||
await _component.logIn(code, codeVerifier, orgIdFromState);
|
||||
|
||||
expect(mockAuthService.logIn).toHaveBeenCalled();
|
||||
|
||||
expect(mockOnSuccessfulLoginNavigate).not.toHaveBeenCalled();
|
||||
expect(mockOnSuccessfulLogin).not.toHaveBeenCalled();
|
||||
|
||||
expect(mockRouter.navigate).toHaveBeenCalledTimes(1);
|
||||
expect(mockRouter.navigate).toHaveBeenCalledWith([_component.successRoute], undefined);
|
||||
expect(mockLogService.error).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("calls onSuccessfulLogin if defined when login is successful", async () => {
|
||||
mockOnSuccessfulLogin = jest.fn().mockResolvedValue(null);
|
||||
component.onSuccessfulLogin = mockOnSuccessfulLogin;
|
||||
|
||||
await _component.logIn(code, codeVerifier, orgIdFromState);
|
||||
|
||||
expect(mockAuthService.logIn).toHaveBeenCalled();
|
||||
expect(mockOnSuccessfulLogin).toHaveBeenCalledTimes(1);
|
||||
|
||||
expect(mockOnSuccessfulLoginNavigate).not.toHaveBeenCalled();
|
||||
|
||||
expect(mockRouter.navigate).toHaveBeenCalledTimes(1);
|
||||
expect(mockRouter.navigate).toHaveBeenCalledWith([_component.successRoute], undefined);
|
||||
|
||||
expect(mockLogService.error).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("calls onSuccessfulLoginNavigate instead of router.navigate when login is successful and the callback is defined", async () => {
|
||||
mockOnSuccessfulLoginNavigate = jest.fn().mockResolvedValue(null);
|
||||
component.onSuccessfulLoginNavigate = mockOnSuccessfulLoginNavigate;
|
||||
|
||||
await _component.logIn(code, codeVerifier, orgIdFromState);
|
||||
|
||||
expect(mockAuthService.logIn).toHaveBeenCalled();
|
||||
|
||||
expect(mockOnSuccessfulLoginNavigate).toHaveBeenCalledTimes(1);
|
||||
|
||||
expect(mockRouter.navigate).not.toHaveBeenCalled();
|
||||
|
||||
expect(mockLogService.error).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
describe("Error scenarios", () => {
|
||||
it("calls handleLoginError when an error is thrown during logIn", async () => {
|
||||
const errorMessage = "Key Connector error";
|
||||
const error = new Error(errorMessage);
|
||||
mockAuthService.logIn.mockRejectedValue(error);
|
||||
|
||||
const handleLoginErrorSpy = jest.spyOn(_component, "handleLoginError");
|
||||
|
||||
await _component.logIn(code, codeVerifier, orgIdFromState);
|
||||
|
||||
expect(handleLoginErrorSpy).toHaveBeenCalledWith(error);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("handleLoginError(e)", () => {
|
||||
it("logs the error and shows a toast when the error message is 'Key Connector error'", async () => {
|
||||
const errorMessage = "Key Connector error";
|
||||
const error = new Error(errorMessage);
|
||||
|
||||
mockI18nService.t.mockReturnValueOnce("ssoKeyConnectorError");
|
||||
|
||||
await _component.handleLoginError(error);
|
||||
|
||||
expect(mockLogService.error).toHaveBeenCalledTimes(1);
|
||||
expect(mockLogService.error).toHaveBeenCalledWith(error);
|
||||
|
||||
expect(mockPlatformUtilsService.showToast).toHaveBeenCalledTimes(1);
|
||||
expect(mockPlatformUtilsService.showToast).toHaveBeenCalledWith(
|
||||
"error",
|
||||
null,
|
||||
"ssoKeyConnectorError"
|
||||
);
|
||||
|
||||
expect(mockRouter.navigate).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -1,5 +1,5 @@
|
||||
import { Directive } from "@angular/core";
|
||||
import { ActivatedRoute, Router } from "@angular/router";
|
||||
import { ActivatedRoute, NavigationExtras, Router } from "@angular/router";
|
||||
import { first } from "rxjs/operators";
|
||||
|
||||
import { ApiService } from "@bitwarden/common/abstractions/api.service";
|
||||
@@ -7,7 +7,10 @@ import { AuthService } from "@bitwarden/common/auth/abstractions/auth.service";
|
||||
import { AuthResult } from "@bitwarden/common/auth/models/domain/auth-result";
|
||||
import { ForceResetPasswordReason } from "@bitwarden/common/auth/models/domain/force-reset-password-reason";
|
||||
import { SsoLogInCredentials } from "@bitwarden/common/auth/models/domain/log-in-credentials";
|
||||
import { TrustedDeviceUserDecryptionOption } from "@bitwarden/common/auth/models/domain/user-decryption-options/trusted-device-user-decryption-option";
|
||||
import { SsoPreValidateResponse } from "@bitwarden/common/auth/models/response/sso-pre-validate.response";
|
||||
import { FeatureFlag } from "@bitwarden/common/enums/feature-flag.enum";
|
||||
import { ConfigServiceAbstraction } from "@bitwarden/common/platform/abstractions/config/config.service.abstraction";
|
||||
import { CryptoFunctionService } from "@bitwarden/common/platform/abstractions/crypto-function.service";
|
||||
import { EnvironmentService } from "@bitwarden/common/platform/abstractions/environment.service";
|
||||
import { I18nService } from "@bitwarden/common/platform/abstractions/i18n.service";
|
||||
@@ -15,6 +18,7 @@ import { LogService } from "@bitwarden/common/platform/abstractions/log.service"
|
||||
import { PlatformUtilsService } from "@bitwarden/common/platform/abstractions/platform-utils.service";
|
||||
import { StateService } from "@bitwarden/common/platform/abstractions/state.service";
|
||||
import { Utils } from "@bitwarden/common/platform/misc/utils";
|
||||
import { AccountDecryptionOptions } from "@bitwarden/common/platform/models/domain/account";
|
||||
import { PasswordGenerationServiceAbstraction } from "@bitwarden/common/tools/generator/password";
|
||||
|
||||
@Directive()
|
||||
@@ -24,14 +28,18 @@ export class SsoComponent {
|
||||
|
||||
formPromise: Promise<AuthResult>;
|
||||
initiateSsoFormPromise: Promise<SsoPreValidateResponse>;
|
||||
onSuccessfulLogin: () => Promise<any>;
|
||||
onSuccessfulLoginNavigate: () => Promise<any>;
|
||||
onSuccessfulLoginTwoFactorNavigate: () => Promise<any>;
|
||||
onSuccessfulLoginChangePasswordNavigate: () => Promise<any>;
|
||||
onSuccessfulLoginForceResetNavigate: () => Promise<any>;
|
||||
onSuccessfulLogin: () => Promise<void>;
|
||||
onSuccessfulLoginNavigate: () => Promise<void>;
|
||||
onSuccessfulLoginTwoFactorNavigate: () => Promise<void>;
|
||||
onSuccessfulLoginChangePasswordNavigate: () => Promise<void>;
|
||||
onSuccessfulLoginForceResetNavigate: () => Promise<void>;
|
||||
|
||||
onSuccessfulLoginTde: () => Promise<void>;
|
||||
onSuccessfulLoginTdeNavigate: () => Promise<void>;
|
||||
|
||||
protected twoFactorRoute = "2fa";
|
||||
protected successRoute = "lock";
|
||||
protected trustedDeviceEncRoute = "login-initiated";
|
||||
protected changePasswordRoute = "set-password";
|
||||
protected forcePasswordResetRoute = "update-temp-password";
|
||||
protected clientId: string;
|
||||
@@ -50,7 +58,8 @@ export class SsoComponent {
|
||||
protected cryptoFunctionService: CryptoFunctionService,
|
||||
protected environmentService: EnvironmentService,
|
||||
protected passwordGenerationService: PasswordGenerationServiceAbstraction,
|
||||
protected logService: LogService
|
||||
protected logService: LogService,
|
||||
protected configService: ConfigServiceAbstraction
|
||||
) {}
|
||||
|
||||
async ngOnInit() {
|
||||
@@ -67,11 +76,12 @@ export class SsoComponent {
|
||||
state != null &&
|
||||
this.checkState(state, qParams.state)
|
||||
) {
|
||||
await this.logIn(
|
||||
qParams.code,
|
||||
codeVerifier,
|
||||
this.getOrgIdentifierFromState(qParams.state)
|
||||
);
|
||||
// We are not using a query param to pass org identifier around specifically
|
||||
// for the browser SSO case when it needs it on extension open after SSO success
|
||||
// on the TDE login decryption options component
|
||||
const ssoOrganizationIdentifier = this.getOrgIdentifierFromState(qParams.state);
|
||||
await this.logIn(qParams.code, codeVerifier, ssoOrganizationIdentifier);
|
||||
await this.stateService.setUserSsoOrganizationIdentifier(ssoOrganizationIdentifier);
|
||||
}
|
||||
} else if (
|
||||
qParams.clientId != null &&
|
||||
@@ -173,67 +183,172 @@ export class SsoComponent {
|
||||
return authorizeUrl;
|
||||
}
|
||||
|
||||
private async logIn(code: string, codeVerifier: string, orgIdFromState: string) {
|
||||
private async logIn(code: string, codeVerifier: string, orgIdentifier: string) {
|
||||
this.loggingIn = true;
|
||||
try {
|
||||
const credentials = new SsoLogInCredentials(
|
||||
code,
|
||||
codeVerifier,
|
||||
this.redirectUri,
|
||||
orgIdFromState
|
||||
orgIdentifier
|
||||
);
|
||||
this.formPromise = this.authService.logIn(credentials);
|
||||
const response = await this.formPromise;
|
||||
if (response.requiresTwoFactor) {
|
||||
if (this.onSuccessfulLoginTwoFactorNavigate != null) {
|
||||
await this.onSuccessfulLoginTwoFactorNavigate();
|
||||
} else {
|
||||
this.router.navigate([this.twoFactorRoute], {
|
||||
queryParams: {
|
||||
identifier: orgIdFromState,
|
||||
sso: "true",
|
||||
},
|
||||
});
|
||||
}
|
||||
} else if (response.resetMasterPassword) {
|
||||
if (this.onSuccessfulLoginChangePasswordNavigate != null) {
|
||||
await this.onSuccessfulLoginChangePasswordNavigate();
|
||||
} else {
|
||||
this.router.navigate([this.changePasswordRoute], {
|
||||
queryParams: {
|
||||
identifier: orgIdFromState,
|
||||
},
|
||||
});
|
||||
}
|
||||
} else if (response.forcePasswordReset !== ForceResetPasswordReason.None) {
|
||||
if (this.onSuccessfulLoginForceResetNavigate != null) {
|
||||
await this.onSuccessfulLoginForceResetNavigate();
|
||||
} else {
|
||||
this.router.navigate([this.forcePasswordResetRoute]);
|
||||
}
|
||||
} else {
|
||||
if (this.onSuccessfulLogin != null) {
|
||||
await this.onSuccessfulLogin();
|
||||
}
|
||||
if (this.onSuccessfulLoginNavigate != null) {
|
||||
await this.onSuccessfulLoginNavigate();
|
||||
} else {
|
||||
this.router.navigate([this.successRoute]);
|
||||
}
|
||||
}
|
||||
} catch (e) {
|
||||
this.logService.error(e);
|
||||
const authResult = await this.formPromise;
|
||||
|
||||
// TODO: Key Connector Service should pass this error message to the logout callback instead of displaying here
|
||||
if (e.message === "Key Connector error") {
|
||||
this.platformUtilsService.showToast(
|
||||
"error",
|
||||
null,
|
||||
this.i18nService.t("ssoKeyConnectorError")
|
||||
const acctDecryptionOpts: AccountDecryptionOptions =
|
||||
await this.stateService.getAccountDecryptionOptions();
|
||||
|
||||
if (authResult.requiresTwoFactor) {
|
||||
return await this.handleTwoFactorRequired(orgIdentifier);
|
||||
}
|
||||
|
||||
const tdeEnabled = await this.isTrustedDeviceEncEnabled(
|
||||
acctDecryptionOpts.trustedDeviceOption
|
||||
);
|
||||
|
||||
if (tdeEnabled) {
|
||||
return await this.handleTrustedDeviceEncryptionEnabled(
|
||||
authResult,
|
||||
orgIdentifier,
|
||||
acctDecryptionOpts
|
||||
);
|
||||
}
|
||||
|
||||
// In the standard, non TDE case, a user must set password if they don't
|
||||
// have one and they aren't using key connector.
|
||||
// Note: TDE & Key connector are mutually exclusive org config options.
|
||||
const requireSetPassword =
|
||||
!acctDecryptionOpts.hasMasterPassword &&
|
||||
acctDecryptionOpts.keyConnectorOption === undefined;
|
||||
|
||||
if (requireSetPassword || authResult.resetMasterPassword) {
|
||||
// Change implies going no password -> password in this case
|
||||
return await this.handleChangePasswordRequired(orgIdentifier);
|
||||
}
|
||||
|
||||
// Users can be forced to reset their password via an admin or org policy
|
||||
// disallowing weak passwords
|
||||
if (authResult.forcePasswordReset !== ForceResetPasswordReason.None) {
|
||||
return await this.handleForcePasswordReset(orgIdentifier);
|
||||
}
|
||||
|
||||
// Standard SSO login success case
|
||||
return await this.handleSuccessfulLogin();
|
||||
} catch (e) {
|
||||
await this.handleLoginError(e);
|
||||
}
|
||||
}
|
||||
|
||||
private async isTrustedDeviceEncEnabled(
|
||||
trustedDeviceOption: TrustedDeviceUserDecryptionOption
|
||||
): Promise<boolean> {
|
||||
const trustedDeviceEncryptionFeatureActive = await this.configService.getFeatureFlagBool(
|
||||
FeatureFlag.TrustedDeviceEncryption
|
||||
);
|
||||
|
||||
return trustedDeviceEncryptionFeatureActive && trustedDeviceOption !== undefined;
|
||||
}
|
||||
|
||||
private async handleTwoFactorRequired(orgIdentifier: string) {
|
||||
await this.navigateViaCallbackOrRoute(
|
||||
this.onSuccessfulLoginTwoFactorNavigate,
|
||||
[this.twoFactorRoute],
|
||||
{
|
||||
queryParams: {
|
||||
identifier: orgIdentifier,
|
||||
sso: "true",
|
||||
},
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
private async handleTrustedDeviceEncryptionEnabled(
|
||||
authResult: AuthResult,
|
||||
orgIdentifier: string,
|
||||
acctDecryptionOpts: AccountDecryptionOptions
|
||||
): Promise<void> {
|
||||
// If user doesn't have a MP, but has reset password permission, they must set a MP
|
||||
if (
|
||||
!acctDecryptionOpts.hasMasterPassword &&
|
||||
acctDecryptionOpts.trustedDeviceOption.hasManageResetPasswordPermission
|
||||
) {
|
||||
// Change implies going no password -> password in this case
|
||||
return await this.handleChangePasswordRequired(orgIdentifier);
|
||||
}
|
||||
|
||||
if (authResult.forcePasswordReset !== ForceResetPasswordReason.None) {
|
||||
return await this.handleForcePasswordReset(orgIdentifier);
|
||||
}
|
||||
|
||||
if (this.onSuccessfulLoginTde != null) {
|
||||
// Don't await b/c causes hang on desktop & browser
|
||||
this.onSuccessfulLoginTde();
|
||||
}
|
||||
|
||||
this.navigateViaCallbackOrRoute(
|
||||
this.onSuccessfulLoginTdeNavigate,
|
||||
// Navigate to TDE page (if user was on trusted device and TDE has decrypted
|
||||
// their user key, the login-initiated guard will redirect them to the vault)
|
||||
[this.trustedDeviceEncRoute]
|
||||
);
|
||||
}
|
||||
|
||||
private async handleChangePasswordRequired(orgIdentifier: string) {
|
||||
await this.navigateViaCallbackOrRoute(
|
||||
this.onSuccessfulLoginChangePasswordNavigate,
|
||||
[this.changePasswordRoute],
|
||||
{
|
||||
queryParams: {
|
||||
identifier: orgIdentifier,
|
||||
},
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
private async handleForcePasswordReset(orgIdentifier: string) {
|
||||
await this.navigateViaCallbackOrRoute(
|
||||
this.onSuccessfulLoginForceResetNavigate,
|
||||
[this.forcePasswordResetRoute],
|
||||
{
|
||||
queryParams: {
|
||||
identifier: orgIdentifier,
|
||||
},
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
private async handleSuccessfulLogin() {
|
||||
if (this.onSuccessfulLogin != null) {
|
||||
// Don't await b/c causes hang on desktop & browser
|
||||
this.onSuccessfulLogin();
|
||||
}
|
||||
|
||||
await this.navigateViaCallbackOrRoute(this.onSuccessfulLoginNavigate, [this.successRoute]);
|
||||
}
|
||||
|
||||
private async handleLoginError(e: any) {
|
||||
this.logService.error(e);
|
||||
|
||||
// TODO: Key Connector Service should pass this error message to the logout callback instead of displaying here
|
||||
if (e.message === "Key Connector error") {
|
||||
this.platformUtilsService.showToast(
|
||||
"error",
|
||||
null,
|
||||
this.i18nService.t("ssoKeyConnectorError")
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
private async navigateViaCallbackOrRoute(
|
||||
callback: () => Promise<unknown>,
|
||||
commands: unknown[],
|
||||
extras?: NavigationExtras
|
||||
): Promise<void> {
|
||||
if (callback) {
|
||||
await callback();
|
||||
} else {
|
||||
await this.router.navigate(commands, extras);
|
||||
}
|
||||
this.loggingIn = false;
|
||||
}
|
||||
|
||||
private getOrgIdentifierFromState(state: string): string {
|
||||
|
||||
451
libs/angular/src/auth/components/two-factor.component.spec.ts
Normal file
451
libs/angular/src/auth/components/two-factor.component.spec.ts
Normal file
@@ -0,0 +1,451 @@
|
||||
import { Component } from "@angular/core";
|
||||
import { ComponentFixture, TestBed } from "@angular/core/testing";
|
||||
import { ActivatedRoute, Router, convertToParamMap } from "@angular/router";
|
||||
import { MockProxy, mock } from "jest-mock-extended";
|
||||
|
||||
// eslint-disable-next-line no-restricted-imports
|
||||
import { WINDOW } from "@bitwarden/angular/services/injection-tokens";
|
||||
import { ApiService } from "@bitwarden/common/abstractions/api.service";
|
||||
import { AuthService } from "@bitwarden/common/auth/abstractions/auth.service";
|
||||
import { LoginService } from "@bitwarden/common/auth/abstractions/login.service";
|
||||
import { TwoFactorService } from "@bitwarden/common/auth/abstractions/two-factor.service";
|
||||
import { AuthResult } from "@bitwarden/common/auth/models/domain/auth-result";
|
||||
import { ForceResetPasswordReason } from "@bitwarden/common/auth/models/domain/force-reset-password-reason";
|
||||
import { KeyConnectorUserDecryptionOption } from "@bitwarden/common/auth/models/domain/user-decryption-options/key-connector-user-decryption-option";
|
||||
import { TrustedDeviceUserDecryptionOption } from "@bitwarden/common/auth/models/domain/user-decryption-options/trusted-device-user-decryption-option";
|
||||
import { TokenTwoFactorRequest } from "@bitwarden/common/auth/models/request/identity-token/token-two-factor.request";
|
||||
import { AppIdService } from "@bitwarden/common/platform/abstractions/app-id.service";
|
||||
import { ConfigServiceAbstraction } from "@bitwarden/common/platform/abstractions/config/config.service.abstraction";
|
||||
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 { PlatformUtilsService } from "@bitwarden/common/platform/abstractions/platform-utils.service";
|
||||
import { StateService } from "@bitwarden/common/platform/abstractions/state.service";
|
||||
import { AccountDecryptionOptions } from "@bitwarden/common/platform/models/domain/account";
|
||||
|
||||
import { TwoFactorComponent } from "./two-factor.component";
|
||||
|
||||
// test component that extends the TwoFactorComponent
|
||||
@Component({})
|
||||
class TestTwoFactorComponent extends TwoFactorComponent {}
|
||||
|
||||
interface TwoFactorComponentProtected {
|
||||
trustedDeviceEncRoute: string;
|
||||
changePasswordRoute: string;
|
||||
forcePasswordResetRoute: string;
|
||||
successRoute: string;
|
||||
}
|
||||
|
||||
describe("TwoFactorComponent", () => {
|
||||
let component: TestTwoFactorComponent;
|
||||
let _component: TwoFactorComponentProtected;
|
||||
|
||||
let fixture: ComponentFixture<TestTwoFactorComponent>;
|
||||
|
||||
// Mock Services
|
||||
let mockAuthService: MockProxy<AuthService>;
|
||||
let mockRouter: MockProxy<Router>;
|
||||
let mockI18nService: MockProxy<I18nService>;
|
||||
let mockApiService: MockProxy<ApiService>;
|
||||
let mockPlatformUtilsService: MockProxy<PlatformUtilsService>;
|
||||
let mockWin: MockProxy<Window>;
|
||||
let mockEnvironmentService: MockProxy<EnvironmentService>;
|
||||
let mockStateService: MockProxy<StateService>;
|
||||
let mockLogService: MockProxy<LogService>;
|
||||
let mockTwoFactorService: MockProxy<TwoFactorService>;
|
||||
let mockAppIdService: MockProxy<AppIdService>;
|
||||
let mockLoginService: MockProxy<LoginService>;
|
||||
let mockConfigService: MockProxy<ConfigServiceAbstraction>;
|
||||
|
||||
let mockAcctDecryptionOpts: {
|
||||
noMasterPassword: AccountDecryptionOptions;
|
||||
withMasterPassword: AccountDecryptionOptions;
|
||||
withMasterPasswordAndTrustedDevice: AccountDecryptionOptions;
|
||||
withMasterPasswordAndTrustedDeviceWithManageResetPassword: AccountDecryptionOptions;
|
||||
withMasterPasswordAndKeyConnector: AccountDecryptionOptions;
|
||||
noMasterPasswordWithTrustedDevice: AccountDecryptionOptions;
|
||||
noMasterPasswordWithTrustedDeviceWithManageResetPassword: AccountDecryptionOptions;
|
||||
noMasterPasswordWithKeyConnector: AccountDecryptionOptions;
|
||||
};
|
||||
|
||||
beforeEach(() => {
|
||||
mockAuthService = mock<AuthService>();
|
||||
mockRouter = mock<Router>();
|
||||
mockI18nService = mock<I18nService>();
|
||||
mockApiService = mock<ApiService>();
|
||||
mockPlatformUtilsService = mock<PlatformUtilsService>();
|
||||
mockWin = mock<Window>();
|
||||
mockEnvironmentService = mock<EnvironmentService>();
|
||||
mockStateService = mock<StateService>();
|
||||
mockLogService = mock<LogService>();
|
||||
mockTwoFactorService = mock<TwoFactorService>();
|
||||
mockAppIdService = mock<AppIdService>();
|
||||
mockLoginService = mock<LoginService>();
|
||||
mockConfigService = mock<ConfigServiceAbstraction>();
|
||||
|
||||
mockAcctDecryptionOpts = {
|
||||
noMasterPassword: new AccountDecryptionOptions({
|
||||
hasMasterPassword: false,
|
||||
trustedDeviceOption: undefined,
|
||||
keyConnectorOption: undefined,
|
||||
}),
|
||||
withMasterPassword: new AccountDecryptionOptions({
|
||||
hasMasterPassword: true,
|
||||
trustedDeviceOption: undefined,
|
||||
keyConnectorOption: undefined,
|
||||
}),
|
||||
withMasterPasswordAndTrustedDevice: new AccountDecryptionOptions({
|
||||
hasMasterPassword: true,
|
||||
trustedDeviceOption: new TrustedDeviceUserDecryptionOption(true, false, false),
|
||||
keyConnectorOption: undefined,
|
||||
}),
|
||||
withMasterPasswordAndTrustedDeviceWithManageResetPassword: new AccountDecryptionOptions({
|
||||
hasMasterPassword: true,
|
||||
trustedDeviceOption: new TrustedDeviceUserDecryptionOption(true, false, true),
|
||||
keyConnectorOption: undefined,
|
||||
}),
|
||||
withMasterPasswordAndKeyConnector: new AccountDecryptionOptions({
|
||||
hasMasterPassword: true,
|
||||
trustedDeviceOption: undefined,
|
||||
keyConnectorOption: new KeyConnectorUserDecryptionOption("http://example.com"),
|
||||
}),
|
||||
noMasterPasswordWithTrustedDevice: new AccountDecryptionOptions({
|
||||
hasMasterPassword: false,
|
||||
trustedDeviceOption: new TrustedDeviceUserDecryptionOption(true, false, false),
|
||||
keyConnectorOption: undefined,
|
||||
}),
|
||||
noMasterPasswordWithTrustedDeviceWithManageResetPassword: new AccountDecryptionOptions({
|
||||
hasMasterPassword: false,
|
||||
trustedDeviceOption: new TrustedDeviceUserDecryptionOption(true, false, true),
|
||||
keyConnectorOption: undefined,
|
||||
}),
|
||||
noMasterPasswordWithKeyConnector: new AccountDecryptionOptions({
|
||||
hasMasterPassword: false,
|
||||
trustedDeviceOption: undefined,
|
||||
keyConnectorOption: new KeyConnectorUserDecryptionOption("http://example.com"),
|
||||
}),
|
||||
};
|
||||
|
||||
TestBed.configureTestingModule({
|
||||
declarations: [TestTwoFactorComponent],
|
||||
providers: [
|
||||
{ provide: AuthService, useValue: mockAuthService },
|
||||
{ provide: Router, useValue: mockRouter },
|
||||
{ provide: I18nService, useValue: mockI18nService },
|
||||
{ provide: ApiService, useValue: mockApiService },
|
||||
{ provide: PlatformUtilsService, useValue: mockPlatformUtilsService },
|
||||
{ provide: WINDOW, useValue: mockWin },
|
||||
{ provide: EnvironmentService, useValue: mockEnvironmentService },
|
||||
{ provide: StateService, useValue: mockStateService },
|
||||
{
|
||||
provide: ActivatedRoute,
|
||||
useValue: {
|
||||
snapshot: {
|
||||
// Default to standard 2FA flow - not SSO + 2FA
|
||||
queryParamMap: convertToParamMap({ sso: "false" }),
|
||||
},
|
||||
},
|
||||
},
|
||||
{ provide: LogService, useValue: mockLogService },
|
||||
{ provide: TwoFactorService, useValue: mockTwoFactorService },
|
||||
{ provide: AppIdService, useValue: mockAppIdService },
|
||||
{ provide: LoginService, useValue: mockLoginService },
|
||||
{ provide: ConfigServiceAbstraction, useValue: mockConfigService },
|
||||
],
|
||||
});
|
||||
|
||||
fixture = TestBed.createComponent(TestTwoFactorComponent);
|
||||
component = fixture.componentInstance;
|
||||
_component = component as any;
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
// Reset all mocks after each test
|
||||
jest.resetAllMocks();
|
||||
});
|
||||
|
||||
it("should create", () => {
|
||||
expect(component).toBeTruthy();
|
||||
});
|
||||
|
||||
// Shared tests
|
||||
const testChangePasswordOnSuccessfulLogin = () => {
|
||||
it("navigates to the component's defined change password route when user doesn't have a MP and key connector isn't enabled", async () => {
|
||||
// Act
|
||||
await component.doSubmit();
|
||||
|
||||
// Assert
|
||||
expect(mockRouter.navigate).toHaveBeenCalledTimes(1);
|
||||
expect(mockRouter.navigate).toHaveBeenCalledWith([_component.changePasswordRoute], {
|
||||
queryParams: {
|
||||
identifier: component.orgIdentifier,
|
||||
},
|
||||
});
|
||||
});
|
||||
};
|
||||
|
||||
const testForceResetOnSuccessfulLogin = (reasonString: string) => {
|
||||
it(`navigates to the component's defined forcePasswordResetRoute route when response.forcePasswordReset is ${reasonString}`, async () => {
|
||||
// Act
|
||||
await component.doSubmit();
|
||||
|
||||
// expect(mockRouter.navigate).toHaveBeenCalledTimes(1);
|
||||
expect(mockRouter.navigate).toHaveBeenCalledWith([_component.forcePasswordResetRoute], {
|
||||
queryParams: {
|
||||
identifier: component.orgIdentifier,
|
||||
},
|
||||
});
|
||||
});
|
||||
};
|
||||
|
||||
describe("Standard 2FA scenarios", () => {
|
||||
describe("doSubmit", () => {
|
||||
const token = "testToken";
|
||||
const remember = false;
|
||||
const captchaToken = "testCaptchaToken";
|
||||
|
||||
beforeEach(() => {
|
||||
component.token = token;
|
||||
component.remember = remember;
|
||||
component.captchaToken = captchaToken;
|
||||
|
||||
mockStateService.getAccountDecryptionOptions.mockResolvedValue(
|
||||
mockAcctDecryptionOpts.withMasterPassword
|
||||
);
|
||||
});
|
||||
|
||||
it("calls authService.logInTwoFactor with correct parameters when form is submitted", async () => {
|
||||
// Arrange
|
||||
mockAuthService.logInTwoFactor.mockResolvedValue(new AuthResult());
|
||||
|
||||
// Act
|
||||
await component.doSubmit();
|
||||
|
||||
// Assert
|
||||
expect(mockAuthService.logInTwoFactor).toHaveBeenCalledWith(
|
||||
new TokenTwoFactorRequest(component.selectedProviderType, token, remember),
|
||||
captchaToken
|
||||
);
|
||||
});
|
||||
|
||||
it("should return when handleCaptchaRequired returns true", async () => {
|
||||
// Arrange
|
||||
const captchaSiteKey = "testCaptchaSiteKey";
|
||||
const authResult = new AuthResult();
|
||||
authResult.captchaSiteKey = captchaSiteKey;
|
||||
|
||||
mockAuthService.logInTwoFactor.mockResolvedValue(authResult);
|
||||
|
||||
// Note: the any casts are required b/c typescript cant recognize that
|
||||
// handleCaptureRequired is a method on TwoFactorComponent b/c it is inherited
|
||||
// from the CaptchaProtectedComponent
|
||||
const handleCaptchaRequiredSpy = jest
|
||||
.spyOn<any, any>(component, "handleCaptchaRequired")
|
||||
.mockReturnValue(true);
|
||||
|
||||
// Act
|
||||
const result = await component.doSubmit();
|
||||
|
||||
// Assert
|
||||
expect(handleCaptchaRequiredSpy).toHaveBeenCalled();
|
||||
expect(result).toBeUndefined();
|
||||
});
|
||||
|
||||
it("calls onSuccessfulLogin when defined", async () => {
|
||||
// Arrange
|
||||
component.onSuccessfulLogin = jest.fn().mockResolvedValue(undefined);
|
||||
mockAuthService.logInTwoFactor.mockResolvedValue(new AuthResult());
|
||||
|
||||
// Act
|
||||
await component.doSubmit();
|
||||
|
||||
// Assert
|
||||
expect(component.onSuccessfulLogin).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("calls loginService.clearValues() when login is successful", async () => {
|
||||
// Arrange
|
||||
mockAuthService.logInTwoFactor.mockResolvedValue(new AuthResult());
|
||||
// spy on loginService.clearValues
|
||||
const clearValuesSpy = jest.spyOn(mockLoginService, "clearValues");
|
||||
|
||||
// Act
|
||||
await component.doSubmit();
|
||||
|
||||
// Assert
|
||||
expect(clearValuesSpy).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
describe("Set Master Password scenarios", () => {
|
||||
beforeEach(() => {
|
||||
const authResult = new AuthResult();
|
||||
mockAuthService.logInTwoFactor.mockResolvedValue(authResult);
|
||||
});
|
||||
|
||||
describe("Given user needs to set a master password", () => {
|
||||
beforeEach(() => {
|
||||
// Only need to test the case where the user has no master password to test the primary change mp flow here
|
||||
mockStateService.getAccountDecryptionOptions.mockResolvedValue(
|
||||
mockAcctDecryptionOpts.noMasterPassword
|
||||
);
|
||||
});
|
||||
|
||||
testChangePasswordOnSuccessfulLogin();
|
||||
});
|
||||
|
||||
it("does not navigate to the change password route when the user has key connector even if user has no master password", async () => {
|
||||
mockStateService.getAccountDecryptionOptions.mockResolvedValue(
|
||||
mockAcctDecryptionOpts.noMasterPasswordWithKeyConnector
|
||||
);
|
||||
|
||||
await component.doSubmit();
|
||||
|
||||
expect(mockRouter.navigate).not.toHaveBeenCalledWith([_component.changePasswordRoute], {
|
||||
queryParams: {
|
||||
identifier: component.orgIdentifier,
|
||||
},
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("Force Master Password Reset scenarios", () => {
|
||||
[
|
||||
ForceResetPasswordReason.AdminForcePasswordReset,
|
||||
ForceResetPasswordReason.WeakMasterPassword,
|
||||
].forEach((forceResetPasswordReason) => {
|
||||
const reasonString = ForceResetPasswordReason[forceResetPasswordReason];
|
||||
|
||||
beforeEach(() => {
|
||||
// use standard user with MP because this test is not concerned with password reset.
|
||||
mockStateService.getAccountDecryptionOptions.mockResolvedValue(
|
||||
mockAcctDecryptionOpts.withMasterPassword
|
||||
);
|
||||
|
||||
const authResult = new AuthResult();
|
||||
authResult.forcePasswordReset = forceResetPasswordReason;
|
||||
mockAuthService.logInTwoFactor.mockResolvedValue(authResult);
|
||||
});
|
||||
|
||||
testForceResetOnSuccessfulLogin(reasonString);
|
||||
});
|
||||
});
|
||||
|
||||
it("calls onSuccessfulLoginNavigate when the callback is defined", async () => {
|
||||
// Arrange
|
||||
component.onSuccessfulLoginNavigate = jest.fn().mockResolvedValue(undefined);
|
||||
mockAuthService.logInTwoFactor.mockResolvedValue(new AuthResult());
|
||||
|
||||
// Act
|
||||
await component.doSubmit();
|
||||
|
||||
// Assert
|
||||
expect(component.onSuccessfulLoginNavigate).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("navigates to the component's defined success route when the login is successful and onSuccessfulLoginNavigate is undefined", async () => {
|
||||
mockAuthService.logInTwoFactor.mockResolvedValue(new AuthResult());
|
||||
|
||||
// Act
|
||||
await component.doSubmit();
|
||||
|
||||
// Assert
|
||||
expect(component.onSuccessfulLoginNavigate).not.toBeDefined();
|
||||
|
||||
expect(mockRouter.navigate).toHaveBeenCalledTimes(1);
|
||||
expect(mockRouter.navigate).toHaveBeenCalledWith([_component.successRoute], undefined);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("SSO > 2FA scenarios", () => {
|
||||
beforeEach(() => {
|
||||
const mockActivatedRoute = TestBed.inject(ActivatedRoute);
|
||||
mockActivatedRoute.snapshot.queryParamMap.get = jest.fn().mockReturnValue("true");
|
||||
});
|
||||
|
||||
describe("doSubmit", () => {
|
||||
const token = "testToken";
|
||||
const remember = false;
|
||||
const captchaToken = "testCaptchaToken";
|
||||
|
||||
beforeEach(() => {
|
||||
component.token = token;
|
||||
component.remember = remember;
|
||||
component.captchaToken = captchaToken;
|
||||
});
|
||||
|
||||
describe("Trusted Device Encryption scenarios", () => {
|
||||
beforeEach(() => {
|
||||
mockConfigService.getFeatureFlagBool.mockResolvedValue(true);
|
||||
});
|
||||
|
||||
describe("Given Trusted Device Encryption is enabled and user needs to set a master password", () => {
|
||||
beforeEach(() => {
|
||||
mockStateService.getAccountDecryptionOptions.mockResolvedValue(
|
||||
mockAcctDecryptionOpts.noMasterPasswordWithTrustedDeviceWithManageResetPassword
|
||||
);
|
||||
|
||||
const authResult = new AuthResult();
|
||||
mockAuthService.logInTwoFactor.mockResolvedValue(authResult);
|
||||
});
|
||||
|
||||
testChangePasswordOnSuccessfulLogin();
|
||||
});
|
||||
|
||||
describe("Given Trusted Device Encryption is enabled, user doesn't need to set a MP, and forcePasswordReset is required", () => {
|
||||
[
|
||||
ForceResetPasswordReason.AdminForcePasswordReset,
|
||||
ForceResetPasswordReason.WeakMasterPassword,
|
||||
].forEach((forceResetPasswordReason) => {
|
||||
const reasonString = ForceResetPasswordReason[forceResetPasswordReason];
|
||||
|
||||
beforeEach(() => {
|
||||
// use standard user with MP because this test is not concerned with password reset.
|
||||
mockStateService.getAccountDecryptionOptions.mockResolvedValue(
|
||||
mockAcctDecryptionOpts.withMasterPasswordAndTrustedDevice
|
||||
);
|
||||
|
||||
const authResult = new AuthResult();
|
||||
authResult.forcePasswordReset = forceResetPasswordReason;
|
||||
mockAuthService.logInTwoFactor.mockResolvedValue(authResult);
|
||||
});
|
||||
|
||||
testForceResetOnSuccessfulLogin(reasonString);
|
||||
});
|
||||
});
|
||||
|
||||
describe("Given Trusted Device Encryption is enabled, user doesn't need to set a MP, and forcePasswordReset is not required", () => {
|
||||
let authResult;
|
||||
beforeEach(() => {
|
||||
mockStateService.getAccountDecryptionOptions.mockResolvedValue(
|
||||
mockAcctDecryptionOpts.withMasterPasswordAndTrustedDevice
|
||||
);
|
||||
|
||||
authResult = new AuthResult();
|
||||
authResult.forcePasswordReset = ForceResetPasswordReason.None;
|
||||
mockAuthService.logInTwoFactor.mockResolvedValue(authResult);
|
||||
});
|
||||
|
||||
it("navigates to the component's defined trusted device encryption route when login is successful and onSuccessfulLoginTdeNavigate is undefined", async () => {
|
||||
await component.doSubmit();
|
||||
|
||||
expect(mockRouter.navigate).toHaveBeenCalledTimes(1);
|
||||
expect(mockRouter.navigate).toHaveBeenCalledWith(
|
||||
[_component.trustedDeviceEncRoute],
|
||||
undefined
|
||||
);
|
||||
});
|
||||
|
||||
it("calls onSuccessfulLoginTdeNavigate instead of router.navigate when the callback is defined", async () => {
|
||||
component.onSuccessfulLoginTdeNavigate = jest.fn().mockResolvedValue(undefined);
|
||||
|
||||
await component.doSubmit();
|
||||
|
||||
expect(mockRouter.navigate).not.toHaveBeenCalled();
|
||||
expect(component.onSuccessfulLoginTdeNavigate).toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -1,8 +1,10 @@
|
||||
import { Directive, OnDestroy, OnInit } from "@angular/core";
|
||||
import { ActivatedRoute, Router } from "@angular/router";
|
||||
import { Directive, Inject, OnDestroy, OnInit } from "@angular/core";
|
||||
import { ActivatedRoute, NavigationExtras, Router } from "@angular/router";
|
||||
import * as DuoWebSDK from "duo_web_sdk";
|
||||
import { first } from "rxjs/operators";
|
||||
|
||||
// eslint-disable-next-line no-restricted-imports
|
||||
import { WINDOW } from "@bitwarden/angular/services/injection-tokens";
|
||||
import { ApiService } from "@bitwarden/common/abstractions/api.service";
|
||||
import { AuthService } from "@bitwarden/common/auth/abstractions/auth.service";
|
||||
import { LoginService } from "@bitwarden/common/auth/abstractions/login.service";
|
||||
@@ -10,16 +12,20 @@ import { TwoFactorService } from "@bitwarden/common/auth/abstractions/two-factor
|
||||
import { TwoFactorProviderType } from "@bitwarden/common/auth/enums/two-factor-provider-type";
|
||||
import { AuthResult } from "@bitwarden/common/auth/models/domain/auth-result";
|
||||
import { ForceResetPasswordReason } from "@bitwarden/common/auth/models/domain/force-reset-password-reason";
|
||||
import { TrustedDeviceUserDecryptionOption } from "@bitwarden/common/auth/models/domain/user-decryption-options/trusted-device-user-decryption-option";
|
||||
import { TokenTwoFactorRequest } from "@bitwarden/common/auth/models/request/identity-token/token-two-factor.request";
|
||||
import { TwoFactorEmailRequest } from "@bitwarden/common/auth/models/request/two-factor-email.request";
|
||||
import { TwoFactorProviders } from "@bitwarden/common/auth/services/two-factor.service";
|
||||
import { WebAuthnIFrame } from "@bitwarden/common/auth/webauthn-iframe";
|
||||
import { FeatureFlag } from "@bitwarden/common/enums/feature-flag.enum";
|
||||
import { AppIdService } from "@bitwarden/common/platform/abstractions/app-id.service";
|
||||
import { ConfigServiceAbstraction } from "@bitwarden/common/platform/abstractions/config/config.service.abstraction";
|
||||
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 { PlatformUtilsService } from "@bitwarden/common/platform/abstractions/platform-utils.service";
|
||||
import { StateService } from "@bitwarden/common/platform/abstractions/state.service";
|
||||
import { AccountDecryptionOptions } from "@bitwarden/common/platform/models/domain/account";
|
||||
|
||||
import { CaptchaProtectedComponent } from "./captcha-protected.component";
|
||||
|
||||
@@ -38,11 +44,18 @@ export class TwoFactorComponent extends CaptchaProtectedComponent implements OnI
|
||||
twoFactorEmail: string = null;
|
||||
formPromise: Promise<any>;
|
||||
emailPromise: Promise<any>;
|
||||
identifier: string = null;
|
||||
onSuccessfulLogin: () => Promise<any>;
|
||||
onSuccessfulLoginNavigate: () => Promise<any>;
|
||||
orgIdentifier: string = null;
|
||||
onSuccessfulLogin: () => Promise<void>;
|
||||
onSuccessfulLoginNavigate: () => Promise<void>;
|
||||
|
||||
onSuccessfulLoginTde: () => Promise<void>;
|
||||
onSuccessfulLoginTdeNavigate: () => Promise<void>;
|
||||
|
||||
protected loginRoute = "login";
|
||||
|
||||
protected trustedDeviceEncRoute = "login-initiated";
|
||||
protected changePasswordRoute = "set-password";
|
||||
protected forcePasswordResetRoute = "update-temp-password";
|
||||
protected successRoute = "vault";
|
||||
|
||||
constructor(
|
||||
@@ -51,14 +64,15 @@ export class TwoFactorComponent extends CaptchaProtectedComponent implements OnI
|
||||
protected i18nService: I18nService,
|
||||
protected apiService: ApiService,
|
||||
protected platformUtilsService: PlatformUtilsService,
|
||||
protected win: Window,
|
||||
@Inject(WINDOW) protected win: Window,
|
||||
protected environmentService: EnvironmentService,
|
||||
protected stateService: StateService,
|
||||
protected route: ActivatedRoute,
|
||||
protected logService: LogService,
|
||||
protected twoFactorService: TwoFactorService,
|
||||
protected appIdService: AppIdService,
|
||||
protected loginService: LoginService
|
||||
protected loginService: LoginService,
|
||||
protected configService: ConfigServiceAbstraction
|
||||
) {
|
||||
super(environmentService, i18nService, platformUtilsService);
|
||||
this.webAuthnSupported = this.platformUtilsService.supportsWebAuthn(win);
|
||||
@@ -72,7 +86,7 @@ export class TwoFactorComponent extends CaptchaProtectedComponent implements OnI
|
||||
|
||||
this.route.queryParams.pipe(first()).subscribe((qParams) => {
|
||||
if (qParams.identifier != null) {
|
||||
this.identifier = qParams.identifier;
|
||||
this.orgIdentifier = qParams.identifier;
|
||||
}
|
||||
});
|
||||
|
||||
@@ -196,32 +210,132 @@ export class TwoFactorComponent extends CaptchaProtectedComponent implements OnI
|
||||
new TokenTwoFactorRequest(this.selectedProviderType, this.token, this.remember),
|
||||
this.captchaToken
|
||||
);
|
||||
const response: AuthResult = await this.formPromise;
|
||||
if (this.handleCaptchaRequired(response)) {
|
||||
const authResult: AuthResult = await this.formPromise;
|
||||
|
||||
await this.handleLoginResponse(authResult);
|
||||
}
|
||||
|
||||
private async handleLoginResponse(authResult: AuthResult) {
|
||||
if (this.handleCaptchaRequired(authResult)) {
|
||||
return;
|
||||
}
|
||||
if (this.onSuccessfulLogin != null) {
|
||||
this.loginService.clearValues();
|
||||
|
||||
this.loginService.clearValues();
|
||||
|
||||
const acctDecryptionOpts: AccountDecryptionOptions =
|
||||
await this.stateService.getAccountDecryptionOptions();
|
||||
|
||||
const tdeEnabled = await this.isTrustedDeviceEncEnabled(acctDecryptionOpts.trustedDeviceOption);
|
||||
|
||||
if (tdeEnabled) {
|
||||
return await this.handleTrustedDeviceEncryptionEnabled(
|
||||
authResult,
|
||||
this.orgIdentifier,
|
||||
acctDecryptionOpts
|
||||
);
|
||||
}
|
||||
|
||||
// User must set password if they don't have one and they aren't using either TDE or key connector.
|
||||
const requireSetPassword =
|
||||
!acctDecryptionOpts.hasMasterPassword && acctDecryptionOpts.keyConnectorOption === undefined;
|
||||
|
||||
if (requireSetPassword || authResult.resetMasterPassword) {
|
||||
// Change implies going no password -> password in this case
|
||||
return await this.handleChangePasswordRequired(this.orgIdentifier);
|
||||
}
|
||||
|
||||
// Users can be forced to reset their password via an admin or org policy
|
||||
// disallowing weak passwords
|
||||
if (authResult.forcePasswordReset !== ForceResetPasswordReason.None) {
|
||||
return await this.handleForcePasswordReset(this.orgIdentifier);
|
||||
}
|
||||
|
||||
return await this.handleSuccessfulLogin();
|
||||
}
|
||||
|
||||
private async isTrustedDeviceEncEnabled(
|
||||
trustedDeviceOption: TrustedDeviceUserDecryptionOption
|
||||
): Promise<boolean> {
|
||||
const ssoTo2faFlowActive = this.route.snapshot.queryParamMap.get("sso") === "true";
|
||||
const trustedDeviceEncryptionFeatureActive = await this.configService.getFeatureFlagBool(
|
||||
FeatureFlag.TrustedDeviceEncryption
|
||||
);
|
||||
|
||||
return (
|
||||
ssoTo2faFlowActive &&
|
||||
trustedDeviceEncryptionFeatureActive &&
|
||||
trustedDeviceOption !== undefined
|
||||
);
|
||||
}
|
||||
|
||||
private async handleTrustedDeviceEncryptionEnabled(
|
||||
authResult: AuthResult,
|
||||
orgIdentifier: string,
|
||||
acctDecryptionOpts: AccountDecryptionOptions
|
||||
): Promise<void> {
|
||||
// If user doesn't have a MP, but has reset password permission, they must set a MP
|
||||
if (
|
||||
!acctDecryptionOpts.hasMasterPassword &&
|
||||
acctDecryptionOpts.trustedDeviceOption.hasManageResetPasswordPermission
|
||||
) {
|
||||
// Change implies going no password -> password in this case
|
||||
return await this.handleChangePasswordRequired(orgIdentifier);
|
||||
}
|
||||
|
||||
// Users can be forced to reset their password via an admin or org policy
|
||||
// disallowing weak passwords
|
||||
if (authResult.forcePasswordReset !== ForceResetPasswordReason.None) {
|
||||
return await this.handleForcePasswordReset(orgIdentifier);
|
||||
}
|
||||
|
||||
if (this.onSuccessfulLoginTde != null) {
|
||||
// Note: awaiting this will currently cause a hang on desktop & browser as they will wait for a full sync to complete
|
||||
// before nagivating to the success route.
|
||||
// before navigating to the success route.
|
||||
this.onSuccessfulLoginTde();
|
||||
}
|
||||
|
||||
this.navigateViaCallbackOrRoute(
|
||||
this.onSuccessfulLoginTdeNavigate,
|
||||
// Navigate to TDE page (if user was on trusted device and TDE has decrypted
|
||||
// their user key, the login-initiated guard will redirect them to the vault)
|
||||
[this.trustedDeviceEncRoute]
|
||||
);
|
||||
}
|
||||
|
||||
private async handleChangePasswordRequired(orgIdentifier: string) {
|
||||
await this.router.navigate([this.changePasswordRoute], {
|
||||
queryParams: {
|
||||
identifier: orgIdentifier,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
private async handleForcePasswordReset(orgIdentifier: string) {
|
||||
this.router.navigate([this.forcePasswordResetRoute], {
|
||||
queryParams: {
|
||||
identifier: orgIdentifier,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
private async handleSuccessfulLogin() {
|
||||
if (this.onSuccessfulLogin != null) {
|
||||
// Note: awaiting this will currently cause a hang on desktop & browser as they will wait for a full sync to complete
|
||||
// before navigating to the success route.
|
||||
this.onSuccessfulLogin();
|
||||
}
|
||||
if (response.resetMasterPassword) {
|
||||
this.successRoute = "set-password";
|
||||
}
|
||||
if (response.forcePasswordReset !== ForceResetPasswordReason.None) {
|
||||
this.successRoute = "update-temp-password";
|
||||
}
|
||||
if (this.onSuccessfulLoginNavigate != null) {
|
||||
this.loginService.clearValues();
|
||||
await this.onSuccessfulLoginNavigate();
|
||||
await this.navigateViaCallbackOrRoute(this.onSuccessfulLoginNavigate, [this.successRoute]);
|
||||
}
|
||||
|
||||
private async navigateViaCallbackOrRoute(
|
||||
callback: () => Promise<unknown>,
|
||||
commands: unknown[],
|
||||
extras?: NavigationExtras
|
||||
): Promise<void> {
|
||||
if (callback) {
|
||||
await callback();
|
||||
} else {
|
||||
this.loginService.clearValues();
|
||||
this.router.navigate([this.successRoute], {
|
||||
queryParams: {
|
||||
identifier: this.identifier,
|
||||
},
|
||||
});
|
||||
await this.router.navigate(commands, extras);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -14,7 +14,7 @@ import { MessagingService } from "@bitwarden/common/platform/abstractions/messag
|
||||
import { PlatformUtilsService } from "@bitwarden/common/platform/abstractions/platform-utils.service";
|
||||
import { StateService } from "@bitwarden/common/platform/abstractions/state.service";
|
||||
import { EncString } from "@bitwarden/common/platform/models/domain/enc-string";
|
||||
import { SymmetricCryptoKey } from "@bitwarden/common/platform/models/domain/symmetric-crypto-key";
|
||||
import { MasterKey, UserKey } from "@bitwarden/common/platform/models/domain/symmetric-crypto-key";
|
||||
import { PasswordGenerationServiceAbstraction } from "@bitwarden/common/tools/generator/password";
|
||||
import { Verification } from "@bitwarden/common/types/verification";
|
||||
import { DialogService } from "@bitwarden/components";
|
||||
@@ -94,19 +94,19 @@ export class UpdatePasswordComponent extends BaseChangePasswordComponent {
|
||||
}
|
||||
|
||||
async performSubmitActions(
|
||||
masterPasswordHash: string,
|
||||
key: SymmetricCryptoKey,
|
||||
encKey: [SymmetricCryptoKey, EncString]
|
||||
newMasterKeyHash: string,
|
||||
newMasterKey: MasterKey,
|
||||
newUserKey: [UserKey, EncString]
|
||||
) {
|
||||
try {
|
||||
// Create Request
|
||||
const request = new PasswordRequest();
|
||||
request.masterPasswordHash = await this.cryptoService.hashPassword(
|
||||
request.masterPasswordHash = await this.cryptoService.hashMasterKey(
|
||||
this.currentMasterPassword,
|
||||
null
|
||||
await this.cryptoService.getOrDeriveMasterKey(this.currentMasterPassword)
|
||||
);
|
||||
request.newMasterPasswordHash = masterPasswordHash;
|
||||
request.key = encKey[1].encryptedString;
|
||||
request.newMasterPasswordHash = newMasterKeyHash;
|
||||
request.key = newUserKey[1].encryptedString;
|
||||
|
||||
// Update user's password
|
||||
this.apiService.postPassword(request);
|
||||
|
||||
@@ -16,7 +16,7 @@ import { MessagingService } from "@bitwarden/common/platform/abstractions/messag
|
||||
import { PlatformUtilsService } from "@bitwarden/common/platform/abstractions/platform-utils.service";
|
||||
import { StateService } from "@bitwarden/common/platform/abstractions/state.service";
|
||||
import { EncString } from "@bitwarden/common/platform/models/domain/enc-string";
|
||||
import { SymmetricCryptoKey } from "@bitwarden/common/platform/models/domain/symmetric-crypto-key";
|
||||
import { MasterKey, UserKey } from "@bitwarden/common/platform/models/domain/symmetric-crypto-key";
|
||||
import { PasswordGenerationServiceAbstraction } from "@bitwarden/common/tools/generator/password";
|
||||
import { Verification } from "@bitwarden/common/types/verification";
|
||||
import { SyncService } from "@bitwarden/common/vault/abstractions/sync/sync.service.abstraction";
|
||||
@@ -113,21 +113,27 @@ export class UpdateTempPasswordComponent extends BaseChangePasswordComponent {
|
||||
|
||||
try {
|
||||
// Create new key and hash new password
|
||||
const newKey = await this.cryptoService.makeKey(
|
||||
const newMasterKey = await this.cryptoService.makeMasterKey(
|
||||
this.masterPassword,
|
||||
this.email.trim().toLowerCase(),
|
||||
this.kdf,
|
||||
this.kdfConfig
|
||||
);
|
||||
const newPasswordHash = await this.cryptoService.hashPassword(this.masterPassword, newKey);
|
||||
const newPasswordHash = await this.cryptoService.hashMasterKey(
|
||||
this.masterPassword,
|
||||
newMasterKey
|
||||
);
|
||||
|
||||
// Grab user's current enc key
|
||||
const userEncKey = await this.cryptoService.getEncKey();
|
||||
// Grab user key
|
||||
const userKey = await this.cryptoService.getUserKey();
|
||||
|
||||
// Create new encKey for the User
|
||||
const newEncKey = await this.cryptoService.remakeEncKey(newKey, userEncKey);
|
||||
// Encrypt user key with new master key
|
||||
const newProtectedUserKey = await this.cryptoService.encryptUserKeyWithMasterKey(
|
||||
newMasterKey,
|
||||
userKey
|
||||
);
|
||||
|
||||
await this.performSubmitActions(newPasswordHash, newKey, newEncKey);
|
||||
await this.performSubmitActions(newPasswordHash, newMasterKey, newProtectedUserKey);
|
||||
} catch (e) {
|
||||
this.logService.error(e);
|
||||
}
|
||||
@@ -135,16 +141,16 @@ export class UpdateTempPasswordComponent extends BaseChangePasswordComponent {
|
||||
|
||||
async performSubmitActions(
|
||||
masterPasswordHash: string,
|
||||
key: SymmetricCryptoKey,
|
||||
encKey: [SymmetricCryptoKey, EncString]
|
||||
masterKey: MasterKey,
|
||||
userKey: [UserKey, EncString]
|
||||
) {
|
||||
try {
|
||||
switch (this.reason) {
|
||||
case ForceResetPasswordReason.AdminForcePasswordReset:
|
||||
this.formPromise = this.updateTempPassword(masterPasswordHash, encKey);
|
||||
this.formPromise = this.updateTempPassword(masterPasswordHash, userKey);
|
||||
break;
|
||||
case ForceResetPasswordReason.WeakMasterPassword:
|
||||
this.formPromise = this.updatePassword(masterPasswordHash, encKey);
|
||||
this.formPromise = this.updatePassword(masterPasswordHash, userKey);
|
||||
break;
|
||||
}
|
||||
|
||||
@@ -166,29 +172,23 @@ export class UpdateTempPasswordComponent extends BaseChangePasswordComponent {
|
||||
this.logService.error(e);
|
||||
}
|
||||
}
|
||||
private async updateTempPassword(
|
||||
masterPasswordHash: string,
|
||||
encKey: [SymmetricCryptoKey, EncString]
|
||||
) {
|
||||
private async updateTempPassword(masterPasswordHash: string, userKey: [UserKey, EncString]) {
|
||||
const request = new UpdateTempPasswordRequest();
|
||||
request.key = encKey[1].encryptedString;
|
||||
request.key = userKey[1].encryptedString;
|
||||
request.newMasterPasswordHash = masterPasswordHash;
|
||||
request.masterPasswordHint = this.hint;
|
||||
|
||||
return this.apiService.putUpdateTempPassword(request);
|
||||
}
|
||||
|
||||
private async updatePassword(
|
||||
newMasterPasswordHash: string,
|
||||
encKey: [SymmetricCryptoKey, EncString]
|
||||
) {
|
||||
private async updatePassword(newMasterPasswordHash: string, userKey: [UserKey, EncString]) {
|
||||
const request = await this.userVerificationService.buildRequest(
|
||||
this.verification,
|
||||
PasswordRequest
|
||||
);
|
||||
request.masterPasswordHint = this.hint;
|
||||
request.newMasterPasswordHash = newMasterPasswordHash;
|
||||
request.key = encKey[1].encryptedString;
|
||||
request.key = userKey[1].encryptedString;
|
||||
|
||||
return this.apiService.postPassword(request);
|
||||
}
|
||||
|
||||
@@ -2,16 +2,16 @@ import { Directive, EventEmitter, Input, OnDestroy, OnInit, Output } from "@angu
|
||||
import { ControlValueAccessor, FormControl, Validators } from "@angular/forms";
|
||||
import { Subject, takeUntil } from "rxjs";
|
||||
|
||||
import { KeyConnectorService } from "@bitwarden/common/auth/abstractions/key-connector.service";
|
||||
import { UserVerificationService } from "@bitwarden/common/auth/abstractions/user-verification/user-verification.service.abstraction";
|
||||
import { VerificationType } from "@bitwarden/common/auth/enums/verification-type";
|
||||
import { CryptoService } from "@bitwarden/common/platform/abstractions/crypto.service";
|
||||
import { I18nService } from "@bitwarden/common/platform/abstractions/i18n.service";
|
||||
import { Utils } from "@bitwarden/common/platform/misc/utils";
|
||||
import { Verification } from "@bitwarden/common/types/verification";
|
||||
|
||||
/**
|
||||
* Used for general-purpose user verification throughout the app.
|
||||
* Collects the user's master password, or if they are using Key Connector, prompts for an OTP via email.
|
||||
* Collects the user's master password, or if they are not using a password, prompts for an OTP via email.
|
||||
* This is exposed to the parent component via the ControlValueAccessor interface (e.g. bind it to a FormControl).
|
||||
* Use UserVerificationService to verify the user's input.
|
||||
*/
|
||||
@@ -40,7 +40,7 @@ export class UserVerificationComponent implements ControlValueAccessor, OnInit,
|
||||
}
|
||||
@Output() invalidSecretChange = new EventEmitter<boolean>();
|
||||
|
||||
usesKeyConnector = true;
|
||||
hasMasterPassword = true;
|
||||
disableRequestOTP = false;
|
||||
sentCode = false;
|
||||
|
||||
@@ -50,7 +50,7 @@ export class UserVerificationComponent implements ControlValueAccessor, OnInit,
|
||||
if (this.invalidSecret) {
|
||||
return {
|
||||
invalidSecret: {
|
||||
message: this.usesKeyConnector
|
||||
message: this.hasMasterPassword
|
||||
? this.i18nService.t("incorrectCode")
|
||||
: this.i18nService.t("incorrectPassword"),
|
||||
},
|
||||
@@ -63,13 +63,13 @@ export class UserVerificationComponent implements ControlValueAccessor, OnInit,
|
||||
private destroy$ = new Subject<void>();
|
||||
|
||||
constructor(
|
||||
private keyConnectorService: KeyConnectorService,
|
||||
private cryptoService: CryptoService,
|
||||
private userVerificationService: UserVerificationService,
|
||||
private i18nService: I18nService
|
||||
) {}
|
||||
|
||||
async ngOnInit() {
|
||||
this.usesKeyConnector = await this.keyConnectorService.getUsesKeyConnector();
|
||||
this.hasMasterPassword = await this.userVerificationService.hasMasterPasswordAndMasterKeyHash();
|
||||
this.processChanges(this.secret.value);
|
||||
|
||||
this.secret.valueChanges
|
||||
@@ -78,7 +78,7 @@ export class UserVerificationComponent implements ControlValueAccessor, OnInit,
|
||||
}
|
||||
|
||||
requestOTP = async () => {
|
||||
if (this.usesKeyConnector) {
|
||||
if (!this.hasMasterPassword) {
|
||||
this.disableRequestOTP = true;
|
||||
try {
|
||||
await this.userVerificationService.requestOTP();
|
||||
@@ -123,7 +123,7 @@ export class UserVerificationComponent implements ControlValueAccessor, OnInit,
|
||||
}
|
||||
|
||||
this.onChange({
|
||||
type: this.usesKeyConnector ? VerificationType.OTP : VerificationType.MasterPassword,
|
||||
type: this.hasMasterPassword ? VerificationType.MasterPassword : VerificationType.OTP,
|
||||
secret: Utils.isNullOrWhitespace(secret) ? null : secret,
|
||||
});
|
||||
}
|
||||
|
||||
5
libs/angular/src/auth/guards/index.ts
Normal file
5
libs/angular/src/auth/guards/index.ts
Normal file
@@ -0,0 +1,5 @@
|
||||
export * from "./auth.guard";
|
||||
export * from "./lock.guard";
|
||||
export * from "./redirect.guard";
|
||||
export * from "./tde-decryption-required.guard";
|
||||
export * from "./unauth.guard";
|
||||
@@ -1,25 +1,59 @@
|
||||
import { Injectable } from "@angular/core";
|
||||
import { CanActivate, Router } from "@angular/router";
|
||||
import { inject } from "@angular/core";
|
||||
import {
|
||||
ActivatedRouteSnapshot,
|
||||
CanActivateFn,
|
||||
Router,
|
||||
RouterStateSnapshot,
|
||||
} from "@angular/router";
|
||||
|
||||
import { AuthService } from "@bitwarden/common/auth/abstractions/auth.service";
|
||||
import { DeviceTrustCryptoServiceAbstraction } from "@bitwarden/common/auth/abstractions/device-trust-crypto.service.abstraction";
|
||||
import { UserVerificationService } from "@bitwarden/common/auth/abstractions/user-verification/user-verification.service.abstraction";
|
||||
import { AuthenticationStatus } from "@bitwarden/common/auth/enums/authentication-status";
|
||||
import { CryptoService } from "@bitwarden/common/platform/abstractions/crypto.service";
|
||||
|
||||
@Injectable()
|
||||
export class LockGuard implements CanActivate {
|
||||
protected homepage = "vault";
|
||||
protected loginpage = "login";
|
||||
constructor(private authService: AuthService, private router: Router) {}
|
||||
/**
|
||||
* Only allow access to this route if the vault is locked.
|
||||
* If TDE is enabled then the user must also have had a user key at some point.
|
||||
* Otherwise redirect to root.
|
||||
*/
|
||||
export function lockGuard(): CanActivateFn {
|
||||
return async (
|
||||
activatedRouteSnapshot: ActivatedRouteSnapshot,
|
||||
routerStateSnapshot: RouterStateSnapshot
|
||||
) => {
|
||||
const authService = inject(AuthService);
|
||||
const cryptoService = inject(CryptoService);
|
||||
const deviceTrustCryptoService = inject(DeviceTrustCryptoServiceAbstraction);
|
||||
const router = inject(Router);
|
||||
const userVerificationService = inject(UserVerificationService);
|
||||
|
||||
async canActivate() {
|
||||
const authStatus = await this.authService.getAuthStatus();
|
||||
const authStatus = await authService.getAuthStatus();
|
||||
if (authStatus !== AuthenticationStatus.Locked) {
|
||||
return router.createUrlTree(["/"]);
|
||||
}
|
||||
|
||||
if (authStatus === AuthenticationStatus.Locked) {
|
||||
// User is authN and in locked state.
|
||||
|
||||
const tdeEnabled = await deviceTrustCryptoService.supportsDeviceTrust();
|
||||
|
||||
// Create special exception which allows users to go from the login-initiated page to the lock page for the approve w/ MP flow
|
||||
// The MP check is necessary to prevent direct manual navigation from other locked state pages for users who don't have a MP
|
||||
if (
|
||||
activatedRouteSnapshot.queryParams["from"] === "login-initiated" &&
|
||||
tdeEnabled &&
|
||||
(await userVerificationService.hasMasterPassword())
|
||||
) {
|
||||
return true;
|
||||
}
|
||||
|
||||
const redirectUrl =
|
||||
authStatus === AuthenticationStatus.LoggedOut ? this.loginpage : this.homepage;
|
||||
// If authN user with TDE directly navigates to lock, kick them upwards so redirect guard can
|
||||
// properly route them to the login decryption options component.
|
||||
const everHadUserKey = await cryptoService.getEverHadUserKey();
|
||||
if (tdeEnabled && !everHadUserKey) {
|
||||
return router.createUrlTree(["/"]);
|
||||
}
|
||||
|
||||
return this.router.createUrlTree([redirectUrl]);
|
||||
}
|
||||
return true;
|
||||
};
|
||||
}
|
||||
|
||||
58
libs/angular/src/auth/guards/redirect.guard.ts
Normal file
58
libs/angular/src/auth/guards/redirect.guard.ts
Normal file
@@ -0,0 +1,58 @@
|
||||
import { inject } from "@angular/core";
|
||||
import { CanActivateFn, Router } from "@angular/router";
|
||||
|
||||
import { AuthService } from "@bitwarden/common/auth/abstractions/auth.service";
|
||||
import { DeviceTrustCryptoServiceAbstraction } from "@bitwarden/common/auth/abstractions/device-trust-crypto.service.abstraction";
|
||||
import { AuthenticationStatus } from "@bitwarden/common/auth/enums/authentication-status";
|
||||
import { CryptoService } from "@bitwarden/common/platform/abstractions/crypto.service";
|
||||
|
||||
export interface RedirectRoutes {
|
||||
loggedIn: string;
|
||||
loggedOut: string;
|
||||
locked: string;
|
||||
notDecrypted: string;
|
||||
}
|
||||
|
||||
const defaultRoutes: RedirectRoutes = {
|
||||
loggedIn: "/vault",
|
||||
loggedOut: "/login",
|
||||
locked: "/lock",
|
||||
notDecrypted: "/login-initiated",
|
||||
};
|
||||
|
||||
/**
|
||||
* Guard that consolidates all redirection logic, should be applied to root route.
|
||||
*/
|
||||
export function redirectGuard(overrides: Partial<RedirectRoutes> = {}): CanActivateFn {
|
||||
const routes = { ...defaultRoutes, ...overrides };
|
||||
return async (route) => {
|
||||
const authService = inject(AuthService);
|
||||
const cryptoService = inject(CryptoService);
|
||||
const deviceTrustCryptoService = inject(DeviceTrustCryptoServiceAbstraction);
|
||||
const router = inject(Router);
|
||||
|
||||
const authStatus = await authService.getAuthStatus();
|
||||
|
||||
if (authStatus === AuthenticationStatus.LoggedOut) {
|
||||
return router.createUrlTree([routes.loggedOut], { queryParams: route.queryParams });
|
||||
}
|
||||
|
||||
if (authStatus === AuthenticationStatus.Unlocked) {
|
||||
return router.createUrlTree([routes.loggedIn], { queryParams: route.queryParams });
|
||||
}
|
||||
|
||||
// If locked, TDE is enabled, and the user hasn't decrypted yet, then redirect to the
|
||||
// login decryption options component.
|
||||
const tdeEnabled = await deviceTrustCryptoService.supportsDeviceTrust();
|
||||
const everHadUserKey = await cryptoService.getEverHadUserKey();
|
||||
if (authStatus === AuthenticationStatus.Locked && tdeEnabled && !everHadUserKey) {
|
||||
return router.createUrlTree([routes.notDecrypted], { queryParams: route.queryParams });
|
||||
}
|
||||
|
||||
if (authStatus === AuthenticationStatus.Locked) {
|
||||
return router.createUrlTree([routes.locked], { queryParams: route.queryParams });
|
||||
}
|
||||
|
||||
return router.createUrlTree(["/"]);
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
import { inject } from "@angular/core";
|
||||
import {
|
||||
ActivatedRouteSnapshot,
|
||||
Router,
|
||||
RouterStateSnapshot,
|
||||
CanActivateFn,
|
||||
} from "@angular/router";
|
||||
|
||||
import { AuthService } from "@bitwarden/common/auth/abstractions/auth.service";
|
||||
import { DeviceTrustCryptoServiceAbstraction } from "@bitwarden/common/auth/abstractions/device-trust-crypto.service.abstraction";
|
||||
import { AuthenticationStatus } from "@bitwarden/common/auth/enums/authentication-status";
|
||||
import { CryptoService } from "@bitwarden/common/platform/abstractions/crypto.service";
|
||||
|
||||
/**
|
||||
* Only allow access to this route if the vault is locked and has never been decrypted.
|
||||
* Otherwise redirect to root.
|
||||
*/
|
||||
export function tdeDecryptionRequiredGuard(): CanActivateFn {
|
||||
return async (_: ActivatedRouteSnapshot, state: RouterStateSnapshot) => {
|
||||
const authService = inject(AuthService);
|
||||
const cryptoService = inject(CryptoService);
|
||||
const deviceTrustCryptoService = inject(DeviceTrustCryptoServiceAbstraction);
|
||||
const router = inject(Router);
|
||||
|
||||
const authStatus = await authService.getAuthStatus();
|
||||
const tdeEnabled = await deviceTrustCryptoService.supportsDeviceTrust();
|
||||
const everHadUserKey = await cryptoService.getEverHadUserKey();
|
||||
if (authStatus !== AuthenticationStatus.Locked || !tdeEnabled || everHadUserKey) {
|
||||
return router.createUrlTree(["/"]);
|
||||
}
|
||||
|
||||
return true;
|
||||
};
|
||||
}
|
||||
@@ -271,16 +271,16 @@ export class RegisterComponent extends CaptchaProtectedComponent implements OnIn
|
||||
const hint = this.formGroup.value.hint;
|
||||
const kdf = DEFAULT_KDF_TYPE;
|
||||
const kdfConfig = DEFAULT_KDF_CONFIG;
|
||||
const key = await this.cryptoService.makeKey(masterPassword, email, kdf, kdfConfig);
|
||||
const encKey = await this.cryptoService.makeEncKey(key);
|
||||
const hashedPassword = await this.cryptoService.hashPassword(masterPassword, key);
|
||||
const keys = await this.cryptoService.makeKeyPair(encKey[0]);
|
||||
const key = await this.cryptoService.makeMasterKey(masterPassword, email, kdf, kdfConfig);
|
||||
const newUserKey = await this.cryptoService.makeUserKey(key);
|
||||
const masterKeyHash = await this.cryptoService.hashMasterKey(masterPassword, key);
|
||||
const keys = await this.cryptoService.makeKeyPair(newUserKey[0]);
|
||||
const request = new RegisterRequest(
|
||||
email,
|
||||
name,
|
||||
hashedPassword,
|
||||
masterKeyHash,
|
||||
hint,
|
||||
encKey[1].encryptedString,
|
||||
newUserKey[1].encryptedString,
|
||||
this.referenceData,
|
||||
this.captchaToken,
|
||||
kdf,
|
||||
|
||||
@@ -18,7 +18,7 @@ import { PlatformUtilsService } from "@bitwarden/common/platform/abstractions/pl
|
||||
import { StateService } from "@bitwarden/common/platform/abstractions/state.service";
|
||||
import { Utils } from "@bitwarden/common/platform/misc/utils";
|
||||
import { EncString } from "@bitwarden/common/platform/models/domain/enc-string";
|
||||
import { SymmetricCryptoKey } from "@bitwarden/common/platform/models/domain/symmetric-crypto-key";
|
||||
import { MasterKey, UserKey } from "@bitwarden/common/platform/models/domain/symmetric-crypto-key";
|
||||
import { PasswordGenerationServiceAbstraction } from "@bitwarden/common/tools/generator/password";
|
||||
import { SyncService } from "@bitwarden/common/vault/abstractions/sync/sync.service.abstraction";
|
||||
import { DialogService } from "@bitwarden/components";
|
||||
@@ -101,16 +101,16 @@ export class SetPasswordComponent extends BaseChangePasswordComponent {
|
||||
|
||||
async performSubmitActions(
|
||||
masterPasswordHash: string,
|
||||
key: SymmetricCryptoKey,
|
||||
encKey: [SymmetricCryptoKey, EncString]
|
||||
masterKey: MasterKey,
|
||||
userKey: [UserKey, EncString]
|
||||
) {
|
||||
const keys = await this.cryptoService.makeKeyPair(encKey[0]);
|
||||
const newKeyPair = await this.cryptoService.makeKeyPair(userKey[0]);
|
||||
const request = new SetPasswordRequest(
|
||||
masterPasswordHash,
|
||||
encKey[1].encryptedString,
|
||||
userKey[1].encryptedString,
|
||||
this.hint,
|
||||
this.identifier,
|
||||
new KeysRequest(keys[0], keys[1].encryptedString),
|
||||
new KeysRequest(newKeyPair[0], newKeyPair[1].encryptedString),
|
||||
this.kdf,
|
||||
this.kdfConfig.iterations,
|
||||
this.kdfConfig.memory,
|
||||
@@ -121,7 +121,7 @@ export class SetPasswordComponent extends BaseChangePasswordComponent {
|
||||
this.formPromise = this.apiService
|
||||
.setPassword(request)
|
||||
.then(async () => {
|
||||
await this.onSetPasswordSuccess(key, encKey, keys);
|
||||
await this.onSetPasswordSuccess(masterKey, userKey, newKeyPair);
|
||||
return this.organizationApiService.getKeys(this.orgId);
|
||||
})
|
||||
.then(async (response) => {
|
||||
@@ -131,13 +131,13 @@ export class SetPasswordComponent extends BaseChangePasswordComponent {
|
||||
const userId = await this.stateService.getUserId();
|
||||
const publicKey = Utils.fromB64ToArray(response.publicKey);
|
||||
|
||||
// RSA Encrypt user's encKey.key with organization public key
|
||||
const userEncKey = await this.cryptoService.getEncKey();
|
||||
const encryptedKey = await this.cryptoService.rsaEncrypt(userEncKey.key, publicKey);
|
||||
// RSA Encrypt user key with organization public key
|
||||
const userKey = await this.cryptoService.getUserKey();
|
||||
const encryptedUserKey = await this.cryptoService.rsaEncrypt(userKey.key, publicKey);
|
||||
|
||||
const resetRequest = new OrganizationUserResetPasswordEnrollmentRequest();
|
||||
resetRequest.masterPasswordHash = masterPasswordHash;
|
||||
resetRequest.resetPasswordKey = encryptedKey.encryptedString;
|
||||
resetRequest.resetPasswordKey = encryptedUserKey.encryptedString;
|
||||
|
||||
return this.organizationUserService.putOrganizationUserResetPasswordEnrollment(
|
||||
this.orgId,
|
||||
@@ -147,7 +147,7 @@ export class SetPasswordComponent extends BaseChangePasswordComponent {
|
||||
});
|
||||
} else {
|
||||
this.formPromise = this.apiService.setPassword(request).then(async () => {
|
||||
await this.onSetPasswordSuccess(key, encKey, keys);
|
||||
await this.onSetPasswordSuccess(masterKey, userKey, newKeyPair);
|
||||
});
|
||||
}
|
||||
|
||||
@@ -169,21 +169,21 @@ export class SetPasswordComponent extends BaseChangePasswordComponent {
|
||||
}
|
||||
|
||||
private async onSetPasswordSuccess(
|
||||
key: SymmetricCryptoKey,
|
||||
encKey: [SymmetricCryptoKey, EncString],
|
||||
keys: [string, EncString]
|
||||
masterKey: MasterKey,
|
||||
userKey: [UserKey, EncString],
|
||||
keyPair: [string, EncString]
|
||||
) {
|
||||
await this.stateService.setKdfType(this.kdf);
|
||||
await this.stateService.setKdfConfig(this.kdfConfig);
|
||||
await this.cryptoService.setKey(key);
|
||||
await this.cryptoService.setEncKey(encKey[1].encryptedString);
|
||||
await this.cryptoService.setEncPrivateKey(keys[1].encryptedString);
|
||||
await this.cryptoService.setMasterKey(masterKey);
|
||||
await this.cryptoService.setUserKey(userKey[0]);
|
||||
await this.cryptoService.setPrivateKey(keyPair[1].encryptedString);
|
||||
|
||||
const localKeyHash = await this.cryptoService.hashPassword(
|
||||
const localMasterKeyHash = await this.cryptoService.hashMasterKey(
|
||||
this.masterPassword,
|
||||
key,
|
||||
masterKey,
|
||||
HashPurpose.LocalAuthorization
|
||||
);
|
||||
await this.cryptoService.setKeyHash(localKeyHash);
|
||||
await this.cryptoService.setMasterKeyHash(localMasterKeyHash);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { Directive, OnInit } from "@angular/core";
|
||||
|
||||
import { KeyConnectorService } from "@bitwarden/common/auth/abstractions/key-connector.service";
|
||||
import { UserVerificationService } from "@bitwarden/common/auth/abstractions/user-verification/user-verification.service.abstraction";
|
||||
import { KeySuffixOptions } from "@bitwarden/common/enums/key-suffix-options.enum";
|
||||
import { CryptoService } from "@bitwarden/common/platform/abstractions/crypto.service";
|
||||
import { StateService } from "@bitwarden/common/platform/abstractions/state.service";
|
||||
import { Utils } from "@bitwarden/common/platform/misc/utils";
|
||||
@@ -17,13 +18,13 @@ export class SetPinComponent implements OnInit {
|
||||
constructor(
|
||||
private modalRef: ModalRef,
|
||||
private cryptoService: CryptoService,
|
||||
private keyConnectorService: KeyConnectorService,
|
||||
private userVerificationService: UserVerificationService,
|
||||
private stateService: StateService
|
||||
) {}
|
||||
|
||||
async ngOnInit() {
|
||||
this.showMasterPassOnRestart = this.masterPassOnRestart =
|
||||
!(await this.keyConnectorService.getUsesKeyConnector());
|
||||
await this.userVerificationService.hasMasterPassword();
|
||||
}
|
||||
|
||||
toggleVisibility() {
|
||||
@@ -35,19 +36,22 @@ export class SetPinComponent implements OnInit {
|
||||
this.modalRef.close(false);
|
||||
}
|
||||
|
||||
const kdf = await this.stateService.getKdfType();
|
||||
const kdfConfig = await this.stateService.getKdfConfig();
|
||||
const email = await this.stateService.getEmail();
|
||||
const pinKey = await this.cryptoService.makePinKey(this.pin, email, kdf, kdfConfig);
|
||||
const key = await this.cryptoService.getKey();
|
||||
const pinProtectedKey = await this.cryptoService.encrypt(key.key, pinKey);
|
||||
const pinKey = await this.cryptoService.makePinKey(
|
||||
this.pin,
|
||||
await this.stateService.getEmail(),
|
||||
await this.stateService.getKdfType(),
|
||||
await this.stateService.getKdfConfig()
|
||||
);
|
||||
const userKey = await this.cryptoService.getUserKey();
|
||||
const pinProtectedKey = await this.cryptoService.encrypt(userKey.key, pinKey);
|
||||
const encPin = await this.cryptoService.encrypt(this.pin, userKey);
|
||||
await this.stateService.setProtectedPin(encPin.encryptedString);
|
||||
if (this.masterPassOnRestart) {
|
||||
const encPin = await this.cryptoService.encrypt(this.pin);
|
||||
await this.stateService.setProtectedPin(encPin.encryptedString);
|
||||
await this.stateService.setDecryptedPinProtected(pinProtectedKey);
|
||||
await this.stateService.setPinKeyEncryptedUserKeyEphemeral(pinProtectedKey);
|
||||
} else {
|
||||
await this.stateService.setEncryptedPinProtected(pinProtectedKey.encryptedString);
|
||||
await this.stateService.setPinKeyEncryptedUserKey(pinProtectedKey);
|
||||
}
|
||||
await this.cryptoService.clearDeprecatedKeys(KeySuffixOptions.Pin);
|
||||
|
||||
this.modalRef.close(true);
|
||||
}
|
||||
|
||||
@@ -6,11 +6,13 @@ import {
|
||||
ValidationErrors,
|
||||
Validator,
|
||||
} from "@angular/forms";
|
||||
import { filter, Subject, takeUntil } from "rxjs";
|
||||
import { filter, map, Observable, Subject, takeUntil } from "rxjs";
|
||||
|
||||
import { VaultTimeoutSettingsService } from "@bitwarden/common/abstractions/vault-timeout/vault-timeout-settings.service";
|
||||
import { PolicyService } from "@bitwarden/common/admin-console/abstractions/policy/policy.service.abstraction";
|
||||
import { PolicyType } from "@bitwarden/common/admin-console/enums";
|
||||
import { Policy } from "@bitwarden/common/admin-console/models/domain/policy";
|
||||
import { VaultTimeoutAction } from "@bitwarden/common/enums/vault-timeout-action.enum";
|
||||
import { I18nService } from "@bitwarden/common/platform/abstractions/i18n.service";
|
||||
|
||||
@Directive()
|
||||
@@ -43,6 +45,8 @@ export class VaultTimeoutInputComponent
|
||||
vaultTimeoutPolicyHours: number;
|
||||
vaultTimeoutPolicyMinutes: number;
|
||||
|
||||
protected canLockVault$: Observable<boolean>;
|
||||
|
||||
private onChange: (vaultTimeout: number) => void;
|
||||
private validatorChange: () => void;
|
||||
private destroy$ = new Subject<void>();
|
||||
@@ -50,6 +54,7 @@ export class VaultTimeoutInputComponent
|
||||
constructor(
|
||||
private formBuilder: FormBuilder,
|
||||
private policyService: PolicyService,
|
||||
private vaultTimeoutSettingsService: VaultTimeoutSettingsService,
|
||||
private i18nService: I18nService
|
||||
) {}
|
||||
|
||||
@@ -86,6 +91,10 @@ export class VaultTimeoutInputComponent
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
this.canLockVault$ = this.vaultTimeoutSettingsService
|
||||
.availableVaultTimeoutActions$()
|
||||
.pipe(map((actions) => actions.includes(VaultTimeoutAction.Lock)));
|
||||
}
|
||||
|
||||
ngOnDestroy() {
|
||||
|
||||
@@ -11,10 +11,12 @@ export const MEMORY_STORAGE = new InjectionToken<AbstractMemoryStorageService>("
|
||||
export const SECURE_STORAGE = new InjectionToken<AbstractStorageService>("SECURE_STORAGE");
|
||||
export const STATE_FACTORY = new InjectionToken<StateFactory>("STATE_FACTORY");
|
||||
export const STATE_SERVICE_USE_CACHE = new InjectionToken<boolean>("STATE_SERVICE_USE_CACHE");
|
||||
export const LOGOUT_CALLBACK = new InjectionToken<(expired: boolean, userId?: string) => void>(
|
||||
"LOGOUT_CALLBACK"
|
||||
export const LOGOUT_CALLBACK = new InjectionToken<
|
||||
(expired: boolean, userId?: string) => Promise<void>
|
||||
>("LOGOUT_CALLBACK");
|
||||
export const LOCKED_CALLBACK = new InjectionToken<(userId?: string) => Promise<void>>(
|
||||
"LOCKED_CALLBACK"
|
||||
);
|
||||
export const LOCKED_CALLBACK = new InjectionToken<() => void>("LOCKED_CALLBACK");
|
||||
export const CLIENT_TYPE = new InjectionToken<boolean>("CLIENT_TYPE");
|
||||
export const LOCALES_DIRECTORY = new InjectionToken<string>("LOCALES_DIRECTORY");
|
||||
export const SYSTEM_LANGUAGE = new InjectionToken<string>("SYSTEM_LANGUAGE");
|
||||
|
||||
@@ -4,8 +4,7 @@ import { AvatarUpdateService as AccountUpdateServiceAbstraction } from "@bitward
|
||||
import { AnonymousHubService as AnonymousHubServiceAbstraction } from "@bitwarden/common/abstractions/anonymousHub.service";
|
||||
import { ApiService as ApiServiceAbstraction } from "@bitwarden/common/abstractions/api.service";
|
||||
import { AuditService as AuditServiceAbstraction } from "@bitwarden/common/abstractions/audit.service";
|
||||
import { DeviceCryptoServiceAbstraction } from "@bitwarden/common/abstractions/device-crypto.service.abstraction";
|
||||
import { DevicesApiServiceAbstraction } from "@bitwarden/common/abstractions/devices/devices-api.service.abstraction";
|
||||
import { DevicesServiceAbstraction } from "@bitwarden/common/abstractions/devices/devices.service.abstraction";
|
||||
import { EventCollectionService as EventCollectionServiceAbstraction } from "@bitwarden/common/abstractions/event/event-collection.service";
|
||||
import { EventUploadService as EventUploadServiceAbstraction } from "@bitwarden/common/abstractions/event/event-upload.service";
|
||||
import { NotificationsService as NotificationsServiceAbstraction } from "@bitwarden/common/abstractions/notifications.service";
|
||||
@@ -18,8 +17,8 @@ import { OrganizationUserService } from "@bitwarden/common/abstractions/organiza
|
||||
import { SearchService as SearchServiceAbstraction } from "@bitwarden/common/abstractions/search.service";
|
||||
import { SettingsService as SettingsServiceAbstraction } from "@bitwarden/common/abstractions/settings.service";
|
||||
import { TotpService as TotpServiceAbstraction } from "@bitwarden/common/abstractions/totp.service";
|
||||
import { VaultTimeoutService as VaultTimeoutServiceAbstraction } from "@bitwarden/common/abstractions/vaultTimeout/vaultTimeout.service";
|
||||
import { VaultTimeoutSettingsService as VaultTimeoutSettingsServiceAbstraction } from "@bitwarden/common/abstractions/vaultTimeout/vaultTimeoutSettings.service";
|
||||
import { VaultTimeoutSettingsService as VaultTimeoutSettingsServiceAbstraction } from "@bitwarden/common/abstractions/vault-timeout/vault-timeout-settings.service";
|
||||
import { VaultTimeoutService as VaultTimeoutServiceAbstraction } from "@bitwarden/common/abstractions/vault-timeout/vault-timeout.service";
|
||||
import { OrganizationApiServiceAbstraction } from "@bitwarden/common/admin-console/abstractions/organization/organization-api.service.abstraction";
|
||||
import {
|
||||
InternalOrganizationServiceAbstraction,
|
||||
@@ -41,18 +40,26 @@ import {
|
||||
AccountService as AccountServiceAbstraction,
|
||||
InternalAccountService,
|
||||
} from "@bitwarden/common/auth/abstractions/account.service";
|
||||
import { AuthRequestCryptoServiceAbstraction } from "@bitwarden/common/auth/abstractions/auth-request-crypto.service.abstraction";
|
||||
import { AuthService as AuthServiceAbstraction } from "@bitwarden/common/auth/abstractions/auth.service";
|
||||
import { DeviceTrustCryptoServiceAbstraction } from "@bitwarden/common/auth/abstractions/device-trust-crypto.service.abstraction";
|
||||
import { DevicesApiServiceAbstraction } from "@bitwarden/common/auth/abstractions/devices-api.service.abstraction";
|
||||
import { KeyConnectorService as KeyConnectorServiceAbstraction } from "@bitwarden/common/auth/abstractions/key-connector.service";
|
||||
import { LoginService as LoginServiceAbstraction } from "@bitwarden/common/auth/abstractions/login.service";
|
||||
import { PasswordResetEnrollmentServiceAbstraction } from "@bitwarden/common/auth/abstractions/password-reset-enrollment.service.abstraction";
|
||||
import { TokenService as TokenServiceAbstraction } from "@bitwarden/common/auth/abstractions/token.service";
|
||||
import { TwoFactorService as TwoFactorServiceAbstraction } from "@bitwarden/common/auth/abstractions/two-factor.service";
|
||||
import { UserVerificationApiServiceAbstraction } from "@bitwarden/common/auth/abstractions/user-verification/user-verification-api.service.abstraction";
|
||||
import { UserVerificationService as UserVerificationServiceAbstraction } from "@bitwarden/common/auth/abstractions/user-verification/user-verification.service.abstraction";
|
||||
import { AccountApiServiceImplementation } from "@bitwarden/common/auth/services/account-api.service";
|
||||
import { AccountServiceImplementation } from "@bitwarden/common/auth/services/account.service";
|
||||
import { AuthRequestCryptoServiceImplementation } from "@bitwarden/common/auth/services/auth-request-crypto.service.implementation";
|
||||
import { AuthService } from "@bitwarden/common/auth/services/auth.service";
|
||||
import { DeviceTrustCryptoService } from "@bitwarden/common/auth/services/device-trust-crypto.service.implementation";
|
||||
import { DevicesApiServiceImplementation } from "@bitwarden/common/auth/services/devices-api.service.implementation";
|
||||
import { KeyConnectorService } from "@bitwarden/common/auth/services/key-connector.service";
|
||||
import { LoginService } from "@bitwarden/common/auth/services/login.service";
|
||||
import { PasswordResetEnrollmentServiceImplementation } from "@bitwarden/common/auth/services/password-reset-enrollment.service.implementation";
|
||||
import { TokenService } from "@bitwarden/common/auth/services/token.service";
|
||||
import { TwoFactorService } from "@bitwarden/common/auth/services/two-factor.service";
|
||||
import { UserVerificationApiService } from "@bitwarden/common/auth/services/user-verification/user-verification-api.service";
|
||||
@@ -95,8 +102,7 @@ import { AvatarUpdateService } from "@bitwarden/common/services/account/avatar-u
|
||||
import { AnonymousHubService } from "@bitwarden/common/services/anonymousHub.service";
|
||||
import { ApiService } from "@bitwarden/common/services/api.service";
|
||||
import { AuditService } from "@bitwarden/common/services/audit.service";
|
||||
import { DeviceCryptoService } from "@bitwarden/common/services/device-crypto.service.implementation";
|
||||
import { DevicesApiServiceImplementation } from "@bitwarden/common/services/devices/devices-api.service.implementation";
|
||||
import { DevicesServiceImplementation } from "@bitwarden/common/services/devices/devices.service.implementation";
|
||||
import { EventCollectionService } from "@bitwarden/common/services/event/event-collection.service";
|
||||
import { EventUploadService } from "@bitwarden/common/services/event/event-upload.service";
|
||||
import { NotificationsService } from "@bitwarden/common/services/notifications.service";
|
||||
@@ -106,8 +112,8 @@ import { OrganizationUserServiceImplementation } from "@bitwarden/common/service
|
||||
import { SearchService } from "@bitwarden/common/services/search.service";
|
||||
import { SettingsService } from "@bitwarden/common/services/settings.service";
|
||||
import { TotpService } from "@bitwarden/common/services/totp.service";
|
||||
import { VaultTimeoutService } from "@bitwarden/common/services/vaultTimeout/vaultTimeout.service";
|
||||
import { VaultTimeoutSettingsService } from "@bitwarden/common/services/vaultTimeout/vaultTimeoutSettings.service";
|
||||
import { VaultTimeoutSettingsService } from "@bitwarden/common/services/vault-timeout/vault-timeout-settings.service";
|
||||
import { VaultTimeoutService } from "@bitwarden/common/services/vault-timeout/vault-timeout.service";
|
||||
import {
|
||||
PasswordGenerationService,
|
||||
PasswordGenerationServiceAbstraction,
|
||||
@@ -148,7 +154,6 @@ import {
|
||||
} from "@bitwarden/exporter/vault-export";
|
||||
|
||||
import { AuthGuard } from "../auth/guards/auth.guard";
|
||||
import { LockGuard } from "../auth/guards/lock.guard";
|
||||
import { UnauthGuard } from "../auth/guards/unauth.guard";
|
||||
import { FormValidationErrorsService as FormValidationErrorsServiceAbstraction } from "../platform/abstractions/form-validation-errors.service";
|
||||
import { BroadcasterService } from "../platform/services/broadcaster.service";
|
||||
@@ -176,7 +181,6 @@ import { AbstractThemingService } from "./theming/theming.service.abstraction";
|
||||
providers: [
|
||||
AuthGuard,
|
||||
UnauthGuard,
|
||||
LockGuard,
|
||||
ModalService,
|
||||
{ provide: WINDOW, useValue: window },
|
||||
{
|
||||
@@ -245,6 +249,8 @@ import { AbstractThemingService } from "./theming/theming.service.abstraction";
|
||||
EncryptService,
|
||||
PasswordStrengthServiceAbstraction,
|
||||
PolicyServiceAbstraction,
|
||||
DeviceTrustCryptoServiceAbstraction,
|
||||
AuthRequestCryptoServiceAbstraction,
|
||||
],
|
||||
},
|
||||
{
|
||||
@@ -441,11 +447,40 @@ import { AbstractThemingService } from "./theming/theming.service.abstraction";
|
||||
TokenServiceAbstraction,
|
||||
PolicyServiceAbstraction,
|
||||
StateServiceAbstraction,
|
||||
UserVerificationServiceAbstraction,
|
||||
],
|
||||
},
|
||||
{
|
||||
provide: VaultTimeoutServiceAbstraction,
|
||||
useClass: VaultTimeoutService,
|
||||
provide: VaultTimeoutService,
|
||||
useFactory: (
|
||||
cipherService: CipherServiceAbstraction,
|
||||
folderService: FolderServiceAbstraction,
|
||||
collectionService: CollectionServiceAbstraction,
|
||||
cryptoService: CryptoServiceAbstraction,
|
||||
platformUtilsService: PlatformUtilsServiceAbstraction,
|
||||
messagingService: MessagingServiceAbstraction,
|
||||
searchService: SearchServiceAbstraction,
|
||||
stateService: StateServiceAbstraction,
|
||||
authService: AuthServiceAbstraction,
|
||||
vaultTimeoutSettingsService: VaultTimeoutSettingsServiceAbstraction,
|
||||
lockedCallback: (userId?: string) => Promise<void>,
|
||||
logoutCallback: (expired: boolean, userId?: string) => Promise<void>
|
||||
) => {
|
||||
return new VaultTimeoutService(
|
||||
cipherService,
|
||||
folderService,
|
||||
collectionService,
|
||||
cryptoService,
|
||||
platformUtilsService,
|
||||
messagingService,
|
||||
searchService,
|
||||
stateService,
|
||||
authService,
|
||||
vaultTimeoutSettingsService,
|
||||
lockedCallback,
|
||||
logoutCallback
|
||||
);
|
||||
},
|
||||
deps: [
|
||||
CipherServiceAbstraction,
|
||||
FolderServiceAbstraction,
|
||||
@@ -454,7 +489,6 @@ import { AbstractThemingService } from "./theming/theming.service.abstraction";
|
||||
PlatformUtilsServiceAbstraction,
|
||||
MessagingServiceAbstraction,
|
||||
SearchServiceAbstraction,
|
||||
KeyConnectorServiceAbstraction,
|
||||
StateServiceAbstraction,
|
||||
AuthServiceAbstraction,
|
||||
VaultTimeoutSettingsServiceAbstraction,
|
||||
@@ -462,6 +496,10 @@ import { AbstractThemingService } from "./theming/theming.service.abstraction";
|
||||
LOGOUT_CALLBACK,
|
||||
],
|
||||
},
|
||||
{
|
||||
provide: VaultTimeoutServiceAbstraction,
|
||||
useExisting: VaultTimeoutService,
|
||||
},
|
||||
{
|
||||
provide: StateServiceAbstraction,
|
||||
useClass: StateService,
|
||||
@@ -571,6 +609,7 @@ import { AbstractThemingService } from "./theming/theming.service.abstraction";
|
||||
provide: UserVerificationServiceAbstraction,
|
||||
useClass: UserVerificationService,
|
||||
deps: [
|
||||
StateServiceAbstraction,
|
||||
CryptoServiceAbstraction,
|
||||
I18nServiceAbstraction,
|
||||
UserVerificationApiServiceAbstraction,
|
||||
@@ -591,6 +630,17 @@ import { AbstractThemingService } from "./theming/theming.service.abstraction";
|
||||
useClass: OrganizationUserServiceImplementation,
|
||||
deps: [ApiServiceAbstraction],
|
||||
},
|
||||
{
|
||||
provide: PasswordResetEnrollmentServiceAbstraction,
|
||||
useClass: PasswordResetEnrollmentServiceImplementation,
|
||||
deps: [
|
||||
OrganizationApiServiceAbstraction,
|
||||
StateServiceAbstraction,
|
||||
CryptoServiceAbstraction,
|
||||
OrganizationUserService,
|
||||
I18nServiceAbstraction,
|
||||
],
|
||||
},
|
||||
{
|
||||
provide: ProviderServiceAbstraction,
|
||||
useClass: ProviderService,
|
||||
@@ -677,8 +727,13 @@ import { AbstractThemingService } from "./theming/theming.service.abstraction";
|
||||
deps: [ApiServiceAbstraction],
|
||||
},
|
||||
{
|
||||
provide: DeviceCryptoServiceAbstraction,
|
||||
useClass: DeviceCryptoService,
|
||||
provide: DevicesServiceAbstraction,
|
||||
useClass: DevicesServiceImplementation,
|
||||
deps: [DevicesApiServiceAbstraction],
|
||||
},
|
||||
{
|
||||
provide: DeviceTrustCryptoServiceAbstraction,
|
||||
useClass: DeviceTrustCryptoService,
|
||||
deps: [
|
||||
CryptoFunctionServiceAbstraction,
|
||||
CryptoServiceAbstraction,
|
||||
@@ -686,8 +741,15 @@ import { AbstractThemingService } from "./theming/theming.service.abstraction";
|
||||
StateServiceAbstraction,
|
||||
AppIdServiceAbstraction,
|
||||
DevicesApiServiceAbstraction,
|
||||
I18nServiceAbstraction,
|
||||
PlatformUtilsServiceAbstraction,
|
||||
],
|
||||
},
|
||||
{
|
||||
provide: AuthRequestCryptoServiceAbstraction,
|
||||
useClass: AuthRequestCryptoServiceImplementation,
|
||||
deps: [CryptoServiceAbstraction],
|
||||
},
|
||||
],
|
||||
})
|
||||
export class JslibServicesModule {}
|
||||
|
||||
@@ -191,7 +191,7 @@ export class AttachmentsComponent implements OnInit {
|
||||
this.cipherDomain = await this.loadCipher();
|
||||
this.cipher = await this.cipherDomain.decrypt();
|
||||
|
||||
this.hasUpdatedKey = await this.cryptoService.hasEncKey();
|
||||
this.hasUpdatedKey = await this.cryptoService.hasUserKey();
|
||||
const canAccessPremium = await this.stateService.getCanAccessPremium();
|
||||
this.canAccessAttachments = canAccessPremium || this.cipher.organizationId != null;
|
||||
|
||||
|
||||
@@ -0,0 +1,34 @@
|
||||
import { MockProxy, mock } from "jest-mock-extended";
|
||||
|
||||
import { UserVerificationService } from "@bitwarden/common/auth/abstractions/user-verification/user-verification.service.abstraction";
|
||||
|
||||
import { ModalService } from "../../services/modal.service";
|
||||
|
||||
import { PasswordRepromptService } from "./password-reprompt.service";
|
||||
|
||||
describe("PasswordRepromptService", () => {
|
||||
let passwordRepromptService: PasswordRepromptService;
|
||||
|
||||
let userVerificationService: MockProxy<UserVerificationService>;
|
||||
let modalService: MockProxy<ModalService>;
|
||||
|
||||
beforeEach(() => {
|
||||
modalService = mock<ModalService>();
|
||||
userVerificationService = mock<UserVerificationService>();
|
||||
|
||||
passwordRepromptService = new PasswordRepromptService(modalService, userVerificationService);
|
||||
});
|
||||
|
||||
describe("enabled()", () => {
|
||||
it("returns false if a user does not have a master password", async () => {
|
||||
userVerificationService.hasMasterPasswordAndMasterKeyHash.mockResolvedValue(false);
|
||||
|
||||
expect(await passwordRepromptService.enabled()).toBe(false);
|
||||
});
|
||||
it("returns true if the user has a master password", async () => {
|
||||
userVerificationService.hasMasterPasswordAndMasterKeyHash.mockResolvedValue(true);
|
||||
|
||||
expect(await passwordRepromptService.enabled()).toBe(true);
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -1,6 +1,6 @@
|
||||
import { Injectable } from "@angular/core";
|
||||
|
||||
import { KeyConnectorService } from "@bitwarden/common/auth/abstractions/key-connector.service";
|
||||
import { UserVerificationService } from "@bitwarden/common/auth/abstractions/user-verification/user-verification.service.abstraction";
|
||||
import { PasswordRepromptService as PasswordRepromptServiceAbstraction } from "@bitwarden/common/vault/abstractions/password-reprompt.service";
|
||||
|
||||
import { ModalService } from "../../services/modal.service";
|
||||
@@ -16,7 +16,7 @@ export class PasswordRepromptService implements PasswordRepromptServiceAbstracti
|
||||
|
||||
constructor(
|
||||
private modalService: ModalService,
|
||||
private keyConnectorService: KeyConnectorService
|
||||
private userVerificationService: UserVerificationService
|
||||
) {}
|
||||
|
||||
protectedFields() {
|
||||
@@ -39,6 +39,6 @@ export class PasswordRepromptService implements PasswordRepromptServiceAbstracti
|
||||
}
|
||||
|
||||
async enabled() {
|
||||
return !(await this.keyConnectorService.getUsesKeyConnector());
|
||||
return await this.userVerificationService.hasMasterPasswordAndMasterKeyHash();
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user