diff --git a/apps/browser/src/auth/popup/lock.component.ts b/apps/browser/src/auth/popup/lock.component.ts index 75fcfc58f6..c7fb108de8 100644 --- a/apps/browser/src/auth/popup/lock.component.ts +++ b/apps/browser/src/auth/popup/lock.component.ts @@ -16,7 +16,6 @@ import { KdfConfigService } from "@bitwarden/common/auth/abstractions/kdf-config import { InternalMasterPasswordServiceAbstraction } from "@bitwarden/common/auth/abstractions/master-password.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"; 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"; @@ -26,7 +25,7 @@ import { StateService } from "@bitwarden/common/platform/abstractions/state.serv import { PasswordStrengthServiceAbstraction } from "@bitwarden/common/tools/password-strength"; import { SyncService } from "@bitwarden/common/vault/abstractions/sync/sync.service.abstraction"; import { DialogService, ToastService } from "@bitwarden/components"; -import { BiometricsService, BiometricStateService } from "@bitwarden/key-management"; +import { KeyService, BiometricsService, BiometricStateService } from "@bitwarden/key-management"; import { BiometricErrors, BiometricErrorTypes } from "../../models/biometricErrors"; import { BrowserRouterService } from "../../platform/popup/services/browser-router.service"; @@ -49,7 +48,7 @@ export class LockComponent extends BaseLockComponent implements OnInit { i18nService: I18nService, platformUtilsService: PlatformUtilsService, messagingService: MessagingService, - cryptoService: CryptoService, + keyService: KeyService, vaultTimeoutService: VaultTimeoutService, vaultTimeoutSettingsService: VaultTimeoutSettingsService, environmentService: EnvironmentService, @@ -79,7 +78,7 @@ export class LockComponent extends BaseLockComponent implements OnInit { i18nService, platformUtilsService, messagingService, - cryptoService, + keyService, vaultTimeoutService, vaultTimeoutSettingsService, environmentService, diff --git a/apps/browser/src/auth/popup/login-via-auth-request.component.ts b/apps/browser/src/auth/popup/login-via-auth-request.component.ts index 33ec2acf38..9dc0d7d545 100644 --- a/apps/browser/src/auth/popup/login-via-auth-request.component.ts +++ b/apps/browser/src/auth/popup/login-via-auth-request.component.ts @@ -15,7 +15,6 @@ import { AuthService } from "@bitwarden/common/auth/abstractions/auth.service"; import { DeviceTrustServiceAbstraction } from "@bitwarden/common/auth/abstractions/device-trust.service.abstraction"; import { AppIdService } from "@bitwarden/common/platform/abstractions/app-id.service"; import { CryptoFunctionService } from "@bitwarden/common/platform/abstractions/crypto-function.service"; -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"; import { LogService } from "@bitwarden/common/platform/abstractions/log.service"; @@ -24,6 +23,7 @@ import { ValidationService } from "@bitwarden/common/platform/abstractions/valid import { SyncService } from "@bitwarden/common/vault/abstractions/sync/sync.service.abstraction"; import { ToastService } from "@bitwarden/components"; import { PasswordGenerationServiceAbstraction } from "@bitwarden/generator-legacy"; +import { KeyService } from "@bitwarden/key-management"; @Component({ selector: "app-login-via-auth-request", @@ -32,7 +32,7 @@ import { PasswordGenerationServiceAbstraction } from "@bitwarden/generator-legac export class LoginViaAuthRequestComponent extends BaseLoginWithDeviceComponent { constructor( router: Router, - cryptoService: CryptoService, + keyService: KeyService, cryptoFunctionService: CryptoFunctionService, appIdService: AppIdService, passwordGenerationService: PasswordGenerationServiceAbstraction, @@ -55,7 +55,7 @@ export class LoginViaAuthRequestComponent extends BaseLoginWithDeviceComponent { ) { super( router, - cryptoService, + keyService, cryptoFunctionService, appIdService, passwordGenerationService, diff --git a/apps/browser/src/auth/popup/register.component.ts b/apps/browser/src/auth/popup/register.component.ts index dab1e62f85..7c785d1912 100644 --- a/apps/browser/src/auth/popup/register.component.ts +++ b/apps/browser/src/auth/popup/register.component.ts @@ -7,7 +7,6 @@ import { FormValidationErrorsService } from "@bitwarden/angular/platform/abstrac import { LoginStrategyServiceAbstraction } from "@bitwarden/auth/common"; import { ApiService } from "@bitwarden/common/abstractions/api.service"; import { AuditService } from "@bitwarden/common/abstractions/audit.service"; -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"; import { LogService } from "@bitwarden/common/platform/abstractions/log.service"; @@ -15,6 +14,7 @@ import { PlatformUtilsService } from "@bitwarden/common/platform/abstractions/pl import { StateService } from "@bitwarden/common/platform/abstractions/state.service"; import { DialogService, ToastService } from "@bitwarden/components"; import { PasswordGenerationServiceAbstraction } from "@bitwarden/generator-legacy"; +import { KeyService } from "@bitwarden/key-management"; @Component({ selector: "app-register", @@ -30,7 +30,7 @@ export class RegisterComponent extends BaseRegisterComponent { loginStrategyService: LoginStrategyServiceAbstraction, router: Router, i18nService: I18nService, - cryptoService: CryptoService, + keyService: KeyService, apiService: ApiService, stateService: StateService, platformUtilsService: PlatformUtilsService, @@ -47,7 +47,7 @@ export class RegisterComponent extends BaseRegisterComponent { loginStrategyService, router, i18nService, - cryptoService, + keyService, apiService, stateService, platformUtilsService, diff --git a/apps/browser/src/auth/popup/settings/account-security-v1.component.ts b/apps/browser/src/auth/popup/settings/account-security-v1.component.ts index d2a515b259..db45b3adb7 100644 --- a/apps/browser/src/auth/popup/settings/account-security-v1.component.ts +++ b/apps/browser/src/auth/popup/settings/account-security-v1.component.ts @@ -25,7 +25,6 @@ import { PolicyType } from "@bitwarden/common/admin-console/enums"; import { AccountService } from "@bitwarden/common/auth/abstractions/account.service"; import { UserVerificationService } from "@bitwarden/common/auth/abstractions/user-verification/user-verification.service.abstraction"; 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"; import { MessagingService } from "@bitwarden/common/platform/abstractions/messaging.service"; @@ -37,7 +36,7 @@ import { VaultTimeoutStringType, } from "@bitwarden/common/types/vault-timeout.type"; import { DialogService } from "@bitwarden/components"; -import { BiometricStateService, BiometricsService } from "@bitwarden/key-management"; +import { KeyService, BiometricStateService, BiometricsService } from "@bitwarden/key-management"; import { BiometricErrors, BiometricErrorTypes } from "../../../models/biometricErrors"; import { BrowserApi } from "../../../platform/browser/browser-api"; @@ -87,7 +86,7 @@ export class AccountSecurityComponent implements OnInit, OnDestroy { private vaultTimeoutSettingsService: VaultTimeoutSettingsService, public messagingService: MessagingService, private environmentService: EnvironmentService, - private cryptoService: CryptoService, + private keyService: KeyService, private stateService: StateService, private userVerificationService: UserVerificationService, private dialogService: DialogService, @@ -386,7 +385,7 @@ export class AccountSecurityComponent implements OnInit, OnDestroy { const awaitDesktopDialogRef = AwaitDesktopDialogComponent.open(this.dialogService); const awaitDesktopDialogClosed = firstValueFrom(awaitDesktopDialogRef.closed); - await this.cryptoService.refreshAdditionalKeys(); + await this.keyService.refreshAdditionalKeys(); await Promise.race([ awaitDesktopDialogClosed.then(async (result) => { @@ -465,9 +464,7 @@ export class AccountSecurityComponent implements OnInit, OnDestroy { } async fingerprint() { - const fingerprint = await this.cryptoService.getFingerprint( - await this.stateService.getUserId(), - ); + const fingerprint = await this.keyService.getFingerprint(await this.stateService.getUserId()); const dialogRef = FingerprintDialogComponent.open(this.dialogService, { fingerprint, diff --git a/apps/browser/src/auth/popup/settings/account-security.component.ts b/apps/browser/src/auth/popup/settings/account-security.component.ts index 20286435ed..1617ed8476 100644 --- a/apps/browser/src/auth/popup/settings/account-security.component.ts +++ b/apps/browser/src/auth/popup/settings/account-security.component.ts @@ -27,7 +27,6 @@ import { PolicyType } from "@bitwarden/common/admin-console/enums"; import { AccountService } from "@bitwarden/common/auth/abstractions/account.service"; import { UserVerificationService } from "@bitwarden/common/auth/abstractions/user-verification/user-verification.service.abstraction"; 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"; import { MessagingService } from "@bitwarden/common/platform/abstractions/messaging.service"; @@ -52,7 +51,7 @@ import { TypographyModule, ToastService, } from "@bitwarden/components"; -import { BiometricsService, BiometricStateService } from "@bitwarden/key-management"; +import { KeyService, BiometricsService, BiometricStateService } from "@bitwarden/key-management"; import { BiometricErrors, BiometricErrorTypes } from "../../../models/biometricErrors"; import { BrowserApi } from "../../../platform/browser/browser-api"; @@ -127,7 +126,7 @@ export class AccountSecurityComponent implements OnInit, OnDestroy { private vaultTimeoutSettingsService: VaultTimeoutSettingsService, public messagingService: MessagingService, private environmentService: EnvironmentService, - private cryptoService: CryptoService, + private keyService: KeyService, private stateService: StateService, private userVerificationService: UserVerificationService, private dialogService: DialogService, @@ -436,7 +435,7 @@ export class AccountSecurityComponent implements OnInit, OnDestroy { return; } - await this.cryptoService.refreshAdditionalKeys(); + await this.keyService.refreshAdditionalKeys(); const successful = await this.trySetupBiometrics(); this.form.controls.biometric.setValue(successful); @@ -562,8 +561,8 @@ export class AccountSecurityComponent implements OnInit, OnDestroy { const activeUserId = await firstValueFrom( this.accountService.activeAccount$.pipe(map((a) => a?.id)), ); - const publicKey = await firstValueFrom(this.cryptoService.userPublicKey$(activeUserId)); - const fingerprint = await this.cryptoService.getFingerprint(activeUserId, publicKey); + const publicKey = await firstValueFrom(this.keyService.userPublicKey$(activeUserId)); + const fingerprint = await this.keyService.getFingerprint(activeUserId, publicKey); const dialogRef = FingerprintDialogComponent.open(this.dialogService, { fingerprint, diff --git a/apps/browser/src/background/main.background.ts b/apps/browser/src/background/main.background.ts index e31b40fe81..919ed2a243 100644 --- a/apps/browser/src/background/main.background.ts +++ b/apps/browser/src/background/main.background.ts @@ -2,15 +2,15 @@ import { Subject, filter, firstValueFrom, map, merge, timeout } from "rxjs"; import { CollectionService, DefaultCollectionService } from "@bitwarden/admin-console/common"; import { - PinServiceAbstraction, - PinService, - InternalUserDecryptionOptionsServiceAbstraction, - UserDecryptionOptionsService, - AuthRequestServiceAbstraction, AuthRequestService, + AuthRequestServiceAbstraction, + DefaultLockService, + InternalUserDecryptionOptionsServiceAbstraction, LoginEmailServiceAbstraction, LogoutReason, - DefaultLockService, + PinService, + PinServiceAbstraction, + UserDecryptionOptionsService, } from "@bitwarden/auth/common"; import { ApiService as ApiServiceAbstraction } from "@bitwarden/common/abstractions/api.service"; import { AuditService as AuditServiceAbstraction } from "@bitwarden/common/abstractions/audit.service"; @@ -56,16 +56,16 @@ import { TokenService } from "@bitwarden/common/auth/services/token.service"; import { UserVerificationApiService } from "@bitwarden/common/auth/services/user-verification/user-verification-api.service"; import { UserVerificationService } from "@bitwarden/common/auth/services/user-verification/user-verification.service"; import { - AutofillSettingsServiceAbstraction, AutofillSettingsService, + AutofillSettingsServiceAbstraction, } from "@bitwarden/common/autofill/services/autofill-settings.service"; import { - BadgeSettingsServiceAbstraction, BadgeSettingsService, + BadgeSettingsServiceAbstraction, } from "@bitwarden/common/autofill/services/badge-settings.service"; import { - DomainSettingsService, DefaultDomainSettingsService, + DomainSettingsService, } from "@bitwarden/common/autofill/services/domain-settings.service"; import { UserNotificationSettingsService, @@ -81,7 +81,6 @@ import { AppIdService as AppIdServiceAbstraction } from "@bitwarden/common/platf import { ConfigApiServiceAbstraction } from "@bitwarden/common/platform/abstractions/config/config-api.service.abstraction"; import { ConfigService } from "@bitwarden/common/platform/abstractions/config/config.service"; import { CryptoFunctionService as CryptoFunctionServiceAbstraction } from "@bitwarden/common/platform/abstractions/crypto-function.service"; -import { CryptoService as CryptoServiceAbstraction } from "@bitwarden/common/platform/abstractions/crypto.service"; import { EncryptService } from "@bitwarden/common/platform/abstractions/encrypt.service"; import { RegionConfig } from "@bitwarden/common/platform/abstractions/environment.service"; import { Fido2ActiveRequestManager as Fido2ActiveRequestManagerAbstraction } from "@bitwarden/common/platform/abstractions/fido2/fido2-active-request-manager.abstraction"; @@ -190,10 +189,10 @@ import { FolderService } from "@bitwarden/common/vault/services/folder/folder.se import { TotpService } from "@bitwarden/common/vault/services/totp.service"; import { VaultSettingsService } from "@bitwarden/common/vault/services/vault-settings/vault-settings.service"; import { - legacyPasswordGenerationServiceFactory, PasswordGenerationServiceAbstraction, - legacyUsernameGenerationServiceFactory, UsernameGenerationServiceAbstraction, + legacyPasswordGenerationServiceFactory, + legacyUsernameGenerationServiceFactory, } from "@bitwarden/generator-legacy"; import { ImportApiService, @@ -203,8 +202,9 @@ import { } from "@bitwarden/importer/core"; import { BiometricStateService, - DefaultBiometricStateService, BiometricsService, + DefaultBiometricStateService, + KeyService as KeyServiceAbstraction, } from "@bitwarden/key-management"; import { IndividualVaultExportService, @@ -235,6 +235,7 @@ import { AutofillService as AutofillServiceAbstraction } from "../autofill/servi import AutofillService from "../autofill/services/autofill.service"; import { SafariApp } from "../browser/safariApp"; import { BackgroundBrowserBiometricsService } from "../key-management/biometrics/background-browser-biometrics.service"; +import { BrowserKeyService } from "../key-management/browser-key.service"; import { BrowserApi } from "../platform/browser/browser-api"; import { flagEnabled } from "../platform/flags"; import { UpdateBadge } from "../platform/listeners/update-badge"; @@ -244,7 +245,6 @@ import { ChromeMessageSender } from "../platform/messaging/chrome-message.sender import { OffscreenDocumentService } from "../platform/offscreen-document/abstractions/offscreen-document"; import { DefaultOffscreenDocumentService } from "../platform/offscreen-document/offscreen-document.service"; import { BrowserTaskSchedulerService } from "../platform/services/abstractions/browser-task-scheduler.service"; -import { BrowserCryptoService } from "../platform/services/browser-crypto.service"; import { BrowserEnvironmentService } from "../platform/services/browser-environment.service"; import BrowserLocalStorageService from "../platform/services/browser-local-storage.service"; import BrowserMemoryStorageService from "../platform/services/browser-memory-storage.service"; @@ -284,7 +284,7 @@ export default class MainBackground { platformUtilsService: PlatformUtilsServiceAbstraction; logService: LogServiceAbstraction; keyGenerationService: KeyGenerationServiceAbstraction; - cryptoService: CryptoServiceAbstraction; + keyService: KeyServiceAbstraction; cryptoFunctionService: CryptoFunctionServiceAbstraction; masterPasswordService: InternalMasterPasswordServiceAbstraction; tokenService: TokenServiceAbstraction; @@ -653,7 +653,7 @@ export default class MainBackground { this.stateService, ); - this.cryptoService = new BrowserCryptoService( + this.keyService = new BrowserKeyService( this.pinService, this.masterPasswordService, this.keyGenerationService, @@ -679,7 +679,7 @@ export default class MainBackground { this.accountService, this.pinService, this.userDecryptionOptionsService, - this.cryptoService, + this.keyService, this.tokenService, this.policyService, this.biometricStateService, @@ -708,7 +708,7 @@ export default class MainBackground { this.searchService = new SearchService(this.logService, this.i18nService, this.stateProvider); this.collectionService = new DefaultCollectionService( - this.cryptoService, + this.keyService, this.encryptService, this.i18nService, this.stateProvider, @@ -723,7 +723,7 @@ export default class MainBackground { this.keyConnectorService = new KeyConnectorService( this.accountService, this.masterPasswordService, - this.cryptoService, + this.keyService, this.apiService, this.tokenService, this.logService, @@ -742,7 +742,7 @@ export default class MainBackground { this.platformUtilsService, this.accountService, this.kdfConfigService, - this.cryptoService, + this.keyService, this.apiService, ); @@ -750,7 +750,7 @@ export default class MainBackground { this.passwordGenerationService = legacyPasswordGenerationServiceFactory( this.encryptService, - this.cryptoService, + this.keyService, this.policyService, this.accountService, this.stateProvider, @@ -762,7 +762,7 @@ export default class MainBackground { this.deviceTrustService = new DeviceTrustService( this.keyGenerationService, this.cryptoFunctionService, - this.cryptoService, + this.keyService, this.encryptService, this.appIdService, this.devicesApiService, @@ -781,7 +781,7 @@ export default class MainBackground { this.appIdService, this.accountService, this.masterPasswordService, - this.cryptoService, + this.keyService, this.encryptService, this.apiService, this.stateProvider, @@ -790,7 +790,7 @@ export default class MainBackground { this.authService = new AuthService( this.accountService, this.messagingService, - this.cryptoService, + this.keyService, this.apiService, this.stateService, this.tokenService, @@ -822,7 +822,7 @@ export default class MainBackground { this.bulkEncryptService = new FallbackBulkEncryptService(this.encryptService); this.cipherService = new CipherService( - this.cryptoService, + this.keyService, this.domainSettingsService, this.apiService, this.i18nService, @@ -837,7 +837,7 @@ export default class MainBackground { this.accountService, ); this.folderService = new FolderService( - this.cryptoService, + this.keyService, this.encryptService, this.i18nService, this.cipherService, @@ -846,7 +846,7 @@ export default class MainBackground { this.folderApiService = new FolderApiService(this.folderService, this.apiService); this.userVerificationService = new UserVerificationService( - this.cryptoService, + this.keyService, this.accountService, this.masterPasswordService, this.i18nService, @@ -891,11 +891,11 @@ export default class MainBackground { logoutCallback, ); } - this.containerService = new ContainerService(this.cryptoService, this.encryptService); + this.containerService = new ContainerService(this.keyService, this.encryptService); this.sendStateProvider = new SendStateProvider(this.stateProvider); this.sendService = new SendService( - this.cryptoService, + this.keyService, this.i18nService, this.keyGenerationService, this.sendStateProvider, @@ -936,7 +936,7 @@ export default class MainBackground { this.domainSettingsService, this.folderService, this.cipherService, - this.cryptoService, + this.keyService, this.collectionService, this.messagingService, this.policyService, @@ -1011,7 +1011,7 @@ export default class MainBackground { this.importApiService, this.i18nService, this.collectionService, - this.cryptoService, + this.keyService, this.encryptService, this.pinService, this.accountService, @@ -1021,7 +1021,7 @@ export default class MainBackground { this.folderService, this.cipherService, this.pinService, - this.cryptoService, + this.keyService, this.encryptService, this.cryptoFunctionService, this.kdfConfigService, @@ -1032,7 +1032,7 @@ export default class MainBackground { this.cipherService, this.apiService, this.pinService, - this.cryptoService, + this.keyService, this.encryptService, this.cryptoFunctionService, this.collectionService, @@ -1139,7 +1139,7 @@ export default class MainBackground { lockService, ); this.nativeMessagingBackground = new NativeMessagingBackground( - this.cryptoService, + this.keyService, this.encryptService, this.cryptoFunctionService, this.runtimeBackground, @@ -1244,7 +1244,7 @@ export default class MainBackground { this.usernameGenerationService = legacyUsernameGenerationServiceFactory( this.apiService, this.i18nService, - this.cryptoService, + this.keyService, this.encryptService, this.policyService, this.accountService, @@ -1276,7 +1276,7 @@ export default class MainBackground { } } - this.userAutoUnlockKeyService = new UserAutoUnlockKeyService(this.cryptoService); + this.userAutoUnlockKeyService = new UserAutoUnlockKeyService(this.keyService); this.cipherAuthorizationService = new DefaultCipherAuthorizationService( this.collectionService, @@ -1514,7 +1514,7 @@ export default class MainBackground { ); await Promise.all([ - this.cryptoService.clearKeys(userBeingLoggedOut), + this.keyService.clearKeys(userBeingLoggedOut), this.cipherService.clear(userBeingLoggedOut), this.folderService.clear(userBeingLoggedOut), this.collectionService.clear(userBeingLoggedOut), diff --git a/apps/browser/src/background/nativeMessaging.background.ts b/apps/browser/src/background/nativeMessaging.background.ts index d483b10bc3..2399afd57b 100644 --- a/apps/browser/src/background/nativeMessaging.background.ts +++ b/apps/browser/src/background/nativeMessaging.background.ts @@ -5,7 +5,6 @@ import { AuthService } from "@bitwarden/common/auth/abstractions/auth.service"; import { AuthenticationStatus } from "@bitwarden/common/auth/enums/authentication-status"; import { AppIdService } from "@bitwarden/common/platform/abstractions/app-id.service"; import { CryptoFunctionService } from "@bitwarden/common/platform/abstractions/crypto-function.service"; -import { CryptoService } from "@bitwarden/common/platform/abstractions/crypto.service"; import { EncryptService } from "@bitwarden/common/platform/abstractions/encrypt.service"; import { LogService } from "@bitwarden/common/platform/abstractions/log.service"; import { MessagingService } from "@bitwarden/common/platform/abstractions/messaging.service"; @@ -14,7 +13,7 @@ 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/types/key"; -import { BiometricStateService } from "@bitwarden/key-management"; +import { KeyService, BiometricStateService } from "@bitwarden/key-management"; import { BrowserApi } from "../platform/browser/browser-api"; @@ -73,7 +72,7 @@ export class NativeMessagingBackground { private validatingFingerprint: boolean; constructor( - private cryptoService: CryptoService, + private keyService: KeyService, private encryptService: EncryptService, private cryptoFunctionService: CryptoFunctionService, private runtimeBackground: RuntimeBackground, @@ -318,15 +317,12 @@ export class NativeMessagingBackground { const activeUserId = await firstValueFrom( this.accountService.activeAccount$.pipe(map((a) => a?.id)), ); - const isUserKeyValid = await this.cryptoService.validateUserKey( - userKey, - activeUserId, - ); + const isUserKeyValid = await this.keyService.validateUserKey(userKey, activeUserId); if (isUserKeyValid) { - await this.cryptoService.setUserKey(userKey, activeUserId); + await this.keyService.setUserKey(userKey, activeUserId); } else { this.logService.error("Unable to verify biometric unlocked userkey"); - await this.cryptoService.clearKeys(activeUserId); + await this.keyService.clearKeys(activeUserId); this.rejecter("userkey wrong"); return; } @@ -342,10 +338,10 @@ export class NativeMessagingBackground { // Verify key is correct by attempting to decrypt a secret try { const userId = (await firstValueFrom(this.accountService.activeAccount$))?.id; - await this.cryptoService.getFingerprint(userId); + await this.keyService.getFingerprint(userId); } catch (e) { this.logService.error("Unable to verify key: " + e); - await this.cryptoService.clearKeys(); + await this.keyService.clearKeys(); this.rejecter("userkey wrong"); return; } @@ -398,7 +394,7 @@ export class NativeMessagingBackground { } private async showFingerprintDialog() { - const fingerprint = await this.cryptoService.getFingerprint( + const fingerprint = await this.keyService.getFingerprint( (await firstValueFrom(this.accountService.activeAccount$))?.id, this.publicKey, ); diff --git a/apps/browser/src/platform/services/browser-crypto.service.ts b/apps/browser/src/key-management/browser-key.service.ts similarity index 93% rename from apps/browser/src/platform/services/browser-crypto.service.ts rename to apps/browser/src/key-management/browser-key.service.ts index d0b4e3add7..1fa3e111fe 100644 --- a/apps/browser/src/platform/services/browser-crypto.service.ts +++ b/apps/browser/src/key-management/browser-key.service.ts @@ -11,14 +11,17 @@ 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 { KeySuffixOptions } from "@bitwarden/common/platform/enums"; -import { CryptoService } from "@bitwarden/common/platform/services/crypto.service"; import { USER_KEY } from "@bitwarden/common/platform/services/key-state/user-key.state"; import { StateProvider } from "@bitwarden/common/platform/state"; import { UserId } from "@bitwarden/common/types/guid"; import { UserKey } from "@bitwarden/common/types/key"; -import { BiometricsService, BiometricStateService } from "@bitwarden/key-management"; +import { + DefaultKeyService, + BiometricsService, + BiometricStateService, +} from "@bitwarden/key-management"; -export class BrowserCryptoService extends CryptoService { +export class BrowserKeyService extends DefaultKeyService { constructor( pinService: PinServiceAbstraction, masterPasswordService: InternalMasterPasswordServiceAbstraction, diff --git a/apps/browser/src/popup/services/services.module.ts b/apps/browser/src/popup/services/services.module.ts index 3a6e5586a5..7b35d1d310 100644 --- a/apps/browser/src/popup/services/services.module.ts +++ b/apps/browser/src/popup/services/services.module.ts @@ -6,15 +6,15 @@ import { ViewCacheService } from "@bitwarden/angular/platform/abstractions/view- import { AngularThemingService } from "@bitwarden/angular/platform/services/theming/angular-theming.service"; import { SafeProvider, safeProvider } from "@bitwarden/angular/platform/utils/safe-provider"; import { - MEMORY_STORAGE, - SECURE_STORAGE, - OBSERVABLE_DISK_STORAGE, - OBSERVABLE_MEMORY_STORAGE, - SYSTEM_THEME_OBSERVABLE, - SafeInjectionToken, + CLIENT_TYPE, DEFAULT_VAULT_TIMEOUT, INTRAPROCESS_MESSAGING_SUBJECT, - CLIENT_TYPE, + MEMORY_STORAGE, + OBSERVABLE_DISK_STORAGE, + OBSERVABLE_MEMORY_STORAGE, + SECURE_STORAGE, + SYSTEM_THEME_OBSERVABLE, + SafeInjectionToken, ENV_ADDITIONAL_REGIONS, } from "@bitwarden/angular/services/injection-tokens"; import { JslibServicesModule } from "@bitwarden/angular/services/jslib-services.module"; @@ -50,7 +50,6 @@ import { } from "@bitwarden/common/platform/abstractions/animation-control.service"; import { ConfigService } from "@bitwarden/common/platform/abstractions/config/config.service"; import { CryptoFunctionService } from "@bitwarden/common/platform/abstractions/crypto-function.service"; -import { CryptoService } from "@bitwarden/common/platform/abstractions/crypto.service"; import { EncryptService } from "@bitwarden/common/platform/abstractions/encrypt.service"; import { EnvironmentService } from "@bitwarden/common/platform/abstractions/environment.service"; import { FileDownloadService } from "@bitwarden/common/platform/abstractions/file-download/file-download.service"; @@ -91,7 +90,7 @@ import { FolderService as FolderServiceAbstraction } from "@bitwarden/common/vau import { TotpService as TotpServiceAbstraction } from "@bitwarden/common/vault/abstractions/totp.service"; import { TotpService } from "@bitwarden/common/vault/services/totp.service"; import { DialogService, ToastService } from "@bitwarden/components"; -import { BiometricsService, BiometricStateService } from "@bitwarden/key-management"; +import { BiometricStateService, BiometricsService, KeyService } from "@bitwarden/key-management"; import { PasswordRepromptService } from "@bitwarden/vault"; import { ForegroundLockService } from "../../auth/popup/accounts/foreground-lock.service"; @@ -100,6 +99,7 @@ import { AutofillService as AutofillServiceAbstraction } from "../../autofill/se import AutofillService from "../../autofill/services/autofill.service"; import MainBackground from "../../background/main.background"; import { ForegroundBrowserBiometricsService } from "../../key-management/biometrics/foreground-browser-biometrics"; +import { BrowserKeyService } from "../../key-management/browser-key.service"; import { BrowserApi } from "../../platform/browser/browser-api"; import { runInsideAngular } from "../../platform/browser/run-inside-angular.operator"; /* eslint-disable no-restricted-imports */ @@ -111,7 +111,6 @@ import BrowserPopupUtils from "../../platform/popup/browser-popup-utils"; import { BrowserFileDownloadService } from "../../platform/popup/services/browser-file-download.service"; import { PopupViewCacheService } from "../../platform/popup/view-cache/popup-view-cache.service"; import { ScriptInjectorService } from "../../platform/services/abstractions/script-injector.service"; -import { BrowserCryptoService } from "../../platform/services/browser-crypto.service"; import { BrowserEnvironmentService } from "../../platform/services/browser-environment.service"; import BrowserLocalStorageService from "../../platform/services/browser-local-storage.service"; import { BrowserScriptInjectorService } from "../../platform/services/browser-script-injector.service"; @@ -212,7 +211,7 @@ const safeProviders: SafeProvider[] = [ deps: [GlobalStateProvider], }), safeProvider({ - provide: CryptoService, + provide: KeyService, useFactory: ( pinService: PinServiceAbstraction, masterPasswordService: InternalMasterPasswordServiceAbstraction, @@ -228,7 +227,7 @@ const safeProviders: SafeProvider[] = [ biometricsService: BiometricsService, kdfConfigService: KdfConfigService, ) => { - const cryptoService = new BrowserCryptoService( + const keyService = new BrowserKeyService( pinService, masterPasswordService, keyGenerationService, @@ -243,8 +242,8 @@ const safeProviders: SafeProvider[] = [ biometricsService, kdfConfigService, ); - new ContainerService(cryptoService, encryptService).attachToGlobal(self); - return cryptoService; + new ContainerService(keyService, encryptService).attachToGlobal(self); + return keyService; }, deps: [ PinServiceAbstraction, diff --git a/apps/browser/src/services/extension-lock-component.service.spec.ts b/apps/browser/src/services/extension-lock-component.service.spec.ts index f537897cf8..a8a019662e 100644 --- a/apps/browser/src/services/extension-lock-component.service.spec.ts +++ b/apps/browser/src/services/extension-lock-component.service.spec.ts @@ -8,10 +8,9 @@ import { UserDecryptionOptionsServiceAbstraction, } from "@bitwarden/auth/common"; import { VaultTimeoutSettingsService } from "@bitwarden/common/abstractions/vault-timeout/vault-timeout-settings.service"; -import { CryptoService } from "@bitwarden/common/platform/abstractions/crypto.service"; import { PlatformUtilsService } from "@bitwarden/common/platform/abstractions/platform-utils.service"; import { UserId } from "@bitwarden/common/types/guid"; -import { BiometricsService } from "@bitwarden/key-management"; +import { KeyService, BiometricsService } from "@bitwarden/key-management"; import { BrowserRouterService } from "../platform/popup/services/browser-router.service"; @@ -25,7 +24,7 @@ describe("ExtensionLockComponentService", () => { let biometricsService: MockProxy; let pinService: MockProxy; let vaultTimeoutSettingsService: MockProxy; - let cryptoService: MockProxy; + let keyService: MockProxy; let routerService: MockProxy; beforeEach(() => { @@ -34,7 +33,7 @@ describe("ExtensionLockComponentService", () => { biometricsService = mock(); pinService = mock(); vaultTimeoutSettingsService = mock(); - cryptoService = mock(); + keyService = mock(); routerService = mock(); TestBed.configureTestingModule({ @@ -61,8 +60,8 @@ describe("ExtensionLockComponentService", () => { useValue: vaultTimeoutSettingsService, }, { - provide: CryptoService, - useValue: cryptoService, + provide: KeyService, + useValue: keyService, }, { provide: BrowserRouterService, @@ -307,9 +306,7 @@ describe("ExtensionLockComponentService", () => { // Biometrics biometricsService.supportsBiometric.mockResolvedValue(mockInputs.osSupportsBiometric); vaultTimeoutSettingsService.isBiometricLockSet.mockResolvedValue(mockInputs.biometricLockSet); - cryptoService.hasUserKeyStored.mockResolvedValue( - mockInputs.hasBiometricEncryptedUserKeyStored, - ); + keyService.hasUserKeyStored.mockResolvedValue(mockInputs.hasBiometricEncryptedUserKeyStored); platformUtilsService.supportsSecureStorage.mockReturnValue( mockInputs.platformSupportsSecureStorage, ); diff --git a/apps/browser/src/services/extension-lock-component.service.ts b/apps/browser/src/services/extension-lock-component.service.ts index 58514fa2b1..28fe21ede6 100644 --- a/apps/browser/src/services/extension-lock-component.service.ts +++ b/apps/browser/src/services/extension-lock-component.service.ts @@ -11,11 +11,10 @@ import { UserDecryptionOptionsServiceAbstraction, } from "@bitwarden/auth/common"; import { VaultTimeoutSettingsService } from "@bitwarden/common/abstractions/vault-timeout/vault-timeout-settings.service"; -import { CryptoService } from "@bitwarden/common/platform/abstractions/crypto.service"; import { PlatformUtilsService } from "@bitwarden/common/platform/abstractions/platform-utils.service"; import { KeySuffixOptions } from "@bitwarden/common/platform/enums"; import { UserId } from "@bitwarden/common/types/guid"; -import { BiometricsService } from "@bitwarden/key-management"; +import { KeyService, BiometricsService } from "@bitwarden/key-management"; import { BiometricErrors, BiometricErrorTypes } from "../models/biometricErrors"; import { BrowserRouterService } from "../platform/popup/services/browser-router.service"; @@ -26,7 +25,7 @@ export class ExtensionLockComponentService implements LockComponentService { private readonly biometricsService = inject(BiometricsService); private readonly pinService = inject(PinServiceAbstraction); private readonly vaultTimeoutSettingsService = inject(VaultTimeoutSettingsService); - private readonly cryptoService = inject(CryptoService); + private readonly keyService = inject(KeyService); private readonly routerService = inject(BrowserRouterService); getPreviousUrl(): string | null { @@ -53,7 +52,7 @@ export class ExtensionLockComponentService implements LockComponentService { private async isBiometricLockSet(userId: UserId): Promise { const biometricLockSet = await this.vaultTimeoutSettingsService.isBiometricLockSet(userId); - const hasBiometricEncryptedUserKeyStored = await this.cryptoService.hasUserKeyStored( + const hasBiometricEncryptedUserKeyStored = await this.keyService.hasUserKeyStored( KeySuffixOptions.Biometric, userId, ); diff --git a/apps/browser/src/vault/popup/components/vault-v2/add-edit-folder-dialog/add-edit-folder-dialog.component.spec.ts b/apps/browser/src/vault/popup/components/vault-v2/add-edit-folder-dialog/add-edit-folder-dialog.component.spec.ts index 156cc9d819..4e222a554f 100644 --- a/apps/browser/src/vault/popup/components/vault-v2/add-edit-folder-dialog/add-edit-folder-dialog.component.spec.ts +++ b/apps/browser/src/vault/popup/components/vault-v2/add-edit-folder-dialog/add-edit-folder-dialog.component.spec.ts @@ -4,7 +4,6 @@ import { NoopAnimationsModule } from "@angular/platform-browser/animations"; import { BehaviorSubject } from "rxjs"; import { AccountInfo, AccountService } from "@bitwarden/common/auth/abstractions/account.service"; -import { CryptoService } from "@bitwarden/common/platform/abstractions/crypto.service"; import { I18nService } from "@bitwarden/common/platform/abstractions/i18n.service"; import { LogService } from "@bitwarden/common/platform/abstractions/log.service"; import { UserId } from "@bitwarden/common/types/guid"; @@ -13,6 +12,7 @@ import { FolderService } from "@bitwarden/common/vault/abstractions/folder/folde import { Folder } from "@bitwarden/common/vault/models/domain/folder"; import { FolderView } from "@bitwarden/common/vault/models/view/folder.view"; import { DialogService, ToastService } from "@bitwarden/components"; +import { KeyService } from "@bitwarden/key-management"; import { AddEditFolderDialogComponent, @@ -64,7 +64,7 @@ describe("AddEditFolderDialogComponent", () => { useValue: { activeAccount$: new BehaviorSubject({ id: userId, ...accountInfo }) }, }, { - provide: CryptoService, + provide: KeyService, useValue: { getUserKeyWithLegacySupport, }, diff --git a/apps/browser/src/vault/popup/components/vault-v2/add-edit-folder-dialog/add-edit-folder-dialog.component.ts b/apps/browser/src/vault/popup/components/vault-v2/add-edit-folder-dialog/add-edit-folder-dialog.component.ts index 4f793abb6a..c0cbf87748 100644 --- a/apps/browser/src/vault/popup/components/vault-v2/add-edit-folder-dialog/add-edit-folder-dialog.component.ts +++ b/apps/browser/src/vault/popup/components/vault-v2/add-edit-folder-dialog/add-edit-folder-dialog.component.ts @@ -15,7 +15,6 @@ import { firstValueFrom } from "rxjs"; import { JslibModule } from "@bitwarden/angular/jslib.module"; import { AccountService } from "@bitwarden/common/auth/abstractions/account.service"; -import { CryptoService } from "@bitwarden/common/platform/abstractions/crypto.service"; import { I18nService } from "@bitwarden/common/platform/abstractions/i18n.service"; import { LogService } from "@bitwarden/common/platform/abstractions/log.service"; import { FolderApiServiceAbstraction } from "@bitwarden/common/vault/abstractions/folder/folder-api.service.abstraction"; @@ -32,6 +31,7 @@ import { IconButtonModule, ToastService, } from "@bitwarden/components"; +import { KeyService } from "@bitwarden/key-management"; export type AddEditFolderDialogData = { /** When provided, dialog will display edit folder variant */ @@ -72,7 +72,7 @@ export class AddEditFolderDialogComponent implements AfterViewInit, OnInit { private folderService: FolderService, private folderApiService: FolderApiServiceAbstraction, private accountService: AccountService, - private cryptoService: CryptoService, + private keyService: KeyService, private toastService: ToastService, private i18nService: I18nService, private logService: LogService, @@ -113,7 +113,7 @@ export class AddEditFolderDialogComponent implements AfterViewInit, OnInit { try { const activeUserId = await firstValueFrom(this.accountService.activeAccount$); - const userKey = await this.cryptoService.getUserKeyWithLegacySupport(activeUserId.id); + const userKey = await this.keyService.getUserKeyWithLegacySupport(activeUserId.id); const folder = await this.folderService.encrypt(this.folder, userKey); await this.folderApiService.save(folder); diff --git a/apps/browser/src/vault/popup/components/vault/attachments.component.ts b/apps/browser/src/vault/popup/components/vault/attachments.component.ts index 1ab1ff428b..346451a8af 100644 --- a/apps/browser/src/vault/popup/components/vault/attachments.component.ts +++ b/apps/browser/src/vault/popup/components/vault/attachments.component.ts @@ -7,7 +7,6 @@ import { AttachmentsComponent as BaseAttachmentsComponent } from "@bitwarden/ang import { ApiService } from "@bitwarden/common/abstractions/api.service"; import { AccountService } from "@bitwarden/common/auth/abstractions/account.service"; import { BillingAccountProfileStateService } from "@bitwarden/common/billing/abstractions/account/billing-account-profile-state.service"; -import { CryptoService } from "@bitwarden/common/platform/abstractions/crypto.service"; import { EncryptService } from "@bitwarden/common/platform/abstractions/encrypt.service"; import { FileDownloadService } from "@bitwarden/common/platform/abstractions/file-download/file-download.service"; import { I18nService } from "@bitwarden/common/platform/abstractions/i18n.service"; @@ -16,6 +15,7 @@ import { PlatformUtilsService } from "@bitwarden/common/platform/abstractions/pl import { StateService } from "@bitwarden/common/platform/abstractions/state.service"; import { CipherService } from "@bitwarden/common/vault/abstractions/cipher.service"; import { DialogService, ToastService } from "@bitwarden/components"; +import { KeyService } from "@bitwarden/key-management"; @Component({ selector: "app-vault-attachments", @@ -28,7 +28,7 @@ export class AttachmentsComponent extends BaseAttachmentsComponent implements On constructor( cipherService: CipherService, i18nService: I18nService, - cryptoService: CryptoService, + keyService: KeyService, encryptService: EncryptService, platformUtilsService: PlatformUtilsService, apiService: ApiService, @@ -45,7 +45,7 @@ export class AttachmentsComponent extends BaseAttachmentsComponent implements On super( cipherService, i18nService, - cryptoService, + keyService, encryptService, platformUtilsService, apiService, diff --git a/apps/browser/src/vault/popup/components/vault/view.component.ts b/apps/browser/src/vault/popup/components/vault/view.component.ts index 755426e26b..e45d0556c2 100644 --- a/apps/browser/src/vault/popup/components/vault/view.component.ts +++ b/apps/browser/src/vault/popup/components/vault/view.component.ts @@ -12,7 +12,6 @@ import { AccountService } from "@bitwarden/common/auth/abstractions/account.serv import { TokenService } from "@bitwarden/common/auth/abstractions/token.service"; import { BillingAccountProfileStateService } from "@bitwarden/common/billing/abstractions/account/billing-account-profile-state.service"; import { BroadcasterService } from "@bitwarden/common/platform/abstractions/broadcaster.service"; -import { CryptoService } from "@bitwarden/common/platform/abstractions/crypto.service"; import { EncryptService } from "@bitwarden/common/platform/abstractions/encrypt.service"; import { FileDownloadService } from "@bitwarden/common/platform/abstractions/file-download/file-download.service"; import { I18nService } from "@bitwarden/common/platform/abstractions/i18n.service"; @@ -28,6 +27,7 @@ import { Cipher } from "@bitwarden/common/vault/models/domain/cipher"; import { LoginUriView } from "@bitwarden/common/vault/models/view/login-uri.view"; import { CipherAuthorizationService } from "@bitwarden/common/vault/services/cipher-authorization.service"; import { DialogService } from "@bitwarden/components"; +import { KeyService } from "@bitwarden/key-management"; import { PasswordRepromptService } from "@bitwarden/vault"; import { BrowserFido2UserInterfaceSession } from "../../../../autofill/fido2/services/browser-fido2-user-interface.service"; @@ -81,7 +81,7 @@ export class ViewComponent extends BaseViewComponent implements OnInit, OnDestro totpService: TotpServiceAbstraction, tokenService: TokenService, i18nService: I18nService, - cryptoService: CryptoService, + keyService: KeyService, encryptService: EncryptService, platformUtilsService: PlatformUtilsService, auditService: AuditService, @@ -111,7 +111,7 @@ export class ViewComponent extends BaseViewComponent implements OnInit, OnDestro totpService, tokenService, i18nService, - cryptoService, + keyService, encryptService, platformUtilsService, auditService, diff --git a/apps/browser/src/vault/popup/settings/folder-add-edit.component.ts b/apps/browser/src/vault/popup/settings/folder-add-edit.component.ts index 3ef5fc73aa..122922a4d2 100644 --- a/apps/browser/src/vault/popup/settings/folder-add-edit.component.ts +++ b/apps/browser/src/vault/popup/settings/folder-add-edit.component.ts @@ -5,13 +5,13 @@ import { first } from "rxjs/operators"; import { FolderAddEditComponent as BaseFolderAddEditComponent } from "@bitwarden/angular/vault/components/folder-add-edit.component"; import { AccountService } from "@bitwarden/common/auth/abstractions/account.service"; -import { CryptoService } from "@bitwarden/common/platform/abstractions/crypto.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 { FolderApiServiceAbstraction } from "@bitwarden/common/vault/abstractions/folder/folder-api.service.abstraction"; import { FolderService } from "@bitwarden/common/vault/abstractions/folder/folder.service.abstraction"; import { DialogService } from "@bitwarden/components"; +import { KeyService } from "@bitwarden/key-management"; @Component({ selector: "app-folder-add-edit", @@ -23,7 +23,7 @@ export class FolderAddEditComponent extends BaseFolderAddEditComponent implement folderService: FolderService, folderApiService: FolderApiServiceAbstraction, accountService: AccountService, - cryptoService: CryptoService, + keyService: KeyService, i18nService: I18nService, platformUtilsService: PlatformUtilsService, private router: Router, @@ -36,7 +36,7 @@ export class FolderAddEditComponent extends BaseFolderAddEditComponent implement folderService, folderApiService, accountService, - cryptoService, + keyService, i18nService, platformUtilsService, logService, diff --git a/apps/cli/src/admin-console/commands/confirm.command.ts b/apps/cli/src/admin-console/commands/confirm.command.ts index 42ceea5510..0761dfef18 100644 --- a/apps/cli/src/admin-console/commands/confirm.command.ts +++ b/apps/cli/src/admin-console/commands/confirm.command.ts @@ -3,16 +3,16 @@ import { OrganizationUserConfirmRequest, } from "@bitwarden/admin-console/common"; import { ApiService } from "@bitwarden/common/abstractions/api.service"; -import { CryptoService } from "@bitwarden/common/platform/abstractions/crypto.service"; import { EncryptService } from "@bitwarden/common/platform/abstractions/encrypt.service"; import { Utils } from "@bitwarden/common/platform/misc/utils"; +import { KeyService } from "@bitwarden/key-management"; import { Response } from "../../models/response"; export class ConfirmCommand { constructor( private apiService: ApiService, - private cryptoService: CryptoService, + private keyService: KeyService, private encryptService: EncryptService, private organizationUserApiService: OrganizationUserApiService, ) {} @@ -42,7 +42,7 @@ export class ConfirmCommand { return Response.badRequest("`" + options.organizationId + "` is not a GUID."); } try { - const orgKey = await this.cryptoService.getOrgKey(options.organizationId); + const orgKey = await this.keyService.getOrgKey(options.organizationId); if (orgKey == null) { throw new Error("No encryption key for this organization."); } diff --git a/apps/cli/src/auth/commands/login.command.ts b/apps/cli/src/auth/commands/login.command.ts index 9a69bcc3c0..57477ee2bc 100644 --- a/apps/cli/src/auth/commands/login.command.ts +++ b/apps/cli/src/auth/commands/login.command.ts @@ -29,7 +29,6 @@ import { TwoFactorEmailRequest } from "@bitwarden/common/auth/models/request/two import { UpdateTempPasswordRequest } from "@bitwarden/common/auth/models/request/update-temp-password.request"; import { ErrorResponse } from "@bitwarden/common/models/response/error.response"; import { CryptoFunctionService } from "@bitwarden/common/platform/abstractions/crypto-function.service"; -import { CryptoService } from "@bitwarden/common/platform/abstractions/crypto.service"; import { EnvironmentService } from "@bitwarden/common/platform/abstractions/environment.service"; import { PlatformUtilsService } from "@bitwarden/common/platform/abstractions/platform-utils.service"; import { Utils } from "@bitwarden/common/platform/misc/utils"; @@ -38,6 +37,7 @@ import { SymmetricCryptoKey } from "@bitwarden/common/platform/models/domain/sym import { PasswordStrengthServiceAbstraction } from "@bitwarden/common/tools/password-strength"; import { SyncService } from "@bitwarden/common/vault/abstractions/sync/sync.service.abstraction"; import { PasswordGenerationServiceAbstraction } from "@bitwarden/generator-legacy"; +import { KeyService } from "@bitwarden/key-management"; import { NodeUtils } from "@bitwarden/node/node-utils"; import { Response } from "../../models/response"; @@ -61,7 +61,7 @@ export class LoginCommand { protected passwordStrengthService: PasswordStrengthServiceAbstraction, protected platformUtilsService: PlatformUtilsService, protected accountService: AccountService, - protected cryptoService: CryptoService, + protected keyService: KeyService, protected policyService: PolicyService, protected twoFactorService: TwoFactorService, protected syncService: SyncService, @@ -421,7 +421,7 @@ export class LoginCommand { ); const request = new PasswordRequest(); - request.masterPasswordHash = await this.cryptoService.hashMasterKey(currentPassword, null); + request.masterPasswordHash = await this.keyService.hashMasterKey(currentPassword, null); request.masterPasswordHint = hint; request.newMasterPasswordHash = newPasswordHash; request.key = newUserKey[1].encryptedString; @@ -570,21 +570,21 @@ export class LoginCommand { const kdfConfig = await this.kdfConfigService.getKdfConfig(); // Create new key and hash new password - const newMasterKey = await this.cryptoService.makeMasterKey( + const newMasterKey = await this.keyService.makeMasterKey( masterPassword, this.email.trim().toLowerCase(), kdfConfig, ); - const newPasswordHash = await this.cryptoService.hashMasterKey(masterPassword, newMasterKey); + const newPasswordHash = await this.keyService.hashMasterKey(masterPassword, newMasterKey); // Grab user key - const userKey = await this.cryptoService.getUserKey(); + const userKey = await this.keyService.getUserKey(); if (!userKey) { throw new Error("User key not found."); } // Re-encrypt user key with new master key - const newUserKey = await this.cryptoService.encryptUserKeyWithMasterKey(newMasterKey, userKey); + const newUserKey = await this.keyService.encryptUserKeyWithMasterKey(newMasterKey, userKey); return { newPasswordHash, newUserKey: newUserKey, hint: masterPasswordHint }; } diff --git a/apps/cli/src/auth/commands/unlock.command.ts b/apps/cli/src/auth/commands/unlock.command.ts index bebaa94604..9d7f7771db 100644 --- a/apps/cli/src/auth/commands/unlock.command.ts +++ b/apps/cli/src/auth/commands/unlock.command.ts @@ -8,12 +8,12 @@ import { UserVerificationService } from "@bitwarden/common/auth/abstractions/use import { VerificationType } from "@bitwarden/common/auth/enums/verification-type"; import { MasterPasswordVerification } from "@bitwarden/common/auth/types/verification"; import { CryptoFunctionService } from "@bitwarden/common/platform/abstractions/crypto-function.service"; -import { CryptoService } from "@bitwarden/common/platform/abstractions/crypto.service"; import { EnvironmentService } from "@bitwarden/common/platform/abstractions/environment.service"; import { Utils } from "@bitwarden/common/platform/misc/utils"; import { ConsoleLogService } from "@bitwarden/common/platform/services/console-log.service"; import { MasterKey } from "@bitwarden/common/types/key"; import { SyncService } from "@bitwarden/common/vault/abstractions/sync/sync.service.abstraction"; +import { KeyService } from "@bitwarden/key-management"; import { ConvertToKeyConnectorCommand } from "../../commands/convert-to-key-connector.command"; import { Response } from "../../models/response"; @@ -24,7 +24,7 @@ export class UnlockCommand { constructor( private accountService: AccountService, private masterPasswordService: InternalMasterPasswordServiceAbstraction, - private cryptoService: CryptoService, + private keyService: KeyService, private userVerificationService: UserVerificationService, private cryptoFunctionService: CryptoFunctionService, private logService: ConsoleLogService, @@ -69,7 +69,7 @@ export class UnlockCommand { } const userKey = await this.masterPasswordService.decryptUserKeyWithMasterKey(masterKey); - await this.cryptoService.setUserKey(userKey, userId); + await this.keyService.setUserKey(userKey, userId); if (await this.keyConnectorService.getConvertAccountRequired()) { const convertToKeyConnectorCommand = new ConvertToKeyConnectorCommand( diff --git a/apps/cli/src/base-program.ts b/apps/cli/src/base-program.ts index 0f200d49d9..29a895e516 100644 --- a/apps/cli/src/base-program.ts +++ b/apps/cli/src/base-program.ts @@ -171,7 +171,7 @@ export abstract class BaseProgram { const command = new UnlockCommand( this.serviceContainer.accountService, this.serviceContainer.masterPasswordService, - this.serviceContainer.cryptoService, + this.serviceContainer.keyService, this.serviceContainer.userVerificationService, this.serviceContainer.cryptoFunctionService, this.serviceContainer.logService, diff --git a/apps/cli/src/commands/edit.command.ts b/apps/cli/src/commands/edit.command.ts index fe31bba799..2e97f68380 100644 --- a/apps/cli/src/commands/edit.command.ts +++ b/apps/cli/src/commands/edit.command.ts @@ -7,12 +7,12 @@ import { AccountService } from "@bitwarden/common/auth/abstractions/account.serv import { CipherExport } from "@bitwarden/common/models/export/cipher.export"; import { CollectionExport } from "@bitwarden/common/models/export/collection.export"; import { FolderExport } from "@bitwarden/common/models/export/folder.export"; -import { CryptoService } from "@bitwarden/common/platform/abstractions/crypto.service"; import { EncryptService } from "@bitwarden/common/platform/abstractions/encrypt.service"; import { Utils } from "@bitwarden/common/platform/misc/utils"; import { CipherService } from "@bitwarden/common/vault/abstractions/cipher.service"; import { FolderApiServiceAbstraction } from "@bitwarden/common/vault/abstractions/folder/folder-api.service.abstraction"; import { FolderService } from "@bitwarden/common/vault/abstractions/folder/folder.service.abstraction"; +import { KeyService } from "@bitwarden/key-management"; import { OrganizationCollectionRequest } from "../admin-console/models/request/organization-collection.request"; import { OrganizationCollectionResponse } from "../admin-console/models/response/organization-collection.response"; @@ -25,7 +25,7 @@ export class EditCommand { constructor( private cipherService: CipherService, private folderService: FolderService, - private cryptoService: CryptoService, + private keyService: KeyService, private encryptService: EncryptService, private apiService: ApiService, private folderApiService: FolderApiServiceAbstraction, @@ -143,7 +143,7 @@ export class EditCommand { folderView = FolderExport.toView(req, folderView); const activeUserId = await firstValueFrom(this.accountService.activeAccount$); - const userKey = await this.cryptoService.getUserKeyWithLegacySupport(activeUserId.id); + const userKey = await this.keyService.getUserKeyWithLegacySupport(activeUserId.id); const encFolder = await this.folderService.encrypt(folderView, userKey); try { await this.folderApiService.save(encFolder); @@ -174,7 +174,7 @@ export class EditCommand { return Response.badRequest("`organizationid` option does not match request object."); } try { - const orgKey = await this.cryptoService.getOrgKey(req.organizationId); + const orgKey = await this.keyService.getOrgKey(req.organizationId); if (orgKey == null) { throw new Error("No encryption key for this organization."); } diff --git a/apps/cli/src/commands/get.command.ts b/apps/cli/src/commands/get.command.ts index 1cd1cdc0f7..0bf1487b2e 100644 --- a/apps/cli/src/commands/get.command.ts +++ b/apps/cli/src/commands/get.command.ts @@ -20,7 +20,6 @@ import { LoginUriExport } from "@bitwarden/common/models/export/login-uri.export import { LoginExport } from "@bitwarden/common/models/export/login.export"; import { SecureNoteExport } from "@bitwarden/common/models/export/secure-note.export"; import { ErrorResponse } from "@bitwarden/common/models/response/error.response"; -import { CryptoService } from "@bitwarden/common/platform/abstractions/crypto.service"; import { EncryptService } from "@bitwarden/common/platform/abstractions/encrypt.service"; import { StateService } from "@bitwarden/common/platform/abstractions/state.service"; import { Utils } from "@bitwarden/common/platform/misc/utils"; @@ -33,6 +32,7 @@ import { TotpService } from "@bitwarden/common/vault/abstractions/totp.service"; import { CipherType } from "@bitwarden/common/vault/enums"; import { CipherView } from "@bitwarden/common/vault/models/view/cipher.view"; import { FolderView } from "@bitwarden/common/vault/models/view/folder.view"; +import { KeyService } from "@bitwarden/key-management"; import { OrganizationCollectionRequest } from "../admin-console/models/request/organization-collection.request"; import { OrganizationCollectionResponse } from "../admin-console/models/response/organization-collection.response"; @@ -56,7 +56,7 @@ export class GetCommand extends DownloadCommand { private collectionService: CollectionService, private totpService: TotpService, private auditService: AuditService, - private cryptoService: CryptoService, + private keyService: KeyService, encryptService: EncryptService, private stateService: StateService, private searchService: SearchService, @@ -377,7 +377,7 @@ export class GetCommand extends DownloadCommand { const key = attachments[0].key != null ? attachments[0].key - : await this.cryptoService.getOrgKey(cipher.organizationId); + : await this.keyService.getOrgKey(cipher.organizationId); return await this.saveAttachmentToFile(url, key, attachments[0].fileName, options.output); } @@ -411,7 +411,7 @@ export class GetCommand extends DownloadCommand { if (Utils.isGuid(id)) { const collection = await this.collectionService.get(id); if (collection != null) { - const orgKeys = await firstValueFrom(this.cryptoService.activeUserOrgKeys$); + const orgKeys = await firstValueFrom(this.keyService.activeUserOrgKeys$); decCollection = await collection.decrypt( orgKeys[collection.organizationId as OrganizationId], ); @@ -445,7 +445,7 @@ export class GetCommand extends DownloadCommand { return Response.badRequest("`" + options.organizationId + "` is not a GUID."); } try { - const orgKey = await this.cryptoService.getOrgKey(options.organizationId); + const orgKey = await this.keyService.getOrgKey(options.organizationId); if (orgKey == null) { throw new Error("No encryption key for this organization."); } @@ -553,13 +553,13 @@ export class GetCommand extends DownloadCommand { const activeUserId = await firstValueFrom( this.accountService.activeAccount$.pipe(map((a) => a?.id)), ); - const publicKey = await firstValueFrom(this.cryptoService.userPublicKey$(activeUserId)); - fingerprint = await this.cryptoService.getFingerprint(activeUserId, publicKey); + const publicKey = await firstValueFrom(this.keyService.userPublicKey$(activeUserId)); + fingerprint = await this.keyService.getFingerprint(activeUserId, publicKey); } else if (Utils.isGuid(id)) { try { const response = await this.apiService.getUserPublicKey(id); const pubKey = Utils.fromB64ToArray(response.publicKey); - fingerprint = await this.cryptoService.getFingerprint(id, pubKey); + fingerprint = await this.keyService.getFingerprint(id, pubKey); } catch { // eslint-disable-next-line } diff --git a/apps/cli/src/oss-serve-configurator.ts b/apps/cli/src/oss-serve-configurator.ts index a204ec6422..a25357f6f6 100644 --- a/apps/cli/src/oss-serve-configurator.ts +++ b/apps/cli/src/oss-serve-configurator.ts @@ -56,7 +56,7 @@ export class OssServeConfigurator { this.serviceContainer.collectionService, this.serviceContainer.totpService, this.serviceContainer.auditService, - this.serviceContainer.cryptoService, + this.serviceContainer.keyService, this.serviceContainer.encryptService, this.serviceContainer.stateService, this.serviceContainer.searchService, @@ -79,7 +79,7 @@ export class OssServeConfigurator { this.createCommand = new CreateCommand( this.serviceContainer.cipherService, this.serviceContainer.folderService, - this.serviceContainer.cryptoService, + this.serviceContainer.keyService, this.serviceContainer.encryptService, this.serviceContainer.apiService, this.serviceContainer.folderApiService, @@ -90,7 +90,7 @@ export class OssServeConfigurator { this.editCommand = new EditCommand( this.serviceContainer.cipherService, this.serviceContainer.folderService, - this.serviceContainer.cryptoService, + this.serviceContainer.keyService, this.serviceContainer.encryptService, this.serviceContainer.apiService, this.serviceContainer.folderApiService, @@ -117,7 +117,7 @@ export class OssServeConfigurator { ); this.confirmCommand = new ConfirmCommand( this.serviceContainer.apiService, - this.serviceContainer.cryptoService, + this.serviceContainer.keyService, this.serviceContainer.encryptService, this.serviceContainer.organizationUserApiService, ); @@ -130,7 +130,7 @@ export class OssServeConfigurator { this.unlockCommand = new UnlockCommand( this.serviceContainer.accountService, this.serviceContainer.masterPasswordService, - this.serviceContainer.cryptoService, + this.serviceContainer.keyService, this.serviceContainer.userVerificationService, this.serviceContainer.cryptoFunctionService, this.serviceContainer.logService, @@ -399,7 +399,7 @@ export class OssServeConfigurator { this.processResponse(res, Response.error("You are not logged in.")); return true; } - if (await this.serviceContainer.cryptoService.hasUserKey()) { + if (await this.serviceContainer.keyService.hasUserKey()) { return false; } this.processResponse(res, Response.error("Vault is locked.")); diff --git a/apps/cli/src/program.ts b/apps/cli/src/program.ts index 7582c76095..7e0f75de4e 100644 --- a/apps/cli/src/program.ts +++ b/apps/cli/src/program.ts @@ -150,7 +150,7 @@ export class Program extends BaseProgram { this.serviceContainer.passwordStrengthService, this.serviceContainer.platformUtilsService, this.serviceContainer.accountService, - this.serviceContainer.cryptoService, + this.serviceContainer.keyService, this.serviceContainer.policyService, this.serviceContainer.twoFactorService, this.serviceContainer.syncService, @@ -258,7 +258,7 @@ export class Program extends BaseProgram { const command = new UnlockCommand( this.serviceContainer.accountService, this.serviceContainer.masterPasswordService, - this.serviceContainer.cryptoService, + this.serviceContainer.keyService, this.serviceContainer.userVerificationService, this.serviceContainer.cryptoFunctionService, this.serviceContainer.logService, diff --git a/apps/cli/src/service-container/service-container.ts b/apps/cli/src/service-container/service-container.ts index 9180863d50..48f4e17b34 100644 --- a/apps/cli/src/service-container/service-container.ts +++ b/apps/cli/src/service-container/service-container.ts @@ -79,7 +79,6 @@ import { AppIdService } from "@bitwarden/common/platform/services/app-id.service import { ConfigApiService } from "@bitwarden/common/platform/services/config/config-api.service"; import { DefaultConfigService } from "@bitwarden/common/platform/services/config/default-config.service"; import { ContainerService } from "@bitwarden/common/platform/services/container.service"; -import { CryptoService } from "@bitwarden/common/platform/services/crypto.service"; import { EncryptServiceImplementation } from "@bitwarden/common/platform/services/cryptography/encrypt.service.implementation"; import { FallbackBulkEncryptService } from "@bitwarden/common/platform/services/cryptography/fallback-bulk-encrypt.service"; import { DefaultEnvironmentService } from "@bitwarden/common/platform/services/default-environment.service"; @@ -127,6 +126,7 @@ import { import { SendApiService } from "@bitwarden/common/tools/send/services/send-api.service"; import { SendStateProvider } from "@bitwarden/common/tools/send/services/send-state.provider"; import { SendService } from "@bitwarden/common/tools/send/services/send.service"; +import { UserId } from "@bitwarden/common/types/guid"; import { VaultTimeoutStringType } from "@bitwarden/common/types/vault-timeout.type"; import { InternalFolderService } from "@bitwarden/common/vault/abstractions/folder/folder.service.abstraction"; import { @@ -148,7 +148,11 @@ import { ImportService, ImportServiceAbstraction, } from "@bitwarden/importer/core"; -import { BiometricStateService, DefaultBiometricStateService } from "@bitwarden/key-management"; +import { + DefaultKeyService as KeyService, + BiometricStateService, + DefaultBiometricStateService, +} from "@bitwarden/key-management"; import { NodeCryptoFunctionService } from "@bitwarden/node/services/node-crypto-function.service"; import { IndividualVaultExportService, @@ -187,7 +191,7 @@ export class ServiceContainer { memoryStorageForStateProviders: MemoryStorageServiceForStateProviders; i18nService: I18nService; platformUtilsService: CliPlatformUtilsService; - cryptoService: CryptoService; + keyService: KeyService; tokenService: TokenService; appIdService: AppIdService; apiService: NodeApiService; @@ -416,7 +420,7 @@ export class ServiceContainer { this.stateService, ); - this.cryptoService = new CryptoService( + this.keyService = new KeyService( this.pinService, this.masterPasswordService, this.keyGenerationService, @@ -449,7 +453,7 @@ export class ServiceContainer { this.accountService, this.pinService, this.userDecryptionOptionsService, - this.cryptoService, + this.keyService, this.tokenService, this.policyService, this.biometricStateService, @@ -474,7 +478,7 @@ export class ServiceContainer { customUserAgent, ); - this.containerService = new ContainerService(this.cryptoService, this.encryptService); + this.containerService = new ContainerService(this.keyService, this.encryptService); this.domainSettingsService = new DefaultDomainSettingsService(this.stateProvider); @@ -483,7 +487,7 @@ export class ServiceContainer { this.sendStateProvider = new SendStateProvider(this.stateProvider); this.sendService = new SendService( - this.cryptoService, + this.keyService, this.i18nService, this.keyGenerationService, this.sendStateProvider, @@ -504,7 +508,7 @@ export class ServiceContainer { this.searchService = new SearchService(this.logService, this.i18nService, this.stateProvider); this.collectionService = new DefaultCollectionService( - this.cryptoService, + this.keyService, this.encryptService, this.i18nService, this.stateProvider, @@ -517,7 +521,7 @@ export class ServiceContainer { this.keyConnectorService = new KeyConnectorService( this.accountService, this.masterPasswordService, - this.cryptoService, + this.keyService, this.apiService, this.tokenService, this.logService, @@ -542,7 +546,7 @@ export class ServiceContainer { this.platformUtilsService, this.accountService, this.kdfConfigService, - this.cryptoService, + this.keyService, this.apiService, customUserAgent, ); @@ -551,7 +555,7 @@ export class ServiceContainer { this.passwordGenerationService = legacyPasswordGenerationServiceFactory( this.encryptService, - this.cryptoService, + this.keyService, this.policyService, this.accountService, this.stateProvider, @@ -561,7 +565,7 @@ export class ServiceContainer { this.appIdService, this.accountService, this.masterPasswordService, - this.cryptoService, + this.keyService, this.encryptService, this.apiService, this.stateProvider, @@ -576,7 +580,7 @@ export class ServiceContainer { this.authService = new AuthService( this.accountService, this.messagingService, - this.cryptoService, + this.keyService, this.apiService, this.stateService, this.tokenService, @@ -596,7 +600,7 @@ export class ServiceContainer { this.deviceTrustService = new DeviceTrustService( this.keyGenerationService, this.cryptoFunctionService, - this.cryptoService, + this.keyService, this.encryptService, this.appIdService, this.devicesApiService, @@ -612,7 +616,7 @@ export class ServiceContainer { this.loginStrategyService = new LoginStrategyService( this.accountService, this.masterPasswordService, - this.cryptoService, + this.keyService, this.apiService, this.tokenService, this.appIdService, @@ -644,7 +648,7 @@ export class ServiceContainer { ); this.cipherService = new CipherService( - this.cryptoService, + this.keyService, this.domainSettingsService, this.apiService, this.i18nService, @@ -660,7 +664,7 @@ export class ServiceContainer { ); this.folderService = new FolderService( - this.cryptoService, + this.keyService, this.encryptService, this.i18nService, this.cipherService, @@ -670,12 +674,12 @@ export class ServiceContainer { this.folderApiService = new FolderApiService(this.folderService, this.apiService); const lockedCallback = async (userId?: string) => - await this.cryptoService.clearStoredUserKey(KeySuffixOptions.Auto); + await this.keyService.clearStoredUserKey(KeySuffixOptions.Auto); this.userVerificationApiService = new UserVerificationApiService(this.apiService); this.userVerificationService = new UserVerificationService( - this.cryptoService, + this.keyService, this.accountService, this.masterPasswordService, this.i18nService, @@ -716,7 +720,7 @@ export class ServiceContainer { this.domainSettingsService, this.folderService, this.cipherService, - this.cryptoService, + this.keyService, this.collectionService, this.messagingService, this.policyService, @@ -747,7 +751,7 @@ export class ServiceContainer { this.importApiService, this.i18nService, this.collectionService, - this.cryptoService, + this.keyService, this.encryptService, this.pinService, this.accountService, @@ -757,7 +761,7 @@ export class ServiceContainer { this.folderService, this.cipherService, this.pinService, - this.cryptoService, + this.keyService, this.encryptService, this.cryptoFunctionService, this.kdfConfigService, @@ -768,7 +772,7 @@ export class ServiceContainer { this.cipherService, this.apiService, this.pinService, - this.cryptoService, + this.keyService, this.encryptService, this.cryptoFunctionService, this.collectionService, @@ -781,7 +785,7 @@ export class ServiceContainer { this.organizationExportService, ); - this.userAutoUnlockKeyService = new UserAutoUnlockKeyService(this.cryptoService); + this.userAutoUnlockKeyService = new UserAutoUnlockKeyService(this.keyService); this.auditService = new AuditService(this.cryptoFunctionService, this.apiService); @@ -823,17 +827,17 @@ export class ServiceContainer { }); const userId = await firstValueFrom(this.accountService.activeAccount$.pipe(map((a) => a?.id))); await Promise.all([ - this.eventUploadService.uploadEvents(userId), - this.cryptoService.clearKeys(), + this.eventUploadService.uploadEvents(userId as UserId), + this.keyService.clearKeys(), this.cipherService.clear(userId), this.folderService.clear(userId), this.collectionService.clear(userId), ]); - await this.stateEventRunnerService.handleEvent("logout", userId); + await this.stateEventRunnerService.handleEvent("logout", userId as UserId); await this.stateService.clean(); - await this.accountService.clean(userId); + await this.accountService.clean(userId as UserId); await this.accountService.switchAccount(null); process.env.BW_SESSION = undefined; } diff --git a/apps/cli/src/tools/send/commands/receive.command.ts b/apps/cli/src/tools/send/commands/receive.command.ts index a8740992f7..76fdc3fca6 100644 --- a/apps/cli/src/tools/send/commands/receive.command.ts +++ b/apps/cli/src/tools/send/commands/receive.command.ts @@ -4,7 +4,6 @@ import { firstValueFrom } from "rxjs"; import { ErrorResponse } from "@bitwarden/common/models/response/error.response"; import { CryptoFunctionService } from "@bitwarden/common/platform/abstractions/crypto-function.service"; -import { CryptoService } from "@bitwarden/common/platform/abstractions/crypto.service"; import { EncryptService } from "@bitwarden/common/platform/abstractions/encrypt.service"; import { EnvironmentService } from "@bitwarden/common/platform/abstractions/environment.service"; import { PlatformUtilsService } from "@bitwarden/common/platform/abstractions/platform-utils.service"; @@ -15,6 +14,7 @@ import { SendAccess } from "@bitwarden/common/tools/send/models/domain/send-acce import { SendAccessRequest } from "@bitwarden/common/tools/send/models/request/send-access.request"; import { SendAccessView } from "@bitwarden/common/tools/send/models/view/send-access.view"; import { SendApiService } from "@bitwarden/common/tools/send/services/send-api.service.abstraction"; +import { KeyService } from "@bitwarden/key-management"; import { NodeUtils } from "@bitwarden/node/node-utils"; import { DownloadCommand } from "../../../commands/download.command"; @@ -27,7 +27,7 @@ export class SendReceiveCommand extends DownloadCommand { private sendAccessRequest: SendAccessRequest; constructor( - private cryptoService: CryptoService, + private keyService: KeyService, encryptService: EncryptService, private cryptoFunctionService: CryptoFunctionService, private platformUtilsService: PlatformUtilsService, @@ -146,7 +146,7 @@ export class SendReceiveCommand extends DownloadCommand { ); const sendAccess = new SendAccess(sendResponse); - this.decKey = await this.cryptoService.makeSendKey(key); + this.decKey = await this.keyService.makeSendKey(key); return await sendAccess.decrypt(this.decKey); } catch (e) { if (e instanceof ErrorResponse) { diff --git a/apps/cli/src/tools/send/send.program.ts b/apps/cli/src/tools/send/send.program.ts index 878eaa52b2..60e78137e7 100644 --- a/apps/cli/src/tools/send/send.program.ts +++ b/apps/cli/src/tools/send/send.program.ts @@ -100,7 +100,7 @@ export class SendProgram extends BaseProgram { }) .action(async (url: string, options: OptionValues) => { const cmd = new SendReceiveCommand( - this.serviceContainer.cryptoService, + this.serviceContainer.keyService, this.serviceContainer.encryptService, this.serviceContainer.cryptoFunctionService, this.serviceContainer.platformUtilsService, @@ -142,7 +142,7 @@ export class SendProgram extends BaseProgram { this.serviceContainer.collectionService, this.serviceContainer.totpService, this.serviceContainer.auditService, - this.serviceContainer.cryptoService, + this.serviceContainer.keyService, this.serviceContainer.encryptService, this.serviceContainer.stateService, this.serviceContainer.searchService, diff --git a/apps/cli/src/vault.program.ts b/apps/cli/src/vault.program.ts index cbc8c3620d..4d3215944e 100644 --- a/apps/cli/src/vault.program.ts +++ b/apps/cli/src/vault.program.ts @@ -177,7 +177,7 @@ export class VaultProgram extends BaseProgram { this.serviceContainer.collectionService, this.serviceContainer.totpService, this.serviceContainer.auditService, - this.serviceContainer.cryptoService, + this.serviceContainer.keyService, this.serviceContainer.encryptService, this.serviceContainer.stateService, this.serviceContainer.searchService, @@ -224,7 +224,7 @@ export class VaultProgram extends BaseProgram { const command = new CreateCommand( this.serviceContainer.cipherService, this.serviceContainer.folderService, - this.serviceContainer.cryptoService, + this.serviceContainer.keyService, this.serviceContainer.encryptService, this.serviceContainer.apiService, this.serviceContainer.folderApiService, @@ -273,7 +273,7 @@ export class VaultProgram extends BaseProgram { const command = new EditCommand( this.serviceContainer.cipherService, this.serviceContainer.folderService, - this.serviceContainer.cryptoService, + this.serviceContainer.keyService, this.serviceContainer.encryptService, this.serviceContainer.apiService, this.serviceContainer.folderApiService, @@ -415,7 +415,7 @@ export class VaultProgram extends BaseProgram { await this.exitIfLocked(); const command = new ConfirmCommand( this.serviceContainer.apiService, - this.serviceContainer.cryptoService, + this.serviceContainer.keyService, this.serviceContainer.encryptService, this.serviceContainer.organizationUserApiService, ); diff --git a/apps/cli/src/vault/create.command.ts b/apps/cli/src/vault/create.command.ts index 74d1a4e0ad..35bd68b74e 100644 --- a/apps/cli/src/vault/create.command.ts +++ b/apps/cli/src/vault/create.command.ts @@ -12,12 +12,12 @@ import { BillingAccountProfileStateService } from "@bitwarden/common/billing/abs import { CipherExport } from "@bitwarden/common/models/export/cipher.export"; import { CollectionExport } from "@bitwarden/common/models/export/collection.export"; import { FolderExport } from "@bitwarden/common/models/export/folder.export"; -import { CryptoService } from "@bitwarden/common/platform/abstractions/crypto.service"; import { EncryptService } from "@bitwarden/common/platform/abstractions/encrypt.service"; import { Utils } from "@bitwarden/common/platform/misc/utils"; import { CipherService } from "@bitwarden/common/vault/abstractions/cipher.service"; import { FolderApiServiceAbstraction } from "@bitwarden/common/vault/abstractions/folder/folder-api.service.abstraction"; import { FolderService } from "@bitwarden/common/vault/abstractions/folder/folder.service.abstraction"; +import { KeyService } from "@bitwarden/key-management"; import { OrganizationCollectionRequest } from "../admin-console/models/request/organization-collection.request"; import { OrganizationCollectionResponse } from "../admin-console/models/response/organization-collection.response"; @@ -31,7 +31,7 @@ export class CreateCommand { constructor( private cipherService: CipherService, private folderService: FolderService, - private cryptoService: CryptoService, + private keyService: KeyService, private encryptService: EncryptService, private apiService: ApiService, private folderApiService: FolderApiServiceAbstraction, @@ -141,7 +141,7 @@ export class CreateCommand { return Response.error("Premium status is required to use this feature."); } - const userKey = await this.cryptoService.getUserKey(); + const userKey = await this.keyService.getUserKey(); if (userKey == null) { return Response.error( "You must update your encryption key before you can use this feature. " + @@ -170,7 +170,7 @@ export class CreateCommand { private async createFolder(req: FolderExport) { const activeAccountId = await firstValueFrom(this.accountService.activeAccount$); - const userKey = await this.cryptoService.getUserKeyWithLegacySupport(activeAccountId.id); + const userKey = await this.keyService.getUserKeyWithLegacySupport(activeAccountId.id); const folder = await this.folderService.encrypt(FolderExport.toView(req), userKey); try { await this.folderApiService.save(folder); @@ -194,7 +194,7 @@ export class CreateCommand { return Response.badRequest("`organizationid` option does not match request object."); } try { - const orgKey = await this.cryptoService.getOrgKey(req.organizationId); + const orgKey = await this.keyService.getOrgKey(req.organizationId); if (orgKey == null) { throw new Error("No encryption key for this organization."); } diff --git a/apps/desktop/src/app/accounts/settings.component.ts b/apps/desktop/src/app/accounts/settings.component.ts index f7cd2bdc4d..572dbc5e8b 100644 --- a/apps/desktop/src/app/accounts/settings.component.ts +++ b/apps/desktop/src/app/accounts/settings.component.ts @@ -13,7 +13,6 @@ import { AutofillSettingsServiceAbstraction } from "@bitwarden/common/autofill/s import { DomainSettingsService } from "@bitwarden/common/autofill/services/domain-settings.service"; import { DeviceType } from "@bitwarden/common/enums"; import { VaultTimeoutAction } from "@bitwarden/common/enums/vault-timeout-action.enum"; -import { CryptoService } from "@bitwarden/common/platform/abstractions/crypto.service"; import { I18nService } from "@bitwarden/common/platform/abstractions/i18n.service"; import { LogService } from "@bitwarden/common/platform/abstractions/log.service"; import { MessagingService } from "@bitwarden/common/platform/abstractions/messaging.service"; @@ -29,7 +28,7 @@ import { VaultTimeoutStringType, } from "@bitwarden/common/types/vault-timeout.type"; import { DialogService } from "@bitwarden/components"; -import { BiometricsService, BiometricStateService } from "@bitwarden/key-management"; +import { KeyService, BiometricsService, BiometricStateService } from "@bitwarden/key-management"; import { SetPinComponent } from "../../auth/components/set-pin.component"; import { DesktopAutofillSettingsService } from "../../autofill/services/desktop-autofill-settings.service"; @@ -126,7 +125,7 @@ export class SettingsComponent implements OnInit, OnDestroy { private stateService: StateService, private autofillSettingsService: AutofillSettingsServiceAbstraction, private messagingService: MessagingService, - private cryptoService: CryptoService, + private keyService: KeyService, private themeStateService: ThemeStateService, private domainSettingsService: DomainSettingsService, private dialogService: DialogService, @@ -460,7 +459,7 @@ export class SettingsComponent implements OnInit, OnDestroy { if (!enabled || !this.supportsBiometric) { this.form.controls.biometric.setValue(false, { emitEvent: false }); await this.biometricStateService.setBiometricUnlockEnabled(false); - await this.cryptoService.refreshAdditionalKeys(); + await this.keyService.refreshAdditionalKeys(); return; } @@ -499,10 +498,10 @@ export class SettingsComponent implements OnInit, OnDestroy { await this.biometricStateService.setRequirePasswordOnStart(true); await this.biometricStateService.setDismissedRequirePasswordOnStartCallout(); } - await this.cryptoService.refreshAdditionalKeys(); + await this.keyService.refreshAdditionalKeys(); // Validate the key is stored in case biometrics fail. - const biometricSet = await this.cryptoService.hasUserKeyStored(KeySuffixOptions.Biometric); + const biometricSet = await this.keyService.hasUserKeyStored(KeySuffixOptions.Biometric); this.form.controls.biometric.setValue(biometricSet, { emitEvent: false }); if (!biometricSet) { await this.biometricStateService.setBiometricUnlockEnabled(false); @@ -534,7 +533,7 @@ export class SettingsComponent implements OnInit, OnDestroy { await this.biometricStateService.setRequirePasswordOnStart(false); } await this.biometricStateService.setDismissedRequirePasswordOnStartCallout(); - await this.cryptoService.refreshAdditionalKeys(); + await this.keyService.refreshAdditionalKeys(); } async saveFavicons() { diff --git a/apps/desktop/src/app/app.component.ts b/apps/desktop/src/app/app.component.ts index 83dc1619fa..cefcb9d709 100644 --- a/apps/desktop/src/app/app.component.ts +++ b/apps/desktop/src/app/app.component.ts @@ -35,7 +35,6 @@ import { VaultTimeoutAction } from "@bitwarden/common/enums/vault-timeout-action import { ProcessReloadServiceAbstraction } from "@bitwarden/common/key-management/abstractions/process-reload.service"; import { BroadcasterService } from "@bitwarden/common/platform/abstractions/broadcaster.service"; import { ConfigService } from "@bitwarden/common/platform/abstractions/config/config.service"; -import { CryptoService } from "@bitwarden/common/platform/abstractions/crypto.service"; import { I18nService } from "@bitwarden/common/platform/abstractions/i18n.service"; import { LogService } from "@bitwarden/common/platform/abstractions/log.service"; import { MessagingService } from "@bitwarden/common/platform/abstractions/messaging.service"; @@ -53,7 +52,7 @@ import { InternalFolderService } from "@bitwarden/common/vault/abstractions/fold import { CipherType } from "@bitwarden/common/vault/enums"; import { DialogService, ToastOptions, ToastService } from "@bitwarden/components"; import { PasswordGenerationServiceAbstraction } from "@bitwarden/generator-legacy"; -import { BiometricStateService } from "@bitwarden/key-management"; +import { KeyService, BiometricStateService } from "@bitwarden/key-management"; import { DeleteAccountComponent } from "../auth/delete-account.component"; import { LoginApprovalComponent } from "../auth/login/login-approval.component"; @@ -135,7 +134,7 @@ export class AppComponent implements OnInit, OnDestroy { private ngZone: NgZone, private vaultTimeoutService: VaultTimeoutService, private vaultTimeoutSettingsService: VaultTimeoutSettingsService, - private cryptoService: CryptoService, + private keyService: KeyService, private logService: LogService, private messagingService: MessagingService, private collectionService: CollectionService, @@ -303,8 +302,8 @@ export class AppComponent implements OnInit, OnDestroy { const activeUserId = await firstValueFrom( this.accountService.activeAccount$.pipe(map((a) => a?.id)), ); - const publicKey = await firstValueFrom(this.cryptoService.userPublicKey$(activeUserId)); - const fingerprint = await this.cryptoService.getFingerprint(activeUserId, publicKey); + const publicKey = await firstValueFrom(this.keyService.userPublicKey$(activeUserId)); + const fingerprint = await this.keyService.getFingerprint(activeUserId, publicKey); const dialogRef = FingerprintDialogComponent.open(this.dialogService, { fingerprint }); await firstValueFrom(dialogRef.closed); break; @@ -692,7 +691,7 @@ export class AppComponent implements OnInit, OnDestroy { // Provide the userId of the user to upload events for await this.eventUploadService.uploadEvents(userBeingLoggedOut); - await this.cryptoService.clearKeys(userBeingLoggedOut); + await this.keyService.clearKeys(userBeingLoggedOut); await this.cipherService.clear(userBeingLoggedOut); await this.folderService.clear(userBeingLoggedOut); await this.collectionService.clear(userBeingLoggedOut); diff --git a/apps/desktop/src/app/services/init.service.ts b/apps/desktop/src/app/services/init.service.ts index 8793587300..bc3f63a790 100644 --- a/apps/desktop/src/app/services/init.service.ts +++ b/apps/desktop/src/app/services/init.service.ts @@ -8,7 +8,6 @@ import { EventUploadService as EventUploadServiceAbstraction } from "@bitwarden/ import { NotificationsService as NotificationsServiceAbstraction } from "@bitwarden/common/abstractions/notifications.service"; import { AccountService } from "@bitwarden/common/auth/abstractions/account.service"; import { TwoFactorService as TwoFactorServiceAbstraction } from "@bitwarden/common/auth/abstractions/two-factor.service"; -import { CryptoService as CryptoServiceAbstraction } from "@bitwarden/common/platform/abstractions/crypto.service"; import { EncryptService } from "@bitwarden/common/platform/abstractions/encrypt.service"; import { I18nService as I18nServiceAbstraction } from "@bitwarden/common/platform/abstractions/i18n.service"; import { PlatformUtilsService as PlatformUtilsServiceAbstraction } from "@bitwarden/common/platform/abstractions/platform-utils.service"; @@ -19,6 +18,7 @@ import { SyncService as SyncServiceAbstraction } from "@bitwarden/common/platfor import { EventUploadService } from "@bitwarden/common/services/event/event-upload.service"; import { VaultTimeoutService } from "@bitwarden/common/services/vault-timeout/vault-timeout.service"; import { UserId } from "@bitwarden/common/types/guid"; +import { KeyService as KeyServiceAbstraction } from "@bitwarden/key-management"; import { I18nRendererService } from "../../platform/services/i18n.renderer.service"; import { NativeMessagingService } from "../../services/native-messaging.service"; @@ -35,7 +35,7 @@ export class InitService { private notificationsService: NotificationsServiceAbstraction, private platformUtilsService: PlatformUtilsServiceAbstraction, private stateService: StateServiceAbstraction, - private cryptoService: CryptoServiceAbstraction, + private keyService: KeyServiceAbstraction, private nativeMessagingService: NativeMessagingService, private themingService: AbstractThemingService, private encryptService: EncryptService, @@ -73,7 +73,7 @@ export class InitService { htmlEl.classList.add("os_" + this.platformUtilsService.getDeviceString()); this.themingService.applyThemeChangesTo(this.document); - const containerService = new ContainerService(this.cryptoService, this.encryptService); + const containerService = new ContainerService(this.keyService, this.encryptService); containerService.attachToGlobal(this.win); }; } diff --git a/apps/desktop/src/app/services/services.module.ts b/apps/desktop/src/app/services/services.module.ts index 3611368442..d3a7b7c0a1 100644 --- a/apps/desktop/src/app/services/services.module.ts +++ b/apps/desktop/src/app/services/services.module.ts @@ -40,10 +40,6 @@ import { ClientType } from "@bitwarden/common/enums"; import { ProcessReloadServiceAbstraction } from "@bitwarden/common/key-management/abstractions/process-reload.service"; import { ProcessReloadService } from "@bitwarden/common/key-management/services/process-reload.service"; import { CryptoFunctionService as CryptoFunctionServiceAbstraction } from "@bitwarden/common/platform/abstractions/crypto-function.service"; -import { - CryptoService, - CryptoService as CryptoServiceAbstraction, -} from "@bitwarden/common/platform/abstractions/crypto.service"; import { EncryptService } from "@bitwarden/common/platform/abstractions/encrypt.service"; import { FileDownloadService } from "@bitwarden/common/platform/abstractions/file-download/file-download.service"; import { I18nService as I18nServiceAbstraction } from "@bitwarden/common/platform/abstractions/i18n.service"; @@ -74,13 +70,18 @@ import { VaultTimeoutStringType } from "@bitwarden/common/types/vault-timeout.ty import { CipherService as CipherServiceAbstraction } from "@bitwarden/common/vault/abstractions/cipher.service"; import { DialogService } from "@bitwarden/components"; import { PasswordGenerationServiceAbstraction } from "@bitwarden/generator-legacy"; -import { BiometricStateService, BiometricsService } from "@bitwarden/key-management"; +import { + KeyService, + KeyService as KeyServiceAbstraction, + BiometricStateService, + BiometricsService, +} from "@bitwarden/key-management"; import { DesktopAutofillSettingsService } from "../../autofill/services/desktop-autofill-settings.service"; import { ElectronBiometricsService } from "../../key-management/biometrics/electron-biometrics.service"; import { flagEnabled } from "../../platform/flags"; import { DesktopSettingsService } from "../../platform/services/desktop-settings.service"; -import { ElectronCryptoService } from "../../platform/services/electron-crypto.service"; +import { ElectronKeyService } from "../../platform/services/electron-key.service"; import { ElectronLogRendererService } from "../../platform/services/electron-log.renderer.service"; import { ELECTRON_SUPPORTS_SECURE_STORAGE, @@ -260,8 +261,8 @@ const safeProviders: SafeProvider[] = [ deps: [WINDOW], }), safeProvider({ - provide: CryptoServiceAbstraction, - useClass: ElectronCryptoService, + provide: KeyServiceAbstraction, + useClass: ElectronKeyService, deps: [ PinServiceAbstraction, InternalMasterPasswordServiceAbstraction, @@ -304,7 +305,7 @@ const safeProviders: SafeProvider[] = [ useClass: DesktopSetPasswordJitService, deps: [ ApiService, - CryptoService, + KeyService, EncryptService, I18nServiceAbstraction, KdfConfigService, diff --git a/apps/desktop/src/auth/lock.component.spec.ts b/apps/desktop/src/auth/lock.component.spec.ts index 6bf3442882..b67a386845 100644 --- a/apps/desktop/src/auth/lock.component.spec.ts +++ b/apps/desktop/src/auth/lock.component.spec.ts @@ -20,7 +20,6 @@ import { InternalMasterPasswordServiceAbstraction } from "@bitwarden/common/auth import { UserVerificationService } from "@bitwarden/common/auth/abstractions/user-verification/user-verification.service.abstraction"; import { FakeMasterPasswordService } from "@bitwarden/common/auth/services/master-password/fake-master-password.service"; import { BroadcasterService } from "@bitwarden/common/platform/abstractions/broadcaster.service"; -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"; import { LogService } from "@bitwarden/common/platform/abstractions/log.service"; @@ -34,6 +33,7 @@ import { UserId } from "@bitwarden/common/types/guid"; import { SyncService } from "@bitwarden/common/vault/abstractions/sync/sync.service.abstraction"; import { DialogService, ToastService } from "@bitwarden/components"; import { + KeyService, BiometricsService as AbstractBiometricService, BiometricStateService, } from "@bitwarden/key-management"; @@ -106,8 +106,8 @@ describe("LockComponent", () => { useValue: messagingServiceMock, }, { - provide: CryptoService, - useValue: mock(), + provide: KeyService, + useValue: mock(), }, { provide: VaultTimeoutService, diff --git a/apps/desktop/src/auth/lock.component.ts b/apps/desktop/src/auth/lock.component.ts index 6ab39f92a6..cc062965f3 100644 --- a/apps/desktop/src/auth/lock.component.ts +++ b/apps/desktop/src/auth/lock.component.ts @@ -17,7 +17,6 @@ import { InternalMasterPasswordServiceAbstraction } from "@bitwarden/common/auth import { UserVerificationService } from "@bitwarden/common/auth/abstractions/user-verification/user-verification.service.abstraction"; import { DeviceType } from "@bitwarden/common/enums"; import { BroadcasterService } from "@bitwarden/common/platform/abstractions/broadcaster.service"; -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"; import { LogService } from "@bitwarden/common/platform/abstractions/log.service"; @@ -27,7 +26,7 @@ import { StateService } from "@bitwarden/common/platform/abstractions/state.serv import { PasswordStrengthServiceAbstraction } from "@bitwarden/common/tools/password-strength"; import { SyncService } from "@bitwarden/common/vault/abstractions/sync/sync.service.abstraction"; import { DialogService, ToastService } from "@bitwarden/components"; -import { BiometricsService, BiometricStateService } from "@bitwarden/key-management"; +import { KeyService, BiometricsService, BiometricStateService } from "@bitwarden/key-management"; const BroadcasterSubscriptionId = "LockComponent"; @@ -48,7 +47,7 @@ export class LockComponent extends BaseLockComponent implements OnInit, OnDestro i18nService: I18nService, platformUtilsService: PlatformUtilsService, messagingService: MessagingService, - cryptoService: CryptoService, + keyService: KeyService, vaultTimeoutService: VaultTimeoutService, vaultTimeoutSettingsService: VaultTimeoutSettingsService, environmentService: EnvironmentService, @@ -79,7 +78,7 @@ export class LockComponent extends BaseLockComponent implements OnInit, OnDestro i18nService, platformUtilsService, messagingService, - cryptoService, + keyService, vaultTimeoutService, vaultTimeoutSettingsService, environmentService, diff --git a/apps/desktop/src/auth/login/login-approval.component.ts b/apps/desktop/src/auth/login/login-approval.component.ts index 4bffc338b3..e6428e0020 100644 --- a/apps/desktop/src/auth/login/login-approval.component.ts +++ b/apps/desktop/src/auth/login/login-approval.component.ts @@ -9,7 +9,6 @@ import { ApiService } from "@bitwarden/common/abstractions/api.service"; import { AccountService } from "@bitwarden/common/auth/abstractions/account.service"; import { AuthRequestResponse } from "@bitwarden/common/auth/models/response/auth-request.response"; import { AppIdService } from "@bitwarden/common/platform/abstractions/app-id.service"; -import { CryptoService } from "@bitwarden/common/platform/abstractions/crypto.service"; import { I18nService } from "@bitwarden/common/platform/abstractions/i18n.service"; import { PlatformUtilsService } from "@bitwarden/common/platform/abstractions/platform-utils.service"; import { Utils } from "@bitwarden/common/platform/misc/utils"; @@ -20,6 +19,7 @@ import { DialogService, ToastService, } from "@bitwarden/components"; +import { KeyService } from "@bitwarden/key-management"; const RequestTimeOut = 60000 * 15; //15 Minutes const RequestTimeUpdate = 60000 * 5; //5 Minutes @@ -53,7 +53,7 @@ export class LoginApprovalComponent implements OnInit, OnDestroy { protected i18nService: I18nService, protected apiService: ApiService, protected appIdService: AppIdService, - protected cryptoService: CryptoService, + protected keyService: KeyService, private dialogRef: DialogRef, private toastService: ToastService, ) { diff --git a/apps/desktop/src/auth/login/login-via-auth-request.component.ts b/apps/desktop/src/auth/login/login-via-auth-request.component.ts index 12be2f01c0..8459dc7441 100644 --- a/apps/desktop/src/auth/login/login-via-auth-request.component.ts +++ b/apps/desktop/src/auth/login/login-via-auth-request.component.ts @@ -16,7 +16,6 @@ import { AuthService } from "@bitwarden/common/auth/abstractions/auth.service"; import { DeviceTrustServiceAbstraction } from "@bitwarden/common/auth/abstractions/device-trust.service.abstraction"; import { AppIdService } from "@bitwarden/common/platform/abstractions/app-id.service"; import { CryptoFunctionService } from "@bitwarden/common/platform/abstractions/crypto-function.service"; -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"; import { LogService } from "@bitwarden/common/platform/abstractions/log.service"; @@ -25,6 +24,7 @@ import { ValidationService } from "@bitwarden/common/platform/abstractions/valid import { SyncService } from "@bitwarden/common/vault/abstractions/sync/sync.service.abstraction"; import { ToastService } from "@bitwarden/components"; import { PasswordGenerationServiceAbstraction } from "@bitwarden/generator-legacy"; +import { KeyService } from "@bitwarden/key-management"; import { EnvironmentComponent } from "../environment.component"; @@ -39,7 +39,7 @@ export class LoginViaAuthRequestComponent extends BaseLoginWithDeviceComponent { constructor( protected router: Router, - cryptoService: CryptoService, + keyService: KeyService, cryptoFunctionService: CryptoFunctionService, appIdService: AppIdService, passwordGenerationService: PasswordGenerationServiceAbstraction, @@ -63,7 +63,7 @@ export class LoginViaAuthRequestComponent extends BaseLoginWithDeviceComponent { ) { super( router, - cryptoService, + keyService, cryptoFunctionService, appIdService, passwordGenerationService, diff --git a/apps/desktop/src/auth/register.component.ts b/apps/desktop/src/auth/register.component.ts index e7c2cfd32b..f3df5b8847 100644 --- a/apps/desktop/src/auth/register.component.ts +++ b/apps/desktop/src/auth/register.component.ts @@ -8,7 +8,6 @@ import { LoginStrategyServiceAbstraction } from "@bitwarden/auth/common"; import { ApiService } from "@bitwarden/common/abstractions/api.service"; import { AuditService } from "@bitwarden/common/abstractions/audit.service"; import { BroadcasterService } from "@bitwarden/common/platform/abstractions/broadcaster.service"; -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"; import { LogService } from "@bitwarden/common/platform/abstractions/log.service"; @@ -16,6 +15,7 @@ import { PlatformUtilsService } from "@bitwarden/common/platform/abstractions/pl import { StateService } from "@bitwarden/common/platform/abstractions/state.service"; import { DialogService, ToastService } from "@bitwarden/components"; import { PasswordGenerationServiceAbstraction } from "@bitwarden/generator-legacy"; +import { KeyService } from "@bitwarden/key-management"; const BroadcasterSubscriptionId = "RegisterComponent"; @@ -30,7 +30,7 @@ export class RegisterComponent extends BaseRegisterComponent implements OnInit, loginStrategyService: LoginStrategyServiceAbstraction, router: Router, i18nService: I18nService, - cryptoService: CryptoService, + keyService: KeyService, apiService: ApiService, stateService: StateService, platformUtilsService: PlatformUtilsService, @@ -49,7 +49,7 @@ export class RegisterComponent extends BaseRegisterComponent implements OnInit, loginStrategyService, router, i18nService, - cryptoService, + keyService, apiService, stateService, platformUtilsService, diff --git a/apps/desktop/src/auth/set-password.component.ts b/apps/desktop/src/auth/set-password.component.ts index 21bc7e8db1..61ab198b61 100644 --- a/apps/desktop/src/auth/set-password.component.ts +++ b/apps/desktop/src/auth/set-password.component.ts @@ -13,7 +13,6 @@ import { KdfConfigService } from "@bitwarden/common/auth/abstractions/kdf-config import { InternalMasterPasswordServiceAbstraction } from "@bitwarden/common/auth/abstractions/master-password.service.abstraction"; import { SsoLoginServiceAbstraction } from "@bitwarden/common/auth/abstractions/sso-login.service.abstraction"; import { BroadcasterService } from "@bitwarden/common/platform/abstractions/broadcaster.service"; -import { CryptoService } from "@bitwarden/common/platform/abstractions/crypto.service"; import { EncryptService } from "@bitwarden/common/platform/abstractions/encrypt.service"; import { I18nService } from "@bitwarden/common/platform/abstractions/i18n.service"; import { MessagingService } from "@bitwarden/common/platform/abstractions/messaging.service"; @@ -24,6 +23,7 @@ import { MasterKey, UserKey } from "@bitwarden/common/types/key"; import { SyncService } from "@bitwarden/common/vault/abstractions/sync/sync.service.abstraction"; import { DialogService, ToastService } from "@bitwarden/components"; import { PasswordGenerationServiceAbstraction } from "@bitwarden/generator-legacy"; +import { KeyService } from "@bitwarden/key-management"; const BroadcasterSubscriptionId = "SetPasswordComponent"; @@ -37,7 +37,7 @@ export class SetPasswordComponent extends BaseSetPasswordComponent implements On masterPasswordService: InternalMasterPasswordServiceAbstraction, apiService: ApiService, i18nService: I18nService, - cryptoService: CryptoService, + keyService: KeyService, messagingService: MessagingService, passwordGenerationService: PasswordGenerationServiceAbstraction, platformUtilsService: PlatformUtilsService, @@ -62,7 +62,7 @@ export class SetPasswordComponent extends BaseSetPasswordComponent implements On accountService, masterPasswordService, i18nService, - cryptoService, + keyService, messagingService, passwordGenerationService, platformUtilsService, diff --git a/apps/desktop/src/platform/services/electron-crypto.service.spec.ts b/apps/desktop/src/platform/services/electron-key.service.spec.ts similarity index 96% rename from apps/desktop/src/platform/services/electron-crypto.service.spec.ts rename to apps/desktop/src/platform/services/electron-key.service.spec.ts index 0674151741..8705f1fba6 100644 --- a/apps/desktop/src/platform/services/electron-crypto.service.spec.ts +++ b/apps/desktop/src/platform/services/electron-key.service.spec.ts @@ -22,10 +22,10 @@ import { mockAccountServiceWith, } from "../../../../../libs/common/spec/fake-account-service"; -import { ElectronCryptoService } from "./electron-crypto.service"; +import { ElectronKeyService } from "./electron-key.service"; -describe("electronCryptoService", () => { - let sut: ElectronCryptoService; +describe("electronKeyService", () => { + let sut: ElectronKeyService; const pinService = mock(); const keyGenerationService = mock(); @@ -47,7 +47,7 @@ describe("electronCryptoService", () => { masterPasswordService = new FakeMasterPasswordService(); stateProvider = new FakeStateProvider(accountService); - sut = new ElectronCryptoService( + sut = new ElectronKeyService( pinService, masterPasswordService, keyGenerationService, diff --git a/apps/desktop/src/platform/services/electron-crypto.service.ts b/apps/desktop/src/platform/services/electron-key.service.ts similarity index 96% rename from apps/desktop/src/platform/services/electron-crypto.service.ts rename to apps/desktop/src/platform/services/electron-key.service.ts index b780f1ebc2..f7cfb3cf92 100644 --- a/apps/desktop/src/platform/services/electron-crypto.service.ts +++ b/apps/desktop/src/platform/services/electron-key.service.ts @@ -13,14 +13,13 @@ import { StateService } from "@bitwarden/common/platform/abstractions/state.serv import { KeySuffixOptions } from "@bitwarden/common/platform/enums"; import { Utils } from "@bitwarden/common/platform/misc/utils"; import { SymmetricCryptoKey } from "@bitwarden/common/platform/models/domain/symmetric-crypto-key"; -import { CryptoService } from "@bitwarden/common/platform/services/crypto.service"; import { StateProvider } from "@bitwarden/common/platform/state"; import { CsprngString } from "@bitwarden/common/types/csprng"; import { UserId } from "@bitwarden/common/types/guid"; import { UserKey } from "@bitwarden/common/types/key"; -import { BiometricStateService } from "@bitwarden/key-management"; +import { DefaultKeyService, BiometricStateService } from "@bitwarden/key-management"; -export class ElectronCryptoService extends CryptoService { +export class ElectronKeyService extends DefaultKeyService { constructor( pinService: PinServiceAbstraction, masterPasswordService: InternalMasterPasswordServiceAbstraction, diff --git a/apps/desktop/src/services/desktop-lock-component.service.spec.ts b/apps/desktop/src/services/desktop-lock-component.service.spec.ts index ff1f8328ea..0d673a5b51 100644 --- a/apps/desktop/src/services/desktop-lock-component.service.spec.ts +++ b/apps/desktop/src/services/desktop-lock-component.service.spec.ts @@ -9,10 +9,9 @@ import { } from "@bitwarden/auth/common"; import { VaultTimeoutSettingsService } from "@bitwarden/common/abstractions/vault-timeout/vault-timeout-settings.service"; import { DeviceType } from "@bitwarden/common/enums"; -import { CryptoService } from "@bitwarden/common/platform/abstractions/crypto.service"; import { PlatformUtilsService } from "@bitwarden/common/platform/abstractions/platform-utils.service"; import { UserId } from "@bitwarden/common/types/guid"; -import { BiometricsService } from "@bitwarden/key-management"; +import { KeyService, BiometricsService } from "@bitwarden/key-management"; import { DesktopLockComponentService } from "./desktop-lock-component.service"; @@ -38,7 +37,7 @@ describe("DesktopLockComponentService", () => { let biometricsService: MockProxy; let pinService: MockProxy; let vaultTimeoutSettingsService: MockProxy; - let cryptoService: MockProxy; + let keyService: MockProxy; beforeEach(() => { userDecryptionOptionsService = mock(); @@ -46,7 +45,7 @@ describe("DesktopLockComponentService", () => { biometricsService = mock(); pinService = mock(); vaultTimeoutSettingsService = mock(); - cryptoService = mock(); + keyService = mock(); TestBed.configureTestingModule({ providers: [ @@ -72,8 +71,8 @@ describe("DesktopLockComponentService", () => { useValue: vaultTimeoutSettingsService, }, { - provide: CryptoService, - useValue: cryptoService, + provide: KeyService, + useValue: keyService, }, ], }); @@ -358,9 +357,7 @@ describe("DesktopLockComponentService", () => { // Biometrics biometricsService.supportsBiometric.mockResolvedValue(mockInputs.osSupportsBiometric); vaultTimeoutSettingsService.isBiometricLockSet.mockResolvedValue(mockInputs.biometricLockSet); - cryptoService.hasUserKeyStored.mockResolvedValue( - mockInputs.hasBiometricEncryptedUserKeyStored, - ); + keyService.hasUserKeyStored.mockResolvedValue(mockInputs.hasBiometricEncryptedUserKeyStored); platformUtilsService.supportsSecureStorage.mockReturnValue( mockInputs.platformSupportsSecureStorage, ); diff --git a/apps/desktop/src/services/desktop-lock-component.service.ts b/apps/desktop/src/services/desktop-lock-component.service.ts index f31ee93a72..7402779121 100644 --- a/apps/desktop/src/services/desktop-lock-component.service.ts +++ b/apps/desktop/src/services/desktop-lock-component.service.ts @@ -12,11 +12,10 @@ import { } from "@bitwarden/auth/common"; import { VaultTimeoutSettingsService } from "@bitwarden/common/abstractions/vault-timeout/vault-timeout-settings.service"; import { DeviceType } from "@bitwarden/common/enums"; -import { CryptoService } from "@bitwarden/common/platform/abstractions/crypto.service"; import { PlatformUtilsService } from "@bitwarden/common/platform/abstractions/platform-utils.service"; import { KeySuffixOptions } from "@bitwarden/common/platform/enums"; import { UserId } from "@bitwarden/common/types/guid"; -import { BiometricsService } from "@bitwarden/key-management"; +import { KeyService, BiometricsService } from "@bitwarden/key-management"; export class DesktopLockComponentService implements LockComponentService { private readonly userDecryptionOptionsService = inject(UserDecryptionOptionsServiceAbstraction); @@ -24,7 +23,7 @@ export class DesktopLockComponentService implements LockComponentService { private readonly biometricsService = inject(BiometricsService); private readonly pinService = inject(PinServiceAbstraction); private readonly vaultTimeoutSettingsService = inject(VaultTimeoutSettingsService); - private readonly cryptoService = inject(CryptoService); + private readonly keyService = inject(KeyService); constructor() {} @@ -55,7 +54,7 @@ export class DesktopLockComponentService implements LockComponentService { private async isBiometricLockSet(userId: UserId): Promise { const biometricLockSet = await this.vaultTimeoutSettingsService.isBiometricLockSet(userId); - const hasBiometricEncryptedUserKeyStored = await this.cryptoService.hasUserKeyStored( + const hasBiometricEncryptedUserKeyStored = await this.keyService.hasUserKeyStored( KeySuffixOptions.Biometric, userId, ); diff --git a/apps/desktop/src/services/native-messaging.service.ts b/apps/desktop/src/services/native-messaging.service.ts index 7f707737c5..c9830030ef 100644 --- a/apps/desktop/src/services/native-messaging.service.ts +++ b/apps/desktop/src/services/native-messaging.service.ts @@ -5,7 +5,6 @@ import { AccountService } from "@bitwarden/common/auth/abstractions/account.serv import { AuthService } from "@bitwarden/common/auth/abstractions/auth.service"; import { AuthenticationStatus } from "@bitwarden/common/auth/enums/authentication-status"; import { CryptoFunctionService } from "@bitwarden/common/platform/abstractions/crypto-function.service"; -import { CryptoService } from "@bitwarden/common/platform/abstractions/crypto.service"; import { EncryptService } from "@bitwarden/common/platform/abstractions/encrypt.service"; import { LogService } from "@bitwarden/common/platform/abstractions/log.service"; import { MessagingService } from "@bitwarden/common/platform/abstractions/messaging.service"; @@ -15,7 +14,7 @@ import { EncString } from "@bitwarden/common/platform/models/domain/enc-string"; import { SymmetricCryptoKey } from "@bitwarden/common/platform/models/domain/symmetric-crypto-key"; import { UserId } from "@bitwarden/common/types/guid"; import { DialogService } from "@bitwarden/components"; -import { BiometricsService, BiometricStateService } from "@bitwarden/key-management"; +import { KeyService, BiometricsService, BiometricStateService } from "@bitwarden/key-management"; import { BrowserSyncVerificationDialogComponent } from "../app/components/browser-sync-verification-dialog.component"; import { LegacyMessage } from "../models/native-messaging/legacy-message"; @@ -32,7 +31,7 @@ const HashAlgorithmForAsymmetricEncryption = "sha1"; export class NativeMessagingService { constructor( private cryptoFunctionService: CryptoFunctionService, - private cryptoService: CryptoService, + private keyService: KeyService, private encryptService: EncryptService, private logService: LogService, private messagingService: MessagingService, @@ -81,7 +80,7 @@ export class NativeMessagingService { appId: appId, }); - const fingerprint = await this.cryptoService.getFingerprint( + const fingerprint = await this.keyService.getFingerprint( rawMessage.userId, remotePublicKey, ); @@ -172,7 +171,7 @@ export class NativeMessagingService { } try { - const userKey = await this.cryptoService.getUserKeyFromStorage( + const userKey = await this.keyService.getUserKeyFromStorage( KeySuffixOptions.Biometric, message.userId, ); diff --git a/apps/desktop/src/vault/app/vault/attachments.component.ts b/apps/desktop/src/vault/app/vault/attachments.component.ts index 47e08a13cd..2b554ba229 100644 --- a/apps/desktop/src/vault/app/vault/attachments.component.ts +++ b/apps/desktop/src/vault/app/vault/attachments.component.ts @@ -4,7 +4,6 @@ import { AttachmentsComponent as BaseAttachmentsComponent } from "@bitwarden/ang import { ApiService } from "@bitwarden/common/abstractions/api.service"; import { AccountService } from "@bitwarden/common/auth/abstractions/account.service"; import { BillingAccountProfileStateService } from "@bitwarden/common/billing/abstractions/account/billing-account-profile-state.service"; -import { CryptoService } from "@bitwarden/common/platform/abstractions/crypto.service"; import { EncryptService } from "@bitwarden/common/platform/abstractions/encrypt.service"; import { FileDownloadService } from "@bitwarden/common/platform/abstractions/file-download/file-download.service"; import { I18nService } from "@bitwarden/common/platform/abstractions/i18n.service"; @@ -13,6 +12,7 @@ import { PlatformUtilsService } from "@bitwarden/common/platform/abstractions/pl import { StateService } from "@bitwarden/common/platform/abstractions/state.service"; import { CipherService } from "@bitwarden/common/vault/abstractions/cipher.service"; import { DialogService, ToastService } from "@bitwarden/components"; +import { KeyService } from "@bitwarden/key-management"; @Component({ selector: "app-vault-attachments", @@ -22,7 +22,7 @@ export class AttachmentsComponent extends BaseAttachmentsComponent { constructor( cipherService: CipherService, i18nService: I18nService, - cryptoService: CryptoService, + keyService: KeyService, encryptService: EncryptService, platformUtilsService: PlatformUtilsService, apiService: ApiService, @@ -37,7 +37,7 @@ export class AttachmentsComponent extends BaseAttachmentsComponent { super( cipherService, i18nService, - cryptoService, + keyService, encryptService, platformUtilsService, apiService, diff --git a/apps/desktop/src/vault/app/vault/folder-add-edit.component.ts b/apps/desktop/src/vault/app/vault/folder-add-edit.component.ts index 0cc55d65f3..1cab5a940d 100644 --- a/apps/desktop/src/vault/app/vault/folder-add-edit.component.ts +++ b/apps/desktop/src/vault/app/vault/folder-add-edit.component.ts @@ -3,13 +3,13 @@ import { FormBuilder } from "@angular/forms"; import { FolderAddEditComponent as BaseFolderAddEditComponent } from "@bitwarden/angular/vault/components/folder-add-edit.component"; import { AccountService } from "@bitwarden/common/auth/abstractions/account.service"; -import { CryptoService } from "@bitwarden/common/platform/abstractions/crypto.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 { FolderApiServiceAbstraction } from "@bitwarden/common/vault/abstractions/folder/folder-api.service.abstraction"; import { FolderService } from "@bitwarden/common/vault/abstractions/folder/folder.service.abstraction"; import { DialogService } from "@bitwarden/components"; +import { KeyService } from "@bitwarden/key-management"; @Component({ selector: "app-folder-add-edit", @@ -20,7 +20,7 @@ export class FolderAddEditComponent extends BaseFolderAddEditComponent { folderService: FolderService, folderApiService: FolderApiServiceAbstraction, accountService: AccountService, - cryptoService: CryptoService, + keyService: KeyService, i18nService: I18nService, platformUtilsService: PlatformUtilsService, logService: LogService, @@ -31,7 +31,7 @@ export class FolderAddEditComponent extends BaseFolderAddEditComponent { folderService, folderApiService, accountService, - cryptoService, + keyService, i18nService, platformUtilsService, logService, diff --git a/apps/desktop/src/vault/app/vault/view.component.ts b/apps/desktop/src/vault/app/vault/view.component.ts index 82f68b65ad..60380ba225 100644 --- a/apps/desktop/src/vault/app/vault/view.component.ts +++ b/apps/desktop/src/vault/app/vault/view.component.ts @@ -18,7 +18,6 @@ import { AccountService } from "@bitwarden/common/auth/abstractions/account.serv import { TokenService } from "@bitwarden/common/auth/abstractions/token.service"; import { BillingAccountProfileStateService } from "@bitwarden/common/billing/abstractions/account/billing-account-profile-state.service"; import { BroadcasterService } from "@bitwarden/common/platform/abstractions/broadcaster.service"; -import { CryptoService } from "@bitwarden/common/platform/abstractions/crypto.service"; import { EncryptService } from "@bitwarden/common/platform/abstractions/encrypt.service"; import { FileDownloadService } from "@bitwarden/common/platform/abstractions/file-download/file-download.service"; import { I18nService } from "@bitwarden/common/platform/abstractions/i18n.service"; @@ -32,6 +31,7 @@ import { TotpService } from "@bitwarden/common/vault/abstractions/totp.service"; import { CipherView } from "@bitwarden/common/vault/models/view/cipher.view"; import { CipherAuthorizationService } from "@bitwarden/common/vault/services/cipher-authorization.service"; import { DialogService } from "@bitwarden/components"; +import { KeyService } from "@bitwarden/key-management"; import { PasswordRepromptService } from "@bitwarden/vault"; const BroadcasterSubscriptionId = "ViewComponent"; @@ -49,7 +49,7 @@ export class ViewComponent extends BaseViewComponent implements OnInit, OnDestro totpService: TotpService, tokenService: TokenService, i18nService: I18nService, - cryptoService: CryptoService, + keyService: KeyService, encryptService: EncryptService, platformUtilsService: PlatformUtilsService, auditService: AuditService, @@ -75,7 +75,7 @@ export class ViewComponent extends BaseViewComponent implements OnInit, OnDestro totpService, tokenService, i18nService, - cryptoService, + keyService, encryptService, platformUtilsService, auditService, diff --git a/apps/web/src/app/admin-console/common/base-members.component.ts b/apps/web/src/app/admin-console/common/base-members.component.ts index 2d0d66e293..8de0d022e2 100644 --- a/apps/web/src/app/admin-console/common/base-members.component.ts +++ b/apps/web/src/app/admin-console/common/base-members.component.ts @@ -14,12 +14,12 @@ import { } from "@bitwarden/common/admin-console/enums"; import { ProviderUserUserDetailsResponse } from "@bitwarden/common/admin-console/models/response/provider/provider-user.response"; import { ListResponse } from "@bitwarden/common/models/response/list.response"; -import { CryptoService } from "@bitwarden/common/platform/abstractions/crypto.service"; import { I18nService } from "@bitwarden/common/platform/abstractions/i18n.service"; import { LogService } from "@bitwarden/common/platform/abstractions/log.service"; import { ValidationService } from "@bitwarden/common/platform/abstractions/validation.service"; import { Utils } from "@bitwarden/common/platform/misc/utils"; import { DialogService, ToastService } from "@bitwarden/components"; +import { KeyService } from "@bitwarden/key-management"; import { OrganizationUserView } from "../organizations/core/views/organization-user.view"; import { UserConfirmComponent } from "../organizations/manage/user-confirm.component"; @@ -78,7 +78,7 @@ export abstract class BaseMembersComponent { constructor( protected apiService: ApiService, protected i18nService: I18nService, - protected cryptoService: CryptoService, + protected keyService: KeyService, protected validationService: ValidationService, private logService: LogService, protected userNamePipe: UserNamePipe, @@ -213,7 +213,7 @@ export abstract class BaseMembersComponent { } try { - const fingerprint = await this.cryptoService.getFingerprint(user.userId, publicKey); + const fingerprint = await this.keyService.getFingerprint(user.userId, publicKey); this.logService.info(`User's fingerprint: ${fingerprint.join("-")}`); } catch (e) { this.logService.error(e); diff --git a/apps/web/src/app/admin-console/common/base.people.component.ts b/apps/web/src/app/admin-console/common/base.people.component.ts index e24f3ac78e..6b4f09cbd8 100644 --- a/apps/web/src/app/admin-console/common/base.people.component.ts +++ b/apps/web/src/app/admin-console/common/base.people.component.ts @@ -16,13 +16,13 @@ import { } from "@bitwarden/common/admin-console/enums"; import { ProviderUserUserDetailsResponse } from "@bitwarden/common/admin-console/models/response/provider/provider-user.response"; import { ListResponse } from "@bitwarden/common/models/response/list.response"; -import { CryptoService } from "@bitwarden/common/platform/abstractions/crypto.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 { ValidationService } from "@bitwarden/common/platform/abstractions/validation.service"; import { Utils } from "@bitwarden/common/platform/misc/utils"; import { DialogService, ToastService } from "@bitwarden/components"; +import { KeyService } from "@bitwarden/key-management"; import { OrganizationUserView } from "../organizations/core/views/organization-user.view"; import { UserConfirmComponent } from "../organizations/manage/user-confirm.component"; @@ -119,7 +119,7 @@ export abstract class BasePeopleComponent< private searchService: SearchService, protected i18nService: I18nService, protected platformUtilsService: PlatformUtilsService, - protected cryptoService: CryptoService, + protected keyService: KeyService, protected validationService: ValidationService, protected modalService: ModalService, private logService: LogService, @@ -384,7 +384,7 @@ export abstract class BasePeopleComponent< } try { - const fingerprint = await this.cryptoService.getFingerprint(user.userId, publicKey); + const fingerprint = await this.keyService.getFingerprint(user.userId, publicKey); this.logService.info(`User's fingerprint: ${fingerprint.join("-")}`); } catch (e) { this.logService.error(e); diff --git a/apps/web/src/app/admin-console/organizations/manage/user-confirm.component.ts b/apps/web/src/app/admin-console/organizations/manage/user-confirm.component.ts index e96b349e03..c533f73927 100644 --- a/apps/web/src/app/admin-console/organizations/manage/user-confirm.component.ts +++ b/apps/web/src/app/admin-console/organizations/manage/user-confirm.component.ts @@ -3,9 +3,9 @@ import { Component, Inject, OnInit } from "@angular/core"; import { FormControl, FormGroup } from "@angular/forms"; import { OrganizationManagementPreferencesService } from "@bitwarden/common/admin-console/abstractions/organization-management-preferences/organization-management-preferences.service"; -import { CryptoService } from "@bitwarden/common/platform/abstractions/crypto.service"; import { LogService } from "@bitwarden/common/platform/abstractions/log.service"; import { DialogService } from "@bitwarden/components"; +import { KeyService } from "@bitwarden/key-management"; export type UserConfirmDialogData = { name: string; @@ -34,7 +34,7 @@ export class UserConfirmComponent implements OnInit { constructor( @Inject(DIALOG_DATA) protected data: UserConfirmDialogData, private dialogRef: DialogRef, - private cryptoService: CryptoService, + private keyService: KeyService, private logService: LogService, private organizationManagementPreferencesService: OrganizationManagementPreferencesService, ) { @@ -46,7 +46,7 @@ export class UserConfirmComponent implements OnInit { async ngOnInit() { try { if (this.publicKey != null) { - const fingerprint = await this.cryptoService.getFingerprint(this.userId, this.publicKey); + const fingerprint = await this.keyService.getFingerprint(this.userId, this.publicKey); if (fingerprint != null) { this.fingerprint = fingerprint.join("-"); } diff --git a/apps/web/src/app/admin-console/organizations/members/components/bulk/base-bulk-confirm.component.ts b/apps/web/src/app/admin-console/organizations/members/components/bulk/base-bulk-confirm.component.ts index 3cbb71878c..3e9bef4534 100644 --- a/apps/web/src/app/admin-console/organizations/members/components/bulk/base-bulk-confirm.component.ts +++ b/apps/web/src/app/admin-console/organizations/members/components/bulk/base-bulk-confirm.component.ts @@ -7,11 +7,11 @@ import { import { ProviderUserBulkPublicKeyResponse } from "@bitwarden/common/admin-console/models/response/provider/provider-user-bulk-public-key.response"; import { ProviderUserBulkResponse } from "@bitwarden/common/admin-console/models/response/provider/provider-user-bulk.response"; import { ListResponse } from "@bitwarden/common/models/response/list.response"; -import { CryptoService } from "@bitwarden/common/platform/abstractions/crypto.service"; import { EncryptService } from "@bitwarden/common/platform/abstractions/encrypt.service"; import { I18nService } from "@bitwarden/common/platform/abstractions/i18n.service"; import { Utils } from "@bitwarden/common/platform/misc/utils"; import { SymmetricCryptoKey } from "@bitwarden/common/platform/models/domain/symmetric-crypto-key"; +import { KeyService } from "@bitwarden/key-management"; import { BulkUserDetails } from "./bulk-status.component"; @@ -31,7 +31,7 @@ export abstract class BaseBulkConfirmComponent implements OnInit { protected error: string; protected constructor( - protected cryptoService: CryptoService, + protected keyService: KeyService, protected encryptService: EncryptService, protected i18nService: I18nService, ) {} @@ -48,7 +48,7 @@ export abstract class BaseBulkConfirmComponent implements OnInit { for (const entry of publicKeysResponse.data) { const publicKey = Utils.fromB64ToArray(entry.key); - const fingerprint = await this.cryptoService.getFingerprint(entry.userId, publicKey); + const fingerprint = await this.keyService.getFingerprint(entry.userId, publicKey); if (fingerprint != null) { this.publicKeys.set(entry.id, publicKey); this.fingerprints.set(entry.id, fingerprint.join("-")); diff --git a/apps/web/src/app/admin-console/organizations/members/components/bulk/bulk-confirm-dialog.component.ts b/apps/web/src/app/admin-console/organizations/members/components/bulk/bulk-confirm-dialog.component.ts index 8e6ec1dbc3..9c03c9e61c 100644 --- a/apps/web/src/app/admin-console/organizations/members/components/bulk/bulk-confirm-dialog.component.ts +++ b/apps/web/src/app/admin-console/organizations/members/components/bulk/bulk-confirm-dialog.component.ts @@ -13,7 +13,6 @@ import { OrganizationUserStatusType } from "@bitwarden/common/admin-console/enum import { ProviderUserBulkPublicKeyResponse } from "@bitwarden/common/admin-console/models/response/provider/provider-user-bulk-public-key.response"; import { ProviderUserBulkResponse } from "@bitwarden/common/admin-console/models/response/provider/provider-user-bulk.response"; import { ListResponse } from "@bitwarden/common/models/response/list.response"; -import { CryptoService } from "@bitwarden/common/platform/abstractions/crypto.service"; import { EncryptService } from "@bitwarden/common/platform/abstractions/encrypt.service"; import { I18nService } from "@bitwarden/common/platform/abstractions/i18n.service"; import { SymmetricCryptoKey } from "@bitwarden/common/platform/models/domain/symmetric-crypto-key"; @@ -21,6 +20,7 @@ import { StateProvider } from "@bitwarden/common/platform/state"; import { OrganizationId } from "@bitwarden/common/types/guid"; import { OrgKey } from "@bitwarden/common/types/key"; import { DialogService } from "@bitwarden/components"; +import { KeyService } from "@bitwarden/key-management"; import { BaseBulkConfirmComponent } from "./base-bulk-confirm.component"; import { BulkUserDetails } from "./bulk-status.component"; @@ -39,18 +39,18 @@ export class BulkConfirmDialogComponent extends BaseBulkConfirmComponent { users: BulkUserDetails[]; constructor( - protected cryptoService: CryptoService, + protected keyService: KeyService, @Inject(DIALOG_DATA) protected dialogParams: BulkConfirmDialogParams, protected encryptService: EncryptService, private organizationUserApiService: OrganizationUserApiService, protected i18nService: I18nService, private stateProvider: StateProvider, ) { - super(cryptoService, encryptService, i18nService); + super(keyService, encryptService, i18nService); this.organizationId = dialogParams.organizationId; this.organizationKey$ = this.stateProvider.activeUserId$.pipe( - switchMap((userId) => this.cryptoService.orgKeys$(userId)), + switchMap((userId) => this.keyService.orgKeys$(userId)), map((organizationKeysById) => organizationKeysById[this.organizationId as OrganizationId]), takeUntilDestroyed(), ); diff --git a/apps/web/src/app/admin-console/organizations/members/members.component.ts b/apps/web/src/app/admin-console/organizations/members/members.component.ts index 7ee99ff2e3..394c900f8d 100644 --- a/apps/web/src/app/admin-console/organizations/members/members.component.ts +++ b/apps/web/src/app/admin-console/organizations/members/members.component.ts @@ -42,13 +42,13 @@ import { BillingApiServiceAbstraction } from "@bitwarden/common/billing/abstract import { isNotSelfUpgradable, ProductTierType } from "@bitwarden/common/billing/enums"; import { FeatureFlag } from "@bitwarden/common/enums/feature-flag.enum"; import { ConfigService } from "@bitwarden/common/platform/abstractions/config/config.service"; -import { CryptoService } from "@bitwarden/common/platform/abstractions/crypto.service"; import { EncryptService } from "@bitwarden/common/platform/abstractions/encrypt.service"; import { I18nService } from "@bitwarden/common/platform/abstractions/i18n.service"; import { LogService } from "@bitwarden/common/platform/abstractions/log.service"; import { ValidationService } from "@bitwarden/common/platform/abstractions/validation.service"; import { SyncService } from "@bitwarden/common/vault/abstractions/sync/sync.service.abstraction"; import { DialogService, SimpleDialogOptions, ToastService } from "@bitwarden/components"; +import { KeyService } from "@bitwarden/key-management"; import { ChangePlanDialogResultType, @@ -110,7 +110,7 @@ export class MembersComponent extends BaseMembersComponent apiService: ApiService, i18nService: I18nService, organizationManagementPreferencesService: OrganizationManagementPreferencesService, - cryptoService: CryptoService, + keyService: KeyService, private encryptService: EncryptService, validationService: ValidationService, logService: LogService, @@ -134,7 +134,7 @@ export class MembersComponent extends BaseMembersComponent super( apiService, i18nService, - cryptoService, + keyService, validationService, logService, userNamePipe, @@ -172,8 +172,8 @@ export class MembersComponent extends BaseMembersComponent this.organization.canManageUsersPassword && !this.organization.hasPublicAndPrivateKeys ) { - const orgShareKey = await this.cryptoService.getOrgKey(this.organization.id); - const orgKeys = await this.cryptoService.makeKeyPair(orgShareKey); + const orgShareKey = await this.keyService.getOrgKey(this.organization.id); + const orgKeys = await this.keyService.makeKeyPair(orgShareKey); const request = new OrganizationKeysRequest(orgKeys[0], orgKeys[1].encryptedString); const response = await this.organizationApiService.updateKeys( this.organization.id, @@ -293,7 +293,7 @@ export class MembersComponent extends BaseMembersComponent } async confirmUser(user: OrganizationUserView, publicKey: Uint8Array): Promise { - const orgKey = await this.cryptoService.getOrgKey(this.organization.id); + const orgKey = await this.keyService.getOrgKey(this.organization.id); const key = await this.encryptService.rsaEncrypt(orgKey.key, publicKey); const request = new OrganizationUserConfirmRequest(); request.key = key.encryptedString; diff --git a/apps/web/src/app/admin-console/organizations/members/services/organization-user-reset-password/organization-user-reset-password.service.spec.ts b/apps/web/src/app/admin-console/organizations/members/services/organization-user-reset-password/organization-user-reset-password.service.spec.ts index 3b903701d6..feb95df40c 100644 --- a/apps/web/src/app/admin-console/organizations/members/services/organization-user-reset-password/organization-user-reset-password.service.spec.ts +++ b/apps/web/src/app/admin-console/organizations/members/services/organization-user-reset-password/organization-user-reset-password.service.spec.ts @@ -8,7 +8,6 @@ import { OrganizationService } from "@bitwarden/common/admin-console/abstraction import { Organization } from "@bitwarden/common/admin-console/models/domain/organization"; import { OrganizationKeysResponse } from "@bitwarden/common/admin-console/models/response/organization-keys.response"; import { OrganizationApiService } from "@bitwarden/common/admin-console/services/organization/organization-api.service"; -import { CryptoService } from "@bitwarden/common/platform/abstractions/crypto.service"; import { EncryptService } from "@bitwarden/common/platform/abstractions/encrypt.service"; import { I18nService } from "@bitwarden/common/platform/abstractions/i18n.service"; import { EncryptionType, KdfType } from "@bitwarden/common/platform/enums"; @@ -17,13 +16,14 @@ import { SymmetricCryptoKey } from "@bitwarden/common/platform/models/domain/sym import { CsprngArray } from "@bitwarden/common/types/csprng"; import { UserId } from "@bitwarden/common/types/guid"; import { UserKey, OrgKey, MasterKey } from "@bitwarden/common/types/key"; +import { KeyService } from "@bitwarden/key-management"; import { OrganizationUserResetPasswordService } from "./organization-user-reset-password.service"; describe("OrganizationUserResetPasswordService", () => { let sut: OrganizationUserResetPasswordService; - let cryptoService: MockProxy; + let keyService: MockProxy; let encryptService: MockProxy; let organizationService: MockProxy; let organizationUserApiService: MockProxy; @@ -31,7 +31,7 @@ describe("OrganizationUserResetPasswordService", () => { let i18nService: MockProxy; beforeAll(() => { - cryptoService = mock(); + keyService = mock(); encryptService = mock(); organizationService = mock(); organizationUserApiService = mock(); @@ -39,7 +39,7 @@ describe("OrganizationUserResetPasswordService", () => { i18nService = mock(); sut = new OrganizationUserResetPasswordService( - cryptoService, + keyService, encryptService, organizationService, organizationUserApiService, @@ -69,7 +69,7 @@ describe("OrganizationUserResetPasswordService", () => { const mockRandomBytes = new Uint8Array(64) as CsprngArray; const mockUserKey = new SymmetricCryptoKey(mockRandomBytes) as UserKey; - cryptoService.getUserKey.mockResolvedValue(mockUserKey); + keyService.getUserKey.mockResolvedValue(mockUserKey); encryptService.rsaEncrypt.mockResolvedValue( new EncString(EncryptionType.Rsa2048_OaepSha1_B64, "mockEncryptedUserKey"), @@ -87,7 +87,7 @@ describe("OrganizationUserResetPasswordService", () => { await sut.buildRecoveryKey(mockOrgId, mockUserKey); - expect(cryptoService.getUserKey).not.toHaveBeenCalled(); + expect(keyService.getUserKey).not.toHaveBeenCalled(); }); it("should throw an error if the organization keys are null", async () => { @@ -96,7 +96,7 @@ describe("OrganizationUserResetPasswordService", () => { }); it("should throw an error if the user key can't be found", async () => { - cryptoService.getUserKey.mockResolvedValue(null); + keyService.getUserKey.mockResolvedValue(null); await expect(sut.buildRecoveryKey(mockOrgId)).rejects.toThrow(); }); @@ -125,16 +125,16 @@ describe("OrganizationUserResetPasswordService", () => { const mockRandomBytes = new Uint8Array(64) as CsprngArray; const mockOrgKey = new SymmetricCryptoKey(mockRandomBytes) as OrgKey; - cryptoService.getOrgKey.mockResolvedValue(mockOrgKey); + keyService.getOrgKey.mockResolvedValue(mockOrgKey); encryptService.decryptToBytes.mockResolvedValue(mockRandomBytes); encryptService.rsaDecrypt.mockResolvedValue(mockRandomBytes); const mockMasterKey = new SymmetricCryptoKey(mockRandomBytes) as MasterKey; - cryptoService.makeMasterKey.mockResolvedValue(mockMasterKey); - cryptoService.hashMasterKey.mockResolvedValue("test-master-key-hash"); + keyService.makeMasterKey.mockResolvedValue(mockMasterKey); + keyService.hashMasterKey.mockResolvedValue("test-master-key-hash"); const mockUserKey = new SymmetricCryptoKey(mockRandomBytes) as UserKey; - cryptoService.encryptUserKeyWithMasterKey.mockResolvedValue([ + keyService.encryptUserKeyWithMasterKey.mockResolvedValue([ mockUserKey, new EncString(EncryptionType.AesCbc256_HmacSha256_B64, "test-encrypted-user-key"), ]); @@ -153,7 +153,7 @@ describe("OrganizationUserResetPasswordService", () => { }); it("should throw an error if the org key is null", async () => { - cryptoService.getOrgKey.mockResolvedValue(null); + keyService.getOrgKey.mockResolvedValue(null); await expect( sut.resetMasterPassword(mockNewMP, mockEmail, mockOrgUserId, mockOrgId), ).rejects.toThrow(); diff --git a/apps/web/src/app/admin-console/organizations/members/services/organization-user-reset-password/organization-user-reset-password.service.ts b/apps/web/src/app/admin-console/organizations/members/services/organization-user-reset-password/organization-user-reset-password.service.ts index 6d5d7508b6..abfae811d5 100644 --- a/apps/web/src/app/admin-console/organizations/members/services/organization-user-reset-password/organization-user-reset-password.service.ts +++ b/apps/web/src/app/admin-console/organizations/members/services/organization-user-reset-password/organization-user-reset-password.service.ts @@ -13,7 +13,6 @@ import { KdfConfig, PBKDF2KdfConfig, } from "@bitwarden/common/auth/models/domain/kdf-config"; -import { CryptoService } from "@bitwarden/common/platform/abstractions/crypto.service"; import { EncryptService } from "@bitwarden/common/platform/abstractions/encrypt.service"; import { I18nService } from "@bitwarden/common/platform/abstractions/i18n.service"; import { KdfType } from "@bitwarden/common/platform/enums"; @@ -22,6 +21,7 @@ import { EncryptedString, EncString } from "@bitwarden/common/platform/models/do import { SymmetricCryptoKey } from "@bitwarden/common/platform/models/domain/symmetric-crypto-key"; import { UserId } from "@bitwarden/common/types/guid"; import { UserKey } from "@bitwarden/common/types/key"; +import { KeyService } from "@bitwarden/key-management"; @Injectable({ providedIn: "root", @@ -30,7 +30,7 @@ export class OrganizationUserResetPasswordService implements UserKeyRotationDataProvider { constructor( - private cryptoService: CryptoService, + private keyService: KeyService, private encryptService: EncryptService, private organizationService: OrganizationService, private organizationUserApiService: OrganizationUserApiService, @@ -53,7 +53,7 @@ export class OrganizationUserResetPasswordService const publicKey = Utils.fromB64ToArray(orgKeys.publicKey); // RSA Encrypt user key with organization's public key - userKey ??= await this.cryptoService.getUserKey(); + userKey ??= await this.keyService.getUserKey(); if (userKey == null) { throw new Error("No user key found"); } @@ -86,7 +86,7 @@ export class OrganizationUserResetPasswordService } // Decrypt Organization's encrypted Private Key with org key - const orgSymKey = await this.cryptoService.getOrgKey(orgId); + const orgSymKey = await this.keyService.getOrgKey(orgId); if (orgSymKey == null) { throw new Error("No org key found"); } @@ -109,18 +109,15 @@ export class OrganizationUserResetPasswordService : new Argon2KdfConfig(response.kdfIterations, response.kdfMemory, response.kdfParallelism); // Create new master key and hash new password - const newMasterKey = await this.cryptoService.makeMasterKey( + const newMasterKey = await this.keyService.makeMasterKey( newMasterPassword, email.trim().toLowerCase(), kdfConfig, ); - const newMasterKeyHash = await this.cryptoService.hashMasterKey( - newMasterPassword, - newMasterKey, - ); + const newMasterKeyHash = await this.keyService.hashMasterKey(newMasterPassword, newMasterKey); // Create new encrypted user key for the User - const newUserKey = await this.cryptoService.encryptUserKeyWithMasterKey( + const newUserKey = await this.keyService.encryptUserKeyWithMasterKey( newMasterKey, existingUserKey, ); diff --git a/apps/web/src/app/admin-console/organizations/settings/account.component.ts b/apps/web/src/app/admin-console/organizations/settings/account.component.ts index 67e94fad37..ffcf0cef9c 100644 --- a/apps/web/src/app/admin-console/organizations/settings/account.component.ts +++ b/apps/web/src/app/admin-console/organizations/settings/account.component.ts @@ -12,11 +12,11 @@ import { OrganizationUpdateRequest } from "@bitwarden/common/admin-console/model import { OrganizationResponse } from "@bitwarden/common/admin-console/models/response/organization.response"; import { FeatureFlag } from "@bitwarden/common/enums/feature-flag.enum"; import { ConfigService } from "@bitwarden/common/platform/abstractions/config/config.service"; -import { CryptoService } from "@bitwarden/common/platform/abstractions/crypto.service"; import { I18nService } from "@bitwarden/common/platform/abstractions/i18n.service"; import { PlatformUtilsService } from "@bitwarden/common/platform/abstractions/platform-utils.service"; import { Utils } from "@bitwarden/common/platform/misc/utils"; import { DialogService, ToastService } from "@bitwarden/components"; +import { KeyService } from "@bitwarden/key-management"; import { ApiKeyComponent } from "../../../auth/settings/security/api-key.component"; import { PurgeVaultComponent } from "../../../vault/settings/purge-vault.component"; @@ -85,7 +85,7 @@ export class AccountComponent implements OnInit, OnDestroy { private i18nService: I18nService, private route: ActivatedRoute, private platformUtilsService: PlatformUtilsService, - private cryptoService: CryptoService, + private keyService: KeyService, private router: Router, private organizationService: OrganizationService, private organizationApiService: OrganizationApiServiceAbstraction, @@ -194,8 +194,8 @@ export class AccountComponent implements OnInit, OnDestroy { // Backfill pub/priv key if necessary if (!this.org.hasPublicAndPrivateKeys) { - const orgShareKey = await this.cryptoService.getOrgKey(this.organizationId); - const orgKeys = await this.cryptoService.makeKeyPair(orgShareKey); + const orgShareKey = await this.keyService.getOrgKey(this.organizationId); + const orgKeys = await this.keyService.makeKeyPair(orgShareKey); request.keys = new OrganizationKeysRequest(orgKeys[0], orgKeys[1].encryptedString); } diff --git a/apps/web/src/app/app.component.ts b/apps/web/src/app/app.component.ts index 7cefdd2165..f1b079b81a 100644 --- a/apps/web/src/app/app.component.ts +++ b/apps/web/src/app/app.component.ts @@ -19,7 +19,6 @@ import { KeyConnectorService } from "@bitwarden/common/auth/abstractions/key-con import { AuthenticationStatus } from "@bitwarden/common/auth/enums/authentication-status"; import { BroadcasterService } from "@bitwarden/common/platform/abstractions/broadcaster.service"; import { ConfigService } from "@bitwarden/common/platform/abstractions/config/config.service"; -import { CryptoService } from "@bitwarden/common/platform/abstractions/crypto.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"; @@ -31,7 +30,7 @@ import { CipherService } from "@bitwarden/common/vault/abstractions/cipher.servi import { InternalFolderService } from "@bitwarden/common/vault/abstractions/folder/folder.service.abstraction"; import { DialogService, ToastOptions, ToastService } from "@bitwarden/components"; import { PasswordGenerationServiceAbstraction } from "@bitwarden/generator-legacy"; -import { BiometricStateService } from "@bitwarden/key-management"; +import { KeyService, BiometricStateService } from "@bitwarden/key-management"; import { flagEnabled } from "../utils/flags"; @@ -75,7 +74,7 @@ export class AppComponent implements OnDestroy, OnInit { private platformUtilsService: PlatformUtilsService, private ngZone: NgZone, private vaultTimeoutService: VaultTimeoutService, - private cryptoService: CryptoService, + private keyService: KeyService, private collectionService: CollectionService, private searchService: SearchService, private notificationsService: NotificationsService, @@ -317,7 +316,7 @@ export class AppComponent implements OnDestroy, OnInit { ); await Promise.all([ - this.cryptoService.clearKeys(), + this.keyService.clearKeys(), this.cipherService.clear(userId), this.folderService.clear(userId), this.collectionService.clear(userId), diff --git a/apps/web/src/app/auth/core/services/registration/web-registration-finish.service.spec.ts b/apps/web/src/app/auth/core/services/registration/web-registration-finish.service.spec.ts index 45eb3c5c0d..dc8dfcfb51 100644 --- a/apps/web/src/app/auth/core/services/registration/web-registration-finish.service.spec.ts +++ b/apps/web/src/app/auth/core/services/registration/web-registration-finish.service.spec.ts @@ -8,12 +8,12 @@ import { MasterPasswordPolicyOptions } from "@bitwarden/common/admin-console/mod import { Policy } from "@bitwarden/common/admin-console/models/domain/policy"; import { AccountApiService } from "@bitwarden/common/auth/abstractions/account-api.service"; import { DEFAULT_KDF_CONFIG } from "@bitwarden/common/auth/models/domain/kdf-config"; -import { CryptoService } from "@bitwarden/common/platform/abstractions/crypto.service"; import { LogService } from "@bitwarden/common/platform/abstractions/log.service"; import { EncString } from "@bitwarden/common/platform/models/domain/enc-string"; import { SymmetricCryptoKey } from "@bitwarden/common/platform/models/domain/symmetric-crypto-key"; import { CsprngArray } from "@bitwarden/common/types/csprng"; import { MasterKey, UserKey } from "@bitwarden/common/types/key"; +import { KeyService } from "@bitwarden/key-management"; import { AcceptOrganizationInviteService } from "../../../organization-invite/accept-organization.service"; import { OrganizationInvite } from "../../../organization-invite/organization-invite"; @@ -23,7 +23,7 @@ import { WebRegistrationFinishService } from "./web-registration-finish.service" describe("DefaultRegistrationFinishService", () => { let service: WebRegistrationFinishService; - let cryptoService: MockProxy; + let keyService: MockProxy; let accountApiService: MockProxy; let acceptOrgInviteService: MockProxy; let policyApiService: MockProxy; @@ -31,7 +31,7 @@ describe("DefaultRegistrationFinishService", () => { let policyService: MockProxy; beforeEach(() => { - cryptoService = mock(); + keyService = mock(); accountApiService = mock(); acceptOrgInviteService = mock(); policyApiService = mock(); @@ -39,7 +39,7 @@ describe("DefaultRegistrationFinishService", () => { policyService = mock(); service = new WebRegistrationFinishService( - cryptoService, + keyService, accountApiService, acceptOrgInviteService, policyApiService, @@ -193,7 +193,7 @@ describe("DefaultRegistrationFinishService", () => { }); it("throws an error if the user key cannot be created", async () => { - cryptoService.makeUserKey.mockResolvedValue([null, null]); + keyService.makeUserKey.mockResolvedValue([null, null]); await expect(service.finishRegistration(email, passwordInputResult)).rejects.toThrow( "User key could not be created", @@ -201,8 +201,8 @@ describe("DefaultRegistrationFinishService", () => { }); it("registers the user and returns a captcha bypass token when given valid email verification input", async () => { - cryptoService.makeUserKey.mockResolvedValue([userKey, userKeyEncString]); - cryptoService.makeKeyPair.mockResolvedValue(userKeyPair); + keyService.makeUserKey.mockResolvedValue([userKey, userKeyEncString]); + keyService.makeKeyPair.mockResolvedValue(userKeyPair); accountApiService.registerFinish.mockResolvedValue(capchaBypassToken); acceptOrgInviteService.getOrganizationInvite.mockResolvedValue(null); @@ -214,8 +214,8 @@ describe("DefaultRegistrationFinishService", () => { expect(result).toEqual(capchaBypassToken); - expect(cryptoService.makeUserKey).toHaveBeenCalledWith(masterKey); - expect(cryptoService.makeKeyPair).toHaveBeenCalledWith(userKey); + expect(keyService.makeUserKey).toHaveBeenCalledWith(masterKey); + expect(keyService.makeKeyPair).toHaveBeenCalledWith(userKey); expect(accountApiService.registerFinish).toHaveBeenCalledWith( expect.objectContaining({ email, @@ -238,8 +238,8 @@ describe("DefaultRegistrationFinishService", () => { }); it("it registers the user and returns a captcha bypass token when given an org invite", async () => { - cryptoService.makeUserKey.mockResolvedValue([userKey, userKeyEncString]); - cryptoService.makeKeyPair.mockResolvedValue(userKeyPair); + keyService.makeUserKey.mockResolvedValue([userKey, userKeyEncString]); + keyService.makeKeyPair.mockResolvedValue(userKeyPair); accountApiService.registerFinish.mockResolvedValue(capchaBypassToken); acceptOrgInviteService.getOrganizationInvite.mockResolvedValue(orgInvite); @@ -247,8 +247,8 @@ describe("DefaultRegistrationFinishService", () => { expect(result).toEqual(capchaBypassToken); - expect(cryptoService.makeUserKey).toHaveBeenCalledWith(masterKey); - expect(cryptoService.makeKeyPair).toHaveBeenCalledWith(userKey); + expect(keyService.makeUserKey).toHaveBeenCalledWith(masterKey); + expect(keyService.makeKeyPair).toHaveBeenCalledWith(userKey); expect(accountApiService.registerFinish).toHaveBeenCalledWith( expect.objectContaining({ email, diff --git a/apps/web/src/app/auth/core/services/registration/web-registration-finish.service.ts b/apps/web/src/app/auth/core/services/registration/web-registration-finish.service.ts index 560196dd19..03afce6348 100644 --- a/apps/web/src/app/auth/core/services/registration/web-registration-finish.service.ts +++ b/apps/web/src/app/auth/core/services/registration/web-registration-finish.service.ts @@ -11,9 +11,9 @@ import { MasterPasswordPolicyOptions } from "@bitwarden/common/admin-console/mod import { Policy } from "@bitwarden/common/admin-console/models/domain/policy"; import { AccountApiService } from "@bitwarden/common/auth/abstractions/account-api.service"; import { RegisterFinishRequest } from "@bitwarden/common/auth/models/request/registration/register-finish.request"; -import { CryptoService } from "@bitwarden/common/platform/abstractions/crypto.service"; import { LogService } from "@bitwarden/common/platform/abstractions/log.service"; import { EncryptedString, EncString } from "@bitwarden/common/platform/models/domain/enc-string"; +import { KeyService } from "@bitwarden/key-management"; import { AcceptOrganizationInviteService } from "../../../organization-invite/accept-organization.service"; @@ -22,14 +22,14 @@ export class WebRegistrationFinishService implements RegistrationFinishService { constructor( - protected cryptoService: CryptoService, + protected keyService: KeyService, protected accountApiService: AccountApiService, private acceptOrgInviteService: AcceptOrganizationInviteService, private policyApiService: PolicyApiServiceAbstraction, private logService: LogService, private policyService: PolicyService, ) { - super(cryptoService, accountApiService); + super(keyService, accountApiService); } override async getOrgNameFromOrgInvite(): Promise { diff --git a/apps/web/src/app/auth/core/services/rotateable-key-set.service.spec.ts b/apps/web/src/app/auth/core/services/rotateable-key-set.service.spec.ts index 7ba586e957..e032f19829 100644 --- a/apps/web/src/app/auth/core/services/rotateable-key-set.service.spec.ts +++ b/apps/web/src/app/auth/core/services/rotateable-key-set.service.spec.ts @@ -1,25 +1,25 @@ import { TestBed } from "@angular/core/testing"; import { mock, MockProxy } from "jest-mock-extended"; -import { CryptoService } from "@bitwarden/common/platform/abstractions/crypto.service"; import { EncryptService } from "@bitwarden/common/platform/abstractions/encrypt.service"; import { Utils } from "@bitwarden/common/platform/misc/utils"; import { SymmetricCryptoKey } from "@bitwarden/common/platform/models/domain/symmetric-crypto-key"; +import { KeyService } from "@bitwarden/key-management"; import { RotateableKeySetService } from "./rotateable-key-set.service"; describe("RotateableKeySetService", () => { let testBed!: TestBed; - let cryptoService!: MockProxy; + let keyService!: MockProxy; let encryptService!: MockProxy; let service!: RotateableKeySetService; beforeEach(() => { - cryptoService = mock(); + keyService = mock(); encryptService = mock(); testBed = TestBed.configureTestingModule({ providers: [ - { provide: CryptoService, useValue: cryptoService }, + { provide: KeyService, useValue: keyService }, { provide: EncryptService, useValue: encryptService }, ], }); @@ -33,8 +33,8 @@ describe("RotateableKeySetService", () => { const encryptedUserKey = Symbol(); const encryptedPublicKey = Symbol(); const encryptedPrivateKey = Symbol(); - cryptoService.makeKeyPair.mockResolvedValue(["publicKey", encryptedPrivateKey as any]); - cryptoService.getUserKey.mockResolvedValue({ key: userKey.key } as any); + keyService.makeKeyPair.mockResolvedValue(["publicKey", encryptedPrivateKey as any]); + keyService.getUserKey.mockResolvedValue({ key: userKey.key } as any); encryptService.rsaEncrypt.mockResolvedValue(encryptedUserKey as any); encryptService.encrypt.mockResolvedValue(encryptedPublicKey as any); diff --git a/apps/web/src/app/auth/core/services/rotateable-key-set.service.ts b/apps/web/src/app/auth/core/services/rotateable-key-set.service.ts index 2c1df24b75..044f140c53 100644 --- a/apps/web/src/app/auth/core/services/rotateable-key-set.service.ts +++ b/apps/web/src/app/auth/core/services/rotateable-key-set.service.ts @@ -1,14 +1,14 @@ import { inject, Injectable } from "@angular/core"; import { RotateableKeySet } from "@bitwarden/auth/common"; -import { CryptoService } from "@bitwarden/common/platform/abstractions/crypto.service"; import { EncryptService } from "@bitwarden/common/platform/abstractions/encrypt.service"; import { Utils } from "@bitwarden/common/platform/misc/utils"; import { SymmetricCryptoKey } from "@bitwarden/common/platform/models/domain/symmetric-crypto-key"; +import { KeyService } from "@bitwarden/key-management"; @Injectable({ providedIn: "root" }) export class RotateableKeySetService { - private readonly cryptoService = inject(CryptoService); + private readonly keyService = inject(KeyService); private readonly encryptService = inject(EncryptService); /** @@ -21,9 +21,9 @@ export class RotateableKeySetService { async createKeySet( externalKey: ExternalKey, ): Promise> { - const [publicKey, encryptedPrivateKey] = await this.cryptoService.makeKeyPair(externalKey); + const [publicKey, encryptedPrivateKey] = await this.keyService.makeKeyPair(externalKey); - const userKey = await this.cryptoService.getUserKey(); + const userKey = await this.keyService.getUserKey(); const rawPublicKey = Utils.fromB64ToArray(publicKey); const encryptedUserKey = await this.encryptService.rsaEncrypt(userKey.key, rawPublicKey); const encryptedPublicKey = await this.encryptService.encrypt(rawPublicKey, userKey); diff --git a/apps/web/src/app/auth/core/services/webauthn-login/webauthn-login-admin.service.spec.ts b/apps/web/src/app/auth/core/services/webauthn-login/webauthn-login-admin.service.spec.ts index 83e8c890f5..cc6d94532e 100644 --- a/apps/web/src/app/auth/core/services/webauthn-login/webauthn-login-admin.service.spec.ts +++ b/apps/web/src/app/auth/core/services/webauthn-login/webauthn-login-admin.service.spec.ts @@ -4,7 +4,7 @@ import { mock, MockProxy } from "jest-mock-extended"; import { RotateableKeySet } from "@bitwarden/auth/common"; import { UserVerificationService } from "@bitwarden/common/auth/abstractions/user-verification/user-verification.service.abstraction"; -import { WebAuthnLoginPrfCryptoServiceAbstraction } from "@bitwarden/common/auth/abstractions/webauthn/webauthn-login-prf-crypto.service.abstraction"; +import { WebAuthnLoginPrfKeyServiceAbstraction } from "@bitwarden/common/auth/abstractions/webauthn/webauthn-login-prf-key.service.abstraction"; import { WebAuthnLoginCredentialAssertionView } from "@bitwarden/common/auth/models/view/webauthn-login/webauthn-login-credential-assertion.view"; import { WebAuthnLoginAssertionResponseRequest } from "@bitwarden/common/auth/services/webauthn-login/request/webauthn-login-assertion-response.request"; import { Utils } from "@bitwarden/common/platform/misc/utils"; @@ -24,7 +24,7 @@ describe("WebauthnAdminService", () => { let apiService!: MockProxy; let userVerificationService!: MockProxy; let rotateableKeySetService!: MockProxy; - let webAuthnLoginPrfCryptoService!: MockProxy; + let webAuthnLoginPrfKeyService!: MockProxy; let credentials: MockProxy; let service!: WebauthnLoginAdminService; @@ -38,13 +38,13 @@ describe("WebauthnAdminService", () => { apiService = mock(); userVerificationService = mock(); rotateableKeySetService = mock(); - webAuthnLoginPrfCryptoService = mock(); + webAuthnLoginPrfKeyService = mock(); credentials = mock(); service = new WebauthnLoginAdminService( apiService, userVerificationService, rotateableKeySetService, - webAuthnLoginPrfCryptoService, + webAuthnLoginPrfKeyService, credentials, ); diff --git a/apps/web/src/app/auth/core/services/webauthn-login/webauthn-login-admin.service.ts b/apps/web/src/app/auth/core/services/webauthn-login/webauthn-login-admin.service.ts index 1b04614e54..09ea17829c 100644 --- a/apps/web/src/app/auth/core/services/webauthn-login/webauthn-login-admin.service.ts +++ b/apps/web/src/app/auth/core/services/webauthn-login/webauthn-login-admin.service.ts @@ -3,7 +3,7 @@ import { BehaviorSubject, filter, from, map, Observable, shareReplay, switchMap, import { PrfKeySet, UserKeyRotationDataProvider } from "@bitwarden/auth/common"; import { UserVerificationService } from "@bitwarden/common/auth/abstractions/user-verification/user-verification.service.abstraction"; -import { WebAuthnLoginPrfCryptoServiceAbstraction } from "@bitwarden/common/auth/abstractions/webauthn/webauthn-login-prf-crypto.service.abstraction"; +import { WebAuthnLoginPrfKeyServiceAbstraction } from "@bitwarden/common/auth/abstractions/webauthn/webauthn-login-prf-key.service.abstraction"; import { WebauthnRotateCredentialRequest } from "@bitwarden/common/auth/models/request/webauthn-rotate-credential.request"; import { WebAuthnLoginCredentialAssertionOptionsView } from "@bitwarden/common/auth/models/view/webauthn-login/webauthn-login-credential-assertion-options.view"; import { WebAuthnLoginCredentialAssertionView } from "@bitwarden/common/auth/models/view/webauthn-login/webauthn-login-credential-assertion.view"; @@ -51,7 +51,7 @@ export class WebauthnLoginAdminService private apiService: WebAuthnLoginAdminApiService, private userVerificationService: UserVerificationService, private rotateableKeySetService: RotateableKeySetService, - private webAuthnLoginPrfCryptoService: WebAuthnLoginPrfCryptoServiceAbstraction, + private webAuthnLoginPrfKeyService: WebAuthnLoginPrfKeyServiceAbstraction, @Optional() navigatorCredentials?: CredentialsContainer, @Optional() private logService?: LogService, ) { @@ -143,7 +143,7 @@ export class WebauthnLoginAdminService pendingCredential.createOptions.options.authenticatorSelection.userVerification, // TODO: Remove `any` when typescript typings add support for PRF extensions: { - prf: { eval: { first: await this.webAuthnLoginPrfCryptoService.getLoginWithPrfSalt() } }, + prf: { eval: { first: await this.webAuthnLoginPrfKeyService.getLoginWithPrfSalt() } }, } as any, }, }; @@ -162,7 +162,7 @@ export class WebauthnLoginAdminService } const symmetricPrfKey = - await this.webAuthnLoginPrfCryptoService.createSymmetricKeyFromPrf(prfResult); + await this.webAuthnLoginPrfKeyService.createSymmetricKeyFromPrf(prfResult); return await this.rotateableKeySetService.createKeySet(symmetricPrfKey); } catch (error) { this.logService?.error(error); diff --git a/apps/web/src/app/auth/emergency-access/services/emergency-access.service.spec.ts b/apps/web/src/app/auth/emergency-access/services/emergency-access.service.spec.ts index 1ea91c68d0..c5aa27324d 100644 --- a/apps/web/src/app/auth/emergency-access/services/emergency-access.service.spec.ts +++ b/apps/web/src/app/auth/emergency-access/services/emergency-access.service.spec.ts @@ -6,7 +6,6 @@ import { ListResponse } from "@bitwarden/common/models/response/list.response"; import { UserKeyResponse } from "@bitwarden/common/models/response/user-key.response"; import { BulkEncryptService } from "@bitwarden/common/platform/abstractions/bulk-encrypt.service"; import { ConfigService } from "@bitwarden/common/platform/abstractions/config/config.service"; -import { CryptoService } from "@bitwarden/common/platform/abstractions/crypto.service"; import { EncryptService } from "@bitwarden/common/platform/abstractions/encrypt.service"; import { LogService } from "@bitwarden/common/platform/abstractions/log.service"; import { EncryptionType, KdfType } from "@bitwarden/common/platform/enums"; @@ -16,6 +15,7 @@ import { CsprngArray } from "@bitwarden/common/types/csprng"; import { UserId } from "@bitwarden/common/types/guid"; import { UserKey, MasterKey } from "@bitwarden/common/types/key"; import { CipherService } from "@bitwarden/common/vault/abstractions/cipher.service"; +import { KeyService } from "@bitwarden/key-management"; import { EmergencyAccessStatusType } from "../enums/emergency-access-status-type"; import { EmergencyAccessType } from "../enums/emergency-access-type"; @@ -31,7 +31,7 @@ import { EmergencyAccessService } from "./emergency-access.service"; describe("EmergencyAccessService", () => { let emergencyAccessApiService: MockProxy; let apiService: MockProxy; - let cryptoService: MockProxy; + let keyService: MockProxy; let encryptService: MockProxy; let bulkEncryptService: MockProxy; let cipherService: MockProxy; @@ -42,7 +42,7 @@ describe("EmergencyAccessService", () => { beforeAll(() => { emergencyAccessApiService = mock(); apiService = mock(); - cryptoService = mock(); + keyService = mock(); encryptService = mock(); bulkEncryptService = mock(); cipherService = mock(); @@ -51,7 +51,7 @@ describe("EmergencyAccessService", () => { emergencyAccessService = new EmergencyAccessService( emergencyAccessApiService, apiService, - cryptoService, + keyService, encryptService, bulkEncryptService, cipherService, @@ -129,7 +129,7 @@ describe("EmergencyAccessService", () => { "mockUserPublicKeyEncryptedUserKey", ); - cryptoService.getUserKey.mockResolvedValueOnce(mockUserKey); + keyService.getUserKey.mockResolvedValueOnce(mockUserKey); apiService.getUserPublicKey.mockResolvedValueOnce(mockUserPublicKeyResponse); encryptService.rsaEncrypt.mockResolvedValueOnce(mockUserPublicKeyEncryptedUserKey); @@ -161,17 +161,17 @@ describe("EmergencyAccessService", () => { } as EmergencyAccessTakeoverResponse); const mockDecryptedGrantorUserKey = new Uint8Array(64); - cryptoService.getPrivateKey.mockResolvedValue(new Uint8Array(64)); + keyService.getPrivateKey.mockResolvedValue(new Uint8Array(64)); encryptService.rsaDecrypt.mockResolvedValueOnce(mockDecryptedGrantorUserKey); const mockMasterKey = new SymmetricCryptoKey(new Uint8Array(64) as CsprngArray) as MasterKey; - cryptoService.makeMasterKey.mockResolvedValueOnce(mockMasterKey); + keyService.makeMasterKey.mockResolvedValueOnce(mockMasterKey); const mockMasterKeyHash = "mockMasterKeyHash"; - cryptoService.hashMasterKey.mockResolvedValueOnce(mockMasterKeyHash); + keyService.hashMasterKey.mockResolvedValueOnce(mockMasterKeyHash); - // must mock [UserKey, EncString] return from cryptoService.encryptUserKeyWithMasterKey + // must mock [UserKey, EncString] return from keyService.encryptUserKeyWithMasterKey // where UserKey is the decrypted grantor user key const mockMasterKeyEncryptedUserKey = new EncString( EncryptionType.AesCbc256_HmacSha256_B64, @@ -180,7 +180,7 @@ describe("EmergencyAccessService", () => { const mockUserKey = new SymmetricCryptoKey(mockDecryptedGrantorUserKey) as UserKey; - cryptoService.encryptUserKeyWithMasterKey.mockResolvedValueOnce([ + keyService.encryptUserKeyWithMasterKey.mockResolvedValueOnce([ mockUserKey, mockMasterKeyEncryptedUserKey, ]); @@ -206,7 +206,7 @@ describe("EmergencyAccessService", () => { kdf: KdfType.PBKDF2_SHA256, kdfIterations: 500, } as EmergencyAccessTakeoverResponse); - cryptoService.getPrivateKey.mockResolvedValue(new Uint8Array(64)); + keyService.getPrivateKey.mockResolvedValue(new Uint8Array(64)); await expect( emergencyAccessService.takeover(mockId, mockEmail, mockName), @@ -221,7 +221,7 @@ describe("EmergencyAccessService", () => { kdf: KdfType.PBKDF2_SHA256, kdfIterations: 500, } as EmergencyAccessTakeoverResponse); - cryptoService.getPrivateKey.mockResolvedValue(null); + keyService.getPrivateKey.mockResolvedValue(null); await expect(emergencyAccessService.takeover(mockId, mockEmail, mockName)).rejects.toThrow( "user does not have a private key", diff --git a/apps/web/src/app/auth/emergency-access/services/emergency-access.service.ts b/apps/web/src/app/auth/emergency-access/services/emergency-access.service.ts index 83a2808d4e..a4fd9eeff0 100644 --- a/apps/web/src/app/auth/emergency-access/services/emergency-access.service.ts +++ b/apps/web/src/app/auth/emergency-access/services/emergency-access.service.ts @@ -12,7 +12,6 @@ import { import { FeatureFlag } from "@bitwarden/common/enums/feature-flag.enum"; import { BulkEncryptService } from "@bitwarden/common/platform/abstractions/bulk-encrypt.service"; import { ConfigService } from "@bitwarden/common/platform/abstractions/config/config.service"; -import { CryptoService } from "@bitwarden/common/platform/abstractions/crypto.service"; import { EncryptService } from "@bitwarden/common/platform/abstractions/encrypt.service"; import { LogService } from "@bitwarden/common/platform/abstractions/log.service"; import { KdfType } from "@bitwarden/common/platform/enums"; @@ -24,6 +23,7 @@ import { UserKey } from "@bitwarden/common/types/key"; import { CipherService } from "@bitwarden/common/vault/abstractions/cipher.service"; import { Cipher } from "@bitwarden/common/vault/models/domain/cipher"; import { CipherView } from "@bitwarden/common/vault/models/view/cipher.view"; +import { KeyService } from "@bitwarden/key-management"; import { EmergencyAccessStatusType } from "../enums/emergency-access-status-type"; import { EmergencyAccessType } from "../enums/emergency-access-type"; @@ -46,7 +46,7 @@ export class EmergencyAccessService constructor( private emergencyAccessApiService: EmergencyAccessApiService, private apiService: ApiService, - private cryptoService: CryptoService, + private keyService: KeyService, private encryptService: EncryptService, private bulkEncryptService: BulkEncryptService, private cipherService: CipherService, @@ -153,7 +153,7 @@ export class EmergencyAccessService * @param token secret token provided in email */ async confirm(id: string, granteeId: string) { - const userKey = await this.cryptoService.getUserKey(); + const userKey = await this.keyService.getUserKey(); if (!userKey) { throw new Error("No user key found"); } @@ -163,7 +163,7 @@ export class EmergencyAccessService try { this.logService.debug( "User's fingerprint: " + - (await this.cryptoService.getFingerprint(granteeId, publicKey)).join("-"), + (await this.keyService.getFingerprint(granteeId, publicKey)).join("-"), ); } catch { // Ignore errors since it's just a debug message @@ -218,7 +218,7 @@ export class EmergencyAccessService async getViewOnlyCiphers(id: string): Promise { const response = await this.emergencyAccessApiService.postEmergencyAccessView(id); - const activeUserPrivateKey = await this.cryptoService.getPrivateKey(); + const activeUserPrivateKey = await this.keyService.getPrivateKey(); if (activeUserPrivateKey == null) { throw new Error("Active user does not have a private key, cannot get view only ciphers."); @@ -255,7 +255,7 @@ export class EmergencyAccessService async takeover(id: string, masterPassword: string, email: string) { const takeoverResponse = await this.emergencyAccessApiService.postEmergencyAccessTakeover(id); - const activeUserPrivateKey = await this.cryptoService.getPrivateKey(); + const activeUserPrivateKey = await this.keyService.getPrivateKey(); if (activeUserPrivateKey == null) { throw new Error("Active user does not have a private key, cannot complete a takeover."); @@ -286,10 +286,10 @@ export class EmergencyAccessService break; } - const masterKey = await this.cryptoService.makeMasterKey(masterPassword, email, config); - const masterKeyHash = await this.cryptoService.hashMasterKey(masterPassword, masterKey); + const masterKey = await this.keyService.makeMasterKey(masterPassword, email, config); + const masterKeyHash = await this.keyService.hashMasterKey(masterPassword, masterKey); - const encKey = await this.cryptoService.encryptUserKeyWithMasterKey(masterKey, grantorUserKey); + const encKey = await this.keyService.encryptUserKeyWithMasterKey(masterKey, grantorUserKey); const request = new EmergencyAccessPasswordRequest(); request.newMasterPasswordHash = masterKeyHash; diff --git a/apps/web/src/app/auth/key-rotation/user-key-rotation.service.spec.ts b/apps/web/src/app/auth/key-rotation/user-key-rotation.service.spec.ts index 2c803a627f..619652f16a 100644 --- a/apps/web/src/app/auth/key-rotation/user-key-rotation.service.spec.ts +++ b/apps/web/src/app/auth/key-rotation/user-key-rotation.service.spec.ts @@ -6,7 +6,6 @@ import { DeviceTrustServiceAbstraction } from "@bitwarden/common/auth/abstractio import { UserVerificationService } from "@bitwarden/common/auth/abstractions/user-verification/user-verification.service.abstraction"; import { WebauthnRotateCredentialRequest } from "@bitwarden/common/auth/models/request/webauthn-rotate-credential.request"; import { ConfigService } from "@bitwarden/common/platform/abstractions/config/config.service"; -import { CryptoService } from "@bitwarden/common/platform/abstractions/crypto.service"; import { EncryptService } from "@bitwarden/common/platform/abstractions/encrypt.service"; import { SymmetricCryptoKey } from "@bitwarden/common/platform/models/domain/symmetric-crypto-key"; import { SendWithIdRequest } from "@bitwarden/common/tools/send/models/request/send-with-id.request"; @@ -19,6 +18,7 @@ import { SyncService } from "@bitwarden/common/vault/abstractions/sync/sync.serv import { CipherType } from "@bitwarden/common/vault/enums"; import { CipherWithIdRequest } from "@bitwarden/common/vault/models/request/cipher-with-id.request"; import { FolderWithIdRequest } from "@bitwarden/common/vault/models/request/folder-with-id.request"; +import { KeyService } from "@bitwarden/key-management"; import { OrganizationUserResetPasswordService } from "../../admin-console/organizations/members/services/organization-user-reset-password/organization-user-reset-password.service"; import { WebauthnLoginAdminService } from "../core"; @@ -39,7 +39,7 @@ describe("KeyRotationService", () => { let mockEmergencyAccessService: MockProxy; let mockResetPasswordService: MockProxy; let mockDeviceTrustService: MockProxy; - let mockCryptoService: MockProxy; + let mockKeyService: MockProxy; let mockEncryptService: MockProxy; let mockConfigService: MockProxy; let mockSyncService: MockProxy; @@ -61,7 +61,7 @@ describe("KeyRotationService", () => { mockEmergencyAccessService = mock(); mockResetPasswordService = mock(); mockDeviceTrustService = mock(); - mockCryptoService = mock(); + mockKeyService = mock(); mockEncryptService = mock(); mockConfigService = mock(); mockSyncService = mock(); @@ -76,7 +76,7 @@ describe("KeyRotationService", () => { mockEmergencyAccessService, mockResetPasswordService, mockDeviceTrustService, - mockCryptoService, + mockKeyService, mockEncryptService, mockSyncService, mockWebauthnLoginAdminService, @@ -91,13 +91,13 @@ describe("KeyRotationService", () => { let privateKey: BehaviorSubject; beforeEach(() => { - mockCryptoService.makeUserKey.mockResolvedValue([ + mockKeyService.makeUserKey.mockResolvedValue([ new SymmetricCryptoKey(new Uint8Array(64)) as UserKey, { encryptedString: "mockNewUserKey", } as any, ]); - mockCryptoService.hashMasterKey.mockResolvedValue("mockMasterPasswordHash"); + mockKeyService.hashMasterKey.mockResolvedValue("mockMasterPasswordHash"); mockConfigService.getFeatureFlag.mockResolvedValue(true); mockEncryptService.encrypt.mockResolvedValue({ @@ -111,11 +111,11 @@ describe("KeyRotationService", () => { }); // Mock user key - mockCryptoService.userKey$.mockReturnValue(new BehaviorSubject("mockOriginalUserKey" as any)); + mockKeyService.userKey$.mockReturnValue(new BehaviorSubject("mockOriginalUserKey" as any)); // Mock private key privateKey = new BehaviorSubject("mockPrivateKey" as any); - mockCryptoService.userPrivateKeyWithLegacySupport$.mockReturnValue(privateKey); + mockKeyService.userPrivateKeyWithLegacySupport$.mockReturnValue(privateKey); // Mock ciphers const mockCiphers = [createMockCipher("1", "Cipher 1"), createMockCipher("2", "Cipher 2")]; @@ -164,7 +164,7 @@ describe("KeyRotationService", () => { }); it("throws if user key creation fails", async () => { - mockCryptoService.makeUserKey.mockResolvedValueOnce([null, null]); + mockKeyService.makeUserKey.mockResolvedValueOnce([null, null]); await expect( keyRotationService.rotateUserKeyAndEncryptedData("mockMasterPassword", mockUser), diff --git a/apps/web/src/app/auth/key-rotation/user-key-rotation.service.ts b/apps/web/src/app/auth/key-rotation/user-key-rotation.service.ts index f2ec25d9c5..5c6132c266 100644 --- a/apps/web/src/app/auth/key-rotation/user-key-rotation.service.ts +++ b/apps/web/src/app/auth/key-rotation/user-key-rotation.service.ts @@ -6,7 +6,6 @@ import { DeviceTrustServiceAbstraction } from "@bitwarden/common/auth/abstractio import { UserVerificationService } from "@bitwarden/common/auth/abstractions/user-verification/user-verification.service.abstraction"; import { VerificationType } from "@bitwarden/common/auth/enums/verification-type"; import { MasterPasswordVerification } from "@bitwarden/common/auth/types/verification"; -import { CryptoService } from "@bitwarden/common/platform/abstractions/crypto.service"; import { EncryptService } from "@bitwarden/common/platform/abstractions/encrypt.service"; import { EncryptedString } from "@bitwarden/common/platform/models/domain/enc-string"; import { SendService } from "@bitwarden/common/tools/send/services/send.service.abstraction"; @@ -15,6 +14,7 @@ import { UserKey } from "@bitwarden/common/types/key"; import { CipherService } from "@bitwarden/common/vault/abstractions/cipher.service"; import { FolderService } from "@bitwarden/common/vault/abstractions/folder/folder.service.abstraction"; import { SyncService } from "@bitwarden/common/vault/abstractions/sync/sync.service.abstraction"; +import { KeyService } from "@bitwarden/key-management"; import { OrganizationUserResetPasswordService } from "../../admin-console/organizations/members/services/organization-user-reset-password/organization-user-reset-password.service"; import { WebauthnLoginAdminService } from "../core"; @@ -34,7 +34,7 @@ export class UserKeyRotationService { private emergencyAccessService: EmergencyAccessService, private resetPasswordService: OrganizationUserResetPasswordService, private deviceTrustService: DeviceTrustServiceAbstraction, - private cryptoService: CryptoService, + private keyService: KeyService, private encryptService: EncryptService, private syncService: SyncService, private webauthnLoginAdminService: WebauthnLoginAdminService, @@ -71,7 +71,7 @@ export class UserKeyRotationService { user.email, ); - const [newUserKey, newEncUserKey] = await this.cryptoService.makeUserKey(masterKey); + const [newUserKey, newEncUserKey] = await this.keyService.makeUserKey(masterKey); if (!newUserKey || !newEncUserKey) { throw new Error("User key could not be created"); @@ -84,13 +84,13 @@ export class UserKeyRotationService { request.key = newEncUserKey.encryptedString; // Add master key hash - const masterPasswordHash = await this.cryptoService.hashMasterKey(masterPassword, masterKey); + const masterPasswordHash = await this.keyService.hashMasterKey(masterPassword, masterKey); request.masterPasswordHash = masterPasswordHash; // Get original user key // Note: We distribute the legacy key, but not all domains actually use it. If any of those // domains break their legacy support it will break the migration process for legacy users. - const originalUserKey = await this.cryptoService.getUserKeyWithLegacySupport(user.id); + const originalUserKey = await this.keyService.getUserKeyWithLegacySupport(user.id); // Add re-encrypted data request.privateKey = await this.encryptPrivateKey(newUserKey, user.id); @@ -162,7 +162,7 @@ export class UserKeyRotationService { userId: UserId, ): Promise { const privateKey = await firstValueFrom( - this.cryptoService.userPrivateKeyWithLegacySupport$(userId), + this.keyService.userPrivateKeyWithLegacySupport$(userId), ); if (!privateKey) { throw new Error("No private key found for user key rotation"); diff --git a/apps/web/src/app/auth/migrate-encryption/migrate-legacy-encryption.component.ts b/apps/web/src/app/auth/migrate-encryption/migrate-legacy-encryption.component.ts index 6c894f4fa8..68ef95fef6 100644 --- a/apps/web/src/app/auth/migrate-encryption/migrate-legacy-encryption.component.ts +++ b/apps/web/src/app/auth/migrate-encryption/migrate-legacy-encryption.component.ts @@ -3,13 +3,13 @@ import { FormControl, FormGroup, Validators } from "@angular/forms"; import { firstValueFrom } from "rxjs"; import { AccountService } from "@bitwarden/common/auth/abstractions/account.service"; -import { CryptoService } from "@bitwarden/common/platform/abstractions/crypto.service"; import { I18nService } from "@bitwarden/common/platform/abstractions/i18n.service"; import { LogService } from "@bitwarden/common/platform/abstractions/log.service"; import { MessagingService } from "@bitwarden/common/platform/abstractions/messaging.service"; import { FolderApiServiceAbstraction } from "@bitwarden/common/vault/abstractions/folder/folder-api.service.abstraction"; import { SyncService } from "@bitwarden/common/vault/abstractions/sync/sync.service.abstraction"; import { DialogService, ToastService } from "@bitwarden/components"; +import { KeyService } from "@bitwarden/key-management"; import { SharedModule } from "../../shared"; import { UserKeyRotationModule } from "../key-rotation/user-key-rotation.module"; @@ -31,7 +31,7 @@ export class MigrateFromLegacyEncryptionComponent { private accountService: AccountService, private keyRotationService: UserKeyRotationService, private i18nService: I18nService, - private cryptoService: CryptoService, + private keyService: KeyService, private messagingService: MessagingService, private logService: LogService, private syncService: SyncService, @@ -49,7 +49,7 @@ export class MigrateFromLegacyEncryptionComponent { const activeUser = await firstValueFrom(this.accountService.activeAccount$); - const hasUserKey = await this.cryptoService.hasUserKey(activeUser.id); + const hasUserKey = await this.keyService.hasUserKey(activeUser.id); if (hasUserKey) { this.messagingService.send("logout"); throw new Error("User key already exists, cannot migrate legacy encryption."); diff --git a/apps/web/src/app/auth/organization-invite/accept-organization.service.spec.ts b/apps/web/src/app/auth/organization-invite/accept-organization.service.spec.ts index 13b704b546..a5bd8ae3b0 100644 --- a/apps/web/src/app/auth/organization-invite/accept-organization.service.spec.ts +++ b/apps/web/src/app/auth/organization-invite/accept-organization.service.spec.ts @@ -10,12 +10,12 @@ import { PolicyType } from "@bitwarden/common/admin-console/enums"; import { Policy } from "@bitwarden/common/admin-console/models/domain/policy"; import { ResetPasswordPolicyOptions } from "@bitwarden/common/admin-console/models/domain/reset-password-policy-options"; import { AuthService } from "@bitwarden/common/auth/abstractions/auth.service"; -import { CryptoService } from "@bitwarden/common/platform/abstractions/crypto.service"; import { EncryptService } from "@bitwarden/common/platform/abstractions/encrypt.service"; import { LogService } from "@bitwarden/common/platform/abstractions/log.service"; import { EncString } from "@bitwarden/common/platform/models/domain/enc-string"; import { FakeGlobalState } from "@bitwarden/common/spec/fake-state"; import { OrgKey } from "@bitwarden/common/types/key"; +import { KeyService } from "@bitwarden/key-management"; import { I18nService } from "../../core/i18n.service"; @@ -29,7 +29,7 @@ describe("AcceptOrganizationInviteService", () => { let sut: AcceptOrganizationInviteService; let apiService: MockProxy; let authService: MockProxy; - let cryptoService: MockProxy; + let keyService: MockProxy; let encryptService: MockProxy; let policyApiService: MockProxy; let policyService: MockProxy; @@ -43,7 +43,7 @@ describe("AcceptOrganizationInviteService", () => { beforeEach(() => { apiService = mock(); authService = mock(); - cryptoService = mock(); + keyService = mock(); encryptService = mock(); policyApiService = mock(); policyService = mock(); @@ -57,7 +57,7 @@ describe("AcceptOrganizationInviteService", () => { sut = new AcceptOrganizationInviteService( apiService, authService, - cryptoService, + keyService, encryptService, policyApiService, policyService, @@ -71,11 +71,11 @@ describe("AcceptOrganizationInviteService", () => { describe("validateAndAcceptInvite", () => { it("initializes an organization when given an invite where initOrganization is true", async () => { - cryptoService.makeOrgKey.mockResolvedValue([ + keyService.makeOrgKey.mockResolvedValue([ { encryptedString: "string" } as EncString, "orgPrivateKey" as unknown as OrgKey, ]); - cryptoService.makeKeyPair.mockResolvedValue([ + keyService.makeKeyPair.mockResolvedValue([ "orgPublicKey", { encryptedString: "string" } as EncString, ]); diff --git a/apps/web/src/app/auth/organization-invite/accept-organization.service.ts b/apps/web/src/app/auth/organization-invite/accept-organization.service.ts index f014372a7b..6d00f58f44 100644 --- a/apps/web/src/app/auth/organization-invite/accept-organization.service.ts +++ b/apps/web/src/app/auth/organization-invite/accept-organization.service.ts @@ -14,7 +14,6 @@ import { PolicyType } from "@bitwarden/common/admin-console/enums"; import { Policy } from "@bitwarden/common/admin-console/models/domain/policy"; import { OrganizationKeysRequest } from "@bitwarden/common/admin-console/models/request/organization-keys.request"; import { AuthService } from "@bitwarden/common/auth/abstractions/auth.service"; -import { CryptoService } from "@bitwarden/common/platform/abstractions/crypto.service"; import { EncryptService } from "@bitwarden/common/platform/abstractions/encrypt.service"; import { I18nService } from "@bitwarden/common/platform/abstractions/i18n.service"; import { LogService } from "@bitwarden/common/platform/abstractions/log.service"; @@ -26,6 +25,7 @@ import { ORGANIZATION_INVITE_DISK, } from "@bitwarden/common/platform/state"; import { OrgKey } from "@bitwarden/common/types/key"; +import { KeyService } from "@bitwarden/key-management"; import { OrganizationInvite } from "./organization-invite"; @@ -52,7 +52,7 @@ export class AcceptOrganizationInviteService { constructor( private readonly apiService: ApiService, private readonly authService: AuthService, - private readonly cryptoService: CryptoService, + private readonly keyService: KeyService, private readonly encryptService: EncryptService, private readonly policyApiService: PolicyApiServiceAbstraction, private readonly policyService: PolicyService, @@ -137,8 +137,8 @@ export class AcceptOrganizationInviteService { const request = new OrganizationUserAcceptInitRequest(); request.token = invite.token; - const [encryptedOrgKey, orgKey] = await this.cryptoService.makeOrgKey(); - const [orgPublicKey, encryptedOrgPrivateKey] = await this.cryptoService.makeKeyPair(orgKey); + const [encryptedOrgKey, orgKey] = await this.keyService.makeOrgKey(); + const [orgPublicKey, encryptedOrgPrivateKey] = await this.keyService.makeKeyPair(orgKey); const collection = await this.encryptService.encrypt( this.i18nService.t("defaultCollection"), orgKey, @@ -183,7 +183,7 @@ export class AcceptOrganizationInviteService { const publicKey = Utils.fromB64ToArray(response.publicKey); // RSA Encrypt user's encKey.key with organization public key - const userKey = await this.cryptoService.getUserKey(); + const userKey = await this.keyService.getUserKey(); const encryptedKey = await this.encryptService.rsaEncrypt(userKey.key, publicKey); // Add reset password key to accept request diff --git a/apps/web/src/app/auth/recover-two-factor.component.ts b/apps/web/src/app/auth/recover-two-factor.component.ts index 0774a9c777..5059546096 100644 --- a/apps/web/src/app/auth/recover-two-factor.component.ts +++ b/apps/web/src/app/auth/recover-two-factor.component.ts @@ -5,10 +5,10 @@ import { Router } from "@angular/router"; import { LoginStrategyServiceAbstraction } from "@bitwarden/auth/common"; import { ApiService } from "@bitwarden/common/abstractions/api.service"; import { TwoFactorRecoveryRequest } from "@bitwarden/common/auth/models/request/two-factor-recovery.request"; -import { CryptoService } from "@bitwarden/common/platform/abstractions/crypto.service"; import { I18nService } from "@bitwarden/common/platform/abstractions/i18n.service"; import { PlatformUtilsService } from "@bitwarden/common/platform/abstractions/platform-utils.service"; import { ToastService } from "@bitwarden/components"; +import { KeyService } from "@bitwarden/key-management"; @Component({ selector: "app-recover-two-factor", @@ -26,7 +26,7 @@ export class RecoverTwoFactorComponent { private apiService: ApiService, private platformUtilsService: PlatformUtilsService, private i18nService: I18nService, - private cryptoService: CryptoService, + private keyService: KeyService, private loginStrategyService: LoginStrategyServiceAbstraction, private toastService: ToastService, ) {} @@ -53,7 +53,7 @@ export class RecoverTwoFactorComponent { request.recoveryCode = this.recoveryCode.replace(/\s/g, "").toLowerCase(); request.email = this.email.trim().toLowerCase(); const key = await this.loginStrategyService.makePreloginKey(this.masterPassword, request.email); - request.masterPasswordHash = await this.cryptoService.hashMasterKey(this.masterPassword, key); + request.masterPasswordHash = await this.keyService.hashMasterKey(this.masterPassword, key); await this.apiService.postTwoFactorRecover(request); this.toastService.showToast({ variant: "success", diff --git a/apps/web/src/app/auth/register-form/register-form.component.ts b/apps/web/src/app/auth/register-form/register-form.component.ts index 9982af2ab5..b44ce1843c 100644 --- a/apps/web/src/app/auth/register-form/register-form.component.ts +++ b/apps/web/src/app/auth/register-form/register-form.component.ts @@ -11,7 +11,6 @@ import { PolicyService } from "@bitwarden/common/admin-console/abstractions/poli import { MasterPasswordPolicyOptions } from "@bitwarden/common/admin-console/models/domain/master-password-policy-options"; import { ReferenceEventRequest } from "@bitwarden/common/models/request/reference-event.request"; import { RegisterRequest } from "@bitwarden/common/models/request/register.request"; -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"; import { LogService } from "@bitwarden/common/platform/abstractions/log.service"; @@ -19,6 +18,7 @@ import { PlatformUtilsService } from "@bitwarden/common/platform/abstractions/pl import { StateService } from "@bitwarden/common/platform/abstractions/state.service"; import { DialogService, ToastService } from "@bitwarden/components"; import { PasswordGenerationServiceAbstraction } from "@bitwarden/generator-legacy"; +import { KeyService } from "@bitwarden/key-management"; import { AcceptOrganizationInviteService } from "../organization-invite/accept-organization.service"; @@ -41,7 +41,7 @@ export class RegisterFormComponent extends BaseRegisterComponent implements OnIn loginStrategyService: LoginStrategyServiceAbstraction, router: Router, i18nService: I18nService, - cryptoService: CryptoService, + keyService: KeyService, apiService: ApiService, stateService: StateService, platformUtilsService: PlatformUtilsService, @@ -60,7 +60,7 @@ export class RegisterFormComponent extends BaseRegisterComponent implements OnIn loginStrategyService, router, i18nService, - cryptoService, + keyService, apiService, stateService, platformUtilsService, diff --git a/apps/web/src/app/auth/settings/account/change-email.component.ts b/apps/web/src/app/auth/settings/account/change-email.component.ts index ac49335776..734df68295 100644 --- a/apps/web/src/app/auth/settings/account/change-email.component.ts +++ b/apps/web/src/app/auth/settings/account/change-email.component.ts @@ -6,13 +6,13 @@ import { KdfConfigService } from "@bitwarden/common/auth/abstractions/kdf-config import { TwoFactorProviderType } from "@bitwarden/common/auth/enums/two-factor-provider-type"; import { EmailTokenRequest } from "@bitwarden/common/auth/models/request/email-token.request"; import { EmailRequest } from "@bitwarden/common/auth/models/request/email.request"; -import { CryptoService } from "@bitwarden/common/platform/abstractions/crypto.service"; import { I18nService } from "@bitwarden/common/platform/abstractions/i18n.service"; import { LogService } from "@bitwarden/common/platform/abstractions/log.service"; import { MessagingService } from "@bitwarden/common/platform/abstractions/messaging.service"; import { PlatformUtilsService } from "@bitwarden/common/platform/abstractions/platform-utils.service"; import { StateService } from "@bitwarden/common/platform/abstractions/state.service"; import { ToastService } from "@bitwarden/components"; +import { KeyService } from "@bitwarden/key-management"; @Component({ selector: "app-change-email", @@ -34,7 +34,7 @@ export class ChangeEmailComponent implements OnInit { private apiService: ApiService, private i18nService: I18nService, private platformUtilsService: PlatformUtilsService, - private cryptoService: CryptoService, + private keyService: KeyService, private messagingService: MessagingService, private logService: LogService, private stateService: StateService, @@ -69,9 +69,9 @@ export class ChangeEmailComponent implements OnInit { if (!this.tokenSent) { const request = new EmailTokenRequest(); request.newEmail = newEmail; - request.masterPasswordHash = await this.cryptoService.hashMasterKey( + request.masterPasswordHash = await this.keyService.hashMasterKey( step1Value.masterPassword, - await this.cryptoService.getOrDeriveMasterKey(step1Value.masterPassword), + await this.keyService.getOrDeriveMasterKey(step1Value.masterPassword), ); try { await this.apiService.postEmailToken(request); @@ -83,21 +83,21 @@ export class ChangeEmailComponent implements OnInit { const request = new EmailRequest(); request.token = this.formGroup.value.token; request.newEmail = newEmail; - request.masterPasswordHash = await this.cryptoService.hashMasterKey( + request.masterPasswordHash = await this.keyService.hashMasterKey( step1Value.masterPassword, - await this.cryptoService.getOrDeriveMasterKey(step1Value.masterPassword), + await this.keyService.getOrDeriveMasterKey(step1Value.masterPassword), ); const kdfConfig = await this.kdfConfigService.getKdfConfig(); - const newMasterKey = await this.cryptoService.makeMasterKey( + const newMasterKey = await this.keyService.makeMasterKey( step1Value.masterPassword, newEmail, kdfConfig, ); - request.newMasterPasswordHash = await this.cryptoService.hashMasterKey( + request.newMasterPasswordHash = await this.keyService.hashMasterKey( step1Value.masterPassword, newMasterKey, ); - const newUserKey = await this.cryptoService.encryptUserKeyWithMasterKey(newMasterKey); + const newUserKey = await this.keyService.encryptUserKeyWithMasterKey(newMasterKey); request.key = newUserKey[1].encryptedString; try { await this.apiService.postEmail(request); diff --git a/apps/web/src/app/auth/settings/change-password.component.ts b/apps/web/src/app/auth/settings/change-password.component.ts index 2cc7c101d0..ec1416ba0a 100644 --- a/apps/web/src/app/auth/settings/change-password.component.ts +++ b/apps/web/src/app/auth/settings/change-password.component.ts @@ -11,7 +11,6 @@ import { KdfConfigService } from "@bitwarden/common/auth/abstractions/kdf-config import { InternalMasterPasswordServiceAbstraction } from "@bitwarden/common/auth/abstractions/master-password.service.abstraction"; import { UserVerificationService } from "@bitwarden/common/auth/abstractions/user-verification/user-verification.service.abstraction"; import { PasswordRequest } from "@bitwarden/common/auth/models/request/password.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"; @@ -24,6 +23,7 @@ import { CipherService } from "@bitwarden/common/vault/abstractions/cipher.servi import { SyncService } from "@bitwarden/common/vault/abstractions/sync/sync.service.abstraction"; import { DialogService, ToastService } from "@bitwarden/components"; import { PasswordGenerationServiceAbstraction } from "@bitwarden/generator-legacy"; +import { KeyService } from "@bitwarden/key-management"; import { UserKeyRotationService } from "../key-rotation/user-key-rotation.service"; @@ -43,7 +43,7 @@ export class ChangePasswordComponent constructor( i18nService: I18nService, - cryptoService: CryptoService, + keyService: KeyService, messagingService: MessagingService, stateService: StateService, passwordGenerationService: PasswordGenerationServiceAbstraction, @@ -64,7 +64,7 @@ export class ChangePasswordComponent ) { super( i18nService, - cryptoService, + keyService, messagingService, passwordGenerationService, platformUtilsService, @@ -181,14 +181,14 @@ export class ChangePasswordComponent newMasterKey: MasterKey, newUserKey: [UserKey, EncString], ) { - const masterKey = await this.cryptoService.makeMasterKey( + const masterKey = await this.keyService.makeMasterKey( this.currentMasterPassword, await firstValueFrom(this.accountService.activeAccount$.pipe(map((a) => a?.email))), await this.kdfConfigService.getKdfConfig(), ); const userId = await firstValueFrom(this.accountService.activeAccount$.pipe(map((a) => a?.id))); - const newLocalKeyHash = await this.cryptoService.hashMasterKey( + const newLocalKeyHash = await this.keyService.hashMasterKey( this.masterPassword, newMasterKey, HashPurpose.LocalAuthorization, @@ -205,7 +205,7 @@ export class ChangePasswordComponent } const request = new PasswordRequest(); - request.masterPasswordHash = await this.cryptoService.hashMasterKey( + request.masterPasswordHash = await this.keyService.hashMasterKey( this.currentMasterPassword, masterKey, ); diff --git a/apps/web/src/app/auth/settings/emergency-access/attachments/emergency-access-attachments.component.ts b/apps/web/src/app/auth/settings/emergency-access/attachments/emergency-access-attachments.component.ts index 4912a866fd..75d43bb3bc 100644 --- a/apps/web/src/app/auth/settings/emergency-access/attachments/emergency-access-attachments.component.ts +++ b/apps/web/src/app/auth/settings/emergency-access/attachments/emergency-access-attachments.component.ts @@ -4,7 +4,6 @@ import { AttachmentsComponent as BaseAttachmentsComponent } from "@bitwarden/ang import { ApiService } from "@bitwarden/common/abstractions/api.service"; import { AccountService } from "@bitwarden/common/auth/abstractions/account.service"; import { BillingAccountProfileStateService } from "@bitwarden/common/billing/abstractions/account/billing-account-profile-state.service"; -import { CryptoService } from "@bitwarden/common/platform/abstractions/crypto.service"; import { EncryptService } from "@bitwarden/common/platform/abstractions/encrypt.service"; import { FileDownloadService } from "@bitwarden/common/platform/abstractions/file-download/file-download.service"; import { I18nService } from "@bitwarden/common/platform/abstractions/i18n.service"; @@ -14,6 +13,7 @@ import { StateService } from "@bitwarden/common/platform/abstractions/state.serv import { CipherService } from "@bitwarden/common/vault/abstractions/cipher.service"; import { AttachmentView } from "@bitwarden/common/vault/models/view/attachment.view"; import { DialogService, ToastService } from "@bitwarden/components"; +import { KeyService } from "@bitwarden/key-management"; @Component({ selector: "emergency-access-attachments", @@ -26,7 +26,7 @@ export class EmergencyAccessAttachmentsComponent extends BaseAttachmentsComponen constructor( cipherService: CipherService, i18nService: I18nService, - cryptoService: CryptoService, + keyService: KeyService, encryptService: EncryptService, stateService: StateService, platformUtilsService: PlatformUtilsService, @@ -41,7 +41,7 @@ export class EmergencyAccessAttachmentsComponent extends BaseAttachmentsComponen super( cipherService, i18nService, - cryptoService, + keyService, encryptService, platformUtilsService, apiService, diff --git a/apps/web/src/app/auth/settings/emergency-access/confirm/emergency-access-confirm.component.ts b/apps/web/src/app/auth/settings/emergency-access/confirm/emergency-access-confirm.component.ts index 3bfe90d48e..3b387b3c1e 100644 --- a/apps/web/src/app/auth/settings/emergency-access/confirm/emergency-access-confirm.component.ts +++ b/apps/web/src/app/auth/settings/emergency-access/confirm/emergency-access-confirm.component.ts @@ -4,10 +4,10 @@ import { FormBuilder } from "@angular/forms"; import { ApiService } from "@bitwarden/common/abstractions/api.service"; import { OrganizationManagementPreferencesService } from "@bitwarden/common/admin-console/abstractions/organization-management-preferences/organization-management-preferences.service"; -import { CryptoService } from "@bitwarden/common/platform/abstractions/crypto.service"; import { LogService } from "@bitwarden/common/platform/abstractions/log.service"; import { Utils } from "@bitwarden/common/platform/misc/utils"; import { DialogService } from "@bitwarden/components"; +import { KeyService } from "@bitwarden/key-management"; export enum EmergencyAccessConfirmDialogResult { Confirmed = "confirmed", @@ -35,7 +35,7 @@ export class EmergencyAccessConfirmComponent implements OnInit { @Inject(DIALOG_DATA) protected params: EmergencyAccessConfirmDialogData, private formBuilder: FormBuilder, private apiService: ApiService, - private cryptoService: CryptoService, + private keyService: KeyService, protected organizationManagementPreferencesService: OrganizationManagementPreferencesService, private logService: LogService, private dialogRef: DialogRef, @@ -46,7 +46,7 @@ export class EmergencyAccessConfirmComponent implements OnInit { const publicKeyResponse = await this.apiService.getUserPublicKey(this.params.userId); if (publicKeyResponse != null) { const publicKey = Utils.fromB64ToArray(publicKeyResponse.publicKey); - const fingerprint = await this.cryptoService.getFingerprint(this.params.userId, publicKey); + const fingerprint = await this.keyService.getFingerprint(this.params.userId, publicKey); if (fingerprint != null) { this.fingerprint = fingerprint.join("-"); } diff --git a/apps/web/src/app/auth/settings/emergency-access/takeover/emergency-access-takeover.component.ts b/apps/web/src/app/auth/settings/emergency-access/takeover/emergency-access-takeover.component.ts index 26995c7ce0..c567508e05 100644 --- a/apps/web/src/app/auth/settings/emergency-access/takeover/emergency-access-takeover.component.ts +++ b/apps/web/src/app/auth/settings/emergency-access/takeover/emergency-access-takeover.component.ts @@ -8,7 +8,6 @@ import { PolicyService } from "@bitwarden/common/admin-console/abstractions/poli import { AccountService } from "@bitwarden/common/auth/abstractions/account.service"; import { KdfConfigService } from "@bitwarden/common/auth/abstractions/kdf-config.service"; import { InternalMasterPasswordServiceAbstraction } from "@bitwarden/common/auth/abstractions/master-password.service.abstraction"; -import { CryptoService } from "@bitwarden/common/platform/abstractions/crypto.service"; import { I18nService } from "@bitwarden/common/platform/abstractions/i18n.service"; import { LogService } from "@bitwarden/common/platform/abstractions/log.service"; import { MessagingService } from "@bitwarden/common/platform/abstractions/messaging.service"; @@ -17,6 +16,7 @@ import { StateService } from "@bitwarden/common/platform/abstractions/state.serv import { KdfType } from "@bitwarden/common/platform/enums"; import { DialogService, ToastService } from "@bitwarden/components"; import { PasswordGenerationServiceAbstraction } from "@bitwarden/generator-legacy"; +import { KeyService } from "@bitwarden/key-management"; import { EmergencyAccessService } from "../../../emergency-access"; @@ -51,7 +51,7 @@ export class EmergencyAccessTakeoverComponent @Inject(DIALOG_DATA) protected params: EmergencyAccessTakeoverDialogData, private formBuilder: FormBuilder, i18nService: I18nService, - cryptoService: CryptoService, + keyService: KeyService, messagingService: MessagingService, stateService: StateService, passwordGenerationService: PasswordGenerationServiceAbstraction, @@ -68,7 +68,7 @@ export class EmergencyAccessTakeoverComponent ) { super( i18nService, - cryptoService, + keyService, messagingService, passwordGenerationService, platformUtilsService, diff --git a/apps/web/src/app/auth/settings/security/change-kdf/change-kdf-confirmation.component.ts b/apps/web/src/app/auth/settings/security/change-kdf/change-kdf-confirmation.component.ts index 2249c83ebc..17954b3ee8 100644 --- a/apps/web/src/app/auth/settings/security/change-kdf/change-kdf-confirmation.component.ts +++ b/apps/web/src/app/auth/settings/security/change-kdf/change-kdf-confirmation.component.ts @@ -7,12 +7,12 @@ import { ApiService } from "@bitwarden/common/abstractions/api.service"; import { AccountService } from "@bitwarden/common/auth/abstractions/account.service"; import { KdfConfig } from "@bitwarden/common/auth/models/domain/kdf-config"; import { KdfRequest } from "@bitwarden/common/models/request/kdf.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 { KdfType } from "@bitwarden/common/platform/enums"; import { ToastService } from "@bitwarden/components"; +import { KeyService } from "@bitwarden/key-management"; @Component({ selector: "app-change-kdf-confirmation", @@ -32,7 +32,7 @@ export class ChangeKdfConfirmationComponent { private apiService: ApiService, private i18nService: I18nService, private platformUtilsService: PlatformUtilsService, - private cryptoService: CryptoService, + private keyService: KeyService, private messagingService: MessagingService, @Inject(DIALOG_DATA) params: { kdf: KdfType; kdfConfig: KdfConfig }, private accountService: AccountService, @@ -70,22 +70,18 @@ export class ChangeKdfConfirmationComponent { request.kdfMemory = this.kdfConfig.memory; request.kdfParallelism = this.kdfConfig.parallelism; } - const masterKey = await this.cryptoService.getOrDeriveMasterKey(masterPassword); - request.masterPasswordHash = await this.cryptoService.hashMasterKey(masterPassword, masterKey); + const masterKey = await this.keyService.getOrDeriveMasterKey(masterPassword); + request.masterPasswordHash = await this.keyService.hashMasterKey(masterPassword, masterKey); const email = await firstValueFrom( this.accountService.activeAccount$.pipe(map((a) => a?.email)), ); - const newMasterKey = await this.cryptoService.makeMasterKey( - masterPassword, - email, - this.kdfConfig, - ); - request.newMasterPasswordHash = await this.cryptoService.hashMasterKey( + const newMasterKey = await this.keyService.makeMasterKey(masterPassword, email, this.kdfConfig); + request.newMasterPasswordHash = await this.keyService.hashMasterKey( masterPassword, newMasterKey, ); - const newUserKey = await this.cryptoService.encryptUserKeyWithMasterKey(newMasterKey); + const newUserKey = await this.keyService.encryptUserKeyWithMasterKey(newMasterKey); request.key = newUserKey[1].encryptedString; await this.apiService.postAccountKdf(request); diff --git a/apps/web/src/app/billing/organizations/change-plan-dialog.component.ts b/apps/web/src/app/billing/organizations/change-plan-dialog.component.ts index c7cd7e45a9..0ba4829c7c 100644 --- a/apps/web/src/app/billing/organizations/change-plan-dialog.component.ts +++ b/apps/web/src/app/billing/organizations/change-plan-dialog.component.ts @@ -36,11 +36,11 @@ import { PaymentSourceResponse } from "@bitwarden/common/billing/models/response import { PlanResponse } from "@bitwarden/common/billing/models/response/plan.response"; import { FeatureFlag } from "@bitwarden/common/enums/feature-flag.enum"; import { ConfigService } from "@bitwarden/common/platform/abstractions/config/config.service"; -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 { SyncService } from "@bitwarden/common/vault/abstractions/sync/sync.service.abstraction"; import { DialogService, ToastService } from "@bitwarden/components"; +import { KeyService } from "@bitwarden/key-management"; import { PaymentV2Component } from "../shared/payment/payment-v2.component"; import { PaymentComponent } from "../shared/payment/payment.component"; @@ -177,7 +177,7 @@ export class ChangePlanDialogComponent implements OnInit, OnDestroy { private toastService: ToastService, private apiService: ApiService, private i18nService: I18nService, - private cryptoService: CryptoService, + private keyService: KeyService, private router: Router, private syncService: SyncService, private policyService: PolicyService, @@ -755,8 +755,8 @@ export class ChangePlanDialogComponent implements OnInit, OnDestroy { // Backfill pub/priv key if necessary if (!this.organization.hasPublicAndPrivateKeys) { - const orgShareKey = await this.cryptoService.getOrgKey(this.organizationId); - const orgKeys = await this.cryptoService.makeKeyPair(orgShareKey); + const orgShareKey = await this.keyService.getOrgKey(this.organizationId); + const orgKeys = await this.keyService.makeKeyPair(orgShareKey); request.keys = new OrganizationKeysRequest(orgKeys[0], orgKeys[1].encryptedString); } diff --git a/apps/web/src/app/billing/organizations/organization-plans.component.ts b/apps/web/src/app/billing/organizations/organization-plans.component.ts index 40dd0d7646..88b5685431 100644 --- a/apps/web/src/app/billing/organizations/organization-plans.component.ts +++ b/apps/web/src/app/billing/organizations/organization-plans.component.ts @@ -33,7 +33,6 @@ import { OrganizationSubscriptionResponse } from "@bitwarden/common/billing/mode import { PlanResponse } from "@bitwarden/common/billing/models/response/plan.response"; import { FeatureFlag } from "@bitwarden/common/enums/feature-flag.enum"; import { ConfigService } from "@bitwarden/common/platform/abstractions/config/config.service"; -import { CryptoService } from "@bitwarden/common/platform/abstractions/crypto.service"; import { EncryptService } from "@bitwarden/common/platform/abstractions/encrypt.service"; import { I18nService } from "@bitwarden/common/platform/abstractions/i18n.service"; import { MessagingService } from "@bitwarden/common/platform/abstractions/messaging.service"; @@ -43,6 +42,7 @@ import { SymmetricCryptoKey } from "@bitwarden/common/platform/models/domain/sym import { OrgKey } from "@bitwarden/common/types/key"; import { SyncService } from "@bitwarden/common/vault/abstractions/sync/sync.service.abstraction"; import { ToastService } from "@bitwarden/components"; +import { KeyService } from "@bitwarden/key-management"; import { OrganizationCreateModule } from "../../admin-console/organizations/create/organization-create.module"; import { BillingSharedModule, secretsManagerSubscribeFormFactory } from "../shared"; @@ -153,7 +153,7 @@ export class OrganizationPlansComponent implements OnInit, OnDestroy { private apiService: ApiService, private i18nService: I18nService, private platformUtilsService: PlatformUtilsService, - private cryptoService: CryptoService, + private keyService: KeyService, private encryptService: EncryptService, private router: Router, private syncService: SyncService, @@ -596,14 +596,14 @@ export class OrganizationPlansComponent implements OnInit, OnDestroy { const doSubmit = async (): Promise => { let orgId: string = null; if (this.createOrganization) { - const orgKey = await this.cryptoService.makeOrgKey(); + const orgKey = await this.keyService.makeOrgKey(); const key = orgKey[0].encryptedString; const collection = await this.encryptService.encrypt( this.i18nService.t("defaultCollection"), orgKey[1], ); const collectionCt = collection.encryptedString; - const orgKeys = await this.cryptoService.makeKeyPair(orgKey[1]); + const orgKeys = await this.keyService.makeKeyPair(orgKey[1]); if (this.selfHosted) { orgId = await this.createSelfHosted(key, collectionCt, orgKeys); @@ -690,8 +690,8 @@ export class OrganizationPlansComponent implements OnInit, OnDestroy { // Backfill pub/priv key if necessary if (!this.organization.hasPublicAndPrivateKeys) { - const orgShareKey = await this.cryptoService.getOrgKey(this.organizationId); - const orgKeys = await this.cryptoService.makeKeyPair(orgShareKey); + const orgShareKey = await this.keyService.getOrgKey(this.organizationId); + const orgKeys = await this.keyService.makeKeyPair(orgShareKey); request.keys = new OrganizationKeysRequest(orgKeys[0], orgKeys[1].encryptedString); } @@ -755,7 +755,7 @@ export class OrganizationPlansComponent implements OnInit, OnDestroy { this.formGroup.controls.clientOwnerEmail.value, request, ); - const providerKey = await this.cryptoService.getProviderKey(this.providerId); + const providerKey = await this.keyService.getProviderKey(this.providerId); providerRequest.organizationCreateRequest.key = ( await this.encryptService.encrypt(orgKey.key, providerKey) ).encryptedString; diff --git a/apps/web/src/app/billing/shared/self-hosting-license-uploader/organization-self-hosting-license-uploader.component.ts b/apps/web/src/app/billing/shared/self-hosting-license-uploader/organization-self-hosting-license-uploader.component.ts index 79c3cb83a4..87edce7b89 100644 --- a/apps/web/src/app/billing/shared/self-hosting-license-uploader/organization-self-hosting-license-uploader.component.ts +++ b/apps/web/src/app/billing/shared/self-hosting-license-uploader/organization-self-hosting-license-uploader.component.ts @@ -5,13 +5,13 @@ import { ApiService } from "@bitwarden/common/abstractions/api.service"; import { OrganizationApiServiceAbstraction } from "@bitwarden/common/admin-console/abstractions/organization/organization-api.service.abstraction"; import { OrganizationKeysRequest } from "@bitwarden/common/admin-console/models/request/organization-keys.request"; import { TokenService } from "@bitwarden/common/auth/abstractions/token.service"; -import { CryptoService } from "@bitwarden/common/platform/abstractions/crypto.service"; import { EncryptService } from "@bitwarden/common/platform/abstractions/encrypt.service"; import { I18nService } from "@bitwarden/common/platform/abstractions/i18n.service"; import { PlatformUtilsService } from "@bitwarden/common/platform/abstractions/platform-utils.service"; import { SyncService } from "@bitwarden/common/platform/sync"; import { OrgKey } from "@bitwarden/common/types/key"; import { ToastService } from "@bitwarden/components"; +import { KeyService } from "@bitwarden/key-management"; import { AbstractSelfHostingLicenseUploaderComponent } from "../../shared/self-hosting-license-uploader/abstract-self-hosting-license-uploader.component"; @@ -37,7 +37,7 @@ export class OrganizationSelfHostingLicenseUploaderComponent extends AbstractSel protected readonly tokenService: TokenService, private readonly apiService: ApiService, private readonly encryptService: EncryptService, - private readonly cryptoService: CryptoService, + private readonly keyService: KeyService, private readonly organizationApiService: OrganizationApiServiceAbstraction, private readonly syncService: SyncService, ) { @@ -47,14 +47,14 @@ export class OrganizationSelfHostingLicenseUploaderComponent extends AbstractSel protected async submit(): Promise { await super.submit(); - const orgKey = await this.cryptoService.makeOrgKey(); + const orgKey = await this.keyService.makeOrgKey(); const key = orgKey[0].encryptedString; const collection = await this.encryptService.encrypt( this.i18nService.t("defaultCollection"), orgKey[1], ); const collectionCt = collection.encryptedString; - const orgKeys = await this.cryptoService.makeKeyPair(orgKey[1]); + const orgKeys = await this.keyService.makeKeyPair(orgKey[1]); const fd = new FormData(); fd.append("license", this.formValue.file); diff --git a/apps/web/src/app/core/core.module.ts b/apps/web/src/app/core/core.module.ts index 48377c8e8e..bcf3ce6ec6 100644 --- a/apps/web/src/app/core/core.module.ts +++ b/apps/web/src/app/core/core.module.ts @@ -42,7 +42,6 @@ import { InternalMasterPasswordServiceAbstraction } from "@bitwarden/common/auth import { ClientType } from "@bitwarden/common/enums"; import { AppIdService } from "@bitwarden/common/platform/abstractions/app-id.service"; import { ConfigService } from "@bitwarden/common/platform/abstractions/config/config.service"; -import { CryptoService as CryptoServiceAbstraction } from "@bitwarden/common/platform/abstractions/crypto.service"; import { EncryptService } from "@bitwarden/common/platform/abstractions/encrypt.service"; import { EnvironmentService, @@ -72,7 +71,7 @@ import { ThemeStateService, } from "@bitwarden/common/platform/theming/theme-state.service"; import { VaultTimeout, VaultTimeoutStringType } from "@bitwarden/common/types/vault-timeout.type"; -import { BiometricsService } from "@bitwarden/key-management"; +import { KeyService as KeyServiceAbstraction, BiometricsService } from "@bitwarden/key-management"; import { flagEnabled } from "../../utils/flags"; import { PolicyListService } from "../admin-console/core/policy-list.service"; @@ -211,7 +210,7 @@ const safeProviders: SafeProvider[] = [ provide: RegistrationFinishServiceAbstraction, useClass: WebRegistrationFinishService, deps: [ - CryptoServiceAbstraction, + KeyServiceAbstraction, AccountApiServiceAbstraction, AcceptOrganizationInviteService, PolicyApiServiceAbstraction, @@ -229,7 +228,7 @@ const safeProviders: SafeProvider[] = [ useClass: WebSetPasswordJitService, deps: [ ApiService, - CryptoServiceAbstraction, + KeyServiceAbstraction, EncryptService, I18nServiceAbstraction, KdfConfigService, @@ -247,7 +246,7 @@ const safeProviders: SafeProvider[] = [ safeProvider({ provide: CollectionAdminService, useClass: DefaultCollectionAdminService, - deps: [ApiService, CryptoServiceAbstraction, EncryptService, CollectionService], + deps: [ApiService, KeyServiceAbstraction, EncryptService, CollectionService], }), safeProvider({ provide: SdkClientFactory, diff --git a/apps/web/src/app/core/init.service.ts b/apps/web/src/app/core/init.service.ts index 55dc1544ff..4bd0ff1f48 100644 --- a/apps/web/src/app/core/init.service.ts +++ b/apps/web/src/app/core/init.service.ts @@ -8,7 +8,6 @@ import { EventUploadService as EventUploadServiceAbstraction } from "@bitwarden/ import { NotificationsService as NotificationsServiceAbstraction } from "@bitwarden/common/abstractions/notifications.service"; import { AccountService } from "@bitwarden/common/auth/abstractions/account.service"; import { TwoFactorService as TwoFactorServiceAbstraction } from "@bitwarden/common/auth/abstractions/two-factor.service"; -import { CryptoService as CryptoServiceAbstraction } from "@bitwarden/common/platform/abstractions/crypto.service"; import { EncryptService } from "@bitwarden/common/platform/abstractions/encrypt.service"; import { I18nService as I18nServiceAbstraction } from "@bitwarden/common/platform/abstractions/i18n.service"; import { StateService as StateServiceAbstraction } from "@bitwarden/common/platform/abstractions/state.service"; @@ -16,6 +15,7 @@ import { ContainerService } from "@bitwarden/common/platform/services/container. import { UserAutoUnlockKeyService } from "@bitwarden/common/platform/services/user-auto-unlock-key.service"; import { EventUploadService } from "@bitwarden/common/services/event/event-upload.service"; import { VaultTimeoutService } from "@bitwarden/common/services/vault-timeout/vault-timeout.service"; +import { KeyService as KeyServiceAbstraction } from "@bitwarden/key-management"; @Injectable() export class InitService { @@ -27,7 +27,7 @@ export class InitService { private eventUploadService: EventUploadServiceAbstraction, private twoFactorService: TwoFactorServiceAbstraction, private stateService: StateServiceAbstraction, - private cryptoService: CryptoServiceAbstraction, + private keyService: KeyServiceAbstraction, private themingService: AbstractThemingService, private encryptService: EncryptService, private userAutoUnlockKeyService: UserAutoUnlockKeyService, @@ -54,7 +54,7 @@ export class InitService { const htmlEl = this.win.document.documentElement; htmlEl.classList.add("locale_" + this.i18nService.translationLocale); this.themingService.applyThemeChangesTo(this.document); - const containerService = new ContainerService(this.cryptoService, this.encryptService); + const containerService = new ContainerService(this.keyService, this.encryptService); containerService.attachToGlobal(this.win); }; } diff --git a/apps/web/src/app/shared/components/account-fingerprint/account-fingerprint.component.ts b/apps/web/src/app/shared/components/account-fingerprint/account-fingerprint.component.ts index e937806990..79f9ed1bf8 100644 --- a/apps/web/src/app/shared/components/account-fingerprint/account-fingerprint.component.ts +++ b/apps/web/src/app/shared/components/account-fingerprint/account-fingerprint.component.ts @@ -1,6 +1,6 @@ import { Component, Input, OnInit } from "@angular/core"; -import { CryptoService } from "@bitwarden/common/platform/abstractions/crypto.service"; +import { KeyService } from "@bitwarden/key-management"; import { SharedModule } from "../../shared.module"; @@ -17,11 +17,11 @@ export class AccountFingerprintComponent implements OnInit { protected fingerprint: string; - constructor(private cryptoService: CryptoService) {} + constructor(private keyService: KeyService) {} async ngOnInit() { // TODO - In the future, remove this code and use the fingerprint pipe once merged - const generatedFingerprint = await this.cryptoService.getFingerprint( + const generatedFingerprint = await this.keyService.getFingerprint( this.fingerprintMaterial, this.publicKeyBuffer, ); diff --git a/apps/web/src/app/tools/send/access.component.ts b/apps/web/src/app/tools/send/access.component.ts index 32bd554baa..3c64ee90ca 100644 --- a/apps/web/src/app/tools/send/access.component.ts +++ b/apps/web/src/app/tools/send/access.component.ts @@ -7,7 +7,6 @@ import { RegisterRouteService } from "@bitwarden/auth/common"; import { ErrorResponse } from "@bitwarden/common/models/response/error.response"; import { ConfigService } from "@bitwarden/common/platform/abstractions/config/config.service"; import { CryptoFunctionService } from "@bitwarden/common/platform/abstractions/crypto-function.service"; -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 { SymmetricCryptoKey } from "@bitwarden/common/platform/models/domain/symmetric-crypto-key"; @@ -19,6 +18,7 @@ import { SendAccessView } from "@bitwarden/common/tools/send/models/view/send-ac import { SEND_KDF_ITERATIONS } from "@bitwarden/common/tools/send/send-kdf"; import { SendApiService } from "@bitwarden/common/tools/send/services/send-api.service.abstraction"; import { NoItemsModule, ToastService } from "@bitwarden/components"; +import { KeyService } from "@bitwarden/key-management"; import { ExpiredSendIcon } from "@bitwarden/send-ui"; import { SharedModule } from "../../shared"; @@ -65,7 +65,7 @@ export class AccessComponent implements OnInit { constructor( private cryptoFunctionService: CryptoFunctionService, private route: ActivatedRoute, - private cryptoService: CryptoService, + private keyService: KeyService, private sendApiService: SendApiService, private toastService: ToastService, private i18nService: I18nService, @@ -126,7 +126,7 @@ export class AccessComponent implements OnInit { } this.passwordRequired = false; const sendAccess = new SendAccess(sendResponse); - this.decKey = await this.cryptoService.makeSendKey(keyArray); + this.decKey = await this.keyService.makeSendKey(keyArray); this.send = await sendAccess.decrypt(this.decKey); } catch (e) { if (e instanceof ErrorResponse) { diff --git a/apps/web/src/app/vault/individual-vault/add-edit-v2.component.spec.ts b/apps/web/src/app/vault/individual-vault/add-edit-v2.component.spec.ts index 25115c29c3..6c12623523 100644 --- a/apps/web/src/app/vault/individual-vault/add-edit-v2.component.spec.ts +++ b/apps/web/src/app/vault/individual-vault/add-edit-v2.component.spec.ts @@ -10,13 +10,13 @@ import { PolicyService } from "@bitwarden/common/admin-console/abstractions/poli import { PolicyType } from "@bitwarden/common/admin-console/enums"; import { Organization } from "@bitwarden/common/admin-console/models/domain/organization"; import { BillingAccountProfileStateService } from "@bitwarden/common/billing/abstractions/account/billing-account-profile-state.service"; -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 { CipherService } from "@bitwarden/common/vault/abstractions/cipher.service"; import { FolderService } from "@bitwarden/common/vault/abstractions/folder/folder.service.abstraction"; import { DialogService } from "@bitwarden/components"; import { PasswordGenerationServiceAbstraction } from "@bitwarden/generator-legacy"; +import { KeyService } from "@bitwarden/key-management"; import { CipherFormConfig, DefaultCipherFormConfigService } from "@bitwarden/vault"; import { AddEditComponentV2 } from "./add-edit-v2.component"; @@ -89,7 +89,7 @@ describe("AddEditComponentV2", () => { { provide: ActivatedRoute, useValue: activatedRoute }, { provide: CollectionService, useValue: collectionService }, { provide: FolderService, useValue: folderService }, - { provide: CryptoService, useValue: mock() }, + { provide: KeyService, useValue: mock() }, { provide: BillingAccountProfileStateService, useValue: billingAccountProfileStateService }, { provide: PolicyService, useValue: policyService }, { provide: DefaultCipherFormConfigService, useValue: mockDefaultCipherFormConfigService }, diff --git a/apps/web/src/app/vault/individual-vault/attachments.component.ts b/apps/web/src/app/vault/individual-vault/attachments.component.ts index bb070ef688..a6c25b71fd 100644 --- a/apps/web/src/app/vault/individual-vault/attachments.component.ts +++ b/apps/web/src/app/vault/individual-vault/attachments.component.ts @@ -4,7 +4,6 @@ import { AttachmentsComponent as BaseAttachmentsComponent } from "@bitwarden/ang import { ApiService } from "@bitwarden/common/abstractions/api.service"; import { AccountService } from "@bitwarden/common/auth/abstractions/account.service"; import { BillingAccountProfileStateService } from "@bitwarden/common/billing/abstractions/account/billing-account-profile-state.service"; -import { CryptoService } from "@bitwarden/common/platform/abstractions/crypto.service"; import { EncryptService } from "@bitwarden/common/platform/abstractions/encrypt.service"; import { FileDownloadService } from "@bitwarden/common/platform/abstractions/file-download/file-download.service"; import { I18nService } from "@bitwarden/common/platform/abstractions/i18n.service"; @@ -14,6 +13,7 @@ import { StateService } from "@bitwarden/common/platform/abstractions/state.serv import { CipherService } from "@bitwarden/common/vault/abstractions/cipher.service"; import { AttachmentView } from "@bitwarden/common/vault/models/view/attachment.view"; import { DialogService, ToastService } from "@bitwarden/components"; +import { KeyService } from "@bitwarden/key-management"; @Component({ selector: "app-vault-attachments", @@ -25,7 +25,7 @@ export class AttachmentsComponent extends BaseAttachmentsComponent { constructor( cipherService: CipherService, i18nService: I18nService, - cryptoService: CryptoService, + keyService: KeyService, encryptService: EncryptService, stateService: StateService, platformUtilsService: PlatformUtilsService, @@ -40,7 +40,7 @@ export class AttachmentsComponent extends BaseAttachmentsComponent { super( cipherService, i18nService, - cryptoService, + keyService, encryptService, platformUtilsService, apiService, diff --git a/apps/web/src/app/vault/individual-vault/folder-add-edit.component.ts b/apps/web/src/app/vault/individual-vault/folder-add-edit.component.ts index bc31cdc8cd..95f3e60d8c 100644 --- a/apps/web/src/app/vault/individual-vault/folder-add-edit.component.ts +++ b/apps/web/src/app/vault/individual-vault/folder-add-edit.component.ts @@ -5,13 +5,13 @@ import { firstValueFrom } from "rxjs"; import { FolderAddEditComponent as BaseFolderAddEditComponent } from "@bitwarden/angular/vault/components/folder-add-edit.component"; import { AccountService } from "@bitwarden/common/auth/abstractions/account.service"; -import { CryptoService } from "@bitwarden/common/platform/abstractions/crypto.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 { FolderApiServiceAbstraction } from "@bitwarden/common/vault/abstractions/folder/folder-api.service.abstraction"; import { FolderService } from "@bitwarden/common/vault/abstractions/folder/folder.service.abstraction"; import { DialogService, ToastService } from "@bitwarden/components"; +import { KeyService } from "@bitwarden/key-management"; @Component({ selector: "app-folder-add-edit", @@ -23,7 +23,7 @@ export class FolderAddEditComponent extends BaseFolderAddEditComponent { folderService: FolderService, folderApiService: FolderApiServiceAbstraction, protected accountSerivce: AccountService, - protected cryptoService: CryptoService, + protected keyService: KeyService, i18nService: I18nService, platformUtilsService: PlatformUtilsService, logService: LogService, @@ -37,7 +37,7 @@ export class FolderAddEditComponent extends BaseFolderAddEditComponent { folderService, folderApiService, accountSerivce, - cryptoService, + keyService, i18nService, platformUtilsService, logService, @@ -81,7 +81,7 @@ export class FolderAddEditComponent extends BaseFolderAddEditComponent { try { const activeAccountId = (await firstValueFrom(this.accountSerivce.activeAccount$)).id; - const userKey = await this.cryptoService.getUserKeyWithLegacySupport(activeAccountId); + const userKey = await this.keyService.getUserKeyWithLegacySupport(activeAccountId); const folder = await this.folderService.encrypt(this.folder, userKey); this.formPromise = this.folderApiService.save(folder); await this.formPromise; diff --git a/apps/web/src/app/vault/individual-vault/view.component.spec.ts b/apps/web/src/app/vault/individual-vault/view.component.spec.ts index d1bfd22117..b26c55d46e 100644 --- a/apps/web/src/app/vault/individual-vault/view.component.spec.ts +++ b/apps/web/src/app/vault/individual-vault/view.component.spec.ts @@ -7,7 +7,6 @@ import { OrganizationService } from "@bitwarden/common/admin-console/abstraction import { Organization } from "@bitwarden/common/admin-console/models/domain/organization"; import { BillingAccountProfileStateService } from "@bitwarden/common/billing/abstractions/account/billing-account-profile-state.service"; import { ConfigService } from "@bitwarden/common/platform/abstractions/config/config.service"; -import { CryptoService } from "@bitwarden/common/platform/abstractions/crypto.service"; import { I18nService } from "@bitwarden/common/platform/abstractions/i18n.service"; import { LogService } from "@bitwarden/common/platform/abstractions/log.service"; import { MessagingService } from "@bitwarden/common/platform/abstractions/messaging.service"; @@ -16,6 +15,7 @@ import { FolderService } from "@bitwarden/common/vault/abstractions/folder/folde import { CipherView } from "@bitwarden/common/vault/models/view/cipher.view"; import { CipherAuthorizationService } from "@bitwarden/common/vault/services/cipher-authorization.service"; import { DialogService, ToastService } from "@bitwarden/components"; +import { KeyService } from "@bitwarden/key-management"; import { ViewCipherDialogParams, ViewCipherDialogResult, ViewComponent } from "./view.component"; @@ -57,7 +57,7 @@ describe("ViewComponent", () => { }, { provide: CollectionService, useValue: mock() }, { provide: FolderService, useValue: mock() }, - { provide: CryptoService, useValue: mock() }, + { provide: KeyService, useValue: mock() }, { provide: BillingAccountProfileStateService, useValue: mock(), diff --git a/apps/web/src/app/vault/org-vault/attachments.component.ts b/apps/web/src/app/vault/org-vault/attachments.component.ts index 62e65ade5d..2f3f477cb2 100644 --- a/apps/web/src/app/vault/org-vault/attachments.component.ts +++ b/apps/web/src/app/vault/org-vault/attachments.component.ts @@ -4,7 +4,6 @@ import { ApiService } from "@bitwarden/common/abstractions/api.service"; import { Organization } from "@bitwarden/common/admin-console/models/domain/organization"; import { AccountService } from "@bitwarden/common/auth/abstractions/account.service"; import { BillingAccountProfileStateService } from "@bitwarden/common/billing/abstractions/account/billing-account-profile-state.service"; -import { CryptoService } from "@bitwarden/common/platform/abstractions/crypto.service"; import { EncryptService } from "@bitwarden/common/platform/abstractions/encrypt.service"; import { FileDownloadService } from "@bitwarden/common/platform/abstractions/file-download/file-download.service"; import { I18nService } from "@bitwarden/common/platform/abstractions/i18n.service"; @@ -17,6 +16,7 @@ import { CipherData } from "@bitwarden/common/vault/models/data/cipher.data"; import { Cipher } from "@bitwarden/common/vault/models/domain/cipher"; import { AttachmentView } from "@bitwarden/common/vault/models/view/attachment.view"; import { DialogService, ToastService } from "@bitwarden/components"; +import { KeyService } from "@bitwarden/key-management"; import { AttachmentsComponent as BaseAttachmentsComponent } from "../individual-vault/attachments.component"; @@ -31,7 +31,7 @@ export class AttachmentsComponent extends BaseAttachmentsComponent implements On constructor( cipherService: CipherService, i18nService: I18nService, - cryptoService: CryptoService, + keyService: KeyService, encryptService: EncryptService, stateService: StateService, platformUtilsService: PlatformUtilsService, @@ -46,7 +46,7 @@ export class AttachmentsComponent extends BaseAttachmentsComponent implements On super( cipherService, i18nService, - cryptoService, + keyService, encryptService, stateService, platformUtilsService, diff --git a/bitwarden_license/bit-cli/src/service-container.ts b/bitwarden_license/bit-cli/src/service-container.ts index c624afd946..f82efecdce 100644 --- a/bitwarden_license/bit-cli/src/service-container.ts +++ b/bitwarden_license/bit-cli/src/service-container.ts @@ -17,7 +17,7 @@ export class ServiceContainer extends OssServiceContainer { this.organizationAuthRequestApiService = new OrganizationAuthRequestApiService(this.apiService); this.organizationAuthRequestService = new OrganizationAuthRequestService( this.organizationAuthRequestApiService, - this.cryptoService, + this.keyService, this.encryptService, this.organizationUserApiService, ); diff --git a/bitwarden_license/bit-common/src/admin-console/auth-requests/organization-auth-request.service.spec.ts b/bitwarden_license/bit-common/src/admin-console/auth-requests/organization-auth-request.service.spec.ts index 0eda8aa765..e893b2dfe8 100644 --- a/bitwarden_license/bit-common/src/admin-console/auth-requests/organization-auth-request.service.spec.ts +++ b/bitwarden_license/bit-common/src/admin-console/auth-requests/organization-auth-request.service.spec.ts @@ -5,9 +5,9 @@ import { OrganizationUserResetPasswordDetailsResponse, } from "@bitwarden/admin-console/common"; import { ListResponse } from "@bitwarden/common/models/response/list.response"; -import { CryptoService } from "@bitwarden/common/platform/abstractions/crypto.service"; import { EncryptService } from "@bitwarden/common/platform/abstractions/encrypt.service"; import { EncString } from "@bitwarden/common/platform/models/domain/enc-string"; +import { KeyService } from "@bitwarden/key-management"; import { OrganizationAuthRequestApiService } from "./organization-auth-request-api.service"; import { OrganizationAuthRequestUpdateRequest } from "./organization-auth-request-update.request"; @@ -16,19 +16,19 @@ import { PendingAuthRequestView } from "./pending-auth-request.view"; describe("OrganizationAuthRequestService", () => { let organizationAuthRequestApiService: MockProxy; - let cryptoService: MockProxy; + let keyService: MockProxy; let encryptService: MockProxy; let organizationUserApiService: MockProxy; let organizationAuthRequestService: OrganizationAuthRequestService; beforeEach(() => { organizationAuthRequestApiService = mock(); - cryptoService = mock(); + keyService = mock(); encryptService = mock(); organizationUserApiService = mock(); organizationAuthRequestService = new OrganizationAuthRequestService( organizationAuthRequestApiService, - cryptoService, + keyService, encryptService, organizationUserApiService, ); diff --git a/bitwarden_license/bit-common/src/admin-console/auth-requests/organization-auth-request.service.ts b/bitwarden_license/bit-common/src/admin-console/auth-requests/organization-auth-request.service.ts index 9c86b59dfb..b2c4c1c04f 100644 --- a/bitwarden_license/bit-common/src/admin-console/auth-requests/organization-auth-request.service.ts +++ b/bitwarden_license/bit-common/src/admin-console/auth-requests/organization-auth-request.service.ts @@ -2,11 +2,11 @@ import { OrganizationUserApiService, OrganizationUserResetPasswordDetailsResponse, } from "@bitwarden/admin-console/common"; -import { CryptoService } from "@bitwarden/common/platform/abstractions/crypto.service"; import { EncryptService } from "@bitwarden/common/platform/abstractions/encrypt.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 { KeyService } from "@bitwarden/key-management"; import { OrganizationAuthRequestApiService } from "./organization-auth-request-api.service"; import { OrganizationAuthRequestUpdateRequest } from "./organization-auth-request-update.request"; @@ -15,7 +15,7 @@ import { PendingAuthRequestView } from "./pending-auth-request.view"; export class OrganizationAuthRequestService { constructor( private organizationAuthRequestApiService: OrganizationAuthRequestApiService, - private cryptoService: CryptoService, + private keyService: KeyService, private encryptService: EncryptService, private organizationUserApiService: OrganizationUserApiService, ) {} @@ -110,7 +110,7 @@ export class OrganizationAuthRequestService { const devicePubKey = Utils.fromB64ToArray(devicePublicKey); // Decrypt Organization's encrypted Private Key with org key - const orgSymKey = await this.cryptoService.getOrgKey(organizationId); + const orgSymKey = await this.keyService.getOrgKey(organizationId); const decOrgPrivateKey = await this.encryptService.decryptToBytes( new EncString(encryptedOrgPrivateKey), orgSymKey, diff --git a/bitwarden_license/bit-web/src/app/admin-console/organizations/manage/device-approvals/device-approvals.component.ts b/bitwarden_license/bit-web/src/app/admin-console/organizations/manage/device-approvals/device-approvals.component.ts index e074e0dd31..4a4cbe312c 100644 --- a/bitwarden_license/bit-web/src/app/admin-console/organizations/manage/device-approvals/device-approvals.component.ts +++ b/bitwarden_license/bit-web/src/app/admin-console/organizations/manage/device-approvals/device-approvals.component.ts @@ -9,13 +9,13 @@ import { OrganizationAuthRequestService } from "@bitwarden/bit-common/admin-cons import { PendingAuthRequestView } from "@bitwarden/bit-common/admin-console/auth-requests/pending-auth-request.view"; import { ApiService } from "@bitwarden/common/abstractions/api.service"; import { ConfigService } from "@bitwarden/common/platform/abstractions/config/config.service"; -import { CryptoService } from "@bitwarden/common/platform/abstractions/crypto.service"; import { EncryptService } from "@bitwarden/common/platform/abstractions/encrypt.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 { ValidationService } from "@bitwarden/common/platform/abstractions/validation.service"; import { TableDataSource, NoItemsModule, ToastService } from "@bitwarden/components"; +import { KeyService } from "@bitwarden/key-management"; import { Devices } from "@bitwarden/web-vault/app/admin-console/icons"; import { LooseComponentsModule } from "@bitwarden/web-vault/app/shared"; import { SharedModule } from "@bitwarden/web-vault/app/shared/shared.module"; @@ -33,7 +33,7 @@ import { SharedModule } from "@bitwarden/web-vault/app/shared/shared.module"; provide: OrganizationAuthRequestService, deps: [ OrganizationAuthRequestApiService, - CryptoService, + KeyService, EncryptService, OrganizationUserApiService, ], diff --git a/bitwarden_license/bit-web/src/app/admin-console/providers/manage/dialogs/bulk-confirm-dialog.component.ts b/bitwarden_license/bit-web/src/app/admin-console/providers/manage/dialogs/bulk-confirm-dialog.component.ts index 61145efb78..644070c12d 100644 --- a/bitwarden_license/bit-web/src/app/admin-console/providers/manage/dialogs/bulk-confirm-dialog.component.ts +++ b/bitwarden_license/bit-web/src/app/admin-console/providers/manage/dialogs/bulk-confirm-dialog.component.ts @@ -12,11 +12,11 @@ import { ProviderUserBulkRequest } from "@bitwarden/common/admin-console/models/ import { ProviderUserBulkPublicKeyResponse } from "@bitwarden/common/admin-console/models/response/provider/provider-user-bulk-public-key.response"; import { ProviderUserBulkResponse } from "@bitwarden/common/admin-console/models/response/provider/provider-user-bulk.response"; import { ListResponse } from "@bitwarden/common/models/response/list.response"; -import { CryptoService } from "@bitwarden/common/platform/abstractions/crypto.service"; import { EncryptService } from "@bitwarden/common/platform/abstractions/encrypt.service"; import { I18nService } from "@bitwarden/common/platform/abstractions/i18n.service"; import { SymmetricCryptoKey } from "@bitwarden/common/platform/models/domain/symmetric-crypto-key"; import { DialogService } from "@bitwarden/components"; +import { KeyService } from "@bitwarden/key-management"; import { BaseBulkConfirmComponent } from "@bitwarden/web-vault/app/admin-console/organizations/members/components/bulk/base-bulk-confirm.component"; import { BulkUserDetails } from "@bitwarden/web-vault/app/admin-console/organizations/members/components/bulk/bulk-status.component"; @@ -34,19 +34,19 @@ export class BulkConfirmDialogComponent extends BaseBulkConfirmComponent { constructor( private apiService: ApiService, - protected cryptoService: CryptoService, + protected keyService: KeyService, protected encryptService: EncryptService, @Inject(DIALOG_DATA) protected dialogParams: BulkConfirmDialogParams, protected i18nService: I18nService, ) { - super(cryptoService, encryptService, i18nService); + super(keyService, encryptService, i18nService); this.providerId = dialogParams.providerId; this.users = dialogParams.users; } protected getCryptoKey = (): Promise => - this.cryptoService.getProviderKey(this.providerId); + this.keyService.getProviderKey(this.providerId); protected getPublicKeys = async (): Promise< ListResponse diff --git a/bitwarden_license/bit-web/src/app/admin-console/providers/manage/members.component.ts b/bitwarden_license/bit-web/src/app/admin-console/providers/manage/members.component.ts index 38c2dade20..86d52c3815 100644 --- a/bitwarden_license/bit-web/src/app/admin-console/providers/manage/members.component.ts +++ b/bitwarden_license/bit-web/src/app/admin-console/providers/manage/members.component.ts @@ -14,12 +14,12 @@ import { ProviderUserBulkRequest } from "@bitwarden/common/admin-console/models/ import { ProviderUserConfirmRequest } from "@bitwarden/common/admin-console/models/request/provider/provider-user-confirm.request"; import { ProviderUserUserDetailsResponse } from "@bitwarden/common/admin-console/models/response/provider/provider-user.response"; import { ListResponse } from "@bitwarden/common/models/response/list.response"; -import { CryptoService } from "@bitwarden/common/platform/abstractions/crypto.service"; import { EncryptService } from "@bitwarden/common/platform/abstractions/encrypt.service"; import { I18nService } from "@bitwarden/common/platform/abstractions/i18n.service"; import { LogService } from "@bitwarden/common/platform/abstractions/log.service"; import { ValidationService } from "@bitwarden/common/platform/abstractions/validation.service"; import { DialogService, ToastService } from "@bitwarden/components"; +import { KeyService } from "@bitwarden/key-management"; import { BaseMembersComponent } from "@bitwarden/web-vault/app/admin-console/common/base-members.component"; import { peopleFilter, @@ -59,7 +59,7 @@ export class MembersComponent extends BaseMembersComponent { constructor( apiService: ApiService, - cryptoService: CryptoService, + keyService: KeyService, dialogService: DialogService, i18nService: I18nService, logService: LogService, @@ -75,7 +75,7 @@ export class MembersComponent extends BaseMembersComponent { super( apiService, i18nService, - cryptoService, + keyService, validationService, logService, userNamePipe, @@ -185,7 +185,7 @@ export class MembersComponent extends BaseMembersComponent { } async confirmUser(user: ProviderUser, publicKey: Uint8Array): Promise { - const providerKey = await this.cryptoService.getProviderKey(this.providerId); + const providerKey = await this.keyService.getProviderKey(this.providerId); const key = await this.encryptService.rsaEncrypt(providerKey.key, publicKey); const request = new ProviderUserConfirmRequest(); request.key = key.encryptedString; diff --git a/bitwarden_license/bit-web/src/app/admin-console/providers/services/web-provider.service.ts b/bitwarden_license/bit-web/src/app/admin-console/providers/services/web-provider.service.ts index 3a2c7b8b64..6f013d27f7 100644 --- a/bitwarden_license/bit-web/src/app/admin-console/providers/services/web-provider.service.ts +++ b/bitwarden_license/bit-web/src/app/admin-console/providers/services/web-provider.service.ts @@ -6,16 +6,16 @@ import { ProviderAddOrganizationRequest } from "@bitwarden/common/admin-console/ import { BillingApiServiceAbstraction } from "@bitwarden/common/billing/abstractions/billing-api.service.abstraction"; import { PlanType } from "@bitwarden/common/billing/enums"; import { CreateClientOrganizationRequest } from "@bitwarden/common/billing/models/request/create-client-organization.request"; -import { CryptoService } from "@bitwarden/common/platform/abstractions/crypto.service"; import { EncryptService } from "@bitwarden/common/platform/abstractions/encrypt.service"; import { I18nService } from "@bitwarden/common/platform/abstractions/i18n.service"; import { OrgKey } from "@bitwarden/common/types/key"; import { SyncService } from "@bitwarden/common/vault/abstractions/sync/sync.service.abstraction"; +import { KeyService } from "@bitwarden/key-management"; @Injectable() export class WebProviderService { constructor( - private cryptoService: CryptoService, + private keyService: KeyService, private syncService: SyncService, private apiService: ApiService, private i18nService: I18nService, @@ -24,8 +24,8 @@ export class WebProviderService { ) {} async addOrganizationToProvider(providerId: string, organizationId: string) { - const orgKey = await this.cryptoService.getOrgKey(organizationId); - const providerKey = await this.cryptoService.getProviderKey(providerId); + const orgKey = await this.keyService.getOrgKey(organizationId); + const providerKey = await this.keyService.getProviderKey(providerId); const encryptedOrgKey = await this.encryptService.encrypt(orgKey.key, providerKey); @@ -45,16 +45,16 @@ export class WebProviderService { planType: PlanType, seats: number, ): Promise { - const organizationKey = (await this.cryptoService.makeOrgKey())[1]; + const organizationKey = (await this.keyService.makeOrgKey())[1]; - const [publicKey, encryptedPrivateKey] = await this.cryptoService.makeKeyPair(organizationKey); + const [publicKey, encryptedPrivateKey] = await this.keyService.makeKeyPair(organizationKey); const encryptedCollectionName = await this.encryptService.encrypt( this.i18nService.t("defaultCollection"), organizationKey, ); - const providerKey = await this.cryptoService.getProviderKey(providerId); + const providerKey = await this.keyService.getProviderKey(providerId); const encryptedProviderKey = await this.encryptService.encrypt( organizationKey.key, diff --git a/bitwarden_license/bit-web/src/app/admin-console/providers/setup/setup.component.ts b/bitwarden_license/bit-web/src/app/admin-console/providers/setup/setup.component.ts index e01c01b4da..aaad0ce457 100644 --- a/bitwarden_license/bit-web/src/app/admin-console/providers/setup/setup.component.ts +++ b/bitwarden_license/bit-web/src/app/admin-console/providers/setup/setup.component.ts @@ -10,12 +10,12 @@ import { ProviderSetupRequest } from "@bitwarden/common/admin-console/models/req import { ExpandedTaxInfoUpdateRequest } from "@bitwarden/common/billing/models/request/expanded-tax-info-update.request"; import { FeatureFlag } from "@bitwarden/common/enums/feature-flag.enum"; import { ConfigService } from "@bitwarden/common/platform/abstractions/config/config.service"; -import { CryptoService } from "@bitwarden/common/platform/abstractions/crypto.service"; import { I18nService } from "@bitwarden/common/platform/abstractions/i18n.service"; import { ValidationService } from "@bitwarden/common/platform/abstractions/validation.service"; import { ProviderKey } from "@bitwarden/common/types/key"; import { SyncService } from "@bitwarden/common/vault/abstractions/sync/sync.service.abstraction"; import { ToastService } from "@bitwarden/components"; +import { KeyService } from "@bitwarden/key-management"; @Component({ selector: "provider-setup", @@ -44,7 +44,7 @@ export class SetupComponent implements OnInit, OnDestroy { private router: Router, private i18nService: I18nService, private route: ActivatedRoute, - private cryptoService: CryptoService, + private keyService: KeyService, private syncService: SyncService, private validationService: ValidationService, private configService: ConfigService, @@ -124,7 +124,7 @@ export class SetupComponent implements OnInit, OnDestroy { return; } - const providerKey = await this.cryptoService.makeOrgKey(); + const providerKey = await this.keyService.makeOrgKey(); const key = providerKey[0].encryptedString; const request = new ProviderSetupRequest(); diff --git a/bitwarden_license/bit-web/src/app/secrets-manager/projects/project.service.ts b/bitwarden_license/bit-web/src/app/secrets-manager/projects/project.service.ts index 282980ece7..db1ee181e6 100644 --- a/bitwarden_license/bit-web/src/app/secrets-manager/projects/project.service.ts +++ b/bitwarden_license/bit-web/src/app/secrets-manager/projects/project.service.ts @@ -3,10 +3,10 @@ import { Subject } from "rxjs"; import { ApiService } from "@bitwarden/common/abstractions/api.service"; import { ListResponse } from "@bitwarden/common/models/response/list.response"; -import { CryptoService } from "@bitwarden/common/platform/abstractions/crypto.service"; import { EncryptService } from "@bitwarden/common/platform/abstractions/encrypt.service"; import { EncString } from "@bitwarden/common/platform/models/domain/enc-string"; import { SymmetricCryptoKey } from "@bitwarden/common/platform/models/domain/symmetric-crypto-key"; +import { KeyService } from "@bitwarden/key-management"; import { ProjectListView } from "../models/view/project-list.view"; import { ProjectView } from "../models/view/project.view"; @@ -24,7 +24,7 @@ export class ProjectService { project$ = this._project.asObservable(); constructor( - private cryptoService: CryptoService, + private keyService: KeyService, private apiService: ApiService, private encryptService: EncryptService, ) {} @@ -82,7 +82,7 @@ export class ProjectService { } private async getOrganizationKey(organizationId: string): Promise { - return await this.cryptoService.getOrgKey(organizationId); + return await this.keyService.getOrgKey(organizationId); } private async getProjectRequest( diff --git a/bitwarden_license/bit-web/src/app/secrets-manager/secrets/secret.service.spec.ts b/bitwarden_license/bit-web/src/app/secrets-manager/secrets/secret.service.spec.ts index f2a77553fb..a3d46d2ef2 100644 --- a/bitwarden_license/bit-web/src/app/secrets-manager/secrets/secret.service.spec.ts +++ b/bitwarden_license/bit-web/src/app/secrets-manager/secrets/secret.service.spec.ts @@ -1,9 +1,9 @@ import { mock } from "jest-mock-extended"; import { ApiService } from "@bitwarden/common/abstractions/api.service"; -import { CryptoService } from "@bitwarden/common/platform/abstractions/crypto.service"; import { EncryptService } from "@bitwarden/common/platform/abstractions/encrypt.service"; import { EncString } from "@bitwarden/common/platform/models/domain/enc-string"; +import { KeyService } from "@bitwarden/key-management"; import { SecretAccessPoliciesView } from "../models/view/access-policies/secret-access-policies.view"; import { SecretView } from "../models/view/secret.view"; @@ -14,7 +14,7 @@ import { SecretService } from "./secret.service"; describe("SecretService", () => { let sut: SecretService; - const cryptoService = mock(); + const keyService = mock(); const apiService = mock(); const encryptService = mock(); const accessPolicyService = mock(); @@ -22,7 +22,7 @@ describe("SecretService", () => { beforeEach(() => { jest.resetAllMocks(); - sut = new SecretService(cryptoService, apiService, encryptService, accessPolicyService); + sut = new SecretService(keyService, apiService, encryptService, accessPolicyService); encryptService.encrypt.mockResolvedValue({ encryptedString: "mockEncryptedString", diff --git a/bitwarden_license/bit-web/src/app/secrets-manager/secrets/secret.service.ts b/bitwarden_license/bit-web/src/app/secrets-manager/secrets/secret.service.ts index 0848ab9e7a..4547831ae1 100644 --- a/bitwarden_license/bit-web/src/app/secrets-manager/secrets/secret.service.ts +++ b/bitwarden_license/bit-web/src/app/secrets-manager/secrets/secret.service.ts @@ -2,10 +2,10 @@ import { Injectable } from "@angular/core"; import { Subject } from "rxjs"; import { ApiService } from "@bitwarden/common/abstractions/api.service"; -import { CryptoService } from "@bitwarden/common/platform/abstractions/crypto.service"; import { EncryptService } from "@bitwarden/common/platform/abstractions/encrypt.service"; import { EncString } from "@bitwarden/common/platform/models/domain/enc-string"; import { SymmetricCryptoKey } from "@bitwarden/common/platform/models/domain/symmetric-crypto-key"; +import { KeyService } from "@bitwarden/key-management"; import { SecretAccessPoliciesView } from "../models/view/access-policies/secret-access-policies.view"; import { SecretListView } from "../models/view/secret-list.view"; @@ -29,7 +29,7 @@ export class SecretService { secret$ = this._secret.asObservable(); constructor( - private cryptoService: CryptoService, + private keyService: KeyService, private apiService: ApiService, private encryptService: EncryptService, private accessPolicyService: AccessPolicyService, @@ -153,7 +153,7 @@ export class SecretService { } private async getOrganizationKey(organizationId: string): Promise { - return await this.cryptoService.getOrgKey(organizationId); + return await this.keyService.getOrgKey(organizationId); } private async getSecretRequest( diff --git a/bitwarden_license/bit-web/src/app/secrets-manager/service-accounts/access/access.service.ts b/bitwarden_license/bit-web/src/app/secrets-manager/service-accounts/access/access.service.ts index c0e13961c0..6b04e53feb 100644 --- a/bitwarden_license/bit-web/src/app/secrets-manager/service-accounts/access/access.service.ts +++ b/bitwarden_license/bit-web/src/app/secrets-manager/service-accounts/access/access.service.ts @@ -3,12 +3,12 @@ import { Subject } from "rxjs"; import { ApiService } from "@bitwarden/common/abstractions/api.service"; import { ListResponse } from "@bitwarden/common/models/response/list.response"; -import { CryptoService } from "@bitwarden/common/platform/abstractions/crypto.service"; import { EncryptService } from "@bitwarden/common/platform/abstractions/encrypt.service"; import { KeyGenerationService } from "@bitwarden/common/platform/abstractions/key-generation.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 { KeyService } from "@bitwarden/key-management"; import { AccessTokenRequest } from "../models/requests/access-token.request"; import { RevokeAccessTokensRequest } from "../models/requests/revoke-access-tokens.request"; @@ -26,7 +26,7 @@ export class AccessService { accessToken$ = this._accessToken.asObservable(); constructor( - private cryptoService: CryptoService, + private keyService: KeyService, private apiService: ApiService, private keyGenerationService: KeyGenerationService, private encryptService: EncryptService, @@ -116,7 +116,7 @@ export class AccessService { } private async getOrganizationKey(organizationId: string): Promise { - return await this.cryptoService.getOrgKey(organizationId); + return await this.keyService.getOrgKey(organizationId); } private async createAccessTokenViews( diff --git a/bitwarden_license/bit-web/src/app/secrets-manager/service-accounts/service-account.service.ts b/bitwarden_license/bit-web/src/app/secrets-manager/service-accounts/service-account.service.ts index 33f99040b9..dcca871948 100644 --- a/bitwarden_license/bit-web/src/app/secrets-manager/service-accounts/service-account.service.ts +++ b/bitwarden_license/bit-web/src/app/secrets-manager/service-accounts/service-account.service.ts @@ -3,10 +3,10 @@ import { Subject } from "rxjs"; import { ApiService } from "@bitwarden/common/abstractions/api.service"; import { ListResponse } from "@bitwarden/common/models/response/list.response"; -import { CryptoService } from "@bitwarden/common/platform/abstractions/crypto.service"; import { EncryptService } from "@bitwarden/common/platform/abstractions/encrypt.service"; import { EncString } from "@bitwarden/common/platform/models/domain/enc-string"; import { SymmetricCryptoKey } from "@bitwarden/common/platform/models/domain/symmetric-crypto-key"; +import { KeyService } from "@bitwarden/key-management"; import { ServiceAccountSecretsDetailsView, @@ -29,7 +29,7 @@ export class ServiceAccountService { serviceAccount$ = this._serviceAccount.asObservable(); constructor( - private cryptoService: CryptoService, + private keyService: KeyService, private apiService: ApiService, private encryptService: EncryptService, ) {} @@ -120,7 +120,7 @@ export class ServiceAccountService { } private async getOrganizationKey(organizationId: string): Promise { - return await this.cryptoService.getOrgKey(organizationId); + return await this.keyService.getOrgKey(organizationId); } private async getServiceAccountRequest( diff --git a/bitwarden_license/bit-web/src/app/secrets-manager/settings/services/sm-porting-api.service.spec.ts b/bitwarden_license/bit-web/src/app/secrets-manager/settings/services/sm-porting-api.service.spec.ts index 00e96c1f90..fb0ab467a0 100644 --- a/bitwarden_license/bit-web/src/app/secrets-manager/settings/services/sm-porting-api.service.spec.ts +++ b/bitwarden_license/bit-web/src/app/secrets-manager/settings/services/sm-porting-api.service.spec.ts @@ -1,13 +1,13 @@ import { mock } from "jest-mock-extended"; import { ApiService } from "@bitwarden/common/abstractions/api.service"; -import { CryptoService } from "@bitwarden/common/platform/abstractions/crypto.service"; import { EncryptService } from "@bitwarden/common/platform/abstractions/encrypt.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 { CsprngArray } from "@bitwarden/common/types/csprng"; import { OrgKey } from "@bitwarden/common/types/key"; +import { KeyService } from "@bitwarden/key-management"; import { SecretsManagerImportError } from "../models/error/sm-import-error"; import { SecretsManagerImportRequest } from "../models/requests/sm-import.request"; @@ -21,19 +21,19 @@ describe("SecretsManagerPortingApiService", () => { const apiService = mock(); const encryptService = mock(); - const cryptoService = mock(); + const keyService = mock(); beforeEach(() => { jest.resetAllMocks(); - sut = new SecretsManagerPortingApiService(apiService, encryptService, cryptoService); + sut = new SecretsManagerPortingApiService(apiService, encryptService, keyService); encryptService.encrypt.mockResolvedValue(mockEncryptedString); encryptService.decryptToUtf8.mockResolvedValue(mockUnencryptedString); const mockRandomBytes = new Uint8Array(64) as CsprngArray; const mockOrgKey = new SymmetricCryptoKey(mockRandomBytes) as OrgKey; - cryptoService.getOrgKey.mockResolvedValue(mockOrgKey); + keyService.getOrgKey.mockResolvedValue(mockOrgKey); }); it("instantiates", () => { diff --git a/bitwarden_license/bit-web/src/app/secrets-manager/settings/services/sm-porting-api.service.ts b/bitwarden_license/bit-web/src/app/secrets-manager/settings/services/sm-porting-api.service.ts index ea33bb86d1..4051be51a7 100644 --- a/bitwarden_license/bit-web/src/app/secrets-manager/settings/services/sm-porting-api.service.ts +++ b/bitwarden_license/bit-web/src/app/secrets-manager/settings/services/sm-porting-api.service.ts @@ -3,9 +3,9 @@ import { Subject } from "rxjs"; import { ApiService } from "@bitwarden/common/abstractions/api.service"; import { ErrorResponse } from "@bitwarden/common/models/response/error.response"; -import { CryptoService } from "@bitwarden/common/platform/abstractions/crypto.service"; import { EncryptService } from "@bitwarden/common/platform/abstractions/encrypt.service"; import { EncString } from "@bitwarden/common/platform/models/domain/enc-string"; +import { KeyService } from "@bitwarden/key-management"; import { SecretsManagerImportError } from "../models/error/sm-import-error"; import { SecretsManagerImportRequest } from "../models/requests/sm-import.request"; @@ -28,7 +28,7 @@ export class SecretsManagerPortingApiService { constructor( private apiService: ApiService, private encryptService: EncryptService, - private cryptoService: CryptoService, + private keyService: KeyService, ) {} async export(organizationId: string): Promise { @@ -76,7 +76,7 @@ export class SecretsManagerPortingApiService { const encryptedImport = new SecretsManagerImportRequest(); try { - const orgKey = await this.cryptoService.getOrgKey(organizationId); + const orgKey = await this.keyService.getOrgKey(organizationId); encryptedImport.projects = []; encryptedImport.secrets = []; @@ -116,7 +116,7 @@ export class SecretsManagerPortingApiService { organizationId: string, exportData: SecretsManagerExportResponse, ): Promise { - const orgKey = await this.cryptoService.getOrgKey(organizationId); + const orgKey = await this.keyService.getOrgKey(organizationId); const decryptedExport = new SecretsManagerExport(); decryptedExport.projects = []; decryptedExport.secrets = []; diff --git a/bitwarden_license/bit-web/src/app/secrets-manager/shared/access-policies/access-policy.service.spec.ts b/bitwarden_license/bit-web/src/app/secrets-manager/shared/access-policies/access-policy.service.spec.ts index 9ac505da18..c5de1e0278 100644 --- a/bitwarden_license/bit-web/src/app/secrets-manager/shared/access-policies/access-policy.service.spec.ts +++ b/bitwarden_license/bit-web/src/app/secrets-manager/shared/access-policies/access-policy.service.spec.ts @@ -1,12 +1,12 @@ import { mock } from "jest-mock-extended"; import { ApiService } from "@bitwarden/common/abstractions/api.service"; -import { CryptoService } from "@bitwarden/common/platform/abstractions/crypto.service"; import { EncryptService } from "@bitwarden/common/platform/abstractions/encrypt.service"; import { Utils } from "@bitwarden/common/platform/misc/utils"; import { SymmetricCryptoKey } from "@bitwarden/common/platform/models/domain/symmetric-crypto-key"; import { CsprngArray } from "@bitwarden/common/types/csprng"; import { OrgKey } from "@bitwarden/common/types/key"; +import { KeyService } from "@bitwarden/key-management"; import { GroupAccessPolicyView, @@ -31,14 +31,14 @@ import { trackEmissions } from "@bitwarden/common/../spec"; describe("AccessPolicyService", () => { let sut: AccessPolicyService; - const cryptoService = mock(); + const keyService = mock(); const apiService = mock(); const encryptService = mock(); beforeEach(() => { jest.resetAllMocks(); - sut = new AccessPolicyService(cryptoService, apiService, encryptService); + sut = new AccessPolicyService(keyService, apiService, encryptService); }); it("instantiates", () => { @@ -135,7 +135,7 @@ describe("AccessPolicyService", () => { const expectedRequest = toServiceAccountGrantedPoliciesRequest(view); const mockRandomBytes = new Uint8Array(64) as CsprngArray; const mockOrgKey = new SymmetricCryptoKey(mockRandomBytes) as OrgKey; - cryptoService.getOrgKey.mockResolvedValue(mockOrgKey); + keyService.getOrgKey.mockResolvedValue(mockOrgKey); encryptService.decryptToUtf8.mockImplementation((c) => Promise.resolve(c.encryptedString)); const organizationId = Utils.newGuid(); const serviceAccountId = Utils.newGuid(); @@ -172,7 +172,7 @@ describe("AccessPolicyService", () => { const expectedRequest = toProjectServiceAccountsAccessPoliciesRequest(view); const mockRandomBytes = new Uint8Array(64) as CsprngArray; const mockOrgKey = new SymmetricCryptoKey(mockRandomBytes) as OrgKey; - cryptoService.getOrgKey.mockResolvedValue(mockOrgKey); + keyService.getOrgKey.mockResolvedValue(mockOrgKey); encryptService.decryptToUtf8.mockImplementation((c) => Promise.resolve(c.encryptedString)); const organizationId = Utils.newGuid(); const projectId = Utils.newGuid(); diff --git a/bitwarden_license/bit-web/src/app/secrets-manager/shared/access-policies/access-policy.service.ts b/bitwarden_license/bit-web/src/app/secrets-manager/shared/access-policies/access-policy.service.ts index 9828fad93f..9d0752b987 100644 --- a/bitwarden_license/bit-web/src/app/secrets-manager/shared/access-policies/access-policy.service.ts +++ b/bitwarden_license/bit-web/src/app/secrets-manager/shared/access-policies/access-policy.service.ts @@ -3,10 +3,10 @@ import { Subject } from "rxjs"; import { ApiService } from "@bitwarden/common/abstractions/api.service"; import { ListResponse } from "@bitwarden/common/models/response/list.response"; -import { CryptoService } from "@bitwarden/common/platform/abstractions/crypto.service"; import { EncryptService } from "@bitwarden/common/platform/abstractions/encrypt.service"; import { EncString } from "@bitwarden/common/platform/models/domain/enc-string"; import { SymmetricCryptoKey } from "@bitwarden/common/platform/models/domain/symmetric-crypto-key"; +import { KeyService } from "@bitwarden/key-management"; import { UserAccessPolicyView, @@ -57,7 +57,7 @@ export class AccessPolicyService { accessPolicy$ = this._accessPolicy.asObservable(); constructor( - private cryptoService: CryptoService, + private keyService: KeyService, protected apiService: ApiService, protected encryptService: EncryptService, ) {} @@ -267,7 +267,7 @@ export class AccessPolicyService { } private async getOrganizationKey(organizationId: string): Promise { - return await this.cryptoService.getOrgKey(organizationId); + return await this.keyService.getOrgKey(organizationId); } private getAccessPolicyRequest( diff --git a/libs/admin-console/src/common/collections/services/default-collection-admin.service.ts b/libs/admin-console/src/common/collections/services/default-collection-admin.service.ts index 3d4fab7a9b..0851853498 100644 --- a/libs/admin-console/src/common/collections/services/default-collection-admin.service.ts +++ b/libs/admin-console/src/common/collections/services/default-collection-admin.service.ts @@ -1,8 +1,8 @@ import { ApiService } from "@bitwarden/common/abstractions/api.service"; import { SelectionReadOnlyRequest } from "@bitwarden/common/admin-console/models/request/selection-read-only.request"; -import { CryptoService } from "@bitwarden/common/platform/abstractions/crypto.service"; import { EncryptService } from "@bitwarden/common/platform/abstractions/encrypt.service"; import { EncString } from "@bitwarden/common/platform/models/domain/enc-string"; +import { KeyService } from "@bitwarden/key-management"; import { CollectionAdminService, CollectionService } from "../abstractions"; import { @@ -19,7 +19,7 @@ import { export class DefaultCollectionAdminService implements CollectionAdminService { constructor( private apiService: ApiService, - private cryptoService: CryptoService, + private keyService: KeyService, private encryptService: EncryptService, private collectionService: CollectionService, ) {} @@ -109,7 +109,7 @@ export class DefaultCollectionAdminService implements CollectionAdminService { organizationId: string, collections: CollectionResponse[] | CollectionAccessDetailsResponse[], ): Promise { - const orgKey = await this.cryptoService.getOrgKey(organizationId); + const orgKey = await this.keyService.getOrgKey(organizationId); const promises = collections.map(async (c) => { const view = new CollectionAdminView(); @@ -138,7 +138,7 @@ export class DefaultCollectionAdminService implements CollectionAdminService { if (model.organizationId == null) { throw new Error("Collection has no organization id."); } - const key = await this.cryptoService.getOrgKey(model.organizationId); + const key = await this.keyService.getOrgKey(model.organizationId); if (key == null) { throw new Error("No key for this collection's organization."); } diff --git a/libs/admin-console/src/common/collections/services/default-collection.service.spec.ts b/libs/admin-console/src/common/collections/services/default-collection.service.spec.ts index 502d554d5f..a230a20b2e 100644 --- a/libs/admin-console/src/common/collections/services/default-collection.service.spec.ts +++ b/libs/admin-console/src/common/collections/services/default-collection.service.spec.ts @@ -1,7 +1,6 @@ import { mock } from "jest-mock-extended"; import { firstValueFrom, of } from "rxjs"; -import { CryptoService } from "@bitwarden/common/platform/abstractions/crypto.service"; import { EncryptService } from "@bitwarden/common/platform/abstractions/encrypt.service"; import { I18nService } from "@bitwarden/common/platform/abstractions/i18n.service"; import { Utils } from "@bitwarden/common/platform/misc/utils"; @@ -15,6 +14,7 @@ import { } from "@bitwarden/common/spec"; import { CollectionId, OrganizationId, UserId } from "@bitwarden/common/types/guid"; import { OrgKey } from "@bitwarden/common/types/key"; +import { KeyService } from "@bitwarden/key-management"; import { CollectionData } from "../models"; @@ -118,15 +118,15 @@ const mockStateProvider = () => { }; const mockCryptoService = () => { - const cryptoService = mock(); + const keyService = mock(); const encryptService = mock(); encryptService.decryptToUtf8 .calledWith(expect.any(EncString), expect.anything()) .mockResolvedValue("DECRYPTED_STRING"); - (window as any).bitwardenContainerService = new ContainerService(cryptoService, encryptService); + (window as any).bitwardenContainerService = new ContainerService(keyService, encryptService); - return cryptoService; + return keyService; }; const collectionDataFactory = (orgId: OrganizationId) => { diff --git a/libs/admin-console/src/common/collections/services/default-collection.service.ts b/libs/admin-console/src/common/collections/services/default-collection.service.ts index 507e21bdb4..c83bb6fb16 100644 --- a/libs/admin-console/src/common/collections/services/default-collection.service.ts +++ b/libs/admin-console/src/common/collections/services/default-collection.service.ts @@ -1,7 +1,6 @@ import { combineLatest, firstValueFrom, map, Observable, of, switchMap } from "rxjs"; import { Jsonify } from "type-fest"; -import { CryptoService } from "@bitwarden/common/platform/abstractions/crypto.service"; import { EncryptService } from "@bitwarden/common/platform/abstractions/encrypt.service"; import { I18nService } from "@bitwarden/common/platform/abstractions/i18n.service"; import { Utils } from "@bitwarden/common/platform/misc/utils"; @@ -17,6 +16,7 @@ import { CollectionId, OrganizationId, UserId } from "@bitwarden/common/types/gu import { OrgKey } from "@bitwarden/common/types/key"; import { TreeNode } from "@bitwarden/common/vault/models/domain/tree-node"; import { ServiceUtils } from "@bitwarden/common/vault/service-utils"; +import { KeyService } from "@bitwarden/key-management"; import { CollectionService } from "../abstractions"; import { Collection, CollectionData, CollectionView } from "../models"; @@ -61,7 +61,7 @@ export class DefaultCollectionService implements CollectionService { } constructor( - private cryptoService: CryptoService, + private keyService: KeyService, private encryptService: EncryptService, private i18nService: I18nService, protected stateProvider: StateProvider, @@ -80,7 +80,7 @@ export class DefaultCollectionService implements CollectionService { const encryptedCollectionsWithKeys = this.encryptedCollectionDataState.combinedState$.pipe( switchMap(([userId, collectionData]) => - combineLatest([of(collectionData), this.cryptoService.orgKeys$(userId)]), + combineLatest([of(collectionData), this.keyService.orgKeys$(userId)]), ), ); @@ -101,7 +101,7 @@ export class DefaultCollectionService implements CollectionService { if (model.organizationId == null) { throw new Error("Collection has no organization id."); } - const key = await this.cryptoService.getOrgKey(model.organizationId); + const key = await this.keyService.getOrgKey(model.organizationId); if (key == null) { throw new Error("No key for this collection's organization."); } @@ -125,7 +125,7 @@ export class DefaultCollectionService implements CollectionService { } const decCollections: CollectionView[] = []; - orgKeys ??= await firstValueFrom(this.cryptoService.activeUserOrgKeys$); + orgKeys ??= await firstValueFrom(this.keyService.activeUserOrgKeys$); const promises: Promise[] = []; collections.forEach((collection) => { diff --git a/libs/angular/src/auth/components/base-login-decryption-options.component.ts b/libs/angular/src/auth/components/base-login-decryption-options.component.ts index c237c98c0b..f674a32af8 100644 --- a/libs/angular/src/auth/components/base-login-decryption-options.component.ts +++ b/libs/angular/src/auth/components/base-login-decryption-options.component.ts @@ -32,7 +32,6 @@ import { PasswordResetEnrollmentServiceAbstraction } from "@bitwarden/common/aut import { SsoLoginServiceAbstraction } from "@bitwarden/common/auth/abstractions/sso-login.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"; @@ -40,6 +39,7 @@ import { StateService } from "@bitwarden/common/platform/abstractions/state.serv import { ValidationService } from "@bitwarden/common/platform/abstractions/validation.service"; import { UserId } from "@bitwarden/common/types/guid"; import { ToastService } from "@bitwarden/components"; +import { KeyService } from "@bitwarden/key-management"; enum State { NewUser, @@ -94,7 +94,7 @@ export class BaseLoginDecryptionOptionsComponent implements OnInit, OnDestroy { protected tokenService: TokenService, protected loginEmailService: LoginEmailServiceAbstraction, protected organizationApiService: OrganizationApiServiceAbstraction, - protected cryptoService: CryptoService, + protected keyService: KeyService, protected organizationUserApiService: OrganizationUserApiService, protected apiService: ApiService, protected i18nService: I18nService, @@ -273,7 +273,7 @@ export class BaseLoginDecryptionOptionsComponent implements OnInit, OnDestroy { this.loading = true; // errors must be caught in child components to prevent navigation try { - const { publicKey, privateKey } = await this.cryptoService.initAccount(); + const { publicKey, privateKey } = await this.keyService.initAccount(); const keysRequest = new KeysRequest(publicKey, privateKey.encryptedString); await this.apiService.postAccountKeys(keysRequest); diff --git a/libs/angular/src/auth/components/change-password.component.ts b/libs/angular/src/auth/components/change-password.component.ts index 45ddf9095f..92b34c08f4 100644 --- a/libs/angular/src/auth/components/change-password.component.ts +++ b/libs/angular/src/auth/components/change-password.component.ts @@ -7,7 +7,6 @@ import { AccountService } from "@bitwarden/common/auth/abstractions/account.serv import { KdfConfigService } from "@bitwarden/common/auth/abstractions/kdf-config.service"; import { InternalMasterPasswordServiceAbstraction } from "@bitwarden/common/auth/abstractions/master-password.service.abstraction"; import { KdfConfig } from "@bitwarden/common/auth/models/domain/kdf-config"; -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"; @@ -17,6 +16,7 @@ import { EncString } from "@bitwarden/common/platform/models/domain/enc-string"; import { UserKey, MasterKey } from "@bitwarden/common/types/key"; import { DialogService, ToastService } from "@bitwarden/components"; import { PasswordGenerationServiceAbstraction } from "@bitwarden/generator-legacy"; +import { KeyService } from "@bitwarden/key-management"; import { PasswordColorText } from "../../tools/password-strength/password-strength.component"; @@ -39,7 +39,7 @@ export class ChangePasswordComponent implements OnInit, OnDestroy { constructor( protected i18nService: I18nService, - protected cryptoService: CryptoService, + protected keyService: KeyService, protected messagingService: MessagingService, protected passwordGenerationService: PasswordGenerationServiceAbstraction, protected platformUtilsService: PlatformUtilsService, @@ -91,22 +91,19 @@ export class ChangePasswordComponent implements OnInit, OnDestroy { } // Create new master key - const newMasterKey = await this.cryptoService.makeMasterKey( + const newMasterKey = await this.keyService.makeMasterKey( this.masterPassword, email.trim().toLowerCase(), this.kdfConfig, ); - const newMasterKeyHash = await this.cryptoService.hashMasterKey( - this.masterPassword, - newMasterKey, - ); + const newMasterKeyHash = await this.keyService.hashMasterKey(this.masterPassword, newMasterKey); let newProtectedUserKey: [UserKey, EncString] = null; - const userKey = await this.cryptoService.getUserKey(); + const userKey = await this.keyService.getUserKey(); if (userKey == null) { - newProtectedUserKey = await this.cryptoService.makeUserKey(newMasterKey); + newProtectedUserKey = await this.keyService.makeUserKey(newMasterKey); } else { - newProtectedUserKey = await this.cryptoService.encryptUserKeyWithMasterKey(newMasterKey); + newProtectedUserKey = await this.keyService.encryptUserKeyWithMasterKey(newMasterKey); } await this.performSubmitActions(newMasterKeyHash, newMasterKey, newProtectedUserKey); diff --git a/libs/angular/src/auth/components/lock.component.ts b/libs/angular/src/auth/components/lock.component.ts index 5fc8f51d57..bc9c667bc8 100644 --- a/libs/angular/src/auth/components/lock.component.ts +++ b/libs/angular/src/auth/components/lock.component.ts @@ -22,7 +22,6 @@ import { MasterPasswordVerification, MasterPasswordVerificationResponse, } from "@bitwarden/common/auth/types/verification"; -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"; import { LogService } from "@bitwarden/common/platform/abstractions/log.service"; @@ -35,7 +34,7 @@ import { UserId } from "@bitwarden/common/types/guid"; import { UserKey } from "@bitwarden/common/types/key"; import { SyncService } from "@bitwarden/common/vault/abstractions/sync/sync.service.abstraction"; import { DialogService, ToastService } from "@bitwarden/components"; -import { BiometricStateService, BiometricsService } from "@bitwarden/key-management"; +import { KeyService, BiometricStateService, BiometricsService } from "@bitwarden/key-management"; @Directive() export class LockComponent implements OnInit, OnDestroy { @@ -68,7 +67,7 @@ export class LockComponent implements OnInit, OnDestroy { protected i18nService: I18nService, protected platformUtilsService: PlatformUtilsService, protected messagingService: MessagingService, - protected cryptoService: CryptoService, + protected keyService: KeyService, protected vaultTimeoutService: VaultTimeoutService, protected vaultTimeoutSettingsService: VaultTimeoutSettingsService, protected environmentService: EnvironmentService, @@ -136,7 +135,7 @@ export class LockComponent implements OnInit, OnDestroy { } await this.biometricStateService.setUserPromptCancelled(); - const userKey = await this.cryptoService.getUserKeyFromStorage( + const userKey = await this.keyService.getUserKeyFromStorage( KeySuffixOptions.Biometric, this.activeUserId, ); @@ -277,7 +276,7 @@ export class LockComponent implements OnInit, OnDestroy { userId: UserId, evaluatePasswordAfterUnlock = false, ) { - await this.cryptoService.setUserKey(key, userId); + await this.keyService.setUserKey(key, userId); // Now that we have a decrypted user key in memory, we can check if we // need to establish trust on the current device @@ -339,7 +338,7 @@ export class LockComponent implements OnInit, OnDestroy { this.supportsBiometric = await this.biometricsService.supportsBiometric(); this.biometricLock = (await this.vaultTimeoutSettingsService.isBiometricLockSet()) && - ((await this.cryptoService.hasUserKeyStored(KeySuffixOptions.Biometric)) || + ((await this.keyService.hasUserKeyStored(KeySuffixOptions.Biometric)) || !this.platformUtilsService.supportsSecureStorage()); this.email = await firstValueFrom( this.accountService.activeAccount$.pipe(map((a) => a?.email)), diff --git a/libs/angular/src/auth/components/login-via-auth-request.component.ts b/libs/angular/src/auth/components/login-via-auth-request.component.ts index ed9ed6ef70..b960cafe9c 100644 --- a/libs/angular/src/auth/components/login-via-auth-request.component.ts +++ b/libs/angular/src/auth/components/login-via-auth-request.component.ts @@ -24,7 +24,6 @@ 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"; -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"; import { LogService } from "@bitwarden/common/platform/abstractions/log.service"; @@ -34,6 +33,7 @@ import { Utils } from "@bitwarden/common/platform/misc/utils"; import { UserId } from "@bitwarden/common/types/guid"; import { ToastService } from "@bitwarden/components"; import { PasswordGenerationServiceAbstraction } from "@bitwarden/generator-legacy"; +import { KeyService } from "@bitwarden/key-management"; import { CaptchaProtectedComponent } from "./captcha-protected.component"; @@ -72,7 +72,7 @@ export class LoginViaAuthRequestComponent constructor( protected router: Router, - private cryptoService: CryptoService, + private keyService: KeyService, private cryptoFunctionService: CryptoFunctionService, private appIdService: AppIdService, private passwordGenerationService: PasswordGenerationServiceAbstraction, diff --git a/libs/angular/src/auth/components/register.component.ts b/libs/angular/src/auth/components/register.component.ts index 60adcba4d9..94f60ff637 100644 --- a/libs/angular/src/auth/components/register.component.ts +++ b/libs/angular/src/auth/components/register.component.ts @@ -10,7 +10,6 @@ import { RegisterResponse } from "@bitwarden/common/auth/models/response/registe import { KeysRequest } from "@bitwarden/common/models/request/keys.request"; import { ReferenceEventRequest } from "@bitwarden/common/models/request/reference-event.request"; import { RegisterRequest } from "@bitwarden/common/models/request/register.request"; -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"; import { LogService } from "@bitwarden/common/platform/abstractions/log.service"; @@ -19,6 +18,7 @@ import { StateService } from "@bitwarden/common/platform/abstractions/state.serv import { Utils } from "@bitwarden/common/platform/misc/utils"; import { DialogService, ToastService } from "@bitwarden/components"; import { PasswordGenerationServiceAbstraction } from "@bitwarden/generator-legacy"; +import { KeyService } from "@bitwarden/key-management"; import { AllValidationErrors, @@ -88,7 +88,7 @@ export class RegisterComponent extends CaptchaProtectedComponent implements OnIn protected loginStrategyService: LoginStrategyServiceAbstraction, protected router: Router, i18nService: I18nService, - protected cryptoService: CryptoService, + protected keyService: KeyService, protected apiService: ApiService, protected stateService: StateService, platformUtilsService: PlatformUtilsService, @@ -283,10 +283,10 @@ export class RegisterComponent extends CaptchaProtectedComponent implements OnIn ): Promise { const hint = this.formGroup.value.hint; const kdfConfig = DEFAULT_KDF_CONFIG; - const key = await this.cryptoService.makeMasterKey(masterPassword, email, 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 key = await this.keyService.makeMasterKey(masterPassword, email, kdfConfig); + const newUserKey = await this.keyService.makeUserKey(key); + const masterKeyHash = await this.keyService.hashMasterKey(masterPassword, key); + const keys = await this.keyService.makeKeyPair(newUserKey[0]); const request = new RegisterRequest( email, name, diff --git a/libs/angular/src/auth/components/set-password.component.ts b/libs/angular/src/auth/components/set-password.component.ts index d1a21e4abb..81981de79d 100644 --- a/libs/angular/src/auth/components/set-password.component.ts +++ b/libs/angular/src/auth/components/set-password.component.ts @@ -22,7 +22,6 @@ import { ForceSetPasswordReason } from "@bitwarden/common/auth/models/domain/for import { DEFAULT_KDF_CONFIG } from "@bitwarden/common/auth/models/domain/kdf-config"; import { SetPasswordRequest } from "@bitwarden/common/auth/models/request/set-password.request"; import { KeysRequest } from "@bitwarden/common/models/request/keys.request"; -import { CryptoService } from "@bitwarden/common/platform/abstractions/crypto.service"; import { EncryptService } from "@bitwarden/common/platform/abstractions/encrypt.service"; import { I18nService } from "@bitwarden/common/platform/abstractions/i18n.service"; import { MessagingService } from "@bitwarden/common/platform/abstractions/messaging.service"; @@ -36,6 +35,7 @@ import { MasterKey, UserKey } from "@bitwarden/common/types/key"; import { SyncService } from "@bitwarden/common/vault/abstractions/sync/sync.service.abstraction"; import { DialogService, ToastService } from "@bitwarden/components"; import { PasswordGenerationServiceAbstraction } from "@bitwarden/generator-legacy"; +import { KeyService } from "@bitwarden/key-management"; import { ChangePasswordComponent as BaseChangePasswordComponent } from "./change-password.component"; @@ -58,7 +58,7 @@ export class SetPasswordComponent extends BaseChangePasswordComponent implements accountService: AccountService, masterPasswordService: InternalMasterPasswordServiceAbstraction, i18nService: I18nService, - cryptoService: CryptoService, + keyService: KeyService, messagingService: MessagingService, passwordGenerationService: PasswordGenerationServiceAbstraction, platformUtilsService: PlatformUtilsService, @@ -80,7 +80,7 @@ export class SetPasswordComponent extends BaseChangePasswordComponent implements ) { super( i18nService, - cryptoService, + keyService, messagingService, passwordGenerationService, platformUtilsService, @@ -173,10 +173,10 @@ export class SetPasswordComponent extends BaseChangePasswordComponent implements // in case we have a local private key, and are not sure whether it has been posted to the server, we post the local private key instead of generating a new one const existingUserPrivateKey = (await firstValueFrom( - this.cryptoService.userPrivateKey$(this.userId), + this.keyService.userPrivateKey$(this.userId), )) as Uint8Array; const existingUserPublicKey = await firstValueFrom( - this.cryptoService.userPublicKey$(this.userId), + this.keyService.userPublicKey$(this.userId), ); if (existingUserPrivateKey != null && existingUserPublicKey != null) { const existingUserPublicKeyB64 = Utils.fromBufferToB64(existingUserPublicKey); @@ -185,7 +185,7 @@ export class SetPasswordComponent extends BaseChangePasswordComponent implements await this.encryptService.encrypt(existingUserPrivateKey, userKey[0]), ]; } else { - newKeyPair = await this.cryptoService.makeKeyPair(userKey[0]); + newKeyPair = await this.keyService.makeKeyPair(userKey[0]); } keysRequest = new KeysRequest(newKeyPair[0], newKeyPair[1].encryptedString); } @@ -214,7 +214,7 @@ export class SetPasswordComponent extends BaseChangePasswordComponent implements const publicKey = Utils.fromB64ToArray(response.publicKey); // RSA Encrypt user key with organization public key - const userKey = await this.cryptoService.getUserKey(); + const userKey = await this.keyService.getUserKey(); const encryptedUserKey = await this.encryptService.rsaEncrypt(userKey.key, publicKey); const resetRequest = new OrganizationUserResetPasswordEnrollmentRequest(); @@ -277,7 +277,7 @@ export class SetPasswordComponent extends BaseChangePasswordComponent implements await this.userDecryptionOptionsService.setUserDecryptionOptions(userDecryptionOpts); await this.kdfConfigService.setKdfConfig(this.userId, this.kdfConfig); await this.masterPasswordService.setMasterKey(masterKey, this.userId); - await this.cryptoService.setUserKey(userKey[0], this.userId); + await this.keyService.setUserKey(userKey[0], this.userId); // Set private key only for new JIT provisioned users in MP encryption orgs // Existing TDE users will have private key set on sync or on login @@ -286,10 +286,10 @@ export class SetPasswordComponent extends BaseChangePasswordComponent implements this.forceSetPasswordReason != ForceSetPasswordReason.TdeUserWithoutPasswordHasPasswordResetPermission ) { - await this.cryptoService.setPrivateKey(keyPair[1].encryptedString, this.userId); + await this.keyService.setPrivateKey(keyPair[1].encryptedString, this.userId); } - const localMasterKeyHash = await this.cryptoService.hashMasterKey( + const localMasterKeyHash = await this.keyService.hashMasterKey( this.masterPassword, masterKey, HashPurpose.LocalAuthorization, diff --git a/libs/angular/src/auth/components/set-pin.component.ts b/libs/angular/src/auth/components/set-pin.component.ts index 97cc8ef4b0..1e3c1e6d56 100644 --- a/libs/angular/src/auth/components/set-pin.component.ts +++ b/libs/angular/src/auth/components/set-pin.component.ts @@ -6,8 +6,8 @@ import { firstValueFrom } from "rxjs"; import { PinServiceAbstraction } from "@bitwarden/auth/common"; import { AccountService } from "@bitwarden/common/auth/abstractions/account.service"; import { UserVerificationService } from "@bitwarden/common/auth/abstractions/user-verification/user-verification.service.abstraction"; -import { CryptoService } from "@bitwarden/common/platform/abstractions/crypto.service"; import { Utils } from "@bitwarden/common/platform/misc/utils"; +import { KeyService } from "@bitwarden/key-management"; @Directive() export class SetPinComponent implements OnInit { @@ -20,7 +20,7 @@ export class SetPinComponent implements OnInit { constructor( private accountService: AccountService, - private cryptoService: CryptoService, + private keyService: KeyService, private dialogRef: DialogRef, private formBuilder: FormBuilder, private pinService: PinServiceAbstraction, @@ -46,7 +46,7 @@ export class SetPinComponent implements OnInit { } const userId = (await firstValueFrom(this.accountService.activeAccount$))?.id; - const userKey = await this.cryptoService.getUserKey(); + const userKey = await this.keyService.getUserKey(); const userKeyEncryptedPin = await this.pinService.createUserKeyEncryptedPin(pin, userKey); await this.pinService.setUserKeyEncryptedPin(userKeyEncryptedPin, userId); diff --git a/libs/angular/src/auth/components/update-password.component.ts b/libs/angular/src/auth/components/update-password.component.ts index 98dd4aeb49..bc31be283e 100644 --- a/libs/angular/src/auth/components/update-password.component.ts +++ b/libs/angular/src/auth/components/update-password.component.ts @@ -11,7 +11,6 @@ import { UserVerificationService } from "@bitwarden/common/auth/abstractions/use import { VerificationType } from "@bitwarden/common/auth/enums/verification-type"; import { PasswordRequest } from "@bitwarden/common/auth/models/request/password.request"; import { Verification } from "@bitwarden/common/auth/types/verification"; -import { CryptoService } from "@bitwarden/common/platform/abstractions/crypto.service"; import { I18nService } from "@bitwarden/common/platform/abstractions/i18n.service"; import { LogService } from "@bitwarden/common/platform/abstractions/log.service"; import { MessagingService } from "@bitwarden/common/platform/abstractions/messaging.service"; @@ -21,6 +20,7 @@ import { EncString } from "@bitwarden/common/platform/models/domain/enc-string"; import { MasterKey, UserKey } from "@bitwarden/common/types/key"; import { DialogService, ToastService } from "@bitwarden/components"; import { PasswordGenerationServiceAbstraction } from "@bitwarden/generator-legacy"; +import { KeyService } from "@bitwarden/key-management"; import { ChangePasswordComponent as BaseChangePasswordComponent } from "./change-password.component"; @@ -40,7 +40,7 @@ export class UpdatePasswordComponent extends BaseChangePasswordComponent { platformUtilsService: PlatformUtilsService, passwordGenerationService: PasswordGenerationServiceAbstraction, policyService: PolicyService, - cryptoService: CryptoService, + keyService: KeyService, messagingService: MessagingService, private apiService: ApiService, stateService: StateService, @@ -54,7 +54,7 @@ export class UpdatePasswordComponent extends BaseChangePasswordComponent { ) { super( i18nService, - cryptoService, + keyService, messagingService, passwordGenerationService, platformUtilsService, @@ -114,9 +114,9 @@ export class UpdatePasswordComponent extends BaseChangePasswordComponent { try { // Create Request const request = new PasswordRequest(); - request.masterPasswordHash = await this.cryptoService.hashMasterKey( + request.masterPasswordHash = await this.keyService.hashMasterKey( this.currentMasterPassword, - await this.cryptoService.getOrDeriveMasterKey(this.currentMasterPassword), + await this.keyService.getOrDeriveMasterKey(this.currentMasterPassword), ); request.newMasterPasswordHash = newMasterKeyHash; request.key = newUserKey[1].encryptedString; diff --git a/libs/angular/src/auth/components/update-temp-password.component.ts b/libs/angular/src/auth/components/update-temp-password.component.ts index b08c6313d6..2019d6f73c 100644 --- a/libs/angular/src/auth/components/update-temp-password.component.ts +++ b/libs/angular/src/auth/components/update-temp-password.component.ts @@ -15,7 +15,6 @@ import { PasswordRequest } from "@bitwarden/common/auth/models/request/password. import { UpdateTdeOffboardingPasswordRequest } from "@bitwarden/common/auth/models/request/update-tde-offboarding-password.request"; import { UpdateTempPasswordRequest } from "@bitwarden/common/auth/models/request/update-temp-password.request"; import { MasterPasswordVerification } from "@bitwarden/common/auth/types/verification"; -import { CryptoService } from "@bitwarden/common/platform/abstractions/crypto.service"; import { I18nService } from "@bitwarden/common/platform/abstractions/i18n.service"; import { LogService } from "@bitwarden/common/platform/abstractions/log.service"; import { MessagingService } from "@bitwarden/common/platform/abstractions/messaging.service"; @@ -26,6 +25,7 @@ import { MasterKey, UserKey } from "@bitwarden/common/types/key"; import { SyncService } from "@bitwarden/common/vault/abstractions/sync/sync.service.abstraction"; import { DialogService, ToastService } from "@bitwarden/components"; import { PasswordGenerationServiceAbstraction } from "@bitwarden/generator-legacy"; +import { KeyService } from "@bitwarden/key-management"; import { ChangePasswordComponent as BaseChangePasswordComponent } from "./change-password.component"; @@ -52,7 +52,7 @@ export class UpdateTempPasswordComponent extends BaseChangePasswordComponent imp platformUtilsService: PlatformUtilsService, passwordGenerationService: PasswordGenerationServiceAbstraction, policyService: PolicyService, - cryptoService: CryptoService, + keyService: KeyService, messagingService: MessagingService, private apiService: ApiService, stateService: StateService, @@ -68,7 +68,7 @@ export class UpdateTempPasswordComponent extends BaseChangePasswordComponent imp ) { super( i18nService, - cryptoService, + keyService, messagingService, passwordGenerationService, platformUtilsService, @@ -134,21 +134,21 @@ export class UpdateTempPasswordComponent extends BaseChangePasswordComponent imp try { // Create new key and hash new password - const newMasterKey = await this.cryptoService.makeMasterKey( + const newMasterKey = await this.keyService.makeMasterKey( this.masterPassword, this.email.trim().toLowerCase(), this.kdfConfig, ); - const newPasswordHash = await this.cryptoService.hashMasterKey( + const newPasswordHash = await this.keyService.hashMasterKey( this.masterPassword, newMasterKey, ); // Grab user key - const userKey = await this.cryptoService.getUserKey(); + const userKey = await this.keyService.getUserKey(); // Encrypt user key with new master key - const newProtectedUserKey = await this.cryptoService.encryptUserKeyWithMasterKey( + const newProtectedUserKey = await this.keyService.encryptUserKeyWithMasterKey( newMasterKey, userKey, ); diff --git a/libs/angular/src/auth/components/user-verification.component.ts b/libs/angular/src/auth/components/user-verification.component.ts index 7fe866a9f6..385c9b9acf 100644 --- a/libs/angular/src/auth/components/user-verification.component.ts +++ b/libs/angular/src/auth/components/user-verification.component.ts @@ -5,9 +5,9 @@ import { Subject, takeUntil } from "rxjs"; import { UserVerificationService } from "@bitwarden/common/auth/abstractions/user-verification/user-verification.service.abstraction"; import { VerificationType } from "@bitwarden/common/auth/enums/verification-type"; import { Verification } from "@bitwarden/common/auth/types/verification"; -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 { KeyService } from "@bitwarden/key-management"; /** * Used for general-purpose user verification throughout the app. @@ -66,7 +66,7 @@ export class UserVerificationComponent implements ControlValueAccessor, OnInit, private destroy$ = new Subject(); constructor( - private cryptoService: CryptoService, + private keyService: KeyService, private userVerificationService: UserVerificationService, private i18nService: I18nService, ) {} diff --git a/libs/angular/src/auth/guards/lock.guard.spec.ts b/libs/angular/src/auth/guards/lock.guard.spec.ts index 7ff7feb920..0d41be87a4 100644 --- a/libs/angular/src/auth/guards/lock.guard.spec.ts +++ b/libs/angular/src/auth/guards/lock.guard.spec.ts @@ -12,10 +12,10 @@ import { DeviceTrustServiceAbstraction } from "@bitwarden/common/auth/abstractio import { UserVerificationService } from "@bitwarden/common/auth/abstractions/user-verification/user-verification.service.abstraction"; import { AuthenticationStatus } from "@bitwarden/common/auth/enums/authentication-status"; import { ClientType } from "@bitwarden/common/enums"; -import { CryptoService } from "@bitwarden/common/platform/abstractions/crypto.service"; import { MessagingService } from "@bitwarden/common/platform/abstractions/messaging.service"; import { PlatformUtilsService } from "@bitwarden/common/platform/abstractions/platform-utils.service"; import { UserId } from "@bitwarden/common/types/guid"; +import { KeyService } from "@bitwarden/key-management"; import { lockGuard } from "./lock.guard"; @@ -38,9 +38,9 @@ describe("lockGuard", () => { mock(); vaultTimeoutSettingsService.canLock.mockResolvedValue(setupParams.canLock); - const cryptoService: MockProxy = mock(); - cryptoService.isLegacyUser.mockResolvedValue(setupParams.isLegacyUser); - cryptoService.everHadUserKey$ = of(setupParams.everHadUserKey); + const keyService: MockProxy = mock(); + keyService.isLegacyUser.mockResolvedValue(setupParams.isLegacyUser); + keyService.everHadUserKey$ = of(setupParams.everHadUserKey); const platformUtilService: MockProxy = mock(); platformUtilService.getClientType.mockReturnValue(setupParams.clientType); @@ -83,7 +83,7 @@ describe("lockGuard", () => { { provide: MessagingService, useValue: messagingService }, { provide: AccountService, useValue: accountService }, { provide: VaultTimeoutSettingsService, useValue: vaultTimeoutSettingsService }, - { provide: CryptoService, useValue: cryptoService }, + { provide: KeyService, useValue: keyService }, { provide: PlatformUtilsService, useValue: platformUtilService }, { provide: DeviceTrustServiceAbstraction, useValue: deviceTrustService }, { provide: UserVerificationService, useValue: userVerificationService }, diff --git a/libs/angular/src/auth/guards/lock.guard.ts b/libs/angular/src/auth/guards/lock.guard.ts index 440e6931a0..8665c09b1e 100644 --- a/libs/angular/src/auth/guards/lock.guard.ts +++ b/libs/angular/src/auth/guards/lock.guard.ts @@ -14,9 +14,9 @@ import { DeviceTrustServiceAbstraction } from "@bitwarden/common/auth/abstractio import { UserVerificationService } from "@bitwarden/common/auth/abstractions/user-verification/user-verification.service.abstraction"; import { AuthenticationStatus } from "@bitwarden/common/auth/enums/authentication-status"; import { ClientType } from "@bitwarden/common/enums"; -import { CryptoService } from "@bitwarden/common/platform/abstractions/crypto.service"; import { MessagingService } from "@bitwarden/common/platform/abstractions/messaging.service"; import { PlatformUtilsService } from "@bitwarden/common/platform/abstractions/platform-utils.service"; +import { KeyService } from "@bitwarden/key-management"; /** * Only allow access to this route if the vault is locked. @@ -31,7 +31,7 @@ export function lockGuard(): CanActivateFn { routerStateSnapshot: RouterStateSnapshot, ) => { const authService = inject(AuthService); - const cryptoService = inject(CryptoService); + const keyService = inject(KeyService); const deviceTrustService = inject(DeviceTrustServiceAbstraction); const platformUtilService = inject(PlatformUtilsService); const messagingService = inject(MessagingService); @@ -54,7 +54,7 @@ export function lockGuard(): CanActivateFn { } // If legacy user on web, redirect to migration page - if (await cryptoService.isLegacyUser()) { + if (await keyService.isLegacyUser()) { if (platformUtilService.getClientType() === ClientType.Web) { return router.createUrlTree(["migrate-legacy-encryption"]); } @@ -78,7 +78,7 @@ export function lockGuard(): CanActivateFn { } // If authN user with TDE directly navigates to lock, reject that navigation - const everHadUserKey = await firstValueFrom(cryptoService.everHadUserKey$); + const everHadUserKey = await firstValueFrom(keyService.everHadUserKey$); if (tdeEnabled && !everHadUserKey) { return false; } diff --git a/libs/angular/src/auth/guards/redirect.guard.ts b/libs/angular/src/auth/guards/redirect.guard.ts index 760558dfb5..f79f5d3c4b 100644 --- a/libs/angular/src/auth/guards/redirect.guard.ts +++ b/libs/angular/src/auth/guards/redirect.guard.ts @@ -5,8 +5,8 @@ import { firstValueFrom } from "rxjs"; import { AuthService } from "@bitwarden/common/auth/abstractions/auth.service"; import { DeviceTrustServiceAbstraction } from "@bitwarden/common/auth/abstractions/device-trust.service.abstraction"; import { AuthenticationStatus } from "@bitwarden/common/auth/enums/authentication-status"; -import { CryptoService } from "@bitwarden/common/platform/abstractions/crypto.service"; import { LogService } from "@bitwarden/common/platform/abstractions/log.service"; +import { KeyService } from "@bitwarden/key-management"; export interface RedirectRoutes { loggedIn: string; @@ -31,7 +31,7 @@ export function redirectGuard(overrides: Partial = {}): CanActiv const routes = { ...defaultRoutes, ...overrides }; return async (route) => { const authService = inject(AuthService); - const cryptoService = inject(CryptoService); + const keyService = inject(KeyService); const deviceTrustService = inject(DeviceTrustServiceAbstraction); const logService = inject(LogService); const router = inject(Router); @@ -49,7 +49,7 @@ export function redirectGuard(overrides: Partial = {}): CanActiv // If locked, TDE is enabled, and the user hasn't decrypted yet, then redirect to the // login decryption options component. const tdeEnabled = await firstValueFrom(deviceTrustService.supportsDeviceTrust$); - const everHadUserKey = await firstValueFrom(cryptoService.everHadUserKey$); + const everHadUserKey = await firstValueFrom(keyService.everHadUserKey$); if (authStatus === AuthenticationStatus.Locked && tdeEnabled && !everHadUserKey) { logService.info( "Sending user to TDE decryption options. AuthStatus is %s. TDE support is %s. Ever had user key is %s.", diff --git a/libs/angular/src/auth/guards/tde-decryption-required.guard.ts b/libs/angular/src/auth/guards/tde-decryption-required.guard.ts index 51d1a5a3b5..6bb83021fd 100644 --- a/libs/angular/src/auth/guards/tde-decryption-required.guard.ts +++ b/libs/angular/src/auth/guards/tde-decryption-required.guard.ts @@ -10,8 +10,8 @@ import { firstValueFrom } from "rxjs"; import { AuthService } from "@bitwarden/common/auth/abstractions/auth.service"; import { DeviceTrustServiceAbstraction } from "@bitwarden/common/auth/abstractions/device-trust.service.abstraction"; import { AuthenticationStatus } from "@bitwarden/common/auth/enums/authentication-status"; -import { CryptoService } from "@bitwarden/common/platform/abstractions/crypto.service"; import { LogService } from "@bitwarden/common/platform/abstractions/log.service"; +import { KeyService } from "@bitwarden/key-management"; /** * Only allow access to this route if the vault is locked and has never been decrypted. @@ -22,14 +22,14 @@ import { LogService } from "@bitwarden/common/platform/abstractions/log.service" export function tdeDecryptionRequiredGuard(): CanActivateFn { return async (_: ActivatedRouteSnapshot, state: RouterStateSnapshot) => { const authService = inject(AuthService); - const cryptoService = inject(CryptoService); + const keyService = inject(KeyService); const deviceTrustService = inject(DeviceTrustServiceAbstraction); const logService = inject(LogService); const router = inject(Router); const authStatus = await authService.getAuthStatus(); const tdeEnabled = await firstValueFrom(deviceTrustService.supportsDeviceTrust$); - const everHadUserKey = await firstValueFrom(cryptoService.everHadUserKey$); + const everHadUserKey = await firstValueFrom(keyService.everHadUserKey$); // We need to determine if we should bypass the decryption options and send the user to the vault. // The ONLY time that we want to send a user to the decryption options is when: diff --git a/libs/angular/src/platform/pipes/fingerprint.pipe.ts b/libs/angular/src/platform/pipes/fingerprint.pipe.ts index a01ec21e6c..8f1a07cfd6 100644 --- a/libs/angular/src/platform/pipes/fingerprint.pipe.ts +++ b/libs/angular/src/platform/pipes/fingerprint.pipe.ts @@ -1,13 +1,13 @@ import { Pipe } from "@angular/core"; -import { CryptoService } from "@bitwarden/common/platform/abstractions/crypto.service"; import { Utils } from "@bitwarden/common/platform/misc/utils"; +import { KeyService } from "@bitwarden/key-management"; @Pipe({ name: "fingerprint", }) export class FingerprintPipe { - constructor(private cryptoService: CryptoService) {} + constructor(private keyService: KeyService) {} async transform(publicKey: string | Uint8Array, fingerprintMaterial: string): Promise { try { @@ -15,7 +15,7 @@ export class FingerprintPipe { publicKey = Utils.fromB64ToArray(publicKey); } - const fingerprint = await this.cryptoService.getFingerprint(fingerprintMaterial, publicKey); + const fingerprint = await this.keyService.getFingerprint(fingerprintMaterial, publicKey); if (fingerprint != null) { return fingerprint.join("-"); diff --git a/libs/angular/src/services/jslib-services.module.ts b/libs/angular/src/services/jslib-services.module.ts index e8d29bd69b..b7c4a02dec 100644 --- a/libs/angular/src/services/jslib-services.module.ts +++ b/libs/angular/src/services/jslib-services.module.ts @@ -89,7 +89,7 @@ import { TwoFactorService as TwoFactorServiceAbstraction } from "@bitwarden/comm 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 { WebAuthnLoginApiServiceAbstraction } from "@bitwarden/common/auth/abstractions/webauthn/webauthn-login-api.service.abstraction"; -import { WebAuthnLoginPrfCryptoServiceAbstraction } from "@bitwarden/common/auth/abstractions/webauthn/webauthn-login-prf-crypto.service.abstraction"; +import { WebAuthnLoginPrfKeyServiceAbstraction } from "@bitwarden/common/auth/abstractions/webauthn/webauthn-login-prf-key.service.abstraction"; import { WebAuthnLoginServiceAbstraction } from "@bitwarden/common/auth/abstractions/webauthn/webauthn-login.service.abstraction"; import { AccountApiServiceImplementation } from "@bitwarden/common/auth/services/account-api.service"; import { AccountServiceImplementation } from "@bitwarden/common/auth/services/account.service"; @@ -109,7 +109,7 @@ import { TwoFactorService } from "@bitwarden/common/auth/services/two-factor.ser import { UserVerificationApiService } from "@bitwarden/common/auth/services/user-verification/user-verification-api.service"; import { UserVerificationService } from "@bitwarden/common/auth/services/user-verification/user-verification.service"; import { WebAuthnLoginApiService } from "@bitwarden/common/auth/services/webauthn-login/webauthn-login-api.service"; -import { WebAuthnLoginPrfCryptoService } from "@bitwarden/common/auth/services/webauthn-login/webauthn-login-prf-crypto.service"; +import { WebAuthnLoginPrfKeyService } from "@bitwarden/common/auth/services/webauthn-login/webauthn-login-prf-key.service"; import { WebAuthnLoginService } from "@bitwarden/common/auth/services/webauthn-login/webauthn-login.service"; import { AutofillSettingsServiceAbstraction, @@ -141,7 +141,6 @@ import { BulkEncryptService } from "@bitwarden/common/platform/abstractions/bulk import { ConfigApiServiceAbstraction } from "@bitwarden/common/platform/abstractions/config/config-api.service.abstraction"; import { ConfigService } from "@bitwarden/common/platform/abstractions/config/config.service"; import { CryptoFunctionService as CryptoFunctionServiceAbstraction } from "@bitwarden/common/platform/abstractions/crypto-function.service"; -import { CryptoService as CryptoServiceAbstraction } from "@bitwarden/common/platform/abstractions/crypto.service"; import { EncryptService } from "@bitwarden/common/platform/abstractions/encrypt.service"; import { EnvironmentService, @@ -173,7 +172,6 @@ import { AppIdService } from "@bitwarden/common/platform/services/app-id.service import { ConfigApiService } from "@bitwarden/common/platform/services/config/config-api.service"; import { DefaultConfigService } from "@bitwarden/common/platform/services/config/default-config.service"; import { ConsoleLogService } from "@bitwarden/common/platform/services/console-log.service"; -import { CryptoService } from "@bitwarden/common/platform/services/crypto.service"; import { BulkEncryptServiceImplementation } from "@bitwarden/common/platform/services/cryptography/bulk-encrypt.service.implementation"; import { MultithreadEncryptServiceImplementation } from "@bitwarden/common/platform/services/cryptography/multithread-encrypt.service.implementation"; import { DefaultBroadcasterService } from "@bitwarden/common/platform/services/default-broadcaster.service"; @@ -269,7 +267,12 @@ import { ImportService, ImportServiceAbstraction, } from "@bitwarden/importer/core"; -import { BiometricStateService, DefaultBiometricStateService } from "@bitwarden/key-management"; +import { + KeyService as KeyServiceAbstraction, + DefaultKeyService as KeyService, + BiometricStateService, + DefaultBiometricStateService, +} from "@bitwarden/key-management"; import { PasswordRepromptService } from "@bitwarden/vault"; import { VaultExportService, @@ -395,7 +398,7 @@ const safeProviders: SafeProvider[] = [ deps: [ AccountServiceAbstraction, MessagingServiceAbstraction, - CryptoServiceAbstraction, + KeyServiceAbstraction, ApiServiceAbstraction, StateServiceAbstraction, TokenServiceAbstraction, @@ -407,7 +410,7 @@ const safeProviders: SafeProvider[] = [ deps: [ AccountServiceAbstraction, InternalMasterPasswordServiceAbstraction, - CryptoServiceAbstraction, + KeyServiceAbstraction, ApiServiceAbstraction, TokenServiceAbstraction, AppIdServiceAbstraction, @@ -445,7 +448,7 @@ const safeProviders: SafeProvider[] = [ safeProvider({ provide: CipherServiceAbstraction, useFactory: ( - cryptoService: CryptoServiceAbstraction, + keyService: KeyServiceAbstraction, domainSettingsService: DomainSettingsService, apiService: ApiServiceAbstraction, i18nService: I18nServiceAbstraction, @@ -460,7 +463,7 @@ const safeProviders: SafeProvider[] = [ accountService: AccountServiceAbstraction, ) => new CipherService( - cryptoService, + keyService, domainSettingsService, apiService, i18nService, @@ -475,7 +478,7 @@ const safeProviders: SafeProvider[] = [ accountService, ), deps: [ - CryptoServiceAbstraction, + KeyServiceAbstraction, DomainSettingsService, ApiServiceAbstraction, I18nServiceAbstraction, @@ -494,7 +497,7 @@ const safeProviders: SafeProvider[] = [ provide: InternalFolderService, useClass: FolderService, deps: [ - CryptoServiceAbstraction, + KeyServiceAbstraction, EncryptService, I18nServiceAbstraction, CipherServiceAbstraction, @@ -539,7 +542,7 @@ const safeProviders: SafeProvider[] = [ safeProvider({ provide: CollectionService, useClass: DefaultCollectionService, - deps: [CryptoServiceAbstraction, EncryptService, I18nServiceAbstraction, StateProvider], + deps: [KeyServiceAbstraction, EncryptService, I18nServiceAbstraction, StateProvider], }), safeProvider({ provide: ENV_ADDITIONAL_REGIONS, @@ -584,8 +587,8 @@ const safeProviders: SafeProvider[] = [ deps: [CryptoFunctionServiceAbstraction], }), safeProvider({ - provide: CryptoServiceAbstraction, - useClass: CryptoService, + provide: KeyServiceAbstraction, + useClass: KeyService, deps: [ PinServiceAbstraction, InternalMasterPasswordServiceAbstraction, @@ -610,7 +613,7 @@ const safeProviders: SafeProvider[] = [ useFactory: legacyPasswordGenerationServiceFactory, deps: [ EncryptService, - CryptoServiceAbstraction, + KeyServiceAbstraction, PolicyServiceAbstraction, AccountServiceAbstraction, StateProvider, @@ -619,7 +622,7 @@ const safeProviders: SafeProvider[] = [ safeProvider({ provide: GeneratorHistoryService, useClass: LocalGeneratorHistoryService, - deps: [EncryptService, CryptoServiceAbstraction, StateProvider], + deps: [EncryptService, KeyServiceAbstraction, StateProvider], }), safeProvider({ provide: UsernameGenerationServiceAbstraction, @@ -627,7 +630,7 @@ const safeProviders: SafeProvider[] = [ deps: [ ApiServiceAbstraction, I18nServiceAbstraction, - CryptoServiceAbstraction, + KeyServiceAbstraction, EncryptService, PolicyServiceAbstraction, AccountServiceAbstraction, @@ -667,7 +670,7 @@ const safeProviders: SafeProvider[] = [ provide: InternalSendService, useClass: SendService, deps: [ - CryptoServiceAbstraction, + KeyServiceAbstraction, I18nServiceAbstraction, KeyGenerationServiceAbstraction, SendStateProviderAbstraction, @@ -694,7 +697,7 @@ const safeProviders: SafeProvider[] = [ DomainSettingsService, InternalFolderService, CipherServiceAbstraction, - CryptoServiceAbstraction, + KeyServiceAbstraction, CollectionService, MessagingServiceAbstraction, InternalPolicyService, @@ -727,7 +730,7 @@ const safeProviders: SafeProvider[] = [ AccountServiceAbstraction, PinServiceAbstraction, UserDecryptionOptionsServiceAbstraction, - CryptoServiceAbstraction, + KeyServiceAbstraction, TokenServiceAbstraction, PolicyServiceAbstraction, BiometricStateService, @@ -800,7 +803,7 @@ const safeProviders: SafeProvider[] = [ ImportApiServiceAbstraction, I18nServiceAbstraction, CollectionService, - CryptoServiceAbstraction, + KeyServiceAbstraction, EncryptService, PinServiceAbstraction, AccountServiceAbstraction, @@ -813,7 +816,7 @@ const safeProviders: SafeProvider[] = [ FolderServiceAbstraction, CipherServiceAbstraction, PinServiceAbstraction, - CryptoServiceAbstraction, + KeyServiceAbstraction, EncryptService, CryptoFunctionServiceAbstraction, KdfConfigServiceAbstraction, @@ -827,7 +830,7 @@ const safeProviders: SafeProvider[] = [ CipherServiceAbstraction, ApiServiceAbstraction, PinServiceAbstraction, - CryptoServiceAbstraction, + KeyServiceAbstraction, EncryptService, CryptoFunctionServiceAbstraction, CollectionService, @@ -928,7 +931,7 @@ const safeProviders: SafeProvider[] = [ deps: [ AccountServiceAbstraction, InternalMasterPasswordServiceAbstraction, - CryptoServiceAbstraction, + KeyServiceAbstraction, ApiServiceAbstraction, TokenServiceAbstraction, LogService, @@ -942,7 +945,7 @@ const safeProviders: SafeProvider[] = [ provide: UserVerificationServiceAbstraction, useClass: UserVerificationService, deps: [ - CryptoServiceAbstraction, + KeyServiceAbstraction, AccountServiceAbstraction, InternalMasterPasswordServiceAbstraction, I18nServiceAbstraction, @@ -975,7 +978,7 @@ const safeProviders: SafeProvider[] = [ deps: [ OrganizationApiServiceAbstraction, AccountServiceAbstraction, - CryptoServiceAbstraction, + KeyServiceAbstraction, EncryptService, OrganizationUserApiService, I18nServiceAbstraction, @@ -1085,7 +1088,7 @@ const safeProviders: SafeProvider[] = [ deps: [ KeyGenerationServiceAbstraction, CryptoFunctionServiceAbstraction, - CryptoServiceAbstraction, + KeyServiceAbstraction, EncryptService, AppIdServiceAbstraction, DevicesApiServiceAbstraction, @@ -1105,7 +1108,7 @@ const safeProviders: SafeProvider[] = [ AppIdServiceAbstraction, AccountServiceAbstraction, InternalMasterPasswordServiceAbstraction, - CryptoServiceAbstraction, + KeyServiceAbstraction, EncryptService, ApiServiceAbstraction, StateProvider, @@ -1127,8 +1130,8 @@ const safeProviders: SafeProvider[] = [ ], }), safeProvider({ - provide: WebAuthnLoginPrfCryptoServiceAbstraction, - useClass: WebAuthnLoginPrfCryptoService, + provide: WebAuthnLoginPrfKeyServiceAbstraction, + useClass: WebAuthnLoginPrfKeyService, deps: [CryptoFunctionServiceAbstraction], }), safeProvider({ @@ -1142,7 +1145,7 @@ const safeProviders: SafeProvider[] = [ deps: [ WebAuthnLoginApiServiceAbstraction, LoginStrategyServiceAbstraction, - WebAuthnLoginPrfCryptoServiceAbstraction, + WebAuthnLoginPrfKeyServiceAbstraction, WINDOW, LogService, ], @@ -1197,7 +1200,7 @@ const safeProviders: SafeProvider[] = [ useClass: OrganizationBillingService, deps: [ ApiServiceAbstraction, - CryptoServiceAbstraction, + KeyServiceAbstraction, EncryptService, I18nServiceAbstraction, OrganizationApiServiceAbstraction, @@ -1257,7 +1260,7 @@ const safeProviders: SafeProvider[] = [ safeProvider({ provide: UserAutoUnlockKeyService, useClass: UserAutoUnlockKeyService, - deps: [CryptoServiceAbstraction], + deps: [KeyServiceAbstraction], }), safeProvider({ provide: ErrorHandler, @@ -1301,7 +1304,7 @@ const safeProviders: SafeProvider[] = [ useClass: DefaultSetPasswordJitService, deps: [ ApiServiceAbstraction, - CryptoServiceAbstraction, + KeyServiceAbstraction, EncryptService, I18nServiceAbstraction, KdfConfigServiceAbstraction, @@ -1324,7 +1327,7 @@ const safeProviders: SafeProvider[] = [ safeProvider({ provide: RegistrationFinishServiceAbstraction, useClass: DefaultRegistrationFinishService, - deps: [CryptoServiceAbstraction, AccountApiServiceAbstraction], + deps: [KeyServiceAbstraction, AccountApiServiceAbstraction], }), safeProvider({ provide: ViewCacheService, @@ -1340,7 +1343,7 @@ const safeProviders: SafeProvider[] = [ PlatformUtilsServiceAbstraction, AccountServiceAbstraction, KdfConfigServiceAbstraction, - CryptoServiceAbstraction, + KeyServiceAbstraction, ApiServiceAbstraction, ], }), diff --git a/libs/angular/src/vault/components/attachments.component.ts b/libs/angular/src/vault/components/attachments.component.ts index 43c5a0d6d4..879cb9b4d5 100644 --- a/libs/angular/src/vault/components/attachments.component.ts +++ b/libs/angular/src/vault/components/attachments.component.ts @@ -5,7 +5,6 @@ import { ApiService } from "@bitwarden/common/abstractions/api.service"; import { AccountService } from "@bitwarden/common/auth/abstractions/account.service"; import { BillingAccountProfileStateService } from "@bitwarden/common/billing/abstractions/account/billing-account-profile-state.service"; import { ErrorResponse } from "@bitwarden/common/models/response/error.response"; -import { CryptoService } from "@bitwarden/common/platform/abstractions/crypto.service"; import { EncryptService } from "@bitwarden/common/platform/abstractions/encrypt.service"; import { FileDownloadService } from "@bitwarden/common/platform/abstractions/file-download/file-download.service"; import { I18nService } from "@bitwarden/common/platform/abstractions/i18n.service"; @@ -19,6 +18,7 @@ import { Cipher } from "@bitwarden/common/vault/models/domain/cipher"; import { AttachmentView } from "@bitwarden/common/vault/models/view/attachment.view"; import { CipherView } from "@bitwarden/common/vault/models/view/cipher.view"; import { DialogService, ToastService } from "@bitwarden/components"; +import { KeyService } from "@bitwarden/key-management"; @Directive() export class AttachmentsComponent implements OnInit { @@ -40,7 +40,7 @@ export class AttachmentsComponent implements OnInit { constructor( protected cipherService: CipherService, protected i18nService: I18nService, - protected cryptoService: CryptoService, + protected keyService: KeyService, protected encryptService: EncryptService, protected platformUtilsService: PlatformUtilsService, protected apiService: ApiService, @@ -179,7 +179,7 @@ export class AttachmentsComponent implements OnInit { const key = attachment.key != null ? attachment.key - : await this.cryptoService.getOrgKey(this.cipher.organizationId); + : await this.keyService.getOrgKey(this.cipher.organizationId); const decBuf = await this.encryptService.decryptToBytes(encBuf, key); this.fileDownloadService.download({ fileName: attachment.fileName, @@ -250,7 +250,7 @@ export class AttachmentsComponent implements OnInit { const key = attachment.key != null ? attachment.key - : await this.cryptoService.getOrgKey(this.cipher.organizationId); + : await this.keyService.getOrgKey(this.cipher.organizationId); const decBuf = await this.encryptService.decryptToBytes(encBuf, key); const activeUserId = await firstValueFrom( this.accountService.activeAccount$.pipe(map((a) => a?.id)), diff --git a/libs/angular/src/vault/components/folder-add-edit.component.ts b/libs/angular/src/vault/components/folder-add-edit.component.ts index 199feb599f..71d7b32baf 100644 --- a/libs/angular/src/vault/components/folder-add-edit.component.ts +++ b/libs/angular/src/vault/components/folder-add-edit.component.ts @@ -3,7 +3,6 @@ import { Validators, FormBuilder } from "@angular/forms"; import { firstValueFrom } from "rxjs"; import { AccountService } from "@bitwarden/common/auth/abstractions/account.service"; -import { CryptoService } from "@bitwarden/common/platform/abstractions/crypto.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"; @@ -11,6 +10,7 @@ import { FolderApiServiceAbstraction } from "@bitwarden/common/vault/abstraction import { FolderService } from "@bitwarden/common/vault/abstractions/folder/folder.service.abstraction"; import { FolderView } from "@bitwarden/common/vault/models/view/folder.view"; import { DialogService } from "@bitwarden/components"; +import { KeyService } from "@bitwarden/key-management"; @Directive() export class FolderAddEditComponent implements OnInit { @@ -33,7 +33,7 @@ export class FolderAddEditComponent implements OnInit { protected folderService: FolderService, protected folderApiService: FolderApiServiceAbstraction, protected accountService: AccountService, - protected cryptoService: CryptoService, + protected keyService: KeyService, protected i18nService: I18nService, protected platformUtilsService: PlatformUtilsService, protected logService: LogService, @@ -58,7 +58,7 @@ export class FolderAddEditComponent implements OnInit { try { const activeAccountId = await firstValueFrom(this.accountService.activeAccount$); - const userKey = await this.cryptoService.getUserKeyWithLegacySupport(activeAccountId.id); + const userKey = await this.keyService.getUserKeyWithLegacySupport(activeAccountId.id); const folder = await this.folderService.encrypt(this.folder, userKey); this.formPromise = this.folderApiService.save(folder); await this.formPromise; diff --git a/libs/angular/src/vault/components/view.component.ts b/libs/angular/src/vault/components/view.component.ts index 2ff34ebafa..c266605670 100644 --- a/libs/angular/src/vault/components/view.component.ts +++ b/libs/angular/src/vault/components/view.component.ts @@ -20,7 +20,6 @@ import { BillingAccountProfileStateService } from "@bitwarden/common/billing/abs import { EventType } from "@bitwarden/common/enums"; import { ErrorResponse } from "@bitwarden/common/models/response/error.response"; import { BroadcasterService } from "@bitwarden/common/platform/abstractions/broadcaster.service"; -import { CryptoService } from "@bitwarden/common/platform/abstractions/crypto.service"; import { EncryptService } from "@bitwarden/common/platform/abstractions/encrypt.service"; import { FileDownloadService } from "@bitwarden/common/platform/abstractions/file-download/file-download.service"; import { I18nService } from "@bitwarden/common/platform/abstractions/i18n.service"; @@ -40,6 +39,7 @@ import { CipherView } from "@bitwarden/common/vault/models/view/cipher.view"; import { FolderView } from "@bitwarden/common/vault/models/view/folder.view"; import { CipherAuthorizationService } from "@bitwarden/common/vault/services/cipher-authorization.service"; import { DialogService } from "@bitwarden/components"; +import { KeyService } from "@bitwarden/key-management"; import { PasswordRepromptService } from "@bitwarden/vault"; const BroadcasterSubscriptionId = "ViewComponent"; @@ -91,7 +91,7 @@ export class ViewComponent implements OnDestroy, OnInit { protected totpService: TotpService, protected tokenService: TokenService, protected i18nService: I18nService, - protected cryptoService: CryptoService, + protected keyService: KeyService, protected encryptService: EncryptService, protected platformUtilsService: PlatformUtilsService, protected auditService: AuditService, @@ -449,7 +449,7 @@ export class ViewComponent implements OnDestroy, OnInit { const key = attachment.key != null ? attachment.key - : await this.cryptoService.getOrgKey(this.cipher.organizationId); + : await this.keyService.getOrgKey(this.cipher.organizationId); const decBuf = await this.encryptService.decryptToBytes(encBuf, key); this.fileDownloadService.download({ fileName: attachment.fileName, diff --git a/libs/auth/src/angular/input-password/input-password.component.ts b/libs/auth/src/angular/input-password/input-password.component.ts index dbacf28054..e110d2d53e 100644 --- a/libs/auth/src/angular/input-password/input-password.component.ts +++ b/libs/auth/src/angular/input-password/input-password.component.ts @@ -10,7 +10,6 @@ import { AuditService } from "@bitwarden/common/abstractions/audit.service"; import { PolicyService } from "@bitwarden/common/admin-console/abstractions/policy/policy.service.abstraction"; import { MasterPasswordPolicyOptions } from "@bitwarden/common/admin-console/models/domain/master-password-policy-options"; import { DEFAULT_KDF_CONFIG } from "@bitwarden/common/auth/models/domain/kdf-config"; -import { CryptoService } from "@bitwarden/common/platform/abstractions/crypto.service"; import { I18nService } from "@bitwarden/common/platform/abstractions/i18n.service"; import { HashPurpose } from "@bitwarden/common/platform/enums"; import { Utils } from "@bitwarden/common/platform/misc/utils"; @@ -24,6 +23,7 @@ import { InputModule, ToastService, } from "@bitwarden/components"; +import { KeyService } from "@bitwarden/key-management"; import { InputsFieldMatch } from "../../../../angular/src/auth/validators/inputs-field-match.validator"; import { SharedModule } from "../../../../components/src/shared"; @@ -96,7 +96,7 @@ export class InputPasswordComponent { constructor( private auditService: AuditService, - private cryptoService: CryptoService, + private keyService: KeyService, private dialogService: DialogService, private formBuilder: FormBuilder, private i18nService: I18nService, @@ -146,15 +146,15 @@ export class InputPasswordComponent { throw new Error("Email is required to create master key."); } - const masterKey = await this.cryptoService.makeMasterKey( + const masterKey = await this.keyService.makeMasterKey( password, this.email.trim().toLowerCase(), kdfConfig, ); - const masterKeyHash = await this.cryptoService.hashMasterKey(password, masterKey); + const masterKeyHash = await this.keyService.hashMasterKey(password, masterKey); - const localMasterKeyHash = await this.cryptoService.hashMasterKey( + const localMasterKeyHash = await this.keyService.hashMasterKey( password, masterKey, HashPurpose.LocalAuthorization, diff --git a/libs/auth/src/angular/input-password/input-password.stories.ts b/libs/auth/src/angular/input-password/input-password.stories.ts index 5b9805fde5..e483ae16b3 100644 --- a/libs/auth/src/angular/input-password/input-password.stories.ts +++ b/libs/auth/src/angular/input-password/input-password.stories.ts @@ -7,9 +7,9 @@ import { ZXCVBNResult } from "zxcvbn"; import { AuditService } from "@bitwarden/common/abstractions/audit.service"; import { PolicyService } from "@bitwarden/common/admin-console/abstractions/policy/policy.service.abstraction"; import { MasterPasswordPolicyOptions } from "@bitwarden/common/admin-console/models/domain/master-password-policy-options"; -import { CryptoService } from "@bitwarden/common/platform/abstractions/crypto.service"; import { PasswordStrengthServiceAbstraction } from "@bitwarden/common/tools/password-strength"; import { DialogService, ToastService } from "@bitwarden/components"; +import { KeyService } from "@bitwarden/key-management"; // FIXME: remove `/apps` import from `/libs` // eslint-disable-next-line import/no-restricted-paths @@ -32,7 +32,7 @@ export default { } as Partial, }, { - provide: CryptoService, + provide: KeyService, useValue: { makeMasterKey: () => Promise.resolve("example-master-key"), hashMasterKey: () => Promise.resolve("example-master-key-hash"), diff --git a/libs/auth/src/angular/lock/lock.component.ts b/libs/auth/src/angular/lock/lock.component.ts index 33d318ac05..f2ffc1fbed 100644 --- a/libs/auth/src/angular/lock/lock.component.ts +++ b/libs/auth/src/angular/lock/lock.component.ts @@ -19,7 +19,6 @@ import { } from "@bitwarden/common/auth/types/verification"; import { ClientType } from "@bitwarden/common/enums"; import { BroadcasterService } from "@bitwarden/common/platform/abstractions/broadcaster.service"; -import { CryptoService } from "@bitwarden/common/platform/abstractions/crypto.service"; import { I18nService } from "@bitwarden/common/platform/abstractions/i18n.service"; import { LogService } from "@bitwarden/common/platform/abstractions/log.service"; import { MessagingService } from "@bitwarden/common/platform/abstractions/messaging.service"; @@ -37,7 +36,7 @@ import { IconButtonModule, ToastService, } from "@bitwarden/components"; -import { BiometricStateService } from "@bitwarden/key-management"; +import { KeyService, BiometricStateService } from "@bitwarden/key-management"; import { PinServiceAbstraction } from "../../common/abstractions"; import { AnonLayoutWrapperDataService } from "../anon-layout/anon-layout-wrapper-data.service"; @@ -123,7 +122,7 @@ export class LockV2Component implements OnInit, OnDestroy { private accountService: AccountService, private pinService: PinServiceAbstraction, private userVerificationService: UserVerificationService, - private cryptoService: CryptoService, + private keyService: KeyService, private platformUtilsService: PlatformUtilsService, private router: Router, private dialogService: DialogService, @@ -307,7 +306,7 @@ export class LockV2Component implements OnInit, OnDestroy { try { await this.biometricStateService.setUserPromptCancelled(); - const userKey = await this.cryptoService.getUserKeyFromStorage( + const userKey = await this.keyService.getUserKeyFromStorage( KeySuffixOptions.Biometric, this.activeAccount.id, ); @@ -486,7 +485,7 @@ export class LockV2Component implements OnInit, OnDestroy { } private async setUserKeyAndContinue(key: UserKey, evaluatePasswordAfterUnlock = false) { - await this.cryptoService.setUserKey(key, this.activeAccount.id); + await this.keyService.setUserKey(key, this.activeAccount.id); // Now that we have a decrypted user key in memory, we can check if we // need to establish trust on the current device diff --git a/libs/auth/src/angular/registration/registration-finish/default-registration-finish.service.spec.ts b/libs/auth/src/angular/registration/registration-finish/default-registration-finish.service.spec.ts index fe6b9b2c7d..bf0e75ed33 100644 --- a/libs/auth/src/angular/registration/registration-finish/default-registration-finish.service.spec.ts +++ b/libs/auth/src/angular/registration/registration-finish/default-registration-finish.service.spec.ts @@ -2,11 +2,11 @@ import { MockProxy, mock } from "jest-mock-extended"; import { AccountApiService } from "@bitwarden/common/auth/abstractions/account-api.service"; import { DEFAULT_KDF_CONFIG } from "@bitwarden/common/auth/models/domain/kdf-config"; -import { CryptoService } from "@bitwarden/common/platform/abstractions/crypto.service"; import { EncString } from "@bitwarden/common/platform/models/domain/enc-string"; import { SymmetricCryptoKey } from "@bitwarden/common/platform/models/domain/symmetric-crypto-key"; import { CsprngArray } from "@bitwarden/common/types/csprng"; import { MasterKey, UserKey } from "@bitwarden/common/types/key"; +import { KeyService } from "@bitwarden/key-management"; import { PasswordInputResult } from "../../input-password/password-input-result"; @@ -15,14 +15,14 @@ import { DefaultRegistrationFinishService } from "./default-registration-finish. describe("DefaultRegistrationFinishService", () => { let service: DefaultRegistrationFinishService; - let cryptoService: MockProxy; + let keyService: MockProxy; let accountApiService: MockProxy; beforeEach(() => { - cryptoService = mock(); + keyService = mock(); accountApiService = mock(); - service = new DefaultRegistrationFinishService(cryptoService, accountApiService); + service = new DefaultRegistrationFinishService(keyService, accountApiService); }); it("instantiates", () => { @@ -76,7 +76,7 @@ describe("DefaultRegistrationFinishService", () => { }); it("throws an error if the user key cannot be created", async () => { - cryptoService.makeUserKey.mockResolvedValue([null, null]); + keyService.makeUserKey.mockResolvedValue([null, null]); await expect(service.finishRegistration(email, passwordInputResult)).rejects.toThrow( "User key could not be created", @@ -84,8 +84,8 @@ describe("DefaultRegistrationFinishService", () => { }); it("registers the user and returns a captcha bypass token when given valid email verification input", async () => { - cryptoService.makeUserKey.mockResolvedValue([userKey, userKeyEncString]); - cryptoService.makeKeyPair.mockResolvedValue(userKeyPair); + keyService.makeUserKey.mockResolvedValue([userKey, userKeyEncString]); + keyService.makeKeyPair.mockResolvedValue(userKeyPair); accountApiService.registerFinish.mockResolvedValue(capchaBypassToken); const result = await service.finishRegistration( @@ -96,8 +96,8 @@ describe("DefaultRegistrationFinishService", () => { expect(result).toEqual(capchaBypassToken); - expect(cryptoService.makeUserKey).toHaveBeenCalledWith(masterKey); - expect(cryptoService.makeKeyPair).toHaveBeenCalledWith(userKey); + expect(keyService.makeUserKey).toHaveBeenCalledWith(masterKey); + expect(keyService.makeKeyPair).toHaveBeenCalledWith(userKey); expect(accountApiService.registerFinish).toHaveBeenCalledWith( expect.objectContaining({ email, diff --git a/libs/auth/src/angular/registration/registration-finish/default-registration-finish.service.ts b/libs/auth/src/angular/registration/registration-finish/default-registration-finish.service.ts index 6d77c77749..2443f77464 100644 --- a/libs/auth/src/angular/registration/registration-finish/default-registration-finish.service.ts +++ b/libs/auth/src/angular/registration/registration-finish/default-registration-finish.service.ts @@ -2,8 +2,8 @@ import { MasterPasswordPolicyOptions } from "@bitwarden/common/admin-console/mod import { AccountApiService } from "@bitwarden/common/auth/abstractions/account-api.service"; import { RegisterFinishRequest } from "@bitwarden/common/auth/models/request/registration/register-finish.request"; import { KeysRequest } from "@bitwarden/common/models/request/keys.request"; -import { CryptoService } from "@bitwarden/common/platform/abstractions/crypto.service"; import { EncryptedString, EncString } from "@bitwarden/common/platform/models/domain/enc-string"; +import { KeyService } from "@bitwarden/key-management"; import { PasswordInputResult } from "../../input-password/password-input-result"; @@ -11,7 +11,7 @@ import { RegistrationFinishService } from "./registration-finish.service"; export class DefaultRegistrationFinishService implements RegistrationFinishService { constructor( - protected cryptoService: CryptoService, + protected keyService: KeyService, protected accountApiService: AccountApiService, ) {} @@ -31,14 +31,14 @@ export class DefaultRegistrationFinishService implements RegistrationFinishServi acceptEmergencyAccessInviteToken?: string, emergencyAccessId?: string, ): Promise { - const [newUserKey, newEncUserKey] = await this.cryptoService.makeUserKey( + const [newUserKey, newEncUserKey] = await this.keyService.makeUserKey( passwordInputResult.masterKey, ); if (!newUserKey || !newEncUserKey) { throw new Error("User key could not be created"); } - const userAsymmetricKeys = await this.cryptoService.makeKeyPair(newUserKey); + const userAsymmetricKeys = await this.keyService.makeKeyPair(newUserKey); const registerRequest = await this.buildRegisterRequest( email, diff --git a/libs/auth/src/angular/set-password-jit/default-set-password-jit.service.spec.ts b/libs/auth/src/angular/set-password-jit/default-set-password-jit.service.spec.ts index f36283e0c0..da49067d7b 100644 --- a/libs/auth/src/angular/set-password-jit/default-set-password-jit.service.spec.ts +++ b/libs/auth/src/angular/set-password-jit/default-set-password-jit.service.spec.ts @@ -14,7 +14,6 @@ import { InternalMasterPasswordServiceAbstraction } from "@bitwarden/common/auth import { DEFAULT_KDF_CONFIG } from "@bitwarden/common/auth/models/domain/kdf-config"; import { SetPasswordRequest } from "@bitwarden/common/auth/models/request/set-password.request"; import { KeysRequest } from "@bitwarden/common/models/request/keys.request"; -import { CryptoService } from "@bitwarden/common/platform/abstractions/crypto.service"; import { EncryptService } from "@bitwarden/common/platform/abstractions/encrypt.service"; import { I18nService } from "@bitwarden/common/platform/abstractions/i18n.service"; import { Utils } from "@bitwarden/common/platform/misc/utils"; @@ -23,6 +22,7 @@ import { SymmetricCryptoKey } from "@bitwarden/common/platform/models/domain/sym import { CsprngArray } from "@bitwarden/common/types/csprng"; import { UserId } from "@bitwarden/common/types/guid"; import { MasterKey, UserKey } from "@bitwarden/common/types/key"; +import { KeyService } from "@bitwarden/key-management"; import { PasswordInputResult } from "../input-password/password-input-result"; @@ -33,7 +33,7 @@ describe("DefaultSetPasswordJitService", () => { let sut: DefaultSetPasswordJitService; let apiService: MockProxy; - let cryptoService: MockProxy; + let keyService: MockProxy; let encryptService: MockProxy; let i18nService: MockProxy; let kdfConfigService: MockProxy; @@ -44,7 +44,7 @@ describe("DefaultSetPasswordJitService", () => { beforeEach(() => { apiService = mock(); - cryptoService = mock(); + keyService = mock(); encryptService = mock(); i18nService = mock(); kdfConfigService = mock(); @@ -55,7 +55,7 @@ describe("DefaultSetPasswordJitService", () => { sut = new DefaultSetPasswordJitService( apiService, - cryptoService, + keyService, encryptService, i18nService, kdfConfigService, @@ -141,14 +141,14 @@ describe("DefaultSetPasswordJitService", () => { function setupSetPasswordMocks(hasUserKey = true) { if (!hasUserKey) { - cryptoService.userKey$.mockReturnValue(of(null)); - cryptoService.makeUserKey.mockResolvedValue(protectedUserKey); + keyService.userKey$.mockReturnValue(of(null)); + keyService.makeUserKey.mockResolvedValue(protectedUserKey); } else { - cryptoService.userKey$.mockReturnValue(of(userKey)); - cryptoService.encryptUserKeyWithMasterKey.mockResolvedValue(protectedUserKey); + keyService.userKey$.mockReturnValue(of(userKey)); + keyService.encryptUserKeyWithMasterKey.mockResolvedValue(protectedUserKey); } - cryptoService.makeKeyPair.mockResolvedValue(keyPair); + keyService.makeKeyPair.mockResolvedValue(keyPair); apiService.setPassword.mockResolvedValue(undefined); masterPasswordService.setForceSetPasswordReason.mockResolvedValue(undefined); @@ -156,9 +156,9 @@ describe("DefaultSetPasswordJitService", () => { userDecryptionOptionsSubject.next(new UserDecryptionOptions({ hasMasterPassword: true })); userDecryptionOptionsService.setUserDecryptionOptions.mockResolvedValue(undefined); kdfConfigService.setKdfConfig.mockResolvedValue(undefined); - cryptoService.setUserKey.mockResolvedValue(undefined); + keyService.setUserKey.mockResolvedValue(undefined); - cryptoService.setPrivateKey.mockResolvedValue(undefined); + keyService.setPrivateKey.mockResolvedValue(undefined); masterPasswordService.setMasterKeyHash.mockResolvedValue(undefined); } @@ -171,7 +171,7 @@ describe("DefaultSetPasswordJitService", () => { return; } - cryptoService.userKey$.mockReturnValue(of(userKey)); + keyService.userKey$.mockReturnValue(of(userKey)); encryptService.rsaEncrypt.mockResolvedValue(userKeyEncString); organizationUserApiService.putOrganizationUserResetPasswordEnrollment.mockResolvedValue( diff --git a/libs/auth/src/angular/set-password-jit/default-set-password-jit.service.ts b/libs/auth/src/angular/set-password-jit/default-set-password-jit.service.ts index 1993877966..76477a0e5d 100644 --- a/libs/auth/src/angular/set-password-jit/default-set-password-jit.service.ts +++ b/libs/auth/src/angular/set-password-jit/default-set-password-jit.service.ts @@ -13,13 +13,13 @@ import { ForceSetPasswordReason } from "@bitwarden/common/auth/models/domain/for import { PBKDF2KdfConfig } from "@bitwarden/common/auth/models/domain/kdf-config"; import { SetPasswordRequest } from "@bitwarden/common/auth/models/request/set-password.request"; import { KeysRequest } from "@bitwarden/common/models/request/keys.request"; -import { CryptoService } from "@bitwarden/common/platform/abstractions/crypto.service"; import { EncryptService } from "@bitwarden/common/platform/abstractions/encrypt.service"; import { I18nService } from "@bitwarden/common/platform/abstractions/i18n.service"; import { Utils } from "@bitwarden/common/platform/misc/utils"; import { EncString } from "@bitwarden/common/platform/models/domain/enc-string"; import { UserId } from "@bitwarden/common/types/guid"; import { MasterKey, UserKey } from "@bitwarden/common/types/key"; +import { KeyService } from "@bitwarden/key-management"; import { SetPasswordCredentials, @@ -29,7 +29,7 @@ import { export class DefaultSetPasswordJitService implements SetPasswordJitService { constructor( protected apiService: ApiService, - protected cryptoService: CryptoService, + protected keyService: KeyService, protected encryptService: EncryptService, protected i18nService: I18nService, protected kdfConfigService: KdfConfigService, @@ -85,7 +85,7 @@ export class DefaultSetPasswordJitService implements SetPasswordJitService { // User now has a password so update account decryption options in state await this.updateAccountDecryptionProperties(masterKey, kdfConfig, protectedUserKey, userId); - await this.cryptoService.setPrivateKey(keyPair[1].encryptedString, userId); + await this.keyService.setPrivateKey(keyPair[1].encryptedString, userId); await this.masterPasswordService.setMasterKeyHash(localMasterKeyHash, userId); @@ -100,12 +100,12 @@ export class DefaultSetPasswordJitService implements SetPasswordJitService { ): Promise<[UserKey, EncString]> { let protectedUserKey: [UserKey, EncString] = null; - const userKey = await firstValueFrom(this.cryptoService.userKey$(userId)); + const userKey = await firstValueFrom(this.keyService.userKey$(userId)); if (userKey == null) { - protectedUserKey = await this.cryptoService.makeUserKey(masterKey); + protectedUserKey = await this.keyService.makeUserKey(masterKey); } else { - protectedUserKey = await this.cryptoService.encryptUserKeyWithMasterKey(masterKey); + protectedUserKey = await this.keyService.encryptUserKeyWithMasterKey(masterKey); } return protectedUserKey; @@ -114,7 +114,7 @@ export class DefaultSetPasswordJitService implements SetPasswordJitService { private async makeKeyPairAndRequest( protectedUserKey: [UserKey, EncString], ): Promise<[[string, EncString], KeysRequest]> { - const keyPair = await this.cryptoService.makeKeyPair(protectedUserKey[0]); + const keyPair = await this.keyService.makeKeyPair(protectedUserKey[0]); if (keyPair == null) { throw new Error("keyPair not found. Could not set password."); } @@ -136,7 +136,7 @@ export class DefaultSetPasswordJitService implements SetPasswordJitService { await this.userDecryptionOptionsService.setUserDecryptionOptions(userDecryptionOpts); await this.kdfConfigService.setKdfConfig(userId, kdfConfig); await this.masterPasswordService.setMasterKey(masterKey, userId); - await this.cryptoService.setUserKey(protectedUserKey[0], userId); + await this.keyService.setUserKey(protectedUserKey[0], userId); } private async handleResetPasswordAutoEnroll( @@ -153,7 +153,7 @@ export class DefaultSetPasswordJitService implements SetPasswordJitService { const publicKey = Utils.fromB64ToArray(organizationKeys.publicKey); // RSA Encrypt user key with organization public key - const userKey = await firstValueFrom(this.cryptoService.userKey$(userId)); + const userKey = await firstValueFrom(this.keyService.userKey$(userId)); if (userKey == null) { throw new Error("userKey not found. Could not handle reset password auto enroll."); diff --git a/libs/auth/src/common/login-strategies/auth-request-login.strategy.spec.ts b/libs/auth/src/common/login-strategies/auth-request-login.strategy.spec.ts index efc6da51d9..c0e7d2c00a 100644 --- a/libs/auth/src/common/login-strategies/auth-request-login.strategy.spec.ts +++ b/libs/auth/src/common/login-strategies/auth-request-login.strategy.spec.ts @@ -11,7 +11,6 @@ import { FakeMasterPasswordService } from "@bitwarden/common/auth/services/maste import { BillingAccountProfileStateService } from "@bitwarden/common/billing/abstractions/account/billing-account-profile-state.service"; import { VaultTimeoutAction } from "@bitwarden/common/enums/vault-timeout-action.enum"; import { AppIdService } from "@bitwarden/common/platform/abstractions/app-id.service"; -import { CryptoService } from "@bitwarden/common/platform/abstractions/crypto.service"; import { EncryptService } from "@bitwarden/common/platform/abstractions/encrypt.service"; import { LogService } from "@bitwarden/common/platform/abstractions/log.service"; import { MessagingService } from "@bitwarden/common/platform/abstractions/messaging.service"; @@ -24,6 +23,7 @@ import { FakeAccountService, mockAccountServiceWith } from "@bitwarden/common/sp import { CsprngArray } from "@bitwarden/common/types/csprng"; import { UserId } from "@bitwarden/common/types/guid"; import { MasterKey, UserKey } from "@bitwarden/common/types/key"; +import { KeyService } from "@bitwarden/key-management"; import { InternalUserDecryptionOptionsServiceAbstraction } from "../abstractions/user-decryption-options.service.abstraction"; import { AuthRequestLoginCredentials } from "../models/domain/login-credentials"; @@ -37,7 +37,7 @@ import { identityTokenResponseFactory } from "./login.strategy.spec"; describe("AuthRequestLoginStrategy", () => { let cache: AuthRequestLoginStrategyData; - let cryptoService: MockProxy; + let keyService: MockProxy; let encryptService: MockProxy; let apiService: MockProxy; let tokenService: MockProxy; @@ -73,7 +73,7 @@ describe("AuthRequestLoginStrategy", () => { const decMasterKeyHash = "LOCAL_PASSWORD_HASH"; beforeEach(async () => { - cryptoService = mock(); + keyService = mock(); apiService = mock(); tokenService = mock(); appIdService = mock(); @@ -102,7 +102,7 @@ describe("AuthRequestLoginStrategy", () => { deviceTrustService, accountService, masterPasswordService, - cryptoService, + keyService, encryptService, apiService, tokenService, @@ -161,13 +161,13 @@ describe("AuthRequestLoginStrategy", () => { decMasterKeyHash, mockUserId, ); - expect(cryptoService.setMasterKeyEncryptedUserKey).toHaveBeenCalledWith( + expect(keyService.setMasterKeyEncryptedUserKey).toHaveBeenCalledWith( tokenResponse.key, mockUserId, ); - expect(cryptoService.setUserKey).toHaveBeenCalledWith(userKey, mockUserId); + expect(keyService.setUserKey).toHaveBeenCalledWith(userKey, mockUserId); expect(deviceTrustService.trustDeviceIfRequired).toHaveBeenCalled(); - expect(cryptoService.setPrivateKey).toHaveBeenCalledWith(tokenResponse.privateKey, mockUserId); + expect(keyService.setPrivateKey).toHaveBeenCalledWith(tokenResponse.privateKey, mockUserId); }); it("sets keys after a successful authentication when only userKey provided in login credentials", async () => { @@ -189,12 +189,12 @@ describe("AuthRequestLoginStrategy", () => { expect(masterPasswordService.mock.setMasterKeyHash).not.toHaveBeenCalled(); // setMasterKeyEncryptedUserKey, setUserKey, and setPrivateKey should still be called - expect(cryptoService.setMasterKeyEncryptedUserKey).toHaveBeenCalledWith( + expect(keyService.setMasterKeyEncryptedUserKey).toHaveBeenCalledWith( tokenResponse.key, mockUserId, ); - expect(cryptoService.setUserKey).toHaveBeenCalledWith(decUserKey, mockUserId); - expect(cryptoService.setPrivateKey).toHaveBeenCalledWith(tokenResponse.privateKey, mockUserId); + expect(keyService.setUserKey).toHaveBeenCalledWith(decUserKey, mockUserId); + expect(keyService.setPrivateKey).toHaveBeenCalledWith(tokenResponse.privateKey, mockUserId); // trustDeviceIfRequired should be called expect(deviceTrustService.trustDeviceIfRequired).not.toHaveBeenCalled(); diff --git a/libs/auth/src/common/login-strategies/auth-request-login.strategy.ts b/libs/auth/src/common/login-strategies/auth-request-login.strategy.ts index ae0024d218..3f7e107fa9 100644 --- a/libs/auth/src/common/login-strategies/auth-request-login.strategy.ts +++ b/libs/auth/src/common/login-strategies/auth-request-login.strategy.ts @@ -99,10 +99,10 @@ export class AuthRequestLoginStrategy extends LoginStrategy { const authRequestCredentials = this.cache.value.authRequestCredentials; // User now may or may not have a master password // but set the master key encrypted user key if it exists regardless - await this.cryptoService.setMasterKeyEncryptedUserKey(response.key, userId); + await this.keyService.setMasterKeyEncryptedUserKey(response.key, userId); if (authRequestCredentials.decryptedUserKey) { - await this.cryptoService.setUserKey(authRequestCredentials.decryptedUserKey, userId); + await this.keyService.setUserKey(authRequestCredentials.decryptedUserKey, userId); } else { await this.trySetUserKeyWithMasterKey(userId); @@ -115,7 +115,7 @@ export class AuthRequestLoginStrategy extends LoginStrategy { const masterKey = await firstValueFrom(this.masterPasswordService.masterKey$(userId)); if (masterKey) { const userKey = await this.masterPasswordService.decryptUserKeyWithMasterKey(masterKey); - await this.cryptoService.setUserKey(userKey, userId); + await this.keyService.setUserKey(userKey, userId); } } @@ -123,7 +123,7 @@ export class AuthRequestLoginStrategy extends LoginStrategy { response: IdentityTokenResponse, userId: UserId, ): Promise { - await this.cryptoService.setPrivateKey( + await this.keyService.setPrivateKey( response.privateKey ?? (await this.createKeyPairForOldAccount(userId)), userId, ); diff --git a/libs/auth/src/common/login-strategies/login.strategy.spec.ts b/libs/auth/src/common/login-strategies/login.strategy.spec.ts index 35d62ca76b..49140cc2cc 100644 --- a/libs/auth/src/common/login-strategies/login.strategy.spec.ts +++ b/libs/auth/src/common/login-strategies/login.strategy.spec.ts @@ -21,7 +21,6 @@ import { FakeMasterPasswordService } from "@bitwarden/common/auth/services/maste import { BillingAccountProfileStateService } from "@bitwarden/common/billing/abstractions/account/billing-account-profile-state.service"; import { VaultTimeoutAction } from "@bitwarden/common/enums/vault-timeout-action.enum"; import { AppIdService } from "@bitwarden/common/platform/abstractions/app-id.service"; -import { CryptoService } from "@bitwarden/common/platform/abstractions/crypto.service"; import { EncryptService } from "@bitwarden/common/platform/abstractions/encrypt.service"; import { LogService } from "@bitwarden/common/platform/abstractions/log.service"; import { MessagingService } from "@bitwarden/common/platform/abstractions/messaging.service"; @@ -39,6 +38,7 @@ import { import { CsprngArray } from "@bitwarden/common/types/csprng"; import { UserId } from "@bitwarden/common/types/guid"; import { UserKey, MasterKey } from "@bitwarden/common/types/key"; +import { KeyService } from "@bitwarden/key-management"; import { LoginStrategyServiceAbstraction } from "../abstractions"; import { InternalUserDecryptionOptionsServiceAbstraction } from "../abstractions/user-decryption-options.service.abstraction"; @@ -104,7 +104,7 @@ describe("LoginStrategy", () => { let masterPasswordService: FakeMasterPasswordService; let loginStrategyService: MockProxy; - let cryptoService: MockProxy; + let keyService: MockProxy; let encryptService: MockProxy; let apiService: MockProxy; let tokenService: MockProxy; @@ -129,7 +129,7 @@ describe("LoginStrategy", () => { masterPasswordService = new FakeMasterPasswordService(); loginStrategyService = mock(); - cryptoService = mock(); + keyService = mock(); encryptService = mock(); apiService = mock(); tokenService = mock(); @@ -158,7 +158,7 @@ describe("LoginStrategy", () => { loginStrategyService, accountService, masterPasswordService, - cryptoService, + keyService, encryptService, apiService, tokenService, @@ -321,7 +321,7 @@ describe("LoginStrategy", () => { it("makes a new public and private key for an old account", async () => { const tokenResponse = identityTokenResponseFactory(); tokenResponse.privateKey = null; - cryptoService.makeKeyPair.mockResolvedValue(["PUBLIC_KEY", new EncString("PRIVATE_KEY")]); + keyService.makeKeyPair.mockResolvedValue(["PUBLIC_KEY", new EncString("PRIVATE_KEY")]); apiService.postIdentityToken.mockResolvedValue(tokenResponse); masterPasswordService.masterKeySubject.next(masterKey); @@ -330,10 +330,10 @@ describe("LoginStrategy", () => { await passwordLoginStrategy.logIn(credentials); // User symmetric key must be set before the new RSA keypair is generated - expect(cryptoService.setUserKey).toHaveBeenCalled(); - expect(cryptoService.makeKeyPair).toHaveBeenCalled(); - expect(cryptoService.setUserKey.mock.invocationCallOrder[0]).toBeLessThan( - cryptoService.makeKeyPair.mock.invocationCallOrder[0], + expect(keyService.setUserKey).toHaveBeenCalled(); + expect(keyService.makeKeyPair).toHaveBeenCalled(); + expect(keyService.setUserKey.mock.invocationCallOrder[0]).toBeLessThan( + keyService.makeKeyPair.mock.invocationCallOrder[0], ); expect(apiService.postAccountKeys).toHaveBeenCalled(); @@ -470,7 +470,7 @@ describe("LoginStrategy", () => { loginStrategyService, accountService, masterPasswordService, - cryptoService, + keyService, encryptService, apiService, tokenService, diff --git a/libs/auth/src/common/login-strategies/login.strategy.ts b/libs/auth/src/common/login-strategies/login.strategy.ts index 2e881f978d..67a286d819 100644 --- a/libs/auth/src/common/login-strategies/login.strategy.ts +++ b/libs/auth/src/common/login-strategies/login.strategy.ts @@ -25,7 +25,6 @@ import { ClientType } from "@bitwarden/common/enums"; import { VaultTimeoutAction } from "@bitwarden/common/enums/vault-timeout-action.enum"; import { KeysRequest } from "@bitwarden/common/models/request/keys.request"; import { AppIdService } from "@bitwarden/common/platform/abstractions/app-id.service"; -import { CryptoService } from "@bitwarden/common/platform/abstractions/crypto.service"; import { EncryptService } from "@bitwarden/common/platform/abstractions/encrypt.service"; import { LogService } from "@bitwarden/common/platform/abstractions/log.service"; import { MessagingService } from "@bitwarden/common/platform/abstractions/messaging.service"; @@ -34,6 +33,7 @@ import { StateService } from "@bitwarden/common/platform/abstractions/state.serv import { KdfType } from "@bitwarden/common/platform/enums"; import { Account, AccountProfile } from "@bitwarden/common/platform/models/domain/account"; import { UserId } from "@bitwarden/common/types/guid"; +import { KeyService } from "@bitwarden/key-management"; import { InternalUserDecryptionOptionsServiceAbstraction } from "../abstractions/user-decryption-options.service.abstraction"; import { @@ -66,7 +66,7 @@ export abstract class LoginStrategy { constructor( protected accountService: AccountService, protected masterPasswordService: InternalMasterPasswordServiceAbstraction, - protected cryptoService: CryptoService, + protected keyService: KeyService, protected encryptService: EncryptService, protected apiService: ApiService, protected tokenService: TokenService, @@ -284,8 +284,8 @@ export abstract class LoginStrategy { protected async createKeyPairForOldAccount(userId: UserId) { try { - const userKey = await this.cryptoService.getUserKeyWithLegacySupport(userId); - const [publicKey, privateKey] = await this.cryptoService.makeKeyPair(userKey); + const userKey = await this.keyService.getUserKeyWithLegacySupport(userId); + const [publicKey, privateKey] = await this.keyService.makeKeyPair(userKey); await this.apiService.postAccountKeys(new KeysRequest(publicKey, privateKey.encryptedString)); return privateKey.encryptedString; } catch (e) { diff --git a/libs/auth/src/common/login-strategies/password-login.strategy.spec.ts b/libs/auth/src/common/login-strategies/password-login.strategy.spec.ts index 07cbf2424a..4da6272cca 100644 --- a/libs/auth/src/common/login-strategies/password-login.strategy.spec.ts +++ b/libs/auth/src/common/login-strategies/password-login.strategy.spec.ts @@ -15,7 +15,6 @@ import { FakeMasterPasswordService } from "@bitwarden/common/auth/services/maste import { BillingAccountProfileStateService } from "@bitwarden/common/billing/abstractions/account/billing-account-profile-state.service"; import { VaultTimeoutAction } from "@bitwarden/common/enums/vault-timeout-action.enum"; import { AppIdService } from "@bitwarden/common/platform/abstractions/app-id.service"; -import { CryptoService } from "@bitwarden/common/platform/abstractions/crypto.service"; import { EncryptService } from "@bitwarden/common/platform/abstractions/encrypt.service"; import { LogService } from "@bitwarden/common/platform/abstractions/log.service"; import { MessagingService } from "@bitwarden/common/platform/abstractions/messaging.service"; @@ -33,6 +32,7 @@ import { import { CsprngArray } from "@bitwarden/common/types/csprng"; import { UserId } from "@bitwarden/common/types/guid"; import { MasterKey, UserKey } from "@bitwarden/common/types/key"; +import { KeyService } from "@bitwarden/key-management"; import { LoginStrategyServiceAbstraction } from "../abstractions"; import { InternalUserDecryptionOptionsServiceAbstraction } from "../abstractions/user-decryption-options.service.abstraction"; @@ -63,7 +63,7 @@ describe("PasswordLoginStrategy", () => { let masterPasswordService: FakeMasterPasswordService; let loginStrategyService: MockProxy; - let cryptoService: MockProxy; + let keyService: MockProxy; let encryptService: MockProxy; let apiService: MockProxy; let tokenService: MockProxy; @@ -89,7 +89,7 @@ describe("PasswordLoginStrategy", () => { masterPasswordService = new FakeMasterPasswordService(); loginStrategyService = mock(); - cryptoService = mock(); + keyService = mock(); encryptService = mock(); apiService = mock(); tokenService = mock(); @@ -113,10 +113,10 @@ describe("PasswordLoginStrategy", () => { loginStrategyService.makePreloginKey.mockResolvedValue(masterKey); - cryptoService.hashMasterKey + keyService.hashMasterKey .calledWith(masterPassword, expect.anything(), undefined) .mockResolvedValue(hashedPassword); - cryptoService.hashMasterKey + keyService.hashMasterKey .calledWith(masterPassword, expect.anything(), HashPurpose.LocalAuthorization) .mockResolvedValue(localHashedPassword); @@ -129,7 +129,7 @@ describe("PasswordLoginStrategy", () => { loginStrategyService, accountService, masterPasswordService, - cryptoService, + keyService, encryptService, apiService, tokenService, @@ -198,12 +198,9 @@ describe("PasswordLoginStrategy", () => { localHashedPassword, userId, ); - expect(cryptoService.setMasterKeyEncryptedUserKey).toHaveBeenCalledWith( - tokenResponse.key, - userId, - ); - expect(cryptoService.setUserKey).toHaveBeenCalledWith(userKey, userId); - expect(cryptoService.setPrivateKey).toHaveBeenCalledWith(tokenResponse.privateKey, userId); + expect(keyService.setMasterKeyEncryptedUserKey).toHaveBeenCalledWith(tokenResponse.key, userId); + expect(keyService.setUserKey).toHaveBeenCalledWith(userKey, userId); + expect(keyService.setPrivateKey).toHaveBeenCalledWith(tokenResponse.privateKey, userId); }); it("does not force the user to update their master password when there are no requirements", async () => { diff --git a/libs/auth/src/common/login-strategies/password-login.strategy.ts b/libs/auth/src/common/login-strategies/password-login.strategy.ts index 7f73898ff6..55e869e822 100644 --- a/libs/auth/src/common/login-strategies/password-login.strategy.ts +++ b/libs/auth/src/common/login-strategies/password-login.strategy.ts @@ -83,15 +83,12 @@ export class PasswordLoginStrategy extends LoginStrategy { data.userEnteredEmail = email; // Hash the password early (before authentication) so we don't persist it in memory in plaintext - data.localMasterKeyHash = await this.cryptoService.hashMasterKey( + data.localMasterKeyHash = await this.keyService.hashMasterKey( masterPassword, data.masterKey, HashPurpose.LocalAuthorization, ); - const serverMasterKeyHash = await this.cryptoService.hashMasterKey( - masterPassword, - data.masterKey, - ); + const serverMasterKeyHash = await this.keyService.hashMasterKey(masterPassword, data.masterKey); data.tokenRequest = new PasswordTokenRequest( email, @@ -182,12 +179,12 @@ export class PasswordLoginStrategy extends LoginStrategy { if (this.encryptionKeyMigrationRequired(response)) { return; } - await this.cryptoService.setMasterKeyEncryptedUserKey(response.key, userId); + await this.keyService.setMasterKeyEncryptedUserKey(response.key, userId); const masterKey = await firstValueFrom(this.masterPasswordService.masterKey$(userId)); if (masterKey) { const userKey = await this.masterPasswordService.decryptUserKeyWithMasterKey(masterKey); - await this.cryptoService.setUserKey(userKey, userId); + await this.keyService.setUserKey(userKey, userId); } } @@ -195,7 +192,7 @@ export class PasswordLoginStrategy extends LoginStrategy { response: IdentityTokenResponse, userId: UserId, ): Promise { - await this.cryptoService.setPrivateKey( + await this.keyService.setPrivateKey( response.privateKey ?? (await this.createKeyPairForOldAccount(userId)), userId, ); diff --git a/libs/auth/src/common/login-strategies/sso-login.strategy.spec.ts b/libs/auth/src/common/login-strategies/sso-login.strategy.spec.ts index f5de10766c..d9827c2e28 100644 --- a/libs/auth/src/common/login-strategies/sso-login.strategy.spec.ts +++ b/libs/auth/src/common/login-strategies/sso-login.strategy.spec.ts @@ -16,7 +16,6 @@ import { BillingAccountProfileStateService } from "@bitwarden/common/billing/abs import { VaultTimeoutAction } from "@bitwarden/common/enums/vault-timeout-action.enum"; import { ErrorResponse } from "@bitwarden/common/models/response/error.response"; import { AppIdService } from "@bitwarden/common/platform/abstractions/app-id.service"; -import { CryptoService } from "@bitwarden/common/platform/abstractions/crypto.service"; import { EncryptService } from "@bitwarden/common/platform/abstractions/encrypt.service"; import { I18nService } from "@bitwarden/common/platform/abstractions/i18n.service"; import { LogService } from "@bitwarden/common/platform/abstractions/log.service"; @@ -30,6 +29,7 @@ import { FakeAccountService, mockAccountServiceWith } from "@bitwarden/common/sp import { CsprngArray } from "@bitwarden/common/types/csprng"; import { UserId } from "@bitwarden/common/types/guid"; import { DeviceKey, UserKey, MasterKey } from "@bitwarden/common/types/key"; +import { KeyService } from "@bitwarden/key-management"; import { AuthRequestServiceAbstraction, @@ -44,7 +44,7 @@ describe("SsoLoginStrategy", () => { let accountService: FakeAccountService; let masterPasswordService: FakeMasterPasswordService; - let cryptoService: MockProxy; + let keyService: MockProxy; let encryptService: MockProxy; let apiService: MockProxy; let tokenService: MockProxy; @@ -79,7 +79,7 @@ describe("SsoLoginStrategy", () => { accountService = mockAccountServiceWith(userId); masterPasswordService = new FakeMasterPasswordService(); - cryptoService = mock(); + keyService = mock(); encryptService = mock(); apiService = mock(); tokenService = mock(); @@ -127,7 +127,7 @@ describe("SsoLoginStrategy", () => { i18nService, accountService, masterPasswordService, - cryptoService, + keyService, encryptService, apiService, tokenService, @@ -174,8 +174,8 @@ describe("SsoLoginStrategy", () => { await ssoLoginStrategy.logIn(credentials); expect(masterPasswordService.mock.setMasterKey).not.toHaveBeenCalled(); - expect(cryptoService.setUserKey).not.toHaveBeenCalled(); - expect(cryptoService.setPrivateKey).not.toHaveBeenCalled(); + expect(keyService.setUserKey).not.toHaveBeenCalled(); + expect(keyService.setPrivateKey).not.toHaveBeenCalled(); }); it("sets master key encrypted user key for existing SSO users", async () => { @@ -187,11 +187,8 @@ describe("SsoLoginStrategy", () => { await ssoLoginStrategy.logIn(credentials); // Assert - expect(cryptoService.setMasterKeyEncryptedUserKey).toHaveBeenCalledTimes(1); - expect(cryptoService.setMasterKeyEncryptedUserKey).toHaveBeenCalledWith( - tokenResponse.key, - userId, - ); + expect(keyService.setMasterKeyEncryptedUserKey).toHaveBeenCalledTimes(1); + expect(keyService.setMasterKeyEncryptedUserKey).toHaveBeenCalledWith(tokenResponse.key, userId); }); describe("Trusted Device Decryption", () => { @@ -247,7 +244,7 @@ describe("SsoLoginStrategy", () => { deviceTrustService.getDeviceKey.mockResolvedValue(mockDeviceKey); deviceTrustService.decryptUserKeyWithDeviceKey.mockResolvedValue(mockUserKey); - const cryptoSvcSetUserKeySpy = jest.spyOn(cryptoService, "setUserKey"); + const cryptoSvcSetUserKeySpy = jest.spyOn(keyService, "setUserKey"); // Act await ssoLoginStrategy.logIn(credentials); @@ -274,7 +271,7 @@ describe("SsoLoginStrategy", () => { await ssoLoginStrategy.logIn(credentials); // Assert - expect(cryptoService.setUserKey).not.toHaveBeenCalled(); + expect(keyService.setUserKey).not.toHaveBeenCalled(); }); describe.each([ @@ -295,7 +292,7 @@ describe("SsoLoginStrategy", () => { await ssoLoginStrategy.logIn(credentials); // Assert - expect(cryptoService.setUserKey).not.toHaveBeenCalled(); + expect(keyService.setUserKey).not.toHaveBeenCalled(); }); }); @@ -314,7 +311,7 @@ describe("SsoLoginStrategy", () => { await ssoLoginStrategy.logIn(credentials); // Assert - expect(cryptoService.setUserKey).not.toHaveBeenCalled(); + expect(keyService.setUserKey).not.toHaveBeenCalled(); }); it("logs when a device key is found but no decryption keys were recieved in token response", async () => { @@ -365,7 +362,7 @@ describe("SsoLoginStrategy", () => { it("sets the user key using master key and hash from approved admin request if exists", async () => { apiService.postIdentityToken.mockResolvedValue(tokenResponse); - cryptoService.hasUserKey.mockResolvedValue(true); + keyService.hasUserKey.mockResolvedValue(true); const adminAuthResponse = { id: "1", publicKey: "PRIVATE" as any, @@ -383,7 +380,7 @@ describe("SsoLoginStrategy", () => { it("sets the user key from approved admin request if exists", async () => { apiService.postIdentityToken.mockResolvedValue(tokenResponse); - cryptoService.hasUserKey.mockResolvedValue(true); + keyService.hasUserKey.mockResolvedValue(true); const adminAuthResponse = { id: "1", publicKey: "PRIVATE" as any, @@ -400,7 +397,7 @@ describe("SsoLoginStrategy", () => { it("attempts to establish a trusted device if successful", async () => { apiService.postIdentityToken.mockResolvedValue(tokenResponse); - cryptoService.hasUserKey.mockResolvedValue(true); + keyService.hasUserKey.mockResolvedValue(true); const adminAuthResponse = { id: "1", publicKey: "PRIVATE" as any, @@ -438,7 +435,7 @@ describe("SsoLoginStrategy", () => { requestApproved: true, }; apiService.getAuthRequest.mockResolvedValue(adminAuthResponse as AuthRequestResponse); - cryptoService.hasUserKey.mockResolvedValue(false); + keyService.hasUserKey.mockResolvedValue(false); deviceTrustService.getDeviceKey.mockResolvedValue("DEVICE_KEY" as any); await ssoLoginStrategy.logIn(credentials); @@ -502,7 +499,7 @@ describe("SsoLoginStrategy", () => { undefined, undefined, ); - expect(cryptoService.setUserKey).toHaveBeenCalledWith(userKey, userId); + expect(keyService.setUserKey).toHaveBeenCalledWith(userKey, userId); }); }); @@ -558,7 +555,7 @@ describe("SsoLoginStrategy", () => { undefined, undefined, ); - expect(cryptoService.setUserKey).toHaveBeenCalledWith(userKey, userId); + expect(keyService.setUserKey).toHaveBeenCalledWith(userKey, userId); }); }); }); diff --git a/libs/auth/src/common/login-strategies/sso-login.strategy.ts b/libs/auth/src/common/login-strategies/sso-login.strategy.ts index 5ddf7428d2..d2660eef8a 100644 --- a/libs/auth/src/common/login-strategies/sso-login.strategy.ts +++ b/libs/auth/src/common/login-strategies/sso-login.strategy.ts @@ -192,7 +192,7 @@ export class SsoLoginStrategy extends LoginStrategy { if (masterKeyEncryptedUserKey) { // set the master key encrypted user key if it exists - await this.cryptoService.setMasterKeyEncryptedUserKey(masterKeyEncryptedUserKey, userId); + await this.keyService.setMasterKeyEncryptedUserKey(masterKeyEncryptedUserKey, userId); } const userDecryptionOptions = tokenResponse?.userDecryptionOptions; @@ -205,7 +205,7 @@ export class SsoLoginStrategy extends LoginStrategy { // Using it will clear it from state and future requests will use the device key. await this.trySetUserKeyWithApprovedAdminRequestIfExists(userId); - const hasUserKey = await this.cryptoService.hasUserKey(userId); + const hasUserKey = await this.keyService.hasUserKey(userId); // Only try to set user key with device key if admin approval request was not successful. if (!hasUserKey) { @@ -267,7 +267,7 @@ export class SsoLoginStrategy extends LoginStrategy { ); } - if (await this.cryptoService.hasUserKey()) { + if (await this.keyService.hasUserKey()) { // 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.deviceTrustService.trustDeviceIfRequired(userId); @@ -323,7 +323,7 @@ export class SsoLoginStrategy extends LoginStrategy { ); if (userKey) { - await this.cryptoService.setUserKey(userKey, userId); + await this.keyService.setUserKey(userKey, userId); } } @@ -339,7 +339,7 @@ export class SsoLoginStrategy extends LoginStrategy { } const userKey = await this.masterPasswordService.decryptUserKeyWithMasterKey(masterKey); - await this.cryptoService.setUserKey(userKey, userId); + await this.keyService.setUserKey(userKey, userId); } protected override async setPrivateKey( @@ -349,7 +349,7 @@ export class SsoLoginStrategy extends LoginStrategy { const newSsoUser = tokenResponse.key == null; if (!newSsoUser) { - await this.cryptoService.setPrivateKey( + await this.keyService.setPrivateKey( tokenResponse.privateKey ?? (await this.createKeyPairForOldAccount(userId)), userId, ); diff --git a/libs/auth/src/common/login-strategies/user-api-login.strategy.spec.ts b/libs/auth/src/common/login-strategies/user-api-login.strategy.spec.ts index d299a8e0ce..14fafcb58c 100644 --- a/libs/auth/src/common/login-strategies/user-api-login.strategy.spec.ts +++ b/libs/auth/src/common/login-strategies/user-api-login.strategy.spec.ts @@ -10,7 +10,6 @@ import { FakeMasterPasswordService } from "@bitwarden/common/auth/services/maste import { BillingAccountProfileStateService } from "@bitwarden/common/billing/abstractions/account/billing-account-profile-state.service"; import { VaultTimeoutAction } from "@bitwarden/common/enums/vault-timeout-action.enum"; import { AppIdService } from "@bitwarden/common/platform/abstractions/app-id.service"; -import { CryptoService } from "@bitwarden/common/platform/abstractions/crypto.service"; import { EncryptService } from "@bitwarden/common/platform/abstractions/encrypt.service"; import { Environment, @@ -27,6 +26,7 @@ import { FakeAccountService, mockAccountServiceWith } from "@bitwarden/common/sp import { CsprngArray } from "@bitwarden/common/types/csprng"; import { UserId } from "@bitwarden/common/types/guid"; import { UserKey, MasterKey } from "@bitwarden/common/types/key"; +import { KeyService } from "@bitwarden/key-management"; import { InternalUserDecryptionOptionsServiceAbstraction } from "../abstractions/user-decryption-options.service.abstraction"; import { UserApiLoginCredentials } from "../models/domain/login-credentials"; @@ -39,7 +39,7 @@ describe("UserApiLoginStrategy", () => { let accountService: FakeAccountService; let masterPasswordService: FakeMasterPasswordService; - let cryptoService: MockProxy; + let keyService: MockProxy; let encryptService: MockProxy; let apiService: MockProxy; let tokenService: MockProxy; @@ -72,7 +72,7 @@ describe("UserApiLoginStrategy", () => { accountService = mockAccountServiceWith(userId); masterPasswordService = new FakeMasterPasswordService(); - cryptoService = mock(); + keyService = mock(); apiService = mock(); tokenService = mock(); appIdService = mock(); @@ -100,7 +100,7 @@ describe("UserApiLoginStrategy", () => { keyConnectorService, accountService, masterPasswordService, - cryptoService, + keyService, encryptService, apiService, tokenService, @@ -175,11 +175,8 @@ describe("UserApiLoginStrategy", () => { await apiLogInStrategy.logIn(credentials); - expect(cryptoService.setMasterKeyEncryptedUserKey).toHaveBeenCalledWith( - tokenResponse.key, - userId, - ); - expect(cryptoService.setPrivateKey).toHaveBeenCalledWith(tokenResponse.privateKey, userId); + expect(keyService.setMasterKeyEncryptedUserKey).toHaveBeenCalledWith(tokenResponse.key, userId); + expect(keyService.setPrivateKey).toHaveBeenCalledWith(tokenResponse.privateKey, userId); }); it("gets and sets the master key if Key Connector is enabled", async () => { @@ -219,6 +216,6 @@ describe("UserApiLoginStrategy", () => { undefined, undefined, ); - expect(cryptoService.setUserKey).toHaveBeenCalledWith(userKey, userId); + expect(keyService.setUserKey).toHaveBeenCalledWith(userKey, userId); }); }); diff --git a/libs/auth/src/common/login-strategies/user-api-login.strategy.ts b/libs/auth/src/common/login-strategies/user-api-login.strategy.ts index 3b112c79a0..4ae95fdbc7 100644 --- a/libs/auth/src/common/login-strategies/user-api-login.strategy.ts +++ b/libs/auth/src/common/login-strategies/user-api-login.strategy.ts @@ -64,13 +64,13 @@ export class UserApiLoginStrategy extends LoginStrategy { response: IdentityTokenResponse, userId: UserId, ): Promise { - await this.cryptoService.setMasterKeyEncryptedUserKey(response.key, userId); + await this.keyService.setMasterKeyEncryptedUserKey(response.key, userId); if (response.apiUseKeyConnector) { const masterKey = await firstValueFrom(this.masterPasswordService.masterKey$(userId)); if (masterKey) { const userKey = await this.masterPasswordService.decryptUserKeyWithMasterKey(masterKey); - await this.cryptoService.setUserKey(userKey, userId); + await this.keyService.setUserKey(userKey, userId); } } } @@ -79,7 +79,7 @@ export class UserApiLoginStrategy extends LoginStrategy { response: IdentityTokenResponse, userId: UserId, ): Promise { - await this.cryptoService.setPrivateKey( + await this.keyService.setPrivateKey( response.privateKey ?? (await this.createKeyPairForOldAccount(userId)), userId, ); diff --git a/libs/auth/src/common/login-strategies/webauthn-login.strategy.spec.ts b/libs/auth/src/common/login-strategies/webauthn-login.strategy.spec.ts index e4b1f74031..88392b57c5 100644 --- a/libs/auth/src/common/login-strategies/webauthn-login.strategy.spec.ts +++ b/libs/auth/src/common/login-strategies/webauthn-login.strategy.spec.ts @@ -13,7 +13,6 @@ import { WebAuthnLoginAssertionResponseRequest } from "@bitwarden/common/auth/se import { BillingAccountProfileStateService } from "@bitwarden/common/billing/abstractions/account/billing-account-profile-state.service"; import { VaultTimeoutAction } from "@bitwarden/common/enums/vault-timeout-action.enum"; import { AppIdService } from "@bitwarden/common/platform/abstractions/app-id.service"; -import { CryptoService } from "@bitwarden/common/platform/abstractions/crypto.service"; import { EncryptService } from "@bitwarden/common/platform/abstractions/encrypt.service"; import { LogService } from "@bitwarden/common/platform/abstractions/log.service"; import { MessagingService } from "@bitwarden/common/platform/abstractions/messaging.service"; @@ -25,6 +24,7 @@ import { VaultTimeoutSettingsService } from "@bitwarden/common/services/vault-ti import { FakeAccountService, mockAccountServiceWith } from "@bitwarden/common/spec"; import { UserId } from "@bitwarden/common/types/guid"; import { PrfKey, UserKey } from "@bitwarden/common/types/key"; +import { KeyService } from "@bitwarden/key-management"; import { InternalUserDecryptionOptionsServiceAbstraction } from "../abstractions/user-decryption-options.service.abstraction"; import { WebAuthnLoginCredentials } from "../models/domain/login-credentials"; @@ -37,7 +37,7 @@ describe("WebAuthnLoginStrategy", () => { let accountService: FakeAccountService; let masterPasswordService: FakeMasterPasswordService; - let cryptoService!: MockProxy; + let keyService!: MockProxy; let encryptService!: MockProxy; let apiService!: MockProxy; let tokenService!: MockProxy; @@ -80,7 +80,7 @@ describe("WebAuthnLoginStrategy", () => { accountService = mockAccountServiceWith(userId); masterPasswordService = new FakeMasterPasswordService(); - cryptoService = mock(); + keyService = mock(); encryptService = mock(); apiService = mock(); tokenService = mock(); @@ -105,7 +105,7 @@ describe("WebAuthnLoginStrategy", () => { cache, accountService, masterPasswordService, - cryptoService, + keyService, encryptService, apiService, tokenService, @@ -233,8 +233,8 @@ describe("WebAuthnLoginStrategy", () => { // Assert // Master key encrypted user key should be set - expect(cryptoService.setMasterKeyEncryptedUserKey).toHaveBeenCalledTimes(1); - expect(cryptoService.setMasterKeyEncryptedUserKey).toHaveBeenCalledWith( + expect(keyService.setMasterKeyEncryptedUserKey).toHaveBeenCalledTimes(1); + expect(keyService.setMasterKeyEncryptedUserKey).toHaveBeenCalledWith( idTokenResponse.key, userId, ); @@ -249,8 +249,8 @@ describe("WebAuthnLoginStrategy", () => { idTokenResponse.userDecryptionOptions.webAuthnPrfOption.encryptedUserKey, mockPrfPrivateKey, ); - expect(cryptoService.setUserKey).toHaveBeenCalledWith(mockUserKey, userId); - expect(cryptoService.setPrivateKey).toHaveBeenCalledWith(idTokenResponse.privateKey, userId); + expect(keyService.setUserKey).toHaveBeenCalledWith(mockUserKey, userId); + expect(keyService.setPrivateKey).toHaveBeenCalledWith(idTokenResponse.privateKey, userId); // Master key and private key should not be set expect(masterPasswordService.mock.setMasterKey).not.toHaveBeenCalled(); @@ -274,7 +274,7 @@ describe("WebAuthnLoginStrategy", () => { // Assert expect(encryptService.decryptToBytes).not.toHaveBeenCalled(); expect(encryptService.rsaDecrypt).not.toHaveBeenCalled(); - expect(cryptoService.setUserKey).not.toHaveBeenCalled(); + expect(keyService.setUserKey).not.toHaveBeenCalled(); }); describe.each([ @@ -294,7 +294,7 @@ describe("WebAuthnLoginStrategy", () => { await webAuthnLoginStrategy.logIn(webAuthnCredentials); // Assert - expect(cryptoService.setUserKey).not.toHaveBeenCalled(); + expect(keyService.setUserKey).not.toHaveBeenCalled(); }); }); @@ -313,7 +313,7 @@ describe("WebAuthnLoginStrategy", () => { await webAuthnLoginStrategy.logIn(webAuthnCredentials); // Assert - expect(cryptoService.setUserKey).not.toHaveBeenCalled(); + expect(keyService.setUserKey).not.toHaveBeenCalled(); }); it("does not set the user key when the encrypted user key decryption fails", async () => { @@ -331,7 +331,7 @@ describe("WebAuthnLoginStrategy", () => { await webAuthnLoginStrategy.logIn(webAuthnCredentials); // Assert - expect(cryptoService.setUserKey).not.toHaveBeenCalled(); + expect(keyService.setUserKey).not.toHaveBeenCalled(); }); }); diff --git a/libs/auth/src/common/login-strategies/webauthn-login.strategy.ts b/libs/auth/src/common/login-strategies/webauthn-login.strategy.ts index c5451d13df..df67108098 100644 --- a/libs/auth/src/common/login-strategies/webauthn-login.strategy.ts +++ b/libs/auth/src/common/login-strategies/webauthn-login.strategy.ts @@ -66,7 +66,7 @@ export class WebAuthnLoginStrategy extends LoginStrategy { if (masterKeyEncryptedUserKey) { // set the master key encrypted user key if it exists - await this.cryptoService.setMasterKeyEncryptedUserKey(masterKeyEncryptedUserKey, userId); + await this.keyService.setMasterKeyEncryptedUserKey(masterKeyEncryptedUserKey, userId); } const userDecryptionOptions = idTokenResponse?.userDecryptionOptions; @@ -93,7 +93,7 @@ export class WebAuthnLoginStrategy extends LoginStrategy { ); if (userKey) { - await this.cryptoService.setUserKey(new SymmetricCryptoKey(userKey) as UserKey, userId); + await this.keyService.setUserKey(new SymmetricCryptoKey(userKey) as UserKey, userId); } } } @@ -102,7 +102,7 @@ export class WebAuthnLoginStrategy extends LoginStrategy { response: IdentityTokenResponse, userId: UserId, ): Promise { - await this.cryptoService.setPrivateKey( + await this.keyService.setPrivateKey( response.privateKey ?? (await this.createKeyPairForOldAccount(userId)), userId, ); diff --git a/libs/auth/src/common/services/auth-request/auth-request.service.spec.ts b/libs/auth/src/common/services/auth-request/auth-request.service.spec.ts index 58dbae6d78..a4f1d5d972 100644 --- a/libs/auth/src/common/services/auth-request/auth-request.service.spec.ts +++ b/libs/auth/src/common/services/auth-request/auth-request.service.spec.ts @@ -5,7 +5,6 @@ import { AuthRequestResponse } from "@bitwarden/common/auth/models/response/auth import { FakeMasterPasswordService } from "@bitwarden/common/auth/services/master-password/fake-master-password.service"; import { AuthRequestPushNotification } from "@bitwarden/common/models/response/notification.response"; import { AppIdService } from "@bitwarden/common/platform/abstractions/app-id.service"; -import { CryptoService } from "@bitwarden/common/platform/abstractions/crypto.service"; import { EncryptService } from "@bitwarden/common/platform/abstractions/encrypt.service"; import { Utils } from "@bitwarden/common/platform/misc/utils"; import { EncString } from "@bitwarden/common/platform/models/domain/enc-string"; @@ -14,6 +13,7 @@ import { StateProvider } from "@bitwarden/common/platform/state"; import { FakeAccountService, mockAccountServiceWith } from "@bitwarden/common/spec"; import { UserId } from "@bitwarden/common/types/guid"; import { MasterKey, UserKey } from "@bitwarden/common/types/key"; +import { KeyService } from "@bitwarden/key-management"; import { AuthRequestService } from "./auth-request.service"; @@ -24,7 +24,7 @@ describe("AuthRequestService", () => { let accountService: FakeAccountService; let masterPasswordService: FakeMasterPasswordService; const appIdService = mock(); - const cryptoService = mock(); + const keyService = mock(); const encryptService = mock(); const apiService = mock(); @@ -41,7 +41,7 @@ describe("AuthRequestService", () => { appIdService, accountService, masterPasswordService, - cryptoService, + keyService, encryptService, apiService, stateProvider, @@ -115,7 +115,7 @@ describe("AuthRequestService", () => { }); it("should use the user key if the master key and hash do not exist", async () => { - cryptoService.getUserKey.mockResolvedValueOnce({ key: new Uint8Array(64) } as UserKey); + keyService.getUserKey.mockResolvedValueOnce({ key: new Uint8Array(64) } as UserKey); await sut.approveOrDenyAuthRequest( true, @@ -135,7 +135,7 @@ describe("AuthRequestService", () => { const mockDecryptedUserKey = {} as UserKey; jest.spyOn(sut, "decryptPubKeyEncryptedUserKey").mockResolvedValueOnce(mockDecryptedUserKey); - cryptoService.setUserKey.mockResolvedValueOnce(undefined); + keyService.setUserKey.mockResolvedValueOnce(undefined); // Act await sut.setUserKeyAfterDecryptingSharedUserKey( @@ -149,7 +149,7 @@ describe("AuthRequestService", () => { mockAuthReqResponse.key, mockPrivateKey, ); - expect(cryptoService.setUserKey).toBeCalledWith(mockDecryptedUserKey, mockUserId); + expect(keyService.setUserKey).toBeCalledWith(mockDecryptedUserKey, mockUserId); }); }); @@ -175,7 +175,7 @@ describe("AuthRequestService", () => { masterPasswordService.mock.decryptUserKeyWithMasterKey.mockResolvedValue( mockDecryptedUserKey, ); - cryptoService.setUserKey.mockResolvedValueOnce(undefined); + keyService.setUserKey.mockResolvedValueOnce(undefined); // Act await sut.setKeysAfterDecryptingSharedMasterKeyAndHash( @@ -203,7 +203,7 @@ describe("AuthRequestService", () => { undefined, undefined, ); - expect(cryptoService.setUserKey).toHaveBeenCalledWith(mockDecryptedUserKey, mockUserId); + expect(keyService.setUserKey).toHaveBeenCalledWith(mockDecryptedUserKey, mockUserId); }); }); diff --git a/libs/auth/src/common/services/auth-request/auth-request.service.ts b/libs/auth/src/common/services/auth-request/auth-request.service.ts index 51926d6598..0e416a4a25 100644 --- a/libs/auth/src/common/services/auth-request/auth-request.service.ts +++ b/libs/auth/src/common/services/auth-request/auth-request.service.ts @@ -9,7 +9,6 @@ import { PasswordlessAuthRequest } from "@bitwarden/common/auth/models/request/p import { AuthRequestResponse } from "@bitwarden/common/auth/models/response/auth-request.response"; import { AuthRequestPushNotification } from "@bitwarden/common/models/response/notification.response"; import { AppIdService } from "@bitwarden/common/platform/abstractions/app-id.service"; -import { CryptoService } from "@bitwarden/common/platform/abstractions/crypto.service"; import { EncryptService } from "@bitwarden/common/platform/abstractions/encrypt.service"; import { Utils } from "@bitwarden/common/platform/misc/utils"; import { EncString } from "@bitwarden/common/platform/models/domain/enc-string"; @@ -21,6 +20,7 @@ import { } from "@bitwarden/common/platform/state"; import { UserId } from "@bitwarden/common/types/guid"; import { MasterKey, UserKey } from "@bitwarden/common/types/key"; +import { KeyService } from "@bitwarden/key-management"; import { AuthRequestServiceAbstraction } from "../../abstractions/auth-request.service.abstraction"; @@ -45,7 +45,7 @@ export class AuthRequestService implements AuthRequestServiceAbstraction { private appIdService: AppIdService, private accountService: AccountService, private masterPasswordService: InternalMasterPasswordServiceAbstraction, - private cryptoService: CryptoService, + private keyService: KeyService, private encryptService: EncryptService, private apiService: ApiService, private stateProvider: StateProvider, @@ -111,7 +111,7 @@ export class AuthRequestService implements AuthRequestServiceAbstraction { ); keyToEncrypt = masterKey.encKey; } else { - const userKey = await this.cryptoService.getUserKey(); + const userKey = await this.keyService.getUserKey(); keyToEncrypt = userKey.key; } @@ -135,7 +135,7 @@ export class AuthRequestService implements AuthRequestServiceAbstraction { authReqResponse.key, authReqPrivateKey, ); - await this.cryptoService.setUserKey(userKey, userId); + await this.keyService.setUserKey(userKey, userId); } async setKeysAfterDecryptingSharedMasterKeyAndHash( @@ -156,7 +156,7 @@ export class AuthRequestService implements AuthRequestServiceAbstraction { await this.masterPasswordService.setMasterKey(masterKey, userId); await this.masterPasswordService.setMasterKeyHash(masterKeyHash, userId); - await this.cryptoService.setUserKey(userKey, userId); + await this.keyService.setUserKey(userKey, userId); } // Decryption helpers @@ -203,6 +203,6 @@ export class AuthRequestService implements AuthRequestServiceAbstraction { } async getFingerprintPhrase(email: string, publicKey: Uint8Array): Promise { - return (await this.cryptoService.getFingerprint(email.toLowerCase(), publicKey)).join("-"); + return (await this.keyService.getFingerprint(email.toLowerCase(), publicKey)).join("-"); } } diff --git a/libs/auth/src/common/services/login-strategies/login-strategy.service.spec.ts b/libs/auth/src/common/services/login-strategies/login-strategy.service.spec.ts index 14662bb4b8..8647260ce5 100644 --- a/libs/auth/src/common/services/login-strategies/login-strategy.service.spec.ts +++ b/libs/auth/src/common/services/login-strategies/login-strategy.service.spec.ts @@ -20,7 +20,6 @@ import { FakeMasterPasswordService } from "@bitwarden/common/auth/services/maste import { BillingAccountProfileStateService } from "@bitwarden/common/billing/abstractions/account/billing-account-profile-state.service"; import { VaultTimeoutAction } from "@bitwarden/common/enums/vault-timeout-action.enum"; import { AppIdService } from "@bitwarden/common/platform/abstractions/app-id.service"; -import { CryptoService } from "@bitwarden/common/platform/abstractions/crypto.service"; import { EncryptService } from "@bitwarden/common/platform/abstractions/encrypt.service"; import { EnvironmentService } from "@bitwarden/common/platform/abstractions/environment.service"; import { I18nService } from "@bitwarden/common/platform/abstractions/i18n.service"; @@ -38,6 +37,7 @@ import { } from "@bitwarden/common/spec"; import { PasswordStrengthServiceAbstraction } from "@bitwarden/common/tools/password-strength"; import { UserId } from "@bitwarden/common/types/guid"; +import { KeyService } from "@bitwarden/key-management"; import { AuthRequestServiceAbstraction, @@ -54,7 +54,7 @@ describe("LoginStrategyService", () => { let accountService: FakeAccountService; let masterPasswordService: FakeMasterPasswordService; - let cryptoService: MockProxy; + let keyService: MockProxy; let apiService: MockProxy; let tokenService: MockProxy; let appIdService: MockProxy; @@ -85,7 +85,7 @@ describe("LoginStrategyService", () => { beforeEach(() => { accountService = mockAccountServiceWith(userId); masterPasswordService = new FakeMasterPasswordService(); - cryptoService = mock(); + keyService = mock(); apiService = mock(); tokenService = mock(); appIdService = mock(); @@ -112,7 +112,7 @@ describe("LoginStrategyService", () => { sut = new LoginStrategyService( accountService, masterPasswordService, - cryptoService, + keyService, apiService, tokenService, appIdService, diff --git a/libs/auth/src/common/services/login-strategies/login-strategy.service.ts b/libs/auth/src/common/services/login-strategies/login-strategy.service.ts index 35f2b90bbd..721ee98497 100644 --- a/libs/auth/src/common/services/login-strategies/login-strategy.service.ts +++ b/libs/auth/src/common/services/login-strategies/login-strategy.service.ts @@ -29,7 +29,6 @@ import { BillingAccountProfileStateService } from "@bitwarden/common/billing/abs import { PreloginRequest } from "@bitwarden/common/models/request/prelogin.request"; import { ErrorResponse } from "@bitwarden/common/models/response/error.response"; import { AppIdService } from "@bitwarden/common/platform/abstractions/app-id.service"; -import { CryptoService } from "@bitwarden/common/platform/abstractions/crypto.service"; import { EncryptService } from "@bitwarden/common/platform/abstractions/encrypt.service"; import { EnvironmentService } from "@bitwarden/common/platform/abstractions/environment.service"; import { I18nService } from "@bitwarden/common/platform/abstractions/i18n.service"; @@ -43,6 +42,7 @@ import { GlobalState, GlobalStateProvider } from "@bitwarden/common/platform/sta import { DeviceTrustServiceAbstraction } from "@bitwarden/common/src/auth/abstractions/device-trust.service.abstraction"; import { PasswordStrengthServiceAbstraction } from "@bitwarden/common/tools/password-strength"; import { MasterKey } from "@bitwarden/common/types/key"; +import { KeyService } from "@bitwarden/key-management"; import { AuthRequestServiceAbstraction, LoginStrategyServiceAbstraction } from "../../abstractions"; import { InternalUserDecryptionOptionsServiceAbstraction } from "../../abstractions/user-decryption-options.service.abstraction"; @@ -91,7 +91,7 @@ export class LoginStrategyService implements LoginStrategyServiceAbstraction { constructor( protected accountService: AccountService, protected masterPasswordService: InternalMasterPasswordServiceAbstraction, - protected cryptoService: CryptoService, + protected keyService: KeyService, protected apiService: ApiService, protected tokenService: TokenService, protected appIdService: AppIdService, @@ -267,7 +267,7 @@ export class LoginStrategyService implements LoginStrategyServiceAbstraction { kdfConfig.validateKdfConfigForPrelogin(); - return await this.cryptoService.makeMasterKey(masterPassword, email, kdfConfig); + return await this.keyService.makeMasterKey(masterPassword, email, kdfConfig); } private async clearCache(): Promise { @@ -319,7 +319,7 @@ export class LoginStrategyService implements LoginStrategyServiceAbstraction { const sharedDeps: ConstructorParameters = [ this.accountService, this.masterPasswordService, - this.cryptoService, + this.keyService, this.encryptService, this.apiService, this.tokenService, diff --git a/libs/common/src/auth/abstractions/webauthn/webauthn-login-prf-crypto.service.abstraction.ts b/libs/common/src/auth/abstractions/webauthn/webauthn-login-prf-key.service.abstraction.ts similarity index 88% rename from libs/common/src/auth/abstractions/webauthn/webauthn-login-prf-crypto.service.abstraction.ts rename to libs/common/src/auth/abstractions/webauthn/webauthn-login-prf-key.service.abstraction.ts index b2c59e76af..c3c0946609 100644 --- a/libs/common/src/auth/abstractions/webauthn/webauthn-login-prf-crypto.service.abstraction.ts +++ b/libs/common/src/auth/abstractions/webauthn/webauthn-login-prf-key.service.abstraction.ts @@ -3,7 +3,7 @@ import { PrfKey } from "../../../types/key"; /** * Contains methods for all crypto operations specific to the WebAuthn login flow. */ -export abstract class WebAuthnLoginPrfCryptoServiceAbstraction { +export abstract class WebAuthnLoginPrfKeyServiceAbstraction { /** * Get the salt used to generate the PRF-output used when logging in with WebAuthn. */ diff --git a/libs/common/src/auth/services/auth.service.spec.ts b/libs/common/src/auth/services/auth.service.spec.ts index 9a93a4207b..5663384714 100644 --- a/libs/common/src/auth/services/auth.service.spec.ts +++ b/libs/common/src/auth/services/auth.service.spec.ts @@ -1,6 +1,7 @@ import { MockProxy, mock } from "jest-mock-extended"; import { firstValueFrom, of } from "rxjs"; +import { KeyService } from "../../../../key-management/src/abstractions/key.service"; import { FakeAccountService, makeStaticByteArray, @@ -8,7 +9,6 @@ import { trackEmissions, } from "../../../spec"; import { ApiService } from "../../abstractions/api.service"; -import { CryptoService } from "../../platform/abstractions/crypto.service"; import { MessagingService } from "../../platform/abstractions/messaging.service"; import { StateService } from "../../platform/abstractions/state.service"; import { Utils } from "../../platform/misc/utils"; @@ -25,7 +25,7 @@ describe("AuthService", () => { let accountService: FakeAccountService; let messagingService: MockProxy; - let cryptoService: MockProxy; + let keyService: MockProxy; let apiService: MockProxy; let stateService: MockProxy; let tokenService: MockProxy; @@ -36,7 +36,7 @@ describe("AuthService", () => { beforeEach(() => { accountService = mockAccountServiceWith(userId); messagingService = mock(); - cryptoService = mock(); + keyService = mock(); apiService = mock(); stateService = mock(); tokenService = mock(); @@ -44,7 +44,7 @@ describe("AuthService", () => { sut = new AuthService( accountService, messagingService, - cryptoService, + keyService, apiService, stateService, tokenService, @@ -63,7 +63,7 @@ describe("AuthService", () => { beforeEach(() => { accountService.activeAccountSubject.next(accountInfo); tokenService.hasAccessToken$.mockReturnValue(of(true)); - cryptoService.getInMemoryUserKeyFor$.mockReturnValue(of(undefined)); + keyService.getInMemoryUserKeyFor$.mockReturnValue(of(undefined)); }); it("emits LoggedOut when there is no active account", async () => { @@ -84,7 +84,7 @@ describe("AuthService", () => { it("emits LoggedOut when there is no access token but has a user key", async () => { tokenService.hasAccessToken$.mockReturnValue(of(false)); - cryptoService.getInMemoryUserKeyFor$.mockReturnValue(of(userKey)); + keyService.getInMemoryUserKeyFor$.mockReturnValue(of(userKey)); expect(await firstValueFrom(sut.activeAccountStatus$)).toEqual( AuthenticationStatus.LoggedOut, @@ -93,14 +93,14 @@ describe("AuthService", () => { it("emits Locked when there is an access token and no user key", async () => { tokenService.hasAccessToken$.mockReturnValue(of(true)); - cryptoService.getInMemoryUserKeyFor$.mockReturnValue(of(undefined)); + keyService.getInMemoryUserKeyFor$.mockReturnValue(of(undefined)); expect(await firstValueFrom(sut.activeAccountStatus$)).toEqual(AuthenticationStatus.Locked); }); it("emits Unlocked when there is an access token and user key", async () => { tokenService.hasAccessToken$.mockReturnValue(of(true)); - cryptoService.getInMemoryUserKeyFor$.mockReturnValue(of(userKey)); + keyService.getInMemoryUserKeyFor$.mockReturnValue(of(userKey)); expect(await firstValueFrom(sut.activeAccountStatus$)).toEqual(AuthenticationStatus.Unlocked); }); @@ -117,7 +117,7 @@ describe("AuthService", () => { const emissions = trackEmissions(sut.activeAccountStatus$); tokenService.hasAccessToken$.mockReturnValue(of(true)); - cryptoService.getInMemoryUserKeyFor$.mockReturnValue(of(userKey)); + keyService.getInMemoryUserKeyFor$.mockReturnValue(of(userKey)); accountService.activeAccountSubject.next(accountInfo2); expect(emissions).toEqual([AuthenticationStatus.Locked, AuthenticationStatus.Unlocked]); @@ -150,7 +150,7 @@ describe("AuthService", () => { describe("authStatusFor$", () => { beforeEach(() => { tokenService.hasAccessToken$.mockReturnValue(of(true)); - cryptoService.getInMemoryUserKeyFor$.mockReturnValue(of(undefined)); + keyService.getInMemoryUserKeyFor$.mockReturnValue(of(undefined)); }); it.each([null, undefined, "not a userId"])( @@ -172,14 +172,14 @@ describe("AuthService", () => { it("emits Locked when there is an access token and no user key", async () => { tokenService.hasAccessToken$.mockReturnValue(of(true)); - cryptoService.getInMemoryUserKeyFor$.mockReturnValue(of(undefined)); + keyService.getInMemoryUserKeyFor$.mockReturnValue(of(undefined)); expect(await firstValueFrom(sut.authStatusFor$(userId))).toEqual(AuthenticationStatus.Locked); }); it("emits Unlocked when there is an access token and user key", async () => { tokenService.hasAccessToken$.mockReturnValue(of(true)); - cryptoService.getInMemoryUserKeyFor$.mockReturnValue(of(userKey)); + keyService.getInMemoryUserKeyFor$.mockReturnValue(of(userKey)); expect(await firstValueFrom(sut.authStatusFor$(userId))).toEqual( AuthenticationStatus.Unlocked, diff --git a/libs/common/src/auth/services/auth.service.ts b/libs/common/src/auth/services/auth.service.ts index 307da55a5e..2b8cd7919f 100644 --- a/libs/common/src/auth/services/auth.service.ts +++ b/libs/common/src/auth/services/auth.service.ts @@ -9,8 +9,8 @@ import { switchMap, } from "rxjs"; +import { KeyService } from "../../../../key-management/src/abstractions/key.service"; import { ApiService } from "../../abstractions/api.service"; -import { CryptoService } from "../../platform/abstractions/crypto.service"; import { StateService } from "../../platform/abstractions/state.service"; import { MessageSender } from "../../platform/messaging"; import { Utils } from "../../platform/misc/utils"; @@ -27,7 +27,7 @@ export class AuthService implements AuthServiceAbstraction { constructor( protected accountService: AccountService, protected messageSender: MessageSender, - protected cryptoService: CryptoService, + protected keyService: KeyService, protected apiService: ApiService, protected stateService: StateService, private tokenService: TokenService, @@ -69,7 +69,7 @@ export class AuthService implements AuthServiceAbstraction { } return combineLatest([ - this.cryptoService.getInMemoryUserKeyFor$(userId), + this.keyService.getInMemoryUserKeyFor$(userId), this.tokenService.hasAccessToken$(userId), ]).pipe( map(([userKey, hasAccessToken]) => { diff --git a/libs/common/src/auth/services/device-trust.service.implementation.ts b/libs/common/src/auth/services/device-trust.service.implementation.ts index 178f4b0654..88963c524c 100644 --- a/libs/common/src/auth/services/device-trust.service.implementation.ts +++ b/libs/common/src/auth/services/device-trust.service.implementation.ts @@ -2,10 +2,10 @@ import { firstValueFrom, map, Observable } from "rxjs"; import { UserDecryptionOptionsServiceAbstraction } from "@bitwarden/auth/common"; +import { KeyService } from "../../../../key-management/src/abstractions/key.service"; import { AppIdService } from "../../platform/abstractions/app-id.service"; import { ConfigService } from "../../platform/abstractions/config/config.service"; import { CryptoFunctionService } from "../../platform/abstractions/crypto-function.service"; -import { CryptoService } from "../../platform/abstractions/crypto.service"; import { EncryptService } from "../../platform/abstractions/encrypt.service"; import { I18nService } from "../../platform/abstractions/i18n.service"; import { KeyGenerationService } from "../../platform/abstractions/key-generation.service"; @@ -64,7 +64,7 @@ export class DeviceTrustService implements DeviceTrustServiceAbstraction { constructor( private keyGenerationService: KeyGenerationService, private cryptoFunctionService: CryptoFunctionService, - private cryptoService: CryptoService, + private keyService: KeyService, private encryptService: EncryptService, private appIdService: AppIdService, private devicesApiService: DevicesApiServiceAbstraction, @@ -124,7 +124,7 @@ export class DeviceTrustService implements DeviceTrustServiceAbstraction { } // Attempt to get user key - const userKey: UserKey = await this.cryptoService.getUserKey(userId); + const userKey: UserKey = await this.keyService.getUserKey(userId); // If user key is not found, throw error if (!userKey) { @@ -187,7 +187,7 @@ export class DeviceTrustService implements DeviceTrustServiceAbstraction { } // At this point of rotating their keys, they should still have their old user key in state - const oldUserKey = await firstValueFrom(this.cryptoService.userKey$(userId)); + const oldUserKey = await firstValueFrom(this.keyService.userKey$(userId)); const deviceIdentifier = await this.appIdService.getAppId(); const secretVerificationRequest = new SecretVerificationRequest(); diff --git a/libs/common/src/auth/services/device-trust.service.spec.ts b/libs/common/src/auth/services/device-trust.service.spec.ts index 1171ae2918..66a91a693e 100644 --- a/libs/common/src/auth/services/device-trust.service.spec.ts +++ b/libs/common/src/auth/services/device-trust.service.spec.ts @@ -4,6 +4,7 @@ import { BehaviorSubject, of } from "rxjs"; import { UserDecryptionOptionsServiceAbstraction } from "@bitwarden/auth/common"; import { UserDecryptionOptions } from "../../../../auth/src/common/models/domain/user-decryption-options"; +import { KeyService } from "../../../../key-management/src/abstractions/key.service"; import { FakeAccountService, mockAccountServiceWith } from "../../../spec/fake-account-service"; import { FakeActiveUserState } from "../../../spec/fake-state"; import { FakeStateProvider } from "../../../spec/fake-state-provider"; @@ -11,7 +12,6 @@ import { DeviceType } from "../../enums"; import { AppIdService } from "../../platform/abstractions/app-id.service"; import { ConfigService } from "../../platform/abstractions/config/config.service"; import { CryptoFunctionService } from "../../platform/abstractions/crypto-function.service"; -import { CryptoService } from "../../platform/abstractions/crypto.service"; import { EncryptService } from "../../platform/abstractions/encrypt.service"; import { I18nService } from "../../platform/abstractions/i18n.service"; import { KeyGenerationService } from "../../platform/abstractions/key-generation.service"; @@ -43,7 +43,7 @@ describe("deviceTrustService", () => { const keyGenerationService = mock(); const cryptoFunctionService = mock(); - const cryptoService = mock(); + const keyService = mock(); const encryptService = mock(); const appIdService = mock(); const devicesApiService = mock(); @@ -368,7 +368,7 @@ describe("deviceTrustService", () => { .mockResolvedValue(mockDeviceRsaKeyPair); cryptoSvcGetUserKeySpy = jest - .spyOn(cryptoService, "getUserKey") + .spyOn(keyService, "getUserKey") .mockResolvedValue(mockUserKey); cryptoSvcRsaEncryptSpy = jest @@ -623,7 +623,7 @@ describe("deviceTrustService", () => { const fakeNewUserKeyData = new Uint8Array(64); fakeNewUserKeyData.fill(FakeNewUserKeyMarker, 0, 1); fakeNewUserKey = new SymmetricCryptoKey(fakeNewUserKeyData) as UserKey; - cryptoService.userKey$.mockReturnValue(of(fakeNewUserKey)); + keyService.userKey$.mockReturnValue(of(fakeNewUserKey)); }); it("throws an error when a null user id is passed in", async () => { @@ -659,7 +659,7 @@ describe("deviceTrustService", () => { fakeOldUserKeyData.fill(FakeOldUserKeyMarker, 0, 1); // Mock the retrieval of a user key that differs from the new one passed into the method - cryptoService.userKey$.mockReturnValue( + keyService.userKey$.mockReturnValue( of(new SymmetricCryptoKey(fakeOldUserKeyData) as UserKey), ); @@ -749,7 +749,7 @@ describe("deviceTrustService", () => { return new DeviceTrustService( keyGenerationService, cryptoFunctionService, - cryptoService, + keyService, encryptService, appIdService, devicesApiService, diff --git a/libs/common/src/auth/services/key-connector.service.spec.ts b/libs/common/src/auth/services/key-connector.service.spec.ts index eb3e4cfc0e..b1bf87693c 100644 --- a/libs/common/src/auth/services/key-connector.service.spec.ts +++ b/libs/common/src/auth/services/key-connector.service.spec.ts @@ -1,12 +1,12 @@ import { mock } from "jest-mock-extended"; +import { KeyService } from "../../../../key-management/src/abstractions/key.service"; import { FakeAccountService, FakeStateProvider, mockAccountServiceWith } from "../../../spec"; import { ApiService } from "../../abstractions/api.service"; import { OrganizationService } from "../../admin-console/abstractions/organization/organization.service.abstraction"; import { OrganizationData } from "../../admin-console/models/data/organization.data"; import { Organization } from "../../admin-console/models/domain/organization"; import { ProfileOrganizationResponse } from "../../admin-console/models/response/profile-organization.response"; -import { CryptoService } from "../../platform/abstractions/crypto.service"; import { LogService } from "../../platform/abstractions/log.service"; import { Utils } from "../../platform/misc/utils"; import { SymmetricCryptoKey } from "../../platform/models/domain/symmetric-crypto-key"; @@ -27,7 +27,7 @@ import { TokenService } from "./token.service"; describe("KeyConnectorService", () => { let keyConnectorService: KeyConnectorService; - const cryptoService = mock(); + const keyService = mock(); const apiService = mock(); const tokenService = mock(); const logService = mock(); @@ -56,7 +56,7 @@ describe("KeyConnectorService", () => { keyConnectorService = new KeyConnectorService( accountService, masterPasswordService, - cryptoService, + keyService, apiService, tokenService, logService, diff --git a/libs/common/src/auth/services/key-connector.service.ts b/libs/common/src/auth/services/key-connector.service.ts index ad9b7081cd..111f82e6e5 100644 --- a/libs/common/src/auth/services/key-connector.service.ts +++ b/libs/common/src/auth/services/key-connector.service.ts @@ -2,12 +2,12 @@ import { firstValueFrom } from "rxjs"; import { LogoutReason } from "@bitwarden/auth/common"; +import { KeyService } from "../../../../key-management/src/abstractions/key.service"; import { ApiService } from "../../abstractions/api.service"; import { OrganizationService } from "../../admin-console/abstractions/organization/organization.service.abstraction"; import { OrganizationUserType } from "../../admin-console/enums"; import { Organization } from "../../admin-console/models/domain/organization"; import { KeysRequest } from "../../models/request/keys.request"; -import { CryptoService } from "../../platform/abstractions/crypto.service"; import { KeyGenerationService } from "../../platform/abstractions/key-generation.service"; import { LogService } from "../../platform/abstractions/log.service"; import { KdfType } from "../../platform/enums/kdf-type.enum"; @@ -54,7 +54,7 @@ export class KeyConnectorService implements KeyConnectorServiceAbstraction { constructor( private accountService: AccountService, private masterPasswordService: InternalMasterPasswordServiceAbstraction, - private cryptoService: CryptoService, + private keyService: KeyService, private apiService: ApiService, private tokenService: TokenService, private logService: LogService, @@ -146,7 +146,7 @@ export class KeyConnectorService implements KeyConnectorServiceAbstraction { ? new PBKDF2KdfConfig(kdfIterations) : new Argon2KdfConfig(kdfIterations, kdfMemory, kdfParallelism); - const masterKey = await this.cryptoService.makeMasterKey( + const masterKey = await this.keyService.makeMasterKey( password.keyB64, await this.tokenService.getEmail(), kdfConfig, @@ -154,11 +154,11 @@ export class KeyConnectorService implements KeyConnectorServiceAbstraction { const keyConnectorRequest = new KeyConnectorUserKeyRequest(masterKey.encKeyB64); await this.masterPasswordService.setMasterKey(masterKey, userId); - const userKey = await this.cryptoService.makeUserKey(masterKey); - await this.cryptoService.setUserKey(userKey[0], userId); - await this.cryptoService.setMasterKeyEncryptedUserKey(userKey[1].encryptedString, userId); + const userKey = await this.keyService.makeUserKey(masterKey); + await this.keyService.setUserKey(userKey[0], userId); + await this.keyService.setMasterKeyEncryptedUserKey(userKey[1].encryptedString, userId); - const [pubKey, privKey] = await this.cryptoService.makeKeyPair(userKey[0]); + const [pubKey, privKey] = await this.keyService.makeKeyPair(userKey[0]); try { const keyConnectorUrl = diff --git a/libs/common/src/auth/services/password-reset-enrollment.service.implementation.spec.ts b/libs/common/src/auth/services/password-reset-enrollment.service.implementation.spec.ts index b78ef52f07..088ce96079 100644 --- a/libs/common/src/auth/services/password-reset-enrollment.service.implementation.spec.ts +++ b/libs/common/src/auth/services/password-reset-enrollment.service.implementation.spec.ts @@ -5,9 +5,9 @@ import { OrganizationUserApiService } from "@bitwarden/admin-console/common"; import { EncryptService } from "@bitwarden/common/platform/abstractions/encrypt.service"; import { UserId } from "../../../../common/src/types/guid"; +import { KeyService } from "../../../../key-management/src/abstractions/key.service"; import { OrganizationApiServiceAbstraction } from "../../admin-console/abstractions/organization/organization-api.service.abstraction"; import { OrganizationAutoEnrollStatusResponse } from "../../admin-console/models/response/organization-auto-enroll-status.response"; -import { CryptoService } from "../../platform/abstractions/crypto.service"; import { I18nService } from "../../platform/abstractions/i18n.service"; import { AccountInfo, AccountService } from "../abstractions/account.service"; @@ -18,7 +18,7 @@ describe("PasswordResetEnrollmentServiceImplementation", () => { let organizationApiService: MockProxy; let accountService: MockProxy; - let cryptoService: MockProxy; + let keyService: MockProxy; let encryptService: MockProxy; let organizationUserApiService: MockProxy; let i18nService: MockProxy; @@ -28,14 +28,14 @@ describe("PasswordResetEnrollmentServiceImplementation", () => { organizationApiService = mock(); accountService = mock(); accountService.activeAccount$ = activeAccountSubject; - cryptoService = mock(); + keyService = mock(); encryptService = mock(); organizationUserApiService = mock(); i18nService = mock(); service = new PasswordResetEnrollmentServiceImplementation( organizationApiService, accountService, - cryptoService, + keyService, encryptService, organizationUserApiService, i18nService, @@ -99,7 +99,7 @@ describe("PasswordResetEnrollmentServiceImplementation", () => { }; activeAccountSubject.next(Object.assign(user1AccountInfo, { id: "userId" as UserId })); - cryptoService.getUserKey.mockResolvedValue({ key: "key" } as any); + keyService.getUserKey.mockResolvedValue({ key: "key" } as any); encryptService.rsaEncrypt.mockResolvedValue(encryptedKey as any); await service.enroll("orgId"); diff --git a/libs/common/src/auth/services/password-reset-enrollment.service.implementation.ts b/libs/common/src/auth/services/password-reset-enrollment.service.implementation.ts index 7dc5f44995..9adcd0b7c1 100644 --- a/libs/common/src/auth/services/password-reset-enrollment.service.implementation.ts +++ b/libs/common/src/auth/services/password-reset-enrollment.service.implementation.ts @@ -6,8 +6,8 @@ import { } from "@bitwarden/admin-console/common"; import { EncryptService } from "@bitwarden/common/platform/abstractions/encrypt.service"; +import { KeyService } from "../../../../key-management/src/abstractions/key.service"; import { OrganizationApiServiceAbstraction } from "../../admin-console/abstractions/organization/organization-api.service.abstraction"; -import { CryptoService } from "../../platform/abstractions/crypto.service"; import { I18nService } from "../../platform/abstractions/i18n.service"; import { Utils } from "../../platform/misc/utils"; import { UserKey } from "../../types/key"; @@ -20,7 +20,7 @@ export class PasswordResetEnrollmentServiceImplementation constructor( protected organizationApiService: OrganizationApiServiceAbstraction, protected accountService: AccountService, - protected cryptoService: CryptoService, + protected keyService: KeyService, protected encryptService: EncryptService, protected organizationUserApiService: OrganizationUserApiService, protected i18nService: I18nService, @@ -47,7 +47,7 @@ export class PasswordResetEnrollmentServiceImplementation userId = userId ?? (await firstValueFrom(this.accountService.activeAccount$.pipe(map((a) => a?.id)))); - userKey = userKey ?? (await this.cryptoService.getUserKey(userId)); + userKey = userKey ?? (await this.keyService.getUserKey(userId)); // RSA Encrypt user's userKey.key with organization public key const encryptedKey = await this.encryptService.rsaEncrypt(userKey.key, orgPublicKey); diff --git a/libs/common/src/auth/services/user-verification/user-verification.service.spec.ts b/libs/common/src/auth/services/user-verification/user-verification.service.spec.ts index 73a97cbc8b..02cd6056ef 100644 --- a/libs/common/src/auth/services/user-verification/user-verification.service.spec.ts +++ b/libs/common/src/auth/services/user-verification/user-verification.service.spec.ts @@ -8,9 +8,9 @@ import { UserDecryptionOptionsServiceAbstraction, } from "@bitwarden/auth/common"; +import { KeyService } from "../../../../../key-management/src/abstractions/key.service"; import { FakeAccountService, mockAccountServiceWith } from "../../../../spec"; import { VaultTimeoutSettingsService } from "../../../abstractions/vault-timeout/vault-timeout-settings.service"; -import { CryptoService } from "../../../platform/abstractions/crypto.service"; import { I18nService } from "../../../platform/abstractions/i18n.service"; import { LogService } from "../../../platform/abstractions/log.service"; import { PlatformUtilsService } from "../../../platform/abstractions/platform-utils.service"; @@ -31,7 +31,7 @@ import { UserVerificationService } from "./user-verification.service"; describe("UserVerificationService", () => { let sut: UserVerificationService; - const cryptoService = mock(); + const keyService = mock(); const masterPasswordService = mock(); const i18nService = mock(); const userVerificationApiService = mock(); @@ -50,7 +50,7 @@ describe("UserVerificationService", () => { accountService = mockAccountServiceWith(mockUserId); sut = new UserVerificationService( - cryptoService, + keyService, accountService, masterPasswordService, i18nService, @@ -132,7 +132,7 @@ describe("UserVerificationService", () => { setMasterPasswordAvailability(false); setPinAvailability("DISABLED"); vaultTimeoutSettingsService.isBiometricLockSet.mockResolvedValue(isBiometricsLockSet); - cryptoService.hasUserKeyStored.mockResolvedValue(isBiometricsUserKeyStored); + keyService.hasUserKeyStored.mockResolvedValue(isBiometricsUserKeyStored); platformUtilsService.supportsSecureStorage.mockReturnValue(platformSupportSecureStorage); const result = await sut.getAvailableVerificationOptions("client"); @@ -205,7 +205,7 @@ describe("UserVerificationService", () => { kdfConfigService.getKdfConfig.mockResolvedValue("kdfConfig" as unknown as KdfConfig); masterPasswordService.masterKey$.mockReturnValue(of("masterKey" as unknown as MasterKey)); - cryptoService.hashMasterKey + keyService.hashMasterKey .calledWith("password", "masterKey" as unknown as MasterKey, HashPurpose.LocalAuthorization) .mockResolvedValue("localHash"); }); @@ -216,7 +216,7 @@ describe("UserVerificationService", () => { }); it("returns if verification is successful", async () => { - cryptoService.compareAndUpdateKeyHash.mockResolvedValueOnce(true); + keyService.compareAndUpdateKeyHash.mockResolvedValueOnce(true); const result = await sut.verifyUserByMasterPassword( { @@ -227,7 +227,7 @@ describe("UserVerificationService", () => { "email", ); - expect(cryptoService.compareAndUpdateKeyHash).toHaveBeenCalled(); + expect(keyService.compareAndUpdateKeyHash).toHaveBeenCalled(); expect(masterPasswordService.setMasterKeyHash).toHaveBeenCalledWith( "localHash", mockUserId, @@ -240,7 +240,7 @@ describe("UserVerificationService", () => { }); it("throws if verification fails", async () => { - cryptoService.compareAndUpdateKeyHash.mockResolvedValueOnce(false); + keyService.compareAndUpdateKeyHash.mockResolvedValueOnce(false); await expect( sut.verifyUserByMasterPassword( @@ -253,7 +253,7 @@ describe("UserVerificationService", () => { ), ).rejects.toThrow("Invalid master password"); - expect(cryptoService.compareAndUpdateKeyHash).toHaveBeenCalled(); + expect(keyService.compareAndUpdateKeyHash).toHaveBeenCalled(); expect(masterPasswordService.setMasterKeyHash).not.toHaveBeenCalledWith(); expect(masterPasswordService.setMasterKey).not.toHaveBeenCalledWith(); }); @@ -265,7 +265,7 @@ describe("UserVerificationService", () => { }); it("returns if verification is successful", async () => { - cryptoService.hashMasterKey + keyService.hashMasterKey .calledWith( "password", "masterKey" as unknown as MasterKey, @@ -285,7 +285,7 @@ describe("UserVerificationService", () => { "email", ); - expect(cryptoService.compareAndUpdateKeyHash).not.toHaveBeenCalled(); + expect(keyService.compareAndUpdateKeyHash).not.toHaveBeenCalled(); expect(masterPasswordService.setMasterKeyHash).toHaveBeenCalledWith( "localHash", mockUserId, @@ -298,7 +298,7 @@ describe("UserVerificationService", () => { }); it("throws if verification fails", async () => { - cryptoService.hashMasterKey + keyService.hashMasterKey .calledWith( "password", "masterKey" as unknown as MasterKey, @@ -318,7 +318,7 @@ describe("UserVerificationService", () => { ), ).rejects.toThrow("Invalid master password"); - expect(cryptoService.compareAndUpdateKeyHash).not.toHaveBeenCalled(); + expect(keyService.compareAndUpdateKeyHash).not.toHaveBeenCalled(); expect(masterPasswordService.setMasterKeyHash).not.toHaveBeenCalledWith(); expect(masterPasswordService.setMasterKey).not.toHaveBeenCalledWith(); }); @@ -380,7 +380,7 @@ describe("UserVerificationService", () => { it("throws if master key cannot be created", async () => { kdfConfigService.getKdfConfig.mockResolvedValueOnce("kdfConfig" as unknown as KdfConfig); masterPasswordService.masterKey$.mockReturnValueOnce(of(null)); - cryptoService.makeMasterKey.mockResolvedValueOnce(null); + keyService.makeMasterKey.mockResolvedValueOnce(null); await expect( sut.verifyUserByMasterPassword( diff --git a/libs/common/src/auth/services/user-verification/user-verification.service.ts b/libs/common/src/auth/services/user-verification/user-verification.service.ts index 3b133891c9..b31ba59c98 100644 --- a/libs/common/src/auth/services/user-verification/user-verification.service.ts +++ b/libs/common/src/auth/services/user-verification/user-verification.service.ts @@ -3,8 +3,8 @@ import { firstValueFrom, map } from "rxjs"; import { UserDecryptionOptionsServiceAbstraction } from "@bitwarden/auth/common"; import { PinServiceAbstraction } from "../../../../../auth/src/common/abstractions/pin.service.abstraction"; +import { KeyService } from "../../../../../key-management/src/abstractions/key.service"; import { VaultTimeoutSettingsService as VaultTimeoutSettingsServiceAbstraction } from "../../../abstractions/vault-timeout/vault-timeout-settings.service"; -import { CryptoService } from "../../../platform/abstractions/crypto.service"; import { I18nService } from "../../../platform/abstractions/i18n.service"; import { LogService } from "../../../platform/abstractions/log.service"; import { PlatformUtilsService } from "../../../platform/abstractions/platform-utils.service"; @@ -39,7 +39,7 @@ import { */ export class UserVerificationService implements UserVerificationServiceAbstraction { constructor( - private cryptoService: CryptoService, + private keyService: KeyService, private accountService: AccountService, private masterPasswordService: InternalMasterPasswordServiceAbstraction, private i18nService: I18nService, @@ -66,7 +66,7 @@ export class UserVerificationService implements UserVerificationServiceAbstracti this.hasMasterPasswordAndMasterKeyHash(userId), this.pinService.isPinDecryptionAvailable(userId), this.vaultTimeoutSettingsService.isBiometricLockSet(userId), - this.cryptoService.hasUserKeyStored(KeySuffixOptions.Biometric, userId), + this.keyService.hasUserKeyStored(KeySuffixOptions.Biometric, userId), ]); // note: we do not need to check this.platformUtilsService.supportsBiometric() because @@ -119,7 +119,7 @@ export class UserVerificationService implements UserVerificationServiceAbstracti ); let masterKey = await firstValueFrom(this.masterPasswordService.masterKey$(userId)); if (!masterKey && !alreadyHashed) { - masterKey = await this.cryptoService.makeMasterKey( + masterKey = await this.keyService.makeMasterKey( verification.secret, email, await this.kdfConfigService.getKdfConfig(), @@ -127,7 +127,7 @@ export class UserVerificationService implements UserVerificationServiceAbstracti } request.masterPasswordHash = alreadyHashed ? verification.secret - : await this.cryptoService.hashMasterKey(verification.secret, masterKey); + : await this.keyService.hashMasterKey(verification.secret, masterKey); } return request; @@ -196,7 +196,7 @@ export class UserVerificationService implements UserVerificationServiceAbstracti let masterKey = await firstValueFrom(this.masterPasswordService.masterKey$(userId)); if (!masterKey) { - masterKey = await this.cryptoService.makeMasterKey(verification.secret, email, kdfConfig); + masterKey = await this.keyService.makeMasterKey(verification.secret, email, kdfConfig); } if (!masterKey) { @@ -206,7 +206,7 @@ export class UserVerificationService implements UserVerificationServiceAbstracti let policyOptions: MasterPasswordPolicyResponse | null; // Client-side verification if (await this.hasMasterPasswordAndMasterKeyHash(userId)) { - const passwordValid = await this.cryptoService.compareAndUpdateKeyHash( + const passwordValid = await this.keyService.compareAndUpdateKeyHash( verification.secret, masterKey, ); @@ -217,7 +217,7 @@ export class UserVerificationService implements UserVerificationServiceAbstracti } else { // Server-side verification const request = new SecretVerificationRequest(); - const serverKeyHash = await this.cryptoService.hashMasterKey( + const serverKeyHash = await this.keyService.hashMasterKey( verification.secret, masterKey, HashPurpose.ServerAuthorization, @@ -230,7 +230,7 @@ export class UserVerificationService implements UserVerificationServiceAbstracti } } - const localKeyHash = await this.cryptoService.hashMasterKey( + const localKeyHash = await this.keyService.hashMasterKey( verification.secret, masterKey, HashPurpose.LocalAuthorization, @@ -254,7 +254,7 @@ export class UserVerificationService implements UserVerificationServiceAbstracti let userKey: UserKey; // Biometrics crashes and doesn't return a value if the user cancels the prompt try { - userKey = await this.cryptoService.getUserKeyFromStorage(KeySuffixOptions.Biometric); + userKey = await this.keyService.getUserKeyFromStorage(KeySuffixOptions.Biometric); } catch (e) { this.logService.error(`Biometrics User Verification failed: ${e.message}`); // So, any failures should be treated as a failed verification diff --git a/libs/common/src/auth/services/webauthn-login/webauthn-login-prf-crypto.service.spec.ts b/libs/common/src/auth/services/webauthn-login/webauthn-login-prf-key.service.spec.ts similarity index 78% rename from libs/common/src/auth/services/webauthn-login/webauthn-login-prf-crypto.service.spec.ts rename to libs/common/src/auth/services/webauthn-login/webauthn-login-prf-key.service.spec.ts index 96eb466b20..f1fe07a996 100644 --- a/libs/common/src/auth/services/webauthn-login/webauthn-login-prf-crypto.service.spec.ts +++ b/libs/common/src/auth/services/webauthn-login/webauthn-login-prf-key.service.spec.ts @@ -2,15 +2,15 @@ import { mock, MockProxy } from "jest-mock-extended"; import { CryptoFunctionService } from "../../../platform/abstractions/crypto-function.service"; -import { WebAuthnLoginPrfCryptoService } from "./webauthn-login-prf-crypto.service"; +import { WebAuthnLoginPrfKeyService } from "./webauthn-login-prf-key.service"; -describe("WebAuthnLoginPrfCryptoService", () => { +describe("WebAuthnLoginPrfKeyService", () => { let cryptoFunctionService: MockProxy; - let service: WebAuthnLoginPrfCryptoService; + let service: WebAuthnLoginPrfKeyService; beforeEach(() => { cryptoFunctionService = mock(); - service = new WebAuthnLoginPrfCryptoService(cryptoFunctionService); + service = new WebAuthnLoginPrfKeyService(cryptoFunctionService); }); describe("createSymmetricKeyFromPrf", () => { diff --git a/libs/common/src/auth/services/webauthn-login/webauthn-login-prf-crypto.service.ts b/libs/common/src/auth/services/webauthn-login/webauthn-login-prf-key.service.ts similarity index 82% rename from libs/common/src/auth/services/webauthn-login/webauthn-login-prf-crypto.service.ts rename to libs/common/src/auth/services/webauthn-login/webauthn-login-prf-key.service.ts index 29032cd587..92cc03e759 100644 --- a/libs/common/src/auth/services/webauthn-login/webauthn-login-prf-crypto.service.ts +++ b/libs/common/src/auth/services/webauthn-login/webauthn-login-prf-key.service.ts @@ -1,11 +1,11 @@ import { CryptoFunctionService } from "../../../platform/abstractions/crypto-function.service"; import { SymmetricCryptoKey } from "../../../platform/models/domain/symmetric-crypto-key"; import { PrfKey } from "../../../types/key"; -import { WebAuthnLoginPrfCryptoServiceAbstraction } from "../../abstractions/webauthn/webauthn-login-prf-crypto.service.abstraction"; +import { WebAuthnLoginPrfKeyServiceAbstraction } from "../../abstractions/webauthn/webauthn-login-prf-key.service.abstraction"; const LoginWithPrfSalt = "passwordless-login"; -export class WebAuthnLoginPrfCryptoService implements WebAuthnLoginPrfCryptoServiceAbstraction { +export class WebAuthnLoginPrfKeyService implements WebAuthnLoginPrfKeyServiceAbstraction { constructor(private cryptoFunctionService: CryptoFunctionService) {} async getLoginWithPrfSalt(): Promise { diff --git a/libs/common/src/auth/services/webauthn-login/webauthn-login.service.spec.ts b/libs/common/src/auth/services/webauthn-login/webauthn-login.service.spec.ts index 1c7f045461..1044406234 100644 --- a/libs/common/src/auth/services/webauthn-login/webauthn-login.service.spec.ts +++ b/libs/common/src/auth/services/webauthn-login/webauthn-login.service.spec.ts @@ -7,7 +7,7 @@ import { Utils } from "../../../platform/misc/utils"; import { SymmetricCryptoKey } from "../../../platform/models/domain/symmetric-crypto-key"; import { PrfKey } from "../../../types/key"; import { WebAuthnLoginApiServiceAbstraction } from "../../abstractions/webauthn/webauthn-login-api.service.abstraction"; -import { WebAuthnLoginPrfCryptoServiceAbstraction } from "../../abstractions/webauthn/webauthn-login-prf-crypto.service.abstraction"; +import { WebAuthnLoginPrfKeyServiceAbstraction } from "../../abstractions/webauthn/webauthn-login-prf-key.service.abstraction"; import { AuthResult } from "../../models/domain/auth-result"; import { WebAuthnLoginCredentialAssertionOptionsView } from "../../models/view/webauthn-login/webauthn-login-credential-assertion-options.view"; import { WebAuthnLoginCredentialAssertionView } from "../../models/view/webauthn-login/webauthn-login-credential-assertion.view"; @@ -21,7 +21,7 @@ describe("WebAuthnLoginService", () => { const webAuthnLoginApiService = mock(); const loginStrategyService = mock(); - const webAuthnLoginPrfCryptoService = mock(); + const webAuthnLoginPrfKeyService = mock(); const navigatorCredentials = mock(); const logService = mock(); @@ -72,7 +72,7 @@ describe("WebAuthnLoginService", () => { return new WebAuthnLoginService( webAuthnLoginApiService, loginStrategyService, - webAuthnLoginPrfCryptoService, + webAuthnLoginPrfKeyService, window, logService, ); @@ -141,8 +141,8 @@ describe("WebAuthnLoginService", () => { publicKeyCredential.getClientExtensionResults().prf?.results?.first; const prfKey = new SymmetricCryptoKey(new Uint8Array(prfResult)) as PrfKey; - webAuthnLoginPrfCryptoService.getLoginWithPrfSalt.mockResolvedValue(saltArrayBuffer); - webAuthnLoginPrfCryptoService.createSymmetricKeyFromPrf.mockResolvedValue(prfKey); + webAuthnLoginPrfKeyService.getLoginWithPrfSalt.mockResolvedValue(saltArrayBuffer); + webAuthnLoginPrfKeyService.createSymmetricKeyFromPrf.mockResolvedValue(prfKey); // Mock implementations navigatorCredentials.get.mockResolvedValue(publicKeyCredential); @@ -152,7 +152,7 @@ describe("WebAuthnLoginService", () => { // Assert - expect(webAuthnLoginPrfCryptoService.getLoginWithPrfSalt).toHaveBeenCalled(); + expect(webAuthnLoginPrfKeyService.getLoginWithPrfSalt).toHaveBeenCalled(); expect(navigatorCredentials.get).toHaveBeenCalledWith( expect.objectContaining({ @@ -169,9 +169,7 @@ describe("WebAuthnLoginService", () => { }), ); - expect(webAuthnLoginPrfCryptoService.createSymmetricKeyFromPrf).toHaveBeenCalledWith( - prfResult, - ); + expect(webAuthnLoginPrfKeyService.createSymmetricKeyFromPrf).toHaveBeenCalledWith(prfResult); expect(result).toBeInstanceOf(WebAuthnLoginCredentialAssertionView); expect(result.token).toEqual(credentialAssertionOptions.token); diff --git a/libs/common/src/auth/services/webauthn-login/webauthn-login.service.ts b/libs/common/src/auth/services/webauthn-login/webauthn-login.service.ts index 7fca20e615..41f4994fab 100644 --- a/libs/common/src/auth/services/webauthn-login/webauthn-login.service.ts +++ b/libs/common/src/auth/services/webauthn-login/webauthn-login.service.ts @@ -3,7 +3,7 @@ import { LoginStrategyServiceAbstraction, WebAuthnLoginCredentials } from "@bitw import { LogService } from "../../../platform/abstractions/log.service"; import { PrfKey } from "../../../types/key"; import { WebAuthnLoginApiServiceAbstraction } from "../../abstractions/webauthn/webauthn-login-api.service.abstraction"; -import { WebAuthnLoginPrfCryptoServiceAbstraction } from "../../abstractions/webauthn/webauthn-login-prf-crypto.service.abstraction"; +import { WebAuthnLoginPrfKeyServiceAbstraction } from "../../abstractions/webauthn/webauthn-login-prf-key.service.abstraction"; import { WebAuthnLoginServiceAbstraction } from "../../abstractions/webauthn/webauthn-login.service.abstraction"; import { AuthResult } from "../../models/domain/auth-result"; import { WebAuthnLoginCredentialAssertionOptionsView } from "../../models/view/webauthn-login/webauthn-login-credential-assertion-options.view"; @@ -17,7 +17,7 @@ export class WebAuthnLoginService implements WebAuthnLoginServiceAbstraction { constructor( private webAuthnLoginApiService: WebAuthnLoginApiServiceAbstraction, private loginStrategyService: LoginStrategyServiceAbstraction, - private webAuthnLoginPrfCryptoService: WebAuthnLoginPrfCryptoServiceAbstraction, + private webAuthnLoginPrfKeyService: WebAuthnLoginPrfKeyServiceAbstraction, private window: Window, private logService?: LogService, ) { @@ -37,7 +37,7 @@ export class WebAuthnLoginService implements WebAuthnLoginServiceAbstraction { }; // TODO: Remove `any` when typescript typings add support for PRF nativeOptions.publicKey.extensions = { - prf: { eval: { first: await this.webAuthnLoginPrfCryptoService.getLoginWithPrfSalt() } }, + prf: { eval: { first: await this.webAuthnLoginPrfKeyService.getLoginWithPrfSalt() } }, } as any; try { @@ -50,7 +50,7 @@ export class WebAuthnLoginService implements WebAuthnLoginServiceAbstraction { let symmetricPrfKey: PrfKey | undefined; if (prfResult != undefined) { symmetricPrfKey = - await this.webAuthnLoginPrfCryptoService.createSymmetricKeyFromPrf(prfResult); + await this.webAuthnLoginPrfKeyService.createSymmetricKeyFromPrf(prfResult); } const deviceResponse = new WebAuthnLoginAssertionResponseRequest(response); diff --git a/libs/common/src/billing/services/organization-billing.service.ts b/libs/common/src/billing/services/organization-billing.service.ts index 6b326472c9..eebea0ca74 100644 --- a/libs/common/src/billing/services/organization-billing.service.ts +++ b/libs/common/src/billing/services/organization-billing.service.ts @@ -1,9 +1,9 @@ +import { KeyService } from "../../../../key-management/src/abstractions/key.service"; import { ApiService } from "../../abstractions/api.service"; import { OrganizationApiServiceAbstraction as OrganizationApiService } from "../../admin-console/abstractions/organization/organization-api.service.abstraction"; import { OrganizationCreateRequest } from "../../admin-console/models/request/organization-create.request"; import { OrganizationKeysRequest } from "../../admin-console/models/request/organization-keys.request"; import { OrganizationResponse } from "../../admin-console/models/response/organization.response"; -import { CryptoService } from "../../platform/abstractions/crypto.service"; import { EncryptService } from "../../platform/abstractions/encrypt.service"; import { I18nService } from "../../platform/abstractions/i18n.service"; import { EncString } from "../../platform/models/domain/enc-string"; @@ -28,7 +28,7 @@ interface OrganizationKeys { export class OrganizationBillingService implements OrganizationBillingServiceAbstraction { constructor( private apiService: ApiService, - private cryptoService: CryptoService, + private keyService: KeyService, private encryptService: EncryptService, private i18nService: I18nService, private organizationApiService: OrganizationApiService, @@ -78,8 +78,8 @@ export class OrganizationBillingService implements OrganizationBillingServiceAbs } private async makeOrganizationKeys(): Promise { - const [encryptedKey, key] = await this.cryptoService.makeOrgKey(); - const [publicKey, encryptedPrivateKey] = await this.cryptoService.makeKeyPair(key); + const [encryptedKey, key] = await this.keyService.makeOrgKey(); + const [publicKey, encryptedPrivateKey] = await this.keyService.makeKeyPair(key); const encryptedCollectionName = await this.encryptService.encrypt( this.i18nService.t("defaultCollection"), key, diff --git a/libs/common/src/platform/misc/utils.ts b/libs/common/src/platform/misc/utils.ts index 326ed5e8e8..a7cc05bbf6 100644 --- a/libs/common/src/platform/misc/utils.ts +++ b/libs/common/src/platform/misc/utils.ts @@ -6,7 +6,7 @@ import { Observable, of, switchMap } from "rxjs"; import { getHostname, parse } from "tldts"; import { Merge } from "type-fest"; -import { CryptoService } from "../abstractions/crypto.service"; +import { KeyService } from "../../../../key-management/src/abstractions/key.service"; import { EncryptService } from "../abstractions/encrypt.service"; import { I18nService } from "../abstractions/i18n.service"; @@ -18,7 +18,7 @@ declare global { } interface BitwardenContainerService { - getCryptoService: () => CryptoService; + getKeyService: () => KeyService; getEncryptService: () => EncryptService; } diff --git a/libs/common/src/platform/models/domain/enc-string.spec.ts b/libs/common/src/platform/models/domain/enc-string.spec.ts index 39d5883177..462a977ff8 100644 --- a/libs/common/src/platform/models/domain/enc-string.spec.ts +++ b/libs/common/src/platform/models/domain/enc-string.spec.ts @@ -1,10 +1,10 @@ import { mock, MockProxy } from "jest-mock-extended"; +import { KeyService } from "../../../../../key-management/src/abstractions/key.service"; import { makeEncString, makeStaticByteArray } from "../../../../spec"; import { EncryptService } from "../../../platform/abstractions/encrypt.service"; import { SymmetricCryptoKey } from "../../../platform/models/domain/symmetric-crypto-key"; import { UserKey, OrgKey } from "../../../types/key"; -import { CryptoService } from "../../abstractions/crypto.service"; import { EncryptionType } from "../../enums"; import { Utils } from "../../misc/utils"; import { ContainerService } from "../../services/container.service"; @@ -81,9 +81,9 @@ describe("EncString", () => { describe("decrypt", () => { const encString = new EncString(EncryptionType.Rsa2048_OaepSha256_B64, "data"); - const cryptoService = mock(); - cryptoService.hasUserKey.mockResolvedValue(true); - cryptoService.getUserKeyWithLegacySupport.mockResolvedValue( + const keyService = mock(); + keyService.hasUserKey.mockResolvedValue(true); + keyService.getUserKeyWithLegacySupport.mockResolvedValue( new SymmetricCryptoKey(makeStaticByteArray(32)) as UserKey, ); @@ -94,7 +94,7 @@ describe("EncString", () => { beforeEach(() => { (window as any).bitwardenContainerService = new ContainerService( - cryptoService, + keyService, encryptService, ); }); @@ -117,7 +117,7 @@ describe("EncString", () => { describe("decryptWithKey", () => { const encString = new EncString(EncryptionType.Rsa2048_OaepSha256_B64, "data"); - const cryptoService = mock(); + const keyService = mock(); const encryptService = mock(); encryptService.decryptToUtf8 .calledWith(encString, expect.anything()) @@ -140,10 +140,7 @@ describe("EncString", () => { } beforeEach(() => { - (window as any).bitwardenContainerService = new ContainerService( - cryptoService, - encryptService, - ); + (window as any).bitwardenContainerService = new ContainerService(keyService, encryptService); }); it("decrypts using the provided key and encryptService", async () => { @@ -321,28 +318,22 @@ describe("EncString", () => { }); describe("decrypt", () => { - let cryptoService: MockProxy; + let keyService: MockProxy; let encryptService: MockProxy; let encString: EncString; beforeEach(() => { - cryptoService = mock(); + keyService = mock(); encryptService = mock(); encString = new EncString(null); - (window as any).bitwardenContainerService = new ContainerService( - cryptoService, - encryptService, - ); + (window as any).bitwardenContainerService = new ContainerService(keyService, encryptService); }); it("handles value it can't decrypt", async () => { encryptService.decryptToUtf8.mockRejectedValue("error"); - (window as any).bitwardenContainerService = new ContainerService( - cryptoService, - encryptService, - ); + (window as any).bitwardenContainerService = new ContainerService(keyService, encryptService); const decrypted = await encString.decrypt(null); @@ -354,34 +345,34 @@ describe("EncString", () => { }); }); - it("uses provided key without depending on CryptoService", async () => { + it("uses provided key without depending on KeyService", async () => { const key = mock(); await encString.decrypt(null, key); - expect(cryptoService.getUserKeyWithLegacySupport).not.toHaveBeenCalled(); + expect(keyService.getUserKeyWithLegacySupport).not.toHaveBeenCalled(); expect(encryptService.decryptToUtf8).toHaveBeenCalledWith(encString, key); }); it("gets an organization key if required", async () => { const orgKey = mock(); - cryptoService.getOrgKey.calledWith("orgId").mockResolvedValue(orgKey); + keyService.getOrgKey.calledWith("orgId").mockResolvedValue(orgKey); await encString.decrypt("orgId", null); - expect(cryptoService.getOrgKey).toHaveBeenCalledWith("orgId"); + expect(keyService.getOrgKey).toHaveBeenCalledWith("orgId"); expect(encryptService.decryptToUtf8).toHaveBeenCalledWith(encString, orgKey); }); it("gets the user's decryption key if required", async () => { const userKey = mock(); - cryptoService.getUserKeyWithLegacySupport.mockResolvedValue(userKey); + keyService.getUserKeyWithLegacySupport.mockResolvedValue(userKey); await encString.decrypt(null, null); - expect(cryptoService.getUserKeyWithLegacySupport).toHaveBeenCalledWith(); + expect(keyService.getUserKeyWithLegacySupport).toHaveBeenCalledWith(); expect(encryptService.decryptToUtf8).toHaveBeenCalledWith(encString, userKey); }); }); diff --git a/libs/common/src/platform/models/domain/enc-string.ts b/libs/common/src/platform/models/domain/enc-string.ts index 0b0a597acd..40f36306bf 100644 --- a/libs/common/src/platform/models/domain/enc-string.ts +++ b/libs/common/src/platform/models/domain/enc-string.ts @@ -189,10 +189,10 @@ export class EncString implements Encrypted { return this.decryptedValue; } private async getKeyForDecryption(orgId: string) { - const cryptoService = Utils.getContainerService().getCryptoService(); + const keyService = Utils.getContainerService().getKeyService(); return orgId != null - ? await cryptoService.getOrgKey(orgId) - : await cryptoService.getUserKeyWithLegacySupport(); + ? await keyService.getOrgKey(orgId) + : await keyService.getUserKeyWithLegacySupport(); } } diff --git a/libs/common/src/platform/services/container.service.ts b/libs/common/src/platform/services/container.service.ts index 2e0748a32a..6022e097ab 100644 --- a/libs/common/src/platform/services/container.service.ts +++ b/libs/common/src/platform/services/container.service.ts @@ -1,9 +1,9 @@ -import { CryptoService } from "../abstractions/crypto.service"; +import { KeyService } from "../../../../key-management/src/abstractions/key.service"; import { EncryptService } from "../abstractions/encrypt.service"; export class ContainerService { constructor( - private cryptoService: CryptoService, + private keyService: KeyService, private encryptService: EncryptService, ) {} @@ -14,13 +14,13 @@ export class ContainerService { } /** - * @throws Will throw if CryptoService was not instantiated and provided to the ContainerService constructor + * @throws Will throw if KeyService was not instantiated and provided to the ContainerService constructor */ - getCryptoService(): CryptoService { - if (this.cryptoService == null) { - throw new Error("ContainerService.cryptoService not initialized."); + getKeyService(): KeyService { + if (this.keyService == null) { + throw new Error("ContainerService.keyService not initialized."); } - return this.cryptoService; + return this.keyService; } /** diff --git a/libs/common/src/platform/services/sdk/default-sdk.service.spec.ts b/libs/common/src/platform/services/sdk/default-sdk.service.spec.ts index dad99401f7..ff82b3aa76 100644 --- a/libs/common/src/platform/services/sdk/default-sdk.service.spec.ts +++ b/libs/common/src/platform/services/sdk/default-sdk.service.spec.ts @@ -1,6 +1,7 @@ import { mock, MockProxy } from "jest-mock-extended"; import { BehaviorSubject, firstValueFrom, of } from "rxjs"; +import { KeyService } from "@bitwarden/key-management"; import { BitwardenClient } from "@bitwarden/sdk-internal"; import { ApiService } from "../../../abstractions/api.service"; @@ -9,7 +10,6 @@ import { KdfConfigService } from "../../../auth/abstractions/kdf-config.service" import { PBKDF2KdfConfig } from "../../../auth/models/domain/kdf-config"; import { UserId } from "../../../types/guid"; import { UserKey } from "../../../types/key"; -import { CryptoService } from "../../abstractions/crypto.service"; import { Environment, EnvironmentService } from "../../abstractions/environment.service"; import { PlatformUtilsService } from "../../abstractions/platform-utils.service"; import { SdkClientFactory } from "../../abstractions/sdk/sdk-client-factory"; @@ -25,7 +25,7 @@ describe("DefaultSdkService", () => { let platformUtilsService!: MockProxy; let accountService!: MockProxy; let kdfConfigService!: MockProxy; - let cryptoService!: MockProxy; + let keyService!: MockProxy; let apiService!: MockProxy; let service!: DefaultSdkService; @@ -37,7 +37,7 @@ describe("DefaultSdkService", () => { platformUtilsService = mock(); accountService = mock(); kdfConfigService = mock(); - cryptoService = mock(); + keyService = mock(); apiService = mock(); // Can't use `of(mock())` for some reason @@ -49,7 +49,7 @@ describe("DefaultSdkService", () => { platformUtilsService, accountService, kdfConfigService, - cryptoService, + keyService, apiService, ); @@ -68,13 +68,13 @@ describe("DefaultSdkService", () => { kdfConfigService.getKdfConfig$ .calledWith(userId) .mockReturnValue(of(new PBKDF2KdfConfig())); - cryptoService.userKey$ + keyService.userKey$ .calledWith(userId) .mockReturnValue(of(new SymmetricCryptoKey(new Uint8Array(64)) as UserKey)); - cryptoService.userEncryptedPrivateKey$ + keyService.userEncryptedPrivateKey$ .calledWith(userId) .mockReturnValue(of("private-key" as EncryptedString)); - cryptoService.encryptedOrgKeys$.calledWith(userId).mockReturnValue(of({})); + keyService.encryptedOrgKeys$.calledWith(userId).mockReturnValue(of({})); }); it("creates an SDK client when called the first time", async () => { @@ -115,7 +115,7 @@ describe("DefaultSdkService", () => { it("destroys the SDK client when the userKey is unset (i.e. lock or logout)", async () => { const userKey$ = new BehaviorSubject(new SymmetricCryptoKey(new Uint8Array(64)) as UserKey); - cryptoService.userKey$.calledWith(userId).mockReturnValue(userKey$); + keyService.userKey$.calledWith(userId).mockReturnValue(userKey$); const subject = new BehaviorSubject(undefined); service.userClient$(userId).subscribe(subject); diff --git a/libs/common/src/platform/services/sdk/default-sdk.service.ts b/libs/common/src/platform/services/sdk/default-sdk.service.ts index 1b7a9a939a..adea07becc 100644 --- a/libs/common/src/platform/services/sdk/default-sdk.service.ts +++ b/libs/common/src/platform/services/sdk/default-sdk.service.ts @@ -10,6 +10,7 @@ import { switchMap, } from "rxjs"; +import { KeyService } from "@bitwarden/key-management"; import { BitwardenClient, ClientSettings, @@ -25,7 +26,6 @@ import { KdfConfig } from "../../../auth/models/domain/kdf-config"; import { DeviceType } from "../../../enums/device-type.enum"; import { OrganizationId, UserId } from "../../../types/guid"; import { UserKey } from "../../../types/key"; -import { CryptoService } from "../../abstractions/crypto.service"; import { Environment, EnvironmentService } from "../../abstractions/environment.service"; import { PlatformUtilsService } from "../../abstractions/platform-utils.service"; import { SdkClientFactory } from "../../abstractions/sdk/sdk-client-factory"; @@ -57,7 +57,7 @@ export class DefaultSdkService implements SdkService { private platformUtilsService: PlatformUtilsService, private accountService: AccountService, private kdfConfigService: KdfConfigService, - private cryptoService: CryptoService, + private keyService: KeyService, private apiService: ApiService, // Yes we shouldn't import ApiService, but it's temporary private userAgent: string = null, ) {} @@ -73,11 +73,11 @@ export class DefaultSdkService implements SdkService { distinctUntilChanged(), ); const kdfParams$ = this.kdfConfigService.getKdfConfig$(userId).pipe(distinctUntilChanged()); - const privateKey$ = this.cryptoService + const privateKey$ = this.keyService .userEncryptedPrivateKey$(userId) .pipe(distinctUntilChanged()); - const userKey$ = this.cryptoService.userKey$(userId).pipe(distinctUntilChanged()); - const orgKeys$ = this.cryptoService.encryptedOrgKeys$(userId).pipe( + const userKey$ = this.keyService.userKey$(userId).pipe(distinctUntilChanged()); + const orgKeys$ = this.keyService.encryptedOrgKeys$(userId).pipe( distinctUntilChanged(compareValues), // The upstream observable emits different objects with the same values ); diff --git a/libs/common/src/platform/services/user-auto-unlock-key.service.spec.ts b/libs/common/src/platform/services/user-auto-unlock-key.service.spec.ts index f0d60158c1..23a8ba3138 100644 --- a/libs/common/src/platform/services/user-auto-unlock-key.service.spec.ts +++ b/libs/common/src/platform/services/user-auto-unlock-key.service.spec.ts @@ -1,5 +1,6 @@ import { mock } from "jest-mock-extended"; +import { DefaultKeyService } from "../../../../key-management/src/key.service"; import { CsprngArray } from "../../types/csprng"; import { UserId } from "../../types/guid"; import { UserKey } from "../../types/key"; @@ -7,7 +8,6 @@ import { KeySuffixOptions } from "../enums"; import { Utils } from "../misc/utils"; import { SymmetricCryptoKey } from "../models/domain/symmetric-crypto-key"; -import { CryptoService } from "./crypto.service"; import { UserAutoUnlockKeyService } from "./user-auto-unlock-key.service"; describe("UserAutoUnlockKeyService", () => { @@ -15,10 +15,10 @@ describe("UserAutoUnlockKeyService", () => { const mockUserId = Utils.newGuid() as UserId; - const cryptoService = mock(); + const keyService = mock(); beforeEach(() => { - userAutoUnlockKeyService = new UserAutoUnlockKeyService(cryptoService); + userAutoUnlockKeyService = new UserAutoUnlockKeyService(keyService); }); describe("setUserKeyInMemoryIfAutoUserKeySet", () => { @@ -27,25 +27,22 @@ describe("UserAutoUnlockKeyService", () => { await (userAutoUnlockKeyService as any).setUserKeyInMemoryIfAutoUserKeySet(null); // Assert - expect(cryptoService.getUserKeyFromStorage).not.toHaveBeenCalled(); - expect(cryptoService.setUserKey).not.toHaveBeenCalled(); + expect(keyService.getUserKeyFromStorage).not.toHaveBeenCalled(); + expect(keyService.setUserKey).not.toHaveBeenCalled(); }); it("does nothing if the autoUserKey is null", async () => { // Arrange const userId = mockUserId; - cryptoService.getUserKeyFromStorage.mockResolvedValue(null); + keyService.getUserKeyFromStorage.mockResolvedValue(null); // Act await (userAutoUnlockKeyService as any).setUserKeyInMemoryIfAutoUserKeySet(userId); // Assert - expect(cryptoService.getUserKeyFromStorage).toHaveBeenCalledWith( - KeySuffixOptions.Auto, - userId, - ); - expect(cryptoService.setUserKey).not.toHaveBeenCalled(); + expect(keyService.getUserKeyFromStorage).toHaveBeenCalledWith(KeySuffixOptions.Auto, userId); + expect(keyService.setUserKey).not.toHaveBeenCalled(); }); it("sets the user key in memory if the autoUserKey is not null", async () => { @@ -55,17 +52,14 @@ describe("UserAutoUnlockKeyService", () => { const mockRandomBytes = new Uint8Array(64) as CsprngArray; const mockAutoUserKey: UserKey = new SymmetricCryptoKey(mockRandomBytes) as UserKey; - cryptoService.getUserKeyFromStorage.mockResolvedValue(mockAutoUserKey); + keyService.getUserKeyFromStorage.mockResolvedValue(mockAutoUserKey); // Act await (userAutoUnlockKeyService as any).setUserKeyInMemoryIfAutoUserKeySet(userId); // Assert - expect(cryptoService.getUserKeyFromStorage).toHaveBeenCalledWith( - KeySuffixOptions.Auto, - userId, - ); - expect(cryptoService.setUserKey).toHaveBeenCalledWith(mockAutoUserKey, userId); + expect(keyService.getUserKeyFromStorage).toHaveBeenCalledWith(KeySuffixOptions.Auto, userId); + expect(keyService.setUserKey).toHaveBeenCalledWith(mockAutoUserKey, userId); }); }); }); diff --git a/libs/common/src/platform/services/user-auto-unlock-key.service.ts b/libs/common/src/platform/services/user-auto-unlock-key.service.ts index b4a154133c..abb8993c39 100644 --- a/libs/common/src/platform/services/user-auto-unlock-key.service.ts +++ b/libs/common/src/platform/services/user-auto-unlock-key.service.ts @@ -1,15 +1,15 @@ +import { KeyService } from "../../../../key-management/src/abstractions/key.service"; import { UserId } from "../../types/guid"; -import { CryptoService } from "../abstractions/crypto.service"; import { KeySuffixOptions } from "../enums"; -// TODO: this is a half measure improvement which allows us to reduce some side effects today (cryptoService.getUserKey setting user key in memory if auto key exists) -// but ideally, in the future, we would be able to put this logic into the cryptoService +// TODO: this is a half measure improvement which allows us to reduce some side effects today (keyService.getUserKey setting user key in memory if auto key exists) +// but ideally, in the future, we would be able to put this logic into the keyService // after the vault timeout settings service is transitioned to state provider so that // the getUserKey logic can simply go to the correct location based on the vault timeout settings // similar to the TokenService (it would either go to secure storage for the auto user key or memory for the user key) export class UserAutoUnlockKeyService { - constructor(private cryptoService: CryptoService) {} + constructor(private keyService: KeyService) {} /** * The presence of the user key in memory dictates whether the user's vault is locked or unlocked. @@ -23,16 +23,13 @@ export class UserAutoUnlockKeyService { return false; } - const autoUserKey = await this.cryptoService.getUserKeyFromStorage( - KeySuffixOptions.Auto, - userId, - ); + const autoUserKey = await this.keyService.getUserKeyFromStorage(KeySuffixOptions.Auto, userId); if (autoUserKey == null) { return false; } - await this.cryptoService.setUserKey(autoUserKey, userId); + await this.keyService.setUserKey(autoUserKey, userId); return true; } } diff --git a/libs/common/src/platform/sync/default-sync.service.ts b/libs/common/src/platform/sync/default-sync.service.ts index 66a6c8e350..eaf804d286 100644 --- a/libs/common/src/platform/sync/default-sync.service.ts +++ b/libs/common/src/platform/sync/default-sync.service.ts @@ -8,6 +8,7 @@ import { import { UserDecryptionOptionsServiceAbstraction } from "../../../../auth/src/common/abstractions"; import { LogoutReason } from "../../../../auth/src/common/types"; +import { KeyService } from "../../../../key-management/src/abstractions/key.service"; import { ApiService } from "../../abstractions/api.service"; import { InternalOrganizationServiceAbstraction } from "../../admin-console/abstractions/organization/organization.service.abstraction"; import { InternalPolicyService } from "../../admin-console/abstractions/policy/policy.service.abstraction"; @@ -41,7 +42,6 @@ import { CipherData } from "../../vault/models/data/cipher.data"; import { FolderData } from "../../vault/models/data/folder.data"; import { CipherResponse } from "../../vault/models/response/cipher.response"; import { FolderResponse } from "../../vault/models/response/folder.response"; -import { CryptoService } from "../abstractions/crypto.service"; import { LogService } from "../abstractions/log.service"; import { StateService } from "../abstractions/state.service"; import { MessageSender } from "../messaging"; @@ -60,7 +60,7 @@ export class DefaultSyncService extends CoreSyncService { private domainSettingsService: DomainSettingsService, folderService: InternalFolderService, cipherService: CipherService, - private cryptoService: CryptoService, + private keyService: KeyService, collectionService: CollectionService, messageSender: MessageSender, private policyService: InternalPolicyService, @@ -178,10 +178,10 @@ export class DefaultSyncService extends CoreSyncService { throw new Error("Stamp has changed"); } - await this.cryptoService.setMasterKeyEncryptedUserKey(response.key, response.id); - await this.cryptoService.setPrivateKey(response.privateKey, response.id); - await this.cryptoService.setProviderKeys(response.providers, response.id); - await this.cryptoService.setOrgKeys( + await this.keyService.setMasterKeyEncryptedUserKey(response.key, response.id); + await this.keyService.setPrivateKey(response.privateKey, response.id); + await this.keyService.setProviderKeys(response.providers, response.id); + await this.keyService.setOrgKeys( response.organizations, response.providerOrganizations, response.id, diff --git a/libs/common/src/services/vault-timeout/vault-timeout-settings.service.spec.ts b/libs/common/src/services/vault-timeout/vault-timeout-settings.service.spec.ts index d90388f866..540f26bba2 100644 --- a/libs/common/src/services/vault-timeout/vault-timeout-settings.service.spec.ts +++ b/libs/common/src/services/vault-timeout/vault-timeout-settings.service.spec.ts @@ -10,13 +10,13 @@ import { Utils } from "@bitwarden/common/platform/misc/utils"; import { UserId } from "@bitwarden/common/types/guid"; import { BiometricStateService } from "@bitwarden/key-management"; +import { KeyService } from "../../../../key-management/src/abstractions/key.service"; import { FakeAccountService, mockAccountServiceWith, FakeStateProvider } from "../../../spec"; import { VaultTimeoutSettingsService as VaultTimeoutSettingsServiceAbstraction } from "../../abstractions/vault-timeout/vault-timeout-settings.service"; import { PolicyService } from "../../admin-console/abstractions/policy/policy.service.abstraction"; import { Policy } from "../../admin-console/models/domain/policy"; import { TokenService } from "../../auth/abstractions/token.service"; import { VaultTimeoutAction } from "../../enums/vault-timeout-action.enum"; -import { CryptoService } from "../../platform/abstractions/crypto.service"; import { LogService } from "../../platform/abstractions/log.service"; import { VAULT_TIMEOUT, @@ -30,7 +30,7 @@ describe("VaultTimeoutSettingsService", () => { let accountService: FakeAccountService; let pinService: MockProxy; let userDecryptionOptionsService: MockProxy; - let cryptoService: MockProxy; + let keyService: MockProxy; let tokenService: MockProxy; let policyService: MockProxy; const biometricStateService = mock(); @@ -46,7 +46,7 @@ describe("VaultTimeoutSettingsService", () => { accountService = mockAccountServiceWith(mockUserId); pinService = mock(); userDecryptionOptionsService = mock(); - cryptoService = mock(); + keyService = mock(); tokenService = mock(); policyService = mock(); @@ -342,7 +342,7 @@ describe("VaultTimeoutSettingsService", () => { stateProvider.singleUser.getFake(mockUserId, VAULT_TIMEOUT).nextMock, ).toHaveBeenCalledWith(timeout); - expect(cryptoService.refreshAdditionalKeys).toHaveBeenCalled(); + expect(keyService.refreshAdditionalKeys).toHaveBeenCalled(); }); it("should clear the tokens when the timeout is not never and the action is log out", async () => { @@ -377,7 +377,7 @@ describe("VaultTimeoutSettingsService", () => { accountService, pinService, userDecryptionOptionsService, - cryptoService, + keyService, tokenService, policyService, biometricStateService, diff --git a/libs/common/src/services/vault-timeout/vault-timeout-settings.service.ts b/libs/common/src/services/vault-timeout/vault-timeout-settings.service.ts index a90842b208..a1bc93144b 100644 --- a/libs/common/src/services/vault-timeout/vault-timeout-settings.service.ts +++ b/libs/common/src/services/vault-timeout/vault-timeout-settings.service.ts @@ -19,6 +19,7 @@ import { } from "@bitwarden/auth/common"; import { BiometricStateService } from "@bitwarden/key-management"; +import { KeyService } from "../../../../key-management/src/abstractions/key.service"; import { VaultTimeoutSettingsService as VaultTimeoutSettingsServiceAbstraction } from "../../abstractions/vault-timeout/vault-timeout-settings.service"; import { PolicyService } from "../../admin-console/abstractions/policy/policy.service.abstraction"; import { PolicyType } from "../../admin-console/enums"; @@ -26,7 +27,6 @@ import { Policy } from "../../admin-console/models/domain/policy"; import { AccountService } from "../../auth/abstractions/account.service"; import { TokenService } from "../../auth/abstractions/token.service"; import { VaultTimeoutAction } from "../../enums/vault-timeout-action.enum"; -import { CryptoService } from "../../platform/abstractions/crypto.service"; import { LogService } from "../../platform/abstractions/log.service"; import { StateProvider } from "../../platform/state"; import { UserId } from "../../types/guid"; @@ -39,7 +39,7 @@ export class VaultTimeoutSettingsService implements VaultTimeoutSettingsServiceA private accountService: AccountService, private pinService: PinServiceAbstraction, private userDecryptionOptionsService: UserDecryptionOptionsServiceAbstraction, - private cryptoService: CryptoService, + private keyService: KeyService, private tokenService: TokenService, private policyService: PolicyService, private biometricStateService: BiometricStateService, @@ -87,7 +87,7 @@ export class VaultTimeoutSettingsService implements VaultTimeoutSettingsServiceA clientSecret, ]); - await this.cryptoService.refreshAdditionalKeys(); + await this.keyService.refreshAdditionalKeys(); } availableVaultTimeoutActions$(userId?: string): Observable { @@ -287,7 +287,7 @@ export class VaultTimeoutSettingsService implements VaultTimeoutSettingsServiceA } async clear(userId?: string): Promise { - await this.cryptoService.clearPinKeys(userId); + await this.keyService.clearPinKeys(userId); } private async userHasMasterPassword(userId: string): Promise { diff --git a/libs/common/src/tools/send/models/domain/send.spec.ts b/libs/common/src/tools/send/models/domain/send.spec.ts index 5b1d7e73da..74c0e77b39 100644 --- a/libs/common/src/tools/send/models/domain/send.spec.ts +++ b/libs/common/src/tools/send/models/domain/send.spec.ts @@ -3,8 +3,8 @@ import { mock } from "jest-mock-extended"; import { SymmetricCryptoKey } from "@bitwarden/common/platform/models/domain/symmetric-crypto-key"; import { UserKey } from "@bitwarden/common/types/key"; +import { KeyService } from "../../../../../../key-management/src/abstractions/key.service"; import { makeStaticByteArray, mockEnc } from "../../../../../spec"; -import { CryptoService } from "../../../../platform/abstractions/crypto.service"; import { EncryptService } from "../../../../platform/abstractions/encrypt.service"; import { ContainerService } from "../../../../platform/services/container.service"; import { SendType } from "../../enums/send-type"; @@ -111,14 +111,14 @@ describe("Send", () => { send.hideEmail = true; const encryptService = mock(); - const cryptoService = mock(); + const keyService = mock(); encryptService.decryptToBytes .calledWith(send.key, userKey) .mockResolvedValue(makeStaticByteArray(32)); - cryptoService.makeSendKey.mockResolvedValue("cryptoKey" as any); - cryptoService.getUserKey.mockResolvedValue(userKey); + keyService.makeSendKey.mockResolvedValue("cryptoKey" as any); + keyService.getUserKey.mockResolvedValue(userKey); - (window as any).bitwardenContainerService = new ContainerService(cryptoService, encryptService); + (window as any).bitwardenContainerService = new ContainerService(keyService, encryptService); const view = await send.decrypt(); diff --git a/libs/common/src/tools/send/models/domain/send.ts b/libs/common/src/tools/send/models/domain/send.ts index 41d1fecc10..6e53813a36 100644 --- a/libs/common/src/tools/send/models/domain/send.ts +++ b/libs/common/src/tools/send/models/domain/send.ts @@ -72,13 +72,13 @@ export class Send extends Domain { async decrypt(): Promise { const model = new SendView(this); - const cryptoService = Utils.getContainerService().getCryptoService(); + const keyService = Utils.getContainerService().getKeyService(); const encryptService = Utils.getContainerService().getEncryptService(); try { - const sendKeyEncryptionKey = await cryptoService.getUserKey(); + const sendKeyEncryptionKey = await keyService.getUserKey(); model.key = await encryptService.decryptToBytes(this.key, sendKeyEncryptionKey); - model.cryptoKey = await cryptoService.makeSendKey(model.key); + model.cryptoKey = await keyService.makeSendKey(model.key); } catch (e) { // TODO: error? } diff --git a/libs/common/src/tools/send/services/send.service.spec.ts b/libs/common/src/tools/send/services/send.service.spec.ts index 5743eff481..5aca3a4b5c 100644 --- a/libs/common/src/tools/send/services/send.service.spec.ts +++ b/libs/common/src/tools/send/services/send.service.spec.ts @@ -4,6 +4,7 @@ import { firstValueFrom, of } from "rxjs"; import { EnvironmentService } from "@bitwarden/common/platform/abstractions/environment.service"; import { SelfHostedEnvironment } from "@bitwarden/common/platform/services/default-environment.service"; +import { KeyService } from "../../../../../key-management/src/abstractions/key.service"; import { FakeAccountService, FakeActiveUserState, @@ -11,7 +12,6 @@ import { awaitAsync, mockAccountServiceWith, } from "../../../../spec"; -import { CryptoService } from "../../../platform/abstractions/crypto.service"; import { EncryptService } from "../../../platform/abstractions/encrypt.service"; import { I18nService } from "../../../platform/abstractions/i18n.service"; import { KeyGenerationService } from "../../../platform/abstractions/key-generation.service"; @@ -40,7 +40,7 @@ import { } from "./test-data/send-tests.data"; describe("SendService", () => { - const cryptoService = mock(); + const keyService = mock(); const i18nService = mock(); const keyGenerationService = mock(); const encryptService = mock(); @@ -65,7 +65,7 @@ describe("SendService", () => { get: () => of(new SelfHostedEnvironment({ webVault: "https://example.com" })), }); - (window as any).bitwardenContainerService = new ContainerService(cryptoService, encryptService); + (window as any).bitwardenContainerService = new ContainerService(keyService, encryptService); accountService.activeAccountSubject.next({ id: mockUserId, @@ -84,7 +84,7 @@ describe("SendService", () => { decryptedState.nextState([testSendViewData("1", "Test Send")]); sendService = new SendService( - cryptoService, + keyService, i18nService, keyGenerationService, sendStateProvider, diff --git a/libs/common/src/tools/send/services/send.service.ts b/libs/common/src/tools/send/services/send.service.ts index 25937e7da1..3ba1cb92e2 100644 --- a/libs/common/src/tools/send/services/send.service.ts +++ b/libs/common/src/tools/send/services/send.service.ts @@ -1,7 +1,7 @@ import { Observable, concatMap, distinctUntilChanged, firstValueFrom, map } from "rxjs"; +import { KeyService } from "../../../../../key-management/src/abstractions/key.service"; import { PBKDF2KdfConfig } from "../../../auth/models/domain/kdf-config"; -import { CryptoService } from "../../../platform/abstractions/crypto.service"; import { EncryptService } from "../../../platform/abstractions/encrypt.service"; import { I18nService } from "../../../platform/abstractions/i18n.service"; import { KeyGenerationService } from "../../../platform/abstractions/key-generation.service"; @@ -37,7 +37,7 @@ export class SendService implements InternalSendServiceAbstraction { ); constructor( - private cryptoService: CryptoService, + private keyService: KeyService, private i18nService: I18nService, private keyGenerationService: KeyGenerationService, private stateProvider: SendStateProvider, @@ -77,7 +77,7 @@ export class SendService implements InternalSendServiceAbstraction { send.password = passwordKey.keyB64; } if (key == null) { - key = await this.cryptoService.getUserKey(); + key = await this.keyService.getUserKey(); } send.key = await this.encryptService.encrypt(model.key, key); send.name = await this.encryptService.encrypt(model.name, model.cryptoKey); @@ -197,7 +197,7 @@ export class SendService implements InternalSendServiceAbstraction { } decSends = []; - const hasKey = await this.cryptoService.hasUserKey(); + const hasKey = await this.keyService.hasUserKey(); if (!hasKey) { throw new Error("No user key found."); } @@ -322,7 +322,7 @@ export class SendService implements InternalSendServiceAbstraction { key: SymmetricCryptoKey, ): Promise<[EncString, EncArrayBuffer]> { if (key == null) { - key = await this.cryptoService.getUserKey(); + key = await this.keyService.getUserKey(); } const encFileName = await this.encryptService.encrypt(fileName, key); const encFileData = await this.encryptService.encryptToBytes(new Uint8Array(data), key); diff --git a/libs/common/src/vault/models/domain/attachment.spec.ts b/libs/common/src/vault/models/domain/attachment.spec.ts index 690866e173..14dec8dea0 100644 --- a/libs/common/src/vault/models/domain/attachment.spec.ts +++ b/libs/common/src/vault/models/domain/attachment.spec.ts @@ -1,7 +1,7 @@ import { mock, MockProxy } from "jest-mock-extended"; +import { KeyService } from "../../../../../key-management/src/abstractions/key.service"; import { makeStaticByteArray, mockEnc, mockFromJson } from "../../../../spec"; -import { CryptoService } from "../../../platform/abstractions/crypto.service"; import { EncryptService } from "../../../platform/abstractions/encrypt.service"; import { EncryptedString, EncString } from "../../../platform/models/domain/enc-string"; import { SymmetricCryptoKey } from "../../../platform/models/domain/symmetric-crypto-key"; @@ -57,17 +57,14 @@ describe("Attachment", () => { }); describe("decrypt", () => { - let cryptoService: MockProxy; + let keyService: MockProxy; let encryptService: MockProxy; beforeEach(() => { - cryptoService = mock(); + keyService = mock(); encryptService = mock(); - (window as any).bitwardenContainerService = new ContainerService( - cryptoService, - encryptService, - ); + (window as any).bitwardenContainerService = new ContainerService(keyService, encryptService); }); it("expected output", async () => { @@ -101,32 +98,32 @@ describe("Attachment", () => { attachment.key = mock(); }); - it("uses the provided key without depending on CryptoService", async () => { + it("uses the provided key without depending on KeyService", async () => { const providedKey = mock(); await attachment.decrypt(null, providedKey); - expect(cryptoService.getUserKeyWithLegacySupport).not.toHaveBeenCalled(); + expect(keyService.getUserKeyWithLegacySupport).not.toHaveBeenCalled(); expect(encryptService.decryptToBytes).toHaveBeenCalledWith(attachment.key, providedKey); }); it("gets an organization key if required", async () => { const orgKey = mock(); - cryptoService.getOrgKey.calledWith("orgId").mockResolvedValue(orgKey); + keyService.getOrgKey.calledWith("orgId").mockResolvedValue(orgKey); await attachment.decrypt("orgId", null); - expect(cryptoService.getOrgKey).toHaveBeenCalledWith("orgId"); + expect(keyService.getOrgKey).toHaveBeenCalledWith("orgId"); expect(encryptService.decryptToBytes).toHaveBeenCalledWith(attachment.key, orgKey); }); it("gets the user's decryption key if required", async () => { const userKey = mock(); - cryptoService.getUserKeyWithLegacySupport.mockResolvedValue(userKey); + keyService.getUserKeyWithLegacySupport.mockResolvedValue(userKey); await attachment.decrypt(null, null); - expect(cryptoService.getUserKeyWithLegacySupport).toHaveBeenCalled(); + expect(keyService.getUserKeyWithLegacySupport).toHaveBeenCalled(); expect(encryptService.decryptToBytes).toHaveBeenCalledWith(attachment.key, userKey); }); }); diff --git a/libs/common/src/vault/models/domain/attachment.ts b/libs/common/src/vault/models/domain/attachment.ts index 7a234fa21c..117b3b26e9 100644 --- a/libs/common/src/vault/models/domain/attachment.ts +++ b/libs/common/src/vault/models/domain/attachment.ts @@ -68,10 +68,10 @@ export class Attachment extends Domain { } private async getKeyForDecryption(orgId: string) { - const cryptoService = Utils.getContainerService().getCryptoService(); + const keyService = Utils.getContainerService().getKeyService(); return orgId != null - ? await cryptoService.getOrgKey(orgId) - : await cryptoService.getUserKeyWithLegacySupport(); + ? await keyService.getOrgKey(orgId) + : await keyService.getUserKeyWithLegacySupport(); } toAttachmentData(): AttachmentData { diff --git a/libs/common/src/vault/models/domain/cipher.spec.ts b/libs/common/src/vault/models/domain/cipher.spec.ts index f10884b55a..509a17a8a0 100644 --- a/libs/common/src/vault/models/domain/cipher.spec.ts +++ b/libs/common/src/vault/models/domain/cipher.spec.ts @@ -3,9 +3,9 @@ import { Jsonify } from "type-fest"; import { UserId } from "@bitwarden/common/types/guid"; +import { KeyService } from "../../../../../key-management/src/abstractions/key.service"; import { makeStaticByteArray, mockEnc, mockFromJson } from "../../../../spec/utils"; import { UriMatchStrategy } from "../../../models/domain/domain-service"; -import { CryptoService } from "../../../platform/abstractions/crypto.service"; import { EncryptService } from "../../../platform/abstractions/encrypt.service"; import { EncString } from "../../../platform/models/domain/enc-string"; import { ContainerService } from "../../../platform/services/container.service"; @@ -237,16 +237,13 @@ describe("Cipher DTO", () => { login.decrypt.mockResolvedValue(loginView); cipher.login = login; - const cryptoService = mock(); + const keyService = mock(); const encryptService = mock(); const cipherService = mock(); encryptService.decryptToBytes.mockResolvedValue(makeStaticByteArray(64)); - (window as any).bitwardenContainerService = new ContainerService( - cryptoService, - encryptService, - ); + (window as any).bitwardenContainerService = new ContainerService(keyService, encryptService); const cipherView = await cipher.decrypt( await cipherService.getKeyForCipherKeyDecryption(cipher, mockUserId), @@ -357,16 +354,13 @@ describe("Cipher DTO", () => { cipher.secureNote.type = SecureNoteType.Generic; cipher.key = mockEnc("EncKey"); - const cryptoService = mock(); + const keyService = mock(); const encryptService = mock(); const cipherService = mock(); encryptService.decryptToBytes.mockResolvedValue(makeStaticByteArray(64)); - (window as any).bitwardenContainerService = new ContainerService( - cryptoService, - encryptService, - ); + (window as any).bitwardenContainerService = new ContainerService(keyService, encryptService); const cipherView = await cipher.decrypt( await cipherService.getKeyForCipherKeyDecryption(cipher, mockUserId), @@ -495,16 +489,13 @@ describe("Cipher DTO", () => { card.decrypt.mockResolvedValue(cardView); cipher.card = card; - const cryptoService = mock(); + const keyService = mock(); const encryptService = mock(); const cipherService = mock(); encryptService.decryptToBytes.mockResolvedValue(makeStaticByteArray(64)); - (window as any).bitwardenContainerService = new ContainerService( - cryptoService, - encryptService, - ); + (window as any).bitwardenContainerService = new ContainerService(keyService, encryptService); const cipherView = await cipher.decrypt( await cipherService.getKeyForCipherKeyDecryption(cipher, mockUserId), @@ -657,16 +648,13 @@ describe("Cipher DTO", () => { identity.decrypt.mockResolvedValue(identityView); cipher.identity = identity; - const cryptoService = mock(); + const keyService = mock(); const encryptService = mock(); const cipherService = mock(); encryptService.decryptToBytes.mockResolvedValue(makeStaticByteArray(64)); - (window as any).bitwardenContainerService = new ContainerService( - cryptoService, - encryptService, - ); + (window as any).bitwardenContainerService = new ContainerService(keyService, encryptService); const cipherView = await cipher.decrypt( await cipherService.getKeyForCipherKeyDecryption(cipher, mockUserId), diff --git a/libs/common/src/vault/models/domain/login-uri.spec.ts b/libs/common/src/vault/models/domain/login-uri.spec.ts index c42b0cc9d1..a1ecb47359 100644 --- a/libs/common/src/vault/models/domain/login-uri.spec.ts +++ b/libs/common/src/vault/models/domain/login-uri.spec.ts @@ -70,7 +70,7 @@ describe("LoginUri", () => { encryptService = mock(); global.bitwardenContainerService = { getEncryptService: () => encryptService, - getCryptoService: () => null, + getKeyService: () => null, }; }); diff --git a/libs/common/src/vault/models/domain/login-uri.ts b/libs/common/src/vault/models/domain/login-uri.ts index 0a0c5765a3..e5943929f2 100644 --- a/libs/common/src/vault/models/domain/login-uri.ts +++ b/libs/common/src/vault/models/domain/login-uri.ts @@ -47,8 +47,8 @@ export class LoginUri extends Domain { return false; } - const cryptoService = Utils.getContainerService().getEncryptService(); - const localChecksum = await cryptoService.hash(clearTextUri, "sha256"); + const keyService = Utils.getContainerService().getEncryptService(); + const localChecksum = await keyService.hash(clearTextUri, "sha256"); const remoteChecksum = await this.uriChecksum.decrypt(orgId, encKey); return remoteChecksum === localChecksum; diff --git a/libs/common/src/vault/services/cipher.service.spec.ts b/libs/common/src/vault/services/cipher.service.spec.ts index 3e8ec843fd..961bc03bbb 100644 --- a/libs/common/src/vault/services/cipher.service.spec.ts +++ b/libs/common/src/vault/services/cipher.service.spec.ts @@ -3,6 +3,10 @@ import { BehaviorSubject, map, of } from "rxjs"; import { BulkEncryptService } from "@bitwarden/common/platform/abstractions/bulk-encrypt.service"; +import { + CipherDecryptionKeys, + KeyService, +} from "../../../../key-management/src/abstractions/key.service"; import { FakeAccountService, mockAccountServiceWith } from "../../../spec/fake-account-service"; import { FakeStateProvider } from "../../../spec/fake-state-provider"; import { makeStaticByteArray } from "../../../spec/utils"; @@ -12,7 +16,6 @@ import { AutofillSettingsService } from "../../autofill/services/autofill-settin import { DomainSettingsService } from "../../autofill/services/domain-settings.service"; import { UriMatchStrategy } from "../../models/domain/domain-service"; import { ConfigService } from "../../platform/abstractions/config/config.service"; -import { CipherDecryptionKeys, CryptoService } from "../../platform/abstractions/crypto.service"; import { EncryptService } from "../../platform/abstractions/encrypt.service"; import { I18nService } from "../../platform/abstractions/i18n.service"; import { StateService } from "../../platform/abstractions/state.service"; @@ -107,7 +110,7 @@ const mockUserId = Utils.newGuid() as UserId; let accountService: FakeAccountService; describe("Cipher Service", () => { - const cryptoService = mock(); + const keyService = mock(); const stateService = mock(); const autofillSettingsService = mock(); const domainSettingsService = mock(); @@ -130,10 +133,10 @@ describe("Cipher Service", () => { encryptService.encryptToBytes.mockReturnValue(Promise.resolve(ENCRYPTED_BYTES)); encryptService.encrypt.mockReturnValue(Promise.resolve(new EncString(ENCRYPTED_TEXT))); - (window as any).bitwardenContainerService = new ContainerService(cryptoService, encryptService); + (window as any).bitwardenContainerService = new ContainerService(keyService, encryptService); cipherService = new CipherService( - cryptoService, + keyService, domainSettingsService, apiService, i18nService, @@ -159,10 +162,10 @@ describe("Cipher Service", () => { it("should upload encrypted file contents with save attachments", async () => { const fileName = "filename"; const fileData = new Uint8Array(10); - cryptoService.getOrgKey.mockReturnValue( + keyService.getOrgKey.mockReturnValue( Promise.resolve(new SymmetricCryptoKey(new Uint8Array(32)) as OrgKey), ); - cryptoService.makeDataEncKey.mockReturnValue( + keyService.makeDataEncKey.mockReturnValue( Promise.resolve(new SymmetricCryptoKey(new Uint8Array(32))), ); @@ -271,7 +274,7 @@ describe("Cipher Service", () => { encryptService.decryptToBytes.mockReturnValue(Promise.resolve(makeStaticByteArray(64))); configService.checkServerMeetsVersionRequirement$.mockReturnValue(of(true)); - cryptoService.makeCipherKey.mockReturnValue( + keyService.makeCipherKey.mockReturnValue( Promise.resolve(new SymmetricCryptoKey(makeStaticByteArray(64)) as CipherKey), ); encryptService.encrypt.mockImplementation(encryptText); @@ -286,7 +289,7 @@ describe("Cipher Service", () => { { uri: "uri", match: UriMatchStrategy.RegularExpression } as LoginUriView, ]; - cryptoService.getOrgKey.mockReturnValue( + keyService.getOrgKey.mockReturnValue( Promise.resolve(new SymmetricCryptoKey(new Uint8Array(32)) as OrgKey), ); @@ -306,7 +309,7 @@ describe("Cipher Service", () => { it("is null when feature flag is false", async () => { configService.getFeatureFlag.mockResolvedValue(false); - cryptoService.getOrgKey.mockReturnValue( + keyService.getOrgKey.mockReturnValue( Promise.resolve(new SymmetricCryptoKey(new Uint8Array(32)) as OrgKey), ); const cipher = await cipherService.encrypt(cipherView, userId); @@ -330,7 +333,7 @@ describe("Cipher Service", () => { it("is not called when feature flag is false", async () => { configService.getFeatureFlag.mockResolvedValue(false); - cryptoService.getOrgKey.mockReturnValue( + keyService.getOrgKey.mockReturnValue( Promise.resolve(new SymmetricCryptoKey(new Uint8Array(32)) as OrgKey), ); @@ -341,7 +344,7 @@ describe("Cipher Service", () => { it("is called when feature flag is true", async () => { configService.getFeatureFlag.mockResolvedValue(true); - cryptoService.getOrgKey.mockReturnValue( + keyService.getOrgKey.mockReturnValue( Promise.resolve(new SymmetricCryptoKey(new Uint8Array(32)) as OrgKey), ); @@ -368,7 +371,7 @@ describe("Cipher Service", () => { const keys = { userKey: originalUserKey, } as CipherDecryptionKeys; - cryptoService.cipherDecryptionKeys$.mockReturnValue(of(keys)); + keyService.cipherDecryptionKeys$.mockReturnValue(of(keys)); const cipher1 = new CipherView(cipherObj); cipher1.id = "Cipher 1"; @@ -387,7 +390,7 @@ describe("Cipher Service", () => { encryptedKey = new EncString("Re-encrypted Cipher Key"); encryptService.encrypt.mockResolvedValue(encryptedKey); - cryptoService.makeCipherKey.mockResolvedValue( + keyService.makeCipherKey.mockResolvedValue( new SymmetricCryptoKey(new Uint8Array(32)) as CipherKey, ); }); diff --git a/libs/common/src/vault/services/cipher.service.ts b/libs/common/src/vault/services/cipher.service.ts index 207a5da3cb..154042601e 100644 --- a/libs/common/src/vault/services/cipher.service.ts +++ b/libs/common/src/vault/services/cipher.service.ts @@ -15,6 +15,7 @@ import { AccountService } from "@bitwarden/common/auth/abstractions/account.serv import { FeatureFlag } from "@bitwarden/common/enums/feature-flag.enum"; import { BulkEncryptService } from "@bitwarden/common/platform/abstractions/bulk-encrypt.service"; +import { KeyService } from "../../../../key-management/src/abstractions/key.service"; import { ApiService } from "../../abstractions/api.service"; import { SearchService } from "../../abstractions/search.service"; import { AutofillSettingsServiceAbstraction } from "../../autofill/services/autofill-settings.service"; @@ -24,7 +25,6 @@ import { ErrorResponse } from "../../models/response/error.response"; import { ListResponse } from "../../models/response/list.response"; import { View } from "../../models/view/view"; import { ConfigService } from "../../platform/abstractions/config/config.service"; -import { CryptoService } from "../../platform/abstractions/crypto.service"; import { EncryptService } from "../../platform/abstractions/encrypt.service"; import { I18nService } from "../../platform/abstractions/i18n.service"; import { StateService } from "../../platform/abstractions/state.service"; @@ -112,7 +112,7 @@ export class CipherService implements CipherServiceAbstraction { private addEditCipherInfoState: ActiveUserState; constructor( - private cryptoService: CryptoService, + private keyService: KeyService, private domainSettingsService: DomainSettingsService, private apiService: ApiService, private i18nService: I18nService, @@ -400,7 +400,7 @@ export class CipherService implements CipherServiceAbstraction { } private async decryptCiphers(ciphers: Cipher[], userId: UserId) { - const keys = await firstValueFrom(this.cryptoService.cipherDecryptionKeys$(userId, true)); + const keys = await firstValueFrom(this.keyService.cipherDecryptionKeys$(userId, true)); if (keys == null || (keys.userKey == null && Object.keys(keys.orgKeys).length === 0)) { // return early if there are no keys to decrypt with @@ -550,7 +550,7 @@ export class CipherService implements CipherServiceAbstraction { } const ciphers = response.data.map((cr) => new Cipher(new CipherData(cr))); - const key = await this.cryptoService.getOrgKey(organizationId); + const key = await this.keyService.getOrgKey(organizationId); let decCiphers: CipherView[] = []; if (await this.configService.getFeatureFlag(FeatureFlag.PM4154_BulkEncryptionService)) { decCiphers = await this.bulkEncryptService.decryptItems(ciphers, key); @@ -848,7 +848,7 @@ export class CipherService implements CipherServiceAbstraction { const encFileName = await this.encryptService.encrypt(filename, cipherEncKey); - const dataEncKey = await this.cryptoService.makeDataEncKey(cipherEncKey); + const dataEncKey = await this.keyService.makeDataEncKey(cipherEncKey); const encData = await this.encryptService.encryptToBytes(new Uint8Array(data), dataEncKey[0]); const response = await this.cipherFileUploadService.upload( @@ -1245,8 +1245,8 @@ export class CipherService implements CipherServiceAbstraction { async getKeyForCipherKeyDecryption(cipher: Cipher, userId: UserId): Promise { return ( - (await this.cryptoService.getOrgKey(cipher.organizationId)) || - ((await this.cryptoService.getUserKeyWithLegacySupport(userId)) as UserKey) + (await this.keyService.getOrgKey(cipher.organizationId)) || + ((await this.keyService.getUserKeyWithLegacySupport(userId)) as UserKey) ); } @@ -1294,7 +1294,7 @@ export class CipherService implements CipherServiceAbstraction { // In the case of a cipher that is being shared with an organization, we want to decrypt the // cipher key with the user's key and then re-encrypt it with the organization's key. private async encryptSharedCipher(model: CipherView, userId: UserId): Promise { - const keyForCipherKeyDecryption = await this.cryptoService.getUserKeyWithLegacySupport(userId); + const keyForCipherKeyDecryption = await this.keyService.getUserKeyWithLegacySupport(userId); return await this.encrypt(model, userId, null, keyForCipherKeyDecryption); } @@ -1371,14 +1371,14 @@ export class CipherService implements CipherServiceAbstraction { const encBuf = await EncArrayBuffer.fromResponse(attachmentResponse); const activeUserId = await firstValueFrom(this.accountService.activeAccount$); - const userKey = await this.cryptoService.getUserKeyWithLegacySupport(activeUserId.id); + const userKey = await this.keyService.getUserKeyWithLegacySupport(activeUserId.id); const decBuf = await this.encryptService.decryptToBytes(encBuf, userKey); let encKey: UserKey | OrgKey; - encKey = await this.cryptoService.getOrgKey(organizationId); - encKey ||= (await this.cryptoService.getUserKeyWithLegacySupport()) as UserKey; + encKey = await this.keyService.getOrgKey(organizationId); + encKey ||= (await this.keyService.getUserKeyWithLegacySupport()) as UserKey; - const dataEncKey = await this.cryptoService.makeDataEncKey(encKey); + const dataEncKey = await this.keyService.makeDataEncKey(encKey); const encFileName = await this.encryptService.encrypt(attachmentView.fileName, encKey); const encData = await this.encryptService.encryptToBytes(new Uint8Array(decBuf), dataEncKey[0]); @@ -1679,7 +1679,7 @@ export class CipherService implements CipherServiceAbstraction { // First, we get the key for cipher key encryption, in its decrypted form let decryptedCipherKey: SymmetricCryptoKey; if (cipher.key == null) { - decryptedCipherKey = await this.cryptoService.makeCipherKey(); + decryptedCipherKey = await this.keyService.makeCipherKey(); } else { decryptedCipherKey = new SymmetricCryptoKey( await this.encryptService.decryptToBytes(cipher.key, keyForCipherKeyDecryption), diff --git a/libs/common/src/vault/services/folder/folder.service.spec.ts b/libs/common/src/vault/services/folder/folder.service.spec.ts index 05e1cdebc9..193d0e85e6 100644 --- a/libs/common/src/vault/services/folder/folder.service.spec.ts +++ b/libs/common/src/vault/services/folder/folder.service.spec.ts @@ -1,11 +1,11 @@ import { mock, MockProxy } from "jest-mock-extended"; import { firstValueFrom } from "rxjs"; +import { KeyService } from "../../../../../key-management/src/abstractions/key.service"; import { makeStaticByteArray } from "../../../../spec"; import { FakeAccountService, mockAccountServiceWith } from "../../../../spec/fake-account-service"; import { FakeActiveUserState } from "../../../../spec/fake-state"; import { FakeStateProvider } from "../../../../spec/fake-state-provider"; -import { CryptoService } from "../../../platform/abstractions/crypto.service"; import { EncryptService } from "../../../platform/abstractions/encrypt.service"; import { I18nService } from "../../../platform/abstractions/i18n.service"; import { Utils } from "../../../platform/misc/utils"; @@ -22,7 +22,7 @@ import { FOLDER_ENCRYPTED_FOLDERS } from "../key-state/folder.state"; describe("Folder Service", () => { let folderService: FolderService; - let cryptoService: MockProxy; + let keyService: MockProxy; let encryptService: MockProxy; let i18nService: MockProxy; let cipherService: MockProxy; @@ -33,7 +33,7 @@ describe("Folder Service", () => { let folderState: FakeActiveUserState>; beforeEach(() => { - cryptoService = mock(); + keyService = mock(); encryptService = mock(); i18nService = mock(); cipherService = mock(); @@ -43,14 +43,14 @@ describe("Folder Service", () => { i18nService.collator = new Intl.Collator("en"); - cryptoService.hasUserKey.mockResolvedValue(true); - cryptoService.getUserKeyWithLegacySupport.mockResolvedValue( + keyService.hasUserKey.mockResolvedValue(true); + keyService.getUserKeyWithLegacySupport.mockResolvedValue( new SymmetricCryptoKey(makeStaticByteArray(32)) as UserKey, ); encryptService.decryptToUtf8.mockResolvedValue("DEC"); folderService = new FolderService( - cryptoService, + keyService, encryptService, i18nService, cipherService, diff --git a/libs/common/src/vault/services/folder/folder.service.ts b/libs/common/src/vault/services/folder/folder.service.ts index 2adbc8c6d0..2a76e82f3b 100644 --- a/libs/common/src/vault/services/folder/folder.service.ts +++ b/libs/common/src/vault/services/folder/folder.service.ts @@ -2,7 +2,7 @@ import { Observable, firstValueFrom, map, shareReplay } from "rxjs"; import { EncryptService } from "@bitwarden/common/platform/abstractions/encrypt.service"; -import { CryptoService } from "../../../platform/abstractions/crypto.service"; +import { KeyService } from "../../../../../key-management/src/abstractions/key.service"; import { I18nService } from "../../../platform/abstractions/i18n.service"; import { Utils } from "../../../platform/misc/utils"; import { SymmetricCryptoKey } from "../../../platform/models/domain/symmetric-crypto-key"; @@ -26,7 +26,7 @@ export class FolderService implements InternalFolderServiceAbstraction { private decryptedFoldersState: DerivedState; constructor( - private cryptoService: CryptoService, + private keyService: KeyService, private encryptService: EncryptService, private i18nService: I18nService, private cipherService: CipherService, @@ -36,7 +36,7 @@ export class FolderService implements InternalFolderServiceAbstraction { this.decryptedFoldersState = this.stateProvider.getDerived( this.encryptedFoldersState.state$, FOLDER_DECRYPTED_FOLDERS, - { folderService: this, cryptoService: this.cryptoService }, + { folderService: this, keyService: this.keyService }, ); this.folders$ = this.encryptedFoldersState.state$.pipe( diff --git a/libs/common/src/vault/services/key-state/folder.state.spec.ts b/libs/common/src/vault/services/key-state/folder.state.spec.ts index 072372f55d..ece66b5d45 100644 --- a/libs/common/src/vault/services/key-state/folder.state.spec.ts +++ b/libs/common/src/vault/services/key-state/folder.state.spec.ts @@ -1,6 +1,6 @@ import { mock } from "jest-mock-extended"; -import { CryptoService } from "../../../platform/abstractions/crypto.service"; +import { KeyService } from "../../../../../key-management/src/abstractions/key.service"; import { FolderService } from "../../abstractions/folder/folder.service.abstraction"; import { FolderData } from "../../models/data/folder.data"; import { Folder } from "../../models/domain/folder"; @@ -31,7 +31,7 @@ describe("encrypted folders", () => { }); describe("derived decrypted folders", () => { - const cryptoService = mock(); + const keyService = mock(); const folderService = mock(); const sut = FOLDER_DECRYPTED_FOLDERS; let data: FolderData; @@ -64,13 +64,13 @@ describe("derived decrypted folders", () => { it("should derive encrypted folders", async () => { const folderViewMock = new FolderView(new Folder(data)); - cryptoService.hasUserKey.mockResolvedValue(true); + keyService.hasUserKey.mockResolvedValue(true); folderService.decryptFolders.mockResolvedValue([folderViewMock]); const encryptedFoldersState = { id: data }; const derivedStateResult = await sut.derive(encryptedFoldersState, { folderService, - cryptoService, + keyService, }); expect(derivedStateResult).toEqual([folderViewMock]); diff --git a/libs/common/src/vault/services/key-state/folder.state.ts b/libs/common/src/vault/services/key-state/folder.state.ts index 1a45c88d6f..7262d72d58 100644 --- a/libs/common/src/vault/services/key-state/folder.state.ts +++ b/libs/common/src/vault/services/key-state/folder.state.ts @@ -1,6 +1,6 @@ import { Jsonify } from "type-fest"; -import { CryptoService } from "../../../platform/abstractions/crypto.service"; +import { KeyService } from "../../../../../key-management/src/abstractions/key.service"; import { DeriveDefinition, FOLDER_DISK, UserKeyDefinition } from "../../../platform/state"; import { FolderService } from "../../abstractions/folder/folder.service.abstraction"; import { FolderData } from "../../models/data/folder.data"; @@ -19,13 +19,13 @@ export const FOLDER_ENCRYPTED_FOLDERS = UserKeyDefinition.record( export const FOLDER_DECRYPTED_FOLDERS = DeriveDefinition.from< Record, FolderView[], - { folderService: FolderService; cryptoService: CryptoService } + { folderService: FolderService; keyService: KeyService } >(FOLDER_ENCRYPTED_FOLDERS, { deserializer: (obj) => obj.map((f) => FolderView.fromJSON(f)), - derive: async (from, { folderService, cryptoService }) => { + derive: async (from, { folderService, keyService }) => { const folders = Object.values(from || {}).map((f) => new Folder(f)); - if (await cryptoService.hasUserKey()) { + if (await keyService.hasUserKey()) { return await folderService.decryptFolders(folders); } else { return []; diff --git a/libs/common/tsconfig.json b/libs/common/tsconfig.json index 11cdb4e44c..99c58f3cf2 100644 --- a/libs/common/tsconfig.json +++ b/libs/common/tsconfig.json @@ -1,5 +1,12 @@ { "extends": "../shared/tsconfig.libs", - "include": ["src", "spec", "./custom-matchers.d.ts"], + "include": [ + "src", + "spec", + "./custom-matchers.d.ts", + "../key-management/src/key.service.spec.ts", + "../key-management/src/key.service.ts", + "../key-management/src/abstractions/key.service.ts" + ], "exclude": ["node_modules", "dist"] } diff --git a/libs/components/src/async-actions/in-forms.mdx b/libs/components/src/async-actions/in-forms.mdx index e0715fed41..6b1ab86424 100644 --- a/libs/components/src/async-actions/in-forms.mdx +++ b/libs/components/src/async-actions/in-forms.mdx @@ -42,7 +42,7 @@ class Component { return; } - await this.cryptoService.encrypt(/* ... */); + await this.keyService.encrypt(/* ... */); // `formGroup.invalid` will always return `true` here diff --git a/libs/importer/spec/bitwarden-password-protected-importer.spec.ts b/libs/importer/spec/bitwarden-password-protected-importer.spec.ts index e5100e4990..d15aa61c8a 100644 --- a/libs/importer/spec/bitwarden-password-protected-importer.spec.ts +++ b/libs/importer/spec/bitwarden-password-protected-importer.spec.ts @@ -2,12 +2,12 @@ import { mock, MockProxy } from "jest-mock-extended"; import { PinServiceAbstraction } from "@bitwarden/auth/common"; import { AccountService } from "@bitwarden/common/auth/abstractions/account.service"; -import { CryptoService } from "@bitwarden/common/platform/abstractions/crypto.service"; import { EncryptService } from "@bitwarden/common/platform/abstractions/encrypt.service"; import { I18nService } from "@bitwarden/common/platform/abstractions/i18n.service"; import { KdfType } from "@bitwarden/common/platform/enums"; import { Utils } from "@bitwarden/common/platform/misc/utils"; import { CipherService } from "@bitwarden/common/vault/abstractions/cipher.service"; +import { KeyService } from "@bitwarden/key-management"; import { BitwardenPasswordProtectedImporter, @@ -19,7 +19,7 @@ import { emptyUnencryptedExport } from "./test-data/bitwarden-json/unencrypted.j describe("BitwardenPasswordProtectedImporter", () => { let importer: BitwardenPasswordProtectedImporter; - let cryptoService: MockProxy; + let keyService: MockProxy; let encryptService: MockProxy; let i18nService: MockProxy; let cipherService: MockProxy; @@ -31,7 +31,7 @@ describe("BitwardenPasswordProtectedImporter", () => { }; beforeEach(() => { - cryptoService = mock(); + keyService = mock(); encryptService = mock(); i18nService = mock(); cipherService = mock(); @@ -39,7 +39,7 @@ describe("BitwardenPasswordProtectedImporter", () => { accountService = mock(); importer = new BitwardenPasswordProtectedImporter( - cryptoService, + keyService, encryptService, i18nService, cipherService, diff --git a/libs/importer/src/components/import.component.ts b/libs/importer/src/components/import.component.ts index 9be0428c86..1ffe2728b0 100644 --- a/libs/importer/src/components/import.component.ts +++ b/libs/importer/src/components/import.component.ts @@ -30,7 +30,6 @@ import { PolicyType } from "@bitwarden/common/admin-console/enums"; import { Organization } from "@bitwarden/common/admin-console/models/domain/organization"; import { AccountService } from "@bitwarden/common/auth/abstractions/account.service"; import { ClientType } from "@bitwarden/common/enums"; -import { CryptoService } from "@bitwarden/common/platform/abstractions/crypto.service"; import { EncryptService } from "@bitwarden/common/platform/abstractions/encrypt.service"; import { I18nService } from "@bitwarden/common/platform/abstractions/i18n.service"; import { LogService } from "@bitwarden/common/platform/abstractions/log.service"; @@ -56,6 +55,7 @@ import { SelectModule, ToastService, } from "@bitwarden/components"; +import { KeyService } from "@bitwarden/key-management"; import { ImportOption, ImportResult, ImportType } from "../models"; import { @@ -88,7 +88,7 @@ const safeProviders: SafeProvider[] = [ ImportApiServiceAbstraction, I18nService, CollectionService, - CryptoService, + KeyService, EncryptService, PinServiceAbstraction, AccountService, diff --git a/libs/importer/src/importers/bitwarden/bitwarden-json-importer.ts b/libs/importer/src/importers/bitwarden/bitwarden-json-importer.ts index 160a55e6f2..42033b3d61 100644 --- a/libs/importer/src/importers/bitwarden/bitwarden-json-importer.ts +++ b/libs/importer/src/importers/bitwarden/bitwarden-json-importer.ts @@ -8,7 +8,6 @@ import { CollectionWithIdExport, FolderWithIdExport, } from "@bitwarden/common/models/export"; -import { CryptoService } from "@bitwarden/common/platform/abstractions/crypto.service"; import { EncryptService } from "@bitwarden/common/platform/abstractions/encrypt.service"; import { I18nService } from "@bitwarden/common/platform/abstractions/i18n.service"; import { EncString } from "@bitwarden/common/platform/models/domain/enc-string"; @@ -16,6 +15,7 @@ import { SymmetricCryptoKey } from "@bitwarden/common/platform/models/domain/sym import { OrganizationId } from "@bitwarden/common/types/guid"; import { CipherService } from "@bitwarden/common/vault/abstractions/cipher.service"; import { FolderView } from "@bitwarden/common/vault/models/view/folder.view"; +import { KeyService } from "@bitwarden/key-management"; import { BitwardenEncryptedIndividualJsonExport, BitwardenEncryptedOrgJsonExport, @@ -32,7 +32,7 @@ export class BitwardenJsonImporter extends BaseImporter implements Importer { private result: ImportResult; protected constructor( - protected cryptoService: CryptoService, + protected keyService: KeyService, protected encryptService: EncryptService, protected i18nService: I18nService, protected cipherService: CipherService, @@ -63,11 +63,11 @@ export class BitwardenJsonImporter extends BaseImporter implements Importer { results: BitwardenEncryptedIndividualJsonExport | BitwardenEncryptedOrgJsonExport, ) { if (results.encKeyValidation_DO_NOT_EDIT != null) { - let keyForDecryption: SymmetricCryptoKey = await this.cryptoService.getOrgKey( + let keyForDecryption: SymmetricCryptoKey = await this.keyService.getOrgKey( this.organizationId, ); if (keyForDecryption == null) { - keyForDecryption = await this.cryptoService.getUserKeyWithLegacySupport(); + keyForDecryption = await this.keyService.getUserKeyWithLegacySupport(); } const encKeyValidation = new EncString(results.encKeyValidation_DO_NOT_EDIT); const encKeyValidationDecrypt = await this.encryptService.decryptToUtf8( @@ -210,8 +210,8 @@ export class BitwardenJsonImporter extends BaseImporter implements Importer { if (data.encrypted) { const collection = CollectionWithIdExport.toDomain(c); collection.organizationId = this.organizationId; - collectionView = await firstValueFrom(this.cryptoService.activeUserOrgKeys$).then( - (orgKeys) => collection.decrypt(orgKeys[c.organizationId as OrganizationId]), + collectionView = await firstValueFrom(this.keyService.activeUserOrgKeys$).then((orgKeys) => + collection.decrypt(orgKeys[c.organizationId as OrganizationId]), ); } else { collectionView = CollectionWithIdExport.toView(c); diff --git a/libs/importer/src/importers/bitwarden/bitwarden-password-protected-importer.ts b/libs/importer/src/importers/bitwarden/bitwarden-password-protected-importer.ts index 35a0ec0f22..fa19e3c000 100644 --- a/libs/importer/src/importers/bitwarden/bitwarden-password-protected-importer.ts +++ b/libs/importer/src/importers/bitwarden/bitwarden-password-protected-importer.ts @@ -5,13 +5,13 @@ import { KdfConfig, PBKDF2KdfConfig, } from "@bitwarden/common/auth/models/domain/kdf-config"; -import { CryptoService } from "@bitwarden/common/platform/abstractions/crypto.service"; import { EncryptService } from "@bitwarden/common/platform/abstractions/encrypt.service"; import { I18nService } from "@bitwarden/common/platform/abstractions/i18n.service"; import { KdfType } from "@bitwarden/common/platform/enums"; import { EncString } from "@bitwarden/common/platform/models/domain/enc-string"; import { SymmetricCryptoKey } from "@bitwarden/common/platform/models/domain/symmetric-crypto-key"; import { CipherService } from "@bitwarden/common/vault/abstractions/cipher.service"; +import { KeyService } from "@bitwarden/key-management"; import { BitwardenPasswordProtectedFileFormat } from "@bitwarden/vault-export-core"; import { ImportResult } from "../../models/import-result"; @@ -23,7 +23,7 @@ export class BitwardenPasswordProtectedImporter extends BitwardenJsonImporter im private key: SymmetricCryptoKey; constructor( - cryptoService: CryptoService, + keyService: KeyService, encryptService: EncryptService, i18nService: I18nService, cipherService: CipherService, @@ -31,7 +31,7 @@ export class BitwardenPasswordProtectedImporter extends BitwardenJsonImporter im accountService: AccountService, private promptForPassword_callback: () => Promise, ) { - super(cryptoService, encryptService, i18nService, cipherService, pinService, accountService); + super(keyService, encryptService, i18nService, cipherService, pinService, accountService); } async parse(data: string): Promise { diff --git a/libs/importer/src/services/import.service.spec.ts b/libs/importer/src/services/import.service.spec.ts index c221e15aa7..8b497beac9 100644 --- a/libs/importer/src/services/import.service.spec.ts +++ b/libs/importer/src/services/import.service.spec.ts @@ -3,7 +3,6 @@ import { mock, MockProxy } from "jest-mock-extended"; import { CollectionService, CollectionView } from "@bitwarden/admin-console/common"; import { PinServiceAbstraction } from "@bitwarden/auth/common"; import { AccountService } from "@bitwarden/common/auth/abstractions/account.service"; -import { CryptoService } from "@bitwarden/common/platform/abstractions/crypto.service"; import { EncryptService } from "@bitwarden/common/platform/abstractions/encrypt.service"; import { I18nService } from "@bitwarden/common/platform/abstractions/i18n.service"; import { Utils } from "@bitwarden/common/platform/misc/utils"; @@ -11,6 +10,7 @@ import { CipherService } from "@bitwarden/common/vault/abstractions/cipher.servi import { FolderService } from "@bitwarden/common/vault/abstractions/folder/folder.service.abstraction"; import { CipherView } from "@bitwarden/common/vault/models/view/cipher.view"; import { FolderView } from "@bitwarden/common/vault/models/view/folder.view"; +import { KeyService } from "@bitwarden/key-management"; import { BitwardenPasswordProtectedImporter } from "../importers/bitwarden/bitwarden-password-protected-importer"; import { Importer } from "../importers/importer"; @@ -26,7 +26,7 @@ describe("ImportService", () => { let importApiService: MockProxy; let i18nService: MockProxy; let collectionService: MockProxy; - let cryptoService: MockProxy; + let keyService: MockProxy; let encryptService: MockProxy; let pinService: MockProxy; let accountService: MockProxy; @@ -37,7 +37,7 @@ describe("ImportService", () => { importApiService = mock(); i18nService = mock(); collectionService = mock(); - cryptoService = mock(); + keyService = mock(); encryptService = mock(); pinService = mock(); @@ -47,7 +47,7 @@ describe("ImportService", () => { importApiService, i18nService, collectionService, - cryptoService, + keyService, encryptService, pinService, accountService, diff --git a/libs/importer/src/services/import.service.ts b/libs/importer/src/services/import.service.ts index 1e983aa3d1..17695c29d5 100644 --- a/libs/importer/src/services/import.service.ts +++ b/libs/importer/src/services/import.service.ts @@ -11,7 +11,6 @@ import { ImportCiphersRequest } from "@bitwarden/common/models/request/import-ci import { ImportOrganizationCiphersRequest } from "@bitwarden/common/models/request/import-organization-ciphers.request"; import { KvpRequest } from "@bitwarden/common/models/request/kvp.request"; import { ErrorResponse } from "@bitwarden/common/models/response/error.response"; -import { CryptoService } from "@bitwarden/common/platform/abstractions/crypto.service"; import { EncryptService } from "@bitwarden/common/platform/abstractions/encrypt.service"; import { I18nService } from "@bitwarden/common/platform/abstractions/i18n.service"; import { Utils } from "@bitwarden/common/platform/misc/utils"; @@ -22,6 +21,7 @@ import { CipherRequest } from "@bitwarden/common/vault/models/request/cipher.req import { FolderWithIdRequest } from "@bitwarden/common/vault/models/request/folder-with-id.request"; import { CipherView } from "@bitwarden/common/vault/models/view/cipher.view"; import { FolderView } from "@bitwarden/common/vault/models/view/folder.view"; +import { KeyService } from "@bitwarden/key-management"; import { AscendoCsvImporter, @@ -106,7 +106,7 @@ export class ImportService implements ImportServiceAbstraction { private importApiService: ImportApiServiceAbstraction, private i18nService: I18nService, private collectionService: CollectionService, - private cryptoService: CryptoService, + private keyService: KeyService, private encryptService: EncryptService, private pinService: PinServiceAbstraction, private accountService: AccountService, @@ -210,7 +210,7 @@ export class ImportService implements ImportServiceAbstraction { case "bitwardenjson": case "bitwardenpasswordprotected": return new BitwardenPasswordProtectedImporter( - this.cryptoService, + this.keyService, this.encryptService, this.i18nService, this.cipherService, @@ -349,7 +349,7 @@ export class ImportService implements ImportServiceAbstraction { const c = await this.cipherService.encrypt(importResult.ciphers[i], activeUserId); request.ciphers.push(new CipherRequest(c)); } - const userKey = await this.cryptoService.getUserKeyWithLegacySupport(activeUserId); + const userKey = await this.keyService.getUserKeyWithLegacySupport(activeUserId); if (importResult.folders != null) { for (let i = 0; i < importResult.folders.length; i++) { const f = await this.folderService.encrypt(importResult.folders[i], userKey); diff --git a/libs/common/src/platform/abstractions/crypto.service.ts b/libs/key-management/src/abstractions/key.service.ts similarity index 94% rename from libs/common/src/platform/abstractions/crypto.service.ts rename to libs/key-management/src/abstractions/key.service.ts index 0a554f6249..55ffea9db7 100644 --- a/libs/common/src/platform/abstractions/crypto.service.ts +++ b/libs/key-management/src/abstractions/key.service.ts @@ -1,11 +1,15 @@ import { Observable } from "rxjs"; -import { EncryptedOrganizationKeyData } from "../../admin-console/models/data/encrypted-organization-key.data"; -import { ProfileOrganizationResponse } from "../../admin-console/models/response/profile-organization.response"; -import { ProfileProviderOrganizationResponse } from "../../admin-console/models/response/profile-provider-organization.response"; -import { ProfileProviderResponse } from "../../admin-console/models/response/profile-provider.response"; -import { KdfConfig } from "../../auth/models/domain/kdf-config"; -import { OrganizationId, UserId } from "../../types/guid"; +import { EncryptedOrganizationKeyData } from "@bitwarden/common/admin-console/models/data/encrypted-organization-key.data"; + +import { ProfileOrganizationResponse } from "../../../common/src/admin-console/models/response/profile-organization.response"; +import { ProfileProviderOrganizationResponse } from "../../../common/src/admin-console/models/response/profile-provider-organization.response"; +import { ProfileProviderResponse } from "../../../common/src/admin-console/models/response/profile-provider.response"; +import { KdfConfig } from "../../../common/src/auth/models/domain/kdf-config"; +import { KeySuffixOptions, HashPurpose } from "../../../common/src/platform/enums"; +import { EncryptedString, EncString } from "../../../common/src/platform/models/domain/enc-string"; +import { SymmetricCryptoKey } from "../../../common/src/platform/models/domain/symmetric-crypto-key"; +import { OrganizationId, UserId } from "../../../common/src/types/guid"; import { UserKey, MasterKey, @@ -14,10 +18,7 @@ import { CipherKey, UserPrivateKey, UserPublicKey, -} from "../../types/key"; -import { KeySuffixOptions, HashPurpose } from "../enums"; -import { EncryptedString, EncString } from "../models/domain/enc-string"; -import { SymmetricCryptoKey } from "../models/domain/symmetric-crypto-key"; +} from "../../../common/src/types/key"; export class UserPrivateKeyDecryptionFailedError extends Error { constructor() { @@ -40,7 +41,7 @@ export type CipherDecryptionKeys = { orgKeys: Record; }; -export abstract class CryptoService { +export abstract class KeyService { /** * Retrieves a stream of the given users {@see UserKey} values. Can emit null if the user does not have a user key, e.g. the user * is in a locked or logged out state. diff --git a/libs/key-management/src/index.ts b/libs/key-management/src/index.ts index 298ffd145f..f2bb5e3016 100644 --- a/libs/key-management/src/index.ts +++ b/libs/key-management/src/index.ts @@ -4,3 +4,6 @@ export { } from "./biometrics/biometric-state.service"; export { BiometricsService } from "./biometrics/biometric.service"; export * from "./biometrics/biometric.state"; + +export { KeyService } from "./abstractions/key.service"; +export { DefaultKeyService } from "./key.service"; diff --git a/libs/common/src/platform/services/crypto.service.spec.ts b/libs/key-management/src/key.service.spec.ts similarity index 80% rename from libs/common/src/platform/services/crypto.service.spec.ts rename to libs/key-management/src/key.service.spec.ts index 769e6942b0..263779f59b 100644 --- a/libs/common/src/platform/services/crypto.service.spec.ts +++ b/libs/key-management/src/key.service.spec.ts @@ -1,48 +1,48 @@ import { mock } from "jest-mock-extended"; import { bufferCount, firstValueFrom, lastValueFrom, of, take, tap } from "rxjs"; -import { PinServiceAbstraction } from "../../../../auth/src/common/abstractions"; +import { PinServiceAbstraction } from "../../auth/src/common/abstractions"; import { awaitAsync, makeEncString, makeStaticByteArray, makeSymmetricCryptoKey, -} from "../../../spec"; -import { FakeAccountService, mockAccountServiceWith } from "../../../spec/fake-account-service"; -import { FakeActiveUserState, FakeSingleUserState } from "../../../spec/fake-state"; -import { FakeStateProvider } from "../../../spec/fake-state-provider"; -import { EncryptedOrganizationKeyData } from "../../admin-console/models/data/encrypted-organization-key.data"; -import { KdfConfigService } from "../../auth/abstractions/kdf-config.service"; -import { FakeMasterPasswordService } from "../../auth/services/master-password/fake-master-password.service"; -import { VAULT_TIMEOUT } from "../../services/vault-timeout/vault-timeout-settings.state"; -import { CsprngArray } from "../../types/csprng"; -import { OrganizationId, UserId } from "../../types/guid"; -import { UserKey, MasterKey } from "../../types/key"; -import { VaultTimeoutStringType } from "../../types/vault-timeout.type"; -import { CryptoFunctionService } from "../abstractions/crypto-function.service"; -import { UserPrivateKeyDecryptionFailedError } from "../abstractions/crypto.service"; -import { EncryptService } from "../abstractions/encrypt.service"; -import { KeyGenerationService } from "../abstractions/key-generation.service"; -import { LogService } from "../abstractions/log.service"; -import { PlatformUtilsService } from "../abstractions/platform-utils.service"; -import { StateService } from "../abstractions/state.service"; -import { Encrypted } from "../interfaces/encrypted"; -import { Utils } from "../misc/utils"; -import { EncString, EncryptedString } from "../models/domain/enc-string"; -import { SymmetricCryptoKey } from "../models/domain/symmetric-crypto-key"; -import { CryptoService } from "../services/crypto.service"; -import { UserKeyDefinition } from "../state"; - -import { USER_ENCRYPTED_ORGANIZATION_KEYS } from "./key-state/org-keys.state"; -import { USER_ENCRYPTED_PROVIDER_KEYS } from "./key-state/provider-keys.state"; +} from "../../common/spec"; +import { FakeAccountService, mockAccountServiceWith } from "../../common/spec/fake-account-service"; +import { FakeActiveUserState, FakeSingleUserState } from "../../common/spec/fake-state"; +import { FakeStateProvider } from "../../common/spec/fake-state-provider"; +import { EncryptedOrganizationKeyData } from "../../common/src/admin-console/models/data/encrypted-organization-key.data"; +import { KdfConfigService } from "../../common/src/auth/abstractions/kdf-config.service"; +import { FakeMasterPasswordService } from "../../common/src/auth/services/master-password/fake-master-password.service"; +import { CryptoFunctionService } from "../../common/src/platform/abstractions/crypto-function.service"; +import { EncryptService } from "../../common/src/platform/abstractions/encrypt.service"; +import { KeyGenerationService } from "../../common/src/platform/abstractions/key-generation.service"; +import { LogService } from "../../common/src/platform/abstractions/log.service"; +import { PlatformUtilsService } from "../../common/src/platform/abstractions/platform-utils.service"; +import { StateService } from "../../common/src/platform/abstractions/state.service"; +import { Encrypted } from "../../common/src/platform/interfaces/encrypted"; +import { Utils } from "../../common/src/platform/misc/utils"; +import { EncString, EncryptedString } from "../../common/src/platform/models/domain/enc-string"; +import { SymmetricCryptoKey } from "../../common/src/platform/models/domain/symmetric-crypto-key"; +import { USER_ENCRYPTED_ORGANIZATION_KEYS } from "../../common/src/platform/services/key-state/org-keys.state"; +import { USER_ENCRYPTED_PROVIDER_KEYS } from "../../common/src/platform/services/key-state/provider-keys.state"; import { USER_ENCRYPTED_PRIVATE_KEY, USER_EVER_HAD_USER_KEY, USER_KEY, -} from "./key-state/user-key.state"; +} from "../../common/src/platform/services/key-state/user-key.state"; +import { UserKeyDefinition } from "../../common/src/platform/state"; +import { VAULT_TIMEOUT } from "../../common/src/services/vault-timeout/vault-timeout-settings.state"; +import { CsprngArray } from "../../common/src/types/csprng"; +import { OrganizationId, UserId } from "../../common/src/types/guid"; +import { UserKey, MasterKey } from "../../common/src/types/key"; +import { VaultTimeoutStringType } from "../../common/src/types/vault-timeout.type"; -describe("cryptoService", () => { - let cryptoService: CryptoService; +import { UserPrivateKeyDecryptionFailedError } from "./abstractions/key.service"; +import { DefaultKeyService } from "./key.service"; + +describe("keyService", () => { + let keyService: DefaultKeyService; const pinService = mock(); const keyGenerationService = mock(); @@ -63,7 +63,7 @@ describe("cryptoService", () => { masterPasswordService = new FakeMasterPasswordService(); stateProvider = new FakeStateProvider(accountService); - cryptoService = new CryptoService( + keyService = new DefaultKeyService( pinService, masterPasswordService, keyGenerationService, @@ -83,7 +83,7 @@ describe("cryptoService", () => { }); it("instantiates", () => { - expect(cryptoService).not.toBeFalsy(); + expect(keyService).not.toBeFalsy(); }); describe("getUserKey", () => { @@ -95,7 +95,7 @@ describe("cryptoService", () => { }); it("retrieves the key state of the requested user", async () => { - await cryptoService.getUserKey(mockUserId); + await keyService.getUserKey(mockUserId); expect(stateProvider.mock.getUserState$).toHaveBeenCalledWith(USER_KEY, mockUserId); }); @@ -103,13 +103,13 @@ describe("cryptoService", () => { it("returns the User Key if available", async () => { stateProvider.singleUser.getFake(mockUserId, USER_KEY).nextState(mockUserKey); - const userKey = await cryptoService.getUserKey(mockUserId); + const userKey = await keyService.getUserKey(mockUserId); expect(userKey).toEqual(mockUserKey); }); it("returns nullish if the user key is not set", async () => { - const userKey = await cryptoService.getUserKey(mockUserId); + const userKey = await keyService.getUserKey(mockUserId); expect(userKey).toBeFalsy(); }); @@ -129,12 +129,12 @@ describe("cryptoService", () => { stateProvider.singleUser .getFake(mockUserId, USER_KEY) .nextState(hasKey ? mockUserKey : null); - expect(await cryptoService[method](mockUserId)).toBe(hasKey); + expect(await keyService[method](mockUserId)).toBe(hasKey); }); it("returns false when no active userId is set", async () => { accountService.activeAccountSubject.next(null); - expect(await cryptoService[method]()).toBe(false); + expect(await keyService[method]()).toBe(false); }); it.each([true, false])( @@ -144,7 +144,7 @@ describe("cryptoService", () => { stateProvider.singleUser .getFake(mockUserId, USER_KEY) .nextState(hasKey ? mockUserKey : null); - expect(await cryptoService[method]()).toBe(hasKey); + expect(await keyService[method]()).toBe(hasKey); }, ); }, @@ -165,9 +165,9 @@ describe("cryptoService", () => { it("returns the User Key if available", async () => { stateProvider.singleUser.getFake(mockUserId, USER_KEY).nextState(mockUserKey); - const getKeySpy = jest.spyOn(cryptoService, "getUserKey"); + const getKeySpy = jest.spyOn(keyService, "getUserKey"); - const userKey = await cryptoService.getUserKeyWithLegacySupport(mockUserId); + const userKey = await keyService.getUserKeyWithLegacySupport(mockUserId); expect(getKeySpy).toHaveBeenCalledWith(mockUserId); expect(getMasterKey).not.toHaveBeenCalled(); @@ -178,7 +178,7 @@ describe("cryptoService", () => { it("returns the user's master key when User Key is not available", async () => { masterPasswordService.masterKeySubject.next(mockMasterKey); - const userKey = await cryptoService.getUserKeyWithLegacySupport(mockUserId); + const userKey = await keyService.getUserKeyWithLegacySupport(mockUserId); expect(getMasterKey).toHaveBeenCalledWith(mockUserId); expect(userKey).toEqual(mockMasterKey); @@ -195,19 +195,19 @@ describe("cryptoService", () => { it("should return true when stored value is true", async () => { everHadUserKeyState.nextState(true); - expect(await firstValueFrom(cryptoService.everHadUserKey$)).toBe(true); + expect(await firstValueFrom(keyService.everHadUserKey$)).toBe(true); }); it("should return false when stored value is false", async () => { everHadUserKeyState.nextState(false); - expect(await firstValueFrom(cryptoService.everHadUserKey$)).toBe(false); + expect(await firstValueFrom(keyService.everHadUserKey$)).toBe(false); }); it("should return false when stored value is null", async () => { everHadUserKeyState.nextState(null); - expect(await firstValueFrom(cryptoService.everHadUserKey$)).toBe(false); + expect(await firstValueFrom(keyService.everHadUserKey$)).toBe(false); }); }); @@ -225,7 +225,7 @@ describe("cryptoService", () => { }); it("should set everHadUserKey if key is not null to true", async () => { - await cryptoService.setUserKey(mockUserKey, mockUserId); + await keyService.setUserKey(mockUserKey, mockUserId); expect(await firstValueFrom(everHadUserKeyState.state$)).toBe(true); }); @@ -234,7 +234,7 @@ describe("cryptoService", () => { it("sets an Auto key if vault timeout is set to 'never'", async () => { await stateProvider.setUserState(VAULT_TIMEOUT, VaultTimeoutStringType.Never, mockUserId); - await cryptoService.setUserKey(mockUserKey, mockUserId); + await keyService.setUserKey(mockUserKey, mockUserId); expect(stateService.setUserKeyAutoUnlock).toHaveBeenCalledWith(mockUserKey.keyB64, { userId: mockUserId, @@ -244,7 +244,7 @@ describe("cryptoService", () => { it("clears the Auto key if vault timeout is set to anything other than null", async () => { await stateProvider.setUserState(VAULT_TIMEOUT, 10, mockUserId); - await cryptoService.setUserKey(mockUserKey, mockUserId); + await keyService.setUserKey(mockUserKey, mockUserId); expect(stateService.setUserKeyAutoUnlock).toHaveBeenCalledWith(null, { userId: mockUserId, @@ -252,7 +252,7 @@ describe("cryptoService", () => { }); it("clears the old deprecated Auto key whenever a User Key is set", async () => { - await cryptoService.setUserKey(mockUserKey, mockUserId); + await keyService.setUserKey(mockUserKey, mockUserId); expect(stateService.setCryptoMasterKeyAuto).toHaveBeenCalledWith(null, { userId: mockUserId, @@ -261,13 +261,11 @@ describe("cryptoService", () => { }); it("throws if key is null", async () => { - await expect(cryptoService.setUserKey(null, mockUserId)).rejects.toThrow("No key provided."); + await expect(keyService.setUserKey(null, mockUserId)).rejects.toThrow("No key provided."); }); it("throws if userId is null", async () => { - await expect(cryptoService.setUserKey(mockUserKey, null)).rejects.toThrow( - "No userId provided.", - ); + await expect(keyService.setUserKey(mockUserKey, null)).rejects.toThrow("No userId provided."); }); describe("Pin Key refresh", () => { @@ -285,7 +283,7 @@ describe("cryptoService", () => { mockPinKeyEncryptedUserKey, ); - await cryptoService.setUserKey(mockUserKey, mockUserId); + await keyService.setUserKey(mockUserKey, mockUserId); expect(pinService.storePinKeyEncryptedUserKey).toHaveBeenCalledWith( mockPinKeyEncryptedUserKey, @@ -299,7 +297,7 @@ describe("cryptoService", () => { pinService.getUserKeyEncryptedPin.mockResolvedValue(mockUserKeyEncryptedPin); pinService.getPinKeyEncryptedUserKeyPersistent.mockResolvedValue(null); - await cryptoService.setUserKey(mockUserKey, mockUserId); + await keyService.setUserKey(mockUserKey, mockUserId); expect(pinService.storePinKeyEncryptedUserKey).toHaveBeenCalledWith( mockPinKeyEncryptedUserKey, @@ -311,7 +309,7 @@ describe("cryptoService", () => { it("clears the pinKeyEncryptedUserKeyPersistent and pinKeyEncryptedUserKeyEphemeral if the UserKeyEncryptedPin is not set", async () => { pinService.getUserKeyEncryptedPin.mockResolvedValue(null); - await cryptoService.setUserKey(mockUserKey, mockUserId); + await keyService.setUserKey(mockUserKey, mockUserId); expect(pinService.clearPinKeyEncryptedUserKeyPersistent).toHaveBeenCalledWith(mockUserId); expect(pinService.clearPinKeyEncryptedUserKeyEphemeral).toHaveBeenCalledWith(mockUserId); @@ -338,19 +336,19 @@ describe("cryptoService", () => { }); it("throws if userKey is null", async () => { - await expect(cryptoService.setUserKeys(null, mockEncPrivateKey, mockUserId)).rejects.toThrow( + await expect(keyService.setUserKeys(null, mockEncPrivateKey, mockUserId)).rejects.toThrow( "No userKey provided.", ); }); it("throws if encPrivateKey is null", async () => { - await expect(cryptoService.setUserKeys(mockUserKey, null, mockUserId)).rejects.toThrow( + await expect(keyService.setUserKeys(mockUserKey, null, mockUserId)).rejects.toThrow( "No encPrivateKey provided.", ); }); it("throws if userId is null", async () => { - await expect(cryptoService.setUserKeys(mockUserKey, mockEncPrivateKey, null)).rejects.toThrow( + await expect(keyService.setUserKeys(mockUserKey, mockEncPrivateKey, null)).rejects.toThrow( "No userId provided.", ); }); @@ -359,15 +357,15 @@ describe("cryptoService", () => { encryptService.decryptToBytes.mockResolvedValue(null); await expect( - cryptoService.setUserKeys(mockUserKey, mockEncPrivateKey, mockUserId), + keyService.setUserKeys(mockUserKey, mockEncPrivateKey, mockUserId), ).rejects.toThrow(UserPrivateKeyDecryptionFailedError); }); // We already have tests for setUserKey, so we just need to test that the correct methods are called it("calls setUserKey with the userKey and userId", async () => { - const setUserKeySpy = jest.spyOn(cryptoService, "setUserKey"); + const setUserKeySpy = jest.spyOn(keyService, "setUserKey"); - await cryptoService.setUserKeys(mockUserKey, mockEncPrivateKey, mockUserId); + await keyService.setUserKeys(mockUserKey, mockEncPrivateKey, mockUserId); expect(setUserKeySpy).toHaveBeenCalledWith(mockUserKey, mockUserId); }); @@ -375,9 +373,9 @@ describe("cryptoService", () => { // We already have tests for setPrivateKey, so we just need to test that the correct methods are called // TODO: Move those tests into here since `setPrivateKey` will be converted to a private method it("calls setPrivateKey with the encPrivateKey and userId", async () => { - const setEncryptedPrivateKeySpy = jest.spyOn(cryptoService, "setPrivateKey"); + const setEncryptedPrivateKeySpy = jest.spyOn(keyService, "setPrivateKey"); - await cryptoService.setUserKeys(mockUserKey, mockEncPrivateKey, mockUserId); + await keyService.setUserKeys(mockUserKey, mockEncPrivateKey, mockUserId); expect(setEncryptedPrivateKeySpy).toHaveBeenCalledWith(mockEncPrivateKey, mockUserId); }); @@ -388,7 +386,7 @@ describe("cryptoService", () => { let callCount = 0; stateProvider.activeUserId$ = stateProvider.activeUserId$.pipe(tap(() => callCount++)); - await cryptoService.clearKeys(null); + await keyService.clearKeys(null); expect(callCount).toBe(1); // revert to the original state @@ -402,7 +400,7 @@ describe("cryptoService", () => { USER_KEY, ])("key removal", (key: UserKeyDefinition) => { it(`clears ${key.key} for active user when unspecified`, async () => { - await cryptoService.clearKeys(null); + await keyService.clearKeys(null); const encryptedOrgKeyState = stateProvider.singleUser.getFake(mockUserId, key); expect(encryptedOrgKeyState.nextMock).toHaveBeenCalledTimes(1); @@ -411,7 +409,7 @@ describe("cryptoService", () => { it(`clears ${key.key} for the specified user when specified`, async () => { const userId = "someOtherUser" as UserId; - await cryptoService.clearKeys(userId); + await keyService.clearKeys(userId); const encryptedOrgKeyState = stateProvider.singleUser.getFake(userId, key); expect(encryptedOrgKeyState.nextMock).toHaveBeenCalledTimes(1); @@ -458,7 +456,7 @@ describe("cryptoService", () => { const fakeUserPublicKey = makeStaticByteArray(10, 2); cryptoFunctionService.rsaExtractPublicKey.mockResolvedValue(fakeUserPublicKey); - const userPrivateKey = await firstValueFrom(cryptoService.userPrivateKey$(mockUserId)); + const userPrivateKey = await firstValueFrom(keyService.userPrivateKey$(mockUserId)); expect(encryptService.decryptToBytes).toHaveBeenCalledWith( fakeEncryptedUserPrivateKey, @@ -471,7 +469,7 @@ describe("cryptoService", () => { it("returns null user private key when no user key is found", async () => { setupKeys({ makeMasterKey: false, makeUserKey: false }); - const userPrivateKey = await firstValueFrom(cryptoService.userPrivateKey$(mockUserId)); + const userPrivateKey = await firstValueFrom(keyService.userPrivateKey$(mockUserId)); expect(encryptService.decryptToBytes).not.toHaveBeenCalled(); @@ -487,7 +485,7 @@ describe("cryptoService", () => { ); encryptedUserPrivateKeyState.nextState(null); - const userPrivateKey = await firstValueFrom(cryptoService.userPrivateKey$(mockUserId)); + const userPrivateKey = await firstValueFrom(keyService.userPrivateKey$(mockUserId)); expect(userPrivateKey).toBeFalsy(); }); }); @@ -568,7 +566,7 @@ describe("cryptoService", () => { encryptedPrivateKey: makeEncString("privateKey"), }); - const decryptionKeys = await firstValueFrom(cryptoService.cipherDecryptionKeys$(mockUserId)); + const decryptionKeys = await firstValueFrom(keyService.cipherDecryptionKeys$(mockUserId)); expect(decryptionKeys).not.toBeNull(); expect(decryptionKeys.userKey).not.toBeNull(); @@ -584,7 +582,7 @@ describe("cryptoService", () => { }, }); - const decryptionKeys = await firstValueFrom(cryptoService.cipherDecryptionKeys$(mockUserId)); + const decryptionKeys = await firstValueFrom(keyService.cipherDecryptionKeys$(mockUserId)); expect(decryptionKeys).not.toBeNull(); expect(decryptionKeys.userKey).not.toBeNull(); @@ -605,7 +603,7 @@ describe("cryptoService", () => { providerKeys: {}, }); - const decryptionKeys = await firstValueFrom(cryptoService.cipherDecryptionKeys$(mockUserId)); + const decryptionKeys = await firstValueFrom(keyService.cipherDecryptionKeys$(mockUserId)); expect(decryptionKeys).not.toBeNull(); expect(decryptionKeys.userKey).not.toBeNull(); @@ -634,7 +632,7 @@ describe("cryptoService", () => { }, }); - const decryptionKeys = await firstValueFrom(cryptoService.cipherDecryptionKeys$(mockUserId)); + const decryptionKeys = await firstValueFrom(keyService.cipherDecryptionKeys$(mockUserId)); expect(decryptionKeys).not.toBeNull(); expect(decryptionKeys.userKey).not.toBeNull(); @@ -653,7 +651,7 @@ describe("cryptoService", () => { it("returns a stream that pays attention to updates of all data", async () => { // Start listening until there have been 6 emissions const promise = lastValueFrom( - cryptoService.cipherDecryptionKeys$(mockUserId).pipe(bufferCount(6), take(1)), + keyService.cipherDecryptionKeys$(mockUserId).pipe(bufferCount(6), take(1)), ); // User has their UserKey set diff --git a/libs/common/src/platform/services/crypto.service.ts b/libs/key-management/src/key.service.ts similarity index 91% rename from libs/common/src/platform/services/crypto.service.ts rename to libs/key-management/src/key.service.ts index a6db9a2c1b..b12db176ce 100644 --- a/libs/common/src/platform/services/crypto.service.ts +++ b/libs/key-management/src/key.service.ts @@ -10,20 +10,39 @@ import { switchMap, } from "rxjs"; -import { PinServiceAbstraction } from "../../../../auth/src/common/abstractions"; -import { EncryptedOrganizationKeyData } from "../../admin-console/models/data/encrypted-organization-key.data"; -import { BaseEncryptedOrganizationKey } from "../../admin-console/models/domain/encrypted-organization-key"; -import { ProfileOrganizationResponse } from "../../admin-console/models/response/profile-organization.response"; -import { ProfileProviderOrganizationResponse } from "../../admin-console/models/response/profile-provider-organization.response"; -import { ProfileProviderResponse } from "../../admin-console/models/response/profile-provider.response"; -import { AccountService } from "../../auth/abstractions/account.service"; -import { KdfConfigService } from "../../auth/abstractions/kdf-config.service"; -import { InternalMasterPasswordServiceAbstraction } from "../../auth/abstractions/master-password.service.abstraction"; -import { KdfConfig } from "../../auth/models/domain/kdf-config"; -import { Utils } from "../../platform/misc/utils"; -import { VAULT_TIMEOUT } from "../../services/vault-timeout/vault-timeout-settings.state"; -import { CsprngArray } from "../../types/csprng"; -import { OrganizationId, ProviderId, UserId } from "../../types/guid"; +import { PinServiceAbstraction } from "../../auth/src/common/abstractions"; +import { EncryptedOrganizationKeyData } from "../../common/src/admin-console/models/data/encrypted-organization-key.data"; +import { BaseEncryptedOrganizationKey } from "../../common/src/admin-console/models/domain/encrypted-organization-key"; +import { ProfileOrganizationResponse } from "../../common/src/admin-console/models/response/profile-organization.response"; +import { ProfileProviderOrganizationResponse } from "../../common/src/admin-console/models/response/profile-provider-organization.response"; +import { ProfileProviderResponse } from "../../common/src/admin-console/models/response/profile-provider.response"; +import { AccountService } from "../../common/src/auth/abstractions/account.service"; +import { KdfConfigService } from "../../common/src/auth/abstractions/kdf-config.service"; +import { InternalMasterPasswordServiceAbstraction } from "../../common/src/auth/abstractions/master-password.service.abstraction"; +import { KdfConfig } from "../../common/src/auth/models/domain/kdf-config"; +import { CryptoFunctionService } from "../../common/src/platform/abstractions/crypto-function.service"; +import { EncryptService } from "../../common/src/platform/abstractions/encrypt.service"; +import { KeyGenerationService } from "../../common/src/platform/abstractions/key-generation.service"; +import { LogService } from "../../common/src/platform/abstractions/log.service"; +import { PlatformUtilsService } from "../../common/src/platform/abstractions/platform-utils.service"; +import { StateService } from "../../common/src/platform/abstractions/state.service"; +import { KeySuffixOptions, HashPurpose } from "../../common/src/platform/enums"; +import { convertValues } from "../../common/src/platform/misc/convert-values"; +import { Utils } from "../../common/src/platform/misc/utils"; +import { EFFLongWordList } from "../../common/src/platform/misc/wordlist"; +import { EncString, EncryptedString } from "../../common/src/platform/models/domain/enc-string"; +import { SymmetricCryptoKey } from "../../common/src/platform/models/domain/symmetric-crypto-key"; +import { USER_ENCRYPTED_ORGANIZATION_KEYS } from "../../common/src/platform/services/key-state/org-keys.state"; +import { USER_ENCRYPTED_PROVIDER_KEYS } from "../../common/src/platform/services/key-state/provider-keys.state"; +import { + USER_ENCRYPTED_PRIVATE_KEY, + USER_EVER_HAD_USER_KEY, + USER_KEY, +} from "../../common/src/platform/services/key-state/user-key.state"; +import { ActiveUserState, StateProvider } from "../../common/src/platform/state"; +import { VAULT_TIMEOUT } from "../../common/src/services/vault-timeout/vault-timeout-settings.state"; +import { CsprngArray } from "../../common/src/types/csprng"; +import { OrganizationId, ProviderId, UserId } from "../../common/src/types/guid"; import { OrgKey, UserKey, @@ -32,35 +51,16 @@ import { CipherKey, UserPrivateKey, UserPublicKey, -} from "../../types/key"; -import { VaultTimeoutStringType } from "../../types/vault-timeout.type"; -import { CryptoFunctionService } from "../abstractions/crypto-function.service"; +} from "../../common/src/types/key"; +import { VaultTimeoutStringType } from "../../common/src/types/vault-timeout.type"; + import { CipherDecryptionKeys, - CryptoService as CryptoServiceAbstraction, + KeyService as KeyServiceAbstraction, UserPrivateKeyDecryptionFailedError, -} from "../abstractions/crypto.service"; -import { EncryptService } from "../abstractions/encrypt.service"; -import { KeyGenerationService } from "../abstractions/key-generation.service"; -import { LogService } from "../abstractions/log.service"; -import { PlatformUtilsService } from "../abstractions/platform-utils.service"; -import { StateService } from "../abstractions/state.service"; -import { KeySuffixOptions, HashPurpose } from "../enums"; -import { convertValues } from "../misc/convert-values"; -import { EFFLongWordList } from "../misc/wordlist"; -import { EncString, EncryptedString } from "../models/domain/enc-string"; -import { SymmetricCryptoKey } from "../models/domain/symmetric-crypto-key"; -import { ActiveUserState, StateProvider } from "../state"; +} from "./abstractions/key.service"; -import { USER_ENCRYPTED_ORGANIZATION_KEYS } from "./key-state/org-keys.state"; -import { USER_ENCRYPTED_PROVIDER_KEYS } from "./key-state/provider-keys.state"; -import { - USER_ENCRYPTED_PRIVATE_KEY, - USER_EVER_HAD_USER_KEY, - USER_KEY, -} from "./key-state/user-key.state"; - -export class CryptoService implements CryptoServiceAbstraction { +export class DefaultKeyService implements KeyServiceAbstraction { private readonly activeUserEverHadUserKey: ActiveUserState; readonly everHadUserKey$: Observable; diff --git a/libs/tools/export/vault-export/vault-export-core/src/services/individual-vault-export.service.spec.ts b/libs/tools/export/vault-export/vault-export-core/src/services/individual-vault-export.service.spec.ts index 1a66fe9225..d264991ae4 100644 --- a/libs/tools/export/vault-export/vault-export-core/src/services/individual-vault-export.service.spec.ts +++ b/libs/tools/export/vault-export/vault-export-core/src/services/individual-vault-export.service.spec.ts @@ -10,7 +10,6 @@ import { } from "@bitwarden/common/auth/models/domain/kdf-config"; import { CipherWithIdExport } from "@bitwarden/common/models/export/cipher-with-ids.export"; import { CryptoFunctionService } from "@bitwarden/common/platform/abstractions/crypto-function.service"; -import { CryptoService } from "@bitwarden/common/platform/abstractions/crypto.service"; import { EncryptService } from "@bitwarden/common/platform/abstractions/encrypt.service"; import { KdfType } from "@bitwarden/common/platform/enums"; import { Utils } from "@bitwarden/common/platform/misc/utils"; @@ -25,6 +24,7 @@ import { Login } from "@bitwarden/common/vault/models/domain/login"; import { CipherView } from "@bitwarden/common/vault/models/view/cipher.view"; import { FolderView } from "@bitwarden/common/vault/models/view/folder.view"; import { LoginView } from "@bitwarden/common/vault/models/view/login.view"; +import { KeyService } from "@bitwarden/key-management"; import { BuildTestObject, GetUniqueString } from "../../../../../../common/spec"; @@ -152,7 +152,7 @@ describe("VaultExportService", () => { let cipherService: MockProxy; let pinService: MockProxy; let folderService: MockProxy; - let cryptoService: MockProxy; + let keyService: MockProxy; let encryptService: MockProxy; let kdfConfigService: MockProxy; let accountService: MockProxy; @@ -162,12 +162,12 @@ describe("VaultExportService", () => { cipherService = mock(); pinService = mock(); folderService = mock(); - cryptoService = mock(); + keyService = mock(); encryptService = mock(); kdfConfigService = mock(); accountService = mock(); - cryptoService.userKey$.mockReturnValue(new BehaviorSubject("mockOriginalUserKey" as any)); + keyService.userKey$.mockReturnValue(new BehaviorSubject("mockOriginalUserKey" as any)); const userId = "" as UserId; const accountInfo: AccountInfo = { @@ -187,7 +187,7 @@ describe("VaultExportService", () => { folderService, cipherService, pinService, - cryptoService, + keyService, encryptService, cryptoFunctionService, kdfConfigService, diff --git a/libs/tools/export/vault-export/vault-export-core/src/services/individual-vault-export.service.ts b/libs/tools/export/vault-export/vault-export-core/src/services/individual-vault-export.service.ts index d6d37b28ac..04dba1299d 100644 --- a/libs/tools/export/vault-export/vault-export-core/src/services/individual-vault-export.service.ts +++ b/libs/tools/export/vault-export/vault-export-core/src/services/individual-vault-export.service.ts @@ -6,7 +6,6 @@ import { AccountService } from "@bitwarden/common/auth/abstractions/account.serv import { KdfConfigService } from "@bitwarden/common/auth/abstractions/kdf-config.service"; import { CipherWithIdExport, FolderWithIdExport } from "@bitwarden/common/models/export"; import { CryptoFunctionService } from "@bitwarden/common/platform/abstractions/crypto-function.service"; -import { CryptoService } from "@bitwarden/common/platform/abstractions/crypto.service"; import { EncryptService } from "@bitwarden/common/platform/abstractions/encrypt.service"; import { Utils } from "@bitwarden/common/platform/misc/utils"; import { CipherService } from "@bitwarden/common/vault/abstractions/cipher.service"; @@ -16,6 +15,7 @@ import { Cipher } from "@bitwarden/common/vault/models/domain/cipher"; import { Folder } from "@bitwarden/common/vault/models/domain/folder"; import { CipherView } from "@bitwarden/common/vault/models/view/cipher.view"; import { FolderView } from "@bitwarden/common/vault/models/view/folder.view"; +import { KeyService } from "@bitwarden/key-management"; import { BitwardenCsvIndividualExportType, @@ -35,7 +35,7 @@ export class IndividualVaultExportService private folderService: FolderService, private cipherService: CipherService, pinService: PinServiceAbstraction, - private cryptoService: CryptoService, + private keyService: KeyService, encryptService: EncryptService, cryptoFunctionService: CryptoFunctionService, kdfConfigService: KdfConfigService, @@ -104,7 +104,7 @@ export class IndividualVaultExportService const activeUserId = await firstValueFrom( this.accountService.activeAccount$.pipe(map((a) => a?.id)), ); - const userKey = await this.cryptoService.getUserKeyWithLegacySupport(activeUserId); + const userKey = await this.keyService.getUserKeyWithLegacySupport(activeUserId); const encKeyValidation = await this.encryptService.encrypt(Utils.newGuid(), userKey); const jsonDoc: BitwardenEncryptedIndividualJsonExport = { diff --git a/libs/tools/export/vault-export/vault-export-core/src/services/org-vault-export.service.ts b/libs/tools/export/vault-export/vault-export-core/src/services/org-vault-export.service.ts index 28ffa8e83d..4e23a0ed25 100644 --- a/libs/tools/export/vault-export/vault-export-core/src/services/org-vault-export.service.ts +++ b/libs/tools/export/vault-export/vault-export-core/src/services/org-vault-export.service.ts @@ -14,7 +14,6 @@ import { AccountService } from "@bitwarden/common/auth/abstractions/account.serv import { KdfConfigService } from "@bitwarden/common/auth/abstractions/kdf-config.service"; import { CipherWithIdExport, CollectionWithIdExport } from "@bitwarden/common/models/export"; import { CryptoFunctionService } from "@bitwarden/common/platform/abstractions/crypto-function.service"; -import { CryptoService } from "@bitwarden/common/platform/abstractions/crypto.service"; import { EncryptService } from "@bitwarden/common/platform/abstractions/encrypt.service"; import { Utils } from "@bitwarden/common/platform/misc/utils"; import { OrganizationId } from "@bitwarden/common/types/guid"; @@ -23,6 +22,7 @@ import { CipherType } from "@bitwarden/common/vault/enums"; import { CipherData } from "@bitwarden/common/vault/models/data/cipher.data"; import { Cipher } from "@bitwarden/common/vault/models/domain/cipher"; import { CipherView } from "@bitwarden/common/vault/models/view/cipher.view"; +import { KeyService } from "@bitwarden/key-management"; import { BitwardenCsvOrgExportType, @@ -42,7 +42,7 @@ export class OrganizationVaultExportService private cipherService: CipherService, private apiService: ApiService, pinService: PinServiceAbstraction, - private cryptoService: CryptoService, + private keyService: KeyService, encryptService: EncryptService, cryptoFunctionService: CryptoFunctionService, private collectionService: CollectionService, @@ -105,7 +105,7 @@ export class OrganizationVaultExportService exportData.collections.forEach((c) => { const collection = new Collection(new CollectionData(c as CollectionDetailsResponse)); exportPromises.push( - firstValueFrom(this.cryptoService.activeUserOrgKeys$) + firstValueFrom(this.keyService.activeUserOrgKeys$) .then((keys) => collection.decrypt(keys[organizationId as OrganizationId])) .then((decCol) => { decCollections.push(decCol); @@ -245,7 +245,7 @@ export class OrganizationVaultExportService collections: Collection[], ciphers: Cipher[], ): Promise { - const orgKey = await this.cryptoService.getOrgKey(organizationId); + const orgKey = await this.keyService.getOrgKey(organizationId); const encKeyValidation = await this.encryptService.encrypt(Utils.newGuid(), orgKey); const jsonDoc: BitwardenEncryptedOrgJsonExport = { diff --git a/libs/tools/export/vault-export/vault-export-core/src/services/vault-export.service.spec.ts b/libs/tools/export/vault-export/vault-export-core/src/services/vault-export.service.spec.ts index 7e93c78fc5..525e769957 100644 --- a/libs/tools/export/vault-export/vault-export-core/src/services/vault-export.service.spec.ts +++ b/libs/tools/export/vault-export/vault-export-core/src/services/vault-export.service.spec.ts @@ -10,7 +10,6 @@ import { } from "@bitwarden/common/auth/models/domain/kdf-config"; import { CipherWithIdExport } from "@bitwarden/common/models/export/cipher-with-ids.export"; import { CryptoFunctionService } from "@bitwarden/common/platform/abstractions/crypto-function.service"; -import { CryptoService } from "@bitwarden/common/platform/abstractions/crypto.service"; import { EncryptService } from "@bitwarden/common/platform/abstractions/encrypt.service"; import { KdfType } from "@bitwarden/common/platform/enums"; import { Utils } from "@bitwarden/common/platform/misc/utils"; @@ -25,6 +24,7 @@ import { Login } from "@bitwarden/common/vault/models/domain/login"; import { CipherView } from "@bitwarden/common/vault/models/view/cipher.view"; import { FolderView } from "@bitwarden/common/vault/models/view/folder.view"; import { LoginView } from "@bitwarden/common/vault/models/view/login.view"; +import { KeyService } from "@bitwarden/key-management"; import { BuildTestObject, GetUniqueString } from "../../../../../../common/spec"; @@ -152,7 +152,7 @@ describe("VaultExportService", () => { let cipherService: MockProxy; let pinService: MockProxy; let folderService: MockProxy; - let cryptoService: MockProxy; + let keyService: MockProxy; let encryptService: MockProxy; let accountService: MockProxy; let kdfConfigService: MockProxy; @@ -162,7 +162,7 @@ describe("VaultExportService", () => { cipherService = mock(); pinService = mock(); folderService = mock(); - cryptoService = mock(); + keyService = mock(); encryptService = mock(); accountService = mock(); @@ -172,7 +172,7 @@ describe("VaultExportService", () => { folderService.getAllFromState.mockResolvedValue(UserFolders); kdfConfigService.getKdfConfig.mockResolvedValue(DEFAULT_KDF_CONFIG); encryptService.encrypt.mockResolvedValue(new EncString("encrypted")); - cryptoService.userKey$.mockReturnValue(new BehaviorSubject("mockOriginalUserKey" as any)); + keyService.userKey$.mockReturnValue(new BehaviorSubject("mockOriginalUserKey" as any)); const userId = "" as UserId; const accountInfo: AccountInfo = { email: "", @@ -186,7 +186,7 @@ describe("VaultExportService", () => { folderService, cipherService, pinService, - cryptoService, + keyService, encryptService, cryptoFunctionService, kdfConfigService, diff --git a/libs/tools/generator/components/src/generator.module.ts b/libs/tools/generator/components/src/generator.module.ts index 58117bec49..2d1cedca40 100644 --- a/libs/tools/generator/components/src/generator.module.ts +++ b/libs/tools/generator/components/src/generator.module.ts @@ -7,7 +7,6 @@ import { safeProvider } from "@bitwarden/angular/platform/utils/safe-provider"; import { SafeInjectionToken } from "@bitwarden/angular/services/injection-tokens"; import { ApiService } from "@bitwarden/common/abstractions/api.service"; import { PolicyService } from "@bitwarden/common/admin-console/abstractions/policy/policy.service.abstraction"; -import { CryptoService } from "@bitwarden/common/platform/abstractions/crypto.service"; import { EncryptService } from "@bitwarden/common/platform/abstractions/encrypt.service"; import { I18nService } from "@bitwarden/common/platform/abstractions/i18n.service"; import { StateProvider } from "@bitwarden/common/platform/state"; @@ -30,6 +29,7 @@ import { CredentialGeneratorService, Randomizer, } from "@bitwarden/generator-core"; +import { KeyService } from "@bitwarden/key-management"; import { CatchallSettingsComponent } from "./catchall-settings.component"; import { CredentialGeneratorComponent } from "./credential-generator.component"; @@ -66,7 +66,7 @@ const RANDOMIZER = new SafeInjectionToken("Randomizer"); safeProvider({ provide: RANDOMIZER, useFactory: createRandomizer, - deps: [CryptoService], + deps: [KeyService], }), safeProvider({ provide: CredentialGeneratorService, @@ -78,7 +78,7 @@ const RANDOMIZER = new SafeInjectionToken("Randomizer"); ApiService, I18nService, EncryptService, - CryptoService, + KeyService, ], }), ], diff --git a/libs/tools/generator/core/src/engine/index.ts b/libs/tools/generator/core/src/engine/index.ts index c3d2aefef1..2d272e7c11 100644 --- a/libs/tools/generator/core/src/engine/index.ts +++ b/libs/tools/generator/core/src/engine/index.ts @@ -1,4 +1,4 @@ -export { CryptoServiceRandomizer } from "./crypto-service-randomizer"; +export { KeyServiceRandomizer } from "./key-service-randomizer"; export { ForwarderConfiguration, AccountRequest } from "./forwarder-configuration"; export { ForwarderContext } from "./forwarder-context"; export * from "./settings"; diff --git a/libs/tools/generator/core/src/engine/crypto-service-randomizer.spec.ts b/libs/tools/generator/core/src/engine/key-service-randomizer.spec.ts similarity index 58% rename from libs/tools/generator/core/src/engine/crypto-service-randomizer.spec.ts rename to libs/tools/generator/core/src/engine/key-service-randomizer.spec.ts index c3908bc86a..459a05618f 100644 --- a/libs/tools/generator/core/src/engine/crypto-service-randomizer.spec.ts +++ b/libs/tools/generator/core/src/engine/key-service-randomizer.spec.ts @@ -1,11 +1,11 @@ import { mock } from "jest-mock-extended"; -import { CryptoService } from "@bitwarden/common/platform/abstractions/crypto.service"; +import { KeyService } from "@bitwarden/key-management"; -import { CryptoServiceRandomizer } from "./crypto-service-randomizer"; +import { KeyServiceRandomizer } from "./key-service-randomizer"; -describe("CryptoServiceRandomizer", () => { - const cryptoService = mock(); +describe("KeyServiceRandomizer", () => { + const keyService = mock(); afterEach(() => { jest.resetAllMocks(); @@ -13,7 +13,7 @@ describe("CryptoServiceRandomizer", () => { describe("pick", () => { it.each([[null], [undefined], [[]]])("throws when the list is %p", async (list) => { - const randomizer = new CryptoServiceRandomizer(cryptoService); + const randomizer = new KeyServiceRandomizer(keyService); await expect(() => randomizer.pick(list)).rejects.toBeInstanceOf(Error); @@ -21,8 +21,8 @@ describe("CryptoServiceRandomizer", () => { }); it("picks an item from the list", async () => { - const randomizer = new CryptoServiceRandomizer(cryptoService); - cryptoService.randomNumber.mockResolvedValue(1); + const randomizer = new KeyServiceRandomizer(keyService); + keyService.randomNumber.mockResolvedValue(1); const result = await randomizer.pick([0, 1]); @@ -32,7 +32,7 @@ describe("CryptoServiceRandomizer", () => { describe("pickWord", () => { it.each([[null], [undefined], [[]]])("throws when the list is %p", async (list) => { - const randomizer = new CryptoServiceRandomizer(cryptoService); + const randomizer = new KeyServiceRandomizer(keyService); await expect(() => randomizer.pickWord(list)).rejects.toBeInstanceOf(Error); @@ -40,8 +40,8 @@ describe("CryptoServiceRandomizer", () => { }); it("picks a word from the list", async () => { - const randomizer = new CryptoServiceRandomizer(cryptoService); - cryptoService.randomNumber.mockResolvedValue(1); + const randomizer = new KeyServiceRandomizer(keyService); + keyService.randomNumber.mockResolvedValue(1); const result = await randomizer.pickWord(["foo", "bar"]); @@ -49,8 +49,8 @@ describe("CryptoServiceRandomizer", () => { }); it("capitalizes the word when options.titleCase is true", async () => { - const randomizer = new CryptoServiceRandomizer(cryptoService); - cryptoService.randomNumber.mockResolvedValue(1); + const randomizer = new KeyServiceRandomizer(keyService); + keyService.randomNumber.mockResolvedValue(1); const result = await randomizer.pickWord(["foo", "bar"], { titleCase: true }); @@ -58,9 +58,9 @@ describe("CryptoServiceRandomizer", () => { }); it("appends a random number when options.number is true", async () => { - const randomizer = new CryptoServiceRandomizer(cryptoService); - cryptoService.randomNumber.mockResolvedValueOnce(1); - cryptoService.randomNumber.mockResolvedValueOnce(2); + const randomizer = new KeyServiceRandomizer(keyService); + keyService.randomNumber.mockResolvedValueOnce(1); + keyService.randomNumber.mockResolvedValueOnce(2); const result = await randomizer.pickWord(["foo", "bar"], { number: true }); @@ -70,7 +70,7 @@ describe("CryptoServiceRandomizer", () => { describe("shuffle", () => { it.each([[null], [undefined], [[]]])("throws when the list is %p", async (list) => { - const randomizer = new CryptoServiceRandomizer(cryptoService); + const randomizer = new KeyServiceRandomizer(keyService); await expect(() => randomizer.shuffle(list)).rejects.toBeInstanceOf(Error); @@ -78,18 +78,18 @@ describe("CryptoServiceRandomizer", () => { }); it("returns a copy of the list without shuffling it when theres only one entry", async () => { - const randomizer = new CryptoServiceRandomizer(cryptoService); + const randomizer = new KeyServiceRandomizer(keyService); const result = await randomizer.shuffle(["foo"]); expect(result).toEqual(["foo"]); expect(result).not.toBe(["foo"]); - expect(cryptoService.randomNumber).not.toHaveBeenCalled(); + expect(keyService.randomNumber).not.toHaveBeenCalled(); }); it("shuffles the tail of the list", async () => { - const randomizer = new CryptoServiceRandomizer(cryptoService); - cryptoService.randomNumber.mockResolvedValueOnce(0); + const randomizer = new KeyServiceRandomizer(keyService); + keyService.randomNumber.mockResolvedValueOnce(0); const result = await randomizer.shuffle(["bar", "foo"]); @@ -97,9 +97,9 @@ describe("CryptoServiceRandomizer", () => { }); it("shuffles the list", async () => { - const randomizer = new CryptoServiceRandomizer(cryptoService); - cryptoService.randomNumber.mockResolvedValueOnce(0); - cryptoService.randomNumber.mockResolvedValueOnce(1); + const randomizer = new KeyServiceRandomizer(keyService); + keyService.randomNumber.mockResolvedValueOnce(0); + keyService.randomNumber.mockResolvedValueOnce(1); const result = await randomizer.shuffle(["baz", "bar", "foo"]); @@ -107,8 +107,8 @@ describe("CryptoServiceRandomizer", () => { }); it("returns the input list when options.copy is false", async () => { - const randomizer = new CryptoServiceRandomizer(cryptoService); - cryptoService.randomNumber.mockResolvedValueOnce(0); + const randomizer = new KeyServiceRandomizer(keyService); + keyService.randomNumber.mockResolvedValueOnce(0); const expectedResult = ["foo"]; const result = await randomizer.shuffle(expectedResult, { copy: false }); @@ -119,7 +119,7 @@ describe("CryptoServiceRandomizer", () => { describe("chars", () => { it("returns an empty string when the length is 0", async () => { - const randomizer = new CryptoServiceRandomizer(cryptoService); + const randomizer = new KeyServiceRandomizer(keyService); const result = await randomizer.chars(0); @@ -127,8 +127,8 @@ describe("CryptoServiceRandomizer", () => { }); it("returns an arbitrary lowercase ascii character", async () => { - const randomizer = new CryptoServiceRandomizer(cryptoService); - cryptoService.randomNumber.mockResolvedValueOnce(0); + const randomizer = new KeyServiceRandomizer(keyService); + keyService.randomNumber.mockResolvedValueOnce(0); const result = await randomizer.chars(1); @@ -136,38 +136,38 @@ describe("CryptoServiceRandomizer", () => { }); it("returns a number of ascii characters based on the length", async () => { - const randomizer = new CryptoServiceRandomizer(cryptoService); - cryptoService.randomNumber.mockResolvedValue(0); + const randomizer = new KeyServiceRandomizer(keyService); + keyService.randomNumber.mockResolvedValue(0); const result = await randomizer.chars(2); expect(result).toEqual("aa"); - expect(cryptoService.randomNumber).toHaveBeenCalledTimes(2); + expect(keyService.randomNumber).toHaveBeenCalledTimes(2); }); it("returns a new random character each time its called", async () => { - const randomizer = new CryptoServiceRandomizer(cryptoService); - cryptoService.randomNumber.mockResolvedValueOnce(0); - cryptoService.randomNumber.mockResolvedValueOnce(1); + const randomizer = new KeyServiceRandomizer(keyService); + keyService.randomNumber.mockResolvedValueOnce(0); + keyService.randomNumber.mockResolvedValueOnce(1); const resultA = await randomizer.chars(1); const resultB = await randomizer.chars(1); expect(resultA).toEqual("a"); expect(resultB).toEqual("b"); - expect(cryptoService.randomNumber).toHaveBeenCalledTimes(2); + expect(keyService.randomNumber).toHaveBeenCalledTimes(2); }); }); describe("uniform", () => { it("forwards requests to the crypto service", async () => { - const randomizer = new CryptoServiceRandomizer(cryptoService); - cryptoService.randomNumber.mockResolvedValue(5); + const randomizer = new KeyServiceRandomizer(keyService); + keyService.randomNumber.mockResolvedValue(5); const result = await randomizer.uniform(0, 5); expect(result).toBe(5); - expect(cryptoService.randomNumber).toHaveBeenCalledWith(0, 5); + expect(keyService.randomNumber).toHaveBeenCalledWith(0, 5); }); }); }); diff --git a/libs/tools/generator/core/src/engine/crypto-service-randomizer.ts b/libs/tools/generator/core/src/engine/key-service-randomizer.ts similarity index 79% rename from libs/tools/generator/core/src/engine/crypto-service-randomizer.ts rename to libs/tools/generator/core/src/engine/key-service-randomizer.ts index cc7ceef4bb..5fc719042b 100644 --- a/libs/tools/generator/core/src/engine/crypto-service-randomizer.ts +++ b/libs/tools/generator/core/src/engine/key-service-randomizer.ts @@ -1,14 +1,14 @@ -import { CryptoService } from "@bitwarden/common/platform/abstractions/crypto.service"; +import { KeyService } from "@bitwarden/key-management"; import { Randomizer } from "../abstractions"; import { WordOptions } from "../types"; -/** A randomizer backed by a CryptoService. */ -export class CryptoServiceRandomizer implements Randomizer { +/** A randomizer backed by a KeyService. */ +export class KeyServiceRandomizer implements Randomizer { /** instantiates the type. - * @param crypto generates random numbers + * @param keyService generates random numbers */ - constructor(private crypto: CryptoService) {} + constructor(private keyService: KeyService) {} async pick(list: Array): Promise { const length = list?.length ?? 0; @@ -28,7 +28,7 @@ export class CryptoServiceRandomizer implements Randomizer { } if (options?.number ?? false) { - const num = await this.crypto.randomNumber(1, 9); + const num = await this.keyService.randomNumber(1, 9); word = word + num.toString(); } @@ -63,6 +63,6 @@ export class CryptoServiceRandomizer implements Randomizer { } async uniform(min: number, max: number) { - return this.crypto.randomNumber(min, max); + return this.keyService.randomNumber(min, max); } } diff --git a/libs/tools/generator/core/src/factories.ts b/libs/tools/generator/core/src/factories.ts index 6c09b8d315..479545c78f 100644 --- a/libs/tools/generator/core/src/factories.ts +++ b/libs/tools/generator/core/src/factories.ts @@ -1,11 +1,11 @@ // contains logic that constructs generator services dynamically given // a generator id. -import { CryptoService } from "@bitwarden/common/platform/abstractions/crypto.service"; +import { KeyService } from "@bitwarden/key-management"; import { Randomizer } from "./abstractions"; -import { CryptoServiceRandomizer } from "./engine/crypto-service-randomizer"; +import { KeyServiceRandomizer } from "./engine/key-service-randomizer"; -export function createRandomizer(cryptoService: CryptoService): Randomizer { - return new CryptoServiceRandomizer(cryptoService); +export function createRandomizer(keyService: KeyService): Randomizer { + return new KeyServiceRandomizer(keyService); } diff --git a/libs/tools/generator/core/src/services/credential-generator.service.spec.ts b/libs/tools/generator/core/src/services/credential-generator.service.spec.ts index e11e555d6a..edb817361d 100644 --- a/libs/tools/generator/core/src/services/credential-generator.service.spec.ts +++ b/libs/tools/generator/core/src/services/credential-generator.service.spec.ts @@ -5,13 +5,13 @@ import { ApiService } from "@bitwarden/common/abstractions/api.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 { CryptoService } from "@bitwarden/common/platform/abstractions/crypto.service"; import { EncryptService } from "@bitwarden/common/platform/abstractions/encrypt.service"; import { I18nService } from "@bitwarden/common/platform/abstractions/i18n.service"; import { GENERATOR_DISK, UserKeyDefinition } from "@bitwarden/common/platform/state"; import { StateConstraints } from "@bitwarden/common/tools/types"; import { OrganizationId, PolicyId, UserId } from "@bitwarden/common/types/guid"; import { UserKey } from "@bitwarden/common/types/key"; +import { KeyService } from "@bitwarden/key-management"; import { FakeStateProvider, @@ -175,7 +175,7 @@ const apiService = mock(); const encryptService = mock(); -const cryptoService = mock(); +const keyService = mock(); describe("CredentialGeneratorService", () => { beforeEach(async () => { @@ -184,7 +184,7 @@ describe("CredentialGeneratorService", () => { i18nService.t.mockImplementation((key) => key); apiService.fetch.mockImplementation(() => Promise.resolve(mock())); const keyAvailable = new BehaviorSubject({} as UserKey); - cryptoService.userKey$.mockReturnValue(keyAvailable); + keyService.userKey$.mockReturnValue(keyAvailable); jest.clearAllMocks(); }); @@ -199,7 +199,7 @@ describe("CredentialGeneratorService", () => { apiService, i18nService, encryptService, - cryptoService, + keyService, ); const generated = new ObservableTracker(generator.generate$(SomeConfiguration)); @@ -220,7 +220,7 @@ describe("CredentialGeneratorService", () => { apiService, i18nService, encryptService, - cryptoService, + keyService, ); const generated = new ObservableTracker(generator.generate$(SomeConfiguration)); @@ -245,7 +245,7 @@ describe("CredentialGeneratorService", () => { apiService, i18nService, encryptService, - cryptoService, + keyService, ); const generated = new ObservableTracker(generator.generate$(SomeConfiguration)); @@ -273,7 +273,7 @@ describe("CredentialGeneratorService", () => { apiService, i18nService, encryptService, - cryptoService, + keyService, ); const website$ = new BehaviorSubject("some website"); const generated = new ObservableTracker(generator.generate$(SomeConfiguration, { website$ })); @@ -294,7 +294,7 @@ describe("CredentialGeneratorService", () => { apiService, i18nService, encryptService, - cryptoService, + keyService, ); const website$ = new BehaviorSubject("some website"); let error = null; @@ -319,7 +319,7 @@ describe("CredentialGeneratorService", () => { apiService, i18nService, encryptService, - cryptoService, + keyService, ); const website$ = new BehaviorSubject("some website"); let completed = false; @@ -345,7 +345,7 @@ describe("CredentialGeneratorService", () => { apiService, i18nService, encryptService, - cryptoService, + keyService, ); const userId$ = new BehaviorSubject(AnotherUser).asObservable(); const generated = new ObservableTracker(generator.generate$(SomeConfiguration, { userId$ })); @@ -365,7 +365,7 @@ describe("CredentialGeneratorService", () => { apiService, i18nService, encryptService, - cryptoService, + keyService, ); const userId = new BehaviorSubject(SomeUser); const userId$ = userId.pipe(filter((u) => !!u)); @@ -389,7 +389,7 @@ describe("CredentialGeneratorService", () => { apiService, i18nService, encryptService, - cryptoService, + keyService, ); const userId$ = new BehaviorSubject(SomeUser); let error = null; @@ -414,7 +414,7 @@ describe("CredentialGeneratorService", () => { apiService, i18nService, encryptService, - cryptoService, + keyService, ); const userId$ = new BehaviorSubject(SomeUser); let completed = false; @@ -440,7 +440,7 @@ describe("CredentialGeneratorService", () => { apiService, i18nService, encryptService, - cryptoService, + keyService, ); const on$ = new Subject(); const results: any[] = []; @@ -482,7 +482,7 @@ describe("CredentialGeneratorService", () => { apiService, i18nService, encryptService, - cryptoService, + keyService, ); const on$ = new Subject(); let error: any = null; @@ -508,7 +508,7 @@ describe("CredentialGeneratorService", () => { apiService, i18nService, encryptService, - cryptoService, + keyService, ); const on$ = new Subject(); let complete = false; @@ -539,7 +539,7 @@ describe("CredentialGeneratorService", () => { apiService, i18nService, encryptService, - cryptoService, + keyService, ); const result = generator.algorithms("password"); @@ -560,7 +560,7 @@ describe("CredentialGeneratorService", () => { apiService, i18nService, encryptService, - cryptoService, + keyService, ); const result = generator.algorithms("username"); @@ -580,7 +580,7 @@ describe("CredentialGeneratorService", () => { apiService, i18nService, encryptService, - cryptoService, + keyService, ); const result = generator.algorithms("email"); @@ -601,7 +601,7 @@ describe("CredentialGeneratorService", () => { apiService, i18nService, encryptService, - cryptoService, + keyService, ); const result = generator.algorithms(["username", "email"]); @@ -626,7 +626,7 @@ describe("CredentialGeneratorService", () => { apiService, i18nService, encryptService, - cryptoService, + keyService, ); const result = await firstValueFrom(generator.algorithms$("password")); @@ -643,7 +643,7 @@ describe("CredentialGeneratorService", () => { apiService, i18nService, encryptService, - cryptoService, + keyService, ); const result = await firstValueFrom(generator.algorithms$("username")); @@ -659,7 +659,7 @@ describe("CredentialGeneratorService", () => { apiService, i18nService, encryptService, - cryptoService, + keyService, ); const result = await firstValueFrom(generator.algorithms$("email")); @@ -676,7 +676,7 @@ describe("CredentialGeneratorService", () => { apiService, i18nService, encryptService, - cryptoService, + keyService, ); const result = await firstValueFrom(generator.algorithms$(["username", "email"])); @@ -698,7 +698,7 @@ describe("CredentialGeneratorService", () => { apiService, i18nService, encryptService, - cryptoService, + keyService, ); const result = await firstValueFrom(generator.algorithms$(["password"])); @@ -723,7 +723,7 @@ describe("CredentialGeneratorService", () => { apiService, i18nService, encryptService, - cryptoService, + keyService, ); const results: any = []; const sub = generator.algorithms$("password").subscribe((r) => results.push(r)); @@ -760,7 +760,7 @@ describe("CredentialGeneratorService", () => { apiService, i18nService, encryptService, - cryptoService, + keyService, ); const userId$ = new BehaviorSubject(AnotherUser).asObservable(); @@ -781,7 +781,7 @@ describe("CredentialGeneratorService", () => { apiService, i18nService, encryptService, - cryptoService, + keyService, ); const userId = new BehaviorSubject(SomeUser); const userId$ = userId.asObservable(); @@ -811,7 +811,7 @@ describe("CredentialGeneratorService", () => { apiService, i18nService, encryptService, - cryptoService, + keyService, ); const userId = new BehaviorSubject(SomeUser); const userId$ = userId.asObservable(); @@ -837,7 +837,7 @@ describe("CredentialGeneratorService", () => { apiService, i18nService, encryptService, - cryptoService, + keyService, ); const userId = new BehaviorSubject(SomeUser); const userId$ = userId.asObservable(); @@ -863,7 +863,7 @@ describe("CredentialGeneratorService", () => { apiService, i18nService, encryptService, - cryptoService, + keyService, ); const userId = new BehaviorSubject(SomeUser); const userId$ = userId.asObservable(); @@ -895,7 +895,7 @@ describe("CredentialGeneratorService", () => { apiService, i18nService, encryptService, - cryptoService, + keyService, ); const result = await firstValueFrom(generator.settings$(SomeConfiguration)); @@ -913,7 +913,7 @@ describe("CredentialGeneratorService", () => { apiService, i18nService, encryptService, - cryptoService, + keyService, ); const result = await firstValueFrom(generator.settings$(SomeConfiguration)); @@ -933,7 +933,7 @@ describe("CredentialGeneratorService", () => { apiService, i18nService, encryptService, - cryptoService, + keyService, ); const result = await firstValueFrom(generator.settings$(SomeConfiguration)); @@ -958,7 +958,7 @@ describe("CredentialGeneratorService", () => { apiService, i18nService, encryptService, - cryptoService, + keyService, ); const results: any = []; const sub = generator.settings$(SomeConfiguration).subscribe((r) => results.push(r)); @@ -983,7 +983,7 @@ describe("CredentialGeneratorService", () => { apiService, i18nService, encryptService, - cryptoService, + keyService, ); const userId$ = new BehaviorSubject(AnotherUser).asObservable(); @@ -1004,7 +1004,7 @@ describe("CredentialGeneratorService", () => { apiService, i18nService, encryptService, - cryptoService, + keyService, ); const userId = new BehaviorSubject(SomeUser); const userId$ = userId.asObservable(); @@ -1031,7 +1031,7 @@ describe("CredentialGeneratorService", () => { apiService, i18nService, encryptService, - cryptoService, + keyService, ); const userId = new BehaviorSubject(SomeUser); const userId$ = userId.asObservable(); @@ -1057,7 +1057,7 @@ describe("CredentialGeneratorService", () => { apiService, i18nService, encryptService, - cryptoService, + keyService, ); const userId = new BehaviorSubject(SomeUser); const userId$ = userId.asObservable(); @@ -1083,7 +1083,7 @@ describe("CredentialGeneratorService", () => { apiService, i18nService, encryptService, - cryptoService, + keyService, ); const userId = new BehaviorSubject(SomeUser); const userId$ = userId.asObservable(); @@ -1115,7 +1115,7 @@ describe("CredentialGeneratorService", () => { apiService, i18nService, encryptService, - cryptoService, + keyService, ); const subject = await generator.settings(SomeConfiguration, { singleUserId$ }); @@ -1136,7 +1136,7 @@ describe("CredentialGeneratorService", () => { apiService, i18nService, encryptService, - cryptoService, + keyService, ); let completed = false; @@ -1162,7 +1162,7 @@ describe("CredentialGeneratorService", () => { apiService, i18nService, encryptService, - cryptoService, + keyService, ); const userId$ = new BehaviorSubject(SomeUser).asObservable(); @@ -1179,7 +1179,7 @@ describe("CredentialGeneratorService", () => { apiService, i18nService, encryptService, - cryptoService, + keyService, ); const userId$ = new BehaviorSubject(SomeUser).asObservable(); const policy$ = new BehaviorSubject([somePolicy]); @@ -1198,7 +1198,7 @@ describe("CredentialGeneratorService", () => { apiService, i18nService, encryptService, - cryptoService, + keyService, ); const userId = new BehaviorSubject(SomeUser); const userId$ = userId.asObservable(); @@ -1227,7 +1227,7 @@ describe("CredentialGeneratorService", () => { apiService, i18nService, encryptService, - cryptoService, + keyService, ); const userId = new BehaviorSubject(SomeUser); const userId$ = userId.asObservable(); @@ -1257,7 +1257,7 @@ describe("CredentialGeneratorService", () => { apiService, i18nService, encryptService, - cryptoService, + keyService, ); const userId = new BehaviorSubject(SomeUser); const userId$ = userId.asObservable(); @@ -1283,7 +1283,7 @@ describe("CredentialGeneratorService", () => { apiService, i18nService, encryptService, - cryptoService, + keyService, ); const userId = new BehaviorSubject(SomeUser); const userId$ = userId.asObservable(); diff --git a/libs/tools/generator/core/src/services/credential-generator.service.ts b/libs/tools/generator/core/src/services/credential-generator.service.ts index a137c153a6..ebcc207715 100644 --- a/libs/tools/generator/core/src/services/credential-generator.service.ts +++ b/libs/tools/generator/core/src/services/credential-generator.service.ts @@ -23,7 +23,6 @@ import { Simplify } from "type-fest"; import { ApiService } from "@bitwarden/common/abstractions/api.service"; import { PolicyService } from "@bitwarden/common/admin-console/abstractions/policy/policy.service.abstraction"; import { PolicyType } from "@bitwarden/common/admin-console/enums"; -import { CryptoService } from "@bitwarden/common/platform/abstractions/crypto.service"; import { EncryptService } from "@bitwarden/common/platform/abstractions/encrypt.service"; import { I18nService } from "@bitwarden/common/platform/abstractions/i18n.service"; import { StateProvider } from "@bitwarden/common/platform/state"; @@ -41,6 +40,7 @@ import { UserEncryptor } from "@bitwarden/common/tools/state/user-encryptor.abst import { UserKeyEncryptor } from "@bitwarden/common/tools/state/user-key-encryptor"; import { UserStateSubject } from "@bitwarden/common/tools/state/user-state-subject"; import { UserId } from "@bitwarden/common/types/guid"; +import { KeyService } from "@bitwarden/key-management"; import { Randomizer } from "../abstractions"; import { @@ -97,7 +97,7 @@ export class CredentialGeneratorService { private readonly apiService: ApiService, private readonly i18nService: I18nService, private readonly encryptService: EncryptService, - private readonly cryptoService: CryptoService, + private readonly keyService: KeyService, ) {} private getDependencyProvider(): GeneratorDependencyProvider { @@ -272,7 +272,7 @@ export class CredentialGeneratorService { private encryptor$(userId: UserId) { const packer = new PaddedDataPacker(OPTIONS_FRAME_SIZE); - const encryptor$ = this.cryptoService.userKey$(userId).pipe( + const encryptor$ = this.keyService.userKey$(userId).pipe( // complete when the account locks takeWhile((key) => !!key), map((key) => { diff --git a/libs/tools/generator/core/src/strategies/forwarder-generator-strategy.spec.ts b/libs/tools/generator/core/src/strategies/forwarder-generator-strategy.spec.ts index 09f3ccd87a..f57a1e5f2b 100644 --- a/libs/tools/generator/core/src/strategies/forwarder-generator-strategy.spec.ts +++ b/libs/tools/generator/core/src/strategies/forwarder-generator-strategy.spec.ts @@ -5,13 +5,13 @@ import { PolicyType } from "@bitwarden/common/admin-console/enums"; // FIXME: use index.ts imports once policy abstractions and models // implement ADR-0002 import { Policy } from "@bitwarden/common/admin-console/models/domain/policy"; -import { CryptoService } from "@bitwarden/common/platform/abstractions/crypto.service"; import { EncryptService } from "@bitwarden/common/platform/abstractions/encrypt.service"; import { I18nService } from "@bitwarden/common/platform/abstractions/i18n.service"; import { RestClient } from "@bitwarden/common/tools/integration/rpc"; import { BufferedState } from "@bitwarden/common/tools/state/buffered-state"; import { UserId } from "@bitwarden/common/types/guid"; import { UserKey } from "@bitwarden/common/types/key"; +import { KeyService } from "@bitwarden/key-management"; import { FakeStateProvider, mockAccountServiceWith } from "../../../../../common/spec"; import { AddyIo, Fastmail, FirefoxRelay } from "../integration"; @@ -30,7 +30,7 @@ const SomePolicy = mock({ describe("ForwarderGeneratorStrategy", () => { const encryptService = mock(); - const keyService = mock(); + const keyService = mock(); const stateProvider = new FakeStateProvider(mockAccountServiceWith(SomeUser)); const restClient = mock(); const i18nService = mock(); diff --git a/libs/tools/generator/core/src/strategies/forwarder-generator-strategy.ts b/libs/tools/generator/core/src/strategies/forwarder-generator-strategy.ts index 04989cce19..9163d4c3a2 100644 --- a/libs/tools/generator/core/src/strategies/forwarder-generator-strategy.ts +++ b/libs/tools/generator/core/src/strategies/forwarder-generator-strategy.ts @@ -2,7 +2,6 @@ import { filter, map } from "rxjs"; import { Jsonify } from "type-fest"; import { PolicyType } from "@bitwarden/common/admin-console/enums"; -import { CryptoService } from "@bitwarden/common/platform/abstractions/crypto.service"; import { EncryptService } from "@bitwarden/common/platform/abstractions/encrypt.service"; import { I18nService } from "@bitwarden/common/platform/abstractions/i18n.service"; import { SingleUserState, StateProvider } from "@bitwarden/common/platform/state"; @@ -17,6 +16,7 @@ import { SecretKeyDefinition } from "@bitwarden/common/tools/state/secret-key-de import { SecretState } from "@bitwarden/common/tools/state/secret-state"; import { UserKeyEncryptor } from "@bitwarden/common/tools/state/user-key-encryptor"; import { UserId } from "@bitwarden/common/types/guid"; +import { KeyService } from "@bitwarden/key-management"; import { GeneratorStrategy } from "../abstractions"; import { ForwarderConfiguration, AccountRequest, ForwarderContext } from "../engine"; @@ -45,7 +45,7 @@ export class ForwarderGeneratorStrategy< private client: RestClient, private i18nService: I18nService, private readonly encryptService: EncryptService, - private readonly keyService: CryptoService, + private readonly keyService: KeyService, private stateProvider: StateProvider, ) { super(); diff --git a/libs/tools/generator/extensions/history/src/legacy-password-history-decryptor.ts b/libs/tools/generator/extensions/history/src/legacy-password-history-decryptor.ts index 5769d79da4..6a27ad476a 100644 --- a/libs/tools/generator/extensions/history/src/legacy-password-history-decryptor.ts +++ b/libs/tools/generator/extensions/history/src/legacy-password-history-decryptor.ts @@ -1,7 +1,7 @@ -import { CryptoService } from "@bitwarden/common/platform/abstractions/crypto.service"; import { EncryptService } from "@bitwarden/common/platform/abstractions/encrypt.service"; import { EncString } from "@bitwarden/common/platform/models/domain/enc-string"; import { UserId } from "@bitwarden/common/types/guid"; +import { KeyService } from "@bitwarden/key-management"; import { GeneratedPasswordHistory } from "./generated-password-history"; @@ -9,13 +9,13 @@ import { GeneratedPasswordHistory } from "./generated-password-history"; export class LegacyPasswordHistoryDecryptor { constructor( private userId: UserId, - private cryptoService: CryptoService, + private keyService: KeyService, private encryptService: EncryptService, ) {} /** Decrypts a password history. */ async decrypt(history: GeneratedPasswordHistory[]): Promise { - const key = await this.cryptoService.getUserKey(this.userId); + const key = await this.keyService.getUserKey(this.userId); const promises = (history ?? []).map(async (item) => { const encrypted = new EncString(item.password); diff --git a/libs/tools/generator/extensions/history/src/local-generator-history.service.spec.ts b/libs/tools/generator/extensions/history/src/local-generator-history.service.spec.ts index 1fbc956bc5..3936b03acc 100644 --- a/libs/tools/generator/extensions/history/src/local-generator-history.service.spec.ts +++ b/libs/tools/generator/extensions/history/src/local-generator-history.service.spec.ts @@ -1,13 +1,13 @@ import { mock } from "jest-mock-extended"; import { firstValueFrom, of } from "rxjs"; -import { CryptoService } from "@bitwarden/common/platform/abstractions/crypto.service"; import { EncryptService } from "@bitwarden/common/platform/abstractions/encrypt.service"; import { EncString } from "@bitwarden/common/platform/models/domain/enc-string"; import { SymmetricCryptoKey } from "@bitwarden/common/platform/models/domain/symmetric-crypto-key"; import { CsprngArray } from "@bitwarden/common/types/csprng"; import { UserId } from "@bitwarden/common/types/guid"; import { UserKey } from "@bitwarden/common/types/key"; +import { KeyService } from "@bitwarden/key-management"; import { FakeStateProvider, awaitAsync, mockAccountServiceWith } from "../../../../../common/spec"; @@ -18,7 +18,7 @@ const AnotherUser = "AnotherUser" as UserId; describe("LocalGeneratorHistoryService", () => { const encryptService = mock(); - const keyService = mock(); + const keyService = mock(); const userKey = new SymmetricCryptoKey(new Uint8Array(64) as CsprngArray) as UserKey; beforeEach(() => { diff --git a/libs/tools/generator/extensions/history/src/local-generator-history.service.ts b/libs/tools/generator/extensions/history/src/local-generator-history.service.ts index 99497f7ad5..7a5743f21b 100644 --- a/libs/tools/generator/extensions/history/src/local-generator-history.service.ts +++ b/libs/tools/generator/extensions/history/src/local-generator-history.service.ts @@ -1,6 +1,5 @@ import { filter, map } from "rxjs"; -import { CryptoService } from "@bitwarden/common/platform/abstractions/crypto.service"; import { EncryptService } from "@bitwarden/common/platform/abstractions/encrypt.service"; import { SingleUserState, StateProvider } from "@bitwarden/common/platform/state"; import { BufferedState } from "@bitwarden/common/tools/state/buffered-state"; @@ -9,6 +8,7 @@ import { SecretState } from "@bitwarden/common/tools/state/secret-state"; import { UserKeyEncryptor } from "@bitwarden/common/tools/state/user-key-encryptor"; import { UserId } from "@bitwarden/common/types/guid"; import { CredentialAlgorithm } from "@bitwarden/generator-core"; +import { KeyService } from "@bitwarden/key-management"; import { GeneratedCredential } from "./generated-credential"; import { GeneratorHistoryService } from "./generator-history.abstraction"; @@ -24,7 +24,7 @@ const OPTIONS_FRAME_SIZE = 2048; export class LocalGeneratorHistoryService extends GeneratorHistoryService { constructor( private readonly encryptService: EncryptService, - private readonly keyService: CryptoService, + private readonly keyService: KeyService, private readonly stateProvider: StateProvider, private readonly options: HistoryServiceOptions = { maxTotal: 200 }, ) { diff --git a/libs/tools/generator/extensions/legacy/src/create-legacy-password-generation-service.ts b/libs/tools/generator/extensions/legacy/src/create-legacy-password-generation-service.ts index 8ef14a3a9e..a76fba9759 100644 --- a/libs/tools/generator/extensions/legacy/src/create-legacy-password-generation-service.ts +++ b/libs/tools/generator/extensions/legacy/src/create-legacy-password-generation-service.ts @@ -1,28 +1,28 @@ import { PolicyService } from "@bitwarden/common/admin-console/abstractions/policy/policy.service.abstraction"; import { AccountService } from "@bitwarden/common/auth/abstractions/account.service"; -import { CryptoService } from "@bitwarden/common/platform/abstractions/crypto.service"; import { EncryptService } from "@bitwarden/common/platform/abstractions/encrypt.service"; import { StateProvider } from "@bitwarden/common/platform/state"; import { engine, services, strategies } from "@bitwarden/generator-core"; import { LocalGeneratorHistoryService } from "@bitwarden/generator-history"; import { DefaultGeneratorNavigationService } from "@bitwarden/generator-navigation"; +import { KeyService } from "@bitwarden/key-management"; import { LegacyPasswordGenerationService } from "./legacy-password-generation.service"; import { PasswordGenerationServiceAbstraction } from "./password-generation.service.abstraction"; const { PassphraseGeneratorStrategy, PasswordGeneratorStrategy } = strategies; -const { CryptoServiceRandomizer, PasswordRandomizer } = engine; +const { KeyServiceRandomizer, PasswordRandomizer } = engine; const DefaultGeneratorService = services.DefaultGeneratorService; export function legacyPasswordGenerationServiceFactory( encryptService: EncryptService, - cryptoService: CryptoService, + keyService: KeyService, policyService: PolicyService, accountService: AccountService, stateProvider: StateProvider, ): PasswordGenerationServiceAbstraction { - const randomizer = new CryptoServiceRandomizer(cryptoService); + const randomizer = new KeyServiceRandomizer(keyService); const passwordRandomizer = new PasswordRandomizer(randomizer); const passwords = new DefaultGeneratorService( @@ -37,7 +37,7 @@ export function legacyPasswordGenerationServiceFactory( const navigation = new DefaultGeneratorNavigationService(stateProvider, policyService); - const history = new LocalGeneratorHistoryService(encryptService, cryptoService, stateProvider); + const history = new LocalGeneratorHistoryService(encryptService, keyService, stateProvider); return new LegacyPasswordGenerationService( accountService, diff --git a/libs/tools/generator/extensions/legacy/src/create-legacy-username-generation-service.ts b/libs/tools/generator/extensions/legacy/src/create-legacy-username-generation-service.ts index 8626ef81f9..1d8a36eeb0 100644 --- a/libs/tools/generator/extensions/legacy/src/create-legacy-username-generation-service.ts +++ b/libs/tools/generator/extensions/legacy/src/create-legacy-username-generation-service.ts @@ -1,18 +1,18 @@ import { ApiService } from "@bitwarden/common/abstractions/api.service"; import { PolicyService } from "@bitwarden/common/admin-console/abstractions/policy/policy.service.abstraction"; import { AccountService } from "@bitwarden/common/auth/abstractions/account.service"; -import { CryptoService } from "@bitwarden/common/platform/abstractions/crypto.service"; import { EncryptService } from "@bitwarden/common/platform/abstractions/encrypt.service"; import { I18nService } from "@bitwarden/common/platform/abstractions/i18n.service"; import { StateProvider } from "@bitwarden/common/platform/state"; import { RestClient } from "@bitwarden/common/tools/integration/rpc"; import { engine, services, strategies, Integrations } from "@bitwarden/generator-core"; import { DefaultGeneratorNavigationService } from "@bitwarden/generator-navigation"; +import { KeyService } from "@bitwarden/key-management"; import { LegacyUsernameGenerationService } from "./legacy-username-generation.service"; import { UsernameGenerationServiceAbstraction } from "./username-generation.service.abstraction"; -const { CryptoServiceRandomizer, UsernameRandomizer, EmailRandomizer, EmailCalculator } = engine; +const { KeyServiceRandomizer, UsernameRandomizer, EmailRandomizer, EmailCalculator } = engine; const DefaultGeneratorService = services.DefaultGeneratorService; const { CatchallGeneratorStrategy, @@ -24,13 +24,13 @@ const { export function legacyUsernameGenerationServiceFactory( apiService: ApiService, i18nService: I18nService, - cryptoService: CryptoService, + keyService: KeyService, encryptService: EncryptService, policyService: PolicyService, accountService: AccountService, stateProvider: StateProvider, ): UsernameGenerationServiceAbstraction { - const randomizer = new CryptoServiceRandomizer(cryptoService); + const randomizer = new KeyServiceRandomizer(keyService); const restClient = new RestClient(apiService, i18nService); const usernameRandomizer = new UsernameRandomizer(randomizer); const emailRandomizer = new EmailRandomizer(randomizer); @@ -57,7 +57,7 @@ export function legacyUsernameGenerationServiceFactory( restClient, i18nService, encryptService, - cryptoService, + keyService, stateProvider, ), policyService, @@ -69,7 +69,7 @@ export function legacyUsernameGenerationServiceFactory( restClient, i18nService, encryptService, - cryptoService, + keyService, stateProvider, ), policyService, @@ -81,7 +81,7 @@ export function legacyUsernameGenerationServiceFactory( restClient, i18nService, encryptService, - cryptoService, + keyService, stateProvider, ), policyService, @@ -93,7 +93,7 @@ export function legacyUsernameGenerationServiceFactory( restClient, i18nService, encryptService, - cryptoService, + keyService, stateProvider, ), policyService, @@ -105,7 +105,7 @@ export function legacyUsernameGenerationServiceFactory( restClient, i18nService, encryptService, - cryptoService, + keyService, stateProvider, ), policyService, @@ -117,7 +117,7 @@ export function legacyUsernameGenerationServiceFactory( restClient, i18nService, encryptService, - cryptoService, + keyService, stateProvider, ), policyService, diff --git a/libs/tools/send/send-ui/src/send-form/send-form.module.ts b/libs/tools/send/send-ui/src/send-form/send-form.module.ts index df10b56391..67f1f910cc 100644 --- a/libs/tools/send/send-ui/src/send-form/send-form.module.ts +++ b/libs/tools/send/send-ui/src/send-form/send-form.module.ts @@ -4,7 +4,6 @@ import { safeProvider } from "@bitwarden/angular/platform/utils/safe-provider"; import { SafeInjectionToken } from "@bitwarden/angular/services/injection-tokens"; import { ApiService } from "@bitwarden/common/abstractions/api.service"; import { PolicyService } from "@bitwarden/common/admin-console/abstractions/policy/policy.service.abstraction"; -import { CryptoService } from "@bitwarden/common/platform/abstractions/crypto.service"; import { EncryptService } from "@bitwarden/common/platform/abstractions/encrypt.service"; import { I18nService } from "@bitwarden/common/platform/abstractions/i18n.service"; import { StateProvider } from "@bitwarden/common/platform/state"; @@ -13,6 +12,7 @@ import { CredentialGeneratorService, Randomizer, } from "@bitwarden/generator-core"; +import { KeyService } from "@bitwarden/key-management"; import { SendFormService } from "./abstractions/send-form.service"; import { SendFormComponent } from "./components/send-form.component"; @@ -30,7 +30,7 @@ const RANDOMIZER = new SafeInjectionToken("Randomizer"); safeProvider({ provide: RANDOMIZER, useFactory: createRandomizer, - deps: [CryptoService], + deps: [KeyService], }), safeProvider({ useClass: CredentialGeneratorService, @@ -42,7 +42,7 @@ const RANDOMIZER = new SafeInjectionToken("Randomizer"); ApiService, I18nService, EncryptService, - CryptoService, + KeyService, ], }), ], diff --git a/libs/vault/src/cipher-view/attachments/attachments-v2-view.component.ts b/libs/vault/src/cipher-view/attachments/attachments-v2-view.component.ts index d7af28cb1e..d3a446eee4 100644 --- a/libs/vault/src/cipher-view/attachments/attachments-v2-view.component.ts +++ b/libs/vault/src/cipher-view/attachments/attachments-v2-view.component.ts @@ -5,7 +5,6 @@ import { NEVER, switchMap } from "rxjs"; import { JslibModule } from "@bitwarden/angular/jslib.module"; import { BillingAccountProfileStateService } from "@bitwarden/common/billing/abstractions"; -import { CryptoService } from "@bitwarden/common/platform/abstractions/crypto.service"; import { StateProvider } from "@bitwarden/common/platform/state"; import { OrganizationId } from "@bitwarden/common/types/guid"; import { OrgKey } from "@bitwarden/common/types/key"; @@ -17,6 +16,7 @@ import { SectionHeaderComponent, TypographyModule, } from "@bitwarden/components"; +import { KeyService } from "@bitwarden/key-management"; import { DownloadAttachmentComponent } from "../../components/download-attachment/download-attachment.component"; @@ -42,7 +42,7 @@ export class AttachmentsV2ViewComponent { orgKey: OrgKey; constructor( - private cryptoService: CryptoService, + private keyService: KeyService, private billingAccountProfileStateService: BillingAccountProfileStateService, private stateProvider: StateProvider, ) { @@ -61,7 +61,7 @@ export class AttachmentsV2ViewComponent { subscribeToOrgKey() { this.stateProvider.activeUserId$ .pipe( - switchMap((userId) => (userId != null ? this.cryptoService.orgKeys$(userId) : NEVER)), + switchMap((userId) => (userId != null ? this.keyService.orgKeys$(userId) : NEVER)), takeUntilDestroyed(), ) .subscribe((data: Record | null) => { diff --git a/libs/vault/src/components/download-attachment/download-attachment.component.spec.ts b/libs/vault/src/components/download-attachment/download-attachment.component.spec.ts index 39a6e6bc2f..dc6ca16ddd 100644 --- a/libs/vault/src/components/download-attachment/download-attachment.component.spec.ts +++ b/libs/vault/src/components/download-attachment/download-attachment.component.spec.ts @@ -5,7 +5,6 @@ import { BehaviorSubject } from "rxjs"; import { ApiService } from "@bitwarden/common/abstractions/api.service"; import { ErrorResponse } from "@bitwarden/common/models/response/error.response"; -import { CryptoService } from "@bitwarden/common/platform/abstractions/crypto.service"; import { EncryptService } from "@bitwarden/common/platform/abstractions/encrypt.service"; import { FileDownloadService } from "@bitwarden/common/platform/abstractions/file-download/file-download.service"; import { I18nService } from "@bitwarden/common/platform/abstractions/i18n.service"; @@ -15,6 +14,7 @@ import { CipherType } from "@bitwarden/common/vault/enums"; import { AttachmentView } from "@bitwarden/common/vault/models/view/attachment.view"; import { CipherView } from "@bitwarden/common/vault/models/view/cipher.view"; import { ToastService } from "@bitwarden/components"; +import { KeyService } from "@bitwarden/key-management"; import { PasswordRepromptService } from "../../services/password-reprompt.service"; @@ -60,7 +60,7 @@ describe("DownloadAttachmentComponent", () => { imports: [DownloadAttachmentComponent], providers: [ { provide: EncryptService, useValue: mock() }, - { provide: CryptoService, useValue: mock() }, + { provide: KeyService, useValue: mock() }, { provide: I18nService, useValue: { t: (key: string) => key } }, { provide: StateProvider, useValue: { activeUserId$ } }, { provide: ToastService, useValue: { showToast } }, diff --git a/libs/vault/src/components/download-attachment/download-attachment.component.ts b/libs/vault/src/components/download-attachment/download-attachment.component.ts index b9d5f35dce..938252defe 100644 --- a/libs/vault/src/components/download-attachment/download-attachment.component.ts +++ b/libs/vault/src/components/download-attachment/download-attachment.component.ts @@ -6,7 +6,6 @@ import { NEVER, switchMap } from "rxjs"; import { JslibModule } from "@bitwarden/angular/jslib.module"; import { ApiService } from "@bitwarden/common/abstractions/api.service"; import { ErrorResponse } from "@bitwarden/common/models/response/error.response"; -import { CryptoService } from "@bitwarden/common/platform/abstractions/crypto.service"; import { EncryptService } from "@bitwarden/common/platform/abstractions/encrypt.service"; import { FileDownloadService } from "@bitwarden/common/platform/abstractions/file-download/file-download.service"; import { I18nService } from "@bitwarden/common/platform/abstractions/i18n.service"; @@ -17,6 +16,7 @@ import { OrgKey } from "@bitwarden/common/types/key"; import { AttachmentView } from "@bitwarden/common/vault/models/view/attachment.view"; import { CipherView } from "@bitwarden/common/vault/models/view/cipher.view"; import { AsyncActionsModule, IconButtonModule, ToastService } from "@bitwarden/components"; +import { KeyService } from "@bitwarden/key-management"; @Component({ standalone: true, @@ -44,11 +44,11 @@ export class DownloadAttachmentComponent { private toastService: ToastService, private encryptService: EncryptService, private stateProvider: StateProvider, - private cryptoService: CryptoService, + private keyService: KeyService, ) { this.stateProvider.activeUserId$ .pipe( - switchMap((userId) => (userId !== null ? this.cryptoService.orgKeys$(userId) : NEVER)), + switchMap((userId) => (userId !== null ? this.keyService.orgKeys$(userId) : NEVER)), takeUntilDestroyed(), ) .subscribe((data: Record | null) => { diff --git a/libs/vault/src/components/password-reprompt.component.ts b/libs/vault/src/components/password-reprompt.component.ts index dcc20f7982..3cbdfa1416 100644 --- a/libs/vault/src/components/password-reprompt.component.ts +++ b/libs/vault/src/components/password-reprompt.component.ts @@ -3,7 +3,6 @@ import { Component } from "@angular/core"; import { FormBuilder, ReactiveFormsModule, Validators } from "@angular/forms"; import { JslibModule } from "@bitwarden/angular/jslib.module"; -import { CryptoService } from "@bitwarden/common/platform/abstractions/crypto.service"; import { I18nService } from "@bitwarden/common/platform/abstractions/i18n.service"; import { PlatformUtilsService } from "@bitwarden/common/platform/abstractions/platform-utils.service"; import { @@ -13,6 +12,7 @@ import { FormFieldModule, IconButtonModule, } from "@bitwarden/components"; +import { KeyService } from "@bitwarden/key-management"; /** * Used to verify the user's Master Password for the "Master Password Re-prompt" feature only. @@ -38,7 +38,7 @@ export class PasswordRepromptComponent { }); constructor( - protected cryptoService: CryptoService, + protected keyService: KeyService, protected platformUtilsService: PlatformUtilsService, protected i18nService: I18nService, protected formBuilder: FormBuilder, @@ -46,11 +46,11 @@ export class PasswordRepromptComponent { ) {} submit = async () => { - const storedMasterKey = await this.cryptoService.getOrDeriveMasterKey( + const storedMasterKey = await this.keyService.getOrDeriveMasterKey( this.formGroup.value.masterPassword, ); if ( - !(await this.cryptoService.compareAndUpdateKeyHash( + !(await this.keyService.compareAndUpdateKeyHash( this.formGroup.value.masterPassword, storedMasterKey, ))