credential-store-recovery.test.ts 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391
  1. import { execFile } from "node:child_process";
  2. import { promisify } from "node:util";
  3. import { fileURLToPath } from "node:url";
  4. import { createHash } from "node:crypto";
  5. import { chmod, mkdir, readFile, readdir, rm, writeFile } from "node:fs/promises";
  6. import { basename, dirname, join } from "node:path";
  7. import {
  8. getE2EAppDataPaths,
  9. waitForTestIdByDom,
  10. clickTestIdByDom,
  11. readE2ECredentialValue,
  12. } from "#e2e/helpers/desktop-app";
  13. import { openSubagentHostWindow } from "#e2e/helpers/subagent-host-window";
  14. import { setRendererViewport, clearRendererViewport } from "#e2e/helpers/renderer-viewport";
  15. async function selectRecoveryLocale(locale: string) {
  16. await browser.execute((value) => {
  17. type Fiber = {
  18. return?: Fiber;
  19. memoizedProps?: { value?: { setLocalePreference?: (locale: string) => void } };
  20. };
  21. for (const element of document.querySelectorAll("div,button")) {
  22. const key = Object.keys(element).find((name) => name.startsWith("__reactFiber$"));
  23. for (
  24. let fiber = key ? (Reflect.get(element, key) as Fiber) : undefined;
  25. fiber;
  26. fiber = fiber.return
  27. ) {
  28. const context = fiber.memoizedProps?.value;
  29. if (context?.setLocalePreference) {
  30. context.setLocalePreference(value);
  31. return;
  32. }
  33. }
  34. }
  35. throw new Error("Missing actual locale context");
  36. }, locale);
  37. }
  38. /**
  39. * 单入口登录按区域选择渠道:中文默认国内 zai_cn,其轮询只受夹具 cn-ready 控制。
  40. * 恢复用例依赖 hold-poll / enable-poll 挂起与放行旧流程,因此登录前显式选全球区 zai。
  41. */
  42. async function selectGlobalLoginRegion() {
  43. // 切换区域会同时切换界面语言并重渲染,每次从 DOM 重新读取,避免持有失效节点。
  44. const readRegion = () =>
  45. browser.execute(
  46. () => document.querySelector('[data-testid="login-region-switch"]')?.textContent ?? "",
  47. );
  48. await waitForTestIdByDom("login-region-switch", { timeout: 30000 });
  49. if ((await readRegion()).includes("Global")) await clickTestIdByDom("login-region-switch");
  50. let text = "";
  51. await browser.waitUntil(async () => (text = await readRegion()).includes("中国"), {
  52. timeoutMsg: `登录区域未切到全球区,当前开关文案:${text}`,
  53. });
  54. }
  55. describe("凭据容器确认恢复", () => {
  56. it("整库恢复后拒绝旧纯归因回调,新流程和归因去重仍有效", async function () {
  57. this.timeout(30_000);
  58. const fixture = fileURLToPath(
  59. new URL("../../../../fixtures/credential-recovery/oauth-attribution.ts", import.meta.url),
  60. );
  61. const result = join(process.env.ZCODE_E2E_ARTIFACT_DIR!, "oauth-attribution-recovery.json");
  62. await promisify(execFile)(process.execPath, ["--import", "tsx", fixture, result], {
  63. timeout: 25_000,
  64. });
  65. expect(JSON.parse(await readFile(result, "utf8")).results).toEqual(
  66. ["zai", "bigmodel"].map((provider) => ({
  67. provider,
  68. staleAttributionRejected: true,
  69. emptyStorePreserved: true,
  70. freshAttributionPreserved: true,
  71. duplicateRejected: true,
  72. })),
  73. );
  74. });
  75. it("恢复期间排队的条件写入或删除拒绝旧代次,新请求保持比较语义", async function () {
  76. this.timeout(30_000);
  77. const fixture = fileURLToPath(
  78. new URL("../../../../fixtures/credential-recovery/conditional-mutations.ts", import.meta.url),
  79. );
  80. const result = join(
  81. process.env.ZCODE_E2E_ARTIFACT_DIR!,
  82. "conditional-credential-mutations.json",
  83. );
  84. await promisify(execFile)(process.execPath, ["--import", "tsx", fixture, result], {
  85. timeout: 25_000,
  86. });
  87. expect(JSON.parse(await readFile(result, "utf8")).results).toEqual([
  88. { method: "saveIfAbsent", staleRejected: true, newOperationsPreserved: true },
  89. { method: "deleteIfEquals", staleRejected: true, newOperationsPreserved: true },
  90. ]);
  91. });
  92. it("所有网络入口和提权路径拒绝恢复,仅本机桌面保留", async function () {
  93. this.timeout(30_000);
  94. const fixture = fileURLToPath(
  95. new URL("../../../../fixtures/credential-recovery/server-websocket.ts", import.meta.url),
  96. );
  97. const result = join(process.env.ZCODE_E2E_ARTIFACT_DIR!, "server-credential-rpc-denied.json");
  98. await promisify(execFile)(process.execPath, ["--import", "tsx", fixture, result], {
  99. timeout: 25_000,
  100. });
  101. const rows = JSON.parse(await readFile(result, "utf8")).results;
  102. expect(rows.map((row: { publisher: string }) => row.publisher)).toEqual([
  103. "web-server-public",
  104. "web-server-authenticated",
  105. "source-server-core",
  106. "legacy-stdio",
  107. "local-desktop-policy",
  108. "attachment-desktop-continuous-remote",
  109. "attachment-desktop-continuous-source-settings",
  110. "attachment-desktop-continuous-unspecified",
  111. "attachment-web-remote-replayable-local",
  112. ]);
  113. for (const row of rows) {
  114. if (row.publisher === "local-desktop-policy") expect(row.recoveryPreserved).toBe(true);
  115. else {
  116. for (const boundary of row.direct ? [row.direct, row.selfIssuedCapability] : [row]) {
  117. expect(boundary.denied).toEqual({
  118. inspectStore: "feature_disabled",
  119. recoverStore: "feature_disabled",
  120. });
  121. expect(boundary.originalAndGenerationUnchanged).toBe(true);
  122. expect(boundary.ordinaryReadWritePreserved).toBe(true);
  123. }
  124. if (row.direct) {
  125. expect(row.missingAndForgedTicketDenied).toBe(true);
  126. expect(row.ticketReplayDenied).toBe(true);
  127. }
  128. }
  129. }
  130. });
  131. it("取消保留原件、备份失败不覆盖,确认后可恢复登录入口", async () => {
  132. const openExternal = await browser.electron.mock("shell", "openExternal");
  133. await openExternal.mockResolvedValue(undefined);
  134. const file = getE2EAppDataPaths().credentialsFile;
  135. const original = await readFile(file);
  136. const backup = `${file}.corrupt-${createHash("sha256").update(original).digest("hex").slice(0, 24)}.bak`;
  137. await waitForTestIdByDom("credential-store-recovery", { timeout: 30000 });
  138. await browser.$("#loading").waitForExist({ reverse: true });
  139. await clickTestIdByDom("credential-store-recovery-open");
  140. await clickTestIdByDom("credential-store-recovery-cancel");
  141. expect(await readFile(file)).toEqual(original);
  142. await rm(backup, { force: true });
  143. await mkdir(backup);
  144. try {
  145. await clickTestIdByDom("credential-store-recovery-open");
  146. await clickTestIdByDom("credential-store-recovery-confirm");
  147. await waitForTestIdByDom("credential-store-recovery-error");
  148. expect(await readFile(file)).toEqual(original);
  149. } finally {
  150. await rm(backup, { recursive: true, force: true });
  151. }
  152. await clickTestIdByDom("credential-store-recovery-open");
  153. await clickTestIdByDom("credential-store-recovery-confirm");
  154. await waitForTestIdByDom("credential-store-recovery-reload");
  155. expect(await readFile(backup)).toEqual(original);
  156. expect(JSON.parse(await readFile(file, "utf8"))).toEqual({});
  157. const generation = await readFile(`${file}.recovery-generation`, "utf8");
  158. expect(generation.length).toBeGreaterThan(0);
  159. await browser.saveScreenshot(
  160. join(process.env.ZCODE_E2E_ARTIFACT_DIR!, "credential-recovered.png"),
  161. );
  162. await clickTestIdByDom("credential-store-recovery-reload");
  163. await waitForTestIdByDom("oauth-login-button", { timeout: 30000 });
  164. expect(await readFile(`${file}.recovery-generation`, "utf8")).toBe(generation);
  165. await selectGlobalLoginRegion();
  166. await clickTestIdByDom("oauth-login-button");
  167. // 主 JWT 与渠道无关;写入即证明恢复后的空库可以重新完成 OAuth 登录。
  168. await browser.waitUntil(
  169. async () => Boolean(JSON.parse(await readFile(file, "utf8"))["zcodejwttoken"]),
  170. { timeout: 15000, timeoutMsg: "空库恢复后未能重新 OAuth 登录并保存凭据" },
  171. );
  172. await writeFile(
  173. join(process.env.ZCODE_E2E_ARTIFACT_DIR!, "credential-recovery.json"),
  174. JSON.stringify({
  175. originalBytes: original.length,
  176. backupMatches: (await readFile(backup)).equals(original),
  177. recovered: true,
  178. }),
  179. );
  180. });
  181. it("已有不完整备份时保留旧件,并独立创建完整备份后恢复", async () => {
  182. const file = getE2EAppDataPaths().credentialsFile;
  183. const raw = Buffer.from('{"unfinished":"backup-collision"');
  184. const prefix = `${file}.corrupt-${createHash("sha256").update(raw).digest("hex").slice(0, 24)}`;
  185. const originalBackup = `${prefix}.bak`;
  186. // 后台读取也会创建备份;先放置旧备份再暴露损坏原件,避免夹具覆盖正在写入的备份。
  187. await writeFile(originalBackup, "partial-backup");
  188. await writeFile(file, raw);
  189. await browser.refresh();
  190. await waitForTestIdByDom("credential-store-recovery", { timeout: 30000 });
  191. await clickTestIdByDom("credential-store-recovery-open");
  192. await clickTestIdByDom("credential-store-recovery-confirm");
  193. await waitForTestIdByDom("credential-store-recovery-reload");
  194. expect(await readFile(originalBackup, "utf8")).toBe("partial-backup");
  195. expect(JSON.parse(await readFile(file, "utf8"))).toEqual({});
  196. const directory = dirname(file);
  197. const backupName = basename(prefix);
  198. const backups = (await readdir(directory)).filter(
  199. (name) =>
  200. name.startsWith(`${backupName}.`) && name.endsWith(".bak") && name !== `${backupName}.bak`,
  201. );
  202. expect(backups).toHaveLength(1);
  203. expect(await readFile(join(directory, backups[0]!))).toEqual(raw);
  204. });
  205. it("旧确认不得清空已经有效的库,单条坏密文不进入重建入口", async () => {
  206. const file = getE2EAppDataPaths().credentialsFile;
  207. await writeFile(file, '{"unfinished":');
  208. await browser.refresh();
  209. await waitForTestIdByDom("credential-store-recovery", { timeout: 30000 });
  210. await clickTestIdByDom("credential-store-recovery-open");
  211. const valid = JSON.stringify({ "bot:fixture": "enc:v1:bad.bad.bad" });
  212. await writeFile(file, valid);
  213. const generation = await readFile(`${file}.recovery-generation`, "utf8");
  214. await clickTestIdByDom("credential-store-recovery-confirm");
  215. await waitForTestIdByDom("credential-store-recovery-reload");
  216. expect(await readFile(file, "utf8")).toBe(valid);
  217. expect(await readFile(`${file}.recovery-generation`, "utf8")).toBe(generation);
  218. await clickTestIdByDom("credential-store-recovery-reload");
  219. await waitForTestIdByDom("oauth-login-button", { timeout: 30000 });
  220. expect(await browser.$('[data-testid="credential-store-recovery"]').isExisting()).toBe(false);
  221. });
  222. it("两个 Host 的重复确认不能覆盖恢复后保存的凭据", async () => {
  223. const file = getE2EAppDataPaths().credentialsFile;
  224. await writeFile(file, '{"unfinished":');
  225. await browser.refresh();
  226. await waitForTestIdByDom("credential-store-recovery", { timeout: 30000 });
  227. const main = await browser.getWindowHandle();
  228. const second = await openSubagentHostWindow();
  229. try {
  230. await waitForTestIdByDom("credential-store-recovery", { timeout: 30000 });
  231. await clickTestIdByDom("credential-store-recovery-open");
  232. await browser.switchToWindow(main);
  233. await clickTestIdByDom("credential-store-recovery-open");
  234. await clickTestIdByDom("credential-store-recovery-confirm");
  235. await waitForTestIdByDom("credential-store-recovery-reload");
  236. const saved = '{"bot:new":"new-credential"}';
  237. await writeFile(file, saved);
  238. const generation = await readFile(`${file}.recovery-generation`, "utf8");
  239. await browser.switchToWindow(second.handle);
  240. await clickTestIdByDom("credential-store-recovery-confirm");
  241. await waitForTestIdByDom("credential-store-recovery-reload");
  242. // 系统安全存储会把合成明文迁移为密文;断言旧确认没有清空库,而不比较磁盘格式。
  243. expect(Object.keys(JSON.parse(await readFile(file, "utf8")))).toEqual(["bot:new"]);
  244. expect(await readE2ECredentialValue("bot:new")).toBe("new-credential");
  245. expect(await readFile(`${file}.recovery-generation`, "utf8")).toBe(generation);
  246. } finally {
  247. await browser.electron.execute(
  248. (electron, id) => electron.BrowserWindow.fromId(id)?.close(),
  249. second.windowId,
  250. );
  251. await browser.switchToWindow(main);
  252. }
  253. });
  254. it("另一 Host 恢复后,旧 OAuth 响应不得重新写入凭据", async () => {
  255. const file = getE2EAppDataPaths().credentialsFile;
  256. const baseUrl = process.env.ZCODE_E2E_OAUTH_RACE_URL!;
  257. await writeFile(file, "{}");
  258. await browser.refresh();
  259. await waitForTestIdByDom("oauth-login-button", { timeout: 30000 });
  260. await selectGlobalLoginRegion();
  261. await fetch(`${baseUrl}/__e2e/hold-poll`, { method: "POST" });
  262. await clickTestIdByDom("oauth-login-button");
  263. await waitForTestIdByDom("oauth-cancel");
  264. const main = await browser.getWindowHandle();
  265. await writeFile(file, '{"unfinished":');
  266. const second = await openSubagentHostWindow();
  267. try {
  268. await waitForTestIdByDom("credential-store-recovery", { timeout: 30000 });
  269. await clickTestIdByDom("credential-store-recovery-open");
  270. await clickTestIdByDom("credential-store-recovery-confirm");
  271. await waitForTestIdByDom("credential-store-recovery-reload");
  272. await fetch(`${baseUrl}/__e2e/enable-poll`, { method: "POST" });
  273. await browser.switchToWindow(main);
  274. await waitForTestIdByDom("oauth-error", { timeout: 15000 });
  275. expect(JSON.parse(await readFile(file, "utf8"))).toEqual({});
  276. } finally {
  277. await fetch(`${baseUrl}/__e2e/enable-poll`, { method: "POST" });
  278. await browser.electron.execute(
  279. (electron, id) => electron.BrowserWindow.fromId(id)?.close(),
  280. second.windowId,
  281. );
  282. await browser.switchToWindow(main);
  283. }
  284. });
  285. it("恢复页与确认框兼容双主题、中英文及窄屏", async () => {
  286. const { credentialsFile, appDataDir } = getE2EAppDataPaths();
  287. const settingsFile = join(appDataDir, "setting.json");
  288. const settings = await readFile(settingsFile, "utf8");
  289. const credentials = await readFile(credentialsFile);
  290. try {
  291. await writeFile(credentialsFile, '{"unfinished":');
  292. for (const theme of ["zai-light", "zai-dark"]) {
  293. for (const locale of ["en-US", "zh-CN"]) {
  294. for (const width of [1280, 390]) {
  295. // 手改文件不会清除浏览器已保存的语言偏好;使用设置页相同的真实切换入口。
  296. await selectRecoveryLocale(locale);
  297. await browser.waitUntil(
  298. async () =>
  299. JSON.parse(await readFile(settingsFile, "utf8")).localePreference === locale,
  300. );
  301. await browser.execute((value) => localStorage.setItem("zcode-theme", value), theme);
  302. await setRendererViewport(width, 844);
  303. await browser.refresh();
  304. await waitForTestIdByDom("credential-store-recovery", { timeout: 30000 });
  305. await browser.$("#loading").waitForExist({ reverse: true });
  306. expect(
  307. await browser.execute(
  308. (value) => document.documentElement.classList.contains(`theme-${value}`),
  309. theme,
  310. ),
  311. ).toBe(true);
  312. await clickTestIdByDom("credential-store-recovery-open");
  313. await browser.$('[role="alertdialog"]').waitForDisplayed();
  314. await waitForTestIdByDom("credential-store-recovery-confirm");
  315. const text = await browser.$('[role="alertdialog"]').getText();
  316. expect(text).toContain(locale === "zh-CN" ? "重新配置" : "reconfigure");
  317. expect(
  318. await browser.execute(
  319. () => document.documentElement.scrollWidth <= window.innerWidth,
  320. ),
  321. ).toBe(true);
  322. await browser.saveScreenshot(
  323. join(process.env.ZCODE_E2E_ARTIFACT_DIR!, `recovery-${theme}-${locale}-${width}.png`),
  324. );
  325. await clickTestIdByDom("credential-store-recovery-cancel");
  326. expect(await readFile(credentialsFile)).toEqual(Buffer.from('{"unfinished":'));
  327. }
  328. }
  329. }
  330. } finally {
  331. await writeFile(settingsFile, settings);
  332. await writeFile(credentialsFile, credentials);
  333. await clearRendererViewport();
  334. }
  335. });
  336. it("非法 UTF-8、非字符串记录可恢复;文件缺失与 IO 错误不得提供重建入口", async () => {
  337. const file = getE2EAppDataPaths().credentialsFile;
  338. const original = await readFile(file);
  339. try {
  340. for (const content of [Buffer.from([0xff, 0xfe]), Buffer.from('{"key":42}')]) {
  341. await writeFile(file, content);
  342. await browser.refresh();
  343. await waitForTestIdByDom("credential-store-recovery", { timeout: 30000 });
  344. await clickTestIdByDom("credential-store-recovery-open");
  345. await clickTestIdByDom("credential-store-recovery-cancel");
  346. expect(await readFile(file)).toEqual(content);
  347. }
  348. await rm(file);
  349. await browser.refresh();
  350. await waitForTestIdByDom("oauth-login-button", { timeout: 30000 });
  351. expect(await browser.$('[data-testid="credential-store-recovery"]').isExisting()).toBe(false);
  352. await mkdir(file);
  353. const logDir = await browser.electron.execute(() => process.env.ZCODE_E2E_RUNTIME_LOG_DIR!);
  354. const logs = join(logDir, new Date().toISOString().slice(0, 10) + ".log");
  355. const before = (await readFile(logs, "utf8").catch(() => "")).length;
  356. await browser.refresh();
  357. await browser.waitUntil(
  358. async () =>
  359. (await readFile(logs, "utf8")).slice(before).includes("credential.inspectStore FAIL"),
  360. { timeout: 10000, timeoutMsg: "IO 失败未经过真实 Host 读取边界" },
  361. );
  362. expect(await browser.$('[data-testid="credential-store-recovery-open"]').isExisting()).toBe(
  363. false,
  364. );
  365. if (process.platform !== "win32") {
  366. await rm(file, { recursive: true });
  367. await writeFile(file, original);
  368. await chmod(file, 0o000);
  369. const beforePermissionFailure = (await readFile(logs, "utf8")).length;
  370. await browser.refresh();
  371. await browser.waitUntil(
  372. async () =>
  373. (await readFile(logs, "utf8"))
  374. .slice(beforePermissionFailure)
  375. .includes("credential.inspectStore FAIL"),
  376. { timeout: 10000, timeoutMsg: "权限失败未经过真实 Host 读取边界" },
  377. );
  378. expect(await browser.$('[data-testid="credential-store-recovery-open"]').isExisting()).toBe(
  379. false,
  380. );
  381. }
  382. } finally {
  383. await chmod(file, 0o600).catch(() => undefined);
  384. await rm(file, { recursive: true, force: true });
  385. await writeFile(file, original);
  386. }
  387. });
  388. });