workspace-hook-trust-store-lock-ownership.test.ts 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262
  1. import { spawn } from "node:child_process";
  2. import { mkdtemp, readFile, rm, stat, utimes, writeFile } from "node:fs/promises";
  3. import { tmpdir } from "node:os";
  4. import { join } from "node:path";
  5. import { afterEach, describe, expect, it } from "vitest";
  6. import type { WorkspaceHookTrustRecord } from "@zcode/contracts";
  7. import { createFileWorkspaceHookTrustStore } from "../src/storage/workspace-hook-trust-store.js";
  8. /**
  9. * 锁所有权与 stale 回收(CR-02 回归)。
  10. *
  11. * Bug 背景:锁仅依赖固定 .lock 路径 + mtime,锁内容为空、释放时无条件
  12. * unlink,stale 回收仅看年龄。两条危害链:
  13. * 1. 持锁进程 A 被系统休眠/调试暂停超过 staleLockMs 后恢复,其 finally
  14. * 无条件 unlink 会删掉"回收后新持有者 B"的锁,第三个 writer C 得以
  15. * 与 B 并发进入临界区。
  16. * 2. mtime 无法区分"持有者死亡"与"持有者暂停或慢"——A 只是慢就会被 B
  17. * 误回收,A/B 基于不同旧快照 read-modify-write,已提交的 revoke 可能
  18. * 被旧 grant 快照恢复。
  19. *
  20. * 修复契约:
  21. * 1. 锁内容写入 {pid, token};释放前重读并验证 token,不是自己的锁绝不删。
  22. * 2. stale 回收前做 pid 存活检测:持有进程仍存活则不回收(等它自行释放);
  23. * 无法解析(旧版空锁)或 pid 已死才回收。
  24. */
  25. const roots: string[] = [];
  26. const DIGEST_A = "a".repeat(64);
  27. const DEAD_PID = 999_999_999; // 远超典型 pid 上限,进程不存在的概率趋近 1
  28. async function root(): Promise<string> {
  29. const value = await mkdtemp(join(tmpdir(), "zcode-hook-store-lock-"));
  30. roots.push(value);
  31. return value;
  32. }
  33. function record(workspaceIdentity: string, digest: string): WorkspaceHookTrustRecord {
  34. return {
  35. workspaceIdentity,
  36. hookDeclarationDigest: digest,
  37. digestAlgorithm: "sha256",
  38. decision: "trusted",
  39. grantedAt: "2026-08-06T00:00:00.000Z",
  40. eventAtGrant: "SessionStart",
  41. displayCommandAtGrant: "echo trusted",
  42. sourcePathAtGrant: ".zcode/config.json",
  43. sourceDiscoveryOrderAtGrant: 0,
  44. matcherAtGrant: "startup",
  45. matcherIndexAtGrant: 0,
  46. hookIndexAtGrant: 0,
  47. };
  48. }
  49. function deferred<T = void>(): { promise: Promise<T>; resolve: (value: T) => void } {
  50. let resolve!: (value: T) => void;
  51. const promise = new Promise<T>((res) => {
  52. resolve = res;
  53. });
  54. return { promise, resolve };
  55. }
  56. async function ageLockBeyond(lockPath: string, staleLockMs: number): Promise<void> {
  57. const staleTime = new Date(Date.now() - staleLockMs * 12);
  58. await utimes(lockPath, staleTime, staleTime);
  59. }
  60. afterEach(async () => {
  61. await Promise.all(roots.splice(0).map((value) => rm(value, { recursive: true, force: true })));
  62. });
  63. describe("FileWorkspaceHookTrustStore lock ownership(CR-02)", () => {
  64. it("契约 3a(CR-01):pid 存活但启动时间不一致(PID 复用)→ 超龄锁必须被回收", async () => {
  65. const dir = await root();
  66. const filePath = join(dir, "workspace-hook-trust-v1.json");
  67. const lockPath = `${filePath}.lock`;
  68. // 用一个真实存活的外部进程模拟「pid 被复用给无关进程」:锁记录的 pid
  69. // 当前存活(该子进程),但锁内 startTime 属于早已死去的原实例。
  70. const sleeper = spawn(process.execPath, ["-e", "setInterval(() => {}, 60000)"], {
  71. stdio: "ignore",
  72. });
  73. try {
  74. const reusedStartTime = Date.now() - 86_400_000;
  75. await writeFile(
  76. lockPath,
  77. `${JSON.stringify({ pid: sleeper.pid, startTime: reusedStartTime, token: "dead-original" })}\n`,
  78. "utf8",
  79. );
  80. await ageLockBeyond(lockPath, 5_000);
  81. // 注入 identity probe:报告该 pid 当前实例的真实启动时间(与锁内不同)。
  82. const storeB = createFileWorkspaceHookTrustStore({
  83. filePath,
  84. staleLockMs: 5_000,
  85. lockTimeoutMs: 5_000,
  86. probeProcessStartTime: async () => Date.now() - 1_000,
  87. });
  88. await storeB.grant([record("/ws/owner-b", DIGEST_A)]);
  89. const loaded = await storeB.load();
  90. expect(loaded.status).toBe("ok");
  91. await expect(stat(lockPath)).rejects.toMatchObject({ code: "ENOENT" });
  92. } finally {
  93. sleeper.kill();
  94. await new Promise((resolve) => {
  95. sleeper.once("exit", resolve);
  96. setTimeout(resolve, 2_000);
  97. });
  98. }
  99. });
  100. it("契约 4:owner metadata 写入失败 → 不残留空锁与句柄", async () => {
  101. const dir = await root();
  102. const filePath = join(dir, "workspace-hook-trust-v1.json");
  103. const lockPath = `${filePath}.lock`;
  104. const store = createFileWorkspaceHookTrustStore({
  105. filePath,
  106. writeLockOwnerMetadata: async () => {
  107. throw new Error("disk full while writing lock metadata");
  108. },
  109. });
  110. await expect(store.grant([record("/ws/owner-b", DIGEST_A)])).rejects.toThrow(/disk full/);
  111. // 关键:open("wx") 成功但 metadata 写失败后,必须清理自己刚建的空锁,
  112. // 否则下一个 writer 会读到一个无法解析的无主锁。
  113. await expect(stat(lockPath)).rejects.toMatchObject({ code: "ENOENT" });
  114. // 清理后后续 mutation 可正常进行。
  115. const retry = createFileWorkspaceHookTrustStore({ filePath });
  116. await retry.grant([record("/ws/owner-b", DIGEST_A)]);
  117. const loaded = await retry.load();
  118. expect(loaded.status).toBe("ok");
  119. });
  120. it("契约 1:被回收后恢复的旧 owner 不得删除新持有者的锁", async () => {
  121. const dir = await root();
  122. const filePath = join(dir, "workspace-hook-trust-v1.json");
  123. const lockPath = `${filePath}.lock`;
  124. // A 持锁暂停在临界区内(rename 前)。
  125. const writerAHold = deferred<void>();
  126. const releaseWriterA = deferred<void>();
  127. const storeA = createFileWorkspaceHookTrustStore({
  128. filePath,
  129. beforeRename: async () => {
  130. writerAHold.resolve();
  131. await releaseWriterA.promise;
  132. },
  133. });
  134. const grantA = storeA.grant([record("/ws/owner-a", DIGEST_A)]);
  135. await writerAHold.promise;
  136. // 模拟 A 的锁已被 stale 回收、B 建立了新锁(不同 pid + token):
  137. // 直接覆写锁文件内容为 B 的持有信息。
  138. const lockOfB = `${JSON.stringify({ pid: DEAD_PID, token: "owner-b-token" })}\n`;
  139. await writeFile(lockPath, lockOfB, "utf8");
  140. // 放行 A:其 finally 不得删除 B 的锁。
  141. releaseWriterA.resolve();
  142. await grantA;
  143. const lockContent = await readFile(lockPath, "utf8");
  144. expect(lockContent).toBe(lockOfB);
  145. });
  146. it("契约 2a:超龄但持有进程存活的锁不得被回收(暂停 ≠ 死亡)", async () => {
  147. const dir = await root();
  148. const filePath = join(dir, "workspace-hook-trust-v1.json");
  149. const lockPath = `${filePath}.lock`;
  150. // 手写一把"活着但超龄"的锁:pid = 本进程(存活)。
  151. await writeFile(
  152. lockPath,
  153. `${JSON.stringify({ pid: process.pid, token: "slow-but-alive" })}\n`,
  154. "utf8",
  155. );
  156. await ageLockBeyond(lockPath, 5_000);
  157. // 另一 writer 在 lockTimeoutMs 内必须拿不到锁(不回收活锁)。
  158. const storeB = createFileWorkspaceHookTrustStore({
  159. filePath,
  160. staleLockMs: 5_000,
  161. lockTimeoutMs: 300,
  162. });
  163. await expect(storeB.grant([record("/ws/owner-b", DIGEST_A)])).rejects.toThrow(
  164. /Timed out acquiring/,
  165. );
  166. // 锁原样保留。
  167. expect(await readFile(lockPath, "utf8")).toContain("slow-but-alive");
  168. });
  169. it("契约 2b:持有进程已死亡的超龄锁正常回收,mutation 不被卡死", async () => {
  170. const dir = await root();
  171. const filePath = join(dir, "workspace-hook-trust-v1.json");
  172. const lockPath = `${filePath}.lock`;
  173. // 手写一把"死亡且超龄"的锁(崩溃残留)。
  174. await writeFile(
  175. lockPath,
  176. `${JSON.stringify({ pid: DEAD_PID, token: "dead-owner" })}\n`,
  177. "utf8",
  178. );
  179. await ageLockBeyond(lockPath, 5_000);
  180. const storeB = createFileWorkspaceHookTrustStore({
  181. filePath,
  182. staleLockMs: 5_000,
  183. lockTimeoutMs: 5_000,
  184. });
  185. await storeB.grant([record("/ws/owner-b", DIGEST_A)]);
  186. const loaded = await storeB.load();
  187. expect(loaded.status).toBe("ok");
  188. await expect(stat(lockPath)).rejects.toMatchObject({ code: "ENOENT" });
  189. });
  190. it("契约 2c:旧版本空锁(无 pid 可查)超龄后仍按无主回收,升级不卡死", async () => {
  191. const dir = await root();
  192. const filePath = join(dir, "workspace-hook-trust-v1.json");
  193. const lockPath = `${filePath}.lock`;
  194. await writeFile(lockPath, "", "utf8");
  195. await ageLockBeyond(lockPath, 5_000);
  196. const store = createFileWorkspaceHookTrustStore({
  197. filePath,
  198. staleLockMs: 5_000,
  199. lockTimeoutMs: 5_000,
  200. });
  201. await store.grant([record("/ws/upgraded", DIGEST_A)]);
  202. await expect(stat(lockPath)).rejects.toMatchObject({ code: "ENOENT" });
  203. });
  204. it("并发 grant/revoke 多 writer:已撤销的记录不得被旧 grant 快照恢复", async () => {
  205. const dir = await root();
  206. const filePath = join(dir, "workspace-hook-trust-v1.json");
  207. const seed = createFileWorkspaceHookTrustStore({ filePath });
  208. await seed.grant([record("/ws/victim", DIGEST_A)]);
  209. const writers = ["/ws/w1", "/ws/w2", "/ws/w3"].map((identity, index) =>
  210. createFileWorkspaceHookTrustStore({
  211. filePath,
  212. staleLockMs: 1,
  213. lockTimeoutMs: 10_000,
  214. }).grant([record(identity, `${String(index + 1).repeat(64)}`)]),
  215. );
  216. const revoker = createFileWorkspaceHookTrustStore({
  217. filePath,
  218. staleLockMs: 1,
  219. lockTimeoutMs: 10_000,
  220. }).revoke({ workspaceIdentity: "/ws/victim" });
  221. await Promise.all([...writers, revoker]);
  222. const final = await createFileWorkspaceHookTrustStore({ filePath }).load();
  223. expect(final.status).toBe("ok");
  224. if (final.status !== "ok") return;
  225. expect(final.records.some((item) => item.workspaceIdentity === "/ws/victim")).toBe(false);
  226. expect(final.records).toHaveLength(3);
  227. });
  228. });