workspace-hook-trust-protocol.test.ts 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272
  1. import { describe, expect, it, vi } from "vitest";
  2. import { InMemoryWorkspaceHookPolicyProvider } from "@zcode/core";
  3. import { grantWorkspaceHookTrustForProtocol } from "../src/zcode-protocol/workspace-hook-trust.js";
  4. import { notifyWorkspaceHookTrustGrantSessions } from "../src/zcode-protocol/server.js";
  5. const BUNDLE = "b".repeat(64);
  6. const DIGEST = "a".repeat(64);
  7. function userDecidesPolicyProvider(): InMemoryWorkspaceHookPolicyProvider {
  8. return new InMemoryWorkspaceHookPolicyProvider({
  9. mode: "user_decides",
  10. policyRevision: "test:user-decides:v1",
  11. });
  12. }
  13. describe("workspace Hook Trust protocol operation", () => {
  14. it("maps the trusted host workspace request to exact canonical pretrust input", async () => {
  15. const grant = vi.fn(async () => ({
  16. workspacePath: "/repo",
  17. workspaceIdentity: "workspace:repo",
  18. bundleDigest: BUNDLE,
  19. reasonCode: "workspace_hooks_trusted_persistent" as const,
  20. items: [
  21. {
  22. reviewItemId: "item-0",
  23. event: "SessionStart",
  24. matcher: null,
  25. displayCommand: "echo project",
  26. sourcePath: ".zcode/config.json",
  27. configuredEnabled: false,
  28. hookDeclarationDigest: DIGEST,
  29. trustState: "trusted_persistent" as const,
  30. },
  31. ],
  32. }));
  33. await expect(
  34. grantWorkspaceHookTrustForProtocol(
  35. {
  36. workspace: {
  37. workspacePath: "/repo",
  38. workspaceIdentity: "workspace:repo",
  39. workspaceKey: "workspace:repo",
  40. },
  41. bundleDigest: BUNDLE,
  42. hookDeclarationDigest: DIGEST,
  43. },
  44. { appVersion: "test", grant, policyProvider: userDecidesPolicyProvider() },
  45. ),
  46. ).resolves.toEqual({ accepted: true });
  47. expect(grant).toHaveBeenCalledWith({
  48. workspacePath: "/repo",
  49. workspaceIdentity: "workspace:repo",
  50. bundleDigest: BUNDLE,
  51. hookDeclarationDigests: [DIGEST],
  52. appVersion: "test",
  53. });
  54. });
  55. it.each([
  56. {
  57. policy: {
  58. mode: "deny" as const,
  59. reason: "managed",
  60. policyRevision: "test:deny:v1",
  61. },
  62. reasonCode: "workspace_hooks_blocked_by_policy",
  63. },
  64. {
  65. policy: {
  66. mode: "allow_trusted_only" as const,
  67. policyRevision: "test:pretrust:v1",
  68. },
  69. reasonCode: "workspace_hooks_policy_requires_pretrust",
  70. },
  71. ])("rejects Settings pretrust before mutation for $policy.mode", async ({ policy, reasonCode }) => {
  72. const grant = vi.fn();
  73. await expect(
  74. grantWorkspaceHookTrustForProtocol(
  75. {
  76. workspace: {
  77. workspacePath: "/repo",
  78. workspaceIdentity: "workspace:repo",
  79. workspaceKey: "workspace:repo",
  80. },
  81. bundleDigest: BUNDLE,
  82. hookDeclarationDigest: DIGEST,
  83. },
  84. {
  85. grant,
  86. policyProvider: new InMemoryWorkspaceHookPolicyProvider(policy),
  87. },
  88. ),
  89. ).resolves.toEqual({ accepted: false, reasonCode });
  90. expect(grant).not.toHaveBeenCalled();
  91. });
  92. it("fails closed before mutation when the managed policy provider is unavailable", async () => {
  93. const grant = vi.fn();
  94. await expect(
  95. grantWorkspaceHookTrustForProtocol(
  96. {
  97. workspace: { workspacePath: "/repo", workspaceKey: "/repo" },
  98. bundleDigest: BUNDLE,
  99. hookDeclarationDigest: DIGEST,
  100. },
  101. {
  102. grant,
  103. policyProvider: {
  104. getPolicy: () => {
  105. throw new Error("managed policy unavailable");
  106. },
  107. subscribe: () => () => undefined,
  108. },
  109. },
  110. ),
  111. ).resolves.toEqual({
  112. accepted: false,
  113. reasonCode: "workspace_hooks_blocked_by_policy",
  114. });
  115. expect(grant).not.toHaveBeenCalled();
  116. });
  117. it("returns a stable rejection for a known public reason code", async () => {
  118. await expect(
  119. grantWorkspaceHookTrustForProtocol(
  120. {
  121. workspace: { workspacePath: "/repo", workspaceKey: "/repo" },
  122. bundleDigest: BUNDLE,
  123. hookDeclarationDigest: DIGEST,
  124. },
  125. {
  126. policyProvider: userDecidesPolicyProvider(),
  127. grant: vi.fn(async () => {
  128. throw new Error("workspace_hooks_bundle_changed");
  129. }),
  130. },
  131. ),
  132. ).resolves.toEqual({
  133. accepted: false,
  134. reasonCode: "workspace_hooks_bundle_changed",
  135. });
  136. });
  137. it("redacts absolute paths and arbitrary implementation messages from protocol reasonCode", async () => {
  138. const internalMessage =
  139. "Unable to read Workspace Hook config: /Users/alice/private/repo/.zcode/config.json";
  140. const result = await grantWorkspaceHookTrustForProtocol(
  141. {
  142. workspace: { workspacePath: "/repo", workspaceKey: "/repo" },
  143. bundleDigest: BUNDLE,
  144. hookDeclarationDigest: DIGEST,
  145. },
  146. {
  147. policyProvider: userDecidesPolicyProvider(),
  148. grant: vi.fn(async () => {
  149. throw new Error(internalMessage);
  150. }),
  151. },
  152. );
  153. expect(result).toEqual({
  154. accepted: false,
  155. reasonCode: "workspace_hooks_config_unreadable",
  156. });
  157. expect(JSON.stringify(result)).not.toContain("/Users/alice");
  158. expect(JSON.stringify(result)).not.toContain("Unable to read");
  159. });
  160. it("does not trust arbitrary workspace_hooks_ prefixed implementation messages", async () => {
  161. await expect(
  162. grantWorkspaceHookTrustForProtocol(
  163. {
  164. workspace: { workspacePath: "/repo", workspaceKey: "/repo" },
  165. bundleDigest: BUNDLE,
  166. hookDeclarationDigest: DIGEST,
  167. },
  168. {
  169. policyProvider: userDecidesPolicyProvider(),
  170. grant: vi.fn(async () => {
  171. throw new Error("workspace_hooks_internal_path_/Users/alice");
  172. }),
  173. },
  174. ),
  175. ).resolves.toEqual({
  176. accepted: false,
  177. reasonCode: "workspace_hooks_config_unreadable",
  178. });
  179. });
  180. });
  181. // P2 回归:Settings pretrust 授权成功后,server 必须按 workspaceKey 通知同 workspace
  182. // 的全部活跃 session 重载 Trust store(否则运行中 session 的 coordinator 内存镜像
  183. // 停留旧值:已信任 Hook 继续被拒、banner pendingCount 不刷新)。
  184. describe("notifyWorkspaceHookTrustGrantSessions fan-out", () => {
  185. function fakeSessionRecord(workspaceKey: string, workspacePath: string, workspaceIdentity?: string) {
  186. const reload = vi.fn(async () => undefined);
  187. return {
  188. reload,
  189. record: {
  190. app: { reloadWorkspaceHookTrust: reload },
  191. workspace: {
  192. workspaceKey,
  193. workspacePath,
  194. ...(workspaceIdentity ? { workspaceIdentity } : {}),
  195. },
  196. } as never,
  197. };
  198. }
  199. it("notifies every live session of the granted workspace and skips others", async () => {
  200. const grantedA1 = fakeSessionRecord("workspace:repo-a", "/repo-a", "workspace:repo-a");
  201. const grantedA2 = fakeSessionRecord("workspace:repo-a", "/repo-a", "workspace:repo-a");
  202. const otherB = fakeSessionRecord("workspace:repo-b", "/repo-b", "workspace:repo-b");
  203. const sessions = new Map([
  204. ["s-a1", grantedA1.record],
  205. ["s-a2", grantedA2.record],
  206. ["s-b1", otherB.record],
  207. ]);
  208. await notifyWorkspaceHookTrustGrantSessions({
  209. grantedWorkspaceKey: "workspace:repo-a",
  210. sessions,
  211. });
  212. expect(grantedA1.reload).toHaveBeenCalledTimes(1);
  213. expect(grantedA2.reload).toHaveBeenCalledTimes(1);
  214. expect(otherB.reload).not.toHaveBeenCalled();
  215. });
  216. it("is a safe no-op without a granted workspace key", async () => {
  217. const session = fakeSessionRecord("workspace:repo-a", "/repo-a");
  218. await notifyWorkspaceHookTrustGrantSessions({
  219. grantedWorkspaceKey: undefined,
  220. sessions: new Map([["s1", session.record]]),
  221. });
  222. expect(session.reload).not.toHaveBeenCalled();
  223. });
  224. it("waits for all notified sessions before returning", async () => {
  225. let release: (() => void) | undefined;
  226. const gate = new Promise<void>((resolve) => {
  227. release = resolve;
  228. });
  229. const reloadStarted = vi.fn();
  230. const record = {
  231. app: {
  232. reloadWorkspaceHookTrust: () => {
  233. reloadStarted();
  234. return gate;
  235. },
  236. },
  237. workspace: { workspaceKey: "workspace:repo-a", workspacePath: "/repo-a" },
  238. } as never;
  239. const promise = notifyWorkspaceHookTrustGrantSessions({
  240. grantedWorkspaceKey: "workspace:repo-a",
  241. sessions: new Map([["s1", record]]),
  242. });
  243. // fan-out 经 Promise.all 调度:先让微任务跑起来确认 reload 已开始且未完成。
  244. await Promise.resolve();
  245. expect(reloadStarted).toHaveBeenCalledTimes(1);
  246. let settled = false;
  247. void promise.then(() => {
  248. settled = true;
  249. });
  250. release?.();
  251. await promise;
  252. expect(settled).toBe(true);
  253. });
  254. });