conversation-session-preinstalled-tools-rewrite.test.ts 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203
  1. import { pinE2ELocale } from "#e2e/helpers/desktop-app";
  2. import { execFile } from "node:child_process";
  3. import { createHash } from "node:crypto";
  4. import { readFile, readdir, writeFile } from "node:fs/promises";
  5. import { join, normalize } from "node:path";
  6. import { promisify } from "node:util";
  7. import { prepareV4ConversationE2E } from "#e2e/helpers/v4-conversation";
  8. import { reloadElectronSessionPreservingBrowserProfile } from "#e2e/helpers/e2e-electron-reload";
  9. import { resolveE2EStorageRoot } from "#e2e/helpers/e2e-runtime-paths";
  10. const exec = promisify(execFile);
  11. const fixtureUrl = () => process.env.ZCODE_E2E_PREINSTALL_FIXTURE_URL!;
  12. async function openDialog() {
  13. // macOS 首帧跟随宿主语言;路径改写的错误文案按中文合同验证。
  14. await pinE2ELocale("zh-CN");
  15. await $('[data-testid="workspace-help-menu-trigger"]').click();
  16. await $('[data-testid="workspace-help-menu-preinstalled-tools"]').click();
  17. await $('[data-testid="preinstalled-tools-dialog"]').waitForDisplayed();
  18. }
  19. async function waitStatus(status: string) {
  20. await browser.waitUntil(
  21. async () =>
  22. (await $('[data-tool-id="qpdf"] [data-testid="preinstalled-tools-status"]').getAttribute(
  23. "data-status",
  24. )) === status,
  25. { timeout: 60000 },
  26. );
  27. }
  28. async function restart(scenario: string) {
  29. await reloadElectronSessionPreservingBrowserProfile(browser, {
  30. afterElectronProcessExit: async () => {
  31. expect((await fetch(`${fixtureUrl()}/scenario/${scenario}`)).ok).toBe(true);
  32. },
  33. });
  34. await prepareV4ConversationE2E();
  35. await openDialog();
  36. }
  37. async function waitForRewrite(tool: string, scenario: string): Promise<string> {
  38. const finalDirectory = join(tool, "versions", `rewrite-${scenario}-${process.arch}`);
  39. let payload: string | undefined;
  40. await browser.waitUntil(
  41. async () => {
  42. for (const operation of await readdir(join(tool, "staging"))) {
  43. const directory = join(tool, "staging", operation, "payload");
  44. try {
  45. if ((await readFile(join(directory, "data/value.txt"), "utf8")) === finalDirectory) {
  46. payload = directory;
  47. return true;
  48. }
  49. } catch (error) {
  50. if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error;
  51. }
  52. }
  53. return false;
  54. },
  55. { timeout: 30000, interval: 10, timeoutMsg: "未观察到改写开始" },
  56. );
  57. return payload!;
  58. }
  59. describe("预装工具安装路径改写(待审核)", () => {
  60. it("PT-REWRITE: 文本与Mach-O可重定位,超长、失败和中途取消不发布", async function () {
  61. this.timeout(600000);
  62. expect(process.platform).toBe("darwin");
  63. expect(resolveE2EStorageRoot()).toContain("中文 空格");
  64. await prepareV4ConversationE2E();
  65. await openDialog();
  66. await waitStatus("ready");
  67. const roots = join(resolveE2EStorageRoot(), "preinstalled-tools");
  68. const root = join(roots, (await readdir(roots))[0]!);
  69. const tool = join(root, "tools", "qpdf");
  70. const recordPath = join(tool, "installation.json");
  71. expect((await exec(join(root, "bin", "qpdf"))).stdout.trim()).toBe("plain-ok");
  72. await restart("success");
  73. await waitStatus("ready");
  74. let record = JSON.parse(await readFile(recordPath, "utf8")) as {
  75. installationDir: string;
  76. resourceId: string;
  77. };
  78. expect(record.resourceId).toBe(`rewrite-success-${process.arch}`);
  79. expect((await exec(join(root, "bin", "qpdf"))).stdout.trim()).toBe(
  80. `rewrite-ok:${record.installationDir}`,
  81. );
  82. expect(await readFile(join(record.installationDir, "data/value.txt"), "utf8")).toBe(
  83. record.installationDir,
  84. );
  85. const binary = await readFile(join(record.installationDir, "data/binary.bin"));
  86. const fixture = (await (await fetch(`${fixtureUrl()}/status`)).json()) as {
  87. binarySize: number;
  88. directoryPrefixSize: number;
  89. originalBinarySha256: string;
  90. };
  91. expect(binary.length).toBe(fixture.binarySize);
  92. expect(binary.toString("utf8").split("\0")[0]).toBe(
  93. `${record.installationDir}/one:${record.installationDir}/二`,
  94. );
  95. expect(binary.toString("utf8")).toContain(`tail/${record.installationDir}/tail`);
  96. await exec("/usr/bin/codesign", [
  97. "--verify",
  98. "--strict",
  99. join(record.installationDir, "bin/probe"),
  100. ]);
  101. await exec("/usr/bin/codesign", [
  102. "--verify",
  103. "--strict",
  104. join(record.installationDir, "bin/unchanged"),
  105. ]);
  106. expect(
  107. createHash("sha256")
  108. .update(await readFile(join(record.installationDir, "bin/unchanged")))
  109. .digest("hex"),
  110. ).toBe(fixture.originalBinarySha256);
  111. await browser.saveScreenshot(`${process.env.ZCODE_E2E_ARTIFACT_DIR}/rewrite-ready.png`);
  112. await restart("dir-prefix");
  113. await waitStatus("ready");
  114. record = JSON.parse(await readFile(recordPath, "utf8"));
  115. expect((await exec(join(root, "bin", "qpdf"))).stdout.trim()).toBe(
  116. `rewrite-ok:${record.installationDir}`,
  117. );
  118. const directoryBytes = await readFile(join(record.installationDir, "data/directory.bin"));
  119. expect(directoryBytes.length).toBe(fixture.directoryPrefixSize);
  120. expect(
  121. directoryBytes
  122. .toString("utf8")
  123. .split("\0")
  124. .map((value) => normalize(value).replace(/\/+$/, "")),
  125. ).toEqual([
  126. join(record.installationDir, "one"),
  127. join(record.installationDir, "two"),
  128. record.installationDir,
  129. ]);
  130. await exec("/usr/bin/codesign", [
  131. "--verify",
  132. "--strict",
  133. join(record.installationDir, "bin/directory-probe"),
  134. ]);
  135. for (const [scenario, message] of [
  136. ["dir-prefix-too-long", "暂不支持当前系统"],
  137. ["dir-prefix-invalid", "解压失败"],
  138. ["dir-prefix-binary", "工具无法在这台电脑上运行"],
  139. ["too-long", "暂不支持当前系统"],
  140. ["missing", "解压失败"],
  141. ["signing-failure", "解压失败"],
  142. ]) {
  143. await restart(scenario!);
  144. if (scenario === "signing-failure") {
  145. await waitStatus("preparing");
  146. await fetch(`${fixtureUrl()}/release/signing-failure`);
  147. const payload = await waitForRewrite(tool, scenario);
  148. // codesign 可以给任意数据文件签名;真实 Mach-O 的 FinderInfo 才会触发可重复的重签失败。
  149. await exec("/usr/bin/xattr", [
  150. "-wx",
  151. "com.apple.FinderInfo",
  152. "01".repeat(32),
  153. join(payload, "bin/signing-probe"),
  154. ]);
  155. }
  156. await waitStatus("failed");
  157. expect(await $('[data-testid="preinstalled-tools-dialog"]').getText()).toContain(message!);
  158. expect(JSON.parse(await readFile(recordPath, "utf8"))).toEqual(record);
  159. expect((await exec(join(root, "bin", "qpdf"))).stdout.trim()).toBe(
  160. `rewrite-ok:${record.installationDir}`,
  161. );
  162. expect(await readdir(join(tool, "staging"))).toEqual([]);
  163. expect(await readdir(join(tool, "versions"))).not.toContain(
  164. `rewrite-${scenario}-${process.arch}`,
  165. );
  166. await browser.saveScreenshot(`${process.env.ZCODE_E2E_ARTIFACT_DIR}/rewrite-${scenario}.png`);
  167. }
  168. await restart("cancel");
  169. const cancel = $('[data-testid="preinstalled-tools-cancel"]');
  170. await cancel.waitForDisplayed();
  171. await fetch(`${fixtureUrl()}/release/cancel`);
  172. await waitForRewrite(tool, "cancel");
  173. await cancel.click();
  174. await waitStatus("not-installed");
  175. expect(JSON.parse(await readFile(recordPath, "utf8"))).toEqual(record);
  176. expect(await readdir(join(tool, "staging"))).toEqual([]);
  177. expect(await readdir(join(tool, "versions"))).not.toContain(`rewrite-cancel-${process.arch}`);
  178. expect((await exec(join(root, "bin", "qpdf"))).stdout.trim()).toBe(
  179. `rewrite-ok:${record.installationDir}`,
  180. );
  181. await writeFile(
  182. join(process.env.ZCODE_E2E_ARTIFACT_DIR!, "rewrite-evidence.json"),
  183. JSON.stringify(
  184. {
  185. platform: process.platform,
  186. arch: process.arch,
  187. installationDir: record.installationDir,
  188. binaryBytes: binary.length,
  189. directoryPrefixBytes: directoryBytes.length,
  190. fixedLengthDirectoryProbe: true,
  191. directoryPrefixFailures: ["too-long", "invalid-later-occurrence", "original-binary"],
  192. unchangedSignedBinary: true,
  193. midRewriteCancel: true,
  194. },
  195. null,
  196. 2,
  197. ),
  198. );
  199. await browser.saveScreenshot(`${process.env.ZCODE_E2E_ARTIFACT_DIR}/rewrite-cancelled.png`);
  200. });
  201. });