system-credential-data-root.test.ts 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167
  1. import { createHash } from "node:crypto";
  2. import { execFile } from "node:child_process";
  3. import { access, mkdir, readFile, rm, writeFile } from "node:fs/promises";
  4. import { join } from "node:path";
  5. import { promisify } from "node:util";
  6. import { AsyncEntry } from "@napi-rs/keyring";
  7. import { TID_LOGIN_TRIGGER } from "@zcode/shared/test-ids";
  8. import { reloadElectronSessionPreservingBrowserProfile } from "#e2e/helpers/e2e-electron-reload";
  9. import { clearAppData, getE2EAppDataPaths } from "#e2e/helpers/desktop-app";
  10. // ZCT-2120723935487688704:3.18.0 起系统条目按凭据文件路径区分,切换数据存储路径只复制文件时,
  11. // 新根启动后解不开原凭据,也不能重新登录。本用例在真实系统库上验证切换时由 Main 登记密钥。
  12. const SERVICE = "ZCode Credential Encryption";
  13. const KEY = "bot:e2e:data-root";
  14. const VALUE = "E2E_DATA_ROOT_SYNTHETIC_VALUE";
  15. const RELOGIN_KEY = "bot:e2e:data-root-relogin";
  16. const RELOGIN_VALUE = "E2E_DATA_ROOT_RELOGIN_VALUE";
  17. const SHELL_SELECTOR_IDS = ["onboarding-page", "oauth-login-button"] as const;
  18. const CASE_TIMEOUT_MS = 240_000;
  19. type HostServiceName = "credentialService" | "settingService";
  20. /** 经 Renderer 的服务访问器调用真实 Host RPC,与设置页、登录页使用同一入口。 */
  21. async function callHostService(service: HostServiceName, method: string, args: unknown[]) {
  22. return browser.execute(
  23. async (loginTriggerId, extraIds, serviceName, methodName, methodArgs) => {
  24. const selector = [loginTriggerId, ...extraIds]
  25. .map((id) => `[data-testid="${id}"]`)
  26. .join(", ");
  27. const element = document.querySelector(selector)!;
  28. let fiber = (element as any)[
  29. Object.keys(element).find((name) => name.startsWith("__reactFiber"))!
  30. ];
  31. while (fiber) {
  32. const context = fiber.memoizedProps?.value;
  33. const services = context?.[serviceName] ? context : fiber.memoizedProps?.services;
  34. const target = services?.[serviceName];
  35. if (target) return target[methodName](...methodArgs);
  36. fiber = fiber.return;
  37. }
  38. throw new Error(`${serviceName} not found`);
  39. },
  40. TID_LOGIN_TRIGGER,
  41. [...SHELL_SELECTOR_IDS],
  42. service,
  43. method,
  44. args,
  45. );
  46. }
  47. async function waitForShell() {
  48. await browser.waitUntil(
  49. async () =>
  50. browser.execute(
  51. (loginTriggerId, extraIds) =>
  52. Boolean(
  53. document.querySelector(
  54. [loginTriggerId, ...extraIds].map((id) => `[data-testid="${id}"]`).join(", "),
  55. ),
  56. ),
  57. TID_LOGIN_TRIGGER,
  58. [...SHELL_SELECTOR_IDS],
  59. ),
  60. { timeout: 60_000, timeoutMsg: "数据根切换用例:应用外壳没有就绪" },
  61. );
  62. }
  63. const accountFor = (credentialsFile: string) =>
  64. createHash("sha256").update(credentialsFile).digest("hex");
  65. const fingerprintOf = (ciphertext: string) => ciphertext.split(":")[3];
  66. async function readRecord(file: string): Promise<Record<string, string>> {
  67. return JSON.parse(await readFile(file, "utf8")) as Record<string, string>;
  68. }
  69. /** macOS 只查询条目是否存在,不读取密钥(只有 Main 可以访问系统库中的密钥)。 */
  70. async function hasMacKeychainEntry(account: string): Promise<boolean> {
  71. try {
  72. await promisify(execFile)("/usr/bin/security", [
  73. "find-generic-password",
  74. "-s",
  75. SERVICE,
  76. "-a",
  77. account,
  78. ]);
  79. return true;
  80. } catch (error) {
  81. if ((error as { code?: number }).code === 44) return false;
  82. throw error;
  83. }
  84. }
  85. async function deleteKeychainEntry(account: string) {
  86. if (process.platform === "darwin") {
  87. // 原生条目由 Main 创建;runner 的 SDK 删除会返回 owner-edit 错误,按唯一 account 精确删除。
  88. await promisify(execFile)("/usr/bin/security", [
  89. "delete-generic-password",
  90. "-s",
  91. SERVICE,
  92. "-a",
  93. account,
  94. ]).catch((error: { code?: number }) => {
  95. if (error.code !== 44) throw error;
  96. });
  97. return;
  98. }
  99. await new AsyncEntry(SERVICE, account, { linux: { store: "secret-service" } })
  100. .deleteCredential()
  101. .catch(() => {});
  102. }
  103. describe("System credential storage across a data directory change", () => {
  104. it("registers the OS key for the new data root so credentials survive restart and new writes succeed", async function () {
  105. this.timeout(CASE_TIMEOUT_MS);
  106. const paths = getE2EAppDataPaths();
  107. const customBaseDir = join(paths.homeDir, "scs-data-root-custom");
  108. const customCredentialsFile = join(customBaseDir, ".zcode", "v2", "credentials.json");
  109. const bootstrapSettingsFile = join(paths.appDataDir, "setting.json");
  110. const keychainLink = join(paths.homeDir, "Library", "Keychains");
  111. const accounts = [paths.credentialsFile, customCredentialsFile].map(accountFor);
  112. expect(await browser.electron.execute(() => Boolean(process.env.ZCODE_CREDENTIAL_SECRET))).toBe(
  113. false,
  114. );
  115. try {
  116. await waitForShell();
  117. // 1) 默认根:合成旧明文经真实 Host 委托 Main 迁移为 OS 密文,并创建默认根的系统条目。
  118. const existing = await readRecord(paths.credentialsFile);
  119. await writeFile(paths.credentialsFile, JSON.stringify({ ...existing, [KEY]: VALUE }));
  120. expect(await callHostService("credentialService", "load", [KEY])).toBe(VALUE);
  121. const migrated = (await readRecord(paths.credentialsFile))[KEY]!;
  122. expect(migrated).toMatch(/^enc:v2:os:/);
  123. const fingerprint = fingerprintOf(migrated);
  124. // 2) 切换数据存储路径:与设置页相同的 Host RPC;复制后由 Main 登记目标根条目。
  125. await rm(customBaseDir, { force: true, recursive: true });
  126. await mkdir(customBaseDir, { recursive: true });
  127. await callHostService("settingService", "updateDataBaseDir", [customBaseDir]);
  128. const bootstrap = await readRecord(bootstrapSettingsFile);
  129. expect(bootstrap.dataBaseDir).toBe(customBaseDir);
  130. expect((await readRecord(customCredentialsFile))[KEY]).toBe(migrated);
  131. if (process.platform === "darwin") {
  132. expect(await hasMacKeychainEntry(accounts[1]!)).toBe(true);
  133. }
  134. // 3) 冷重启:Main 绑定新根凭据路径,复制来的密文仍可读取(修复前为安全存储不可用)。
  135. await reloadElectronSessionPreservingBrowserProfile(browser);
  136. await waitForShell();
  137. expect(await callHostService("credentialService", "load", [KEY])).toBe(VALUE);
  138. // 4) 新根上写入新凭据(等价于重新登录写入)成功,且沿用同一把密钥。
  139. await callHostService("credentialService", "save", [RELOGIN_KEY, RELOGIN_VALUE]);
  140. expect(await callHostService("credentialService", "load", [RELOGIN_KEY])).toBe(RELOGIN_VALUE);
  141. const customRecord = await readRecord(customCredentialsFile);
  142. expect(customRecord[RELOGIN_KEY]).toMatch(/^enc:v2:os:/);
  143. expect(fingerprintOf(customRecord[RELOGIN_KEY]!)).toBe(fingerprint);
  144. expect(JSON.stringify(customRecord)).not.toContain(RELOGIN_VALUE);
  145. // 原根文件保持复制语义:仍在原处且未被改写。
  146. await access(paths.credentialsFile);
  147. expect((await readRecord(paths.credentialsFile))[KEY]).toBe(migrated);
  148. } finally {
  149. await clearAppData();
  150. await rm(customBaseDir, { force: true, recursive: true });
  151. for (const account of accounts) await deleteKeychainEntry(account);
  152. if (process.platform === "darwin") await rm(keychainLink, { force: true });
  153. }
  154. });
  155. });