diff --git a/apps/browser/src/background/main.background.ts b/apps/browser/src/background/main.background.ts index 85e4a5eae25d..fd730a7f129a 100644 --- a/apps/browser/src/background/main.background.ts +++ b/apps/browser/src/background/main.background.ts @@ -206,6 +206,8 @@ import { ProviderService as ProviderServiceAbstraction } from "@bitwarden/common import { ProviderService } from "@bitwarden/common/provider/services/provider.service"; import { ApiService } from "@bitwarden/common/services/api.service"; import { AuditService } from "@bitwarden/common/services/audit.service"; +import { AgentConnectionStateProvider } from "@bitwarden/common/tools/agent-connection/services/agent-connection-state.provider"; +import { AgentConnectionService } from "@bitwarden/common/tools/agent-connection/services/agent-connection.service"; import { KeyServiceLegacyEncryptorProvider } from "@bitwarden/common/tools/cryptography/key-service-legacy-encryptor-provider"; import { buildExtensionRegistry } from "@bitwarden/common/tools/extension/factory"; import { @@ -1312,6 +1314,15 @@ export default class MainBackground { this.providerService = new ProviderService(this.stateProvider); + // Agent connections are only populated on sync when the LoginWithBitwarden flag is on; the + // browser does not wire the broker UI (web-only v1) but must still satisfy the sync dependency. + const agentConnectionService = new AgentConnectionService( + this.keyService, + this.encryptService, + this.i18nService, + new AgentConnectionStateProvider(this.stateProvider), + ); + this.syncService = new DefaultSyncService( this.masterPasswordService, this.accountService, @@ -1339,6 +1350,7 @@ export default class MainBackground { this.stateProvider, this.configService, this.sdkService, + agentConnectionService, ); this.syncServiceListener = new SyncServiceListener( diff --git a/apps/cli/src/service-container/service-container.ts b/apps/cli/src/service-container/service-container.ts index 66322c7cafec..b753506d3338 100644 --- a/apps/cli/src/service-container/service-container.ts +++ b/apps/cli/src/service-container/service-container.ts @@ -145,6 +145,8 @@ import { ProviderApiServiceAbstraction } from "@bitwarden/common/provider"; import { ProviderApiService } from "@bitwarden/common/provider/services/provider-api.service"; import { ProviderService } from "@bitwarden/common/provider/services/provider.service"; import { AuditService } from "@bitwarden/common/services/audit.service"; +import { AgentConnectionStateProvider } from "@bitwarden/common/tools/agent-connection/services/agent-connection-state.provider"; +import { AgentConnectionService } from "@bitwarden/common/tools/agent-connection/services/agent-connection.service"; import { KeyServiceLegacyEncryptorProvider } from "@bitwarden/common/tools/cryptography/key-service-legacy-encryptor-provider"; import { buildExtensionRegistry } from "@bitwarden/common/tools/extension/factory"; import { @@ -1069,6 +1071,15 @@ export class ServiceContainer { this.avatarService = new AvatarService(this.apiService, this.stateProvider); + // Agent connections are only populated on sync when the LoginWithBitwarden flag is on; the CLI + // does not wire the broker UI (web-only v1) but must still satisfy the sync dependency. + const agentConnectionService = new AgentConnectionService( + this.keyService, + this.encryptService, + this.i18nService, + new AgentConnectionStateProvider(this.stateProvider), + ); + this.syncService = new DefaultSyncService( this.masterPasswordService, this.accountService, @@ -1096,6 +1107,7 @@ export class ServiceContainer { this.stateProvider, this.configService, this.sdkService, + agentConnectionService, ); this.totpService = new TotpService(this.sdkService); diff --git a/apps/web/src/app/key-management/key-rotation/request/userdata.request.ts b/apps/web/src/app/key-management/key-rotation/request/userdata.request.ts index 022044286868..850f16f73c64 100644 --- a/apps/web/src/app/key-management/key-rotation/request/userdata.request.ts +++ b/apps/web/src/app/key-management/key-rotation/request/userdata.request.ts @@ -1,3 +1,4 @@ +import { AgentConnectionWithIdRequest } from "@bitwarden/common/tools/agent-connection/models/request/agent-connection-with-id.request"; import { SendWithIdRequest } from "@bitwarden/common/tools/send/models/request/send-with-id.request"; import { CipherWithIdRequest } from "@bitwarden/common/vault/models/request/cipher-with-id.request"; import { FolderWithIdRequest } from "@bitwarden/common/vault/models/request/folder-with-id.request"; @@ -6,14 +7,17 @@ export class UserDataRequest { ciphers: CipherWithIdRequest[]; folders: FolderWithIdRequest[]; sends: SendWithIdRequest[]; + agentConnections: AgentConnectionWithIdRequest[]; constructor( ciphers: CipherWithIdRequest[], folders: FolderWithIdRequest[], sends: SendWithIdRequest[], + agentConnections: AgentConnectionWithIdRequest[] = [], ) { this.ciphers = ciphers; this.folders = folders; this.sends = sends; + this.agentConnections = agentConnections; } } diff --git a/apps/web/src/app/key-management/key-rotation/user-key-rotation.service.spec.ts b/apps/web/src/app/key-management/key-rotation/user-key-rotation.service.spec.ts index 161963e46751..0658dfc50157 100644 --- a/apps/web/src/app/key-management/key-rotation/user-key-rotation.service.spec.ts +++ b/apps/web/src/app/key-management/key-rotation/user-key-rotation.service.spec.ts @@ -15,6 +15,7 @@ import { LogService } from "@bitwarden/common/platform/abstractions/log.service" import { SdkLoadService } from "@bitwarden/common/platform/abstractions/sdk/sdk-load.service"; import { Utils } from "@bitwarden/common/platform/misc/utils"; import { mockAccountInfoWith } from "@bitwarden/common/spec"; +import { AgentConnectionService } from "@bitwarden/common/tools/agent-connection/services/agent-connection.service.abstraction"; import { SendWithIdRequest } from "@bitwarden/common/tools/send/models/request/send-with-id.request"; import { SendService } from "@bitwarden/common/tools/send/services/send.service.abstraction"; import { UserId } from "@bitwarden/common/types/guid"; @@ -244,6 +245,7 @@ describe("KeyRotationService", () => { let mockCipherService: MockProxy; let mockFolderService: MockProxy; let mockSendService: MockProxy; + let mockAgentConnectionService: MockProxy; let mockEmergencyAccessService: MockProxy; let mockResetPasswordService: MockProxy; let mockDeviceTrustService: MockProxy; @@ -280,6 +282,8 @@ describe("KeyRotationService", () => { mockCipherService = mock(); mockFolderService = mock(); mockSendService = mock(); + mockAgentConnectionService = mock(); + mockAgentConnectionService.getRotatedData.mockResolvedValue([]); mockEmergencyAccessService = mock(); mockEmergencyAccessService.getPublicKeys.mockResolvedValue( mockTrustedPublicKeys.map((key) => { @@ -329,6 +333,7 @@ describe("KeyRotationService", () => { mockCipherService, mockFolderService, mockSendService, + mockAgentConnectionService, mockEmergencyAccessService, mockResetPasswordService, mockDeviceTrustService, @@ -945,6 +950,7 @@ describe("KeyRotationService", () => { ciphers: mockCiphers, folders: mockFolders, sends: mockSends, + agentConnections: [], }); }); diff --git a/apps/web/src/app/key-management/key-rotation/user-key-rotation.service.ts b/apps/web/src/app/key-management/key-rotation/user-key-rotation.service.ts index 572d8ef0b8a7..4211edf75cc1 100644 --- a/apps/web/src/app/key-management/key-rotation/user-key-rotation.service.ts +++ b/apps/web/src/app/key-management/key-rotation/user-key-rotation.service.ts @@ -12,6 +12,7 @@ import { I18nService } from "@bitwarden/common/platform/abstractions/i18n.servic import { LogService } from "@bitwarden/common/platform/abstractions/log.service"; import { SdkLoadService } from "@bitwarden/common/platform/abstractions/sdk/sdk-load.service"; import { asUuid } from "@bitwarden/common/platform/abstractions/sdk/sdk.service"; +import { AgentConnectionService } from "@bitwarden/common/tools/agent-connection/services/agent-connection.service.abstraction"; import { SendService } from "@bitwarden/common/tools/send/services/send.service.abstraction"; import { UserId } from "@bitwarden/common/types/guid"; import { UserKey } from "@bitwarden/common/types/key"; @@ -66,6 +67,7 @@ export class UserKeyRotationService { private cipherService: CipherService, private folderService: FolderService, private sendService: SendService, + private agentConnectionService: AgentConnectionService, private emergencyAccessService: EmergencyAccessService, private resetPasswordService: OrganizationUserResetPasswordService, private deviceTrustService: DeviceTrustServiceAbstraction, @@ -462,7 +464,24 @@ export class UserKeyRotationService { this.logService.info("[Userkey rotation] ciphers, folders, or sends are null. Aborting!"); throw new Error("ciphers, folders, or sends are null"); } - return new UserDataRequest(rotatedCiphers, rotatedFolders, rotatedSends); + + // The agent-access PSK is wrapped with the user key, so each connection must be re-wrapped on + // rotation. Gated behind the feature flag; when off no connections are stored, so this is empty. + let rotatedAgentConnections: Awaited> = []; + if (await this.configService.getFeatureFlag(FeatureFlag.LoginWithBitwarden)) { + rotatedAgentConnections = await this.agentConnectionService.getRotatedData( + originalUserKey, + newUnencryptedUserKey, + user.id, + ); + } + + return new UserDataRequest( + rotatedCiphers, + rotatedFolders, + rotatedSends, + rotatedAgentConnections, + ); } /** diff --git a/apps/web/src/app/layouts/user-layout.component.html b/apps/web/src/app/layouts/user-layout.component.html index a833670b00e5..ecdddfd8987c 100644 --- a/apps/web/src/app/layouts/user-layout.component.html +++ b/apps/web/src/app/layouts/user-layout.component.html @@ -51,6 +51,12 @@ route="settings/emergency-access" > } + @if (loginWithBitwardenEnabled()) { + + } @@ -111,6 +117,12 @@ route="settings/emergency-access" > } + @if (loginWithBitwardenEnabled()) { + + } } diff --git a/apps/web/src/app/layouts/user-layout.component.ts b/apps/web/src/app/layouts/user-layout.component.ts index 6d987c51135b..45bac4f98957 100644 --- a/apps/web/src/app/layouts/user-layout.component.ts +++ b/apps/web/src/app/layouts/user-layout.component.ts @@ -92,6 +92,11 @@ export class UserLayoutComponent implements OnInit { { initialValue: false }, ); + protected readonly loginWithBitwardenEnabled: Signal = toSignal( + this.configService.getFeatureFlag$(FeatureFlag.LoginWithBitwarden), + { initialValue: false }, + ); + protected readonly singleOrgPolicyApplies = toSignal( this.accountService.activeAccount$.pipe( getUserId, diff --git a/apps/web/src/app/oss-routing.module.ts b/apps/web/src/app/oss-routing.module.ts index 49c42286eebb..ac4df5015bf6 100644 --- a/apps/web/src/app/oss-routing.module.ts +++ b/apps/web/src/app/oss-routing.module.ts @@ -165,12 +165,29 @@ const routes: Routes = [ canActivate: [unauthGuardFn()], data: { titleId: "deleteOrganization" }, }, + // Note: the OAuth completion/broker page is a static connector served at + // /oauth-complete-connector.html (see apps/web/src/connectors/oauth-complete.ts), not an Angular + // route, because it is the registered redirect_uri and must run outside the hash router. ], }, { path: "", component: AnonLayoutWrapperComponent, children: [ + { + path: "oauth/authorize", + canActivate: [canAccessFeature(FeatureFlag.LoginWithBitwarden), deepLinkGuard(), authGuard], + loadComponent: () => + import("./tools/agent-connection/oauth-authorize.component").then( + (m) => m.OAuthAuthorizeComponent, + ), + data: { + pageIcon: UserLockIcon, + titleId: "loginWithBitwarden", + pageTitle: { key: "loginWithBitwarden" }, + doNotSaveUrl: true, + } satisfies RouteDataProperties & AnonLayoutWrapperData, + }, { path: AuthRoute.LoginWithPasskey, canActivate: [unauthGuardFn()], @@ -785,6 +802,15 @@ const routes: Routes = [ path: "security", loadChildren: () => SecurityRoutingModule, }, + { + path: "agent-connections", + canActivate: [canAccessFeature(FeatureFlag.LoginWithBitwarden)], + loadComponent: () => + import("./tools/agent-connection/agent-connections.component").then( + (m) => m.AgentConnectionsComponent, + ), + data: { titleId: "loginWithBitwardenConnections" } satisfies RouteDataProperties, + }, { path: "data-recovery", component: DataRecoveryComponent, diff --git a/apps/web/src/app/tools/agent-connection/agent-connections.component.html b/apps/web/src/app/tools/agent-connection/agent-connections.component.html new file mode 100644 index 000000000000..df39afbfd78e --- /dev/null +++ b/apps/web/src/app/tools/agent-connection/agent-connections.component.html @@ -0,0 +1,40 @@ + + + +

{{ "loginWithBitwardenConnectionsDescription" | i18n }}

+ + @if (connections$ | async; as connections) { + @if (connections.length === 0) { +

{{ "loginWithBitwardenNoConnections" | i18n }}

+ } @else { + + + + {{ "name" | i18n }} + {{ "dateCreated" | i18n }} + {{ "options" | i18n }} + + + + @for (connection of connections; track connection.id) { + + {{ connection.name }} + {{ connection.creationDate | date: "medium" }} + + + + + } + + + } + } +
diff --git a/apps/web/src/app/tools/agent-connection/agent-connections.component.ts b/apps/web/src/app/tools/agent-connection/agent-connections.component.ts new file mode 100644 index 000000000000..dfaeec7dcccb --- /dev/null +++ b/apps/web/src/app/tools/agent-connection/agent-connections.component.ts @@ -0,0 +1,54 @@ +import { Component } from "@angular/core"; +import { Observable } from "rxjs"; + +import { I18nService } from "@bitwarden/common/platform/abstractions/i18n.service"; +import { AgentConnectionView } from "@bitwarden/common/tools/agent-connection/models/view/agent-connection.view"; +import { AgentConnectionApiService } from "@bitwarden/common/tools/agent-connection/services/agent-connection-api.service.abstraction"; +import { InternalAgentConnectionService } from "@bitwarden/common/tools/agent-connection/services/agent-connection.service.abstraction"; +import { DialogService, ToastService } from "@bitwarden/components"; + +import { HeaderModule } from "../../layouts/header/header.module"; +import { SharedModule } from "../../shared"; + +/** + * Settings page listing the user's "Login with Bitwarden" agent connections with a revoke action. + * Revoking deletes the connection server-side (which pushes to the user's other clients) and from + * local state; the bot's short-lived token then expires on its own (no refresh). + */ +// FIXME(https://bitwarden.atlassian.net/browse/CL-764): Migrate to OnPush +// eslint-disable-next-line @angular-eslint/prefer-on-push-component-change-detection +@Component({ + imports: [SharedModule, HeaderModule], + templateUrl: "agent-connections.component.html", +}) +export class AgentConnectionsComponent { + protected connections$: Observable = + this.agentConnectionService.agentConnectionViews$; + + constructor( + private agentConnectionService: InternalAgentConnectionService, + private agentConnectionApiService: AgentConnectionApiService, + private dialogService: DialogService, + private i18nService: I18nService, + private toastService: ToastService, + ) {} + + async revoke(connection: AgentConnectionView): Promise { + const confirmed = await this.dialogService.openSimpleDialog({ + title: { key: "loginWithBitwardenRevokeTitle" }, + content: { key: "loginWithBitwardenRevokeConfirm", placeholders: [connection.name] }, + type: "warning", + acceptButtonText: { key: "revoke" }, + }); + if (!confirmed) { + return; + } + + await this.agentConnectionApiService.delete(connection.id); + await this.agentConnectionService.delete(connection.id); + this.toastService.showToast({ + variant: "success", + message: this.i18nService.t("loginWithBitwardenRevoked"), + }); + } +} diff --git a/apps/web/src/app/tools/agent-connection/oauth-authorize.component.html b/apps/web/src/app/tools/agent-connection/oauth-authorize.component.html new file mode 100644 index 000000000000..893a97f59a23 --- /dev/null +++ b/apps/web/src/app/tools/agent-connection/oauth-authorize.component.html @@ -0,0 +1,51 @@ +@if (loading) { +
+ + {{ "loading" | i18n }} +
+} @else if (context) { +

+ {{ "loginWithBitwardenConsentDescription" | i18n: context.clientName }} +

+ +

+ {{ "loginWithBitwardenScopesTitle" | i18n }} +

+
    + @for (scope of context.scopes; track scope) { +
  • + + {{ scopeLabel(scope) }} +
  • + } +
+ +
+ + +
+} @else { +

{{ "loginWithBitwardenRequestInvalid" | i18n }}

+} diff --git a/apps/web/src/app/tools/agent-connection/oauth-authorize.component.ts b/apps/web/src/app/tools/agent-connection/oauth-authorize.component.ts new file mode 100644 index 000000000000..e867ec8db3bd --- /dev/null +++ b/apps/web/src/app/tools/agent-connection/oauth-authorize.component.ts @@ -0,0 +1,146 @@ +import { ChangeDetectorRef, Component, OnInit } from "@angular/core"; +import { ActivatedRoute, Router } from "@angular/router"; +import { firstValueFrom } from "rxjs"; + +import { AccountService } from "@bitwarden/common/auth/abstractions/account.service"; +import { getUserId } from "@bitwarden/common/auth/services/account.service"; +import { I18nService } from "@bitwarden/common/platform/abstractions/i18n.service"; +import { AgentAccessPskGenerator } from "@bitwarden/common/tools/agent-connection/abstractions/agent-access-psk-generator.abstraction"; +import { AgentConnectionRequest } from "@bitwarden/common/tools/agent-connection/models/request/agent-connection.request"; +import { AgentConnectionApiService } from "@bitwarden/common/tools/agent-connection/services/agent-connection-api.service.abstraction"; +import { AgentConnectionService } from "@bitwarden/common/tools/agent-connection/services/agent-connection.service.abstraction"; +import { ToastService } from "@bitwarden/components"; + +import { SharedModule } from "../../shared"; + +import { AuthorizeContext, OAuthBrokerApiService } from "./services/oauth-broker-api.service"; +import { OAuthBrokerStateService } from "./services/oauth-broker-state.service"; + +/** + * "Login with Bitwarden" consent screen. Identity redirects a pre-registered partner's + * `/connect/authorize` request here (hash route `/#/oauth/authorize?returnUrl=...`). The user must be + * authenticated (route guards) so the master-password-derived user key is available to wrap the PSK. + * + * On approval it: (1) generates the plaintext agent-access PSK, (2) wraps it under the user key and + * stores the ciphertext via `POST /agent-connections`, (3) records consent via the API (which mints a + * single-use token), and (4) navigates to Identity's consent callback, which grants consent and + * resumes the authorize request — issuing the code to the registered `redirect_uri` (the completion + * page). The plaintext PSK never leaves the client and is never sent to the Bitwarden server. + */ +// FIXME(https://bitwarden.atlassian.net/browse/CL-764): Migrate to OnPush +// eslint-disable-next-line @angular-eslint/prefer-on-push-component-change-detection +@Component({ + imports: [SharedModule], + templateUrl: "oauth-authorize.component.html", +}) +export class OAuthAuthorizeComponent implements OnInit { + protected loading = true; + protected submitting = false; + protected context?: AuthorizeContext; + + /** The `returnUrl` of the pending authorize request, from Identity's login redirect. */ + private returnUrl = ""; + /** The OAuth `state`, parsed out of `returnUrl` (Identity does not pass it as a top-level param). */ + private state = ""; + + constructor( + private route: ActivatedRoute, + private router: Router, + private brokerApiService: OAuthBrokerApiService, + private brokerStateService: OAuthBrokerStateService, + private pskGenerator: AgentAccessPskGenerator, + private agentConnectionService: AgentConnectionService, + private agentConnectionApiService: AgentConnectionApiService, + private accountService: AccountService, + private i18nService: I18nService, + private toastService: ToastService, + private changeDetectorRef: ChangeDetectorRef, + ) {} + + async ngOnInit(): Promise { + try { + const params = await firstValueFrom(this.route.queryParams); + this.returnUrl = params.returnUrl ?? ""; + this.state = this.parseState(this.returnUrl); + this.context = await this.brokerApiService.getAuthorizeContext(this.returnUrl); + } catch { + this.toastService.showToast({ + variant: "error", + message: this.i18nService.t("loginWithBitwardenRequestInvalid"), + }); + } finally { + this.loading = false; + // getAuthorizeContext uses native fetch, which can resolve outside Angular's zone, so force a + // change-detection pass to render the resolved consent state. + this.changeDetectorRef.detectChanges(); + } + } + + /** Maps a raw OIDC scope to a friendly, localized description, falling back to the raw value. */ + protected scopeLabel(scope: string): string { + const key = { + openid: "loginWithBitwardenScopeOpenid", + profile: "loginWithBitwardenScopeProfile", + email: "loginWithBitwardenScopeEmail", + }[scope]; + return key != null ? this.i18nService.t(key) : scope; + } + + /** Extracts the `state` value from the embedded authorize query inside `returnUrl`. */ + private parseState(returnUrl: string): string { + const queryIndex = returnUrl.indexOf("?"); + if (queryIndex < 0) { + return ""; + } + return new URLSearchParams(returnUrl.substring(queryIndex + 1)).get("state") ?? ""; + } + + async approve(): Promise { + if (this.context == null || this.submitting) { + return; + } + this.submitting = true; + try { + const userId = await firstValueFrom(this.accountService.activeAccount$.pipe(getUserId)); + + // Generate the PSK only after consent; the plaintext stays client-side. + const psk = await this.pskGenerator.generate(); + + // Store the user-key-encrypted PSK (ciphertext only) on the account, bound to the partner. + const connection = await this.agentConnectionService.encrypt( + this.context.clientId, + this.context.clientName, + psk, + userId, + ); + await this.agentConnectionApiService.post(new AgentConnectionRequest(connection)); + + // Record consent via the API (mints a single-use token). No PSK is sent. + const { token } = await this.brokerApiService.postConsent(this.returnUrl); + + // Hand the plaintext PSK (and the agent's loopback, when the server provides it) to the + // completion connector; survives the navigation via sessionStorage. + this.brokerStateService.set(this.state, psk, this.context.agentRedirectUri); + + // Identity grants consent and resumes the authorize request, issuing the code to the + // registered redirect_uri (the completion page). + window.location.href = await this.brokerApiService.buildConsentCallbackUrl( + token, + this.returnUrl, + ); + } catch { + this.submitting = false; + this.brokerStateService.clear(this.state); + this.toastService.showToast({ + variant: "error", + message: this.i18nService.t("loginWithBitwardenConsentFailed"), + }); + this.changeDetectorRef.detectChanges(); + } + } + + async deny(): Promise { + this.brokerStateService.clear(this.state); + await this.router.navigate(["/"]); + } +} diff --git a/apps/web/src/app/tools/agent-connection/services/oauth-broker-api.service.ts b/apps/web/src/app/tools/agent-connection/services/oauth-broker-api.service.ts new file mode 100644 index 000000000000..8f0e9dffa704 --- /dev/null +++ b/apps/web/src/app/tools/agent-connection/services/oauth-broker-api.service.ts @@ -0,0 +1,89 @@ +import { Injectable } from "@angular/core"; +import { firstValueFrom } from "rxjs"; + +import { ApiService } from "@bitwarden/common/abstractions/api.service"; +import { EnvironmentService } from "@bitwarden/common/platform/abstractions/environment.service"; + +/** The partner app + requested scopes for a pending authorize request, shown on the consent screen. */ +export interface AuthorizeContext { + /** The registered partner's OAuth client id (e.g. `partner.acme`) — bound to the AgentConnection. */ + clientId: string; + clientName: string; + scopes: string[]; + /** + * The agent's loopback redirect the completion connector forwards the PSK to, validated server-side + * against the partner's allow-list. Optional — absent when the partner has no registered agent + * redirect, in which case the completion connector shows "complete" instead of forwarding. + */ + agentRedirectUri?: string; +} + +/** Response of the API consent endpoint — the single-use token handed to Identity's consent callback. */ +interface ConsentResponse { + token: string; +} + +/** + * Talks to the "Login with Bitwarden" OIDC endpoints that drive the web-vault consent flow. They are + * split across two servers: + * - Identity (`src/Identity`) exposes `GET /oidc/AuthorizeContext` and the `GET /oidc/ConsentCallback` + * the browser is finally sent to. + * - The API (`src/Api`) exposes the authenticated `POST /oidc/consent`, which mints the single-use + * consent token. + * + * No PSK is ever sent to any of these endpoints — Identity only records consent. + */ +@Injectable({ providedIn: "root" }) +export class OAuthBrokerApiService { + constructor( + private environmentService: EnvironmentService, + private apiService: ApiService, + ) {} + + /** Fetches the partner app id/name + requested scopes for the pending authorize request. */ + async getAuthorizeContext(returnUrl: string): Promise { + const identityUrl = await this.getIdentityUrl(); + const response = await fetch( + `${identityUrl}/oidc/AuthorizeContext?returnUrl=${encodeURIComponent(returnUrl)}`, + { headers: { Accept: "application/json" } }, + ); + if (!response.ok) { + throw new Error(`Authorize context request failed with status ${response.status}`); + } + const body = await response.json(); + return { + clientId: body.clientId, + clientName: body.clientName, + scopes: body.scopes ?? [], + agentRedirectUri: body.agentRedirectUri, + }; + } + + /** + * Records the user's consent for the pending authorize request (authenticated API call) and returns + * the single-use token to hand to Identity's consent callback. No PSK is sent. + */ + async postConsent(returnUrl: string): Promise<{ token: string }> { + const response = (await this.apiService.send( + "POST", + "/oidc/consent", + { returnUrl }, + true, + true, + )) as ConsentResponse; + return { token: response.token }; + } + + /** + * The Identity URL the browser is navigated to after consent; it signs the user in, grants consent, + * and resumes the original authorize request (which issues the code to the registered redirect URI). + */ + async buildConsentCallbackUrl(token: string, returnUrl: string): Promise { + const identityUrl = await this.getIdentityUrl(); + return `${identityUrl}/oidc/ConsentCallback?token=${encodeURIComponent(token)}&returnUrl=${encodeURIComponent(returnUrl)}`; + } + + private async getIdentityUrl(): Promise { + return (await firstValueFrom(this.environmentService.environment$)).getIdentityUrl(); + } +} diff --git a/apps/web/src/app/tools/agent-connection/services/oauth-broker-state.service.ts b/apps/web/src/app/tools/agent-connection/services/oauth-broker-state.service.ts new file mode 100644 index 000000000000..79384dc997d7 --- /dev/null +++ b/apps/web/src/app/tools/agent-connection/services/oauth-broker-state.service.ts @@ -0,0 +1,49 @@ +import { Injectable } from "@angular/core"; + +/** + * Transient handoff from the consent page (`/oauth/authorize`) to the static completion/broker + * connector (`oauth-complete-connector.html`, the registered `redirect_uri`). + * + * The flow navigates away from the SPA (to Identity's consent callback, which then redirects to the + * registered `redirect_uri`), so the SPA that generated the PSK is torn down before the completion + * page loads — an in-memory handoff cannot survive. `sessionStorage` is the narrowest mechanism that + * does: it is same-origin, scoped to this tab, never leaves the browser, and is removed the instant + * the completion connector consumes it. The plaintext PSK is never persisted to disk and never sent + * to the Bitwarden server. + * + * Keyed by the OAuth `state` so a stale or mismatched completion request can't pick up a PSK. The + * key names here MUST match the ones the connector reads (`apps/web/src/connectors/oauth-complete.ts`). + */ +@Injectable({ providedIn: "root" }) +export class OAuthBrokerStateService { + private readonly pskKeyPrefix = "oauthBrokerPsk:"; + private readonly redirectKeyPrefix = "oauthBrokerRedirect:"; + + /** + * Stashes the plaintext PSK (and, when known, the agent's loopback redirect) for the given OAuth + * `state`, for the completion connector to consume. + */ + set(state: string, psk: string, agentRedirect?: string): void { + sessionStorage.setItem(this.pskKeyPrefix + state, psk); + if (agentRedirect != null && agentRedirect.length > 0) { + sessionStorage.setItem(this.redirectKeyPrefix + state, agentRedirect); + } + } + + /** + * Returns and removes the plaintext PSK for the given `state`. Returns `null` if nothing is held + * for that `state` (e.g. a stale or forged completion request). + */ + take(state: string): string | null { + const key = this.pskKeyPrefix + state; + const psk = sessionStorage.getItem(key); + sessionStorage.removeItem(key); + return psk; + } + + /** Clears any handoff data held for the given `state`. */ + clear(state: string): void { + sessionStorage.removeItem(this.pskKeyPrefix + state); + sessionStorage.removeItem(this.redirectKeyPrefix + state); + } +} diff --git a/apps/web/src/connectors/oauth-complete.html b/apps/web/src/connectors/oauth-complete.html new file mode 100644 index 000000000000..619901b7bf1e --- /dev/null +++ b/apps/web/src/connectors/oauth-complete.html @@ -0,0 +1,30 @@ + + + + + + + + Bitwarden Web vault + + + + + + + + + +
+ Bitwarden +
+ +
+

+
+ + diff --git a/apps/web/src/connectors/oauth-complete.ts b/apps/web/src/connectors/oauth-complete.ts new file mode 100644 index 000000000000..2c6f2e6b7beb --- /dev/null +++ b/apps/web/src/connectors/oauth-complete.ts @@ -0,0 +1,82 @@ +// "Login with Bitwarden" completion/broker connector. This is the registered OAuth `redirect_uri`. +// +// Identity redirects here with `?code&state` (plus `session_state`/`iss`) after the user consents. +// Running at a real path (not the Angular hash router), it: +// 1. reads `code`/`state` from the query, +// 2. retrieves the plaintext PSK the consent page stashed in sessionStorage (keyed by `state`), +// 3. forwards the browser to the agent's loopback with `code`/`state` in the query and the PSK in +// the URL **fragment** (`#psk=...`), then removes the PSK from sessionStorage. +// +// The PSK rides the fragment only, so it never reaches any server. Forwarding is restricted to +// loopback addresses to prevent leaking the secret via an open redirect. + +const PSK_KEY_PREFIX = "oauthBrokerPsk:"; +const REDIRECT_KEY_PREFIX = "oauthBrokerRedirect:"; + +window.addEventListener("load", () => { + const params = new URLSearchParams(window.location.search); + const code = params.get("code"); + const state = params.get("state"); + const error = params.get("error"); + + if (error != null) { + showMessage(`Authorization failed: ${error}`); + return; + } + + if (!code || !state) { + showMessage("Missing authorization response. You can close this window."); + return; + } + + // Retrieve and immediately clear the plaintext PSK stashed by the consent page. + const psk = sessionStorage.getItem(PSK_KEY_PREFIX + state); + sessionStorage.removeItem(PSK_KEY_PREFIX + state); + + // The agent's loopback redirect, stashed by the consent page when the authorize context provides it. + const agentRedirect = sessionStorage.getItem(REDIRECT_KEY_PREFIX + state); + sessionStorage.removeItem(REDIRECT_KEY_PREFIX + state); + + if (psk == null) { + showMessage("Could not complete the connection (missing handoff). You can close this window."); + return; + } + + if (agentRedirect != null && isLoopback(agentRedirect)) { + const separator = agentRedirect.includes("?") ? "&" : "?"; + const target = + `${agentRedirect}${separator}code=${encodeURIComponent(code)}&state=${encodeURIComponent(state)}` + + `#psk=${encodeURIComponent(psk)}`; + window.location.href = target; + return; + } + + // No (valid) agent loopback available — e.g. a manual/dev run. Confirm completion without ever + // rendering the PSK, which has already been consumed from sessionStorage. + showMessage("Authorization complete. You can return to the app."); +}); + +/** Only forward the PSK to loopback addresses, so a bad redirect can't exfiltrate it. */ +function isLoopback(url: string): boolean { + try { + const parsed = new URL(url); + return ( + parsed.hostname === "127.0.0.1" || + parsed.hostname === "localhost" || + parsed.hostname === "[::1]" + ); + } catch { + return false; + } +} + +function showMessage(message: string): void { + const spinner = document.getElementById("spinner"); + if (spinner != null) { + spinner.style.display = "none"; + } + const messageEl = document.getElementById("message"); + if (messageEl != null) { + messageEl.textContent = message; + } +} diff --git a/apps/web/src/locales/en/messages.json b/apps/web/src/locales/en/messages.json index 6f5e8cddba7f..16a74ef38d28 100644 --- a/apps/web/src/locales/en/messages.json +++ b/apps/web/src/locales/en/messages.json @@ -21938,5 +21938,71 @@ "example": "1a2b3c4d" } } + }, + "loginWithBitwarden": { + "message": "Log in with Bitwarden" + }, + "loginWithBitwardenConnections": { + "message": "Connected apps" + }, + "loginWithBitwardenConnectionsDescription": { + "message": "Apps you have authorized to connect to your Bitwarden account. Revoke access at any time." + }, + "loginWithBitwardenConsentDescription": { + "message": "$APPNAME$ wants to connect to your Bitwarden account.", + "placeholders": { + "appname": { + "content": "$1", + "example": "Acme Bot" + } + } + }, + "loginWithBitwardenScopesTitle": { + "message": "This app will be able to access" + }, + "loginWithBitwardenScopeOpenid": { + "message": "Verify your identity" + }, + "loginWithBitwardenScopeProfile": { + "message": "Your name" + }, + "loginWithBitwardenScopeEmail": { + "message": "Your email address" + }, + "loginWithBitwardenApprove": { + "message": "Approve" + }, + "loginWithBitwardenDeny": { + "message": "Deny" + }, + "loginWithBitwardenRequestInvalid": { + "message": "This authorization request is invalid or has expired." + }, + "loginWithBitwardenConsentFailed": { + "message": "Could not complete the authorization. Please try again." + }, + "loginWithBitwardenCompleting": { + "message": "Finishing up, please wait..." + }, + "loginWithBitwardenCompleteFailed": { + "message": "Could not return to the app. You can close this window and try again." + }, + "loginWithBitwardenNoConnections": { + "message": "You have not connected any apps yet." + }, + "loginWithBitwardenRevokeTitle": { + "message": "Revoke access" + }, + "loginWithBitwardenRevokeConfirm": { + "message": "Are you sure you want to revoke access for $APPNAME$?", + "placeholders": { + "appname": { + "content": "$1", + "example": "Acme Bot" + } + } + }, + "loginWithBitwardenRevoked": { + "message": "Access revoked" } } diff --git a/apps/web/webpack.base.js b/apps/web/webpack.base.js index 498e8e6f1d8a..75501b0da701 100644 --- a/apps/web/webpack.base.js +++ b/apps/web/webpack.base.js @@ -146,6 +146,11 @@ module.exports.buildConfig = function buildConfig(params) { filename: "redirect-connector.html", chunks: ["connectors/redirect", "styles"], }), + new HtmlWebpackPlugin({ + template: path.resolve(__dirname, "src/connectors/oauth-complete.html"), + filename: "oauth-complete-connector.html", + chunks: ["connectors/oauth-complete", "styles"], + }), new HtmlWebpackPlugin({ template: path.resolve(__dirname, "src/connectors/duo-redirect.html"), filename: "duo-redirect-connector.html", @@ -256,6 +261,15 @@ module.exports.buildConfig = function buildConfig(params) { secure: false, changeOrigin: true, }, + { + // Duende's interactive OIDC flow (e.g. Login with Bitwarden consent) emits root-relative + // redirects to /connect/*. Proxy them to Identity so they resolve in dev (prod serves + // Identity on its own origin, so this isn't needed there). + context: ["/connect"], + target: envConfig.dev?.proxyIdentity, + secure: false, + changeOrigin: true, + }, { context: ["/events"], target: envConfig.dev?.proxyEvents, @@ -399,6 +413,7 @@ module.exports.buildConfig = function buildConfig(params) { "connectors/sso": path.resolve(__dirname, "src/connectors/sso.ts"), "connectors/duo-redirect": path.resolve(__dirname, "src/connectors/duo-redirect.ts"), "connectors/redirect": path.resolve(__dirname, "src/connectors/redirect.ts"), + "connectors/oauth-complete": path.resolve(__dirname, "src/connectors/oauth-complete.ts"), "connectors/platform/proxy-cookie-redirect": path.resolve( __dirname, "src/connectors/platform/proxy-cookie-redirect.ts", diff --git a/libs/angular/src/services/jslib-services.module.ts b/libs/angular/src/services/jslib-services.module.ts index adf9a1ca25de..410ae6d467bd 100644 --- a/libs/angular/src/services/jslib-services.module.ts +++ b/libs/angular/src/services/jslib-services.module.ts @@ -307,6 +307,17 @@ import { ProviderApiService } from "@bitwarden/common/provider/services/provider import { ProviderService } from "@bitwarden/common/provider/services/provider.service"; import { ApiService } from "@bitwarden/common/services/api.service"; import { AuditService } from "@bitwarden/common/services/audit.service"; +import { AgentAccessPskGenerator } from "@bitwarden/common/tools/agent-connection/abstractions/agent-access-psk-generator.abstraction"; +import { AgentConnectionApiService } from "@bitwarden/common/tools/agent-connection/services/agent-connection-api.service"; +import { AgentConnectionApiService as AgentConnectionApiServiceAbstraction } from "@bitwarden/common/tools/agent-connection/services/agent-connection-api.service.abstraction"; +import { AgentConnectionStateProvider } from "@bitwarden/common/tools/agent-connection/services/agent-connection-state.provider"; +import { AgentConnectionStateProvider as AgentConnectionStateProviderAbstraction } from "@bitwarden/common/tools/agent-connection/services/agent-connection-state.provider.abstraction"; +import { AgentConnectionService } from "@bitwarden/common/tools/agent-connection/services/agent-connection.service"; +import { + AgentConnectionService as AgentConnectionServiceAbstraction, + InternalAgentConnectionService, +} from "@bitwarden/common/tools/agent-connection/services/agent-connection.service.abstraction"; +import { DefaultAgentAccessPskGenerator } from "@bitwarden/common/tools/agent-connection/services/default-agent-access-psk-generator"; import { PasswordStrengthService, PasswordStrengthServiceAbstraction, @@ -1044,6 +1055,35 @@ const safeProviders: SafeProvider[] = [ provide: SendApiServiceAbstraction, useExisting: SendApiService, }), + safeProvider({ + provide: InternalAgentConnectionService, + useClass: AgentConnectionService, + deps: [ + KeyService, + EncryptService, + I18nServiceAbstraction, + AgentConnectionStateProviderAbstraction, + ], + }), + safeProvider({ + provide: AgentConnectionServiceAbstraction, + useExisting: InternalAgentConnectionService, + }), + safeProvider({ + provide: AgentConnectionStateProviderAbstraction, + useClass: AgentConnectionStateProvider, + deps: [StateProvider], + }), + safeProvider({ + provide: AgentConnectionApiServiceAbstraction, + useClass: AgentConnectionApiService, + deps: [ApiServiceAbstraction], + }), + safeProvider({ + provide: AgentAccessPskGenerator, + useClass: DefaultAgentAccessPskGenerator, + deps: [KeyGenerationService], + }), safeProvider({ provide: SyncService, useClass: DefaultSyncService, @@ -1074,6 +1114,7 @@ const safeProviders: SafeProvider[] = [ StateProvider, ConfigService, SdkService, + InternalAgentConnectionService, ], }), safeProvider({ diff --git a/libs/common/src/enums/feature-flag.enum.ts b/libs/common/src/enums/feature-flag.enum.ts index 55295b565bb4..9f3e14e7082f 100644 --- a/libs/common/src/enums/feature-flag.enum.ts +++ b/libs/common/src/enums/feature-flag.enum.ts @@ -69,6 +69,7 @@ export enum FeatureFlag { /* Tools */ ImportUpgrade = "pm-35053-import-upgrade", PM34203TemporaryItemSharing = "pm-34203-temporary-item-sharing", + LoginWithBitwarden = "pm-oidc-provider-agent-access", /* DIRT */ EventManagementForBlumira = "event-management-for-blumira", @@ -147,6 +148,7 @@ export const DefaultFeatureFlagValue = { /* Tools */ [FeatureFlag.ImportUpgrade]: FALSE, [FeatureFlag.PM34203TemporaryItemSharing]: FALSE, + [FeatureFlag.LoginWithBitwarden]: FALSE, /* DIRT */ [FeatureFlag.EventManagementForBlumira]: FALSE, diff --git a/libs/common/src/enums/notification-type.enum.ts b/libs/common/src/enums/notification-type.enum.ts index d94db9d06b3a..fb94a1a21ce4 100644 --- a/libs/common/src/enums/notification-type.enum.ts +++ b/libs/common/src/enums/notification-type.enum.ts @@ -41,4 +41,8 @@ export enum NotificationType { RefreshApproverInbox = 28, RefreshAccessRequest = 29, + + SyncAgentConnectionCreate = 30, + SyncAgentConnectionUpdate = 31, + SyncAgentConnectionDelete = 32, } diff --git a/libs/common/src/models/response/notification.response.ts b/libs/common/src/models/response/notification.response.ts index d8fe45a6f170..eeade8ec4843 100644 --- a/libs/common/src/models/response/notification.response.ts +++ b/libs/common/src/models/response/notification.response.ts @@ -50,6 +50,11 @@ export class NotificationResponse extends BaseResponse { case NotificationType.SyncSendDelete: this.payload = new SyncSendNotification(payload); break; + case NotificationType.SyncAgentConnectionCreate: + case NotificationType.SyncAgentConnectionUpdate: + case NotificationType.SyncAgentConnectionDelete: + this.payload = new SyncAgentConnectionNotification(payload); + break; case NotificationType.AuthRequest: case NotificationType.AuthRequestResponse: this.payload = new AuthRequestPushNotification(payload); @@ -136,6 +141,19 @@ export class SyncSendNotification extends BaseResponse { } } +export class SyncAgentConnectionNotification extends BaseResponse { + id: string; + userId: string; + revisionDate: Date; + + constructor(response: any) { + super(response); + this.id = this.getResponseProperty("Id"); + this.userId = this.getResponseProperty("UserId"); + this.revisionDate = new Date(this.getResponseProperty("RevisionDate")); + } +} + export class AuthRequestPushNotification extends BaseResponse { id: string; userId: string; diff --git a/libs/common/src/platform/server-notifications/internal/default-server-notifications.service.ts b/libs/common/src/platform/server-notifications/internal/default-server-notifications.service.ts index 470bf23121f3..4c12b54d5a8a 100644 --- a/libs/common/src/platform/server-notifications/internal/default-server-notifications.service.ts +++ b/libs/common/src/platform/server-notifications/internal/default-server-notifications.service.ts @@ -271,6 +271,13 @@ export class DefaultServerNotificationsService implements ServerNotificationsSer case NotificationType.SyncSendDelete: await this.syncService.syncDeleteSend(notification.payload as SyncSendNotification); break; + case NotificationType.SyncAgentConnectionCreate: + case NotificationType.SyncAgentConnectionUpdate: + case NotificationType.SyncAgentConnectionDelete: + // Agent connections have no targeted fetch path; a full sync re-pulls the encrypted PSKs + // (and drops revoked ones). Inclusion is feature-flag gated inside the sync handler. + await this.syncService.fullSync(true); + break; case NotificationType.AuthRequest: { // Only Extension and Desktop implement the AuthRequestAnsweringService if (this.authRequestAnsweringService.receivedPendingAuthRequest) { diff --git a/libs/common/src/platform/sync/default-sync.service.spec.ts b/libs/common/src/platform/sync/default-sync.service.spec.ts index c3347d4e8d99..1cbe2ad031b9 100644 --- a/libs/common/src/platform/sync/default-sync.service.spec.ts +++ b/libs/common/src/platform/sync/default-sync.service.spec.ts @@ -38,6 +38,7 @@ import { SyncSendNotification, } from "../../models/response/notification.response"; import { ProviderService } from "../../provider/abstractions/provider.service"; +import { InternalAgentConnectionService } from "../../tools/agent-connection/services/agent-connection.service.abstraction"; import { SendApiService } from "../../tools/send/services/send-api.service.abstraction"; import { InternalSendService } from "../../tools/send/services/send.service.abstraction"; import { SendType } from "../../tools/send/types/send-type"; @@ -85,6 +86,7 @@ describe("DefaultSyncService", () => { let stateProvider: MockProxy; let configService: MockProxy; let sdkService: MockProxy; + let agentConnectionService: MockProxy; let cryptoSyncHandler: { on_sync: jest.Mock, [CryptoSyncData]> }; let sendsClient: { fetch: jest.Mock; retry_pending_deletions: jest.Mock }; @@ -118,6 +120,7 @@ describe("DefaultSyncService", () => { stateProvider = mock(); configService = mock(); sdkService = mock(); + agentConnectionService = mock(); cryptoSyncHandler = { on_sync: jest.fn().mockResolvedValue(undefined) }; sendsClient = { fetch: jest.fn(), @@ -162,6 +165,7 @@ describe("DefaultSyncService", () => { stateProvider, configService, sdkService, + agentConnectionService, ); }); diff --git a/libs/common/src/platform/sync/default-sync.service.ts b/libs/common/src/platform/sync/default-sync.service.ts index 21c3189ff0ad..afc7e3b26473 100644 --- a/libs/common/src/platform/sync/default-sync.service.ts +++ b/libs/common/src/platform/sync/default-sync.service.ts @@ -39,6 +39,9 @@ import { DomainsResponse } from "../../models/response/domains.response"; import { ProfileResponse } from "../../models/response/profile.response"; import { ProviderService } from "../../provider/abstractions/provider.service"; import { ProviderData } from "../../provider/models/data/provider.data"; +import { AgentConnectionData } from "../../tools/agent-connection/models/data/agent-connection.data"; +import { AgentConnectionResponse } from "../../tools/agent-connection/models/response/agent-connection.response"; +import { InternalAgentConnectionService } from "../../tools/agent-connection/services/agent-connection.service.abstraction"; import { SendData } from "../../tools/send/models/data/send.data"; import { SendResponse } from "../../tools/send/models/response/send.response"; import { SendApiService } from "../../tools/send/services/send-api.service.abstraction"; @@ -103,6 +106,7 @@ export class DefaultSyncService extends CoreSyncService { stateProvider: StateProvider, configService: ConfigService, sdkService: SdkService, + private agentConnectionService: InternalAgentConnectionService, ) { super( tokenService, @@ -185,6 +189,7 @@ export class DefaultSyncService extends CoreSyncService { await this.syncCiphers(response.ciphers, response.profile.id); await this.syncSends(response.sends, response.profile.id); await this.retryPendingSendDeletions(response.profile.id); + await this.syncAgentConnections(response.agentConnections, response.profile.id); await this.syncSettings(response.domains, response.profile.id); await this.syncPolicies(response.policiesNew, response.policies, response.profile.id); processMeasurement.finish([["Ciphers", response.ciphers?.length ?? 0]]); @@ -430,6 +435,20 @@ export class DefaultSyncService extends CoreSyncService { return await this.sendService.replace(sends, userId); } + private async syncAgentConnections(response: AgentConnectionResponse[], userId: UserId) { + // Gated behind the feature flag so nothing is stored when the feature is off. + const enabled = await this.configService.getFeatureFlag(FeatureFlag.LoginWithBitwarden); + if (!enabled) { + return; + } + + const connections: { [id: string]: AgentConnectionData } = {}; + (response ?? []).forEach((c) => { + connections[c.id] = new AgentConnectionData(c); + }); + return await this.agentConnectionService.replace(connections, userId); + } + private async syncSettings(response: DomainsResponse, userId: UserId) { let eqDomains: string[][] = []; if (response != null && response.equivalentDomains != null) { diff --git a/libs/common/src/platform/sync/sync.response.ts b/libs/common/src/platform/sync/sync.response.ts index c0d0f12b9cfa..e282d20e4400 100644 --- a/libs/common/src/platform/sync/sync.response.ts +++ b/libs/common/src/platform/sync/sync.response.ts @@ -4,6 +4,7 @@ import { UserDecryptionResponse } from "../../key-management/models/response/use import { BaseResponse } from "../../models/response/base.response"; import { DomainsResponse } from "../../models/response/domains.response"; import { ProfileResponse } from "../../models/response/profile.response"; +import { AgentConnectionResponse } from "../../tools/agent-connection/models/response/agent-connection.response"; import { SendResponse } from "../../tools/send/models/response/send.response"; import { CipherResponse } from "../../vault/models/response/cipher.response"; import { FolderResponse } from "../../vault/models/response/folder.response"; @@ -17,6 +18,7 @@ export class SyncResponse extends BaseResponse { policies?: PolicyResponse[] = []; policiesNew?: PolicyResponse[]; sends: SendResponse[] = []; + agentConnections: AgentConnectionResponse[] = []; userDecryption?: UserDecryptionResponse; constructor(response: any) { @@ -62,6 +64,11 @@ export class SyncResponse extends BaseResponse { this.sends = sends.map((s: any) => new SendResponse(s)); } + const agentConnections = this.getResponseProperty("AgentConnections"); + if (agentConnections != null) { + this.agentConnections = agentConnections.map((c: any) => new AgentConnectionResponse(c)); + } + const userDecryption = this.getResponseProperty("UserDecryption"); if (userDecryption != null && typeof userDecryption === "object") { this.userDecryption = new UserDecryptionResponse(userDecryption); diff --git a/libs/common/src/tools/agent-connection/abstractions/agent-access-psk-generator.abstraction.ts b/libs/common/src/tools/agent-connection/abstractions/agent-access-psk-generator.abstraction.ts new file mode 100644 index 000000000000..8d4933a52879 --- /dev/null +++ b/libs/common/src/tools/agent-connection/abstractions/agent-access-psk-generator.abstraction.ts @@ -0,0 +1,11 @@ +/** + * Generates the plaintext agent-access pre-shared key (PSK) for a new agent connection. + * + * The real implementation is owned by the agent-access library (out of scope here); this seam lets + * the OAuth broker flow be built and tested before that library lands. The returned PSK is + * Protected Data: it is wrapped under the user key before it leaves the client and is never sent to + * the server in plaintext. + */ +export abstract class AgentAccessPskGenerator { + abstract generate(): Promise; +} diff --git a/libs/common/src/tools/agent-connection/models/data/agent-connection.data.ts b/libs/common/src/tools/agent-connection/models/data/agent-connection.data.ts new file mode 100644 index 000000000000..6d6d2547cc6a --- /dev/null +++ b/libs/common/src/tools/agent-connection/models/data/agent-connection.data.ts @@ -0,0 +1,32 @@ +// FIXME: Update this file to be type safe and remove this and next line +// @ts-strict-ignore +import { AgentConnectionResponse } from "../response/agent-connection.response"; + +/** + * The string-shaped, encrypted-at-rest representation of an {@link AgentConnection} stored in + * `AGENT_CONNECTION_USER_ENCRYPTED` state. `key` holds the user-key-encrypted PSK as an + * `encryptedString`. + */ +export class AgentConnectionData { + id: string; + partnerClientId: string; + name: string; + key: string; + creationDate: string; + revisionDate: string; + revokedDate: string | null; + + constructor(response?: AgentConnectionResponse) { + if (response == null) { + return; + } + + this.id = response.id; + this.partnerClientId = response.partnerClientId; + this.name = response.name; + this.key = response.key; + this.creationDate = response.creationDate; + this.revisionDate = response.revisionDate; + this.revokedDate = response.revokedDate; + } +} diff --git a/libs/common/src/tools/agent-connection/models/domain/agent-connection.spec.ts b/libs/common/src/tools/agent-connection/models/domain/agent-connection.spec.ts new file mode 100644 index 000000000000..7415c50bc084 --- /dev/null +++ b/libs/common/src/tools/agent-connection/models/domain/agent-connection.spec.ts @@ -0,0 +1,72 @@ +import { mock } from "jest-mock-extended"; + +// eslint-disable-next-line no-restricted-imports +import { EncryptService, EncString } from "@bitwarden/legacy-crypto"; + +import { UserKey } from "../../../../types/key"; +import { AgentConnectionData } from "../data/agent-connection.data"; + +import { AgentConnection } from "./agent-connection"; + +describe("AgentConnection", () => { + function data(): AgentConnectionData { + const d = new AgentConnectionData(); + d.id = "id-1"; + d.partnerClientId = "partner.acme"; + d.name = "Acme Bot"; + d.key = "2.abc|def|ghi"; + d.creationDate = "2024-01-01T00:00:00.000Z"; + d.revisionDate = "2024-01-02T00:00:00.000Z"; + d.revokedDate = null; + return d; + } + + it("constructs a domain model from data", () => { + const connection = new AgentConnection(data()); + + expect(connection.id).toBe("id-1"); + expect(connection.partnerClientId).toBe("partner.acme"); + expect(connection.name).toBe("Acme Bot"); + expect(connection.key).toEqual(new EncString("2.abc|def|ghi")); + expect(connection.creationDate).toEqual(new Date("2024-01-01T00:00:00.000Z")); + expect(connection.revisionDate).toEqual(new Date("2024-01-02T00:00:00.000Z")); + expect(connection.revokedDate).toBeNull(); + expect(connection.revoked).toBe(false); + }); + + it("round-trips through toAgentConnectionData", () => { + const connection = new AgentConnection(data()); + + expect(connection.toAgentConnectionData()).toEqual(data()); + }); + + it("reports revoked when a revoked date is present", () => { + const d = data(); + d.revokedDate = "2024-02-01T00:00:00.000Z"; + + expect(new AgentConnection(d).revoked).toBe(true); + }); + + it("decrypts the PSK with the user key", async () => { + const connection = new AgentConnection(data()); + const encryptService = mock(); + const userKey = mock(); + encryptService.decryptString.mockResolvedValue("plaintext-psk"); + + const view = await connection.decrypt(userKey, encryptService); + + expect(encryptService.decryptString).toHaveBeenCalledWith(connection.key, userKey); + expect(view.psk).toBe("plaintext-psk"); + expect(view.id).toBe("id-1"); + expect(view.name).toBe("Acme Bot"); + }); + + it("deserializes from JSON", () => { + const connection = new AgentConnection(data()); + const json = JSON.parse(JSON.stringify(connection)); + + const restored = AgentConnection.fromJSON(json); + + expect(restored).toEqual(connection); + }); +}); diff --git a/libs/common/src/tools/agent-connection/models/domain/agent-connection.ts b/libs/common/src/tools/agent-connection/models/domain/agent-connection.ts new file mode 100644 index 000000000000..7b01fb4e3837 --- /dev/null +++ b/libs/common/src/tools/agent-connection/models/domain/agent-connection.ts @@ -0,0 +1,77 @@ +// FIXME: Update this file to be type safe and remove this and next line +// @ts-strict-ignore +import { Jsonify } from "type-fest"; + +// eslint-disable-next-line no-restricted-imports +import { EncryptService, EncString } from "@bitwarden/legacy-crypto"; + +import Domain from "../../../../platform/models/domain/domain-base"; +import { UserKey } from "../../../../types/key"; +import { AgentConnectionData } from "../data/agent-connection.data"; +import { AgentConnectionView } from "../view/agent-connection.view"; + +/** + * Domain model for an agent connection. The agent-access PSK lives in {@link key} as an + * {@link EncString} wrapped directly under the user key (no per-item key derivation, unlike + * `Send`). Only the user's own clients can decrypt it; the server never sees plaintext. + */ +export class AgentConnection extends Domain { + id: string; + partnerClientId: string; + name: string; + key: EncString; + creationDate: Date; + revisionDate: Date; + revokedDate: Date | null; + + constructor(obj?: AgentConnectionData) { + super(); + if (obj == null) { + return; + } + + this.id = obj.id; + this.partnerClientId = obj.partnerClientId; + this.name = obj.name; + this.key = obj.key != null ? new EncString(obj.key) : null; + this.creationDate = obj.creationDate != null ? new Date(obj.creationDate) : null; + this.revisionDate = obj.revisionDate != null ? new Date(obj.revisionDate) : null; + this.revokedDate = obj.revokedDate != null ? new Date(obj.revokedDate) : null; + } + + get revoked(): boolean { + return this.revokedDate != null; + } + + /** Decrypts the PSK with the user key, producing a {@link AgentConnectionView}. */ + async decrypt(userKey: UserKey, encryptService: EncryptService): Promise { + const view = new AgentConnectionView(this); + view.psk = this.key != null ? await encryptService.decryptString(this.key, userKey) : null; + return view; + } + + toAgentConnectionData(): AgentConnectionData { + const data = new AgentConnectionData(); + data.id = this.id; + data.partnerClientId = this.partnerClientId; + data.name = this.name; + data.key = this.key?.encryptedString ?? null; + data.creationDate = this.creationDate?.toISOString() ?? null; + data.revisionDate = this.revisionDate?.toISOString() ?? null; + data.revokedDate = this.revokedDate?.toISOString() ?? null; + return data; + } + + static fromJSON(obj: Jsonify): AgentConnection { + if (obj == null) { + return null; + } + + return Object.assign(new AgentConnection(), obj, { + key: EncString.fromJSON(obj.key), + creationDate: obj.creationDate == null ? null : new Date(obj.creationDate), + revisionDate: obj.revisionDate == null ? null : new Date(obj.revisionDate), + revokedDate: obj.revokedDate == null ? null : new Date(obj.revokedDate), + }); + } +} diff --git a/libs/common/src/tools/agent-connection/models/request/agent-connection-with-id.request.ts b/libs/common/src/tools/agent-connection/models/request/agent-connection-with-id.request.ts new file mode 100644 index 000000000000..02751c560ac9 --- /dev/null +++ b/libs/common/src/tools/agent-connection/models/request/agent-connection-with-id.request.ts @@ -0,0 +1,16 @@ +import { AgentConnection } from "../domain/agent-connection"; + +import { AgentConnectionRequest } from "./agent-connection.request"; + +/** + * Agent-connection request carrying its id, used by the account key-rotation flow to submit each + * connection's PSK re-wrapped under the new user key. + */ +export class AgentConnectionWithIdRequest extends AgentConnectionRequest { + id: string; + + constructor(connection: AgentConnection) { + super(connection); + this.id = connection.id; + } +} diff --git a/libs/common/src/tools/agent-connection/models/request/agent-connection.request.ts b/libs/common/src/tools/agent-connection/models/request/agent-connection.request.ts new file mode 100644 index 000000000000..161ea1a6269e --- /dev/null +++ b/libs/common/src/tools/agent-connection/models/request/agent-connection.request.ts @@ -0,0 +1,21 @@ +// FIXME: Update this file to be type safe and remove this and next line +// @ts-strict-ignore +import { AgentConnection } from "../domain/agent-connection"; + +/** + * Create request for an agent connection. `key` is the user-key-encrypted PSK + * (`encryptedString`); the server stores it as ciphertext only. `partnerClientId` is validated by + * the server against the user's pending authorize/consent context — it is not trusted as a + * free-form value. + */ +export class AgentConnectionRequest { + partnerClientId: string; + name: string; + key: string; + + constructor(connection: AgentConnection) { + this.partnerClientId = connection.partnerClientId; + this.name = connection.name; + this.key = connection.key?.encryptedString ?? null; + } +} diff --git a/libs/common/src/tools/agent-connection/models/response/agent-connection.response.ts b/libs/common/src/tools/agent-connection/models/response/agent-connection.response.ts new file mode 100644 index 000000000000..04c8db1b4e2a --- /dev/null +++ b/libs/common/src/tools/agent-connection/models/response/agent-connection.response.ts @@ -0,0 +1,27 @@ +import { BaseResponse } from "../../../../models/response/base.response"; + +/** + * API response for an {@link AgentConnection} returned by the server (sync and the + * `/agent-connections` endpoints). `key` is the user-key-encrypted agent-access PSK; the server + * stores and relays it as ciphertext only and cannot decrypt it. + */ +export class AgentConnectionResponse extends BaseResponse { + id: string; + partnerClientId: string; + name: string; + key: string; + creationDate: string; + revisionDate: string; + revokedDate: string | null; + + constructor(response: unknown) { + super(response); + this.id = this.getResponseProperty("Id"); + this.partnerClientId = this.getResponseProperty("PartnerClientId"); + this.name = this.getResponseProperty("Name"); + this.key = this.getResponseProperty("Key"); + this.creationDate = this.getResponseProperty("CreationDate"); + this.revisionDate = this.getResponseProperty("RevisionDate"); + this.revokedDate = this.getResponseProperty("RevokedDate") ?? null; + } +} diff --git a/libs/common/src/tools/agent-connection/models/view/agent-connection.view.ts b/libs/common/src/tools/agent-connection/models/view/agent-connection.view.ts new file mode 100644 index 000000000000..c8185932051a --- /dev/null +++ b/libs/common/src/tools/agent-connection/models/view/agent-connection.view.ts @@ -0,0 +1,49 @@ +// FIXME: Update this file to be type safe and remove this and next line +// @ts-strict-ignore +import { Jsonify } from "type-fest"; + +import { View } from "../../../../models/view/view"; +import { AgentConnection } from "../domain/agent-connection"; + +/** + * Decrypted view of an {@link AgentConnection}. {@link psk} is the plaintext agent-access PSK and + * is Protected Data — never log it or send it to the server. + */ +export class AgentConnectionView implements View { + id: string = null; + partnerClientId: string = null; + name: string = null; + psk: string = null; + creationDate: Date = null; + revisionDate: Date = null; + revokedDate: Date | null = null; + + constructor(c?: AgentConnection) { + if (c == null) { + return; + } + + this.id = c.id; + this.partnerClientId = c.partnerClientId; + this.name = c.name; + this.creationDate = c.creationDate; + this.revisionDate = c.revisionDate; + this.revokedDate = c.revokedDate; + } + + get revoked(): boolean { + return this.revokedDate != null; + } + + static fromJSON(obj: Jsonify): AgentConnectionView { + if (obj == null) { + return null; + } + + return Object.assign(new AgentConnectionView(), obj, { + creationDate: obj.creationDate == null ? null : new Date(obj.creationDate), + revisionDate: obj.revisionDate == null ? null : new Date(obj.revisionDate), + revokedDate: obj.revokedDate == null ? null : new Date(obj.revokedDate), + }); + } +} diff --git a/libs/common/src/tools/agent-connection/services/agent-connection-api.service.abstraction.ts b/libs/common/src/tools/agent-connection/services/agent-connection-api.service.abstraction.ts new file mode 100644 index 000000000000..e7c9e1176de8 --- /dev/null +++ b/libs/common/src/tools/agent-connection/services/agent-connection-api.service.abstraction.ts @@ -0,0 +1,12 @@ +import { ListResponse } from "../../../models/response/list.response"; +import { AgentConnectionRequest } from "../models/request/agent-connection.request"; +import { AgentConnectionResponse } from "../models/response/agent-connection.response"; + +export abstract class AgentConnectionApiService { + /** Creates an agent connection. The request carries the user-key-encrypted PSK (ciphertext). */ + abstract post(request: AgentConnectionRequest): Promise; + /** Lists the authenticated user's agent connections. */ + abstract getAll(): Promise>; + /** Revokes (deletes) an agent connection by id. */ + abstract delete(id: string): Promise; +} diff --git a/libs/common/src/tools/agent-connection/services/agent-connection-api.service.ts b/libs/common/src/tools/agent-connection/services/agent-connection-api.service.ts new file mode 100644 index 000000000000..e484d7fb63af --- /dev/null +++ b/libs/common/src/tools/agent-connection/services/agent-connection-api.service.ts @@ -0,0 +1,24 @@ +import { ApiService } from "../../../abstractions/api.service"; +import { ListResponse } from "../../../models/response/list.response"; +import { AgentConnectionRequest } from "../models/request/agent-connection.request"; +import { AgentConnectionResponse } from "../models/response/agent-connection.response"; + +import { AgentConnectionApiService as AgentConnectionApiServiceAbstraction } from "./agent-connection-api.service.abstraction"; + +export class AgentConnectionApiService implements AgentConnectionApiServiceAbstraction { + constructor(private apiService: ApiService) {} + + async post(request: AgentConnectionRequest): Promise { + const result = await this.apiService.send("POST", "/agent-connections", request, true, true); + return new AgentConnectionResponse(result); + } + + async getAll(): Promise> { + const result = await this.apiService.send("GET", "/agent-connections", null, true, true); + return new ListResponse(result, AgentConnectionResponse); + } + + async delete(id: string): Promise { + await this.apiService.send("DELETE", "/agent-connections/" + id, null, true, false); + } +} diff --git a/libs/common/src/tools/agent-connection/services/agent-connection-state.provider.abstraction.ts b/libs/common/src/tools/agent-connection/services/agent-connection-state.provider.abstraction.ts new file mode 100644 index 000000000000..67c0bc69ed08 --- /dev/null +++ b/libs/common/src/tools/agent-connection/services/agent-connection-state.provider.abstraction.ts @@ -0,0 +1,21 @@ +// FIXME: Update this file to be type safe and remove this and next line +// @ts-strict-ignore +import { Observable } from "rxjs"; +import type { Simplify } from "type-fest"; + +import { CombinedState } from "../../../platform/state"; +import { UserId } from "../../../types/guid"; +import { AgentConnectionData } from "../models/data/agent-connection.data"; + +type EncryptedAgentConnectionState = Simplify>>; + +export abstract class AgentConnectionStateProvider { + encryptedState$: Observable; + + getEncryptedAgentConnections: () => Promise; + + setEncryptedAgentConnections: ( + value: Record, + userId: UserId, + ) => Promise; +} diff --git a/libs/common/src/tools/agent-connection/services/agent-connection-state.provider.ts b/libs/common/src/tools/agent-connection/services/agent-connection-state.provider.ts new file mode 100644 index 000000000000..748a988bc8df --- /dev/null +++ b/libs/common/src/tools/agent-connection/services/agent-connection-state.provider.ts @@ -0,0 +1,35 @@ +// FIXME: Update this file to be type safe and remove this and next line +// @ts-strict-ignore +import { Observable, firstValueFrom } from "rxjs"; + +import { ActiveUserState, CombinedState, StateProvider } from "../../../platform/state"; +import { UserId } from "../../../types/guid"; +import { AgentConnectionData } from "../models/data/agent-connection.data"; + +import { AgentConnectionStateProvider as AgentConnectionStateProviderAbstraction } from "./agent-connection-state.provider.abstraction"; +import { AGENT_CONNECTION_USER_ENCRYPTED } from "./key-definitions"; + +/** State provider for agent connections. */ +export class AgentConnectionStateProvider implements AgentConnectionStateProviderAbstraction { + encryptedState$: Observable>>; + + private activeUserEncryptedState: ActiveUserState>; + + constructor(protected stateProvider: StateProvider) { + this.activeUserEncryptedState = this.stateProvider.getActive(AGENT_CONNECTION_USER_ENCRYPTED); + this.encryptedState$ = this.activeUserEncryptedState.combinedState$; + } + + async getEncryptedAgentConnections(): Promise< + CombinedState> + > { + return await firstValueFrom(this.encryptedState$); + } + + async setEncryptedAgentConnections( + value: Record, + userId: UserId, + ): Promise { + await this.stateProvider.getUser(userId, AGENT_CONNECTION_USER_ENCRYPTED).update(() => value); + } +} diff --git a/libs/common/src/tools/agent-connection/services/agent-connection.service.abstraction.ts b/libs/common/src/tools/agent-connection/services/agent-connection.service.abstraction.ts new file mode 100644 index 000000000000..3d6a0f22aba8 --- /dev/null +++ b/libs/common/src/tools/agent-connection/services/agent-connection.service.abstraction.ts @@ -0,0 +1,40 @@ +import { Observable } from "rxjs"; + +// eslint-disable-next-line no-restricted-imports +import { UserKeyRotationDataProvider } from "@bitwarden/key-management"; + +import { UserId } from "../../../types/guid"; +import { UserKey } from "../../../types/key"; +import { AgentConnectionData } from "../models/data/agent-connection.data"; +import { AgentConnection } from "../models/domain/agent-connection"; +import { AgentConnectionWithIdRequest } from "../models/request/agent-connection-with-id.request"; +import { AgentConnectionView } from "../models/view/agent-connection.view"; + +export abstract class AgentConnectionService implements UserKeyRotationDataProvider { + abstract agentConnections$: Observable; + abstract agentConnectionViews$: Observable; + + /** + * Builds an encrypted {@link AgentConnection} by wrapping the plaintext PSK under the user key. + * @param plaintextPsk Protected Data — the plaintext agent-access PSK. Never logged or persisted. + */ + abstract encrypt( + partnerClientId: string, + name: string, + plaintextPsk: string, + userId: UserId, + ): Promise; + + /** Re-wraps each connection's PSK under the new user key for the account key-rotation flow. */ + abstract getRotatedData( + originalUserKey: UserKey, + newUserKey: UserKey, + userId: UserId, + ): Promise; +} + +export abstract class InternalAgentConnectionService extends AgentConnectionService { + abstract upsert(connection: AgentConnectionData | AgentConnectionData[]): Promise; + abstract replace(connections: Record, userId: UserId): Promise; + abstract delete(id: string | string[]): Promise; +} diff --git a/libs/common/src/tools/agent-connection/services/agent-connection.service.spec.ts b/libs/common/src/tools/agent-connection/services/agent-connection.service.spec.ts new file mode 100644 index 000000000000..70161f4e6973 --- /dev/null +++ b/libs/common/src/tools/agent-connection/services/agent-connection.service.spec.ts @@ -0,0 +1,128 @@ +import { mock } from "jest-mock-extended"; +import { of } from "rxjs"; + +// eslint-disable-next-line no-restricted-imports +import { KeyService } from "@bitwarden/key-management"; +// eslint-disable-next-line no-restricted-imports +import { EncryptService, EncString, SymmetricCryptoKey } from "@bitwarden/legacy-crypto"; + +import { I18nService } from "../../../platform/abstractions/i18n.service"; +import { UserId } from "../../../types/guid"; +import { UserKey } from "../../../types/key"; +import { AgentConnectionData } from "../models/data/agent-connection.data"; + +import { AgentConnectionStateProvider } from "./agent-connection-state.provider.abstraction"; +import { AgentConnectionService } from "./agent-connection.service"; + +describe("AgentConnectionService", () => { + const userId = "user-1" as UserId; + let keyService: ReturnType>; + let encryptService: ReturnType>; + let i18nService: ReturnType>; + let stateProvider: ReturnType>; + let sut: AgentConnectionService; + + const userKey = new SymmetricCryptoKey(new Uint8Array(64)) as UserKey; + const newUserKey = new SymmetricCryptoKey(new Uint8Array(64).fill(1)) as UserKey; + + function data(id: string): AgentConnectionData { + const d = new AgentConnectionData(); + d.id = id; + d.partnerClientId = "partner.acme"; + d.name = "Acme Bot"; + d.key = "2.enc|data|mac"; + d.creationDate = "2024-01-01T00:00:00.000Z"; + d.revisionDate = "2024-01-01T00:00:00.000Z"; + d.revokedDate = null; + return d; + } + + beforeEach(() => { + keyService = mock(); + encryptService = mock(); + i18nService = mock(); + stateProvider = mock(); + stateProvider.encryptedState$ = of([userId, {}]); + + sut = new AgentConnectionService(keyService, encryptService, i18nService, stateProvider); + }); + + describe("encrypt", () => { + it("wraps the plaintext PSK under the user key", async () => { + keyService.userKey$.mockReturnValue(of(userKey)); + const encrypted = new EncString("2.wrapped|psk|mac"); + encryptService.encryptString.mockResolvedValue(encrypted); + + const connection = await sut.encrypt("partner.acme", "Acme Bot", "plaintext-psk", userId); + + expect(encryptService.encryptString).toHaveBeenCalledWith("plaintext-psk", userKey); + expect(connection.partnerClientId).toBe("partner.acme"); + expect(connection.name).toBe("Acme Bot"); + expect(connection.key).toBe(encrypted); + }); + + it("throws when there is no user key", async () => { + keyService.userKey$.mockReturnValue(of(null as unknown as UserKey)); + + await expect(sut.encrypt("partner.acme", "Acme Bot", "psk", userId)).rejects.toThrow(); + }); + }); + + describe("replace/upsert/delete", () => { + it("replace writes the record to state", async () => { + const record = { a: data("a") }; + + await sut.replace(record, userId); + + expect(stateProvider.setEncryptedAgentConnections).toHaveBeenCalledWith(record, userId); + }); + + it("upsert merges into existing state", async () => { + stateProvider.getEncryptedAgentConnections.mockResolvedValue([userId, { a: data("a") }]); + + await sut.upsert(data("b")); + + expect(stateProvider.setEncryptedAgentConnections).toHaveBeenCalledWith( + expect.objectContaining({ a: expect.anything(), b: expect.anything() }), + userId, + ); + }); + + it("delete removes the id from state", async () => { + stateProvider.getEncryptedAgentConnections.mockResolvedValue([ + userId, + { a: data("a"), b: data("b") }, + ]); + + await sut.delete("a"); + + const [written] = stateProvider.setEncryptedAgentConnections.mock.calls[0]; + expect(written).not.toHaveProperty("a"); + expect(written).toHaveProperty("b"); + }); + }); + + describe("getRotatedData", () => { + it("re-wraps each connection's PSK under the new user key", async () => { + stateProvider.encryptedState$ = of([userId, { a: data("a") }]); + sut = new AgentConnectionService(keyService, encryptService, i18nService, stateProvider); + + encryptService.decryptString.mockResolvedValue("plaintext-psk"); + encryptService.encryptString.mockResolvedValue(new EncString("2.rewrapped|psk|mac")); + + const rotated = await sut.getRotatedData(userKey, newUserKey, userId); + + expect(encryptService.decryptString).toHaveBeenCalledWith(expect.anything(), userKey); + expect(encryptService.encryptString).toHaveBeenCalledWith("plaintext-psk", newUserKey); + expect(rotated).toHaveLength(1); + expect(rotated[0].id).toBe("a"); + expect(rotated[0].key).toBe("2.rewrapped|psk|mac"); + }); + + it("throws when the new user key is missing", async () => { + await expect( + sut.getRotatedData(userKey, null as unknown as UserKey, userId), + ).rejects.toThrow(); + }); + }); +}); diff --git a/libs/common/src/tools/agent-connection/services/agent-connection.service.ts b/libs/common/src/tools/agent-connection/services/agent-connection.service.ts new file mode 100644 index 000000000000..5b8aac2f6dc2 --- /dev/null +++ b/libs/common/src/tools/agent-connection/services/agent-connection.service.ts @@ -0,0 +1,134 @@ +// FIXME: Update this file to be type safe and remove this and next line +// @ts-strict-ignore +import { Observable, concatMap, firstValueFrom, map } from "rxjs"; + +// This import may be involved in a circular dependency loop. +// eslint-disable-next-line no-restricted-imports +import { KeyService } from "@bitwarden/key-management"; +// eslint-disable-next-line no-restricted-imports +import { EncryptService } from "@bitwarden/legacy-crypto"; + +import { I18nService } from "../../../platform/abstractions/i18n.service"; +import { Utils } from "../../../platform/misc/utils"; +import { UserId } from "../../../types/guid"; +import { UserKey } from "../../../types/key"; +import { AgentConnectionData } from "../models/data/agent-connection.data"; +import { AgentConnection } from "../models/domain/agent-connection"; +import { AgentConnectionWithIdRequest } from "../models/request/agent-connection-with-id.request"; +import { AgentConnectionView } from "../models/view/agent-connection.view"; + +import { AgentConnectionStateProvider } from "./agent-connection-state.provider.abstraction"; +import { InternalAgentConnectionService as InternalAgentConnectionServiceAbstraction } from "./agent-connection.service.abstraction"; + +export class AgentConnectionService implements InternalAgentConnectionServiceAbstraction { + agentConnections$: Observable = this.stateProvider.encryptedState$.pipe( + map(([, record]) => Object.values(record ?? {}).map((data) => new AgentConnection(data))), + ); + + agentConnectionViews$: Observable = + this.stateProvider.encryptedState$.pipe( + concatMap(([userId, record]) => + this.decryptConnections( + Object.values(record ?? {}).map((data) => new AgentConnection(data)), + userId, + ), + ), + ); + + constructor( + private keyService: KeyService, + private encryptService: EncryptService, + private i18nService: I18nService, + private stateProvider: AgentConnectionStateProvider, + ) {} + + async encrypt( + partnerClientId: string, + name: string, + plaintextPsk: string, + userId: UserId, + ): Promise { + if (!userId) { + throw new Error("User ID is required to encrypt an agent connection."); + } + + const userKey = await firstValueFrom(this.keyService.userKey$(userId)); + if (userKey == null) { + throw new Error("No user key found."); + } + + const connection = new AgentConnection(); + connection.partnerClientId = partnerClientId; + connection.name = name; + connection.key = await this.encryptService.encryptString(plaintextPsk, userKey); + return connection; + } + + async upsert(connection: AgentConnectionData | AgentConnectionData[]): Promise { + const [userId, current] = await this.stateProvider.getEncryptedAgentConnections(); + const connections = current ?? {}; + if (Array.isArray(connection)) { + connection.forEach((c) => (connections[c.id] = c)); + } else { + connections[connection.id] = connection; + } + await this.replace(connections, userId); + } + + async delete(id: string | string[]): Promise { + const [userId, connections] = await this.stateProvider.getEncryptedAgentConnections(); + if (connections == null) { + return; + } + + const ids = Array.isArray(id) ? id : [id]; + ids.forEach((i) => delete connections[i]); + await this.replace(connections, userId); + } + + async replace(connections: Record, userId: UserId): Promise { + await this.stateProvider.setEncryptedAgentConnections(connections, userId); + } + + async getRotatedData( + originalUserKey: UserKey, + newUserKey: UserKey, + userId: UserId, + ): Promise { + if (originalUserKey == null) { + throw new Error("Original user key is required for rotation."); + } + if (newUserKey == null) { + throw new Error("New user key is required for rotation."); + } + + const connections = await firstValueFrom(this.agentConnections$); + return await Promise.all( + connections.map(async (connection) => { + const psk = await this.encryptService.decryptString(connection.key, originalUserKey); + const rotated = new AgentConnection(connection.toAgentConnectionData()); + rotated.key = await this.encryptService.encryptString(psk, newUserKey); + return new AgentConnectionWithIdRequest(rotated); + }), + ); + } + + private async decryptConnections( + connections: AgentConnection[], + userId: UserId, + ): Promise { + if (!userId || connections.length === 0) { + return []; + } + + const userKey = await firstValueFrom(this.keyService.userKey$(userId)); + if (userKey == null) { + return []; + } + + const views = await Promise.all( + connections.map((connection) => connection.decrypt(userKey, this.encryptService)), + ); + return views.sort(Utils.getSortFunction(this.i18nService, "name")); + } +} diff --git a/libs/common/src/tools/agent-connection/services/default-agent-access-psk-generator.ts b/libs/common/src/tools/agent-connection/services/default-agent-access-psk-generator.ts new file mode 100644 index 000000000000..06dabcbdcd34 --- /dev/null +++ b/libs/common/src/tools/agent-connection/services/default-agent-access-psk-generator.ts @@ -0,0 +1,27 @@ +// eslint-disable-next-line no-restricted-imports +import { KeyGenerationService } from "@bitwarden/legacy-crypto"; + +import { Utils } from "../../../platform/misc/utils"; +import { AgentAccessPskGenerator } from "../abstractions/agent-access-psk-generator.abstraction"; + +/** + * Temporary stub PSK generator. It produces a random 256-bit CSPRNG value (base64) using the + * existing {@link KeyGenerationService} — it does NOT add new encryption logic. The real + * agent-access library will replace this implementation; until then it lets the OAuth broker flow + * run end-to-end. + */ +export class DefaultAgentAccessPskGenerator implements AgentAccessPskGenerator { + private readonly pskPurpose = "agent-access-psk"; + private readonly pskSalt = "bitwarden-agent-access"; + + constructor(private keyGenerationService: KeyGenerationService) {} + + async generate(): Promise { + const key = await this.keyGenerationService.createKeyWithPurpose( + 256, + this.pskPurpose, + this.pskSalt, + ); + return Utils.fromBufferToB64(key.material); + } +} diff --git a/libs/common/src/tools/agent-connection/services/key-definitions.ts b/libs/common/src/tools/agent-connection/services/key-definitions.ts new file mode 100644 index 000000000000..f0ceded53c97 --- /dev/null +++ b/libs/common/src/tools/agent-connection/services/key-definitions.ts @@ -0,0 +1,12 @@ +import { AGENT_CONNECTION_DISK, UserKeyDefinition } from "../../../platform/state"; +import { AgentConnectionData } from "../models/data/agent-connection.data"; + +/** Encrypted agent-connection state (keyed by connection id) stored on disk. */ +export const AGENT_CONNECTION_USER_ENCRYPTED = UserKeyDefinition.record( + AGENT_CONNECTION_DISK, + "agentConnectionUserEncrypted", + { + deserializer: (obj: AgentConnectionData) => obj, + clearOn: ["logout"], + }, +); diff --git a/libs/state/src/core/state-definitions.ts b/libs/state/src/core/state-definitions.ts index f6775c9e7048..6b0073de0811 100644 --- a/libs/state/src/core/state-definitions.ts +++ b/libs/state/src/core/state-definitions.ts @@ -201,6 +201,9 @@ export const SEND_MEMORY = new StateDefinition("decryptedSend", "memory", { browser: "memory-large-object", }); export const SEND_ACCESS_AUTH_MEMORY = new StateDefinition("sendAccessAuth", "memory"); +export const AGENT_CONNECTION_DISK = new StateDefinition("encryptedAgentConnection", "disk", { + web: "memory", +}); // Vault diff --git a/package-lock.json b/package-lock.json index a90dfde368a7..2107657f7385 100644 --- a/package-lock.json +++ b/package-lock.json @@ -2366,6 +2366,40 @@ "url": "https://github.com/sponsors/epoberezkin" } }, + "node_modules/@angular-eslint/builder/node_modules/chokidar": { + "version": "4.0.3", + "resolved": "https://registry.npmjs.org/chokidar/-/chokidar-4.0.3.tgz", + "integrity": "sha512-Qgzu8kfBvo+cA4962jnP1KkS6Dop5NS6g7R5LFYJr4b8Ub94PPQXUksCw9PvXoeXPRRddRNC5C1JQUR2SMGtnA==", + "dev": true, + "license": "MIT", + "optional": true, + "peer": true, + "dependencies": { + "readdirp": "^4.0.1" + }, + "engines": { + "node": ">= 14.16.0" + }, + "funding": { + "url": "https://paulmillr.com/funding/" + } + }, + "node_modules/@angular-eslint/builder/node_modules/readdirp": { + "version": "4.1.2", + "resolved": "https://registry.npmjs.org/readdirp/-/readdirp-4.1.2.tgz", + "integrity": "sha512-GDhwkLfywWL2s6vEjyhri+eXmfH6j1L7JE27WhqLeYzoh/A3DBaYGEj2H/HFZCn/kMfim73FXxEJTw06WtxQwg==", + "dev": true, + "license": "MIT", + "optional": true, + "peer": true, + "engines": { + "node": ">= 14.18.0" + }, + "funding": { + "type": "individual", + "url": "https://paulmillr.com/funding/" + } + }, "node_modules/@angular-eslint/builder/node_modules/rxjs": { "version": "7.8.2", "resolved": "https://registry.npmjs.org/rxjs/-/rxjs-7.8.2.tgz", @@ -10436,6 +10470,21 @@ "@msgpack/msgpack": "^2.7.0" } }, + "node_modules/@microsoft/signalr/node_modules/utf-8-validate": { + "version": "5.0.10", + "resolved": "https://registry.npmjs.org/utf-8-validate/-/utf-8-validate-5.0.10.tgz", + "integrity": "sha512-Z6czzLq4u8fPOyx7TU6X3dvUZVvoJmxSQ+IcrlmagKhilxlhZgxPK6C5Jqbkw1IDUmFTM+cz9QDnnLTwDz/2gQ==", + "hasInstallScript": true, + "license": "MIT", + "optional": true, + "peer": true, + "dependencies": { + "node-gyp-build": "^4.3.0" + }, + "engines": { + "node": ">=6.14.2" + } + }, "node_modules/@microsoft/signalr/node_modules/ws": { "version": "7.5.13", "resolved": "https://registry.npmjs.org/ws/-/ws-7.5.13.tgz", @@ -14057,7 +14106,7 @@ "version": "2.6.0", "resolved": "https://registry.npmjs.org/@parcel/watcher/-/watcher-2.6.0.tgz", "integrity": "sha512-7FNeNl8NCE7aINx7WXiKQrPYZWC/hvrTsmk6zmxbI7LTXE7hVek/n8AfVgpe2y82zl3w0HvCHN0bVKMBoJcC0w==", - "devOptional": true, + "dev": true, "hasInstallScript": true, "license": "MIT", "dependencies": { @@ -14095,6 +14144,7 @@ "cpu": [ "arm64" ], + "dev": true, "license": "MIT", "optional": true, "os": [ @@ -14115,6 +14165,7 @@ "cpu": [ "arm64" ], + "dev": true, "license": "MIT", "optional": true, "os": [ @@ -14135,6 +14186,7 @@ "cpu": [ "x64" ], + "dev": true, "license": "MIT", "optional": true, "os": [ @@ -14155,6 +14207,7 @@ "cpu": [ "x64" ], + "dev": true, "license": "MIT", "optional": true, "os": [ @@ -14175,6 +14228,7 @@ "cpu": [ "arm" ], + "dev": true, "license": "MIT", "optional": true, "os": [ @@ -14195,6 +14249,7 @@ "cpu": [ "arm" ], + "dev": true, "license": "MIT", "optional": true, "os": [ @@ -14215,6 +14270,7 @@ "cpu": [ "arm64" ], + "dev": true, "license": "MIT", "optional": true, "os": [ @@ -14235,6 +14291,7 @@ "cpu": [ "arm64" ], + "dev": true, "license": "MIT", "optional": true, "os": [ @@ -14255,6 +14312,7 @@ "cpu": [ "x64" ], + "dev": true, "license": "MIT", "optional": true, "os": [ @@ -14275,6 +14333,7 @@ "cpu": [ "x64" ], + "dev": true, "license": "MIT", "optional": true, "os": [ @@ -14295,6 +14354,7 @@ "cpu": [ "arm64" ], + "dev": true, "license": "MIT", "optional": true, "os": [ @@ -14315,6 +14375,7 @@ "cpu": [ "x64" ], + "dev": true, "license": "MIT", "optional": true, "os": [ @@ -14332,7 +14393,7 @@ "version": "7.1.1", "resolved": "https://registry.npmjs.org/node-addon-api/-/node-addon-api-7.1.1.tgz", "integrity": "sha512-5m3bsyrjFWE1xf7nz7YXdN4udnVtXK6/Yfgn5qnahL6bCkf2yKt4k3nuTKAtT4r3IG8JNR2ncsIMdZuAzJjHQQ==", - "devOptional": true, + "dev": true, "license": "MIT" }, "node_modules/@paypal/accelerated-checkout-loader": { @@ -19127,6 +19188,24 @@ "url": "https://github.com/chalk/chalk?sponsor=1" } }, + "node_modules/angular-eslint/node_modules/chokidar": { + "version": "4.0.3", + "resolved": "https://registry.npmjs.org/chokidar/-/chokidar-4.0.3.tgz", + "integrity": "sha512-Qgzu8kfBvo+cA4962jnP1KkS6Dop5NS6g7R5LFYJr4b8Ub94PPQXUksCw9PvXoeXPRRddRNC5C1JQUR2SMGtnA==", + "dev": true, + "license": "MIT", + "optional": true, + "peer": true, + "dependencies": { + "readdirp": "^4.0.1" + }, + "engines": { + "node": ">= 14.16.0" + }, + "funding": { + "url": "https://paulmillr.com/funding/" + } + }, "node_modules/angular-eslint/node_modules/cli-cursor": { "version": "5.0.0", "resolved": "https://registry.npmjs.org/cli-cursor/-/cli-cursor-5.0.0.tgz", @@ -19269,6 +19348,22 @@ "url": "https://github.com/sponsors/sindresorhus" } }, + "node_modules/angular-eslint/node_modules/readdirp": { + "version": "4.1.2", + "resolved": "https://registry.npmjs.org/readdirp/-/readdirp-4.1.2.tgz", + "integrity": "sha512-GDhwkLfywWL2s6vEjyhri+eXmfH6j1L7JE27WhqLeYzoh/A3DBaYGEj2H/HFZCn/kMfim73FXxEJTw06WtxQwg==", + "dev": true, + "license": "MIT", + "optional": true, + "peer": true, + "engines": { + "node": ">= 14.18.0" + }, + "funding": { + "type": "individual", + "url": "https://paulmillr.com/funding/" + } + }, "node_modules/angular-eslint/node_modules/restore-cursor": { "version": "5.1.0", "resolved": "https://registry.npmjs.org/restore-cursor/-/restore-cursor-5.1.0.tgz", @@ -21702,7 +21797,7 @@ "version": "5.0.0", "resolved": "https://registry.npmjs.org/chokidar/-/chokidar-5.0.0.tgz", "integrity": "sha512-TQMmc3w+5AxjpL8iIiwebF73dRDF4fBIieAqGn9RGCWaEVwQ6Fb2cGe31Yns0RRIzii5goJ1Y7xbMwo1TxMplw==", - "devOptional": true, + "dev": true, "license": "MIT", "dependencies": { "readdirp": "^5.0.0" @@ -23489,7 +23584,7 @@ "version": "2.1.2", "resolved": "https://registry.npmjs.org/detect-libc/-/detect-libc-2.1.2.tgz", "integrity": "sha512-Btj2BOOO83o3WyH59e8MgXsxEQVcarkUOpEYrubB0urwnN10yQ364rsiByU11nZlqWYZm05i/of7io4mzihBtQ==", - "devOptional": true, + "dev": true, "license": "Apache-2.0", "engines": { "node": ">=8" @@ -28765,7 +28860,7 @@ "version": "2.1.1", "resolved": "https://registry.npmjs.org/is-extglob/-/is-extglob-2.1.1.tgz", "integrity": "sha512-SbKbANkN603Vi4jEZv49LeVJMn4yGwsbzZworEoyEiutsN3nJYdbO36zfhGJ6QEDpOZIFkDtnq5JRxmvl3jsoQ==", - "devOptional": true, + "dev": true, "license": "MIT", "engines": { "node": ">=0.10.0" @@ -28830,7 +28925,7 @@ "version": "4.0.3", "resolved": "https://registry.npmjs.org/is-glob/-/is-glob-4.0.3.tgz", "integrity": "sha512-xelSayHH36ZgE7ZWhli7pW34hNbNl8Ojv5KVmkJD4hBdD3th8Tfk9vYasLM+mXWOZhFkgZfxhLSnrwRr4elSSg==", - "devOptional": true, + "dev": true, "license": "MIT", "dependencies": { "is-extglob": "^2.1.1" @@ -40923,7 +41018,7 @@ "version": "5.1.1", "resolved": "https://registry.npmjs.org/readdirp/-/readdirp-5.1.1.tgz", "integrity": "sha512-Kko+Y5XQ6fM+Ce3dq3m9YGxnacYZYl9cA1wZjaF3Vbry2L3i1qVg8+CAgNPsXRArPMUMCaOR7oa9Nqntc43JKA==", - "devOptional": true, + "dev": true, "license": "MIT", "engines": { "node": ">= 20.19.0" @@ -41994,6 +42089,7 @@ "!riscv64", "!x64" ], + "dev": true, "license": "MIT", "optional": true, "dependencies": { @@ -42004,6 +42100,7 @@ "version": "1.105.1", "resolved": "https://registry.npmjs.org/sass/-/sass-1.105.1.tgz", "integrity": "sha512-1CnAWPyrrnVQzXGB/DUep1vYCKCm1CIBr+YxjjiW6wk9qtzemnGP4qicH56T2F9S4Hjtv/Ne3jDz8JqfdDU4oA==", + "dev": true, "license": "MIT", "optional": true, "dependencies": { @@ -42028,6 +42125,7 @@ "cpu": [ "arm" ], + "dev": true, "license": "MIT", "optional": true, "os": [ @@ -42044,6 +42142,7 @@ "cpu": [ "arm64" ], + "dev": true, "license": "MIT", "optional": true, "os": [ @@ -42060,6 +42159,7 @@ "cpu": [ "riscv64" ], + "dev": true, "license": "MIT", "optional": true, "os": [ @@ -42076,6 +42176,7 @@ "cpu": [ "x64" ], + "dev": true, "license": "MIT", "optional": true, "os": [ @@ -42092,6 +42193,7 @@ "cpu": [ "arm64" ], + "dev": true, "license": "MIT", "optional": true, "os": [ @@ -42108,6 +42210,7 @@ "cpu": [ "x64" ], + "dev": true, "license": "MIT", "optional": true, "os": [ @@ -42124,6 +42227,7 @@ "cpu": [ "arm" ], + "dev": true, "license": "MIT", "optional": true, "os": [ @@ -42140,6 +42244,7 @@ "cpu": [ "arm64" ], + "dev": true, "license": "MIT", "optional": true, "os": [ @@ -42156,6 +42261,7 @@ "cpu": [ "arm" ], + "dev": true, "license": "MIT", "optional": true, "os": [ @@ -42172,6 +42278,7 @@ "cpu": [ "arm64" ], + "dev": true, "license": "MIT", "optional": true, "os": [ @@ -42188,6 +42295,7 @@ "cpu": [ "riscv64" ], + "dev": true, "license": "MIT", "optional": true, "os": [ @@ -42204,6 +42312,7 @@ "cpu": [ "x64" ], + "dev": true, "license": "MIT", "optional": true, "os": [ @@ -42220,6 +42329,7 @@ "cpu": [ "riscv64" ], + "dev": true, "license": "MIT", "optional": true, "os": [ @@ -42236,6 +42346,7 @@ "cpu": [ "x64" ], + "dev": true, "license": "MIT", "optional": true, "os": [ @@ -42249,6 +42360,7 @@ "version": "1.105.1", "resolved": "https://registry.npmjs.org/sass-embedded-unknown-all/-/sass-embedded-unknown-all-1.105.1.tgz", "integrity": "sha512-bd2zDf+MdoPdRDH1awSQ+IL67vHvCbiKsWJ95XchPg3I67zQlXjTSf9KqRiE6twjNT1fRV82JUKoc0Hf6CUmfQ==", + "dev": true, "license": "MIT", "optional": true, "os": [ @@ -42265,6 +42377,7 @@ "version": "1.105.1", "resolved": "https://registry.npmjs.org/sass/-/sass-1.105.1.tgz", "integrity": "sha512-1CnAWPyrrnVQzXGB/DUep1vYCKCm1CIBr+YxjjiW6wk9qtzemnGP4qicH56T2F9S4Hjtv/Ne3jDz8JqfdDU4oA==", + "dev": true, "license": "MIT", "optional": true, "dependencies": { @@ -42289,6 +42402,7 @@ "cpu": [ "arm64" ], + "dev": true, "license": "MIT", "optional": true, "os": [ @@ -42305,6 +42419,7 @@ "cpu": [ "x64" ], + "dev": true, "license": "MIT", "optional": true, "os": [