hook-on-error.test.ts 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351
  1. /**
  2. * PreToolUse hook 的 `onError`(docs/hooks-implementation-analysis.md「执行与输出」)。
  3. *
  4. * hook 自身出错(非 0 且非 2 退出、超时、JSON 不合 schema)时,默认仍放行(fail-open);
  5. * `onError: "deny"` 让这次出错等同于 hook 以退出码 2 拦截。用户中断、未受信任的工作区 hook、
  6. * 非 PreToolUse 事件和 async hook 不受影响。放行时记一条 info 日志,让「放行」也留痕。
  7. */
  8. import { describe, expect, it } from "vitest";
  9. import {
  10. HookEventName,
  11. HookOutcome,
  12. SessionEventType,
  13. createSessionId,
  14. createTraceId,
  15. createTurnId,
  16. createWorkspaceHookBundleSnapshot,
  17. type ExecutionPort,
  18. type HookRunLifecyclePayload,
  19. type Logger,
  20. type SessionEvent,
  21. } from "@zcode/contracts";
  22. import {
  23. WorkspaceHookTrustCoordinator,
  24. createConfiguredHookRunner,
  25. createInMemoryHookRunner,
  26. createWorkspaceHookRuntimeAdmission,
  27. createWorkspaceHookTrustRecords,
  28. } from "../src/hooks/index.js";
  29. import type { HookRegistration } from "../src/hooks/types.js";
  30. function preToolInput() {
  31. return {
  32. cwd: "/workspace",
  33. hookEventName: HookEventName.PreToolUse,
  34. mode: "build" as const,
  35. riskLevel: "low" as const,
  36. sessionId: createSessionId("hook-on-error"),
  37. timestamp: new Date().toISOString(),
  38. toolCallId: "call-1",
  39. toolInput: { script: "return 1;" },
  40. toolName: "CreateWorkflow",
  41. traceId: createTraceId(),
  42. turnId: createTurnId("turn-1"),
  43. };
  44. }
  45. function postToolInput() {
  46. return {
  47. ...preToolInput(),
  48. hookEventName: HookEventName.PostToolUse,
  49. toolResponse: { ok: true },
  50. };
  51. }
  52. const failing: HookRegistration["callback"] = async () => {
  53. throw new Error("guard crashed");
  54. };
  55. function recordingLogger(): { logger: Logger; infos: { message: string; context?: object }[] } {
  56. const infos: { message: string; context?: object }[] = [];
  57. const noop = () => {};
  58. const logger = {
  59. debug: noop,
  60. error: noop,
  61. info: (message: string, context?: object) => infos.push({ message, context }),
  62. warn: noop,
  63. child: () => logger,
  64. } as unknown as Logger;
  65. return { logger, infos };
  66. }
  67. describe("PreToolUse hook onError", () => {
  68. it("keeps the default fail-open: a failing hook does not deny the tool", async () => {
  69. const runner = createInMemoryHookRunner({
  70. hooks: [{ callback: failing, event: HookEventName.PreToolUse, sourceKind: "user" }],
  71. });
  72. const result = await runner.run(preToolInput());
  73. expect(result.permissionBehavior).toBeUndefined();
  74. });
  75. it("denies the tool when a hook with onError deny fails, as an exit code 2 would", async () => {
  76. const events: SessionEvent[] = [];
  77. const runner = createInMemoryHookRunner({
  78. emitEvent: async (event) => {
  79. events.push(event);
  80. },
  81. hooks: [
  82. {
  83. callback: failing,
  84. event: HookEventName.PreToolUse,
  85. onError: "deny",
  86. sourceKind: "user",
  87. },
  88. ],
  89. });
  90. const result = await runner.run(preToolInput());
  91. expect(result.permissionBehavior).toBe("deny");
  92. expect(result.hookPermissionDecisionReason).toContain("guard crashed");
  93. const terminal = events.at(-1);
  94. expect(terminal?.type).toBe(SessionEventType.HookRunBlocked);
  95. const payload = terminal?.payload as HookRunLifecyclePayload;
  96. expect(payload.outcome).toBe(HookOutcome.Blocked);
  97. expect(payload.blockReason).toContain("onError");
  98. expect(payload.errorMessage).toBe("guard crashed");
  99. });
  100. it("denies on a timeout too", async () => {
  101. const runner = createInMemoryHookRunner({
  102. hooks: [
  103. {
  104. callback: () => new Promise<never>(() => {}),
  105. event: HookEventName.PreToolUse,
  106. onError: "deny",
  107. timeoutMs: 1,
  108. },
  109. ],
  110. });
  111. const result = await runner.run(preToolInput());
  112. expect(result.permissionBehavior).toBe("deny");
  113. });
  114. it("does not deny when the user cancelled the hook", async () => {
  115. const controller = new AbortController();
  116. controller.abort("user cancelled");
  117. const runner = createInMemoryHookRunner({
  118. hooks: [
  119. {
  120. callback: () => new Promise<never>(() => {}),
  121. event: HookEventName.PreToolUse,
  122. onError: "deny",
  123. },
  124. ],
  125. });
  126. const result = await runner.run(preToolInput(), { signal: controller.signal });
  127. expect(result.permissionBehavior).toBeUndefined();
  128. });
  129. it("ignores onError on events other than PreToolUse", async () => {
  130. const runner = createInMemoryHookRunner({
  131. hooks: [{ callback: failing, event: HookEventName.PostToolUse, onError: "deny" }],
  132. });
  133. const result = await runner.run(postToolInput());
  134. expect(result.permissionBehavior).toBeUndefined();
  135. expect(result.preventContinuation).toBeUndefined();
  136. });
  137. it("does not deny for an untrusted workspace hook: it never ran", async () => {
  138. const runner = createInMemoryHookRunner({
  139. hooks: [
  140. {
  141. admission: () => ({ allowed: false, reasonCode: "workspace_hook_untrusted" }),
  142. callback: failing,
  143. event: HookEventName.PreToolUse,
  144. onError: "deny",
  145. sourceKind: "project",
  146. },
  147. ],
  148. });
  149. const result = await runner.run(preToolInput());
  150. expect(result.permissionBehavior).toBeUndefined();
  151. });
  152. it("logs an allowed PreToolUse call at info for configured hooks, not for internal ones", async () => {
  153. const { logger, infos } = recordingLogger();
  154. const runner = createInMemoryHookRunner({
  155. hooks: [
  156. {
  157. callback: async () => undefined,
  158. event: HookEventName.PreToolUse,
  159. source: "config.PreToolUse.0.0",
  160. sourceKind: "user",
  161. },
  162. {
  163. callback: async () => undefined,
  164. event: HookEventName.PreToolUse,
  165. sourceKind: "internal",
  166. },
  167. ],
  168. logger,
  169. });
  170. await runner.run(preToolInput());
  171. const allowed = infos.filter(
  172. (entry) => (entry.context as { event?: string } | undefined)?.event === "hook.run.allowed",
  173. );
  174. expect(allowed).toHaveLength(1);
  175. expect(allowed[0]!.context).toMatchObject({
  176. source: "config.PreToolUse.0.0",
  177. sourceKind: "user",
  178. toolCallId: "call-1",
  179. toolName: "CreateWorkflow",
  180. });
  181. });
  182. });
  183. function exitingWith(exitCode: number): ExecutionPort {
  184. return {
  185. async run() {
  186. const now = new Date();
  187. return {
  188. status: "completed",
  189. exitCode,
  190. stdout: { text: "", bytes: 0, truncated: false },
  191. stderr: { text: "guard: cannot read field", bytes: 24, truncated: false },
  192. durationMs: 1,
  193. timedOut: false,
  194. cancelled: false,
  195. startedAt: now,
  196. completedAt: now,
  197. };
  198. },
  199. };
  200. }
  201. describe("configured PreToolUse hook onError", () => {
  202. function runnerFor(onError: "allow" | "deny" | undefined, exitCode: number) {
  203. return createConfiguredHookRunner({
  204. config: {
  205. enabled: true,
  206. events: {
  207. PreToolUse: [
  208. {
  209. matcher: "CreateWorkflow",
  210. hooks: [
  211. {
  212. type: "command",
  213. command: "node guard.mjs",
  214. ...(onError === undefined ? {} : { onError }),
  215. },
  216. ],
  217. },
  218. ],
  219. },
  220. maxOutputBytes: 1_024,
  221. timeoutMs: 5_000,
  222. },
  223. executionPort: exitingWith(exitCode),
  224. getWorkingDirectory: () => "/workspace",
  225. });
  226. }
  227. it("carries onError from the settings to the hook: exit 1 denies", async () => {
  228. const result = await runnerFor("deny", 1)?.run(preToolInput(), {
  229. matchValue: "CreateWorkflow",
  230. });
  231. expect(result?.permissionBehavior).toBe("deny");
  232. expect(result?.hookPermissionDecisionReason).toContain("guard: cannot read field");
  233. });
  234. it("lets exit 1 through without onError, and with onError allow", async () => {
  235. for (const onError of [undefined, "allow"] as const) {
  236. const result = await runnerFor(onError, 1)?.run(preToolInput(), {
  237. matchValue: "CreateWorkflow",
  238. });
  239. expect(result?.permissionBehavior).toBeUndefined();
  240. }
  241. });
  242. });
  243. describe("workspace PreToolUse hook onError", () => {
  244. // 工作区 hook 从规范条目重建配置(configured-runner.ts 的 workspaceEntryToHookConfig):
  245. // onError 必须过规范条目的 strict schema、并被带回 registration,否则信任过的 deny 静默失效。
  246. it("carries onError from a trusted canonical entry to the hook", async () => {
  247. const hookSnapshot = createWorkspaceHookBundleSnapshot({
  248. schemaVersion: 1,
  249. workspaceIdentity: "local:/workspace",
  250. discoveredAt: "2026-10-19T00:00:00.000Z",
  251. sourceFiles: [
  252. {
  253. canonicalPath: "/workspace/.zcode/config.json",
  254. baseDir: "/workspace",
  255. discoveryOrder: 0,
  256. configFileKind: ".zcode/config.json",
  257. explicitProjectConfig: false,
  258. editable: true,
  259. hooksRoot: { enabled: true },
  260. },
  261. ],
  262. hooks: [
  263. {
  264. reviewItemId: "item-0",
  265. event: HookEventName.PreToolUse,
  266. matcherIndex: 0,
  267. hookIndex: 0,
  268. sourceFileIndex: 0,
  269. sourceRelativePath: ".zcode/config.json",
  270. matcher: "CreateWorkflow",
  271. type: "command",
  272. command: "node guard.mjs",
  273. onError: "deny",
  274. resolvedTimeoutMs: 60_000,
  275. resolvedMaxOutputBytes: 32_768,
  276. sourceRootEnabled: true,
  277. declarationEnabled: true,
  278. runtimeHooksEnabled: true,
  279. configuredEnabled: true,
  280. editable: true,
  281. declarationDigestAlgorithm: "sha256",
  282. hookDeclarationDigest: "a".repeat(64),
  283. },
  284. ],
  285. digestAlgorithm: "sha256",
  286. bundleDigest: "c".repeat(64),
  287. });
  288. const coordinator = new WorkspaceHookTrustCoordinator({ coordinatorEpoch: "epoch-on-error" });
  289. coordinator.replacePersistentTrustRecords(
  290. createWorkspaceHookTrustRecords({
  291. snapshot: hookSnapshot,
  292. reviewItemIds: ["item-0"],
  293. grantedAt: "2026-10-19T00:00:00.000Z",
  294. }),
  295. { status: "ok" },
  296. );
  297. const admission = createWorkspaceHookRuntimeAdmission({
  298. coordinator,
  299. ready: Promise.resolve(),
  300. snapshot: hookSnapshot,
  301. });
  302. await admission.activate("startup");
  303. const events: SessionEvent[] = [];
  304. const runner = createConfiguredHookRunner({
  305. config: { enabled: true, events: {}, maxOutputBytes: 32_768, timeoutMs: 60_000 },
  306. emitEvent: async (event) => {
  307. events.push(event);
  308. },
  309. executionPort: exitingWith(1),
  310. getWorkingDirectory: () => "/workspace",
  311. workspaceHookAdmission: admission,
  312. workspaceHookSnapshot: hookSnapshot,
  313. });
  314. const result = await runner?.run(preToolInput(), { matchValue: "CreateWorkflow" });
  315. expect(events.at(-1)?.type).toBe(SessionEventType.HookRunBlocked);
  316. expect(result?.permissionBehavior).toBe("deny");
  317. });
  318. });