workspace-hook-trust-script-flow.test.ts 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281
  1. // Workspace Hook Trust 端到端集成(docs/specs/workspace-hook-trust.md D23/D24)。
  2. // 真实文件系统 + 真实配置发现 + 真实 Trust store + bootstrap 的 createWorkspaceHookRuntimeSecurity 装配,
  3. // 只用记录型 ExecutionPort 代替进程启动:
  4. // 1) 远程工作区:Settings 预信任 → 通知活跃会话重载 → Hook 执行 → revoke 后阻断;
  5. // 2) 会话中替换或删除已信任脚本:HookRunBlocked、不创建进程;onError: deny 的守卫拦截工具调用。
  6. import { mkdir, mkdtemp, rm, writeFile } from "node:fs/promises";
  7. import { tmpdir } from "node:os";
  8. import { join } from "node:path";
  9. import { afterEach, describe, expect, it, vi } from "vitest";
  10. import {
  11. HookEventName,
  12. SessionEventType,
  13. type ExecutionPort,
  14. type HookInput,
  15. type HookRunLifecyclePayload,
  16. type Logger,
  17. type SessionEvent,
  18. } from "@zcode/contracts";
  19. import { createConfigWithPluginMigrations } from "@zcode/adapters/config";
  20. import { InMemoryWorkspaceHookPolicyProvider, createConfiguredHookRunner } from "@zcode/core";
  21. import { buildRemoteWorkspaceIdentity } from "@zcode/shared";
  22. import { createWorkspaceHookRuntimeSecurity } from "../src/app/workspace-hook-trust.js";
  23. import { grantWorkspaceHookTrust } from "../src/workspace-hook-trust-cli.js";
  24. import { grantWorkspaceHookTrustForProtocol } from "../src/zcode-protocol/workspace-hook-trust.js";
  25. import { notifyWorkspaceHookTrustGrantSessions } from "../src/zcode-protocol/server.js";
  26. const logger: Logger = {
  27. debug: () => undefined,
  28. info: () => undefined,
  29. warn: () => undefined,
  30. error: () => undefined,
  31. child: () => logger,
  32. };
  33. const SSH = { kind: "ssh", host: "example.test", port: 22, username: "coder" } as const;
  34. const roots: string[] = [];
  35. afterEach(async () => {
  36. await Promise.all(roots.splice(0).map((path) => rm(path, { recursive: true, force: true })));
  37. });
  38. async function fixture(event: "SessionStart" | "PreToolUse", hook: Record<string, unknown>) {
  39. const root = await mkdtemp(join(tmpdir(), "zcode-hook-trust-flow-"));
  40. roots.push(root);
  41. const homeDir = join(root, "home");
  42. const workspace = join(root, "workspace");
  43. const userConfigPath = join(homeDir, ".zcode", "cli", "config.json");
  44. await mkdir(join(homeDir, ".zcode", "security"), { recursive: true });
  45. await mkdir(join(homeDir, ".zcode", "cli"), { recursive: true });
  46. await mkdir(join(workspace, ".zcode"), { recursive: true });
  47. await mkdir(join(workspace, ".git"));
  48. // storage.dir 指向测试 HOME:CLI/协议授权与会话装配读写同一个 Trust store,不碰真实 HOME。
  49. await writeFile(
  50. userConfigPath,
  51. JSON.stringify({ storage: { dir: join(homeDir, ".zcode") }, hooks: { enabled: true, events: {} } }),
  52. );
  53. await writeFile(
  54. join(workspace, ".zcode", "config.json"),
  55. JSON.stringify({ hooks: { enabled: true, events: { [event]: [{ hooks: [hook] }] } } }),
  56. );
  57. await writeFile(join(workspace, "hook.sh"), "echo one\n", "utf8");
  58. return { homeDir, userConfigPath, workspace };
  59. }
  60. async function session(input: {
  61. homeDir: string;
  62. userConfigPath: string;
  63. workspace: string;
  64. workspaceKey?: string;
  65. }) {
  66. const config = await createConfigWithPluginMigrations({
  67. env: {},
  68. userConfigPath: input.userConfigPath,
  69. workingDirectory: input.workspace,
  70. ...(input.workspaceKey ? { workspaceIdentity: input.workspaceKey } : {}),
  71. });
  72. const snapshot = config.sources.project.workspaceHookSnapshot;
  73. if (!snapshot) throw new Error("expected workspace hook snapshot");
  74. const security = createWorkspaceHookRuntimeSecurity({
  75. homeDir: input.homeDir,
  76. logger,
  77. policyProvider: new InMemoryWorkspaceHookPolicyProvider(),
  78. reviewHost: { taskId: "task-1", runId: "run-1", workspaceLabel: "workspace" },
  79. emitReviewEvent: async () => undefined,
  80. runtimeRoot: { enabled: true, timeoutMs: 60_000, maxOutputBytes: 32_768 },
  81. sessionId: "sess-flow" as never,
  82. snapshot,
  83. userConfigPath: input.userConfigPath,
  84. workspaceHookTrustEnabled: true,
  85. ...(input.workspaceKey ? { workspaceKey: input.workspaceKey } : {}),
  86. workingDirectory: input.workspace,
  87. });
  88. if (!security) throw new Error("expected runtime security");
  89. const commands: string[] = [];
  90. const events: SessionEvent[] = [];
  91. const executionPort: ExecutionPort = {
  92. async run(request) {
  93. commands.push(
  94. request.command.mode === "shell"
  95. ? request.command.command
  96. : [request.command.file, ...(request.command.args ?? [])].join(" "),
  97. );
  98. const now = new Date();
  99. return {
  100. status: "completed",
  101. exitCode: 0,
  102. stdout: { text: "", bytes: 0, truncated: false },
  103. stderr: { text: "", bytes: 0, truncated: false },
  104. durationMs: 1,
  105. timedOut: false,
  106. cancelled: false,
  107. startedAt: now,
  108. completedAt: now,
  109. };
  110. },
  111. };
  112. const runner = createConfiguredHookRunner({
  113. config: { enabled: true, events: {}, maxOutputBytes: 32_768, timeoutMs: 60_000 },
  114. emitEvent: async (event) => {
  115. events.push(event);
  116. },
  117. executionPort,
  118. getWorkingDirectory: () => input.workspace,
  119. workspaceHookAdmission: security.admission,
  120. workspaceHookSnapshot: security.snapshot,
  121. });
  122. if (!runner) throw new Error("expected configured runner");
  123. await security.admission.activate("startup");
  124. return { commands, events, runner, security, snapshot };
  125. }
  126. function hookInput(event: HookEventName, cwd: string): HookInput {
  127. return {
  128. cwd,
  129. hookEventName: event,
  130. mode: "build",
  131. sessionId: "sess-flow" as never,
  132. source: "startup",
  133. timestamp: new Date().toISOString(),
  134. toolInput: {},
  135. toolName: "Write",
  136. traceId: "trace-flow" as never,
  137. } as HookInput;
  138. }
  139. function lastErrorCode(events: SessionEvent[]): string | undefined {
  140. return (events.at(-1)?.payload as HookRunLifecyclePayload | undefined)?.errorCode;
  141. }
  142. describe("远程工作区:Settings 预信任 → 活跃会话重载 → Hook 执行 → revoke 后阻断", () => {
  143. it("全链路使用 host + 执行目录作为 Trust identity,其他 host 的会话不被通知", async () => {
  144. const value = await fixture("SessionStart", {
  145. type: "process",
  146. command: "sh",
  147. args: ["hook.sh"],
  148. });
  149. const workspaceKey = buildRemoteWorkspaceIdentity(value.workspace, SSH);
  150. const live = await session({ ...value, workspaceKey });
  151. const entry = live.snapshot.hooks[0]!;
  152. expect(live.snapshot.workspaceIdentity).toBe(workspaceKey);
  153. expect(entry.scriptEntry?.state.kind).toBe("file");
  154. // 未信任:阻断,不创建进程。
  155. await live.runner.run(hookInput(HookEventName.SessionStart, value.workspace), {
  156. matchValue: "startup",
  157. });
  158. expect(live.commands).toEqual([]);
  159. expect(lastErrorCode(live.events)).toBe("workspace_hooks_pending_trust");
  160. // Settings 预信任(无 task 的协议入口),store 写在测试 HOME。
  161. const ref = { workspacePath: value.workspace, workspaceIdentity: workspaceKey, workspaceKey };
  162. await expect(
  163. grantWorkspaceHookTrustForProtocol(
  164. {
  165. workspace: ref,
  166. bundleDigest: live.snapshot.bundleDigest,
  167. hookDeclarationDigest: entry.hookDeclarationDigest,
  168. },
  169. {
  170. grant: (input) => grantWorkspaceHookTrust({ ...input, userConfigPath: value.userConfigPath }),
  171. policyProvider: new InMemoryWorkspaceHookPolicyProvider(),
  172. },
  173. ),
  174. ).resolves.toEqual({ accepted: true });
  175. // 授权落盘后按 Trust identity 通知活跃会话重载;其他 host 的同路径会话不受影响。
  176. const otherReload = vi.fn(async () => undefined);
  177. const otherKey = buildRemoteWorkspaceIdentity(value.workspace, {
  178. ...SSH,
  179. host: "other.example.test",
  180. });
  181. await notifyWorkspaceHookTrustGrantSessions({
  182. grantedWorkspace: ref,
  183. sessions: new Map([
  184. ["live", { workspace: ref, app: { reloadWorkspaceHookTrust: () => live.security.reloadTrust() } }],
  185. [
  186. "other",
  187. {
  188. workspace: { workspacePath: value.workspace, workspaceIdentity: otherKey, workspaceKey: otherKey },
  189. app: { reloadWorkspaceHookTrust: otherReload },
  190. },
  191. ],
  192. ]) as never,
  193. });
  194. expect(otherReload).not.toHaveBeenCalled();
  195. await live.runner.run(hookInput(HookEventName.SessionStart, value.workspace), {
  196. matchValue: "startup",
  197. });
  198. expect(live.commands).toEqual(["sh hook.sh"]);
  199. expect(live.events.at(-1)?.type).toBe(SessionEventType.HookRunCompleted);
  200. // revoke 后下一次 dispatch 阻断,不再创建进程。
  201. await expect(
  202. live.security.revokeCurrent({
  203. sessionId: "sess-flow",
  204. workspaceIdentity: workspaceKey,
  205. bundleDigest: live.snapshot.bundleDigest,
  206. hookDeclarationDigests: [entry.hookDeclarationDigest],
  207. }),
  208. ).resolves.toMatchObject({ accepted: true });
  209. await live.runner.run(hookInput(HookEventName.SessionStart, value.workspace), {
  210. matchValue: "startup",
  211. });
  212. expect(live.commands).toEqual(["sh hook.sh"]);
  213. expect(live.events.at(-1)?.type).toBe(SessionEventType.HookRunBlocked);
  214. });
  215. });
  216. describe("会话中替换或删除已信任脚本(真实文件系统)", () => {
  217. async function trustedGuard() {
  218. const value = await fixture("PreToolUse", {
  219. type: "process",
  220. command: "sh",
  221. args: ["hook.sh"],
  222. onError: "deny",
  223. });
  224. const live = await session(value);
  225. const entry = live.snapshot.hooks[0]!;
  226. await grantWorkspaceHookTrust({
  227. workspacePath: value.workspace,
  228. userConfigPath: value.userConfigPath,
  229. hookDeclarationDigests: [entry.hookDeclarationDigest],
  230. });
  231. await live.security.reloadTrust();
  232. const first = await live.runner.run(hookInput(HookEventName.PreToolUse, value.workspace));
  233. expect(live.commands).toEqual(["sh hook.sh"]);
  234. expect(first.permissionBehavior).toBeUndefined();
  235. return { ...value, ...live };
  236. }
  237. it("脚本被替换:HookRunBlocked(declaration_changed),不创建进程,onError: deny 拦截工具", async () => {
  238. const value = await trustedGuard();
  239. await writeFile(join(value.workspace, "hook.sh"), "echo replaced\n", "utf8");
  240. const result = await value.runner.run(hookInput(HookEventName.PreToolUse, value.workspace));
  241. expect(value.commands).toEqual(["sh hook.sh"]);
  242. expect(value.events.at(-1)?.type).toBe(SessionEventType.HookRunBlocked);
  243. expect(lastErrorCode(value.events)).toBe("workspace_hook_declaration_changed");
  244. expect(result.permissionBehavior).toBe("deny");
  245. });
  246. it("脚本被删除:HookRunBlocked(script_unavailable),不创建进程,onError: deny 拦截工具", async () => {
  247. const value = await trustedGuard();
  248. await rm(join(value.workspace, "hook.sh"));
  249. const result = await value.runner.run(hookInput(HookEventName.PreToolUse, value.workspace));
  250. expect(value.commands).toEqual(["sh hook.sh"]);
  251. expect(lastErrorCode(value.events)).toBe("workspace_hook_script_unavailable");
  252. expect(result.permissionBehavior).toBe("deny");
  253. });
  254. // 发现阶段没有可审核的内容,无法证明当前声明就是曾信任的那一条(第七轮 CR 的 DoS),按未信任跳过。
  255. it("下一个会话发现阶段脚本已删除:守卫被跳过,不启动进程,不拦截工具", async () => {
  256. const value = await trustedGuard();
  257. await rm(join(value.workspace, "hook.sh"));
  258. const next = await session(value);
  259. expect(next.snapshot.hooks[0]?.scriptEntry?.state.kind).toBe("missing");
  260. const result = await next.runner.run(hookInput(HookEventName.PreToolUse, value.workspace));
  261. expect(next.commands).toEqual([]);
  262. expect(lastErrorCode(next.events)).toBe("workspace_hook_script_unavailable");
  263. expect(result.permissionBehavior).toBeUndefined();
  264. });
  265. });