workspace-hook-script-dispatch.test.ts 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554
  1. import { describe, expect, it } from "vitest";
  2. import {
  3. HookEventName,
  4. SessionEventType,
  5. createWorkspaceHookBundleSnapshot,
  6. type ExecutionPort,
  7. type HookExecutionDescriptor,
  8. type HookInput,
  9. type HookRunLifecyclePayload,
  10. type SessionEvent,
  11. type WorkspaceHookBundleSnapshot,
  12. } from "@zcode/contracts";
  13. import type { WorkspaceHookScriptState } from "@zcode/shared/workspace-hook-discovery";
  14. import {
  15. WorkspaceHookTrustCoordinator,
  16. createConfiguredHookRunner,
  17. createInMemoryHookRunner,
  18. createWorkspaceHookRuntimeAdmission,
  19. createWorkspaceHookTrustRecords,
  20. } from "../src/hooks/index.js";
  21. /**
  22. * D24(ZP-20261110-06):有 scriptEntry 的项目 Hook 派发前复核入口脚本。
  23. * 修复前会话中替换或删除已信任的脚本,后续 dispatch 仍按旧 Trust 启动进程。
  24. */
  25. const WORKSPACE = "/workspace";
  26. const BUNDLE = "c".repeat(64);
  27. const DIGEST = "a".repeat(64);
  28. const TRUSTED_SHA = "1".repeat(64);
  29. function snapshot(state: WorkspaceHookScriptState): WorkspaceHookBundleSnapshot {
  30. return createWorkspaceHookBundleSnapshot({
  31. schemaVersion: 1,
  32. workspaceIdentity: WORKSPACE,
  33. discoveredAt: "2026-11-13T00:00:00.000Z",
  34. sourceFiles: [
  35. {
  36. canonicalPath: "/workspace/.zcode/config.json",
  37. baseDir: "/workspace",
  38. discoveryOrder: 0,
  39. configFileKind: ".zcode/config.json",
  40. explicitProjectConfig: false,
  41. editable: true,
  42. hooksRoot: { enabled: true },
  43. },
  44. ],
  45. hooks: [
  46. {
  47. reviewItemId: "item-0",
  48. event: HookEventName.SessionStart,
  49. matcherIndex: 0,
  50. hookIndex: 0,
  51. sourceFileIndex: 0,
  52. sourceRelativePath: ".zcode/config.json",
  53. matcher: null,
  54. type: "command",
  55. command: "bash .zcode/hook.sh",
  56. resolvedTimeoutMs: 60_000,
  57. resolvedMaxOutputBytes: 32_768,
  58. scriptEntry: { path: ".zcode/hook.sh", state },
  59. sourceRootEnabled: true,
  60. declarationEnabled: true,
  61. runtimeHooksEnabled: true,
  62. configuredEnabled: true,
  63. editable: true,
  64. declarationDigestAlgorithm: "sha256",
  65. hookDeclarationDigest: DIGEST,
  66. },
  67. ],
  68. digestAlgorithm: "sha256",
  69. bundleDigest: BUNDLE,
  70. });
  71. }
  72. function trustedCoordinator(hookSnapshot: WorkspaceHookBundleSnapshot) {
  73. const coordinator = new WorkspaceHookTrustCoordinator({ coordinatorEpoch: "epoch-script" });
  74. coordinator.replacePersistentTrustRecords(
  75. createWorkspaceHookTrustRecords({
  76. snapshot: hookSnapshot,
  77. reviewItemIds: ["item-0"],
  78. grantedAt: "2026-11-13T00:00:00.000Z",
  79. }),
  80. { status: "ok" },
  81. );
  82. return coordinator;
  83. }
  84. function executionPort(commands: string[]): ExecutionPort {
  85. return {
  86. async run(request) {
  87. commands.push(request.command.mode === "shell" ? request.command.command : request.command.file);
  88. const now = new Date("2026-11-13T00:00:00.000Z");
  89. return {
  90. status: "completed",
  91. exitCode: 0,
  92. stdout: { text: "", bytes: 0, truncated: false },
  93. stderr: { text: "", bytes: 0, truncated: false },
  94. durationMs: 1,
  95. timedOut: false,
  96. cancelled: false,
  97. startedAt: now,
  98. completedAt: now,
  99. };
  100. },
  101. };
  102. }
  103. function sessionStartInput(cwd = WORKSPACE): HookInput {
  104. return {
  105. cwd,
  106. hookEventName: HookEventName.SessionStart,
  107. mode: "build",
  108. sessionId: "session-1" as never,
  109. source: "startup",
  110. timestamp: "2026-11-13T00:00:00.000Z",
  111. traceId: "trace-1" as never,
  112. };
  113. }
  114. async function runOnce(input: {
  115. recorded: WorkspaceHookScriptState;
  116. current: WorkspaceHookScriptState | (() => Promise<WorkspaceHookScriptState>);
  117. inject?: boolean;
  118. trusted?: boolean;
  119. beforeResolve?: (coordinator: WorkspaceHookTrustCoordinator) => void;
  120. }) {
  121. const hookSnapshot = snapshot(input.recorded);
  122. const coordinator =
  123. input.trusted === false
  124. ? new WorkspaceHookTrustCoordinator({ coordinatorEpoch: "epoch-script" })
  125. : trustedCoordinator(hookSnapshot);
  126. if (input.trusted === false) coordinator.replacePersistentTrustRecords([], { status: "missing" });
  127. const reads: Array<{ cwd: string; path: string }> = [];
  128. const admission = createWorkspaceHookRuntimeAdmission({
  129. coordinator,
  130. ready: Promise.resolve(),
  131. snapshot: hookSnapshot,
  132. ...(input.inject === false
  133. ? {}
  134. : {
  135. readScriptState: async (cwd: string, path: string) => {
  136. reads.push({ cwd, path });
  137. input.beforeResolve?.(coordinator);
  138. return typeof input.current === "function" ? input.current() : input.current;
  139. },
  140. }),
  141. });
  142. const events: SessionEvent[] = [];
  143. const commands: string[] = [];
  144. const runner = createConfiguredHookRunner({
  145. config: { enabled: true, events: {}, maxOutputBytes: 32_768, timeoutMs: 60_000 },
  146. emitEvent: async (event) => {
  147. events.push(event);
  148. },
  149. executionPort: executionPort(commands),
  150. getWorkingDirectory: () => WORKSPACE,
  151. workspaceHookAdmission: admission,
  152. workspaceHookSnapshot: hookSnapshot,
  153. });
  154. if (!runner) throw new Error("expected configured runner");
  155. await admission.activate("startup");
  156. await runner.run(sessionStartInput("/workspace/sub"), { matchValue: "startup" });
  157. const payload = events[0]?.payload as HookRunLifecyclePayload | undefined;
  158. return { admission, commands, events, payload, reads };
  159. }
  160. describe("Workspace Hook 入口脚本派发前复核(D24)", () => {
  161. it("内容与记录相同:按实际 cwd 复核后执行,命令不变", async () => {
  162. const result = await runOnce({
  163. recorded: { kind: "file", sha256: TRUSTED_SHA },
  164. current: { kind: "file", sha256: TRUSTED_SHA },
  165. });
  166. expect(result.reads).toEqual([{ cwd: "/workspace/sub", path: ".zcode/hook.sh" }]);
  167. expect(result.commands).toEqual(["bash .zcode/hook.sh"]);
  168. expect(result.events[0]?.type).toBe(SessionEventType.HookRunStarted);
  169. });
  170. it("会话中脚本内容变化:HookRunBlocked(declaration_changed),不创建进程", async () => {
  171. const result = await runOnce({
  172. recorded: { kind: "file", sha256: TRUSTED_SHA },
  173. current: { kind: "file", sha256: "2".repeat(64) },
  174. });
  175. expect(result.commands).toEqual([]);
  176. expect(result.events.map((event) => event.type)).toEqual([SessionEventType.HookRunBlocked]);
  177. expect(result.payload?.errorCode).toBe("workspace_hook_declaration_changed");
  178. });
  179. it.each([{ kind: "missing" }, { kind: "unverifiable" }] as const)(
  180. "会话中脚本变为 %j:HookRunBlocked(script_unavailable)",
  181. async (current) => {
  182. const result = await runOnce({
  183. recorded: { kind: "file", sha256: TRUSTED_SHA },
  184. current,
  185. });
  186. expect(result.commands).toEqual([]);
  187. expect(result.payload?.errorCode).toBe("workspace_hook_script_unavailable");
  188. },
  189. );
  190. it("复核期间 revoke:复核返回后重验 admission 并阻断", async () => {
  191. const result = await runOnce({
  192. recorded: { kind: "file", sha256: TRUSTED_SHA },
  193. current: { kind: "file", sha256: TRUSTED_SHA },
  194. beforeResolve: (coordinator) =>
  195. coordinator.revoke({ workspaceIdentity: WORKSPACE, hookDeclarationDigests: [DIGEST] }),
  196. });
  197. expect(result.commands).toEqual([]);
  198. expect(result.payload?.errorCode).toBe("workspace_hooks_revoked");
  199. });
  200. it("没有注入读取端口时 fail closed", async () => {
  201. const result = await runOnce({
  202. recorded: { kind: "file", sha256: TRUSTED_SHA },
  203. current: { kind: "file", sha256: TRUSTED_SHA },
  204. inject: false,
  205. });
  206. expect(result.commands).toEqual([]);
  207. expect(result.payload?.errorCode).toBe("workspace_hook_script_unavailable");
  208. });
  209. it.each([{ kind: "missing" }, { kind: "unverifiable" }] as const)(
  210. "snapshot 记录为 %j:即使存在匹配 record 也 blocked,不计入 pending,不读文件",
  211. async (recorded) => {
  212. const states: number[] = [];
  213. const hookSnapshot = snapshot(recorded);
  214. const admission = createWorkspaceHookRuntimeAdmission({
  215. coordinator: trustedCoordinator(hookSnapshot),
  216. ready: Promise.resolve(),
  217. snapshot: hookSnapshot,
  218. onAdmissionStateChanged: (state) => states.push(state.pendingCount),
  219. readScriptState: async () => {
  220. throw new Error("must not read");
  221. },
  222. });
  223. await admission.activate("startup");
  224. expect(
  225. admission.evaluateDispatch({ hookDeclarationDigest: DIGEST, reviewItemId: "item-0" }),
  226. ).toEqual({ allowed: false, reasonCode: "workspace_hook_script_unavailable" });
  227. expect(states).toEqual([0]);
  228. },
  229. );
  230. });
  231. describe("Hook runner 派发前复核的取消与超时(D24)", () => {
  232. const descriptor: HookExecutionDescriptor = {
  233. clientVisible: true,
  234. commandDisplay: "hook",
  235. executionMode: "foreground",
  236. executionType: "command",
  237. sourceKind: "project",
  238. timeoutMs: 20,
  239. };
  240. it("复核超过 timeoutMs:HookRunBlocked(script_unavailable),callback 不执行", async () => {
  241. const events: SessionEvent[] = [];
  242. let ran = false;
  243. let observedAbort = false;
  244. const runner = createInMemoryHookRunner({
  245. emitEvent: async (event) => {
  246. events.push(event);
  247. },
  248. hooks: [
  249. {
  250. callback: () => {
  251. ran = true;
  252. return undefined;
  253. },
  254. descriptor,
  255. event: HookEventName.SessionStart,
  256. timeoutMs: 20,
  257. verifyBeforeDispatch: (_input, signal) =>
  258. new Promise((resolve) => {
  259. signal.addEventListener("abort", () => {
  260. observedAbort = true;
  261. // 迟到结果必须被忽略。
  262. setTimeout(() => resolve({ allowed: true }), 5);
  263. });
  264. }),
  265. },
  266. ],
  267. });
  268. await runner.run(sessionStartInput());
  269. expect(ran).toBe(false);
  270. expect(observedAbort).toBe(true);
  271. expect(events.map((event) => event.type)).toEqual([SessionEventType.HookRunBlocked]);
  272. expect((events[0]?.payload as HookRunLifecyclePayload).errorCode).toBe(
  273. "workspace_hook_script_unavailable",
  274. );
  275. });
  276. it("父信号已取消:不复核成功也不执行", async () => {
  277. const events: SessionEvent[] = [];
  278. let ran = false;
  279. const controller = new AbortController();
  280. controller.abort();
  281. const runner = createInMemoryHookRunner({
  282. emitEvent: async (event) => {
  283. events.push(event);
  284. },
  285. hooks: [
  286. {
  287. callback: () => {
  288. ran = true;
  289. return undefined;
  290. },
  291. descriptor,
  292. event: HookEventName.SessionStart,
  293. verifyBeforeDispatch: async () => ({ allowed: true }),
  294. },
  295. ],
  296. });
  297. await runner.run(sessionStartInput(), { signal: controller.signal });
  298. expect(ran).toBe(false);
  299. expect((events[0]?.payload as HookRunLifecyclePayload).errorCode).toBe(
  300. "workspace_hook_script_unavailable",
  301. );
  302. });
  303. });
  304. /**
  305. * 第二轮 CR 需确认项:已信任的 PreToolUse 守卫(onError: deny)在脚本被删后,修复前会以非零退出
  306. * 触发 deny;复核前移后曾变成 HookRunBlocked 并放行工具调用。复核失败现在按 Hook 出错处理。
  307. */
  308. describe("派发前复核失败与 onError: deny(D24)", () => {
  309. const descriptor: HookExecutionDescriptor = {
  310. clientVisible: true,
  311. commandDisplay: "guard",
  312. executionMode: "foreground",
  313. executionType: "command",
  314. sourceKind: "project",
  315. timeoutMs: 1_000,
  316. };
  317. function preToolUseInput(): HookInput {
  318. return {
  319. cwd: WORKSPACE,
  320. hookEventName: HookEventName.PreToolUse,
  321. mode: "build",
  322. sessionId: "session-1" as never,
  323. timestamp: "2026-11-13T00:00:00.000Z",
  324. toolInput: {},
  325. toolName: "Write",
  326. traceId: "trace-1" as never,
  327. } as HookInput;
  328. }
  329. function guardRunner(input: {
  330. onError?: "deny";
  331. verify: () => Promise<{ allowed: boolean; reasonCode?: string }>;
  332. admission?: () => { allowed: boolean; reasonCode?: string };
  333. }) {
  334. const events: SessionEvent[] = [];
  335. let ran = false;
  336. const runner = createInMemoryHookRunner({
  337. emitEvent: async (event) => {
  338. events.push(event);
  339. },
  340. hooks: [
  341. {
  342. ...(input.admission ? { admission: input.admission } : {}),
  343. callback: () => {
  344. ran = true;
  345. return undefined;
  346. },
  347. descriptor,
  348. event: HookEventName.PreToolUse,
  349. ...(input.onError ? { onError: input.onError } : {}),
  350. timeoutMs: 1_000,
  351. verifyBeforeDispatch: input.verify,
  352. },
  353. ],
  354. });
  355. return { events, runner, ran: () => ran };
  356. }
  357. it("onError: deny 的守卫复核失败时拦截工具调用,callback 不执行", async () => {
  358. const value = guardRunner({
  359. onError: "deny",
  360. verify: async () => ({ allowed: false, reasonCode: "workspace_hook_script_unavailable" }),
  361. });
  362. const result = await value.runner.run(preToolUseInput());
  363. expect(value.ran()).toBe(false);
  364. expect(result.permissionBehavior).toBe("deny");
  365. const payload = value.events[0]?.payload as HookRunLifecyclePayload;
  366. expect(value.events[0]?.type).toBe(SessionEventType.HookRunBlocked);
  367. expect(payload.errorCode).toBe("workspace_hook_script_unavailable");
  368. expect(payload.blockReason).toContain('onError is "deny"');
  369. });
  370. it("未配置 onError: deny 时复核失败仍只跳过该 Hook", async () => {
  371. const value = guardRunner({
  372. verify: async () => ({ allowed: false, reasonCode: "workspace_hook_declaration_changed" }),
  373. });
  374. const result = await value.runner.run(preToolUseInput());
  375. expect(result.permissionBehavior).toBeUndefined();
  376. });
  377. it("未信任(admission 拒绝)不按出错处理,onError: deny 也不拦截", async () => {
  378. const value = guardRunner({
  379. onError: "deny",
  380. admission: () => ({ allowed: false, reasonCode: "workspace_hooks_pending_trust" }),
  381. verify: async () => ({ allowed: true }),
  382. });
  383. const result = await value.runner.run(preToolUseInput());
  384. expect(result.permissionBehavior).toBeUndefined();
  385. });
  386. });
  387. /**
  388. * 发现阶段入口已不可用:一律按未信任跳过,不按 Hook 出错处理(不触发 onError: deny)。
  389. * 第七轮 CR:曾按“同一位置曾被信任”判断为出错,但只比较展示命令;仓库只改 onError/timeout/shell 并删除
  390. * 脚本,就能把曾信任的普通 Hook 变成拒绝所有工具的守卫(DoS)。发现阶段没有可审核的内容,也就无法
  391. * 证明当前声明就是曾信任的那一条,因此不拦截。会话进行中脚本被删仍由派发前复核按出错处理。
  392. */
  393. describe("发现阶段入口不可用(D24)", () => {
  394. const FILE_DIGEST = "e".repeat(64);
  395. const UNAVAILABLE_DIGEST = "f".repeat(64);
  396. function guardSnapshot(
  397. state: WorkspaceHookScriptState,
  398. digest: string,
  399. command = "bash .zcode/hook.sh",
  400. onError?: "deny",
  401. ): WorkspaceHookBundleSnapshot {
  402. const base = snapshot(state);
  403. return createWorkspaceHookBundleSnapshot({
  404. ...base,
  405. hooks: [
  406. {
  407. ...base.hooks[0]!,
  408. event: HookEventName.PreToolUse,
  409. matcher: null,
  410. ...(onError ? { onError } : {}),
  411. command,
  412. hookDeclarationDigest: digest,
  413. },
  414. ],
  415. });
  416. }
  417. function preToolUseInput(): HookInput {
  418. return {
  419. cwd: WORKSPACE,
  420. hookEventName: HookEventName.PreToolUse,
  421. mode: "build",
  422. sessionId: "session-1" as never,
  423. timestamp: "2026-11-16T00:00:00.000Z",
  424. toolInput: {},
  425. toolName: "Write",
  426. traceId: "trace-1" as never,
  427. } as HookInput;
  428. }
  429. async function run(input: {
  430. state: WorkspaceHookScriptState;
  431. previouslyTrusted: boolean;
  432. trustedCommand?: string;
  433. trustedOnError?: "deny" | "allow";
  434. corrupt?: boolean;
  435. abort?: boolean;
  436. }) {
  437. const current = guardSnapshot(input.state, UNAVAILABLE_DIGEST, undefined, "deny");
  438. const coordinator = new WorkspaceHookTrustCoordinator({ coordinatorEpoch: "epoch-guard" });
  439. coordinator.replacePersistentTrustRecords(
  440. input.previouslyTrusted
  441. ? createWorkspaceHookTrustRecords({
  442. // 用户信任的是脚本存在时的同一声明位置。
  443. snapshot: guardSnapshot(
  444. { kind: "file", sha256: TRUSTED_SHA },
  445. FILE_DIGEST,
  446. input.trustedCommand,
  447. input.trustedOnError === "allow" ? undefined : "deny",
  448. ),
  449. reviewItemIds: ["item-0"],
  450. grantedAt: "2026-11-16T00:00:00.000Z",
  451. })
  452. : [],
  453. { status: input.corrupt ? "corrupt" : "ok" },
  454. );
  455. const admission = createWorkspaceHookRuntimeAdmission({
  456. coordinator,
  457. ready: Promise.resolve(),
  458. snapshot: current,
  459. readScriptState: async () => {
  460. throw new Error("must not read");
  461. },
  462. });
  463. const events: SessionEvent[] = [];
  464. const commands: string[] = [];
  465. const runner = createConfiguredHookRunner({
  466. config: { enabled: true, events: {}, maxOutputBytes: 32_768, timeoutMs: 60_000 },
  467. emitEvent: async (event) => {
  468. events.push(event);
  469. },
  470. executionPort: executionPort(commands),
  471. getWorkingDirectory: () => WORKSPACE,
  472. workspaceHookAdmission: admission,
  473. workspaceHookSnapshot: current,
  474. });
  475. if (!runner) throw new Error("expected configured runner");
  476. await admission.activate("startup");
  477. const controller = new AbortController();
  478. if (input.abort) controller.abort();
  479. const result = await runner.run(preToolUseInput(), { signal: controller.signal });
  480. return { commands, events, result };
  481. }
  482. it.each([{ kind: "missing" }, { kind: "unverifiable" }] as const)(
  483. "曾信任的同一守卫发现时入口为 %j:HookRunBlocked,不启动进程,不拦截工具",
  484. async (state) => {
  485. const value = await run({ state, previouslyTrusted: true });
  486. expect(value.commands).toEqual([]);
  487. expect(value.result.permissionBehavior).toBeUndefined();
  488. expect(value.events[0]?.type).toBe(SessionEventType.HookRunBlocked);
  489. expect((value.events[0]?.payload as HookRunLifecyclePayload).errorCode).toBe(
  490. "workspace_hook_script_unavailable",
  491. );
  492. },
  493. );
  494. // 第七轮 CR 的 DoS 场景:曾信任 onError: allow 的普通 Hook,仓库改成 deny 并删除脚本。
  495. it("曾信任的普通 Hook 被改为 onError: deny 并删除脚本:不拦截工具", async () => {
  496. const value = await run({
  497. state: { kind: "missing" },
  498. previouslyTrusted: true,
  499. trustedOnError: "allow",
  500. });
  501. expect(value.commands).toEqual([]);
  502. expect(value.result.permissionBehavior).toBeUndefined();
  503. });
  504. it("从未信任过的守卫入口不可用:不拦截", async () => {
  505. const value = await run({ state: { kind: "missing" }, previouslyTrusted: false });
  506. expect(value.result.permissionBehavior).toBeUndefined();
  507. });
  508. it("Trust store 损坏时按 store 原因阻断,不按守卫出错处理", async () => {
  509. const value = await run({
  510. state: { kind: "missing" },
  511. previouslyTrusted: true,
  512. corrupt: true,
  513. });
  514. expect(value.result.permissionBehavior).toBeUndefined();
  515. expect((value.events[0]?.payload as HookRunLifecyclePayload).errorCode).toBe(
  516. "workspace_hooks_blocked_untrusted",
  517. );
  518. });
  519. it("用户已取消:不拦截", async () => {
  520. const value = await run({ state: { kind: "missing" }, previouslyTrusted: true, abort: true });
  521. expect(value.result.permissionBehavior).toBeUndefined();
  522. });
  523. });