workspaceHookTrustStoreSchemaParity.test.ts 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245
  1. import { mkdirSync, mkdtempSync, writeFileSync } from "node:fs";
  2. import { tmpdir } from "node:os";
  3. import { join } from "node:path";
  4. import { afterEach, describe, expect, it, vi } from "vitest";
  5. import { createHooksService } from "../src/hooks/hooksService.js";
  6. import {
  7. parseWorkspaceHookTrustStoreContent,
  8. type WorkspaceHookTrustStoreParseResult,
  9. } from "@zcode/shared/workspace-hook-trust-store-file";
  10. /**
  11. * Trust store schema parity(CR-01 回归)。
  12. *
  13. * Bug 背景:services 层曾用手写的局部字段校验读 trust store,而 runtime/adapters
  14. * 用 contracts 的完整 strict schema。同一份"JSON 合法但结构非法"的文件,services
  15. * 会把其中形似合法的 digest 当作 trusted_persistent 展示,runtime 却 fail-closed
  16. * 全部阻断——UI 与执行层状态分裂。信任存储是权限边界,所有消费者必须对同一
  17. * 文件得出同一结论。
  18. *
  19. * 本测试以 shared 的 parseWorkspaceHookTrustStoreContent(与 adapters 使用的
  20. * contracts schema 同源 re-export)作为 runtime 侧判定基准,对一组损坏样本
  21. * 断言:runtime 判 invalid ⇔ services 必须 corrupt 且不产出任何 trusted 展示;
  22. * runtime 判 ok ⇔ services 采纳其中匹配的 digest。
  23. */
  24. const roots: string[] = [];
  25. function makeRoot(): string {
  26. const root = mkdtempSync(join(tmpdir(), "zcode-hook-trust-parity-"));
  27. roots.push(root);
  28. return root;
  29. }
  30. function writeJson(path: string, value: unknown): void {
  31. mkdirSync(join(path, ".."), { recursive: true });
  32. writeFileSync(path, typeof value === "string" ? value : `${JSON.stringify(value, null, 2)}\n`, "utf8");
  33. }
  34. function setupWorkspaceWithHook(): { home: string; workspace: string } {
  35. const home = makeRoot();
  36. const workspace = makeRoot();
  37. mkdirSync(join(workspace, ".git"));
  38. writeJson(join(workspace, ".zcode", "config.json"), {
  39. hooks: {
  40. enabled: true,
  41. events: {
  42. SessionStart: [{ hooks: [{ type: "command", command: "echo hello" }] }],
  43. },
  44. },
  45. });
  46. vi.stubEnv("HOME", home);
  47. vi.stubEnv("USERPROFILE", home);
  48. return { home, workspace };
  49. }
  50. function trustStorePath(home: string): string {
  51. return join(home, ".zcode", "security", "workspace-hook-trust-v1.json");
  52. }
  53. const VALID_DIGEST = "a".repeat(64);
  54. function runtimeVerdict(content: string): WorkspaceHookTrustStoreParseResult {
  55. return parseWorkspaceHookTrustStoreContent(content);
  56. }
  57. /** CR-01 原始症状样本:JSON 合法、digest 形似合法,但结构不符合 schema。 */
  58. const STRUCTURALLY_INVALID_SAMPLES: Array<{ name: string; file: unknown }> = [
  59. {
  60. name: "缺少 schemaVersion",
  61. file: { records: [{ workspaceIdentity: "PLACEHOLDER", hookDeclarationDigest: VALID_DIGEST }] },
  62. },
  63. {
  64. name: "record 缺少 decision/grantedAt/digestAlgorithm 等必需字段",
  65. file: {
  66. schemaVersion: 1,
  67. records: [{ workspaceIdentity: "PLACEHOLDER", hookDeclarationDigest: VALID_DIGEST }],
  68. },
  69. },
  70. {
  71. name: "非法 decision",
  72. file: {
  73. schemaVersion: 1,
  74. records: [
  75. {
  76. workspaceIdentity: "PLACEHOLDER",
  77. hookDeclarationDigest: VALID_DIGEST,
  78. digestAlgorithm: "sha256",
  79. decision: "allow_once",
  80. grantedAt: "2026-08-17T09:00:00.000Z",
  81. eventAtGrant: "SessionStart",
  82. displayCommandAtGrant: "node recorder.mjs",
  83. sourcePathAtGrant: ".zcode/config.json",
  84. },
  85. ],
  86. },
  87. },
  88. {
  89. name: "非法时间戳",
  90. file: {
  91. schemaVersion: 1,
  92. records: [
  93. {
  94. workspaceIdentity: "PLACEHOLDER",
  95. hookDeclarationDigest: VALID_DIGEST,
  96. digestAlgorithm: "sha256",
  97. decision: "trusted",
  98. grantedAt: "not-a-timestamp",
  99. eventAtGrant: "SessionStart",
  100. displayCommandAtGrant: "node recorder.mjs",
  101. sourcePathAtGrant: ".zcode/config.json",
  102. },
  103. ],
  104. },
  105. },
  106. {
  107. name: "records 非数组",
  108. file: { schemaVersion: 1, records: { workspaceIdentity: "PLACEHOLDER" } },
  109. },
  110. {
  111. name: "未知顶层字段",
  112. file: {
  113. schemaVersion: 1,
  114. records: [],
  115. extra: { workspaceIdentity: "PLACEHOLDER", hookDeclarationDigest: VALID_DIGEST },
  116. },
  117. },
  118. {
  119. name: "未知 record 字段",
  120. file: {
  121. schemaVersion: 1,
  122. records: [
  123. {
  124. workspaceIdentity: "PLACEHOLDER",
  125. hookDeclarationDigest: VALID_DIGEST,
  126. digestAlgorithm: "sha256",
  127. decision: "trusted",
  128. grantedAt: "2026-08-17T09:00:00.000Z",
  129. eventAtGrant: "SessionStart",
  130. displayCommandAtGrant: "node recorder.mjs",
  131. sourcePathAtGrant: ".zcode/config.json",
  132. injected: true,
  133. },
  134. ],
  135. },
  136. },
  137. ];
  138. afterEach(async () => {
  139. const { rm } = await import("node:fs/promises");
  140. await Promise.all(roots.splice(0).map((root) => rm(root, { force: true, recursive: true })));
  141. vi.unstubAllEnvs();
  142. vi.restoreAllMocks();
  143. });
  144. describe("trust store schema parity:services 与 runtime 对同一文件必须同判(CR-01)", () => {
  145. for (const sample of STRUCTURALLY_INVALID_SAMPLES) {
  146. it(`结构非法样本(${sample.name}):runtime 判 invalid ⇔ services 必须 corrupt 且不展示 trusted`, async () => {
  147. const { home, workspace } = setupWorkspaceWithHook();
  148. // 先拿到该 workspace 声明的真实 digest,替换样本占位符,确保"digest 本应匹配"。
  149. const first = await createHooksService().loadHooks({ workspacePath: workspace });
  150. const digest = first.workspaceHookSnapshot?.hooks[0]?.hookDeclarationDigest;
  151. expect(digest).toBeTruthy();
  152. // Bugfix 原因:直接把 workspace 路径 replaceAll 进 JSON 字符串,在 Windows 上
  153. // 会注入未转义的反斜杠,产生非法 JSON(Bad escaped character),样本构造直接崩。
  154. // 改为连引号一起替换成 JSON.stringify 的产物,保持任意平台的路径转义合法。
  155. const serialized = JSON.stringify(sample.file).replaceAll(
  156. '"PLACEHOLDER"',
  157. JSON.stringify(workspace),
  158. );
  159. // 基准:runtime 侧(shared schema,与 adapters 同源)判 invalid。
  160. expect(runtimeVerdict(serialized).status).toBe("invalid");
  161. writeJson(trustStorePath(home), JSON.parse(serialized));
  162. const warnSpy = vi.spyOn(console, "warn").mockImplementation(() => {});
  163. const loaded = await createHooksService().loadHooks({ workspacePath: workspace });
  164. // services 必须 fail-closed:不展示 trusted、标记 corrupt、发出诊断。
  165. expect(loaded.hooks[0]?.workspaceHook?.trustState).toBe("pending_trust");
  166. expect(loaded.trustStoreCorrupt).toBe(true);
  167. expect(warnSpy).toHaveBeenCalled();
  168. });
  169. }
  170. it("合法完整记录:runtime 判 ok ⇔ services 采纳匹配 digest 展示 trusted_persistent", async () => {
  171. const { home, workspace } = setupWorkspaceWithHook();
  172. const first = await createHooksService().loadHooks({ workspacePath: workspace });
  173. const digest = first.workspaceHookSnapshot?.hooks[0]?.hookDeclarationDigest;
  174. expect(digest).toBeTruthy();
  175. const file = {
  176. schemaVersion: 1,
  177. records: [
  178. {
  179. workspaceIdentity: workspace,
  180. hookDeclarationDigest: digest,
  181. digestAlgorithm: "sha256",
  182. decision: "trusted",
  183. grantedAt: "2026-08-17T09:00:00.000Z",
  184. eventAtGrant: "SessionStart",
  185. displayCommandAtGrant: "echo hello",
  186. sourcePathAtGrant: ".zcode/config.json",
  187. },
  188. ],
  189. };
  190. const serialized = JSON.stringify(file);
  191. expect(runtimeVerdict(serialized).status).toBe("ok");
  192. writeJson(trustStorePath(home), file);
  193. const loaded = await createHooksService().loadHooks({ workspacePath: workspace });
  194. expect(loaded.hooks[0]?.workspaceHook?.trustState).toBe("trusted_persistent");
  195. expect(loaded.trustStoreCorrupt).toBeUndefined();
  196. });
  197. it("合法文件但记录属于其他 workspace:services 只采纳本 workspace 的 digest", async () => {
  198. const { home, workspace } = setupWorkspaceWithHook();
  199. const first = await createHooksService().loadHooks({ workspacePath: workspace });
  200. const digest = first.workspaceHookSnapshot?.hooks[0]?.hookDeclarationDigest;
  201. const file = {
  202. schemaVersion: 1,
  203. records: [
  204. {
  205. workspaceIdentity: "/another/workspace",
  206. hookDeclarationDigest: digest,
  207. digestAlgorithm: "sha256",
  208. decision: "trusted",
  209. grantedAt: "2026-08-17T09:00:00.000Z",
  210. eventAtGrant: "SessionStart",
  211. displayCommandAtGrant: "echo hello",
  212. sourcePathAtGrant: ".zcode/config.json",
  213. },
  214. ],
  215. };
  216. const serialized = JSON.stringify(file);
  217. expect(runtimeVerdict(serialized).status).toBe("ok");
  218. writeJson(trustStorePath(home), file);
  219. const loaded = await createHooksService().loadHooks({ workspacePath: workspace });
  220. expect(loaded.hooks[0]?.workspaceHook?.trustState).toBe("pending_trust");
  221. expect(loaded.trustStoreCorrupt).toBeUndefined();
  222. });
  223. });