download-native-search-tools.test.ts 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264
  1. import { createHash } from "node:crypto";
  2. import {
  3. createReadStream,
  4. chmodSync,
  5. existsSync,
  6. mkdirSync,
  7. mkdtempSync,
  8. readFileSync,
  9. rmSync,
  10. statSync,
  11. writeFileSync,
  12. } from "node:fs";
  13. import { createServer } from "node:http";
  14. import { tmpdir } from "node:os";
  15. import { join } from "node:path";
  16. import { afterEach, describe, expect, it } from "vitest";
  17. import { packSourceAsDeterministicTarGzip } from "../../../scripts/deterministic-tar-archive.mjs";
  18. import { downloadNativeSearchTools } from "../../../scripts/download-native-search-tools.mjs";
  19. import {
  20. resolveNativeSearchBundleMetaPath,
  21. writeNativeSearchBundleMeta,
  22. } from "../../../scripts/native-search-tools-bundle-meta.mjs";
  23. import { resolveNativeSearchPrebuiltPlan } from "../../../scripts/native-search-tools-config.mjs";
  24. import {
  25. downloadPrebuiltArchive,
  26. downloadAndExtractPrebuiltBinary,
  27. shouldUsePrebuiltDownloadProxy,
  28. verifyPrebuiltArchiveSha256,
  29. } from "../../../scripts/prebuilt-binary-download.mjs";
  30. const temporaryDirectories: string[] = [];
  31. function createTemporaryDirectory(): string {
  32. const directory = mkdtempSync(join(tmpdir(), "zcode-native-search-download-test-"));
  33. temporaryDirectories.push(directory);
  34. return directory;
  35. }
  36. function createMachOFixture(arch: "arm64" | "x64", label: string): Buffer {
  37. const labelBytes = Buffer.from(label);
  38. const buffer = Buffer.alloc(32 + labelBytes.length);
  39. buffer.writeUInt32LE(0xfeedfacf, 0);
  40. buffer.writeUInt32LE(arch === "arm64" ? 0x0100000c : 0x01000007, 4);
  41. buffer.writeUInt32LE(2, 12);
  42. labelBytes.copy(buffer, 32);
  43. return buffer;
  44. }
  45. afterEach(() => {
  46. for (const directory of temporaryDirectories.splice(0)) {
  47. rmSync(directory, { force: true, recursive: true });
  48. }
  49. });
  50. describe("downloadNativeSearchTools", () => {
  51. it("下载响应中途断开时清理半截归档并明确失败", async () => {
  52. const root = createTemporaryDirectory();
  53. const archivePath = join(root, "partial-archive.tar.gz");
  54. const server = createServer((_request, response) => {
  55. response.writeHead(200, { "content-length": 1024 });
  56. response.flushHeaders();
  57. response.write("partial archive");
  58. setTimeout(() => response.destroy(), 10);
  59. });
  60. await new Promise<void>((resolvePromise) => server.listen(0, "127.0.0.1", resolvePromise));
  61. try {
  62. const address = server.address();
  63. if (!address || typeof address === "string") throw new Error("test server has no TCP port");
  64. await expect(
  65. downloadPrebuiltArchive(`http://127.0.0.1:${address.port}/archive`, archivePath),
  66. ).rejects.toThrow("Download aborted before completion");
  67. expect(existsSync(archivePath)).toBe(false);
  68. } finally {
  69. await new Promise<void>((resolvePromise, rejectPromise) => {
  70. server.close((error) => (error ? rejectPromise(error) : resolvePromise()));
  71. });
  72. }
  73. });
  74. it("只为固定的 GitHub release 主机启用下载代理", () => {
  75. expect(
  76. shouldUsePrebuiltDownloadProxy(
  77. "https://github.com/microsoft/ripgrep-prebuilt/releases/download/v14.1.1-1/rg.tar.gz",
  78. ),
  79. ).toBe(true);
  80. expect(
  81. shouldUsePrebuiltDownloadProxy(
  82. "https://release-assets.githubusercontent.com/asset/rg.tar.gz",
  83. ),
  84. ).toBe(true);
  85. expect(
  86. shouldUsePrebuiltDownloadProxy(
  87. "http://intranet.example.invalid:12345/zcode/deps/native-search-tools/rg.tar.gz",
  88. ),
  89. ).toBe(false);
  90. expect(shouldUsePrebuiltDownloadProxy("https://github.com.example.test/rg.tar.gz")).toBe(false);
  91. });
  92. it("从预编译归档安装目标工具,已存在时跳过,缺失时失败", async () => {
  93. const root = createTemporaryDirectory();
  94. const archives = new Map<string, string>();
  95. let requestCount = 0;
  96. const server = createServer((request, response) => {
  97. requestCount += 1;
  98. const archivePath = archives.get(request.url ?? "");
  99. if (!archivePath) {
  100. response.writeHead(404).end();
  101. return;
  102. }
  103. response.writeHead(200, { "content-type": "application/gzip" });
  104. createReadStream(archivePath).pipe(response);
  105. });
  106. await new Promise<void>((resolvePromise) => server.listen(0, "127.0.0.1", resolvePromise));
  107. try {
  108. const address = server.address();
  109. if (!address || typeof address === "string") throw new Error("test server has no TCP port");
  110. const baseUrl = `http://127.0.0.1:${address.port}`;
  111. const env = {
  112. NATIVE_SEARCH_RIPGREP_DOWNLOAD_BASE_URL: `${baseUrl}/microsoft-ripgrep`,
  113. NATIVE_SEARCH_TOOLS_DOWNLOAD_BASE_URL: baseUrl,
  114. };
  115. const outputDir = join(root, "output");
  116. const plan = resolveNativeSearchPrebuiltPlan({
  117. platform: "darwin",
  118. arch: "arm64",
  119. outputDir,
  120. env,
  121. });
  122. const fixtures = new Map<string, Buffer>();
  123. for (const artifact of plan.artifacts) {
  124. const sourcePath = join(root, artifact.binaryName);
  125. const archivePath = join(root, artifact.releaseFileName);
  126. const fixture = createMachOFixture("arm64", `${artifact.toolId}-fixture`);
  127. fixtures.set(artifact.toolId, fixture);
  128. if (artifact.source === "official") {
  129. mkdirSync(join(outputDir, artifact.toolId), { recursive: true });
  130. writeFileSync(artifact.binaryPath, fixture);
  131. chmodSync(artifact.binaryPath, 0o755);
  132. writeNativeSearchBundleMeta(artifact, plan.platformKey);
  133. } else {
  134. writeFileSync(sourcePath, fixture);
  135. chmodSync(sourcePath, 0o755);
  136. packSourceAsDeterministicTarGzip(sourcePath, archivePath);
  137. artifact.archiveSha256 = createHash("sha256")
  138. .update(readFileSync(archivePath))
  139. .digest("hex");
  140. archives.set(new URL(artifact.downloadUrl).pathname, archivePath);
  141. }
  142. }
  143. await downloadNativeSearchTools({
  144. prebuiltPlan: plan,
  145. });
  146. expect(readFileSync(plan.bfsPath)).toEqual(fixtures.get("bfs"));
  147. expect(readFileSync(plan.rgPath)).toEqual(fixtures.get("ripgrep"));
  148. expect(readFileSync(plan.ugrepPath)).toEqual(fixtures.get("ugrep"));
  149. expect(requestCount).toBe(2);
  150. expect(
  151. JSON.parse(readFileSync(resolveNativeSearchBundleMetaPath(plan.rgPath), "utf8")),
  152. ).toMatchObject({ source: "official" });
  153. await downloadNativeSearchTools({
  154. prebuiltPlan: plan,
  155. });
  156. expect(requestCount).toBe(2);
  157. if (process.platform !== "win32") {
  158. chmodSync(plan.bfsPath, 0o644);
  159. await downloadNativeSearchTools({
  160. prebuiltPlan: plan,
  161. });
  162. expect(requestCount).toBe(2);
  163. expect(statSync(plan.bfsPath).mode & 0o111).not.toBe(0);
  164. }
  165. const ugrepArtifact = plan.artifacts.find(({ toolId }) => toolId === "ugrep");
  166. if (!ugrepArtifact) throw new Error("ugrep artifact is missing");
  167. writeFileSync(ugrepArtifact.binaryPath, createMachOFixture("x64", "wrong-arch-cache"));
  168. writeNativeSearchBundleMeta(ugrepArtifact, plan.platformKey);
  169. await downloadNativeSearchTools({
  170. prebuiltPlan: plan,
  171. });
  172. expect(requestCount).toBe(3);
  173. expect(readFileSync(plan.ugrepPath)).toEqual(fixtures.get("ugrep"));
  174. const invalidArchivePath = join(root, "invalid-ugrep.tar.gz");
  175. const ugrepSourcePath = join(root, ugrepArtifact.binaryName);
  176. writeFileSync(ugrepSourcePath, createMachOFixture("x64", "wrong-arch-download"));
  177. packSourceAsDeterministicTarGzip(ugrepSourcePath, invalidArchivePath);
  178. archives.set(new URL(ugrepArtifact.downloadUrl).pathname, invalidArchivePath);
  179. const invalidOutputDir = join(root, "invalid-output");
  180. const invalidPlan = resolveNativeSearchPrebuiltPlan({
  181. platform: "darwin",
  182. arch: "arm64",
  183. outputDir: invalidOutputDir,
  184. env,
  185. });
  186. for (const artifact of invalidPlan.artifacts.filter(({ source }) => source === "producer")) {
  187. const archivePath = archives.get(new URL(artifact.downloadUrl).pathname);
  188. if (!archivePath) throw new Error(`fixture archive is missing for ${artifact.toolId}`);
  189. artifact.archiveSha256 = createHash("sha256")
  190. .update(readFileSync(archivePath))
  191. .digest("hex");
  192. }
  193. await expect(
  194. downloadNativeSearchTools({
  195. prebuiltPlan: invalidPlan,
  196. }),
  197. ).rejects.toThrow("expected 0x100000c for arm64");
  198. expect(existsSync(invalidPlan.rgPath)).toBe(false);
  199. expect(existsSync(resolveNativeSearchBundleMetaPath(invalidPlan.rgPath))).toBe(false);
  200. const missingOutputDir = join(root, "missing-output");
  201. await expect(
  202. downloadNativeSearchTools({
  203. platform: "darwin",
  204. arch: "arm64",
  205. outputDir: missingOutputDir,
  206. env: {
  207. ...env,
  208. NATIVE_SEARCH_TOOLS_DOWNLOAD_BASE_URL: `${baseUrl}/missing`,
  209. },
  210. }),
  211. ).rejects.toThrow("Download failed: HTTP 404");
  212. expect(existsSync(join(missingOutputDir, "bfs", "bfs"))).toBe(false);
  213. } finally {
  214. await new Promise<void>((resolvePromise, rejectPromise) => {
  215. server.close((error) => (error ? rejectPromise(error) : resolvePromise()));
  216. });
  217. }
  218. });
  219. it("在解包前按可信摘要校验预编译归档", () => {
  220. const root = createTemporaryDirectory();
  221. const archivePath = join(root, "archive.tar.gz");
  222. writeFileSync(archivePath, "official-archive-fixture");
  223. const expectedSha256 = createHash("sha256").update(readFileSync(archivePath)).digest("hex");
  224. expect(() => verifyPrebuiltArchiveSha256(archivePath, expectedSha256)).not.toThrow();
  225. expect(() => verifyPrebuiltArchiveSha256(archivePath, "0".repeat(64))).toThrow(
  226. "Archive SHA-256 mismatch",
  227. );
  228. });
  229. it("缺少归档摘要时在下载前失败", async () => {
  230. const root = createTemporaryDirectory();
  231. await expect(
  232. downloadAndExtractPrebuiltBinary({
  233. archiveExt: "tar.gz",
  234. binaryName: "ugrep",
  235. binaryPath: join(root, "output", "ugrep"),
  236. cwd: root,
  237. downloadUrl: "http://127.0.0.1:1/unreachable",
  238. targetPlatform: "darwin",
  239. }),
  240. ).rejects.toThrow("missing prebuilt archive SHA-256");
  241. });
  242. });