workspace-hook-trust-managed-worktree.test.ts 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202
  1. // CLI 侧 Hook Trust identity 接入(docs/specs/workspace-hook-trust.md D23,docs/git/worktree.md §6.2)。
  2. // 真实 git 临时仓库 + ZCODE_DATA_BASE_DIR 临时目录,按 <dataBaseDir>/.zcode/worktrees/<4hex>/<repo>
  3. // 布局创建受管 worktree,验证 Trust CLI、协议授予与活跃 session 重载都按 Trust identity 工作。
  4. import { execFile } from "node:child_process";
  5. import { mkdir, mkdtemp, realpath, rm, writeFile } from "node:fs/promises";
  6. import { tmpdir } from "node:os";
  7. import { join } from "node:path";
  8. import { promisify } from "node:util";
  9. import { afterEach, describe, expect, it, vi } from "vitest";
  10. import { InMemoryWorkspaceHookPolicyProvider } from "@zcode/core";
  11. import {
  12. grantWorkspaceHookTrust,
  13. inspectWorkspaceHookTrust,
  14. } from "../src/workspace-hook-trust-cli.js";
  15. import { grantWorkspaceHookTrustForProtocol } from "../src/zcode-protocol/workspace-hook-trust.js";
  16. import { notifyWorkspaceHookTrustGrantSessions } from "../src/zcode-protocol/server.js";
  17. const execFileAsync = promisify(execFile);
  18. const roots: string[] = [];
  19. const BUCKET = "3f2a";
  20. const REPO = "repo";
  21. afterEach(async () => {
  22. vi.unstubAllEnvs();
  23. await Promise.all(roots.splice(0).map((path) => rm(path, { recursive: true, force: true })));
  24. });
  25. async function git(cwd: string, ...args: string[]): Promise<void> {
  26. await execFileAsync(
  27. "git",
  28. ["-c", "user.name=ZCode Test", "-c", "user.email=test@example.com", ...args],
  29. { cwd },
  30. );
  31. }
  32. async function fixture() {
  33. // resolver 按 realpath 判定;macOS 临时目录是软链,fixture 统一用 realpath。
  34. const root = await realpath(await mkdtemp(join(tmpdir(), "zcode-hook-trust-worktree-")));
  35. roots.push(root);
  36. const source = join(root, "projects", REPO);
  37. const dataBaseDir = join(root, "data");
  38. const worktree = join(dataBaseDir, ".zcode", "worktrees", BUCKET, REPO);
  39. const userConfigPath = join(root, "config.json");
  40. await writeFile(
  41. userConfigPath,
  42. JSON.stringify({
  43. storage: { dir: join(root, "user-data") },
  44. hooks: { enabled: true, events: {} },
  45. }),
  46. );
  47. await mkdir(join(source, ".zcode"), { recursive: true });
  48. await writeFile(
  49. join(source, ".zcode", "config.json"),
  50. JSON.stringify({
  51. hooks: {
  52. enabled: true,
  53. events: {
  54. SessionStart: [
  55. { matcher: "startup", hooks: [{ type: "command", command: "./start.sh" }] },
  56. ],
  57. },
  58. },
  59. }),
  60. );
  61. await git(source, "init", "-q");
  62. await git(source, "add", ".");
  63. await git(source, "commit", "-q", "-m", "init");
  64. await mkdir(join(dataBaseDir, ".zcode", "worktrees", BUCKET), { recursive: true });
  65. await git(source, "worktree", "add", "-q", "--detach", worktree);
  66. const env = { ZCODE_DATA_BASE_DIR: dataBaseDir };
  67. return { dataBaseDir, env, root, source, userConfigPath, worktree };
  68. }
  69. async function trustSourceHook(value: Awaited<ReturnType<typeof fixture>>) {
  70. const pending = await inspectWorkspaceHookTrust({
  71. workspacePath: value.source,
  72. userConfigPath: value.userConfigPath,
  73. env: value.env,
  74. });
  75. const digest = pending.items[0]!.hookDeclarationDigest;
  76. await grantWorkspaceHookTrust({
  77. workspacePath: value.source,
  78. userConfigPath: value.userConfigPath,
  79. env: value.env,
  80. hookDeclarationDigests: [digest],
  81. });
  82. return digest;
  83. }
  84. describe("Workspace Hook Trust:受管 worktree 继承源仓库", () => {
  85. it("源仓库已有 Trust record 时,worktree 中同一声明直接 trusted,identity 为源仓库路径", async () => {
  86. const value = await fixture();
  87. const digest = await trustSourceHook(value);
  88. const status = await inspectWorkspaceHookTrust({
  89. workspacePath: value.worktree,
  90. userConfigPath: value.userConfigPath,
  91. env: value.env,
  92. });
  93. expect(status.workspacePath).toBe(value.worktree);
  94. expect(status.workspaceIdentity).toBe(value.source);
  95. expect(status.reasonCode).toBe("workspace_hooks_trusted_persistent");
  96. expect(status.items).toEqual([
  97. expect.objectContaining({ hookDeclarationDigest: digest, trustState: "trusted_persistent" }),
  98. ]);
  99. });
  100. it("伪造 gitdir 反向链接时不继承,worktree 中该声明回到 pending", async () => {
  101. const value = await fixture();
  102. await trustSourceHook(value);
  103. await writeFile(
  104. join(value.source, ".git", "worktrees", REPO, "gitdir"),
  105. `${join(value.root, "elsewhere", ".git")}\n`,
  106. );
  107. const status = await inspectWorkspaceHookTrust({
  108. workspacePath: value.worktree,
  109. userConfigPath: value.userConfigPath,
  110. env: value.env,
  111. });
  112. expect(status.workspaceIdentity).toBe(value.worktree);
  113. expect(status.reasonCode).toBe("workspace_hooks_pending_trust");
  114. });
  115. it("远程 identity 原样作为 Trust identity,不做本地解析", async () => {
  116. const value = await fixture();
  117. const identity = "remote:ssh:example.test:22:coder:/workspace/repo";
  118. const status = await inspectWorkspaceHookTrust({
  119. workspacePath: value.worktree,
  120. workspaceIdentity: identity,
  121. userConfigPath: value.userConfigPath,
  122. env: value.env,
  123. });
  124. expect(status.workspaceIdentity).toBe(identity);
  125. });
  126. it("协议授予在 worktree 中按 Trust identity 评估 policy 并写入源仓库 record", async () => {
  127. const value = await fixture();
  128. vi.stubEnv("ZCODE_DATA_BASE_DIR", value.dataBaseDir);
  129. const pending = await inspectWorkspaceHookTrust({
  130. workspacePath: value.worktree,
  131. userConfigPath: value.userConfigPath,
  132. env: value.env,
  133. });
  134. const policyProvider = new InMemoryWorkspaceHookPolicyProvider({
  135. mode: "user_decides",
  136. policyRevision: "test:user-decides:v1",
  137. });
  138. const getPolicy = vi.spyOn(policyProvider, "getPolicy");
  139. const grant = vi.fn((input: Parameters<typeof grantWorkspaceHookTrust>[0]) =>
  140. grantWorkspaceHookTrust({ ...input, userConfigPath: value.userConfigPath }),
  141. );
  142. await expect(
  143. grantWorkspaceHookTrustForProtocol(
  144. {
  145. workspace: { workspacePath: value.worktree, workspaceKey: value.worktree },
  146. bundleDigest: pending.bundleDigest!,
  147. hookDeclarationDigest: pending.items[0]!.hookDeclarationDigest,
  148. },
  149. { grant, policyProvider },
  150. ),
  151. ).resolves.toEqual({ accepted: true });
  152. expect(getPolicy).toHaveBeenCalledWith(value.source);
  153. const sourceStatus = await inspectWorkspaceHookTrust({
  154. workspacePath: value.source,
  155. userConfigPath: value.userConfigPath,
  156. env: value.env,
  157. });
  158. expect(sourceStatus.reasonCode).toBe("workspace_hooks_trusted_persistent");
  159. });
  160. it("Trust 授予通知同一 Trust identity 下的源仓库与 worktree session,跳过无关 workspace", async () => {
  161. const value = await fixture();
  162. vi.stubEnv("ZCODE_DATA_BASE_DIR", value.dataBaseDir);
  163. const session = (workspacePath: string) => {
  164. const reload = vi.fn(async () => undefined);
  165. return {
  166. reload,
  167. record: {
  168. app: { reloadWorkspaceHookTrust: reload },
  169. workspace: { workspaceKey: workspacePath, workspacePath },
  170. } as never,
  171. };
  172. };
  173. const inSource = session(value.source);
  174. const inWorktree = session(value.worktree);
  175. const other = session(join(value.root, "other"));
  176. await notifyWorkspaceHookTrustGrantSessions({
  177. grantedWorkspace: { workspaceKey: value.source, workspacePath: value.source },
  178. sessions: new Map([
  179. ["s-source", inSource.record],
  180. ["s-worktree", inWorktree.record],
  181. ["s-other", other.record],
  182. ]),
  183. });
  184. expect(inSource.reload).toHaveBeenCalledTimes(1);
  185. expect(inWorktree.reload).toHaveBeenCalledTimes(1);
  186. expect(other.reload).not.toHaveBeenCalled();
  187. });
  188. });