🪢 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(shared): harden outbound URL validation against SSRF bypasses (#13485)
Tobias Wochinger96dc4ef2081f
diff --git a/packages/shared/src/server/llm/baseUrlValidation.ts b/packages/shared/src/server/llm/baseUrlValidation.tsindex 8ec60505d1..79dba3ed07 100644--- a/packages/shared/src/server/llm/baseUrlValidation.ts+++ b/packages/shared/src/server/llm/baseUrlValidation.ts@@ -1,18 +1,11 @@-import { URL } from "node:url";import { env } from "../../env";-import { logger } from "../logger";import {- isHostnameBlocked,- isIPBlocked,- isIPAddress,-} from "../webhooks/ipBlocking";-import { resolveHost } from "../webhooks/validation";+ type OutboundUrlValidationWhitelist,+ parseOutboundUrl,+ validateOutboundUrlHost,+} from "../outboundUrlValidation";-export interface LlmBaseUrlValidationWhitelist {- hosts: string[];- ips: string[];- ip_ranges: string[];-}+export type LlmBaseUrlValidationWhitelist = OutboundUrlValidationWhitelist;export function llmBaseUrlWhitelistFromEnv(): LlmBaseUrlValidationWhitelist {if (env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION) {@@ -42,92 +35,23 @@ export async function validateLlmConnectionBaseURL(}: whitelist;- let url: URL;- try {- url = new URL(normalizeURL(urlString));- } catch {- throw new Error("Invalid URL syntax");- }+ const url = parseOutboundUrl(urlString);if (!["https:", "http:"].includes(url.protocol)) {throw new Error("Only HTTP and HTTPS protocols are allowed");}- const hostname = normalizeHostname(url.hostname);-- if (effectiveWhitelist.hosts.includes(hostname)) {- return;- }-- if (isHostnameBlocked(hostname)) {- throw new Error("Blocked hostname detected");- }+ await validateOutboundUrlHost({+ url,+ whitelist: effectiveWhitelist,+ shouldThrowIfDnsResolutionFails: false,+ logContext: "LLM base URL",+ // Existing LLM validation accepts public IP literals after CIDR checks so+ // custom gateways are not forced through DNS at write time.+ shouldSkipDnsCheckForLiteralIps: true,+ });if (env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION && url.protocol !== "https:") {throw new Error("Only HTTPS base URLs are allowed on Langfuse Cloud");}-- if (isIPAddress(hostname)) {- if (- isIPBlocked(- hostname,- effectiveWhitelist.ips,- effectiveWhitelist.ip_ranges,- )- ) {- logger.warn(- `LLM base URL validation blocked IP address in hostname: ${hostname}`,- );- throw new Error("Blocked IP address detected");- }-- return;- }-- let ips: string[];- try {- ips = await resolveHost(hostname);- } catch {- // DNS resolution is best-effort here so valid custom gateways do not fail at write time.- return;- }-- for (const ip of ips) {- if (isIPBlocked(ip, effectiveWhitelist.ips, effectiveWhitelist.ip_ranges)) {- logger.warn(- `LLM base URL validation blocked resolved IP address: ${ip} for hostname: ${hostname}`,- );- throw new Error("Blocked IP address detected");- }- }-}--function normalizeURL(urlString: string): string {- let normalized = urlString.trim();-- try {- normalized = decodeURIComponent(normalized);- } catch {- throw new Error("Invalid URL encoding");- }-- try {- normalized = normalized.normalize("NFC");- } catch {- throw new Error("Invalid unicode in URL");- }-- return normalized;-}--function normalizeHostname(hostname: string): string {- let normalized = hostname.toLowerCase();-- try {- normalized = new URL(`http://${normalized}`).hostname;- } catch {- // Keep the original hostname so URL parsing can fail consistently elsewhere.- }-- return normalized;}diff --git a/packages/shared/src/server/outboundUrlValidation.ts b/packages/shared/src/server/outboundUrlValidation.tsnew file mode 100644index 0000000000..be1763c1ed--- /dev/null+++ b/packages/shared/src/server/outboundUrlValidation.ts@@ -0,0 +1,133 @@+import dns from "node:dns/promises";+import { URL } from "node:url";+import { logger } from "./logger";+import {+ isHostnameBlocked,+ isIPBlocked,+ isIPAddress,+} from "./webhooks/ipBlocking";++export interface OutboundUrlValidationWhitelist {+ hosts: string[];+ ips: string[];+ ip_ranges: string[];+}++export async function resolveHost(hostname: string): Promise<string[]> {+ // Returns every A + AAAA address.+ const [v4, v6, lookup] = await Promise.allSettled([+ dns.resolve4(hostname),+ dns.resolve6(hostname),+ // fetch resolves through getaddrinfo, which can include hosts file/NSS+ // entries that resolve4/resolve6 do not see. Include them so validation+ // checks the same local resolution sources that runtime requests can use.+ dns.lookup(hostname, { all: true }),+ ]);++ const ips = new Set<string>();+ if (v4.status === "fulfilled") {+ const validV4Ips = v4.value.filter((ip) => ip && typeof ip === "string");+ validV4Ips.forEach((ip) => ips.add(ip));+ }+ if (v6.status === "fulfilled") {+ const validV6Ips = v6.value.filter((ip) => ip && typeof ip === "string");+ validV6Ips.forEach((ip) => ips.add(ip));+ }+ if (lookup.status === "fulfilled") {+ lookup.value+ .map(({ address }) => address)+ .filter((ip) => ip && typeof ip === "string")+ .forEach((ip) => ips.add(ip));+ }++ if (!ips.size) throw new Error(`DNS lookup failed for ${hostname}`);+ return [...ips];+}++export function parseOutboundUrl(urlString: string): URL {+ const trimmedUrl = urlString.trim();+ assertValidUrlEncoding(trimmedUrl);++ let url: URL;+ try {+ // Parse the original URL string so validation uses the same WHATWG URL+ // semantics as fetch. Decoding the whole URL first can turn encoded data+ // into delimiters and make validation inspect a different hostname.+ url = new URL(trimmedUrl);+ } catch {+ throw new Error("Invalid URL syntax");+ }++ if (url.username !== "" || url.password !== "") {+ throw new Error(+ "URL credentials are not allowed. Use authentication headers instead.",+ );+ }++ return url;+}++export async function validateOutboundUrlHost({+ url,+ whitelist,+ shouldThrowIfDnsResolutionFails,+ logContext,+ shouldSkipDnsCheckForLiteralIps,+}: {+ url: URL;+ whitelist: OutboundUrlValidationWhitelist;+ shouldThrowIfDnsResolutionFails: boolean;+ logContext: string;+ shouldSkipDnsCheckForLiteralIps: boolean;+}): Promise<void> {+ // WHATWG URL parsing already lowercases and punycodes HTTP(S) hostnames, so+ // host safety checks stay tied to the parsed URL component.+ const hostname = url.hostname;++ if (whitelist.hosts.includes(hostname)) {+ return;+ }++ if (isHostnameBlocked(hostname)) {+ throw new Error("Blocked hostname detected");+ }++ 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");+ }++ if (shouldSkipDnsCheckForLiteralIps) return;+ }++ let ips: string[];+ try {+ ips = await resolveHost(hostname);+ } catch (error) {+ if (!shouldThrowIfDnsResolutionFails) return;+ throw error;+ }++ 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");+ }+ }+}++function assertValidUrlEncoding(urlString: string): void {+ // This intentionally checks encoding validity only. Do not parse or validate+ // the decoded result: decoding the whole URL can turn encoded data into URL+ // delimiters and make validation inspect a different hostname than fetch.+ try {+ decodeURIComponent(urlString);+ } catch {+ throw new Error("Invalid URL encoding");+ }+}diff --git a/packages/shared/src/server/webhooks/ipBlocking.ts b/packages/shared/src/server/webhooks/ipBlocking.tsindex 548b9c10b8..ee06aeadda 100644--- a/packages/shared/src/server/webhooks/ipBlocking.ts+++ b/packages/shared/src/server/webhooks/ipBlocking.ts@@ -26,8 +26,12 @@ const BLOCKED_CIDRS = ["fe80::/10", // link-local"ff00::/8", // multicast"100::/64", // discard-only+ "64:ff9b::/96", // NAT64 IPv4 embedded in IPv6+ "64:ff9b:1::/48", // NAT64 IPv4 embedded in IPv6 (local-use)+ "::/96", // IPv4-compatible IPv6"2001::/32", // Teredo tunneling"2001:db8::/32", // doc+ "2002::/16", // IPv6 prefix for transmitting IPv6 to IPv4 via 6to4 tunneling];// Pre-parse blocked networks once for performancediff --git a/packages/shared/src/server/webhooks/redirectHandler.ts b/packages/shared/src/server/webhooks/redirectHandler.tsindex c03e5aae58..fc1ab46705 100644--- a/packages/shared/src/server/webhooks/redirectHandler.ts+++ b/packages/shared/src/server/webhooks/redirectHandler.ts@@ -2,6 +2,13 @@ import { validateWebhookURL } from "./validation";import type { WebhookValidationWhitelist } from "./validation";import { logger } from "../logger";+const SENSITIVE_REDIRECT_HEADERS = new Set([+ "authorization",+ "cookie",+ "proxy-authorization",+ "x-langfuse-signature",+]);+/*** Custom error for redirect validation failures*/@@ -59,6 +66,7 @@ export interface RedirectOptions {maxRedirects: number;skipValidation?: boolean;whitelist?: WebhookValidationWhitelist;+ additionalSensitiveHeaders?: string[];}/**@@ -92,15 +100,24 @@ export async function fetchWithSecureRedirects(options: RequestInit,redirectOptions: RedirectOptions,): Promise<RedirectResult> {- const { maxRedirects, skipValidation = false, whitelist } = redirectOptions;+ const {+ maxRedirects,+ skipValidation = false,+ whitelist,+ additionalSensitiveHeaders = [],+ } = redirectOptions;+ const sensitiveRedirectHeaders = new Set([+ ...SENSITIVE_REDIRECT_HEADERS,+ ...additionalSensitiveHeaders.map((headerName) => headerName.toLowerCase()),+ ]);// Track redirect chain for loop detection and loggingconst redirectChain: string[] = [];let currentUrl = url;let redirectDepth = 0;- // Force manual redirect handling to prevent automatic following- const fetchOptions: RequestInit = {+ // Force manual redirect handling to prevent automatic following.+ let fetchOptions: RequestInit = {...options,redirect: "manual",};@@ -199,6 +216,31 @@ export async function fetchWithSecureRedirects(}}+ const currentOrigin = new URL(currentUrl).origin;+ const redirectOrigin = new URL(redirectUrl).origin;+ if (currentOrigin !== redirectOrigin) {+ const { headers, strippedHeaderNames } = stripSensitiveRedirectHeaders(+ fetchOptions.headers,+ sensitiveRedirectHeaders,+ );++ if (strippedHeaderNames.length > 0) {+ logger.warn("Stripping sensitive headers for cross-origin redirect", {+ from: currentOrigin,+ to: redirectOrigin,+ redirectDepth,+ strippedHeaderNames,+ });++ fetchOptions = {+ ...fetchOptions,+ // Sensitive credentials are origin-scoped. Keep them on same-origin+ // redirects, but strip them before a cross-origin follow-up request.+ headers,+ };+ }+ }+// Follow the redirectcurrentUrl = redirectUrl;redirectDepth++;@@ -211,3 +253,29 @@ export async function fetchWithSecureRedirects(currentUrl,]);}++function stripSensitiveRedirectHeaders(+ headers: RequestInit["headers"],+ sensitiveHeaderNames: Set<string>,+): {+ headers: RequestInit["headers"];+ strippedHeaderNames: string[];+} {+ const strippedHeaderNames: string[] = [];++ const headerEntries = Array.from(new Headers(headers).entries()).filter(+ ([headerName]) => {+ if (sensitiveHeaderNames.has(headerName)) {+ strippedHeaderNames.push(headerName);+ return false;+ }++ return true;+ },+ );++ return {+ headers: new Headers(headerEntries),+ strippedHeaderNames,+ };+}diff --git a/packages/shared/src/server/webhooks/validation.ts b/packages/shared/src/server/webhooks/validation.tsindex aff53d83f6..e73091f037 100644--- a/packages/shared/src/server/webhooks/validation.ts+++ b/packages/shared/src/server/webhooks/validation.ts@@ -1,38 +1,13 @@-import dns from "node:dns/promises";-import { URL } from "node:url";-import { isIPBlocked, isIPAddress, isHostnameBlocked } from "./ipBlocking";import { env } from "../../env";-import { logger } from "../logger";+import {+ type OutboundUrlValidationWhitelist,+ parseOutboundUrl,+ resolveHost,+ validateOutboundUrlHost,+} from "../outboundUrlValidation";-export async function resolveHost(hostname: string): Promise<string[]> {- // Returns every A + AAAA address- const [v4, v6] = await Promise.allSettled([- dns.resolve4(hostname),- dns.resolve6(hostname),- ]);-- const ips: string[] = [];- if (v4.status === "fulfilled") {- // Filter out any undefined/null values- const validV4Ips = v4.value.filter((ip) => ip && typeof ip === "string");-- ips.push(...validV4Ips);- }- if (v6.status === "fulfilled") {- // Filter out any undefined/null values- const validV6Ips = v6.value.filter((ip) => ip && typeof ip === "string");-- ips.push(...validV6Ips);- }- if (!ips.length) throw new Error(`DNS lookup failed for ${hostname}`);- return ips;-}--export interface WebhookValidationWhitelist {- hosts: string[];- ips: string[];- ip_ranges: string[];-}+export type WebhookValidationWhitelist = OutboundUrlValidationWhitelist;+export { resolveHost };export function whitelistFromEnv(): WebhookValidationWhitelist {return {@@ -54,102 +29,23 @@ export async function validateWebhookURL(urlString: string,whitelist: WebhookValidationWhitelist = whitelistFromEnv(),): Promise<void> {- // Step 1: Basic URL parsing and normalization- let url: URL;- try {- // Normalize the URL string first to handle encoding issues- const normalizedUrl = normalizeURL(urlString);- url = new URL(normalizedUrl);- } catch {- throw new Error("Invalid URL syntax");- }+ const url = parseOutboundUrl(urlString);if (!["https:", "http:"].includes(url.protocol)) {throw new Error("Only HTTP and HTTPS protocols are allowed");}- // Step 2: Port validationif (url.port && !["443", "80"].includes(url.port)) {throw new Error("Only ports 80 and 443 are allowed");}- // Step 3: Hostname normalization and validation- const hostname = normalizeHostname(url.hostname);-- if (whitelist.hosts.includes(hostname)) {- // skip further checks if hostname is whitelisted- return;- }-- // Block obviously dangerous hostnames- if (isHostnameBlocked(hostname)) {- throw new Error("Blocked hostname detected");- }-- // Step 4: Check for IP address literals in hostname- if (isIPAddress(hostname)) {- if (isIPBlocked(hostname, whitelist.ips, whitelist.ip_ranges)) {- // Log detailed error internally for debugging- logger.warn(- `Webhook validation blocked IP address in hostname: ${hostname}`,- );- // Throw generic error to user to prevent IP leakage- throw new Error("Blocked IP address detected");- }- }-- // Step 5: DNS resolution and validation- const ips = await resolveHost(hostname);- for (const ip of ips) {- if (isIPBlocked(ip, whitelist.ips, whitelist.ip_ranges)) {- // Log detailed error internally for debugging- logger.warn(- `Webhook validation blocked resolved IP address: ${ip} for hostname: ${hostname}`,- );- // Throw generic error to user to prevent IP leakage- throw new Error("Blocked IP address detected");- }- }-}--/**- * Normalize URL to prevent encoding/unicode bypass attempts- */-function normalizeURL(urlString: string): string {- // Remove leading/trailing whitespace- let normalized = urlString.trim();-- // Decode URL encoding to prevent bypass attempts like %6C%6F%63%61%6C%68%6F%73%74 (localhost)- try {- normalized = decodeURIComponent(normalized);- } catch {- throw new Error("Invalid URL encoding");- }-- // Normalize unicode to prevent IDN bypass attempts- try {- normalized = normalized.normalize("NFC");- } catch {- throw new Error("Invalid unicode in URL");- }-- return normalized;-}--/**- * Normalize hostname to handle IDN and case sensitivity- */-function normalizeHostname(hostname: string): string {- let normalized = hostname.toLowerCase();-- // Convert internationalized domain names to ASCII (Punycode)- try {- // This will convert unicode domain names to their ASCII representation- const url = new URL(`http://${normalized}`);- normalized = url.hostname;- } catch {- // If hostname is invalid, keep the original for later validation failure- }-- return normalized;+ await validateOutboundUrlHost({+ url,+ whitelist,+ shouldThrowIfDnsResolutionFails: true,+ logContext: "Webhook",+ // Preserve the existing webhook behavior: public IP literals must still+ // pass the same DNS-resolution path as hostname destinations.+ shouldSkipDnsCheckForLiteralIps: false,+ });}diff --git a/worker/src/__tests__/ip-blocking.test.ts b/worker/src/__tests__/ip-blocking.test.tsindex 086b2ea2f7..49e8153b8d 100644--- a/worker/src/__tests__/ip-blocking.test.ts+++ b/worker/src/__tests__/ip-blocking.test.ts@@ -81,6 +81,13 @@ describe("IP Blocking Module", () => {isIPBlocked("2001:0000:4136:e378:8000:63bf:3fff:fdd2", [], []),).toBe(true);});++ it("should block NAT64 and 6to4 transition addresses", () => {+ expect(isIPBlocked("64:ff9b::7f00:1", [], [])).toBe(true); // NAT64 for 127.0.0.1+ expect(isIPBlocked("64:ff9b:1::7f00:1", [], [])).toBe(true); // NAT64 local-use for 127.0.0.1+ expect(isIPBlocked("::7f00:1", [], [])).toBe(true); // IPv4-compatible IPv6 for 127.0.0.1+ expect(isIPBlocked("2002:7f00:1::", [], [])).toBe(true); // 6to4 for 127.0.0.1+ });});describe("allowed public addresses", () => {diff --git a/worker/src/__tests__/llm-base-url-validation.test.ts b/worker/src/__tests__/llm-base-url-validation.test.tsindex 01300805de..fe3b77e32a 100644--- a/worker/src/__tests__/llm-base-url-validation.test.ts+++ b/worker/src/__tests__/llm-base-url-validation.test.ts@@ -1,4 +1,28 @@-import { afterEach, describe, expect, it } from "vitest";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";++const { resolve4Mock, resolve6Mock, lookupMock } = vi.hoisted(() => ({+ resolve4Mock: vi.fn<(hostname: string) => Promise<string[]>>(),+ resolve6Mock: vi.fn<(hostname: string) => Promise<string[]>>(),+ lookupMock:+ vi.fn<+ (+ hostname: string,+ options: { all: true },+ ) => Promise<Array<{ address: string; family: 4 | 6 }>>+ >(),+}));++vi.mock("node:dns/promises", () => ({+ default: {+ resolve4: resolve4Mock,+ resolve6: resolve6Mock,+ lookup: lookupMock,+ },+ resolve4: resolve4Mock,+ resolve6: resolve6Mock,+ lookup: lookupMock,+}));+import {validateLlmConnectionBaseURL,type LlmBaseUrlValidationWhitelist,@@ -12,6 +36,14 @@ const originalAllowedIpSegments =env.LANGFUSE_LLM_CONNECTION_WHITELISTED_IP_SEGMENTS;describe("LLM base URL validation", () => {+ beforeEach(() => {+ vi.clearAllMocks();++ resolve4Mock.mockRejectedValue(new Error("ENOTFOUND"));+ resolve6Mock.mockRejectedValue(new Error("ENODATA"));+ lookupMock.mockRejectedValue(new Error("ENOTFOUND"));+ });+afterEach(() => {(env as any).NEXT_PUBLIC_LANGFUSE_CLOUD_REGION = originalCloudRegion;(env as any).LANGFUSE_LLM_CONNECTION_WHITELISTED_HOST =@@ -29,6 +61,39 @@ describe("LLM base URL validation", () => {).rejects.toThrow("Blocked hostname detected");});+ it("should reject encoded delimiter userinfo SSRF bypass attempts", async () => {+ (env as any).NEXT_PUBLIC_LANGFUSE_CLOUD_REGION = undefined;++ await expect(+ validateLlmConnectionBaseURL("https://example.com%[email protected]/v1"),+ ).rejects.toThrow(+ "URL credentials are not allowed. Use authentication headers instead.",+ );+ });++ it("should reject URLs with embedded credentials", async () => {+ (env as any).NEXT_PUBLIC_LANGFUSE_CLOUD_REGION = undefined;++ await expect(+ validateLlmConnectionBaseURL("https://user:[email protected]/v1"),+ ).rejects.toThrow(+ "URL credentials are not allowed. Use authentication headers instead.",+ );+ });++ it("should reject hostnames that resolve to blocked IPs through local lookup", async () => {+ (env as any).NEXT_PUBLIC_LANGFUSE_CLOUD_REGION = undefined;+ lookupMock.mockResolvedValue([{ address: "127.0.0.1", family: 4 }]);++ await expect(validateLlmConnectionBaseURL("http://vm/v1")).rejects.toThrow(+ "Blocked IP address detected",+ );++ expect(resolve4Mock).toHaveBeenCalledWith("vm");+ expect(resolve6Mock).toHaveBeenCalledWith("vm");+ expect(lookupMock).toHaveBeenCalledWith("vm", { all: true });+ });+it("should allow explicitly allowlisted localhost hosts for self-hosted instances", async () => {(env as any).NEXT_PUBLIC_LANGFUSE_CLOUD_REGION = undefined;diff --git a/worker/src/__tests__/webhook-redirect-headers.test.ts b/worker/src/__tests__/webhook-redirect-headers.test.tsnew file mode 100644index 0000000000..9528749ad6--- /dev/null+++ b/worker/src/__tests__/webhook-redirect-headers.test.ts@@ -0,0 +1,146 @@+import { afterEach, describe, expect, it, vi } from "vitest";+import { logger } from "../../../packages/shared/src/server/logger";+import { fetchWithSecureRedirects } from "../../../packages/shared/src/server/webhooks/redirectHandler";++const fetchMock = vi.fn<typeof fetch>();+vi.stubGlobal("fetch", fetchMock);++afterEach(() => {+ fetchMock.mockReset();+ vi.restoreAllMocks();+});++describe("fetchWithSecureRedirects header handling", () => {+ it("should keep sensitive headers on same-origin redirects", async () => {+ fetchMock+ .mockResolvedValueOnce(+ new Response(null, {+ status: 302,+ headers: { Location: "https://example.com/final" },+ }),+ )+ .mockResolvedValueOnce(new Response("ok", { status: 200 }));++ await fetchWithSecureRedirects(+ "https://example.com/start",+ {+ method: "POST",+ headers: {+ Authorization: "Bearer token",+ Cookie: "session=secret",+ "Proxy-Authorization": "Basic proxy-secret",+ "x-langfuse-signature": "t=1,v1=secret",+ "X-API-Key": "custom-secret",+ "x-custom-header": "keep-me",+ },+ },+ {+ maxRedirects: 1,+ skipValidation: true,+ additionalSensitiveHeaders: ["X-API-Key"],+ },+ );++ const finalRequest = fetchMock.mock.calls[1];+ const finalHeaders = new Headers(finalRequest?.[1]?.headers);++ expect(finalHeaders.get("authorization")).toBe("Bearer token");+ expect(finalHeaders.get("cookie")).toBe("session=secret");+ expect(finalHeaders.get("proxy-authorization")).toBe("Basic proxy-secret");+ expect(finalHeaders.get("x-langfuse-signature")).toBe("t=1,v1=secret");+ expect(finalHeaders.get("x-api-key")).toBe("custom-secret");+ expect(finalHeaders.get("x-custom-header")).toBe("keep-me");+ });++ it("should strip sensitive headers on cross-origin redirects", async () => {+ const warnSpy = vi+ .spyOn(logger, "warn")+ .mockImplementation(() => undefined);++ fetchMock+ .mockResolvedValueOnce(+ new Response(null, {+ status: 302,+ headers: { Location: "https://other.example.com/final" },+ }),+ )+ .mockResolvedValueOnce(new Response("ok", { status: 200 }));++ await fetchWithSecureRedirects(+ "https://example.com/start",+ {+ method: "POST",+ headers: {+ Authorization: "Bearer token",+ Cookie: "session=secret",+ "Proxy-Authorization": "Basic proxy-secret",+ "x-langfuse-signature": "t=1,v1=secret",+ "X-API-Key": "custom-secret",+ "x-custom-header": "keep-me",+ },+ },+ {+ maxRedirects: 1,+ skipValidation: true,+ additionalSensitiveHeaders: ["X-API-Key"],+ },+ );++ const finalRequest = fetchMock.mock.calls[1];+ const finalHeaders = new Headers(finalRequest?.[1]?.headers);++ expect(finalHeaders.get("authorization")).toBeNull();+ expect(finalHeaders.get("cookie")).toBeNull();+ expect(finalHeaders.get("proxy-authorization")).toBeNull();+ expect(finalHeaders.get("x-langfuse-signature")).toBeNull();+ expect(finalHeaders.get("x-api-key")).toBeNull();+ expect(finalHeaders.get("x-custom-header")).toBe("keep-me");+ expect(warnSpy).toHaveBeenCalledWith(+ "Stripping sensitive headers for cross-origin redirect",+ {+ from: "https://example.com",+ to: "https://other.example.com",+ redirectDepth: 0,+ strippedHeaderNames: [+ "authorization",+ "cookie",+ "proxy-authorization",+ "x-api-key",+ "x-langfuse-signature",+ ],+ },+ );+ });++ it("should not warn on cross-origin redirects without sensitive headers", async () => {+ const warnSpy = vi+ .spyOn(logger, "warn")+ .mockImplementation(() => undefined);++ fetchMock+ .mockResolvedValueOnce(+ new Response(null, {+ status: 302,+ headers: { Location: "https://other.example.com/final" },+ }),+ )+ .mockResolvedValueOnce(new Response("ok", { status: 200 }));++ await fetchWithSecureRedirects(+ "https://example.com/start",+ {+ method: "POST",+ headers: {+ "x-custom-header": "keep-me",+ },+ },+ { maxRedirects: 1, skipValidation: true },+ );++ const finalRequest = fetchMock.mock.calls[1];+ const finalHeaders = new Headers(finalRequest?.[1]?.headers);++ expect(finalHeaders.get("x-custom-header")).toBe("keep-me");+ expect(warnSpy).not.toHaveBeenCalled();+ });+});diff --git a/worker/src/__tests__/webhook-validation.test.ts b/worker/src/__tests__/webhook-validation.test.tsindex a4254b330c..e3b14ab501 100644--- a/worker/src/__tests__/webhook-validation.test.ts+++ b/worker/src/__tests__/webhook-validation.test.ts@@ -1,17 +1,26 @@import { beforeEach, describe, it, expect, vi } from "vitest";-const { resolve4Mock, resolve6Mock } = vi.hoisted(() => ({+const { resolve4Mock, resolve6Mock, lookupMock } = vi.hoisted(() => ({resolve4Mock: vi.fn<(hostname: string) => Promise<string[]>>(),resolve6Mock: vi.fn<(hostname: string) => Promise<string[]>>(),+ lookupMock:+ vi.fn<+ (+ hostname: string,+ options: { all: true },+ ) => Promise<Array<{ address: string; family: 4 | 6 }>>+ >(),}));vi.mock("node:dns/promises", () => ({default: {resolve4: resolve4Mock,resolve6: resolve6Mock,+ lookup: lookupMock,},resolve4: resolve4Mock,resolve6: resolve6Mock,+ lookup: lookupMock,}));import { validateWebhookURL } from "../../../packages/shared/src/server/webhooks/validation";@@ -32,6 +41,13 @@ beforeEach(() => {return ["93.184.216.34"];});resolve6Mock.mockRejectedValue(dnsError("ENODATA", "mocked-hostname"));+ lookupMock.mockImplementation(async (hostname: string) => {+ if (hostname === nonexistentDomain) {+ throw dnsError("ENOTFOUND", hostname);+ }++ return [{ address: "93.184.216.34", family: 4 }];+ });});describe("Webhook URL Validation", () => {@@ -146,6 +162,9 @@ describe("Webhook URL Validation", () => {).rejects.toThrow("DNS lookup failed");expect(resolve4Mock).toHaveBeenCalledWith(nonexistentDomain);expect(resolve6Mock).toHaveBeenCalledWith(nonexistentDomain);+ expect(lookupMock).toHaveBeenCalledWith(nonexistentDomain, {+ all: true,+ });});it("should reject URL-encoded localhost bypass attempts", async () => {@@ -155,6 +174,41 @@ describe("Webhook URL Validation", () => {).rejects.toThrow("Blocked hostname detected");});+ it("should reject encoded delimiter userinfo SSRF bypass attempts", async () => {+ // Percent-encoded delimiters are data to the WHATWG URL parser before+ // parsing, but become syntax if the whole URL is decoded first.+ // Validation must parse the same URL string that fetch will execute.+ const encodedDelimiters = ["%2F", "%23", "%3F", "%5C"];++ for (const delimiter of encodedDelimiters) {+ await expect(+ validateWebhookURL(`http://example.com${delimiter}@127.0.0.1/hook`),+ ).rejects.toThrow(+ "URL credentials are not allowed. Use authentication headers instead.",+ );+ }+ });++ it("should reject URLs with embedded credentials", async () => {+ await expect(+ validateWebhookURL("https://user:[email protected]/hook"),+ ).rejects.toThrow(+ "URL credentials are not allowed. Use authentication headers instead.",+ );+ });++ it("should validate IDN hostnames using their punycoded hostname", async () => {+ await expect(+ validateWebhookURL("http://тест.example.com/hook"),+ ).resolves.not.toThrow();++ expect(resolve4Mock).toHaveBeenCalledWith("xn--e1aybc.example.com");+ expect(resolve6Mock).toHaveBeenCalledWith("xn--e1aybc.example.com");+ expect(lookupMock).toHaveBeenCalledWith("xn--e1aybc.example.com", {+ all: true,+ });+ });+it("should reject internal/intranet hostnames", async () => {// Note: "internal.company.com" would require DNS resolution which can timeout// Using domains that match blocked patterns directly for faster testsdiff --git a/worker/src/queues/webhooks.ts b/worker/src/queues/webhooks.tsindex 8d6ebb0a36..d5dc056e5b 100644--- a/worker/src/queues/webhooks.ts+++ b/worker/src/queues/webhooks.ts@@ -115,6 +115,7 @@ async function executeHttpAction({executionId,executionStart,actionConfig,+ additionalSensitiveHeaders,}: {url: string;payload: string;@@ -125,6 +126,7 @@ async function executeHttpAction({executionId: string;executionStart: Date;actionConfig: ActionDomainWithSecrets;+ additionalSensitiveHeaders?: string[];}): Promise<{ httpStatus: number; responseBody: string }> {let httpStatus: number | undefined;let responseBody: string | undefined;@@ -161,6 +163,7 @@ async function executeHttpAction({maxRedirects: env.LANGFUSE_WEBHOOK_MAX_REDIRECTS,skipValidation,whitelist: whitelistFromEnv(),+ additionalSensitiveHeaders,},);@@ -383,11 +386,15 @@ async function executeWebhookAction({// Prepare headers with signature if secret existsconst requestHeaders: Record<string, string> = {};+ const additionalSensitiveHeaders: string[] = [];// Add webhook config headers firstif (webhookConfig.requestHeaders) {for (const [key, value] of Object.entries(webhookConfig.requestHeaders)) {requestHeaders[key] = value.value;+ if (value.secret) {+ additionalSensitiveHeaders.push(key);+ }}}@@ -419,6 +426,7 @@ async function executeWebhookAction({executionId,executionStart,actionConfig,+ additionalSensitiveHeaders,});}