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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326
  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("契约 3b:pid 存活且启动时间一致(原实例仍活着)→ 不回收", async () => {
  101. const dir = await root();
  102. const filePath = join(dir, "workspace-hook-trust-v1.json");
  103. const lockPath = `${filePath}.lock`;
  104. const originalStart = Date.now() - 10_000;
  105. await writeFile(
  106. lockPath,
  107. `${JSON.stringify({ pid: process.pid, startTime: originalStart, token: "slow-but-alive" })}\n`,
  108. "utf8",
  109. );
  110. await ageLockBeyond(lockPath, 5_000);
  111. const storeB = createFileWorkspaceHookTrustStore({
  112. filePath,
  113. staleLockMs: 5_000,
  114. lockTimeoutMs: 300,
  115. probeProcessStartTime: async () => originalStart,
  116. });
  117. await expect(storeB.grant([record("/ws/owner-b", DIGEST_A)])).rejects.toThrow(
  118. /Timed out acquiring/,
  119. );
  120. });
  121. it("契约 3c:identity probe 不可用(null)→ 保守不回收,行为与旧版一致", async () => {
  122. const dir = await root();
  123. const filePath = join(dir, "workspace-hook-trust-v1.json");
  124. const lockPath = `${filePath}.lock`;
  125. await writeFile(
  126. lockPath,
  127. `${JSON.stringify({ pid: process.pid, startTime: Date.now() - 60_000, token: "probe-less" })}\n`,
  128. "utf8",
  129. );
  130. await ageLockBeyond(lockPath, 5_000);
  131. const storeB = createFileWorkspaceHookTrustStore({
  132. filePath,
  133. staleLockMs: 5_000,
  134. lockTimeoutMs: 300,
  135. probeProcessStartTime: async () => null,
  136. });
  137. await expect(storeB.grant([record("/ws/owner-b", DIGEST_A)])).rejects.toThrow(
  138. /Timed out acquiring/,
  139. );
  140. });
  141. it("契约 4:owner metadata 写入失败 → 不残留空锁与句柄", async () => {
  142. const dir = await root();
  143. const filePath = join(dir, "workspace-hook-trust-v1.json");
  144. const lockPath = `${filePath}.lock`;
  145. const store = createFileWorkspaceHookTrustStore({
  146. filePath,
  147. writeLockOwnerMetadata: async () => {
  148. throw new Error("disk full while writing lock metadata");
  149. },
  150. });
  151. await expect(store.grant([record("/ws/owner-b", DIGEST_A)])).rejects.toThrow(
  152. /disk full/,
  153. );
  154. // 关键:open("wx") 成功但 metadata 写失败后,必须清理自己刚建的空锁,
  155. // 否则下一个 writer 会读到一个无法解析的无主锁。
  156. await expect(stat(lockPath)).rejects.toMatchObject({ code: "ENOENT" });
  157. // 清理后后续 mutation 可正常进行。
  158. const retry = createFileWorkspaceHookTrustStore({ filePath });
  159. await retry.grant([record("/ws/owner-b", DIGEST_A)]);
  160. const loaded = await retry.load();
  161. expect(loaded.status).toBe("ok");
  162. });
  163. it("契约 1:被回收后恢复的旧 owner 不得删除新持有者的锁", async () => {
  164. const dir = await root();
  165. const filePath = join(dir, "workspace-hook-trust-v1.json");
  166. const lockPath = `${filePath}.lock`;
  167. // A 持锁暂停在临界区内(rename 前)。
  168. const writerAHold = deferred<void>();
  169. const releaseWriterA = deferred<void>();
  170. const storeA = createFileWorkspaceHookTrustStore({
  171. filePath,
  172. beforeRename: async () => {
  173. writerAHold.resolve();
  174. await releaseWriterA.promise;
  175. },
  176. });
  177. const grantA = storeA.grant([record("/ws/owner-a", DIGEST_A)]);
  178. await writerAHold.promise;
  179. // 模拟 A 的锁已被 stale 回收、B 建立了新锁(不同 pid + token):
  180. // 直接覆写锁文件内容为 B 的持有信息。
  181. const lockOfB = `${JSON.stringify({ pid: DEAD_PID, token: "owner-b-token" })}\n`;
  182. await writeFile(lockPath, lockOfB, "utf8");
  183. // 放行 A:其 finally 不得删除 B 的锁。
  184. releaseWriterA.resolve();
  185. await grantA;
  186. const lockContent = await readFile(lockPath, "utf8");
  187. expect(lockContent).toBe(lockOfB);
  188. });
  189. it("契约 2a:超龄但持有进程存活的锁不得被回收(暂停 ≠ 死亡)", async () => {
  190. const dir = await root();
  191. const filePath = join(dir, "workspace-hook-trust-v1.json");
  192. const lockPath = `${filePath}.lock`;
  193. // 手写一把"活着但超龄"的锁:pid = 本进程(存活)。
  194. await writeFile(
  195. lockPath,
  196. `${JSON.stringify({ pid: process.pid, token: "slow-but-alive" })}\n`,
  197. "utf8",
  198. );
  199. await ageLockBeyond(lockPath, 5_000);
  200. // 另一 writer 在 lockTimeoutMs 内必须拿不到锁(不回收活锁)。
  201. const storeB = createFileWorkspaceHookTrustStore({
  202. filePath,
  203. staleLockMs: 5_000,
  204. lockTimeoutMs: 300,
  205. });
  206. await expect(storeB.grant([record("/ws/owner-b", DIGEST_A)])).rejects.toThrow(
  207. /Timed out acquiring/,
  208. );
  209. // 锁原样保留。
  210. expect(await readFile(lockPath, "utf8")).toContain("slow-but-alive");
  211. });
  212. it("契约 2b:持有进程已死亡的超龄锁正常回收,mutation 不被卡死", async () => {
  213. const dir = await root();
  214. const filePath = join(dir, "workspace-hook-trust-v1.json");
  215. const lockPath = `${filePath}.lock`;
  216. // 手写一把"死亡且超龄"的锁(崩溃残留)。
  217. await writeFile(
  218. lockPath,
  219. `${JSON.stringify({ pid: DEAD_PID, token: "dead-owner" })}\n`,
  220. "utf8",
  221. );
  222. await ageLockBeyond(lockPath, 5_000);
  223. const storeB = createFileWorkspaceHookTrustStore({
  224. filePath,
  225. staleLockMs: 5_000,
  226. lockTimeoutMs: 5_000,
  227. });
  228. await storeB.grant([record("/ws/owner-b", DIGEST_A)]);
  229. const loaded = await storeB.load();
  230. expect(loaded.status).toBe("ok");
  231. await expect(stat(lockPath)).rejects.toMatchObject({ code: "ENOENT" });
  232. });
  233. it("契约 2c:旧版本空锁(无 pid 可查)超龄后仍按无主回收,升级不卡死", async () => {
  234. const dir = await root();
  235. const filePath = join(dir, "workspace-hook-trust-v1.json");
  236. const lockPath = `${filePath}.lock`;
  237. await writeFile(lockPath, "", "utf8");
  238. await ageLockBeyond(lockPath, 5_000);
  239. const store = createFileWorkspaceHookTrustStore({
  240. filePath,
  241. staleLockMs: 5_000,
  242. lockTimeoutMs: 5_000,
  243. });
  244. await store.grant([record("/ws/upgraded", DIGEST_A)]);
  245. await expect(stat(lockPath)).rejects.toMatchObject({ code: "ENOENT" });
  246. });
  247. it("正常串行 mutation:锁写入并验证所有权后清理,行为不变", async () => {
  248. const dir = await root();
  249. const filePath = join(dir, "workspace-hook-trust-v1.json");
  250. const lockPath = `${filePath}.lock`;
  251. const store = createFileWorkspaceHookTrustStore({ filePath });
  252. await store.grant([record("/ws/token", DIGEST_A)]);
  253. await expect(stat(lockPath)).rejects.toMatchObject({ code: "ENOENT" });
  254. const loaded = await store.load();
  255. expect(loaded.status).toBe("ok");
  256. });
  257. it("并发 grant/revoke 多 writer:已撤销的记录不得被旧 grant 快照恢复", async () => {
  258. const dir = await root();
  259. const filePath = join(dir, "workspace-hook-trust-v1.json");
  260. const seed = createFileWorkspaceHookTrustStore({ filePath });
  261. await seed.grant([record("/ws/victim", DIGEST_A)]);
  262. const writers = ["/ws/w1", "/ws/w2", "/ws/w3"].map((identity, index) =>
  263. createFileWorkspaceHookTrustStore({
  264. filePath,
  265. staleLockMs: 1,
  266. lockTimeoutMs: 10_000,
  267. }).grant([record(identity, `${String(index + 1).repeat(64)}`)]),
  268. );
  269. const revoker = createFileWorkspaceHookTrustStore({
  270. filePath,
  271. staleLockMs: 1,
  272. lockTimeoutMs: 10_000,
  273. }).revoke({ workspaceIdentity: "/ws/victim" });
  274. await Promise.all([...writers, revoker]);
  275. const final = await createFileWorkspaceHookTrustStore({ filePath }).load();
  276. expect(final.status).toBe("ok");
  277. if (final.status !== "ok") return;
  278. expect(
  279. final.records.some((item) => item.workspaceIdentity === "/ws/victim"),
  280. ).toBe(false);
  281. expect(final.records).toHaveLength(3);
  282. });
  283. });