[SM-2108] Land the Secrets Manager CLI stack in main (#24684)

* [SM-2108] Move Secrets Manager services and models to bit-sm (#23925)

* [SM-2109] Return results from Secrets Manager service create, update and restore calls (#23926)

* [SM-2110] Add the feature-flagged bw sm command foundation (#23927)

* [SM-2112] Add bw sm secret and bw sm template commands (#23929)

* [SM-2113] Add bw sm trash commands (#23930)

* [SM-2114] Add bw sm machine-account and access token commands (#23931)

* [SM-2115] Add bw sm access and bw sm grantees commands (#23932)

* [SM-2116] Add Secrets Manager counts, events, import/export and bw serve endpoints (#23933)

---------

Co-authored-by: cd-bitwarden <106776772+cd-bitwarden@users.noreply.github.com>
This commit is contained in:
Max
2026-11-13 17:47:07 +01:00
committed by GitHub
parent ebe2148cfa
commit 95f5897428
232 changed files with 9852 additions and 250 deletions

1
.github/CODEOWNERS vendored
View File

@@ -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

View File

@@ -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<ConfigService>();
const organizationService = mock<OrganizationService>();
const accountService = mock<AccountService>();
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<string, string>,
request: { body?: unknown; query?: Record<string, string> } = {},
) => {
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<ServiceContainer>({ 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<boolean> }, "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();
});
});

View File

@@ -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<Response>;
type SmOrgRouteHandler = (ctx: RouterContext, org: SmOrganization) => Promise<Response>;
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<unknown>) => {
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<string, unknown> {
const body: unknown = ctx.request.body;
return body != null && typeof body === "object" ? (body as Record<string, unknown>) : {};
}
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",
};
}

View File

@@ -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();
}

View File

@@ -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<KeyService>();
const apiService = mock<ApiService>();
const keyGenerationService = mock<KeyGenerationService>();
const encryptService = mock<EncryptService>();
const logService = mock<LogService>();
const serviceAccountService = mock<ServiceAccountService>();
const accountService = mock<AccountService>();
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<OrganizationId, OrgKey>),
);
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.<id>.<clientSecret>:<key>` 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.",
);
});
});

View File

@@ -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<Response> {
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 `<version>.<id>.<clientSecret>:<encryptionKey>`.
*/
private static getAccessTokenId(accessToken: string): string {
return accessToken.split(":")[0].split(".")[1];
}
static create(serviceContainer: ServiceContainer) {
return new AccessTokenCreateCommand(
serviceContainer.accessService,
serviceContainer.serviceAccountService,
);
}
}

View File

@@ -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<AccessService>();
const serviceAccountService = mock<ServiceAccountService>();
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();
});
});

View File

@@ -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<Response> {
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,
);
}
}

View File

@@ -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<AccessService>();
const serviceAccountService = mock<ServiceAccountService>();
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();
});
});

View File

@@ -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<Response> {
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,
);
}
}

View File

@@ -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 };
}

View File

@@ -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<typeof createSmAccessFixture>;
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"]]);
});
});

View File

@@ -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<Response> {
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));
}
}

View File

@@ -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<typeof createSmAccessFixture>;
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();
});
});
});

View File

@@ -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<Response> {
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));
}
}

View File

@@ -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<typeof createSmAccessFixture>;
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();
});
});

View File

@@ -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<Response> {
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));
}
}

View File

@@ -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<typeof createSmAccessFixture>;
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();
});
});

View File

@@ -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<Response> {
const parsedTarget = parseSmAccessTarget(target);
if (parsedTarget.error) {
return parsedTarget.error;
}
const parsed = await parseSmRequest<SmAccessSetRequest>(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<string, unknown>;
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));
}
}

View File

@@ -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.",
);
});
});
});

View File

@@ -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<SmAccessTarget, string> = {
project: "project",
"machine-account": "machine account",
secret: "secret",
};
const GranteeTypes: Record<SmAccessTarget, SmGranteeType[]> = {
project: ["user", "group", "machineAccount"],
"machine-account": ["user", "group", "project"],
secret: ["user", "group", "machineAccount"],
};
const GranteeTypeLabels: Record<SmGranteeType, string> = {
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<SmAccessPolicy[]> {
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<Response | void> {
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,
);
}
}

View File

@@ -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<CountService>();
const projectService = mock<ProjectService>();
const serviceAccountService = mock<ServiceAccountService>();
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.",
);
});
});

View File

@@ -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<Response> {
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,
);
}
}

View File

@@ -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<ServiceAccountEventLogApiService>();
const serviceAccountService = mock<ServiceAccountService>();
const machineAccountId = "22222222-2222-2222-2222-222222222222";
const secretId = "33333333-3333-3333-3333-333333333333";
let command: EventsCommand;
const options = (overrides: Record<string, string> = {}) => ({
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.",
);
});
});

View File

@@ -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<Response> {
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,
);
}
}

View File

@@ -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<AccessPolicyService>();
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.",
);
});
});

View File

@@ -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<Response> {
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);
}
}

View File

@@ -0,0 +1 @@
export * from "./sm.program";

View File

@@ -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<ServiceAccountService>();
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();
});
});

View File

@@ -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<Response> {
const parsed = await parseSmRequest<Record<string, unknown>>(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);
}
}

View File

@@ -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<ServiceAccountService>();
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();
});
});

View File

@@ -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<Response> {
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);
}
}

View File

@@ -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<ServiceAccountService>();
const machineAccountId = "22222222-2222-2222-2222-222222222222";
let command: MachineAccountEditCommand;
const makeMachineAccount = (overrides: Partial<ServiceAccountView> = {}) =>
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();
});
});

View File

@@ -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<Response> {
const machineAccount = parseSmId(machineAccountId, "machineAccountId");
if (machineAccount.error) {
return machineAccount.error;
}
const parsed = await parseSmRequest<Record<string, unknown>>(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);
}
}

View File

@@ -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<ServiceAccountService>();
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.",
);
});
});

View File

@@ -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<Response> {
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);
}
}

View File

@@ -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<ServiceAccountService>();
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.",
);
});
});

View File

@@ -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<Response> {
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);
}
}

View File

@@ -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);
}
}

View File

@@ -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;
}
}

View File

@@ -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;
}
}
}

View File

@@ -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<Partial<SmCountsResponse>, "object" | "scope" | "id">,
) {
this.scope = scope;
this.id = id;
Object.assign(this, counts);
}
}

View File

@@ -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;
}
}

View File

@@ -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;
}
}

View File

@@ -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;
}
}

View File

@@ -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;
}
}

View File

@@ -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;
}
}

View File

@@ -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;
}
}

View File

@@ -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;
}
}

View File

@@ -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<AccountService>();
const portingApiService = mock<SecretsManagerPortingApiService>();
const userVerificationService = mock<UserVerificationService>();
const userDecryptionOptionsService = mock<UserDecryptionOptionsServiceAbstraction>();
const logService = mock<LogService>();
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();
});
});
});

View File

@@ -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<Response> {
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<Response | undefined> {
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";
}

View File

@@ -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<SecretsManagerPortingApiService>();
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.");
});
});

View File

@@ -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<Response> {
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<string, unknown>;
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<string, unknown>).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<string, unknown>)[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);
}

View File

@@ -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<ProjectService>();
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.",
);
});
});

View File

@@ -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<Response> {
const parsed = await parseSmRequest<Record<string, unknown>>(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);
}
}

View File

@@ -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<ProjectService>();
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.");
});
});

View File

@@ -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<Response> {
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);
}
}

View File

@@ -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<ProjectService>();
const projectId = "22222222-2222-2222-2222-222222222222";
let command: ProjectEditCommand;
const makeProject = (overrides: Partial<ProjectView> = {}) =>
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.");
});
});

View File

@@ -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<Response> {
const project = parseSmId(projectId, "projectId");
if (project.error) {
return project.error;
}
const parsed = await parseSmRequest<Record<string, unknown>>(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);
}
}

View File

@@ -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<ProjectService>();
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.");
});
});

View File

@@ -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<Response> {
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);
}
}

View File

@@ -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<ProjectService>();
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.",
);
});
});

View File

@@ -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<Response> {
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);
}
}

View File

@@ -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<SecretService>();
const projectService = mock<ProjectService>();
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.");
});
});

View File

@@ -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<Response> {
const parsed = await parseSmRequest<Record<string, unknown>>(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);
}
}

View File

@@ -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<SecretService>();
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();
});
});

View File

@@ -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<Response> {
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);
}
}

View File

@@ -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<SecretService>();
const projectService = mock<ProjectService>();
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<SecretView> = {}) =>
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();
});
});

View File

@@ -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<Response> {
const secret = parseSmId(secretId, "secretId");
if (secret.error) {
return secret.error;
}
const parsed = await parseSmRequest<Record<string, unknown>>(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);
}
}

View File

@@ -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<SecretService>();
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.");
});
});

View File

@@ -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<Response> {
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);
}
}

View File

@@ -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<SecretService>();
const projectService = mock<ProjectService>();
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.");
});
});

View File

@@ -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<Response> {
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);
}
}

View File

@@ -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<SecretService>();
const secretId = "22222222-2222-2222-2222-222222222222";
const versionId = "33333333-3333-3333-3333-333333333333";
let command: SecretRestoreVersionCommand;
const makeSecret = (overrides: Partial<SecretView> = {}) =>
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.",
);
});
});

View File

@@ -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<Response> {
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);
}
}

View File

@@ -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<SecretService>();
const secretVersionService = mock<SecretVersionService>();
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.");
});
});

View File

@@ -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<Response> {
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,
);
}
}

View File

@@ -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<void> {
const known = new Map<string, string>();
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 }),
);
}

View File

@@ -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<string, unknown>,
): { 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 };
}

View File

@@ -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<AccountService>();
const organizationService = mock<OrganizationService>();
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.");
});
});
});

View File

@@ -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<T extends object>(
requestJson: unknown,
): Promise<{ request: Partial<T>; 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<T> };
}
/**
* 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<string, unknown>,
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<string, unknown>): { 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<SmOrganizationResult> {
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<Response>,
): Promise<Response> {
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);
}

View File

@@ -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<ConfigService>();
const projectService = mock<ProjectService>();
const organizationService = mock<OrganizationService>();
const accountService = mock<AccountService>();
const probe = jest.fn();
let exitSpy: jest.SpyInstance;
beforeAll(() => {
new SmProgram(
mock<ServiceContainer>({
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();
});
});
});

File diff suppressed because it is too large Load Diff

View File

@@ -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<AccessPolicyService>();
const projectService = mock<ProjectService>();
const serviceAccountService = mock<ServiceAccountService>();
const secretService = mock<SecretService>();
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 };
}

View File

@@ -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<Organization> = {}): 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>) {
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<AccountService>,
organizationService: MockProxy<OrganizationService>,
canAccessSecretsManager = true,
organization: Partial<Organization> = {},
) {
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");
}

View File

@@ -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>();
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.",
);
});
});

View File

@@ -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<Response> {
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();
}
}

View File

@@ -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<SecretService>();
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.",
);
});
});

View File

@@ -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<Response> {
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);
}
}

View File

@@ -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<SecretService>();
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.",
);
});
});

View File

@@ -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<Response> {
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);
}
}

View File

@@ -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<SecretService>();
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.",
);
});
});

View File

@@ -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<Response> {
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);
}
}

View File

@@ -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);
}),
),
);
}

View File

@@ -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,
);
}
}

View File

@@ -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`

View File

@@ -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: ["<rootDir>/test.setup.ts"],
moduleNameMapper: pathsToModuleNameMapper(
// lets us use @bitwarden/common/spec in tests
{ "@bitwarden/common/spec": ["libs/common/spec"], ...(compilerOptions?.paths ?? {}) },
{
prefix: "<rootDir>/../../",
},
),
};

View File

@@ -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"
}
}

View File

@@ -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"
}
}
}
}

View File

@@ -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";

Some files were not shown because too many files have changed in this diff Show More