hook-on-error.test.ts 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460
  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(
  184. exitCode: number,
  185. output: { stderr: string; stdout?: string } = { stderr: "guard: cannot read field" },
  186. ): ExecutionPort {
  187. return {
  188. async run() {
  189. const now = new Date();
  190. const stdout = output.stdout ?? "";
  191. return {
  192. status: "completed",
  193. exitCode,
  194. stdout: { text: stdout, bytes: stdout.length, truncated: false },
  195. stderr: { text: output.stderr, bytes: output.stderr.length, truncated: false },
  196. durationMs: 1,
  197. timedOut: false,
  198. cancelled: false,
  199. startedAt: now,
  200. completedAt: now,
  201. };
  202. },
  203. };
  204. }
  205. describe("configured PreToolUse hook onError", () => {
  206. function runnerFor(onError: "allow" | "deny" | undefined, exitCode: number) {
  207. return createConfiguredHookRunner({
  208. config: {
  209. enabled: true,
  210. events: {
  211. PreToolUse: [
  212. {
  213. matcher: "CreateWorkflow",
  214. hooks: [
  215. {
  216. type: "command",
  217. command: "node guard.mjs",
  218. ...(onError === undefined ? {} : { onError }),
  219. },
  220. ],
  221. },
  222. ],
  223. },
  224. maxOutputBytes: 1_024,
  225. timeoutMs: 5_000,
  226. },
  227. executionPort: exitingWith(exitCode),
  228. getWorkingDirectory: () => "/workspace",
  229. });
  230. }
  231. it("carries onError from the settings to the hook: exit 1 denies", async () => {
  232. const result = await runnerFor("deny", 1)?.run(preToolInput(), {
  233. matchValue: "CreateWorkflow",
  234. });
  235. expect(result?.permissionBehavior).toBe("deny");
  236. expect(result?.hookPermissionDecisionReason).toContain("guard: cannot read field");
  237. });
  238. it("lets exit 1 through without onError, and with onError allow", async () => {
  239. for (const onError of [undefined, "allow"] as const) {
  240. const result = await runnerFor(onError, 1)?.run(preToolInput(), {
  241. matchValue: "CreateWorkflow",
  242. });
  243. expect(result?.permissionBehavior).toBeUndefined();
  244. }
  245. });
  246. });
  247. describe("configured PreToolUse hook exit code 2", () => {
  248. function runnerWithOutput(
  249. output: { stderr: string; stdout?: string },
  250. plugin?: { id: string; name: string },
  251. command = "node guard.mjs --strict",
  252. args?: string[],
  253. ) {
  254. const events: SessionEvent[] = [];
  255. const runner = createConfiguredHookRunner({
  256. config: {
  257. enabled: true,
  258. events: {
  259. PreToolUse: [
  260. {
  261. matcher: "CreateWorkflow",
  262. hooks: [
  263. {
  264. ...(args
  265. ? { type: "process" as const, command, args }
  266. : { type: "command" as const, command }),
  267. ...(plugin
  268. ? { plugin: { ...plugin, dataPath: "/data", rootPath: "/plugins/acme" } }
  269. : {}),
  270. },
  271. ],
  272. },
  273. ],
  274. },
  275. maxOutputBytes: 1_024,
  276. timeoutMs: 5_000,
  277. },
  278. emitEvent: async (event) => {
  279. events.push(event);
  280. },
  281. executionPort: exitingWith(2, output),
  282. getWorkingDirectory: () => "/workspace",
  283. });
  284. return { events, runner };
  285. }
  286. it("tells the model a hook blocked the tool and why, without the hook command", async () => {
  287. const { events, runner } = runnerWithOutput({ stderr: "no workflows on main\n" });
  288. const result = await runner?.run(preToolInput(), { matchValue: "CreateWorkflow" });
  289. expect(result?.permissionBehavior).toBe("deny");
  290. expect(result?.hookPermissionDecisionReason).toBe(
  291. "PreToolUse:CreateWorkflow hook error: [command hidden]: no workflows on main",
  292. );
  293. // Hooks 明细不显示命令,仍是 stderr 预览。
  294. const payload = events.at(-1)?.payload as HookRunLifecyclePayload;
  295. expect(payload.blockReason).toBe("no workflows on main");
  296. });
  297. it("writes No stderr output instead of falling back to stdout, and names the plugin", async () => {
  298. const { events, runner } = runnerWithOutput(
  299. { stderr: "", stdout: "diagnostic only" },
  300. { id: "acme@market", name: "acme" },
  301. );
  302. const result = await runner?.run(preToolInput(), { matchValue: "CreateWorkflow" });
  303. expect(result?.hookPermissionDecisionReason).toBe(
  304. "PreToolUse:CreateWorkflow hook error: [command hidden]: No stderr output\nThis hook comes from the acme plugin.",
  305. );
  306. const payload = events.at(-1)?.payload as HookRunLifecyclePayload;
  307. expect(payload.blockReason).toBe("diagnostic only");
  308. });
  309. it("trims stderr and cuts it at 4000 characters", async () => {
  310. const stderr = "x".repeat(5000);
  311. const { runner } = runnerWithOutput({ stderr: ` ${stderr}\n` });
  312. const result = await runner?.run(preToolInput(), { matchValue: "CreateWorkflow" });
  313. expect(result?.hookPermissionDecisionReason).toBe(
  314. `PreToolUse:CreateWorkflow hook error: [command hidden]: ${stderr.slice(0, 4000)}...`,
  315. );
  316. });
  317. it.each([
  318. ["curl -u", "curl -u example-user:EXAMPLE_SECRET https://hooks.example.com/check", undefined],
  319. ["mysql -p", "mysql -pEXAMPLE_SECRET -e 'select 1'", undefined],
  320. ["sshpass -p", "sshpass -p EXAMPLE_SECRET ssh guard@hooks.example.com", undefined],
  321. [
  322. "Cookie header",
  323. "curl -H 'Cookie: session=EXAMPLE_SECRET' https://hooks.example.com",
  324. undefined,
  325. ],
  326. ["process args", "curl", ["-u", "example-user:EXAMPLE_SECRET", "https://hooks.example.com"]],
  327. ])(
  328. "keeps a credential in the hook command (%s) out of the model text",
  329. async (_case, command, args) => {
  330. const { runner } = runnerWithOutput({ stderr: "denied" }, undefined, command, args);
  331. const result = await runner?.run(preToolInput(), { matchValue: "CreateWorkflow" });
  332. // 拒绝理由会进入 tool_result、会话持久化和之后的 provider 请求;脱敏规则覆盖不了这些写法,所以不写命令。
  333. expect(result?.hookPermissionDecisionReason).toBe(
  334. "PreToolUse:CreateWorkflow hook error: [command hidden]: denied",
  335. );
  336. },
  337. );
  338. });
  339. describe("workspace PreToolUse hook onError", () => {
  340. // 工作区 hook 从规范条目重建配置(configured-runner.ts 的 workspaceEntryToHookConfig):
  341. // onError 必须过规范条目的 strict schema、并被带回 registration,否则信任过的 deny 静默失效。
  342. it("carries onError from a trusted canonical entry to the hook", async () => {
  343. const hookSnapshot = createWorkspaceHookBundleSnapshot({
  344. schemaVersion: 1,
  345. workspaceIdentity: "local:/workspace",
  346. discoveredAt: "2026-10-19T00:00:00.000Z",
  347. sourceFiles: [
  348. {
  349. canonicalPath: "/workspace/.zcode/config.json",
  350. baseDir: "/workspace",
  351. discoveryOrder: 0,
  352. configFileKind: ".zcode/config.json",
  353. explicitProjectConfig: false,
  354. editable: true,
  355. hooksRoot: { enabled: true },
  356. },
  357. ],
  358. hooks: [
  359. {
  360. reviewItemId: "item-0",
  361. event: HookEventName.PreToolUse,
  362. matcherIndex: 0,
  363. hookIndex: 0,
  364. sourceFileIndex: 0,
  365. sourceRelativePath: ".zcode/config.json",
  366. matcher: "CreateWorkflow",
  367. type: "command",
  368. command: "node guard.mjs",
  369. onError: "deny",
  370. resolvedTimeoutMs: 60_000,
  371. resolvedMaxOutputBytes: 32_768,
  372. sourceRootEnabled: true,
  373. declarationEnabled: true,
  374. runtimeHooksEnabled: true,
  375. configuredEnabled: true,
  376. editable: true,
  377. declarationDigestAlgorithm: "sha256",
  378. hookDeclarationDigest: "a".repeat(64),
  379. },
  380. ],
  381. digestAlgorithm: "sha256",
  382. bundleDigest: "c".repeat(64),
  383. });
  384. const coordinator = new WorkspaceHookTrustCoordinator({ coordinatorEpoch: "epoch-on-error" });
  385. coordinator.replacePersistentTrustRecords(
  386. createWorkspaceHookTrustRecords({
  387. snapshot: hookSnapshot,
  388. reviewItemIds: ["item-0"],
  389. grantedAt: "2026-10-19T00:00:00.000Z",
  390. }),
  391. { status: "ok" },
  392. );
  393. const admission = createWorkspaceHookRuntimeAdmission({
  394. coordinator,
  395. ready: Promise.resolve(),
  396. snapshot: hookSnapshot,
  397. });
  398. await admission.activate("startup");
  399. const events: SessionEvent[] = [];
  400. const runner = createConfiguredHookRunner({
  401. config: { enabled: true, events: {}, maxOutputBytes: 32_768, timeoutMs: 60_000 },
  402. emitEvent: async (event) => {
  403. events.push(event);
  404. },
  405. executionPort: exitingWith(1),
  406. getWorkingDirectory: () => "/workspace",
  407. workspaceHookAdmission: admission,
  408. workspaceHookSnapshot: hookSnapshot,
  409. });
  410. const result = await runner?.run(preToolInput(), { matchValue: "CreateWorkflow" });
  411. expect(events.at(-1)?.type).toBe(SessionEventType.HookRunBlocked);
  412. expect(result?.permissionBehavior).toBe("deny");
  413. });
  414. });