hook-trust-fixture.ts 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201
  1. import { mkdir, readFile, rm, writeFile } from "node:fs/promises";
  2. import { dirname, join } from "node:path";
  3. import { DEFAULT_WORKSPACE } from "./desktop-app.js";
  4. /**
  5. * Workspace Hook Trust e2e fixture(HK05–HK07、HK18)。
  6. *
  7. * 与 hooks-lifecycle-fixture 的关键区别:hook trust 的审核对象是 workspace
  8. * (project)级 `.zcode/config.json`,而不是 user 级 CLI config;且该配置
  9. * 必须在首个 agent 进程冷启动前落盘(wdio.conf.ts 的 resetE2EHome 会针对
  10. * 本 spec 再调用一次 installHookTrustFixture),否则 SessionStart 软门禁
  11. * 不会在首轮 turn 中生效。
  12. */
  13. export const E2E_HOOK_TRUST_LABELS = {
  14. sessionStartA: "hook-trust-session-start-a",
  15. sessionStartB: "hook-trust-session-start-b",
  16. promptSubmit: "hook-trust-prompt-submit",
  17. } as const;
  18. /** HK18:入口脚本不存在的声明,没有可审核的内容,不能信任也不会执行(D24)。 */
  19. export const E2E_HOOK_TRUST_SCRIPT_MISSING_LABEL = "hook-trust-script-missing";
  20. const WORKSPACE_ZCODE_DIR = join(DEFAULT_WORKSPACE, ".zcode");
  21. const CONFIG_PATH = join(WORKSPACE_ZCODE_DIR, "config.json");
  22. const RECORDER_PATH = join(WORKSPACE_ZCODE_DIR, "hook-trust-e2e-recorder.mjs");
  23. const EVIDENCE_DIR = join(DEFAULT_WORKSPACE, ".hook-trust-e2e");
  24. const EVIDENCE_PATH = join(EVIDENCE_DIR, "executions.jsonl");
  25. // Trust store 位于隔离 E2E HOME(= DEFAULT_WORKSPACE 的上级目录)下,
  26. // 与 adapters 的 resolveWorkspaceHookTrustStorePath 默认值一致。
  27. const TRUST_STORE_PATH = join(
  28. dirname(DEFAULT_WORKSPACE),
  29. ".zcode",
  30. "security",
  31. "workspace-hook-trust-v1.json",
  32. );
  33. export interface HookTrustExecutionRecord {
  34. event: string;
  35. label: string;
  36. executedAt: string;
  37. }
  38. export interface HookTrustStoreRecord {
  39. workspaceIdentity: string;
  40. hookDeclarationDigest: string;
  41. decision: string;
  42. eventAtGrant?: string;
  43. }
  44. function processHook(event: string, label: string): Record<string, unknown> {
  45. return {
  46. type: "process",
  47. command: process.execPath,
  48. // 绝对路径:project hook 属于不可信可执行配置,相对路径解析依赖 cwd,不稳。
  49. args: [RECORDER_PATH, EVIDENCE_DIR, event, label],
  50. enabled: true,
  51. timeoutMs: 10000,
  52. statusMessage: `Workspace Hook Trust E2E — ${event} ${label}`,
  53. };
  54. }
  55. // 相对路径的 node 脚本入口会被识别为直接入口;该文件刻意不创建。
  56. function missingScriptHook(): Record<string, unknown> {
  57. return {
  58. type: "process",
  59. command: "node",
  60. args: [".zcode/hook-trust-missing-script.mjs", E2E_HOOK_TRUST_SCRIPT_MISSING_LABEL],
  61. enabled: true,
  62. timeoutMs: 10000,
  63. };
  64. }
  65. export async function installHookTrustFixture(): Promise<void> {
  66. await mkdir(WORKSPACE_ZCODE_DIR, { recursive: true });
  67. await rm(EVIDENCE_DIR, { recursive: true, force: true });
  68. await writeFile(RECORDER_PATH, RECORDER_SOURCE, "utf8");
  69. await writeFile(
  70. CONFIG_PATH,
  71. `${JSON.stringify(
  72. {
  73. hooks: {
  74. enabled: true,
  75. timeoutMs: 10000,
  76. maxOutputBytes: 32768,
  77. events: {
  78. SessionStart: [
  79. {
  80. matcher: "startup",
  81. hooks: [
  82. processHook("SessionStart", E2E_HOOK_TRUST_LABELS.sessionStartA),
  83. processHook("SessionStart", E2E_HOOK_TRUST_LABELS.sessionStartB),
  84. ],
  85. },
  86. ],
  87. UserPromptSubmit: [
  88. {
  89. hooks: [processHook("UserPromptSubmit", E2E_HOOK_TRUST_LABELS.promptSubmit)],
  90. },
  91. ],
  92. Stop: [{ hooks: [missingScriptHook()] }],
  93. },
  94. },
  95. },
  96. null,
  97. 2,
  98. )}\n`,
  99. "utf8",
  100. );
  101. }
  102. export async function restoreHookTrustFixture(): Promise<void> {
  103. await rm(CONFIG_PATH, { force: true });
  104. await rm(RECORDER_PATH, { force: true });
  105. await rm(EVIDENCE_DIR, { recursive: true, force: true });
  106. }
  107. export async function readHookTrustExecutions(): Promise<HookTrustExecutionRecord[]> {
  108. try {
  109. return (await readFile(EVIDENCE_PATH, "utf8"))
  110. .split("\n")
  111. .filter(Boolean)
  112. .map((line) => JSON.parse(line) as HookTrustExecutionRecord);
  113. } catch (error) {
  114. if (isMissingFileError(error)) return [];
  115. throw error;
  116. }
  117. }
  118. export async function waitForHookTrustExecution(
  119. label: string,
  120. timeoutMsg: string,
  121. timeout = 30000,
  122. ): Promise<HookTrustExecutionRecord> {
  123. let record: HookTrustExecutionRecord | undefined;
  124. await browser.waitUntil(
  125. async () => {
  126. record = (await readHookTrustExecutions()).find((item) => item.label === label);
  127. return Boolean(record);
  128. },
  129. { timeout, timeoutMsg },
  130. );
  131. return record!;
  132. }
  133. /** 读取持久 Trust store;文件不存在(尚无任何信任)时返回 null。 */
  134. export async function readHookTrustStore(): Promise<HookTrustStoreRecord[] | null> {
  135. let raw: string;
  136. try {
  137. raw = await readFile(TRUST_STORE_PATH, "utf8");
  138. } catch (error) {
  139. if (isMissingFileError(error)) return null;
  140. throw error;
  141. }
  142. const parsed = JSON.parse(raw) as { records?: HookTrustStoreRecord[] };
  143. return parsed.records ?? [];
  144. }
  145. export async function waitForHookTrustStoreRecords(
  146. predicate: (records: HookTrustStoreRecord[]) => boolean,
  147. timeoutMsg: string,
  148. timeout = 30000,
  149. ): Promise<HookTrustStoreRecord[]> {
  150. let latest: HookTrustStoreRecord[] = [];
  151. await browser.waitUntil(
  152. async () => {
  153. const records = await readHookTrustStore();
  154. if (!records) return false;
  155. latest = records;
  156. return predicate(records);
  157. },
  158. { timeout, timeoutMsg },
  159. );
  160. return latest;
  161. }
  162. function isMissingFileError(error: unknown): boolean {
  163. return Boolean(
  164. error &&
  165. typeof error === "object" &&
  166. "code" in error &&
  167. error.code === "ENOENT",
  168. );
  169. }
  170. // recorder 只做一件事:向 evidence JSONL 追加一条执行记录,供 e2e 断言
  171. // “未信任的 Hook 零执行”与“信任后的自然事件执行”。
  172. const RECORDER_SOURCE = String.raw`import { appendFile, mkdir } from "node:fs/promises";
  173. import { join } from "node:path";
  174. const outputDirectory = process.argv[2];
  175. const event = process.argv[3] ?? "unknown";
  176. const label = process.argv[4] ?? "unknown";
  177. await mkdir(outputDirectory, { recursive: true });
  178. await appendFile(
  179. join(outputDirectory, "executions.jsonl"),
  180. JSON.stringify({ event, label, executedAt: new Date().toISOString() }) + "\n",
  181. "utf8",
  182. );
  183. `;