481 lines
18 KiB
TypeScript
481 lines
18 KiB
TypeScript
import { afterEach, describe, expect, test } from "bun:test";
|
|
import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
|
|
import { tmpdir } from "node:os";
|
|
import { join } from "node:path";
|
|
import type { CorpConfig } from "../../core/config/types.js";
|
|
import { runCli } from "../runner.js";
|
|
|
|
const ORIGINAL_ENV = {
|
|
enterprises: process.env.SEAL_USE_ENTERPRISES_DIR,
|
|
config: process.env.SEAL_USE_CONFIG_FILE,
|
|
tokenStore: process.env.SEAL_USE_TOKEN_STORE
|
|
};
|
|
const ORIGINAL_FETCH = globalThis.fetch;
|
|
const tempDirs: string[] = [];
|
|
|
|
afterEach(() => {
|
|
restoreEnv("SEAL_USE_ENTERPRISES_DIR", ORIGINAL_ENV.enterprises);
|
|
restoreEnv("SEAL_USE_CONFIG_FILE", ORIGINAL_ENV.config);
|
|
restoreEnv("SEAL_USE_TOKEN_STORE", ORIGINAL_ENV.tokenStore);
|
|
globalThis.fetch = ORIGINAL_FETCH;
|
|
|
|
for (const dir of tempDirs.splice(0)) {
|
|
rmSync(dir, { recursive: true, force: true });
|
|
}
|
|
});
|
|
|
|
function setupTestEnv() {
|
|
const root = mkdtempSync(join(tmpdir(), "seal-use-bind-test-"));
|
|
const enterprises = join(root, "enterprises");
|
|
mkdirSync(enterprises, { recursive: true });
|
|
tempDirs.push(root);
|
|
|
|
process.env.SEAL_USE_ENTERPRISES_DIR = enterprises;
|
|
process.env.SEAL_USE_CONFIG_FILE = join(root, "config.json");
|
|
process.env.SEAL_USE_TOKEN_STORE = join(root, "tokens.json");
|
|
|
|
const prodCorp: CorpConfig = {
|
|
id: "corp-prod",
|
|
name: "Acme Production",
|
|
environment: "production",
|
|
seal: {
|
|
url: "https://acme-prod.sealai.cc",
|
|
endpoints: { approvalStylePreferences: "api/v1/agent/ai-approval/config" }
|
|
},
|
|
source: {
|
|
type: "seal",
|
|
token: "prod-token",
|
|
sealUrl: "https://acme-prod.sealai.cc",
|
|
expiresIn: 3600,
|
|
staffId: "seal"
|
|
},
|
|
auth: { refreshTtl: 300 }
|
|
};
|
|
|
|
const testCorp: CorpConfig = {
|
|
id: "corp-test",
|
|
name: "Acme Staging Test",
|
|
environment: "test",
|
|
seal: {
|
|
url: "https://acme-test.sealai.cc",
|
|
endpoints: { approvalStylePreferences: "api/v1/agent/ai-approval/config" }
|
|
},
|
|
source: {
|
|
type: "seal",
|
|
token: "test-token",
|
|
sealUrl: "https://acme-test.sealai.cc",
|
|
expiresIn: 3600,
|
|
staffId: "seal"
|
|
},
|
|
auth: { refreshTtl: 300 }
|
|
};
|
|
|
|
writeFileSync(join(enterprises, "corp-prod.json"), JSON.stringify(prodCorp, null, 2));
|
|
writeFileSync(join(enterprises, "corp-test.json"), JSON.stringify(testCorp, null, 2));
|
|
|
|
return { root, enterprises, prodCorp, testCorp };
|
|
}
|
|
|
|
function restoreEnv(name: string, value: string | undefined) {
|
|
if (value === undefined) delete process.env[name];
|
|
else process.env[name] = value;
|
|
}
|
|
|
|
describe("corps mark", () => {
|
|
test("requires confirmation and exit code 10 without --confirm", async () => {
|
|
setupTestEnv();
|
|
const result = await runCli(["corps", "mark", "corp-prod", "--env", "test"]);
|
|
|
|
expect(result.isError).toBe(true);
|
|
expect(result.exitCode).toBe(10);
|
|
expect(result.stderr).toContain("without --confirm");
|
|
expect(result.stderr).toContain("seal-use corps mark corp-prod --env test --confirm");
|
|
});
|
|
|
|
test("successfully updates environment with --confirm", async () => {
|
|
const { enterprises } = setupTestEnv();
|
|
const result = await runCli(["corps", "mark", "corp-prod", "--env", "test", "--confirm"]);
|
|
|
|
expect(result.isError).toBe(false);
|
|
expect(result.exitCode).toBe(0);
|
|
const parsed = JSON.parse(result.stdout);
|
|
expect(parsed.id).toBe("corp-prod");
|
|
expect(parsed.environment).toBe("test");
|
|
|
|
const saved = JSON.parse(readFileSync(join(enterprises, "corp-prod.json"), "utf-8"));
|
|
expect(saved.environment).toBe("test");
|
|
});
|
|
});
|
|
|
|
describe("corps bind-test & unbind-test", () => {
|
|
test("rejects self-binding with exit code 2", async () => {
|
|
setupTestEnv();
|
|
const result = await runCli(["corps", "bind-test", "corp-prod", "corp-prod", "--confirm"]);
|
|
|
|
expect(result.isError).toBe(true);
|
|
expect(result.exitCode).toBe(2);
|
|
expect(result.stderr).toContain("Cannot bind enterprise 'corp-prod' to itself");
|
|
});
|
|
|
|
test("requires confirmation and exit code 10 without --confirm", async () => {
|
|
setupTestEnv();
|
|
const result = await runCli(["corps", "bind-test", "corp-prod", "corp-test"]);
|
|
|
|
expect(result.isError).toBe(true);
|
|
expect(result.exitCode).toBe(10);
|
|
expect(result.stderr).toContain("without --confirm");
|
|
expect(result.stderr).toContain("seal-use corps bind-test corp-prod corp-test --confirm");
|
|
});
|
|
|
|
test("successfully binds 1-to-1 with --confirm and sets tags", async () => {
|
|
const { enterprises } = setupTestEnv();
|
|
const result = await runCli(["corps", "bind-test", "corp-prod", "corp-test", "--confirm"]);
|
|
|
|
expect(result.isError).toBe(false);
|
|
expect(result.exitCode).toBe(0);
|
|
const parsed = JSON.parse(result.stdout);
|
|
expect(parsed.success).toBe(true);
|
|
expect(parsed.productionEnterprise.id).toBe("corp-prod");
|
|
expect(parsed.productionEnterprise.testCorpId).toBe("corp-test");
|
|
expect(parsed.productionEnterprise.environment).toBe("production");
|
|
expect(parsed.testEnterprise.id).toBe("corp-test");
|
|
expect(parsed.testEnterprise.prodCorpId).toBe("corp-prod");
|
|
expect(parsed.testEnterprise.environment).toBe("test");
|
|
|
|
const savedProd = JSON.parse(readFileSync(join(enterprises, "corp-prod.json"), "utf-8"));
|
|
expect(savedProd.testCorpId).toBe("corp-test");
|
|
expect(savedProd.environment).toBe("production");
|
|
|
|
const savedTest = JSON.parse(readFileSync(join(enterprises, "corp-test.json"), "utf-8"));
|
|
expect(savedTest.prodCorpId).toBe("corp-prod");
|
|
expect(savedTest.environment).toBe("test");
|
|
});
|
|
|
|
test("prevents multi-tier chaining: test corp cannot be bound as prod parent", async () => {
|
|
const { enterprises } = setupTestEnv();
|
|
await runCli(["corps", "bind-test", "corp-prod", "corp-test", "--confirm"]);
|
|
|
|
const thirdCorp: CorpConfig = {
|
|
id: "corp-subtest",
|
|
name: "Acme Subtest",
|
|
environment: "test",
|
|
seal: { url: "https://sub.sealai.cc", endpoints: { approvalStylePreferences: "" } },
|
|
source: { type: "seal", token: "tok", sealUrl: "https://sub.sealai.cc", expiresIn: 3600, staffId: "seal" },
|
|
auth: { refreshTtl: 300 }
|
|
};
|
|
writeFileSync(join(enterprises, "corp-subtest.json"), JSON.stringify(thirdCorp, null, 2));
|
|
|
|
const result = await runCli(["corps", "bind-test", "corp-test", "corp-subtest", "--confirm"]);
|
|
expect(result.isError).toBe(true);
|
|
expect(result.exitCode).toBe(2);
|
|
expect(result.stderr).toContain("Multi-tier chaining is not permitted");
|
|
});
|
|
|
|
test("requires --force when re-binding an already bound corp", async () => {
|
|
const { enterprises } = setupTestEnv();
|
|
await runCli(["corps", "bind-test", "corp-prod", "corp-test", "--confirm"]);
|
|
|
|
const testCorp2: CorpConfig = {
|
|
id: "corp-test-2",
|
|
name: "Acme Staging 2",
|
|
environment: "test",
|
|
seal: { url: "https://test2.sealai.cc", endpoints: { approvalStylePreferences: "" } },
|
|
source: { type: "seal", token: "tok2", sealUrl: "https://test2.sealai.cc", expiresIn: 3600, staffId: "seal" },
|
|
auth: { refreshTtl: 300 }
|
|
};
|
|
writeFileSync(join(enterprises, "corp-test-2.json"), JSON.stringify(testCorp2, null, 2));
|
|
|
|
const conflictResult = await runCli(["corps", "bind-test", "corp-prod", "corp-test-2", "--confirm"]);
|
|
expect(conflictResult.isError).toBe(true);
|
|
expect(conflictResult.exitCode).toBe(10);
|
|
expect(conflictResult.stderr).toContain("requires --force");
|
|
|
|
const forceResult = await runCli(["corps", "bind-test", "corp-prod", "corp-test-2", "--confirm", "--force"]);
|
|
expect(forceResult.isError).toBe(false);
|
|
expect(forceResult.exitCode).toBe(0);
|
|
|
|
const savedProd = JSON.parse(readFileSync(join(enterprises, "corp-prod.json"), "utf-8"));
|
|
expect(savedProd.testCorpId).toBe("corp-test-2");
|
|
});
|
|
|
|
test("unbind-test requires confirmation then unlinks both sides", async () => {
|
|
const { enterprises } = setupTestEnv();
|
|
await runCli(["corps", "bind-test", "corp-prod", "corp-test", "--confirm"]);
|
|
|
|
const blockResult = await runCli(["corps", "unbind-test", "corp-prod"]);
|
|
expect(blockResult.isError).toBe(true);
|
|
expect(blockResult.exitCode).toBe(10);
|
|
expect(blockResult.stderr).toContain("without --confirm");
|
|
|
|
const successResult = await runCli(["corps", "unbind-test", "corp-prod", "--confirm"]);
|
|
expect(successResult.isError).toBe(false);
|
|
expect(successResult.exitCode).toBe(0);
|
|
const parsed = JSON.parse(successResult.stdout);
|
|
expect(parsed.success).toBe(true);
|
|
expect(parsed.unboundProduction).toBe("corp-prod");
|
|
expect(parsed.unboundTest).toBe("corp-test");
|
|
|
|
const savedProd = JSON.parse(readFileSync(join(enterprises, "corp-prod.json"), "utf-8"));
|
|
expect(savedProd.testCorpId).toBeUndefined();
|
|
|
|
const savedTest = JSON.parse(readFileSync(join(enterprises, "corp-test.json"), "utf-8"));
|
|
expect(savedTest.prodCorpId).toBeUndefined();
|
|
});
|
|
});
|
|
|
|
describe("corps sync-test", () => {
|
|
test("fails if production corp has no bound test corp", async () => {
|
|
setupTestEnv();
|
|
const result = await runCli(["corps", "sync-test", "corp-prod", "--dry-run"]);
|
|
expect(result.isError).toBe(true);
|
|
expect(result.exitCode).toBe(2);
|
|
expect(result.stderr).toContain("has no bound test enterprise");
|
|
});
|
|
|
|
test("dry-run produces preview diff without making network mutations", async () => {
|
|
setupTestEnv();
|
|
await runCli(["corps", "bind-test", "corp-prod", "corp-test", "--confirm"]);
|
|
|
|
const mockMutations: string[] = [];
|
|
mockSealSyncRequests({ onMutation: (method, path) => mockMutations.push(`${method} ${path}`) });
|
|
|
|
const result = await runCli(["corps", "sync-test", "corp-prod", "--dry-run"]);
|
|
expect(result.isError).toBe(false);
|
|
expect(result.exitCode).toBe(0);
|
|
|
|
const parsed = JSON.parse(result.stdout);
|
|
expect(parsed.dryRun).toBe(true);
|
|
expect(parsed.source.id).toBe("corp-prod");
|
|
expect(parsed.target.id).toBe("corp-test");
|
|
expect(parsed.rulesPlan.sourceDraftRuleCount).toBe(2);
|
|
expect(parsed.rulesPlan.targetExistingDraftRuleCount).toBe(1);
|
|
expect(parsed.rulesPlan.toDeleteCount).toBe(1);
|
|
expect(parsed.rulesPlan.toCreateCount).toBe(2);
|
|
expect(parsed.productionGuarantees.prodRulesStayDraft).toBe(true);
|
|
expect(parsed.productionGuarantees.prodVersionPublished).toBe(false);
|
|
|
|
expect(mockMutations).toEqual([]);
|
|
});
|
|
|
|
test("sync-test requires --yes and blocks with exit code 10", async () => {
|
|
setupTestEnv();
|
|
await runCli(["corps", "bind-test", "corp-prod", "corp-test", "--confirm"]);
|
|
mockSealSyncRequests();
|
|
|
|
const result = await runCli(["corps", "sync-test", "corp-prod"]);
|
|
expect(result.isError).toBe(true);
|
|
expect(result.exitCode).toBe(10);
|
|
expect(result.stderr).toContain("without --yes");
|
|
expect(result.stderr).toContain("seal-use corps sync-test corp-prod --yes");
|
|
});
|
|
|
|
test("sync-test --yes overwrites test preferences, syncs rules, publishes new test version, and guarantees prod draft safety", async () => {
|
|
setupTestEnv();
|
|
await runCli(["corps", "bind-test", "corp-prod", "corp-test", "--confirm"]);
|
|
|
|
const requests: { method: string; path: string; body?: unknown }[] = [];
|
|
mockSealSyncRequests({
|
|
onMutation: (method, path, body) => requests.push({ method, path, body })
|
|
});
|
|
|
|
const result = await runCli([
|
|
"corps",
|
|
"sync-test",
|
|
"corp-prod",
|
|
"--yes",
|
|
"--version-name",
|
|
"v1.5-staging"
|
|
]);
|
|
|
|
expect(result.isError).toBe(false);
|
|
expect(result.exitCode).toBe(0);
|
|
|
|
const parsed = JSON.parse(result.stdout);
|
|
expect(parsed.success).toBe(true);
|
|
expect(parsed.source.id).toBe("corp-prod");
|
|
expect(parsed.source.draftRulesCount).toBe(2);
|
|
expect(parsed.target.id).toBe("corp-test");
|
|
expect(parsed.target.deletedDraftRulesCount).toBe(1);
|
|
expect(parsed.target.createdDraftRulesCount).toBe(2);
|
|
expect(parsed.target.publishedVersion.versionName).toBe("v1.5-staging");
|
|
expect(parsed.target.publishedVersion.versionNumber).toBe(3);
|
|
expect(parsed.productionGuarantees.prodRulesStayDraft).toBe(true);
|
|
expect(parsed.productionGuarantees.prodVersionPublished).toBe(false);
|
|
|
|
const postPref = requests.find((r) => (r.method === "POST" || r.method === "PATCH") && r.path.includes("config"));
|
|
expect(postPref).toBeDefined();
|
|
expect((postPref?.body as any).decisionPreferences?.explicitApprove).toBe("Prod approve note");
|
|
|
|
const deleteRule = requests.find((r) => r.method === "DELETE" && r.path === "/api/v1/rules/test-rule-old");
|
|
expect(deleteRule).toBeDefined();
|
|
|
|
const createdRules = requests.filter((r) => r.method === "POST" && r.path === "/api/v1/rules");
|
|
expect(createdRules.length).toBe(2);
|
|
expect((createdRules[0]?.body as any).description).toBe("Production Rule A");
|
|
expect((createdRules[1]?.body as any).description).toBe("Production Rule B");
|
|
|
|
const publishVersion = requests.find((r) => r.method === "POST" && r.path === "/api/v1/rule-set-versions/publish");
|
|
expect(publishVersion).toBeDefined();
|
|
expect((publishVersion?.body as any).versionName).toBe("v1.5-staging");
|
|
|
|
const allPublishCalls = requests.filter((r) => r.path === "/api/v1/rule-set-versions/publish");
|
|
expect(allPublishCalls.length).toBe(1);
|
|
});
|
|
});
|
|
|
|
describe("corps list & current", () => {
|
|
test("outputs environment, testCorpId, and prodCorpId", async () => {
|
|
setupTestEnv();
|
|
await runCli(["corps", "bind-test", "corp-prod", "corp-test", "--confirm"]);
|
|
|
|
const listResult = await runCli(["corps", "list"]);
|
|
expect(listResult.isError).toBe(false);
|
|
const list = JSON.parse(listResult.stdout);
|
|
const prodItem = list.find((item: any) => item.id === "corp-prod");
|
|
const testItem = list.find((item: any) => item.id === "corp-test");
|
|
|
|
expect(prodItem.environment).toBe("production");
|
|
expect(prodItem.testCorpId).toBe("corp-test");
|
|
expect(testItem.environment).toBe("test");
|
|
expect(testItem.prodCorpId).toBe("corp-prod");
|
|
|
|
const currentResult = await runCli(["corps", "current", "--corp", "corp-prod"]);
|
|
expect(currentResult.isError).toBe(false);
|
|
const current = JSON.parse(currentResult.stdout);
|
|
expect(current.id).toBe("corp-prod");
|
|
expect(current.environment).toBe("production");
|
|
expect(current.testCorpId).toBe("corp-test");
|
|
});
|
|
});
|
|
|
|
function mockSealSyncRequests(options: {
|
|
onMutation?: (method: string, path: string, body?: unknown) => void;
|
|
} = {}) {
|
|
globalThis.fetch = (async (input: RequestInfo | URL, init?: RequestInit) => {
|
|
const requestUrl = typeof input === "string"
|
|
? input
|
|
: input instanceof URL
|
|
? input.toString()
|
|
: input.url;
|
|
const url = new URL(requestUrl);
|
|
const method = (
|
|
init?.method ??
|
|
(typeof input === "object" && "method" in input ? (input as Request).method : "GET")
|
|
).toUpperCase();
|
|
const isProd = url.host.includes("prod");
|
|
|
|
let rawBody = typeof init?.body === "string" ? init.body : undefined;
|
|
if (!rawBody && typeof input === "object" && "text" in input) {
|
|
rawBody = await (input as Request).clone().text().catch(() => "{}");
|
|
}
|
|
|
|
if (url.pathname === "/api/v1/auth/me") {
|
|
return jsonResponse({
|
|
data: {
|
|
user: { id: "user-1", name: isProd ? "Prod User" : "Test User" },
|
|
tenant: { id: isProd ? "tenant-prod" : "tenant-test", tenantSlug: isProd ? "acme-prod" : "acme-test" }
|
|
}
|
|
});
|
|
}
|
|
|
|
if (url.pathname === "/api/v1/agent/ai-approval/config" && method === "GET") {
|
|
return jsonResponse({
|
|
data: {
|
|
id: isProd ? "pref-prod" : "pref-test",
|
|
tenantId: isProd ? "tenant-prod" : "tenant-test",
|
|
tone: isProd ? "formal" : "casual",
|
|
language: "zh-CN",
|
|
decisionPreferences: {
|
|
explicitApprove: isProd ? "Prod approve note" : "Test approve note",
|
|
explicitReject: "Reject invalid expenses",
|
|
exemptApprove: "",
|
|
review: ""
|
|
},
|
|
thinkingDepthPreference: {
|
|
defaultLevel: isProd ? "high" : "medium",
|
|
routingPolicies: []
|
|
},
|
|
integrations: [
|
|
{ type: "hosecloud", signKey: isProd ? "prod-sign" : "test-sign" }
|
|
]
|
|
}
|
|
});
|
|
}
|
|
|
|
if (url.pathname === "/api/v1/agent/ai-approval/config" && (method === "POST" || method === "PATCH")) {
|
|
const body = JSON.parse(rawBody || "{}");
|
|
options.onMutation?.(method, url.pathname, body);
|
|
return jsonResponse({ data: { success: true } });
|
|
}
|
|
|
|
if (url.pathname === "/api/v1/rules" && method === "GET") {
|
|
if (isProd) {
|
|
return jsonResponse({
|
|
data: {
|
|
rules: [
|
|
{ id: "prod-rule-1", description: "Production Rule A", scope: "global", strictness: "strict" },
|
|
{ id: "prod-rule-2", description: "Production Rule B", scope: "invoice", strictness: "flexible" }
|
|
],
|
|
hasPendingDeletes: false
|
|
}
|
|
});
|
|
} else {
|
|
return jsonResponse({
|
|
data: {
|
|
rules: [
|
|
{ id: "test-rule-old", description: "Old test rule", scope: "global", strictness: "strict" }
|
|
],
|
|
hasPendingDeletes: false
|
|
}
|
|
});
|
|
}
|
|
}
|
|
|
|
if (url.pathname.startsWith("/api/v1/rules/") && method === "DELETE") {
|
|
options.onMutation?.("DELETE", url.pathname);
|
|
return jsonResponse({ data: { success: true } });
|
|
}
|
|
|
|
if (url.pathname === "/api/v1/rules" && method === "POST") {
|
|
const body = JSON.parse(rawBody || "{}");
|
|
options.onMutation?.("POST", url.pathname, body);
|
|
return jsonResponse({
|
|
data: {
|
|
id: `new-rule-${Date.now()}`,
|
|
...body
|
|
}
|
|
});
|
|
}
|
|
|
|
if (url.pathname === "/api/v1/rules/batch-recode" && method === "POST") {
|
|
options.onMutation?.("POST", url.pathname);
|
|
return jsonResponse({ data: { success: true } });
|
|
}
|
|
|
|
if (url.pathname === "/api/v1/rule-set-versions/publish" && method === "POST") {
|
|
const body = JSON.parse(rawBody || "{}");
|
|
options.onMutation?.("POST", url.pathname, body);
|
|
return jsonResponse({
|
|
data: {
|
|
version: {
|
|
id: "ver-3",
|
|
versionNumber: 3,
|
|
versionName: body.versionName ?? "v1.0",
|
|
rules: []
|
|
},
|
|
rulesCount: 2
|
|
}
|
|
});
|
|
}
|
|
|
|
return jsonResponse({ error: `Unexpected request: ${method} ${url.pathname}` }, 404);
|
|
}) as typeof fetch;
|
|
}
|
|
|
|
function jsonResponse(value: unknown, status = 200) {
|
|
return new Response(JSON.stringify(value), {
|
|
status,
|
|
headers: { "content-type": "application/json" }
|
|
});
|
|
}
|