contentBundleCache.test.ts 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244
  1. import { createHash } from "node:crypto";
  2. import { createServer } from "node:http";
  3. import { mkdtemp, readFile, readdir, rm, writeFile, symlink } from "node:fs/promises";
  4. import { tmpdir } from "node:os";
  5. import { join } from "node:path";
  6. import { afterEach, describe, expect, it, vi } from "vitest";
  7. import yazl from "yazl";
  8. import {
  9. createContentBundleCache,
  10. validateContentBundlePath,
  11. } from "#src/cloud-content/contentBundleCache.js";
  12. const directories: string[] = [];
  13. afterEach(async () => {
  14. await Promise.all(
  15. directories.splice(0).map((path) => rm(path, { recursive: true, force: true })),
  16. );
  17. });
  18. async function fixture(
  19. entries: Record<string, string> = { "index.html": "<h1>Hello</h1>", "assets/main.js": "void 0" },
  20. ) {
  21. const root = await mkdtemp(join(tmpdir(), "zcode-bundle-test-"));
  22. directories.push(root);
  23. const zip = new yazl.ZipFile();
  24. for (const [path, text] of Object.entries(entries)) zip.addBuffer(Buffer.from(text), path);
  25. zip.end();
  26. const chunks: Buffer[] = [];
  27. for await (const chunk of zip.outputStream) chunks.push(chunk);
  28. const bytes = Buffer.concat(chunks);
  29. const bundle = {
  30. format: "zip" as const,
  31. url: "https://cdn.example.com/hero.zip",
  32. entry: "index.html",
  33. sizeBytes: bytes.length,
  34. sha256: createHash("sha256").update(bytes).digest("hex"),
  35. };
  36. const fetcher = vi.fn(async () => new Response(bytes));
  37. const cache = createContentBundleCache({
  38. cacheRoot: root,
  39. isTrustedUrl: (url) => url.origin === "https://cdn.example.com",
  40. fetch: fetcher,
  41. });
  42. return { root, bytes, bundle, cache, fetcher };
  43. }
  44. describe("content bundle cache", () => {
  45. it("accepts a server bundle without declared size but still verifies its digest", async () => {
  46. const { cache, bundle } = await fixture();
  47. const { sizeBytes: _sizeBytes, ...published } = bundle;
  48. const lease = await cache.acquire(published);
  49. expect((await cache.read(lease.leaseId, "index.html")).toString()).toContain("Hello");
  50. await cache.release(lease.leaseId);
  51. await expect(cache.acquire({ ...published, sha256: "0".repeat(64) })).rejects.toThrow(
  52. /integrity/,
  53. );
  54. });
  55. it("aborts in-flight download when its owning host is disposed", async () => {
  56. const { root, bundle } = await fixture();
  57. const controller = new AbortController();
  58. let started!: () => void;
  59. const entered = new Promise<void>((resolve) => {
  60. started = resolve;
  61. });
  62. const cache = createContentBundleCache({
  63. cacheRoot: root,
  64. isTrustedUrl: () => true,
  65. signal: controller.signal,
  66. fetch: async (_url, init) =>
  67. new Promise<Response>((_resolve, reject) => {
  68. init?.signal?.addEventListener("abort", () => reject(init.signal!.reason), {
  69. once: true,
  70. });
  71. started();
  72. }),
  73. });
  74. const result = cache.acquire(bundle);
  75. const rejected = expect(result).rejects.toThrow();
  76. await entered;
  77. controller.abort();
  78. await rejected;
  79. expect((await readdir(root)).filter((name) => name === bundle.sha256)).toEqual([]);
  80. });
  81. it("runs the HTTP download-to-cache path with the real fetch implementation", async () => {
  82. const { root, bytes, bundle } = await fixture();
  83. let requests = 0;
  84. const server = createServer((_request, response) => {
  85. requests++;
  86. response.writeHead(200, { "Content-Type": "application/zip" }).end(bytes);
  87. });
  88. await new Promise<void>((resolve) => server.listen(0, "127.0.0.1", resolve));
  89. const address = server.address();
  90. if (!address || typeof address === "string") throw new Error("fixture address");
  91. const origin = `http://127.0.0.1:${address.port}`;
  92. const cache = createContentBundleCache({
  93. cacheRoot: root,
  94. isTrustedUrl: (url) => url.origin === origin,
  95. });
  96. try {
  97. const first = await cache.acquire({ ...bundle, url: `${origin}/hero.zip` });
  98. const second = await cache.acquire({ ...bundle, url: `${origin}/hero.zip` });
  99. expect((await cache.read(first.leaseId, first.entry)).toString()).toBe("<h1>Hello</h1>");
  100. expect(second.cacheHit).toBe(true);
  101. expect(requests).toBe(1);
  102. } finally {
  103. await new Promise<void>((resolve, reject) => {
  104. server.close((error) => (error ? reject(error) : resolve()));
  105. server.closeIdleConnections();
  106. });
  107. }
  108. });
  109. it("downloads, verifies, extracts, deduplicates and protects leased resources", async () => {
  110. const { root, bundle, cache, fetcher } = await fixture();
  111. const [first, second] = await Promise.all([cache.acquire(bundle), cache.acquire(bundle)]);
  112. expect(fetcher).toHaveBeenCalledTimes(1);
  113. expect(first.cacheHit).toBe(false);
  114. expect(second.cacheHit).toBe(true);
  115. expect(await readFile(join(root, bundle.sha256, "index.html"), "utf8")).toBe("<h1>Hello</h1>");
  116. expect((await cache.read(first.leaseId, "assets/main.js")).toString()).toBe("void 0");
  117. await expect(cache.read(first.leaseId, "../secret")).rejects.toThrow();
  118. await cache.clear();
  119. expect((await cache.read(first.leaseId, "index.html")).length).toBeGreaterThan(0);
  120. await cache.release(first.leaseId);
  121. await cache.release(second.leaseId);
  122. await cache.clear();
  123. await expect(cache.read(first.leaseId, "index.html")).rejects.toThrow();
  124. expect((await readdir(root)).filter((name) => name !== "staging")).toEqual([]);
  125. });
  126. it("rejects integrity failures without publishing partial cache", async () => {
  127. const { root, bundle, cache } = await fixture();
  128. await expect(cache.acquire({ ...bundle, sha256: "0".repeat(64) })).rejects.toThrow(/integrity/);
  129. expect(await readdir(join(root, "staging"))).toEqual([]);
  130. await expect(cache.acquire({ ...bundle, sizeBytes: bundle.sizeBytes + 1 })).rejects.toThrow(
  131. /size/,
  132. );
  133. });
  134. it("rejects missing entry and case-colliding ZIP files", async () => {
  135. for (const entries of [
  136. { "other.html": "hello" },
  137. { "index.html": "hello", "INDEX.HTML": "bad" },
  138. ]) {
  139. const { cache, bundle } = await fixture(entries);
  140. await expect(cache.acquire(bundle)).rejects.toThrow();
  141. }
  142. });
  143. it("rejects path traversal in ZIP metadata and removes staging", async () => {
  144. const { cache, bundle, bytes, fetcher, root } = await fixture();
  145. const malicious = Buffer.from(bytes);
  146. let index = malicious.indexOf("index.html");
  147. while (index !== -1) {
  148. malicious.write("../xx.html", index, "utf8");
  149. index = malicious.indexOf("index.html", index + 10);
  150. }
  151. fetcher.mockImplementation(async () => new Response(malicious));
  152. await expect(
  153. cache.acquire({ ...bundle, sha256: createHash("sha256").update(malicious).digest("hex") }),
  154. ).rejects.toThrow();
  155. expect(await readdir(join(root, "staging"))).toEqual([]);
  156. });
  157. it("checks trust before fetching and never follows an untrusted redirect", async () => {
  158. const { cache, bundle, fetcher } = await fixture();
  159. await expect(cache.acquire({ ...bundle, url: "http://127.0.0.1/private" })).rejects.toThrow(
  160. /source/,
  161. );
  162. expect(fetcher).not.toHaveBeenCalled();
  163. fetcher.mockImplementation(
  164. async () =>
  165. new Response(null, {
  166. status: 302,
  167. headers: { location: "https://untrusted.example/hero.zip" },
  168. }),
  169. );
  170. await expect(cache.acquire(bundle)).rejects.toThrow(/source/);
  171. expect(fetcher).toHaveBeenCalledTimes(1);
  172. });
  173. it("rejects unsafe cross-platform archive paths", () => {
  174. for (const path of [
  175. "../x",
  176. "/x",
  177. "C:/x",
  178. "a\\b",
  179. "a/../b",
  180. "a//b",
  181. "a/./b",
  182. "CON",
  183. "a/NUL.txt",
  184. "a.",
  185. "a ",
  186. ".bundle.json",
  187. ]) {
  188. expect(() => validateContentBundlePath(path)).toThrow();
  189. }
  190. expect(validateContentBundlePath("assets/main.js")).toBe("assets/main.js");
  191. });
  192. it("detects tampering on reads and rebuilds corrupt unleased cache", async () => {
  193. const { cache, bundle, root, fetcher } = await fixture();
  194. const lease = await cache.acquire(bundle);
  195. await writeFile(join(root, bundle.sha256, "index.html"), "tampered");
  196. await expect(cache.read(lease.leaseId, "index.html")).rejects.toThrow(/cache/);
  197. await expect(cache.acquire(bundle)).rejects.toThrow(/active_cache_corrupt/);
  198. await cache.release(lease.leaseId);
  199. const next = await cache.acquire(bundle);
  200. expect(next.cacheHit).toBe(false);
  201. expect(fetcher).toHaveBeenCalledTimes(2);
  202. expect((await cache.read(next.leaseId, "index.html")).toString()).toBe("<h1>Hello</h1>");
  203. });
  204. // Windows 普通用户无符号链接权限(需开发者模式),fs.symlink EPERM;覆盖由 CI Linux 承担。
  205. it.skipIf(process.platform === "win32")(
  206. "rejects symlink replacement and files outside the published manifest",
  207. async () => {
  208. const { cache, bundle, root } = await fixture();
  209. const lease = await cache.acquire(bundle);
  210. await writeFile(join(root, "secret"), "secret");
  211. await rm(join(root, bundle.sha256, "index.html"));
  212. await symlink(join(root, "secret"), join(root, bundle.sha256, "index.html"));
  213. await expect(cache.read(lease.leaseId, "index.html")).rejects.toThrow(/symlink/);
  214. await expect(cache.read(lease.leaseId, ".bundle.json")).rejects.toThrow();
  215. await expect(cache.read(lease.leaseId, "unknown.js")).rejects.toThrow(/missing/);
  216. },
  217. );
  218. it("enforces expanded file size and entry count before publishing", async () => {
  219. for (const entries of [
  220. { "index.html": "x".repeat(8 * 1024 * 1024 + 1) },
  221. Object.fromEntries(
  222. Array.from({ length: 129 }, (_, index) => [
  223. index === 0 ? "index.html" : `${index}.txt`,
  224. "x",
  225. ]),
  226. ),
  227. ]) {
  228. const { cache, bundle, root } = await fixture(entries);
  229. await expect(cache.acquire(bundle)).rejects.toThrow(/size|limit/);
  230. expect(await readdir(join(root, "staging"))).toEqual([]);
  231. }
  232. });
  233. });