http.test.ts 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714
  1. import http, { type Server } from "node:http";
  2. import { mkdtemp, rm, writeFile } from "node:fs/promises";
  3. import type { AddressInfo } from "node:net";
  4. import { tmpdir } from "node:os";
  5. import { join } from "node:path";
  6. import { afterEach, describe, expect, it, vi } from "vitest";
  7. import { createRootTraceContext, isHttpClientPortError } from "@zcode/contracts";
  8. import { ZCODE_TOOL_ENV_PASSTHROUGH_ENV_KEY } from "@zcode/shared";
  9. import {
  10. createNodeHttpClientAdapter,
  11. createNodeWebFetchHttpClientAdapter,
  12. } from "../src/http/index.js";
  13. import {
  14. loadTlsCaCertificates,
  15. resolveProxyForRequest,
  16. resolveWebFetchProxyForRequest,
  17. resolveTlsCaCertFile,
  18. } from "../src/network/http-config.js";
  19. import { createNetworkProxyFetch } from "../src/network/proxy-fetch.js";
  20. describe("NodeHttpClientAdapter", () => {
  21. afterEach(() => {
  22. vi.unstubAllGlobals();
  23. });
  24. it("propagates trace ids through a request header", async () => {
  25. const fetchMock = vi.fn(async () => new Response("ok", { status: 200 }));
  26. vi.stubGlobal("fetch", fetchMock);
  27. const adapter = createNodeHttpClientAdapter();
  28. const output = await adapter.request({
  29. url: "https://example.com/page",
  30. trace: createRootTraceContext({ traceId: "trace-http" as never }),
  31. });
  32. const init = fetchMock.mock.calls[0]?.[1] as RequestInit | undefined;
  33. expect(output).toMatchObject({
  34. bytes: 2,
  35. status: 200,
  36. url: "https://example.com/page",
  37. });
  38. expect(init?.headers).toBeInstanceOf(Headers);
  39. expect((init?.headers as Headers).get("x-zcode-trace-id")).toBe("trace-http");
  40. });
  41. it("forwards POST request bodies", async () => {
  42. const fetchMock = vi.fn(async () => new Response("ok", { status: 200 }));
  43. vi.stubGlobal("fetch", fetchMock);
  44. const adapter = createNodeHttpClientAdapter();
  45. const body = new TextEncoder().encode('{"hello":"world"}');
  46. await adapter.request({
  47. body,
  48. headers: { "content-type": "application/json" },
  49. method: "POST",
  50. url: "https://example.com/api",
  51. });
  52. const init = fetchMock.mock.calls[0]?.[1] as RequestInit | undefined;
  53. expect(init?.method).toBe("POST");
  54. expect(init?.body).toEqual(Buffer.from(body));
  55. });
  56. it("routes requests through explicit ZCODE_HTTP_PROXY env", async () => {
  57. const proxyRequests: string[] = [];
  58. const upstream = http.createServer((request, response) => {
  59. response.writeHead(200, { "content-type": "application/json" });
  60. response.end(JSON.stringify({ path: request.url, success: true }));
  61. });
  62. const proxy = http.createServer((clientRequest, clientResponse) => {
  63. proxyRequests.push(clientRequest.url ?? "");
  64. if (!clientRequest.url) {
  65. clientResponse.writeHead(400);
  66. clientResponse.end();
  67. return;
  68. }
  69. const target = new URL(clientRequest.url);
  70. const upstreamRequest = http.request(
  71. {
  72. headers: clientRequest.headers,
  73. hostname: target.hostname,
  74. method: clientRequest.method,
  75. path: `${target.pathname}${target.search}`,
  76. port: target.port,
  77. },
  78. (upstreamResponse) => {
  79. clientResponse.writeHead(upstreamResponse.statusCode ?? 502, upstreamResponse.headers);
  80. upstreamResponse.pipe(clientResponse);
  81. },
  82. );
  83. upstreamRequest.once("error", (error) => {
  84. clientResponse.writeHead(502, { "content-type": "text/plain" });
  85. clientResponse.end(String(error));
  86. });
  87. clientRequest.pipe(upstreamRequest);
  88. });
  89. try {
  90. const upstreamBaseUrl = await listenServer(upstream);
  91. const proxyBaseUrl = await listenServer(proxy);
  92. const adapter = createNodeHttpClientAdapter({
  93. env: {
  94. ZCODE_HTTP_PROXY: proxyBaseUrl,
  95. },
  96. });
  97. const response = await adapter.request({
  98. url: `${upstreamBaseUrl}/v1/search?q=test`,
  99. });
  100. expect(JSON.parse(new TextDecoder().decode(response.body))).toEqual({
  101. path: "/v1/search?q=test",
  102. success: true,
  103. });
  104. expect(response.egress).toMatchObject({
  105. proxied: true,
  106. proxyHost: new URL(proxyBaseUrl).host,
  107. proxySource: "env:ZCODE_HTTP_PROXY",
  108. });
  109. expect(proxyRequests).toEqual([`${upstreamBaseUrl}/v1/search?q=test`]);
  110. } finally {
  111. await closeServer(proxy);
  112. await closeServer(upstream);
  113. }
  114. });
  115. it("bypasses explicit proxy when configured noProxy matches the target host", async () => {
  116. const proxyRequests: string[] = [];
  117. const upstream = http.createServer((_request, response) => {
  118. response.writeHead(200, { "content-type": "application/json" });
  119. response.end(JSON.stringify({ direct: true, success: true }));
  120. });
  121. const proxy = http.createServer((request, response) => {
  122. proxyRequests.push(request.url ?? "");
  123. response.writeHead(502, { "content-type": "application/json" });
  124. response.end(JSON.stringify({ success: false }));
  125. });
  126. try {
  127. const upstreamBaseUrl = await listenServer(upstream);
  128. const proxyBaseUrl = await listenServer(proxy);
  129. const adapter = createNodeHttpClientAdapter({
  130. env: {
  131. ZCODE_HTTP_PROXY: proxyBaseUrl,
  132. },
  133. noProxy: "127.0.0.1",
  134. });
  135. const response = await adapter.request({
  136. url: `${upstreamBaseUrl}/v1/search?q=test`,
  137. });
  138. expect(JSON.parse(new TextDecoder().decode(response.body))).toEqual({
  139. direct: true,
  140. success: true,
  141. });
  142. expect(response.egress).toMatchObject({
  143. noProxyMatched: true,
  144. proxied: false,
  145. });
  146. expect(proxyRequests).toEqual([]);
  147. } finally {
  148. await closeServer(proxy);
  149. await closeServer(upstream);
  150. }
  151. });
  152. it("bypasses explicit proxy when ZCODE_NO_PROXY matches the target host", async () => {
  153. const proxyRequests: string[] = [];
  154. const upstream = http.createServer((_request, response) => {
  155. response.writeHead(200, { "content-type": "application/json" });
  156. response.end(JSON.stringify({ direct: true, success: true }));
  157. });
  158. const proxy = http.createServer((request, response) => {
  159. proxyRequests.push(request.url ?? "");
  160. response.writeHead(502, { "content-type": "application/json" });
  161. response.end(JSON.stringify({ success: false }));
  162. });
  163. try {
  164. const upstreamBaseUrl = await listenServer(upstream);
  165. const proxyBaseUrl = await listenServer(proxy);
  166. const adapter = createNodeHttpClientAdapter({
  167. env: {
  168. ZCODE_HTTP_PROXY: proxyBaseUrl,
  169. ZCODE_NO_PROXY: "127.0.0.1",
  170. },
  171. });
  172. const response = await adapter.request({
  173. url: `${upstreamBaseUrl}/v1/search?q=test`,
  174. });
  175. expect(JSON.parse(new TextDecoder().decode(response.body))).toEqual({
  176. direct: true,
  177. success: true,
  178. });
  179. expect(response.egress).toMatchObject({
  180. noProxyMatched: true,
  181. proxied: false,
  182. });
  183. expect(proxyRequests).toEqual([]);
  184. } finally {
  185. await closeServer(proxy);
  186. await closeServer(upstream);
  187. }
  188. });
  189. it("uses explicit ZCODE_AGENT_CA_CERT for custom CA resolution", () => {
  190. expect(
  191. resolveTlsCaCertFile({
  192. env: {
  193. NODE_EXTRA_CA_CERTS: "/tmp/ambient-node-extra.pem",
  194. SSL_CERT_FILE: "/tmp/ambient-ssl-cert-file.pem",
  195. ZCODE_AGENT_CA_CERT: "/tmp/zcode-agent-ca.pem",
  196. },
  197. }),
  198. ).toBe("/tmp/zcode-agent-ca.pem");
  199. });
  200. it("prefers configured CA cert files over TLS env files", () => {
  201. expect(
  202. resolveTlsCaCertFile({
  203. caCertFile: "/tmp/configured-ca.pem",
  204. env: {
  205. ZCODE_AGENT_CA_CERT: "/tmp/env-ca.pem",
  206. },
  207. }),
  208. ).toBe("/tmp/configured-ca.pem");
  209. });
  210. it("ignores ambient standard proxy and CA env", async () => {
  211. const proxyRequests: string[] = [];
  212. const upstream = http.createServer((_request, response) => {
  213. response.writeHead(200, { "content-type": "application/json" });
  214. response.end(JSON.stringify({ direct: true, success: true }));
  215. });
  216. const proxy = http.createServer((request, response) => {
  217. proxyRequests.push(request.url ?? "");
  218. response.writeHead(502, { "content-type": "application/json" });
  219. response.end(JSON.stringify({ success: false }));
  220. });
  221. try {
  222. const upstreamBaseUrl = await listenServer(upstream);
  223. const proxyBaseUrl = await listenServer(proxy);
  224. const adapter = createNodeHttpClientAdapter({
  225. env: {
  226. http_proxy: proxyBaseUrl,
  227. NODE_EXTRA_CA_CERTS: "/tmp/ambient-ca.pem",
  228. },
  229. });
  230. const response = await adapter.request({
  231. url: `${upstreamBaseUrl}/v1/search?q=test`,
  232. });
  233. expect(JSON.parse(new TextDecoder().decode(response.body))).toEqual({
  234. direct: true,
  235. success: true,
  236. });
  237. expect(response.egress).toMatchObject({
  238. proxied: false,
  239. });
  240. expect(proxyRequests).toEqual([]);
  241. expect(
  242. resolveTlsCaCertFile({ env: { NODE_EXTRA_CA_CERTS: "/tmp/ambient-ca.pem" } }),
  243. ).toBeUndefined();
  244. } finally {
  245. await closeServer(proxy);
  246. await closeServer(upstream);
  247. }
  248. });
  249. it("loads CA certificates from custom TLS env files", async () => {
  250. const directory = await mkdtemp(join(tmpdir(), "zcode-http-ca-"));
  251. const certPath = join(directory, "ca.pem");
  252. const pem = "-----BEGIN CERTIFICATE-----\nTEST\n-----END CERTIFICATE-----\n";
  253. try {
  254. await writeFile(certPath, pem, "utf8");
  255. expect(
  256. loadTlsCaCertificates({
  257. env: {
  258. ZCODE_AGENT_CA_CERT: certPath,
  259. },
  260. })?.toString("utf8"),
  261. ).toBe(pem);
  262. } finally {
  263. await rm(directory, { force: true, recursive: true });
  264. }
  265. });
  266. it("destroys proxy fetch response streams when aborted after headers", async () => {
  267. const directory = await mkdtemp(join(tmpdir(), "zcode-http-abort-"));
  268. const certPath = join(directory, "ca.pem");
  269. const serverClosed = deferred();
  270. const server = http.createServer((_request, response) => {
  271. response.writeHead(200, { "content-type": "text/event-stream" });
  272. response.write("data: started\n\n");
  273. response.once("close", () => {
  274. serverClosed.resolve();
  275. });
  276. });
  277. try {
  278. await writeFile(certPath, "-----BEGIN CERTIFICATE-----\nTEST\n-----END CERTIFICATE-----\n", "utf8");
  279. const baseUrl = await listenServer(server);
  280. const fetch = createNetworkProxyFetch({ caCertFile: certPath });
  281. const abortController = new AbortController();
  282. const response = await fetch(`${baseUrl}/stream`, { signal: abortController.signal });
  283. const reader = response.body?.getReader();
  284. expect(reader).toBeDefined();
  285. const firstChunk = await reader?.read();
  286. expect(new TextDecoder().decode(firstChunk?.value)).toContain("data: started");
  287. const pendingRead = reader?.read();
  288. const pendingReadRejected = expect(pendingRead).rejects.toThrow(/test abort|aborted/i);
  289. abortController.abort(new Error("test abort"));
  290. await expect(withTimeout(serverClosed.promise, 1_000)).resolves.toBeUndefined();
  291. await pendingReadRejected;
  292. } finally {
  293. await closeServer(server);
  294. await rm(directory, { force: true, recursive: true });
  295. }
  296. });
  297. it("destroys proxy fetch requests when aborted before response headers", async () => {
  298. const directory = await mkdtemp(join(tmpdir(), "zcode-http-abort-pending-"));
  299. const certPath = join(directory, "ca.pem");
  300. const requestReceived = deferred();
  301. const serverClosed = deferred();
  302. const server = http.createServer((request, _response) => {
  303. requestReceived.resolve();
  304. request.once("close", () => {
  305. serverClosed.resolve();
  306. });
  307. });
  308. try {
  309. await writeFile(certPath, "-----BEGIN CERTIFICATE-----\nTEST\n-----END CERTIFICATE-----\n", "utf8");
  310. const baseUrl = await listenServer(server);
  311. const fetch = createNetworkProxyFetch({ caCertFile: certPath });
  312. const abortController = new AbortController();
  313. const pendingFetch = fetch(`${baseUrl}/pending`, { signal: abortController.signal });
  314. const pendingRejected = expect(pendingFetch).rejects.toThrow(/test abort|aborted/i);
  315. await expect(withTimeout(requestReceived.promise, 1_000)).resolves.toBeUndefined();
  316. abortController.abort(new Error("test abort"));
  317. await pendingRejected;
  318. await expect(withTimeout(serverClosed.promise, 1_000)).resolves.toBeUndefined();
  319. } finally {
  320. await closeServer(server);
  321. await rm(directory, { force: true, recursive: true });
  322. }
  323. });
  324. it("fails before reading responses that exceed the declared content length budget", async () => {
  325. vi.stubGlobal(
  326. "fetch",
  327. vi.fn(async () =>
  328. new Response("too large", {
  329. headers: { "content-length": "9" },
  330. status: 200,
  331. }),
  332. ),
  333. );
  334. const adapter = createNodeHttpClientAdapter();
  335. await expect(
  336. adapter.request({
  337. maxResponseBytes: 8,
  338. url: "https://example.com/large",
  339. }),
  340. ).rejects.toMatchObject({
  341. code: "too_large",
  342. url: "https://example.com/large",
  343. });
  344. });
  345. it("rejects unsupported protocols without touching fetch", async () => {
  346. const fetchMock = vi.fn();
  347. vi.stubGlobal("fetch", fetchMock);
  348. const adapter = createNodeHttpClientAdapter();
  349. await expect(adapter.request({ url: "file:///tmp/demo.txt" })).rejects.toSatisfy(
  350. isHttpClientPortError,
  351. );
  352. expect(fetchMock).not.toHaveBeenCalled();
  353. });
  354. it("blocks public egress requests when DNS resolves to a non-public address", async () => {
  355. const fetchMock = vi.fn();
  356. vi.stubGlobal("fetch", fetchMock);
  357. const adapter = createNodeHttpClientAdapter({
  358. dnsLookup: async () => [{ address: "169.254.169.254", family: 4 }],
  359. });
  360. const request = adapter.request({
  361. egressPolicy: "public",
  362. url: "https://metadata.example/latest",
  363. });
  364. await expect(request).rejects.toThrow(
  365. "HTTP public egress blocked metadata.example because it resolved to a non-public address",
  366. );
  367. await expect(request).rejects.toMatchObject({
  368. code: "egress_blocked",
  369. url: "https://metadata.example/latest",
  370. });
  371. expect(fetchMock).not.toHaveBeenCalled();
  372. });
  373. it("applies request timeout while resolving public egress DNS", async () => {
  374. const adapter = createNodeHttpClientAdapter({
  375. dnsLookup: async () => new Promise(() => undefined),
  376. });
  377. await expect(
  378. Promise.race([
  379. adapter.request({
  380. egressPolicy: "public",
  381. timeoutMs: 20,
  382. url: "https://example.com/slow-dns",
  383. }),
  384. new Promise((_, reject) =>
  385. setTimeout(() => reject(new Error("public egress DNS preflight did not time out")), 200),
  386. ),
  387. ]),
  388. ).rejects.toMatchObject({
  389. code: "timeout",
  390. url: "https://example.com/slow-dns",
  391. });
  392. });
  393. it("applies caller abort while resolving public egress DNS", async () => {
  394. const abortController = new AbortController();
  395. const adapter = createNodeHttpClientAdapter({
  396. dnsLookup: async () => new Promise(() => undefined),
  397. });
  398. const request = adapter.request(
  399. {
  400. egressPolicy: "public",
  401. timeoutMs: 1_000,
  402. url: "https://example.com/abort-dns",
  403. },
  404. { signal: abortController.signal },
  405. );
  406. abortController.abort(new Error("manual abort"));
  407. await expect(
  408. Promise.race([
  409. request,
  410. new Promise((_, reject) =>
  411. setTimeout(() => reject(new Error("public egress DNS preflight ignored abort")), 200),
  412. ),
  413. ]),
  414. ).rejects.toMatchObject({
  415. code: "cancelled",
  416. url: "https://example.com/abort-dns",
  417. });
  418. });
  419. it("applies caller abort when it fires during public egress DNS lookup setup", async () => {
  420. const abortController = new AbortController();
  421. const adapter = createNodeHttpClientAdapter({
  422. dnsLookup: async () => {
  423. abortController.abort(new Error("manual abort during lookup setup"));
  424. return new Promise(() => undefined);
  425. },
  426. });
  427. await expect(
  428. Promise.race([
  429. adapter.request(
  430. {
  431. egressPolicy: "public",
  432. timeoutMs: 1_000,
  433. url: "https://example.com/abort-dns-setup",
  434. },
  435. { signal: abortController.signal },
  436. ),
  437. new Promise((_, reject) =>
  438. setTimeout(() => reject(new Error("public egress DNS setup abort was missed")), 200),
  439. ),
  440. ]),
  441. ).rejects.toMatchObject({
  442. code: "cancelled",
  443. url: "https://example.com/abort-dns-setup",
  444. });
  445. });
  446. it("blocks public egress requests when DNS resolves to IPv4-mapped non-public IPv6", async () => {
  447. const adapter = createNodeHttpClientAdapter({
  448. dnsLookup: async () => [{ address: "::ffff:7f00:1", family: 6 }],
  449. });
  450. await expect(
  451. adapter.request({
  452. egressPolicy: "public",
  453. timeoutMs: 100,
  454. url: "https://metadata.example:9/latest",
  455. }),
  456. ).rejects.toMatchObject({
  457. code: "egress_blocked",
  458. url: "https://metadata.example:9/latest",
  459. });
  460. });
  461. it("blocks public egress requests through ordinary proxies", async () => {
  462. const dnsLookup = vi.fn(async () => [{ address: "93.184.216.34", family: 4 }]);
  463. const adapter = createNodeHttpClientAdapter({
  464. dnsLookup,
  465. proxyUrl: "http://127.0.0.1:9",
  466. });
  467. await expect(
  468. adapter.request({
  469. egressPolicy: "public",
  470. timeoutMs: 100,
  471. url: "https://public.example/page",
  472. }),
  473. ).rejects.toMatchObject({
  474. code: "egress_blocked",
  475. message: expect.stringContaining("proxy"),
  476. url: "https://public.example/page",
  477. });
  478. expect(dnsLookup).not.toHaveBeenCalled();
  479. });
  480. it("blocks public egress requests to literal non-public addresses", async () => {
  481. const fetchMock = vi.fn();
  482. vi.stubGlobal("fetch", fetchMock);
  483. const adapter = createNodeHttpClientAdapter();
  484. await expect(
  485. adapter.request({
  486. egressPolicy: "public",
  487. url: "https://127.0.0.1/status",
  488. }),
  489. ).rejects.toMatchObject({
  490. code: "egress_blocked",
  491. url: "https://127.0.0.1/status",
  492. });
  493. expect(fetchMock).not.toHaveBeenCalled();
  494. });
  495. it("does not use captured user proxy env through the default proxy resolver", () => {
  496. const resolution = resolveProxyForRequest("http://example.com/page", {
  497. env: {
  498. [ZCODE_TOOL_ENV_PASSTHROUGH_ENV_KEY]: JSON.stringify({
  499. HTTPS_PROXY: "http://captured-proxy.example:8080",
  500. }),
  501. },
  502. });
  503. expect(resolution).toEqual({
  504. noProxyMatched: false,
  505. });
  506. });
  507. it("does not let captured no_proxy bypass explicit proxy in the default resolver", () => {
  508. expect(
  509. resolveProxyForRequest("http://api.example.com/page", {
  510. env: {
  511. [ZCODE_TOOL_ENV_PASSTHROUGH_ENV_KEY]: JSON.stringify({
  512. no_proxy: "example.com",
  513. }),
  514. },
  515. httpProxy: "http://explicit-proxy.example:8080",
  516. }),
  517. ).toMatchObject({
  518. noProxyMatched: false,
  519. proxySource: "network.httpProxy",
  520. proxyUrl: "http://explicit-proxy.example:8080/",
  521. });
  522. });
  523. it("routes requests through captured user proxy env", async () => {
  524. const proxyRequests: string[] = [];
  525. const proxy = http.createServer((request, response) => {
  526. proxyRequests.push(request.url ?? "");
  527. response.writeHead(200, { "content-type": "text/plain" });
  528. response.end("captured proxied");
  529. });
  530. try {
  531. const proxyBaseUrl = await listenServer(proxy);
  532. const adapter = createNodeWebFetchHttpClientAdapter({
  533. env: {
  534. [ZCODE_TOOL_ENV_PASSTHROUGH_ENV_KEY]: JSON.stringify({
  535. HTTP_PROXY: proxyBaseUrl,
  536. }),
  537. },
  538. });
  539. const response = await adapter.request({
  540. timeoutMs: 1_000,
  541. url: "http://public.example/from-captured-proxy",
  542. });
  543. expect(new TextDecoder().decode(response.body)).toBe("captured proxied");
  544. expect(response.egress).toMatchObject({
  545. proxied: true,
  546. proxyHost: new URL(proxyBaseUrl).host,
  547. proxySource: `env:${ZCODE_TOOL_ENV_PASSTHROUGH_ENV_KEY}.HTTP_PROXY`,
  548. });
  549. expect(proxyRequests).toEqual(["http://public.example/from-captured-proxy"]);
  550. } finally {
  551. await closeServer(proxy);
  552. }
  553. });
  554. it("prefers lowercase captured proxy env over uppercase variants", () => {
  555. expect(
  556. resolveWebFetchProxyForRequest("http://example.com/page", {
  557. env: {
  558. [ZCODE_TOOL_ENV_PASSTHROUGH_ENV_KEY]: JSON.stringify({
  559. HTTPS_PROXY: "http://upper-https-proxy.example:8080",
  560. https_proxy: "http://lower-https-proxy.example:8080",
  561. HTTP_PROXY: "http://upper-http-proxy.example:8080",
  562. http_proxy: "http://lower-http-proxy.example:8080",
  563. }),
  564. },
  565. }),
  566. ).toMatchObject({
  567. proxySource: `env:${ZCODE_TOOL_ENV_PASSTHROUGH_ENV_KEY}.https_proxy`,
  568. proxyUrl: "http://lower-https-proxy.example:8080/",
  569. });
  570. });
  571. it("prefers lowercase captured no_proxy over uppercase variants", () => {
  572. const resolution = resolveWebFetchProxyForRequest("http://api.example.com/page", {
  573. env: {
  574. [ZCODE_TOOL_ENV_PASSTHROUGH_ENV_KEY]: JSON.stringify({
  575. HTTP_PROXY: "http://proxy.example:8080",
  576. NO_PROXY: "other.example",
  577. no_proxy: "example.com",
  578. }),
  579. },
  580. });
  581. expect(resolution).toMatchObject({
  582. noProxyMatched: true,
  583. });
  584. expect(resolution.proxyUrl).toBeUndefined();
  585. });
  586. });
  587. async function listenServer(server: Server): Promise<string> {
  588. await new Promise<void>((resolve, reject) => {
  589. server.once("error", reject);
  590. server.listen(0, "127.0.0.1", () => {
  591. server.off("error", reject);
  592. resolve();
  593. });
  594. });
  595. const address = server.address() as AddressInfo | null;
  596. if (!address) {
  597. throw new Error("Expected server address");
  598. }
  599. return `http://127.0.0.1:${address.port}`;
  600. }
  601. async function closeServer(server: Server): Promise<void> {
  602. if (!server.listening) {
  603. return;
  604. }
  605. await new Promise<void>((resolve, reject) => {
  606. server.close((error) => {
  607. if (error) {
  608. reject(error);
  609. return;
  610. }
  611. resolve();
  612. });
  613. });
  614. }
  615. function deferred(): { promise: Promise<void>; resolve(): void } {
  616. let resolveDeferred: () => void = () => {};
  617. const promise = new Promise<void>((resolve) => {
  618. resolveDeferred = resolve;
  619. });
  620. return {
  621. promise,
  622. resolve: resolveDeferred,
  623. };
  624. }
  625. function withTimeout<T>(promise: Promise<T>, timeoutMs: number): Promise<T> {
  626. return new Promise<T>((resolve, reject) => {
  627. const timeout = setTimeout(() => {
  628. reject(new Error(`Timed out after ${timeoutMs}ms`));
  629. }, timeoutMs);
  630. promise.then(
  631. (value) => {
  632. clearTimeout(timeout);
  633. resolve(value);
  634. },
  635. (error: unknown) => {
  636. clearTimeout(timeout);
  637. reject(error);
  638. },
  639. );
  640. });
  641. }