🪢 Open source agent evals & observability: Trace, evaluate, and improve LLM applications with one open platform.
TypeScript analyticsautogenevaluationlangchainlarge-language-modelsllama-indexllmllm-evaluationllm-observabilityllmopsmonitoringobservabilityopen-sourceopenaiplaygroundprompt-engineeringprompt-managementself-hostedycombinator
fix(llm): honor NO_PROXY for outbound LLM requests when HTTPS_PROXY is set (#15467)
Steffen Schmitz3ab063cf8219
diff --git a/packages/shared/src/env.ts b/packages/shared/src/env.tsindex ae3f8efb8c..b5b844889c 100644--- a/packages/shared/src/env.ts+++ b/packages/shared/src/env.ts@@ -453,6 +453,12 @@ const EnvSchema = z.object({.default(1000) // Use high default to minimize number of API calls and hence avoid rate limits.describe("Number of channels to fetch per Slack API page"),HTTPS_PROXY: z.string().optional(),+ // Hosts that must be reached directly instead of through HTTPS_PROXY,+ // using the standard NO_PROXY grammar (undici EnvHttpProxyAgent+ // semantics). The lowercase variant wins when both are set, mirroring+ // undici and curl.+ NO_PROXY: z.string().optional(),+ no_proxy: z.string().optional(),LANGFUSE_SERVER_SIDE_IO_CHAR_LIMIT: z.coerce.number()diff --git a/packages/shared/src/server/llm/llmText.ts b/packages/shared/src/server/llm/llmText.tsindex 927e9f6197..1ac665ba36 100644--- a/packages/shared/src/server/llm/llmText.ts+++ b/packages/shared/src/server/llm/llmText.ts@@ -1,6 +1,5 @@import { type ZodType } from "zod";-import { ProxyAgent } from "undici";import {Output,generateText,@@ -286,9 +285,6 @@ async function prepareLLMTextCall<options.connection.extraHeaders,);- const proxyDispatcher = env.HTTPS_PROXY- ? new ProxyAgent(env.HTTPS_PROXY)- : undefined;const createFetch = (logContext: string,additionalSensitiveHeaders?: string[],@@ -301,7 +297,6 @@ async function prepareLLMTextCall<additionalSensitiveHeaders: (additionalSensitiveHeaders ?? []).concat(Object.keys(extraHeaders ?? {}),),- dispatcher: proxyDispatcher,});const languageModel = await buildAiSdkModel({diff --git a/packages/shared/src/server/llm/secureLlmFetch.ts b/packages/shared/src/server/llm/secureLlmFetch.tsindex f6032b26b1..7059e6495c 100644--- a/packages/shared/src/server/llm/secureLlmFetch.ts+++ b/packages/shared/src/server/llm/secureLlmFetch.ts@@ -1,6 +1,7 @@import {CircularRedirectError,fetchWithSecureRedirects,+ getOutboundProxyDispatcher,MaxRedirectsExceededError,OutboundUrlValidationError,RedirectValidationError,@@ -19,14 +20,12 @@ type SecureLlmFetchParams = {whitelist?: OutboundUrlValidationWhitelist;logContext: string;additionalSensitiveHeaders?: string[];- dispatcher?: unknown;};export function createSecureLlmFetch({whitelist = llmBaseUrlWhitelistFromEnv(),logContext,additionalSensitiveHeaders,- dispatcher,}: SecureLlmFetchParams): typeof fetch {return async (input, init) => {try {@@ -36,7 +35,6 @@ export function createSecureLlmFetch({whitelist,logContext,additionalSensitiveHeaders,- dispatcher,});} catch (cause) {const validationError = findSecureLlmValidationError(cause);@@ -62,16 +60,26 @@ export async function fetchSecureLlmUrl(whitelist = llmBaseUrlWhitelistFromEnv(),logContext,additionalSensitiveHeaders,- dispatcher,}: SecureLlmFetchParams,): Promise<Response> {await validateLlmConnectionBaseURL(url, whitelist);const optionsWithoutDispatcher = stripCallerDispatcher(options);- // If we have a proxy dispatcher (HTTPS_PROXY), attach it here so the- // outbound connection traverses the operator's proxy. Otherwise- // fetchWithSecureRedirects will inject the secure-lookup dispatcher.- const fetchOptions: RequestInit = dispatcher- ? ({ ...optionsWithoutDispatcher, dispatcher } as RequestInit)+ // If the operator configured HTTPS_PROXY, attach the NO_PROXY-aware proxy+ // dispatcher: proxied origins traverse the operator's proxy while NO_PROXY+ // matches connect directly through the secure-lookup dispatcher. Without a+ // proxy, fetchWithSecureRedirects will inject the secure-lookup dispatcher.+ // Typed as unknown at this boundary: fetch's RequestInit types dispatcher+ // via undici-types, which structurally drifts from the undici package's+ // Dispatcher across versions.+ const proxyDispatcher: unknown = getOutboundProxyDispatcher({+ whitelist,+ logContext,+ });+ const fetchOptions: RequestInit = proxyDispatcher+ ? ({+ ...optionsWithoutDispatcher,+ dispatcher: proxyDispatcher,+ } as RequestInit): optionsWithoutDispatcher;const { response } = await fetchWithSecureRedirects(url, fetchOptions, {diff --git a/packages/shared/src/server/outbound-url/connection.ts b/packages/shared/src/server/outbound-url/connection.tsindex 605bac7881..77aa30c11b 100644--- a/packages/shared/src/server/outbound-url/connection.ts+++ b/packages/shared/src/server/outbound-url/connection.ts@@ -2,7 +2,9 @@ import dns from "node:dns";import { Agent as HttpAgent } from "node:http";import { Agent as HttpsAgent } from "node:https";import type { LookupFunction } from "node:net";-import { Agent as UndiciAgent } from "undici";+import { Agent as UndiciAgent, type Dispatcher, ProxyAgent } from "undici";+import { env } from "../../env";+import { shouldBypassProxy } from "./noProxy";import type { OutboundUrlValidationWhitelist } from "./validation";import { validateOutboundResolvedIp } from "./validation";@@ -30,16 +32,20 @@ const secureOutboundHttpAgentsByPolicy = new Map<string,{ httpAgent: HttpAgent; httpsAgent: HttpsAgent }>();+const proxyAgentsByUri = new Map<string, ProxyAgent>();+const proxyRoutingDispatchersByPolicy = new Map<string, Dispatcher>();export function addSecureOutboundConnectionValidation(options: RequestInit,validationOptions: OutboundUrlConnectionValidationOptions,): RequestInit {if ((options as RequestInitWithDispatcher).dispatcher) {- // A dispatcher is already attached (today: HTTPS_PROXY routing via- // secureLlmFetch). Forward proxies own DNS resolution at the proxy hop,- // so a connect.lookup hook on our Agent would not see the target host- // anyway. Pre-fetch URL validation and redirect validation still run.+ // A dispatcher is already attached (today: the NO_PROXY-aware+ // HTTPS_PROXY routing dispatcher from secureLlmFetch). It sends NO_PROXY+ // matches through the secure-lookup dispatcher itself, and forward+ // proxies own DNS resolution at the proxy hop, so a connect.lookup hook+ // on our Agent would not see the target host anyway. Pre-fetch URL+ // validation and redirect validation still run.return options;}@@ -49,6 +55,56 @@ export function addSecureOutboundConnectionValidation(} as RequestInit & { dispatcher: UndiciAgent };}+/**+ * Returns the dispatcher for outbound requests when the operator configured a+ * forward proxy via HTTPS_PROXY, or undefined when no proxy is configured.+ *+ * The returned dispatcher decides per request (mirroring undici's+ * EnvHttpProxyAgent): origins matching NO_PROXY connect directly through the+ * secure-lookup dispatcher, so they keep connection-time DNS/IP validation;+ * every other origin traverses the proxy. Routing at dispatch time rather+ * than once per fetch keeps redirect chains correct when a hop crosses the+ * NO_PROXY boundary in either direction.+ */+export function getOutboundProxyDispatcher(+ validationOptions: OutboundUrlConnectionValidationOptions,+): Dispatcher | undefined {+ const proxyUri = env.HTTPS_PROXY;+ if (!proxyUri) return undefined;++ // Lowercase wins when both are set, mirroring undici and curl.+ const noProxyValue = env.no_proxy ?? env.NO_PROXY ?? "";+ const policyKey = JSON.stringify({+ proxyUri,+ noProxyValue,+ validation: getConnectionValidationPolicyKey(validationOptions),+ });++ return getOrCreatePolicyResource(+ proxyRoutingDispatchersByPolicy,+ policyKey,+ "proxy routing dispatcher",+ () => {+ const proxyAgent = getOrCreatePolicyResource(+ proxyAgentsByUri,+ proxyUri,+ "proxy agent",+ () => new ProxyAgent(proxyUri),+ );+ const directDispatcher = getSecureOutboundDispatcher(validationOptions);++ return proxyAgent.compose((dispatch) => (dispatchOptions, handler) => {+ // fetch always sets options.origin; undici's EnvHttpProxyAgent makes+ // the same assumption when it parses the origin for NO_PROXY matching.+ const origin = new URL(String(dispatchOptions.origin));+ return shouldBypassProxy(origin, noProxyValue)+ ? directDispatcher.dispatch(dispatchOptions, handler)+ : dispatch(dispatchOptions, handler);+ });+ },+ );+}+export function createSecureOutboundLookup(validationOptions: OutboundUrlConnectionValidationOptions,lookup: LookupFunction = dns.lookup,diff --git a/packages/shared/src/server/outbound-url/index.ts b/packages/shared/src/server/outbound-url/index.tsindex dcd4ebea96..418cfbc2e9 100644--- a/packages/shared/src/server/outbound-url/index.ts+++ b/packages/shared/src/server/outbound-url/index.ts@@ -1,3 +1,4 @@export * from "./connection";export * from "./fetch";+export * from "./noProxy";export * from "./validation";diff --git a/packages/shared/src/server/outbound-url/noProxy.test.ts b/packages/shared/src/server/outbound-url/noProxy.test.tsnew file mode 100644index 0000000000..d873c78b7a--- /dev/null+++ b/packages/shared/src/server/outbound-url/noProxy.test.ts@@ -0,0 +1,95 @@+import { describe, expect, it } from "vitest";+import { shouldBypassProxy } from "./noProxy";++const url = (value: string) => new URL(value);++describe("shouldBypassProxy", () => {+ it("proxies everything when NO_PROXY is empty", () => {+ expect(shouldBypassProxy(url("https://api.openai.com"), "")).toBe(false);+ expect(shouldBypassProxy(url("http://llm.internal.corp"), "")).toBe(false);+ });++ it("bypasses the proxy for every host on the wildcard", () => {+ expect(shouldBypassProxy(url("https://api.openai.com"), "*")).toBe(true);+ });++ it("bypasses on an exact hostname match", () => {+ expect(+ shouldBypassProxy(url("http://llm.internal.corp"), "llm.internal.corp"),+ ).toBe(true);+ expect(+ shouldBypassProxy(url("https://api.openai.com"), "llm.internal.corp"),+ ).toBe(false);+ });++ it("bypasses subdomains of an entry", () => {+ expect(+ shouldBypassProxy(url("http://llm.internal.corp"), "internal.corp"),+ ).toBe(true);+ expect(+ shouldBypassProxy(url("http://a.b.internal.corp"), "internal.corp"),+ ).toBe(true);+ });++ it("requires a domain-label boundary for suffix matches", () => {+ expect(+ shouldBypassProxy(url("http://evilinternal.corp"), "internal.corp"),+ ).toBe(false);+ });++ it("treats leading-dot and asterisk-dot entries like the bare domain", () => {+ for (const entry of [".internal.corp", "*.internal.corp"]) {+ expect(shouldBypassProxy(url("http://internal.corp"), entry)).toBe(true);+ expect(shouldBypassProxy(url("http://llm.internal.corp"), entry)).toBe(+ true,+ );+ }+ });++ it("matches case-insensitively", () => {+ expect(+ shouldBypassProxy(url("http://LLM.Internal.CORP"), "Internal.Corp"),+ ).toBe(true);+ });++ it("supports comma- and whitespace-separated lists", () => {+ const noProxy = "example.com, internal.corp\tother.example";+ expect(shouldBypassProxy(url("http://internal.corp"), noProxy)).toBe(true);+ expect(shouldBypassProxy(url("http://other.example"), noProxy)).toBe(true);+ expect(shouldBypassProxy(url("http://unrelated.io"), noProxy)).toBe(false);+ });++ it("restricts port-qualified entries to that port", () => {+ expect(+ shouldBypassProxy(url("http://internal.corp:8443"), "internal.corp:8443"),+ ).toBe(true);+ expect(+ shouldBypassProxy(url("http://internal.corp:9000"), "internal.corp:8443"),+ ).toBe(false);+ });++ it("compares port-qualified entries against protocol default ports", () => {+ expect(+ shouldBypassProxy(url("https://internal.corp"), "internal.corp:443"),+ ).toBe(true);+ expect(+ shouldBypassProxy(url("http://internal.corp"), "internal.corp:443"),+ ).toBe(false);+ });++ it("matches IP literals exactly", () => {+ expect(shouldBypassProxy(url("http://127.0.0.1:3000"), "127.0.0.1")).toBe(+ true,+ );+ expect(shouldBypassProxy(url("http://127.0.0.2:3000"), "127.0.0.1")).toBe(+ false,+ );+ });++ it("matches bracketed IPv6 entries against bracketed hosts", () => {+ // url.host keeps the brackets around IPv6 addresses, so entries must be+ // written with brackets too — the same behavior as undici.+ expect(shouldBypassProxy(url("http://[::1]:3000"), "[::1]")).toBe(true);+ expect(shouldBypassProxy(url("http://[::1]:3000"), "::1")).toBe(false);+ });+});diff --git a/packages/shared/src/server/outbound-url/noProxy.ts b/packages/shared/src/server/outbound-url/noProxy.tsnew file mode 100644index 0000000000..ef894d41d5--- /dev/null+++ b/packages/shared/src/server/outbound-url/noProxy.ts@@ -0,0 +1,68 @@+const DEFAULT_PORTS: Record<string, number> = {+ "http:": 80,+ "https:": 443,+};++type NoProxyEntry = {+ hostname: string;+ port: number;+};++function parseNoProxy(noProxyValue: string): NoProxyEntry[] {+ const entries: NoProxyEntry[] = [];++ for (const block of noProxyValue.split(/[,\s]/)) {+ if (!block) continue;++ const parsed = block.match(/^(.+):(\d+)$/);+ entries.push({+ // strip a leading dot or asterisk-with-dot so ".corp" / "*.corp"+ // behave like "corp": the host itself and all of its subdomains+ hostname: (parsed ? parsed[1] : block)+ .replace(/^\*?\./, "")+ .toLowerCase(),+ port: parsed ? Number.parseInt(parsed[2], 10) : 0,+ });+ }++ return entries;+}++/**+ * Decides whether a request to `url` must skip the forward proxy and connect+ * directly, using the same NO_PROXY semantics as undici's EnvHttpProxyAgent:+ * entries are comma- or whitespace-separated hostnames matched+ * case-insensitively against the target host and all of its subdomains, an+ * optional ":<port>" suffix restricts an entry to that port, and a value of+ * "*" bypasses the proxy for every host.+ */+export function shouldBypassProxy(url: URL, noProxyValue: string): boolean {+ const entries = parseNoProxy(noProxyValue);+ if (entries.length === 0) {+ return false; // always proxy when NO_PROXY is unset or empty+ }+ if (noProxyValue === "*") {+ return true; // never proxy when the wildcard is set+ }++ // Strip the port from url.host instead of using url.hostname so the+ // brackets around IPv6 addresses are kept, matching undici.+ const hostname = url.host.replace(/:\d*$/, "").toLowerCase();+ const port =+ Number.parseInt(url.port, 10) || DEFAULT_PORTS[url.protocol] || 0;++ for (const entry of entries) {+ if (entry.port && entry.port !== port) {+ continue;+ }+ if (hostname === entry.hostname) {+ return true;+ }+ // the hostname is a subdomain of the entry+ if (hostname.slice(-(entry.hostname.length + 1)) === `.${entry.hostname}`) {+ return true;+ }+ }++ return false;+}diff --git a/worker/src/__tests__/helpers/localForwardProxy.ts b/worker/src/__tests__/helpers/localForwardProxy.tsnew file mode 100644index 0000000000..cfdfa0e8b4--- /dev/null+++ b/worker/src/__tests__/helpers/localForwardProxy.ts@@ -0,0 +1,98 @@+import {+ createServer,+ request as httpRequest,+ type IncomingMessage,+ type ServerResponse,+} from "node:http";+import { connect as netConnect, type AddressInfo } from "node:net";+import type { Duplex } from "node:stream";++export type LocalForwardProxy = {+ url: string;+ /**+ * One entry per request that traversed the proxy: the absolute-form URL for+ * plain HTTP proxying, or "host:port" for CONNECT tunnels.+ */+ targets: string[];+ close: () => Promise<void>;+};++/**+ * Minimal HTTP forward proxy for tests. Supports both mechanisms a proxy+ * client may use: CONNECT tunneling (undici ProxyAgent's default for every+ * target) and absolute-form proxying of plain HTTP requests.+ */+export async function startLocalForwardProxy(): Promise<LocalForwardProxy> {+ const targets: string[] = [];+ // CONNECT hijacks sockets out of the server's HTTP connection tracking, so+ // closeAllConnections() misses them and server.close() would wait for the+ // peer. Track every socket explicitly and destroy them on close().+ const sockets = new Set<Duplex>();+ const trackSocket = (socket: Duplex) => {+ sockets.add(socket);+ socket.on("close", () => sockets.delete(socket));+ };++ const server = createServer((req: IncomingMessage, res: ServerResponse) => {+ const targetUrl = req.url ?? "";+ targets.push(targetUrl);++ const target = new URL(targetUrl);+ const upstream = httpRequest(+ {+ hostname: target.hostname,+ port: target.port,+ path: `${target.pathname}${target.search}`,+ method: req.method,+ headers: { ...req.headers, host: target.host },+ },+ (upstreamRes) => {+ res.writeHead(upstreamRes.statusCode ?? 502, upstreamRes.headers);+ upstreamRes.pipe(res);+ },+ );+ upstream.on("error", () => {+ res.statusCode = 502;+ res.end();+ });+ req.pipe(upstream);+ });++ server.on("connection", trackSocket);++ server.on(+ "connect",+ (req: IncomingMessage, clientSocket: Duplex, head: Buffer) => {+ const target = req.url ?? "";+ targets.push(target);++ const [host, port] = target.split(":");+ const upstream = netConnect(Number(port), host, () => {+ clientSocket.write("HTTP/1.1 200 Connection Established\r\n\r\n");+ upstream.write(head);+ clientSocket.pipe(upstream);+ upstream.pipe(clientSocket);+ });+ trackSocket(upstream);+ upstream.on("error", () => clientSocket.destroy());+ upstream.on("close", () => clientSocket.destroy());+ clientSocket.on("error", () => upstream.destroy());+ clientSocket.on("close", () => upstream.destroy());+ },+ );++ await new Promise<void>((resolve) => server.listen(0, "127.0.0.1", resolve));+ const port = (server.address() as AddressInfo).port;++ return {+ url: `http://127.0.0.1:${port}`,+ targets,+ close: () =>+ new Promise<void>((resolve, reject) => {+ server.close((err) => (err ? reject(err) : resolve()));+ // Keep-alive and tunneled sockets would otherwise keep close() pending.+ server.closeAllConnections();+ for (const socket of sockets) socket.destroy();+ }),+ };+}diff --git a/worker/src/__tests__/secureLlmFetch.test.ts b/worker/src/__tests__/secureLlmFetch.test.tsindex 90a02606f0..c608e8d2cc 100644--- a/worker/src/__tests__/secureLlmFetch.test.ts+++ b/worker/src/__tests__/secureLlmFetch.test.ts@@ -15,6 +15,10 @@ import {startLocalLlmServer,type LocalLlmServer,} from "./helpers/localLlmServer";+import {+ startLocalForwardProxy,+ type LocalForwardProxy,+} from "./helpers/localForwardProxy";// These tests replace the previous mock-heavy unit tests for the secure LLM// fetch path. The happy-path wiring is now proven against a real local HTTP@@ -442,6 +446,134 @@ describe("secure LLM fetch", () => {});});+ describe("HTTPS_PROXY / NO_PROXY routing", () => {+ const originalHttpsProxy = env.HTTPS_PROXY;+ const originalNoProxy = env.NO_PROXY;+ const originalNoProxyLower = env.no_proxy;+ const proxies: LocalForwardProxy[] = [];++ beforeEach(() => {+ env.HTTPS_PROXY = undefined;+ env.NO_PROXY = undefined;+ env.no_proxy = undefined;+ });++ afterEach(async () => {+ env.HTTPS_PROXY = originalHttpsProxy;+ env.NO_PROXY = originalNoProxy;+ env.no_proxy = originalNoProxyLower;+ await Promise.all(proxies.splice(0).map((p) => p.close()));+ });++ async function spinUpProxy() {+ const proxy = await startLocalForwardProxy();+ proxies.push(proxy);+ return proxy;+ }++ function spinUpTarget() {+ return spinUp((_req, _body, res) => {+ res.setHeader("content-type", "application/json");+ res.end(OPENAI_RESPONSE_BODY);+ });+ }++ async function fetchThroughSecureLlmFetch(url: string) {+ const secureFetch = createSecureLlmFetch({+ logContext: "Test LLM endpoint",+ });+ const response = await secureFetch(`${url}/v1/chat/completions`, {+ method: "POST",+ body: JSON.stringify({ messages: [] }),+ });+ // Consume the body so keep-alive sockets return to the pool instead of+ // staying busy until close.+ await response.text();+ return response;+ }++ test("routes requests through HTTPS_PROXY when NO_PROXY does not match", async () => {+ const target = await spinUpTarget();+ const proxy = await spinUpProxy();++ env.HTTPS_PROXY = proxy.url;+ env.NO_PROXY = "does-not-match.example";++ const response = await fetchThroughSecureLlmFetch(target.url);++ expect(response.status).toBe(200);+ expect(proxy.targets).toHaveLength(1);+ expect(target.requests).toHaveLength(1);+ });++ test("connects directly when the target host matches NO_PROXY", async () => {+ const target = await spinUpTarget();+ const proxy = await spinUpProxy();++ env.HTTPS_PROXY = proxy.url;+ env.NO_PROXY = "127.0.0.1";++ const response = await fetchThroughSecureLlmFetch(target.url);++ expect(response.status).toBe(200);+ expect(proxy.targets).toHaveLength(0);+ expect(target.requests).toHaveLength(1);+ });++ test("NO_PROXY=* connects directly for every host", async () => {+ const target = await spinUpTarget();+ const proxy = await spinUpProxy();++ env.HTTPS_PROXY = proxy.url;+ env.NO_PROXY = "*";++ const response = await fetchThroughSecureLlmFetch(target.url);++ expect(response.status).toBe(200);+ expect(proxy.targets).toHaveLength(0);+ expect(target.requests).toHaveLength(1);+ });++ test("the lowercase no_proxy variant wins over NO_PROXY", async () => {+ const target = await spinUpTarget();+ const proxy = await spinUpProxy();++ env.HTTPS_PROXY = proxy.url;+ env.no_proxy = "127.0.0.1";+ env.NO_PROXY = "does-not-match.example";++ const response = await fetchThroughSecureLlmFetch(target.url);++ expect(response.status).toBe(200);+ expect(proxy.targets).toHaveLength(0);+ expect(target.requests).toHaveLength(1);+ });++ test("redirect hops re-evaluate NO_PROXY per origin", async () => {+ const target = await spinUpTarget();+ const redirector = await spinUp((_req, _body, res) => {+ res.statusCode = 302;+ res.setHeader("location", `${target.url}/v1/chat/completions`);+ res.end();+ });+ const proxy = await spinUpProxy();++ env.HTTPS_PROXY = proxy.url;+ // Port-qualified entry: only the redirector bypasses the proxy, the+ // redirect target (same host, different port) must be proxied.+ env.NO_PROXY = `127.0.0.1:${new URL(redirector.url).port}`;++ const response = await fetchThroughSecureLlmFetch(redirector.url);++ expect(response.status).toBe(200);+ expect(redirector.requests).toHaveLength(1);+ expect(target.requests).toHaveLength(1);+ // Exactly one hop (the redirect target) traversed the proxy.+ expect(proxy.targets).toHaveLength(1);+ expect(proxy.targets[0]).toContain(`:${new URL(target.url).port}`);+ });+ });+describe("abort signal propagation", () => {test("forwards the caller's signal instance to the underlying fetch", async () => {// Identity matters, not just abort wiring: undici links init.signal to