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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259
  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, SessionEventType, createWorkspaceHookBundleSnapshot } from "@zcode/contracts";
  6. import type { Logger } from "@zcode/contracts";
  7. import { buildRemoteWorkspaceIdentity } from "@zcode/shared";
  8. import { toWorkspaceHookReviewTarget } from "../src/app/workspace-hook-review-request.js";
  9. import { createWorkspaceHookRuntimeSecurity } from "../src/app/workspace-hook-trust.js";
  10. const WORKSPACE = "local:/workspace";
  11. const BUNDLE = "c".repeat(64);
  12. const DIGEST_A = "a".repeat(64);
  13. const logger: Logger = {
  14. debug: () => undefined,
  15. info: () => undefined,
  16. warn: () => undefined,
  17. error: () => undefined,
  18. child: () => logger,
  19. };
  20. // P2 回归:Settings pretrust(无 task)授权写盘后,运行中 session 必须通过
  21. // reloadTrust 把 Trust store 重载进 coordinator 并重发 admission 状态——否则
  22. // 已信任 Hook 继续被拒、banner pendingCount 停留旧值(bug 根因见
  23. // workspace-hook-trust.ts reloadTrust 注释)。
  24. describe("createWorkspaceHookRuntimeSecurity reloadTrust", () => {
  25. const cleanup: (() => Promise<void>)[] = [];
  26. afterEach(async () => {
  27. await Promise.all(cleanup.splice(0).map((fn) => fn()));
  28. });
  29. async function tempHome(): Promise<{ homeDir: string; storePath: string }> {
  30. const homeDir = await mkdtemp(join(tmpdir(), "hook-trust-reload-"));
  31. cleanup.push(async () => {
  32. const { rm } = await import("node:fs/promises");
  33. await rm(homeDir, { recursive: true, force: true });
  34. });
  35. const { mkdir } = await import("node:fs/promises");
  36. const securityDir = join(homeDir, ".zcode", "security");
  37. await mkdir(securityDir, { recursive: true });
  38. const storePath = join(securityDir, "workspace-hook-trust-v1.json");
  39. await writeFile(storePath, JSON.stringify({ schemaVersion: 1, records: [] }), "utf8");
  40. return { homeDir, storePath };
  41. }
  42. function snapshot(workspaceIdentity = WORKSPACE) {
  43. return createWorkspaceHookBundleSnapshot({
  44. schemaVersion: 1,
  45. workspaceIdentity,
  46. discoveredAt: "2026-08-06T00:00:00.000Z",
  47. digestAlgorithm: "sha256",
  48. bundleDigest: BUNDLE,
  49. sourceFiles: [
  50. {
  51. canonicalPath: "/workspace/.zcode/config.json",
  52. baseDir: "/workspace",
  53. discoveryOrder: 0,
  54. configFileKind: ".zcode/config.json",
  55. explicitProjectConfig: false,
  56. editable: true,
  57. hooksRoot: { enabled: true },
  58. },
  59. ],
  60. hooks: [
  61. {
  62. reviewItemId: "item-0",
  63. event: HookEventName.SessionStart,
  64. matcherIndex: 0,
  65. hookIndex: 0,
  66. sourceFileIndex: 0,
  67. sourceRelativePath: ".zcode/config.json",
  68. matcher: "startup",
  69. type: "command",
  70. command: "echo project",
  71. resolvedTimeoutMs: 60_000,
  72. resolvedMaxOutputBytes: 32_768,
  73. declarationEnabled: true,
  74. sourceRootEnabled: true,
  75. runtimeHooksEnabled: true,
  76. configuredEnabled: true,
  77. editable: true,
  78. declarationDigestAlgorithm: "sha256",
  79. hookDeclarationDigest: DIGEST_A,
  80. },
  81. ],
  82. });
  83. }
  84. it("reloads externally granted trust into the live admission and re-emits state", async () => {
  85. const { homeDir, storePath } = await tempHome();
  86. // userConfigPath 指向临时 home 下的空配置:readUserConfig 找不到文件时按空配置处理,
  87. // store 路径 = <homeDir>/.zcode/security/workspace-hook-trust-v1.json。
  88. const userConfigPath = join(homeDir, ".zcode", "cli", "config.json");
  89. const emitted: Array<{ pendingCount: number }> = [];
  90. const security = createWorkspaceHookRuntimeSecurity({
  91. emitAdmissionEvent: async (event) => {
  92. emitted.push({ pendingCount: event.payload.pendingCount });
  93. },
  94. homeDir,
  95. logger,
  96. runtimeRoot: { enabled: true },
  97. sessionId: "sess_test",
  98. snapshot: snapshot(),
  99. userConfigPath,
  100. workspaceHookTrustEnabled: true,
  101. workingDirectory: "/workspace",
  102. });
  103. if (!security) throw new Error("security not created");
  104. await security.admission.activate("startup");
  105. expect(emitted.at(-1)?.pendingCount).toBe(1);
  106. // 模拟 Settings pretrust:另一个写入方直接往 store 文件追加一条 trusted 记录。
  107. const grantTime = new Date().toISOString();
  108. await writeFile(
  109. storePath,
  110. JSON.stringify({
  111. schemaVersion: 1,
  112. records: [
  113. {
  114. workspaceIdentity: WORKSPACE,
  115. hookDeclarationDigest: DIGEST_A,
  116. digestAlgorithm: "sha256",
  117. decision: "trusted",
  118. grantedAt: grantTime,
  119. bundleDigestAtGrant: BUNDLE,
  120. eventAtGrant: "SessionStart",
  121. displayCommandAtGrant: "echo project",
  122. sourcePathAtGrant: ".zcode/config.json",
  123. sourceDiscoveryOrderAtGrant: 0,
  124. matcherAtGrant: "startup",
  125. matcherIndexAtGrant: 0,
  126. hookIndexAtGrant: 0,
  127. },
  128. ],
  129. }),
  130. "utf8",
  131. );
  132. await security.reloadTrust();
  133. // coordinator 已重载:该声明从 pending 变 trusted,admission 重发 pendingCount=0。
  134. expect(emitted.at(-1)?.pendingCount).toBe(0);
  135. expect(
  136. security.admission.evaluateDispatch({
  137. reviewItemId: "item-0",
  138. hookDeclarationDigest: DIGEST_A,
  139. bundleDigest: BUNDLE,
  140. }),
  141. ).toEqual({ allowed: true });
  142. // store 文件未被 reload 路径改写(只读重载)。
  143. const after = JSON.parse(await readFile(storePath, "utf8"));
  144. expect(after.records).toHaveLength(1);
  145. });
  146. it("D23:AdmissionUpdated 对外发会话 workspaceKey,而不是 snapshot 的 Trust identity", async () => {
  147. const { homeDir } = await tempHome();
  148. const workspaceKey = "/data/.zcode/worktrees/3f2a/workspace";
  149. const emitted: Array<{ workspaceIdentity?: string }> = [];
  150. const security = createWorkspaceHookRuntimeSecurity({
  151. emitAdmissionEvent: async (event) => {
  152. emitted.push({ workspaceIdentity: event.payload.workspaceIdentity });
  153. },
  154. homeDir,
  155. logger,
  156. runtimeRoot: { enabled: true },
  157. sessionId: "sess_test",
  158. snapshot: snapshot(),
  159. userConfigPath: join(homeDir, ".zcode", "cli", "config.json"),
  160. workspaceHookTrustEnabled: true,
  161. workspaceKey,
  162. workingDirectory: "/workspace",
  163. });
  164. if (!security) throw new Error("security not created");
  165. await security.admission.activate("startup");
  166. expect(security.snapshot.workspaceIdentity).toBe(WORKSPACE);
  167. expect(emitted.at(-1)).toEqual({ workspaceIdentity: workspaceKey });
  168. });
  169. // 第三轮 CR-02 回归:远程 Trust identity = host + 执行目录。审核目标曾把整个 workspaceKey
  170. // 当作路径解析,得到 host:/remote:… 与 snapshot 永远不等,远程会话的审核与撤销全部失败。
  171. it("远程会话经真实装配链可请求审核、信任与撤销;其他 workspace 的 key 被拒绝", async () => {
  172. const { homeDir } = await tempHome();
  173. const ssh = { kind: "ssh", host: "example.test", port: 22, username: "coder" } as const;
  174. const workspaceKey = buildRemoteWorkspaceIdentity("/workspace/repo", ssh);
  175. const requests: unknown[] = [];
  176. const security = createWorkspaceHookRuntimeSecurity({
  177. emitReviewEvent: async (event) => {
  178. if (event.type === SessionEventType.WorkspaceHookReviewRequested) requests.push(event);
  179. },
  180. homeDir,
  181. logger,
  182. reviewHost: { taskId: "task-1", runId: "run-1", workspaceLabel: "repo" },
  183. runtimeRoot: { enabled: true },
  184. sessionId: "sess_test",
  185. // create-app 由同一 resolver 从执行目录得到 snapshot identity。
  186. snapshot: snapshot(workspaceKey),
  187. userConfigPath: join(homeDir, ".zcode", "cli", "config.json"),
  188. workspaceHookTrustEnabled: true,
  189. workspaceKey,
  190. workingDirectory: "/workspace/repo",
  191. });
  192. if (!security) throw new Error("security not created");
  193. await security.admission.activate("startup");
  194. const otherKey = buildRemoteWorkspaceIdentity("/workspace/other", ssh);
  195. await expect(
  196. security.requestReview({ workspaceIdentity: otherKey, bundleDigest: BUNDLE }),
  197. ).resolves.toEqual({ accepted: false, reasonCode: "workspace_hooks_snapshot_mismatch" });
  198. await expect(
  199. security.requestReview({ workspaceIdentity: workspaceKey, bundleDigest: BUNDLE }),
  200. ).resolves.toMatchObject({ accepted: true });
  201. const request = (requests[0] as { payload: { request: Parameters<typeof toWorkspaceHookReviewTarget>[0] } })
  202. .payload.request;
  203. await expect(
  204. security.respond(toWorkspaceHookReviewTarget(request), {
  205. action: "trust_selected",
  206. reviewItemIds: ["item-0"],
  207. }),
  208. ).resolves.toMatchObject({ accepted: true });
  209. expect(
  210. security.admission.evaluateDispatch({
  211. reviewItemId: "item-0",
  212. hookDeclarationDigest: DIGEST_A,
  213. bundleDigest: BUNDLE,
  214. }),
  215. ).toEqual({ allowed: true });
  216. await expect(
  217. security.revokeCurrent({
  218. sessionId: "sess_test",
  219. workspaceIdentity: workspaceKey,
  220. bundleDigest: BUNDLE,
  221. hookDeclarationDigests: [DIGEST_A],
  222. }),
  223. ).resolves.toMatchObject({ accepted: true });
  224. });
  225. it("is a safe no-op when the trust feature is disabled", async () => {
  226. const { homeDir } = await tempHome();
  227. const security = createWorkspaceHookRuntimeSecurity({
  228. homeDir,
  229. logger,
  230. runtimeRoot: { enabled: true },
  231. sessionId: "sess_test",
  232. snapshot: snapshot(),
  233. userConfigPath: join(homeDir, ".zcode", "cli", "config.json"),
  234. workspaceHookTrustEnabled: false,
  235. workingDirectory: "/workspace",
  236. });
  237. if (!security) throw new Error("security not created");
  238. await expect(security.reloadTrust()).resolves.toBeUndefined();
  239. });
  240. });