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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251
  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 { buildRemoteWorkspaceIdentity } from "@zcode/shared";
  12. import {
  13. grantWorkspaceHookTrust,
  14. inspectWorkspaceHookTrust,
  15. } from "../src/workspace-hook-trust-cli.js";
  16. import { grantWorkspaceHookTrustForProtocol } from "../src/zcode-protocol/workspace-hook-trust.js";
  17. import { notifyWorkspaceHookTrustGrantSessions } from "../src/zcode-protocol/server.js";
  18. const execFileAsync = promisify(execFile);
  19. const roots: string[] = [];
  20. const BUCKET = "3f2a";
  21. const REPO = "repo";
  22. afterEach(async () => {
  23. vi.unstubAllEnvs();
  24. await Promise.all(roots.splice(0).map((path) => rm(path, { recursive: true, force: true })));
  25. });
  26. async function git(cwd: string, ...args: string[]): Promise<void> {
  27. await execFileAsync(
  28. "git",
  29. ["-c", "user.name=ZCode Test", "-c", "user.email=test@example.com", ...args],
  30. { cwd },
  31. );
  32. }
  33. async function fixture() {
  34. // resolver 按 realpath 判定;macOS 临时目录是软链,fixture 统一用 realpath。
  35. const root = await realpath(await mkdtemp(join(tmpdir(), "zcode-hook-trust-worktree-")));
  36. roots.push(root);
  37. const source = join(root, "projects", REPO);
  38. const dataBaseDir = join(root, "data");
  39. const worktree = join(dataBaseDir, ".zcode", "worktrees", BUCKET, REPO);
  40. const userConfigPath = join(root, "config.json");
  41. await writeFile(
  42. userConfigPath,
  43. JSON.stringify({
  44. storage: { dir: join(root, "user-data") },
  45. hooks: { enabled: true, events: {} },
  46. }),
  47. );
  48. await mkdir(join(source, ".zcode"), { recursive: true });
  49. await writeFile(
  50. join(source, ".zcode", "config.json"),
  51. JSON.stringify({
  52. hooks: {
  53. enabled: true,
  54. events: {
  55. SessionStart: [
  56. { matcher: "startup", hooks: [{ type: "command", command: "./start.sh" }] },
  57. ],
  58. },
  59. },
  60. }),
  61. );
  62. // 入口脚本必须存在才可授权(D24);随仓库提交,worktree 中内容相同,digest 也相同。
  63. await writeFile(join(source, "start.sh"), "echo start\n");
  64. await git(source, "init", "-q");
  65. await git(source, "add", ".");
  66. await git(source, "commit", "-q", "-m", "init");
  67. await mkdir(join(dataBaseDir, ".zcode", "worktrees", BUCKET), { recursive: true });
  68. await git(source, "worktree", "add", "-q", "--detach", worktree);
  69. const env = { ZCODE_DATA_BASE_DIR: dataBaseDir };
  70. return { dataBaseDir, env, root, source, userConfigPath, worktree };
  71. }
  72. async function trustSourceHook(value: Awaited<ReturnType<typeof fixture>>) {
  73. const pending = await inspectWorkspaceHookTrust({
  74. workspacePath: value.source,
  75. userConfigPath: value.userConfigPath,
  76. env: value.env,
  77. });
  78. const digest = pending.items[0]!.hookDeclarationDigest;
  79. await grantWorkspaceHookTrust({
  80. workspacePath: value.source,
  81. userConfigPath: value.userConfigPath,
  82. env: value.env,
  83. hookDeclarationDigests: [digest],
  84. });
  85. return digest;
  86. }
  87. describe("Workspace Hook Trust:受管 worktree 继承源仓库", () => {
  88. it("源仓库已有 Trust record 时,worktree 中同一声明直接 trusted,identity 为源仓库路径", async () => {
  89. const value = await fixture();
  90. const digest = await trustSourceHook(value);
  91. const status = await inspectWorkspaceHookTrust({
  92. workspacePath: value.worktree,
  93. userConfigPath: value.userConfigPath,
  94. env: value.env,
  95. });
  96. expect(status.workspacePath).toBe(value.worktree);
  97. expect(status.workspaceIdentity).toBe(value.source);
  98. expect(status.reasonCode).toBe("workspace_hooks_trusted_persistent");
  99. expect(status.items).toEqual([
  100. expect.objectContaining({ hookDeclarationDigest: digest, trustState: "trusted_persistent" }),
  101. ]);
  102. });
  103. it("伪造 gitdir 反向链接时不继承,worktree 中该声明回到 pending", async () => {
  104. const value = await fixture();
  105. await trustSourceHook(value);
  106. await writeFile(
  107. join(value.source, ".git", "worktrees", REPO, "gitdir"),
  108. `${join(value.root, "elsewhere", ".git")}\n`,
  109. );
  110. const status = await inspectWorkspaceHookTrust({
  111. workspacePath: value.worktree,
  112. userConfigPath: value.userConfigPath,
  113. env: value.env,
  114. });
  115. expect(status.workspaceIdentity).toBe(value.worktree);
  116. expect(status.reasonCode).toBe("workspace_hooks_pending_trust");
  117. });
  118. it("路径一致的远程 identity 原样作为 Trust identity,不做本地解析", async () => {
  119. const value = await fixture();
  120. const identity = buildRemoteWorkspaceIdentity(value.worktree, {
  121. kind: "ssh",
  122. host: "example.test",
  123. port: 22,
  124. username: "coder",
  125. });
  126. const status = await inspectWorkspaceHookTrust({
  127. workspacePath: value.worktree,
  128. workspaceIdentity: identity,
  129. userConfigPath: value.userConfigPath,
  130. env: value.env,
  131. });
  132. expect(status.workspaceIdentity).toBe(identity);
  133. });
  134. // CR-01 回归:独立 store 中裸路径已有授权;路径不一致的远程 identity 曾退回裸路径而直接命中。
  135. it("远程 identity 不命中本地裸路径或源仓库的已有授权", async () => {
  136. const value = await fixture();
  137. const digest = await trustSourceHook(value);
  138. const ssh = { kind: "ssh", host: "example.test", port: 22, username: "coder" } as const;
  139. const server = { kind: "server", serverId: "example-server", url: "https://example.com" } as const;
  140. const cases = [
  141. { workspacePath: value.source, identity: buildRemoteWorkspaceIdentity("/workspace/repo", ssh) },
  142. { workspacePath: value.source, identity: buildRemoteWorkspaceIdentity("/workspace/repo", server) },
  143. {
  144. workspacePath: value.source,
  145. identity: buildRemoteWorkspaceIdentity(`${value.source}/../${REPO}`, server),
  146. },
  147. { workspacePath: value.worktree, identity: buildRemoteWorkspaceIdentity("/workspace/repo", ssh) },
  148. { workspacePath: value.source, identity: buildRemoteWorkspaceIdentity(value.source, ssh) },
  149. ];
  150. const identities = new Set<string>();
  151. for (const { workspacePath, identity } of cases) {
  152. const status = await inspectWorkspaceHookTrust({
  153. workspacePath,
  154. workspaceIdentity: identity,
  155. userConfigPath: value.userConfigPath,
  156. env: value.env,
  157. });
  158. expect(status.workspaceIdentity).not.toBe(value.source);
  159. expect(status.workspaceIdentity).not.toBe(value.worktree);
  160. expect(status.items).toEqual([
  161. expect.objectContaining({ hookDeclarationDigest: digest, trustState: "pending_trust" }),
  162. ]);
  163. identities.add(status.workspaceIdentity);
  164. }
  165. // ssh 与 server 不共用记录;同一 host 的同一执行目录得到同一个键。
  166. expect(identities).toEqual(
  167. new Set([
  168. buildRemoteWorkspaceIdentity(value.source, ssh),
  169. buildRemoteWorkspaceIdentity(value.source, server),
  170. buildRemoteWorkspaceIdentity(value.worktree, ssh),
  171. ]),
  172. );
  173. });
  174. it("协议授予在 worktree 中按 Trust identity 评估 policy 并写入源仓库 record", async () => {
  175. const value = await fixture();
  176. vi.stubEnv("ZCODE_DATA_BASE_DIR", value.dataBaseDir);
  177. const pending = await inspectWorkspaceHookTrust({
  178. workspacePath: value.worktree,
  179. userConfigPath: value.userConfigPath,
  180. env: value.env,
  181. });
  182. const policyProvider = new InMemoryWorkspaceHookPolicyProvider({
  183. mode: "user_decides",
  184. policyRevision: "test:user-decides:v1",
  185. });
  186. const getPolicy = vi.spyOn(policyProvider, "getPolicy");
  187. const grant = vi.fn((input: Parameters<typeof grantWorkspaceHookTrust>[0]) =>
  188. grantWorkspaceHookTrust({ ...input, userConfigPath: value.userConfigPath }),
  189. );
  190. await expect(
  191. grantWorkspaceHookTrustForProtocol(
  192. {
  193. workspace: { workspacePath: value.worktree, workspaceKey: value.worktree },
  194. bundleDigest: pending.bundleDigest!,
  195. hookDeclarationDigest: pending.items[0]!.hookDeclarationDigest,
  196. },
  197. { grant, policyProvider },
  198. ),
  199. ).resolves.toEqual({ accepted: true });
  200. expect(getPolicy).toHaveBeenCalledWith(value.source);
  201. const sourceStatus = await inspectWorkspaceHookTrust({
  202. workspacePath: value.source,
  203. userConfigPath: value.userConfigPath,
  204. env: value.env,
  205. });
  206. expect(sourceStatus.reasonCode).toBe("workspace_hooks_trusted_persistent");
  207. });
  208. it("Trust 授予通知同一 Trust identity 下的源仓库与 worktree session,跳过无关 workspace", async () => {
  209. const value = await fixture();
  210. vi.stubEnv("ZCODE_DATA_BASE_DIR", value.dataBaseDir);
  211. const session = (workspacePath: string) => {
  212. const reload = vi.fn(async () => undefined);
  213. return {
  214. reload,
  215. record: {
  216. app: { reloadWorkspaceHookTrust: reload },
  217. workspace: { workspaceKey: workspacePath, workspacePath },
  218. } as never,
  219. };
  220. };
  221. const inSource = session(value.source);
  222. const inWorktree = session(value.worktree);
  223. const other = session(join(value.root, "other"));
  224. await notifyWorkspaceHookTrustGrantSessions({
  225. grantedWorkspace: { workspaceKey: value.source, workspacePath: value.source },
  226. sessions: new Map([
  227. ["s-source", inSource.record],
  228. ["s-worktree", inWorktree.record],
  229. ["s-other", other.record],
  230. ]),
  231. });
  232. expect(inSource.reload).toHaveBeenCalledTimes(1);
  233. expect(inWorktree.reload).toHaveBeenCalledTimes(1);
  234. expect(other.reload).not.toHaveBeenCalled();
  235. });
  236. });