Skip to content

🪢 Open source agent evals & observability: Trace, evaluate, and improve LLM applications with one open platform.

fix(shared): validate outbound fetch DNS at connection time (#13554)

Tobias Wochinger35830bcf7eb0
diff --git a/packages/shared/src/server/outbound-url/connection.ts b/packages/shared/src/server/outbound-url/connection.ts
new file mode 100644
index 0000000000..63d2897c9b
--- /dev/null
+++ b/packages/shared/src/server/outbound-url/connection.ts
@@ -0,0 +1,151 @@
+import dns from "node:dns";
+import { Agent } from "undici";
+import type { OutboundUrlValidationWhitelist } from "./validation";
+import { validateOutboundResolvedIp } from "./validation";
+
+// We currently expect only a few policy/context combinations in normal
+// operation, e.g. strict image URL validation and webhook/self-hosting env
+// validation. Keep the cap well above that to allow future static policies, but
+// low enough to catch accidental high-cardinality whitelists before they create
+// unbounded Agent pools.
+const OUTBOUND_AGENT_POLICY_LIMIT = 32;
+const DEFAULT_OUTBOUND_URL_VALIDATION_WHITELIST: OutboundUrlValidationWhitelist =
+ {
+ hosts: [],
+ ips: [],
+ ip_ranges: [],
+ };
+
+type DnsLookupCallback = (
+ err: NodeJS.ErrnoException | null,
+ address: string | dns.LookupAddress[],
+ family?: number,
+) => void;
+type DnsLookup = (
+ hostname: string,
+ options: dns.LookupOptions,
+ callback: DnsLookupCallback,
+) => void;
+
+export interface OutboundUrlConnectionValidationOptions {
+ whitelist?: OutboundUrlValidationWhitelist;
+ logContext?: string;
+}
+
+type RequestInitWithUndiciDispatcher = RequestInit & {
+ dispatcher?: Agent;
+};
+
+const secureOutboundDispatchersByPolicy = new Map<string, Agent>();
+
+export function addSecureOutboundConnectionValidation(
+ options: RequestInit,
+ validationOptions: OutboundUrlConnectionValidationOptions,
+): RequestInit {
+ return {
+ ...options,
+ dispatcher: getSecureOutboundDispatcher(validationOptions),
+ } as RequestInitWithUndiciDispatcher;
+}
+
+function createSecureOutboundLookup(
+ validationOptions: OutboundUrlConnectionValidationOptions,
+ lookup: typeof dns.lookup = dns.lookup,
+): DnsLookup {
+ return (hostname, options, callback) => {
+ lookup(hostname, options, (err, address, family) => {
+ if (err) {
+ callback(err, address, family);
+ return;
+ }
+
+ try {
+ validateConnectionTimeLookupResult(
+ hostname,
+ address,
+ validationOptions,
+ );
+ } catch (error) {
+ callback(error as NodeJS.ErrnoException, address, family);
+ return;
+ }
+
+ callback(null, address, family);
+ });
+ };
+}
+
+function getSecureOutboundDispatcher(
+ validationOptions: OutboundUrlConnectionValidationOptions,
+): Agent {
+ const policyKey = getConnectionValidationPolicyKey(validationOptions);
+ const existingDispatcher = secureOutboundDispatchersByPolicy.get(policyKey);
+ if (existingDispatcher) return existingDispatcher;
+
+ if (secureOutboundDispatchersByPolicy.size >= OUTBOUND_AGENT_POLICY_LIMIT) {
+ // Do not evict existing Agents: they own socket pools and may still have
+ // in-flight streaming responses. Evicting without closing leaks resources,
+ // while closing/destroying can break unrelated requests. Exceeding this
+ // small policy count is unexpected and should fail closed.
+ throw new Error(
+ `Maximum secure outbound connection policy count (${OUTBOUND_AGENT_POLICY_LIMIT}) exceeded`,
+ );
+ }
+
+ const dispatcher = new Agent({
+ connect: {
+ // This lookup runs at socket connection time, so DNS rebinding between
+ // the earlier URL validation and the actual HTTP connection is blocked.
+ lookup: createSecureOutboundLookup(validationOptions),
+ },
+ });
+
+ secureOutboundDispatchersByPolicy.set(policyKey, dispatcher);
+ return dispatcher;
+}
+
+function validateConnectionTimeLookupResult(
+ hostname: string,
+ address: string | dns.LookupAddress[],
+ validationOptions: OutboundUrlConnectionValidationOptions,
+): void {
+ const lookupAddresses = Array.isArray(address)
+ ? address
+ : [{ address, family: undefined }];
+
+ for (const lookupAddress of lookupAddresses) {
+ validateOutboundResolvedIp({
+ hostname,
+ ip: lookupAddress.address,
+ whitelist:
+ validationOptions.whitelist ??
+ DEFAULT_OUTBOUND_URL_VALIDATION_WHITELIST,
+ logContext: validationOptions.logContext ?? "Outbound URL",
+ });
+ }
+}
+
+function getConnectionValidationPolicyKey({
+ whitelist,
+ logContext,
+}: OutboundUrlConnectionValidationOptions): string {
+ // Keep separate Agent pools per whitelist. A single shared Agent could reuse
+ // a socket opened under a permissive policy for a later stricter request to
+ // the same origin without performing another DNS lookup. The lookup closure
+ // also captures logContext, so include it to avoid mislabeling connection-time
+ // block warnings when different flows share the same whitelist.
+ return JSON.stringify({
+ whitelist: normalizeWhitelist(whitelist),
+ logContext: logContext ?? "Outbound URL",
+ });
+}
+
+function normalizeWhitelist(
+ whitelist: OutboundUrlValidationWhitelist = DEFAULT_OUTBOUND_URL_VALIDATION_WHITELIST,
+): OutboundUrlValidationWhitelist {
+ return {
+ hosts: [...whitelist.hosts].sort(),
+ ips: [...whitelist.ips].sort(),
+ ip_ranges: [...whitelist.ip_ranges].sort(),
+ };
+}
diff --git a/packages/shared/src/server/outbound-url/fetch.ts b/packages/shared/src/server/outbound-url/fetch.ts
index 17981a4506..87e87d3343 100644
--- a/packages/shared/src/server/outbound-url/fetch.ts
+++ b/packages/shared/src/server/outbound-url/fetch.ts
@@ -1,3 +1,4 @@
+import { addSecureOutboundConnectionValidation } from "./connection";
import type { OutboundUrlValidationWhitelist } from "./validation";
import { logger } from "../logger";
@@ -71,6 +72,7 @@ interface BaseRedirectOptions {
interface RedirectValidationOptions {
validateUrl: RedirectUrlValidator;
whitelist?: OutboundUrlValidationWhitelist;
+ logContext?: string;
}
/**
@@ -131,11 +133,15 @@ export async function fetchWithSecureRedirects(
let currentUrl = url;
let redirectDepth = 0;
- // Force manual redirect handling to prevent automatic following.
- let fetchOptions: RequestInit = {
- ...options,
- redirect: "manual",
- };
+ // Disable automatic redirects so every Location target is validated before
+ // following it, and attach connection-time DNS/IP validation for each fetch.
+ let fetchOptions: RequestInit = addConnectionTimeValidation(
+ {
+ ...options,
+ redirect: "manual",
+ },
+ redirectOptions,
+ );
while (redirectDepth <= maxRedirects) {
logger.debug("Fetching URL with manual redirect handling", {
@@ -274,6 +280,20 @@ export async function fetchWithSecureRedirects(
]);
}
+function addConnectionTimeValidation(
+ options: RequestInit,
+ redirectOptions: RedirectOptions,
+): RequestInit {
+ if (redirectOptions.skipValidation === true) {
+ return options;
+ }
+
+ return addSecureOutboundConnectionValidation(options, {
+ whitelist: redirectOptions.redirectValidation.whitelist,
+ logContext: redirectOptions.redirectValidation.logContext,
+ });
+}
+
function stripSensitiveRedirectHeaders(
headers: RequestInit["headers"],
sensitiveHeaderNames: Set<string>,
diff --git a/packages/shared/src/server/outbound-url/validation.ts b/packages/shared/src/server/outbound-url/validation.ts
index 8e18403211..691feec341 100644
--- a/packages/shared/src/server/outbound-url/validation.ts
+++ b/packages/shared/src/server/outbound-url/validation.ts
@@ -20,6 +20,13 @@ export interface ValidateOutboundUrlHostOptions {
shouldSkipDnsCheckForLiteralIps: boolean;
}
+interface ValidateOutboundResolvedIpOptions {
+ hostname: string;
+ ip: string;
+ whitelist: OutboundUrlValidationWhitelist;
+ logContext: string;
+}
+
export async function resolveHost(hostname: string): Promise<string[]> {
// Returns every A + AAAA address.
const [v4, v6, lookup] = await Promise.allSettled([
@@ -93,12 +100,12 @@ export async function validateOutboundUrlHost({
}
if (isIPAddress(hostname)) {
- if (isIPBlocked(hostname, whitelist.ips, whitelist.ip_ranges)) {
- logger.warn(
- `${logContext} validation blocked IP address in hostname: ${hostname}`,
- );
- throw new Error("Blocked IP address detected");
- }
+ validateOutboundResolvedIp({
+ hostname,
+ ip: hostname,
+ whitelist,
+ logContext,
+ });
if (shouldSkipDnsCheckForLiteralIps) return;
}
@@ -110,12 +117,30 @@ export async function validateOutboundUrlHost({
const ips = await resolveHost(hostname);
for (const ip of ips) {
- if (isIPBlocked(ip, whitelist.ips, whitelist.ip_ranges)) {
- logger.warn(
- `${logContext} validation blocked resolved IP address: ${ip} for hostname: ${hostname}`,
- );
- throw new Error("Blocked IP address detected");
- }
+ validateOutboundResolvedIp({
+ hostname,
+ ip,
+ whitelist,
+ logContext,
+ });
+ }
+}
+
+export function validateOutboundResolvedIp({
+ hostname,
+ ip,
+ whitelist,
+ logContext,
+}: ValidateOutboundResolvedIpOptions): void {
+ if (whitelist.hosts.includes(hostname)) {
+ return;
+ }
+
+ if (isIPBlocked(ip, whitelist.ips, whitelist.ip_ranges)) {
+ logger.warn(
+ `${logContext} validation blocked resolved IP address: ${ip} for hostname: ${hostname}`,
+ );
+ throw new Error("Blocked IP address detected");
}
}
diff --git a/packages/shared/src/server/webhooks/validation.ts b/packages/shared/src/server/webhooks/validation.ts
index 724745a5dc..ae6b482ef9 100644
--- a/packages/shared/src/server/webhooks/validation.ts
+++ b/packages/shared/src/server/webhooks/validation.ts
@@ -9,6 +9,8 @@ import {
export type WebhookValidationWhitelist = OutboundUrlValidationWhitelist;
export { resolveHost };
+export const WEBHOOK_URL_VALIDATION_LOG_CONTEXT = "Webhook";
+
export function whitelistFromEnv(): WebhookValidationWhitelist {
return {
hosts: env.LANGFUSE_WEBHOOK_WHITELISTED_HOST || [],
@@ -42,7 +44,7 @@ export async function validateWebhookURL(
await validateOutboundUrlHost({
url,
whitelist,
- logContext: "Webhook",
+ logContext: WEBHOOK_URL_VALIDATION_LOG_CONTEXT,
// Preserve the existing webhook behavior: public IP literals must still
// pass the same DNS-resolution path as hostname destinations.
shouldSkipDnsCheckForLiteralIps: false,
diff --git a/web/src/features/datasets/server/dataset-router.ts b/web/src/features/datasets/server/dataset-router.ts
index 93eafefa6d..1593638151 100644
--- a/web/src/features/datasets/server/dataset-router.ts
+++ b/web/src/features/datasets/server/dataset-router.ts
@@ -67,6 +67,7 @@ import {
escapeSqlLikePattern,
fetchWithSecureRedirects,
whitelistFromEnv,
+ WEBHOOK_URL_VALIDATION_LOG_CONTEXT,
} from "@langfuse/shared/src/server";
import { aggregateScores } from "@/src/features/scores/lib/aggregateScores";
import {
@@ -1809,6 +1810,7 @@ export const datasetRouter = createTRPCRouter({
redirectValidation: {
validateUrl: validateWebhookURL,
whitelist,
+ logContext: WEBHOOK_URL_VALIDATION_LOG_CONTEXT,
},
},
);
diff --git a/web/src/server/api/routers/utilities.ts b/web/src/server/api/routers/utilities.ts
index ce4c810f2a..64537b216a 100644
--- a/web/src/server/api/routers/utilities.ts
+++ b/web/src/server/api/routers/utilities.ts
@@ -85,6 +85,8 @@ const fetchImageUrlWithSecureRedirects = async (
);
}
},
+ whitelist: IMAGE_URL_VALIDATION_OPTIONS.whitelist,
+ logContext: IMAGE_URL_VALIDATION_OPTIONS.logContext,
},
});
diff --git a/worker/src/__tests__/outbound-connection-validation.test.ts b/worker/src/__tests__/outbound-connection-validation.test.ts
new file mode 100644
index 0000000000..538507e21c
--- /dev/null
+++ b/worker/src/__tests__/outbound-connection-validation.test.ts
@@ -0,0 +1,145 @@
+import crypto from "node:crypto";
+import { createServer, type Server } from "node:http";
+import { AddressInfo } from "node:net";
+import { afterEach, describe, expect, it, vi } from "vitest";
+import { logger } from "../../../packages/shared/src/server/logger";
+import { fetchWithSecureRedirects } from "../../../packages/shared/src/server/outbound-url";
+
+const strictWhitelist = { hosts: [], ips: [], ip_ranges: [] };
+
+let server: Server | undefined;
+
+afterEach(async () => {
+ await closeServer();
+ vi.restoreAllMocks();
+});
+
+describe("fetchWithSecureRedirects connection-time validation", () => {
+ it("should reject DNS results that resolve to blocked IPs at connection time", async () => {
+ const url = await startLocalhostServer();
+
+ await expect(
+ fetchWithSecureRedirects(url, {}, validationOptions()),
+ ).rejects.toMatchObject({
+ message: "fetch failed",
+ cause: expect.objectContaining({
+ message: "Blocked IP address detected",
+ }),
+ });
+ });
+
+ it("should use the caller log context for connection-time blocks when whitelists match", async () => {
+ const warnSpy = vi
+ .spyOn(logger, "warn")
+ .mockImplementation(() => undefined);
+
+ await expect(
+ fetchWithSecureRedirects(
+ await startLocalhostServer(),
+ {},
+ validationOptions(strictWhitelist, "Webhook"),
+ ),
+ ).rejects.toMatchObject({ message: "fetch failed" });
+ await closeServer();
+
+ await expect(
+ fetchWithSecureRedirects(
+ await startLocalhostServer(),
+ {},
+ validationOptions(strictWhitelist, "Image URL"),
+ ),
+ ).rejects.toMatchObject({ message: "fetch failed" });
+
+ expect(warnSpy).toHaveBeenCalledWith(
+ expect.stringContaining("Webhook validation blocked resolved IP address"),
+ );
+ expect(warnSpy).toHaveBeenCalledWith(
+ expect.stringContaining(
+ "Image URL validation blocked resolved IP address",
+ ),
+ );
+ });
+
+ it("should propagate DNS lookup errors from connection-time validation", async () => {
+ const hostname = `nonexistent-${crypto.randomUUID()}.invalid`;
+
+ await expect(
+ fetchWithSecureRedirects(
+ `http://${hostname}`,
+ {},
+ validationOptions({ hosts: [hostname], ips: [], ip_ranges: [] }),
+ ),
+ ).rejects.toMatchObject({
+ message: "fetch failed",
+ cause: expect.objectContaining({ code: "ENOTFOUND" }),
+ });
+ });
+
+ it("should preserve host whitelist behavior at connection time", async () => {
+ const url = await startLocalhostServer();
+
+ const result = await fetchWithSecureRedirects(
+ url,
+ {},
+ validationOptions({ hosts: ["localhost"], ips: [], ip_ranges: [] }),
+ );
+
+ expect(result.response.status).toBe(200);
+ await expect(result.response.text()).resolves.toBe("ok");
+ });
+
+ it("should preserve IP range whitelist behavior at connection time", async () => {
+ const url = await startLocalhostServer();
+
+ const result = await fetchWithSecureRedirects(
+ url,
+ {},
+ validationOptions({
+ hosts: [],
+ ips: [],
+ ip_ranges: ["127.0.0.0/8", "::1/128"],
+ }),
+ );
+
+ expect(result.response.status).toBe(200);
+ await expect(result.response.text()).resolves.toBe("ok");
+ });
+});
+
+async function startLocalhostServer(): Promise<string> {
+ server = createServer((_request, response) => {
+ response.end("ok");
+ });
+
+ await new Promise<void>((resolve) => server?.listen(0, "127.0.0.1", resolve));
+
+ const address = server.address() as AddressInfo;
+ return `http://localhost:${address.port}`;
+}
+
+async function closeServer(): Promise<void> {
+ if (!server) return;
+
+ await new Promise<void>((resolve, reject) => {
+ server?.close((error) => {
+ if (error) {
+ reject(error);
+ return;
+ }
+
+ resolve();
+ });
+ });
+ server = undefined;
+}
+
+function validationOptions(whitelist = strictWhitelist, logContext?: string) {
+ return {
+ maxRedirects: 0,
+ redirectValidation: {
+ validateUrl: async () => undefined,
+ whitelist,
+ logContext,
+ },
+ };
+}
diff --git a/worker/src/queues/webhooks.ts b/worker/src/queues/webhooks.ts
index 592a5c5f8d..2acbc349d2 100644
--- a/worker/src/queues/webhooks.ts
+++ b/worker/src/queues/webhooks.ts
@@ -17,6 +17,7 @@ import {
validateWebhookURL,
whitelistFromEnv,
fetchWithSecureRedirects,
+ WEBHOOK_URL_VALIDATION_LOG_CONTEXT,
} from "@langfuse/shared/src/server";
import {
TQueueJobTypes,
@@ -164,6 +165,7 @@ async function executeHttpAction({
redirectValidation: {
validateUrl: validateWebhookURL,
whitelist,
+ logContext: WEBHOOK_URL_VALIDATION_LOG_CONTEXT,
},
additionalSensitiveHeaders,
};