workspace-hook-trust-identity.test.ts 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223
  1. // Hook Trust identity 的 CLI adapter(docs/specs/workspace-hook-trust.md D23)。
  2. // 用真实 git 临时仓库 + 受管 worktree 布局 <dataBaseDir>/.zcode/worktrees/<4hex>/<repo> 验证:
  3. // - adapter 与共享 resolver 得到同一个 Trust identity;
  4. // - Runtime snapshot(createConfig)在 worktree 中归一为源仓库路径,bundleDigest 与源仓库一致;
  5. // - 伪造反向链接不继承;远程 identity 保留 host 命名空间、路径取执行目录(CR-01)。
  6. import { execFile } from "node:child_process";
  7. import { mkdir, mkdtemp, realpath, rm, writeFile } from "node:fs/promises";
  8. import { tmpdir } from "node:os";
  9. import { join } from "node:path";
  10. import { promisify } from "node:util";
  11. import { afterEach, describe, expect, it } from "vitest";
  12. import { buildRemoteWorkspaceIdentity } from "@zcode/shared";
  13. import {
  14. createConfig,
  15. resolveWorkspaceHookTrustIdentityForWorkspace,
  16. } from "../src/config/index.js";
  17. const execFileAsync = promisify(execFile);
  18. const roots: string[] = [];
  19. const BUCKET = "3f2a";
  20. const REPO = "repo";
  21. const SSH = { kind: "ssh", host: "example.test", port: 22, username: "coder" } as const;
  22. const SERVER = { kind: "server", serverId: "example-server", url: "https://example.com" } as const;
  23. afterEach(async () => {
  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. /** 源仓库提交一条 workspace Hook,再按受管布局创建 detached worktree。 */
  34. async function managedWorktreeFixture() {
  35. // macOS 临时目录 /var 是 /private/var 的软链;resolver 按 realpath 判定,fixture 也用 realpath。
  36. const root = await realpath(await mkdtemp(join(tmpdir(), "zcode-hook-trust-identity-")));
  37. roots.push(root);
  38. const source = join(root, "projects", REPO);
  39. const dataBaseDir = join(root, "data");
  40. const worktree = join(dataBaseDir, ".zcode", "worktrees", BUCKET, REPO);
  41. await mkdir(join(source, ".zcode"), { recursive: true });
  42. await mkdir(join(source, "packages", "app"), { recursive: true });
  43. await writeFile(join(source, "packages", "app", "README.md"), "app\n");
  44. await writeFile(
  45. join(source, ".zcode", "config.json"),
  46. JSON.stringify({
  47. hooks: {
  48. enabled: true,
  49. events: {
  50. SessionStart: [
  51. { matcher: "startup", hooks: [{ type: "command", command: "./start.sh" }] },
  52. ],
  53. },
  54. },
  55. }),
  56. );
  57. await git(source, "init", "-q");
  58. await git(source, "add", ".");
  59. await git(source, "commit", "-q", "-m", "init");
  60. await mkdir(join(dataBaseDir, ".zcode", "worktrees", BUCKET), { recursive: true });
  61. await git(source, "worktree", "add", "-q", "--detach", worktree);
  62. return { dataBaseDir, env: { ZCODE_DATA_BASE_DIR: dataBaseDir }, root, source, worktree };
  63. }
  64. describe("resolveWorkspaceHookTrustIdentityForWorkspace", () => {
  65. it("受管 worktree 及其子目录归一为源仓库中对应路径;源仓库与非受管目录保持自身路径", async () => {
  66. const value = await managedWorktreeFixture();
  67. await expect(
  68. resolveWorkspaceHookTrustIdentityForWorkspace({
  69. workspacePath: value.worktree,
  70. env: value.env,
  71. }),
  72. ).resolves.toBe(value.source);
  73. await expect(
  74. resolveWorkspaceHookTrustIdentityForWorkspace({
  75. workspacePath: join(value.worktree, "packages", "app"),
  76. env: value.env,
  77. }),
  78. ).resolves.toBe(join(value.source, "packages", "app"));
  79. await expect(
  80. resolveWorkspaceHookTrustIdentityForWorkspace({
  81. workspacePath: value.source,
  82. env: value.env,
  83. }),
  84. ).resolves.toBe(value.source);
  85. // ZCODE_DATA_BASE_DIR 指向别处时,同一路径不在受管根目录下,不继承。
  86. await expect(
  87. resolveWorkspaceHookTrustIdentityForWorkspace({
  88. workspacePath: value.worktree,
  89. env: { ZCODE_DATA_BASE_DIR: join(value.root, "other-data") },
  90. }),
  91. ).resolves.toBe(value.worktree);
  92. });
  93. it("伪造 gitdir 反向链接时不继承,退回 worktree 自身路径", async () => {
  94. const value = await managedWorktreeFixture();
  95. const adminDir = join(value.source, ".git", "worktrees", REPO);
  96. await writeFile(join(adminDir, "gitdir"), `${join(value.root, "elsewhere", ".git")}\n`);
  97. await expect(
  98. resolveWorkspaceHookTrustIdentityForWorkspace({
  99. workspacePath: value.worktree,
  100. env: value.env,
  101. }),
  102. ).resolves.toBe(value.worktree);
  103. });
  104. // SG-01:用共享构造器生成身份,Windows 盘符路径会归一为 /C:/...,与 parser 一致。
  105. it("路径一致的远程 identity 原样返回,不做本地解析与 worktree 继承", async () => {
  106. const value = await managedWorktreeFixture();
  107. const identity = buildRemoteWorkspaceIdentity(value.worktree, SSH);
  108. await expect(
  109. resolveWorkspaceHookTrustIdentityForWorkspace({
  110. workspacePath: value.worktree,
  111. workspaceIdentity: identity,
  112. env: value.env,
  113. }),
  114. ).resolves.toBe(identity);
  115. });
  116. // CR-01 回归:路径不一致的远程 identity 曾退回本地裸路径或源仓库路径,可命中本地已有授权。
  117. it("路径不一致或含 .. 的远程 identity 保留 host 命名空间,路径取执行目录", async () => {
  118. const value = await managedWorktreeFixture();
  119. const resolveWith = (workspaceIdentity: string) =>
  120. resolveWorkspaceHookTrustIdentityForWorkspace({
  121. workspacePath: value.worktree,
  122. workspaceIdentity,
  123. env: value.env,
  124. });
  125. const mismatchedSsh = await resolveWith(buildRemoteWorkspaceIdentity("/workspace/repo", SSH));
  126. const mismatchedServer = await resolveWith(
  127. buildRemoteWorkspaceIdentity("/workspace/repo", SERVER),
  128. );
  129. expect(mismatchedSsh).toBe(buildRemoteWorkspaceIdentity(value.worktree, SSH));
  130. expect(mismatchedServer).toBe(buildRemoteWorkspaceIdentity(value.worktree, SERVER));
  131. expect(mismatchedSsh).not.toBe(mismatchedServer);
  132. for (const identity of [mismatchedSsh, mismatchedServer]) {
  133. expect(identity).not.toBe(value.worktree);
  134. expect(identity).not.toBe(value.source);
  135. }
  136. // 共享构造器不折叠 `..`,Windows 上也得到以 / 开头的 /C:/... 路径,用例语义跨平台一致。
  137. const dotted = buildRemoteWorkspaceIdentity(`${value.worktree}/../${REPO}`, SERVER);
  138. await expect(resolveWith(dotted)).resolves.toBe(
  139. buildRemoteWorkspaceIdentity(value.worktree, SERVER),
  140. );
  141. });
  142. // 第三轮 CR-01 回归:带 remote: 前缀但解析失败的 identity 曾进入本地分支,命中本地或源仓库授权。
  143. it("无法解析的 remote: identity 原样返回,不进入本地与受管 worktree 分支", async () => {
  144. const value = await managedWorktreeFixture();
  145. for (const identity of [
  146. "remote:ssh:example.test:22:coder:relative",
  147. "remote:server:example-server:relative",
  148. "remote:unknown:/workspace/repo",
  149. ]) {
  150. for (const workspacePath of [value.source, value.worktree]) {
  151. await expect(
  152. resolveWorkspaceHookTrustIdentityForWorkspace({
  153. workspacePath,
  154. workspaceIdentity: identity,
  155. env: value.env,
  156. }),
  157. ).resolves.toBe(identity);
  158. }
  159. }
  160. });
  161. it("Windows 盘符路径用共享构造器生成的 identity 可解析并保留盘符", async () => {
  162. const windowsPath = "C:\\Users\\dev\\repo";
  163. const identity = buildRemoteWorkspaceIdentity(windowsPath, SSH);
  164. expect(identity).toBe("remote:ssh:example.test:22:coder:/C:/Users/dev/repo");
  165. await expect(
  166. resolveWorkspaceHookTrustIdentityForWorkspace({
  167. workspacePath: windowsPath,
  168. workspaceIdentity: identity,
  169. }),
  170. ).resolves.toBe(identity);
  171. });
  172. });
  173. describe("Runtime snapshot 的 Trust identity", () => {
  174. it("worktree 中 snapshot identity 是源仓库路径,bundleDigest 与源仓库相同", async () => {
  175. const value = await managedWorktreeFixture();
  176. const build = async (workingDirectory: string) =>
  177. createConfig({
  178. env: value.env,
  179. skipUserConfig: true,
  180. workingDirectory,
  181. workspaceHookTrustIdentity: await resolveWorkspaceHookTrustIdentityForWorkspace({
  182. workspacePath: workingDirectory,
  183. env: value.env,
  184. }),
  185. }).sources.project.workspaceHookSnapshot;
  186. const inWorktree = await build(value.worktree);
  187. const inSource = await build(value.source);
  188. expect(inWorktree?.workspaceIdentity).toBe(value.source);
  189. expect(inSource?.workspaceIdentity).toBe(value.source);
  190. expect(inWorktree?.bundleDigest).toBe(inSource?.bundleDigest);
  191. expect(inWorktree?.hooks.map((hook) => hook.hookDeclarationDigest)).toEqual(
  192. inSource?.hooks.map((hook) => hook.hookDeclarationDigest),
  193. );
  194. });
  195. it("未提供预解析的 Trust identity 时与共享 resolver 同一规则", async () => {
  196. const value = await managedWorktreeFixture();
  197. const snapshotIdentity = (workspaceIdentity?: string) =>
  198. createConfig({
  199. env: value.env,
  200. skipUserConfig: true,
  201. workingDirectory: value.worktree,
  202. workspaceIdentity,
  203. }).sources.project.workspaceHookSnapshot?.workspaceIdentity;
  204. const remote = buildRemoteWorkspaceIdentity(value.worktree, SSH);
  205. expect(snapshotIdentity()).toBe(value.worktree);
  206. expect(snapshotIdentity(value.source)).toBe(value.worktree);
  207. expect(snapshotIdentity(buildRemoteWorkspaceIdentity("/workspace/repo", SSH))).toBe(remote);
  208. expect(snapshotIdentity(remote)).toBe(remote);
  209. });
  210. });