diff --git a/.github/CODEOWNERS b/.github/CODEOWNERS index 99cfbc5a3a1..09a0a6f2fd9 100644 --- a/.github/CODEOWNERS +++ b/.github/CODEOWNERS @@ -103,6 +103,7 @@ libs/common/src/provider @bitwarden/team-provider-business-unit-portals-dev ## Secrets Manager team files ## bitwarden_license/bit-web/src/app/secrets-manager @bitwarden/team-secrets-manager-dev +bitwarden_license/bit-sm @bitwarden/team-secrets-manager-dev ## Platform team files ## apps/browser/src/platform @bitwarden/team-platform-dev diff --git a/apps/cli/package.json b/apps/cli/package.json index 9dae37624e3..db906e7c2fd 100644 --- a/apps/cli/package.json +++ b/apps/cli/package.json @@ -70,7 +70,7 @@ "browser-hrtime": "1.1.8", "chalk": "4.1.2", "commander": "14.0.0", - "core-js": "3.50.0", + "core-js": "3.51.0", "form-data": "4.0.6", "https-proxy-agent": "9.1.0", "inquirer": "8.2.6", diff --git a/apps/desktop/src/app/services/services.module.ts b/apps/desktop/src/app/services/services.module.ts index 924b288bfbc..f1c79cae3ce 100644 --- a/apps/desktop/src/app/services/services.module.ts +++ b/apps/desktop/src/app/services/services.module.ts @@ -532,6 +532,7 @@ const safeProviders: SafeProvider[] = [ DesktopFido2UserVerificationService, PasswordRepromptService, DomainSettingsService, + MessageListener, ], }), safeProvider({ diff --git a/apps/desktop/src/autofill/services/desktop-fido2-user-interface.service.spec.ts b/apps/desktop/src/autofill/services/desktop-fido2-user-interface.service.spec.ts index 7183d60ffaf..da81ffe5bca 100644 --- a/apps/desktop/src/autofill/services/desktop-fido2-user-interface.service.spec.ts +++ b/apps/desktop/src/autofill/services/desktop-fido2-user-interface.service.spec.ts @@ -1,6 +1,6 @@ import { Router } from "@angular/router"; import { mock, MockProxy } from "jest-mock-extended"; -import { BehaviorSubject, of } from "rxjs"; +import { BehaviorSubject, of, Subject } from "rxjs"; import { AccountService } from "@bitwarden/common/auth/abstractions/account.service"; import { AuthService } from "@bitwarden/common/auth/abstractions/auth.service"; @@ -8,6 +8,7 @@ import { AuthenticationStatus } from "@bitwarden/common/auth/enums/authenticatio import { DomainSettingsService } from "@bitwarden/common/autofill/services/domain-settings.service"; import { Fido2AuthenticatorErrorCode } from "@bitwarden/common/platform/abstractions/fido2/fido2-authenticator.service.abstraction"; import { LogService } from "@bitwarden/common/platform/abstractions/log.service"; +import { MessageListener } from "@bitwarden/common/platform/messaging"; import { Fido2Utils } from "@bitwarden/common/platform/services/fido2/fido2-utils"; import { CipherService } from "@bitwarden/common/vault/abstractions/cipher.service"; import { CipherRepromptType, CipherType } from "@bitwarden/common/vault/enums"; @@ -75,6 +76,7 @@ describe("DesktopFido2UserInterfaceSession", () => { let userVerificationService: MockProxy; let passwordRepromptService: MockProxy; let domainSettingsService: MockProxy; + let messages$: Subject<{ command: string }>; let activeAccountStatus$: BehaviorSubject; let abortController: AbortController; @@ -109,6 +111,8 @@ describe("DesktopFido2UserInterfaceSession", () => { domainSettingsService = mock(); domainSettingsService.getUrlEquivalentDomains.mockReturnValue(of(new Set())); + messages$ = new Subject(); + activeAccountStatus$ = new BehaviorSubject(AuthenticationStatus.Unlocked); authService.activeAccountStatus$ = activeAccountStatus$; accountService.activeAccount$ = new BehaviorSubject({ id: "user-1" } as any); @@ -171,6 +175,7 @@ describe("DesktopFido2UserInterfaceSession", () => { userVerificationService, passwordRepromptService, domainSettingsService, + new MessageListener(messages$), ); }); @@ -537,6 +542,40 @@ describe("DesktopFido2UserInterfaceSession", () => { }); }); + describe("closing the window", () => { + const closeWindow = () => messages$.next({ command: "modalWindowClosed" }); + + it("cancels a ceremony waiting on the lock screen", async () => { + activeAccountStatus$.next(AuthenticationStatus.Locked); + + const result = session.ensureUnlockedVault(); + await tick(); + closeWindow(); + + await expect(result).rejects.toThrow("Could not retrieve vault unlock status"); + expect(desktopSettingsService.setModalMode).toHaveBeenCalledWith(false); + }); + + it("does not cancel a ceremony that is not showing UI", async () => { + closeWindow(); + + expect(abortController.signal.aborted).toBe(false); + }); + + it("does not cancel once the ceremony has hidden its UI", async () => { + activeAccountStatus$.next(AuthenticationStatus.Locked); + const result = session.ensureUnlockedVault(); + await tick(); + activeAccountStatus$.next(AuthenticationStatus.Unlocked); + await result; + await session.hideUi(); + + closeWindow(); + + expect(abortController.signal.aborted).toBe(false); + }); + }); + describe("informExcludedCredential", () => { it("shows the excluded credentials UI and waits for the user to dismiss it", async () => { const result = session.informExcludedCredential(["cipher-1"]); diff --git a/apps/desktop/src/autofill/services/desktop-fido2-user-interface.service.ts b/apps/desktop/src/autofill/services/desktop-fido2-user-interface.service.ts index 92c5e0f38cf..ede2a0e7ee7 100644 --- a/apps/desktop/src/autofill/services/desktop-fido2-user-interface.service.ts +++ b/apps/desktop/src/autofill/services/desktop-fido2-user-interface.service.ts @@ -11,6 +11,7 @@ import { switchMap, throwError, MonoTypeOperatorFunction, + Subscription, } from "rxjs"; import { AccountService } from "@bitwarden/common/auth/abstractions/account.service"; @@ -29,6 +30,7 @@ import { } from "@bitwarden/common/platform/abstractions/fido2/fido2-user-interface.service.abstraction"; import { LogService } from "@bitwarden/common/platform/abstractions/log.service"; import { MessagingService } from "@bitwarden/common/platform/abstractions/messaging.service"; +import { CommandDefinition, MessageListener } from "@bitwarden/common/platform/messaging"; import { Fido2Utils } from "@bitwarden/common/platform/services/fido2/fido2-utils"; import { CipherService } from "@bitwarden/common/vault/abstractions/cipher.service"; import { CipherRepromptType, CipherType, SecureNoteType } from "@bitwarden/common/vault/enums"; @@ -91,6 +93,12 @@ export type NativeWindowObject = { userHandle?: number[]; }; +/** + * Sent by the main process when the user closes the app window while it is in + * modal mode, i.e. while a ceremony is showing its UI in it. + */ +const MODAL_WINDOW_CLOSED = new CommandDefinition("modalWindowClosed"); + /** A ceremony that can be refused because of its RP ID. */ export type RpIdNotAllowedOperation = "registration" | "assertion"; @@ -152,6 +160,7 @@ export class DesktopFido2UserInterfaceService implements Fido2UserInterfaceServi private userVerificationService: DesktopFido2UserVerificationService, private passwordRepromptService: PasswordRepromptService, private domainSettingsService: DomainSettingsService, + private messageListener: MessageListener, ) {} private currentSession: any; @@ -184,6 +193,7 @@ export class DesktopFido2UserInterfaceService implements Fido2UserInterfaceServi this.userVerificationService, this.passwordRepromptService, this.domainSettingsService, + this.messageListener, ); this.currentSession = session; @@ -204,6 +214,7 @@ export class DesktopFido2UserInterfaceSession implements Fido2UserInterfaceSessi private userVerificationService: DesktopFido2UserVerificationService, private passwordRepromptService: PasswordRepromptService, private domainSettingsService: DomainSettingsService, + private messageListener: MessageListener, ) {} private confirmCredentialSubject = new Subject(); @@ -235,6 +246,11 @@ export class DesktopFido2UserInterfaceSession implements Fido2UserInterfaceSessi */ private uiShown = false; + /** + * Cancels the ceremony if the user closes the window while it shows our UI. + */ + private windowClosedSubscription: Subscription | undefined; + // Method implementation async pickCredential( params: PickCredentialParams, @@ -610,6 +626,9 @@ export class DesktopFido2UserInterfaceSession implements Fido2UserInterfaceSessi * own `finally`. Safe to call more than once. */ async hideUi(): Promise { + this.windowClosedSubscription?.unsubscribe(); + this.windowClosedSubscription = undefined; + // Always clear modal mode so the app can never get stuck in it. The main // process only restyles the window on the modal -> standard transition, so // this is inert when the ceremony never entered modal mode. @@ -633,6 +652,17 @@ export class DesktopFido2UserInterfaceSession implements Fido2UserInterfaceSessi showTrafficButtons: boolean = false, disableRedirect?: boolean, ): Promise { + this.windowClosedSubscription ??= this.messageListener + .messages$(MODAL_WINDOW_CLOSED) + .pipe(take(1)) + .subscribe(() => { + this.logService.info( + "[DesktopFido2UserInterfaceSession]", + "Window closed while showing UI. Aborting the request.", + ); + this.abortController.abort("Operation cancelled"); + }); + // Load the UI: await this.desktopSettingsService.setModalMode(true, showTrafficButtons, position); await this.accountService.setShowHeader(showTrafficButtons); diff --git a/apps/desktop/src/main/window.main.spec.ts b/apps/desktop/src/main/window.main.spec.ts index 47ffd9ae4e7..98963176f47 100644 --- a/apps/desktop/src/main/window.main.spec.ts +++ b/apps/desktop/src/main/window.main.spec.ts @@ -5,13 +5,14 @@ import * as path from "path"; import { app, BrowserWindow, ipcMain, session } from "electron"; import { mock, MockProxy } from "jest-mock-extended"; -import { NEVER, of } from "rxjs"; +import { BehaviorSubject, NEVER, of } from "rxjs"; import { LogService } from "@bitwarden/common/platform/abstractions/log.service"; import { AbstractStorageService } from "@bitwarden/common/platform/abstractions/storage.service"; import { BiometricStateService } from "@bitwarden/key-management"; import { SafeShell } from "../platform/main/safe-shell.main"; +import { ModalModeState } from "../platform/models/domain/window-state"; import { DesktopSettingsService } from "../platform/services/desktop-settings.service"; // window.main.ts registers a privileged scheme at module load time, which @@ -272,6 +273,7 @@ describe("WindowMain", () => { describe("createWindow", () => { let sut: WindowMain; + let modalMode$: BehaviorSubject; const fakeWindow = () => Object.assign(new EventEmitter(), { @@ -294,9 +296,11 @@ describe("WindowMain", () => { (global as any).BIT_ENVIRONMENT = "production"; const desktopSettingsService = mock(); + modalMode$ = new BehaviorSubject({ isModalModeActive: false }); Object.assign(desktopSettingsService, { alwaysOnTop$: of(false), preventScreenshots$: of(false), + modalMode$, }); sut = new WindowMain( @@ -349,6 +353,33 @@ describe("WindowMain", () => { }); }); + it("tells the renderer when the user closes the window in modal mode", async () => { + const win = fakeWindow(); + jest.mocked(BrowserWindow).mockImplementationOnce(() => win as any); + await sut.createWindow(); + modalMode$.next({ isModalModeActive: true }); + + win.emit("close"); + await new Promise(process.nextTick); + + expect(win.webContents.send).toHaveBeenCalledWith("messagingService", { + command: "modalWindowClosed", + }); + }); + + it("does not tell the renderer when the user closes the window outside modal mode", async () => { + const win = fakeWindow(); + jest.mocked(BrowserWindow).mockImplementationOnce(() => win as any); + await sut.createWindow(); + + win.emit("close"); + await new Promise(process.nextTick); + + expect(win.webContents.send).not.toHaveBeenCalledWith("messagingService", { + command: "modalWindowClosed", + }); + }); + it("clears the window reference when the current window closes", async () => { const win = fakeWindow(); jest.mocked(BrowserWindow).mockImplementationOnce(() => win as any); diff --git a/apps/desktop/src/main/window.main.ts b/apps/desktop/src/main/window.main.ts index 533ad4fb533..fb6f17a6ae8 100644 --- a/apps/desktop/src/main/window.main.ts +++ b/apps/desktop/src/main/window.main.ts @@ -567,6 +567,7 @@ export class WindowMain { win.on("close", async () => { this.isClosing = true; + await this.notifyIfModalWindowClosed(win); await this.updateWindowState(mainWindowSizeKey, win); }); @@ -677,6 +678,18 @@ export class WindowMain { return fn(this.win); } + /** + * Notifies the renderer that the user closed the window while the modal was + * active, e.g. during a passkey ceremony. + */ + private async notifyIfModalWindowClosed(win: BrowserWindow) { + const modalMode = await firstValueFrom(this.desktopSettingsService.modalMode$); + if (!modalMode?.isModalModeActive || win.isDestroyed()) { + return; + } + win.webContents.send("messagingService", { command: "modalWindowClosed" }); + } + private windowStateChangeHandler(configKey: string, win: BrowserWindow) { global.clearTimeout(this.windowStateChangeTimer); this.windowStateChangeTimer = global.setTimeout(async () => { diff --git a/bitwarden_license/bit-cli/src/bit-serve-configurator.spec.ts b/bitwarden_license/bit-cli/src/bit-serve-configurator.spec.ts new file mode 100644 index 00000000000..ed3bda85cf6 --- /dev/null +++ b/bitwarden_license/bit-cli/src/bit-serve-configurator.spec.ts @@ -0,0 +1,336 @@ +import { Router, RouterContext } from "@koa/router"; +import { mock } from "jest-mock-extended"; +import { of } from "rxjs"; + +import { Response } from "@bitwarden/cli/models/response"; +import { OrganizationService } from "@bitwarden/common/admin-console/abstractions/organization/organization.service.abstraction"; +import { AccountService } from "@bitwarden/common/auth/abstractions/account.service"; +import { FeatureFlag } from "@bitwarden/common/enums/feature-flag.enum"; +import { ConfigService } from "@bitwarden/common/platform/abstractions/config/config.service"; + +import { BitServeConfigurator } from "./bit-serve-configurator"; +import { AccessGrantCommand } from "./secrets-manager/access/access-grant.command"; +import { AccessTokenCreateCommand } from "./secrets-manager/access-tokens/access-token-create.command"; +import { SmExportCommand } from "./secrets-manager/porting/sm-export.command"; +import { SmImportCommand } from "./secrets-manager/porting/sm-import.command"; +import { ProjectGetCommand } from "./secrets-manager/projects/project-get.command"; +import { mockSmOrganization, smOrg } from "./secrets-manager/spec/sm-test-utils"; +import { TemplateCommand } from "./secrets-manager/templates/template.command"; +import { TrashRestoreCommand } from "./secrets-manager/trash/trash-restore.command"; +import { ServiceContainer } from "./service-container"; + +describe("BitServeConfigurator", () => { + const orgId = "11111111-1111-1111-1111-111111111111"; + const id = "22222222-2222-2222-2222-222222222222"; + let configurator: BitServeConfigurator; + let router: Router; + let errorIfLocked: jest.SpyInstance; + const configService = mock(); + const organizationService = mock(); + const accountService = mock(); + + const findRoute = (method: string, path: string) => { + const layer = router.stack.find((l) => l.path === path && l.methods.includes(method)); + if (layer == null) { + throw new Error(method + " " + path + " is not registered"); + } + return layer.stack[layer.stack.length - 1]; + }; + + const call = async ( + method: string, + path: string, + params: Record, + request: { body?: unknown; query?: Record } = {}, + ) => { + const ctx = { + params, + request: { body: request.body, query: request.query ?? {} }, + response: {} as { status?: number; body?: unknown }, + }; + const next = jest.fn().mockResolvedValue(undefined); + await findRoute(method, path)(ctx as unknown as RouterContext, next); + expect(next).toHaveBeenCalled(); + return ctx.response; + }; + + beforeEach(async () => { + jest.restoreAllMocks(); + configService.getFeatureFlag$.mockReturnValue(of(true)); + mockSmOrganization(accountService, organizationService); + // Assigned after `mock()` so the observable stubs are not wrapped in deep mocks. + const serviceContainer = mock({ configService }); + serviceContainer.organizationService = + organizationService as unknown as ServiceContainer["organizationService"]; + serviceContainer.accountService = accountService; + configurator = new BitServeConfigurator(serviceContainer); + router = new Router(); + (configurator as unknown as { serveSecretsManager(r: Router): void }).serveSecretsManager( + router, + ); + errorIfLocked = jest + .spyOn(configurator as unknown as { errorIfLocked(): Promise }, "errorIfLocked") + .mockResolvedValue(false); + }); + + it.each([ + ["GET", "/sm/template/:object"], + ["GET", "/sm/:organizationId/projects"], + ["POST", "/sm/:organizationId/projects"], + ["GET", "/sm/:organizationId/projects/:projectId"], + ["PUT", "/sm/:organizationId/projects/:projectId"], + ["DELETE", "/sm/:organizationId/projects/:projectId"], + ["GET", "/sm/:organizationId/secrets"], + ["POST", "/sm/:organizationId/secrets"], + ["GET", "/sm/:organizationId/secrets/:secretId"], + ["PUT", "/sm/:organizationId/secrets/:secretId"], + ["DELETE", "/sm/:organizationId/secrets/:secretId"], + ["GET", "/sm/:organizationId/secrets/:secretId/versions"], + ["POST", "/sm/:organizationId/secrets/:secretId/versions/:versionId/restore"], + ["GET", "/sm/:organizationId/trash"], + ["POST", "/sm/:organizationId/trash/restore"], + ["POST", "/sm/:organizationId/trash/empty"], + ["GET", "/sm/:organizationId/machine-accounts"], + ["POST", "/sm/:organizationId/machine-accounts"], + ["GET", "/sm/:organizationId/machine-accounts/:machineAccountId"], + ["PUT", "/sm/:organizationId/machine-accounts/:machineAccountId"], + ["DELETE", "/sm/:organizationId/machine-accounts/:machineAccountId"], + ["GET", "/sm/:organizationId/machine-accounts/:machineAccountId/events"], + ["GET", "/sm/:organizationId/machine-accounts/:machineAccountId/access-tokens"], + ["POST", "/sm/:organizationId/machine-accounts/:machineAccountId/access-tokens"], + [ + "DELETE", + "/sm/:organizationId/machine-accounts/:machineAccountId/access-tokens/:accessTokenId", + ], + ["GET", "/sm/:organizationId/access/:target/:id"], + ["PUT", "/sm/:organizationId/access/:target/:id"], + ["POST", "/sm/:organizationId/access/:target/:id/grant"], + ["POST", "/sm/:organizationId/access/:target/:id/revoke"], + ["GET", "/sm/:organizationId/grantees/:type"], + ["GET", "/sm/:organizationId/counts"], + ["POST", "/sm/:organizationId/export"], + ["POST", "/sm/:organizationId/import"], + ])("registers %s %s", (method, path) => { + expect(() => findRoute(method, path)).not.toThrow(); + }); + + it("does not run the command when the SmCli flag is off", async () => { + configService.getFeatureFlag$.mockReturnValue(of(false)); + const run = jest.fn(); + jest + .spyOn(ProjectGetCommand, "create") + .mockReturnValue({ run } as unknown as ProjectGetCommand); + + const res = await call("GET", "/sm/:organizationId/projects/:projectId", { + organizationId: orgId, + projectId: id, + }); + + expect(configService.getFeatureFlag$).toHaveBeenCalledWith(FeatureFlag.SmCli); + expect(run).not.toHaveBeenCalled(); + expect(errorIfLocked).not.toHaveBeenCalled(); + expect(res.body).toMatchObject({ + success: false, + message: "This command is temporarily unavailable.", + }); + }); + + it("does not run the command when the vault is locked", async () => { + errorIfLocked.mockResolvedValue(true); + const run = jest.fn(); + jest + .spyOn(ProjectGetCommand, "create") + .mockReturnValue({ run } as unknown as ProjectGetCommand); + + await call("GET", "/sm/:organizationId/projects/:projectId", { + organizationId: orgId, + projectId: id, + }); + + expect(run).not.toHaveBeenCalled(); + }); + + it("passes path parameters to the command and returns its response", async () => { + const run = jest.fn().mockResolvedValue(Response.error("Nope.")); + jest + .spyOn(ProjectGetCommand, "create") + .mockReturnValue({ run } as unknown as ProjectGetCommand); + + const res = await call("GET", "/sm/:organizationId/projects/:projectId", { + organizationId: orgId, + projectId: id, + }); + + expect(run).toHaveBeenCalledWith(smOrg, id); + expect(res.status).toBe(400); + expect(res.body).toMatchObject({ success: false, message: "Nope." }); + }); + + it("passes the validated organization to the command", async () => { + const run = jest.fn().mockResolvedValue(Response.success()); + jest + .spyOn(ProjectGetCommand, "create") + .mockReturnValue({ run } as unknown as ProjectGetCommand); + + await call("GET", "/sm/:organizationId/projects/:projectId", { + organizationId: orgId.toUpperCase(), + projectId: id, + }); + + expect(run).toHaveBeenCalledWith(smOrg, id); + }); + + it("rejects an invalid organization id without running the command", async () => { + const run = jest.fn(); + jest + .spyOn(ProjectGetCommand, "create") + .mockReturnValue({ run } as unknown as ProjectGetCommand); + + const res = await call("GET", "/sm/:organizationId/projects/:projectId", { + organizationId: "bad", + projectId: id, + }); + + expect(run).not.toHaveBeenCalled(); + expect(res.status).toBe(400); + expect(res.body).toMatchObject({ success: false, message: "`bad` is not a GUID." }); + }); + + it("rejects an organization without Secrets Manager access without running the command", async () => { + mockSmOrganization(accountService, organizationService, false); + const run = jest.fn(); + jest + .spyOn(ProjectGetCommand, "create") + .mockReturnValue({ run } as unknown as ProjectGetCommand); + + const res = await call("GET", "/sm/:organizationId/projects/:projectId", { + organizationId: orgId, + projectId: id, + }); + + expect(run).not.toHaveBeenCalled(); + expect(res.body).toMatchObject({ + success: false, + message: "You do not have access to Secrets Manager for this organization.", + }); + }); + + it("does not validate an organization for the template route", async () => { + organizationService.organizations$.mockClear(); + const run = jest.fn().mockResolvedValue(Response.success()); + jest.spyOn(TemplateCommand, "create").mockReturnValue({ run } as unknown as TemplateCommand); + + await call("GET", "/sm/template/:object", { object: "sm-project" }); + + expect(run).toHaveBeenCalledWith("sm-project"); + expect(organizationService.organizations$).not.toHaveBeenCalled(); + }); + + it("reads grant options from the body, ignoring non-string values", async () => { + const run = jest.fn().mockResolvedValue(Response.success()); + jest + .spyOn(AccessGrantCommand, "create") + .mockReturnValue({ run } as unknown as AccessGrantCommand); + + await call( + "POST", + "/sm/:organizationId/access/:target/:id/grant", + { organizationId: orgId, target: "project", id }, + { body: { grantee: "alice@example.com", permission: 5 } }, + ); + + expect(run).toHaveBeenCalledWith(smOrg, "project", id, "alice@example.com", undefined); + }); + + it.each([ + [{ name: "CI", expires: "never" }, "never"], + [{ name: "CI", expires: "none" }, "none"], + [{ name: "CI", expires: "2099-12-31" }, "2099-12-31"], + ])("passes the access token body %j to the create command", async (body, expires) => { + const run = jest.fn().mockResolvedValue(Response.success()); + jest + .spyOn(AccessTokenCreateCommand, "create") + .mockReturnValue({ run } as unknown as AccessTokenCreateCommand); + + await call( + "POST", + "/sm/:organizationId/machine-accounts/:machineAccountId/access-tokens", + { organizationId: orgId, machineAccountId: id }, + { body }, + ); + + expect(run).toHaveBeenCalledWith(smOrg, id, { name: "CI", expires }); + }); + + it.each([ + [{ name: "CI" }], + [{ name: "CI", expires: "" }], + [{ name: "CI", expires: " " }], + [{ name: "CI", expires: null }], + [{ name: "CI", expires: 1767225600 }], + [{ name: "CI", expiresAt: "2099-12-31" }], + ])("rejects the access token body %j without an explicit expiry", async (body) => { + const run = jest.fn().mockResolvedValue(Response.success()); + jest + .spyOn(AccessTokenCreateCommand, "create") + .mockReturnValue({ run } as unknown as AccessTokenCreateCommand); + + const res = await call( + "POST", + "/sm/:organizationId/machine-accounts/:machineAccountId/access-tokens", + { organizationId: orgId, machineAccountId: id }, + { body }, + ); + + expect(run).not.toHaveBeenCalled(); + expect(res.status).toBe(400); + expect(res.body).toMatchObject({ + success: false, + message: + "`expires` is required. Use `never` for an access token that does not expire, or an ISO 8601 date.", + }); + }); + + it("reads the trash selection from the body", async () => { + const run = jest.fn().mockResolvedValue(Response.success()); + jest + .spyOn(TrashRestoreCommand, "create") + .mockReturnValue({ run } as unknown as TrashRestoreCommand); + + await call( + "POST", + "/sm/:organizationId/trash/restore", + { organizationId: orgId }, + { body: { secretIds: [id, 7] } }, + ); + + expect(run).toHaveBeenCalledWith(smOrg, { secretIds: [id], all: false }); + }); + + it("imports the request body", async () => { + const run = jest.fn().mockResolvedValue(Response.success()); + jest.spyOn(SmImportCommand, "create").mockReturnValue({ run } as unknown as SmImportCommand); + const body = { projects: [] as unknown[], secrets: [] as unknown[] }; + + await call("POST", "/sm/:organizationId/import", { organizationId: orgId }, { body }); + + expect(run).toHaveBeenCalledWith(smOrg, { data: body }); + }); + it("passes the master password from the export body to the command", async () => { + const run = jest.fn().mockResolvedValue(Response.success()); + jest.spyOn(SmExportCommand, "create").mockReturnValue({ run } as unknown as SmExportCommand); + + await call( + "POST", + "/sm/:organizationId/export", + { organizationId: orgId }, + { body: { password: "master-password" }, query: { passwordFile: "/etc/passwd" } }, + ); + + expect(run).toHaveBeenCalledWith(smOrg, { password: "master-password" }); + }); + + it("does not register a GET export route", () => { + expect(() => findRoute("GET", "/sm/:organizationId/export")).toThrow(); + }); +}); diff --git a/bitwarden_license/bit-cli/src/bit-serve-configurator.ts b/bitwarden_license/bit-cli/src/bit-serve-configurator.ts index 5a00dccb59b..a3e4c702db3 100644 --- a/bitwarden_license/bit-cli/src/bit-serve-configurator.ts +++ b/bitwarden_license/bit-cli/src/bit-serve-configurator.ts @@ -1,6 +1,10 @@ -import { Router } from "@koa/router"; +import { Router, RouterContext } from "@koa/router"; +import { firstValueFrom } from "rxjs"; +import { Response } from "@bitwarden/cli/models/response"; import { OssServeConfigurator } from "@bitwarden/cli/oss-serve-configurator"; +import { FeatureFlag } from "@bitwarden/common/enums/feature-flag.enum"; +import { Utils } from "@bitwarden/common/platform/misc/utils"; import { ApproveAllCommand, @@ -9,8 +13,46 @@ import { DenyCommand, ListCommand, } from "./admin-console/device-approval"; +import { AccessGetCommand } from "./secrets-manager/access/access-get.command"; +import { AccessGrantCommand } from "./secrets-manager/access/access-grant.command"; +import { AccessRevokeCommand } from "./secrets-manager/access/access-revoke.command"; +import { AccessSetCommand } from "./secrets-manager/access/access-set.command"; +import { AccessTokenCreateCommand } from "./secrets-manager/access-tokens/access-token-create.command"; +import { AccessTokenListCommand } from "./secrets-manager/access-tokens/access-token-list.command"; +import { AccessTokenRevokeCommand } from "./secrets-manager/access-tokens/access-token-revoke.command"; +import { CountsCommand } from "./secrets-manager/counts/counts.command"; +import { EventsCommand } from "./secrets-manager/events/events.command"; +import { GranteesListCommand } from "./secrets-manager/grantees/grantees-list.command"; +import { MachineAccountCreateCommand } from "./secrets-manager/machine-accounts/machine-account-create.command"; +import { MachineAccountDeleteCommand } from "./secrets-manager/machine-accounts/machine-account-delete.command"; +import { MachineAccountEditCommand } from "./secrets-manager/machine-accounts/machine-account-edit.command"; +import { MachineAccountGetCommand } from "./secrets-manager/machine-accounts/machine-account-get.command"; +import { MachineAccountListCommand } from "./secrets-manager/machine-accounts/machine-account-list.command"; +import { SmExportCommand } from "./secrets-manager/porting/sm-export.command"; +import { SmImportCommand } from "./secrets-manager/porting/sm-import.command"; +import { ProjectCreateCommand } from "./secrets-manager/projects/project-create.command"; +import { ProjectDeleteCommand } from "./secrets-manager/projects/project-delete.command"; +import { ProjectEditCommand } from "./secrets-manager/projects/project-edit.command"; +import { ProjectGetCommand } from "./secrets-manager/projects/project-get.command"; +import { ProjectListCommand } from "./secrets-manager/projects/project-list.command"; +import { SecretCreateCommand } from "./secrets-manager/secrets/secret-create.command"; +import { SecretDeleteCommand } from "./secrets-manager/secrets/secret-delete.command"; +import { SecretEditCommand } from "./secrets-manager/secrets/secret-edit.command"; +import { SecretGetCommand } from "./secrets-manager/secrets/secret-get.command"; +import { SecretListCommand } from "./secrets-manager/secrets/secret-list.command"; +import { SecretRestoreVersionCommand } from "./secrets-manager/secrets/secret-restore-version.command"; +import { SecretVersionsCommand } from "./secrets-manager/secrets/secret-versions.command"; +import { SmOrganization, withSmOrganization } from "./secrets-manager/sm-command.utils"; +import { TemplateCommand } from "./secrets-manager/templates/template.command"; +import { TrashEmptyCommand } from "./secrets-manager/trash/trash-empty.command"; +import { TrashListCommand } from "./secrets-manager/trash/trash-list.command"; +import { TrashRestoreCommand } from "./secrets-manager/trash/trash-restore.command"; +import { SmTrashSelection } from "./secrets-manager/trash/trash-selection"; import { ServiceContainer } from "./service-container"; +type SmRouteHandler = (ctx: RouterContext) => Promise; +type SmOrgRouteHandler = (ctx: RouterContext, org: SmOrganization) => Promise; + export class BitServeConfigurator extends OssServeConfigurator { constructor(protected override serviceContainer: ServiceContainer) { super(serviceContainer); @@ -22,6 +64,7 @@ export class BitServeConfigurator extends OssServeConfigurator { // Register bit endpoints this.serveDeviceApprovals(router); + this.serveSecretsManager(router); } private serveDeviceApprovals(router: Router) { @@ -92,4 +135,328 @@ export class BitServeConfigurator extends OssServeConfigurator { await next(); }); } + + private serveSecretsManager(router: Router) { + const sc = this.serviceContainer; + + router.get( + "/sm/template/:object", + this.smRoute(async (ctx) => await TemplateCommand.create().run(ctx.params.object)), + ); + + router.get( + "/sm/:organizationId/projects", + this.smOrgRoute(async (ctx, org) => await ProjectListCommand.create(sc).run(org)), + ); + router.get( + "/sm/:organizationId/projects/:projectId", + this.smOrgRoute( + async (ctx, org) => await ProjectGetCommand.create(sc).run(org, ctx.params.projectId), + ), + ); + router.post( + "/sm/:organizationId/projects", + this.smOrgRoute( + async (ctx, org) => await ProjectCreateCommand.create(sc).run(org, smBody(ctx)), + ), + ); + router.put( + "/sm/:organizationId/projects/:projectId", + this.smOrgRoute( + async (ctx, org) => + await ProjectEditCommand.create(sc).run(org, ctx.params.projectId, smBody(ctx)), + ), + ); + router.delete( + "/sm/:organizationId/projects/:projectId", + this.smOrgRoute( + async (ctx, org) => await ProjectDeleteCommand.create(sc).run(org, [ctx.params.projectId]), + ), + ); + + router.get( + "/sm/:organizationId/secrets", + this.smOrgRoute( + async (ctx, org) => await SecretListCommand.create(sc).run(org, smQuery(ctx, "projectid")), + ), + ); + router.get( + "/sm/:organizationId/secrets/:secretId", + this.smOrgRoute( + async (ctx, org) => await SecretGetCommand.create(sc).run(org, ctx.params.secretId), + ), + ); + router.post( + "/sm/:organizationId/secrets", + this.smOrgRoute( + async (ctx, org) => await SecretCreateCommand.create(sc).run(org, smBody(ctx)), + ), + ); + router.put( + "/sm/:organizationId/secrets/:secretId", + this.smOrgRoute( + async (ctx, org) => + await SecretEditCommand.create(sc).run(org, ctx.params.secretId, smBody(ctx)), + ), + ); + router.delete( + "/sm/:organizationId/secrets/:secretId", + this.smOrgRoute( + async (ctx, org) => await SecretDeleteCommand.create(sc).run(org, [ctx.params.secretId]), + ), + ); + router.get( + "/sm/:organizationId/secrets/:secretId/versions", + this.smOrgRoute( + async (ctx, org) => await SecretVersionsCommand.create(sc).run(org, ctx.params.secretId), + ), + ); + router.post( + "/sm/:organizationId/secrets/:secretId/versions/:versionId/restore", + this.smOrgRoute( + async (ctx, org) => + await SecretRestoreVersionCommand.create(sc).run( + org, + ctx.params.secretId, + ctx.params.versionId, + ), + ), + ); + + router.get( + "/sm/:organizationId/trash", + this.smOrgRoute(async (ctx, org) => await TrashListCommand.create(sc).run(org)), + ); + router.post( + "/sm/:organizationId/trash/restore", + this.smOrgRoute( + async (ctx, org) => await TrashRestoreCommand.create(sc).run(org, smTrashSelection(ctx)), + ), + ); + router.post( + "/sm/:organizationId/trash/empty", + this.smOrgRoute( + async (ctx, org) => await TrashEmptyCommand.create(sc).run(org, smTrashSelection(ctx)), + ), + ); + + router.get( + "/sm/:organizationId/machine-accounts", + this.smOrgRoute(async (ctx, org) => await MachineAccountListCommand.create(sc).run(org)), + ); + router.get( + "/sm/:organizationId/machine-accounts/:machineAccountId", + this.smOrgRoute( + async (ctx, org) => + await MachineAccountGetCommand.create(sc).run(org, ctx.params.machineAccountId), + ), + ); + router.post( + "/sm/:organizationId/machine-accounts", + this.smOrgRoute( + async (ctx, org) => await MachineAccountCreateCommand.create(sc).run(org, smBody(ctx)), + ), + ); + router.put( + "/sm/:organizationId/machine-accounts/:machineAccountId", + this.smOrgRoute( + async (ctx, org) => + await MachineAccountEditCommand.create(sc).run( + org, + ctx.params.machineAccountId, + smBody(ctx), + ), + ), + ); + router.delete( + "/sm/:organizationId/machine-accounts/:machineAccountId", + this.smOrgRoute( + async (ctx, org) => + await MachineAccountDeleteCommand.create(sc).run(org, [ctx.params.machineAccountId]), + ), + ); + router.get( + "/sm/:organizationId/machine-accounts/:machineAccountId/events", + this.smOrgRoute( + async (ctx, org) => + await EventsCommand.create(sc).run(org, { + machineAccountId: ctx.params.machineAccountId, + start: smQuery(ctx, "start"), + end: smQuery(ctx, "end"), + }), + ), + ); + + router.get( + "/sm/:organizationId/machine-accounts/:machineAccountId/access-tokens", + this.smOrgRoute( + async (ctx, org) => + await AccessTokenListCommand.create(sc).run(org, ctx.params.machineAccountId), + ), + ); + // Unlike the CLI, `expires` is required so that a missing or mistyped field cannot silently + // create an access token that never expires. + router.post( + "/sm/:organizationId/machine-accounts/:machineAccountId/access-tokens", + this.smOrgRoute(async (ctx, org) => { + const body = smBody(ctx); + const expires = smString(body.expires); + if (Utils.isNullOrWhitespace(expires)) { + return Response.badRequest( + "`expires` is required. Use `never` for an access token that does not expire, or an ISO 8601 date.", + ); + } + return await AccessTokenCreateCommand.create(sc).run(org, ctx.params.machineAccountId, { + name: smString(body.name), + expires, + }); + }), + ); + router.delete( + "/sm/:organizationId/machine-accounts/:machineAccountId/access-tokens/:accessTokenId", + this.smOrgRoute( + async (ctx, org) => + await AccessTokenRevokeCommand.create(sc).run(org, ctx.params.machineAccountId, [ + ctx.params.accessTokenId, + ]), + ), + ); + + router.get( + "/sm/:organizationId/access/:target/:id", + this.smOrgRoute( + async (ctx, org) => + await AccessGetCommand.create(sc).run(org, ctx.params.target, ctx.params.id), + ), + ); + router.put( + "/sm/:organizationId/access/:target/:id", + this.smOrgRoute( + async (ctx, org) => + await AccessSetCommand.create(sc).run(org, ctx.params.target, ctx.params.id, smBody(ctx)), + ), + ); + router.post( + "/sm/:organizationId/access/:target/:id/grant", + this.smOrgRoute(async (ctx, org) => { + const body = smBody(ctx); + return await AccessGrantCommand.create(sc).run( + org, + ctx.params.target, + ctx.params.id, + smString(body.grantee), + smString(body.permission), + ); + }), + ); + router.post( + "/sm/:organizationId/access/:target/:id/revoke", + this.smOrgRoute( + async (ctx, org) => + await AccessRevokeCommand.create(sc).run( + org, + ctx.params.target, + ctx.params.id, + smString(smBody(ctx).grantee), + ), + ), + ); + + router.get( + "/sm/:organizationId/grantees/:type", + this.smOrgRoute( + async (ctx, org) => await GranteesListCommand.create(sc).run(org, ctx.params.type), + ), + ); + + router.get( + "/sm/:organizationId/counts", + this.smOrgRoute( + async (ctx, org) => + await CountsCommand.create(sc).run(org, { + projectId: smQuery(ctx, "projectid"), + machineAccountId: smQuery(ctx, "machineaccountid"), + }), + ), + ); + + // Requires the master password as `password` in the JSON body. Like /unlock, password file + // and environment variable sources are not accepted over HTTP. + router.post( + "/sm/:organizationId/export", + this.smOrgRoute( + async (ctx, org) => + await SmExportCommand.create(sc).run(org, { + password: smString(smBody(ctx).password), + }), + ), + ); + router.post( + "/sm/:organizationId/import", + this.smOrgRoute( + async (ctx, org) => + await SmImportCommand.create(sc).run(org, { + data: ctx.request.body, + }), + ), + ); + } + + /** An `smRoute` for `/sm/:organizationId/...`; the handler receives the validated organization. */ + private smOrgRoute(handler: SmOrgRouteHandler) { + return this.smRoute((ctx) => + withSmOrganization(this.serviceContainer, ctx.params.organizationId, (org) => + handler(ctx, org), + ), + ); + } + + private smRoute(handler: SmRouteHandler) { + return async (ctx: RouterContext, next: () => Promise) => { + const enabled = await firstValueFrom( + this.serviceContainer.configService.getFeatureFlag$(FeatureFlag.SmCli), + ); + if (!enabled) { + this.processResponse( + ctx.response, + Response.error("This command is temporarily unavailable."), + ); + await next(); + return; + } + + if (await this.errorIfLocked(ctx.response)) { + await next(); + return; + } + + const response = await handler(ctx); + this.processResponse(ctx.response, response); + await next(); + }; + } +} + +function smBody(ctx: RouterContext): Record { + const body: unknown = ctx.request.body; + return body != null && typeof body === "object" ? (body as Record) : {}; +} + +function smQuery(ctx: RouterContext, name: string): string | undefined { + const value = ctx.request.query[name]; + return Array.isArray(value) ? value[0] : value; +} + +function smString(value: unknown): string | undefined { + return typeof value === "string" ? value : undefined; +} + +function smTrashSelection(ctx: RouterContext): SmTrashSelection { + const body = smBody(ctx); + return { + secretIds: Array.isArray(body.secretIds) + ? body.secretIds.filter((id): id is string => typeof id === "string") + : undefined, + all: body.all === true || body.all === "true", + }; } diff --git a/bitwarden_license/bit-cli/src/register-bit-programs.ts b/bitwarden_license/bit-cli/src/register-bit-programs.ts index 0d3f5e39f25..6dcc24fb8c7 100644 --- a/bitwarden_license/bit-cli/src/register-bit-programs.ts +++ b/bitwarden_license/bit-cli/src/register-bit-programs.ts @@ -1,4 +1,5 @@ import { DeviceApprovalProgram } from "./admin-console/device-approval"; +import { SmProgram } from "./secrets-manager"; import { ServiceContainer } from "./service-container"; /** @@ -10,4 +11,5 @@ import { ServiceContainer } from "./service-container"; */ export async function registerBitPrograms(serviceContainer: ServiceContainer) { new DeviceApprovalProgram(serviceContainer).register(); + new SmProgram(serviceContainer).register(); } diff --git a/bitwarden_license/bit-cli/src/secrets-manager/access-tokens/access-token-create.command.spec.ts b/bitwarden_license/bit-cli/src/secrets-manager/access-tokens/access-token-create.command.spec.ts new file mode 100644 index 00000000000..5f15fbfc620 --- /dev/null +++ b/bitwarden_license/bit-cli/src/secrets-manager/access-tokens/access-token-create.command.spec.ts @@ -0,0 +1,254 @@ +import { mock } from "jest-mock-extended"; +import { of } from "rxjs"; + +import { AccessService, ServiceAccountService, ServiceAccountView } from "@bitwarden/bit-sm"; +import { ApiService } from "@bitwarden/common/abstractions/api.service"; +import { AccountService } from "@bitwarden/common/auth/abstractions/account.service"; +import { LogService } from "@bitwarden/common/platform/abstractions/log.service"; +import { Utils } from "@bitwarden/common/platform/misc/utils"; +import { OrganizationId } from "@bitwarden/common/types/guid"; +import { OrgKey } from "@bitwarden/common/types/key"; +import { KeyService } from "@bitwarden/key-management"; +// eslint-disable-next-line no-restricted-imports +import { + CsprngArray, + EncryptService, + EncString, + KeyGenerationService, + SymmetricCryptoKey, +} from "@bitwarden/legacy-crypto"; + +import { + mockSmActiveAccount, + smNotFoundError, + smOrgId, + smOtherOrgId, + smOrg, +} from "../spec/sm-test-utils"; + +import { AccessTokenCreateCommand } from "./access-token-create.command"; + +describe("AccessTokenCreateCommand", () => { + const keyService = mock(); + const apiService = mock(); + const keyGenerationService = mock(); + const encryptService = mock(); + const logService = mock(); + const serviceAccountService = mock(); + const accountService = mock(); + + const machineAccountId = "22222222-2222-2222-2222-222222222222"; + const accessTokenId = "33333333-3333-3333-3333-333333333333"; + const clientSecret = "client-secret"; + const orgKey = new SymmetricCryptoKey(new Uint8Array(64).fill(1) as CsprngArray) as OrgKey; + const derivedKey = new SymmetricCryptoKey(new Uint8Array(64).fill(2) as CsprngArray); + const material = new Uint8Array(16).fill(3) as CsprngArray; + const expectedToken = + "0." + accessTokenId + "." + clientSecret + ":" + Utils.fromBufferToB64(material); + + let accessService: AccessService; + let command: AccessTokenCreateCommand; + + beforeEach(() => { + jest.clearAllMocks(); + mockSmActiveAccount(accountService); + keyService.orgKeys$.mockReturnValue( + of({ [smOrgId as OrganizationId]: orgKey } as Record), + ); + keyGenerationService.createKeyWithPurpose.mockResolvedValue({ + salt: "bitwarden-accesstoken", + material, + derivedKey, + }); + encryptService.encryptString.mockImplementation( + async (plainValue: string) => new EncString("2.enc|" + plainValue), + ); + apiService.send.mockResolvedValue({ + Id: accessTokenId, + Name: "2.enc|CI", + ClientSecret: clientSecret, + ExpireAt: null, + CreationDate: "2026-01-01T00:00:00Z", + RevisionDate: "2026-01-01T00:00:00Z", + }); + serviceAccountService.getByServiceAccountId.mockResolvedValue( + Object.assign(new ServiceAccountView(), { id: machineAccountId, organizationId: smOrgId }), + ); + + accessService = new AccessService( + keyService, + apiService, + keyGenerationService, + encryptService, + accountService, + logService, + ); + command = new AccessTokenCreateCommand(accessService, serviceAccountService); + }); + + it("returns the access token in the `0..:` format", async () => { + const response = await command.run(smOrg, machineAccountId, { name: "CI" }); + + expect(response.success).toBe(true); + expect(response.data).toEqual({ + object: "sm-access-token", + id: accessTokenId, + machineAccountId, + name: "CI", + expireAt: null, + accessToken: expectedToken, + }); + }); + + it("creates the access token with the shared access token crypto", async () => { + const expires = "2099-12-31T00:00:00Z"; + + await command.run(smOrg, machineAccountId, { name: "CI", expires }); + + expect(keyGenerationService.createKeyWithPurpose).toHaveBeenCalledWith( + 128, + "sm-access-token", + "bitwarden-accesstoken", + ); + expect(encryptService.encryptString).toHaveBeenCalledWith("CI", orgKey); + expect(encryptService.encryptString).toHaveBeenCalledWith( + JSON.stringify({ encryptionKey: orgKey.keyB64 }), + derivedKey, + ); + expect(encryptService.encryptString).toHaveBeenCalledWith(derivedKey.keyB64, orgKey); + expect(apiService.send).toHaveBeenCalledWith( + "POST", + "/service-accounts/" + machineAccountId + "/access-tokens", + expect.objectContaining({ + name: new EncString("2.enc|CI"), + expireAt: new Date(expires), + }), + true, + true, + ); + }); + + it("returns only the access token string when raw output is requested", async () => { + const response = await command.run(smOrg, machineAccountId, { name: "CI", raw: true }); + + expect(response.success).toBe(true); + expect(response.data).toEqual({ object: "string", data: expectedToken }); + }); + + it("never logs the access token", async () => { + await command.run(smOrg, machineAccountId, { name: "CI" }); + + for (const call of [ + ...logService.debug.mock.calls, + ...logService.info.mock.calls, + ...logService.warning.mock.calls, + ...logService.error.mock.calls, + ]) { + expect(JSON.stringify(call)).not.toContain(clientSecret); + } + }); + + it("requires a name", async () => { + const response = await command.run(smOrg, machineAccountId, { name: " " }); + + expect(response.success).toBe(false); + expect(response.message).toBe("`name` is required."); + expect(apiService.send).not.toHaveBeenCalled(); + }); + + it("rejects a name longer than 80 characters", async () => { + const response = await command.run(smOrg, machineAccountId, { name: "a".repeat(81) }); + + expect(response.success).toBe(false); + expect(response.message).toBe("`name` must be at most 80 characters."); + }); + + it.each([undefined, "", "never", "none", "NEVER", "None"])( + "creates an access token that does not expire for the expiration `%s`", + async (expires) => { + const response = await command.run(smOrg, machineAccountId, { name: "CI", expires }); + + expect(response.success).toBe(true); + expect(response.data).toMatchObject({ expireAt: null }); + expect(apiService.send).toHaveBeenCalledWith( + "POST", + "/service-accounts/" + machineAccountId + "/access-tokens", + expect.objectContaining({ expireAt: null }), + true, + true, + ); + }, + ); + + it("creates an access token that expires at an ISO 8601 date", async () => { + const response = await command.run(smOrg, machineAccountId, { + name: "CI", + expires: "2099-12-31", + }); + + expect(response.success).toBe(true); + expect(response.data).toMatchObject({ expireAt: new Date("2099-12-31") }); + }); + + it.each(["tomorrow", "12/31/2099", "forever"])( + "rejects the expiration `%s` and names the accepted forms", + async (expires) => { + const response = await command.run(smOrg, machineAccountId, { name: "CI", expires }); + + expect(response.success).toBe(false); + expect(response.message).toBe( + "`expires` must be `never`, `none`, or an ISO 8601 date, e.g. 2026-12-31 or 2026-12-31T23:59:59Z.", + ); + expect(apiService.send).not.toHaveBeenCalled(); + }, + ); + + it("rejects an expiration that is not a real date", async () => { + const response = await command.run(smOrg, machineAccountId, { + name: "CI", + expires: "2099-13-45", + }); + + expect(response.success).toBe(false); + expect(response.message).toBe("`expires` is not a valid date."); + expect(apiService.send).not.toHaveBeenCalled(); + }); + + it("rejects an expiration in the past", async () => { + const response = await command.run(smOrg, machineAccountId, { + name: "CI", + expires: "2000-01-01", + }); + + expect(response.success).toBe(false); + expect(response.message).toBe("`expires` must be in the future."); + }); + + it("rejects a machine account in another organization", async () => { + serviceAccountService.getByServiceAccountId.mockResolvedValue( + Object.assign(new ServiceAccountView(), { + id: machineAccountId, + organizationId: smOtherOrgId, + }), + ); + + const response = await command.run(smOrg, machineAccountId, { name: "CI" }); + + expect(response.success).toBe(false); + expect(response.message).toBe( + "The machine account was not found, or you do not have access to it.", + ); + expect(keyGenerationService.createKeyWithPurpose).not.toHaveBeenCalled(); + }); + + it("reports a machine account the user cannot access", async () => { + serviceAccountService.getByServiceAccountId.mockRejectedValue(smNotFoundError()); + + const response = await command.run(smOrg, machineAccountId, { name: "CI" }); + + expect(response.success).toBe(false); + expect(response.message).toBe( + "The machine account was not found, or you do not have access to it.", + ); + }); +}); diff --git a/bitwarden_license/bit-cli/src/secrets-manager/access-tokens/access-token-create.command.ts b/bitwarden_license/bit-cli/src/secrets-manager/access-tokens/access-token-create.command.ts new file mode 100644 index 00000000000..e4b338620b5 --- /dev/null +++ b/bitwarden_license/bit-cli/src/secrets-manager/access-tokens/access-token-create.command.ts @@ -0,0 +1,117 @@ +import { AccessService, AccessTokenView, ServiceAccountService } from "@bitwarden/bit-sm"; +import { Response } from "@bitwarden/cli/models/response"; +import { StringResponse } from "@bitwarden/cli/models/response/string.response"; +import { Utils } from "@bitwarden/common/platform/misc/utils"; + +import { ServiceContainer } from "../../service-container"; +import { SmAccessTokenCreatedResponse } from "../models/sm-access-token.response"; +import { SmOrganization, smErrorResponse } from "../sm-command.utils"; + +import { resolveSmMachineAccountId } from "./sm-access-token.utils"; + +const MAX_NAME_LENGTH = 80; +const ISO_DATE_PATTERN = /^\d{4}-\d{2}-\d{2}(T\d{2}:\d{2}(:\d{2}(\.\d+)?)?(Z|[+-]\d{2}:?\d{2})?)?$/; +const NO_EXPIRY_VALUES = ["never", "none"]; + +export type AccessTokenCreateOptions = { + name?: string; + expires?: string; + raw?: boolean; +}; + +export class AccessTokenCreateCommand { + constructor( + private accessService: AccessService, + private serviceAccountService: ServiceAccountService, + ) {} + + async run( + org: SmOrganization, + machineAccountId: string, + options: AccessTokenCreateOptions, + ): Promise { + const name = options.name?.trim() ?? ""; + if (Utils.isNullOrWhitespace(name)) { + return Response.badRequest("`name` is required."); + } + if (name.length > MAX_NAME_LENGTH) { + return Response.badRequest("`name` must be at most " + MAX_NAME_LENGTH + " characters."); + } + const expireAt = this.parseExpires(options.expires); + if (expireAt instanceof Response) { + return expireAt; + } + + const machineAccount = await resolveSmMachineAccountId( + this.serviceAccountService, + org.organizationId, + machineAccountId, + ); + if (machineAccount.error) { + return machineAccount.error; + } + + const view = new AccessTokenView(); + view.name = name; + view.expireAt = expireAt; + + let accessToken: string; + try { + accessToken = await this.accessService.createAccessToken( + org.organizationId, + machineAccount.machineAccountId, + view, + ); + } catch (e) { + return smErrorResponse(e, "machine account"); + } + + if (options.raw) { + return Response.success(new StringResponse(accessToken)); + } + return Response.success( + new SmAccessTokenCreatedResponse( + AccessTokenCreateCommand.getAccessTokenId(accessToken), + machineAccount.machineAccountId, + name, + expireAt, + accessToken, + ), + ); + } + + private parseExpires(expires: string | undefined): Date | null | Response { + const normalized = (expires ?? "").toLowerCase(); + const isUnset = Utils.isNullOrEmpty(normalized); + if (isUnset || NO_EXPIRY_VALUES.includes(normalized)) { + return null; + } + if (!ISO_DATE_PATTERN.test(expires)) { + return Response.badRequest( + "`expires` must be `never`, `none`, or an ISO 8601 date, e.g. 2026-12-31 or 2026-12-31T23:59:59Z.", + ); + } + const date = new Date(expires); + if (isNaN(date.getTime())) { + return Response.badRequest("`expires` is not a valid date."); + } + if (date.getTime() <= Date.now()) { + return Response.badRequest("`expires` must be in the future."); + } + return date; + } + + /** + * Access tokens have the form `..:`. + */ + private static getAccessTokenId(accessToken: string): string { + return accessToken.split(":")[0].split(".")[1]; + } + + static create(serviceContainer: ServiceContainer) { + return new AccessTokenCreateCommand( + serviceContainer.accessService, + serviceContainer.serviceAccountService, + ); + } +} diff --git a/bitwarden_license/bit-cli/src/secrets-manager/access-tokens/access-token-list.command.spec.ts b/bitwarden_license/bit-cli/src/secrets-manager/access-tokens/access-token-list.command.spec.ts new file mode 100644 index 00000000000..c0a5ac7c24c --- /dev/null +++ b/bitwarden_license/bit-cli/src/secrets-manager/access-tokens/access-token-list.command.spec.ts @@ -0,0 +1,70 @@ +import { mock } from "jest-mock-extended"; + +import { + AccessService, + AccessTokenView, + ServiceAccountService, + ServiceAccountView, +} from "@bitwarden/bit-sm"; + +import { smNotFoundError, smOrgId, smOrg } from "../spec/sm-test-utils"; + +import { AccessTokenListCommand } from "./access-token-list.command"; + +describe("AccessTokenListCommand", () => { + const accessService = mock(); + const serviceAccountService = mock(); + const machineAccountId = "22222222-2222-2222-2222-222222222222"; + const tokenId = "33333333-3333-3333-3333-333333333333"; + let command: AccessTokenListCommand; + + beforeEach(() => { + jest.clearAllMocks(); + serviceAccountService.getByServiceAccountId.mockResolvedValue( + Object.assign(new ServiceAccountView(), { id: machineAccountId, organizationId: smOrgId }), + ); + command = new AccessTokenListCommand(accessService, serviceAccountService); + }); + + it("lists the machine account's access tokens", async () => { + const creationDate = new Date("2026-01-01T00:00:00Z"); + accessService.getAccessTokens.mockResolvedValue([ + Object.assign(new AccessTokenView(), { + id: tokenId, + name: "CI", + scopes: ["api.secrets"], + creationDate, + revisionDate: creationDate, + }), + ]); + + const response = await command.run(smOrg, machineAccountId); + + expect(response.success).toBe(true); + expect(accessService.getAccessTokens).toHaveBeenCalledWith(smOrgId, machineAccountId); + expect(response.data).toMatchObject({ + data: [ + { + object: "sm-access-token", + id: tokenId, + machineAccountId, + name: "CI", + scopes: ["api.secrets"], + expireAt: null, + }, + ], + }); + }); + + it("reports a machine account the user cannot access", async () => { + serviceAccountService.getByServiceAccountId.mockRejectedValue(smNotFoundError()); + + const response = await command.run(smOrg, machineAccountId); + + expect(response.success).toBe(false); + expect(response.message).toBe( + "The machine account was not found, or you do not have access to it.", + ); + expect(accessService.getAccessTokens).not.toHaveBeenCalled(); + }); +}); diff --git a/bitwarden_license/bit-cli/src/secrets-manager/access-tokens/access-token-list.command.ts b/bitwarden_license/bit-cli/src/secrets-manager/access-tokens/access-token-list.command.ts new file mode 100644 index 00000000000..c72fcabba3a --- /dev/null +++ b/bitwarden_license/bit-cli/src/secrets-manager/access-tokens/access-token-list.command.ts @@ -0,0 +1,48 @@ +import { AccessService, ServiceAccountService } from "@bitwarden/bit-sm"; +import { Response } from "@bitwarden/cli/models/response"; +import { ListResponse } from "@bitwarden/cli/models/response/list.response"; + +import { ServiceContainer } from "../../service-container"; +import { SmAccessTokenResponse } from "../models/sm-access-token.response"; +import { SmOrganization, smErrorResponse } from "../sm-command.utils"; + +import { resolveSmMachineAccountId } from "./sm-access-token.utils"; + +export class AccessTokenListCommand { + constructor( + private accessService: AccessService, + private serviceAccountService: ServiceAccountService, + ) {} + + async run(org: SmOrganization, machineAccountId: string): Promise { + const machineAccount = await resolveSmMachineAccountId( + this.serviceAccountService, + org.organizationId, + machineAccountId, + ); + if (machineAccount.error) { + return machineAccount.error; + } + + try { + const accessTokens = await this.accessService.getAccessTokens( + org.organizationId, + machineAccount.machineAccountId, + ); + return Response.success( + new ListResponse( + accessTokens.map((t) => new SmAccessTokenResponse(machineAccount.machineAccountId, t)), + ), + ); + } catch (e) { + return smErrorResponse(e, "machine account"); + } + } + + static create(serviceContainer: ServiceContainer) { + return new AccessTokenListCommand( + serviceContainer.accessService, + serviceContainer.serviceAccountService, + ); + } +} diff --git a/bitwarden_license/bit-cli/src/secrets-manager/access-tokens/access-token-revoke.command.spec.ts b/bitwarden_license/bit-cli/src/secrets-manager/access-tokens/access-token-revoke.command.spec.ts new file mode 100644 index 00000000000..26c7c74c489 --- /dev/null +++ b/bitwarden_license/bit-cli/src/secrets-manager/access-tokens/access-token-revoke.command.spec.ts @@ -0,0 +1,71 @@ +import { mock } from "jest-mock-extended"; + +import { + AccessService, + AccessTokenView, + ServiceAccountService, + ServiceAccountView, +} from "@bitwarden/bit-sm"; + +import { smOrgId, smOrg } from "../spec/sm-test-utils"; + +import { AccessTokenRevokeCommand } from "./access-token-revoke.command"; + +describe("AccessTokenRevokeCommand", () => { + const accessService = mock(); + const serviceAccountService = mock(); + const machineAccountId = "22222222-2222-2222-2222-222222222222"; + const tokenId1 = "33333333-3333-3333-3333-333333333333"; + const tokenId2 = "44444444-4444-4444-4444-444444444444"; + let command: AccessTokenRevokeCommand; + + beforeEach(() => { + jest.clearAllMocks(); + serviceAccountService.getByServiceAccountId.mockResolvedValue( + Object.assign(new ServiceAccountView(), { id: machineAccountId, organizationId: smOrgId }), + ); + accessService.getAccessTokens.mockResolvedValue([ + Object.assign(new AccessTokenView(), { id: tokenId1, name: "CI" }), + Object.assign(new AccessTokenView(), { id: tokenId2, name: "Deploy" }), + ]); + command = new AccessTokenRevokeCommand(accessService, serviceAccountService); + }); + + it("revokes one or more access tokens", async () => { + const response = await command.run(smOrg, machineAccountId, [tokenId1, tokenId2.toUpperCase()]); + + expect(response.success).toBe(true); + expect(accessService.revokeAccessTokens).toHaveBeenCalledWith(machineAccountId, [ + tokenId1, + tokenId2, + ]); + }); + + it("rejects an access token that does not belong to the machine account", async () => { + const unknownId = "55555555-5555-5555-5555-555555555555"; + + const response = await command.run(smOrg, machineAccountId, [tokenId1, unknownId]); + + expect(response.success).toBe(false); + expect(response.message).toBe( + "The access token `" + unknownId + "` was not found, or you do not have access to it.", + ); + expect(accessService.revokeAccessTokens).not.toHaveBeenCalled(); + }); + + it("requires at least one access token id", async () => { + const response = await command.run(smOrg, machineAccountId, []); + + expect(response.success).toBe(false); + expect(response.message).toBe("At least one `accessTokenId` is required."); + expect(accessService.revokeAccessTokens).not.toHaveBeenCalled(); + }); + + it("rejects an invalid machine account id", async () => { + const response = await command.run(smOrg, "nope", [tokenId1]); + + expect(response.success).toBe(false); + expect(response.message).toBe("`nope` is not a GUID."); + expect(serviceAccountService.getByServiceAccountId).not.toHaveBeenCalled(); + }); +}); diff --git a/bitwarden_license/bit-cli/src/secrets-manager/access-tokens/access-token-revoke.command.ts b/bitwarden_license/bit-cli/src/secrets-manager/access-tokens/access-token-revoke.command.ts new file mode 100644 index 00000000000..014cbd93b51 --- /dev/null +++ b/bitwarden_license/bit-cli/src/secrets-manager/access-tokens/access-token-revoke.command.ts @@ -0,0 +1,62 @@ +import { AccessService, ServiceAccountService } from "@bitwarden/bit-sm"; +import { Response } from "@bitwarden/cli/models/response"; + +import { ServiceContainer } from "../../service-container"; +import { + parseSmIds, + SmOrganization, + smErrorResponse, + smNotFoundResponse, +} from "../sm-command.utils"; + +import { resolveSmMachineAccountId } from "./sm-access-token.utils"; + +export class AccessTokenRevokeCommand { + constructor( + private accessService: AccessService, + private serviceAccountService: ServiceAccountService, + ) {} + + async run( + org: SmOrganization, + machineAccountId: string, + accessTokenIds: string[], + ): Promise { + const parsed = parseSmIds(accessTokenIds, "accessTokenId"); + if (parsed.error) { + return parsed.error; + } + const machineAccount = await resolveSmMachineAccountId( + this.serviceAccountService, + org.organizationId, + machineAccountId, + ); + if (machineAccount.error) { + return machineAccount.error; + } + + try { + const accessTokens = await this.accessService.getAccessTokens( + org.organizationId, + machineAccount.machineAccountId, + ); + for (const id of parsed.ids) { + if (!accessTokens.some((t) => t.id === id)) { + return smNotFoundResponse("access token `" + id + "`"); + } + } + + await this.accessService.revokeAccessTokens(machineAccount.machineAccountId, parsed.ids); + return Response.success(); + } catch (e) { + return smErrorResponse(e, "machine account"); + } + } + + static create(serviceContainer: ServiceContainer) { + return new AccessTokenRevokeCommand( + serviceContainer.accessService, + serviceContainer.serviceAccountService, + ); + } +} diff --git a/bitwarden_license/bit-cli/src/secrets-manager/access-tokens/sm-access-token.utils.ts b/bitwarden_license/bit-cli/src/secrets-manager/access-tokens/sm-access-token.utils.ts new file mode 100644 index 00000000000..2a570387fa7 --- /dev/null +++ b/bitwarden_license/bit-cli/src/secrets-manager/access-tokens/sm-access-token.utils.ts @@ -0,0 +1,35 @@ +import { ServiceAccountService } from "@bitwarden/bit-sm"; +import { Response } from "@bitwarden/cli/models/response"; + +import { parseSmId, smErrorResponse, smNotFoundResponse } from "../sm-command.utils"; + +/** + * Confirms the machine account exists in the organization. Access tokens are encrypted with the + * organization key, so a machine account in another organization must be rejected up front. + */ +export async function resolveSmMachineAccountId( + serviceAccountService: ServiceAccountService, + organizationId: string, + machineAccountId: string, +): Promise< + | { machineAccountId: string; error?: undefined } + | { machineAccountId?: undefined; error: Response } +> { + const parsed = parseSmId(machineAccountId, "machineaccountid"); + if (parsed.error) { + return { error: parsed.error }; + } + + try { + const machineAccount = await serviceAccountService.getByServiceAccountId( + parsed.id, + organizationId, + ); + if (machineAccount.organizationId !== organizationId) { + return { error: smNotFoundResponse("machine account") }; + } + } catch (e) { + return { error: smErrorResponse(e, "machine account") }; + } + return { machineAccountId: parsed.id }; +} diff --git a/bitwarden_license/bit-cli/src/secrets-manager/access/access-get.command.spec.ts b/bitwarden_license/bit-cli/src/secrets-manager/access/access-get.command.spec.ts new file mode 100644 index 00000000000..55596e6d93e --- /dev/null +++ b/bitwarden_license/bit-cli/src/secrets-manager/access/access-get.command.spec.ts @@ -0,0 +1,93 @@ +import { ListResponse } from "@bitwarden/cli/models/response/list.response"; + +import { SmAccessPolicyResponse } from "../models/sm-access-policy.response"; +import { + bobId, + createSmAccessFixture, + groupId, + groupPolicy, + machineAccountId, + machineAccountPolicy, + projectId, + smTargetId, + userPolicy, +} from "../spec/sm-access-test-utils"; +import { smOrgId, smOrg } from "../spec/sm-test-utils"; + +import { AccessGetCommand } from "./access-get.command"; + +describe("AccessGetCommand", () => { + let fixture: ReturnType; + let command: AccessGetCommand; + + const run = async (target: string) => { + const response = await command.run(smOrg, target, smTargetId); + expect(response.success).toBe(true); + return ((response.data as ListResponse).data as SmAccessPolicyResponse[]).map((p) => [ + p.type, + p.id, + p.permission, + ]); + }; + + beforeEach(() => { + jest.clearAllMocks(); + fixture = createSmAccessFixture(); + command = new AccessGetCommand(fixture.store); + }); + + it("lists people and machine account access to a project", async () => { + fixture.accessPolicyService.getProjectPeopleAccessPolicies.mockResolvedValue({ + userAccessPolicies: [userPolicy(bobId, "Bob", true)], + groupAccessPolicies: [groupPolicy(groupId, "Engineering")], + }); + fixture.accessPolicyService.getProjectServiceAccountsAccessPolicies.mockResolvedValue({ + serviceAccountAccessPolicies: [machineAccountPolicy(machineAccountId, "CI runner")], + }); + + expect(await run("project")).toEqual([ + ["user", bobId, "read-write"], + ["group", groupId, "read"], + ["machineAccount", machineAccountId, "read"], + ]); + }); + + it("lists people access and granted projects for a machine account", async () => { + fixture.accessPolicyService.getServiceAccountPeopleAccessPolicies.mockResolvedValue({ + userAccessPolicies: [userPolicy(bobId, "Bob", true)], + groupAccessPolicies: [], + }); + fixture.accessPolicyService.getServiceAccountGrantedPolicies.mockResolvedValue({ + grantedProjectPolicies: [ + { + accessPolicy: { + grantedProjectId: projectId, + grantedProjectName: "Backend", + read: true, + write: false, + }, + hasPermission: true, + }, + ], + }); + + expect(await run("machine-account")).toEqual([ + ["user", bobId, "read-write"], + ["project", projectId, "read"], + ]); + expect(fixture.serviceAccountService.getByServiceAccountId).toHaveBeenCalledWith( + smTargetId, + smOrgId, + ); + }); + + it("lists the access policies on a secret", async () => { + fixture.accessPolicyService.getSecretAccessPolicies.mockResolvedValue({ + userAccessPolicies: [], + groupAccessPolicies: [groupPolicy(groupId, "Engineering", true)], + serviceAccountAccessPolicies: [], + }); + + expect(await run("secret")).toEqual([["group", groupId, "read-write"]]); + }); +}); diff --git a/bitwarden_license/bit-cli/src/secrets-manager/access/access-get.command.ts b/bitwarden_license/bit-cli/src/secrets-manager/access/access-get.command.ts new file mode 100644 index 00000000000..dd82a06caae --- /dev/null +++ b/bitwarden_license/bit-cli/src/secrets-manager/access/access-get.command.ts @@ -0,0 +1,26 @@ +import { Response } from "@bitwarden/cli/models/response"; +import { ListResponse } from "@bitwarden/cli/models/response/list.response"; + +import { ServiceContainer } from "../../service-container"; +import { SmAccessPolicyResponse } from "../models/sm-access-policy.response"; +import { SmOrganization } from "../sm-command.utils"; + +import { SmAccessPolicyStore } from "./sm-access-policies"; + +export class AccessGetCommand { + constructor(private store: SmAccessPolicyStore) {} + + async run(org: SmOrganization, target: string, targetId: string): Promise { + const loaded = await this.store.load(org, target, targetId); + if (loaded.error) { + return loaded.error; + } + return Response.success( + new ListResponse(loaded.state.policies.map((p) => new SmAccessPolicyResponse(p))), + ); + } + + static create(serviceContainer: ServiceContainer) { + return new AccessGetCommand(SmAccessPolicyStore.create(serviceContainer)); + } +} diff --git a/bitwarden_license/bit-cli/src/secrets-manager/access/access-grant.command.spec.ts b/bitwarden_license/bit-cli/src/secrets-manager/access/access-grant.command.spec.ts new file mode 100644 index 00000000000..2f838fcd0e3 --- /dev/null +++ b/bitwarden_license/bit-cli/src/secrets-manager/access/access-grant.command.spec.ts @@ -0,0 +1,235 @@ +import { SecretView } from "@bitwarden/bit-sm"; +import { ListResponse } from "@bitwarden/cli/models/response/list.response"; + +import { SmAccessPolicyResponse } from "../models/sm-access-policy.response"; +import { + aliceId, + bobId, + createSmAccessFixture, + groupId, + groupPolicy, + machineAccountId, + machineAccountPolicy, + potentialGrantee, + projectId, + smTargetId, + userPolicy, +} from "../spec/sm-access-test-utils"; +import { smOrgId, smOrg } from "../spec/sm-test-utils"; + +import { AccessGrantCommand } from "./access-grant.command"; + +describe("AccessGrantCommand", () => { + let fixture: ReturnType; + let command: AccessGrantCommand; + + beforeEach(() => { + jest.clearAllMocks(); + fixture = createSmAccessFixture(); + command = new AccessGrantCommand(fixture.store); + }); + + describe("project", () => { + beforeEach(() => { + fixture.accessPolicyService.getProjectPeopleAccessPolicies.mockResolvedValue({ + userAccessPolicies: [userPolicy(bobId, "Bob", true)], + groupAccessPolicies: [groupPolicy(groupId, "Engineering")], + }); + fixture.accessPolicyService.getProjectServiceAccountsAccessPolicies.mockResolvedValue({ + serviceAccountAccessPolicies: [machineAccountPolicy(machineAccountId, "CI runner")], + }); + }); + + it("adds a user by email and preserves existing policies", async () => { + const response = await command.run(smOrg, "project", smTargetId, "alice@example.com", "read"); + + expect(response.success).toBe(true); + expect(fixture.accessPolicyService.putProjectPeopleAccessPolicies).toHaveBeenCalledWith( + smTargetId, + { + userAccessPolicies: [ + expect.objectContaining({ organizationUserId: bobId, read: true, write: true }), + expect.objectContaining({ organizationUserId: aliceId, read: true, write: false }), + ], + groupAccessPolicies: [ + expect.objectContaining({ groupId: groupId, read: true, write: false }), + ], + }, + ); + expect( + fixture.accessPolicyService.putProjectServiceAccountsAccessPolicies, + ).not.toHaveBeenCalled(); + }); + + it("changes the permission of an existing grantee without duplicating it", async () => { + await command.run(smOrg, "project", smTargetId, "Engineering", "read-write"); + + const people = fixture.accessPolicyService.putProjectPeopleAccessPolicies.mock.calls[0][1]; + expect(people.groupAccessPolicies).toEqual([ + expect.objectContaining({ groupId: groupId, read: true, write: true }), + ]); + expect(people.userAccessPolicies).toEqual([ + expect.objectContaining({ organizationUserId: bobId, read: true, write: true }), + ]); + }); + + it("adds a machine account and preserves existing machine accounts", async () => { + const otherId = "3c3c3c3c-0000-0000-0000-0000000000ff"; + fixture.accessPolicyService.getServiceAccountsPotentialGrantees.mockResolvedValue([ + potentialGrantee("serviceAccount", machineAccountId, "CI runner"), + potentialGrantee("serviceAccount", otherId, "Deploy bot"), + ]); + + const response = await command.run(smOrg, "project", smTargetId, "Deploy bot", "read-write"); + + expect(response.success).toBe(true); + expect( + fixture.accessPolicyService.putProjectServiceAccountsAccessPolicies, + ).toHaveBeenCalledWith(smOrgId, smTargetId, { + serviceAccountAccessPolicies: [ + expect.objectContaining({ serviceAccountId: machineAccountId, write: false }), + expect.objectContaining({ serviceAccountId: otherId, read: true, write: true }), + ], + }); + expect(fixture.accessPolicyService.putProjectPeopleAccessPolicies).not.toHaveBeenCalled(); + }); + + it("returns the policies read back from the server", async () => { + fixture.accessPolicyService.getProjectPeopleAccessPolicies + .mockResolvedValueOnce({ userAccessPolicies: [], groupAccessPolicies: [] }) + .mockResolvedValueOnce({ + userAccessPolicies: [userPolicy(aliceId, "Alice")], + groupAccessPolicies: [], + }); + fixture.accessPolicyService.getProjectServiceAccountsAccessPolicies.mockResolvedValue({ + serviceAccountAccessPolicies: [], + }); + + const response = await command.run(smOrg, "project", smTargetId, "alice@example.com", "read"); + + const data = (response.data as ListResponse).data as SmAccessPolicyResponse[]; + expect(data).toEqual([ + expect.objectContaining({ + object: "sm-access-policy", + type: "user", + id: aliceId, + name: "Alice", + permission: "read", + }), + ]); + }); + + it("errors with every candidate when the grantee is ambiguous", async () => { + fixture.accessPolicyService.getPeoplePotentialGrantees.mockResolvedValue([ + potentialGrantee("group", groupId, "Ops"), + potentialGrantee("group", "9a9a9a9a-0000-0000-0000-0000000000ff", "ops"), + ]); + + const response = await command.run(smOrg, "project", smTargetId, "OPS", "read"); + + expect(response.success).toBe(false); + expect(response.message).toBe( + "`OPS` matches more than one grantee. Use the id of one of the following instead:\n" + + "group " + + groupId + + " (Ops)\n" + + "group 9a9a9a9a-0000-0000-0000-0000000000ff (ops)", + ); + expect(fixture.accessPolicyService.putProjectPeopleAccessPolicies).not.toHaveBeenCalled(); + }); + + it("rejects an invalid permission before calling the server", async () => { + const response = await command.run(smOrg, "project", smTargetId, "Engineering", "manage"); + + expect(response.message).toBe("`permission` must be one of: read, read-write."); + expect(fixture.accessPolicyService.getProjectPeopleAccessPolicies).not.toHaveBeenCalled(); + }); + }); + + describe("machine-account", () => { + it("grants a project by name and preserves people access", async () => { + fixture.accessPolicyService.getServiceAccountPeopleAccessPolicies.mockResolvedValue({ + userAccessPolicies: [userPolicy(bobId, "Bob", true)], + groupAccessPolicies: [], + }); + + const response = await command.run(smOrg, "machine-account", smTargetId, "backend", "read"); + + expect(response.success).toBe(true); + expect(fixture.accessPolicyService.putServiceAccountGrantedPolicies).toHaveBeenCalledWith( + smOrgId, + smTargetId, + { + grantedProjectPolicies: [ + expect.objectContaining({ + accessPolicy: expect.objectContaining({ + grantedProjectId: projectId, + read: true, + write: false, + }), + }), + ], + }, + ); + expect( + fixture.accessPolicyService.putServiceAccountPeopleAccessPolicies, + ).not.toHaveBeenCalled(); + }); + + it("rejects read-only people access", async () => { + const response = await command.run( + smOrg, + "machine-account", + smTargetId, + "alice@example.com", + "read", + ); + + expect(response.message).toBe( + "People can only be granted read-write access to a machine account.", + ); + expect( + fixture.accessPolicyService.putServiceAccountPeopleAccessPolicies, + ).not.toHaveBeenCalled(); + }); + }); + + describe("secret", () => { + it("writes the complete policy set through the secret update request", async () => { + fixture.accessPolicyService.getSecretAccessPolicies.mockResolvedValue({ + userAccessPolicies: [userPolicy(bobId, "Bob")], + groupAccessPolicies: [], + serviceAccountAccessPolicies: [machineAccountPolicy(machineAccountId, "CI runner", true)], + }); + + const response = await command.run(smOrg, "secret", smTargetId, groupId, "read-write"); + + expect(response.success).toBe(true); + expect(fixture.secretService.update).toHaveBeenCalledWith( + smOrgId, + expect.objectContaining({ id: smTargetId, name: "API_KEY", value: "value" }), + { + userAccessPolicies: [expect.objectContaining({ organizationUserId: bobId })], + groupAccessPolicies: [ + expect.objectContaining({ groupId: groupId, read: true, write: true }), + ], + serviceAccountAccessPolicies: [ + expect.objectContaining({ serviceAccountId: machineAccountId, write: true }), + ], + }, + false, + ); + }); + + it("requires write access to the secret", async () => { + fixture.secretService.getBySecretId.mockResolvedValue( + Object.assign(new SecretView(), { id: smTargetId, organizationId: smOrgId, write: false }), + ); + + const response = await command.run(smOrg, "secret", smTargetId, groupId, "read"); + + expect(response.success).toBe(false); + expect(fixture.secretService.update).not.toHaveBeenCalled(); + }); + }); +}); diff --git a/bitwarden_license/bit-cli/src/secrets-manager/access/access-grant.command.ts b/bitwarden_license/bit-cli/src/secrets-manager/access/access-grant.command.ts new file mode 100644 index 00000000000..af41d9bbbc2 --- /dev/null +++ b/bitwarden_license/bit-cli/src/secrets-manager/access/access-grant.command.ts @@ -0,0 +1,75 @@ +import { Response } from "@bitwarden/cli/models/response"; +import { ListResponse } from "@bitwarden/cli/models/response/list.response"; + +import { ServiceContainer } from "../../service-container"; +import { SmAccessPolicyResponse } from "../models/sm-access-policy.response"; +import { SmOrganization } from "../sm-command.utils"; + +import { + checkSmAccessPolicy, + fromSmPermission, + parseSmPermission, + SmAccessPolicyStore, +} from "./sm-access-policies"; + +/** + * Grants a single grantee access, or changes its permission, while keeping every other + * existing policy on the target. + */ +export class AccessGrantCommand { + constructor(private store: SmAccessPolicyStore) {} + + async run( + org: SmOrganization, + target: string, + targetId: string, + grantee: string, + permission: string, + ): Promise { + const parsedPermission = parseSmPermission(permission); + if (parsedPermission.error) { + return parsedPermission.error; + } + const loaded = await this.store.load(org, target, targetId); + if (loaded.error) { + return loaded.error; + } + const state = loaded.state; + const resolved = await this.store.resolveGrantee(state, grantee); + if (resolved.error) { + return resolved.error; + } + const invalid = checkSmAccessPolicy( + state.target, + resolved.grantee.type, + parsedPermission.permission, + ); + if (invalid) { + return invalid; + } + + const isTarget = (p: { type: string; id: string }) => + p.type === resolved.grantee.type && p.id.toLowerCase() === resolved.grantee.id.toLowerCase(); + const policies = [ + ...state.policies.filter((p) => !isTarget(p)), + { + type: resolved.grantee.type, + id: resolved.grantee.id, + name: resolved.grantee.name, + ...fromSmPermission(parsedPermission.permission), + }, + ]; + + const saved = await this.store.save(state, policies); + if (saved.error) { + return saved.error; + } + return Response.success( + new ListResponse(saved.policies.map((p) => new SmAccessPolicyResponse(p))), + ); + } + + static create(serviceContainer: ServiceContainer) { + return new AccessGrantCommand(SmAccessPolicyStore.create(serviceContainer)); + } +} diff --git a/bitwarden_license/bit-cli/src/secrets-manager/access/access-revoke.command.spec.ts b/bitwarden_license/bit-cli/src/secrets-manager/access/access-revoke.command.spec.ts new file mode 100644 index 00000000000..7d9c013e742 --- /dev/null +++ b/bitwarden_license/bit-cli/src/secrets-manager/access/access-revoke.command.spec.ts @@ -0,0 +1,125 @@ +import { + aliceId, + bobId, + createSmAccessFixture, + groupId, + groupPolicy, + machineAccountId, + machineAccountPolicy, + smTargetId, + userPolicy, +} from "../spec/sm-access-test-utils"; +import { smOrgId, smOrg } from "../spec/sm-test-utils"; + +import { AccessRevokeCommand } from "./access-revoke.command"; + +describe("AccessRevokeCommand", () => { + let fixture: ReturnType; + let command: AccessRevokeCommand; + + beforeEach(() => { + jest.clearAllMocks(); + fixture = createSmAccessFixture(); + command = new AccessRevokeCommand(fixture.store); + fixture.accessPolicyService.getProjectPeopleAccessPolicies.mockResolvedValue({ + userAccessPolicies: [userPolicy(aliceId, "Alice"), userPolicy(bobId, "Bob", true)], + groupAccessPolicies: [groupPolicy(groupId, "Engineering")], + }); + fixture.accessPolicyService.getProjectServiceAccountsAccessPolicies.mockResolvedValue({ + serviceAccountAccessPolicies: [machineAccountPolicy(machineAccountId, "CI runner")], + }); + }); + + it("removes only the target user", async () => { + const response = await command.run(smOrg, "project", smTargetId, "alice@example.com"); + + expect(response.success).toBe(true); + expect(fixture.accessPolicyService.putProjectPeopleAccessPolicies).toHaveBeenCalledWith( + smTargetId, + { + userAccessPolicies: [ + expect.objectContaining({ organizationUserId: bobId, read: true, write: true }), + ], + groupAccessPolicies: [expect.objectContaining({ groupId: groupId })], + }, + ); + expect( + fixture.accessPolicyService.putProjectServiceAccountsAccessPolicies, + ).not.toHaveBeenCalled(); + }); + + it("removes a machine account by id without touching people access", async () => { + const response = await command.run(smOrg, "project", smTargetId, machineAccountId); + + expect(response.success).toBe(true); + expect( + fixture.accessPolicyService.putProjectServiceAccountsAccessPolicies, + ).toHaveBeenCalledWith(smOrgId, smTargetId, { serviceAccountAccessPolicies: [] }); + expect(fixture.accessPolicyService.putProjectPeopleAccessPolicies).not.toHaveBeenCalled(); + }); + + it("removes a granted project from a machine account", async () => { + const otherProjectId = "4d4d4d4d-0000-0000-0000-0000000000ff"; + fixture.accessPolicyService.getServiceAccountGrantedPolicies.mockResolvedValue({ + grantedProjectPolicies: [ + { + accessPolicy: { + grantedProjectId: "4d4d4d4d-0000-0000-0000-000000000005", + grantedProjectName: "Backend", + read: true, + write: false, + }, + hasPermission: true, + }, + { + accessPolicy: { + grantedProjectId: otherProjectId, + grantedProjectName: "Frontend", + read: true, + write: true, + }, + hasPermission: true, + }, + ], + }); + + const response = await command.run(smOrg, "machine-account", smTargetId, "Backend"); + + expect(response.success).toBe(true); + expect(fixture.accessPolicyService.putServiceAccountGrantedPolicies).toHaveBeenCalledWith( + smOrgId, + smTargetId, + { + grantedProjectPolicies: [ + expect.objectContaining({ + accessPolicy: expect.objectContaining({ + grantedProjectId: otherProjectId, + read: true, + write: true, + }), + }), + ], + }, + ); + }); + + it("errors when the grantee has no access", async () => { + fixture.accessPolicyService.getProjectPeopleAccessPolicies.mockResolvedValue({ + userAccessPolicies: [userPolicy(bobId, "Bob")], + groupAccessPolicies: [], + }); + + const response = await command.run(smOrg, "project", smTargetId, "alice@example.com"); + + expect(response.success).toBe(false); + expect(response.message).toBe("`alice@example.com` does not have access."); + expect(fixture.accessPolicyService.putProjectPeopleAccessPolicies).not.toHaveBeenCalled(); + }); + + it("errors when the grantee cannot be found", async () => { + const response = await command.run(smOrg, "project", smTargetId, "nobody@example.com"); + + expect(response.success).toBe(false); + expect(fixture.accessPolicyService.putProjectPeopleAccessPolicies).not.toHaveBeenCalled(); + }); +}); diff --git a/bitwarden_license/bit-cli/src/secrets-manager/access/access-revoke.command.ts b/bitwarden_license/bit-cli/src/secrets-manager/access/access-revoke.command.ts new file mode 100644 index 00000000000..8c9b3588426 --- /dev/null +++ b/bitwarden_license/bit-cli/src/secrets-manager/access/access-revoke.command.ts @@ -0,0 +1,53 @@ +import { Response } from "@bitwarden/cli/models/response"; +import { ListResponse } from "@bitwarden/cli/models/response/list.response"; + +import { ServiceContainer } from "../../service-container"; +import { SmAccessPolicyResponse } from "../models/sm-access-policy.response"; +import { SmOrganization } from "../sm-command.utils"; + +import { SmAccessPolicyStore } from "./sm-access-policies"; + +/** + * Removes a single grantee's access while keeping every other existing policy on the target. + */ +export class AccessRevokeCommand { + constructor(private store: SmAccessPolicyStore) {} + + async run( + org: SmOrganization, + target: string, + targetId: string, + grantee: string, + ): Promise { + const loaded = await this.store.load(org, target, targetId); + if (loaded.error) { + return loaded.error; + } + const state = loaded.state; + const resolved = await this.store.resolveGrantee(state, grantee); + if (resolved.error) { + return resolved.error; + } + + const isTarget = (p: { type: string; id: string }) => + p.type === resolved.grantee.type && p.id.toLowerCase() === resolved.grantee.id.toLowerCase(); + if (!state.policies.some(isTarget)) { + return Response.error("`" + grantee + "` does not have access."); + } + + const saved = await this.store.save( + state, + state.policies.filter((p) => !isTarget(p)), + ); + if (saved.error) { + return saved.error; + } + return Response.success( + new ListResponse(saved.policies.map((p) => new SmAccessPolicyResponse(p))), + ); + } + + static create(serviceContainer: ServiceContainer) { + return new AccessRevokeCommand(SmAccessPolicyStore.create(serviceContainer)); + } +} diff --git a/bitwarden_license/bit-cli/src/secrets-manager/access/access-set.command.spec.ts b/bitwarden_license/bit-cli/src/secrets-manager/access/access-set.command.spec.ts new file mode 100644 index 00000000000..d61c05597eb --- /dev/null +++ b/bitwarden_license/bit-cli/src/secrets-manager/access/access-set.command.spec.ts @@ -0,0 +1,128 @@ +import { + aliceId, + bobId, + createSmAccessFixture, + groupId, + machineAccountId, + machineAccountPolicy, + smTargetId, + userPolicy, +} from "../spec/sm-access-test-utils"; +import { encodeSmRequest, smOrgId, smOtherOrgId, smOrg } from "../spec/sm-test-utils"; + +import { AccessSetCommand } from "./access-set.command"; + +describe("AccessSetCommand", () => { + let fixture: ReturnType; + let command: AccessSetCommand; + + beforeEach(() => { + jest.clearAllMocks(); + fixture = createSmAccessFixture(); + command = new AccessSetCommand(fixture.store); + fixture.accessPolicyService.getProjectPeopleAccessPolicies.mockResolvedValue({ + userAccessPolicies: [userPolicy(bobId, "Bob", true)], + groupAccessPolicies: [], + }); + fixture.accessPolicyService.getProjectServiceAccountsAccessPolicies.mockResolvedValue({ + serviceAccountAccessPolicies: [machineAccountPolicy(machineAccountId, "CI runner")], + }); + }); + + it("replaces every policy on the target", async () => { + const response = await command.run( + smOrg, + "project", + smTargetId, + encodeSmRequest({ + policies: [ + { type: "user", id: aliceId.toUpperCase(), permission: "read" }, + { type: "group", id: groupId, permission: "read-write" }, + ], + }), + ); + + expect(response.success).toBe(true); + expect(fixture.accessPolicyService.putProjectPeopleAccessPolicies).toHaveBeenCalledWith( + smTargetId, + { + userAccessPolicies: [ + expect.objectContaining({ organizationUserId: aliceId, read: true, write: false }), + ], + groupAccessPolicies: [ + expect.objectContaining({ groupId: groupId, read: true, write: true }), + ], + }, + ); + expect( + fixture.accessPolicyService.putProjectServiceAccountsAccessPolicies, + ).toHaveBeenCalledWith(smOrgId, smTargetId, { serviceAccountAccessPolicies: [] }); + }); + + it("accepts an object body from bw serve", async () => { + const response = await command.run(smOrg, "project", smTargetId, { + organizationId: smOrgId, + policies: [{ type: "machineAccount", id: machineAccountId, permission: "read" }], + }); + + expect(response.success).toBe(true); + expect(fixture.accessPolicyService.putProjectPeopleAccessPolicies).toHaveBeenCalledWith( + smTargetId, + { userAccessPolicies: [], groupAccessPolicies: [] }, + ); + expect( + fixture.accessPolicyService.putProjectServiceAccountsAccessPolicies, + ).not.toHaveBeenCalled(); + }); + + it.each([ + [{}, "`policies` must be an array."], + [{ policies: ["x"] }, "Each policy must be a JSON object."], + [ + { policies: [{ type: "project", id: aliceId, permission: "read" }] }, + "Each policy's `type` must be one of: user, group, machineAccount.", + ], + [{ policies: [{ type: "user", id: "alice", permission: "read" }] }, "`alice` is not a GUID."], + [ + { policies: [{ type: "user", id: aliceId, permission: "manage" }] }, + "`permission` must be one of: read, read-write.", + ], + [ + { + policies: [ + { type: "user", id: aliceId, permission: "read" }, + { type: "user", id: aliceId, permission: "read-write" }, + ], + }, + "`" + aliceId + "` is listed more than once.", + ], + ])("rejects %j", async (request, message) => { + const response = await command.run(smOrg, "project", smTargetId, request); + + expect(response.success).toBe(false); + expect(response.message).toBe(message); + expect(fixture.accessPolicyService.getProjectPeopleAccessPolicies).not.toHaveBeenCalled(); + }); + + it("rejects read-only people access to a machine account", async () => { + const response = await command.run(smOrg, "machine-account", smTargetId, { + policies: [{ type: "user", id: aliceId, permission: "read" }], + }); + + expect(response.message).toBe( + "People can only be granted read-write access to a machine account.", + ); + }); + + it("rejects a request for another organization", async () => { + const response = await command.run(smOrg, "project", smTargetId, { + organizationId: smOtherOrgId, + policies: [], + }); + + expect(response.message).toBe( + "The request's `organizationId` property does not match the organization id.", + ); + expect(fixture.accessPolicyService.putProjectPeopleAccessPolicies).not.toHaveBeenCalled(); + }); +}); diff --git a/bitwarden_license/bit-cli/src/secrets-manager/access/access-set.command.ts b/bitwarden_license/bit-cli/src/secrets-manager/access/access-set.command.ts new file mode 100644 index 00000000000..f7732c4331e --- /dev/null +++ b/bitwarden_license/bit-cli/src/secrets-manager/access/access-set.command.ts @@ -0,0 +1,122 @@ +import { Response } from "@bitwarden/cli/models/response"; +import { ListResponse } from "@bitwarden/cli/models/response/list.response"; + +import { ServiceContainer } from "../../service-container"; +import { SmAccessPolicyResponse } from "../models/sm-access-policy.response"; +import { + checkSmRequestOrganization, + parseSmId, + parseSmRequest, + SmOrganization, +} from "../sm-command.utils"; + +import { + checkSmAccessPolicy, + fromSmPermission, + isSmGranteeTypeFor, + parseSmAccessTarget, + parseSmPermission, + smAccessGranteeTypes, + SmAccessPolicy, + SmAccessPolicyStore, + SmAccessTarget, +} from "./sm-access-policies"; + +type SmAccessSetRequest = { + organizationId: string; + policies: unknown; +}; + +export class AccessSetCommand { + constructor(private store: SmAccessPolicyStore) {} + + async run( + org: SmOrganization, + target: string, + targetId: string, + requestJson: unknown, + ): Promise { + const parsedTarget = parseSmAccessTarget(target); + if (parsedTarget.error) { + return parsedTarget.error; + } + const parsed = await parseSmRequest(requestJson); + if (parsed.error) { + return parsed.error; + } + const policies = this.readPolicies(parsedTarget.target, parsed.request.policies); + if (policies.error) { + return policies.error; + } + + const loaded = await this.store.load(org, target, targetId); + if (loaded.error) { + return loaded.error; + } + const orgMismatch = checkSmRequestOrganization( + loaded.state.organizationId, + parsed.request.organizationId, + ); + if (orgMismatch) { + return orgMismatch; + } + + const saved = await this.store.save(loaded.state, policies.policies); + if (saved.error) { + return saved.error; + } + return Response.success( + new ListResponse(saved.policies.map((p) => new SmAccessPolicyResponse(p))), + ); + } + + private readPolicies( + target: SmAccessTarget, + value: unknown, + ): { policies: SmAccessPolicy[]; error?: undefined } | { policies?: undefined; error: Response } { + if (!Array.isArray(value)) { + return { error: Response.badRequest("`policies` must be an array.") }; + } + + const policies: SmAccessPolicy[] = []; + for (const item of value) { + if (item == null || typeof item !== "object" || Array.isArray(item)) { + return { error: Response.badRequest("Each policy must be a JSON object.") }; + } + const { type, id, permission } = item as Record; + if (!isSmGranteeTypeFor(target, type)) { + return { + error: Response.badRequest( + "Each policy's `type` must be one of: " + smAccessGranteeTypes(target).join(", ") + ".", + ), + }; + } + if (typeof id !== "string") { + return { error: Response.badRequest("Each policy's `id` must be a string.") }; + } + const parsedId = parseSmId(id, "id"); + if (parsedId.error) { + return { error: parsedId.error }; + } + const parsedPermission = parseSmPermission(permission); + if (parsedPermission.error) { + return { error: parsedPermission.error }; + } + const invalid = checkSmAccessPolicy(target, type, parsedPermission.permission); + if (invalid) { + return { error: invalid }; + } + if (policies.some((p) => p.type === type && p.id === parsedId.id)) { + return { + error: Response.badRequest("`" + parsedId.id + "` is listed more than once."), + }; + } + policies.push({ type, id: parsedId.id, ...fromSmPermission(parsedPermission.permission) }); + } + return { policies }; + } + + static create(serviceContainer: ServiceContainer) { + return new AccessSetCommand(SmAccessPolicyStore.create(serviceContainer)); + } +} diff --git a/bitwarden_license/bit-cli/src/secrets-manager/access/sm-access-policies.spec.ts b/bitwarden_license/bit-cli/src/secrets-manager/access/sm-access-policies.spec.ts new file mode 100644 index 00000000000..218b3f66c08 --- /dev/null +++ b/bitwarden_license/bit-cli/src/secrets-manager/access/sm-access-policies.spec.ts @@ -0,0 +1,138 @@ +import { ProjectView } from "@bitwarden/bit-sm"; + +import { aliceId, createSmAccessFixture, groupId, smTargetId } from "../spec/sm-access-test-utils"; +import { smNotFoundError, smOrg, smOtherOrgId } from "../spec/sm-test-utils"; + +import { + checkSmAccessPolicy, + fromSmPermission, + parseSmPermission, + resolveSmGrantee, + toSmPermission, +} from "./sm-access-policies"; + +describe("sm access policies", () => { + describe("permission mapping", () => { + it("maps read to read-only flags", () => { + expect(fromSmPermission("read")).toEqual({ read: true, write: false }); + }); + + it("maps read-write to read and write flags", () => { + expect(fromSmPermission("read-write")).toEqual({ read: true, write: true }); + }); + + it.each([ + [{ read: true, write: false }, "read"], + [{ read: true, write: true }, "read-write"], + ])("maps %o to %s", (flags, permission) => { + expect(toSmPermission(flags)).toBe(permission); + }); + + it.each(["manage", "write", "", undefined])("rejects the permission %p", (permission) => { + const result = parseSmPermission(permission); + + expect(result.error?.success).toBe(false); + expect(result.error?.message).toBe("`permission` must be one of: read, read-write."); + }); + }); + + describe("checkSmAccessPolicy", () => { + it("rejects read-only people access to a machine account", () => { + expect(checkSmAccessPolicy("machine-account", "user", "read")?.message).toBe( + "People can only be granted read-write access to a machine account.", + ); + }); + + it("allows read-only project access for a machine account", () => { + expect(checkSmAccessPolicy("machine-account", "project", "read")).toBeUndefined(); + }); + + it("rejects a grantee type the target does not support", () => { + expect(checkSmAccessPolicy("project", "project", "read")?.message).toBe( + "A project cannot be granted access to a project. Expected one of: user, group, machineAccount.", + ); + }); + }); + + describe("resolveSmGrantee", () => { + const candidates = [ + { type: "user" as const, id: aliceId, email: "alice@example.com" }, + { type: "group" as const, id: groupId, name: "Alice" }, + { type: "machineAccount" as const, id: "5e5e5e5e-0000-0000-0000-000000000001", name: "CI" }, + { type: "machineAccount" as const, id: "5e5e5e5e-0000-0000-0000-000000000002", name: "ci" }, + ]; + + it("resolves a user by email, ignoring case", () => { + expect(resolveSmGrantee("Alice@Example.com", candidates, "project").grantee?.id).toBe( + aliceId, + ); + }); + + it("resolves a group by name", () => { + expect(resolveSmGrantee("alice", candidates, "project").grantee?.id).toBe(groupId); + }); + + it("prefers an id match over a name match", () => { + expect(resolveSmGrantee(groupId.toUpperCase(), candidates, "project").grantee?.type).toBe( + "group", + ); + }); + + it("lists every candidate when the grantee is ambiguous", () => { + const result = resolveSmGrantee("CI", candidates, "project"); + + expect(result.error?.success).toBe(false); + expect(result.error?.message).toBe( + "`CI` matches more than one grantee. Use the id of one of the following instead:\n" + + "machine account 5e5e5e5e-0000-0000-0000-000000000001 (CI)\n" + + "machine account 5e5e5e5e-0000-0000-0000-000000000002 (ci)", + ); + }); + + it("errors when nothing matches", () => { + const result = resolveSmGrantee("nobody", candidates, "project"); + + expect(result.error?.message).toBe( + "No user, group, or machine account matching `nobody` can be granted access to this project. " + + "Use `bw sm grantees list` to see the available grantees.", + ); + }); + }); + + describe("SmAccessPolicyStore.load", () => { + it("rejects a target in another organization", async () => { + const { store, projectService, accessPolicyService } = createSmAccessFixture(); + projectService.getByProjectId.mockResolvedValue( + Object.assign(new ProjectView(), { id: smTargetId, organizationId: smOtherOrgId }), + ); + + const result = await store.load(smOrg, "project", smTargetId); + + expect(result.error?.message).toBe( + "The project was not found, or you do not have access to it.", + ); + expect(accessPolicyService.getProjectPeopleAccessPolicies).not.toHaveBeenCalled(); + }); + + it("maps a 404 to a not found error", async () => { + const { store, serviceAccountService } = createSmAccessFixture(); + serviceAccountService.getByServiceAccountId.mockRejectedValue(smNotFoundError()); + + const result = await store.load(smOrg, "machine-account", smTargetId); + + expect(result.error?.message).toBe( + "The machine account was not found, or you do not have access to it.", + ); + }); + + it("rejects an unknown target", async () => { + const { store } = createSmAccessFixture(); + + const result = await store.load(smOrg, "folder", smTargetId); + + expect(result.error?.message).toBe( + "Unknown access target `folder`. Expected one of: project, machine-account, secret.", + ); + }); + }); +}); diff --git a/bitwarden_license/bit-cli/src/secrets-manager/access/sm-access-policies.ts b/bitwarden_license/bit-cli/src/secrets-manager/access/sm-access-policies.ts new file mode 100644 index 00000000000..90486680200 --- /dev/null +++ b/bitwarden_license/bit-cli/src/secrets-manager/access/sm-access-policies.ts @@ -0,0 +1,556 @@ +import { + AccessPolicyService, + GrantedProjectPolicyPermissionDetailsView, + PotentialGranteeView, + ProjectService, + SecretService, + SecretView, + ServiceAccountService, +} from "@bitwarden/bit-sm"; +import { Response } from "@bitwarden/cli/models/response"; +import { Utils } from "@bitwarden/common/platform/misc/utils"; +// eslint-disable-next-line no-restricted-imports +import { DECRYPT_ERROR } from "@bitwarden/legacy-crypto"; + +import { ServiceContainer } from "../../service-container"; +import { SmGranteeType, toSmGranteeType } from "../models/sm-grantee.response"; +import { + parseSmId, + SmOrganization, + smErrorResponse, + smNotFoundResponse, +} from "../sm-command.utils"; + +export const SmAccessTargets = ["project", "machine-account", "secret"] as const; +export type SmAccessTarget = (typeof SmAccessTargets)[number]; + +export const SmAccessPermissions = ["read", "read-write"] as const; +export type SmAccessPermission = (typeof SmAccessPermissions)[number]; + +export type SmAccessPolicy = { + type: SmGranteeType; + id: string; + name?: string; + read: boolean; + write: boolean; +}; + +export type SmAccessState = { + organizationId: string; + target: SmAccessTarget; + targetId: string; + policies: SmAccessPolicy[]; + secret?: SecretView; +}; + +type SmGranteeCandidate = { + type: SmGranteeType; + id: string; + name?: string; + email?: string; +}; + +const TargetLabels: Record = { + project: "project", + "machine-account": "machine account", + secret: "secret", +}; + +const GranteeTypes: Record = { + project: ["user", "group", "machineAccount"], + "machine-account": ["user", "group", "project"], + secret: ["user", "group", "machineAccount"], +}; + +const GranteeTypeLabels: Record = { + user: "user", + group: "group", + machineAccount: "machine account", + project: "project", +}; + +/** + * Machine account people access only supports read-write, matching the web vault. + */ +function requiresReadWrite(target: SmAccessTarget, type: SmGranteeType): boolean { + const isMachineAccount = target === "machine-account"; + const isPeopleGrantee = type === "user" || type === "group"; + return isMachineAccount && isPeopleGrantee; +} + +export function parseSmPermission( + permission: unknown, +): + | { permission: SmAccessPermission; error?: undefined } + | { permission?: undefined; error: Response } { + if (!SmAccessPermissions.includes(permission as SmAccessPermission)) { + return { + error: Response.badRequest( + "`permission` must be one of: " + SmAccessPermissions.join(", ") + ".", + ), + }; + } + return { permission: permission as SmAccessPermission }; +} + +export function toSmPermission(policy: { read: boolean; write: boolean }): SmAccessPermission { + return policy.write ? "read-write" : "read"; +} + +export function fromSmPermission(permission: SmAccessPermission): { + read: boolean; + write: boolean; +} { + return { read: true, write: permission === "read-write" }; +} + +export function parseSmAccessTarget( + target: string, +): { target: SmAccessTarget; error?: undefined } | { target?: undefined; error: Response } { + if (!SmAccessTargets.includes(target as SmAccessTarget)) { + return { + error: Response.badRequest( + "Unknown access target `" + + target + + "`. Expected one of: " + + SmAccessTargets.join(", ") + + ".", + ), + }; + } + return { target: target as SmAccessTarget }; +} + +/** + * Validates a policy for the target, returning an error message if the grantee type or + * permission is not supported. + */ +export function checkSmAccessPolicy( + target: SmAccessTarget, + type: SmGranteeType, + permission: SmAccessPermission, +): Response | undefined { + if (!GranteeTypes[target].includes(type)) { + return Response.badRequest( + "A " + + GranteeTypeLabels[type] + + " cannot be granted access to a " + + TargetLabels[target] + + ". Expected one of: " + + GranteeTypes[target].join(", ") + + ".", + ); + } + if (requiresReadWrite(target, type) && permission !== "read-write") { + return Response.badRequest( + "People can only be granted read-write access to a machine account.", + ); + } + return undefined; +} + +export function isSmGranteeTypeFor(target: SmAccessTarget, type: unknown): type is SmGranteeType { + return GranteeTypes[target].includes(type as SmGranteeType); +} + +export function smAccessGranteeTypes(target: SmAccessTarget): SmGranteeType[] { + return GranteeTypes[target]; +} + +function granteeDescription(candidate: SmGranteeCandidate): string { + const label = candidate.email ?? candidate.name; + return GranteeTypeLabels[candidate.type] + " " + candidate.id + (label ? " (" + label + ")" : ""); +} + +function matchesGrantee(candidate: SmGranteeCandidate, normalized: string): boolean { + if (candidate.type === "user") { + return candidate.email?.toLowerCase() === normalized; + } + return candidate.name?.toLowerCase() === normalized; +} + +/** + * Finds the single grantee identified by an id, a user's email, or the name of a group, + * machine account, or project. + */ +export function resolveSmGrantee( + grantee: string, + candidates: SmGranteeCandidate[], + target: SmAccessTarget, +): { grantee: SmGranteeCandidate; error?: undefined } | { grantee?: undefined; error: Response } { + if (Utils.isNullOrWhitespace(grantee)) { + return { error: Response.badRequest("`grantee` is required.") }; + } + const normalized = grantee.trim().toLowerCase(); + + let matches = candidates.filter((c) => c.id.toLowerCase() === normalized); + if (matches.length === 0) { + matches = candidates.filter((c) => matchesGrantee(c, normalized)); + } + + if (matches.length === 0) { + const types = GranteeTypes[target].map((t) => GranteeTypeLabels[t]); + return { + error: Response.error( + "No " + + types.slice(0, -1).join(", ") + + ", or " + + types[types.length - 1] + + " matching `" + + grantee + + "` can be granted access to this " + + TargetLabels[target] + + ". Use `bw sm grantees list` to see the available grantees.", + ), + }; + } + if (matches.length > 1) { + return { + error: Response.error( + "`" + + grantee + + "` matches more than one grantee. Use the id of one of the following instead:\n" + + matches.map(granteeDescription).join("\n"), + ), + }; + } + return { grantee: matches[0] }; +} + +function samePolicies(a: SmAccessPolicy[], b: SmAccessPolicy[]): boolean { + const key = (p: SmAccessPolicy) => + p.type + ":" + p.id.toLowerCase() + ":" + p.read + ":" + p.write; + const aKeys = a.map(key).sort(); + const bKeys = b.map(key).sort(); + return aKeys.length === bKeys.length && aKeys.every((k, i) => k === bKeys[i]); +} + +function ofType(policies: SmAccessPolicy[], ...types: SmGranteeType[]): SmAccessPolicy[] { + return policies.filter((p) => types.includes(p.type)); +} + +function flags(policy: { read: boolean; write: boolean }) { + return { read: policy.read, write: policy.write }; +} + +/** + * Reads and writes the access policies of projects, machine accounts, and secrets as a single + * list. The server replaces each set of policies wholesale, so writes always send the complete + * set for every group of policies that changed. + */ +export class SmAccessPolicyStore { + constructor( + private accessPolicyService: AccessPolicyService, + private projectService: ProjectService, + private serviceAccountService: ServiceAccountService, + private secretService: SecretService, + ) {} + + async load( + org: SmOrganization, + target: string, + targetId: string, + ): Promise<{ state: SmAccessState; error?: undefined } | { state?: undefined; error: Response }> { + const parsedTarget = parseSmAccessTarget(target); + if (parsedTarget.error) { + return { error: parsedTarget.error }; + } + const id = parseSmId(targetId, "id"); + if (id.error) { + return { error: id.error }; + } + + try { + const owner = await this.getOwner(org.organizationId, parsedTarget.target, id.id); + if (owner.organizationId !== org.organizationId) { + return { error: smNotFoundResponse(TargetLabels[parsedTarget.target]) }; + } + const policies = await this.getPolicies(org.organizationId, parsedTarget.target, id.id); + return { + state: { + organizationId: org.organizationId, + target: parsedTarget.target, + targetId: id.id, + policies, + secret: owner.secret, + }, + }; + } catch (e) { + return { error: smErrorResponse(e, TargetLabels[parsedTarget.target]) }; + } + } + + /** + * Replaces the target's policies with `policies` and returns the policies stored on the server. + */ + async save( + state: SmAccessState, + policies: SmAccessPolicy[], + ): Promise< + { policies: SmAccessPolicy[]; error?: undefined } | { policies?: undefined; error: Response } + > { + try { + const error = await this.write(state, policies); + if (error) { + return { error }; + } + return { + policies: await this.getPolicies(state.organizationId, state.target, state.targetId), + }; + } catch (e) { + return { error: smErrorResponse(e, TargetLabels[state.target]) }; + } + } + + async resolveGrantee( + state: SmAccessState, + grantee: string, + ): Promise< + { grantee: SmGranteeCandidate; error?: undefined } | { grantee?: undefined; error: Response } + > { + const current: SmGranteeCandidate[] = state.policies.map((p) => ({ + type: p.type, + id: p.id, + name: p.type === "user" ? undefined : p.name, + })); + const byId = current.filter((c) => c.id.toLowerCase() === grantee?.trim().toLowerCase()); + if (byId.length === 1) { + return { grantee: byId[0] }; + } + + let potential: PotentialGranteeView[]; + try { + potential = await this.getPotentialGrantees(state.organizationId, state.target); + } catch (e) { + return { error: smErrorResponse(e, "organization") }; + } + const candidates: SmGranteeCandidate[] = potential + .map((g) => ({ + type: toSmGranteeType(g.type), + id: g.id, + name: g.name === DECRYPT_ERROR ? undefined : g.name, + email: g.email ?? undefined, + })) + .filter((c) => GranteeTypes[state.target].includes(c.type)); + for (const c of current) { + if (!candidates.some((p) => p.type === c.type && p.id.toLowerCase() === c.id.toLowerCase())) { + candidates.push(c); + } + } + return resolveSmGrantee(grantee, candidates, state.target); + } + + private async getOwner( + organizationId: string, + target: SmAccessTarget, + targetId: string, + ): Promise<{ organizationId: string; secret?: SecretView }> { + switch (target) { + case "project": + return await this.projectService.getByProjectId(targetId, true); + case "machine-account": + return await this.serviceAccountService.getByServiceAccountId(targetId, organizationId); + case "secret": { + const secret = await this.secretService.getBySecretId(targetId); + return { organizationId: secret.organizationId, secret }; + } + } + } + + private getPotentialGrantees(organizationId: string, target: SmAccessTarget) { + const others = + target === "machine-account" + ? this.accessPolicyService.getProjectsPotentialGrantees(organizationId) + : this.accessPolicyService.getServiceAccountsPotentialGrantees(organizationId); + return Promise.all([ + this.accessPolicyService.getPeoplePotentialGrantees(organizationId), + others, + ]).then(([people, rest]) => [...people, ...rest]); + } + + private async getPolicies( + organizationId: string, + target: SmAccessTarget, + targetId: string, + ): Promise { + switch (target) { + case "project": { + const [people, machineAccounts] = await Promise.all([ + this.accessPolicyService.getProjectPeopleAccessPolicies(targetId), + this.accessPolicyService.getProjectServiceAccountsAccessPolicies( + organizationId, + targetId, + ), + ]); + return [ + ...this.fromPeople(people), + ...this.fromMachineAccounts(machineAccounts.serviceAccountAccessPolicies), + ]; + } + case "machine-account": { + const [people, granted] = await Promise.all([ + this.accessPolicyService.getServiceAccountPeopleAccessPolicies(targetId), + this.accessPolicyService.getServiceAccountGrantedPolicies(organizationId, targetId), + ]); + return [ + ...this.fromPeople(people), + ...granted.grantedProjectPolicies.map((g) => ({ + type: "project" as const, + id: g.accessPolicy.grantedProjectId, + name: g.accessPolicy.grantedProjectName, + ...flags(g.accessPolicy), + })), + ]; + } + case "secret": { + const policies = await this.accessPolicyService.getSecretAccessPolicies( + organizationId, + targetId, + ); + return [ + ...this.fromPeople(policies), + ...this.fromMachineAccounts(policies.serviceAccountAccessPolicies), + ]; + } + } + } + + private async write(state: SmAccessState, policies: SmAccessPolicy[]): Promise { + const people = (list: SmAccessPolicy[]) => ofType(list, "user", "group"); + const peopleView = { + userAccessPolicies: ofType(policies, "user").map((p) => ({ + organizationUserId: p.id, + organizationUserName: p.name, + currentUser: false, + ...flags(p), + })), + groupAccessPolicies: ofType(policies, "group").map((p) => ({ + groupId: p.id, + groupName: p.name, + currentUserInGroup: false, + ...flags(p), + })), + }; + const machineAccountViews = ofType(policies, "machineAccount").map((p) => ({ + serviceAccountId: p.id, + serviceAccountName: p.name, + ...flags(p), + })); + const peopleChanged = !samePolicies(people(state.policies), people(policies)); + + switch (state.target) { + case "project": { + if (peopleChanged) { + await this.accessPolicyService.putProjectPeopleAccessPolicies(state.targetId, peopleView); + } + if ( + !samePolicies( + ofType(state.policies, "machineAccount"), + ofType(policies, "machineAccount"), + ) + ) { + await this.accessPolicyService.putProjectServiceAccountsAccessPolicies( + state.organizationId, + state.targetId, + { serviceAccountAccessPolicies: machineAccountViews }, + ); + } + return; + } + case "machine-account": { + if (peopleChanged) { + await this.accessPolicyService.putServiceAccountPeopleAccessPolicies( + state.targetId, + peopleView, + ); + } + if (!samePolicies(ofType(state.policies, "project"), ofType(policies, "project"))) { + await this.accessPolicyService.putServiceAccountGrantedPolicies( + state.organizationId, + state.targetId, + { + grantedProjectPolicies: ofType(policies, "project").map((p) => + Object.assign(new GrantedProjectPolicyPermissionDetailsView(), { + accessPolicy: { grantedProjectId: p.id, grantedProjectName: p.name, ...flags(p) }, + hasPermission: true, + }), + ), + }, + ); + } + return; + } + case "secret": { + if (samePolicies(state.policies, policies)) { + return; + } + const secret = state.secret; + if (!secret.write) { + return Response.noEditPermission(); + } + if ([secret.name, secret.value, secret.note].includes(DECRYPT_ERROR)) { + return Response.error( + "The secret could not be decrypted, so its access cannot be changed.", + ); + } + await this.secretService.update( + state.organizationId, + secret, + { ...peopleView, serviceAccountAccessPolicies: machineAccountViews }, + false, + ); + return; + } + } + } + + private fromPeople(view: { + userAccessPolicies: { + organizationUserId: string; + organizationUserName: string; + read: boolean; + write: boolean; + }[]; + groupAccessPolicies: { groupId: string; groupName: string; read: boolean; write: boolean }[]; + }): SmAccessPolicy[] { + return [ + ...(view.userAccessPolicies ?? []).map((p) => ({ + type: "user" as const, + id: p.organizationUserId, + name: p.organizationUserName, + ...flags(p), + })), + ...(view.groupAccessPolicies ?? []).map((p) => ({ + type: "group" as const, + id: p.groupId, + name: p.groupName, + ...flags(p), + })), + ]; + } + + private fromMachineAccounts( + policies: { + serviceAccountId: string; + serviceAccountName: string; + read: boolean; + write: boolean; + }[], + ): SmAccessPolicy[] { + return (policies ?? []).map((p) => ({ + type: "machineAccount" as const, + id: p.serviceAccountId, + name: p.serviceAccountName, + ...flags(p), + })); + } + + static create(serviceContainer: ServiceContainer) { + return new SmAccessPolicyStore( + serviceContainer.accessPolicyService, + serviceContainer.projectService, + serviceContainer.serviceAccountService, + serviceContainer.secretService, + ); + } +} diff --git a/bitwarden_license/bit-cli/src/secrets-manager/counts/counts.command.spec.ts b/bitwarden_license/bit-cli/src/secrets-manager/counts/counts.command.spec.ts new file mode 100644 index 00000000000..de305e53c9e --- /dev/null +++ b/bitwarden_license/bit-cli/src/secrets-manager/counts/counts.command.spec.ts @@ -0,0 +1,152 @@ +import { mock } from "jest-mock-extended"; + +import { + CountService, + OrganizationCountsResponse, + ProjectService, + ProjectCountsResponse, + ProjectView, + ServiceAccountCountsResponse, + ServiceAccountService, + ServiceAccountView, +} from "@bitwarden/bit-sm"; + +import { smNotFoundError, smOrgId, smOtherOrgId, smOrg } from "../spec/sm-test-utils"; + +import { CountsCommand } from "./counts.command"; + +describe("CountsCommand", () => { + const countService = mock(); + const projectService = mock(); + const serviceAccountService = mock(); + const projectId = "22222222-2222-2222-2222-222222222222"; + const machineAccountId = "33333333-3333-3333-3333-333333333333"; + let command: CountsCommand; + + beforeEach(() => { + jest.clearAllMocks(); + projectService.getByProjectId.mockResolvedValue( + Object.assign(new ProjectView(), { id: projectId, organizationId: smOrgId }), + ); + serviceAccountService.getByServiceAccountId.mockResolvedValue( + Object.assign(new ServiceAccountView(), { id: machineAccountId, organizationId: smOrgId }), + ); + command = new CountsCommand(countService, projectService, serviceAccountService); + }); + + it("returns organization counts by default", async () => { + countService.getOrganizationCounts.mockResolvedValue( + new OrganizationCountsResponse({ Projects: 2, Secrets: 5, ServiceAccounts: 1 }), + ); + + const response = await command.run(smOrg); + + expect(response.success).toBe(true); + expect(response.data).toEqual({ + object: "sm-counts", + scope: "organization", + id: smOrgId, + projects: 2, + secrets: 5, + machineAccounts: 1, + }); + }); + + it("returns project counts", async () => { + countService.getProjectCounts.mockResolvedValue( + new ProjectCountsResponse({ People: 3, Secrets: 4, ServiceAccounts: 2 }), + ); + + const response = await command.run(smOrg, { projectId }); + + expect(response.success).toBe(true); + expect(countService.getProjectCounts).toHaveBeenCalledWith(projectId); + expect(response.data).toMatchObject({ + scope: "project", + id: projectId, + people: 3, + secrets: 4, + machineAccounts: 2, + }); + }); + + it("returns machine account counts", async () => { + countService.getServiceAccountCounts.mockResolvedValue( + new ServiceAccountCountsResponse({ Projects: 1, People: 2, AccessTokens: 3 }), + ); + + const response = await command.run(smOrg, { machineAccountId }); + + expect(response.success).toBe(true); + expect(response.data).toMatchObject({ + scope: "machine-account", + id: machineAccountId, + projects: 1, + people: 2, + accessTokens: 3, + }); + }); + + it("maps a 404 on a project to a friendly error", async () => { + projectService.getByProjectId.mockRejectedValue(smNotFoundError()); + + const response = await command.run(smOrg, { projectId }); + + expect(response.success).toBe(false); + expect(response.message).toBe("The project was not found, or you do not have access to it."); + }); + + it("rejects a project from another organization", async () => { + projectService.getByProjectId.mockResolvedValue( + Object.assign(new ProjectView(), { id: projectId, organizationId: smOtherOrgId }), + ); + + const response = await command.run(smOrg, { projectId }); + + expect(response.success).toBe(false); + expect(response.message).toBe("The project was not found, or you do not have access to it."); + expect(countService.getProjectCounts).not.toHaveBeenCalled(); + }); + + it("rejects a machine account from another organization", async () => { + serviceAccountService.getByServiceAccountId.mockResolvedValue( + Object.assign(new ServiceAccountView(), { + id: machineAccountId, + organizationId: smOtherOrgId, + }), + ); + + const response = await command.run(smOrg, { machineAccountId }); + + expect(response.success).toBe(false); + expect(response.message).toBe( + "The machine account was not found, or you do not have access to it.", + ); + expect(countService.getServiceAccountCounts).not.toHaveBeenCalled(); + }); + + it("rejects both a project and a machine account", async () => { + const response = await command.run(smOrg, { projectId, machineAccountId }); + + expect(response.success).toBe(false); + expect(response.message).toBe("Specify either `projectid` or `machineaccountid`, not both."); + }); + + it("rejects an invalid project id", async () => { + const response = await command.run(smOrg, { projectId: "abc" }); + + expect(response.success).toBe(false); + expect(response.message).toBe("`abc` is not a GUID."); + }); + + it("maps a 404 on a machine account to a friendly error", async () => { + countService.getServiceAccountCounts.mockRejectedValue(smNotFoundError()); + + const response = await command.run(smOrg, { machineAccountId }); + + expect(response.success).toBe(false); + expect(response.message).toBe( + "The machine account was not found, or you do not have access to it.", + ); + }); +}); diff --git a/bitwarden_license/bit-cli/src/secrets-manager/counts/counts.command.ts b/bitwarden_license/bit-cli/src/secrets-manager/counts/counts.command.ts new file mode 100644 index 00000000000..8762400eb99 --- /dev/null +++ b/bitwarden_license/bit-cli/src/secrets-manager/counts/counts.command.ts @@ -0,0 +1,101 @@ +import { CountService, ProjectService, ServiceAccountService } from "@bitwarden/bit-sm"; +import { Response } from "@bitwarden/cli/models/response"; + +import { ServiceContainer } from "../../service-container"; +import { resolveSmMachineAccountId } from "../access-tokens/sm-access-token.utils"; +import { SmCountsResponse } from "../models/sm-counts.response"; +import { + isInSmOrganization, + parseSmId, + SmOrganization, + smErrorResponse, + smNotFoundResponse, +} from "../sm-command.utils"; + +export type CountsOptions = { + projectId?: string; + machineAccountId?: string; +}; + +export class CountsCommand { + constructor( + private countService: CountService, + private projectService: ProjectService, + private serviceAccountService: ServiceAccountService, + ) {} + + async run(org: SmOrganization, options: CountsOptions = {}): Promise { + if (options.projectId != null && options.machineAccountId != null) { + return Response.badRequest("Specify either `projectid` or `machineaccountid`, not both."); + } + + if (options.projectId != null) { + const project = parseSmId(options.projectId, "projectid"); + if (project.error) { + return project.error; + } + try { + const view = await this.projectService.getByProjectId(project.id, true); + if (!isInSmOrganization(view, org)) { + return smNotFoundResponse("project"); + } + const counts = await this.countService.getProjectCounts(project.id); + return Response.success( + new SmCountsResponse("project", project.id, { + secrets: counts.secrets, + people: counts.people, + machineAccounts: counts.serviceAccounts, + }), + ); + } catch (e) { + return smErrorResponse(e, "project"); + } + } + + if (options.machineAccountId != null) { + const machineAccount = await resolveSmMachineAccountId( + this.serviceAccountService, + org.organizationId, + options.machineAccountId, + ); + if (machineAccount.error) { + return machineAccount.error; + } + try { + const counts = await this.countService.getServiceAccountCounts( + machineAccount.machineAccountId, + ); + return Response.success( + new SmCountsResponse("machine-account", machineAccount.machineAccountId, { + projects: counts.projects, + people: counts.people, + accessTokens: counts.accessTokens, + }), + ); + } catch (e) { + return smErrorResponse(e, "machine account"); + } + } + + try { + const counts = await this.countService.getOrganizationCounts(org.organizationId); + return Response.success( + new SmCountsResponse("organization", org.organizationId, { + projects: counts.projects, + secrets: counts.secrets, + machineAccounts: counts.serviceAccounts, + }), + ); + } catch (e) { + return smErrorResponse(e, "organization"); + } + } + + static create(serviceContainer: ServiceContainer) { + return new CountsCommand( + serviceContainer.countService, + serviceContainer.projectService, + serviceContainer.serviceAccountService, + ); + } +} diff --git a/bitwarden_license/bit-cli/src/secrets-manager/events/events.command.spec.ts b/bitwarden_license/bit-cli/src/secrets-manager/events/events.command.spec.ts new file mode 100644 index 00000000000..1172c390d21 --- /dev/null +++ b/bitwarden_license/bit-cli/src/secrets-manager/events/events.command.spec.ts @@ -0,0 +1,129 @@ +import { mock } from "jest-mock-extended"; + +import { + ServiceAccountEventLogApiService, + ServiceAccountService, + ServiceAccountView, +} from "@bitwarden/bit-sm"; +import { ListResponse as CliListResponse } from "@bitwarden/cli/models/response/list.response"; +import { EventResponse, EventType } from "@bitwarden/common/dirt/event-logs"; +import { ListResponse } from "@bitwarden/common/models/response/list.response"; + +import { SmEventResponse } from "../models/sm-event.response"; +import { smNotFoundError, smOrgId, smOtherOrgId, smOrg } from "../spec/sm-test-utils"; + +import { EventsCommand } from "./events.command"; + +describe("EventsCommand", () => { + const eventLogApiService = mock(); + const serviceAccountService = mock(); + const machineAccountId = "22222222-2222-2222-2222-222222222222"; + const secretId = "33333333-3333-3333-3333-333333333333"; + let command: EventsCommand; + + const options = (overrides: Record = {}) => ({ + machineAccountId, + start: "2026-01-01T00:00:00.000Z", + end: "2026-02-01T00:00:00.000Z", + ...overrides, + }); + + const page = (types: EventType[], continuationToken: string | null) => + new ListResponse( + { + Data: types.map((Type) => ({ + Type, + Date: "2026-01-15T00:00:00.000Z", + ServiceAccountId: machineAccountId, + SecretId: secretId, + })), + ContinuationToken: continuationToken, + }, + EventResponse, + ); + + beforeEach(() => { + jest.clearAllMocks(); + serviceAccountService.getByServiceAccountId.mockResolvedValue( + Object.assign(new ServiceAccountView(), { id: machineAccountId, organizationId: smOrgId }), + ); + command = new EventsCommand(eventLogApiService, serviceAccountService); + }); + + it("returns events across all pages", async () => { + eventLogApiService.getEvents + .mockResolvedValueOnce(page([EventType.Secret_Retrieved], "next")) + .mockResolvedValueOnce(page([EventType.Secret_Edited], null)); + + const response = await command.run(smOrg, options()); + + expect(response.success).toBe(true); + expect(eventLogApiService.getEvents).toHaveBeenNthCalledWith( + 1, + machineAccountId, + "2026-01-01T00:00:00.000Z", + "2026-02-01T00:00:00.000Z", + undefined, + ); + expect(eventLogApiService.getEvents).toHaveBeenNthCalledWith( + 2, + machineAccountId, + "2026-01-01T00:00:00.000Z", + "2026-02-01T00:00:00.000Z", + "next", + ); + const data = (response.data as CliListResponse).data as SmEventResponse[]; + expect(data.map((e) => e.typeName)).toEqual(["Secret_Retrieved", "Secret_Edited"]); + expect(data[0]).toMatchObject({ object: "sm-event", machineAccountId, secretId }); + }); + + it("rejects an invalid date", async () => { + const response = await command.run(smOrg, options({ start: "yesterday-ish" })); + + expect(response.success).toBe(false); + expect(response.message).toBe("`yesterday-ish` is not a valid date for `start`."); + expect(eventLogApiService.getEvents).not.toHaveBeenCalled(); + }); + + it("rejects a start date after the end date", async () => { + const response = await command.run(smOrg, options({ start: "2026-03-01", end: "2026-02-01" })); + + expect(response.success).toBe(false); + expect(response.message).toBe("`start` must be before `end`."); + }); + + it("rejects an invalid machine account id", async () => { + const response = await command.run(smOrg, options({ machineAccountId: "abc" })); + + expect(response.success).toBe(false); + expect(response.message).toBe("`abc` is not a GUID."); + }); + + it("rejects a machine account from another organization", async () => { + serviceAccountService.getByServiceAccountId.mockResolvedValue( + Object.assign(new ServiceAccountView(), { + id: machineAccountId, + organizationId: smOtherOrgId, + }), + ); + + const response = await command.run(smOrg, options()); + + expect(response.success).toBe(false); + expect(response.message).toBe( + "The machine account was not found, or you do not have access to it.", + ); + expect(eventLogApiService.getEvents).not.toHaveBeenCalled(); + }); + + it("maps a 404 to a friendly error", async () => { + eventLogApiService.getEvents.mockRejectedValue(smNotFoundError()); + + const response = await command.run(smOrg, options()); + + expect(response.success).toBe(false); + expect(response.message).toBe( + "The machine account was not found, or you do not have access to it.", + ); + }); +}); diff --git a/bitwarden_license/bit-cli/src/secrets-manager/events/events.command.ts b/bitwarden_license/bit-cli/src/secrets-manager/events/events.command.ts new file mode 100644 index 00000000000..46621cb1f3d --- /dev/null +++ b/bitwarden_license/bit-cli/src/secrets-manager/events/events.command.ts @@ -0,0 +1,83 @@ +import { ServiceAccountEventLogApiService, ServiceAccountService } from "@bitwarden/bit-sm"; +import { Response } from "@bitwarden/cli/models/response"; +import { ListResponse } from "@bitwarden/cli/models/response/list.response"; +import { EventResponse } from "@bitwarden/common/dirt/event-logs"; +import { Utils } from "@bitwarden/common/platform/misc/utils"; + +import { ServiceContainer } from "../../service-container"; +import { resolveSmMachineAccountId } from "../access-tokens/sm-access-token.utils"; +import { SmEventResponse } from "../models/sm-event.response"; +import { SmOrganization, smErrorResponse } from "../sm-command.utils"; + +export type EventsOptions = { + machineAccountId: string; + start: string; + end: string; +}; + +export class EventsCommand { + constructor( + private serviceAccountEventLogApiService: ServiceAccountEventLogApiService, + private serviceAccountService: ServiceAccountService, + ) {} + + async run(org: SmOrganization, options: EventsOptions): Promise { + const start = this.parseDate(options.start, "start"); + if (start instanceof Response) { + return start; + } + const end = this.parseDate(options.end, "end"); + if (end instanceof Response) { + return end; + } + if (start > end) { + return Response.badRequest("`start` must be before `end`."); + } + + const machineAccount = await resolveSmMachineAccountId( + this.serviceAccountService, + org.organizationId, + options.machineAccountId, + ); + if (machineAccount.error) { + return machineAccount.error; + } + + try { + const events: EventResponse[] = []; + let continuationToken: string | undefined; + do { + const page = await this.serviceAccountEventLogApiService.getEvents( + machineAccount.machineAccountId, + start.toISOString(), + end.toISOString(), + continuationToken, + ); + events.push(...page.data); + continuationToken = page.continuationToken ?? undefined; + } while (continuationToken); + + return Response.success(new ListResponse(events.map((e) => new SmEventResponse(e)))); + } catch (e) { + return smErrorResponse(e, "machine account"); + } + } + + private parseDate(value: string | undefined, label: string): Date | Response { + if (Utils.isNullOrWhitespace(value)) { + return Response.badRequest("`" + label + "` is required."); + } + const date = new Date(value); + if (isNaN(date.getTime())) { + return Response.badRequest("`" + value + "` is not a valid date for `" + label + "`."); + } + return date; + } + + static create(serviceContainer: ServiceContainer) { + return new EventsCommand( + serviceContainer.serviceAccountEventLogApiService, + serviceContainer.serviceAccountService, + ); + } +} diff --git a/bitwarden_license/bit-cli/src/secrets-manager/grantees/grantees-list.command.spec.ts b/bitwarden_license/bit-cli/src/secrets-manager/grantees/grantees-list.command.spec.ts new file mode 100644 index 00000000000..67993ab7709 --- /dev/null +++ b/bitwarden_license/bit-cli/src/secrets-manager/grantees/grantees-list.command.spec.ts @@ -0,0 +1,86 @@ +import { mock } from "jest-mock-extended"; + +import { AccessPolicyService, PotentialGranteeView } from "@bitwarden/bit-sm"; +import { ListResponse } from "@bitwarden/cli/models/response/list.response"; + +import { SmGranteeResponse } from "../models/sm-grantee.response"; +import { smNotFoundError, smOrgId, smOrg } from "../spec/sm-test-utils"; + +import { GranteesListCommand } from "./grantees-list.command"; + +describe("GranteesListCommand", () => { + const accessPolicyService = mock(); + let command: GranteesListCommand; + + const grantee = (type: string, name: string) => + Object.assign(new PotentialGranteeView(), { + id: "22222222-2222-2222-2222-222222222222", + type, + name, + }); + + beforeEach(() => { + jest.clearAllMocks(); + command = new GranteesListCommand(accessPolicyService); + }); + + it("lists people grantees", async () => { + accessPolicyService.getPeoplePotentialGrantees.mockResolvedValue([ + Object.assign(grantee("user", "Alice"), { email: "alice@example.com" }), + grantee("group", "Engineering"), + ]); + + const response = await command.run(smOrg, "people"); + + expect(response.success).toBe(true); + expect(accessPolicyService.getPeoplePotentialGrantees).toHaveBeenCalledWith(smOrgId); + const data = (response.data as ListResponse).data as SmGranteeResponse[]; + expect(data.map((g) => [g.object, g.type, g.name])).toEqual([ + ["sm-grantee", "user", "Alice"], + ["sm-grantee", "group", "Engineering"], + ]); + }); + + it("lists machine account grantees with the user-facing type name", async () => { + accessPolicyService.getServiceAccountsPotentialGrantees.mockResolvedValue([ + grantee("serviceAccount", "CI runner"), + ]); + + const response = await command.run(smOrg, "machine-accounts"); + + expect(response.success).toBe(true); + const data = (response.data as ListResponse).data as SmGranteeResponse[]; + expect(data[0].type).toBe("machineAccount"); + }); + + it("lists project grantees", async () => { + accessPolicyService.getProjectsPotentialGrantees.mockResolvedValue([ + grantee("project", "Backend"), + ]); + + const response = await command.run(smOrg, "projects"); + + expect(response.success).toBe(true); + expect(accessPolicyService.getProjectsPotentialGrantees).toHaveBeenCalledWith(smOrgId); + }); + + it("rejects an unknown grantee type", async () => { + const response = await command.run(smOrg, "robots"); + + expect(response.success).toBe(false); + expect(response.message).toBe( + "Unknown grantee type `robots`. Expected one of: people, machine-accounts, projects.", + ); + }); + + it("maps a 404 to a friendly error", async () => { + accessPolicyService.getPeoplePotentialGrantees.mockRejectedValue(smNotFoundError()); + + const response = await command.run(smOrg, "people"); + + expect(response.success).toBe(false); + expect(response.message).toBe( + "The organization was not found, or you do not have access to it.", + ); + }); +}); diff --git a/bitwarden_license/bit-cli/src/secrets-manager/grantees/grantees-list.command.ts b/bitwarden_license/bit-cli/src/secrets-manager/grantees/grantees-list.command.ts new file mode 100644 index 00000000000..1b5b5f0c196 --- /dev/null +++ b/bitwarden_license/bit-cli/src/secrets-manager/grantees/grantees-list.command.ts @@ -0,0 +1,44 @@ +import { AccessPolicyService } from "@bitwarden/bit-sm"; +import { Response } from "@bitwarden/cli/models/response"; +import { ListResponse } from "@bitwarden/cli/models/response/list.response"; + +import { ServiceContainer } from "../../service-container"; +import { SmGranteeResponse } from "../models/sm-grantee.response"; +import { SmOrganization, smErrorResponse } from "../sm-command.utils"; + +export const SmGranteeKinds = ["people", "machine-accounts", "projects"] as const; +export type SmGranteeKind = (typeof SmGranteeKinds)[number]; + +export class GranteesListCommand { + constructor(private accessPolicyService: AccessPolicyService) {} + + async run(org: SmOrganization, kind: string): Promise { + if (!SmGranteeKinds.includes(kind as SmGranteeKind)) { + return Response.badRequest( + "Unknown grantee type `" + kind + "`. Expected one of: " + SmGranteeKinds.join(", ") + ".", + ); + } + + try { + const grantees = await this.getGrantees(org.organizationId, kind as SmGranteeKind); + return Response.success(new ListResponse(grantees.map((g) => new SmGranteeResponse(g)))); + } catch (e) { + return smErrorResponse(e, "organization"); + } + } + + private getGrantees(organizationId: string, kind: SmGranteeKind) { + switch (kind) { + case "people": + return this.accessPolicyService.getPeoplePotentialGrantees(organizationId); + case "machine-accounts": + return this.accessPolicyService.getServiceAccountsPotentialGrantees(organizationId); + case "projects": + return this.accessPolicyService.getProjectsPotentialGrantees(organizationId); + } + } + + static create(serviceContainer: ServiceContainer) { + return new GranteesListCommand(serviceContainer.accessPolicyService); + } +} diff --git a/bitwarden_license/bit-cli/src/secrets-manager/index.ts b/bitwarden_license/bit-cli/src/secrets-manager/index.ts new file mode 100644 index 00000000000..8ae4b65655c --- /dev/null +++ b/bitwarden_license/bit-cli/src/secrets-manager/index.ts @@ -0,0 +1 @@ +export * from "./sm.program"; diff --git a/bitwarden_license/bit-cli/src/secrets-manager/machine-accounts/machine-account-create.command.spec.ts b/bitwarden_license/bit-cli/src/secrets-manager/machine-accounts/machine-account-create.command.spec.ts new file mode 100644 index 00000000000..6125ed003f5 --- /dev/null +++ b/bitwarden_license/bit-cli/src/secrets-manager/machine-accounts/machine-account-create.command.spec.ts @@ -0,0 +1,51 @@ +import { mock } from "jest-mock-extended"; + +import { ServiceAccountService, ServiceAccountView } from "@bitwarden/bit-sm"; + +import { encodeSmRequest, smOrgId, smOtherOrgId, smOrg } from "../spec/sm-test-utils"; + +import { MachineAccountCreateCommand } from "./machine-account-create.command"; + +describe("MachineAccountCreateCommand", () => { + const serviceAccountService = mock(); + let command: MachineAccountCreateCommand; + + beforeEach(() => { + jest.clearAllMocks(); + command = new MachineAccountCreateCommand(serviceAccountService); + }); + + it("creates the machine account", async () => { + serviceAccountService.create.mockResolvedValue( + Object.assign(new ServiceAccountView(), { + id: "22222222-2222-2222-2222-222222222222", + organizationId: smOrgId, + name: "CI", + }), + ); + + const response = await command.run(smOrg, encodeSmRequest({ name: "CI" })); + + expect(response.success).toBe(true); + expect(serviceAccountService.create).toHaveBeenCalledWith( + smOrgId, + expect.objectContaining({ organizationId: smOrgId, name: "CI" }), + ); + expect(response.data).toMatchObject({ object: "sm-machine-account", name: "CI" }); + }); + + it("requires a name", async () => { + const response = await command.run(smOrg, {}); + + expect(response.success).toBe(false); + expect(response.message).toBe("`name` is required."); + expect(serviceAccountService.create).not.toHaveBeenCalled(); + }); + + it("rejects a request for another organization", async () => { + const response = await command.run(smOrg, { organizationId: smOtherOrgId, name: "CI" }); + + expect(response.success).toBe(false); + expect(serviceAccountService.create).not.toHaveBeenCalled(); + }); +}); diff --git a/bitwarden_license/bit-cli/src/secrets-manager/machine-accounts/machine-account-create.command.ts b/bitwarden_license/bit-cli/src/secrets-manager/machine-accounts/machine-account-create.command.ts new file mode 100644 index 00000000000..f3ffe329812 --- /dev/null +++ b/bitwarden_license/bit-cli/src/secrets-manager/machine-accounts/machine-account-create.command.ts @@ -0,0 +1,49 @@ +import { ServiceAccountService, ServiceAccountView } from "@bitwarden/bit-sm"; +import { Response } from "@bitwarden/cli/models/response"; + +import { ServiceContainer } from "../../service-container"; +import { SmMachineAccountResponse } from "../models/sm-machine-account.response"; +import { + checkSmRequestOrganization, + parseSmRequest, + readSmName, + SmOrganization, + smErrorResponse, +} from "../sm-command.utils"; + +export class MachineAccountCreateCommand { + constructor(private serviceAccountService: ServiceAccountService) {} + + async run(org: SmOrganization, requestJson: unknown): Promise { + const parsed = await parseSmRequest>(requestJson); + if (parsed.error) { + return parsed.error; + } + const orgMismatch = checkSmRequestOrganization( + org.organizationId, + parsed.request.organizationId, + ); + if (orgMismatch) { + return orgMismatch; + } + const name = readSmName(parsed.request); + if (name.error) { + return name.error; + } + + const view = new ServiceAccountView(); + view.organizationId = org.organizationId; + view.name = name.name!; + + try { + const machineAccount = await this.serviceAccountService.create(org.organizationId, view); + return Response.success(new SmMachineAccountResponse(machineAccount)); + } catch (e) { + return smErrorResponse(e, "organization"); + } + } + + static create(serviceContainer: ServiceContainer) { + return new MachineAccountCreateCommand(serviceContainer.serviceAccountService); + } +} diff --git a/bitwarden_license/bit-cli/src/secrets-manager/machine-accounts/machine-account-delete.command.spec.ts b/bitwarden_license/bit-cli/src/secrets-manager/machine-accounts/machine-account-delete.command.spec.ts new file mode 100644 index 00000000000..0a75c29fe30 --- /dev/null +++ b/bitwarden_license/bit-cli/src/secrets-manager/machine-accounts/machine-account-delete.command.spec.ts @@ -0,0 +1,63 @@ +import { mock } from "jest-mock-extended"; + +import { + BulkOperationStatus, + ServiceAccountSecretsDetailsView, + ServiceAccountService, +} from "@bitwarden/bit-sm"; + +import { smOrgId, smOrg } from "../spec/sm-test-utils"; + +import { MachineAccountDeleteCommand } from "./machine-account-delete.command"; + +describe("MachineAccountDeleteCommand", () => { + const serviceAccountService = mock(); + const machineAccountId = "22222222-2222-2222-2222-222222222222"; + let command: MachineAccountDeleteCommand; + + const machineAccount = Object.assign(new ServiceAccountSecretsDetailsView(), { + id: machineAccountId, + organizationId: smOrgId, + name: "CI", + }); + + beforeEach(() => { + jest.clearAllMocks(); + serviceAccountService.getServiceAccounts.mockResolvedValue([machineAccount]); + command = new MachineAccountDeleteCommand(serviceAccountService); + }); + + it("deletes the machine account", async () => { + serviceAccountService.delete.mockResolvedValue([ + Object.assign(new BulkOperationStatus(), { id: machineAccountId, name: "CI" }), + ]); + + const response = await command.run(smOrg, [machineAccountId]); + + expect(response.success).toBe(true); + expect(serviceAccountService.delete).toHaveBeenCalledWith([machineAccount]); + expect(response.data).toMatchObject({ + data: [{ object: "sm-bulk-status", id: machineAccountId, name: "CI" }], + }); + }); + + it("rejects a machine account that is not in the organization", async () => { + const unknownId = "44444444-4444-4444-4444-444444444444"; + + const response = await command.run(smOrg, [unknownId]); + + expect(response.success).toBe(false); + expect(response.message).toBe( + "The machine account `" + unknownId + "` was not found, or you do not have access to it.", + ); + expect(serviceAccountService.delete).not.toHaveBeenCalled(); + }); + + it("rejects an invalid id", async () => { + const response = await command.run(smOrg, ["nope"]); + + expect(response.success).toBe(false); + expect(response.message).toBe("`nope` is not a GUID."); + expect(serviceAccountService.getServiceAccounts).not.toHaveBeenCalled(); + }); +}); diff --git a/bitwarden_license/bit-cli/src/secrets-manager/machine-accounts/machine-account-delete.command.ts b/bitwarden_license/bit-cli/src/secrets-manager/machine-accounts/machine-account-delete.command.ts new file mode 100644 index 00000000000..65f90c52039 --- /dev/null +++ b/bitwarden_license/bit-cli/src/secrets-manager/machine-accounts/machine-account-delete.command.ts @@ -0,0 +1,45 @@ +import { ServiceAccountService } from "@bitwarden/bit-sm"; +import { Response } from "@bitwarden/cli/models/response"; + +import { ServiceContainer } from "../../service-container"; +import { + parseSmIds, + SmOrganization, + smBulkResponse, + smErrorResponse, + smNotFoundResponse, +} from "../sm-command.utils"; + +export class MachineAccountDeleteCommand { + constructor(private serviceAccountService: ServiceAccountService) {} + + async run(org: SmOrganization, machineAccountIds: string[]): Promise { + const parsed = parseSmIds(machineAccountIds, "machineAccountId"); + if (parsed.error) { + return parsed.error; + } + + try { + const machineAccounts = await this.serviceAccountService.getServiceAccounts( + org.organizationId, + ); + const toDelete = []; + for (const id of parsed.ids) { + const machineAccount = machineAccounts.find((m) => m.id === id); + if (machineAccount == null) { + return smNotFoundResponse("machine account `" + id + "`"); + } + toDelete.push(machineAccount); + } + + const results = await this.serviceAccountService.delete(toDelete); + return smBulkResponse(results, "deleted"); + } catch (e) { + return smErrorResponse(e, "machine account"); + } + } + + static create(serviceContainer: ServiceContainer) { + return new MachineAccountDeleteCommand(serviceContainer.serviceAccountService); + } +} diff --git a/bitwarden_license/bit-cli/src/secrets-manager/machine-accounts/machine-account-edit.command.spec.ts b/bitwarden_license/bit-cli/src/secrets-manager/machine-accounts/machine-account-edit.command.spec.ts new file mode 100644 index 00000000000..51e3f710db1 --- /dev/null +++ b/bitwarden_license/bit-cli/src/secrets-manager/machine-accounts/machine-account-edit.command.spec.ts @@ -0,0 +1,84 @@ +import { mock } from "jest-mock-extended"; + +import { ServiceAccountService, ServiceAccountView } from "@bitwarden/bit-sm"; + +import { + encodeSmRequest, + smNotFoundError, + smOrgId, + smOtherOrgId, + smOrg, +} from "../spec/sm-test-utils"; + +import { MachineAccountEditCommand } from "./machine-account-edit.command"; + +describe("MachineAccountEditCommand", () => { + const serviceAccountService = mock(); + const machineAccountId = "22222222-2222-2222-2222-222222222222"; + let command: MachineAccountEditCommand; + + const makeMachineAccount = (overrides: Partial = {}) => + Object.assign(new ServiceAccountView(), { + id: machineAccountId, + organizationId: smOrgId, + name: "CI", + ...overrides, + }); + + beforeEach(() => { + jest.clearAllMocks(); + command = new MachineAccountEditCommand(serviceAccountService); + }); + + it("renames the machine account", async () => { + serviceAccountService.getByServiceAccountId.mockResolvedValue(makeMachineAccount()); + serviceAccountService.update.mockResolvedValue(makeMachineAccount({ name: "Deploy" })); + + const response = await command.run( + smOrg, + machineAccountId.toUpperCase(), + encodeSmRequest({ name: "Deploy" }), + ); + + expect(response.success).toBe(true); + expect(serviceAccountService.update).toHaveBeenCalledWith( + machineAccountId, + smOrgId, + expect.objectContaining({ id: machineAccountId, name: "Deploy" }), + ); + expect(response.data).toMatchObject({ object: "sm-machine-account", name: "Deploy" }); + }); + + it("treats a machine account from another organization as not found", async () => { + serviceAccountService.getByServiceAccountId.mockResolvedValue( + makeMachineAccount({ organizationId: smOtherOrgId }), + ); + + const response = await command.run(smOrg, machineAccountId, { name: "Deploy" }); + + expect(response.success).toBe(false); + expect(response.message).toBe( + "The machine account was not found, or you do not have access to it.", + ); + expect(serviceAccountService.update).not.toHaveBeenCalled(); + }); + + it("maps a 404 to a friendly error", async () => { + serviceAccountService.getByServiceAccountId.mockRejectedValue(smNotFoundError()); + + const response = await command.run(smOrg, machineAccountId, { name: "Deploy" }); + + expect(response.success).toBe(false); + expect(response.message).toBe( + "The machine account was not found, or you do not have access to it.", + ); + }); + + it("requires a name", async () => { + const response = await command.run(smOrg, machineAccountId, { name: " " }); + + expect(response.success).toBe(false); + expect(response.message).toBe("`name` is required."); + expect(serviceAccountService.getByServiceAccountId).not.toHaveBeenCalled(); + }); +}); diff --git a/bitwarden_license/bit-cli/src/secrets-manager/machine-accounts/machine-account-edit.command.ts b/bitwarden_license/bit-cli/src/secrets-manager/machine-accounts/machine-account-edit.command.ts new file mode 100644 index 00000000000..169d2aa6d9e --- /dev/null +++ b/bitwarden_license/bit-cli/src/secrets-manager/machine-accounts/machine-account-edit.command.ts @@ -0,0 +1,72 @@ +import { ServiceAccountService, ServiceAccountView } from "@bitwarden/bit-sm"; +import { Response } from "@bitwarden/cli/models/response"; + +import { ServiceContainer } from "../../service-container"; +import { SmMachineAccountResponse } from "../models/sm-machine-account.response"; +import { + checkSmRequestOrganization, + parseSmId, + parseSmRequest, + readSmName, + SmOrganization, + smErrorResponse, + smNotFoundResponse, +} from "../sm-command.utils"; + +export class MachineAccountEditCommand { + constructor(private serviceAccountService: ServiceAccountService) {} + + async run( + org: SmOrganization, + machineAccountId: string, + requestJson: unknown, + ): Promise { + const machineAccount = parseSmId(machineAccountId, "machineAccountId"); + if (machineAccount.error) { + return machineAccount.error; + } + const parsed = await parseSmRequest>(requestJson); + if (parsed.error) { + return parsed.error; + } + const orgMismatch = checkSmRequestOrganization( + org.organizationId, + parsed.request.organizationId, + ); + if (orgMismatch) { + return orgMismatch; + } + const name = readSmName(parsed.request); + if (name.error) { + return name.error; + } + + try { + const existing = await this.serviceAccountService.getByServiceAccountId( + machineAccount.id, + org.organizationId, + ); + if (existing.organizationId !== org.organizationId) { + return smNotFoundResponse("machine account"); + } + + const view = new ServiceAccountView(); + view.id = machineAccount.id; + view.organizationId = org.organizationId; + view.name = name.name!; + + const updated = await this.serviceAccountService.update( + machineAccount.id, + org.organizationId, + view, + ); + return Response.success(new SmMachineAccountResponse(updated)); + } catch (e) { + return smErrorResponse(e, "machine account"); + } + } + + static create(serviceContainer: ServiceContainer) { + return new MachineAccountEditCommand(serviceContainer.serviceAccountService); + } +} diff --git a/bitwarden_license/bit-cli/src/secrets-manager/machine-accounts/machine-account-get.command.spec.ts b/bitwarden_license/bit-cli/src/secrets-manager/machine-accounts/machine-account-get.command.spec.ts new file mode 100644 index 00000000000..27674bfc464 --- /dev/null +++ b/bitwarden_license/bit-cli/src/secrets-manager/machine-accounts/machine-account-get.command.spec.ts @@ -0,0 +1,73 @@ +import { mock } from "jest-mock-extended"; + +import { ServiceAccountService, ServiceAccountView } from "@bitwarden/bit-sm"; + +import { smNotFoundError, smOrgId, smOrg, smOtherOrgId } from "../spec/sm-test-utils"; + +import { MachineAccountGetCommand } from "./machine-account-get.command"; + +describe("MachineAccountGetCommand", () => { + const serviceAccountService = mock(); + const machineAccountId = "22222222-2222-2222-2222-222222222222"; + let command: MachineAccountGetCommand; + + const makeMachineAccount = (organizationId = smOrgId) => + Object.assign(new ServiceAccountView(), { + id: machineAccountId, + organizationId, + name: "CI runner", + }); + + beforeEach(() => { + jest.clearAllMocks(); + command = new MachineAccountGetCommand(serviceAccountService); + }); + + it("returns the machine account", async () => { + serviceAccountService.getByServiceAccountId.mockResolvedValue(makeMachineAccount()); + + const response = await command.run(smOrg, machineAccountId); + + expect(response.success).toBe(true); + expect(serviceAccountService.getByServiceAccountId).toHaveBeenCalledWith( + machineAccountId, + smOrgId, + ); + expect(response.data).toMatchObject({ + object: "sm-machine-account", + id: machineAccountId, + name: "CI runner", + }); + expect(response.data).not.toHaveProperty("accessToSecrets"); + }); + + it("returns not found for a machine account from another organization", async () => { + serviceAccountService.getByServiceAccountId.mockResolvedValue(makeMachineAccount(smOtherOrgId)); + + const response = await command.run(smOrg, machineAccountId); + + expect(response.success).toBe(false); + expect(response.message).toBe( + "The machine account was not found, or you do not have access to it.", + ); + }); + + it("rejects an invalid machine account id", async () => { + const response = await command.run(smOrg, "abc"); + + expect(response.success).toBe(false); + expect(response.message).toBe("`abc` is not a GUID."); + expect(serviceAccountService.getByServiceAccountId).not.toHaveBeenCalled(); + }); + + it("maps a 404 to a friendly error", async () => { + serviceAccountService.getByServiceAccountId.mockRejectedValue(smNotFoundError()); + + const response = await command.run(smOrg, machineAccountId); + + expect(response.success).toBe(false); + expect(response.message).toBe( + "The machine account was not found, or you do not have access to it.", + ); + }); +}); diff --git a/bitwarden_license/bit-cli/src/secrets-manager/machine-accounts/machine-account-get.command.ts b/bitwarden_license/bit-cli/src/secrets-manager/machine-accounts/machine-account-get.command.ts new file mode 100644 index 00000000000..3dae3a38898 --- /dev/null +++ b/bitwarden_license/bit-cli/src/secrets-manager/machine-accounts/machine-account-get.command.ts @@ -0,0 +1,40 @@ +import { ServiceAccountService } from "@bitwarden/bit-sm"; +import { Response } from "@bitwarden/cli/models/response"; + +import { ServiceContainer } from "../../service-container"; +import { SmMachineAccountResponse } from "../models/sm-machine-account.response"; +import { + isInSmOrganization, + parseSmId, + SmOrganization, + smErrorResponse, + smNotFoundResponse, +} from "../sm-command.utils"; + +export class MachineAccountGetCommand { + constructor(private serviceAccountService: ServiceAccountService) {} + + async run(org: SmOrganization, machineAccountId: string): Promise { + const machineAccount = parseSmId(machineAccountId, "machineAccountId"); + if (machineAccount.error) { + return machineAccount.error; + } + + try { + const view = await this.serviceAccountService.getByServiceAccountId( + machineAccount.id, + org.organizationId, + ); + if (!isInSmOrganization(view, org)) { + return smNotFoundResponse("machine account"); + } + return Response.success(new SmMachineAccountResponse(view)); + } catch (e) { + return smErrorResponse(e, "machine account"); + } + } + + static create(serviceContainer: ServiceContainer) { + return new MachineAccountGetCommand(serviceContainer.serviceAccountService); + } +} diff --git a/bitwarden_license/bit-cli/src/secrets-manager/machine-accounts/machine-account-list.command.spec.ts b/bitwarden_license/bit-cli/src/secrets-manager/machine-accounts/machine-account-list.command.spec.ts new file mode 100644 index 00000000000..662284a8ad8 --- /dev/null +++ b/bitwarden_license/bit-cli/src/secrets-manager/machine-accounts/machine-account-list.command.spec.ts @@ -0,0 +1,51 @@ +import { mock } from "jest-mock-extended"; + +import { ServiceAccountSecretsDetailsView, ServiceAccountService } from "@bitwarden/bit-sm"; +import { ListResponse } from "@bitwarden/cli/models/response/list.response"; + +import { SmMachineAccountResponse } from "../models/sm-machine-account.response"; +import { smNotFoundError, smOrgId, smOrg } from "../spec/sm-test-utils"; + +import { MachineAccountListCommand } from "./machine-account-list.command"; + +describe("MachineAccountListCommand", () => { + const serviceAccountService = mock(); + let command: MachineAccountListCommand; + + beforeEach(() => { + jest.clearAllMocks(); + command = new MachineAccountListCommand(serviceAccountService); + }); + + it("lists the organization's machine accounts", async () => { + const machineAccount = Object.assign(new ServiceAccountSecretsDetailsView(), { + id: "22222222-2222-2222-2222-222222222222", + organizationId: smOrgId, + name: "CI runner", + accessToSecrets: 3, + }); + serviceAccountService.getServiceAccounts.mockResolvedValue([machineAccount]); + + const response = await command.run(smOrg); + + expect(response.success).toBe(true); + expect(serviceAccountService.getServiceAccounts).toHaveBeenCalledWith(smOrgId, true); + const data = (response.data as ListResponse).data as SmMachineAccountResponse[]; + expect(data[0]).toMatchObject({ + object: "sm-machine-account", + name: "CI runner", + accessToSecrets: 3, + }); + }); + + it("maps a 404 to a friendly error", async () => { + serviceAccountService.getServiceAccounts.mockRejectedValue(smNotFoundError()); + + const response = await command.run(smOrg); + + expect(response.success).toBe(false); + expect(response.message).toBe( + "The organization was not found, or you do not have access to it.", + ); + }); +}); diff --git a/bitwarden_license/bit-cli/src/secrets-manager/machine-accounts/machine-account-list.command.ts b/bitwarden_license/bit-cli/src/secrets-manager/machine-accounts/machine-account-list.command.ts new file mode 100644 index 00000000000..1f4c9647623 --- /dev/null +++ b/bitwarden_license/bit-cli/src/secrets-manager/machine-accounts/machine-account-list.command.ts @@ -0,0 +1,29 @@ +import { ServiceAccountService } from "@bitwarden/bit-sm"; +import { Response } from "@bitwarden/cli/models/response"; +import { ListResponse } from "@bitwarden/cli/models/response/list.response"; + +import { ServiceContainer } from "../../service-container"; +import { SmMachineAccountResponse } from "../models/sm-machine-account.response"; +import { SmOrganization, smErrorResponse } from "../sm-command.utils"; + +export class MachineAccountListCommand { + constructor(private serviceAccountService: ServiceAccountService) {} + + async run(org: SmOrganization): Promise { + try { + const machineAccounts = await this.serviceAccountService.getServiceAccounts( + org.organizationId, + true, + ); + return Response.success( + new ListResponse(machineAccounts.map((m) => new SmMachineAccountResponse(m))), + ); + } catch (e) { + return smErrorResponse(e, "organization"); + } + } + + static create(serviceContainer: ServiceContainer) { + return new MachineAccountListCommand(serviceContainer.serviceAccountService); + } +} diff --git a/bitwarden_license/bit-cli/src/secrets-manager/models/sm-access-policy.response.ts b/bitwarden_license/bit-cli/src/secrets-manager/models/sm-access-policy.response.ts new file mode 100644 index 00000000000..68dd117e4ec --- /dev/null +++ b/bitwarden_license/bit-cli/src/secrets-manager/models/sm-access-policy.response.ts @@ -0,0 +1,21 @@ +import { BaseResponse } from "@bitwarden/cli/models/response/base.response"; + +import { SmAccessPermission, SmAccessPolicy, toSmPermission } from "../access/sm-access-policies"; + +import { SmGranteeType } from "./sm-grantee.response"; + +export class SmAccessPolicyResponse implements BaseResponse { + object = "sm-access-policy"; + + type: SmGranteeType; + id: string; + name: string; + permission: SmAccessPermission; + + constructor(policy: SmAccessPolicy) { + this.type = policy.type; + this.id = policy.id; + this.name = policy.name ?? null; + this.permission = toSmPermission(policy); + } +} diff --git a/bitwarden_license/bit-cli/src/secrets-manager/models/sm-access-token.response.ts b/bitwarden_license/bit-cli/src/secrets-manager/models/sm-access-token.response.ts new file mode 100644 index 00000000000..0389c6ecd75 --- /dev/null +++ b/bitwarden_license/bit-cli/src/secrets-manager/models/sm-access-token.response.ts @@ -0,0 +1,51 @@ +import { AccessTokenView } from "@bitwarden/bit-sm"; +import { BaseResponse } from "@bitwarden/cli/models/response/base.response"; + +export class SmAccessTokenResponse implements BaseResponse { + object = "sm-access-token"; + + id: string; + machineAccountId: string; + name: string; + scopes: string[]; + expireAt: Date | null; + creationDate: Date; + revisionDate: Date; + + constructor(machineAccountId: string, accessToken: AccessTokenView) { + this.id = accessToken.id; + this.machineAccountId = machineAccountId; + this.name = accessToken.name; + this.scopes = accessToken.scopes; + this.expireAt = accessToken.expireAt ?? null; + this.creationDate = accessToken.creationDate; + this.revisionDate = accessToken.revisionDate; + } +} + +/** + * The result of creating an access token. `accessToken` is the only copy of the token's secret. + */ +export class SmAccessTokenCreatedResponse implements BaseResponse { + object = "sm-access-token"; + + id: string; + machineAccountId: string; + name: string; + expireAt: Date | null; + accessToken: string; + + constructor( + id: string, + machineAccountId: string, + name: string, + expireAt: Date | null, + accessToken: string, + ) { + this.id = id; + this.machineAccountId = machineAccountId; + this.name = name; + this.expireAt = expireAt; + this.accessToken = accessToken; + } +} diff --git a/bitwarden_license/bit-cli/src/secrets-manager/models/sm-bulk-status.response.ts b/bitwarden_license/bit-cli/src/secrets-manager/models/sm-bulk-status.response.ts new file mode 100644 index 00000000000..c70077ba7f3 --- /dev/null +++ b/bitwarden_license/bit-cli/src/secrets-manager/models/sm-bulk-status.response.ts @@ -0,0 +1,18 @@ +import { BulkOperationStatus } from "@bitwarden/bit-sm"; +import { BaseResponse } from "@bitwarden/cli/models/response/base.response"; + +export class SmBulkStatusResponse implements BaseResponse { + object = "sm-bulk-status"; + + id: string; + name: string; + error?: string; + + constructor(status: BulkOperationStatus) { + this.id = status.id; + this.name = status.name; + if (status.errorMessage) { + this.error = status.errorMessage; + } + } +} diff --git a/bitwarden_license/bit-cli/src/secrets-manager/models/sm-counts.response.ts b/bitwarden_license/bit-cli/src/secrets-manager/models/sm-counts.response.ts new file mode 100644 index 00000000000..a575b985942 --- /dev/null +++ b/bitwarden_license/bit-cli/src/secrets-manager/models/sm-counts.response.ts @@ -0,0 +1,25 @@ +import { BaseResponse } from "@bitwarden/cli/models/response/base.response"; + +export type SmCountsScope = "organization" | "project" | "machine-account"; + +export class SmCountsResponse implements BaseResponse { + object = "sm-counts"; + + scope: SmCountsScope; + id: string; + projects?: number; + secrets?: number; + machineAccounts?: number; + people?: number; + accessTokens?: number; + + constructor( + scope: SmCountsScope, + id: string, + counts: Omit, "object" | "scope" | "id">, + ) { + this.scope = scope; + this.id = id; + Object.assign(this, counts); + } +} diff --git a/bitwarden_license/bit-cli/src/secrets-manager/models/sm-event.response.ts b/bitwarden_license/bit-cli/src/secrets-manager/models/sm-event.response.ts new file mode 100644 index 00000000000..2c4d0f7c101 --- /dev/null +++ b/bitwarden_license/bit-cli/src/secrets-manager/models/sm-event.response.ts @@ -0,0 +1,31 @@ +import { BaseResponse } from "@bitwarden/cli/models/response/base.response"; +import { EventResponse, EventType } from "@bitwarden/common/dirt/event-logs"; +import { DeviceType } from "@bitwarden/common/enums"; + +export class SmEventResponse implements BaseResponse { + object = "sm-event"; + + type: EventType; + typeName: string; + date: string; + actingUserId: string; + machineAccountId: string; + grantedMachineAccountId: string; + secretId: string; + projectId: string; + deviceType: DeviceType; + ipAddress: string; + + constructor(event: EventResponse) { + this.type = event.type; + this.typeName = EventType[event.type]; + this.date = event.date; + this.actingUserId = event.actingUserId; + this.machineAccountId = event.serviceAccountId; + this.grantedMachineAccountId = event.grantedServiceAccountId; + this.secretId = event.secretId; + this.projectId = event.projectId; + this.deviceType = event.deviceType; + this.ipAddress = event.ipAddress; + } +} diff --git a/bitwarden_license/bit-cli/src/secrets-manager/models/sm-export.response.ts b/bitwarden_license/bit-cli/src/secrets-manager/models/sm-export.response.ts new file mode 100644 index 00000000000..1fcd5f7d0dc --- /dev/null +++ b/bitwarden_license/bit-cli/src/secrets-manager/models/sm-export.response.ts @@ -0,0 +1,18 @@ +import { + SecretsManagerExport, + SecretsManagerExportProject, + SecretsManagerExportSecret, +} from "@bitwarden/bit-sm"; +import { BaseResponse } from "@bitwarden/cli/models/response/base.response"; + +export class SmExportResponse implements BaseResponse { + object = "sm-export"; + + projects: SecretsManagerExportProject[]; + secrets: SecretsManagerExportSecret[]; + + constructor(data: SecretsManagerExport) { + this.projects = data.projects; + this.secrets = data.secrets; + } +} diff --git a/bitwarden_license/bit-cli/src/secrets-manager/models/sm-grantee.response.ts b/bitwarden_license/bit-cli/src/secrets-manager/models/sm-grantee.response.ts new file mode 100644 index 00000000000..b2d4a17849c --- /dev/null +++ b/bitwarden_license/bit-cli/src/secrets-manager/models/sm-grantee.response.ts @@ -0,0 +1,31 @@ +import { PotentialGranteeView } from "@bitwarden/bit-sm"; +import { BaseResponse } from "@bitwarden/cli/models/response/base.response"; + +export type SmGranteeType = "user" | "group" | "machineAccount" | "project"; + +/** + * Maps the API's grantee type to the CLI's user-facing name. + */ +export function toSmGranteeType(apiType: string): SmGranteeType { + return apiType === "serviceAccount" ? "machineAccount" : (apiType as SmGranteeType); +} + +export class SmGranteeResponse implements BaseResponse { + object = "sm-grantee"; + + id: string; + type: SmGranteeType; + name: string; + email: string; + currentUser: boolean; + currentUserInGroup: boolean; + + constructor(grantee: PotentialGranteeView) { + this.id = grantee.id; + this.type = toSmGranteeType(grantee.type); + this.name = grantee.name; + this.email = grantee.email; + this.currentUser = grantee.currentUser; + this.currentUserInGroup = grantee.currentUserInGroup; + } +} diff --git a/bitwarden_license/bit-cli/src/secrets-manager/models/sm-machine-account.response.ts b/bitwarden_license/bit-cli/src/secrets-manager/models/sm-machine-account.response.ts new file mode 100644 index 00000000000..e87b9324991 --- /dev/null +++ b/bitwarden_license/bit-cli/src/secrets-manager/models/sm-machine-account.response.ts @@ -0,0 +1,26 @@ +import { ServiceAccountSecretsDetailsView, ServiceAccountView } from "@bitwarden/bit-sm"; +import { BaseResponse } from "@bitwarden/cli/models/response/base.response"; + +export class SmMachineAccountResponse implements BaseResponse { + object = "sm-machine-account"; + + id: string; + organizationId: string; + name: string; + creationDate: string; + revisionDate: string; + accessToSecrets?: number; + decryptionError: boolean; + + constructor(machineAccount: ServiceAccountView | ServiceAccountSecretsDetailsView) { + this.id = machineAccount.id; + this.organizationId = machineAccount.organizationId; + this.name = machineAccount.name; + this.creationDate = machineAccount.creationDate; + this.revisionDate = machineAccount.revisionDate; + if (machineAccount instanceof ServiceAccountSecretsDetailsView) { + this.accessToSecrets = machineAccount.accessToSecrets; + } + this.decryptionError = machineAccount.decryptionError; + } +} diff --git a/bitwarden_license/bit-cli/src/secrets-manager/models/sm-project.response.ts b/bitwarden_license/bit-cli/src/secrets-manager/models/sm-project.response.ts new file mode 100644 index 00000000000..028484df3fb --- /dev/null +++ b/bitwarden_license/bit-cli/src/secrets-manager/models/sm-project.response.ts @@ -0,0 +1,26 @@ +import { ProjectListView, ProjectView } from "@bitwarden/bit-sm"; +import { BaseResponse } from "@bitwarden/cli/models/response/base.response"; + +export class SmProjectResponse implements BaseResponse { + object = "sm-project"; + + id: string; + organizationId: string; + name: string; + creationDate: string; + revisionDate: string; + read: boolean; + write: boolean; + decryptionError: boolean; + + constructor(project: ProjectView | ProjectListView) { + this.id = project.id; + this.organizationId = project.organizationId; + this.name = project.name; + this.creationDate = project.creationDate; + this.revisionDate = project.revisionDate; + this.read = project.read; + this.write = project.write; + this.decryptionError = project.decryptionError; + } +} diff --git a/bitwarden_license/bit-cli/src/secrets-manager/models/sm-secret-version.response.ts b/bitwarden_license/bit-cli/src/secrets-manager/models/sm-secret-version.response.ts new file mode 100644 index 00000000000..76fd7cf4324 --- /dev/null +++ b/bitwarden_license/bit-cli/src/secrets-manager/models/sm-secret-version.response.ts @@ -0,0 +1,20 @@ +import { SecretVersionView } from "@bitwarden/bit-sm"; +import { BaseResponse } from "@bitwarden/cli/models/response/base.response"; + +export class SmSecretVersionResponse implements BaseResponse { + object = "sm-secret-version"; + + id: string; + secretId: string; + value: string; + versionDate: string; + authorName?: string; + + constructor(version: SecretVersionView) { + this.id = version.id; + this.secretId = version.secretId; + this.value = version.value; + this.versionDate = version.versionDate; + this.authorName = version.authorName; + } +} diff --git a/bitwarden_license/bit-cli/src/secrets-manager/models/sm-secret.response.ts b/bitwarden_license/bit-cli/src/secrets-manager/models/sm-secret.response.ts new file mode 100644 index 00000000000..264d5c70329 --- /dev/null +++ b/bitwarden_license/bit-cli/src/secrets-manager/models/sm-secret.response.ts @@ -0,0 +1,46 @@ +import { SecretListView, SecretProjectView, SecretView } from "@bitwarden/bit-sm"; +import { BaseResponse } from "@bitwarden/cli/models/response/base.response"; + +export class SmSecretProjectResponse { + id: string; + name: string; + + constructor(project: SecretProjectView) { + this.id = project.id; + this.name = project.name; + } +} + +/** + * A Secrets Manager secret. `value` and `note` are only present when a single secret is + * fetched; list endpoints return names only. + */ +export class SmSecretResponse implements BaseResponse { + object = "sm-secret"; + + id: string; + organizationId: string; + key: string; + value?: string; + note?: string; + projects: SmSecretProjectResponse[]; + creationDate: string; + revisionDate: string; + read: boolean; + write: boolean; + + constructor(secret: SecretView | SecretListView) { + this.id = secret.id; + this.organizationId = secret.organizationId; + this.key = secret.name; + if (secret instanceof SecretView) { + this.value = secret.value; + this.note = secret.note; + } + this.projects = (secret.projects ?? []).map((p) => new SmSecretProjectResponse(p)); + this.creationDate = secret.creationDate; + this.revisionDate = secret.revisionDate; + this.read = secret.read; + this.write = secret.write; + } +} diff --git a/bitwarden_license/bit-cli/src/secrets-manager/porting/sm-export.command.spec.ts b/bitwarden_license/bit-cli/src/secrets-manager/porting/sm-export.command.spec.ts new file mode 100644 index 00000000000..dc1b73f3167 --- /dev/null +++ b/bitwarden_license/bit-cli/src/secrets-manager/porting/sm-export.command.spec.ts @@ -0,0 +1,233 @@ +import * as fs from "fs"; +import * as os from "os"; +import * as path from "path"; + +import { mock } from "jest-mock-extended"; +import { of } from "rxjs"; + +import { UserDecryptionOptionsServiceAbstraction } from "@bitwarden/auth/common"; +import { SecretsManagerPortingApiService } from "@bitwarden/bit-sm"; +import { AccountService } from "@bitwarden/common/auth/abstractions/account.service"; +import { UserVerificationService } from "@bitwarden/common/auth/abstractions/user-verification/user-verification.service.abstraction"; +import { VerificationType } from "@bitwarden/common/auth/enums/verification-type"; +import { LogService } from "@bitwarden/common/platform/abstractions/log.service"; + +import { + createSmOrg, + mockSmActiveAccount, + smNotFoundError, + smOrgId, + smUserId, +} from "../spec/sm-test-utils"; + +import { SmExportCommand } from "./sm-export.command"; + +describe("SmExportCommand", () => { + const adminOrg = createSmOrg({ isAdmin: true }); + const accountService = mock(); + const portingApiService = mock(); + const userVerificationService = mock(); + const userDecryptionOptionsService = mock(); + const logService = mock(); + const masterPassword = "correct horse battery staple"; + const passwordEnv = "BW_SM_EXPORT_TEST_PASSWORD"; + const exportData = { + projects: [{ id: "p1", name: "Backend" }], + secrets: [{ id: "s1", key: "DB", value: "pw", note: "", projectIds: ["p1"] }], + }; + const exportJson = JSON.stringify(exportData, null, " "); + let command: SmExportCommand; + let tempDir: string; + + beforeEach(() => { + jest.clearAllMocks(); + delete process.env.BW_SERVE; + delete process.env.BW_NOINTERACTION; + process.env[passwordEnv] = masterPassword; + mockSmActiveAccount(accountService); + portingApiService.export.mockResolvedValue(exportJson); + userDecryptionOptionsService.hasMasterPasswordById$.mockReturnValue(of(true)); + userVerificationService.verifyUser.mockResolvedValue(true); + command = new SmExportCommand( + portingApiService, + accountService, + userVerificationService, + userDecryptionOptionsService, + logService, + ); + tempDir = fs.mkdtempSync(path.join(os.tmpdir(), "sm-export-")); + }); + + afterEach(() => { + delete process.env.BW_SERVE; + delete process.env.BW_NOINTERACTION; + delete process.env[passwordEnv]; + fs.rmSync(tempDir, { recursive: true, force: true }); + }); + + it("returns the export JSON when no output is given", async () => { + const response = await command.run(adminOrg, { passwordEnv }); + + expect(response.success).toBe(true); + expect(portingApiService.export).toHaveBeenCalledWith(smOrgId); + expect(response.data).toEqual({ object: "string", data: exportJson }); + }); + + it("writes the export to the output file", async () => { + const output = path.join(tempDir, "export.json"); + + const response = await command.run(adminOrg, { output, passwordEnv }); + + expect(response.success).toBe(true); + expect(response.data).toMatchObject({ object: "message", raw: output }); + expect(fs.readFileSync(output, "utf8")).toBe(exportJson); + }); + + it("uses a default file name when the output is a directory", async () => { + const response = await command.run(adminOrg, { output: tempDir + path.sep, passwordEnv }); + + expect(response.success).toBe(true); + const files = fs.readdirSync(tempDir); + expect(files).toHaveLength(1); + expect(files[0]).toMatch(/^bitwarden_export_\d{14}\.json$/); + }); + + it("returns the export as an object under bw serve", async () => { + process.env.BW_SERVE = "true"; + + const response = await command.run(adminOrg, { + output: path.join(tempDir, "ignored.json"), + password: masterPassword, + }); + + expect(response.success).toBe(true); + expect(response.data).toEqual({ object: "sm-export", ...exportData }); + expect(fs.readdirSync(tempDir)).toHaveLength(0); + }); + + it("rejects users who are not owners or admins", async () => { + const response = await command.run(createSmOrg({ isAdmin: false }), { passwordEnv }); + + expect(response.success).toBe(false); + expect(response.message).toBe( + "Only organization owners and admins can export Secrets Manager data.", + ); + expect(portingApiService.export).not.toHaveBeenCalled(); + }); + + it("maps a 404 to a clear error", async () => { + portingApiService.export.mockRejectedValue(smNotFoundError()); + + const response = await command.run(adminOrg, { passwordEnv }); + + expect(response.success).toBe(false); + expect(response.message).toBe( + "The organization was not found, or you do not have access to it.", + ); + }); + describe("master password re-verification", () => { + it("verifies the master password before fetching the export", async () => { + const response = await command.run(adminOrg, { passwordEnv }); + + expect(response.success).toBe(true); + expect(userDecryptionOptionsService.hasMasterPasswordById$).toHaveBeenCalledWith(smUserId); + expect(userVerificationService.verifyUser).toHaveBeenCalledWith({ + type: VerificationType.MasterPassword, + secret: masterPassword, + }); + expect(userVerificationService.verifyUser.mock.invocationCallOrder[0]).toBeLessThan( + portingApiService.export.mock.invocationCallOrder[0], + ); + }); + + it("reads the master password from a password file", async () => { + const passwordFile = path.join(tempDir, "password.txt"); + fs.writeFileSync(passwordFile, masterPassword + "\n"); + + const response = await command.run(adminOrg, { passwordFile }); + + expect(response.success).toBe(true); + expect(userVerificationService.verifyUser).toHaveBeenCalledWith({ + type: VerificationType.MasterPassword, + secret: masterPassword, + }); + }); + + it("returns an error without the path when the password file cannot be read", async () => { + const passwordFile = path.join(tempDir, "missing.txt"); + + const response = await command.run(adminOrg, { passwordFile }); + + expect(response.success).toBe(false); + expect(response.message).toBe("Could not read the master password file."); + expect(JSON.stringify(response)).not.toContain(passwordFile); + expect(userVerificationService.verifyUser).not.toHaveBeenCalled(); + expect(portingApiService.export).not.toHaveBeenCalled(); + }); + + it("rejects a wrong master password without fetching or echoing it", async () => { + userVerificationService.verifyUser.mockRejectedValue(new Error("Invalid master password.")); + + const response = await command.run(adminOrg, { passwordEnv }); + + expect(response.success).toBe(false); + expect(response.message).toBe("Invalid master password."); + expect(JSON.stringify(response)).not.toContain(masterPassword); + expect(portingApiService.export).not.toHaveBeenCalled(); + }); + + it("rejects a failed verification without fetching", async () => { + userVerificationService.verifyUser.mockResolvedValue(false); + + const response = await command.run(adminOrg, { passwordEnv }); + + expect(response.success).toBe(false); + expect(portingApiService.export).not.toHaveBeenCalled(); + }); + + it("requires a password source when interaction is disabled", async () => { + process.env.BW_NOINTERACTION = "true"; + + const response = await command.run(adminOrg); + + expect(response.success).toBe(false); + expect(response.message).toBe( + "Master password is required. Try again in interactive mode or provide a password file or environment variable.", + ); + expect(userVerificationService.verifyUser).not.toHaveBeenCalled(); + expect(portingApiService.export).not.toHaveBeenCalled(); + }); + + it("requires the password in the request body under bw serve", async () => { + process.env.BW_SERVE = "true"; + + const response = await command.run(adminOrg, { passwordEnv }); + + expect(response.success).toBe(false); + expect(response.message).toBe( + "Master password is required. Provide it as `password` in the request body.", + ); + expect(userVerificationService.verifyUser).not.toHaveBeenCalled(); + expect(portingApiService.export).not.toHaveBeenCalled(); + }); + + it("rejects accounts without a master password", async () => { + userDecryptionOptionsService.hasMasterPasswordById$.mockReturnValue(of(false)); + + const response = await command.run(adminOrg, { passwordEnv }); + + expect(response.success).toBe(false); + expect(response.message).toBe( + "Exporting Secrets Manager data requires a master password. Use the web vault to export.", + ); + expect(userVerificationService.verifyUser).not.toHaveBeenCalled(); + expect(portingApiService.export).not.toHaveBeenCalled(); + }); + + it("does not ask for the master password when the user cannot export", async () => { + await command.run(createSmOrg({ isAdmin: false }), { passwordEnv }); + + expect(userVerificationService.verifyUser).not.toHaveBeenCalled(); + }); + }); +}); diff --git a/bitwarden_license/bit-cli/src/secrets-manager/porting/sm-export.command.ts b/bitwarden_license/bit-cli/src/secrets-manager/porting/sm-export.command.ts new file mode 100644 index 00000000000..baae6c1ba2f --- /dev/null +++ b/bitwarden_license/bit-cli/src/secrets-manager/porting/sm-export.command.ts @@ -0,0 +1,155 @@ +import { firstValueFrom } from "rxjs"; + +import { UserDecryptionOptionsServiceAbstraction } from "@bitwarden/auth/common"; +import { SecretsManagerPortingApiService } from "@bitwarden/bit-sm"; +import { Response } from "@bitwarden/cli/models/response"; +import { MessageResponse } from "@bitwarden/cli/models/response/message.response"; +import { StringResponse } from "@bitwarden/cli/models/response/string.response"; +import { CliUtils } from "@bitwarden/cli/utils"; +import { AccountService } from "@bitwarden/common/auth/abstractions/account.service"; +import { UserVerificationService } from "@bitwarden/common/auth/abstractions/user-verification/user-verification.service.abstraction"; +import { VerificationType } from "@bitwarden/common/auth/enums/verification-type"; +import { getUserId } from "@bitwarden/common/auth/services/account.service"; +import { LogService } from "@bitwarden/common/platform/abstractions/log.service"; +import { Utils } from "@bitwarden/common/platform/misc/utils"; + +import { ServiceContainer } from "../../service-container"; +import { SmExportResponse } from "../models/sm-export.response"; +import { SmOrganization, smErrorResponse } from "../sm-command.utils"; + +export type SmExportOptions = { + output?: string; + /** Master password supplied directly, e.g. in the `bw serve` request body. */ + password?: string; + passwordFile?: string; + passwordEnv?: string; +}; + +export class SmExportCommand { + constructor( + private portingApiService: SecretsManagerPortingApiService, + private accountService: AccountService, + private userVerificationService: UserVerificationService, + private userDecryptionOptionsService: UserDecryptionOptionsServiceAbstraction, + private logService: LogService, + ) {} + + async run(org: SmOrganization, options: SmExportOptions = {}): Promise { + if (!org.organization.isAdmin) { + return Response.error("Only organization owners and admins can export Secrets Manager data."); + } + + const verificationError = await this.verifyMasterPassword(options); + if (verificationError) { + return verificationError; + } + + let exportJson: string; + try { + exportJson = await this.portingApiService.export(org.organizationId); + } catch (e) { + return smErrorResponse(e, "organization"); + } + + // `bw serve` returns the export in the response body rather than writing a file on the host. + if (process.env.BW_SERVE === "true") { + return Response.success(new SmExportResponse(JSON.parse(exportJson))); + } + + if (Utils.isNullOrWhitespace(options.output)) { + return Response.success(new StringResponse(exportJson)); + } + + try { + const filePath = await CliUtils.saveFile(exportJson, options.output, exportFileName()); + const res = new MessageResponse("Saved " + filePath, null); + res.raw = filePath; + return Response.success(res); + } catch (e) { + return Response.error(String(e)); + } + } + + /** + * Re-verifies the master password, as the web vault does before a Secrets Manager export. + * Returns an error response when verification is not possible or fails. + * + * This protects the bulk export only. As in the web vault, individual secret values remain + * readable without re-verification through the secret list and get commands and routes. + */ + private async verifyMasterPassword(options: SmExportOptions): Promise { + const userId = await firstValueFrom(this.accountService.activeAccount$.pipe(getUserId)); + const hasMasterPassword = await firstValueFrom( + this.userDecryptionOptionsService.hasMasterPasswordById$(userId), + ); + if (!hasMasterPassword) { + return Response.badRequest( + "Exporting Secrets Manager data requires a master password. Use the web vault to export.", + ); + } + + let password: string; + if (process.env.BW_SERVE === "true") { + if (Utils.isNullOrEmpty(options.password)) { + return Response.badRequest( + "Master password is required. Provide it as `password` in the request body.", + ); + } + password = options.password; + } else { + let passwordResult: string | Response; + try { + passwordResult = await CliUtils.getPassword( + options.password, + { passwordFile: options.passwordFile, passwordEnv: options.passwordEnv }, + this.logService, + ); + } catch { + return Response.error("Could not read the master password file."); + } + if (passwordResult instanceof Response) { + return passwordResult; + } + password = passwordResult; + } + + try { + const verified = await this.userVerificationService.verifyUser({ + type: VerificationType.MasterPassword, + secret: password, + }); + if (!verified) { + return Response.error("Invalid master password."); + } + } catch (e) { + return Response.error(e instanceof Error ? e.message : "Invalid master password."); + } + return undefined; + } + + static create(serviceContainer: ServiceContainer) { + return new SmExportCommand( + serviceContainer.secretsManagerPortingApiService, + serviceContainer.accountService, + serviceContainer.userVerificationService, + serviceContainer.userDecryptionOptionsService, + serviceContainer.logService, + ); + } +} + +/** + * Matches the file name the web vault uses for Secrets Manager exports. + */ +function exportFileName(): string { + const now = new Date(); + const pad = (n: number) => n.toString().padStart(2, "0"); + const timestamp = + now.getFullYear().toString() + + pad(now.getMonth() + 1) + + pad(now.getDate()) + + pad(now.getHours()) + + pad(now.getMinutes()) + + pad(now.getSeconds()); + return "bitwarden_export_" + timestamp + ".json"; +} diff --git a/bitwarden_license/bit-cli/src/secrets-manager/porting/sm-import.command.spec.ts b/bitwarden_license/bit-cli/src/secrets-manager/porting/sm-import.command.spec.ts new file mode 100644 index 00000000000..3032cfde9d6 --- /dev/null +++ b/bitwarden_license/bit-cli/src/secrets-manager/porting/sm-import.command.spec.ts @@ -0,0 +1,140 @@ +import * as fs from "fs"; +import * as os from "os"; +import * as path from "path"; + +import { mock } from "jest-mock-extended"; + +import { SecretsManagerImportError, SecretsManagerPortingApiService } from "@bitwarden/bit-sm"; + +import { createSmOrg, smOrgId } from "../spec/sm-test-utils"; + +import { SmImportCommand } from "./sm-import.command"; + +describe("SmImportCommand", () => { + const adminOrg = createSmOrg({ isAdmin: true }); + const portingApiService = mock(); + const importData = { + projects: [{ id: "p1", name: "Backend" }], + secrets: [ + { id: "s1", key: "DB", value: "pw", note: "", projectIds: ["p1"] }, + { id: "s2", key: "API", value: "key", note: "n", projectIds: [] }, + ], + }; + let command: SmImportCommand; + let tempDir: string; + + const writeFile = (contents: string) => { + const file = path.join(tempDir, "import.json"); + fs.writeFileSync(file, contents); + return file; + }; + + beforeEach(() => { + jest.clearAllMocks(); + portingApiService.import.mockResolvedValue(); + command = new SmImportCommand(portingApiService); + tempDir = fs.mkdtempSync(path.join(os.tmpdir(), "sm-import-")); + }); + + afterEach(() => { + fs.rmSync(tempDir, { recursive: true, force: true }); + }); + + it("imports the contents of a file", async () => { + const file = writeFile(JSON.stringify(importData)); + + const response = await command.run(adminOrg, { file }); + + expect(response.success).toBe(true); + expect(portingApiService.import).toHaveBeenCalledWith(smOrgId, JSON.stringify(importData)); + expect(response.data).toMatchObject({ + object: "message", + title: "Imported 1 project(s) and 2 secret(s).", + }); + }); + + it("imports data passed by bw serve", async () => { + const response = await command.run(adminOrg, { data: importData }); + + expect(response.success).toBe(true); + expect(portingApiService.import).toHaveBeenCalledWith(smOrgId, JSON.stringify(importData)); + }); + + it("rejects users who are not owners or admins", async () => { + const response = await command.run(createSmOrg({ isAdmin: false }), { data: importData }); + + expect(response.success).toBe(false); + expect(response.message).toBe( + "Only organization owners and admins can import Secrets Manager data.", + ); + expect(portingApiService.import).not.toHaveBeenCalled(); + }); + + it("rejects a missing file", async () => { + const response = await command.run(adminOrg, { file: path.join(tempDir, "missing.json") }); + + expect(response.success).toBe(false); + expect(response.message).toMatch(/^Could not read file: /); + }); + + it("rejects an empty file", async () => { + const response = await command.run(adminOrg, { file: writeFile(" ") }); + + expect(response.success).toBe(false); + expect(response.message).toBe("Import file was empty."); + }); + + it("rejects a file that is not JSON", async () => { + const response = await command.run(adminOrg, { file: writeFile("not json") }); + + expect(response.success).toBe(false); + expect(response.message).toBe("The import file is not valid JSON."); + }); + + it.each([ + [[], "The import data must be a JSON object."], + [{ secrets: [] }, "`projects` must be an array."], + [{ projects: [] }, "`secrets` must be an array."], + [{ projects: [{ id: "p1" }], secrets: [] }, "`projects[0].name` must be a string."], + [ + { projects: [], secrets: [{ id: "s1", key: "k", value: "v", projectIds: [] }] }, + "`secrets[0].note` must be a string.", + ], + [ + { projects: [], secrets: [{ id: "s1", key: "k", value: "v", note: "" }] }, + "`secrets[0].projectIds` must be an array of strings.", + ], + ])("rejects malformed data %j", async (data, message) => { + const response = await command.run(adminOrg, { data }); + + expect(response.success).toBe(false); + expect(response.message).toBe(message); + expect(portingApiService.import).not.toHaveBeenCalled(); + }); + + it("lists each line the server rejected", async () => { + const error = new SecretsManagerImportError(); + error.lines = [ + { id: 2, type: "Secret", key: "API", errorMessage: "The field Key is invalid." }, + ]; + portingApiService.import.mockRejectedValue(error); + + const response = await command.run(adminOrg, { data: importData }); + + expect(response.success).toBe(false); + expect(response.message).toBe( + "The import failed:\n Secret 2 (API): The field Key is invalid.", + ); + }); + + it("returns the server's message when there are no line errors", async () => { + portingApiService.import.mockRejectedValue( + new SecretsManagerImportError("You do not have permission."), + ); + + const response = await command.run(adminOrg, { data: importData }); + + expect(response.success).toBe(false); + expect(response.message).toBe("You do not have permission."); + }); +}); diff --git a/bitwarden_license/bit-cli/src/secrets-manager/porting/sm-import.command.ts b/bitwarden_license/bit-cli/src/secrets-manager/porting/sm-import.command.ts new file mode 100644 index 00000000000..888605436c7 --- /dev/null +++ b/bitwarden_license/bit-cli/src/secrets-manager/porting/sm-import.command.ts @@ -0,0 +1,134 @@ +import { SecretsManagerImportError, SecretsManagerPortingApiService } from "@bitwarden/bit-sm"; +import { Response } from "@bitwarden/cli/models/response"; +import { MessageResponse } from "@bitwarden/cli/models/response/message.response"; +import { CliUtils } from "@bitwarden/cli/utils"; +import { Utils } from "@bitwarden/common/platform/misc/utils"; + +import { ServiceContainer } from "../../service-container"; +import { SmOrganization } from "../sm-command.utils"; + +export type SmImportInput = + { file: string; data?: undefined } | { file?: undefined; data: unknown }; + +type SmImportCounts = { projects: number; secrets: number }; + +export class SmImportCommand { + constructor(private portingApiService: SecretsManagerPortingApiService) {} + + async run(org: SmOrganization, input: SmImportInput): Promise { + if (!org.organization.isAdmin) { + return Response.error("Only organization owners and admins can import Secrets Manager data."); + } + + let data: unknown = input.data; + if (input.file != null) { + let contents: string; + try { + contents = await CliUtils.readFile(input.file); + } catch (e) { + return Response.badRequest("Could not read file: " + String(e)); + } + if (Utils.isNullOrWhitespace(contents)) { + return Response.badRequest("Import file was empty."); + } + try { + data = JSON.parse(contents); + } catch { + return Response.badRequest("The import file is not valid JSON."); + } + } + + const validated = validateImportData(data); + if (validated.error) { + return validated.error; + } + + try { + await this.portingApiService.import(org.organizationId, JSON.stringify(data)); + } catch (e) { + return importErrorResponse(e); + } + + return Response.success( + new MessageResponse( + "Imported " + + validated.counts.projects + + " project(s) and " + + validated.counts.secrets + + " secret(s).", + null, + ), + ); + } + + static create(serviceContainer: ServiceContainer) { + return new SmImportCommand(serviceContainer.secretsManagerPortingApiService); + } +} + +/** + * Checks the shape of a Secrets Manager export before it is encrypted. The porting service + * cannot report which item is malformed, so this names the first offending property. + */ +function validateImportData( + data: unknown, +): { counts: SmImportCounts; error?: undefined } | { counts?: undefined; error: Response } { + if (data == null || typeof data !== "object" || Array.isArray(data)) { + return { error: Response.badRequest("The import data must be a JSON object.") }; + } + const { projects, secrets } = data as Record; + if (!Array.isArray(projects)) { + return { error: Response.badRequest("`projects` must be an array.") }; + } + if (!Array.isArray(secrets)) { + return { error: Response.badRequest("`secrets` must be an array.") }; + } + + for (let i = 0; i < projects.length; i++) { + const error = checkStrings(projects[i], "projects[" + i + "]", ["id", "name"]); + if (error) { + return { error }; + } + } + + for (let i = 0; i < secrets.length; i++) { + const label = "secrets[" + i + "]"; + const error = checkStrings(secrets[i], label, ["id", "key", "value", "note"]); + if (error) { + return { error }; + } + const projectIds = (secrets[i] as Record).projectIds; + if (!Array.isArray(projectIds) || projectIds.some((id) => typeof id !== "string")) { + return { + error: Response.badRequest("`" + label + ".projectIds` must be an array of strings."), + }; + } + } + + return { counts: { projects: projects.length, secrets: secrets.length } }; +} + +function checkStrings(item: unknown, label: string, properties: string[]): Response | undefined { + if (item == null || typeof item !== "object" || Array.isArray(item)) { + return Response.badRequest("`" + label + "` must be an object."); + } + for (const property of properties) { + if (typeof (item as Record)[property] !== "string") { + return Response.badRequest("`" + label + "." + property + "` must be a string."); + } + } + return undefined; +} + +function importErrorResponse(error: unknown): Response { + if (error instanceof SecretsManagerImportError && error.lines?.length > 0) { + const details = error.lines.map( + (line) => " " + line.type + " " + line.id + " (" + line.key + "): " + line.errorMessage, + ); + return Response.badRequest("The import failed:\n" + details.join("\n")); + } + if (error instanceof Error && !Utils.isNullOrWhitespace(error.message)) { + return Response.badRequest(error.message); + } + return Response.error(error); +} diff --git a/bitwarden_license/bit-cli/src/secrets-manager/projects/project-create.command.spec.ts b/bitwarden_license/bit-cli/src/secrets-manager/projects/project-create.command.spec.ts new file mode 100644 index 00000000000..78ec9d037ff --- /dev/null +++ b/bitwarden_license/bit-cli/src/secrets-manager/projects/project-create.command.spec.ts @@ -0,0 +1,79 @@ +import { mock } from "jest-mock-extended"; + +import { ProjectService, ProjectView } from "@bitwarden/bit-sm"; + +import { + encodeSmRequest, + smNotFoundError, + smOrgId, + smOtherOrgId, + smOrg, +} from "../spec/sm-test-utils"; + +import { ProjectCreateCommand } from "./project-create.command"; + +describe("ProjectCreateCommand", () => { + const projectService = mock(); + let command: ProjectCreateCommand; + + beforeEach(() => { + jest.clearAllMocks(); + command = new ProjectCreateCommand(projectService); + }); + + it("creates the project", async () => { + projectService.create.mockResolvedValue( + Object.assign(new ProjectView(), { + id: "22222222-2222-2222-2222-222222222222", + organizationId: smOrgId, + name: "Backend", + }), + ); + + const response = await command.run( + smOrg, + encodeSmRequest({ organizationId: smOrgId, name: "Backend" }), + ); + + expect(response.success).toBe(true); + expect(projectService.create).toHaveBeenCalledWith( + smOrgId, + expect.objectContaining({ organizationId: smOrgId, name: "Backend" }), + ); + expect(response.data).toMatchObject({ object: "sm-project", name: "Backend" }); + }); + + it("accepts an object body", async () => { + projectService.create.mockResolvedValue(new ProjectView()); + + const response = await command.run(smOrg, { name: "Backend" }); + + expect(response.success).toBe(true); + }); + + it("requires a name", async () => { + const response = await command.run(smOrg, { name: "" }); + + expect(response.success).toBe(false); + expect(response.message).toBe("`name` is required."); + expect(projectService.create).not.toHaveBeenCalled(); + }); + + it("rejects a request for another organization", async () => { + const response = await command.run(smOrg, { organizationId: smOtherOrgId, name: "x" }); + + expect(response.success).toBe(false); + expect(projectService.create).not.toHaveBeenCalled(); + }); + + it("maps a 404 to a friendly error", async () => { + projectService.create.mockRejectedValue(smNotFoundError()); + + const response = await command.run(smOrg, { name: "Backend" }); + + expect(response.success).toBe(false); + expect(response.message).toBe( + "The organization was not found, or you do not have access to it.", + ); + }); +}); diff --git a/bitwarden_license/bit-cli/src/secrets-manager/projects/project-create.command.ts b/bitwarden_license/bit-cli/src/secrets-manager/projects/project-create.command.ts new file mode 100644 index 00000000000..66b6be0f63c --- /dev/null +++ b/bitwarden_license/bit-cli/src/secrets-manager/projects/project-create.command.ts @@ -0,0 +1,49 @@ +import { ProjectService, ProjectView } from "@bitwarden/bit-sm"; +import { Response } from "@bitwarden/cli/models/response"; + +import { ServiceContainer } from "../../service-container"; +import { SmProjectResponse } from "../models/sm-project.response"; +import { + checkSmRequestOrganization, + parseSmRequest, + readSmName, + SmOrganization, + smErrorResponse, +} from "../sm-command.utils"; + +export class ProjectCreateCommand { + constructor(private projectService: ProjectService) {} + + async run(org: SmOrganization, requestJson: unknown): Promise { + const parsed = await parseSmRequest>(requestJson); + if (parsed.error) { + return parsed.error; + } + const orgMismatch = checkSmRequestOrganization( + org.organizationId, + parsed.request.organizationId, + ); + if (orgMismatch) { + return orgMismatch; + } + const name = readSmName(parsed.request); + if (name.error) { + return name.error; + } + + const view = new ProjectView(); + view.organizationId = org.organizationId; + view.name = name.name!; + + try { + const project = await this.projectService.create(org.organizationId, view); + return Response.success(new SmProjectResponse(project)); + } catch (e) { + return smErrorResponse(e, "organization"); + } + } + + static create(serviceContainer: ServiceContainer) { + return new ProjectCreateCommand(serviceContainer.projectService); + } +} diff --git a/bitwarden_license/bit-cli/src/secrets-manager/projects/project-delete.command.spec.ts b/bitwarden_license/bit-cli/src/secrets-manager/projects/project-delete.command.spec.ts new file mode 100644 index 00000000000..1321a65f542 --- /dev/null +++ b/bitwarden_license/bit-cli/src/secrets-manager/projects/project-delete.command.spec.ts @@ -0,0 +1,74 @@ +import { mock } from "jest-mock-extended"; + +import { BulkOperationStatus, ProjectListView, ProjectService } from "@bitwarden/bit-sm"; + +import { smOrgId, smOrg } from "../spec/sm-test-utils"; + +import { ProjectDeleteCommand } from "./project-delete.command"; + +describe("ProjectDeleteCommand", () => { + const projectService = mock(); + const firstId = "22222222-2222-2222-2222-222222222222"; + const secondId = "33333333-3333-3333-3333-333333333333"; + let command: ProjectDeleteCommand; + + const projects = [ + Object.assign(new ProjectListView(), { id: firstId, organizationId: smOrgId, name: "One" }), + Object.assign(new ProjectListView(), { id: secondId, organizationId: smOrgId, name: "Two" }), + ]; + const status = (id: string, name: string, errorMessage?: string) => + Object.assign(new BulkOperationStatus(), { id, name, errorMessage }); + + beforeEach(() => { + jest.clearAllMocks(); + projectService.getProjects.mockResolvedValue(projects); + command = new ProjectDeleteCommand(projectService); + }); + + it("deletes several projects", async () => { + projectService.delete.mockResolvedValue([status(firstId, "One"), status(secondId, "Two")]); + + const response = await command.run(smOrg, [firstId, secondId.toUpperCase()]); + + expect(response.success).toBe(true); + expect(projectService.getProjects).toHaveBeenCalledWith(smOrgId); + expect(projectService.delete).toHaveBeenCalledWith(projects); + expect(response.data).toMatchObject({ + object: "list", + data: [ + { object: "sm-bulk-status", id: firstId, name: "One" }, + { object: "sm-bulk-status", id: secondId, name: "Two" }, + ], + }); + }); + + it("reports projects that could not be deleted", async () => { + projectService.delete.mockResolvedValue([status(firstId, "One", "Access denied.")]); + + const response = await command.run(smOrg, [firstId]); + + expect(response.success).toBe(false); + expect(response.message).toBe( + "1 of 1 could not be deleted.\nOne (" + firstId + "): Access denied.", + ); + }); + + it("rejects a project that is not in the organization", async () => { + const unknownId = "44444444-4444-4444-4444-444444444444"; + + const response = await command.run(smOrg, [firstId, unknownId]); + + expect(response.success).toBe(false); + expect(response.message).toBe( + "The project `" + unknownId + "` was not found, or you do not have access to it.", + ); + expect(projectService.delete).not.toHaveBeenCalled(); + }); + + it("requires at least one id", async () => { + const response = await command.run(smOrg, []); + + expect(response.success).toBe(false); + expect(response.message).toBe("At least one `projectId` is required."); + }); +}); diff --git a/bitwarden_license/bit-cli/src/secrets-manager/projects/project-delete.command.ts b/bitwarden_license/bit-cli/src/secrets-manager/projects/project-delete.command.ts new file mode 100644 index 00000000000..8b4b65c0213 --- /dev/null +++ b/bitwarden_license/bit-cli/src/secrets-manager/projects/project-delete.command.ts @@ -0,0 +1,43 @@ +import { ProjectService } from "@bitwarden/bit-sm"; +import { Response } from "@bitwarden/cli/models/response"; + +import { ServiceContainer } from "../../service-container"; +import { + parseSmIds, + SmOrganization, + smBulkResponse, + smErrorResponse, + smNotFoundResponse, +} from "../sm-command.utils"; + +export class ProjectDeleteCommand { + constructor(private projectService: ProjectService) {} + + async run(org: SmOrganization, projectIds: string[]): Promise { + const parsed = parseSmIds(projectIds, "projectId"); + if (parsed.error) { + return parsed.error; + } + + try { + const projects = await this.projectService.getProjects(org.organizationId); + const toDelete = []; + for (const id of parsed.ids) { + const project = projects.find((p) => p.id === id); + if (project == null) { + return smNotFoundResponse("project `" + id + "`"); + } + toDelete.push(project); + } + + const results = await this.projectService.delete(toDelete); + return smBulkResponse(results, "deleted"); + } catch (e) { + return smErrorResponse(e, "project"); + } + } + + static create(serviceContainer: ServiceContainer) { + return new ProjectDeleteCommand(serviceContainer.projectService); + } +} diff --git a/bitwarden_license/bit-cli/src/secrets-manager/projects/project-edit.command.spec.ts b/bitwarden_license/bit-cli/src/secrets-manager/projects/project-edit.command.spec.ts new file mode 100644 index 00000000000..6614c6c2aca --- /dev/null +++ b/bitwarden_license/bit-cli/src/secrets-manager/projects/project-edit.command.spec.ts @@ -0,0 +1,87 @@ +import { mock } from "jest-mock-extended"; + +import { ProjectService, ProjectView } from "@bitwarden/bit-sm"; + +import { + encodeSmRequest, + smNotFoundError, + smOrgId, + smOtherOrgId, + smOrg, +} from "../spec/sm-test-utils"; + +import { ProjectEditCommand } from "./project-edit.command"; + +describe("ProjectEditCommand", () => { + const projectService = mock(); + const projectId = "22222222-2222-2222-2222-222222222222"; + let command: ProjectEditCommand; + + const makeProject = (overrides: Partial = {}) => + Object.assign(new ProjectView(), { + id: projectId, + organizationId: smOrgId, + name: "Backend", + write: true, + ...overrides, + }); + + beforeEach(() => { + jest.clearAllMocks(); + command = new ProjectEditCommand(projectService); + }); + + it("renames the project", async () => { + projectService.getByProjectId.mockResolvedValue(makeProject()); + projectService.update.mockResolvedValue(makeProject({ name: "Frontend" })); + + const response = await command.run( + smOrg, + projectId.toUpperCase(), + encodeSmRequest({ name: "Frontend" }), + ); + + expect(response.success).toBe(true); + expect(projectService.getByProjectId).toHaveBeenCalledWith(projectId, true); + expect(projectService.update).toHaveBeenCalledWith( + smOrgId, + expect.objectContaining({ id: projectId, organizationId: smOrgId, name: "Frontend" }), + ); + expect(response.data).toMatchObject({ object: "sm-project", name: "Frontend" }); + }); + + it("rejects an invalid project id", async () => { + const response = await command.run(smOrg, "abc", { name: "Frontend" }); + + expect(response.success).toBe(false); + expect(response.message).toBe("`abc` is not a GUID."); + }); + + it("treats a project from another organization as not found", async () => { + projectService.getByProjectId.mockResolvedValue(makeProject({ organizationId: smOtherOrgId })); + + const response = await command.run(smOrg, projectId, { name: "Frontend" }); + + expect(response.success).toBe(false); + expect(response.message).toBe("The project was not found, or you do not have access to it."); + expect(projectService.update).not.toHaveBeenCalled(); + }); + + it("rejects a project the user cannot write", async () => { + projectService.getByProjectId.mockResolvedValue(makeProject({ write: false })); + + const response = await command.run(smOrg, projectId, { name: "Frontend" }); + + expect(response.success).toBe(false); + expect(projectService.update).not.toHaveBeenCalled(); + }); + + it("maps a 404 to a friendly error", async () => { + projectService.getByProjectId.mockRejectedValue(smNotFoundError()); + + const response = await command.run(smOrg, projectId, { name: "Frontend" }); + + expect(response.success).toBe(false); + expect(response.message).toBe("The project was not found, or you do not have access to it."); + }); +}); diff --git a/bitwarden_license/bit-cli/src/secrets-manager/projects/project-edit.command.ts b/bitwarden_license/bit-cli/src/secrets-manager/projects/project-edit.command.ts new file mode 100644 index 00000000000..3e80d3c1334 --- /dev/null +++ b/bitwarden_license/bit-cli/src/secrets-manager/projects/project-edit.command.ts @@ -0,0 +1,64 @@ +import { ProjectService, ProjectView } from "@bitwarden/bit-sm"; +import { Response } from "@bitwarden/cli/models/response"; + +import { ServiceContainer } from "../../service-container"; +import { SmProjectResponse } from "../models/sm-project.response"; +import { + checkSmRequestOrganization, + parseSmId, + parseSmRequest, + readSmName, + SmOrganization, + smErrorResponse, + smNotFoundResponse, +} from "../sm-command.utils"; + +export class ProjectEditCommand { + constructor(private projectService: ProjectService) {} + + async run(org: SmOrganization, projectId: string, requestJson: unknown): Promise { + const project = parseSmId(projectId, "projectId"); + if (project.error) { + return project.error; + } + const parsed = await parseSmRequest>(requestJson); + if (parsed.error) { + return parsed.error; + } + const orgMismatch = checkSmRequestOrganization( + org.organizationId, + parsed.request.organizationId, + ); + if (orgMismatch) { + return orgMismatch; + } + const name = readSmName(parsed.request); + if (name.error) { + return name.error; + } + + try { + const existing = await this.projectService.getByProjectId(project.id, true); + if (existing.organizationId !== org.organizationId) { + return smNotFoundResponse("project"); + } + if (!existing.write) { + return Response.noEditPermission(); + } + + const view = new ProjectView(); + view.id = project.id; + view.organizationId = org.organizationId; + view.name = name.name!; + + const updated = await this.projectService.update(org.organizationId, view); + return Response.success(new SmProjectResponse(updated)); + } catch (e) { + return smErrorResponse(e, "project"); + } + } + + static create(serviceContainer: ServiceContainer) { + return new ProjectEditCommand(serviceContainer.projectService); + } +} diff --git a/bitwarden_license/bit-cli/src/secrets-manager/projects/project-get.command.spec.ts b/bitwarden_license/bit-cli/src/secrets-manager/projects/project-get.command.spec.ts new file mode 100644 index 00000000000..e075aec8d45 --- /dev/null +++ b/bitwarden_license/bit-cli/src/secrets-manager/projects/project-get.command.spec.ts @@ -0,0 +1,57 @@ +import { mock } from "jest-mock-extended"; + +import { ProjectService, ProjectView } from "@bitwarden/bit-sm"; + +import { smNotFoundError, smOrgId, smOrg, smOtherOrgId } from "../spec/sm-test-utils"; + +import { ProjectGetCommand } from "./project-get.command"; + +describe("ProjectGetCommand", () => { + const projectService = mock(); + const projectId = "22222222-2222-2222-2222-222222222222"; + let command: ProjectGetCommand; + + const makeProject = (organizationId = smOrgId) => + Object.assign(new ProjectView(), { id: projectId, organizationId, name: "Backend" }); + + beforeEach(() => { + jest.clearAllMocks(); + command = new ProjectGetCommand(projectService); + }); + + it("returns the project", async () => { + projectService.getByProjectId.mockResolvedValue(makeProject()); + + const response = await command.run(smOrg, projectId.toUpperCase()); + + expect(response.success).toBe(true); + expect(projectService.getByProjectId).toHaveBeenCalledWith(projectId, true); + expect(response.data).toMatchObject({ object: "sm-project", id: projectId, name: "Backend" }); + }); + + it("returns not found for a project from another organization", async () => { + projectService.getByProjectId.mockResolvedValue(makeProject(smOtherOrgId)); + + const response = await command.run(smOrg, projectId); + + expect(response.success).toBe(false); + expect(response.message).toBe("The project was not found, or you do not have access to it."); + }); + + it("rejects an invalid project id", async () => { + const response = await command.run(smOrg, "abc"); + + expect(response.success).toBe(false); + expect(response.message).toBe("`abc` is not a GUID."); + expect(projectService.getByProjectId).not.toHaveBeenCalled(); + }); + + it("maps a 404 to a friendly error", async () => { + projectService.getByProjectId.mockRejectedValue(smNotFoundError()); + + const response = await command.run(smOrg, projectId); + + expect(response.success).toBe(false); + expect(response.message).toBe("The project was not found, or you do not have access to it."); + }); +}); diff --git a/bitwarden_license/bit-cli/src/secrets-manager/projects/project-get.command.ts b/bitwarden_license/bit-cli/src/secrets-manager/projects/project-get.command.ts new file mode 100644 index 00000000000..673d36e230c --- /dev/null +++ b/bitwarden_license/bit-cli/src/secrets-manager/projects/project-get.command.ts @@ -0,0 +1,37 @@ +import { ProjectService } from "@bitwarden/bit-sm"; +import { Response } from "@bitwarden/cli/models/response"; + +import { ServiceContainer } from "../../service-container"; +import { SmProjectResponse } from "../models/sm-project.response"; +import { + isInSmOrganization, + parseSmId, + SmOrganization, + smErrorResponse, + smNotFoundResponse, +} from "../sm-command.utils"; + +export class ProjectGetCommand { + constructor(private projectService: ProjectService) {} + + async run(org: SmOrganization, projectId: string): Promise { + const project = parseSmId(projectId, "projectId"); + if (project.error) { + return project.error; + } + + try { + const view = await this.projectService.getByProjectId(project.id, true); + if (!isInSmOrganization(view, org)) { + return smNotFoundResponse("project"); + } + return Response.success(new SmProjectResponse(view)); + } catch (e) { + return smErrorResponse(e, "project"); + } + } + + static create(serviceContainer: ServiceContainer) { + return new ProjectGetCommand(serviceContainer.projectService); + } +} diff --git a/bitwarden_license/bit-cli/src/secrets-manager/projects/project-list.command.spec.ts b/bitwarden_license/bit-cli/src/secrets-manager/projects/project-list.command.spec.ts new file mode 100644 index 00000000000..7173aba8036 --- /dev/null +++ b/bitwarden_license/bit-cli/src/secrets-manager/projects/project-list.command.spec.ts @@ -0,0 +1,49 @@ +import { mock } from "jest-mock-extended"; + +import { ProjectListView, ProjectService } from "@bitwarden/bit-sm"; +import { ListResponse } from "@bitwarden/cli/models/response/list.response"; + +import { SmProjectResponse } from "../models/sm-project.response"; +import { smNotFoundError, smOrgId, smOrg } from "../spec/sm-test-utils"; + +import { ProjectListCommand } from "./project-list.command"; + +describe("ProjectListCommand", () => { + const projectService = mock(); + let command: ProjectListCommand; + + beforeEach(() => { + jest.clearAllMocks(); + command = new ProjectListCommand(projectService); + }); + + it("lists the organization's projects", async () => { + const project = Object.assign(new ProjectListView(), { + id: "22222222-2222-2222-2222-222222222222", + organizationId: smOrgId, + name: "Backend", + read: true, + write: false, + }); + projectService.getProjects.mockResolvedValue([project]); + + const response = await command.run(smOrg); + + expect(response.success).toBe(true); + expect(projectService.getProjects).toHaveBeenCalledWith(smOrgId); + const data = (response.data as ListResponse).data as SmProjectResponse[]; + expect(data).toHaveLength(1); + expect(data[0]).toMatchObject({ object: "sm-project", id: project.id, name: "Backend" }); + }); + + it("maps a 404 to a friendly error", async () => { + projectService.getProjects.mockRejectedValue(smNotFoundError()); + + const response = await command.run(smOrg); + + expect(response.success).toBe(false); + expect(response.message).toBe( + "The organization was not found, or you do not have access to it.", + ); + }); +}); diff --git a/bitwarden_license/bit-cli/src/secrets-manager/projects/project-list.command.ts b/bitwarden_license/bit-cli/src/secrets-manager/projects/project-list.command.ts new file mode 100644 index 00000000000..ddaeb5ba902 --- /dev/null +++ b/bitwarden_license/bit-cli/src/secrets-manager/projects/project-list.command.ts @@ -0,0 +1,24 @@ +import { ProjectService } from "@bitwarden/bit-sm"; +import { Response } from "@bitwarden/cli/models/response"; +import { ListResponse } from "@bitwarden/cli/models/response/list.response"; + +import { ServiceContainer } from "../../service-container"; +import { SmProjectResponse } from "../models/sm-project.response"; +import { SmOrganization, smErrorResponse } from "../sm-command.utils"; + +export class ProjectListCommand { + constructor(private projectService: ProjectService) {} + + async run(org: SmOrganization): Promise { + try { + const projects = await this.projectService.getProjects(org.organizationId); + return Response.success(new ListResponse(projects.map((p) => new SmProjectResponse(p)))); + } catch (e) { + return smErrorResponse(e, "organization"); + } + } + + static create(serviceContainer: ServiceContainer) { + return new ProjectListCommand(serviceContainer.projectService); + } +} diff --git a/bitwarden_license/bit-cli/src/secrets-manager/secrets/secret-create.command.spec.ts b/bitwarden_license/bit-cli/src/secrets-manager/secrets/secret-create.command.spec.ts new file mode 100644 index 00000000000..65b9fc0f3cd --- /dev/null +++ b/bitwarden_license/bit-cli/src/secrets-manager/secrets/secret-create.command.spec.ts @@ -0,0 +1,154 @@ +import { mock } from "jest-mock-extended"; + +import { ProjectService, ProjectView, SecretService, SecretView } from "@bitwarden/bit-sm"; + +import { + encodeSmRequest, + smNotFoundError, + smOrgId, + smOtherOrgId, + smOrg, +} from "../spec/sm-test-utils"; + +import { SecretCreateCommand } from "./secret-create.command"; + +describe("SecretCreateCommand", () => { + const secretService = mock(); + const projectService = mock(); + const projectId = "33333333-3333-3333-3333-333333333333"; + let command: SecretCreateCommand; + + beforeEach(() => { + jest.clearAllMocks(); + secretService.create.mockImplementation(async (_orgId, view) => + Object.assign(new SecretView(), view, { id: "22222222-2222-2222-2222-222222222222" }), + ); + projectService.getByProjectId.mockResolvedValue( + Object.assign(new ProjectView(), { id: projectId, organizationId: smOrgId, name: "Backend" }), + ); + command = new SecretCreateCommand(secretService, projectService); + }); + + it("creates the secret in a project without changing access policies", async () => { + const response = await command.run( + smOrg, + encodeSmRequest({ + organizationId: smOrgId, + key: "DB_PASSWORD", + value: "hunter2", + note: "prod", + projectIds: [projectId.toUpperCase()], + }), + ); + + expect(response.success).toBe(true); + expect(secretService.create).toHaveBeenCalledWith( + smOrgId, + expect.objectContaining({ + organizationId: smOrgId, + name: "DB_PASSWORD", + value: "hunter2", + note: "prod", + projects: [expect.objectContaining({ id: projectId })], + }), + undefined, + ); + expect(response.data).toMatchObject({ + object: "sm-secret", + key: "DB_PASSWORD", + value: "hunter2", + }); + }); + + it("fills in project names the server leaves null", async () => { + const response = await command.run(smOrg, { key: "K", projectIds: [projectId] }); + + expect(projectService.getByProjectId).toHaveBeenCalledWith(projectId, true); + expect(response.data).toMatchObject({ projects: [{ id: projectId, name: "Backend" }] }); + }); + + it("does not look up projects that the response already names", async () => { + secretService.create.mockImplementation(async (_orgId, view) => + Object.assign(new SecretView(), view, { + projects: [{ id: projectId, name: "Backend", decryptionError: false }], + }), + ); + + const response = await command.run(smOrg, { key: "K", projectIds: [projectId] }); + + expect(projectService.getByProjectId).not.toHaveBeenCalled(); + expect(response.data).toMatchObject({ projects: [{ id: projectId, name: "Backend" }] }); + }); + + it("does not use the name of a project from another organization", async () => { + projectService.getByProjectId.mockResolvedValue( + Object.assign(new ProjectView(), { + id: projectId, + organizationId: smOtherOrgId, + name: "Foreign", + }), + ); + + const response = await command.run(smOrg, { key: "K", projectIds: [projectId] }); + + expect(response.data).toMatchObject({ projects: [{ id: projectId, name: null }] }); + }); + + it("defaults the value and note to empty strings", async () => { + await command.run(smOrg, { key: "EMPTY" }); + + expect(secretService.create).toHaveBeenCalledWith( + smOrgId, + expect.objectContaining({ name: "EMPTY", value: "", note: "", projects: [] }), + undefined, + ); + }); + + it("requires a key", async () => { + const response = await command.run(smOrg, { value: "x" }); + + expect(response.success).toBe(false); + expect(response.message).toBe("`key` is required."); + expect(secretService.create).not.toHaveBeenCalled(); + }); + + it("rejects more than one project", async () => { + const response = await command.run(smOrg, { + key: "A", + projectIds: [projectId, "44444444-4444-4444-4444-444444444444"], + }); + + expect(response.success).toBe(false); + expect(response.message).toBe("A secret can only be assigned to one project."); + }); + + it("rejects an invalid project id", async () => { + const response = await command.run(smOrg, { key: "A", projectIds: ["nope"] }); + + expect(response.success).toBe(false); + expect(response.message).toBe("`nope` is not a GUID."); + }); + + it("rejects a non-string value", async () => { + const response = await command.run(smOrg, { key: "A", value: 42 }); + + expect(response.success).toBe(false); + expect(response.message).toBe("`value` must be a string."); + }); + + it("rejects a request for another organization", async () => { + const response = await command.run(smOrg, { organizationId: smOtherOrgId, key: "A" }); + + expect(response.success).toBe(false); + expect(secretService.create).not.toHaveBeenCalled(); + }); + + it("maps a 404 for a project to a friendly error", async () => { + secretService.create.mockRejectedValue(smNotFoundError()); + + const response = await command.run(smOrg, { key: "A", projectIds: [projectId] }); + + expect(response.success).toBe(false); + expect(response.message).toBe("The project was not found, or you do not have access to it."); + }); +}); diff --git a/bitwarden_license/bit-cli/src/secrets-manager/secrets/secret-create.command.ts b/bitwarden_license/bit-cli/src/secrets-manager/secrets/secret-create.command.ts new file mode 100644 index 00000000000..4517b3341fa --- /dev/null +++ b/bitwarden_license/bit-cli/src/secrets-manager/secrets/secret-create.command.ts @@ -0,0 +1,63 @@ +import { ProjectService, SecretProjectView, SecretService, SecretView } from "@bitwarden/bit-sm"; +import { Response } from "@bitwarden/cli/models/response"; + +import { ServiceContainer } from "../../service-container"; +import { SmSecretResponse } from "../models/sm-secret.response"; +import { + checkSmRequestOrganization, + parseSmRequest, + SmOrganization, + smErrorResponse, +} from "../sm-command.utils"; + +import { fillSmSecretProjectNames } from "./sm-secret-project-names"; +import { readSmSecretRequest } from "./sm-secret-request"; + +export class SecretCreateCommand { + constructor( + private secretService: SecretService, + private projectService: ProjectService, + ) {} + + async run(org: SmOrganization, requestJson: unknown): Promise { + const parsed = await parseSmRequest>(requestJson); + if (parsed.error) { + return parsed.error; + } + const orgMismatch = checkSmRequestOrganization( + org.organizationId, + parsed.request.organizationId, + ); + if (orgMismatch) { + return orgMismatch; + } + const secret = readSmSecretRequest(parsed.request); + if (secret.error) { + return secret.error; + } + if (secret.fields.key == null) { + return Response.badRequest("`key` is required."); + } + + const view = new SecretView(); + view.organizationId = org.organizationId; + view.name = secret.fields.key; + view.value = secret.fields.value ?? ""; + view.note = secret.fields.note ?? ""; + view.projects = (secret.fields.projectIds ?? []).map((id) => + Object.assign(new SecretProjectView(), { id }), + ); + + try { + const created = await this.secretService.create(org.organizationId, view, undefined); + await fillSmSecretProjectNames(this.projectService, org, created, view.projects); + return Response.success(new SmSecretResponse(created)); + } catch (e) { + return smErrorResponse(e, view.projects.length > 0 ? "project" : "organization"); + } + } + + static create(serviceContainer: ServiceContainer) { + return new SecretCreateCommand(serviceContainer.secretService, serviceContainer.projectService); + } +} diff --git a/bitwarden_license/bit-cli/src/secrets-manager/secrets/secret-delete.command.spec.ts b/bitwarden_license/bit-cli/src/secrets-manager/secrets/secret-delete.command.spec.ts new file mode 100644 index 00000000000..d930b02c1cb --- /dev/null +++ b/bitwarden_license/bit-cli/src/secrets-manager/secrets/secret-delete.command.spec.ts @@ -0,0 +1,68 @@ +import { mock } from "jest-mock-extended"; + +import { BulkOperationStatus, SecretListView, SecretService } from "@bitwarden/bit-sm"; + +import { smOrgId, smOrg } from "../spec/sm-test-utils"; + +import { SecretDeleteCommand } from "./secret-delete.command"; + +describe("SecretDeleteCommand", () => { + const secretService = mock(); + const firstId = "22222222-2222-2222-2222-222222222222"; + const secondId = "33333333-3333-3333-3333-333333333333"; + let command: SecretDeleteCommand; + + const secrets = [ + Object.assign(new SecretListView(), { id: firstId, organizationId: smOrgId, name: "A" }), + Object.assign(new SecretListView(), { id: secondId, organizationId: smOrgId, name: "B" }), + ]; + const status = (id: string, name: string, errorMessage?: string) => + Object.assign(new BulkOperationStatus(), { id, name, errorMessage }); + + beforeEach(() => { + jest.clearAllMocks(); + secretService.getSecrets.mockResolvedValue(secrets); + command = new SecretDeleteCommand(secretService); + }); + + it("moves several secrets to the trash", async () => { + secretService.delete.mockResolvedValue([status(firstId, "A"), status(secondId, "B")]); + + const response = await command.run(smOrg, [firstId, secondId]); + + expect(response.success).toBe(true); + expect(secretService.delete).toHaveBeenCalledWith(secrets); + expect(response.data).toMatchObject({ + data: [ + { object: "sm-bulk-status", id: firstId }, + { object: "sm-bulk-status", id: secondId }, + ], + }); + }); + + it("reports secrets that could not be deleted", async () => { + secretService.delete.mockResolvedValue([ + status(firstId, "A"), + status(secondId, "B", "Access denied."), + ]); + + const response = await command.run(smOrg, [firstId, secondId]); + + expect(response.success).toBe(false); + expect(response.message).toBe( + "1 of 2 could not be deleted.\nB (" + secondId + "): Access denied.", + ); + }); + + it("rejects a secret that is not in the organization", async () => { + const unknownId = "44444444-4444-4444-4444-444444444444"; + + const response = await command.run(smOrg, [unknownId]); + + expect(response.success).toBe(false); + expect(response.message).toBe( + "The secret `" + unknownId + "` was not found, or you do not have access to it.", + ); + expect(secretService.delete).not.toHaveBeenCalled(); + }); +}); diff --git a/bitwarden_license/bit-cli/src/secrets-manager/secrets/secret-delete.command.ts b/bitwarden_license/bit-cli/src/secrets-manager/secrets/secret-delete.command.ts new file mode 100644 index 00000000000..053bb0ec5c2 --- /dev/null +++ b/bitwarden_license/bit-cli/src/secrets-manager/secrets/secret-delete.command.ts @@ -0,0 +1,43 @@ +import { SecretService } from "@bitwarden/bit-sm"; +import { Response } from "@bitwarden/cli/models/response"; + +import { ServiceContainer } from "../../service-container"; +import { + parseSmIds, + SmOrganization, + smBulkResponse, + smErrorResponse, + smNotFoundResponse, +} from "../sm-command.utils"; + +export class SecretDeleteCommand { + constructor(private secretService: SecretService) {} + + async run(org: SmOrganization, secretIds: string[]): Promise { + const parsed = parseSmIds(secretIds, "secretId"); + if (parsed.error) { + return parsed.error; + } + + try { + const secrets = await this.secretService.getSecrets(org.organizationId); + const toDelete = []; + for (const id of parsed.ids) { + const secret = secrets.find((s) => s.id === id); + if (secret == null) { + return smNotFoundResponse("secret `" + id + "`"); + } + toDelete.push(secret); + } + + const results = await this.secretService.delete(toDelete); + return smBulkResponse(results, "deleted"); + } catch (e) { + return smErrorResponse(e, "secret"); + } + } + + static create(serviceContainer: ServiceContainer) { + return new SecretDeleteCommand(serviceContainer.secretService); + } +} diff --git a/bitwarden_license/bit-cli/src/secrets-manager/secrets/secret-edit.command.spec.ts b/bitwarden_license/bit-cli/src/secrets-manager/secrets/secret-edit.command.spec.ts new file mode 100644 index 00000000000..5446271d216 --- /dev/null +++ b/bitwarden_license/bit-cli/src/secrets-manager/secrets/secret-edit.command.spec.ts @@ -0,0 +1,186 @@ +import { mock } from "jest-mock-extended"; + +import { + SecretProjectView, + ProjectService, + ProjectView, + SecretService, + SecretView, +} from "@bitwarden/bit-sm"; +// eslint-disable-next-line no-restricted-imports +import { DECRYPT_ERROR } from "@bitwarden/legacy-crypto"; + +import { + encodeSmRequest, + smNotFoundError, + smOrgId, + smOtherOrgId, + smOrg, +} from "../spec/sm-test-utils"; + +import { SecretEditCommand } from "./secret-edit.command"; + +describe("SecretEditCommand", () => { + const secretService = mock(); + const projectService = mock(); + const secretId = "22222222-2222-2222-2222-222222222222"; + const projectId = "33333333-3333-3333-3333-333333333333"; + const otherProjectId = "44444444-4444-4444-4444-444444444444"; + let command: SecretEditCommand; + + const makeSecret = (overrides: Partial = {}) => + Object.assign(new SecretView(), { + id: secretId, + organizationId: smOrgId, + name: "DB_PASSWORD", + value: "hunter2", + note: "prod", + projects: [Object.assign(new SecretProjectView(), { id: projectId, name: "Backend" })], + read: true, + write: true, + ...overrides, + }); + + beforeEach(() => { + jest.clearAllMocks(); + secretService.update.mockImplementation(async (_orgId, view) => + Object.assign(new SecretView(), view), + ); + projectService.getByProjectId.mockResolvedValue( + Object.assign(new ProjectView(), { + id: otherProjectId, + organizationId: smOrgId, + name: "Frontend", + }), + ); + command = new SecretEditCommand(secretService, projectService); + }); + + it("changes only the given properties and records a value change", async () => { + secretService.getBySecretId.mockResolvedValue(makeSecret()); + + const response = await command.run( + smOrg, + secretId.toUpperCase(), + encodeSmRequest({ value: "new value" }), + ); + + expect(response.success).toBe(true); + expect(secretService.getBySecretId).toHaveBeenCalledWith(secretId); + expect(secretService.update).toHaveBeenCalledWith( + smOrgId, + expect.objectContaining({ + id: secretId, + name: "DB_PASSWORD", + value: "new value", + note: "prod", + projects: [expect.objectContaining({ id: projectId })], + }), + undefined, + true, + ); + expect(response.data).toMatchObject({ object: "sm-secret", value: "new value" }); + }); + + it("does not record a value change when the value is unchanged", async () => { + secretService.getBySecretId.mockResolvedValue(makeSecret()); + + await command.run(smOrg, secretId, { key: "RENAMED", value: "hunter2" }); + + expect(secretService.update).toHaveBeenCalledWith( + smOrgId, + expect.objectContaining({ name: "RENAMED", value: "hunter2" }), + undefined, + false, + ); + }); + + it("moves the secret to another project, or out of all projects", async () => { + secretService.getBySecretId.mockResolvedValue(makeSecret()); + + await command.run(smOrg, secretId, { projectIds: [otherProjectId] }); + expect(secretService.update).toHaveBeenLastCalledWith( + smOrgId, + expect.objectContaining({ projects: [expect.objectContaining({ id: otherProjectId })] }), + undefined, + false, + ); + + await command.run(smOrg, secretId, { projectIds: [] }); + expect(secretService.update).toHaveBeenLastCalledWith( + smOrgId, + expect.objectContaining({ projects: [] }), + undefined, + false, + ); + }); + + it("keeps the project name when the server omits an unchanged project", async () => { + secretService.getBySecretId.mockResolvedValue(makeSecret()); + secretService.update.mockImplementation(async (_orgId, view) => + Object.assign(new SecretView(), view, { projects: undefined }), + ); + + const response = await command.run(smOrg, secretId, { note: "new" }); + + expect(projectService.getByProjectId).not.toHaveBeenCalled(); + expect(response.data).toMatchObject({ projects: [{ id: projectId, name: "Backend" }] }); + }); + + it("looks up the name of a project the secret is moved to", async () => { + secretService.getBySecretId.mockResolvedValue(makeSecret()); + + const response = await command.run(smOrg, secretId, { projectIds: [otherProjectId] }); + + expect(projectService.getByProjectId).toHaveBeenCalledWith(otherProjectId, true); + expect(response.data).toMatchObject({ projects: [{ id: otherProjectId, name: "Frontend" }] }); + }); + + it("rejects a secret the user cannot write", async () => { + secretService.getBySecretId.mockResolvedValue(makeSecret({ write: false })); + + const response = await command.run(smOrg, secretId, { value: "x" }); + + expect(response.success).toBe(false); + expect(secretService.update).not.toHaveBeenCalled(); + }); + + it("refuses to write back a value that could not be decrypted", async () => { + secretService.getBySecretId.mockResolvedValue(makeSecret({ note: DECRYPT_ERROR })); + + const response = await command.run(smOrg, secretId, { value: "x" }); + + expect(response.success).toBe(false); + expect(response.message).toBe( + "The secret's note could not be decrypted. Provide new values for them in the request.", + ); + expect(secretService.update).not.toHaveBeenCalled(); + }); + + it("treats a secret from another organization as not found", async () => { + secretService.getBySecretId.mockResolvedValue(makeSecret({ organizationId: smOtherOrgId })); + + const response = await command.run(smOrg, secretId, { value: "x" }); + + expect(response.success).toBe(false); + expect(response.message).toBe("The secret was not found, or you do not have access to it."); + expect(secretService.update).not.toHaveBeenCalled(); + }); + + it("maps a 404 to a friendly error", async () => { + secretService.getBySecretId.mockRejectedValue(smNotFoundError()); + + const response = await command.run(smOrg, secretId, { value: "x" }); + + expect(response.success).toBe(false); + expect(response.message).toBe("The secret was not found, or you do not have access to it."); + }); + + it("rejects an empty key", async () => { + const response = await command.run(smOrg, secretId, { key: "" }); + + expect(response.success).toBe(false); + expect(response.message).toBe("`key` cannot be empty."); + expect(secretService.getBySecretId).not.toHaveBeenCalled(); + }); +}); diff --git a/bitwarden_license/bit-cli/src/secrets-manager/secrets/secret-edit.command.ts b/bitwarden_license/bit-cli/src/secrets-manager/secrets/secret-edit.command.ts new file mode 100644 index 00000000000..a3b7f15dee6 --- /dev/null +++ b/bitwarden_license/bit-cli/src/secrets-manager/secrets/secret-edit.command.ts @@ -0,0 +1,99 @@ +import { ProjectService, SecretProjectView, SecretService, SecretView } from "@bitwarden/bit-sm"; +import { Response } from "@bitwarden/cli/models/response"; +// eslint-disable-next-line no-restricted-imports +import { DECRYPT_ERROR } from "@bitwarden/legacy-crypto"; + +import { ServiceContainer } from "../../service-container"; +import { SmSecretResponse } from "../models/sm-secret.response"; +import { + checkSmRequestOrganization, + parseSmId, + parseSmRequest, + SmOrganization, + smErrorResponse, + smNotFoundResponse, +} from "../sm-command.utils"; + +import { fillSmSecretProjectNames } from "./sm-secret-project-names"; +import { readSmSecretRequest } from "./sm-secret-request"; + +/** + * Edits a secret. Properties missing from the request keep their current values, and the + * secret's access policies are left unchanged. + */ +export class SecretEditCommand { + constructor( + private secretService: SecretService, + private projectService: ProjectService, + ) {} + + async run(org: SmOrganization, secretId: string, requestJson: unknown): Promise { + const secret = parseSmId(secretId, "secretId"); + if (secret.error) { + return secret.error; + } + const parsed = await parseSmRequest>(requestJson); + if (parsed.error) { + return parsed.error; + } + const orgMismatch = checkSmRequestOrganization( + org.organizationId, + parsed.request.organizationId, + ); + if (orgMismatch) { + return orgMismatch; + } + const fields = readSmSecretRequest(parsed.request); + if (fields.error) { + return fields.error; + } + + try { + const existing = await this.secretService.getBySecretId(secret.id); + if (existing.organizationId !== org.organizationId) { + return smNotFoundResponse("secret"); + } + if (!existing.write) { + return Response.noEditPermission(); + } + const undecryptable = (["key", "value", "note"] as const).filter( + (property) => + fields.fields[property] == null && + existing[property === "key" ? "name" : property] === DECRYPT_ERROR, + ); + if (undecryptable.length > 0) { + return Response.error( + "The secret's " + + undecryptable.join(", ") + + " could not be decrypted. Provide new values for them in the request.", + ); + } + + const view = new SecretView(); + view.id = secret.id; + view.organizationId = org.organizationId; + view.name = fields.fields.key ?? existing.name; + view.value = fields.fields.value ?? existing.value; + view.note = fields.fields.note ?? existing.note; + view.projects = + fields.fields.projectIds != null + ? fields.fields.projectIds.map((id) => Object.assign(new SecretProjectView(), { id })) + : (existing.projects ?? []); + + const updated = await this.secretService.update( + org.organizationId, + view, + undefined, + view.value !== existing.value, + ); + await fillSmSecretProjectNames(this.projectService, org, updated, view.projects); + return Response.success(new SmSecretResponse(updated)); + } catch (e) { + return smErrorResponse(e, "secret"); + } + } + + static create(serviceContainer: ServiceContainer) { + return new SecretEditCommand(serviceContainer.secretService, serviceContainer.projectService); + } +} diff --git a/bitwarden_license/bit-cli/src/secrets-manager/secrets/secret-get.command.spec.ts b/bitwarden_license/bit-cli/src/secrets-manager/secrets/secret-get.command.spec.ts new file mode 100644 index 00000000000..e084dc795dd --- /dev/null +++ b/bitwarden_license/bit-cli/src/secrets-manager/secrets/secret-get.command.spec.ts @@ -0,0 +1,70 @@ +import { mock } from "jest-mock-extended"; + +import { SecretService, SecretView } from "@bitwarden/bit-sm"; + +import { smNotFoundError, smOrgId, smOrg, smOtherOrgId } from "../spec/sm-test-utils"; + +import { SecretGetCommand } from "./secret-get.command"; + +describe("SecretGetCommand", () => { + const secretService = mock(); + const secretId = "22222222-2222-2222-2222-222222222222"; + let command: SecretGetCommand; + + const makeSecret = (organizationId = smOrgId) => + Object.assign(new SecretView(), { + id: secretId, + organizationId, + name: "DB_PASSWORD", + value: "hunter2", + note: "rotate monthly", + projects: [], + }); + + beforeEach(() => { + jest.clearAllMocks(); + command = new SecretGetCommand(secretService); + }); + + it("returns the secret with its value", async () => { + secretService.getBySecretId.mockResolvedValue(makeSecret()); + + const response = await command.run(smOrg, secretId); + + expect(response.success).toBe(true); + expect(secretService.getBySecretId).toHaveBeenCalledWith(secretId); + expect(response.data).toMatchObject({ + object: "sm-secret", + id: secretId, + key: "DB_PASSWORD", + value: "hunter2", + note: "rotate monthly", + }); + }); + + it("returns not found for a secret from another organization", async () => { + secretService.getBySecretId.mockResolvedValue(makeSecret(smOtherOrgId)); + + const response = await command.run(smOrg, secretId); + + expect(response.success).toBe(false); + expect(response.message).toBe("The secret was not found, or you do not have access to it."); + }); + + it("rejects an invalid secret id", async () => { + const response = await command.run(smOrg, "abc"); + + expect(response.success).toBe(false); + expect(response.message).toBe("`abc` is not a GUID."); + expect(secretService.getBySecretId).not.toHaveBeenCalled(); + }); + + it("maps a 404 to a friendly error", async () => { + secretService.getBySecretId.mockRejectedValue(smNotFoundError()); + + const response = await command.run(smOrg, secretId); + + expect(response.success).toBe(false); + expect(response.message).toBe("The secret was not found, or you do not have access to it."); + }); +}); diff --git a/bitwarden_license/bit-cli/src/secrets-manager/secrets/secret-get.command.ts b/bitwarden_license/bit-cli/src/secrets-manager/secrets/secret-get.command.ts new file mode 100644 index 00000000000..d1c411562b1 --- /dev/null +++ b/bitwarden_license/bit-cli/src/secrets-manager/secrets/secret-get.command.ts @@ -0,0 +1,37 @@ +import { SecretService } from "@bitwarden/bit-sm"; +import { Response } from "@bitwarden/cli/models/response"; + +import { ServiceContainer } from "../../service-container"; +import { SmSecretResponse } from "../models/sm-secret.response"; +import { + isInSmOrganization, + parseSmId, + SmOrganization, + smErrorResponse, + smNotFoundResponse, +} from "../sm-command.utils"; + +export class SecretGetCommand { + constructor(private secretService: SecretService) {} + + async run(org: SmOrganization, secretId: string): Promise { + const secret = parseSmId(secretId, "secretId"); + if (secret.error) { + return secret.error; + } + + try { + const view = await this.secretService.getBySecretId(secret.id); + if (!isInSmOrganization(view, org)) { + return smNotFoundResponse("secret"); + } + return Response.success(new SmSecretResponse(view)); + } catch (e) { + return smErrorResponse(e, "secret"); + } + } + + static create(serviceContainer: ServiceContainer) { + return new SecretGetCommand(serviceContainer.secretService); + } +} diff --git a/bitwarden_license/bit-cli/src/secrets-manager/secrets/secret-list.command.spec.ts b/bitwarden_license/bit-cli/src/secrets-manager/secrets/secret-list.command.spec.ts new file mode 100644 index 00000000000..056105e7fdb --- /dev/null +++ b/bitwarden_license/bit-cli/src/secrets-manager/secrets/secret-list.command.spec.ts @@ -0,0 +1,86 @@ +import { mock } from "jest-mock-extended"; + +import { ProjectService, ProjectView, SecretListView, SecretService } from "@bitwarden/bit-sm"; +import { ListResponse } from "@bitwarden/cli/models/response/list.response"; + +import { SmSecretResponse } from "../models/sm-secret.response"; +import { smNotFoundError, smOrgId, smOrg, smOtherOrgId } from "../spec/sm-test-utils"; + +import { SecretListCommand } from "./secret-list.command"; + +describe("SecretListCommand", () => { + const secretService = mock(); + const projectService = mock(); + const projectId = "33333333-3333-3333-3333-333333333333"; + let command: SecretListCommand; + + const secret = Object.assign(new SecretListView(), { + id: "22222222-2222-2222-2222-222222222222", + organizationId: smOrgId, + name: "DB_PASSWORD", + projects: [{ id: projectId, name: "Backend", decryptionError: false }], + }); + + beforeEach(() => { + jest.clearAllMocks(); + projectService.getByProjectId.mockResolvedValue( + Object.assign(new ProjectView(), { id: projectId, organizationId: smOrgId }), + ); + command = new SecretListCommand(secretService, projectService); + }); + + it("lists the organization's secrets without values", async () => { + secretService.getSecrets.mockResolvedValue([secret]); + + const response = await command.run(smOrg); + + expect(response.success).toBe(true); + expect(secretService.getSecrets).toHaveBeenCalledWith(smOrgId); + const data = (response.data as ListResponse).data as SmSecretResponse[]; + expect(data[0]).toMatchObject({ + object: "sm-secret", + key: "DB_PASSWORD", + projects: [{ id: projectId, name: "Backend" }], + }); + expect(data[0].value).toBeUndefined(); + }); + + it("lists a project's secrets when a project id is given", async () => { + secretService.getSecretsByProject.mockResolvedValue([secret]); + + const response = await command.run(smOrg, projectId); + + expect(response.success).toBe(true); + expect(secretService.getSecretsByProject).toHaveBeenCalledWith(smOrgId, projectId); + expect(secretService.getSecrets).not.toHaveBeenCalled(); + }); + + it("returns not found for a project from another organization, even when empty", async () => { + projectService.getByProjectId.mockResolvedValue( + Object.assign(new ProjectView(), { id: projectId, organizationId: smOtherOrgId }), + ); + secretService.getSecretsByProject.mockResolvedValue([]); + + const response = await command.run(smOrg, projectId); + + expect(response.success).toBe(false); + expect(response.message).toBe("The project was not found, or you do not have access to it."); + expect(secretService.getSecretsByProject).not.toHaveBeenCalled(); + }); + + it("rejects an invalid project id", async () => { + const response = await command.run(smOrg, "abc"); + + expect(response.success).toBe(false); + expect(response.message).toBe("`abc` is not a GUID."); + }); + + it("maps a 404 on a project to a friendly error", async () => { + projectService.getByProjectId.mockRejectedValue(smNotFoundError()); + + const response = await command.run(smOrg, projectId); + + expect(response.success).toBe(false); + expect(response.message).toBe("The project was not found, or you do not have access to it."); + }); +}); diff --git a/bitwarden_license/bit-cli/src/secrets-manager/secrets/secret-list.command.ts b/bitwarden_license/bit-cli/src/secrets-manager/secrets/secret-list.command.ts new file mode 100644 index 00000000000..e9596ea67be --- /dev/null +++ b/bitwarden_license/bit-cli/src/secrets-manager/secrets/secret-list.command.ts @@ -0,0 +1,51 @@ +import { ProjectService, SecretService } from "@bitwarden/bit-sm"; +import { Response } from "@bitwarden/cli/models/response"; +import { ListResponse } from "@bitwarden/cli/models/response/list.response"; + +import { ServiceContainer } from "../../service-container"; +import { SmSecretResponse } from "../models/sm-secret.response"; +import { + isInSmOrganization, + parseSmId, + SmOrganization, + smErrorResponse, + smNotFoundResponse, +} from "../sm-command.utils"; + +export class SecretListCommand { + constructor( + private secretService: SecretService, + private projectService: ProjectService, + ) {} + + async run(org: SmOrganization, projectId?: string): Promise { + let parsedProjectId: string | undefined; + if (projectId != null) { + const project = parseSmId(projectId, "projectid"); + if (project.error) { + return project.error; + } + parsedProjectId = project.id; + } + + try { + if (parsedProjectId != null) { + const view = await this.projectService.getByProjectId(parsedProjectId, true); + if (!isInSmOrganization(view, org)) { + return smNotFoundResponse("project"); + } + } + const secrets = + parsedProjectId != null + ? await this.secretService.getSecretsByProject(org.organizationId, parsedProjectId) + : await this.secretService.getSecrets(org.organizationId); + return Response.success(new ListResponse(secrets.map((s) => new SmSecretResponse(s)))); + } catch (e) { + return smErrorResponse(e, parsedProjectId != null ? "project" : "organization"); + } + } + + static create(serviceContainer: ServiceContainer) { + return new SecretListCommand(serviceContainer.secretService, serviceContainer.projectService); + } +} diff --git a/bitwarden_license/bit-cli/src/secrets-manager/secrets/secret-restore-version.command.spec.ts b/bitwarden_license/bit-cli/src/secrets-manager/secrets/secret-restore-version.command.spec.ts new file mode 100644 index 00000000000..f1cffbd2f46 --- /dev/null +++ b/bitwarden_license/bit-cli/src/secrets-manager/secrets/secret-restore-version.command.spec.ts @@ -0,0 +1,79 @@ +import { mock } from "jest-mock-extended"; + +import { SecretService, SecretView } from "@bitwarden/bit-sm"; + +import { smNotFoundError, smOrgId, smOtherOrgId, smOrg } from "../spec/sm-test-utils"; + +import { SecretRestoreVersionCommand } from "./secret-restore-version.command"; + +describe("SecretRestoreVersionCommand", () => { + const secretService = mock(); + const secretId = "22222222-2222-2222-2222-222222222222"; + const versionId = "33333333-3333-3333-3333-333333333333"; + let command: SecretRestoreVersionCommand; + + const makeSecret = (overrides: Partial = {}) => + Object.assign(new SecretView(), { + id: secretId, + organizationId: smOrgId, + name: "DB_PASSWORD", + value: "current", + write: true, + ...overrides, + }); + + beforeEach(() => { + jest.clearAllMocks(); + command = new SecretRestoreVersionCommand(secretService); + }); + + it("restores the version", async () => { + secretService.getBySecretId.mockResolvedValue(makeSecret()); + secretService.restoreVersion.mockResolvedValue(makeSecret({ value: "old value" })); + + const response = await command.run(smOrg, secretId, versionId.toUpperCase()); + + expect(response.success).toBe(true); + expect(secretService.restoreVersion).toHaveBeenCalledWith(secretId, versionId); + expect(response.data).toMatchObject({ object: "sm-secret", value: "old value" }); + }); + + it("rejects an invalid version id", async () => { + const response = await command.run(smOrg, secretId, "nope"); + + expect(response.success).toBe(false); + expect(response.message).toBe("`nope` is not a GUID."); + expect(secretService.getBySecretId).not.toHaveBeenCalled(); + }); + + it("rejects a secret the user cannot write", async () => { + secretService.getBySecretId.mockResolvedValue(makeSecret({ write: false })); + + const response = await command.run(smOrg, secretId, versionId); + + expect(response.success).toBe(false); + expect(secretService.restoreVersion).not.toHaveBeenCalled(); + }); + + it("treats a secret from another organization as not found", async () => { + secretService.getBySecretId.mockResolvedValue(makeSecret({ organizationId: smOtherOrgId })); + + const response = await command.run(smOrg, secretId, versionId); + + expect(response.success).toBe(false); + expect(response.message).toBe("The secret was not found, or you do not have access to it."); + expect(secretService.restoreVersion).not.toHaveBeenCalled(); + }); + + it("maps a 404 from the restore to a missing version", async () => { + secretService.getBySecretId.mockResolvedValue(makeSecret()); + secretService.restoreVersion.mockRejectedValue(smNotFoundError()); + + const response = await command.run(smOrg, secretId, versionId); + + expect(response.success).toBe(false); + expect(response.message).toBe( + "The secret version was not found, or you do not have access to it.", + ); + }); +}); diff --git a/bitwarden_license/bit-cli/src/secrets-manager/secrets/secret-restore-version.command.ts b/bitwarden_license/bit-cli/src/secrets-manager/secrets/secret-restore-version.command.ts new file mode 100644 index 00000000000..f277c031dcb --- /dev/null +++ b/bitwarden_license/bit-cli/src/secrets-manager/secrets/secret-restore-version.command.ts @@ -0,0 +1,49 @@ +import { SecretService } from "@bitwarden/bit-sm"; +import { Response } from "@bitwarden/cli/models/response"; + +import { ServiceContainer } from "../../service-container"; +import { SmSecretResponse } from "../models/sm-secret.response"; +import { + parseSmId, + SmOrganization, + smErrorResponse, + smNotFoundResponse, +} from "../sm-command.utils"; + +export class SecretRestoreVersionCommand { + constructor(private secretService: SecretService) {} + + async run(org: SmOrganization, secretId: string, versionId: string): Promise { + const secret = parseSmId(secretId, "secretId"); + if (secret.error) { + return secret.error; + } + const version = parseSmId(versionId, "versionId"); + if (version.error) { + return version.error; + } + + try { + const existing = await this.secretService.getBySecretId(secret.id); + if (existing.organizationId !== org.organizationId) { + return smNotFoundResponse("secret"); + } + if (!existing.write) { + return Response.noEditPermission(); + } + } catch (e) { + return smErrorResponse(e, "secret"); + } + + try { + const restored = await this.secretService.restoreVersion(secret.id, version.id); + return Response.success(new SmSecretResponse(restored)); + } catch (e) { + return smErrorResponse(e, "secret version"); + } + } + + static create(serviceContainer: ServiceContainer) { + return new SecretRestoreVersionCommand(serviceContainer.secretService); + } +} diff --git a/bitwarden_license/bit-cli/src/secrets-manager/secrets/secret-versions.command.spec.ts b/bitwarden_license/bit-cli/src/secrets-manager/secrets/secret-versions.command.spec.ts new file mode 100644 index 00000000000..3c5a5929876 --- /dev/null +++ b/bitwarden_license/bit-cli/src/secrets-manager/secrets/secret-versions.command.spec.ts @@ -0,0 +1,89 @@ +import { mock } from "jest-mock-extended"; + +import { + SecretService, + SecretVersionService, + SecretVersionView, + SecretView, +} from "@bitwarden/bit-sm"; + +import { smNotFoundError, smOrgId, smOrg, smOtherOrgId } from "../spec/sm-test-utils"; + +import { SecretVersionsCommand } from "./secret-versions.command"; + +describe("SecretVersionsCommand", () => { + const secretService = mock(); + const secretVersionService = mock(); + const secretId = "22222222-2222-2222-2222-222222222222"; + const versionId = "33333333-3333-3333-3333-333333333333"; + let command: SecretVersionsCommand; + + beforeEach(() => { + jest.clearAllMocks(); + secretService.getBySecretId.mockResolvedValue( + Object.assign(new SecretView(), { id: secretId, organizationId: smOrgId }), + ); + command = new SecretVersionsCommand(secretService, secretVersionService); + }); + + it("lists the previous values", async () => { + secretVersionService.getSecretVersions.mockResolvedValue({ + currentValueDate: "2026-02-01T00:00:00Z", + versions: [ + new SecretVersionView({ + id: versionId, + secretId, + value: "old value", + versionDate: "2026-01-01T00:00:00Z", + authorName: "Alice", + }), + ], + }); + + const response = await command.run(smOrg, secretId.toUpperCase()); + + expect(response.success).toBe(true); + expect(secretVersionService.getSecretVersions).toHaveBeenCalledWith(smOrgId, secretId); + expect(response.data).toMatchObject({ + object: "list", + data: [ + { + object: "sm-secret-version", + id: versionId, + secretId, + value: "old value", + versionDate: "2026-01-01T00:00:00Z", + authorName: "Alice", + }, + ], + }); + }); + + it("returns not found for a secret from another organization", async () => { + secretService.getBySecretId.mockResolvedValue( + Object.assign(new SecretView(), { id: secretId, organizationId: smOtherOrgId }), + ); + + const response = await command.run(smOrg, secretId); + + expect(response.success).toBe(false); + expect(response.message).toBe("The secret was not found, or you do not have access to it."); + expect(secretVersionService.getSecretVersions).not.toHaveBeenCalled(); + }); + + it("maps a 404 to a friendly error", async () => { + secretService.getBySecretId.mockRejectedValue(smNotFoundError()); + + const response = await command.run(smOrg, secretId); + + expect(response.success).toBe(false); + expect(response.message).toBe("The secret was not found, or you do not have access to it."); + }); + + it("rejects an invalid secret id", async () => { + const response = await command.run(smOrg, "nope"); + + expect(response.success).toBe(false); + expect(response.message).toBe("`nope` is not a GUID."); + }); +}); diff --git a/bitwarden_license/bit-cli/src/secrets-manager/secrets/secret-versions.command.ts b/bitwarden_license/bit-cli/src/secrets-manager/secrets/secret-versions.command.ts new file mode 100644 index 00000000000..739bb8c5eec --- /dev/null +++ b/bitwarden_license/bit-cli/src/secrets-manager/secrets/secret-versions.command.ts @@ -0,0 +1,53 @@ +import { SecretService, SecretVersionService } from "@bitwarden/bit-sm"; +import { Response } from "@bitwarden/cli/models/response"; +import { ListResponse } from "@bitwarden/cli/models/response/list.response"; + +import { ServiceContainer } from "../../service-container"; +import { SmSecretVersionResponse } from "../models/sm-secret-version.response"; +import { + isInSmOrganization, + parseSmId, + SmOrganization, + smErrorResponse, + smNotFoundResponse, +} from "../sm-command.utils"; + +/** + * Lists the previous values of a secret, newest first. The current value is not included. + */ +export class SecretVersionsCommand { + constructor( + private secretService: SecretService, + private secretVersionService: SecretVersionService, + ) {} + + async run(org: SmOrganization, secretId: string): Promise { + const secret = parseSmId(secretId, "secretId"); + if (secret.error) { + return secret.error; + } + + try { + const existing = await this.secretService.getBySecretId(secret.id); + if (!isInSmOrganization(existing, org)) { + return smNotFoundResponse("secret"); + } + const history = await this.secretVersionService.getSecretVersions( + org.organizationId, + secret.id, + ); + return Response.success( + new ListResponse(history.versions.map((v) => new SmSecretVersionResponse(v))), + ); + } catch (e) { + return smErrorResponse(e, "secret"); + } + } + + static create(serviceContainer: ServiceContainer) { + return new SecretVersionsCommand( + serviceContainer.secretService, + serviceContainer.secretVersionService, + ); + } +} diff --git a/bitwarden_license/bit-cli/src/secrets-manager/secrets/sm-secret-project-names.ts b/bitwarden_license/bit-cli/src/secrets-manager/secrets/sm-secret-project-names.ts new file mode 100644 index 00000000000..8af79be343f --- /dev/null +++ b/bitwarden_license/bit-cli/src/secrets-manager/secrets/sm-secret-project-names.ts @@ -0,0 +1,47 @@ +import { ProjectService, SecretProjectView, SecretView } from "@bitwarden/bit-sm"; + +import { isInSmOrganization, SmOrganization } from "../sm-command.utils"; + +/** + * The server returns a created or edited secret's projects without names, or omits them when + * unchanged. Names come from the request view when it has them, otherwise from a project lookup + * limited to the organization. A project that can't be resolved keeps a null name. + */ +export async function fillSmSecretProjectNames( + projectService: ProjectService, + org: SmOrganization, + result: SecretView, + requested: SecretProjectView[], +): Promise { + const known = new Map(); + for (const p of [...(requested ?? []), ...(result.projects ?? [])]) { + if (p.name) { + known.set(p.id, p.name); + } + } + const ids = requested.map((p) => p.id); + if (ids.every((id) => known.has(id))) { + result.projects = ids.map((id) => + Object.assign(new SecretProjectView(), { id, name: known.get(id) }), + ); + return; + } + + await Promise.all( + ids + .filter((id) => !known.has(id)) + .map(async (id) => { + try { + const project = await projectService.getByProjectId(id, true); + if (isInSmOrganization(project, org) && project.name) { + known.set(id, project.name); + } + } catch { + // the secret is already saved, so an unresolved name is not an error + } + }), + ); + result.projects = ids.map((id) => + Object.assign(new SecretProjectView(), { id, name: known.get(id) ?? null }), + ); +} diff --git a/bitwarden_license/bit-cli/src/secrets-manager/secrets/sm-secret-request.ts b/bitwarden_license/bit-cli/src/secrets-manager/secrets/sm-secret-request.ts new file mode 100644 index 00000000000..61ea9c20620 --- /dev/null +++ b/bitwarden_license/bit-cli/src/secrets-manager/secrets/sm-secret-request.ts @@ -0,0 +1,54 @@ +import { Response } from "@bitwarden/cli/models/response"; +import { Utils } from "@bitwarden/common/platform/misc/utils"; + +import { parseSmId, readSmString } from "../sm-command.utils"; + +export type SmSecretRequestFields = { + key?: string; + value?: string; + note?: string; + projectIds?: string[]; +}; + +/** + * Reads and validates the secret properties present in a request body. Properties that are + * absent are left undefined so edits can keep the existing values. + */ +export function readSmSecretRequest( + request: Record, +): { fields: SmSecretRequestFields; error?: undefined } | { fields?: undefined; error: Response } { + const fields: SmSecretRequestFields = {}; + for (const property of ["key", "value", "note"] as const) { + const read = readSmString(request, property); + if (read.error) { + return { error: read.error }; + } + fields[property] = read.value; + } + if (fields.key !== undefined && Utils.isNullOrWhitespace(fields.key)) { + return { error: Response.badRequest("`key` cannot be empty.") }; + } + + const projectIds = request.projectIds; + if (projectIds !== undefined && projectIds !== null) { + if (!Array.isArray(projectIds)) { + return { error: Response.badRequest("`projectIds` must be an array of project ids.") }; + } + if (projectIds.length > 1) { + return { error: Response.badRequest("A secret can only be assigned to one project.") }; + } + fields.projectIds = []; + for (const projectId of projectIds) { + if (typeof projectId !== "string") { + return { error: Response.badRequest("`projectIds` must be an array of project ids.") }; + } + const parsed = parseSmId(projectId, "projectIds"); + if (parsed.error) { + return { error: parsed.error }; + } + fields.projectIds.push(parsed.id); + } + } + + return { fields }; +} diff --git a/bitwarden_license/bit-cli/src/secrets-manager/sm-command.utils.spec.ts b/bitwarden_license/bit-cli/src/secrets-manager/sm-command.utils.spec.ts new file mode 100644 index 00000000000..97798a64b85 --- /dev/null +++ b/bitwarden_license/bit-cli/src/secrets-manager/sm-command.utils.spec.ts @@ -0,0 +1,313 @@ +import { mock } from "jest-mock-extended"; +import { of } from "rxjs"; + +import { BulkOperationStatus } from "@bitwarden/bit-sm"; +import { Response } from "@bitwarden/cli/models/response"; +import { CliUtils } from "@bitwarden/cli/utils"; +import { OrganizationService } from "@bitwarden/common/admin-console/abstractions/organization/organization.service.abstraction"; +import { AccountService } from "@bitwarden/common/auth/abstractions/account.service"; +import { ErrorResponse } from "@bitwarden/common/models/response/error.response"; + +import { + checkSmRequestOrganization, + isInSmOrganization, + parseSmId, + parseSmIds, + parseSmRequest, + readSmName, + validateSmOrganizationAccess, + smBulkResponse, + smErrorResponse, + withSmOrganization, +} from "./sm-command.utils"; +import { + encodeSmRequest, + mockSmOrganization, + smNotFoundError, + smOrg, + smOrgId, + smOtherOrgId, +} from "./spec/sm-test-utils"; + +describe("sm-command.utils", () => { + const accountService = mock(); + const organizationService = mock(); + + beforeEach(() => { + jest.clearAllMocks(); + mockSmOrganization(accountService, organizationService); + }); + + describe("isInSmOrganization", () => { + const org = smOrg; + + it("matches the organization id case-insensitively", () => { + expect(isInSmOrganization({ organizationId: smOrgId.toUpperCase() }, org)).toBe(true); + }); + + it("rejects another organization or a missing id", () => { + expect(isInSmOrganization({ organizationId: smOtherOrgId }, org)).toBe(false); + expect(isInSmOrganization({}, org)).toBe(false); + }); + }); + + describe("parseSmId", () => { + it("lowercases a valid GUID", () => { + expect(parseSmId(smOrgId.toUpperCase(), "id")).toEqual({ id: smOrgId }); + }); + + it("rejects a missing id", () => { + expect(parseSmId("", "projectid").error?.message).toBe("`projectid` is required."); + }); + + it("rejects a non-GUID", () => { + expect(parseSmId("nope", "id").error?.message).toBe("`nope` is not a GUID."); + }); + }); + + describe("parseSmIds", () => { + it("lowercases and de-duplicates ids", () => { + expect(parseSmIds([smOrgId.toUpperCase(), smOrgId], "id")).toEqual({ ids: [smOrgId] }); + }); + + it("rejects an empty list", () => { + expect(parseSmIds([], "secretId").error?.message).toBe( + "At least one `secretId` is required.", + ); + }); + + it("rejects a non-GUID in the list", () => { + expect(parseSmIds([smOrgId, "nope"], "id").error?.message).toBe("`nope` is not a GUID."); + }); + }); + + describe("parseSmRequest", () => { + afterEach(() => { + delete process.env.BW_SERVE; + jest.restoreAllMocks(); + }); + + it("decodes a base64 JSON argument", async () => { + const result = await parseSmRequest(encodeSmRequest({ name: "Backend" })); + expect(result).toEqual({ request: { name: "Backend" } }); + }); + + it("accepts an object body from bw serve", async () => { + const result = await parseSmRequest({ name: "Backend" }); + expect(result).toEqual({ request: { name: "Backend" } }); + }); + + it("reads stdin when no argument is given", async () => { + jest.spyOn(CliUtils, "readStdin").mockResolvedValue(encodeSmRequest({ name: "Backend" })); + const result = await parseSmRequest(undefined); + expect(result).toEqual({ request: { name: "Backend" } }); + }); + + it("does not read stdin under bw serve", async () => { + process.env.BW_SERVE = "true"; + const readStdin = jest.spyOn(CliUtils, "readStdin"); + const result = await parseSmRequest(undefined); + expect(readStdin).not.toHaveBeenCalled(); + expect(result.error?.message).toBe("`requestJson` was not provided."); + }); + + it("rejects data that is not encoded JSON", async () => { + const result = await parseSmRequest("not base64 json"); + expect(result.error?.message).toBe("Error parsing the encoded request data."); + }); + + it("rejects JSON that is not an object", async () => { + const result = await parseSmRequest(encodeSmRequest(["a"])); + expect(result.error?.message).toBe("The request data must be a JSON object."); + }); + }); + + describe("checkSmRequestOrganization", () => { + it("allows a missing or matching organization id", () => { + expect(checkSmRequestOrganization(smOrgId, undefined)).toBeUndefined(); + expect(checkSmRequestOrganization(smOrgId, smOrgId.toUpperCase())).toBeUndefined(); + }); + + it("treats a whitespace-only organization id as missing", () => { + expect(checkSmRequestOrganization(smOrgId, " ")).toBeUndefined(); + }); + + it("rejects a different organization id", () => { + expect(checkSmRequestOrganization(smOrgId, smOtherOrgId)?.message).toBe( + "The request's `organizationId` property does not match the organization id.", + ); + }); + }); + + describe("readSmName", () => { + it("returns the name", () => { + expect(readSmName({ name: "Backend" })).toEqual({ name: "Backend" }); + }); + + it("rejects a blank or missing name", () => { + expect(readSmName({ name: " " }).error?.message).toBe("`name` is required."); + expect(readSmName({}).error?.message).toBe("`name` is required."); + }); + + it("rejects a non-string name", () => { + expect(readSmName({ name: 5 }).error?.message).toBe("`name` must be a string."); + }); + }); + + describe("smBulkResponse", () => { + const status = (id: string, name: string, errorMessage?: string) => + Object.assign(new BulkOperationStatus(), { id, name, errorMessage }); + + it("lists the results when every item succeeded", () => { + const response = smBulkResponse([status("a", "One"), status("b", "Two", "")], "deleted"); + + expect(response.success).toBe(true); + expect(response.data).toMatchObject({ + object: "list", + data: [ + { object: "sm-bulk-status", id: "a", name: "One" }, + { object: "sm-bulk-status", id: "b", name: "Two" }, + ], + }); + }); + + it("fails and names each item that failed", () => { + const response = smBulkResponse( + [status("a", "One"), status("b", "Two", "Access denied.")], + "deleted", + ); + + expect(response.success).toBe(false); + expect(response.message).toBe("1 of 2 could not be deleted.\nTwo (b): Access denied."); + }); + }); + + describe("validateSmOrganizationAccess", () => { + it("returns the normalized organization id and the organization", async () => { + const result = await validateSmOrganizationAccess( + organizationService, + accountService, + smOrgId.toUpperCase(), + ); + expect(result).toEqual({ + organizationId: smOrgId, + organization: expect.objectContaining({ id: smOrgId }), + }); + }); + + it("rejects an invalid organization id", async () => { + const result = await validateSmOrganizationAccess(organizationService, accountService, "bad"); + expect(result.error?.message).toBe("`bad` is not a GUID."); + }); + + it("rejects when there is no active user", async () => { + accountService.activeAccount$ = of(null); + const result = await validateSmOrganizationAccess( + organizationService, + accountService, + smOrgId, + ); + expect(result.error?.message).toBe("No user found."); + }); + + it("rejects an organization the user is not a member of", async () => { + const result = await validateSmOrganizationAccess( + organizationService, + accountService, + smOtherOrgId, + ); + expect(result.error?.message).toBe("Organization not found."); + }); + + it("rejects an organization without Secrets Manager access", async () => { + mockSmOrganization(accountService, organizationService, false); + const result = await validateSmOrganizationAccess( + organizationService, + accountService, + smOrgId, + ); + expect(result.error?.message).toBe( + "You do not have access to Secrets Manager for this organization.", + ); + }); + }); + + describe("withSmOrganization", () => { + const services = { organizationService, accountService }; + + it("runs the action with the validated organization", async () => { + const action = jest.fn().mockResolvedValue(Response.success(undefined)); + + const response = await withSmOrganization(services, smOrgId.toUpperCase(), action); + + expect(response.success).toBe(true); + expect(action).toHaveBeenCalledWith( + expect.objectContaining({ + organizationId: smOrgId, + organization: expect.objectContaining({ id: smOrgId }), + }), + ); + }); + + it.each([ + ["rejects an invalid organization id", "bad", "`bad` is not a GUID."], + ["rejects a missing organization id", "", "`organizationid` is required."], + [ + "rejects an organization the user is not a member of", + smOtherOrgId, + "Organization not found.", + ], + ])("%s without running the action", async (_name, organizationId, message) => { + const action = jest.fn(); + + const response = await withSmOrganization(services, organizationId, action); + + expect(response.success).toBe(false); + expect(response.message).toBe(message); + expect(action).not.toHaveBeenCalled(); + }); + + it("rejects when there is no active user without running the action", async () => { + accountService.activeAccount$ = of(null); + const action = jest.fn(); + + const response = await withSmOrganization(services, smOrgId, action); + + expect(response.message).toBe("No user found."); + expect(action).not.toHaveBeenCalled(); + }); + + it("rejects an organization without Secrets Manager access without running the action", async () => { + mockSmOrganization(accountService, organizationService, false); + const action = jest.fn(); + + const response = await withSmOrganization(services, smOrgId, action); + + expect(response.message).toBe( + "You do not have access to Secrets Manager for this organization.", + ); + expect(action).not.toHaveBeenCalled(); + }); + + it("returns the response of the action", async () => { + const failure = Response.error("Nope."); + + const response = await withSmOrganization(services, smOrgId, async () => failure); + + expect(response).toBe(failure); + }); + }); + + describe("smErrorResponse", () => { + it("maps a 404 to a not-found message", () => { + expect(smErrorResponse(smNotFoundError(), "project").message).toBe( + "The project was not found, or you do not have access to it.", + ); + }); + + it("passes other API errors through", () => { + const error = new ErrorResponse({ Message: "Bad things." }, 400); + expect(smErrorResponse(error, "project").message).toBe("Bad things."); + }); + }); +}); diff --git a/bitwarden_license/bit-cli/src/secrets-manager/sm-command.utils.ts b/bitwarden_license/bit-cli/src/secrets-manager/sm-command.utils.ts new file mode 100644 index 00000000000..451a65fa4ab --- /dev/null +++ b/bitwarden_license/bit-cli/src/secrets-manager/sm-command.utils.ts @@ -0,0 +1,257 @@ +import { firstValueFrom, map } from "rxjs"; + +import { BulkOperationStatus } from "@bitwarden/bit-sm"; +import { Response } from "@bitwarden/cli/models/response"; +import { ListResponse } from "@bitwarden/cli/models/response/list.response"; +import { CliUtils } from "@bitwarden/cli/utils"; +import { OrganizationService } from "@bitwarden/common/admin-console/abstractions/organization/organization.service.abstraction"; +import { Organization } from "@bitwarden/common/admin-console/models/domain/organization"; +import { AccountService } from "@bitwarden/common/auth/abstractions/account.service"; +import { ErrorResponse } from "@bitwarden/common/models/response/error.response"; +import { Utils } from "@bitwarden/common/platform/misc/utils"; + +import { SmBulkStatusResponse } from "./models/sm-bulk-status.response"; + +/** + * An organization the active user is a member of and can use Secrets Manager in. Commands receive + * one instead of a raw `--organizationid` so they never repeat the access check. + */ +export type SmOrganization = { + /** The normalized (lowercased) organization id. */ + organizationId: string; + organization: Organization; +}; + +export type SmOrganizationResult = + | { organizationId: string; organization: Organization; error?: undefined } + | { organizationId?: undefined; organization?: undefined; error: Response }; + +/** + * Normalizes an id argument and rejects anything that is not a GUID. + * @returns the lowercased id, or an error response naming the offending argument. + */ +export function parseSmId( + id: string, + label: string, +): { id: string; error?: undefined } | { id?: undefined; error: Response } { + if (Utils.isNullOrWhitespace(id)) { + return { error: Response.badRequest("`" + label + "` is required.") }; + } + const normalized = id.toLowerCase(); + if (!Utils.isGuid(normalized)) { + return { error: Response.badRequest("`" + id + "` is not a GUID.") }; + } + return { id: normalized }; +} + +/** + * Normalizes a list of id arguments, rejecting an empty list, non-GUIDs, and duplicates. + */ +export function parseSmIds( + ids: string[], + label: string, +): { ids: string[]; error?: undefined } | { ids?: undefined; error: Response } { + if (ids.length === 0) { + return { error: Response.badRequest("At least one `" + label + "` is required.") }; + } + const normalized: string[] = []; + for (const id of ids) { + const parsed = parseSmId(id, label); + if (parsed.error) { + return { error: parsed.error }; + } + if (!normalized.includes(parsed.id)) { + normalized.push(parsed.id); + } + } + return { ids: normalized }; +} + +function isMissing(value: unknown): boolean { + if (value == null) { + return true; + } + if (typeof value !== "string") { + return false; + } + return Utils.isNullOrWhitespace(value); +} + +/** + * Reads a JSON request from a base64 encoded argument, stdin, or an object passed by `bw serve`. + */ +export async function parseSmRequest( + requestJson: unknown, +): Promise<{ request: Partial; error?: undefined } | { request?: undefined; error: Response }> { + const isServe = process.env.BW_SERVE === "true"; + const shouldReadStdin = !isServe && isMissing(requestJson); + const input = shouldReadStdin ? await CliUtils.readStdin() : requestJson; + if (isMissing(input)) { + return { error: Response.badRequest("`requestJson` was not provided.") }; + } + + let request: unknown; + if (typeof input !== "string") { + request = input; + } else { + try { + request = JSON.parse(Buffer.from(input, "base64").toString()); + } catch { + return { error: Response.badRequest("Error parsing the encoded request data.") }; + } + } + if (request == null || typeof request !== "object" || Array.isArray(request)) { + return { error: Response.badRequest("The request data must be a JSON object.") }; + } + return { request: request as Partial }; +} + +/** + * Rejects a request body whose `organizationId` disagrees with the target organization. + */ +export function checkSmRequestOrganization( + organizationId: string, + requestOrganizationId: unknown, +): Response | undefined { + if (isMissing(requestOrganizationId)) { + return undefined; + } + if ( + typeof requestOrganizationId !== "string" || + requestOrganizationId.toLowerCase() !== organizationId + ) { + return Response.badRequest( + "The request's `organizationId` property does not match the organization id.", + ); + } + return undefined; +} + +export function readSmString( + request: Record, + property: string, +): { value?: string; error?: Response } { + const value = request[property]; + if (value === undefined || value === null) { + return {}; + } + if (typeof value !== "string") { + return { error: Response.badRequest("`" + property + "` must be a string.") }; + } + return { value }; +} + +export function readSmName(request: Record): { name?: string; error?: Response } { + const name = readSmString(request, "name"); + if (name.error) { + return { error: name.error }; + } + if (Utils.isNullOrWhitespace(name.value)) { + return { error: Response.badRequest("`name` is required.") }; + } + return { name: name.value }; +} + +/** + * Maps the per-item results of a bulk operation to a CLI response. The response is an error + * if any item failed, naming each failure. + */ +export function smBulkResponse(results: BulkOperationStatus[], action: string): Response { + const failures = results.filter((r) => !Utils.isNullOrWhitespace(r.errorMessage)); + if (failures.length > 0) { + const details = failures.map((f) => f.name + " (" + f.id + "): " + f.errorMessage); + return Response.error( + failures.length + + " of " + + results.length + + " could not be " + + action + + ".\n" + + details.join("\n"), + ); + } + return Response.success(new ListResponse(results.map((r) => new SmBulkStatusResponse(r)))); +} + +/** + * Validates that the active user is a member of the organization and has access to Secrets Manager. + * The server answers permission failures with a 404, so this check runs first to give a clear error. + */ +export async function validateSmOrganizationAccess( + organizationService: OrganizationService, + accountService: AccountService, + organizationId: string, +): Promise { + const parsed = parseSmId(organizationId, "organizationid"); + if (parsed.error) { + return { error: parsed.error }; + } + + const userId = await firstValueFrom(accountService.activeAccount$.pipe(map((a) => a?.id))); + if (!userId) { + return { error: Response.badRequest("No user found.") }; + } + + const organization = await firstValueFrom( + organizationService + .organizations$(userId) + .pipe(map((organizations) => organizations.find((o) => o.id === parsed.id))), + ); + if (organization == null) { + return { error: Response.error("Organization not found.") }; + } + if (!organization.canAccessSecretsManager) { + return { + error: Response.error("You do not have access to Secrets Manager for this organization."), + }; + } + + return { organizationId: parsed.id, organization }; +} + +/** + * Validates the `--organizationid` once and runs `action` with the validated organization. + * Shared by the `bw sm` program and the `bw serve` routes so neither repeats the check. + * @returns the validation error, or the response of `action`. + */ +export async function withSmOrganization( + services: { organizationService: OrganizationService; accountService: AccountService }, + organizationId: string, + action: (org: SmOrganization) => Promise, +): Promise { + const result = await validateSmOrganizationAccess( + services.organizationService, + services.accountService, + organizationId, + ); + if (result.error) { + return result.error; + } + return action({ organizationId: result.organizationId, organization: result.organization }); +} + +/** + * The server returns 404 both for missing objects and for objects the user cannot access, + * so the message covers both cases. + */ +export function smNotFoundResponse(objectName: string): Response { + return Response.error("The " + objectName + " was not found, or you do not have access to it."); +} + +/** + * Fetch-by-id endpoints are not organization scoped, so a command that decrypts with the + * `--organizationid` must reject items that belong to another organization. + */ +export function isInSmOrganization( + item: { organizationId?: string }, + org: SmOrganization, +): boolean { + return item.organizationId?.toLowerCase() === org.organizationId.toLowerCase(); +} + +export function smErrorResponse(error: unknown, objectName: string): Response { + if (error instanceof ErrorResponse && error.statusCode === 404) { + return smNotFoundResponse(objectName); + } + return Response.error(error); +} diff --git a/bitwarden_license/bit-cli/src/secrets-manager/sm.program.spec.ts b/bitwarden_license/bit-cli/src/secrets-manager/sm.program.spec.ts new file mode 100644 index 00000000000..0869a487b05 --- /dev/null +++ b/bitwarden_license/bit-cli/src/secrets-manager/sm.program.spec.ts @@ -0,0 +1,108 @@ +import { Command, program } from "commander"; +import { mock } from "jest-mock-extended"; +import { of } from "rxjs"; + +import { ProjectService } from "@bitwarden/bit-sm"; +import { OrganizationService } from "@bitwarden/common/admin-console/abstractions/organization/organization.service.abstraction"; +import { AccountService } from "@bitwarden/common/auth/abstractions/account.service"; +import { FeatureFlag } from "@bitwarden/common/enums/feature-flag.enum"; +import { ConfigService } from "@bitwarden/common/platform/abstractions/config/config.service"; + +import { ServiceContainer } from "../service-container"; + +import { SmProgram } from "./sm.program"; +import { mockSmOrganization, smOrgId } from "./spec/sm-test-utils"; + +describe("SmProgram", () => { + const configService = mock(); + const projectService = mock(); + const organizationService = mock(); + const accountService = mock(); + const probe = jest.fn(); + let exitSpy: jest.SpyInstance; + + beforeAll(() => { + new SmProgram( + mock({ + configService, + projectService, + organizationService, + accountService, + }), + ).register(); + // Every `bw sm` subcommand runs through the parent's gate; a probe subcommand stands in for them. + program.commands + .find((command) => command.name() === "sm")! + .addCommand(new Command("probe").action(probe)); + }); + + beforeEach(() => { + process.env.BW_QUIET = "true"; + probe.mockReset(); + projectService.getProjects.mockReset(); + mockSmOrganization(accountService, organizationService); + configService.getFeatureFlag$.mockReturnValue(of(true)); + jest.spyOn(SmProgram.prototype as any, "exitIfLocked").mockResolvedValue(undefined); + exitSpy = jest.spyOn(process, "exit").mockImplementation((code) => { + throw new Error("process.exit(" + code + ")"); + }); + }); + + afterEach(() => { + exitSpy.mockRestore(); + delete process.env.BW_QUIET; + }); + + it("hides the sm command from bw --help", () => { + expect(program.helpInformation()).not.toMatch(/^\s+sm\b/m); + }); + + it("exits before running a subcommand when the SmCli flag is off", async () => { + configService.getFeatureFlag$.mockReturnValue(of(false)); + + await expect(program.parseAsync(["node", "bw", "sm", "probe"])).rejects.toThrow( + "process.exit(1)", + ); + + expect(configService.getFeatureFlag$).toHaveBeenCalledWith(FeatureFlag.SmCli); + expect(probe).not.toHaveBeenCalled(); + }); + + it("runs the subcommand when the SmCli flag is on", async () => { + configService.getFeatureFlag$.mockReturnValue(of(true)); + + await program.parseAsync(["node", "bw", "sm", "probe"]); + + expect(exitSpy).not.toHaveBeenCalled(); + expect(probe).toHaveBeenCalled(); + }); + + describe("organization validation", () => { + afterEach(() => { + process.exitCode = undefined; + }); + + it("hands a validated organization to the command", async () => { + projectService.getProjects.mockResolvedValue([]); + + await program.parseAsync([ + "node", + "bw", + "sm", + "project", + "list", + "--organizationid", + smOrgId.toUpperCase(), + ]); + + expect(projectService.getProjects).toHaveBeenCalledWith(smOrgId); + }); + + it("rejects an invalid organization id before the command runs", async () => { + await program.parseAsync(["node", "bw", "sm", "project", "list", "--organizationid", "bad"]); + + expect(process.exitCode).toBe(1); + expect(projectService.getProjects).not.toHaveBeenCalled(); + }); + }); +}); diff --git a/bitwarden_license/bit-cli/src/secrets-manager/sm.program.ts b/bitwarden_license/bit-cli/src/secrets-manager/sm.program.ts new file mode 100644 index 00000000000..25b6039a3c5 --- /dev/null +++ b/bitwarden_license/bit-cli/src/secrets-manager/sm.program.ts @@ -0,0 +1,1122 @@ +import { program, Command } from "commander"; + +import { BaseProgram } from "@bitwarden/cli/base-program"; +import { CliUtils } from "@bitwarden/cli/utils"; +import { FeatureFlag } from "@bitwarden/common/enums/feature-flag.enum"; + +import { ServiceContainer } from "../service-container"; + +import { AccessGetCommand } from "./access/access-get.command"; +import { AccessGrantCommand } from "./access/access-grant.command"; +import { AccessRevokeCommand } from "./access/access-revoke.command"; +import { AccessSetCommand } from "./access/access-set.command"; +import { SmAccessPermissions, SmAccessTargets } from "./access/sm-access-policies"; +import { AccessTokenCreateCommand } from "./access-tokens/access-token-create.command"; +import { AccessTokenListCommand } from "./access-tokens/access-token-list.command"; +import { AccessTokenRevokeCommand } from "./access-tokens/access-token-revoke.command"; +import { CountsCommand } from "./counts/counts.command"; +import { EventsCommand } from "./events/events.command"; +import { GranteesListCommand, SmGranteeKinds } from "./grantees/grantees-list.command"; +import { MachineAccountCreateCommand } from "./machine-accounts/machine-account-create.command"; +import { MachineAccountDeleteCommand } from "./machine-accounts/machine-account-delete.command"; +import { MachineAccountEditCommand } from "./machine-accounts/machine-account-edit.command"; +import { MachineAccountGetCommand } from "./machine-accounts/machine-account-get.command"; +import { MachineAccountListCommand } from "./machine-accounts/machine-account-list.command"; +import { SmExportCommand } from "./porting/sm-export.command"; +import { SmImportCommand } from "./porting/sm-import.command"; +import { ProjectCreateCommand } from "./projects/project-create.command"; +import { ProjectDeleteCommand } from "./projects/project-delete.command"; +import { ProjectEditCommand } from "./projects/project-edit.command"; +import { ProjectGetCommand } from "./projects/project-get.command"; +import { ProjectListCommand } from "./projects/project-list.command"; +import { SecretCreateCommand } from "./secrets/secret-create.command"; +import { SecretDeleteCommand } from "./secrets/secret-delete.command"; +import { SecretEditCommand } from "./secrets/secret-edit.command"; +import { SecretGetCommand } from "./secrets/secret-get.command"; +import { SecretListCommand } from "./secrets/secret-list.command"; +import { SecretRestoreVersionCommand } from "./secrets/secret-restore-version.command"; +import { SecretVersionsCommand } from "./secrets/secret-versions.command"; +import { withSmOrganization } from "./sm-command.utils"; +import { SmTemplateObjects, TemplateCommand } from "./templates/template.command"; +import { TrashEmptyCommand } from "./trash/trash-empty.command"; +import { TrashListCommand } from "./trash/trash-list.command"; +import { TrashRestoreCommand } from "./trash/trash-restore.command"; + +const writeLn = CliUtils.writeLn; + +const ORGANIZATION_ID_OPTION = "--organizationid "; +const ORGANIZATION_ID_DESCRIPTION = "The organization id (required)"; +const ENCODED_JSON_DESCRIPTION = + "Base64 encoded JSON of the object, e.g. from `bw encode`. Can also be piped into stdin."; + +type OrgOptions = { + organizationid: string; +}; + +type TrashOptions = OrgOptions & { + all?: boolean; +}; + +type MachineAccountOptions = OrgOptions & { + machineaccountid: string; +}; + +export class SmProgram extends BaseProgram { + constructor(protected serviceContainer: ServiceContainer) { + super(serviceContainer); + } + + register() { + // Hidden from `bw --help` until the SmCli feature flag is removed. + program.addCommand(this.smCommand(), { hidden: true }); + } + + private smCommand(): Command { + return new Command("sm") + .description( + "Manage Secrets Manager projects, secrets, and machine accounts in an organization.", + ) + .hook("preAction", () => this.exitIfFeatureFlagDisabled(FeatureFlag.SmCli)) + .addCommand(this.projectCommand()) + .addCommand(this.secretCommand()) + .addCommand(this.machineAccountCommand()) + .addCommand(this.accessTokenCommand()) + .addCommand(this.trashCommand()) + .addCommand(this.accessCommand()) + .addCommand(this.granteesCommand()) + .addCommand(this.countsCommand()) + .addCommand(this.eventsCommand()) + .addCommand(this.exportCommand()) + .addCommand(this.importCommand()) + .addCommand(this.templateCommand()) + .on("--help", () => { + writeLn("\n Examples:"); + writeLn(""); + writeLn(" bw sm project list --organizationid "); + writeLn(" bw sm secret list --organizationid --projectid "); + writeLn(" bw sm machine-account list --organizationid "); + writeLn(" bw sm template sm-secret"); + writeLn("", true); + }); + } + + private projectCommand(): Command { + return new Command("project") + .description("Manage Secrets Manager projects.") + .addCommand( + new Command("list") + .description("List the projects you can access in an organization.") + .requiredOption(ORGANIZATION_ID_OPTION, ORGANIZATION_ID_DESCRIPTION) + .on("--help", () => { + writeLn("\n Examples:"); + writeLn(""); + writeLn(" bw sm project list --organizationid "); + writeLn("", true); + }) + .action(async (options: OrgOptions) => { + await this.exitIfLocked(); + const response = await withSmOrganization( + this.serviceContainer, + options.organizationid, + (org) => ProjectListCommand.create(this.serviceContainer).run(org), + ); + this.processResponse(response); + }), + ) + .addCommand( + new Command("get") + .description("Get a project.") + .argument("", "The id of the project") + .requiredOption(ORGANIZATION_ID_OPTION, ORGANIZATION_ID_DESCRIPTION) + .on("--help", () => { + writeLn("\n Examples:"); + writeLn(""); + writeLn(" bw sm project get --organizationid "); + writeLn("", true); + }) + .action(async (projectId: string, options: OrgOptions) => { + await this.exitIfLocked(); + const response = await withSmOrganization( + this.serviceContainer, + options.organizationid, + (org) => ProjectGetCommand.create(this.serviceContainer).run(org, projectId), + ); + this.processResponse(response); + }), + ) + .addCommand( + new Command("create") + .description("Create a project.") + .argument("[encodedJson]", ENCODED_JSON_DESCRIPTION) + .requiredOption(ORGANIZATION_ID_OPTION, ORGANIZATION_ID_DESCRIPTION) + .on("--help", () => { + writeLn("\n Examples:"); + writeLn(""); + writeLn( + ' echo \'{"name":"Backend"}\' | bw encode | bw sm project create --organizationid ', + ); + writeLn("", true); + }) + .action(async (encodedJson: string | undefined, options: OrgOptions) => { + await this.exitIfLocked(); + const response = await withSmOrganization( + this.serviceContainer, + options.organizationid, + (org) => ProjectCreateCommand.create(this.serviceContainer).run(org, encodedJson), + ); + this.processResponse(response); + }), + ) + .addCommand( + new Command("edit") + .description("Rename a project.") + .argument("", "The id of the project") + .argument("[encodedJson]", ENCODED_JSON_DESCRIPTION) + .requiredOption(ORGANIZATION_ID_OPTION, ORGANIZATION_ID_DESCRIPTION) + .on("--help", () => { + writeLn("\n Examples:"); + writeLn(""); + writeLn( + ' echo \'{"name":"Backend"}\' | bw encode | bw sm project edit --organizationid ', + ); + writeLn("", true); + }) + .action( + async (projectId: string, encodedJson: string | undefined, options: OrgOptions) => { + await this.exitIfLocked(); + const response = await withSmOrganization( + this.serviceContainer, + options.organizationid, + (org) => + ProjectEditCommand.create(this.serviceContainer).run(org, projectId, encodedJson), + ); + this.processResponse(response); + }, + ), + ) + .addCommand( + new Command("delete") + .description("Permanently delete one or more projects.") + .argument("", "The ids of the projects") + .requiredOption(ORGANIZATION_ID_OPTION, ORGANIZATION_ID_DESCRIPTION) + .on("--help", () => { + writeLn("\n Notes:"); + writeLn(""); + writeLn(" Secrets in a deleted project are kept but are no longer in a project."); + writeLn(""); + writeLn(" Examples:"); + writeLn(""); + writeLn(" bw sm project delete --organizationid "); + writeLn( + " bw sm project delete --organizationid ", + ); + writeLn("", true); + }) + .action(async (projectIds: string[], options: OrgOptions) => { + await this.exitIfLocked(); + const response = await withSmOrganization( + this.serviceContainer, + options.organizationid, + (org) => ProjectDeleteCommand.create(this.serviceContainer).run(org, projectIds), + ); + this.processResponse(response); + }), + ); + } + + private secretCommand(): Command { + return new Command("secret") + .description("Manage Secrets Manager secrets.") + .addCommand( + new Command("list") + .description("List the secrets you can access in an organization or project.") + .requiredOption(ORGANIZATION_ID_OPTION, ORGANIZATION_ID_DESCRIPTION) + .option("--projectid ", "Only list secrets in this project") + .on("--help", () => { + writeLn("\n Notes:"); + writeLn(""); + writeLn(" Secret values are not included. Use `bw sm secret get` to read a value."); + writeLn(""); + writeLn(" Examples:"); + writeLn(""); + writeLn(" bw sm secret list --organizationid "); + writeLn( + " bw sm secret list --organizationid --projectid ", + ); + writeLn("", true); + }) + .action(async (options: OrgOptions & { projectid?: string }) => { + await this.exitIfLocked(); + const response = await withSmOrganization( + this.serviceContainer, + options.organizationid, + (org) => SecretListCommand.create(this.serviceContainer).run(org, options.projectid), + ); + this.processResponse(response); + }), + ) + .addCommand( + new Command("get") + .description("Get a secret, including its value.") + .argument("", "The id of the secret") + .requiredOption(ORGANIZATION_ID_OPTION, ORGANIZATION_ID_DESCRIPTION) + .on("--help", () => { + writeLn("\n Examples:"); + writeLn(""); + writeLn(" bw sm secret get --organizationid "); + writeLn("", true); + }) + .action(async (secretId: string, options: OrgOptions) => { + await this.exitIfLocked(); + const response = await withSmOrganization( + this.serviceContainer, + options.organizationid, + (org) => SecretGetCommand.create(this.serviceContainer).run(org, secretId), + ); + this.processResponse(response); + }), + ) + .addCommand( + new Command("create") + .description("Create a secret.") + .argument("[encodedJson]", ENCODED_JSON_DESCRIPTION) + .requiredOption(ORGANIZATION_ID_OPTION, ORGANIZATION_ID_DESCRIPTION) + .on("--help", () => { + writeLn("\n Notes:"); + writeLn(""); + writeLn(" `key` is required. `projectIds` may contain at most one project id."); + writeLn(" Only organization admins can create a secret without a project."); + writeLn(""); + writeLn(" Examples:"); + writeLn(""); + writeLn( + ' bw sm template sm-secret | jq \'.key="DB_PASSWORD" | .value="hunter2" | .projectIds=[""]\' | bw encode | bw sm secret create --organizationid ', + ); + writeLn("", true); + }) + .action(async (encodedJson: string | undefined, options: OrgOptions) => { + await this.exitIfLocked(); + const response = await withSmOrganization( + this.serviceContainer, + options.organizationid, + (org) => SecretCreateCommand.create(this.serviceContainer).run(org, encodedJson), + ); + this.processResponse(response); + }), + ) + .addCommand( + new Command("edit") + .description("Edit a secret.") + .argument("", "The id of the secret") + .argument("[encodedJson]", ENCODED_JSON_DESCRIPTION) + .requiredOption(ORGANIZATION_ID_OPTION, ORGANIZATION_ID_DESCRIPTION) + .on("--help", () => { + writeLn("\n Notes:"); + writeLn(""); + writeLn(" Only the `key`, `value`, `note`, and `projectIds` properties in the"); + writeLn(" request are changed; missing properties keep their current values."); + writeLn(" Access to the secret is not changed."); + writeLn(""); + writeLn(" Examples:"); + writeLn(""); + writeLn( + ' echo \'{"value":"new value"}\' | bw encode | bw sm secret edit --organizationid ', + ); + writeLn("", true); + }) + .action( + async (secretId: string, encodedJson: string | undefined, options: OrgOptions) => { + await this.exitIfLocked(); + const response = await withSmOrganization( + this.serviceContainer, + options.organizationid, + (org) => + SecretEditCommand.create(this.serviceContainer).run(org, secretId, encodedJson), + ); + this.processResponse(response); + }, + ), + ) + .addCommand( + new Command("delete") + .description("Move one or more secrets to the trash.") + .argument("", "The ids of the secrets") + .requiredOption(ORGANIZATION_ID_OPTION, ORGANIZATION_ID_DESCRIPTION) + .on("--help", () => { + writeLn("\n Notes:"); + writeLn(""); + writeLn(" Deleted secrets can be restored with `bw sm trash restore`."); + writeLn(""); + writeLn(" Examples:"); + writeLn(""); + writeLn(" bw sm secret delete --organizationid "); + writeLn( + " bw sm secret delete --organizationid ", + ); + writeLn("", true); + }) + .action(async (secretIds: string[], options: OrgOptions) => { + await this.exitIfLocked(); + const response = await withSmOrganization( + this.serviceContainer, + options.organizationid, + (org) => SecretDeleteCommand.create(this.serviceContainer).run(org, secretIds), + ); + this.processResponse(response); + }), + ) + .addCommand( + new Command("versions") + .description("List the previous values of a secret, newest first.") + .argument("", "The id of the secret") + .requiredOption(ORGANIZATION_ID_OPTION, ORGANIZATION_ID_DESCRIPTION) + .on("--help", () => { + writeLn("\n Examples:"); + writeLn(""); + writeLn(" bw sm secret versions --organizationid "); + writeLn("", true); + }) + .action(async (secretId: string, options: OrgOptions) => { + await this.exitIfLocked(); + const response = await withSmOrganization( + this.serviceContainer, + options.organizationid, + (org) => SecretVersionsCommand.create(this.serviceContainer).run(org, secretId), + ); + this.processResponse(response); + }), + ) + .addCommand( + new Command("restore-version") + .description("Restore a previous value of a secret.") + .argument("", "The id of the secret") + .argument("", "The id of the version, from `bw sm secret versions`") + .requiredOption(ORGANIZATION_ID_OPTION, ORGANIZATION_ID_DESCRIPTION) + .on("--help", () => { + writeLn("\n Examples:"); + writeLn(""); + writeLn( + " bw sm secret restore-version --organizationid ", + ); + writeLn("", true); + }) + .action(async (secretId: string, versionId: string, options: OrgOptions) => { + await this.exitIfLocked(); + const response = await withSmOrganization( + this.serviceContainer, + options.organizationid, + (org) => + SecretRestoreVersionCommand.create(this.serviceContainer).run( + org, + secretId, + versionId, + ), + ); + this.processResponse(response); + }), + ); + } + + private machineAccountCommand(): Command { + return new Command("machine-account") + .description("Manage Secrets Manager machine accounts.") + .addCommand( + new Command("list") + .description("List the machine accounts you can access in an organization.") + .requiredOption(ORGANIZATION_ID_OPTION, ORGANIZATION_ID_DESCRIPTION) + .on("--help", () => { + writeLn("\n Examples:"); + writeLn(""); + writeLn(" bw sm machine-account list --organizationid "); + writeLn("", true); + }) + .action(async (options: OrgOptions) => { + await this.exitIfLocked(); + const response = await withSmOrganization( + this.serviceContainer, + options.organizationid, + (org) => MachineAccountListCommand.create(this.serviceContainer).run(org), + ); + this.processResponse(response); + }), + ) + .addCommand( + new Command("get") + .description("Get a machine account.") + .argument("", "The id of the machine account") + .requiredOption(ORGANIZATION_ID_OPTION, ORGANIZATION_ID_DESCRIPTION) + .on("--help", () => { + writeLn("\n Examples:"); + writeLn(""); + writeLn( + " bw sm machine-account get --organizationid ", + ); + writeLn("", true); + }) + .action(async (machineAccountId: string, options: OrgOptions) => { + await this.exitIfLocked(); + const response = await withSmOrganization( + this.serviceContainer, + options.organizationid, + (org) => + MachineAccountGetCommand.create(this.serviceContainer).run(org, machineAccountId), + ); + this.processResponse(response); + }), + ) + .addCommand( + new Command("create") + .description("Create a machine account.") + .argument("[encodedJson]", ENCODED_JSON_DESCRIPTION) + .requiredOption(ORGANIZATION_ID_OPTION, ORGANIZATION_ID_DESCRIPTION) + .on("--help", () => { + writeLn("\n Examples:"); + writeLn(""); + writeLn( + " bw sm template sm-machine-account | jq '.name=\"CI\"' | bw encode | bw sm machine-account create --organizationid ", + ); + writeLn("", true); + }) + .action(async (encodedJson: string | undefined, options: OrgOptions) => { + await this.exitIfLocked(); + const response = await withSmOrganization( + this.serviceContainer, + options.organizationid, + (org) => + MachineAccountCreateCommand.create(this.serviceContainer).run(org, encodedJson), + ); + this.processResponse(response); + }), + ) + .addCommand( + new Command("edit") + .description("Rename a machine account.") + .argument("", "The id of the machine account") + .argument("[encodedJson]", ENCODED_JSON_DESCRIPTION) + .requiredOption(ORGANIZATION_ID_OPTION, ORGANIZATION_ID_DESCRIPTION) + .on("--help", () => { + writeLn("\n Examples:"); + writeLn(""); + writeLn( + ' echo \'{"name":"CI"}\' | bw encode | bw sm machine-account edit --organizationid ', + ); + writeLn("", true); + }) + .action( + async ( + machineAccountId: string, + encodedJson: string | undefined, + options: OrgOptions, + ) => { + await this.exitIfLocked(); + const response = await withSmOrganization( + this.serviceContainer, + options.organizationid, + (org) => + MachineAccountEditCommand.create(this.serviceContainer).run( + org, + machineAccountId, + encodedJson, + ), + ); + this.processResponse(response); + }, + ), + ) + .addCommand( + new Command("delete") + .description("Permanently delete one or more machine accounts.") + .argument("", "The ids of the machine accounts") + .requiredOption(ORGANIZATION_ID_OPTION, ORGANIZATION_ID_DESCRIPTION) + .on("--help", () => { + writeLn("\n Notes:"); + writeLn(""); + writeLn(" The machine accounts' access tokens stop working immediately."); + writeLn(""); + writeLn(" Examples:"); + writeLn(""); + writeLn( + " bw sm machine-account delete --organizationid ", + ); + writeLn("", true); + }) + .action(async (machineAccountIds: string[], options: OrgOptions) => { + await this.exitIfLocked(); + const response = await withSmOrganization( + this.serviceContainer, + options.organizationid, + (org) => + MachineAccountDeleteCommand.create(this.serviceContainer).run( + org, + machineAccountIds, + ), + ); + this.processResponse(response); + }), + ); + } + + private accessTokenCommand(): Command { + const machineAccountOption = "--machineaccountid "; + const machineAccountDescription = "The machine account id (required)"; + + return new Command("access-token") + .description("Manage machine account access tokens.") + .addCommand( + new Command("list") + .description("List a machine account's access tokens.") + .requiredOption(ORGANIZATION_ID_OPTION, ORGANIZATION_ID_DESCRIPTION) + .requiredOption(machineAccountOption, machineAccountDescription) + .on("--help", () => { + writeLn("\n Examples:"); + writeLn(""); + writeLn( + " bw sm access-token list --organizationid --machineaccountid ", + ); + writeLn("", true); + }) + .action(async (options: MachineAccountOptions) => { + await this.exitIfLocked(); + const response = await withSmOrganization( + this.serviceContainer, + options.organizationid, + (org) => + AccessTokenListCommand.create(this.serviceContainer).run( + org, + options.machineaccountid, + ), + ); + this.processResponse(response); + }), + ) + .addCommand( + new Command("create") + .description("Create an access token for a machine account.") + .requiredOption(ORGANIZATION_ID_OPTION, ORGANIZATION_ID_DESCRIPTION) + .requiredOption(machineAccountOption, machineAccountDescription) + .requiredOption("--name ", "The name of the access token (required)") + .option( + "--expires ", + 'When the access token expires, as an ISO 8601 date, or "never" for a token that does not expire. Defaults to never.', + ) + .on("--help", () => { + writeLn("\n Notes:"); + writeLn(""); + writeLn(" The access token is only shown once and cannot be retrieved later."); + writeLn(" Store it somewhere safe before closing your terminal."); + writeLn(""); + writeLn(" Use --raw to print only the access token."); + writeLn(""); + writeLn(" --expires accepts an ISO 8601 date, or never (also none) for a token"); + writeLn(" that does not expire. Omitting --expires is the same as never."); + writeLn(""); + writeLn(" With `bw serve`, `expires` is required in the JSON body of"); + writeLn( + " POST /sm//machine-accounts//access-tokens.", + ); + writeLn(" Send `never` for an access token that does not expire."); + writeLn(""); + writeLn(" Examples:"); + writeLn(""); + writeLn( + ' bw sm access-token create --organizationid --machineaccountid --name "CI"', + ); + writeLn( + ' bw sm access-token create --organizationid --machineaccountid --name "CI" --expires never', + ); + writeLn( + ' bw sm access-token create --organizationid --machineaccountid --name "CI" --expires 2026-12-31 --raw', + ); + writeLn("", true); + }) + .action(async (options: MachineAccountOptions & { name: string; expires?: string }) => { + await this.exitIfLocked(); + const response = await withSmOrganization( + this.serviceContainer, + options.organizationid, + (org) => + AccessTokenCreateCommand.create(this.serviceContainer).run( + org, + options.machineaccountid, + { + name: options.name, + expires: options.expires, + raw: process.env.BW_RAW === "true", + }, + ), + ); + this.processResponse(response); + }), + ) + .addCommand( + new Command("revoke") + .description("Revoke one or more of a machine account's access tokens.") + .argument("", "The ids of the access tokens") + .requiredOption(ORGANIZATION_ID_OPTION, ORGANIZATION_ID_DESCRIPTION) + .requiredOption(machineAccountOption, machineAccountDescription) + .on("--help", () => { + writeLn("\n Notes:"); + writeLn(""); + writeLn(" Revoked access tokens stop working immediately."); + writeLn(""); + writeLn(" Examples:"); + writeLn(""); + writeLn( + " bw sm access-token revoke --organizationid --machineaccountid ", + ); + writeLn("", true); + }) + .action(async (accessTokenIds: string[], options: MachineAccountOptions) => { + await this.exitIfLocked(); + const response = await withSmOrganization( + this.serviceContainer, + options.organizationid, + (org) => + AccessTokenRevokeCommand.create(this.serviceContainer).run( + org, + options.machineaccountid, + accessTokenIds, + ), + ); + this.processResponse(response); + }), + ); + } + + private trashCommand(): Command { + return new Command("trash") + .description("Manage deleted Secrets Manager secrets.") + .addCommand( + new Command("list") + .description("List the secrets in an organization's trash.") + .requiredOption(ORGANIZATION_ID_OPTION, ORGANIZATION_ID_DESCRIPTION) + .on("--help", () => { + writeLn("\n Examples:"); + writeLn(""); + writeLn(" bw sm trash list --organizationid "); + writeLn("", true); + }) + .action(async (options: OrgOptions) => { + await this.exitIfLocked(); + const response = await withSmOrganization( + this.serviceContainer, + options.organizationid, + (org) => TrashListCommand.create(this.serviceContainer).run(org), + ); + this.processResponse(response); + }), + ) + .addCommand( + new Command("restore") + .description("Restore secrets from the trash.") + .argument("[secretIds...]", "The ids of the trashed secrets") + .requiredOption(ORGANIZATION_ID_OPTION, ORGANIZATION_ID_DESCRIPTION) + .option("--all", "Restore every secret in the trash") + .on("--help", () => { + writeLn("\n Examples:"); + writeLn(""); + writeLn(" bw sm trash restore --organizationid "); + writeLn(" bw sm trash restore --all --organizationid "); + writeLn("", true); + }) + .action(async (secretIds: string[], options: TrashOptions) => { + await this.exitIfLocked(); + const response = await withSmOrganization( + this.serviceContainer, + options.organizationid, + (org) => + TrashRestoreCommand.create(this.serviceContainer).run(org, { + secretIds, + all: options.all, + }), + ); + this.processResponse(response); + }), + ) + .addCommand( + new Command("empty") + .description("Permanently delete secrets from the trash.") + .argument("[secretIds...]", "The ids of the trashed secrets") + .requiredOption(ORGANIZATION_ID_OPTION, ORGANIZATION_ID_DESCRIPTION) + .option("--all", "Permanently delete every secret in the trash") + .on("--help", () => { + writeLn("\n Notes:"); + writeLn(""); + writeLn(" Permanently deleted secrets cannot be recovered."); + writeLn(""); + writeLn(" Examples:"); + writeLn(""); + writeLn(" bw sm trash empty --organizationid "); + writeLn(" bw sm trash empty --all --organizationid "); + writeLn("", true); + }) + .action(async (secretIds: string[], options: TrashOptions) => { + await this.exitIfLocked(); + const response = await withSmOrganization( + this.serviceContainer, + options.organizationid, + (org) => + TrashEmptyCommand.create(this.serviceContainer).run(org, { + secretIds, + all: options.all, + }), + ); + this.processResponse(response); + }), + ); + } + + private accessCommand(): Command { + const targetDescription = "The object type: " + SmAccessTargets.join(", "); + const granteeDescription = + "A user's email, the name of a group, machine account, or project, or a grantee id"; + const permissionOption = "--permission "; + const permissionDescription = + "The permission to grant: " + SmAccessPermissions.join(", ") + " (required)"; + + return new Command("access") + .description("Manage who and what can access projects, machine accounts, and secrets.") + .addCommand( + new Command("get") + .description("List the access policies on a project, machine account, or secret.") + .argument("", targetDescription) + .argument("", "The id of the object") + .requiredOption(ORGANIZATION_ID_OPTION, ORGANIZATION_ID_DESCRIPTION) + .on("--help", () => { + writeLn("\n Notes:"); + writeLn(""); + writeLn(" Projects and secrets list user, group, and machine account access."); + writeLn(" Machine accounts list user and group access, and the projects the"); + writeLn(" machine account can access."); + writeLn(""); + writeLn(" Examples:"); + writeLn(""); + writeLn(" bw sm access get project --organizationid "); + writeLn( + " bw sm access get machine-account --organizationid ", + ); + writeLn("", true); + }) + .action(async (target: string, id: string, options: OrgOptions) => { + await this.exitIfLocked(); + const response = await withSmOrganization( + this.serviceContainer, + options.organizationid, + (org) => AccessGetCommand.create(this.serviceContainer).run(org, target, id), + ); + this.processResponse(response); + }), + ) + .addCommand( + new Command("set") + .description("Replace every access policy on a project, machine account, or secret.") + .argument("", targetDescription) + .argument("", "The id of the object") + .argument("[encodedJson]", ENCODED_JSON_DESCRIPTION) + .requiredOption(ORGANIZATION_ID_OPTION, ORGANIZATION_ID_DESCRIPTION) + .on("--help", () => { + writeLn("\n Notes:"); + writeLn(""); + writeLn(" Any existing policy not listed in `policies` is removed. Use `grant`"); + writeLn(" and `revoke` to change a single policy."); + writeLn(""); + writeLn(" Examples:"); + writeLn(""); + writeLn( + " bw sm template sm-access-policies | jq '.policies[0].id=\"\"' | bw encode | bw sm access set project --organizationid ", + ); + writeLn("", true); + }) + .action( + async ( + target: string, + id: string, + encodedJson: string | undefined, + options: OrgOptions, + ) => { + await this.exitIfLocked(); + const response = await withSmOrganization( + this.serviceContainer, + options.organizationid, + (org) => + AccessSetCommand.create(this.serviceContainer).run(org, target, id, encodedJson), + ); + this.processResponse(response); + }, + ), + ) + .addCommand( + new Command("grant") + .description("Grant access to a project, machine account, or secret.") + .argument("", targetDescription) + .argument("", "The id of the object") + .argument("", granteeDescription) + .requiredOption(ORGANIZATION_ID_OPTION, ORGANIZATION_ID_DESCRIPTION) + .requiredOption(permissionOption, permissionDescription) + .on("--help", () => { + writeLn("\n Notes:"); + writeLn(""); + writeLn(" Other existing policies are kept. Granting to a grantee that already has"); + writeLn(" access changes its permission. People can only be granted read-write"); + writeLn(" access to a machine account."); + writeLn(""); + writeLn(" Examples:"); + writeLn(""); + writeLn( + " bw sm access grant project alice@example.com --permission read --organizationid ", + ); + writeLn( + ' bw sm access grant machine-account "Backend" --permission read-write --organizationid ', + ); + writeLn("", true); + }) + .action( + async ( + target: string, + id: string, + grantee: string, + options: OrgOptions & { permission: string }, + ) => { + await this.exitIfLocked(); + const response = await withSmOrganization( + this.serviceContainer, + options.organizationid, + (org) => + AccessGrantCommand.create(this.serviceContainer).run( + org, + target, + id, + grantee, + options.permission, + ), + ); + this.processResponse(response); + }, + ), + ) + .addCommand( + new Command("revoke") + .description("Remove access to a project, machine account, or secret.") + .argument("", targetDescription) + .argument("", "The id of the object") + .argument("", granteeDescription) + .requiredOption(ORGANIZATION_ID_OPTION, ORGANIZATION_ID_DESCRIPTION) + .on("--help", () => { + writeLn("\n Notes:"); + writeLn(""); + writeLn(" Other existing policies are kept."); + writeLn(""); + writeLn(" Examples:"); + writeLn(""); + writeLn( + " bw sm access revoke secret alice@example.com --organizationid ", + ); + writeLn("", true); + }) + .action(async (target: string, id: string, grantee: string, options: OrgOptions) => { + await this.exitIfLocked(); + const response = await withSmOrganization( + this.serviceContainer, + options.organizationid, + (org) => + AccessRevokeCommand.create(this.serviceContainer).run(org, target, id, grantee), + ); + this.processResponse(response); + }), + ); + } + + private granteesCommand(): Command { + return new Command("grantees") + .description("List who and what can be granted access in Secrets Manager.") + .addCommand( + new Command("list") + .description("List potential grantees of the given type.") + .argument("", "The grantee type: " + SmGranteeKinds.join(", ")) + .requiredOption(ORGANIZATION_ID_OPTION, ORGANIZATION_ID_DESCRIPTION) + .on("--help", () => { + writeLn("\n Notes:"); + writeLn(""); + writeLn(" `people` lists users and groups that can be granted access to projects"); + writeLn(" and machine accounts. `machine-accounts` lists machine accounts that can"); + writeLn(" be granted access to projects. `projects` lists projects a machine"); + writeLn(" account can be granted access to."); + writeLn(""); + writeLn(" Examples:"); + writeLn(""); + writeLn(" bw sm grantees list people --organizationid "); + writeLn(" bw sm grantees list machine-accounts --organizationid "); + writeLn("", true); + }) + .action(async (type: string, options: OrgOptions) => { + await this.exitIfLocked(); + const response = await withSmOrganization( + this.serviceContainer, + options.organizationid, + (org) => GranteesListCommand.create(this.serviceContainer).run(org, type), + ); + this.processResponse(response); + }), + ); + } + + private countsCommand(): Command { + return new Command("counts") + .description( + "Show Secrets Manager object counts for an organization, project, or machine account.", + ) + .requiredOption(ORGANIZATION_ID_OPTION, ORGANIZATION_ID_DESCRIPTION) + .option("--projectid ", "Show counts for this project") + .option("--machineaccountid ", "Show counts for this machine account") + .on("--help", () => { + writeLn("\n Examples:"); + writeLn(""); + writeLn(" bw sm counts --organizationid "); + writeLn(" bw sm counts --organizationid --projectid "); + writeLn( + " bw sm counts --organizationid --machineaccountid ", + ); + writeLn("", true); + }) + .action(async (options: OrgOptions & { projectid?: string; machineaccountid?: string }) => { + await this.exitIfLocked(); + const response = await withSmOrganization( + this.serviceContainer, + options.organizationid, + (org) => + CountsCommand.create(this.serviceContainer).run(org, { + projectId: options.projectid, + machineAccountId: options.machineaccountid, + }), + ); + this.processResponse(response); + }); + } + + private eventsCommand(): Command { + return new Command("events") + .description("List the event logs for a machine account.") + .requiredOption(ORGANIZATION_ID_OPTION, ORGANIZATION_ID_DESCRIPTION) + .requiredOption("--machineaccountid ", "The machine account id (required)") + .requiredOption("--start ", "Start of the date range, e.g. 2026-01-01 (required)") + .requiredOption("--end ", "End of the date range, e.g. 2026-01-31T23:59:59Z (required)") + .on("--help", () => { + writeLn("\n Examples:"); + writeLn(""); + writeLn( + " bw sm events --organizationid --machineaccountid --start 2026-01-01 --end 2026-02-01", + ); + writeLn("", true); + }) + .action( + async (options: OrgOptions & { machineaccountid: string; start: string; end: string }) => { + await this.exitIfLocked(); + const response = await withSmOrganization( + this.serviceContainer, + options.organizationid, + (org) => + EventsCommand.create(this.serviceContainer).run(org, { + machineAccountId: options.machineaccountid, + start: options.start, + end: options.end, + }), + ); + this.processResponse(response); + }, + ); + } + + private exportCommand(): Command { + return new Command("export") + .description("Export an organization's Secrets Manager projects and secrets.") + .requiredOption(ORGANIZATION_ID_OPTION, ORGANIZATION_ID_DESCRIPTION) + .option("--output ", "Output directory or filename. Writes to stdout when omitted.") + .option("--passwordenv ", "Environment variable storing your master password") + .option( + "--passwordfile ", + "Path to a file containing your master password as its first line", + ) + .on("--help", () => { + writeLn("\n Notes:"); + writeLn(""); + writeLn(" Only organization owners and admins can export. The export contains"); + writeLn(" decrypted secret values; store it securely."); + writeLn(""); + writeLn(" Exporting requires your master password. You are prompted for it unless"); + writeLn(" --passwordfile or --passwordenv is given. With --nointeraction, one of"); + writeLn(" these options is required."); + writeLn(""); + writeLn(" With `bw serve`, send the master password as `password` in the JSON body"); + writeLn(" of POST /sm//export."); + writeLn(""); + writeLn(" Examples:"); + writeLn(""); + writeLn(" bw sm export --organizationid "); + writeLn(" bw sm export --organizationid --output ./sm-export.json"); + writeLn(" bw sm export --organizationid --passwordfile ~/.bw-password"); + writeLn("", true); + }) + .action( + async ( + options: OrgOptions & { output?: string; passwordenv?: string; passwordfile?: string }, + ) => { + await this.exitIfLocked(); + const response = await withSmOrganization( + this.serviceContainer, + options.organizationid, + (org) => + SmExportCommand.create(this.serviceContainer).run(org, { + output: options.output, + passwordEnv: options.passwordenv, + passwordFile: options.passwordfile, + }), + ); + this.processResponse(response); + }, + ); + } + + private importCommand(): Command { + return new Command("import") + .description("Import Secrets Manager projects and secrets into an organization.") + .argument("", "A file from `bw sm export` or the web vault's Secrets Manager export") + .requiredOption(ORGANIZATION_ID_OPTION, ORGANIZATION_ID_DESCRIPTION) + .on("--help", () => { + writeLn("\n Notes:"); + writeLn(""); + writeLn(" Only organization owners and admins can import."); + writeLn(""); + writeLn(" Examples:"); + writeLn(""); + writeLn(" bw sm import ./sm-export.json --organizationid "); + writeLn("", true); + }) + .action(async (file: string, options: OrgOptions) => { + await this.exitIfLocked(); + const response = await withSmOrganization( + this.serviceContainer, + options.organizationid, + (org) => SmImportCommand.create(this.serviceContainer).run(org, { file }), + ); + this.processResponse(response); + }); + } + + private templateCommand(): Command { + return new Command("template") + .description("Get a JSON template for creating or editing a Secrets Manager object.") + .argument("", "The template object: " + SmTemplateObjects.join(", ")) + .on("--help", () => { + writeLn("\n Examples:"); + writeLn(""); + writeLn(" bw sm template sm-project"); + writeLn(" bw sm template sm-secret"); + writeLn(" bw sm template sm-machine-account"); + writeLn("", true); + }) + .action(async (object: string) => { + const response = await TemplateCommand.create().run(object); + this.processResponse(response); + }); + } +} diff --git a/bitwarden_license/bit-cli/src/secrets-manager/spec/sm-access-test-utils.ts b/bitwarden_license/bit-cli/src/secrets-manager/spec/sm-access-test-utils.ts new file mode 100644 index 00000000000..adcea08c09c --- /dev/null +++ b/bitwarden_license/bit-cli/src/secrets-manager/spec/sm-access-test-utils.ts @@ -0,0 +1,126 @@ +import { mock } from "jest-mock-extended"; + +import { + AccessPolicyService, + PotentialGranteeView, + ProjectService, + ProjectView, + SecretService, + SecretView, + ServiceAccountService, + ServiceAccountView, +} from "@bitwarden/bit-sm"; + +import { SmAccessPolicyStore } from "../access/sm-access-policies"; + +import { smOrgId } from "./sm-test-utils"; + +export const smTargetId = "22222222-2222-2222-2222-222222222222"; +export const aliceId = "a1a1a1a1-0000-0000-0000-000000000001"; +export const bobId = "b0b0b0b0-0000-0000-0000-000000000002"; +export const groupId = "9a9a9a9a-0000-0000-0000-000000000003"; +export const machineAccountId = "3c3c3c3c-0000-0000-0000-000000000004"; +export const projectId = "4d4d4d4d-0000-0000-0000-000000000005"; + +export function potentialGrantee( + type: string, + id: string, + name: string, + email?: string, +): PotentialGranteeView { + return Object.assign(new PotentialGranteeView(), { type, id, name, email }); +} + +/** + * Builds a real `SmAccessPolicyStore` over mocked services. The target project, machine + * account, and secret all belong to `smOrgId` and have no policies until a test stubs them. + */ +export function createSmAccessFixture() { + const accessPolicyService = mock(); + const projectService = mock(); + const serviceAccountService = mock(); + const secretService = mock(); + + projectService.getByProjectId.mockResolvedValue( + Object.assign(new ProjectView(), { id: smTargetId, organizationId: smOrgId, write: true }), + ); + serviceAccountService.getByServiceAccountId.mockResolvedValue( + Object.assign(new ServiceAccountView(), { id: smTargetId, organizationId: smOrgId }), + ); + secretService.getBySecretId.mockResolvedValue( + Object.assign(new SecretView(), { + id: smTargetId, + organizationId: smOrgId, + name: "API_KEY", + value: "value", + note: "", + projects: [], + read: true, + write: true, + }), + ); + + accessPolicyService.getProjectPeopleAccessPolicies.mockResolvedValue({ + userAccessPolicies: [], + groupAccessPolicies: [], + }); + accessPolicyService.getProjectServiceAccountsAccessPolicies.mockResolvedValue({ + serviceAccountAccessPolicies: [], + }); + accessPolicyService.getServiceAccountPeopleAccessPolicies.mockResolvedValue({ + userAccessPolicies: [], + groupAccessPolicies: [], + }); + accessPolicyService.getServiceAccountGrantedPolicies.mockResolvedValue({ + grantedProjectPolicies: [], + }); + accessPolicyService.getSecretAccessPolicies.mockResolvedValue({ + userAccessPolicies: [], + groupAccessPolicies: [], + serviceAccountAccessPolicies: [], + }); + accessPolicyService.getPeoplePotentialGrantees.mockResolvedValue([ + potentialGrantee("user", aliceId, "Alice", "alice@example.com"), + potentialGrantee("user", bobId, "Bob", "bob@example.com"), + potentialGrantee("group", groupId, "Engineering"), + ]); + accessPolicyService.getServiceAccountsPotentialGrantees.mockResolvedValue([ + potentialGrantee("serviceAccount", machineAccountId, "CI runner"), + ]); + accessPolicyService.getProjectsPotentialGrantees.mockResolvedValue([ + potentialGrantee("project", projectId, "Backend"), + ]); + + const store = new SmAccessPolicyStore( + accessPolicyService, + projectService, + serviceAccountService, + secretService, + ); + + return { + store, + accessPolicyService, + projectService, + serviceAccountService, + secretService, + }; +} + +export function userPolicy(id: string, name: string, write = false) { + return { + organizationUserId: id, + organizationUserName: name, + currentUser: false, + read: true, + write, + }; +} + +export function groupPolicy(id: string, name: string, write = false) { + return { groupId: id, groupName: name, currentUserInGroup: false, read: true, write }; +} + +export function machineAccountPolicy(id: string, name: string, write = false) { + return { serviceAccountId: id, serviceAccountName: name, read: true, write }; +} diff --git a/bitwarden_license/bit-cli/src/secrets-manager/spec/sm-test-utils.ts b/bitwarden_license/bit-cli/src/secrets-manager/spec/sm-test-utils.ts new file mode 100644 index 00000000000..0e078dfc28f --- /dev/null +++ b/bitwarden_license/bit-cli/src/secrets-manager/spec/sm-test-utils.ts @@ -0,0 +1,57 @@ +import { MockProxy } from "jest-mock-extended"; +import { of } from "rxjs"; + +import { OrganizationService } from "@bitwarden/common/admin-console/abstractions/organization/organization.service.abstraction"; +import { Organization } from "@bitwarden/common/admin-console/models/domain/organization"; +import { AccountService } from "@bitwarden/common/auth/abstractions/account.service"; +import { ErrorResponse } from "@bitwarden/common/models/response/error.response"; +import { mockAccountInfoWith } from "@bitwarden/common/spec"; +import { UserId } from "@bitwarden/user-core"; + +import { SmOrganization } from "../sm-command.utils"; + +export const smUserId = "user-id" as UserId; +export const smOrgId = "11111111-1111-1111-1111-111111111111"; +export const smOtherOrgId = "99999999-9999-9999-9999-999999999999"; + +/** A validated organization, as the program layer hands it to a command's `run()`. */ +export function createSmOrg(organization: Partial = {}): SmOrganization { + return { + organizationId: smOrgId, + organization: { id: smOrgId, canAccessSecretsManager: true, ...organization } as Organization, + }; +} + +export const smOrg = createSmOrg(); + +/** Makes `smUserId` the active user. */ +export function mockSmActiveAccount(accountService: MockProxy) { + accountService.activeAccount$ = of({ + id: smUserId, + ...mockAccountInfoWith({ email: "user@example.com", name: "Test User" }), + }); +} + +/** + * Wires the account and organization mocks so `smOrgId` resolves to an organization the + * active user is a member of. + */ +export function mockSmOrganization( + accountService: MockProxy, + organizationService: MockProxy, + canAccessSecretsManager = true, + organization: Partial = {}, +) { + mockSmActiveAccount(accountService); + organizationService.organizations$.mockReturnValue( + of([{ id: smOrgId, canAccessSecretsManager, ...organization } as Organization]), + ); +} + +export function smNotFoundError() { + return new ErrorResponse({ Message: "Resource not found." }, 404); +} + +export function encodeSmRequest(request: unknown): string { + return Buffer.from(JSON.stringify(request)).toString("base64"); +} diff --git a/bitwarden_license/bit-cli/src/secrets-manager/templates/template.command.spec.ts b/bitwarden_license/bit-cli/src/secrets-manager/templates/template.command.spec.ts new file mode 100644 index 00000000000..6c5a6142b4a --- /dev/null +++ b/bitwarden_license/bit-cli/src/secrets-manager/templates/template.command.spec.ts @@ -0,0 +1,58 @@ +import { mock } from "jest-mock-extended"; + +import { ProjectService, ProjectView } from "@bitwarden/bit-sm"; +import { TemplateResponse } from "@bitwarden/cli/models/response/template.response"; + +import { ProjectCreateCommand } from "../projects/project-create.command"; +import { checkSmRequestOrganization } from "../sm-command.utils"; +import { encodeSmRequest, smOrg, smOrgId } from "../spec/sm-test-utils"; + +import { TemplateCommand } from "./template.command"; + +describe("TemplateCommand", () => { + const command = new TemplateCommand(); + + const template = async (object: string) => + ((await command.run(object)).data as TemplateResponse).template; + + it.each(["sm-project", "sm-secret", "sm-machine-account", "sm-access-policies"])( + "returns a %s template accepted for any organization", + async (object) => { + const response = await command.run(object); + + expect(response.success).toBe(true); + expect(response.data.object).toBe("template"); + expect( + checkSmRequestOrganization(smOrgId, (await template(object)).organizationId), + ).toBeUndefined(); + }, + ); + + it("returns an sm-project template that project create accepts", async () => { + const projectService = mock(); + projectService.create.mockImplementation(async (_, view) => + Object.assign(new ProjectView(), view, { id: "22222222-2222-2222-2222-222222222222" }), + ); + const createCommand = new ProjectCreateCommand(projectService); + + const response = await createCommand.run( + smOrg, + encodeSmRequest({ ...(await template("sm-project")), name: "Backend" }), + ); + + expect(response.success).toBe(true); + expect(projectService.create).toHaveBeenCalledWith( + smOrgId, + expect.objectContaining({ organizationId: smOrgId, name: "Backend" }), + ); + }); + + it("rejects an unknown object", async () => { + const response = await command.run("item"); + + expect(response.success).toBe(false); + expect(response.message).toBe( + "Unknown template object `item`. Expected one of: sm-project, sm-secret, sm-machine-account, sm-access-policies.", + ); + }); +}); diff --git a/bitwarden_license/bit-cli/src/secrets-manager/templates/template.command.ts b/bitwarden_license/bit-cli/src/secrets-manager/templates/template.command.ts new file mode 100644 index 00000000000..0568a920a21 --- /dev/null +++ b/bitwarden_license/bit-cli/src/secrets-manager/templates/template.command.ts @@ -0,0 +1,46 @@ +import { Response } from "@bitwarden/cli/models/response"; +import { TemplateResponse } from "@bitwarden/cli/models/response/template.response"; + +const SmTemplates = { + "sm-project": () => ({ + organizationId: null as string | null, + name: "Project name", + }), + "sm-secret": () => ({ + organizationId: null as string | null, + key: "SECRET_NAME", + value: "secret value", + note: "", + projectIds: ["00000000-0000-0000-0000-000000000000"], + }), + "sm-machine-account": () => ({ + organizationId: null as string | null, + name: "Machine account name", + }), + "sm-access-policies": () => ({ + organizationId: null as string | null, + policies: [{ type: "user", id: "00000000-0000-0000-0000-000000000000", permission: "read" }], + }), +} as const; + +export type SmTemplateObject = keyof typeof SmTemplates; +export const SmTemplateObjects = Object.keys(SmTemplates) as SmTemplateObject[]; + +export class TemplateCommand { + async run(object: string): Promise { + if (!SmTemplateObjects.includes(object as SmTemplateObject)) { + return Response.badRequest( + "Unknown template object `" + + object + + "`. Expected one of: " + + SmTemplateObjects.join(", ") + + ".", + ); + } + return Response.success(new TemplateResponse(SmTemplates[object as SmTemplateObject]())); + } + + static create() { + return new TemplateCommand(); + } +} diff --git a/bitwarden_license/bit-cli/src/secrets-manager/trash/trash-empty.command.spec.ts b/bitwarden_license/bit-cli/src/secrets-manager/trash/trash-empty.command.spec.ts new file mode 100644 index 00000000000..0b3f871643f --- /dev/null +++ b/bitwarden_license/bit-cli/src/secrets-manager/trash/trash-empty.command.spec.ts @@ -0,0 +1,92 @@ +import { mock } from "jest-mock-extended"; + +import { SecretListView, SecretService } from "@bitwarden/bit-sm"; + +import { smNotFoundError, smOrgId, smOrg } from "../spec/sm-test-utils"; + +import { TrashEmptyCommand } from "./trash-empty.command"; + +describe("TrashEmptyCommand", () => { + const secretService = mock(); + const firstId = "22222222-2222-2222-2222-222222222222"; + const secondId = "33333333-3333-3333-3333-333333333333"; + let command: TrashEmptyCommand; + + const trashed = [ + Object.assign(new SecretListView(), { id: firstId, organizationId: smOrgId, name: "A" }), + Object.assign(new SecretListView(), { id: secondId, organizationId: smOrgId, name: "B" }), + ]; + + beforeEach(() => { + jest.clearAllMocks(); + secretService.getTrashedSecrets.mockResolvedValue(trashed); + command = new TrashEmptyCommand(secretService); + }); + + it("applies to the given trashed secrets", async () => { + const response = await command.run(smOrg, { secretIds: [secondId.toUpperCase()] }); + + expect(response.success).toBe(true); + expect(secretService.deleteTrashed).toHaveBeenCalledWith(smOrgId, [secondId]); + expect(secretService.restoreTrashed).not.toHaveBeenCalled(); + expect(response.data).toMatchObject({ + object: "list", + data: [{ object: "sm-bulk-status", id: secondId, name: "B" }], + }); + }); + + it("applies to every trashed secret with --all", async () => { + const response = await command.run(smOrg, { all: true }); + + expect(response.success).toBe(true); + expect(secretService.deleteTrashed).toHaveBeenCalledWith(smOrgId, [firstId, secondId]); + }); + + it("does nothing when --all is given and the trash is empty", async () => { + secretService.getTrashedSecrets.mockResolvedValue([]); + + const response = await command.run(smOrg, { all: true }); + + expect(response.success).toBe(true); + expect(secretService.deleteTrashed).not.toHaveBeenCalled(); + }); + + it("requires ids or --all", async () => { + const response = await command.run(smOrg, { secretIds: [] }); + + expect(response.success).toBe(false); + expect(response.message).toBe("Provide one or more secret ids, or `--all`."); + expect(secretService.getTrashedSecrets).not.toHaveBeenCalled(); + }); + + it("rejects ids together with --all", async () => { + const response = await command.run(smOrg, { secretIds: [firstId], all: true }); + + expect(response.success).toBe(false); + expect(response.message).toBe("Provide secret ids or `--all`, not both."); + expect(secretService.deleteTrashed).not.toHaveBeenCalled(); + }); + + it("rejects a secret that is not in the trash", async () => { + const unknownId = "44444444-4444-4444-4444-444444444444"; + + const response = await command.run(smOrg, { secretIds: [firstId, unknownId] }); + + expect(response.success).toBe(false); + expect(response.message).toBe( + "The trashed secret `" + unknownId + "` was not found, or you do not have access to it.", + ); + expect(secretService.deleteTrashed).not.toHaveBeenCalled(); + }); + + it("maps a 404 to a friendly error", async () => { + secretService.getTrashedSecrets.mockRejectedValue(smNotFoundError()); + + const response = await command.run(smOrg, { all: true }); + + expect(response.success).toBe(false); + expect(response.message).toBe( + "The organization was not found, or you do not have access to it.", + ); + }); +}); diff --git a/bitwarden_license/bit-cli/src/secrets-manager/trash/trash-empty.command.ts b/bitwarden_license/bit-cli/src/secrets-manager/trash/trash-empty.command.ts new file mode 100644 index 00000000000..305db4f5e7a --- /dev/null +++ b/bitwarden_license/bit-cli/src/secrets-manager/trash/trash-empty.command.ts @@ -0,0 +1,40 @@ +import { SecretService } from "@bitwarden/bit-sm"; +import { Response } from "@bitwarden/cli/models/response"; + +import { ServiceContainer } from "../../service-container"; +import { SmOrganization, smErrorResponse } from "../sm-command.utils"; + +import { selectTrashedSecrets, SmTrashSelection, trashResultResponse } from "./trash-selection"; + +export class TrashEmptyCommand { + constructor(private secretService: SecretService) {} + + async run(org: SmOrganization, selection: SmTrashSelection): Promise { + const hasNoSecretIds = selection.secretIds == null || selection.secretIds.length === 0; + if (!selection.all && hasNoSecretIds) { + return Response.badRequest("Provide one or more secret ids, or `--all`."); + } + + try { + const trashed = await this.secretService.getTrashedSecrets(org.organizationId); + const selected = selectTrashedSecrets(trashed, selection); + if (selected.error) { + return selected.error; + } + + if (selected.secrets.length > 0) { + await this.secretService.deleteTrashed( + org.organizationId, + selected.secrets.map((s) => s.id), + ); + } + return trashResultResponse(selected.secrets); + } catch (e) { + return smErrorResponse(e, "organization"); + } + } + + static create(serviceContainer: ServiceContainer) { + return new TrashEmptyCommand(serviceContainer.secretService); + } +} diff --git a/bitwarden_license/bit-cli/src/secrets-manager/trash/trash-list.command.spec.ts b/bitwarden_license/bit-cli/src/secrets-manager/trash/trash-list.command.spec.ts new file mode 100644 index 00000000000..ec30cc0845e --- /dev/null +++ b/bitwarden_license/bit-cli/src/secrets-manager/trash/trash-list.command.spec.ts @@ -0,0 +1,47 @@ +import { mock } from "jest-mock-extended"; + +import { SecretListView, SecretService } from "@bitwarden/bit-sm"; +import { ListResponse } from "@bitwarden/cli/models/response/list.response"; + +import { SmSecretResponse } from "../models/sm-secret.response"; +import { smNotFoundError, smOrgId, smOrg } from "../spec/sm-test-utils"; + +import { TrashListCommand } from "./trash-list.command"; + +describe("TrashListCommand", () => { + const secretService = mock(); + let command: TrashListCommand; + + beforeEach(() => { + jest.clearAllMocks(); + command = new TrashListCommand(secretService); + }); + + it("lists the trashed secrets", async () => { + const secret = Object.assign(new SecretListView(), { + id: "22222222-2222-2222-2222-222222222222", + organizationId: smOrgId, + name: "OLD_TOKEN", + projects: [], + }); + secretService.getTrashedSecrets.mockResolvedValue([secret]); + + const response = await command.run(smOrg); + + expect(response.success).toBe(true); + expect(secretService.getTrashedSecrets).toHaveBeenCalledWith(smOrgId); + const data = (response.data as ListResponse).data as SmSecretResponse[]; + expect(data[0]).toMatchObject({ object: "sm-secret", key: "OLD_TOKEN" }); + }); + + it("maps a 404 to a friendly error", async () => { + secretService.getTrashedSecrets.mockRejectedValue(smNotFoundError()); + + const response = await command.run(smOrg); + + expect(response.success).toBe(false); + expect(response.message).toBe( + "The organization was not found, or you do not have access to it.", + ); + }); +}); diff --git a/bitwarden_license/bit-cli/src/secrets-manager/trash/trash-list.command.ts b/bitwarden_license/bit-cli/src/secrets-manager/trash/trash-list.command.ts new file mode 100644 index 00000000000..37cadde12a2 --- /dev/null +++ b/bitwarden_license/bit-cli/src/secrets-manager/trash/trash-list.command.ts @@ -0,0 +1,24 @@ +import { SecretService } from "@bitwarden/bit-sm"; +import { Response } from "@bitwarden/cli/models/response"; +import { ListResponse } from "@bitwarden/cli/models/response/list.response"; + +import { ServiceContainer } from "../../service-container"; +import { SmSecretResponse } from "../models/sm-secret.response"; +import { SmOrganization, smErrorResponse } from "../sm-command.utils"; + +export class TrashListCommand { + constructor(private secretService: SecretService) {} + + async run(org: SmOrganization): Promise { + try { + const secrets = await this.secretService.getTrashedSecrets(org.organizationId); + return Response.success(new ListResponse(secrets.map((s) => new SmSecretResponse(s)))); + } catch (e) { + return smErrorResponse(e, "organization"); + } + } + + static create(serviceContainer: ServiceContainer) { + return new TrashListCommand(serviceContainer.secretService); + } +} diff --git a/bitwarden_license/bit-cli/src/secrets-manager/trash/trash-restore.command.spec.ts b/bitwarden_license/bit-cli/src/secrets-manager/trash/trash-restore.command.spec.ts new file mode 100644 index 00000000000..b77b4b2821c --- /dev/null +++ b/bitwarden_license/bit-cli/src/secrets-manager/trash/trash-restore.command.spec.ts @@ -0,0 +1,92 @@ +import { mock } from "jest-mock-extended"; + +import { SecretListView, SecretService } from "@bitwarden/bit-sm"; + +import { smNotFoundError, smOrgId, smOrg } from "../spec/sm-test-utils"; + +import { TrashRestoreCommand } from "./trash-restore.command"; + +describe("TrashRestoreCommand", () => { + const secretService = mock(); + const firstId = "22222222-2222-2222-2222-222222222222"; + const secondId = "33333333-3333-3333-3333-333333333333"; + let command: TrashRestoreCommand; + + const trashed = [ + Object.assign(new SecretListView(), { id: firstId, organizationId: smOrgId, name: "A" }), + Object.assign(new SecretListView(), { id: secondId, organizationId: smOrgId, name: "B" }), + ]; + + beforeEach(() => { + jest.clearAllMocks(); + secretService.getTrashedSecrets.mockResolvedValue(trashed); + command = new TrashRestoreCommand(secretService); + }); + + it("applies to the given trashed secrets", async () => { + const response = await command.run(smOrg, { secretIds: [secondId.toUpperCase()] }); + + expect(response.success).toBe(true); + expect(secretService.restoreTrashed).toHaveBeenCalledWith(smOrgId, [secondId]); + expect(secretService.deleteTrashed).not.toHaveBeenCalled(); + expect(response.data).toMatchObject({ + object: "list", + data: [{ object: "sm-bulk-status", id: secondId, name: "B" }], + }); + }); + + it("applies to every trashed secret with --all", async () => { + const response = await command.run(smOrg, { all: true }); + + expect(response.success).toBe(true); + expect(secretService.restoreTrashed).toHaveBeenCalledWith(smOrgId, [firstId, secondId]); + }); + + it("does nothing when --all is given and the trash is empty", async () => { + secretService.getTrashedSecrets.mockResolvedValue([]); + + const response = await command.run(smOrg, { all: true }); + + expect(response.success).toBe(true); + expect(secretService.restoreTrashed).not.toHaveBeenCalled(); + }); + + it("requires ids or --all", async () => { + const response = await command.run(smOrg, { secretIds: [] }); + + expect(response.success).toBe(false); + expect(response.message).toBe("Provide one or more secret ids, or `--all`."); + expect(secretService.getTrashedSecrets).not.toHaveBeenCalled(); + }); + + it("rejects ids together with --all", async () => { + const response = await command.run(smOrg, { secretIds: [firstId], all: true }); + + expect(response.success).toBe(false); + expect(response.message).toBe("Provide secret ids or `--all`, not both."); + expect(secretService.restoreTrashed).not.toHaveBeenCalled(); + }); + + it("rejects a secret that is not in the trash", async () => { + const unknownId = "44444444-4444-4444-4444-444444444444"; + + const response = await command.run(smOrg, { secretIds: [firstId, unknownId] }); + + expect(response.success).toBe(false); + expect(response.message).toBe( + "The trashed secret `" + unknownId + "` was not found, or you do not have access to it.", + ); + expect(secretService.restoreTrashed).not.toHaveBeenCalled(); + }); + + it("maps a 404 to a friendly error", async () => { + secretService.getTrashedSecrets.mockRejectedValue(smNotFoundError()); + + const response = await command.run(smOrg, { all: true }); + + expect(response.success).toBe(false); + expect(response.message).toBe( + "The organization was not found, or you do not have access to it.", + ); + }); +}); diff --git a/bitwarden_license/bit-cli/src/secrets-manager/trash/trash-restore.command.ts b/bitwarden_license/bit-cli/src/secrets-manager/trash/trash-restore.command.ts new file mode 100644 index 00000000000..5c8824fe83b --- /dev/null +++ b/bitwarden_license/bit-cli/src/secrets-manager/trash/trash-restore.command.ts @@ -0,0 +1,40 @@ +import { SecretService } from "@bitwarden/bit-sm"; +import { Response } from "@bitwarden/cli/models/response"; + +import { ServiceContainer } from "../../service-container"; +import { SmOrganization, smErrorResponse } from "../sm-command.utils"; + +import { selectTrashedSecrets, SmTrashSelection, trashResultResponse } from "./trash-selection"; + +export class TrashRestoreCommand { + constructor(private secretService: SecretService) {} + + async run(org: SmOrganization, selection: SmTrashSelection): Promise { + const hasNoSecretIds = selection.secretIds == null || selection.secretIds.length === 0; + if (!selection.all && hasNoSecretIds) { + return Response.badRequest("Provide one or more secret ids, or `--all`."); + } + + try { + const trashed = await this.secretService.getTrashedSecrets(org.organizationId); + const selected = selectTrashedSecrets(trashed, selection); + if (selected.error) { + return selected.error; + } + + if (selected.secrets.length > 0) { + await this.secretService.restoreTrashed( + org.organizationId, + selected.secrets.map((s) => s.id), + ); + } + return trashResultResponse(selected.secrets); + } catch (e) { + return smErrorResponse(e, "organization"); + } + } + + static create(serviceContainer: ServiceContainer) { + return new TrashRestoreCommand(serviceContainer.secretService); + } +} diff --git a/bitwarden_license/bit-cli/src/secrets-manager/trash/trash-selection.ts b/bitwarden_license/bit-cli/src/secrets-manager/trash/trash-selection.ts new file mode 100644 index 00000000000..a53f5561686 --- /dev/null +++ b/bitwarden_license/bit-cli/src/secrets-manager/trash/trash-selection.ts @@ -0,0 +1,55 @@ +import { BulkOperationStatus, SecretListView } from "@bitwarden/bit-sm"; +import { Response } from "@bitwarden/cli/models/response"; +import { ListResponse } from "@bitwarden/cli/models/response/list.response"; + +import { SmBulkStatusResponse } from "../models/sm-bulk-status.response"; +import { parseSmIds, smNotFoundResponse } from "../sm-command.utils"; + +export type SmTrashSelection = { + secretIds?: string[]; + all?: boolean; +}; + +/** + * Resolves the trashed secrets a trash command applies to: either every trashed secret + * (`all`) or the given ids, each of which must be in the trash. + */ +export function selectTrashedSecrets( + trashed: SecretListView[], + selection: SmTrashSelection, +): { secrets: SecretListView[]; error?: undefined } | { secrets?: undefined; error: Response } { + const secretIds = selection.secretIds ?? []; + if (selection.all && secretIds.length > 0) { + return { error: Response.badRequest("Provide secret ids or `--all`, not both.") }; + } + if (selection.all) { + return { secrets: trashed }; + } + + const parsed = parseSmIds(secretIds, "secretId"); + if (parsed.error) { + return { error: parsed.error }; + } + const secrets: SecretListView[] = []; + for (const id of parsed.ids) { + const secret = trashed.find((s) => s.id === id); + if (secret == null) { + return { error: smNotFoundResponse("trashed secret `" + id + "`") }; + } + secrets.push(secret); + } + return { secrets }; +} + +export function trashResultResponse(secrets: SecretListView[]): Response { + return Response.success( + new ListResponse( + secrets.map((s) => { + const status = new BulkOperationStatus(); + status.id = s.id; + status.name = s.name; + return new SmBulkStatusResponse(status); + }), + ), + ); +} diff --git a/bitwarden_license/bit-cli/src/service-container.ts b/bitwarden_license/bit-cli/src/service-container.ts index 749657e60a1..cacbedfa3f4 100644 --- a/bitwarden_license/bit-cli/src/service-container.ts +++ b/bitwarden_license/bit-cli/src/service-container.ts @@ -4,6 +4,17 @@ import { OrganizationAuthRequestService, OrganizationAuthRequestApiService, } from "@bitwarden/bit-common/admin-console/auth-requests"; +import { + AccessPolicyService, + AccessService, + CountService, + ProjectService, + SecretService, + SecretVersionService, + SecretsManagerPortingApiService, + ServiceAccountEventLogApiService, + ServiceAccountService, +} from "@bitwarden/bit-sm"; import { CliLicenseType } from "@bitwarden/cli/platform/cli-license-type"; import { ServiceContainer as OssServiceContainer } from "@bitwarden/cli/service-container/service-container"; @@ -16,6 +27,15 @@ export class ServiceContainer extends OssServiceContainer { organizationAuthRequestApiService: OrganizationAuthRequestApiService; organizationAuthRequestService: OrganizationAuthRequestService; + accessPolicyService: AccessPolicyService; + projectService: ProjectService; + secretService: SecretService; + secretVersionService: SecretVersionService; + serviceAccountService: ServiceAccountService; + accessService: AccessService; + serviceAccountEventLogApiService: ServiceAccountEventLogApiService; + countService: CountService; + secretsManagerPortingApiService: SecretsManagerPortingApiService; constructor() { super(); @@ -28,5 +48,55 @@ export class ServiceContainer extends OssServiceContainer { this.organizationUserApiService, this.accountService, ); + + this.accessPolicyService = new AccessPolicyService( + this.keyService, + this.apiService, + this.encryptService, + this.accountService, + this.logService, + ); + this.projectService = new ProjectService( + this.keyService, + this.apiService, + this.encryptService, + this.accountService, + ); + this.secretService = new SecretService( + this.keyService, + this.apiService, + this.encryptService, + this.accessPolicyService, + this.accountService, + ); + this.secretVersionService = new SecretVersionService( + this.keyService, + this.apiService, + this.encryptService, + this.accountService, + ); + this.serviceAccountService = new ServiceAccountService( + this.keyService, + this.apiService, + this.encryptService, + this.accountService, + this.logService, + ); + this.accessService = new AccessService( + this.keyService, + this.apiService, + this.keyGenerationService, + this.encryptService, + this.accountService, + this.logService, + ); + this.serviceAccountEventLogApiService = new ServiceAccountEventLogApiService(this.apiService); + this.countService = new CountService(this.apiService); + this.secretsManagerPortingApiService = new SecretsManagerPortingApiService( + this.apiService, + this.encryptService, + this.keyService, + this.accountService, + ); } } diff --git a/bitwarden_license/bit-sm/README.md b/bitwarden_license/bit-sm/README.md new file mode 100644 index 00000000000..80f8ce74856 --- /dev/null +++ b/bitwarden_license/bit-sm/README.md @@ -0,0 +1,16 @@ +# Secrets Manager + +Commercial Secrets Manager library: API services, request/response DTOs and view models for +projects, secrets, machine accounts (service accounts), access policies, counts, events and +import/export. + +The code here is **framework-agnostic** (no Angular) so that it is not tied to the web vault +(`bitwarden_license/bit-web`) or the `bw sm` CLI (`bitwarden_license/bit-cli`), which consume it. +The Angular DI wiring lives in `bitwarden_license/bit-web/src/app/secrets-manager/provide-secrets-manager.ts`; +the CLI instantiates the services in `bitwarden_license/bit-cli/src/service-container.ts`. + +Import from the barrel via the `@bitwarden/bit-sm` path alias (`src/index.ts`); do not deep import. + +## Running tests + +`npm test -- bit-sm` diff --git a/bitwarden_license/bit-sm/jest.config.js b/bitwarden_license/bit-sm/jest.config.js new file mode 100644 index 00000000000..01c63fa9934 --- /dev/null +++ b/bitwarden_license/bit-sm/jest.config.js @@ -0,0 +1,20 @@ +const { pathsToModuleNameMapper } = require("ts-jest"); + +const { compilerOptions } = require("../../tsconfig.base"); + +const sharedConfig = require("../../libs/shared/jest.config.angular"); + +/** @type {import('jest').Config} */ +module.exports = { + ...sharedConfig, + displayName: "bit-sm tests", + coverageDirectory: "../../coverage/bitwarden_license/bit-sm", + setupFilesAfterEnv: ["/test.setup.ts"], + moduleNameMapper: pathsToModuleNameMapper( + // lets us use @bitwarden/common/spec in tests + { "@bitwarden/common/spec": ["libs/common/spec"], ...(compilerOptions?.paths ?? {}) }, + { + prefix: "/../../", + }, + ), +}; diff --git a/bitwarden_license/bit-sm/package.json b/bitwarden_license/bit-sm/package.json new file mode 100644 index 00000000000..3215fcccafe --- /dev/null +++ b/bitwarden_license/bit-sm/package.json @@ -0,0 +1,22 @@ +{ + "name": "@bitwarden/bit-sm", + "version": "0.0.0", + "description": "Secrets Manager services, models, requests and responses — commercial, Angular-free.", + "keywords": [ + "bitwarden" + ], + "author": "Bitwarden Inc.", + "homepage": "https://bitwarden.com", + "repository": { + "type": "git", + "url": "https://github.com/bitwarden/clients" + }, + "license": "SEE LICENSE IN ../../LICENSE_BITWARDEN.txt", + "private": true, + "scripts": { + "clean": "rimraf dist", + "build": "npm run clean && tsc", + "build:watch": "npm run clean && tsc -watch", + "test": "jest" + } +} diff --git a/bitwarden_license/bit-sm/project.json b/bitwarden_license/bit-sm/project.json new file mode 100644 index 00000000000..f3d70695640 --- /dev/null +++ b/bitwarden_license/bit-sm/project.json @@ -0,0 +1,29 @@ +{ + "name": "bit-sm", + "$schema": "../../node_modules/nx/schemas/project-schema.json", + "sourceRoot": "bitwarden_license/bit-sm/src", + "projectType": "library", + "tags": [], + "targets": { + "build": { + "executor": "nx:run-script", + "dependsOn": [], + "options": { + "script": "build" + } + }, + "lint": { + "executor": "@nx/eslint:lint", + "outputs": ["{options.outputFile}"], + "options": { + "lintFilePatterns": ["bitwarden_license/bit-sm/**/*.ts"] + } + }, + "test": { + "executor": "nx:run-script", + "options": { + "script": "test" + } + } + } +} diff --git a/bitwarden_license/bit-sm/src/index.ts b/bitwarden_license/bit-sm/src/index.ts new file mode 100644 index 00000000000..c2c61154e2b --- /dev/null +++ b/bitwarden_license/bit-sm/src/index.ts @@ -0,0 +1,32 @@ +export * from "./models/bulk-operation-status"; +export * from "./models/view/access-policies/access-policy.view"; +export * from "./models/view/access-policies/potential-grantee.view"; +export * from "./models/view/access-policies/project-people-access-policies.view"; +export * from "./models/view/access-policies/project-service-accounts-access-policies.view"; +export * from "./models/view/access-policies/secret-access-policies.view"; +export * from "./models/view/access-policies/service-account-granted-policies.view"; +export * from "./models/view/access-policies/service-account-people-access-policies.view"; +export * from "./models/view/counts.view"; +export * from "./models/view/project-list.view"; +export * from "./models/view/project.view"; +export * from "./models/view/secret-list.view"; +export * from "./models/view/secret-project.view"; +export * from "./models/view/secret-version.view"; +export * from "./models/view/secret.view"; +export * from "./models/view/service-account.view"; +export * from "./projects/project.service"; +export * from "./secrets/secret-version.service"; +export * from "./secrets/secret.service"; +export * from "./service-accounts/access/access.service"; +export * from "./service-accounts/event-logs/service-account-event-log-api.service"; +export * from "./service-accounts/models/view/access-token.view"; +export * from "./service-accounts/service-account.service"; +export * from "./settings/models/error/sm-import-error"; +export * from "./settings/models/error/sm-import-error-line"; +export * from "./settings/models/sm-export"; +export * from "./settings/services/sm-porting-api.service"; +export * from "./shared/access-policies/access-policy.service"; +export * from "./shared/counts/count.service"; +export * from "./shared/counts/models/responses/organization-counts.response"; +export * from "./shared/counts/models/responses/project-counts.response"; +export * from "./shared/counts/models/responses/service-account-counts.response"; diff --git a/bitwarden_license/bit-sm/src/models/bulk-operation-status.ts b/bitwarden_license/bit-sm/src/models/bulk-operation-status.ts new file mode 100644 index 00000000000..338e6c71134 --- /dev/null +++ b/bitwarden_license/bit-sm/src/models/bulk-operation-status.ts @@ -0,0 +1,5 @@ +export class BulkOperationStatus { + id!: string; + name!: string; + errorMessage?: string; +} diff --git a/bitwarden_license/bit-web/src/app/secrets-manager/models/view/access-policies/access-policy.view.ts b/bitwarden_license/bit-sm/src/models/view/access-policies/access-policy.view.ts similarity index 100% rename from bitwarden_license/bit-web/src/app/secrets-manager/models/view/access-policies/access-policy.view.ts rename to bitwarden_license/bit-sm/src/models/view/access-policies/access-policy.view.ts diff --git a/bitwarden_license/bit-web/src/app/secrets-manager/models/view/access-policies/potential-grantee.view.ts b/bitwarden_license/bit-sm/src/models/view/access-policies/potential-grantee.view.ts similarity index 100% rename from bitwarden_license/bit-web/src/app/secrets-manager/models/view/access-policies/potential-grantee.view.ts rename to bitwarden_license/bit-sm/src/models/view/access-policies/potential-grantee.view.ts diff --git a/bitwarden_license/bit-web/src/app/secrets-manager/models/view/access-policies/project-people-access-policies.view.ts b/bitwarden_license/bit-sm/src/models/view/access-policies/project-people-access-policies.view.ts similarity index 100% rename from bitwarden_license/bit-web/src/app/secrets-manager/models/view/access-policies/project-people-access-policies.view.ts rename to bitwarden_license/bit-sm/src/models/view/access-policies/project-people-access-policies.view.ts diff --git a/bitwarden_license/bit-web/src/app/secrets-manager/models/view/access-policies/project-service-accounts-access-policies.view.ts b/bitwarden_license/bit-sm/src/models/view/access-policies/project-service-accounts-access-policies.view.ts similarity index 100% rename from bitwarden_license/bit-web/src/app/secrets-manager/models/view/access-policies/project-service-accounts-access-policies.view.ts rename to bitwarden_license/bit-sm/src/models/view/access-policies/project-service-accounts-access-policies.view.ts diff --git a/bitwarden_license/bit-web/src/app/secrets-manager/models/view/access-policies/secret-access-policies.view.ts b/bitwarden_license/bit-sm/src/models/view/access-policies/secret-access-policies.view.ts similarity index 100% rename from bitwarden_license/bit-web/src/app/secrets-manager/models/view/access-policies/secret-access-policies.view.ts rename to bitwarden_license/bit-sm/src/models/view/access-policies/secret-access-policies.view.ts diff --git a/bitwarden_license/bit-web/src/app/secrets-manager/models/view/access-policies/service-account-granted-policies.view.ts b/bitwarden_license/bit-sm/src/models/view/access-policies/service-account-granted-policies.view.ts similarity index 100% rename from bitwarden_license/bit-web/src/app/secrets-manager/models/view/access-policies/service-account-granted-policies.view.ts rename to bitwarden_license/bit-sm/src/models/view/access-policies/service-account-granted-policies.view.ts diff --git a/bitwarden_license/bit-web/src/app/secrets-manager/models/view/access-policies/service-account-people-access-policies.view.ts b/bitwarden_license/bit-sm/src/models/view/access-policies/service-account-people-access-policies.view.ts similarity index 100% rename from bitwarden_license/bit-web/src/app/secrets-manager/models/view/access-policies/service-account-people-access-policies.view.ts rename to bitwarden_license/bit-sm/src/models/view/access-policies/service-account-people-access-policies.view.ts diff --git a/bitwarden_license/bit-web/src/app/secrets-manager/models/view/counts.view.ts b/bitwarden_license/bit-sm/src/models/view/counts.view.ts similarity index 100% rename from bitwarden_license/bit-web/src/app/secrets-manager/models/view/counts.view.ts rename to bitwarden_license/bit-sm/src/models/view/counts.view.ts diff --git a/bitwarden_license/bit-web/src/app/secrets-manager/models/view/project-list.view.ts b/bitwarden_license/bit-sm/src/models/view/project-list.view.ts similarity index 100% rename from bitwarden_license/bit-web/src/app/secrets-manager/models/view/project-list.view.ts rename to bitwarden_license/bit-sm/src/models/view/project-list.view.ts diff --git a/bitwarden_license/bit-web/src/app/secrets-manager/models/view/project.view.ts b/bitwarden_license/bit-sm/src/models/view/project.view.ts similarity index 100% rename from bitwarden_license/bit-web/src/app/secrets-manager/models/view/project.view.ts rename to bitwarden_license/bit-sm/src/models/view/project.view.ts diff --git a/bitwarden_license/bit-web/src/app/secrets-manager/models/view/secret-list.view.ts b/bitwarden_license/bit-sm/src/models/view/secret-list.view.ts similarity index 100% rename from bitwarden_license/bit-web/src/app/secrets-manager/models/view/secret-list.view.ts rename to bitwarden_license/bit-sm/src/models/view/secret-list.view.ts diff --git a/bitwarden_license/bit-web/src/app/secrets-manager/models/view/secret-project.view.ts b/bitwarden_license/bit-sm/src/models/view/secret-project.view.ts similarity index 100% rename from bitwarden_license/bit-web/src/app/secrets-manager/models/view/secret-project.view.ts rename to bitwarden_license/bit-sm/src/models/view/secret-project.view.ts diff --git a/bitwarden_license/bit-web/src/app/secrets-manager/models/view/secret-version.view.ts b/bitwarden_license/bit-sm/src/models/view/secret-version.view.ts similarity index 100% rename from bitwarden_license/bit-web/src/app/secrets-manager/models/view/secret-version.view.ts rename to bitwarden_license/bit-sm/src/models/view/secret-version.view.ts diff --git a/bitwarden_license/bit-web/src/app/secrets-manager/models/view/secret.view.ts b/bitwarden_license/bit-sm/src/models/view/secret.view.ts similarity index 100% rename from bitwarden_license/bit-web/src/app/secrets-manager/models/view/secret.view.ts rename to bitwarden_license/bit-sm/src/models/view/secret.view.ts diff --git a/bitwarden_license/bit-web/src/app/secrets-manager/models/view/service-account.view.ts b/bitwarden_license/bit-sm/src/models/view/service-account.view.ts similarity index 100% rename from bitwarden_license/bit-web/src/app/secrets-manager/models/view/service-account.view.ts rename to bitwarden_license/bit-sm/src/models/view/service-account.view.ts diff --git a/bitwarden_license/bit-web/src/app/secrets-manager/projects/models/requests/project.request.ts b/bitwarden_license/bit-sm/src/projects/models/requests/project.request.ts similarity index 100% rename from bitwarden_license/bit-web/src/app/secrets-manager/projects/models/requests/project.request.ts rename to bitwarden_license/bit-sm/src/projects/models/requests/project.request.ts diff --git a/bitwarden_license/bit-web/src/app/secrets-manager/projects/models/responses/project-list-item.response.ts b/bitwarden_license/bit-sm/src/projects/models/responses/project-list-item.response.ts similarity index 100% rename from bitwarden_license/bit-web/src/app/secrets-manager/projects/models/responses/project-list-item.response.ts rename to bitwarden_license/bit-sm/src/projects/models/responses/project-list-item.response.ts diff --git a/bitwarden_license/bit-web/src/app/secrets-manager/projects/models/responses/project.response.ts b/bitwarden_license/bit-sm/src/projects/models/responses/project.response.ts similarity index 100% rename from bitwarden_license/bit-web/src/app/secrets-manager/projects/models/responses/project.response.ts rename to bitwarden_license/bit-sm/src/projects/models/responses/project.response.ts diff --git a/bitwarden_license/bit-web/src/app/secrets-manager/projects/project.service.ts b/bitwarden_license/bit-sm/src/projects/project.service.ts similarity index 96% rename from bitwarden_license/bit-web/src/app/secrets-manager/projects/project.service.ts rename to bitwarden_license/bit-sm/src/projects/project.service.ts index c5892304c87..60b6ed05fe0 100644 --- a/bitwarden_license/bit-web/src/app/secrets-manager/projects/project.service.ts +++ b/bitwarden_license/bit-sm/src/projects/project.service.ts @@ -1,6 +1,5 @@ // FIXME: Update this file to be type safe and remove this and next line // @ts-strict-ignore -import { Injectable } from "@angular/core"; import { filter, firstValueFrom, map, Subject, switchMap } from "rxjs"; import { ApiService } from "@bitwarden/common/abstractions/api.service"; @@ -17,17 +16,14 @@ import { SymmetricCryptoKey, } from "@bitwarden/legacy-crypto"; +import { BulkOperationStatus } from "../models/bulk-operation-status"; import { ProjectListView } from "../models/view/project-list.view"; import { ProjectView } from "../models/view/project.view"; -import { BulkOperationStatus } from "../shared/dialogs/bulk-status-dialog.component"; import { ProjectRequest } from "./models/requests/project.request"; import { ProjectListItemResponse } from "./models/responses/project-list-item.response"; import { ProjectResponse } from "./models/responses/project.response"; -@Injectable({ - providedIn: "root", -}) export class ProjectService { protected _project = new Subject(); project$ = this._project.asObservable(); @@ -100,10 +96,12 @@ export class ProjectService { return project; } - async update(organizationId: string, projectView: ProjectView) { + async update(organizationId: string, projectView: ProjectView): Promise { const request = await this.getProjectRequest(organizationId, projectView); const r = await this.apiService.send("PUT", "/projects/" + projectView.id, request, true, true); - this._project.next(await this.createProjectView(new ProjectResponse(r))); + const project = await this.createProjectView(new ProjectResponse(r)); + this._project.next(project); + return project; } async delete(projects: ProjectListView[]): Promise { diff --git a/bitwarden_license/bit-web/src/app/secrets-manager/secrets/requests/secret.request.ts b/bitwarden_license/bit-sm/src/secrets/requests/secret.request.ts similarity index 100% rename from bitwarden_license/bit-web/src/app/secrets-manager/secrets/requests/secret.request.ts rename to bitwarden_license/bit-sm/src/secrets/requests/secret.request.ts diff --git a/bitwarden_license/bit-web/src/app/secrets-manager/secrets/responses/secret-list-item.response.ts b/bitwarden_license/bit-sm/src/secrets/responses/secret-list-item.response.ts similarity index 100% rename from bitwarden_license/bit-web/src/app/secrets-manager/secrets/responses/secret-list-item.response.ts rename to bitwarden_license/bit-sm/src/secrets/responses/secret-list-item.response.ts diff --git a/bitwarden_license/bit-web/src/app/secrets-manager/secrets/responses/secret-project.response.ts b/bitwarden_license/bit-sm/src/secrets/responses/secret-project.response.ts similarity index 100% rename from bitwarden_license/bit-web/src/app/secrets-manager/secrets/responses/secret-project.response.ts rename to bitwarden_license/bit-sm/src/secrets/responses/secret-project.response.ts diff --git a/bitwarden_license/bit-web/src/app/secrets-manager/secrets/responses/secret-version-list.response.ts b/bitwarden_license/bit-sm/src/secrets/responses/secret-version-list.response.ts similarity index 100% rename from bitwarden_license/bit-web/src/app/secrets-manager/secrets/responses/secret-version-list.response.ts rename to bitwarden_license/bit-sm/src/secrets/responses/secret-version-list.response.ts diff --git a/bitwarden_license/bit-web/src/app/secrets-manager/secrets/responses/secret-version.response.ts b/bitwarden_license/bit-sm/src/secrets/responses/secret-version.response.ts similarity index 100% rename from bitwarden_license/bit-web/src/app/secrets-manager/secrets/responses/secret-version.response.ts rename to bitwarden_license/bit-sm/src/secrets/responses/secret-version.response.ts diff --git a/bitwarden_license/bit-web/src/app/secrets-manager/secrets/responses/secret-with-projects-list.response.ts b/bitwarden_license/bit-sm/src/secrets/responses/secret-with-projects-list.response.ts similarity index 100% rename from bitwarden_license/bit-web/src/app/secrets-manager/secrets/responses/secret-with-projects-list.response.ts rename to bitwarden_license/bit-sm/src/secrets/responses/secret-with-projects-list.response.ts diff --git a/bitwarden_license/bit-web/src/app/secrets-manager/secrets/responses/secret.response.ts b/bitwarden_license/bit-sm/src/secrets/responses/secret.response.ts similarity index 100% rename from bitwarden_license/bit-web/src/app/secrets-manager/secrets/responses/secret.response.ts rename to bitwarden_license/bit-sm/src/secrets/responses/secret.response.ts diff --git a/bitwarden_license/bit-web/src/app/secrets-manager/secrets/secret-version.service.spec.ts b/bitwarden_license/bit-sm/src/secrets/secret-version.service.spec.ts similarity index 100% rename from bitwarden_license/bit-web/src/app/secrets-manager/secrets/secret-version.service.spec.ts rename to bitwarden_license/bit-sm/src/secrets/secret-version.service.spec.ts diff --git a/bitwarden_license/bit-web/src/app/secrets-manager/secrets/secret-version.service.ts b/bitwarden_license/bit-sm/src/secrets/secret-version.service.ts similarity index 98% rename from bitwarden_license/bit-web/src/app/secrets-manager/secrets/secret-version.service.ts rename to bitwarden_license/bit-sm/src/secrets/secret-version.service.ts index 4991c3ffb6a..39ab15d60e0 100644 --- a/bitwarden_license/bit-web/src/app/secrets-manager/secrets/secret-version.service.ts +++ b/bitwarden_license/bit-sm/src/secrets/secret-version.service.ts @@ -1,4 +1,3 @@ -import { Injectable } from "@angular/core"; import { filter, firstValueFrom, map, switchMap } from "rxjs"; import { ApiService } from "@bitwarden/common/abstractions/api.service"; @@ -26,9 +25,6 @@ export interface SecretVersionHistory { versions: SecretVersionView[]; } -@Injectable({ - providedIn: "root", -}) export class SecretVersionService { constructor( private keyService: KeyService, diff --git a/bitwarden_license/bit-web/src/app/secrets-manager/secrets/secret.service.spec.ts b/bitwarden_license/bit-sm/src/secrets/secret.service.spec.ts similarity index 72% rename from bitwarden_license/bit-web/src/app/secrets-manager/secrets/secret.service.spec.ts rename to bitwarden_license/bit-sm/src/secrets/secret.service.spec.ts index d968b737ebd..2f2156d1f5e 100644 --- a/bitwarden_license/bit-web/src/app/secrets-manager/secrets/secret.service.spec.ts +++ b/bitwarden_license/bit-sm/src/secrets/secret.service.spec.ts @@ -99,6 +99,64 @@ describe("SecretService", () => { await sut.update("organizationId", secretView, secretAccessPoliciesView); }); + + it("returns the updated secret", async () => { + apiService.send.mockResolvedValue(mockedSecretResponse); + + const result = await sut.update("organizationId", secretView, secretAccessPoliciesView); + + expect(result).toEqual(expectedSecretView); + }); + + it("leaves access policies unchanged when none are given", async () => { + apiService.send.mockResolvedValue(mockedSecretResponse); + + await sut.update("organizationId", secretView, undefined, true); + + expect(accessPolicyService.getSecretAccessPoliciesRequest).not.toHaveBeenCalled(); + expect(apiService.send).toHaveBeenCalledWith( + "PUT", + "/secrets/" + secretView.id, + expect.objectContaining({ accessPoliciesRequests: null, valueChanged: true }), + true, + true, + ); + }); + }); + + describe("create without access policies", () => { + it("returns the created secret and sends no access policies", async () => { + apiService.send.mockResolvedValue(mockedSecretResponse); + + const result = await sut.create("organizationId", secretView); + + expect(result).toEqual(expectedSecretView); + expect(accessPolicyService.getSecretAccessPoliciesRequest).not.toHaveBeenCalled(); + expect(apiService.send).toHaveBeenCalledWith( + "POST", + "/organizations/organizationId/secrets", + expect.objectContaining({ accessPoliciesRequests: null }), + true, + true, + ); + }); + }); + + describe("restoreVersion", () => { + it("restores the version and returns the secret", async () => { + apiService.send.mockResolvedValue(mockedSecretResponse); + + const result = await sut.restoreVersion("secret-id", "version-id"); + + expect(apiService.send).toHaveBeenCalledWith( + "PUT", + "/secrets/secret-id/versions/restore", + { versionId: "version-id" }, + true, + true, + ); + expect(result).toEqual(expectedSecretView); + }); }); }); diff --git a/bitwarden_license/bit-web/src/app/secrets-manager/secrets/secret.service.ts b/bitwarden_license/bit-sm/src/secrets/secret.service.ts similarity index 90% rename from bitwarden_license/bit-web/src/app/secrets-manager/secrets/secret.service.ts rename to bitwarden_license/bit-sm/src/secrets/secret.service.ts index 50dafb41f5b..d66a3ca236f 100644 --- a/bitwarden_license/bit-web/src/app/secrets-manager/secrets/secret.service.ts +++ b/bitwarden_license/bit-sm/src/secrets/secret.service.ts @@ -1,6 +1,5 @@ // FIXME: Update this file to be type safe and remove this and next line // @ts-strict-ignore -import { Injectable } from "@angular/core"; import { Subject, firstValueFrom, switchMap, map, filter } from "rxjs"; import { ApiService } from "@bitwarden/common/abstractions/api.service"; @@ -16,12 +15,12 @@ import { SymmetricCryptoKey, } from "@bitwarden/legacy-crypto"; +import { BulkOperationStatus } from "../models/bulk-operation-status"; import { SecretAccessPoliciesView } from "../models/view/access-policies/secret-access-policies.view"; import { SecretListView } from "../models/view/secret-list.view"; import { SecretProjectView } from "../models/view/secret-project.view"; import { SecretView } from "../models/view/secret.view"; import { AccessPolicyService } from "../shared/access-policies/access-policy.service"; -import { BulkOperationStatus } from "../shared/dialogs/bulk-status-dialog.component"; import { SecretRequest } from "./requests/secret.request"; import { SecretListItemResponse } from "./responses/secret-list-item.response"; @@ -29,9 +28,6 @@ import { SecretProjectResponse } from "./responses/secret-project.response"; import { SecretWithProjectsListResponse } from "./responses/secret-with-projects-list.response"; import { SecretResponse } from "./responses/secret.response"; -@Injectable({ - providedIn: "root", -}) export class SecretService { protected _secret: Subject = new Subject(); secret$ = this._secret.asObservable(); @@ -90,11 +86,15 @@ export class SecretService { return await this.createSecretsListView(organizationId, results); } + /** + * Creates a secret. Omit `secretAccessPoliciesView` to create it without + * direct access policies. + */ async create( organizationId: string, secretView: SecretView, - secretAccessPoliciesView: SecretAccessPoliciesView, - ) { + secretAccessPoliciesView?: SecretAccessPoliciesView, + ): Promise { const request = await this.getSecretRequest( organizationId, secretView, @@ -107,15 +107,21 @@ export class SecretService { true, true, ); - this._secret.next(await this.createSecretView(new SecretResponse(r))); + const secret = await this.createSecretView(new SecretResponse(r)); + this._secret.next(secret); + return secret; } + /** + * Updates a secret. Omit `secretAccessPoliciesView` to leave its existing + * access policies unchanged. + */ async update( organizationId: string, secretView: SecretView, - secretAccessPoliciesView: SecretAccessPoliciesView, + secretAccessPoliciesView?: SecretAccessPoliciesView, valueChanged: boolean = false, - ) { + ): Promise { const request = await this.getSecretRequest( organizationId, secretView, @@ -123,10 +129,12 @@ export class SecretService { valueChanged, ); const r = await this.apiService.send("PUT", "/secrets/" + secretView.id, request, true, true); - this._secret.next(await this.createSecretView(new SecretResponse(r))); + const secret = await this.createSecretView(new SecretResponse(r)); + this._secret.next(secret); + return secret; } - async restoreVersion(secretId: string, versionId: string): Promise { + async restoreVersion(secretId: string, versionId: string): Promise { const r = await this.apiService.send( "PUT", `/secrets/${secretId}/versions/restore`, @@ -134,7 +142,9 @@ export class SecretService { true, true, ); - this._secret.next(await this.createSecretView(new SecretResponse(r))); + const secret = await this.createSecretView(new SecretResponse(r)); + this._secret.next(secret); + return secret; } async delete(secrets: SecretListView[]): Promise { @@ -190,7 +200,7 @@ export class SecretService { private async getSecretRequest( organizationId: string, secretView: SecretView, - secretAccessPoliciesView: SecretAccessPoliciesView, + secretAccessPoliciesView: SecretAccessPoliciesView | undefined, valueChanged: boolean = false, ): Promise { const orgKey = await this.getOrganizationKey(organizationId); @@ -209,7 +219,9 @@ export class SecretService { secretView.projects?.forEach((e) => request.projectIds.push(e.id)); request.accessPoliciesRequests = - this.accessPolicyService.getSecretAccessPoliciesRequest(secretAccessPoliciesView); + secretAccessPoliciesView == null + ? null + : this.accessPolicyService.getSecretAccessPoliciesRequest(secretAccessPoliciesView); return request; } diff --git a/bitwarden_license/bit-web/src/app/secrets-manager/service-accounts/access/access.service.ts b/bitwarden_license/bit-sm/src/service-accounts/access/access.service.ts similarity index 98% rename from bitwarden_license/bit-web/src/app/secrets-manager/service-accounts/access/access.service.ts rename to bitwarden_license/bit-sm/src/service-accounts/access/access.service.ts index e6fa869b72d..cc816dca435 100644 --- a/bitwarden_license/bit-web/src/app/secrets-manager/service-accounts/access/access.service.ts +++ b/bitwarden_license/bit-sm/src/service-accounts/access/access.service.ts @@ -1,6 +1,5 @@ // FIXME: Update this file to be type safe and remove this and next line // @ts-strict-ignore -import { Injectable } from "@angular/core"; import { filter, firstValueFrom, map, Subject, switchMap } from "rxjs"; import { ApiService } from "@bitwarden/common/abstractions/api.service"; @@ -26,9 +25,6 @@ import { AccessTokenCreationResponse } from "../models/responses/access-token-cr import { AccessTokenResponse } from "../models/responses/access-tokens.response"; import { AccessTokenView } from "../models/view/access-token.view"; -@Injectable({ - providedIn: "root", -}) export class AccessService { private readonly _accessTokenVersion = "0"; protected _accessToken: Subject = new Subject(); diff --git a/bitwarden_license/bit-web/src/app/secrets-manager/service-accounts/event-logs/service-account-event-log-api.service.ts b/bitwarden_license/bit-sm/src/service-accounts/event-logs/service-account-event-log-api.service.ts similarity index 89% rename from bitwarden_license/bit-web/src/app/secrets-manager/service-accounts/event-logs/service-account-event-log-api.service.ts rename to bitwarden_license/bit-sm/src/service-accounts/event-logs/service-account-event-log-api.service.ts index fcd7ec05ef4..b1d0f629668 100644 --- a/bitwarden_license/bit-web/src/app/secrets-manager/service-accounts/event-logs/service-account-event-log-api.service.ts +++ b/bitwarden_license/bit-sm/src/service-accounts/event-logs/service-account-event-log-api.service.ts @@ -1,12 +1,7 @@ -import { Injectable } from "@angular/core"; - import { ApiService } from "@bitwarden/common/abstractions/api.service"; import { EventResponse } from "@bitwarden/common/dirt/event-logs"; import { ListResponse } from "@bitwarden/common/models/response/list.response"; -@Injectable({ - providedIn: "root", -}) export class ServiceAccountEventLogApiService { constructor(private apiService: ApiService) {} @@ -14,7 +9,7 @@ export class ServiceAccountEventLogApiService { serviceAccountId: string, start: string, end: string, - token: string, + token?: string, ): Promise> { const r = await this.apiService.send( "GET", @@ -26,7 +21,7 @@ export class ServiceAccountEventLogApiService { return new ListResponse(r, EventResponse); } - private addEventParameters(base: string, start: string, end: string, token: string) { + private addEventParameters(base: string, start: string, end: string, token?: string) { if (start != null) { base += "?start=" + start; } diff --git a/bitwarden_license/bit-web/src/app/secrets-manager/service-accounts/models/requests/access-token.request.ts b/bitwarden_license/bit-sm/src/service-accounts/models/requests/access-token.request.ts similarity index 100% rename from bitwarden_license/bit-web/src/app/secrets-manager/service-accounts/models/requests/access-token.request.ts rename to bitwarden_license/bit-sm/src/service-accounts/models/requests/access-token.request.ts diff --git a/bitwarden_license/bit-web/src/app/secrets-manager/service-accounts/models/requests/revoke-access-tokens.request.ts b/bitwarden_license/bit-sm/src/service-accounts/models/requests/revoke-access-tokens.request.ts similarity index 100% rename from bitwarden_license/bit-web/src/app/secrets-manager/service-accounts/models/requests/revoke-access-tokens.request.ts rename to bitwarden_license/bit-sm/src/service-accounts/models/requests/revoke-access-tokens.request.ts diff --git a/bitwarden_license/bit-web/src/app/secrets-manager/service-accounts/models/requests/service-account.request.ts b/bitwarden_license/bit-sm/src/service-accounts/models/requests/service-account.request.ts similarity index 100% rename from bitwarden_license/bit-web/src/app/secrets-manager/service-accounts/models/requests/service-account.request.ts rename to bitwarden_license/bit-sm/src/service-accounts/models/requests/service-account.request.ts diff --git a/bitwarden_license/bit-web/src/app/secrets-manager/service-accounts/models/responses/access-token-creation.response.ts b/bitwarden_license/bit-sm/src/service-accounts/models/responses/access-token-creation.response.ts similarity index 100% rename from bitwarden_license/bit-web/src/app/secrets-manager/service-accounts/models/responses/access-token-creation.response.ts rename to bitwarden_license/bit-sm/src/service-accounts/models/responses/access-token-creation.response.ts diff --git a/bitwarden_license/bit-web/src/app/secrets-manager/service-accounts/models/responses/access-tokens.response.ts b/bitwarden_license/bit-sm/src/service-accounts/models/responses/access-tokens.response.ts similarity index 100% rename from bitwarden_license/bit-web/src/app/secrets-manager/service-accounts/models/responses/access-tokens.response.ts rename to bitwarden_license/bit-sm/src/service-accounts/models/responses/access-tokens.response.ts diff --git a/bitwarden_license/bit-web/src/app/secrets-manager/service-accounts/models/responses/service-account.response.ts b/bitwarden_license/bit-sm/src/service-accounts/models/responses/service-account.response.ts similarity index 100% rename from bitwarden_license/bit-web/src/app/secrets-manager/service-accounts/models/responses/service-account.response.ts rename to bitwarden_license/bit-sm/src/service-accounts/models/responses/service-account.response.ts diff --git a/bitwarden_license/bit-web/src/app/secrets-manager/service-accounts/models/view/access-token.view.ts b/bitwarden_license/bit-sm/src/service-accounts/models/view/access-token.view.ts similarity index 100% rename from bitwarden_license/bit-web/src/app/secrets-manager/service-accounts/models/view/access-token.view.ts rename to bitwarden_license/bit-sm/src/service-accounts/models/view/access-token.view.ts diff --git a/bitwarden_license/bit-web/src/app/secrets-manager/service-accounts/service-account.service.ts b/bitwarden_license/bit-sm/src/service-accounts/service-account.service.ts similarity index 96% rename from bitwarden_license/bit-web/src/app/secrets-manager/service-accounts/service-account.service.ts rename to bitwarden_license/bit-sm/src/service-accounts/service-account.service.ts index ad12444785d..af699e644cc 100644 --- a/bitwarden_license/bit-web/src/app/secrets-manager/service-accounts/service-account.service.ts +++ b/bitwarden_license/bit-sm/src/service-accounts/service-account.service.ts @@ -1,6 +1,5 @@ // FIXME: Update this file to be type safe and remove this and next line // @ts-strict-ignore -import { Injectable } from "@angular/core"; import { filter, firstValueFrom, map, Subject, switchMap } from "rxjs"; import { ApiService } from "@bitwarden/common/abstractions/api.service"; @@ -18,11 +17,11 @@ import { SymmetricCryptoKey, } from "@bitwarden/legacy-crypto"; +import { BulkOperationStatus } from "../models/bulk-operation-status"; import { ServiceAccountSecretsDetailsView, ServiceAccountView, } from "../models/view/service-account.view"; -import { BulkOperationStatus } from "../shared/dialogs/bulk-status-dialog.component"; import { ServiceAccountRequest } from "./models/requests/service-account.request"; import { @@ -30,9 +29,6 @@ import { ServiceAccountSecretsDetailsResponse, } from "./models/responses/service-account.response"; -@Injectable({ - providedIn: "root", -}) export class ServiceAccountService { protected _serviceAccount: Subject = new Subject(); @@ -99,7 +95,7 @@ export class ServiceAccountService { serviceAccountId: string, organizationId: string, serviceAccountView: ServiceAccountView, - ) { + ): Promise { const orgKey = await this.getOrganizationKey(organizationId); const request = await this.getServiceAccountRequest(orgKey, serviceAccountView); const r = await this.apiService.send( @@ -109,9 +105,12 @@ export class ServiceAccountService { true, true, ); - this._serviceAccount.next( - await this.createServiceAccountView(orgKey, new ServiceAccountResponse(r)), + const serviceAccount = await this.createServiceAccountView( + orgKey, + new ServiceAccountResponse(r), ); + this._serviceAccount.next(serviceAccount); + return serviceAccount; } async create( diff --git a/bitwarden_license/bit-web/src/app/secrets-manager/settings/models/error/sm-import-error-line.ts b/bitwarden_license/bit-sm/src/settings/models/error/sm-import-error-line.ts similarity index 100% rename from bitwarden_license/bit-web/src/app/secrets-manager/settings/models/error/sm-import-error-line.ts rename to bitwarden_license/bit-sm/src/settings/models/error/sm-import-error-line.ts diff --git a/bitwarden_license/bit-web/src/app/secrets-manager/settings/models/error/sm-import-error.ts b/bitwarden_license/bit-sm/src/settings/models/error/sm-import-error.ts similarity index 100% rename from bitwarden_license/bit-web/src/app/secrets-manager/settings/models/error/sm-import-error.ts rename to bitwarden_license/bit-sm/src/settings/models/error/sm-import-error.ts diff --git a/bitwarden_license/bit-web/src/app/secrets-manager/settings/models/requests/sm-import.request.ts b/bitwarden_license/bit-sm/src/settings/models/requests/sm-import.request.ts similarity index 100% rename from bitwarden_license/bit-web/src/app/secrets-manager/settings/models/requests/sm-import.request.ts rename to bitwarden_license/bit-sm/src/settings/models/requests/sm-import.request.ts diff --git a/bitwarden_license/bit-web/src/app/secrets-manager/settings/models/requests/sm-imported-project.request.ts b/bitwarden_license/bit-sm/src/settings/models/requests/sm-imported-project.request.ts similarity index 100% rename from bitwarden_license/bit-web/src/app/secrets-manager/settings/models/requests/sm-imported-project.request.ts rename to bitwarden_license/bit-sm/src/settings/models/requests/sm-imported-project.request.ts diff --git a/bitwarden_license/bit-web/src/app/secrets-manager/settings/models/requests/sm-imported-secret.request.ts b/bitwarden_license/bit-sm/src/settings/models/requests/sm-imported-secret.request.ts similarity index 100% rename from bitwarden_license/bit-web/src/app/secrets-manager/settings/models/requests/sm-imported-secret.request.ts rename to bitwarden_license/bit-sm/src/settings/models/requests/sm-imported-secret.request.ts diff --git a/bitwarden_license/bit-web/src/app/secrets-manager/settings/models/responses/sm-export.response.ts b/bitwarden_license/bit-sm/src/settings/models/responses/sm-export.response.ts similarity index 100% rename from bitwarden_license/bit-web/src/app/secrets-manager/settings/models/responses/sm-export.response.ts rename to bitwarden_license/bit-sm/src/settings/models/responses/sm-export.response.ts diff --git a/bitwarden_license/bit-web/src/app/secrets-manager/settings/models/responses/sm-exported-project.response.ts b/bitwarden_license/bit-sm/src/settings/models/responses/sm-exported-project.response.ts similarity index 100% rename from bitwarden_license/bit-web/src/app/secrets-manager/settings/models/responses/sm-exported-project.response.ts rename to bitwarden_license/bit-sm/src/settings/models/responses/sm-exported-project.response.ts diff --git a/bitwarden_license/bit-web/src/app/secrets-manager/settings/models/responses/sm-exported-secret.response.ts b/bitwarden_license/bit-sm/src/settings/models/responses/sm-exported-secret.response.ts similarity index 100% rename from bitwarden_license/bit-web/src/app/secrets-manager/settings/models/responses/sm-exported-secret.response.ts rename to bitwarden_license/bit-sm/src/settings/models/responses/sm-exported-secret.response.ts diff --git a/bitwarden_license/bit-web/src/app/secrets-manager/settings/models/sm-export.ts b/bitwarden_license/bit-sm/src/settings/models/sm-export.ts similarity index 100% rename from bitwarden_license/bit-web/src/app/secrets-manager/settings/models/sm-export.ts rename to bitwarden_license/bit-sm/src/settings/models/sm-export.ts diff --git a/bitwarden_license/bit-web/src/app/secrets-manager/settings/services/sm-porting-api.service.spec.ts b/bitwarden_license/bit-sm/src/settings/services/sm-porting-api.service.spec.ts similarity index 100% rename from bitwarden_license/bit-web/src/app/secrets-manager/settings/services/sm-porting-api.service.spec.ts rename to bitwarden_license/bit-sm/src/settings/services/sm-porting-api.service.spec.ts diff --git a/bitwarden_license/bit-web/src/app/secrets-manager/settings/services/sm-porting-api.service.ts b/bitwarden_license/bit-sm/src/settings/services/sm-porting-api.service.ts similarity index 99% rename from bitwarden_license/bit-web/src/app/secrets-manager/settings/services/sm-porting-api.service.ts rename to bitwarden_license/bit-sm/src/settings/services/sm-porting-api.service.ts index 772e87b0d33..8a66d6329ea 100644 --- a/bitwarden_license/bit-web/src/app/secrets-manager/settings/services/sm-porting-api.service.ts +++ b/bitwarden_license/bit-sm/src/settings/services/sm-porting-api.service.ts @@ -1,6 +1,5 @@ // FIXME: Update this file to be type safe and remove this and next line // @ts-strict-ignore -import { Injectable } from "@angular/core"; import { filter, firstValueFrom, map, Subject, switchMap } from "rxjs"; import { ApiService } from "@bitwarden/common/abstractions/api.service"; @@ -28,9 +27,6 @@ import { SecretsManagerExportSecret, } from "../models/sm-export"; -@Injectable({ - providedIn: "root", -}) export class SecretsManagerPortingApiService { protected _imports = new Subject(); imports$ = this._imports.asObservable(); diff --git a/bitwarden_license/bit-web/src/app/secrets-manager/shared/access-policies/access-policy.service.spec.ts b/bitwarden_license/bit-sm/src/shared/access-policies/access-policy.service.spec.ts similarity index 99% rename from bitwarden_license/bit-web/src/app/secrets-manager/shared/access-policies/access-policy.service.spec.ts rename to bitwarden_license/bit-sm/src/shared/access-policies/access-policy.service.spec.ts index 7e648b8b4e2..6c6cc398679 100644 --- a/bitwarden_license/bit-web/src/app/secrets-manager/shared/access-policies/access-policy.service.spec.ts +++ b/bitwarden_license/bit-sm/src/shared/access-policies/access-policy.service.spec.ts @@ -1,5 +1,6 @@ // FIXME: Update this file to be type safe and remove this and next line // @ts-strict-ignore +import { trackEmissions, mockAccountInfoWith } from "@bitwarden/common/../spec"; import { mock, MockProxy } from "jest-mock-extended"; import { BehaviorSubject } from "rxjs"; @@ -31,8 +32,6 @@ import { PeopleAccessPoliciesRequest } from "./models/requests/people-access-pol import { ProjectServiceAccountsAccessPoliciesRequest } from "./models/requests/project-service-accounts-access-policies.request"; import { ServiceAccountGrantedPoliciesRequest } from "./models/requests/service-account-granted-policies.request"; -import { trackEmissions, mockAccountInfoWith } from "@bitwarden/common/../spec"; - const SomeCsprngArray = new Uint8Array(64) as CsprngArray; const SomeOrganization = "some organization" as OrganizationId; const AnotherOrganization = "another organization" as OrganizationId; diff --git a/bitwarden_license/bit-web/src/app/secrets-manager/shared/access-policies/access-policy.service.ts b/bitwarden_license/bit-sm/src/shared/access-policies/access-policy.service.ts similarity index 99% rename from bitwarden_license/bit-web/src/app/secrets-manager/shared/access-policies/access-policy.service.ts rename to bitwarden_license/bit-sm/src/shared/access-policies/access-policy.service.ts index a895632b838..f63a4e18ff6 100644 --- a/bitwarden_license/bit-web/src/app/secrets-manager/shared/access-policies/access-policy.service.ts +++ b/bitwarden_license/bit-sm/src/shared/access-policies/access-policy.service.ts @@ -1,6 +1,5 @@ // FIXME: Update this file to be type safe and remove this and next line // @ts-strict-ignore -import { Injectable } from "@angular/core"; import { filter, firstValueFrom, map, Subject, switchMap } from "rxjs"; import { ApiService } from "@bitwarden/common/abstractions/api.service"; @@ -53,9 +52,6 @@ import { ServiceAccountGrantedPoliciesPermissionDetailsResponse } from "./models import { ServiceAccountPeopleAccessPoliciesResponse } from "./models/responses/service-account-people-access-policies.response"; import { GrantedProjectAccessPolicyPermissionDetailsResponse } from "./models/responses/service-account-project-policy-permission-details.response"; -@Injectable({ - providedIn: "root", -}) export class AccessPolicyService { protected _accessPolicy: Subject< | ProjectPeopleAccessPoliciesView diff --git a/bitwarden_license/bit-web/src/app/secrets-manager/shared/access-policies/models/requests/access-policy.request.ts b/bitwarden_license/bit-sm/src/shared/access-policies/models/requests/access-policy.request.ts similarity index 100% rename from bitwarden_license/bit-web/src/app/secrets-manager/shared/access-policies/models/requests/access-policy.request.ts rename to bitwarden_license/bit-sm/src/shared/access-policies/models/requests/access-policy.request.ts diff --git a/bitwarden_license/bit-web/src/app/secrets-manager/shared/access-policies/models/requests/granted-policy.request.ts b/bitwarden_license/bit-sm/src/shared/access-policies/models/requests/granted-policy.request.ts similarity index 100% rename from bitwarden_license/bit-web/src/app/secrets-manager/shared/access-policies/models/requests/granted-policy.request.ts rename to bitwarden_license/bit-sm/src/shared/access-policies/models/requests/granted-policy.request.ts diff --git a/bitwarden_license/bit-web/src/app/secrets-manager/shared/access-policies/models/requests/people-access-policies.request.ts b/bitwarden_license/bit-sm/src/shared/access-policies/models/requests/people-access-policies.request.ts similarity index 100% rename from bitwarden_license/bit-web/src/app/secrets-manager/shared/access-policies/models/requests/people-access-policies.request.ts rename to bitwarden_license/bit-sm/src/shared/access-policies/models/requests/people-access-policies.request.ts diff --git a/bitwarden_license/bit-web/src/app/secrets-manager/shared/access-policies/models/requests/project-service-accounts-access-policies.request.ts b/bitwarden_license/bit-sm/src/shared/access-policies/models/requests/project-service-accounts-access-policies.request.ts similarity index 100% rename from bitwarden_license/bit-web/src/app/secrets-manager/shared/access-policies/models/requests/project-service-accounts-access-policies.request.ts rename to bitwarden_license/bit-sm/src/shared/access-policies/models/requests/project-service-accounts-access-policies.request.ts diff --git a/bitwarden_license/bit-web/src/app/secrets-manager/shared/access-policies/models/requests/secret-access-policies.request.ts b/bitwarden_license/bit-sm/src/shared/access-policies/models/requests/secret-access-policies.request.ts similarity index 100% rename from bitwarden_license/bit-web/src/app/secrets-manager/shared/access-policies/models/requests/secret-access-policies.request.ts rename to bitwarden_license/bit-sm/src/shared/access-policies/models/requests/secret-access-policies.request.ts diff --git a/bitwarden_license/bit-web/src/app/secrets-manager/shared/access-policies/models/requests/service-account-granted-policies.request.ts b/bitwarden_license/bit-sm/src/shared/access-policies/models/requests/service-account-granted-policies.request.ts similarity index 100% rename from bitwarden_license/bit-web/src/app/secrets-manager/shared/access-policies/models/requests/service-account-granted-policies.request.ts rename to bitwarden_license/bit-sm/src/shared/access-policies/models/requests/service-account-granted-policies.request.ts diff --git a/bitwarden_license/bit-web/src/app/secrets-manager/shared/access-policies/models/responses/access-policy.response.ts b/bitwarden_license/bit-sm/src/shared/access-policies/models/responses/access-policy.response.ts similarity index 100% rename from bitwarden_license/bit-web/src/app/secrets-manager/shared/access-policies/models/responses/access-policy.response.ts rename to bitwarden_license/bit-sm/src/shared/access-policies/models/responses/access-policy.response.ts diff --git a/bitwarden_license/bit-web/src/app/secrets-manager/shared/access-policies/models/responses/potential-grantee.response.ts b/bitwarden_license/bit-sm/src/shared/access-policies/models/responses/potential-grantee.response.ts similarity index 100% rename from bitwarden_license/bit-web/src/app/secrets-manager/shared/access-policies/models/responses/potential-grantee.response.ts rename to bitwarden_license/bit-sm/src/shared/access-policies/models/responses/potential-grantee.response.ts diff --git a/bitwarden_license/bit-web/src/app/secrets-manager/shared/access-policies/models/responses/project-people-access-policies.response.ts b/bitwarden_license/bit-sm/src/shared/access-policies/models/responses/project-people-access-policies.response.ts similarity index 100% rename from bitwarden_license/bit-web/src/app/secrets-manager/shared/access-policies/models/responses/project-people-access-policies.response.ts rename to bitwarden_license/bit-sm/src/shared/access-policies/models/responses/project-people-access-policies.response.ts diff --git a/bitwarden_license/bit-web/src/app/secrets-manager/shared/access-policies/models/responses/project-service-accounts-access-policies.response.ts b/bitwarden_license/bit-sm/src/shared/access-policies/models/responses/project-service-accounts-access-policies.response.ts similarity index 100% rename from bitwarden_license/bit-web/src/app/secrets-manager/shared/access-policies/models/responses/project-service-accounts-access-policies.response.ts rename to bitwarden_license/bit-sm/src/shared/access-policies/models/responses/project-service-accounts-access-policies.response.ts diff --git a/bitwarden_license/bit-web/src/app/secrets-manager/shared/access-policies/models/responses/secret-access-policies.response.ts b/bitwarden_license/bit-sm/src/shared/access-policies/models/responses/secret-access-policies.response.ts similarity index 100% rename from bitwarden_license/bit-web/src/app/secrets-manager/shared/access-policies/models/responses/secret-access-policies.response.ts rename to bitwarden_license/bit-sm/src/shared/access-policies/models/responses/secret-access-policies.response.ts diff --git a/bitwarden_license/bit-web/src/app/secrets-manager/shared/access-policies/models/responses/service-account-granted-policies-permission-details.response.ts b/bitwarden_license/bit-sm/src/shared/access-policies/models/responses/service-account-granted-policies-permission-details.response.ts similarity index 100% rename from bitwarden_license/bit-web/src/app/secrets-manager/shared/access-policies/models/responses/service-account-granted-policies-permission-details.response.ts rename to bitwarden_license/bit-sm/src/shared/access-policies/models/responses/service-account-granted-policies-permission-details.response.ts diff --git a/bitwarden_license/bit-web/src/app/secrets-manager/shared/access-policies/models/responses/service-account-people-access-policies.response.ts b/bitwarden_license/bit-sm/src/shared/access-policies/models/responses/service-account-people-access-policies.response.ts similarity index 100% rename from bitwarden_license/bit-web/src/app/secrets-manager/shared/access-policies/models/responses/service-account-people-access-policies.response.ts rename to bitwarden_license/bit-sm/src/shared/access-policies/models/responses/service-account-people-access-policies.response.ts diff --git a/bitwarden_license/bit-web/src/app/secrets-manager/shared/access-policies/models/responses/service-account-project-policy-permission-details.response.ts b/bitwarden_license/bit-sm/src/shared/access-policies/models/responses/service-account-project-policy-permission-details.response.ts similarity index 100% rename from bitwarden_license/bit-web/src/app/secrets-manager/shared/access-policies/models/responses/service-account-project-policy-permission-details.response.ts rename to bitwarden_license/bit-sm/src/shared/access-policies/models/responses/service-account-project-policy-permission-details.response.ts diff --git a/bitwarden_license/bit-web/src/app/secrets-manager/shared/counts/count.service.spec.ts b/bitwarden_license/bit-sm/src/shared/counts/count.service.spec.ts similarity index 100% rename from bitwarden_license/bit-web/src/app/secrets-manager/shared/counts/count.service.spec.ts rename to bitwarden_license/bit-sm/src/shared/counts/count.service.spec.ts diff --git a/bitwarden_license/bit-web/src/app/secrets-manager/shared/counts/count.service.ts b/bitwarden_license/bit-sm/src/shared/counts/count.service.ts similarity index 93% rename from bitwarden_license/bit-web/src/app/secrets-manager/shared/counts/count.service.ts rename to bitwarden_license/bit-sm/src/shared/counts/count.service.ts index bb415d52575..5ae0996a533 100644 --- a/bitwarden_license/bit-web/src/app/secrets-manager/shared/counts/count.service.ts +++ b/bitwarden_license/bit-sm/src/shared/counts/count.service.ts @@ -1,14 +1,9 @@ -import { Injectable } from "@angular/core"; - import { ApiService } from "@bitwarden/common/abstractions/api.service"; import { OrganizationCountsResponse } from "./models/responses/organization-counts.response"; import { ProjectCountsResponse } from "./models/responses/project-counts.response"; import { ServiceAccountCountsResponse } from "./models/responses/service-account-counts.response"; -@Injectable({ - providedIn: "root", -}) export class CountService { constructor(private apiService: ApiService) {} diff --git a/bitwarden_license/bit-web/src/app/secrets-manager/shared/counts/models/responses/organization-counts.response.ts b/bitwarden_license/bit-sm/src/shared/counts/models/responses/organization-counts.response.ts similarity index 100% rename from bitwarden_license/bit-web/src/app/secrets-manager/shared/counts/models/responses/organization-counts.response.ts rename to bitwarden_license/bit-sm/src/shared/counts/models/responses/organization-counts.response.ts diff --git a/bitwarden_license/bit-web/src/app/secrets-manager/shared/counts/models/responses/project-counts.response.ts b/bitwarden_license/bit-sm/src/shared/counts/models/responses/project-counts.response.ts similarity index 100% rename from bitwarden_license/bit-web/src/app/secrets-manager/shared/counts/models/responses/project-counts.response.ts rename to bitwarden_license/bit-sm/src/shared/counts/models/responses/project-counts.response.ts diff --git a/bitwarden_license/bit-web/src/app/secrets-manager/shared/counts/models/responses/service-account-counts.response.ts b/bitwarden_license/bit-sm/src/shared/counts/models/responses/service-account-counts.response.ts similarity index 100% rename from bitwarden_license/bit-web/src/app/secrets-manager/shared/counts/models/responses/service-account-counts.response.ts rename to bitwarden_license/bit-sm/src/shared/counts/models/responses/service-account-counts.response.ts diff --git a/bitwarden_license/bit-sm/test.setup.ts b/bitwarden_license/bit-sm/test.setup.ts new file mode 100644 index 00000000000..3f9ef28ad00 --- /dev/null +++ b/bitwarden_license/bit-sm/test.setup.ts @@ -0,0 +1 @@ +import "@bitwarden/ui-common/setup-jest"; diff --git a/bitwarden_license/bit-sm/tsconfig.json b/bitwarden_license/bit-sm/tsconfig.json new file mode 100644 index 00000000000..9c607a26b09 --- /dev/null +++ b/bitwarden_license/bit-sm/tsconfig.json @@ -0,0 +1,5 @@ +{ + "extends": "../../tsconfig.base", + "include": ["src", "spec"], + "exclude": ["node_modules", "dist"] +} diff --git a/bitwarden_license/bit-sm/tsconfig.spec.json b/bitwarden_license/bit-sm/tsconfig.spec.json new file mode 100644 index 00000000000..d52d889aa78 --- /dev/null +++ b/bitwarden_license/bit-sm/tsconfig.spec.json @@ -0,0 +1,8 @@ +{ + "extends": "./tsconfig.json", + "compilerOptions": { + "isolatedModules": true, + "emitDecoratorMetadata": false + }, + "files": ["./test.setup.ts"] +} diff --git a/bitwarden_license/bit-web/src/app/app.module.ts b/bitwarden_license/bit-web/src/app/app.module.ts index a1726b4668c..7d179565c5f 100644 --- a/bitwarden_license/bit-web/src/app/app.module.ts +++ b/bitwarden_license/bit-web/src/app/app.module.ts @@ -18,6 +18,7 @@ import { bitPolicyEditRegister } from "./admin-console/policies"; import { AppRoutingModule } from "./app-routing.module"; import { AppComponent } from "./app.component"; import { providePam } from "./pam/provide-pam"; +import { provideSecretsManager } from "./secrets-manager/provide-secrets-manager"; /** * This is the AppModule for the commercial version of Bitwarden. @@ -49,6 +50,7 @@ import { providePam } from "./pam/provide-pam"; useValue: bitPolicyEditRegister, }), ...providePam(), + ...provideSecretsManager(), ], }) export class AppModule {} diff --git a/bitwarden_license/bit-web/src/app/secrets-manager/guards/project-access.guard.spec.ts b/bitwarden_license/bit-web/src/app/secrets-manager/guards/project-access.guard.spec.ts index 79c022e8fd2..987da3a4fd9 100644 --- a/bitwarden_license/bit-web/src/app/secrets-manager/guards/project-access.guard.spec.ts +++ b/bitwarden_license/bit-web/src/app/secrets-manager/guards/project-access.guard.spec.ts @@ -5,6 +5,7 @@ import { RouterTestingModule } from "@angular/router/testing"; import { MockProxy, mock } from "jest-mock-extended"; import { of } from "rxjs"; +import { ProjectService, ProjectView } from "@bitwarden/bit-sm"; import { OrganizationService } from "@bitwarden/common/admin-console/abstractions/organization/organization.service.abstraction"; import { Organization } from "@bitwarden/common/admin-console/models/domain/organization"; import { AccountService } from "@bitwarden/common/auth/abstractions/account.service"; @@ -15,9 +16,6 @@ import { UserId } from "@bitwarden/common/types/guid"; import { ToastService } from "@bitwarden/components"; import { RouterService } from "@bitwarden/web-vault/app/core"; -import { ProjectView } from "../models/view/project.view"; -import { ProjectService } from "../projects/project.service"; - import { projectAccessGuard } from "./project-access.guard"; // FIXME(https://bitwarden.atlassian.net/browse/CL-764): Migrate to OnPush diff --git a/bitwarden_license/bit-web/src/app/secrets-manager/guards/project-access.guard.ts b/bitwarden_license/bit-web/src/app/secrets-manager/guards/project-access.guard.ts index b8c9640dc50..fdb17f29332 100644 --- a/bitwarden_license/bit-web/src/app/secrets-manager/guards/project-access.guard.ts +++ b/bitwarden_license/bit-web/src/app/secrets-manager/guards/project-access.guard.ts @@ -3,11 +3,10 @@ import { inject } from "@angular/core"; import { ActivatedRouteSnapshot, CanActivateFn, createUrlTreeFromSnapshot } from "@angular/router"; +import { ProjectService } from "@bitwarden/bit-sm"; import { I18nService } from "@bitwarden/common/platform/abstractions/i18n.service"; import { ToastService } from "@bitwarden/components"; -import { ProjectService } from "../projects/project.service"; - /** * Redirects to projects list if the user doesn't have access to project. */ diff --git a/bitwarden_license/bit-web/src/app/secrets-manager/layout/navigation.component.ts b/bitwarden_license/bit-web/src/app/secrets-manager/layout/navigation.component.ts index d12f15d9a4e..ed8d87f269f 100644 --- a/bitwarden_license/bit-web/src/app/secrets-manager/layout/navigation.component.ts +++ b/bitwarden_license/bit-web/src/app/secrets-manager/layout/navigation.component.ts @@ -16,6 +16,14 @@ import { } from "rxjs"; import { SecretsManagerLogo } from "@bitwarden/assets/svg"; +import { + CountService, + OrganizationCounts, + ProjectService, + SecretService, + SecretsManagerPortingApiService, + ServiceAccountService, +} from "@bitwarden/bit-sm"; import { getOrganizationById, OrganizationService, @@ -26,13 +34,6 @@ import { getUserId } from "@bitwarden/common/auth/services/account.service"; import { FeatureFlag } from "@bitwarden/common/enums/feature-flag.enum"; import { ConfigService } from "@bitwarden/common/platform/abstractions/config/config.service"; -import { OrganizationCounts } from "../models/view/counts.view"; -import { ProjectService } from "../projects/project.service"; -import { SecretService } from "../secrets/secret.service"; -import { ServiceAccountService } from "../service-accounts/service-account.service"; -import { SecretsManagerPortingApiService } from "../settings/services/sm-porting-api.service"; -import { CountService } from "../shared/counts/count.service"; - // FIXME(https://bitwarden.atlassian.net/browse/CL-764): Migrate to OnPush // eslint-disable-next-line @angular-eslint/prefer-on-push-component-change-detection @Component({ diff --git a/bitwarden_license/bit-web/src/app/secrets-manager/overview/overview.component.ts b/bitwarden_license/bit-web/src/app/secrets-manager/overview/overview.component.ts index d534d16db0f..c6422175406 100644 --- a/bitwarden_license/bit-web/src/app/secrets-manager/overview/overview.component.ts +++ b/bitwarden_license/bit-web/src/app/secrets-manager/overview/overview.component.ts @@ -16,6 +16,15 @@ import { firstValueFrom, } from "rxjs"; +import { + CountService, + OrganizationCounts, + ProjectListView, + ProjectService, + SecretListView, + SecretService, + ServiceAccountService, +} from "@bitwarden/bit-sm"; import { getOrganizationById, OrganizationService, @@ -29,9 +38,6 @@ import { PlatformUtilsService } from "@bitwarden/common/platform/abstractions/pl import { OrganizationId } from "@bitwarden/common/types/guid"; import { CenterPositionStrategy, DialogService } from "@bitwarden/components"; -import { OrganizationCounts } from "../models/view/counts.view"; -import { ProjectListView } from "../models/view/project-list.view"; -import { SecretListView } from "../models/view/secret-list.view"; import { ProjectDeleteDialogComponent, ProjectDeleteOperation, @@ -40,7 +46,6 @@ import { ProjectDialogComponent, ProjectOperation, } from "../projects/dialog/project-dialog.component"; -import { ProjectService } from "../projects/project.service"; import { SecretDeleteDialogComponent, SecretDeleteOperation, @@ -55,13 +60,10 @@ import { SecretViewDialogComponent, SecretViewDialogParams, } from "../secrets/dialog/secret-view-dialog.component"; -import { SecretService } from "../secrets/secret.service"; import { ServiceAccountDialogComponent, ServiceAccountOperation, } from "../service-accounts/dialog/service-account-dialog.component"; -import { ServiceAccountService } from "../service-accounts/service-account.service"; -import { CountService } from "../shared/counts/count.service"; import { SecretsListComponent } from "../shared/secrets-list.component"; import { SMOnboardingTasks, SMOnboardingTasksService } from "./sm-onboarding-tasks.service"; diff --git a/bitwarden_license/bit-web/src/app/secrets-manager/projects/dialog/project-delete-dialog.component.ts b/bitwarden_license/bit-web/src/app/secrets-manager/projects/dialog/project-delete-dialog.component.ts index 97c89896c72..c0edb2a54c3 100644 --- a/bitwarden_license/bit-web/src/app/secrets-manager/projects/dialog/project-delete-dialog.component.ts +++ b/bitwarden_license/bit-web/src/app/secrets-manager/projects/dialog/project-delete-dialog.component.ts @@ -9,17 +9,15 @@ import { AbstractControl, } from "@angular/forms"; +import { BulkOperationStatus, ProjectListView, ProjectService } from "@bitwarden/bit-sm"; import { I18nService } from "@bitwarden/common/platform/abstractions/i18n.service"; import { PlatformUtilsService } from "@bitwarden/common/platform/abstractions/platform-utils.service"; import { DialogRef, DIALOG_DATA, DialogService, ToastService } from "@bitwarden/components"; -import { ProjectListView } from "../../models/view/project-list.view"; import { - BulkOperationStatus, BulkStatusDetails, BulkStatusDialogComponent, } from "../../shared/dialogs/bulk-status-dialog.component"; -import { ProjectService } from "../project.service"; export interface ProjectDeleteOperation { projects: ProjectListView[]; diff --git a/bitwarden_license/bit-web/src/app/secrets-manager/projects/dialog/project-dialog.component.ts b/bitwarden_license/bit-web/src/app/secrets-manager/projects/dialog/project-dialog.component.ts index f44cb4ed781..7557163dfda 100644 --- a/bitwarden_license/bit-web/src/app/secrets-manager/projects/dialog/project-dialog.component.ts +++ b/bitwarden_license/bit-web/src/app/secrets-manager/projects/dialog/project-dialog.component.ts @@ -4,13 +4,11 @@ import { Component, Inject, OnInit } from "@angular/core"; import { FormControl, FormGroup, Validators } from "@angular/forms"; import { Router } from "@angular/router"; +import { ProjectService, ProjectView } from "@bitwarden/bit-sm"; import { I18nService } from "@bitwarden/common/platform/abstractions/i18n.service"; import { PlatformUtilsService } from "@bitwarden/common/platform/abstractions/platform-utils.service"; import { DialogRef, DIALOG_DATA, BitValidators, ToastService } from "@bitwarden/components"; -import { ProjectView } from "../../models/view/project.view"; -import { ProjectService } from "../../projects/project.service"; - // FIXME: update to use a const object instead of a typescript enum // eslint-disable-next-line @bitwarden/platform/no-enums export enum OperationType { diff --git a/bitwarden_license/bit-web/src/app/secrets-manager/projects/project/project-people.component.ts b/bitwarden_license/bit-web/src/app/secrets-manager/projects/project/project-people.component.ts index 49b016e921c..230d3125315 100644 --- a/bitwarden_license/bit-web/src/app/secrets-manager/projects/project/project-people.component.ts +++ b/bitwarden_license/bit-web/src/app/secrets-manager/projects/project/project-people.component.ts @@ -5,6 +5,7 @@ import { FormControl, FormGroup } from "@angular/forms"; import { ActivatedRoute, Router } from "@angular/router"; import { combineLatest, Subject, switchMap, takeUntil, catchError } from "rxjs"; +import { AccessPolicyService } from "@bitwarden/bit-sm"; import { I18nService } from "@bitwarden/common/platform/abstractions/i18n.service"; import { LogService } from "@bitwarden/common/platform/abstractions/log.service"; import { PlatformUtilsService } from "@bitwarden/common/platform/abstractions/platform-utils.service"; @@ -22,7 +23,6 @@ import { convertToAccessPolicyItemViews, } from "../../shared/access-policies/access-policy-selector/models/ap-item-view.type"; import { ApItemEnum } from "../../shared/access-policies/access-policy-selector/models/enums/ap-item.enum"; -import { AccessPolicyService } from "../../shared/access-policies/access-policy.service"; // FIXME(https://bitwarden.atlassian.net/browse/CL-764): Migrate to OnPush // eslint-disable-next-line @angular-eslint/prefer-on-push-component-change-detection diff --git a/bitwarden_license/bit-web/src/app/secrets-manager/projects/project/project-secrets.component.ts b/bitwarden_license/bit-web/src/app/secrets-manager/projects/project/project-secrets.component.ts index bfc316e64a0..79a4775936a 100644 --- a/bitwarden_license/bit-web/src/app/secrets-manager/projects/project/project-secrets.component.ts +++ b/bitwarden_license/bit-web/src/app/secrets-manager/projects/project/project-secrets.component.ts @@ -13,6 +13,7 @@ import { } from "rxjs"; import { NoResults } from "@bitwarden/assets/svg"; +import { ProjectService, ProjectView, SecretListView, SecretService } from "@bitwarden/bit-sm"; import { getOrganizationById, OrganizationService, @@ -25,8 +26,6 @@ import { PlatformUtilsService } from "@bitwarden/common/platform/abstractions/pl import { OrganizationId } from "@bitwarden/common/types/guid"; import { CenterPositionStrategy, DialogService } from "@bitwarden/components"; -import { ProjectView } from "../../models/view/project.view"; -import { SecretListView } from "../../models/view/secret-list.view"; import { SecretDeleteDialogComponent, SecretDeleteOperation, @@ -41,9 +40,8 @@ import { SecretViewDialogComponent, SecretViewDialogParams, } from "../../secrets/dialog/secret-view-dialog.component"; -import { SecretService } from "../../secrets/secret.service"; import { SecretsListComponent } from "../../shared/secrets-list.component"; -import { ProjectService } from "../project.service"; + // FIXME(https://bitwarden.atlassian.net/browse/CL-764): Migrate to OnPush // eslint-disable-next-line @angular-eslint/prefer-on-push-component-change-detection @Component({ diff --git a/bitwarden_license/bit-web/src/app/secrets-manager/projects/project/project-service-accounts.component.ts b/bitwarden_license/bit-web/src/app/secrets-manager/projects/project/project-service-accounts.component.ts index e2fd8556621..a476c10392f 100644 --- a/bitwarden_license/bit-web/src/app/secrets-manager/projects/project/project-service-accounts.component.ts +++ b/bitwarden_license/bit-web/src/app/secrets-manager/projects/project/project-service-accounts.component.ts @@ -5,12 +5,12 @@ import { FormControl, FormGroup } from "@angular/forms"; import { ActivatedRoute } from "@angular/router"; import { combineLatest, Subject, switchMap, takeUntil } from "rxjs"; +import { AccessPolicyService, ProjectServiceAccountsAccessPoliciesView } from "@bitwarden/bit-sm"; import { I18nService } from "@bitwarden/common/platform/abstractions/i18n.service"; import { PlatformUtilsService } from "@bitwarden/common/platform/abstractions/platform-utils.service"; import { ValidationService } from "@bitwarden/common/platform/abstractions/validation.service"; import { ToastService } from "@bitwarden/components"; -import { ProjectServiceAccountsAccessPoliciesView } from "../../models/view/access-policies/project-service-accounts-access-policies.view"; import { ApItemValueType, convertToProjectServiceAccountsAccessPoliciesView, @@ -20,7 +20,6 @@ import { convertPotentialGranteesToApItemViewType, convertProjectServiceAccountsViewToApItemViews, } from "../../shared/access-policies/access-policy-selector/models/ap-item-view.type"; -import { AccessPolicyService } from "../../shared/access-policies/access-policy.service"; // FIXME(https://bitwarden.atlassian.net/browse/CL-764): Migrate to OnPush // eslint-disable-next-line @angular-eslint/prefer-on-push-component-change-detection diff --git a/bitwarden_license/bit-web/src/app/secrets-manager/projects/project/project.component.ts b/bitwarden_license/bit-web/src/app/secrets-manager/projects/project/project.component.ts index 96421df7054..368b6bfe9c6 100644 --- a/bitwarden_license/bit-web/src/app/secrets-manager/projects/project/project.component.ts +++ b/bitwarden_license/bit-web/src/app/secrets-manager/projects/project/project.component.ts @@ -15,6 +15,14 @@ import { concatMap, } from "rxjs"; +import { + AccessPolicyService, + CountService, + ProjectCounts, + ProjectService, + ProjectView, + SecretService, +} from "@bitwarden/bit-sm"; import { getOrganizationById, OrganizationService, @@ -25,17 +33,11 @@ import { FeatureFlag } from "@bitwarden/common/enums/feature-flag.enum"; import { ConfigService } from "@bitwarden/common/platform/abstractions/config/config.service"; import { DialogService } from "@bitwarden/components"; -import { ProjectCounts } from "../../models/view/counts.view"; -import { ProjectView } from "../../models/view/project.view"; -import { SecretService } from "../../secrets/secret.service"; -import { AccessPolicyService } from "../../shared/access-policies/access-policy.service"; -import { CountService } from "../../shared/counts/count.service"; import { OperationType, ProjectDialogComponent, ProjectOperation, } from "../dialog/project-dialog.component"; -import { ProjectService } from "../project.service"; // FIXME(https://bitwarden.atlassian.net/browse/CL-764): Migrate to OnPush // eslint-disable-next-line @angular-eslint/prefer-on-push-component-change-detection diff --git a/bitwarden_license/bit-web/src/app/secrets-manager/projects/projects/projects.component.ts b/bitwarden_license/bit-web/src/app/secrets-manager/projects/projects/projects.component.ts index 74f707038ac..fad660ccddd 100644 --- a/bitwarden_license/bit-web/src/app/secrets-manager/projects/projects/projects.component.ts +++ b/bitwarden_license/bit-web/src/app/secrets-manager/projects/projects/projects.component.ts @@ -11,6 +11,7 @@ import { switchMap, } from "rxjs"; +import { ProjectListView, ProjectService, ProjectView } from "@bitwarden/bit-sm"; import { getOrganizationById, OrganizationService, @@ -21,8 +22,6 @@ import { I18nService } from "@bitwarden/common/platform/abstractions/i18n.servic import { DialogRef, DialogService, ToastService } from "@bitwarden/components"; import { openEntityEventsDialog } from "@bitwarden/web-vault/app/dirt/event-logs/components/entity-events/entity-events.component"; -import { ProjectListView } from "../../models/view/project-list.view"; -import { ProjectView } from "../../models/view/project.view"; import { BulkConfirmationDetails, BulkConfirmationDialogComponent, @@ -38,7 +37,6 @@ import { ProjectDialogComponent, ProjectOperation, } from "../dialog/project-dialog.component"; -import { ProjectService } from "../project.service"; // FIXME(https://bitwarden.atlassian.net/browse/CL-764): Migrate to OnPush // eslint-disable-next-line @angular-eslint/prefer-on-push-component-change-detection diff --git a/bitwarden_license/bit-web/src/app/secrets-manager/provide-secrets-manager.ts b/bitwarden_license/bit-web/src/app/secrets-manager/provide-secrets-manager.ts new file mode 100644 index 00000000000..a736f4256f3 --- /dev/null +++ b/bitwarden_license/bit-web/src/app/secrets-manager/provide-secrets-manager.ts @@ -0,0 +1,70 @@ +import { + AccessPolicyService, + AccessService, + CountService, + ProjectService, + SecretService, + SecretsManagerPortingApiService, + SecretVersionService, + ServiceAccountEventLogApiService, + ServiceAccountService, +} from "@bitwarden/bit-sm"; +import { ApiService } from "@bitwarden/common/abstractions/api.service"; +import { AccountService } from "@bitwarden/common/auth/abstractions/account.service"; +import { LogService } from "@bitwarden/common/platform/abstractions/log.service"; +import { KeyService } from "@bitwarden/key-management"; +// eslint-disable-next-line no-restricted-imports +import { EncryptService, KeyGenerationService } from "@bitwarden/legacy-crypto"; +import { SafeProvider, safeProvider } from "@bitwarden/ui-common"; + +/** + * Secrets Manager root-level providers, so web components, guards, and dialogs share a + * single instance of each service. + */ +export function provideSecretsManager(): SafeProvider[] { + return [ + safeProvider({ + provide: AccessPolicyService, + deps: [KeyService, ApiService, EncryptService, AccountService, LogService], + }), + safeProvider({ + provide: ProjectService, + deps: [KeyService, ApiService, EncryptService, AccountService], + }), + safeProvider({ + provide: SecretService, + deps: [KeyService, ApiService, EncryptService, AccessPolicyService, AccountService], + }), + safeProvider({ + provide: SecretVersionService, + deps: [KeyService, ApiService, EncryptService, AccountService], + }), + safeProvider({ + provide: ServiceAccountService, + deps: [KeyService, ApiService, EncryptService, AccountService, LogService], + }), + safeProvider({ + provide: AccessService, + deps: [ + KeyService, + ApiService, + KeyGenerationService, + EncryptService, + AccountService, + LogService, + ], + }), + safeProvider({ + provide: ServiceAccountEventLogApiService, + deps: [ApiService], + }), + safeProvider({ + provide: CountService, + deps: [ApiService], + }), + safeProvider({ + provide: SecretsManagerPortingApiService, + deps: [ApiService, EncryptService, KeyService, AccountService], + }), + ]; +} diff --git a/bitwarden_license/bit-web/src/app/secrets-manager/secrets/dialog/secret-delete.component.ts b/bitwarden_license/bit-web/src/app/secrets-manager/secrets/dialog/secret-delete.component.ts index 2b3b0b2b5f1..1291f31c8bf 100644 --- a/bitwarden_license/bit-web/src/app/secrets-manager/secrets/dialog/secret-delete.component.ts +++ b/bitwarden_license/bit-web/src/app/secrets-manager/secrets/dialog/secret-delete.component.ts @@ -2,17 +2,15 @@ // @ts-strict-ignore import { Component, Inject } from "@angular/core"; +import { BulkOperationStatus, SecretListView, SecretService } from "@bitwarden/bit-sm"; import { I18nService } from "@bitwarden/common/platform/abstractions/i18n.service"; import { PlatformUtilsService } from "@bitwarden/common/platform/abstractions/platform-utils.service"; import { DialogRef, DIALOG_DATA, DialogService, ToastService } from "@bitwarden/components"; -import { SecretListView } from "../../models/view/secret-list.view"; import { - BulkOperationStatus, BulkStatusDetails, BulkStatusDialogComponent, } from "../../shared/dialogs/bulk-status-dialog.component"; -import { SecretService } from "../secret.service"; export interface SecretDeleteOperation { secrets: SecretListView[]; diff --git a/bitwarden_license/bit-web/src/app/secrets-manager/secrets/dialog/secret-dialog.component.ts b/bitwarden_license/bit-web/src/app/secrets-manager/secrets/dialog/secret-dialog.component.ts index 3dc8d496aa1..2e1546388fd 100644 --- a/bitwarden_license/bit-web/src/app/secrets-manager/secrets/dialog/secret-dialog.component.ts +++ b/bitwarden_license/bit-web/src/app/secrets-manager/secrets/dialog/secret-dialog.component.ts @@ -4,6 +4,17 @@ import { ChangeDetectorRef, Component, Inject, OnDestroy, OnInit } from "@angula import { FormControl, FormGroup, Validators } from "@angular/forms"; import { firstValueFrom, lastValueFrom, Subject, takeUntil } from "rxjs"; +import { + AccessPolicyService, + ProjectListView, + ProjectService, + ProjectView, + SecretAccessPoliciesView, + SecretListView, + SecretProjectView, + SecretService, + SecretView, +} from "@bitwarden/bit-sm"; import { getOrganizationById, OrganizationService, @@ -22,13 +33,6 @@ import { CenterPositionStrategy, } from "@bitwarden/components"; -import { SecretAccessPoliciesView } from "../../models/view/access-policies/secret-access-policies.view"; -import { ProjectListView } from "../../models/view/project-list.view"; -import { ProjectView } from "../../models/view/project.view"; -import { SecretListView } from "../../models/view/secret-list.view"; -import { SecretProjectView } from "../../models/view/secret-project.view"; -import { SecretView } from "../../models/view/secret.view"; -import { ProjectService } from "../../projects/project.service"; import { AccessPolicySelectorService } from "../../shared/access-policies/access-policy-selector/access-policy-selector.service"; import { ApItemValueType, @@ -40,8 +44,6 @@ import { convertSecretAccessPoliciesToApItemViews, } from "../../shared/access-policies/access-policy-selector/models/ap-item-view.type"; import { ApItemEnum } from "../../shared/access-policies/access-policy-selector/models/enums/ap-item.enum"; -import { AccessPolicyService } from "../../shared/access-policies/access-policy.service"; -import { SecretService } from "../secret.service"; import { SecretDeleteDialogComponent, SecretDeleteOperation } from "./secret-delete.component"; diff --git a/bitwarden_license/bit-web/src/app/secrets-manager/secrets/dialog/secret-version-dialog.service.spec.ts b/bitwarden_license/bit-web/src/app/secrets-manager/secrets/dialog/secret-version-dialog.service.spec.ts index fbb1badf0a0..a72badf1776 100644 --- a/bitwarden_license/bit-web/src/app/secrets-manager/secrets/dialog/secret-version-dialog.service.spec.ts +++ b/bitwarden_license/bit-web/src/app/secrets-manager/secrets/dialog/secret-version-dialog.service.spec.ts @@ -1,14 +1,12 @@ import { TestBed } from "@angular/core/testing"; import { mock } from "jest-mock-extended"; +import { SecretService, SecretView } from "@bitwarden/bit-sm"; import { I18nService } from "@bitwarden/common/platform/abstractions/i18n.service"; import { LogService } from "@bitwarden/common/platform/abstractions/log.service"; import { OrganizationId } from "@bitwarden/common/types/guid"; import { DialogService, ToastService } from "@bitwarden/components"; -import { SecretView } from "../../models/view/secret.view"; -import { SecretService } from "../secret.service"; - import { SecretVersionDialogService } from "./secret-version-dialog.service"; import { SecretVersionDialogComponent } from "./secret-version.component"; diff --git a/bitwarden_license/bit-web/src/app/secrets-manager/secrets/dialog/secret-version-dialog.service.ts b/bitwarden_license/bit-web/src/app/secrets-manager/secrets/dialog/secret-version-dialog.service.ts index 44a5b905e43..34ec819de13 100644 --- a/bitwarden_license/bit-web/src/app/secrets-manager/secrets/dialog/secret-version-dialog.service.ts +++ b/bitwarden_license/bit-web/src/app/secrets-manager/secrets/dialog/secret-version-dialog.service.ts @@ -1,13 +1,11 @@ import { inject, Injectable } from "@angular/core"; +import { SecretService, SecretView } from "@bitwarden/bit-sm"; import { I18nService } from "@bitwarden/common/platform/abstractions/i18n.service"; import { LogService } from "@bitwarden/common/platform/abstractions/log.service"; import { OrganizationId } from "@bitwarden/common/types/guid"; import { DialogService, ToastService } from "@bitwarden/components"; -import { SecretView } from "../../models/view/secret.view"; -import { SecretService } from "../secret.service"; - import { SecretVersionDialogComponent, SecretVersionDialogParams, diff --git a/bitwarden_license/bit-web/src/app/secrets-manager/secrets/dialog/secret-version.component.spec.ts b/bitwarden_license/bit-web/src/app/secrets-manager/secrets/dialog/secret-version.component.spec.ts index 19d3c54f26c..f41ceda6968 100644 --- a/bitwarden_license/bit-web/src/app/secrets-manager/secrets/dialog/secret-version.component.spec.ts +++ b/bitwarden_license/bit-web/src/app/secrets-manager/secrets/dialog/secret-version.component.spec.ts @@ -2,17 +2,19 @@ import { Signal, WritableSignal } from "@angular/core"; import { ComponentFixture, TestBed } from "@angular/core/testing"; import { mock, MockProxy } from "jest-mock-extended"; +import { + SecretService, + SecretVersionHistory, + SecretVersionService, + SecretVersionView, + SecretView, +} from "@bitwarden/bit-sm"; import { I18nService } from "@bitwarden/common/platform/abstractions/i18n.service"; import { LogService } from "@bitwarden/common/platform/abstractions/log.service"; import { PlatformUtilsService } from "@bitwarden/common/platform/abstractions/platform-utils.service"; import { ValidationService } from "@bitwarden/common/platform/abstractions/validation.service"; import { DIALOG_DATA, DialogRef, DialogService, ToastService } from "@bitwarden/components"; -import { SecretVersionView } from "../../models/view/secret-version.view"; -import { SecretView } from "../../models/view/secret.view"; -import { SecretVersionHistory, SecretVersionService } from "../secret-version.service"; -import { SecretService } from "../secret.service"; - import { SecretVersionDialogComponent, SecretVersionDialogParams, diff --git a/bitwarden_license/bit-web/src/app/secrets-manager/secrets/dialog/secret-version.component.stories.ts b/bitwarden_license/bit-web/src/app/secrets-manager/secrets/dialog/secret-version.component.stories.ts index 5c3bfc5d570..8fb55a02846 100644 --- a/bitwarden_license/bit-web/src/app/secrets-manager/secrets/dialog/secret-version.component.stories.ts +++ b/bitwarden_license/bit-web/src/app/secrets-manager/secrets/dialog/secret-version.component.stories.ts @@ -4,16 +4,18 @@ import { provideRouter } from "@angular/router"; import { applicationConfig, Meta, moduleMetadata, StoryObj } from "@storybook/angular"; import { action } from "storybook/actions"; +import { + SecretService, + SecretVersionHistory, + SecretVersionService, + SecretVersionView, +} from "@bitwarden/bit-sm"; import { LogService } from "@bitwarden/common/platform/abstractions/log.service"; import { PlatformUtilsService } from "@bitwarden/common/platform/abstractions/platform-utils.service"; import { ValidationService } from "@bitwarden/common/platform/abstractions/validation.service"; import { DIALOG_DATA, DialogRef, ToastService } from "@bitwarden/components"; import { PreloadedEnglishI18nModule } from "@bitwarden/web-vault/app/core/tests"; -import { SecretVersionView } from "../../models/view/secret-version.view"; -import { SecretVersionHistory, SecretVersionService } from "../secret-version.service"; -import { SecretService } from "../secret.service"; - import { SecretVersionDialogComponent, SecretVersionDialogParams, diff --git a/bitwarden_license/bit-web/src/app/secrets-manager/secrets/dialog/secret-version.component.ts b/bitwarden_license/bit-web/src/app/secrets-manager/secrets/dialog/secret-version.component.ts index 02cd4b5074e..b2f92a9960a 100644 --- a/bitwarden_license/bit-web/src/app/secrets-manager/secrets/dialog/secret-version.component.ts +++ b/bitwarden_license/bit-web/src/app/secrets-manager/secrets/dialog/secret-version.component.ts @@ -9,6 +9,7 @@ import { } from "@angular/core"; import { JslibModule } from "@bitwarden/angular/jslib.module"; +import { SecretService, SecretVersionService, SecretVersionView } from "@bitwarden/bit-sm"; import { I18nService } from "@bitwarden/common/platform/abstractions/i18n.service"; import { LogService } from "@bitwarden/common/platform/abstractions/log.service"; import { PlatformUtilsService } from "@bitwarden/common/platform/abstractions/platform-utils.service"; @@ -32,10 +33,6 @@ import { TypographyModule, } from "@bitwarden/components"; -import { SecretVersionView } from "../../models/view/secret-version.view"; -import { SecretVersionService } from "../secret-version.service"; -import { SecretService } from "../secret.service"; - export interface SecretVersionDialogParams { organizationId: string; secretId: string; diff --git a/bitwarden_license/bit-web/src/app/secrets-manager/secrets/dialog/secret-view-dialog.component.ts b/bitwarden_license/bit-web/src/app/secrets-manager/secrets/dialog/secret-view-dialog.component.ts index ace8db4e6ba..5e4eab7a81f 100644 --- a/bitwarden_license/bit-web/src/app/secrets-manager/secrets/dialog/secret-view-dialog.component.ts +++ b/bitwarden_license/bit-web/src/app/secrets-manager/secrets/dialog/secret-view-dialog.component.ts @@ -1,10 +1,9 @@ import { Component, Inject, OnInit } from "@angular/core"; import { FormControl, FormGroup } from "@angular/forms"; +import { SecretService } from "@bitwarden/bit-sm"; import { DIALOG_DATA } from "@bitwarden/components"; -import { SecretService } from "../secret.service"; - export interface SecretViewDialogParams { organizationId: string; secretId: string; diff --git a/bitwarden_license/bit-web/src/app/secrets-manager/secrets/secrets.component.ts b/bitwarden_license/bit-web/src/app/secrets-manager/secrets/secrets.component.ts index 2051d09ce0f..8bc9c23210b 100644 --- a/bitwarden_license/bit-web/src/app/secrets-manager/secrets/secrets.component.ts +++ b/bitwarden_license/bit-web/src/app/secrets-manager/secrets/secrets.component.ts @@ -4,6 +4,7 @@ import { Component, OnDestroy, OnInit } from "@angular/core"; import { ActivatedRoute, Router } from "@angular/router"; import { combineLatestWith, firstValueFrom, Observable, startWith, switchMap } from "rxjs"; +import { SecretListView, SecretService } from "@bitwarden/bit-sm"; import { getOrganizationById, OrganizationService, @@ -22,7 +23,6 @@ import { } from "@bitwarden/components"; import { openEntityEventsDialog } from "@bitwarden/web-vault/app/dirt/event-logs/components/entity-events/entity-events.component"; -import { SecretListView } from "../models/view/secret-list.view"; import { SecretsListComponent } from "../shared/secrets-list.component"; import { @@ -39,7 +39,6 @@ import { SecretViewDialogComponent, SecretViewDialogParams, } from "./dialog/secret-view-dialog.component"; -import { SecretService } from "./secret.service"; // FIXME(https://bitwarden.atlassian.net/browse/CL-764): Migrate to OnPush // eslint-disable-next-line @angular-eslint/prefer-on-push-component-change-detection diff --git a/bitwarden_license/bit-web/src/app/secrets-manager/service-accounts/access/access-list.component.spec.ts b/bitwarden_license/bit-web/src/app/secrets-manager/service-accounts/access/access-list.component.spec.ts index 89f83c09d6e..2f0c301a110 100644 --- a/bitwarden_license/bit-web/src/app/secrets-manager/service-accounts/access/access-list.component.spec.ts +++ b/bitwarden_license/bit-web/src/app/secrets-manager/service-accounts/access/access-list.component.spec.ts @@ -1,7 +1,7 @@ import { NO_ERRORS_SCHEMA } from "@angular/core"; import { TestBed } from "@angular/core/testing"; -import { AccessTokenView } from "../models/view/access-token.view"; +import { AccessTokenView } from "@bitwarden/bit-sm"; import { AccessListComponent } from "./access-list.component"; diff --git a/bitwarden_license/bit-web/src/app/secrets-manager/service-accounts/access/access-list.component.ts b/bitwarden_license/bit-web/src/app/secrets-manager/service-accounts/access/access-list.component.ts index 69876cf0926..3a0b1e2d964 100644 --- a/bitwarden_license/bit-web/src/app/secrets-manager/service-accounts/access/access-list.component.ts +++ b/bitwarden_license/bit-web/src/app/secrets-manager/service-accounts/access/access-list.component.ts @@ -4,10 +4,9 @@ import { SelectionModel } from "@angular/cdk/collections"; import { Component, EventEmitter, Input, Output } from "@angular/core"; import { NoResults } from "@bitwarden/assets/svg"; +import { AccessTokenView } from "@bitwarden/bit-sm"; import { TableDataSource } from "@bitwarden/components"; -import { AccessTokenView } from "../models/view/access-token.view"; - // FIXME(https://bitwarden.atlassian.net/browse/CL-764): Migrate to OnPush // eslint-disable-next-line @angular-eslint/prefer-on-push-component-change-detection @Component({ diff --git a/bitwarden_license/bit-web/src/app/secrets-manager/service-accounts/access/access-tokens.component.ts b/bitwarden_license/bit-web/src/app/secrets-manager/service-accounts/access/access-tokens.component.ts index 4e9069cd6cb..719b32c9e2d 100644 --- a/bitwarden_license/bit-web/src/app/secrets-manager/service-accounts/access/access-tokens.component.ts +++ b/bitwarden_license/bit-web/src/app/secrets-manager/service-accounts/access/access-tokens.component.ts @@ -12,16 +12,17 @@ import { takeUntil, } from "rxjs"; +import { + AccessService, + AccessTokenView, + ServiceAccountService, + ServiceAccountView, +} from "@bitwarden/bit-sm"; import { I18nService } from "@bitwarden/common/platform/abstractions/i18n.service"; import { PlatformUtilsService } from "@bitwarden/common/platform/abstractions/platform-utils.service"; import { DialogService, ToastService } from "@bitwarden/components"; import { openUserVerificationPrompt } from "@bitwarden/web-vault/app/auth/shared/components/user-verification"; -import { ServiceAccountView } from "../../models/view/service-account.view"; -import { AccessTokenView } from "../models/view/access-token.view"; -import { ServiceAccountService } from "../service-account.service"; - -import { AccessService } from "./access.service"; import { AccessTokenCreateDialogComponent } from "./dialogs/access-token-create-dialog.component"; // FIXME(https://bitwarden.atlassian.net/browse/CL-764): Migrate to OnPush diff --git a/bitwarden_license/bit-web/src/app/secrets-manager/service-accounts/access/dialogs/access-token-create-dialog.component.ts b/bitwarden_license/bit-web/src/app/secrets-manager/service-accounts/access/dialogs/access-token-create-dialog.component.ts index b90f3ffa3bc..71c66d307bd 100644 --- a/bitwarden_license/bit-web/src/app/secrets-manager/service-accounts/access/dialogs/access-token-create-dialog.component.ts +++ b/bitwarden_license/bit-web/src/app/secrets-manager/service-accounts/access/dialogs/access-token-create-dialog.component.ts @@ -3,12 +3,9 @@ import { Component, Inject, OnInit } from "@angular/core"; import { FormControl, FormGroup, Validators } from "@angular/forms"; +import { AccessService, AccessTokenView, ServiceAccountView } from "@bitwarden/bit-sm"; import { DialogRef, DIALOG_DATA, DialogService, BitValidators } from "@bitwarden/components"; -import { ServiceAccountView } from "../../../models/view/service-account.view"; -import { AccessTokenView } from "../../models/view/access-token.view"; -import { AccessService } from "../access.service"; - import { AccessTokenDetails, AccessTokenDialogComponent } from "./access-token-dialog.component"; export interface AccessTokenOperation { diff --git a/bitwarden_license/bit-web/src/app/secrets-manager/service-accounts/config/config.component.ts b/bitwarden_license/bit-web/src/app/secrets-manager/service-accounts/config/config.component.ts index 18ef397c6ae..88a8e4b8032 100644 --- a/bitwarden_license/bit-web/src/app/secrets-manager/service-accounts/config/config.component.ts +++ b/bitwarden_license/bit-web/src/app/secrets-manager/service-accounts/config/config.component.ts @@ -4,6 +4,7 @@ import { Component, OnDestroy, OnInit } from "@angular/core"; import { ActivatedRoute } from "@angular/router"; import { Subject, combineLatest, from, switchMap, takeUntil } from "rxjs"; +import { AccessPolicyService, ProjectListView, ProjectService } from "@bitwarden/bit-sm"; import { Environment, EnvironmentService, @@ -12,10 +13,6 @@ import { I18nService } from "@bitwarden/common/platform/abstractions/i18n.servic import { PlatformUtilsService } from "@bitwarden/common/platform/abstractions/platform-utils.service"; import { ToastService } from "@bitwarden/components"; -import { ProjectListView } from "../../models/view/project-list.view"; -import { ProjectService } from "../../projects/project.service"; -import { AccessPolicyService } from "../../shared/access-policies/access-policy.service"; - class ServiceAccountConfig { organizationId: string; serviceAccountId: string; diff --git a/bitwarden_license/bit-web/src/app/secrets-manager/service-accounts/dialog/service-account-delete-dialog.component.ts b/bitwarden_license/bit-web/src/app/secrets-manager/service-accounts/dialog/service-account-delete-dialog.component.ts index 9f3a2b7bf1f..389e23097f6 100644 --- a/bitwarden_license/bit-web/src/app/secrets-manager/service-accounts/dialog/service-account-delete-dialog.component.ts +++ b/bitwarden_license/bit-web/src/app/secrets-manager/service-accounts/dialog/service-account-delete-dialog.component.ts @@ -9,17 +9,15 @@ import { AbstractControl, } from "@angular/forms"; +import { BulkOperationStatus, ServiceAccountService, ServiceAccountView } from "@bitwarden/bit-sm"; import { I18nService } from "@bitwarden/common/platform/abstractions/i18n.service"; import { PlatformUtilsService } from "@bitwarden/common/platform/abstractions/platform-utils.service"; import { DialogRef, DIALOG_DATA, DialogService, ToastService } from "@bitwarden/components"; -import { ServiceAccountView } from "../../models/view/service-account.view"; import { - BulkOperationStatus, BulkStatusDetails, BulkStatusDialogComponent, } from "../../shared/dialogs/bulk-status-dialog.component"; -import { ServiceAccountService } from "../service-account.service"; export interface ServiceAccountDeleteOperation { serviceAccounts: ServiceAccountView[]; diff --git a/bitwarden_license/bit-web/src/app/secrets-manager/service-accounts/dialog/service-account-dialog.component.ts b/bitwarden_license/bit-web/src/app/secrets-manager/service-accounts/dialog/service-account-dialog.component.ts index 4ff6a13ae8d..1de3e257a01 100644 --- a/bitwarden_license/bit-web/src/app/secrets-manager/service-accounts/dialog/service-account-dialog.component.ts +++ b/bitwarden_license/bit-web/src/app/secrets-manager/service-accounts/dialog/service-account-dialog.component.ts @@ -4,12 +4,10 @@ import { Component, Inject, OnInit } from "@angular/core"; import { FormControl, FormGroup, Validators } from "@angular/forms"; import { Router } from "@angular/router"; +import { ServiceAccountService, ServiceAccountView } from "@bitwarden/bit-sm"; import { I18nService } from "@bitwarden/common/platform/abstractions/i18n.service"; import { DialogRef, DIALOG_DATA, BitValidators, ToastService } from "@bitwarden/components"; -import { ServiceAccountView } from "../../models/view/service-account.view"; -import { ServiceAccountService } from "../service-account.service"; - // FIXME: update to use a const object instead of a typescript enum // eslint-disable-next-line @bitwarden/platform/no-enums export enum OperationType { diff --git a/bitwarden_license/bit-web/src/app/secrets-manager/service-accounts/event-logs/service-accounts-events.component.ts b/bitwarden_license/bit-web/src/app/secrets-manager/service-accounts/event-logs/service-accounts-events.component.ts index bc4a45383a5..413ed193852 100644 --- a/bitwarden_license/bit-web/src/app/secrets-manager/service-accounts/event-logs/service-accounts-events.component.ts +++ b/bitwarden_license/bit-web/src/app/secrets-manager/service-accounts/event-logs/service-accounts-events.component.ts @@ -6,6 +6,7 @@ import { ChangeDetectionStrategy, Component, OnDestroy, OnInit } from "@angular/ import { ActivatedRoute } from "@angular/router"; import { takeUntil } from "rxjs"; +import { ServiceAccountEventLogApiService } from "@bitwarden/bit-sm"; import { OrganizationService } from "@bitwarden/common/admin-console/abstractions/organization/organization.service.abstraction"; import { AccountService } from "@bitwarden/common/auth/abstractions/account.service"; import { FileDownloadService } from "@bitwarden/common/platform/abstractions/file-download/file-download.service"; @@ -16,8 +17,6 @@ import { ToastService } from "@bitwarden/components"; import { EventService, BaseEventsComponent } from "@bitwarden/web-vault/app/dirt/event-logs"; import { EventExportService } from "@bitwarden/web-vault/app/tools/event-export"; -import { ServiceAccountEventLogApiService } from "./service-account-event-log-api.service"; - @Component({ changeDetection: ChangeDetectionStrategy.OnPush, selector: "sm-service-accounts-events", diff --git a/bitwarden_license/bit-web/src/app/secrets-manager/service-accounts/guards/service-account-access.guard.spec.ts b/bitwarden_license/bit-web/src/app/secrets-manager/service-accounts/guards/service-account-access.guard.spec.ts index e7b258ed1c2..738b4f905b6 100644 --- a/bitwarden_license/bit-web/src/app/secrets-manager/service-accounts/guards/service-account-access.guard.spec.ts +++ b/bitwarden_license/bit-web/src/app/secrets-manager/service-accounts/guards/service-account-access.guard.spec.ts @@ -5,6 +5,7 @@ import { RouterTestingModule } from "@angular/router/testing"; import { MockProxy, mock } from "jest-mock-extended"; import { of } from "rxjs"; +import { ServiceAccountService, ServiceAccountView } from "@bitwarden/bit-sm"; import { OrganizationService } from "@bitwarden/common/admin-console/abstractions/organization/organization.service.abstraction"; import { Organization } from "@bitwarden/common/admin-console/models/domain/organization"; import { AccountService } from "@bitwarden/common/auth/abstractions/account.service"; @@ -15,9 +16,6 @@ import { UserId } from "@bitwarden/common/types/guid"; import { ToastService } from "@bitwarden/components"; import { RouterService } from "@bitwarden/web-vault/app/core"; -import { ServiceAccountView } from "../../models/view/service-account.view"; -import { ServiceAccountService } from "../service-account.service"; - import { serviceAccountAccessGuard } from "./service-account-access.guard"; // FIXME(https://bitwarden.atlassian.net/browse/CL-764): Migrate to OnPush diff --git a/bitwarden_license/bit-web/src/app/secrets-manager/service-accounts/guards/service-account-access.guard.ts b/bitwarden_license/bit-web/src/app/secrets-manager/service-accounts/guards/service-account-access.guard.ts index 0f182a5ca8c..71c79da97b1 100644 --- a/bitwarden_license/bit-web/src/app/secrets-manager/service-accounts/guards/service-account-access.guard.ts +++ b/bitwarden_license/bit-web/src/app/secrets-manager/service-accounts/guards/service-account-access.guard.ts @@ -3,11 +3,10 @@ import { inject } from "@angular/core"; import { ActivatedRouteSnapshot, CanActivateFn, createUrlTreeFromSnapshot } from "@angular/router"; +import { ServiceAccountService } from "@bitwarden/bit-sm"; import { I18nService } from "@bitwarden/common/platform/abstractions/i18n.service"; import { ToastService } from "@bitwarden/components"; -import { ServiceAccountService } from "../service-account.service"; - /** * Redirects to service accounts page if the user doesn't have access to service account. */ diff --git a/bitwarden_license/bit-web/src/app/secrets-manager/service-accounts/people/service-account-people.component.ts b/bitwarden_license/bit-web/src/app/secrets-manager/service-accounts/people/service-account-people.component.ts index 42ab2ec613b..dcf659f8002 100644 --- a/bitwarden_license/bit-web/src/app/secrets-manager/service-accounts/people/service-account-people.component.ts +++ b/bitwarden_license/bit-web/src/app/secrets-manager/service-accounts/people/service-account-people.component.ts @@ -5,12 +5,12 @@ import { FormControl, FormGroup } from "@angular/forms"; import { ActivatedRoute, Router } from "@angular/router"; import { combineLatest, Subject, switchMap, takeUntil } from "rxjs"; +import { AccessPolicyService, ServiceAccountPeopleAccessPoliciesView } from "@bitwarden/bit-sm"; import { I18nService } from "@bitwarden/common/platform/abstractions/i18n.service"; import { PlatformUtilsService } from "@bitwarden/common/platform/abstractions/platform-utils.service"; import { ValidationService } from "@bitwarden/common/platform/abstractions/validation.service"; import { DialogService, ToastService } from "@bitwarden/components"; -import { ServiceAccountPeopleAccessPoliciesView } from "../../models/view/access-policies/service-account-people-access-policies.view"; import { AccessPolicySelectorService } from "../../shared/access-policies/access-policy-selector/access-policy-selector.service"; import { ApItemValueType, @@ -23,7 +23,6 @@ import { } from "../../shared/access-policies/access-policy-selector/models/ap-item-view.type"; import { ApItemEnum } from "../../shared/access-policies/access-policy-selector/models/enums/ap-item.enum"; import { ApPermissionEnum } from "../../shared/access-policies/access-policy-selector/models/enums/ap-permission.enum"; -import { AccessPolicyService } from "../../shared/access-policies/access-policy.service"; // FIXME(https://bitwarden.atlassian.net/browse/CL-764): Migrate to OnPush // eslint-disable-next-line @angular-eslint/prefer-on-push-component-change-detection diff --git a/bitwarden_license/bit-web/src/app/secrets-manager/service-accounts/projects/service-account-projects.component.spec.ts b/bitwarden_license/bit-web/src/app/secrets-manager/service-accounts/projects/service-account-projects.component.spec.ts index 70fba4a4416..b0e240daa63 100644 --- a/bitwarden_license/bit-web/src/app/secrets-manager/service-accounts/projects/service-account-projects.component.spec.ts +++ b/bitwarden_license/bit-web/src/app/secrets-manager/service-accounts/projects/service-account-projects.component.spec.ts @@ -3,18 +3,17 @@ import { ActivatedRoute } from "@angular/router"; import { mock, MockProxy } from "jest-mock-extended"; import { of } from "rxjs"; +import { + AccessPolicyService, + GrantedProjectAccessPolicyView, + GrantedProjectPolicyPermissionDetailsView, + ServiceAccountGrantedPoliciesView, +} from "@bitwarden/bit-sm"; import { I18nService } from "@bitwarden/common/platform/abstractions/i18n.service"; import { PlatformUtilsService } from "@bitwarden/common/platform/abstractions/platform-utils.service"; import { ValidationService } from "@bitwarden/common/platform/abstractions/validation.service"; import { ToastService } from "@bitwarden/components"; -import { GrantedProjectAccessPolicyView } from "../../models/view/access-policies/access-policy.view"; -import { - GrantedProjectPolicyPermissionDetailsView, - ServiceAccountGrantedPoliciesView, -} from "../../models/view/access-policies/service-account-granted-policies.view"; -import { AccessPolicyService } from "../../shared/access-policies/access-policy.service"; - import { ServiceAccountProjectsComponent } from "./service-account-projects.component"; const ORGANIZATION_ID = "org-1"; diff --git a/bitwarden_license/bit-web/src/app/secrets-manager/service-accounts/projects/service-account-projects.component.ts b/bitwarden_license/bit-web/src/app/secrets-manager/service-accounts/projects/service-account-projects.component.ts index 936514f0467..e1a867c03f5 100644 --- a/bitwarden_license/bit-web/src/app/secrets-manager/service-accounts/projects/service-account-projects.component.ts +++ b/bitwarden_license/bit-web/src/app/secrets-manager/service-accounts/projects/service-account-projects.component.ts @@ -5,12 +5,12 @@ import { FormControl, FormGroup } from "@angular/forms"; import { ActivatedRoute } from "@angular/router"; import { combineLatest, Subject, switchMap, takeUntil } from "rxjs"; +import { AccessPolicyService, ServiceAccountGrantedPoliciesView } from "@bitwarden/bit-sm"; import { I18nService } from "@bitwarden/common/platform/abstractions/i18n.service"; import { PlatformUtilsService } from "@bitwarden/common/platform/abstractions/platform-utils.service"; import { ValidationService } from "@bitwarden/common/platform/abstractions/validation.service"; import { ToastService } from "@bitwarden/components"; -import { ServiceAccountGrantedPoliciesView } from "../../models/view/access-policies/service-account-granted-policies.view"; import { ApItemValueType, convertToServiceAccountGrantedPoliciesView, @@ -20,7 +20,6 @@ import { convertPotentialGranteesToApItemViewType, convertGrantedPoliciesToAccessPolicyItemViews, } from "../../shared/access-policies/access-policy-selector/models/ap-item-view.type"; -import { AccessPolicyService } from "../../shared/access-policies/access-policy.service"; // FIXME(https://bitwarden.atlassian.net/browse/CL-764): Migrate to OnPush // eslint-disable-next-line @angular-eslint/prefer-on-push-component-change-detection diff --git a/bitwarden_license/bit-web/src/app/secrets-manager/service-accounts/service-account.component.spec.ts b/bitwarden_license/bit-web/src/app/secrets-manager/service-accounts/service-account.component.spec.ts index d570de21b78..250732e0dd3 100644 --- a/bitwarden_license/bit-web/src/app/secrets-manager/service-accounts/service-account.component.spec.ts +++ b/bitwarden_license/bit-web/src/app/secrets-manager/service-accounts/service-account.component.spec.ts @@ -3,6 +3,13 @@ import { ActivatedRoute } from "@angular/router"; import { mock, MockProxy } from "jest-mock-extended"; import { of, Subject } from "rxjs"; +import { + AccessPolicyService, + AccessService, + CountService, + ServiceAccountService, + ServiceAccountView, +} from "@bitwarden/bit-sm"; import { OrganizationService } from "@bitwarden/common/admin-console/abstractions/organization/organization.service.abstraction"; import { Organization } from "@bitwarden/common/admin-console/models/domain/organization"; import { Account, AccountService } from "@bitwarden/common/auth/abstractions/account.service"; @@ -10,13 +17,7 @@ import { ConfigService } from "@bitwarden/common/platform/abstractions/config/co import { OrganizationId, UserId } from "@bitwarden/common/types/guid"; import { DialogService } from "@bitwarden/components"; -import { ServiceAccountView } from "../models/view/service-account.view"; -import { AccessPolicyService } from "../shared/access-policies/access-policy.service"; -import { CountService } from "../shared/counts/count.service"; - -import { AccessService } from "./access/access.service"; import { ServiceAccountComponent } from "./service-account.component"; -import { ServiceAccountService } from "./service-account.service"; describe("ServiceAccountComponent", () => { const organizationId = "org-1" as OrganizationId; diff --git a/bitwarden_license/bit-web/src/app/secrets-manager/service-accounts/service-account.component.ts b/bitwarden_license/bit-web/src/app/secrets-manager/service-accounts/service-account.component.ts index 68a5246d3b4..1f0e05ceaec 100644 --- a/bitwarden_license/bit-web/src/app/secrets-manager/service-accounts/service-account.component.ts +++ b/bitwarden_license/bit-web/src/app/secrets-manager/service-accounts/service-account.component.ts @@ -14,6 +14,14 @@ import { takeUntil, } from "rxjs"; +import { + AccessPolicyService, + AccessService, + CountService, + ServiceAccountCounts, + ServiceAccountService, + ServiceAccountView, +} from "@bitwarden/bit-sm"; import { OrganizationService } from "@bitwarden/common/admin-console/abstractions/organization/organization.service.abstraction"; import { AccountService } from "@bitwarden/common/auth/abstractions/account.service"; import { getUserId } from "@bitwarden/common/auth/services/account.service"; @@ -23,14 +31,7 @@ import { getById } from "@bitwarden/common/platform/misc"; import { OrganizationId, UserId } from "@bitwarden/common/types/guid"; import { DialogService } from "@bitwarden/components"; -import { ServiceAccountCounts } from "../models/view/counts.view"; -import { ServiceAccountView } from "../models/view/service-account.view"; -import { AccessPolicyService } from "../shared/access-policies/access-policy.service"; -import { CountService } from "../shared/counts/count.service"; - -import { AccessService } from "./access/access.service"; import { AccessTokenCreateDialogComponent } from "./access/dialogs/access-token-create-dialog.component"; -import { ServiceAccountService } from "./service-account.service"; // FIXME(https://bitwarden.atlassian.net/browse/CL-764): Migrate to OnPush // eslint-disable-next-line @angular-eslint/prefer-on-push-component-change-detection diff --git a/bitwarden_license/bit-web/src/app/secrets-manager/service-accounts/service-accounts-list.component.ts b/bitwarden_license/bit-web/src/app/secrets-manager/service-accounts/service-accounts-list.component.ts index 3826e7527f6..fe3957cc579 100644 --- a/bitwarden_license/bit-web/src/app/secrets-manager/service-accounts/service-accounts-list.component.ts +++ b/bitwarden_license/bit-web/src/app/secrets-manager/service-accounts/service-accounts-list.component.ts @@ -6,6 +6,7 @@ import { ActivatedRoute } from "@angular/router"; import { catchError, concatMap, map, Observable, of, Subject, switchMap, takeUntil } from "rxjs"; import { NoResults } from "@bitwarden/assets/svg"; +import { ServiceAccountSecretsDetailsView, ServiceAccountView } from "@bitwarden/bit-sm"; import { getOrganizationById, OrganizationService, @@ -17,11 +18,6 @@ import { DialogRef, DialogService, TableDataSource, ToastService } from "@bitwar import { LogService } from "@bitwarden/logging"; import { openEntityEventsDialog } from "@bitwarden/web-vault/app/dirt/event-logs/components/entity-events/entity-events.component"; -import { - ServiceAccountSecretsDetailsView, - ServiceAccountView, -} from "../models/view/service-account.view"; - // FIXME(https://bitwarden.atlassian.net/browse/CL-764): Migrate to OnPush // eslint-disable-next-line @angular-eslint/prefer-on-push-component-change-detection @Component({ diff --git a/bitwarden_license/bit-web/src/app/secrets-manager/service-accounts/service-accounts.component.ts b/bitwarden_license/bit-web/src/app/secrets-manager/service-accounts/service-accounts.component.ts index 4e48c484c1d..0715bd44e18 100644 --- a/bitwarden_license/bit-web/src/app/secrets-manager/service-accounts/service-accounts.component.ts +++ b/bitwarden_license/bit-web/src/app/secrets-manager/service-accounts/service-accounts.component.ts @@ -4,6 +4,11 @@ import { Component, OnInit } from "@angular/core"; import { ActivatedRoute, Router } from "@angular/router"; import { combineLatestWith, firstValueFrom, Observable, startWith, switchMap } from "rxjs"; +import { + ServiceAccountSecretsDetailsView, + ServiceAccountService, + ServiceAccountView, +} from "@bitwarden/bit-sm"; import { getOrganizationById, OrganizationService, @@ -14,11 +19,6 @@ import { I18nService } from "@bitwarden/common/platform/abstractions/i18n.servic import { DialogRef, DialogService, ToastService } from "@bitwarden/components"; import { openEntityEventsDialog } from "@bitwarden/web-vault/app/dirt/event-logs/components/entity-events/entity-events.component"; -import { - ServiceAccountSecretsDetailsView, - ServiceAccountView, -} from "../models/view/service-account.view"; - import { ServiceAccountDeleteDialogComponent, ServiceAccountDeleteOperation, @@ -28,7 +28,6 @@ import { ServiceAccountDialogComponent, ServiceAccountOperation, } from "./dialog/service-account-dialog.component"; -import { ServiceAccountService } from "./service-account.service"; // FIXME(https://bitwarden.atlassian.net/browse/CL-764): Migrate to OnPush // eslint-disable-next-line @angular-eslint/prefer-on-push-component-change-detection diff --git a/bitwarden_license/bit-web/src/app/secrets-manager/settings/dialog/sm-import-error-dialog.component.ts b/bitwarden_license/bit-web/src/app/secrets-manager/settings/dialog/sm-import-error-dialog.component.ts index 85e054d998b..8ede160aa80 100644 --- a/bitwarden_license/bit-web/src/app/secrets-manager/settings/dialog/sm-import-error-dialog.component.ts +++ b/bitwarden_license/bit-web/src/app/secrets-manager/settings/dialog/sm-import-error-dialog.component.ts @@ -1,11 +1,9 @@ import { Component, Inject } from "@angular/core"; +import { SecretsManagerImportError, SecretsManagerImportErrorLine } from "@bitwarden/bit-sm"; import { I18nService } from "@bitwarden/common/platform/abstractions/i18n.service"; import { DialogRef, DIALOG_DATA } from "@bitwarden/components"; -import { SecretsManagerImportError } from "../models/error/sm-import-error"; -import { SecretsManagerImportErrorLine } from "../models/error/sm-import-error-line"; - export interface SecretsManagerImportErrorDialogOperation { error: SecretsManagerImportError; } diff --git a/bitwarden_license/bit-web/src/app/secrets-manager/settings/porting/sm-export.component.ts b/bitwarden_license/bit-web/src/app/secrets-manager/settings/porting/sm-export.component.ts index f2af3d4e8f8..69fedde4b1b 100644 --- a/bitwarden_license/bit-web/src/app/secrets-manager/settings/porting/sm-export.component.ts +++ b/bitwarden_license/bit-web/src/app/secrets-manager/settings/porting/sm-export.component.ts @@ -5,6 +5,7 @@ import { FormControl, FormGroup, Validators } from "@angular/forms"; import { ActivatedRoute } from "@angular/router"; import { firstValueFrom, Subject, switchMap, takeUntil } from "rxjs"; +import { SecretsManagerPortingApiService } from "@bitwarden/bit-sm"; import { getOrganizationById, OrganizationService, @@ -18,7 +19,6 @@ import { PlatformUtilsService } from "@bitwarden/common/platform/abstractions/pl import { DialogService, ToastService } from "@bitwarden/components"; import { openUserVerificationPrompt } from "@bitwarden/web-vault/app/auth/shared/components/user-verification"; -import { SecretsManagerPortingApiService } from "../services/sm-porting-api.service"; import { SecretsManagerPortingService } from "../services/sm-porting.service"; type ExportFormat = { diff --git a/bitwarden_license/bit-web/src/app/secrets-manager/settings/porting/sm-import.component.ts b/bitwarden_license/bit-web/src/app/secrets-manager/settings/porting/sm-import.component.ts index 217dfada1cf..4ab3e5adb2f 100644 --- a/bitwarden_license/bit-web/src/app/secrets-manager/settings/porting/sm-import.component.ts +++ b/bitwarden_license/bit-web/src/app/secrets-manager/settings/porting/sm-import.component.ts @@ -5,6 +5,7 @@ import { FormControl, FormGroup } from "@angular/forms"; import { ActivatedRoute } from "@angular/router"; import { Subject, takeUntil } from "rxjs"; +import { SecretsManagerImportError, SecretsManagerPortingApiService } from "@bitwarden/bit-sm"; import { FileDownloadService } from "@bitwarden/common/platform/abstractions/file-download/file-download.service"; import { I18nService } from "@bitwarden/common/platform/abstractions/i18n.service"; import { LogService } from "@bitwarden/common/platform/abstractions/log.service"; @@ -15,8 +16,6 @@ import { SecretsManagerImportErrorDialogComponent, SecretsManagerImportErrorDialogOperation, } from "../dialog/sm-import-error-dialog.component"; -import { SecretsManagerImportError } from "../models/error/sm-import-error"; -import { SecretsManagerPortingApiService } from "../services/sm-porting-api.service"; // FIXME(https://bitwarden.atlassian.net/browse/CL-764): Migrate to OnPush // eslint-disable-next-line @angular-eslint/prefer-on-push-component-change-detection diff --git a/bitwarden_license/bit-web/src/app/secrets-manager/shared/access-policies/access-policy-selector/models/ap-item-value.type.ts b/bitwarden_license/bit-web/src/app/secrets-manager/shared/access-policies/access-policy-selector/models/ap-item-value.type.ts index 2de071fb2e8..5b4a6abbca7 100644 --- a/bitwarden_license/bit-web/src/app/secrets-manager/shared/access-policies/access-policy-selector/models/ap-item-value.type.ts +++ b/bitwarden_license/bit-web/src/app/secrets-manager/shared/access-policies/access-policy-selector/models/ap-item-value.type.ts @@ -1,15 +1,13 @@ import { - UserAccessPolicyView, - GroupAccessPolicyView, - ServiceAccountAccessPolicyView, GrantedProjectAccessPolicyView, -} from "../../../../models/view/access-policies/access-policy.view"; -import { ProjectServiceAccountsAccessPoliciesView } from "../../../../models/view/access-policies/project-service-accounts-access-policies.view"; -import { SecretAccessPoliciesView } from "../../../../models/view/access-policies/secret-access-policies.view"; -import { - ServiceAccountGrantedPoliciesView, GrantedProjectPolicyPermissionDetailsView, -} from "../../../../models/view/access-policies/service-account-granted-policies.view"; + GroupAccessPolicyView, + ProjectServiceAccountsAccessPoliciesView, + SecretAccessPoliciesView, + ServiceAccountAccessPolicyView, + ServiceAccountGrantedPoliciesView, + UserAccessPolicyView, +} from "@bitwarden/bit-sm"; import { ApItemEnum } from "./enums/ap-item.enum"; import { ApPermissionEnum, ApPermissionEnumUtil } from "./enums/ap-permission.enum"; diff --git a/bitwarden_license/bit-web/src/app/secrets-manager/shared/access-policies/access-policy-selector/models/ap-item-view.spec.ts b/bitwarden_license/bit-web/src/app/secrets-manager/shared/access-policies/access-policy-selector/models/ap-item-view.spec.ts index c7090391211..446f9ead3cc 100644 --- a/bitwarden_license/bit-web/src/app/secrets-manager/shared/access-policies/access-policy-selector/models/ap-item-view.spec.ts +++ b/bitwarden_license/bit-web/src/app/secrets-manager/shared/access-policies/access-policy-selector/models/ap-item-view.spec.ts @@ -1,13 +1,13 @@ import { GroupAccessPolicyView, + ProjectPeopleAccessPoliciesView, + ProjectServiceAccountsAccessPoliciesView, + SecretAccessPoliciesView, ServiceAccountAccessPolicyView, + ServiceAccountGrantedPoliciesView, + ServiceAccountPeopleAccessPoliciesView, UserAccessPolicyView, -} from "../../../../models/view/access-policies/access-policy.view"; -import { ProjectPeopleAccessPoliciesView } from "../../../../models/view/access-policies/project-people-access-policies.view"; -import { ProjectServiceAccountsAccessPoliciesView } from "../../../../models/view/access-policies/project-service-accounts-access-policies.view"; -import { SecretAccessPoliciesView } from "../../../../models/view/access-policies/secret-access-policies.view"; -import { ServiceAccountGrantedPoliciesView } from "../../../../models/view/access-policies/service-account-granted-policies.view"; -import { ServiceAccountPeopleAccessPoliciesView } from "../../../../models/view/access-policies/service-account-people-access-policies.view"; +} from "@bitwarden/bit-sm"; import { convertGrantedPoliciesToAccessPolicyItemViews, diff --git a/bitwarden_license/bit-web/src/app/secrets-manager/shared/access-policies/access-policy-selector/models/ap-item-view.type.ts b/bitwarden_license/bit-web/src/app/secrets-manager/shared/access-policies/access-policy-selector/models/ap-item-view.type.ts index 607336e4747..43ef5118422 100644 --- a/bitwarden_license/bit-web/src/app/secrets-manager/shared/access-policies/access-policy-selector/models/ap-item-view.type.ts +++ b/bitwarden_license/bit-web/src/app/secrets-manager/shared/access-policies/access-policy-selector/models/ap-item-view.type.ts @@ -1,19 +1,19 @@ // FIXME: Update this file to be type safe and remove this and next line // @ts-strict-ignore -import { Utils } from "@bitwarden/common/platform/misc/utils"; -import { SelectItemView } from "@bitwarden/components"; import { GroupAccessPolicyView, + PotentialGranteeView, + ProjectPeopleAccessPoliciesView, + ProjectServiceAccountsAccessPoliciesView, + SecretAccessPoliciesView, ServiceAccountAccessPolicyView, + ServiceAccountGrantedPoliciesView, + ServiceAccountPeopleAccessPoliciesView, UserAccessPolicyView, -} from "../../../../models/view/access-policies/access-policy.view"; -import { PotentialGranteeView } from "../../../../models/view/access-policies/potential-grantee.view"; -import { ProjectPeopleAccessPoliciesView } from "../../../../models/view/access-policies/project-people-access-policies.view"; -import { ProjectServiceAccountsAccessPoliciesView } from "../../../../models/view/access-policies/project-service-accounts-access-policies.view"; -import { SecretAccessPoliciesView } from "../../../../models/view/access-policies/secret-access-policies.view"; -import { ServiceAccountGrantedPoliciesView } from "../../../../models/view/access-policies/service-account-granted-policies.view"; -import { ServiceAccountPeopleAccessPoliciesView } from "../../../../models/view/access-policies/service-account-people-access-policies.view"; +} from "@bitwarden/bit-sm"; +import { Utils } from "@bitwarden/common/platform/misc/utils"; +import { SelectItemView } from "@bitwarden/components"; import { ApItemEnum, ApItemEnumUtil } from "./enums/ap-item.enum"; import { ApPermissionEnum, ApPermissionEnumUtil } from "./enums/ap-permission.enum"; diff --git a/bitwarden_license/bit-web/src/app/secrets-manager/shared/dialogs/bulk-status-dialog.component.ts b/bitwarden_license/bit-web/src/app/secrets-manager/shared/dialogs/bulk-status-dialog.component.ts index ab9a88d5a19..277e643cc09 100644 --- a/bitwarden_license/bit-web/src/app/secrets-manager/shared/dialogs/bulk-status-dialog.component.ts +++ b/bitwarden_license/bit-web/src/app/secrets-manager/shared/dialogs/bulk-status-dialog.component.ts @@ -2,6 +2,7 @@ // @ts-strict-ignore import { Component, Inject, OnInit } from "@angular/core"; +import { BulkOperationStatus } from "@bitwarden/bit-sm"; import { DialogRef, DIALOG_DATA } from "@bitwarden/components"; export interface BulkStatusDetails { @@ -12,12 +13,6 @@ export interface BulkStatusDetails { details: BulkOperationStatus[]; } -export class BulkOperationStatus { - id: string; - name: string; - errorMessage?: string; -} - // FIXME(https://bitwarden.atlassian.net/browse/CL-764): Migrate to OnPush // eslint-disable-next-line @angular-eslint/prefer-on-push-component-change-detection @Component({ diff --git a/bitwarden_license/bit-web/src/app/secrets-manager/shared/projects-list.component.ts b/bitwarden_license/bit-web/src/app/secrets-manager/shared/projects-list.component.ts index 0a4e0be6ea6..2f92973ad01 100644 --- a/bitwarden_license/bit-web/src/app/secrets-manager/shared/projects-list.component.ts +++ b/bitwarden_license/bit-web/src/app/secrets-manager/shared/projects-list.component.ts @@ -6,6 +6,7 @@ import { ActivatedRoute } from "@angular/router"; import { catchError, concatMap, map, Observable, of, Subject, switchMap, takeUntil } from "rxjs"; import { NoResults } from "@bitwarden/assets/svg"; +import { ProjectListView, ProjectView } from "@bitwarden/bit-sm"; import { getOrganizationById, OrganizationService, @@ -18,9 +19,6 @@ import { DialogRef, DialogService, TableDataSource, ToastService } from "@bitwar import { LogService } from "@bitwarden/logging"; import { openEntityEventsDialog } from "@bitwarden/web-vault/app/dirt/event-logs/components/entity-events/entity-events.component"; -import { ProjectListView } from "../models/view/project-list.view"; -import { ProjectView } from "../models/view/project.view"; - // FIXME(https://bitwarden.atlassian.net/browse/CL-764): Migrate to OnPush // eslint-disable-next-line @angular-eslint/prefer-on-push-component-change-detection @Component({ diff --git a/bitwarden_license/bit-web/src/app/secrets-manager/shared/secrets-list.component.ts b/bitwarden_license/bit-web/src/app/secrets-manager/shared/secrets-list.component.ts index f6a466953f9..52d22cb438f 100644 --- a/bitwarden_license/bit-web/src/app/secrets-manager/shared/secrets-list.component.ts +++ b/bitwarden_license/bit-web/src/app/secrets-manager/shared/secrets-list.component.ts @@ -14,6 +14,7 @@ import { ActivatedRoute } from "@angular/router"; import { catchError, concatMap, map, Observable, of, Subject, switchMap, takeUntil } from "rxjs"; import { NoResults } from "@bitwarden/assets/svg"; +import { SecretListView, SecretService, SecretView } from "@bitwarden/bit-sm"; import { getOrganizationById, OrganizationService, @@ -28,10 +29,6 @@ import { PlatformUtilsService } from "@bitwarden/common/platform/abstractions/pl import { DialogRef, DialogService, TableDataSource, ToastService } from "@bitwarden/components"; import { openEntityEventsDialog } from "@bitwarden/web-vault/app/dirt/event-logs/components/entity-events/entity-events.component"; -import { SecretListView } from "../models/view/secret-list.view"; -import { SecretView } from "../models/view/secret.view"; -import { SecretService } from "../secrets/secret.service"; - @Component({ selector: "sm-secrets-list", templateUrl: "./secrets-list.component.html", diff --git a/bitwarden_license/bit-web/src/app/secrets-manager/trash/dialog/secret-hard-delete.component.ts b/bitwarden_license/bit-web/src/app/secrets-manager/trash/dialog/secret-hard-delete.component.ts index c3300fe040c..589fb44fce2 100644 --- a/bitwarden_license/bit-web/src/app/secrets-manager/trash/dialog/secret-hard-delete.component.ts +++ b/bitwarden_license/bit-web/src/app/secrets-manager/trash/dialog/secret-hard-delete.component.ts @@ -2,12 +2,11 @@ // @ts-strict-ignore import { Component, Inject } from "@angular/core"; +import { SecretService } from "@bitwarden/bit-sm"; import { I18nService } from "@bitwarden/common/platform/abstractions/i18n.service"; import { PlatformUtilsService } from "@bitwarden/common/platform/abstractions/platform-utils.service"; import { DialogRef, DIALOG_DATA, ToastService } from "@bitwarden/components"; -import { SecretService } from "../../secrets/secret.service"; - export interface SecretHardDeleteOperation { secretIds: string[]; organizationId: string; diff --git a/bitwarden_license/bit-web/src/app/secrets-manager/trash/dialog/secret-restore.component.ts b/bitwarden_license/bit-web/src/app/secrets-manager/trash/dialog/secret-restore.component.ts index bb427193a54..f6bf89b52b2 100644 --- a/bitwarden_license/bit-web/src/app/secrets-manager/trash/dialog/secret-restore.component.ts +++ b/bitwarden_license/bit-web/src/app/secrets-manager/trash/dialog/secret-restore.component.ts @@ -2,12 +2,11 @@ // @ts-strict-ignore import { Component, Inject } from "@angular/core"; +import { SecretService } from "@bitwarden/bit-sm"; import { I18nService } from "@bitwarden/common/platform/abstractions/i18n.service"; import { PlatformUtilsService } from "@bitwarden/common/platform/abstractions/platform-utils.service"; import { DialogRef, DIALOG_DATA, ToastService } from "@bitwarden/components"; -import { SecretService } from "../../secrets/secret.service"; - export interface SecretRestoreOperation { secretIds: string[]; organizationId: string; diff --git a/bitwarden_license/bit-web/src/app/secrets-manager/trash/trash.component.ts b/bitwarden_license/bit-web/src/app/secrets-manager/trash/trash.component.ts index 1e6483dcf92..c271b90d220 100644 --- a/bitwarden_license/bit-web/src/app/secrets-manager/trash/trash.component.ts +++ b/bitwarden_license/bit-web/src/app/secrets-manager/trash/trash.component.ts @@ -4,12 +4,11 @@ import { Component, OnInit } from "@angular/core"; import { ActivatedRoute } from "@angular/router"; import { combineLatestWith, Observable, startWith, switchMap } from "rxjs"; +import { SecretListView, SecretService } from "@bitwarden/bit-sm"; import { I18nService } from "@bitwarden/common/platform/abstractions/i18n.service"; import { PlatformUtilsService } from "@bitwarden/common/platform/abstractions/platform-utils.service"; import { CenterPositionStrategy, DialogService } from "@bitwarden/components"; -import { SecretListView } from "../models/view/secret-list.view"; -import { SecretService } from "../secrets/secret.service"; import { SecretsListComponent } from "../shared/secrets-list.component"; import { diff --git a/eslint.config.mjs b/eslint.config.mjs index 67fe0fd6874..848649e727e 100644 --- a/eslint.config.mjs +++ b/eslint.config.mjs @@ -432,6 +432,16 @@ export default tseslint.config( "no-restricted-imports": buildNoRestrictedImports(["@bitwarden/bit-pam-components"]), }, }, + { + files: ["bitwarden_license/bit-sm/src/**/*.ts"], + rules: { + "no-restricted-imports": buildNoRestrictedImports([ + "@bitwarden/bit-sm", + "@bitwarden/bit-web/*", + "@bitwarden/bit-cli/*", + ]), + }, + }, { files: ["apps/**/*.ts"], rules: { @@ -439,9 +449,11 @@ export default tseslint.config( "no-restricted-imports": buildNoRestrictedImports([ "bitwarden_license/**", "@bitwarden/bit-common/*", + "@bitwarden/bit-sm", "@bitwarden/bit-pam", "@bitwarden/bit-pam-components", "@bitwarden/bit-web/*", + "@bitwarden/bit-cli/*", ]), }, }, @@ -451,6 +463,7 @@ export default tseslint.config( "no-restricted-imports": buildNoRestrictedImports([ "bitwarden_license/**", "@bitwarden/bit-common/*", + "@bitwarden/bit-sm", "@bitwarden/bit-pam", "@bitwarden/bit-pam-components", "@bitwarden/bit-web/*", @@ -471,6 +484,7 @@ export default tseslint.config( "@angular", "bitwarden_license/**", "@bitwarden/bit-common/*", + "@bitwarden/bit-sm", "@bitwarden/bit-pam", "@bitwarden/bit-pam-components", "@bitwarden/bit-web/*", @@ -486,9 +500,11 @@ export default tseslint.config( "no-restricted-imports": buildNoRestrictedImports([ "bitwarden_license/**", "@bitwarden/bit-common/*", + "@bitwarden/bit-sm", "@bitwarden/bit-pam", "@bitwarden/bit-pam-components", "@bitwarden/bit-web/*", + "@bitwarden/bit-cli/*", ]), }, }, @@ -768,6 +784,7 @@ export default tseslint.config( files: [ "libs/**/*.ts", "bitwarden_license/bit-common/src/**/*.ts", + "bitwarden_license/bit-sm/src/**/*.ts", "bitwarden_license/bit-pam/src/**/*.ts", "bitwarden_license/bit-pam-components/src/**/*.ts", ], diff --git a/jest.config.js b/jest.config.js index 617c84f942d..72ce5eba92c 100644 --- a/jest.config.js +++ b/jest.config.js @@ -24,6 +24,7 @@ module.exports = { "/bitwarden_license/bit-cli/jest.config.js", "/bitwarden_license/bit-common/jest.config.js", "/bitwarden_license/bit-desktop/jest.config.js", + "/bitwarden_license/bit-sm/jest.config.js", "/bitwarden_license/bit-pam/jest.config.js", "/bitwarden_license/bit-pam-components/jest.config.js", "/bitwarden_license/bit-web/jest.config.js", diff --git a/libs/common/src/enums/feature-flag.enum.ts b/libs/common/src/enums/feature-flag.enum.ts index e12471f50d0..55295b565bb 100644 --- a/libs/common/src/enums/feature-flag.enum.ts +++ b/libs/common/src/enums/feature-flag.enum.ts @@ -100,6 +100,7 @@ export enum FeatureFlag { /* Secrets Manager */ SecretVersioning = "sm-1587-secrets-versioning", + SmCli = "sm-2107-cli", /* PAM */ Pam = "pm-37044-pam-v-0", @@ -209,6 +210,7 @@ export const DefaultFeatureFlagValue = { /* Secrets Manager */ [FeatureFlag.SecretVersioning]: FALSE, + [FeatureFlag.SmCli]: FALSE, /* PAM */ [FeatureFlag.Pam]: FALSE, diff --git a/libs/vault/src/vault-item-dialog/vault-item-dialog.component.spec.ts b/libs/vault/src/vault-item-dialog/vault-item-dialog.component.spec.ts index 11da4f8f359..ea245496e98 100644 --- a/libs/vault/src/vault-item-dialog/vault-item-dialog.component.spec.ts +++ b/libs/vault/src/vault-item-dialog/vault-item-dialog.component.spec.ts @@ -13,7 +13,7 @@ import { ComponentFixture, TestBed } from "@angular/core/testing"; import { NoopAnimationsModule } from "@angular/platform-browser/animations"; import { Router } from "@angular/router"; import { mock, MockProxy } from "jest-mock-extended"; -import { BehaviorSubject, firstValueFrom, of } from "rxjs"; +import { BehaviorSubject, firstValueFrom, NEVER, of } from "rxjs"; import { ApiService } from "@bitwarden/common/abstractions/api.service"; import { AccountService } from "@bitwarden/common/auth/abstractions/account.service"; @@ -124,6 +124,7 @@ describe("VaultItemDialogComponent", () => { cipherServiceMock = mock({ get: jest.fn().mockReturnValue(of({ id: "new-cipher-id" } as any)), }); + cipherServiceMock.cipherView$.mockReturnValue(NEVER); cipherAuthorizationServiceMock = mock({ canEditCipher$: jest.fn().mockReturnValue(canEditCipherReturnValue$), canDeleteCipher$: jest.fn().mockReturnValue(canDeleteCipherReturnValue$), @@ -573,19 +574,42 @@ describe("VaultItemDialogComponent", () => { }); it("refreshes the cipher from local state and switches to view mode", async () => { + const storedCipher = { id: "cipher-id" } as unknown as Cipher; const refreshedCipherView = { id: "cipher-id", attachments: [] } as any; - cipherServiceMock.cipherView$.mockReturnValue(of(refreshedCipherView)); + cipherServiceMock.get.mockResolvedValue(storedCipher); + cipherServiceMock.decrypt.mockResolvedValue(refreshedCipherView); await component.cancel(); - expect(cipherServiceMock.cipherView$).toHaveBeenCalledWith("test-user-id", "cipher-id"); + expect(cipherServiceMock.get).toHaveBeenCalledWith("cipher-id", "test-user-id"); expect(component["cipher"]).toBe(refreshedCipherView); + expect(component["formConfig"].originalCipher).toBe(storedCipher); + expect((component as any).changeMode).toHaveBeenCalledWith("view"); + }); + + it("keeps an admin's original cipher from the admin API", async () => { + const adminCipher = { + id: "cipher-id", + edit: true, + viewPassword: true, + } as unknown as Cipher; + component.setTestFormConfig({ mode: "edit", admin: true, originalCipher: adminCipher }); + cipherServiceMock.get.mockResolvedValue({ + id: "cipher-id", + edit: false, + viewPassword: false, + } as unknown as Cipher); + cipherServiceMock.decrypt.mockResolvedValue({ id: "cipher-id" } as any); + + await component.cancel(); + + expect(component["formConfig"].originalCipher).toBe(adminCipher); expect((component as any).changeMode).toHaveBeenCalledWith("view"); }); it("leaves the existing cipher in place when local state has no cipher", async () => { const originalCipher = component["cipher"]; - cipherServiceMock.cipherView$.mockReturnValue(of(undefined)); + cipherServiceMock.get.mockResolvedValue(null); await component.cancel(); @@ -593,6 +617,16 @@ describe("VaultItemDialogComponent", () => { expect((component as any).changeMode).toHaveBeenCalledWith("view"); }); + it("switches to view mode after a failed save left the decrypted cache empty", async () => { + cipherServiceMock.cipherView$.mockReturnValue(NEVER); + cipherServiceMock.get.mockResolvedValue({ id: "cipher-id" } as unknown as Cipher); + cipherServiceMock.decrypt.mockResolvedValue({ id: "cipher-id" } as any); + + await component.cancel(); + + expect((component as any).changeMode).toHaveBeenCalledWith("view"); + }); + it("does not refresh and closes the dialog when formConfig mode is clone", async () => { component.setTestFormConfig({ mode: "clone" }); @@ -941,4 +975,172 @@ describe("VaultItemDialogComponent", () => { }); }); }); + + describe("syncing with local state", () => { + const storedCipher = { id: "cipher-1" } as unknown as Cipher; + const openedView = { + id: "cipher-1", + name: "opened", + collectionIds: [], + edit: true, + viewPassword: true, + revisionDate: new Date("2026-10-01T00:00:00.000Z"), + } as unknown as CipherView; + let localView$: BehaviorSubject; + + /** Flush the handler, which awaits local state and permission reads. */ + const settle = () => new Promise((resolve) => setTimeout(resolve, 0)); + + async function open(options: Partial = {}): Promise { + jest.spyOn(component as any, "getDecryptedCipherView").mockResolvedValue(openedView); + localView$ = new BehaviorSubject(openedView); + cipherServiceMock.cipherView$.mockReturnValue(localView$); + cipherServiceMock.get.mockResolvedValue(storedCipher); + component.setTestParams({ mode: "view" }); + component.setTestFormConfig({ originalCipher: storedCipher, ...options }); + + await component.ngOnInit(); + await settle(); + } + + afterEach(() => { + canEditCipherReturnValue$.next(false); + canDeleteCipherReturnValue$.next(false); + }); + + it("shows a newer revision from a background sync", async () => { + await open(); + const syncedCipher = { id: "cipher-1", name: "synced" } as unknown as Cipher; + cipherServiceMock.get.mockResolvedValue(syncedCipher); + canEditCipherReturnValue$.next(true); + canDeleteCipherReturnValue$.next(true); + const syncedView = { + ...openedView, + name: "synced", + revisionDate: new Date("2026-10-02T00:00:00.000Z"), + } as unknown as CipherView; + + localView$.next(syncedView); + await settle(); + + expect(cipherServiceMock.cipherView$).toHaveBeenCalledWith("test-user-id", "cipher-1"); + expect(component["cipher"]).toBe(syncedView); + expect(component["formConfig"].originalCipher).toBe(syncedCipher); + expect(component["canEdit"]).toBe(true); + expect(component["canDelete"]).toBe(true); + }); + + it("shows a permission change that leaves the revision date alone", async () => { + await open(); + const syncedView = { ...openedView, edit: false } as unknown as CipherView; + + localView$.next(syncedView); + await settle(); + + expect(component["cipher"]).toBe(syncedView); + }); + + it("ignores an emission with nothing new", async () => { + await open(); + + localView$.next({ ...openedView } as unknown as CipherView); + await settle(); + + expect(component["cipher"]).toBe(openedView); + }); + + it("leaves an open form alone", async () => { + await open(); + component.setTestParams({ mode: "form" }); + component["loadForm"] = true; + + localView$.next({ + ...openedView, + revisionDate: new Date("2026-10-02T00:00:00.000Z"), + } as unknown as CipherView); + await settle(); + + expect(component["cipher"]).toBe(openedView); + expect(component["formConfig"].originalCipher).toBe(storedCipher); + }); + + it("closes as Deleted when the cipher is deleted elsewhere", async () => { + await open(); + component["_cipherModified"] = true; + cipherServiceMock.get.mockResolvedValue(null); + + localView$.next(undefined); + await settle(); + + expect(close).toHaveBeenCalledWith(VaultItemDialogResult.Deleted); + expect(component["_cipherModified"]).toBe(false); + }); + + it("stays open when the cipher left the decrypted views but is still stored", async () => { + await open(); + + localView$.next(undefined); + await settle(); + + expect(close).not.toHaveBeenCalled(); + }); + + it("leaves closing to the dialog's own delete", async () => { + await open(); + cipherServiceMock.get.mockResolvedValue(null); + cipherServiceMock.softDeleteWithServer.mockImplementation(async () => { + localView$.next(undefined); + await settle(); + }); + + await component.delete(); + + expect(close).toHaveBeenCalledTimes(1); + expect(close).toHaveBeenCalledWith(VaultItemDialogResult.Deleted); + }); + + it("follows an admin console cipher that is in local state", async () => { + await open({ isAdminConsole: true }); + const syncedView = { + ...openedView, + revisionDate: new Date("2026-10-02T00:00:00.000Z"), + } as unknown as CipherView; + + localView$.next(syncedView); + await settle(); + + expect(cipherServiceMock.cipherView$).toHaveBeenCalledWith("test-user-id", "cipher-1"); + expect(component["cipher"]).toBe(syncedView); + }); + + it("does not follow an admin console cipher missing from local state", async () => { + jest.spyOn(component as any, "getDecryptedCipherView").mockResolvedValue(openedView); + cipherServiceMock.get.mockResolvedValue(null); + component.setTestParams({ mode: "view" }); + component.setTestFormConfig({ originalCipher: storedCipher, isAdminConsole: true }); + + await component.ngOnInit(); + await settle(); + + expect(cipherServiceMock.cipherView$).not.toHaveBeenCalled(); + expect(close).not.toHaveBeenCalled(); + }); + + it("does not follow a cipher loaded with admin access", async () => { + await open({ isAdminConsole: true, admin: true }); + + expect(cipherServiceMock.cipherView$).not.toHaveBeenCalled(); + }); + + it("follows a newly created cipher once it is saved", async () => { + jest.spyOn(component as any, "changeMode").mockResolvedValue(undefined); + cipherServiceMock.cipherView$.mockReturnValue(new BehaviorSubject(undefined)); + cipherServiceMock.get.mockResolvedValue(storedCipher); + (component as any)._originalFormMode = "add"; + + await component["onCipherSaved"](openedView); + + expect(cipherServiceMock.cipherView$).toHaveBeenCalledWith("test-user-id", "cipher-1"); + }); + }); }); diff --git a/libs/vault/src/vault-item-dialog/vault-item-dialog.component.ts b/libs/vault/src/vault-item-dialog/vault-item-dialog.component.ts index 3db00e218c0..1ee013f257f 100644 --- a/libs/vault/src/vault-item-dialog/vault-item-dialog.component.ts +++ b/libs/vault/src/vault-item-dialog/vault-item-dialog.component.ts @@ -14,7 +14,16 @@ import { } from "@angular/core"; import { takeUntilDestroyed, toSignal } from "@angular/core/rxjs-interop"; import { Router } from "@angular/router"; -import { firstValueFrom, Observable, Subject, switchMap } from "rxjs"; +import { + BehaviorSubject, + concatMap, + distinctUntilChanged, + EMPTY, + firstValueFrom, + Observable, + Subject, + switchMap, +} from "rxjs"; import { map } from "rxjs/operators"; import { PremiumBadgeComponent } from "@bitwarden/angular/billing/components/premium-badge"; @@ -121,7 +130,7 @@ export const VaultItemDialogResult = { Saved: "saved", /** - * A cipher was deleted. + * A cipher was deleted from this dialog, permanently deleted elsewhere, or the user lost access to it. */ Deleted: "deleted", @@ -377,6 +386,15 @@ export class VaultItemDialogComponent implements OnInit, OnDestroy { return this.revealed ? this.cipher : undefined; } + /** + * The id of the cipher kept in sync with local state. Unset until {@link followLocalState} accepts + * one. + */ + private readonly syncedCipherId$ = new BehaviorSubject(undefined); + + /** True while this dialog deletes the cipher, which closes the dialog itself. */ + private deleting = false; + /** Settles once every view `displayView$` has delivered so far is applied. */ private displayViewApplied: Promise = Promise.resolve(); @@ -420,6 +438,29 @@ export class VaultItemDialogComponent implements OnInit, OnDestroy { takeUntilDestroyed(), ) .subscribe(); + + this.syncedCipherId$ + .pipe( + distinctUntilChanged(), + switchMap((cipherId) => + cipherId == null + ? EMPTY + : this.userId$.pipe( + switchMap((userId) => + this.cipherService + .cipherView$(userId, cipherId) + .pipe(map((view) => ({ userId, cipherId, view }))), + ), + ), + ), + concatMap(({ userId, cipherId, view }) => + this.applySyncedView(userId, cipherId, view).catch((e: unknown) => + this.logService.error(e), + ), + ), + takeUntilDestroyed(), + ) + .subscribe(); } async ngOnInit() { @@ -471,6 +512,8 @@ export class VaultItemDialogComponent implements OnInit, OnDestroy { false, this.cipher.organizationId, ); + + await this.followLocalState(this.cipher); } this.showRestore = await this.canUserRestore(); @@ -554,6 +597,7 @@ export class VaultItemDialogComponent implements OnInit, OnDestroy { this.formConfig.originalCipher = cipher; this._cipherModified = true; this.params.cipherSaved?.(cipherView); + await this.followLocalState(this.cipher); // Update canEdit based on the saved cipher (important for newly created items where canEdit was never set) this.canEdit = await firstValueFrom( @@ -599,9 +643,11 @@ export class VaultItemDialogComponent implements OnInit, OnDestroy { return; } + this.deleting = true; try { await this.deleteCipher(); } catch (e) { + this.deleting = false; // Reporting Deleted would close the dialog on a delete the server refused. this.logService.error(e); this.toastService.showToast({ @@ -711,13 +757,22 @@ export class VaultItemDialogComponent implements OnInit, OnDestroy { // Refresh from local state so attachments modified during edit aren't stale in view mode. // A restricted cipher already shows the current view from displayView$. + // Reads the stored cipher rather than `cipherView$`: a failed save clears the decrypted cache, + // which then stays empty until local state changes, so waiting on it would hang. if (this.storedView == null) { const activeUserId = await firstValueFrom(this.userId$); - const latestCipher = await firstValueFrom( - this.cipherService.cipherView$(activeUserId, this.cipher.id as CipherId), - ); - if (latestCipher != null) { + const storedCipher = await this.cipherService.get(this.cipher.id, activeUserId); + const latestCipher = + storedCipher == null + ? undefined + : await this.cipherService.decrypt(storedCipher, activeUserId); + if (latestCipher != null && !latestCipher.decryptionFailure) { this.cipher = latestCipher; + // An admin's original cipher comes from the admin API, which grants permissions the + // member's local copy may lack. + if (!this.formConfig.admin) { + this.formConfig.originalCipher = storedCipher; + } } } @@ -848,6 +903,98 @@ export class VaultItemDialogComponent implements OnInit, OnDestroy { this.updateTitle(); } + /** + * Keeps `cipher` in sync with local state, so changes from a background sync show without + * reopening the dialog. Restricted ciphers follow `displayView$` instead, and admin ciphers come + * from the admin API. + */ + private async followLocalState(cipher: CipherView): Promise { + if (this.formConfig.admin || this.storedView != null) { + return; + } + // The admin console loads a cipher missing from local state (e.g. unassigned) from the admin + // API. Following it would read its absence as a delete and close the dialog. + if (this.formConfig.isAdminConsole) { + const userId = await firstValueFrom(this.userId$); + if ((await this.cipherService.get(cipher.id, userId)) == null) { + return; + } + } + this.syncedCipherId$.next(cipher.id as CipherId); + } + + /** + * Applies a view of the followed cipher from local state. Closes the dialog when the cipher is gone, + * and leaves an open form alone so a sync never discards the user's edits. + */ + private async applySyncedView( + userId: UserId, + cipherId: CipherId, + view: CipherView | undefined, + ): Promise { + if (view == null) { + // A cipher that became restricted leaves the decrypted views but stays in local state. + if (this.deleting || (await this.cipherService.get(cipherId, userId)) != null) { + return; + } + // Permanently deleted elsewhere, or the user lost access to it. + this._cipherModified = false; + await this.dialogRef.close(VaultItemDialogResult.Deleted); + return; + } + + if (this.editing || view.decryptionFailure || !this.changedSinceShown(view)) { + return; + } + + const cipher = await this.cipherService.get(cipherId, userId); + const canEdit = await firstValueFrom( + this.cipherAuthorizationService.canEditCipher$(view, this.params.isAdminConsoleAction), + ); + const canDelete = await firstValueFrom( + this.cipherAuthorizationService.canDeleteCipher$(view, this.params.isAdminConsoleAction), + ); + // The user may have opened the form while the reads were in flight. + if (this.editing) { + return; + } + + this.cipher = view; + if (cipher != null) { + this.formConfig.originalCipher = cipher; + } + this.collections = this.formConfig.collections.filter((c) => + view.collectionIds?.includes(c.id), + ); + this.organization = this.formConfig.organizations.find((o) => o.id === view.organizationId); + this.canEdit = canEdit; + this.canDelete = canDelete; + this.showRestore = await this.canUserRestore(); + this.updateTitle(); + } + + /** True while the form is open or loading, which holds edits a refresh would discard. */ + private get editing(): boolean { + return this.params.mode !== "view" || this.loadForm; + } + + /** + * True when `view` differs from the shown cipher. A permission change from a collection access + * update leaves the revision date alone, so the permissions are compared too. + */ + private changedSinceShown(view: CipherView): boolean { + if (this.cipher == null) { + return false; + } + return ( + view.revisionDate?.getTime() > this.cipher.revisionDate?.getTime() || + view.edit !== this.cipher.edit || + view.viewPassword !== this.cipher.viewPassword || + view.permissions?.delete !== this.cipher.permissions?.delete || + view.permissions?.restore !== this.cipher.permissions?.restore + ); + } + private async getDecryptedCipherView(config: CipherFormConfig) { if (config.originalCipher == null) { return; diff --git a/package-lock.json b/package-lock.json index fbe984744a2..35df9d58b96 100644 --- a/package-lock.json +++ b/package-lock.json @@ -42,7 +42,7 @@ "chart.js": "4.6.1", "chartjs-adapter-date-fns": "3.0.0", "commander": "14.0.0", - "core-js": "3.50.0", + "core-js": "3.51.0", "form-data": "4.0.6", "https-proxy-agent": "9.1.0", "inquirer": "8.2.6", @@ -213,7 +213,7 @@ "browser-hrtime": "1.1.8", "chalk": "4.1.2", "commander": "14.0.0", - "core-js": "3.50.0", + "core-js": "3.51.0", "form-data": "4.0.6", "https-proxy-agent": "9.1.0", "inquirer": "8.2.6", @@ -22615,9 +22615,9 @@ } }, "node_modules/core-js": { - "version": "3.50.0", - "resolved": "https://registry.npmjs.org/core-js/-/core-js-3.50.0.tgz", - "integrity": "sha512-BRWgOLKkFeCgRudR6zrs8p9XJZcE14grzKMMssoYrk6krtuEZ7MTKPIY5RzOnqsEKIR9kst7wNzphttraT+Yqw==", + "version": "3.51.0", + "resolved": "https://registry.npmjs.org/core-js/-/core-js-3.51.0.tgz", + "integrity": "sha512-7bDKx/5jm5MxzsXxc93g6Z2+4ZsuT/MddrfRmTDJNAkWsYWHU8EVNEsBiIEWnMAMCHMmRfUEjkuo3jeNBOIHRw==", "hasInstallScript": true, "license": "MIT", "engines": { diff --git a/package.json b/package.json index 0fafb0aa494..dfe1683d423 100644 --- a/package.json +++ b/package.json @@ -204,7 +204,7 @@ "chart.js": "4.6.1", "chartjs-adapter-date-fns": "3.0.0", "commander": "14.0.0", - "core-js": "3.50.0", + "core-js": "3.51.0", "form-data": "4.0.6", "https-proxy-agent": "9.1.0", "inquirer": "8.2.6", diff --git a/tsconfig.base.json b/tsconfig.base.json index 3c501c43195..e8ffff407d8 100644 --- a/tsconfig.base.json +++ b/tsconfig.base.json @@ -32,6 +32,7 @@ "@bitwarden/bit-common/*": ["./bitwarden_license/bit-common/src/*"], "@bitwarden/bit-pam": ["./bitwarden_license/bit-pam/src"], "@bitwarden/bit-pam-components": ["./bitwarden_license/bit-pam-components/src"], + "@bitwarden/bit-sm": ["./bitwarden_license/bit-sm/src"], "@bitwarden/browser/*": ["./apps/browser/src/*"], "@bitwarden/cli/*": ["./apps/cli/src/*"], "@bitwarden/client-type": ["./libs/client-type/src/index.ts"], diff --git a/tsconfig.json b/tsconfig.json index 6733f54f8b4..0ea406b8c65 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -13,6 +13,7 @@ "bitwarden_license/bit-common/src/**/*", "bitwarden_license/bit-pam/src/**/*", "bitwarden_license/bit-pam-components/src/**/*", + "bitwarden_license/bit-sm/src/**/*", "bitwarden_license/bit-browser/src/**/*" ], "exclude": [