diff --git a/.github/CODEOWNERS b/.github/CODEOWNERS index 99efec2fbbb..1d63af3dd66 100644 --- a/.github/CODEOWNERS +++ b/.github/CODEOWNERS @@ -233,3 +233,4 @@ libs/pricing @bitwarden/team-billing-dev .github/workflows/respond.yml @bitwarden/team-ai-sme .github/workflows/review-code.yml @bitwarden/team-ai-sme libs/subscription @bitwarden/team-billing-dev +libs/user-crypto-management @bitwarden/team-key-management-dev diff --git a/jest.config.js b/jest.config.js index 37d15eb8f92..300246a692b 100644 --- a/jest.config.js +++ b/jest.config.js @@ -60,6 +60,7 @@ module.exports = { "/libs/user-core/jest.config.js", "/libs/vault/jest.config.js", "/libs/subscription/jest.config.js", + "/libs/user-crypto-management/jest.config.js", ], // Workaround for a memory leak that crashes tests in CI: diff --git a/libs/user-crypto-management/README.md b/libs/user-crypto-management/README.md new file mode 100644 index 00000000000..5d348f8f4bb --- /dev/null +++ b/libs/user-crypto-management/README.md @@ -0,0 +1,5 @@ +# user-crypto-management + +Owned by: key-management + +Manage a user's cryptography and cryptographic settings diff --git a/libs/user-crypto-management/eslint.config.mjs b/libs/user-crypto-management/eslint.config.mjs new file mode 100644 index 00000000000..9c37d10e3ff --- /dev/null +++ b/libs/user-crypto-management/eslint.config.mjs @@ -0,0 +1,3 @@ +import baseConfig from "../../eslint.config.mjs"; + +export default [...baseConfig]; diff --git a/libs/user-crypto-management/jest.config.js b/libs/user-crypto-management/jest.config.js new file mode 100644 index 00000000000..44122f8407e --- /dev/null +++ b/libs/user-crypto-management/jest.config.js @@ -0,0 +1,10 @@ +module.exports = { + displayName: "user-crypto-management", + preset: "../../jest.preset.js", + testEnvironment: "node", + transform: { + "^.+\\.[tj]s$": ["ts-jest", { tsconfig: "/tsconfig.spec.json" }], + }, + moduleFileExtensions: ["ts", "js", "html"], + coverageDirectory: "../../coverage/libs/user-crypto-management", +}; diff --git a/libs/user-crypto-management/package.json b/libs/user-crypto-management/package.json new file mode 100644 index 00000000000..d71b90f7cb2 --- /dev/null +++ b/libs/user-crypto-management/package.json @@ -0,0 +1,11 @@ +{ + "name": "@bitwarden/user-crypto-management", + "version": "0.0.1", + "description": "Manage a user's cryptography and cryptographic settings", + "private": true, + "type": "commonjs", + "main": "index.js", + "types": "index.d.ts", + "license": "GPL-3.0", + "author": "key-management" +} diff --git a/libs/user-crypto-management/project.json b/libs/user-crypto-management/project.json new file mode 100644 index 00000000000..548fbe55ec3 --- /dev/null +++ b/libs/user-crypto-management/project.json @@ -0,0 +1,34 @@ +{ + "name": "user-crypto-management", + "$schema": "../../node_modules/nx/schemas/project-schema.json", + "sourceRoot": "libs/user-crypto-management/src", + "projectType": "library", + "tags": [], + "targets": { + "build": { + "executor": "@nx/js:tsc", + "outputs": ["{options.outputPath}"], + "options": { + "outputPath": "dist/libs/user-crypto-management", + "main": "libs/user-crypto-management/src/index.ts", + "tsConfig": "libs/user-crypto-management/tsconfig.lib.json", + "assets": ["libs/user-crypto-management/*.md"], + "rootDir": "libs/user-crypto-management/src" + } + }, + "lint": { + "executor": "@nx/eslint:lint", + "outputs": ["{options.outputFile}"], + "options": { + "lintFilePatterns": ["libs/user-crypto-management/**/*.ts"] + } + }, + "test": { + "executor": "@nx/jest:jest", + "outputs": ["{workspaceRoot}/coverage/{projectRoot}"], + "options": { + "jestConfig": "libs/user-crypto-management/jest.config.js" + } + } + } +} diff --git a/libs/user-crypto-management/src/index.ts b/libs/user-crypto-management/src/index.ts new file mode 100644 index 00000000000..4d0b867579a --- /dev/null +++ b/libs/user-crypto-management/src/index.ts @@ -0,0 +1,2 @@ +export { DefaultUserKeyRotationService as UserKeyRotationService } from "./user-key-rotation.service"; +export { UserKeyRotationService as UserKeyRotationServiceAbstraction } from "./user-key-rotation.service.abstraction"; diff --git a/libs/user-crypto-management/src/user-key-rotation.service.abstraction.ts b/libs/user-crypto-management/src/user-key-rotation.service.abstraction.ts new file mode 100644 index 00000000000..9045a757553 --- /dev/null +++ b/libs/user-crypto-management/src/user-key-rotation.service.abstraction.ts @@ -0,0 +1,40 @@ +import { AsymmetricPublicCryptoKey, UserId } from "@bitwarden/sdk-internal"; + +/** + * Result of the trust verification process. + */ +export type TrustVerificationResult = { + wasTrustDenied: boolean; + trustedOrganizationPublicKeys: AsymmetricPublicCryptoKey[]; + trustedEmergencyAccessUserPublicKeys: AsymmetricPublicCryptoKey[]; +}; + +/** + * Abstraction for the user key rotation service. + * Provides functionality to rotate user keys and verify trust for organizations + * and emergency access users. + */ +export abstract class UserKeyRotationService { + /** + * Rotates the user key using the SDK, re-encrypting all required data with the new key. + * @param currentMasterPassword The current master password + * @param newMasterPassword The new master password + * @param hint Optional hint for the new master password + * @param userId The user account ID + */ + abstract changePasswordAndRotateUserKey( + currentMasterPassword: string, + newMasterPassword: string, + hint: string | undefined, + userId: UserId, + ): Promise; + + /** + * Verifies the trust of organizations and emergency access users by prompting the user. + * Since organizations and emergency access grantees are not signed, manual trust prompts + * are required to verify that the server does not inject public keys. + * @param user The user account + * @returns TrustVerificationResult containing whether trust was denied and the trusted public keys + */ + abstract verifyTrust(userId: UserId): Promise; +} diff --git a/libs/user-crypto-management/src/user-key-rotation.service.ts b/libs/user-crypto-management/src/user-key-rotation.service.ts new file mode 100644 index 00000000000..acb56b5de9f --- /dev/null +++ b/libs/user-crypto-management/src/user-key-rotation.service.ts @@ -0,0 +1,159 @@ +import { catchError, EMPTY, firstValueFrom, map } from "rxjs"; + +import { SdkService } from "@bitwarden/common/platform/abstractions/sdk/sdk.service"; +import { DialogService } from "@bitwarden/components"; +import { + AccountRecoveryTrustComponent, + EmergencyAccessTrustComponent, + KeyRotationTrustInfoComponent, +} from "@bitwarden/key-management-ui"; +import { LogService } from "@bitwarden/logging"; +import { RotateUserKeysRequest } from "@bitwarden/sdk-internal"; +import { UserId } from "@bitwarden/user-core"; + +import { + TrustVerificationResult, + UserKeyRotationService, +} from "./user-key-rotation.service.abstraction"; + +/** + * Service for rotating user keys using the SDK. + * Handles key rotation and trust verification for organizations and emergency access users. + */ +export class DefaultUserKeyRotationService implements UserKeyRotationService { + constructor( + private sdkService: SdkService, + private logService: LogService, + private dialogService: DialogService, + ) {} + + async changePasswordAndRotateUserKey( + currentMasterPassword: string, + newMasterPassword: string, + hint: string | undefined, + userId: UserId, + ): Promise { + // First, the provided organizations and emergency access users need to be verified; + // this is currently done by providing the user a manual confirmation dialog. + const { wasTrustDenied, trustedOrganizationPublicKeys, trustedEmergencyAccessUserPublicKeys } = + await this.verifyTrust(userId); + if (wasTrustDenied) { + this.logService.info("[Userkey rotation] Trust was denied by user. Aborting!"); + return; + } + + return firstValueFrom( + this.sdkService.userClient$(userId).pipe( + map(async (sdk) => { + if (!sdk) { + throw new Error("SDK not available"); + } + + using ref = sdk.take(); + this.logService.info("[UserKey Rotation] Re-encrypting user data with new user key..."); + await ref.value.user_crypto_management().rotate_user_keys_with_password_change({ + old_password: currentMasterPassword, + password: newMasterPassword, + hint, + trusted_emergency_access_public_keys: trustedEmergencyAccessUserPublicKeys, + trusted_organization_public_keys: trustedOrganizationPublicKeys, + } as RotateUserKeysRequest); + }), + catchError((error: unknown) => { + this.logService.error(`Failed to rotate user keys: ${error}`); + return EMPTY; + }), + ), + ); + } + + async verifyTrust(userId: UserId): Promise { + // Since currently the joined organizations and emergency access grantees are + // not signed, manual trust prompts are required, to verify that the server + // does not inject public keys here. + // + // Once signing is implemented, this is the place to also sign the keys and + // upload the signed trust claims. + // + // The flow works in 3 steps: + // 1. Prepare the user by showing them a dialog telling them they'll be asked + // to verify the trust of their organizations and emergency access users. + // 2. Show the user a dialog for each organization and ask them to verify the trust. + // 3. Show the user a dialog for each emergency access user and ask them to verify the trust. + this.logService.info("[Userkey rotation] Verifying trust..."); + const [emergencyAccessMemberships, organizationV1Memberships] = await firstValueFrom( + this.sdkService.userClient$(userId).pipe( + map(async (sdk) => { + if (!sdk) { + throw new Error("SDK not available"); + } + + using ref = sdk.take(); + const emergencyAccessMemberships = await ref.value + .user_crypto_management() + .get_untrusted_emergency_access_public_keys(); + const organizationV1Memberships = await ref.value + .user_crypto_management() + .get_untrusted_organization_public_keys(); + return [emergencyAccessMemberships, organizationV1Memberships] as const; + }), + ), + ); + this.logService.info("result", { emergencyAccessMemberships, organizationV1Memberships }); + + if (organizationV1Memberships.length > 0 || emergencyAccessMemberships.length > 0) { + this.logService.info("[Userkey rotation] Showing trust info dialog..."); + const trustInfoDialog = KeyRotationTrustInfoComponent.open(this.dialogService, { + numberOfEmergencyAccessUsers: emergencyAccessMemberships.length, + orgName: + organizationV1Memberships.length > 0 ? organizationV1Memberships[0].name : undefined, + }); + if (!(await firstValueFrom(trustInfoDialog.closed))) { + return { + wasTrustDenied: true, + trustedOrganizationPublicKeys: [], + trustedEmergencyAccessUserPublicKeys: [], + }; + } + } + + for (const organization of organizationV1Memberships) { + const dialogRef = AccountRecoveryTrustComponent.open(this.dialogService, { + name: organization.name, + orgId: organization.organization_id as string, + publicKey: organization.public_key, + }); + if (!(await firstValueFrom(dialogRef.closed))) { + return { + wasTrustDenied: true, + trustedOrganizationPublicKeys: [], + trustedEmergencyAccessUserPublicKeys: [], + }; + } + } + + for (const details of emergencyAccessMemberships) { + const dialogRef = EmergencyAccessTrustComponent.open(this.dialogService, { + name: details.name, + userId: details.id as string, + publicKey: details.public_key, + }); + if (!(await firstValueFrom(dialogRef.closed))) { + return { + wasTrustDenied: true, + trustedOrganizationPublicKeys: [], + trustedEmergencyAccessUserPublicKeys: [], + }; + } + } + + this.logService.info( + "[Userkey rotation] Trust verified for all organizations and emergency access users", + ); + return { + wasTrustDenied: false, + trustedOrganizationPublicKeys: organizationV1Memberships.map((d) => d.public_key), + trustedEmergencyAccessUserPublicKeys: emergencyAccessMemberships.map((d) => d.public_key), + }; + } +} diff --git a/libs/user-crypto-management/tsconfig.eslint.json b/libs/user-crypto-management/tsconfig.eslint.json new file mode 100644 index 00000000000..3daf120441a --- /dev/null +++ b/libs/user-crypto-management/tsconfig.eslint.json @@ -0,0 +1,6 @@ +{ + "extends": "../../tsconfig.base.json", + "files": [], + "include": ["src/**/*.ts", "src/**/*.js"], + "exclude": ["**/build", "**/dist"] +} diff --git a/libs/user-crypto-management/tsconfig.json b/libs/user-crypto-management/tsconfig.json new file mode 100644 index 00000000000..9c607a26b09 --- /dev/null +++ b/libs/user-crypto-management/tsconfig.json @@ -0,0 +1,5 @@ +{ + "extends": "../../tsconfig.base", + "include": ["src", "spec"], + "exclude": ["node_modules", "dist"] +} diff --git a/libs/user-crypto-management/tsconfig.lib.json b/libs/user-crypto-management/tsconfig.lib.json new file mode 100644 index 00000000000..9cbf6736007 --- /dev/null +++ b/libs/user-crypto-management/tsconfig.lib.json @@ -0,0 +1,10 @@ +{ + "extends": "./tsconfig.json", + "compilerOptions": { + "outDir": "../../dist/out-tsc", + "declaration": true, + "types": ["node"] + }, + "include": ["src/**/*.ts"], + "exclude": ["jest.config.js", "src/**/*.spec.ts"] +} diff --git a/libs/user-crypto-management/tsconfig.spec.json b/libs/user-crypto-management/tsconfig.spec.json new file mode 100644 index 00000000000..1275f148a18 --- /dev/null +++ b/libs/user-crypto-management/tsconfig.spec.json @@ -0,0 +1,10 @@ +{ + "extends": "./tsconfig.json", + "compilerOptions": { + "outDir": "../../dist/out-tsc", + "module": "commonjs", + "moduleResolution": "node10", + "types": ["jest", "node"] + }, + "include": ["jest.config.ts", "src/**/*.test.ts", "src/**/*.spec.ts", "src/**/*.d.ts"] +} diff --git a/package-lock.json b/package-lock.json index e2556015113..e82152eaa78 100644 --- a/package-lock.json +++ b/package-lock.json @@ -683,6 +683,11 @@ "version": "0.0.0", "license": "GPL-3.0" }, + "libs/user-crypto-management": { + "name": "@bitwarden/user-crypto-management", + "version": "0.0.1", + "license": "GPL-3.0" + }, "libs/vault": { "name": "@bitwarden/vault", "version": "0.0.0", @@ -5138,6 +5143,10 @@ "resolved": "libs/user-core", "link": true }, + "node_modules/@bitwarden/user-crypto-management": { + "resolved": "libs/user-crypto-management", + "link": true + }, "node_modules/@bitwarden/vault": { "resolved": "libs/vault", "link": true diff --git a/tsconfig.base.json b/tsconfig.base.json index 2f6499eb374..4fabd403205 100644 --- a/tsconfig.base.json +++ b/tsconfig.base.json @@ -29,8 +29,8 @@ "@bitwarden/browser/*": ["./apps/browser/src/*"], "@bitwarden/cli/*": ["./apps/cli/src/*"], "@bitwarden/client-type": ["libs/client-type/src/index.ts"], - "@bitwarden/common/spec": ["./libs/common/spec"], "@bitwarden/common/*": ["./libs/common/src/*"], + "@bitwarden/common/spec": ["./libs/common/spec"], "@bitwarden/components": ["./libs/components/src"], "@bitwarden/core-test-utils": ["libs/core-test-utils/src/index.ts"], "@bitwarden/dirt-card": ["./libs/dirt/card/src"], @@ -62,6 +62,7 @@ "@bitwarden/ui-common": ["./libs/ui/common/src"], "@bitwarden/ui-common/setup-jest": ["./libs/ui/common/src/setup-jest"], "@bitwarden/user-core": ["libs/user-core/src/index.ts"], + "@bitwarden/user-crypto-management": ["libs/user-crypto-management/src/index.ts"], "@bitwarden/vault": ["./libs/vault/src"], "@bitwarden/vault-export-core": ["./libs/tools/export/vault-export/vault-export-core/src"], "@bitwarden/vault-export-ui": ["./libs/tools/export/vault-export/vault-export-ui/src"],