Files
seal-use/src/cli/read-only.test.ts
T

212 lines
9.2 KiB
TypeScript

import { describe, expect, test } from "bun:test";
import { readFileSync, readdirSync } from "node:fs";
import { join } from "node:path";
import { HELP_REGISTRY } from "./help.js";
import { KNOWN_AREAS } from "./runner.js";
import { SEAL_MUTATING_CAPABILITIES, SEAL_READ_ONLY_CAPABILITIES, sealCapabilities } from "../domains/seal/capabilities.js";
import { isReadOnlyCliCommand, listReadOnlyCommands } from "./read-only.js";
describe("CLI read-only classification", () => {
test("the tool registry is classified exhaustively and without overlap", () => {
const all = sealCapabilities.map((tool) => tool.name);
const classified = [...SEAL_READ_ONLY_CAPABILITIES, ...SEAL_MUTATING_CAPABILITIES];
// A newly added tool must fail here rather than silently defaulting into either bucket.
expect(classified.slice().sort()).toEqual(all.slice().sort());
for (const name of SEAL_READ_ONLY_CAPABILITIES) {
expect({ name, alsoMutating: SEAL_MUTATING_CAPABILITIES.has(name) }).toEqual({ name, alsoMutating: false });
}
});
// Actions the dispatcher accepts that carry no help-registry row, so they are documented
// nowhere else. Kept explicit: anything not a registry entry and not listed here fails below.
const ACTIONS_WITHOUT_REGISTRY_ENTRY = new Set([
"approval-runs search",
"auth diagnose",
"auth status",
"auth test",
"auth doctor",
"auth seal-link list",
"doctor auth",
"expenses "
]);
test("every allow-listed command exists in the help registry", () => {
const byArea = new Map(
HELP_REGISTRY.map((area) => [
area.area,
area.commands.flatMap((c) => [c.name, ...(c.aliases ?? [])])
])
);
for (const { area, action } of listReadOnlyCommands()) {
if (ACTIONS_WITHOUT_REGISTRY_ENTRY.has(`${area} ${action}`)) continue;
expect({ area, dispatchable: KNOWN_AREAS.has(area) }).toEqual({ area, dispatchable: true });
expect({ area, action, known: byArea.get(area)?.includes(action) }).toEqual({
area,
action,
known: true
});
}
});
test("allows read-only commands, including through area aliases and positional arguments", () => {
for (const command of [
["corps", "list"],
["corp", "list"],
["corp", "get", "corp-a"],
["documents", "list", "--corp", "corp-a"],
["expenses", "--sn", "SN-FIXTURE", "--corp", "corp-a"],
["expenses", "list", "--record-id", "run-1", "--corp", "corp-a"],
["expense", "--sn", "SN-FIXTURE", "--corp", "corp-a"],
["data", "expenses", "--sn", "SN-FIXTURE", "--corp", "corp-a"],
["documents", "get", "doc-1", "--corp", "corp-a"],
["documents", "search", "差旅", "--corp", "corp-a"],
["approval-runs", "get", "01a09dac-c688-767b-8eb4-37b945095585"],
["approval-runs", "list", "--corp", "corp-a"],
["deploy", "hosecloud", "status", "--corp", "corp-a"],
["hose-ebot", "search", "SN123", "--type", "callback", "--corp", "corp-a"],
["hose-ebot", "messages", "--corp", "corp-a"],
["preferences", "get"],
["doctor", "tenant", "--corp", "corp-a"],
["langfuse", "check"],
["langfuse", "outline", "trace-1", "--include-io-preview"],
["langfuse", "search", "trace-1", "--query", "发票"],
["langfuse", "observation", "trace-1", "obs-1"],
["version"],
["mcp-config"]
]) {
expect({ command, readOnly: isReadOnlyCliCommand(command) }).toEqual({ command, readOnly: true });
}
});
test("refuses mutating, unclassified, and server-lifetime commands", () => {
for (const command of [
["corps", "mark", "corp-a", "--env", "production"],
["corps", "switch", "corp-a"],
["corps", "extract-keys", "corp-a"],
["corps", "sync-test", "corp-a"],
["rules", "create"],
["rules", "update", "25"],
["rules", "delete", "25"],
["rules", "publish", "v1"],
["rules", "push"],
["rules", "clear"],
["documents", "create"],
["documents", "update", "doc-1"],
["documents", "delete", "doc-1"],
["simulation", "create", "--mode", "hosecloud"],
["deploy", "hosecloud", "sync", "sign-key"],
["deploy", "hosecloud", "configure"],
// The EBot approval callback writes accept/refuse into the live approval flow.
["hose-ebot", "callback", "--flow-id", "f1", "--node-id", "n1", "--action", "accept", "--comment", "ok", "--yes"],
["webhook", "delete", "hook-1"],
["webhook", "replay"],
["users", "reset-password", "corp-a:u1"],
["users", "create"],
["config", "test-dir", "corp-a"],
["skill", "install"],
["mcp"],
["update"],
["auth", "keys"],
// Mints and prints an OpenAPI credential, so it never qualifies as a read.
["auth", "hose-openapi-token"],
["analytics", "analyze", "record-1"],
["tool", "sealApprovalRuleCreate", "--json", "{}"],
["langfuse", "unknown-verb"],
["totally-unknown", "list"],
[]
]) {
expect({ command, readOnly: isReadOnlyCliCommand(command) }).toEqual({ command, readOnly: false });
}
});
test("matches whole tokens, so a read prefix cannot smuggle a mutation", () => {
for (const command of [
["corps", "listing"],
["corps", "list-extra"],
["approval-runs", "getter"],
["rules", "listp"]
]) {
expect({ command, readOnly: isReadOnlyCliCommand(command) }).toEqual({ command, readOnly: false });
}
});
test("a bare allow-listed command does not cover its subcommands", () => {
expect(isReadOnlyCliCommand(["doctor"])).toBe(true);
expect(isReadOnlyCliCommand(["doctor", "guide"])).toBe(true);
expect(isReadOnlyCliCommand(["doctor", "unknown-subcommand"])).toBe(false);
});
test("probe is read-only bare or with its enterprise selector, but not beyond", () => {
// `seal-use probe [<corpId>]` takes a selector, not a verb: the allow-list
// entry covers the bare form and the selector form is matched separately.
expect(isReadOnlyCliCommand(["probe"])).toBe(true);
expect(isReadOnlyCliCommand(["probe", "corp-a"])).toBe(true);
expect(isReadOnlyCliCommand(["probe", "corp-a", "extra"])).toBe(false);
});
test("allows rules push status / --check as read-only while refusing mutating rules push forms", () => {
expect(isReadOnlyCliCommand(["rules", "push", "status", "--corp", "corp-a"])).toBe(true);
expect(isReadOnlyCliCommand(["rules", "push", "--check", "--corp", "corp-a"])).toBe(true);
expect(isReadOnlyCliCommand(["rules", "push", "--corp", "corp-a"])).toBe(false);
expect(isReadOnlyCliCommand(["rules", "push", "status", "--yes", "--corp", "corp-a"])).toBe(false);
});
test("refuses command lines that cannot be parsed", () => {
expect(isReadOnlyCliCommand(["--json"])).toBe(false);
});
});
// The two classifications are maintained in different files: the CLI allow-list here and
// SEAL_READ_ONLY_CAPABILITIES in the tool registry. Nothing stopped them from disagreeing, and they did —
// `analytics analyze` was allow-listed while its tool POSTs, and three read-only approval-runs verbs
// were simply missing. This scans both `runCapability` and `runCapabilityResult` and fails on any disagreement.
describe("CLI allow-list agrees with the tool registry", () => {
// `deploy` only accepts `deploy hosecloud <action>`; the short `deploy <action>` form throws
// "未知的发布目标系统" at runtime. `auth seal-link` only calls `sealDelegationList` when the
// third token `list` is present (`auth seal-link list`); bare `auth seal-link` mints a token.
const UNREACHABLE_CLI_FORMS = new Set([
"deploy requirements",
"deploy list",
"deploy status",
"auth seal-link"
]);
test("every CLI verb dispatching to a read-only tool is itself read-only, and mutating tools are not read-only", () => {
const files = readdirSync(join(import.meta.dir, "commands")).filter(
(f) => f.endsWith(".ts") && !f.endsWith(".test.ts")
);
const pairs: Array<{ area: string; action: string; tool: string }> = [];
for (const file of files) {
const area = file.replace(/\.ts$/, "");
const source = readFileSync(join(import.meta.dir, "commands", file), "utf8");
const pattern =
/if\s*\(\s*action === "([a-z0-9-]+)"(?:(?!\bif\s*\(\s*action\b)[\s\S]){0,600}?runCapability(?:Result)?\(\s*"(seal[A-Z][A-Za-z0-9]*)"/g;
let match;
while ((match = pattern.exec(source))) {
pairs.push({ area, action: match[1]!, tool: match[2]! });
}
}
// If the dispatch shape changes this silently finds nothing, which would make the test vacuous.
expect(pairs.length).toBeGreaterThan(55);
const disagreements = pairs
.filter((pair) => SEAL_READ_ONLY_CAPABILITIES.has(pair.tool))
.filter((pair) => !UNREACHABLE_CLI_FORMS.has(`${pair.area} ${pair.action}`))
.filter((pair) => !isReadOnlyCliCommand([pair.area, pair.action]))
.map((pair) => `${pair.area} ${pair.action} -> ${pair.tool}`);
expect(disagreements).toEqual([]);
const unsafeMutating = pairs
.filter((pair) => SEAL_MUTATING_CAPABILITIES.has(pair.tool))
.filter((pair) => isReadOnlyCliCommand([pair.area, pair.action]))
.map((pair) => `${pair.area} ${pair.action} -> ${pair.tool}`);
expect(unsafeMutating).toEqual([]);
});
});