workspaceHookInlineTrust.test.ts 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311
  1. import type { CommandAck, CommandEnvelope } from "@zcode/shared/zcode-protocol-v4";
  2. import type { Hook } from "@zcode/shared";
  3. import { beforeEach, describe, expect, it, vi } from "vitest";
  4. import { trustWorkspaceHookWithReview } from "@/settings/workspaceHookReviewCommands.js";
  5. import {
  6. useWorkspaceHookReviewStore,
  7. type WorkspaceHookReviewBinding,
  8. } from "@/store/workspaceHookReviewStore.js";
  9. const BUNDLE = "b".repeat(64);
  10. function workspaceHook(): Hook {
  11. return {
  12. id: "workspace-hook-row",
  13. event: "SessionStart",
  14. type: "command",
  15. command: "echo project",
  16. enabled: false,
  17. workspaceHook: {
  18. reviewItemId: "item-0",
  19. workspaceIdentity: "workspace:repo",
  20. bundleDigest: BUNDLE,
  21. hookDeclarationDigest: "a".repeat(64),
  22. sourceFileIndex: 0,
  23. sourceRootEnabled: true,
  24. declarationEnabled: false,
  25. runtimeHooksEnabled: true,
  26. configuredEnabled: false,
  27. sourcePath: ".zcode/config.json",
  28. trustState: "pending_trust",
  29. },
  30. };
  31. }
  32. function reviewBinding(
  33. sendCommand: (envelope: CommandEnvelope) => Promise<CommandAck>,
  34. ): WorkspaceHookReviewBinding {
  35. return {
  36. workspacePath: "/repo",
  37. sendCommand,
  38. request: {
  39. kind: "workspaceHookReview",
  40. reviewFlowId: "flow-1",
  41. generation: 1,
  42. interactionId: "interaction-1",
  43. sessionId: "session-1",
  44. taskId: "task-1",
  45. runId: "run-1",
  46. workspaceIdentity: "workspace:repo",
  47. workspaceLabel: "repo",
  48. bundleDigest: BUNDLE,
  49. createdAt: 1,
  50. deadlineAt: Date.now() + 60_000,
  51. sourceFiles: [],
  52. summary: { eventCount: 1, hookCount: 1, pendingCount: 1 },
  53. items: [
  54. {
  55. reviewItemId: "item-0",
  56. event: "SessionStart",
  57. type: "command",
  58. displayName: "SessionStart",
  59. displayCommand: "echo project",
  60. sourcePath: ".zcode/config.json",
  61. resolvedTimeoutMs: 60_000,
  62. resolvedMaxOutputBytes: 32_768,
  63. executionMode: "foreground",
  64. configuredEnabled: false,
  65. editable: true,
  66. trustState: "pending_trust",
  67. },
  68. ],
  69. warningCode: "workspace_hooks_execute_code",
  70. },
  71. };
  72. }
  73. function accepted(envelope: CommandEnvelope): CommandAck {
  74. return {
  75. commandId: envelope.commandId,
  76. status: "accepted",
  77. revisionAtDecision: 1,
  78. };
  79. }
  80. function failed(envelope: CommandEnvelope, reasonCode: string): CommandAck {
  81. return {
  82. commandId: envelope.commandId,
  83. status: "failed",
  84. reasonCode,
  85. revisionAtDecision: 1,
  86. };
  87. }
  88. beforeEach(() => {
  89. useWorkspaceHookReviewStore.setState({ bindings: {}, commandBindings: {} });
  90. });
  91. describe("workspace Hook Settings inline trust", () => {
  92. it("没有活跃 review 时先 request,再等待同 bundle/item 的 request 后 respond", async () => {
  93. const commandTypes: string[] = [];
  94. const sendCommand = vi.fn(async (envelope: CommandEnvelope) => {
  95. commandTypes.push(envelope.type);
  96. if (envelope.type === "requestWorkspaceHookReview") {
  97. queueMicrotask(() => {
  98. useWorkspaceHookReviewStore.getState().upsert("session-1", reviewBinding(sendCommand));
  99. });
  100. }
  101. return accepted(envelope);
  102. });
  103. useWorkspaceHookReviewStore.getState().connect("session-1", {
  104. sessionId: "session-1",
  105. workspacePath: "/repo",
  106. workspaceIdentity: "workspace:repo",
  107. sendCommand,
  108. });
  109. await expect(
  110. trustWorkspaceHookWithReview({
  111. hook: workspaceHook(),
  112. workspacePath: "/repo",
  113. workspaceIdentity: "workspace:repo",
  114. reviewWaitTimeoutMs: 100,
  115. }),
  116. ).resolves.toEqual({ accepted: true });
  117. expect(commandTypes).toEqual(["requestWorkspaceHookReview", "respondWorkspaceHookReview"]);
  118. expect(sendCommand.mock.calls[0]?.[0].payload).toEqual({
  119. sessionId: "session-1",
  120. workspaceIdentity: "workspace:repo",
  121. bundleDigest: BUNDLE,
  122. });
  123. expect(sendCommand.mock.calls[1]?.[0].payload).toEqual(
  124. expect.objectContaining({
  125. interactionId: "interaction-1",
  126. decision: { action: "trust_selected", reviewItemIds: ["item-0"] },
  127. }),
  128. );
  129. });
  130. it("已有精确 review 时直接 respond,不重复 request", async () => {
  131. const commandTypes: string[] = [];
  132. const sendCommand = vi.fn(async (envelope: CommandEnvelope) => {
  133. commandTypes.push(envelope.type);
  134. return accepted(envelope);
  135. });
  136. useWorkspaceHookReviewStore.getState().upsert("session-1", reviewBinding(sendCommand));
  137. const grantWithoutSession = vi.fn();
  138. await expect(
  139. trustWorkspaceHookWithReview({
  140. hook: workspaceHook(),
  141. workspacePath: "/repo",
  142. workspaceIdentity: "workspace:repo",
  143. grantWithoutSession,
  144. }),
  145. ).resolves.toEqual({ accepted: true });
  146. expect(commandTypes).toEqual(["respondWorkspaceHookReview"]);
  147. expect(grantWithoutSession).not.toHaveBeenCalled();
  148. });
  149. it("等待期间只有错误 bundle 的 review 时有界失败,绝不跨 bundle respond", async () => {
  150. const commandTypes: string[] = [];
  151. const sendCommand = vi.fn(async (envelope: CommandEnvelope) => {
  152. commandTypes.push(envelope.type);
  153. if (envelope.type === "requestWorkspaceHookReview") {
  154. const stale = reviewBinding(sendCommand);
  155. stale.request = { ...stale.request, bundleDigest: "c".repeat(64) };
  156. queueMicrotask(() => {
  157. useWorkspaceHookReviewStore.getState().upsert("session-1", stale);
  158. });
  159. }
  160. return accepted(envelope);
  161. });
  162. useWorkspaceHookReviewStore.getState().connect("session-1", {
  163. sessionId: "session-1",
  164. workspacePath: "/repo",
  165. workspaceIdentity: "workspace:repo",
  166. sendCommand,
  167. });
  168. await expect(
  169. trustWorkspaceHookWithReview({
  170. hook: workspaceHook(),
  171. workspacePath: "/repo",
  172. workspaceIdentity: "workspace:repo",
  173. reviewWaitTimeoutMs: 10,
  174. }),
  175. ).resolves.toEqual({
  176. accepted: false,
  177. reasonCode: "workspace_hooks_interaction_timeout",
  178. });
  179. expect(commandTypes).toEqual(["requestWorkspaceHookReview"]);
  180. });
  181. it.each([
  182. "workspace_hooks_require_trust_capable_host",
  183. "workspace_hooks_snapshot_mismatch",
  184. "workspace_hooks_bundle_changed",
  185. ])("当前 session 无法审核 Settings bundle(%s)时转入 workspace grant", async (reasonCode) => {
  186. const commandTypes: string[] = [];
  187. const sendCommand = vi.fn(async (envelope: CommandEnvelope) => {
  188. commandTypes.push(envelope.type);
  189. return failed(envelope, reasonCode);
  190. });
  191. useWorkspaceHookReviewStore.getState().connect("session-1", {
  192. sessionId: "session-1",
  193. workspacePath: "/repo",
  194. workspaceIdentity: "workspace:repo",
  195. sendCommand,
  196. });
  197. const grantWithoutSession = vi.fn(async () => ({ accepted: true }));
  198. await expect(
  199. trustWorkspaceHookWithReview({
  200. hook: workspaceHook(),
  201. workspacePath: "/repo",
  202. workspaceIdentity: "workspace:repo",
  203. grantWithoutSession,
  204. }),
  205. ).resolves.toEqual({ accepted: true });
  206. expect(commandTypes).toEqual(["requestWorkspaceHookReview"]);
  207. expect(grantWithoutSession).toHaveBeenCalledWith({
  208. workspacePath: "/repo",
  209. workspaceIdentity: "workspace:repo",
  210. bundleDigest: BUNDLE,
  211. hookDeclarationDigest: "a".repeat(64),
  212. });
  213. });
  214. it("当前 session 的其他拒绝不绕过 Runtime authority", async () => {
  215. const sendCommand = vi.fn(async (envelope: CommandEnvelope) =>
  216. failed(envelope, "workspace_hooks_blocked_by_policy"),
  217. );
  218. useWorkspaceHookReviewStore.getState().connect("session-1", {
  219. sessionId: "session-1",
  220. workspacePath: "/repo",
  221. workspaceIdentity: "workspace:repo",
  222. sendCommand,
  223. });
  224. const grantWithoutSession = vi.fn(async () => ({ accepted: true }));
  225. await expect(
  226. trustWorkspaceHookWithReview({
  227. hook: workspaceHook(),
  228. workspacePath: "/repo",
  229. workspaceIdentity: "workspace:repo",
  230. grantWithoutSession,
  231. }),
  232. ).resolves.toEqual({
  233. accepted: false,
  234. reasonCode: "workspace_hooks_blocked_by_policy",
  235. });
  236. expect(grantWithoutSession).not.toHaveBeenCalled();
  237. });
  238. it("当前 session 无法审核且没有 workspace grant authority 时保留原拒绝", async () => {
  239. const sendCommand = vi.fn(async (envelope: CommandEnvelope) =>
  240. failed(envelope, "workspace_hooks_require_trust_capable_host"),
  241. );
  242. useWorkspaceHookReviewStore.getState().connect("session-1", {
  243. sessionId: "session-1",
  244. workspacePath: "/repo",
  245. workspaceIdentity: "workspace:repo",
  246. sendCommand,
  247. });
  248. await expect(
  249. trustWorkspaceHookWithReview({
  250. hook: workspaceHook(),
  251. workspacePath: "/repo",
  252. workspaceIdentity: "workspace:repo",
  253. }),
  254. ).resolves.toEqual({
  255. accepted: false,
  256. reasonCode: "workspace_hooks_require_trust_capable_host",
  257. });
  258. });
  259. it("没有 task/session 时转入 workspace grant,并携带精确 bundle/declaration digest", async () => {
  260. const grantWithoutSession = vi.fn(async () => ({ accepted: true }));
  261. await expect(
  262. trustWorkspaceHookWithReview({
  263. hook: workspaceHook(),
  264. workspacePath: "/repo",
  265. workspaceIdentity: "workspace:repo",
  266. grantWithoutSession,
  267. }),
  268. ).resolves.toEqual({ accepted: true });
  269. expect(grantWithoutSession).toHaveBeenCalledWith({
  270. workspacePath: "/repo",
  271. workspaceIdentity: "workspace:repo",
  272. bundleDigest: BUNDLE,
  273. hookDeclarationDigest: "a".repeat(64),
  274. });
  275. });
  276. it("既无 session binding 又无 workspace grant authority 时仍 fail closed", async () => {
  277. await expect(
  278. trustWorkspaceHookWithReview({
  279. hook: workspaceHook(),
  280. workspacePath: "/repo",
  281. workspaceIdentity: "workspace:repo",
  282. }),
  283. ).resolves.toEqual({
  284. accepted: false,
  285. reasonCode: "workspace_hooks_require_trust_capable_host",
  286. });
  287. });
  288. });