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

This commit is contained in:
Max Power
2026-11-11 18:40:30 +01:00
parent 4d3d2fc338
commit 7e142e1e9b
16 changed files with 2073 additions and 5 deletions

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

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

@@ -14,12 +14,16 @@ import { SmAccessPermissions, SmAccessTargets } from "./access/sm-access-policie
import { AccessTokenCreateCommand } from "./access-tokens/access-token-create.command";
import { AccessTokenListCommand } from "./access-tokens/access-token-list.command";
import { AccessTokenRevokeCommand } from "./access-tokens/access-token-revoke.command";
import { CountsCommand } from "./counts/counts.command";
import { EventsCommand } from "./events/events.command";
import { GranteesListCommand, SmGranteeKinds } from "./grantees/grantees-list.command";
import { MachineAccountCreateCommand } from "./machine-accounts/machine-account-create.command";
import { MachineAccountDeleteCommand } from "./machine-accounts/machine-account-delete.command";
import { MachineAccountEditCommand } from "./machine-accounts/machine-account-edit.command";
import { MachineAccountGetCommand } from "./machine-accounts/machine-account-get.command";
import { MachineAccountListCommand } from "./machine-accounts/machine-account-list.command";
import { SmExportCommand } from "./porting/sm-export.command";
import { SmImportCommand } from "./porting/sm-import.command";
import { ProjectCreateCommand } from "./projects/project-create.command";
import { ProjectDeleteCommand } from "./projects/project-delete.command";
import { ProjectEditCommand } from "./projects/project-edit.command";
@@ -80,6 +84,10 @@ export class SmProgram extends BaseProgram {
.addCommand(this.trashCommand())
.addCommand(this.accessCommand())
.addCommand(this.granteesCommand())
.addCommand(this.countsCommand())
.addCommand(this.eventsCommand())
.addCommand(this.exportCommand())
.addCommand(this.importCommand())
.addCommand(this.templateCommand())
.on("--help", () => {
writeLn("\n Examples:");
@@ -602,6 +610,12 @@ export class SmProgram extends BaseProgram {
writeLn(" --expires accepts an ISO 8601 date, or never (also none) for a token");
writeLn(" that does not expire. Omitting --expires is the same as never.");
writeLn("");
writeLn(" With `bw serve`, `expires` is required in the JSON body of");
writeLn(
" POST /sm/<organizationid>/machine-accounts/<machineaccountid>/access-tokens.",
);
writeLn(" Send `never` for an access token that does not expire.");
writeLn("");
writeLn(" Examples:");
writeLn("");
writeLn(
@@ -946,6 +960,148 @@ export class SmProgram extends BaseProgram {
);
}
private countsCommand(): Command {
return new Command("counts")
.description(
"Show Secrets Manager object counts for an organization, project, or machine account.",
)
.requiredOption(ORGANIZATION_ID_OPTION, ORGANIZATION_ID_DESCRIPTION)
.option("--projectid <projectid>", "Show counts for this project")
.option("--machineaccountid <machineaccountid>", "Show counts for this machine account")
.on("--help", () => {
writeLn("\n Examples:");
writeLn("");
writeLn(" bw sm counts --organizationid <organizationid>");
writeLn(" bw sm counts --organizationid <organizationid> --projectid <projectid>");
writeLn(
" bw sm counts --organizationid <organizationid> --machineaccountid <machineaccountid>",
);
writeLn("", true);
})
.action(async (options: OrgOptions & { projectid?: string; machineaccountid?: string }) => {
await this.exitIfLocked();
const response = await withSmOrganization(
this.serviceContainer,
options.organizationid,
(org) =>
CountsCommand.create(this.serviceContainer).run(org, {
projectId: options.projectid,
machineAccountId: options.machineaccountid,
}),
);
this.processResponse(response);
});
}
private eventsCommand(): Command {
return new Command("events")
.description("List the event logs for a machine account.")
.requiredOption(ORGANIZATION_ID_OPTION, ORGANIZATION_ID_DESCRIPTION)
.requiredOption("--machineaccountid <machineaccountid>", "The machine account id (required)")
.requiredOption("--start <start>", "Start of the date range, e.g. 2026-01-01 (required)")
.requiredOption("--end <end>", "End of the date range, e.g. 2026-01-31T23:59:59Z (required)")
.on("--help", () => {
writeLn("\n Examples:");
writeLn("");
writeLn(
" bw sm events --organizationid <organizationid> --machineaccountid <machineaccountid> --start 2026-01-01 --end 2026-02-01",
);
writeLn("", true);
})
.action(
async (options: OrgOptions & { machineaccountid: string; start: string; end: string }) => {
await this.exitIfLocked();
const response = await withSmOrganization(
this.serviceContainer,
options.organizationid,
(org) =>
EventsCommand.create(this.serviceContainer).run(org, {
machineAccountId: options.machineaccountid,
start: options.start,
end: options.end,
}),
);
this.processResponse(response);
},
);
}
private exportCommand(): Command {
return new Command("export")
.description("Export an organization's Secrets Manager projects and secrets.")
.requiredOption(ORGANIZATION_ID_OPTION, ORGANIZATION_ID_DESCRIPTION)
.option("--output <output>", "Output directory or filename. Writes to stdout when omitted.")
.option("--passwordenv <passwordenv>", "Environment variable storing your master password")
.option(
"--passwordfile <passwordfile>",
"Path to a file containing your master password as its first line",
)
.on("--help", () => {
writeLn("\n Notes:");
writeLn("");
writeLn(" Only organization owners and admins can export. The export contains");
writeLn(" decrypted secret values; store it securely.");
writeLn("");
writeLn(" Exporting requires your master password. You are prompted for it unless");
writeLn(" --passwordfile or --passwordenv is given. With --nointeraction, one of");
writeLn(" these options is required.");
writeLn("");
writeLn(" With `bw serve`, send the master password as `password` in the JSON body");
writeLn(" of POST /sm/<organizationid>/export.");
writeLn("");
writeLn(" Examples:");
writeLn("");
writeLn(" bw sm export --organizationid <organizationid>");
writeLn(" bw sm export --organizationid <organizationid> --output ./sm-export.json");
writeLn(" bw sm export --organizationid <organizationid> --passwordfile ~/.bw-password");
writeLn("", true);
})
.action(
async (
options: OrgOptions & { output?: string; passwordenv?: string; passwordfile?: string },
) => {
await this.exitIfLocked();
const response = await withSmOrganization(
this.serviceContainer,
options.organizationid,
(org) =>
SmExportCommand.create(this.serviceContainer).run(org, {
output: options.output,
passwordEnv: options.passwordenv,
passwordFile: options.passwordfile,
}),
);
this.processResponse(response);
},
);
}
private importCommand(): Command {
return new Command("import")
.description("Import Secrets Manager projects and secrets into an organization.")
.argument("<file>", "A file from `bw sm export` or the web vault's Secrets Manager export")
.requiredOption(ORGANIZATION_ID_OPTION, ORGANIZATION_ID_DESCRIPTION)
.on("--help", () => {
writeLn("\n Notes:");
writeLn("");
writeLn(" Only organization owners and admins can import.");
writeLn("");
writeLn(" Examples:");
writeLn("");
writeLn(" bw sm import ./sm-export.json --organizationid <organizationid>");
writeLn("", true);
})
.action(async (file: string, options: OrgOptions) => {
await this.exitIfLocked();
const response = await withSmOrganization(
this.serviceContainer,
options.organizationid,
(org) => SmImportCommand.create(this.serviceContainer).run(org, { file }),
);
this.processResponse(response);
});
}
private templateCommand(): Command {
return new Command("template")
.description("Get a JSON template for creating or editing a Secrets Manager object.")

View File

@@ -15,10 +15,14 @@ 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 const smOrg: SmOrganization = {
organizationId: smOrgId,
organization: { id: smOrgId, canAccessSecretsManager: true } as Organization,
};
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>) {

View File

@@ -23,6 +23,10 @@ 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";