system-credential-storage.test.ts 4.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. import { createHash } from "node:crypto";
  2. import { readFile, rm, writeFile } from "node:fs/promises";
  3. import { join } from "node:path";
  4. import { reloadElectronSessionPreservingBrowserProfile } from "#e2e/helpers/e2e-electron-reload";
  5. import { AsyncEntry } from "@napi-rs/keyring";
  6. import { execFile } from "node:child_process";
  7. import { promisify } from "node:util";
  8. import { TID_LOGIN_TRIGGER } from "@zcode/shared/test-ids";
  9. import { clearAppData, getE2EAppDataPaths } from "#e2e/helpers/desktop-app";
  10. const KEY = "bot:e2e:secure-storage";
  11. const VALUE = "E2E_SYSTEM_STORAGE_SYNTHETIC_VALUE";
  12. async function readThroughHost() {
  13. return browser.execute(
  14. async (id, key) => {
  15. const element = document.querySelector(
  16. `[data-testid="${id}"], [data-testid="onboarding-page"], [data-testid="oauth-login-button"]`,
  17. )!;
  18. let fiber = (element as any)[
  19. Object.keys(element).find((name) => name.startsWith("__reactFiber"))!
  20. ];
  21. while (fiber) {
  22. const context = fiber.memoizedProps?.value;
  23. const services = context?.credentialService ? context : fiber.memoizedProps?.services;
  24. if (services?.credentialService) return services.credentialService.load(key);
  25. fiber = fiber.return;
  26. }
  27. throw new Error("Credential service not found");
  28. },
  29. TID_LOGIN_TRIGGER,
  30. KEY,
  31. );
  32. }
  33. async function waitForShell() {
  34. await browser.waitUntil(
  35. async () =>
  36. browser.execute(
  37. (id) =>
  38. Boolean(
  39. document.querySelector(
  40. `[data-testid="${id}"], [data-testid="onboarding-page"], [data-testid="oauth-login-button"]`,
  41. ),
  42. ),
  43. TID_LOGIN_TRIGGER,
  44. ),
  45. { timeout: 60000 },
  46. );
  47. }
  48. describe("System credential storage", () => {
  49. it("migrates a legacy secret through the real Host and restores it across restart using the OS key store", async function () {
  50. this.timeout(120000);
  51. const paths = getE2EAppDataPaths();
  52. const file = paths.credentialsFile;
  53. const keychainLink = join(paths.homeDir, "Library", "Keychains");
  54. // 测试 HOME 不含 macOS 默认钥匙串;只链接系统库位置,应用数据仍留在隔离目录。
  55. // 仅创建/清理本用例散列目录名对应的临时条目,不修改系统默认钥匙串设置。
  56. // 链接由 beforeSession 在启动 Main 前准备,不能在首次访问失败后再补。
  57. const entry = new AsyncEntry(
  58. "ZCode Credential Encryption",
  59. createHash("sha256").update(file).digest("hex"),
  60. { linux: { store: "secret-service" } },
  61. );
  62. expect(await browser.electron.execute(() => Boolean(process.env.ZCODE_CREDENTIAL_SECRET))).toBe(
  63. false,
  64. );
  65. try {
  66. await waitForShell();
  67. const existing = JSON.parse(await readFile(file, "utf8"));
  68. await writeFile(file, JSON.stringify({ ...existing, [KEY]: VALUE }));
  69. expect(await readThroughHost()).toBe(VALUE);
  70. const raw = JSON.parse(await readFile(file, "utf8"));
  71. expect(raw[KEY]).toMatch(/^enc:v2:os:/);
  72. expect(JSON.stringify(raw)).not.toContain(VALUE);
  73. // 新合同只允许 Main 访问系统库,runner 不再用独立 Node 身份读取密钥。
  74. for (let index = 0; index < 10; index++) expect(await readThroughHost()).toBe(VALUE);
  75. await reloadElectronSessionPreservingBrowserProfile(browser);
  76. await waitForShell();
  77. expect(await readThroughHost()).toBe(VALUE);
  78. } finally {
  79. await clearAppData();
  80. if (process.platform === "darwin") {
  81. // 原生条目由 Main 创建;测试 runner 的 SDK 删除会返回 owner-edit 错误。
  82. // 系统工具按本用例唯一 account 精确删除,不读取或导出密钥。
  83. await promisify(execFile)("/usr/bin/security", [
  84. "delete-generic-password",
  85. "-s",
  86. "ZCode Credential Encryption",
  87. "-a",
  88. createHash("sha256").update(file).digest("hex"),
  89. ]).catch((error: { code?: number }) => {
  90. if (error.code !== 44) throw error;
  91. });
  92. } else {
  93. await entry.deleteCredential();
  94. }
  95. if (process.platform === "darwin") await rm(keychainLink, { force: true });
  96. }
  97. });
  98. });