Files
HiveGrid-Wireframes/03 Quellen und Referenzen/hivegrid-cloud/packages/cli/src/commands/plugins/index.test.ts
T
2026-07-08 16:15:37 +02:00

319 lines
11 KiB
TypeScript

import { beforeEach, describe, expect, test, vi } from "vitest";
type PluginCliMocks = {
db: {
plugin: {
findUnique: ReturnType<typeof vi.fn>;
update: ReturnType<typeof vi.fn>;
delete: ReturnType<typeof vi.fn>;
};
tenantPluginCapabilityGrant: {
findMany: ReturnType<typeof vi.fn>;
};
$transaction: ReturnType<typeof vi.fn>;
};
publishAuditEventViaOutbox: ReturnType<typeof vi.fn>;
};
const originalNodeEnv = process.env.NODE_ENV;
function getPluginCliMocks(): PluginCliMocks {
const global = globalThis as typeof globalThis & { __pluginCliMocks__?: PluginCliMocks };
global.__pluginCliMocks__ ??= {
db: {
plugin: {
findUnique: vi.fn(),
update: vi.fn(),
delete: vi.fn(),
},
tenantPluginCapabilityGrant: {
findMany: vi.fn(),
},
$transaction: vi.fn(async (fn: (tx: PluginCliMocks["db"]) => Promise<unknown>) => await fn(getPluginCliMocks().db)),
},
publishAuditEventViaOutbox: vi.fn(),
};
return global.__pluginCliMocks__;
}
vi.mock("@hivegrid/db/client.server", () => ({
getDbClient: () => getPluginCliMocks().db,
}));
vi.mock("@hivegrid/db/audit-events.server", () => ({
publishAuditEventViaOutbox: getPluginCliMocks().publishAuditEventViaOutbox,
}));
vi.mock("consola", () => ({
default: {
error: vi.fn(),
info: vi.fn(),
prompt: vi.fn(),
success: vi.fn(),
},
}));
import consola from "consola";
import { stampPluginCapabilityUseChain, verifyPluginCapabilityUseChain, type PluginCapabilityUseChainRow } from "@hivegrid/plugin-runtime";
import { pluginsCommand } from "./index.js";
import { pluginsEnableCommand } from "./toggle.js";
import { pluginsUninstallCommand } from "./uninstall.js";
import { runPluginsVerifyAuditChain, type PluginCapabilityUseChainStoredRow } from "./verify-audit-chain.js";
const mocks = getPluginCliMocks();
const consoleMock = vi.mocked(consola);
describe("plugins CLI", () => {
beforeEach(() => {
vi.clearAllMocks();
process.exitCode = undefined;
process.env.NODE_ENV = originalNodeEnv;
delete process.env.PLUGIN_REQUIRE_CAPABILITY_CONSENT;
delete process.env.PLUGIN_RUNTIME_PRODUCTION_ENABLED;
mocks.db.$transaction.mockImplementation(async (fn: (tx: PluginCliMocks["db"]) => Promise<unknown>) => await fn(mocks.db));
});
test("exposes operator + author subcommands", async () => {
const subs = pluginsCommand.subCommands as Record<string, { meta: { name: string } | (() => { name: string }) } | undefined>;
const keys = Object.keys(subs);
expect(keys).toContain("list");
expect(keys).toContain("enable");
expect(keys).toContain("disable");
expect(keys).toContain("uninstall");
expect(keys).toContain("verify-audit-chain");
expect(keys).toContain("scaffold");
});
test("plugins verify-audit-chain verifies the full tenant capability-use chain", async () => {
const rows = stampedPluginCapabilityRows([
pluginCapabilityRow({ id: "row_1", pluginId: "com.acme.crm" }),
pluginCapabilityRow({ id: "row_2", pluginId: "com.acme.slack" }),
]);
const output = outputCollector();
await expect(
runPluginsVerifyAuditChain(
{ tenantId: "tenant_1", pluginId: "com.acme.crm" },
{
readRows: async function* () {
yield* rows;
},
verify: verifyPluginCapabilityUseChain,
output,
}
)
).resolves.toEqual({
exitCode: 0,
matchingPluginRows: 1,
ok: true,
rowCount: 2,
});
expect(output.info).toHaveBeenCalledWith(expect.stringContaining("matchingPluginRows=1"));
});
test("plugins verify-audit-chain reports the first tampered capability-use row", async () => {
const rows = stampedPluginCapabilityRows([
pluginCapabilityRow({ id: "row_1" }),
pluginCapabilityRow({ id: "row_2" }),
]);
const tampered = rows.map((row) => (row.id === "row_2" ? { ...row, outcome: "denied" } : row));
const output = outputCollector();
await expect(
runPluginsVerifyAuditChain(
{ tenantId: "tenant_1" },
{
readRows: async function* () {
yield* tampered;
},
verify: verifyPluginCapabilityUseChain,
output,
}
)
).resolves.toMatchObject({
exitCode: 1,
ok: false,
rowCount: 2,
});
expect(output.error).toHaveBeenCalledWith(expect.stringContaining("firstBreakId=row_2"));
});
test("plugins enable requires tenantId + pluginId", async () => {
const sub = (pluginsCommand.subCommands as Record<string, { args: Record<string, { required?: boolean }> }>).enable;
expect(sub.args.tenantId.required).toBe(true);
expect(sub.args.pluginId.required).toBe(true);
});
test("plugins enable refuses missing capability grants before toggling", async () => {
mocks.db.plugin.findUnique.mockResolvedValueOnce({
id: "row_1",
tenantId: "tenant_1",
pluginId: "com.acme.crm",
version: "1.0.0",
enabled: false,
manifest: {
capabilities: [{ name: "log" }],
},
});
mocks.db.tenantPluginCapabilityGrant.findMany.mockResolvedValueOnce([]);
await pluginsEnableCommand.run?.({ args: { tenantId: "tenant_1", pluginId: "com.acme.crm" } } as never);
expect(process.exitCode).toBe(1);
expect(consoleMock.error).toHaveBeenCalledWith(expect.stringContaining("missing operator consent"));
expect(mocks.db.plugin.update).not.toHaveBeenCalled();
expect(mocks.publishAuditEventViaOutbox).not.toHaveBeenCalled();
});
test("plugins enable toggles through lifecycle and writes an audit outbox event", async () => {
mocks.db.plugin.findUnique.mockResolvedValueOnce({
id: "row_1",
tenantId: "tenant_1",
pluginId: "com.acme.crm",
version: "1.0.0",
enabled: false,
manifest: {
capabilities: [{ name: "log" }],
},
});
mocks.db.tenantPluginCapabilityGrant.findMany.mockResolvedValueOnce([
{ capabilityName: "log", scopeJson: null },
]);
mocks.db.plugin.update.mockResolvedValueOnce({
id: "row_1",
tenantId: "tenant_1",
pluginId: "com.acme.crm",
version: "1.0.0",
enabled: true,
manifest: { capabilities: [] },
});
await pluginsEnableCommand.run?.({ args: { tenantId: "tenant_1", pluginId: "com.acme.crm" } } as never);
expect(mocks.db.plugin.update).toHaveBeenCalledWith({
where: { id: "row_1" },
data: { enabled: true },
});
expect(mocks.publishAuditEventViaOutbox).toHaveBeenCalledWith(
mocks.db,
expect.objectContaining({
tenantId: "tenant_1",
action: "plugin.enabled",
sourceModule: "cli.plugins",
metadata: { pluginId: "com.acme.crm", version: "1.0.0" },
})
);
expect(consoleMock.success).toHaveBeenCalledWith("Plugin com.acme.crm for tenant tenant_1 is now ENABLED.");
});
test("plugins enable rejects disabled consent guard in production before DB writes", async () => {
process.env.NODE_ENV = "production";
process.env.PLUGIN_REQUIRE_CAPABILITY_CONSENT = "false";
await pluginsEnableCommand.run?.({ args: { tenantId: "tenant_1", pluginId: "com.acme.crm" } } as never);
expect(process.exitCode).toBe(1);
expect(consoleMock.error).toHaveBeenCalledWith("PLUGIN_REQUIRE_CAPABILITY_CONSENT=false is not allowed in production.");
expect(mocks.db.plugin.findUnique).not.toHaveBeenCalled();
expect(mocks.db.plugin.update).not.toHaveBeenCalled();
expect(mocks.publishAuditEventViaOutbox).not.toHaveBeenCalled();
});
test("plugins enable requires the production runtime gate before DB reads in production", async () => {
process.env.NODE_ENV = "production";
await pluginsEnableCommand.run?.({ args: { tenantId: "tenant_1", pluginId: "com.acme.crm" } } as never);
expect(process.exitCode).toBe(1);
expect(consoleMock.error).toHaveBeenCalledWith(expect.stringContaining("PLUGIN_RUNTIME_PRODUCTION_ENABLED=true"));
expect(mocks.db.plugin.findUnique).not.toHaveBeenCalled();
expect(mocks.db.plugin.update).not.toHaveBeenCalled();
expect(mocks.publishAuditEventViaOutbox).not.toHaveBeenCalled();
});
test("plugins enable rejects unavailable production capability host bindings before toggling", async () => {
process.env.NODE_ENV = "production";
process.env.PLUGIN_RUNTIME_PRODUCTION_ENABLED = "true";
mocks.db.plugin.findUnique.mockResolvedValueOnce({
id: "row_1",
tenantId: "tenant_1",
pluginId: "com.acme.crm",
version: "1.0.0",
enabled: false,
manifest: {
capabilities: [{ name: "http.outbound" }],
},
});
await pluginsEnableCommand.run?.({ args: { tenantId: "tenant_1", pluginId: "com.acme.crm" } } as never);
expect(process.exitCode).toBe(1);
expect(consoleMock.error).toHaveBeenCalledWith(expect.stringContaining("do not have reviewed production host bindings"));
expect(mocks.db.tenantPluginCapabilityGrant.findMany).not.toHaveBeenCalled();
expect(mocks.db.plugin.update).not.toHaveBeenCalled();
expect(mocks.publishAuditEventViaOutbox).not.toHaveBeenCalled();
});
test("plugins uninstall deletes through lifecycle and audits in the transaction", async () => {
consoleMock.prompt.mockResolvedValueOnce(true);
mocks.db.plugin.findUnique.mockResolvedValueOnce({
id: "row_1",
tenantId: "tenant_1",
pluginId: "com.acme.crm",
version: "1.0.0",
enabled: true,
manifest: { capabilities: [] },
});
mocks.db.plugin.delete.mockResolvedValueOnce({
id: "row_1",
tenantId: "tenant_1",
pluginId: "com.acme.crm",
version: "1.0.0",
enabled: true,
manifest: { capabilities: [] },
});
await pluginsUninstallCommand.run?.({ args: { tenantId: "tenant_1", pluginId: "com.acme.crm" } } as never);
expect(mocks.db.plugin.delete).toHaveBeenCalledWith({ where: { id: "row_1" } });
expect(mocks.publishAuditEventViaOutbox).toHaveBeenCalledWith(
mocks.db,
expect.objectContaining({
tenantId: "tenant_1",
action: "plugin.uninstalled",
sourceModule: "cli.plugins",
metadata: { pluginId: "com.acme.crm", version: "1.0.0" },
})
);
expect(consoleMock.success).toHaveBeenCalledWith("Plugin com.acme.crm uninstalled from tenant tenant_1.");
});
});
function pluginCapabilityRow(overrides: Partial<PluginCapabilityUseChainRow> = {}): PluginCapabilityUseChainRow {
return {
id: "row_1",
pluginInvocationId: "inv_1",
tenantId: "tenant_1",
pluginId: "com.acme.crm",
capability: "log",
payloadHash: null,
outcome: "success",
errorCode: null,
durationMs: 5,
timestamp: "2026-05-29T04:00:00.000Z",
...overrides,
};
}
function stampedPluginCapabilityRows(rows: ReadonlyArray<PluginCapabilityUseChainRow>): PluginCapabilityUseChainStoredRow[] {
return [...stampPluginCapabilityUseChain({ seedPrevHash: null, rows }).stamped];
}
function outputCollector() {
return {
error: vi.fn(),
info: vi.fn(),
json: vi.fn(),
};
}