workspace-hook-trust-domain.test.ts 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247
  1. import { describe, expect, it } from "vitest";
  2. import type { WorkspaceHookBundleSnapshot, WorkspaceHookTrustRecord } from "@zcode/contracts";
  3. import {
  4. WORKSPACE_HOOK_STATE_ADMISSION_MAP,
  5. createWorkspaceHookBundleSnapshot,
  6. } from "@zcode/contracts";
  7. import {
  8. InMemoryWorkspaceHookPolicyProvider,
  9. WorkspaceHookTrustCoordinator,
  10. createWorkspaceHookTrustRecords,
  11. } from "../src/hooks/workspace-hook-trust-domain.js";
  12. const DIGEST_A = "a".repeat(64);
  13. const DIGEST_B = "b".repeat(64);
  14. const BUNDLE = "c".repeat(64);
  15. const WORKSPACE = "local:/workspace";
  16. function snapshot(
  17. entries: Array<{
  18. digest: string;
  19. command: string;
  20. configuredEnabled?: boolean;
  21. hookIndex?: number;
  22. }> = [{ digest: DIGEST_A, command: "echo one" }],
  23. ): WorkspaceHookBundleSnapshot {
  24. return createWorkspaceHookBundleSnapshot({
  25. schemaVersion: 1,
  26. workspaceIdentity: WORKSPACE,
  27. discoveredAt: "2026-08-06T00:00:00.000Z",
  28. sourceFiles: [
  29. {
  30. canonicalPath: "/workspace/.zcode/config.json",
  31. baseDir: "/workspace",
  32. discoveryOrder: 0,
  33. configFileKind: ".zcode/config.json",
  34. explicitProjectConfig: false,
  35. editable: true,
  36. hooksRoot: { enabled: true },
  37. },
  38. ],
  39. hooks: entries.map((entry, index) => ({
  40. reviewItemId: `item-${index}`,
  41. event: "SessionStart",
  42. matcherIndex: 0,
  43. hookIndex: entry.hookIndex ?? index,
  44. sourceFileIndex: 0,
  45. sourceRelativePath: ".zcode/config.json",
  46. matcher: "startup",
  47. type: "command",
  48. command: entry.command,
  49. resolvedTimeoutMs: 60_000,
  50. resolvedMaxOutputBytes: 32_768,
  51. sourceRootEnabled: true,
  52. declarationEnabled: true,
  53. runtimeHooksEnabled: true,
  54. configuredEnabled: entry.configuredEnabled ?? true,
  55. editable: true,
  56. declarationDigestAlgorithm: "sha256",
  57. hookDeclarationDigest: entry.digest,
  58. })),
  59. digestAlgorithm: "sha256",
  60. bundleDigest: BUNDLE,
  61. });
  62. }
  63. function record(digest = DIGEST_A): WorkspaceHookTrustRecord {
  64. return {
  65. workspaceIdentity: WORKSPACE,
  66. hookDeclarationDigest: digest,
  67. digestAlgorithm: "sha256",
  68. decision: "trusted",
  69. grantedAt: "2026-08-06T00:00:00.000Z",
  70. bundleDigestAtGrant: BUNDLE,
  71. eventAtGrant: "SessionStart",
  72. displayCommandAtGrant: "echo one",
  73. sourcePathAtGrant: ".zcode/config.json",
  74. sourceDiscoveryOrderAtGrant: 0,
  75. matcherAtGrant: "startup",
  76. matcherIndexAtGrant: 0,
  77. hookIndexAtGrant: 0,
  78. };
  79. }
  80. describe("WorkspaceHookTrustCoordinator", () => {
  81. it("按 deny > allow_trusted_only > persistent > pending 顺序同步判定", () => {
  82. const policy = new InMemoryWorkspaceHookPolicyProvider();
  83. const coordinator = new WorkspaceHookTrustCoordinator({
  84. coordinatorEpoch: "epoch-1",
  85. policyProvider: policy,
  86. });
  87. coordinator.replacePersistentTrustRecords([record()], { status: "ok" });
  88. expect(coordinator.evaluateSnapshot({ snapshot: snapshot() }).items[0]).toMatchObject({
  89. trustState: "trusted_persistent",
  90. effectiveRunnable: true,
  91. });
  92. policy.setWorkspacePolicy(WORKSPACE, {
  93. mode: "allow_trusted_only",
  94. policyRevision: "managed:1",
  95. });
  96. expect(
  97. coordinator.evaluateSnapshot({
  98. snapshot: snapshot([{ digest: DIGEST_B, command: "echo two" }]),
  99. }).items[0],
  100. ).toMatchObject({ trustState: "blocked_policy", effectiveRunnable: false });
  101. policy.setWorkspacePolicy(WORKSPACE, {
  102. mode: "user_decides",
  103. policyRevision: "managed:2",
  104. });
  105. expect(
  106. coordinator.evaluateSnapshot({
  107. snapshot: snapshot([{ digest: DIGEST_B, command: "echo two" }]),
  108. }).items[0],
  109. ).toMatchObject({ trustState: "stale_digest", effectiveRunnable: false });
  110. policy.setWorkspacePolicy(WORKSPACE, {
  111. mode: "deny",
  112. reason: "organization disabled workspace hooks",
  113. policyRevision: "managed:3",
  114. });
  115. expect(coordinator.evaluateSnapshot({ snapshot: snapshot() }).items[0]).toMatchObject({
  116. trustState: "blocked_policy",
  117. effectiveRunnable: false,
  118. });
  119. });
  120. it("未持久信任不会因同一会话或 coordinator 重建而自动获得准入", () => {
  121. const coordinator = new WorkspaceHookTrustCoordinator({ coordinatorEpoch: "epoch-1" });
  122. expect(coordinator.evaluateSnapshot({ snapshot: snapshot() }).items[0]?.trustState).toBe(
  123. "pending_trust",
  124. );
  125. const restarted = new WorkspaceHookTrustCoordinator({ coordinatorEpoch: "epoch-2" });
  126. expect(restarted.evaluateSnapshot({ snapshot: snapshot() }).items[0]?.trustState).toBe(
  127. "pending_trust",
  128. );
  129. });
  130. it("policy、持久记录与 revoke 都提升 revision,旧 revision 立即失效且 fast path 同步无 I/O", () => {
  131. const policy = new InMemoryWorkspaceHookPolicyProvider();
  132. const coordinator = new WorkspaceHookTrustCoordinator({
  133. coordinatorEpoch: "epoch-1",
  134. policyProvider: policy,
  135. });
  136. const initial = coordinator.getSecurityRevision(WORKSPACE);
  137. coordinator.replacePersistentTrustRecords([record()], { status: "ok" });
  138. const granted = coordinator.getSecurityRevision(WORKSPACE);
  139. expect(granted.counter).toBeGreaterThan(initial.counter);
  140. expect(coordinator.validateSecurityRevision(WORKSPACE, initial)).toBe(false);
  141. expect(coordinator.validateSecurityRevision(WORKSPACE, granted)).toBe(true);
  142. coordinator.revoke({
  143. workspaceIdentity: WORKSPACE,
  144. hookDeclarationDigests: [DIGEST_A],
  145. });
  146. const revoked = coordinator.getSecurityRevision(WORKSPACE);
  147. expect(revoked.counter).toBeGreaterThan(granted.counter);
  148. expect(
  149. coordinator.evaluateSnapshot({ snapshot: snapshot() }).items[0],
  150. ).toMatchObject({
  151. trustState: "revoked",
  152. admissionClass: WORKSPACE_HOOK_STATE_ADMISSION_MAP.revoked.admissionClass,
  153. effectiveRunnable: false,
  154. });
  155. policy.setWorkspacePolicy(WORKSPACE, {
  156. mode: "deny",
  157. reason: "hot update",
  158. policyRevision: "managed:4",
  159. });
  160. expect(coordinator.getSecurityRevision(WORKSPACE).counter).toBeGreaterThan(revoked.counter);
  161. });
  162. it("persistent record 只从 immutable snapshot 和 opaque item id 构造", () => {
  163. const records = createWorkspaceHookTrustRecords({
  164. snapshot: snapshot(),
  165. reviewItemIds: ["item-0"],
  166. grantedAt: "2026-08-06T00:00:00.000Z",
  167. appVersion: "3.6.4",
  168. });
  169. expect(records).toEqual([
  170. expect.objectContaining({
  171. workspaceIdentity: WORKSPACE,
  172. hookDeclarationDigest: DIGEST_A,
  173. sourceDiscoveryOrderAtGrant: 0,
  174. matcherAtGrant: "startup",
  175. matcherIndexAtGrant: 0,
  176. hookIndexAtGrant: 0,
  177. }),
  178. ]);
  179. expect(() =>
  180. createWorkspaceHookTrustRecords({
  181. snapshot: snapshot(),
  182. reviewItemIds: ["renderer-invented-item"],
  183. grantedAt: "2026-08-06T00:00:00.000Z",
  184. }),
  185. ).toThrow("Unknown Workspace Hook review item");
  186. });
  187. it("policy provider 读取失败时 fail closed,且 capability 不允许写 Trust", () => {
  188. const coordinator = new WorkspaceHookTrustCoordinator({
  189. coordinatorEpoch: "epoch-1",
  190. policyProvider: {
  191. getPolicy() {
  192. throw new Error("managed provider unavailable");
  193. },
  194. subscribe() {
  195. return () => undefined;
  196. },
  197. },
  198. });
  199. const evaluation = coordinator.evaluateSnapshot({ snapshot: snapshot() });
  200. expect(evaluation.policy).toMatchObject({ mode: "deny" });
  201. expect(evaluation.items[0]).toMatchObject({
  202. trustState: "blocked_policy",
  203. effectiveRunnable: false,
  204. });
  205. expect(() => coordinator.assertPersistentTrustMutationAllowed(WORKSPACE)).toThrow(
  206. "does not allow persistent Trust mutation",
  207. );
  208. });
  209. it("store 损坏 fail closed,精确 slot 的旧 record 显示 stale_digest", () => {
  210. const coordinator = new WorkspaceHookTrustCoordinator({ coordinatorEpoch: "epoch-1" });
  211. coordinator.replacePersistentTrustRecords([record()], { status: "ok" });
  212. const changed = snapshot([{ digest: DIGEST_B, command: "echo changed", hookIndex: 0 }]);
  213. expect(coordinator.evaluateSnapshot({ snapshot: changed }).items[0]).toMatchObject({
  214. trustState: "stale_digest",
  215. effectiveRunnable: false,
  216. });
  217. coordinator.replacePersistentTrustRecords([], {
  218. status: "corrupt",
  219. recoveredCorruptPath: "/security/store.corrupt-1",
  220. });
  221. const evaluation = coordinator.evaluateSnapshot({ snapshot: snapshot() });
  222. expect(evaluation.storeStatus).toBe("corrupt");
  223. expect(evaluation.reasonCode).toBe("workspace_hooks_trust_store_corrupt");
  224. expect(evaluation.items[0]).toMatchObject({
  225. trustState: "blocked_untrusted",
  226. effectiveRunnable: false,
  227. });
  228. });
  229. });