system-credential-auto-reset.test.ts 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136
  1. import { createHash } from "node:crypto";
  2. import { execFile } from "node:child_process";
  3. import { readFile, readdir, rm, writeFile } from "node:fs/promises";
  4. import { basename, dirname, join } from "node:path";
  5. import { promisify } from "node:util";
  6. import { TID_LOGIN_TRIGGER } from "@zcode/shared/test-ids";
  7. import { reloadElectronSessionPreservingBrowserProfile } from "#e2e/helpers/e2e-electron-reload";
  8. import { clearAppData, getE2EAppDataPaths } from "#e2e/helpers/desktop-app";
  9. // 规格:docs/plans/2026-10-29-system-credential-storage.md「已绑定目录:自动重置」。
  10. const KEY = "bot:e2e:auto-reset";
  11. const OLD_VALUE = "E2E_AUTO_RESET_OLD_SYNTHETIC_VALUE";
  12. const NEW_VALUE = "E2E_AUTO_RESET_NEW_SYNTHETIC_VALUE";
  13. const SERVICE = "ZCode Credential Encryption";
  14. const SHELL_SELECTOR = `[data-testid="${TID_LOGIN_TRIGGER}"], [data-testid="onboarding-page"], [data-testid="oauth-login-button"]`;
  15. type HostResult = { ok: true; value: string | null } | { ok: false; message: string };
  16. // 经真实 Renderer → Host → 凭据桥 → Main 调用凭据服务;失败以结构化结果返回,便于断言。
  17. async function callHost(method: "load" | "save", args: string[]): Promise<HostResult> {
  18. return browser.execute(
  19. async (selector, name, params) => {
  20. const element = document.querySelector(selector)!;
  21. let fiber = (element as any)[
  22. Object.keys(element).find((key) => key.startsWith("__reactFiber"))!
  23. ];
  24. while (fiber) {
  25. const context = fiber.memoizedProps?.value;
  26. const services = context?.credentialService ? context : fiber.memoizedProps?.services;
  27. if (services?.credentialService) {
  28. try {
  29. const value = await services.credentialService[name](...params);
  30. return { ok: true as const, value: value ?? null };
  31. } catch (error) {
  32. return { ok: false as const, message: String((error as Error)?.message ?? error) };
  33. }
  34. }
  35. fiber = fiber.return;
  36. }
  37. throw new Error("Credential service not found");
  38. },
  39. SHELL_SELECTOR,
  40. method,
  41. args,
  42. );
  43. }
  44. async function waitForShell() {
  45. await browser.waitUntil(
  46. async () =>
  47. browser.execute((selector) => Boolean(document.querySelector(selector)), SHELL_SELECTOR),
  48. { timeout: 60000 },
  49. );
  50. }
  51. async function resetBackups(file: string) {
  52. const prefix = `${basename(file)}.key-unavailable-`;
  53. return (await readdir(dirname(file))).filter((name) => name.startsWith(prefix));
  54. }
  55. describe("System credential storage automatic reset", () => {
  56. it("resets a store whose OS key entry was lost, then saves and restores a new login", async function () {
  57. // 删除系统条目依赖 macOS security 工具;Windows/Linux 原生行为见 spec 的未验证项。
  58. if (process.platform !== "darwin") this.skip();
  59. this.timeout(180000);
  60. const paths = getE2EAppDataPaths();
  61. const file = paths.credentialsFile;
  62. const account = createHash("sha256").update(file).digest("hex");
  63. const keychainLink = join(paths.homeDir, "Library", "Keychains");
  64. const sourceFile = join(dirname(file), "credential-source");
  65. // 原生条目由 Main 创建;测试 runner 的 SDK 删除会返回 owner-edit 错误。
  66. // 系统工具按本用例唯一 account 精确删除,不读取或导出密钥。
  67. const deleteEntry = () =>
  68. promisify(execFile)("/usr/bin/security", [
  69. "delete-generic-password",
  70. "-s",
  71. SERVICE,
  72. "-a",
  73. account,
  74. ]).catch((error: { code?: number }) => {
  75. if (error.code !== 44) throw error;
  76. });
  77. // 真实系统库专项:不得注入托管密钥,否则来源永远是 env,走不到系统库。
  78. expect(await browser.electron.execute(() => Boolean(process.env.ZCODE_CREDENTIAL_SECRET))).toBe(
  79. false,
  80. );
  81. try {
  82. await waitForShell();
  83. // 1. 制造已绑定 os 的凭据库:合成明文经 Host 委托 Main 迁移为 OS 密文。
  84. const existing = JSON.parse(await readFile(file, "utf8"));
  85. await writeFile(file, JSON.stringify({ ...existing, [KEY]: OLD_VALUE }));
  86. expect(await callHost("load", [KEY])).toEqual({ ok: true, value: OLD_VALUE });
  87. const bound = await readFile(file);
  88. expect(JSON.parse(bound.toString("utf8"))[KEY]).toMatch(/^enc:v2:os:/);
  89. expect(await readFile(sourceFile, "utf8")).toBe("os\n");
  90. // 2. 系统条目丢失(如重置登录钥匙串),再冷启动:Main 加载密钥得到 missing。
  91. await deleteEntry();
  92. await reloadElectronSessionPreservingBrowserProfile(browser);
  93. await waitForShell();
  94. // 3. 首次凭据读取让 Main 加载密钥得到 missing:本次请求失败,Main 随后在后台自动重置。
  95. // 隔离环境的启动阶段不读取凭据(运行时日志只有 inspectStore),必须由用例触发首次读取。
  96. const first = await callHost("load", [KEY]);
  97. expect(first.ok).toBe(false);
  98. // 重置后:备份逐字节保留旧库,写空库,解除来源绑定。
  99. await browser.waitUntil(async () => (await resetBackups(file)).length === 1, {
  100. timeout: 30000,
  101. timeoutMsg: "automatic credential reset did not produce a backup",
  102. });
  103. const [backup] = await resetBackups(file);
  104. expect((await readFile(join(dirname(file), backup!))).equals(bound)).toBe(true);
  105. await browser.waitUntil(
  106. async () => JSON.stringify(JSON.parse(await readFile(file, "utf8"))) === "{}",
  107. { timeout: 30000, timeoutMsg: "credential store was not cleared after the reset" },
  108. );
  109. await expect(readFile(sourceFile, "utf8")).rejects.toHaveProperty("code", "ENOENT");
  110. // 4. 无需重启即可重新保存:系统库可用,重建系统密钥并重新固定 os。
  111. expect(await callHost("load", [KEY])).toEqual({ ok: true, value: null });
  112. expect(await callHost("save", [KEY, NEW_VALUE])).toEqual({ ok: true, value: null });
  113. expect(JSON.parse(await readFile(file, "utf8"))[KEY]).toMatch(/^enc:v2:os:/);
  114. expect(await readFile(sourceFile, "utf8")).toBe("os\n");
  115. // 5. 冷启动后读回新值,且不会再次清空。
  116. await reloadElectronSessionPreservingBrowserProfile(browser);
  117. await waitForShell();
  118. expect(await callHost("load", [KEY])).toEqual({ ok: true, value: NEW_VALUE });
  119. expect(await resetBackups(file)).toHaveLength(1);
  120. } finally {
  121. await clearAppData();
  122. await deleteEntry();
  123. await rm(keychainLink, { force: true });
  124. }
  125. });
  126. });