workspace-hook-trust-reload.test.ts 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173
  1. import { mkdtemp, readFile, writeFile } from "node:fs/promises";
  2. import { tmpdir } from "node:os";
  3. import { join } from "node:path";
  4. import { afterEach, describe, expect, it } from "vitest";
  5. import { HookEventName, createWorkspaceHookBundleSnapshot } from "@zcode/contracts";
  6. import type { Logger } from "@zcode/contracts";
  7. import { createWorkspaceHookRuntimeSecurity } from "../src/app/workspace-hook-trust.js";
  8. const WORKSPACE = "local:/workspace";
  9. const BUNDLE = "c".repeat(64);
  10. const DIGEST_A = "a".repeat(64);
  11. const logger: Logger = {
  12. debug: () => undefined,
  13. info: () => undefined,
  14. warn: () => undefined,
  15. error: () => undefined,
  16. child: () => logger,
  17. };
  18. // P2 回归:Settings pretrust(无 task)授权写盘后,运行中 session 必须通过
  19. // reloadTrust 把 Trust store 重载进 coordinator 并重发 admission 状态——否则
  20. // 已信任 Hook 继续被拒、banner pendingCount 停留旧值(bug 根因见
  21. // workspace-hook-trust.ts reloadTrust 注释)。
  22. describe("createWorkspaceHookRuntimeSecurity reloadTrust", () => {
  23. const cleanup: (() => Promise<void>)[] = [];
  24. afterEach(async () => {
  25. await Promise.all(cleanup.splice(0).map((fn) => fn()));
  26. });
  27. async function tempHome(): Promise<{ homeDir: string; storePath: string }> {
  28. const homeDir = await mkdtemp(join(tmpdir(), "hook-trust-reload-"));
  29. cleanup.push(async () => {
  30. const { rm } = await import("node:fs/promises");
  31. await rm(homeDir, { recursive: true, force: true });
  32. });
  33. const { mkdir } = await import("node:fs/promises");
  34. const securityDir = join(homeDir, ".zcode", "security");
  35. await mkdir(securityDir, { recursive: true });
  36. const storePath = join(securityDir, "workspace-hook-trust-v1.json");
  37. await writeFile(storePath, JSON.stringify({ schemaVersion: 1, records: [] }), "utf8");
  38. return { homeDir, storePath };
  39. }
  40. function snapshot() {
  41. return createWorkspaceHookBundleSnapshot({
  42. schemaVersion: 1,
  43. workspaceIdentity: WORKSPACE,
  44. discoveredAt: "2026-08-06T00:00:00.000Z",
  45. digestAlgorithm: "sha256",
  46. bundleDigest: BUNDLE,
  47. sourceFiles: [
  48. {
  49. canonicalPath: "/workspace/.zcode/config.json",
  50. baseDir: "/workspace",
  51. discoveryOrder: 0,
  52. configFileKind: ".zcode/config.json",
  53. explicitProjectConfig: false,
  54. editable: true,
  55. hooksRoot: { enabled: true },
  56. },
  57. ],
  58. hooks: [
  59. {
  60. reviewItemId: "item-0",
  61. event: HookEventName.SessionStart,
  62. matcherIndex: 0,
  63. hookIndex: 0,
  64. sourceFileIndex: 0,
  65. sourceRelativePath: ".zcode/config.json",
  66. matcher: "startup",
  67. type: "command",
  68. command: "echo project",
  69. resolvedTimeoutMs: 60_000,
  70. resolvedMaxOutputBytes: 32_768,
  71. declarationEnabled: true,
  72. sourceRootEnabled: true,
  73. runtimeHooksEnabled: true,
  74. configuredEnabled: true,
  75. editable: true,
  76. declarationDigestAlgorithm: "sha256",
  77. hookDeclarationDigest: DIGEST_A,
  78. },
  79. ],
  80. });
  81. }
  82. it("reloads externally granted trust into the live admission and re-emits state", async () => {
  83. const { homeDir, storePath } = await tempHome();
  84. // userConfigPath 指向临时 home 下的空配置:readUserConfig 找不到文件时按空配置处理,
  85. // store 路径 = <homeDir>/.zcode/security/workspace-hook-trust-v1.json。
  86. const userConfigPath = join(homeDir, ".zcode", "cli", "config.json");
  87. const emitted: Array<{ pendingCount: number }> = [];
  88. const security = createWorkspaceHookRuntimeSecurity({
  89. emitAdmissionEvent: async (event) => {
  90. emitted.push({ pendingCount: event.payload.pendingCount });
  91. },
  92. homeDir,
  93. logger,
  94. runtimeRoot: { enabled: true },
  95. sessionId: "sess_test",
  96. snapshot: snapshot(),
  97. userConfigPath,
  98. workspaceHookTrustEnabled: true,
  99. workingDirectory: "/workspace",
  100. });
  101. if (!security) throw new Error("security not created");
  102. await security.admission.activate("startup");
  103. expect(emitted.at(-1)?.pendingCount).toBe(1);
  104. // 模拟 Settings pretrust:另一个写入方直接往 store 文件追加一条 trusted 记录。
  105. const grantTime = new Date().toISOString();
  106. await writeFile(
  107. storePath,
  108. JSON.stringify({
  109. schemaVersion: 1,
  110. records: [
  111. {
  112. workspaceIdentity: WORKSPACE,
  113. hookDeclarationDigest: DIGEST_A,
  114. digestAlgorithm: "sha256",
  115. decision: "trusted",
  116. grantedAt: grantTime,
  117. bundleDigestAtGrant: BUNDLE,
  118. eventAtGrant: "SessionStart",
  119. displayCommandAtGrant: "echo project",
  120. sourcePathAtGrant: ".zcode/config.json",
  121. sourceDiscoveryOrderAtGrant: 0,
  122. matcherAtGrant: "startup",
  123. matcherIndexAtGrant: 0,
  124. hookIndexAtGrant: 0,
  125. },
  126. ],
  127. }),
  128. "utf8",
  129. );
  130. await security.reloadTrust();
  131. // coordinator 已重载:该声明从 pending 变 trusted,admission 重发 pendingCount=0。
  132. expect(emitted.at(-1)?.pendingCount).toBe(0);
  133. expect(
  134. security.admission.evaluateDispatch({
  135. reviewItemId: "item-0",
  136. hookDeclarationDigest: DIGEST_A,
  137. bundleDigest: BUNDLE,
  138. }),
  139. ).toEqual({ allowed: true });
  140. // store 文件未被 reload 路径改写(只读重载)。
  141. const after = JSON.parse(await readFile(storePath, "utf8"));
  142. expect(after.records).toHaveLength(1);
  143. });
  144. it("is a safe no-op when the trust feature is disabled", async () => {
  145. const { homeDir } = await tempHome();
  146. const security = createWorkspaceHookRuntimeSecurity({
  147. homeDir,
  148. logger,
  149. runtimeRoot: { enabled: true },
  150. sessionId: "sess_test",
  151. snapshot: snapshot(),
  152. userConfigPath: join(homeDir, ".zcode", "cli", "config.json"),
  153. workspaceHookTrustEnabled: false,
  154. workingDirectory: "/workspace",
  155. });
  156. if (!security) throw new Error("security not created");
  157. await expect(security.reloadTrust()).resolves.toBeUndefined();
  158. });
  159. });