workspace-hook-trust-store.test.ts 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198
  1. import { chmod, mkdir, mkdtemp, readFile, readdir, rename, rm, stat, writeFile } from "node:fs/promises";
  2. import { tmpdir } from "node:os";
  3. import { join } from "node:path";
  4. import { afterEach, describe, expect, it, vi } from "vitest";
  5. import type { WorkspaceHookTrustRecord } from "@zcode/contracts";
  6. import {
  7. createFileWorkspaceHookTrustStore,
  8. resolveWorkspaceHookTrustStorePath,
  9. } from "../src/storage/workspace-hook-trust-store.js";
  10. const roots: string[] = [];
  11. const DIGEST_A = "a".repeat(64);
  12. const DIGEST_B = "b".repeat(64);
  13. async function root(): Promise<string> {
  14. const value = await mkdtemp(join(tmpdir(), "zcode-workspace-hook-store-"));
  15. roots.push(value);
  16. return value;
  17. }
  18. function record(
  19. workspaceIdentity: string,
  20. digest: string,
  21. grantedAt = "2026-08-06T00:00:00.000Z",
  22. ): WorkspaceHookTrustRecord {
  23. return {
  24. workspaceIdentity,
  25. hookDeclarationDigest: digest,
  26. digestAlgorithm: "sha256",
  27. decision: "trusted",
  28. grantedAt,
  29. eventAtGrant: "SessionStart",
  30. displayCommandAtGrant: "echo trusted",
  31. sourcePathAtGrant: ".zcode/config.json",
  32. sourceDiscoveryOrderAtGrant: 0,
  33. matcherAtGrant: "startup",
  34. matcherIndexAtGrant: 0,
  35. hookIndexAtGrant: 0,
  36. };
  37. }
  38. afterEach(async () => {
  39. await Promise.all(roots.splice(0).map((value) => rm(value, { recursive: true, force: true })));
  40. });
  41. describe("FileWorkspaceHookTrustStore", () => {
  42. it("只使用 user config storage.dir,不接受 project/env storage 覆盖", async () => {
  43. const home = await root();
  44. const custom = join(home, "trusted-user-storage");
  45. await mkdir(join(home, ".zcode", "cli"), { recursive: true });
  46. await writeFile(
  47. join(home, ".zcode", "cli", "config.json"),
  48. JSON.stringify({ storage: { dir: custom } }),
  49. "utf8",
  50. );
  51. await expect(resolveWorkspaceHookTrustStorePath({ homeDir: home })).resolves.toBe(
  52. join(custom, "security", "workspace-hook-trust-v1.json"),
  53. );
  54. });
  55. it("selected/all grant 单次原子提交,文件和目录权限保持 user-only", async () => {
  56. const base = await root();
  57. const path = join(base, "security", "workspace-hook-trust-v1.json");
  58. const store = createFileWorkspaceHookTrustStore({ filePath: path });
  59. await store.grant([record("workspace:a", DIGEST_A), record("workspace:a", DIGEST_B)]);
  60. const loaded = await store.load();
  61. expect(loaded.status).toBe("ok");
  62. expect(loaded.records).toHaveLength(2);
  63. expect((await stat(path)).mode & 0o777).toBe(0o600);
  64. expect((await stat(join(base, "security"))).mode & 0o777).toBe(0o700);
  65. expect((await readdir(join(base, "security"))).filter((name) => name.endsWith(".tmp"))).toEqual(
  66. [],
  67. );
  68. });
  69. it("并发 grant 持锁重读,不丢失任一进程内 mutation", async () => {
  70. const base = await root();
  71. const path = join(base, "security", "workspace-hook-trust-v1.json");
  72. const first = createFileWorkspaceHookTrustStore({ filePath: path });
  73. const second = createFileWorkspaceHookTrustStore({ filePath: path });
  74. await Promise.all([
  75. first.grant([record("workspace:a", DIGEST_A)]),
  76. second.grant([record("workspace:b", DIGEST_B)]),
  77. ]);
  78. const loaded = await first.load();
  79. expect(loaded.records.map((item) => item.workspaceIdentity).sort()).toEqual([
  80. "workspace:a",
  81. "workspace:b",
  82. ]);
  83. });
  84. it("rename 前失败保留原 store,并清理 temp/lock", async () => {
  85. const base = await root();
  86. const path = join(base, "security", "workspace-hook-trust-v1.json");
  87. const healthy = createFileWorkspaceHookTrustStore({ filePath: path });
  88. await healthy.grant([record("workspace:a", DIGEST_A)]);
  89. const failing = createFileWorkspaceHookTrustStore({
  90. filePath: path,
  91. beforeRename() {
  92. throw new Error("injected before rename");
  93. },
  94. });
  95. await expect(failing.grant([record("workspace:b", DIGEST_B)])).rejects.toThrow(
  96. "injected before rename",
  97. );
  98. await expect(healthy.load()).resolves.toMatchObject({
  99. status: "ok",
  100. records: [{ workspaceIdentity: "workspace:a" }],
  101. });
  102. expect(await readdir(join(base, "security"))).toEqual(["workspace-hook-trust-v1.json"]);
  103. });
  104. it("损坏文件备份后 fail closed,新的显式 grant 才创建干净 store", async () => {
  105. const base = await root();
  106. const path = join(base, "security", "workspace-hook-trust-v1.json");
  107. await mkdir(join(base, "security"), { recursive: true });
  108. await chmod(join(base, "security"), 0o700);
  109. await writeFile(path, "{broken", { encoding: "utf8", mode: 0o600 });
  110. const store = createFileWorkspaceHookTrustStore({
  111. filePath: path,
  112. now: () => 1_786_060_800_000,
  113. });
  114. const corrupt = await store.load();
  115. expect(corrupt).toMatchObject({ status: "corrupt", records: [] });
  116. expect(corrupt.recoveredCorruptPath).toContain(".corrupt-1786060800000");
  117. await expect(readFile(corrupt.recoveredCorruptPath!, "utf8")).resolves.toBe("{broken");
  118. await store.grant([record("workspace:a", DIGEST_A)]);
  119. await expect(store.load()).resolves.toMatchObject({
  120. status: "ok",
  121. records: [
  122. {
  123. workspaceIdentity: "workspace:a",
  124. },
  125. ],
  126. });
  127. });
  128. it("revoke 与 GC 原子执行,保留 current digest 和刚建立记录", async () => {
  129. const base = await root();
  130. const path = join(base, "security", "workspace-hook-trust-v1.json");
  131. const store = createFileWorkspaceHookTrustStore({ filePath: path });
  132. await store.grant([
  133. record("workspace:a", DIGEST_A, "2025-01-01T00:00:00.000Z"),
  134. record("workspace:a", DIGEST_B, "2026-08-06T00:00:00.000Z"),
  135. ]);
  136. await store.revoke({ workspaceIdentity: "workspace:a", hookDeclarationDigests: [DIGEST_A] });
  137. await store.compact({
  138. current: [{ workspaceIdentity: "workspace:a", hookDeclarationDigest: DIGEST_B }],
  139. maxAgeMs: 1,
  140. maxRecords: 1,
  141. now: Date.parse("2026-08-06T01:00:00.000Z"),
  142. });
  143. const loaded = await store.load();
  144. expect(loaded.records.map((item) => item.hookDeclarationDigest)).toEqual([DIGEST_B]);
  145. });
  146. it("revoke 拒绝空 digest 数组,undefined 仍表示撤销 workspace 全部记录", async () => {
  147. const base = await root();
  148. const path = join(base, "security", "workspace-hook-trust-v1.json");
  149. const store = createFileWorkspaceHookTrustStore({ filePath: path });
  150. await store.grant([record("workspace:a", DIGEST_A), record("workspace:a", DIGEST_B)]);
  151. await expect(
  152. store.revoke({ workspaceIdentity: "workspace:a", hookDeclarationDigests: [] }),
  153. ).rejects.toThrow("hookDeclarationDigests must be undefined or non-empty");
  154. await expect(store.load()).resolves.toMatchObject({ status: "ok", records: expect.any(Array) });
  155. expect((await store.load()).records).toHaveLength(2);
  156. await store.revoke({ workspaceIdentity: "workspace:a" });
  157. expect((await store.load()).records).toHaveLength(0);
  158. });
  159. it("Windows 短暂占用导致 rename EPERM 时按有界延迟重试", async () => {
  160. const base = await root();
  161. const path = join(base, "security", "workspace-hook-trust-v1.json");
  162. const renameFile = vi
  163. .fn<typeof rename>()
  164. .mockRejectedValueOnce(Object.assign(new Error("temporarily busy"), { code: "EPERM" }))
  165. .mockImplementation(rename);
  166. const store = createFileWorkspaceHookTrustStore({
  167. filePath: path,
  168. renameFile,
  169. renameRetryDelaysMs: [0],
  170. });
  171. await store.grant([record("workspace:a", DIGEST_A)]);
  172. expect(renameFile).toHaveBeenCalledTimes(2);
  173. await expect(store.load()).resolves.toMatchObject({
  174. status: "ok",
  175. records: [{ hookDeclarationDigest: DIGEST_A }],
  176. });
  177. });
  178. });