🪢 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
chore: validate IP adresses (#8821)
Max Deichmann44ce6ef58156
diff --git a/packages/shared/package.json b/packages/shared/package.jsonindex 4782d9f563..f9b68e3b3c 100644--- a/packages/shared/package.json+++ b/packages/shared/package.json@@ -83,6 +83,7 @@"exponential-backoff": "^3.1.2","https-proxy-agent": "^7.0.6","ioredis": "^5.4.1",+ "ipaddr.js": "^2.2.0","jsonpath-plus": "10.3.0","kysely": "^0.27.4","langchain": "^0.3.28",diff --git a/packages/shared/src/domain/automations.ts b/packages/shared/src/domain/automations.tsindex 9414c19e81..754b1abcde 100644--- a/packages/shared/src/domain/automations.ts+++ b/packages/shared/src/domain/automations.ts@@ -51,7 +51,7 @@ export const RequestHeaderSchema = z.object({export const WebhookActionConfigSchema = z.object({type: z.literal("WEBHOOK"),- url: z.url(),+ url: z.url(), // Basic URL validation only - manual security validation called separatelyheaders: z.record(z.string(), z.string()).optional(), // deprecated field, use requestHeaders insteadrequestHeaders: z.record(z.string(), RequestHeaderSchema).optional(), // might not exist on legacy webhooksdisplayHeaders: z.record(z.string(), RequestHeaderSchema).optional(), // might not exist on legacy webhooksdiff --git a/packages/shared/src/server/index.ts b/packages/shared/src/server/index.tsindex 9b6feef560..253c8bdce5 100644--- a/packages/shared/src/server/index.ts+++ b/packages/shared/src/server/index.ts@@ -48,6 +48,8 @@ export * from "./redis/dataRetentionQueue";export * from "./redis/dataRetentionProcessingQueue";export * from "./redis/coreDataS3ExportQueue";export * from "./redis/meteringDataPostgresExportQueue";+export * from "./webhooks/validation";+export * from "./webhooks/ipBlocking";export * from "./redis/experimentCreateQueue";export * from "./redis/dlqRetryQueue";export * from "./redis/entityChangeQueue";diff --git a/packages/shared/src/server/webhooks/ipBlocking.ts b/packages/shared/src/server/webhooks/ipBlocking.tsnew file mode 100644index 0000000000..077306ead0--- /dev/null+++ b/packages/shared/src/server/webhooks/ipBlocking.ts@@ -0,0 +1,113 @@+import ipaddr from "ipaddr.js";++// Static deny-list (IPv4 + IPv6) for SSRF protection+const BLOCKED_CIDRS = [+ // IPv4+ "0.0.0.0/8", // "this network"+ "10.0.0.0/8", // RFC1918 private+ "100.64.0.0/10", // CG-NAT+ "127.0.0.0/8", // loopback+ "169.254.0.0/16", // link-local (includes AWS/GCP metadata)+ "172.16.0.0/12", // RFC1918 private+ "192.0.0.0/29", // IETF protocol+ "192.0.2.0/24", // TEST-NET-1+ "192.168.0.0/16", // RFC1918 private+ "198.18.0.0/15", // benchmark+ "198.51.100.0/24", // TEST-NET-2+ "203.0.113.0/24", // TEST-NET-3+ "224.0.0.0/4", // multicast+ "240.0.0.0/4", // future / reserved+ "255.255.255.255/32", // broadcast+ // IPv6+ "::/128", // unspecified+ "::1/128", // loopback+ "::ffff:0:0/96", // IPv4-mapped IPv6+ "fc00::/7", // unique-local+ "fe80::/10", // link-local+ "ff00::/8", // multicast+ "100::/64", // discard-only+ "2001::/32", // Teredo tunneling+ "2001:db8::/32", // doc+];++// Pre-parse blocked networks once for performance+const blockedNetworks = BLOCKED_CIDRS.map((cidr) => {+ const [addr, bits] = cidr.split("/");+ const parsed = ipaddr.parse(addr);+ return {+ network: parsed,+ kind: parsed.kind(),+ mask: parseInt(bits, 10),+ };+});++/**+ * Check if an IP address is blocked based on CIDR ranges+ */+export function isIPBlocked(ipString: string): boolean {+ try {+ const ip = ipaddr.parse(ipString);++ for (const { network, mask, kind } of blockedNetworks) {+ if (ip.kind() !== kind) continue;+ if (ip.match(network, mask)) return true;+ }+ return false;+ } catch {+ // If IP parsing fails, block it to be safe+ return true;+ }+}++/**+ * Check if a string is an IP address+ */+export function isIPAddress(hostname: string): boolean {+ // Remove brackets from IPv6 addresses+ const cleaned = hostname.replace(/^\[|\]$/g, "");++ try {+ ipaddr.parse(cleaned);+ return true;+ } catch {+ return false;+ }+}++/**+ * Check if hostname should be blocked based on patterns+ */+export function isHostnameBlocked(hostname: string): boolean {+ const blockedPatterns = [+ // Localhost variations+ "localhost",+ "*.localhost",++ // Common internal hostnames+ "internal",+ "*.internal",+ "intranet",+ "*.intranet",++ // Cloud metadata endpoints+ "metadata.google.internal",+ "169.254.169.254",++ // Docker/container networking+ "host.docker.internal",+ "gateway.docker.internal",+ ];++ for (const pattern of blockedPatterns) {+ if (pattern.startsWith("*.")) {+ const suffix = pattern.slice(2);+ if (hostname === suffix || hostname.endsWith(`.${suffix}`)) {+ return true;+ }+ } else if (hostname === pattern) {+ return true;+ }+ }++ return false;+}diff --git a/packages/shared/src/server/webhooks/validation.ts b/packages/shared/src/server/webhooks/validation.tsnew file mode 100644index 0000000000..cae131662a--- /dev/null+++ b/packages/shared/src/server/webhooks/validation.ts@@ -0,0 +1,121 @@+import dns from "node:dns/promises";+import { URL } from "node:url";+import { isIPBlocked, isIPAddress, isHostnameBlocked } from "./ipBlocking";++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;+}++/**+ * Validates a webhook URL to prevent SSRF attacks by blocking internal/private IP addresses+ * Should be called when saving webhook URLs and before sending webhooks+ *+ * Security Note: This validation has a Time-of-Check-Time-of-Use (TOCTOU) vulnerability+ * where DNS can change between validation and actual HTTP request. For maximum security,+ * the HTTP client should also implement IP blocking at connection time.+ */+export async function validateWebhookURL(urlString: string): 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");+ }++ if (!["https:", "http:"].includes(url.protocol)) {+ throw new Error("Only HTTP and HTTPS protocols are allowed");+ }++ // Step 2: Port validation+ if (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);++ // 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)) {+ throw new Error(`Blocked IP address detected: ${hostname}`);+ }+ }++ // Step 5: DNS resolution and validation+ const ips = await resolveHost(hostname);+ for (const ip of ips) {+ if (isIPBlocked(ip)) {+ throw new Error(`Blocked IP address detected: ${ip}`);+ }+ }+}++/**+ * 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;+}diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex 754e97f0ce..ae6b2f82aa 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -215,6 +215,9 @@ importers:ioredis:specifier: ^5.4.1version: 5.4.1+ ipaddr.js:+ specifier: ^2.2.0+ version: 2.2.0jsonpath-plus:specifier: 10.3.0version: 10.3.0@@ -8344,6 +8347,10 @@ packages:resolution: {integrity: sha512-0KI/607xoxSToH7GjN1FfSbLoU0+btTicjsQSWQlh/hZykN8KpmMf7uYwPW3R+akZ6R/w18ZlXSHBYXiYUPO3g==}engines: {node: '>= 0.10'}+ resolution: {integrity: sha512-Ag3wB2o37wslZS19hZqorUnrnzSkpOVy+IiiDEiTqNubEYpYuHWIf6K4psgN2ZWKExS4xhVCrRVfb/wfW8fWJA==}+ engines: {node: '>= 10'}+resolution: {integrity: sha512-FWyyY60MeTNyeSRpkM2Iry0G9hpr7/9kD40mD/cGQEuilcZYS4okz8SN2Q6rLCJ8gbCt6fN+rC+6tMGS99LaxQ==}@@ -21794,6 +21801,8 @@ snapshots:+ [email protected]: {}+diff --git a/web/src/features/automations/server/webhookHelpers.ts b/web/src/features/automations/server/webhookHelpers.tsindex cc6c599741..19cfa6bbc5 100644--- a/web/src/features/automations/server/webhookHelpers.ts+++ b/web/src/features/automations/server/webhookHelpers.ts@@ -15,6 +15,7 @@ import {mergeHeaders,createDisplayHeaders,encryptSecretHeaders,+ validateWebhookURL,} from "@langfuse/shared/src/server";import { TRPCError } from "@trpc/server";@@ -53,6 +54,15 @@ export async function processWebhookActionConfig({existingActionConfig = existingAction.config;}+ try {+ await validateWebhookURL(actionConfig.url);+ } catch (error) {+ throw new TRPCError({+ code: "BAD_REQUEST",+ message: `Invalid webhook URL: ${error instanceof Error ? error.message : "Unknown error"}`,+ });+ }+const { secretKey: newSecretKey, displaySecretKey: newDisplaySecretKey } =generateWebhookSecret();diff --git a/worker/src/__tests__/ip-blocking.test.ts b/worker/src/__tests__/ip-blocking.test.tsnew file mode 100644index 0000000000..954e0ac500--- /dev/null+++ b/worker/src/__tests__/ip-blocking.test.ts@@ -0,0 +1,181 @@+import { describe, it, expect } from "vitest";+import {+ isIPBlocked,+ isIPAddress,+ isHostnameBlocked,+} from "@langfuse/shared/src/server";++describe("IP Blocking Module", () => {+ describe("isIPBlocked", () => {+ describe("IPv4 blocked addresses", () => {+ it("should block localhost addresses", () => {+ expect(isIPBlocked("127.0.0.1")).toBe(true);+ expect(isIPBlocked("127.1.1.1")).toBe(true);+ expect(isIPBlocked("127.255.255.255")).toBe(true);+ });++ it("should block private network addresses", () => {+ expect(isIPBlocked("10.0.0.1")).toBe(true);+ expect(isIPBlocked("10.255.255.255")).toBe(true);+ expect(isIPBlocked("172.16.0.1")).toBe(true);+ expect(isIPBlocked("172.31.255.255")).toBe(true);+ expect(isIPBlocked("192.168.0.1")).toBe(true);+ expect(isIPBlocked("192.168.255.255")).toBe(true);+ });++ it("should block link-local addresses", () => {+ expect(isIPBlocked("169.254.0.1")).toBe(true);+ expect(isIPBlocked("169.254.169.254")).toBe(true); // AWS metadata+ expect(isIPBlocked("169.254.255.255")).toBe(true);+ });++ it("should block multicast addresses", () => {+ expect(isIPBlocked("224.0.0.1")).toBe(true);+ expect(isIPBlocked("239.255.255.255")).toBe(true);+ });++ it("should block broadcast and reserved addresses", () => {+ expect(isIPBlocked("255.255.255.255")).toBe(true);+ expect(isIPBlocked("240.0.0.1")).toBe(true);+ expect(isIPBlocked("0.0.0.1")).toBe(true);+ });++ it("should block test networks", () => {+ expect(isIPBlocked("192.0.2.1")).toBe(true); // TEST-NET-1+ expect(isIPBlocked("198.51.100.1")).toBe(true); // TEST-NET-2+ expect(isIPBlocked("203.0.113.1")).toBe(true); // TEST-NET-3+ });++ it("should block CG-NAT addresses", () => {+ expect(isIPBlocked("100.64.0.1")).toBe(true);+ expect(isIPBlocked("100.127.255.255")).toBe(true);+ });+ });++ describe("IPv6 blocked addresses", () => {+ it("should block IPv6 localhost", () => {+ expect(isIPBlocked("::1")).toBe(true);+ expect(isIPBlocked("::")).toBe(true);+ });++ it("should block IPv6 private addresses", () => {+ expect(isIPBlocked("fc00::1")).toBe(true);+ expect(isIPBlocked("fd00::1")).toBe(true);+ expect(isIPBlocked("fe80::1")).toBe(true);+ });++ it("should block IPv6 multicast", () => {+ expect(isIPBlocked("ff00::1")).toBe(true);+ expect(isIPBlocked("ff02::1")).toBe(true);+ });++ it("should block IPv4-mapped IPv6 addresses", () => {+ expect(isIPBlocked("::ffff:192.168.1.1")).toBe(true);+ expect(isIPBlocked("::ffff:127.0.0.1")).toBe(true);+ });++ it("should block Teredo addresses", () => {+ expect(isIPBlocked("2001::1")).toBe(true);+ expect(isIPBlocked("2001:0000:4136:e378:8000:63bf:3fff:fdd2")).toBe(+ true,+ );+ });+ });++ describe("allowed public addresses", () => {+ it("should allow public IPv4 addresses", () => {+ expect(isIPBlocked("8.8.8.8")).toBe(false); // Google DNS+ expect(isIPBlocked("1.1.1.1")).toBe(false); // Cloudflare DNS+ expect(isIPBlocked("208.67.222.222")).toBe(false); // OpenDNS+ expect(isIPBlocked("74.125.224.72")).toBe(false); // Google+ });++ it("should allow public IPv6 addresses", () => {+ expect(isIPBlocked("2001:4860:4860::8888")).toBe(false); // Google DNS+ expect(isIPBlocked("2606:4700:4700::1111")).toBe(false); // Cloudflare DNS+ });+ });++ describe("invalid IP addresses", () => {+ it("should block invalid IP strings", () => {+ expect(isIPBlocked("not-an-ip")).toBe(true);+ expect(isIPBlocked("256.256.256.256")).toBe(true);+ expect(isIPBlocked("")).toBe(true);+ expect(isIPBlocked("invalid")).toBe(true);+ });+ });+ });++ describe("isIPAddress", () => {+ it("should detect valid IPv4 addresses", () => {+ expect(isIPAddress("192.168.1.1")).toBe(true);+ expect(isIPAddress("8.8.8.8")).toBe(true);+ expect(isIPAddress("127.0.0.1")).toBe(true);+ });++ it("should detect valid IPv6 addresses", () => {+ expect(isIPAddress("::1")).toBe(true);+ expect(isIPAddress("2001:4860:4860::8888")).toBe(true);+ expect(isIPAddress("fe80::1")).toBe(true);+ });++ it("should handle IPv6 addresses with brackets", () => {+ expect(isIPAddress("[::1]")).toBe(true);+ expect(isIPAddress("[2001:4860:4860::8888]")).toBe(true);+ });++ it("should not detect hostnames as IP addresses", () => {+ expect(isIPAddress("example.com")).toBe(false);+ expect(isIPAddress("localhost")).toBe(false);+ expect(isIPAddress("google.com")).toBe(false);+ });++ it("should handle invalid formats", () => {+ expect(isIPAddress("256.256.256.256")).toBe(false);+ expect(isIPAddress("not-an-ip")).toBe(false);+ expect(isIPAddress("")).toBe(false);+ });+ });++ describe("isHostnameBlocked", () => {+ it("should block localhost variations", () => {+ expect(isHostnameBlocked("localhost")).toBe(true);+ expect(isHostnameBlocked("test.localhost")).toBe(true);+ expect(isHostnameBlocked("api.localhost")).toBe(true);+ });++ it("should block internal hostnames", () => {+ expect(isHostnameBlocked("internal")).toBe(true);+ expect(isHostnameBlocked("api.internal")).toBe(true);+ expect(isHostnameBlocked("service.internal")).toBe(true);+ });++ it("should block intranet hostnames", () => {+ expect(isHostnameBlocked("intranet")).toBe(true);+ expect(isHostnameBlocked("portal.intranet")).toBe(true);+ });++ it("should block cloud metadata endpoints", () => {+ expect(isHostnameBlocked("metadata.google.internal")).toBe(true);+ expect(isHostnameBlocked("169.254.169.254")).toBe(true);+ });++ it("should block Docker internal hostnames", () => {+ expect(isHostnameBlocked("host.docker.internal")).toBe(true);+ expect(isHostnameBlocked("gateway.docker.internal")).toBe(true);+ });++ it("should allow legitimate hostnames", () => {+ expect(isHostnameBlocked("example.com")).toBe(false);+ expect(isHostnameBlocked("google.com")).toBe(false);+ expect(isHostnameBlocked("github.com")).toBe(false);+ expect(isHostnameBlocked("webhook.site")).toBe(false);+ });++ it("should handle edge cases", () => {+ expect(isHostnameBlocked("")).toBe(false);+ expect(isHostnameBlocked("localhostbutnotreally.com")).toBe(false);+ expect(isHostnameBlocked("internal.company.com")).toBe(false); // Only blocks *.internal, not *internal*+ });+ });+});diff --git a/worker/src/__tests__/url-normalization.test.ts b/worker/src/__tests__/url-normalization.test.tsnew file mode 100644index 0000000000..f7d57fdf58--- /dev/null+++ b/worker/src/__tests__/url-normalization.test.ts@@ -0,0 +1,288 @@+import { describe, it, expect } from "vitest";+import { validateWebhookURL } from "@langfuse/shared/src/server";++describe("URL Normalization and Edge Cases", () => {+ describe("URL encoding bypass attempts", () => {+ it("should reject URL-encoded localhost", async () => {+ // %6C%6F%63%61%6C%68%6F%73%74 = "localhost"+ await expect(+ validateWebhookURL("http://%6C%6F%63%61%6C%68%6F%73%74/webhook"),+ ).rejects.toThrow("Blocked hostname detected");+ });++ it("should reject double-encoded URLs", async () => {+ // Double encoding of "localhost"+ await expect(+ validateWebhookURL(+ "http://%256C%256F%2563%2561%256C%2568%256F%2573%2574/webhook",+ ),+ ).rejects.toThrow(/Invalid URL|Blocked hostname detected/);+ });++ it("should reject mixed case encoding", async () => {+ // Mixed case: %6c%6f%63%61%6c%68%6f%73%74 = "localhost"+ await expect(+ validateWebhookURL("http://%6c%6f%63%61%6c%68%6f%73%74/webhook"),+ ).rejects.toThrow("Blocked hostname detected");+ });++ it("should handle partial URL encoding", async () => {+ // Partially encoded: local%68ost = "localhost"+ await expect(+ validateWebhookURL("http://local%68ost/webhook"),+ ).rejects.toThrow("Blocked hostname detected");+ });++ it("should reject encoded private IPs", async () => {+ // %31%39%32%2E%31%36%38%2E%31%2E%31 = "192.168.1.1"+ await expect(+ validateWebhookURL("http://%31%39%32%2E%31%36%38%2E%31%2E%31/webhook"),+ ).rejects.toThrow("Blocked IP address detected");+ });+ });++ describe("Unicode and IDN bypass attempts", () => {+ it("should handle unicode domains properly", async () => {+ // These should be converted to punycode and validated+ await expect(+ validateWebhookURL("http://тест.example.com/webhook"),+ ).rejects.toThrow(/DNS lookup failed|Invalid URL/);+ });++ it("should normalize unicode characters", async () => {+ // Unicode variations that could be used for bypassing+ const unicodeVariations = [+ "http://localhost/webhook", // Fullwidth characters+ "http://localhost\u200d/webhook", // Zero-width joiner+ "http://lօcalhost/webhook", // Armenian O that looks like Latin O+ ];++ for (const url of unicodeVariations) {+ await expect(validateWebhookURL(url)).rejects.toThrow(+ /Blocked hostname detected|Invalid URL|DNS lookup failed/,+ );+ }+ });++ it("should handle homograph attacks", async () => {+ // Cyrillic characters that look like Latin+ await expect(validateWebhookURL("http://ӏocalhost/webhook")) // Cyrillic і that looks like l+ .rejects.toThrow(/Blocked hostname detected|DNS lookup failed/);+ });+ });++ describe("Whitespace and special character handling", () => {+ it("should trim whitespace from URLs", async () => {+ await expect(+ validateWebhookURL(" http://localhost/webhook "),+ ).rejects.toThrow("Blocked hostname detected");+ });++ it("should handle newlines and tabs", async () => {+ await expect(+ validateWebhookURL("http://localhost/webhook\n"),+ ).rejects.toThrow("Blocked hostname detected");++ await expect(+ validateWebhookURL("http://localhost/webhook\t"),+ ).rejects.toThrow("Blocked hostname detected");+ });++ it("should handle URLs with unusual characters", async () => {+ await expect(+ validateWebhookURL("http://localhost:80/../webhook"),+ ).rejects.toThrow("Blocked hostname detected");+ });+ });++ describe("Protocol and port edge cases", () => {+ it("should reject case variations of protocols", async () => {+ await expect(+ validateWebhookURL("HTTP://localhost/webhook"),+ ).rejects.toThrow("Blocked hostname detected");++ await expect(+ validateWebhookURL("hTTp://localhost/webhook"),+ ).rejects.toThrow("Blocked hostname detected");+ });++ it("should handle implicit ports correctly", async () => {+ // These should not be rejected for port reasons, but for hostname+ await expect(+ validateWebhookURL("http://localhost/webhook"),+ ).rejects.toThrow("Blocked hostname detected");++ await expect(+ validateWebhookURL("https://localhost/webhook"),+ ).rejects.toThrow("Blocked hostname detected");+ });++ it("should reject non-standard port formats", async () => {+ await expect(+ validateWebhookURL("http://example.com:08080/webhook"),+ ).rejects.toThrow("Only ports 80 and 443 are allowed");+ });+ });++ describe("IPv6 edge cases", () => {+ it("should handle IPv6 with brackets", async () => {+ await expect(validateWebhookURL("http://[::1]/webhook")).rejects.toThrow(+ /Blocked IP address detected|ipaddr:/,+ );+ });++ it("should handle IPv6 without brackets in URL context", async () => {+ // This should fail URL parsing+ await expect(validateWebhookURL("http://::1/webhook")).rejects.toThrow(+ "Invalid URL syntax",+ );+ });++ it("should handle compressed IPv6 addresses", async () => {+ await expect(+ validateWebhookURL("http://[2001:db8::1]/webhook"),+ ).rejects.toThrow(/Blocked IP address detected|ipaddr:/);+ });++ it("should handle IPv4-mapped IPv6 addresses", async () => {+ await expect(+ validateWebhookURL("http://[::ffff:192.168.1.1]/webhook"),+ ).rejects.toThrow(/Blocked IP address detected|ipaddr:/);+ });+ });++ describe("Malformed URL handling", () => {+ it("should reject URLs with invalid syntax", async () => {+ // URLs that should fail at URL parsing stage+ const invalidSyntaxUrls = [+ "http://",+ "://example.com",+ "http://?",+ "http://#",+ "http://exam ple.com", // Space in hostname+ ];++ // URLs that pass URL parsing but fail DNS resolution+ const invalidDnsUrls = [+ "http://.com",+ "http://.",+ "http://..",+ "http://../",+ "http://invalid-domain-that-should-not-exist-12345.invalid",+ ];++ // Test URLs that fail at parsing+ for (const url of invalidSyntaxUrls) {+ await expect(validateWebhookURL(url)).rejects.toThrow(+ /Invalid URL syntax/,+ );+ }++ // Test URLs that fail at DNS resolution+ for (const url of invalidDnsUrls) {+ await expect(validateWebhookURL(url)).rejects.toThrow(+ /DNS lookup failed/,+ );+ }+ });++ it("should handle URLs with invalid encoding", async () => {+ const invalidEncodedUrls = [+ "http://exam%ple.com/webhook", // Invalid % encoding+ "http://example.com/%ZZ", // Invalid hex in encoding+ "http://example.com/%G1", // Invalid hex characters+ ];++ for (const url of invalidEncodedUrls) {+ await expect(validateWebhookURL(url)).rejects.toThrow(+ /Invalid URL|DNS lookup failed/,+ );+ }+ });+ });++ describe("Boundary conditions", () => {+ it("should handle very long URLs", async () => {+ const longHostname = "a".repeat(253) + ".com"; // Max hostname length+ await expect(+ validateWebhookURL(`https://${longHostname}/webhook`),+ ).rejects.toThrow(/DNS lookup failed/);+ });++ it("should handle URLs with many subdomains", async () => {+ const manySubdomains = Array(50).fill("sub").join(".") + ".example.com";+ await expect(+ validateWebhookURL(`https://${manySubdomains}/webhook`),+ ).rejects.toThrow(/DNS lookup failed/);+ }, 10000);++ it("should handle empty hostname", async () => {+ // This URL is parsed as hostname="webhook" by URL constructor+ // so it fails during DNS resolution, not URL parsing+ await expect(validateWebhookURL("http:///webhook")).rejects.toThrow(+ "DNS lookup failed for webhook",+ );+ });+ });++ describe("Path and query parameter edge cases", () => {+ it("should validate hostname regardless of path", async () => {+ await expect(+ validateWebhookURL(+ "http://localhost/very/long/path/with/many/segments",+ ),+ ).rejects.toThrow("Blocked hostname detected");+ });++ it("should validate hostname regardless of query parameters", async () => {+ await expect(+ validateWebhookURL("http://localhost/webhook?param=value&other=test"),+ ).rejects.toThrow("Blocked hostname detected");+ });++ it("should validate hostname regardless of fragment", async () => {+ await expect(+ validateWebhookURL("http://localhost/webhook#fragment"),+ ).rejects.toThrow("Blocked hostname detected");+ });++ it("should handle encoded path components", async () => {+ await expect(+ validateWebhookURL("http://localhost/web%20hook"),+ ).rejects.toThrow("Blocked hostname detected");+ });+ });++ describe("Real-world bypass attempts", () => {+ it("should block attempts to access cloud metadata services", async () => {+ const metadataAttempts = [+ "http://169.254.169.254/latest/meta-data/",+ "http://metadata.google.internal/computeMetadata/v1/",+ "http://metadata/latest/meta-data/",+ "http://169.254.169.254/v1.0/metadata/",+ ];++ for (const url of metadataAttempts) {+ await expect(validateWebhookURL(url)).rejects.toThrow(+ /Blocked|DNS lookup failed/,+ );+ }+ });++ it("should block attempts to access internal services", async () => {+ const internalAttempts = [+ "http://internal/api/health",+ "http://service.internal/status",+ "http://admin.internal/dashboard",+ "http://localhost:8080/admin",+ "http://127.0.0.1:3000/api",+ ];++ for (const url of internalAttempts) {+ await expect(validateWebhookURL(url)).rejects.toThrow(+ /Blocked|Only ports 80 and 443 are allowed/,+ );+ }+ });+ });+});diff --git a/worker/src/__tests__/webhook-validation.test.ts b/worker/src/__tests__/webhook-validation.test.tsnew file mode 100644index 0000000000..e02533b454--- /dev/null+++ b/worker/src/__tests__/webhook-validation.test.ts@@ -0,0 +1,153 @@+import { describe, it, expect } from "vitest";+import { validateWebhookURL } from "@langfuse/shared/src/server";++describe("Webhook URL Validation", () => {+ describe("validateWebhookURL", () => {+ it("should accept valid public HTTPS URLs", async () => {+ await expect(+ validateWebhookURL("https://httpbin.org/post"),+ ).resolves.not.toThrow();+ });++ it("should accept valid public HTTP URLs", async () => {+ await expect(+ validateWebhookURL("http://httpbin.org/post"),+ ).resolves.not.toThrow();+ });++ it("should reject invalid URL syntax", async () => {+ await expect(validateWebhookURL("not-a-url")).rejects.toThrow(+ "Invalid URL syntax",+ );+ });++ it("should reject non-HTTP/HTTPS protocols", async () => {+ await expect(validateWebhookURL("ftp://example.com")).rejects.toThrow(+ "Only HTTP and HTTPS protocols are allowed",+ );+ await expect(validateWebhookURL("file:///etc/passwd")).rejects.toThrow(+ "Only HTTP and HTTPS protocols are allowed",+ );+ });++ it("should reject disallowed ports", async () => {+ await expect(+ validateWebhookURL("https://example.com:8080/hook"),+ ).rejects.toThrow("Only ports 80 and 443 are allowed");+ await expect(+ validateWebhookURL("http://example.com:3000/hook"),+ ).rejects.toThrow("Only ports 80 and 443 are allowed");+ });++ it("should allow standard ports", async () => {+ await expect(+ validateWebhookURL("https://httpbin.org:443/post"),+ ).resolves.not.toThrow();+ await expect(+ validateWebhookURL("http://httpbin.org:80/post"),+ ).resolves.not.toThrow();+ });++ it("should reject localhost URLs", async () => {+ await expect(validateWebhookURL("http://localhost/hook")).rejects.toThrow(+ "Blocked hostname detected",+ );+ await expect(+ validateWebhookURL("http://test.localhost/hook"),+ ).rejects.toThrow("Blocked hostname detected");+ await expect(+ validateWebhookURL("https://127.0.0.1/hook"),+ ).rejects.toThrow("Blocked IP address detected");+ await expect(validateWebhookURL("http://[::1]/hook")).rejects.toThrow(+ /Blocked IP address detected|ipaddr:/,+ );+ });++ it("should reject private network URLs", async () => {+ await expect(+ validateWebhookURL("http://192.168.1.1/hook"),+ ).rejects.toThrow("Blocked IP address detected");+ await expect(validateWebhookURL("http://10.0.0.1/hook")).rejects.toThrow(+ "Blocked IP address detected",+ );+ await expect(+ validateWebhookURL("http://172.16.0.1/hook"),+ ).rejects.toThrow("Blocked IP address detected");+ });++ it("should reject link-local addresses", async () => {+ await expect(+ validateWebhookURL("http://169.254.169.254/hook"),+ ).rejects.toThrow("Blocked hostname detected");+ });++ it("should reject multicast addresses", async () => {+ await expect(validateWebhookURL("http://224.0.0.1/hook")).rejects.toThrow(+ "Blocked IP address detected",+ );+ });++ it("should reject broadcast addresses", async () => {+ await expect(+ validateWebhookURL("http://255.255.255.255/hook"),+ ).rejects.toThrow("Blocked IP address detected");+ });++ it("should reject IPv6 private addresses", async () => {+ await expect(validateWebhookURL("http://[fc00::1]/hook")).rejects.toThrow(+ /Blocked IP address detected|ipaddr:/,+ );+ await expect(validateWebhookURL("http://[fe80::1]/hook")).rejects.toThrow(+ /Blocked IP address detected|ipaddr:/,+ );+ });++ it("should handle DNS resolution failures gracefully", async () => {+ await expect(+ validateWebhookURL(+ "https://this-domain-definitely-does-not-exist-12345.com/hook",+ ),+ ).rejects.toThrow("DNS lookup failed");+ });++ it("should reject URL-encoded localhost bypass attempts", async () => {+ // %6C%6F%63%61%6C%68%6F%73%74 decodes to "localhost" but fails on port check first+ await expect(+ validateWebhookURL("http://%6C%6F%63%61%6C%68%6F%73%74/hook"),+ ).rejects.toThrow("Blocked hostname detected");+ });++ it("should reject internal/intranet hostnames", async () => {+ await expect(+ validateWebhookURL("http://internal.company.com/hook"),+ ).rejects.toThrow(/Blocked hostname detected|DNS lookup failed/);+ await expect(+ validateWebhookURL("http://app.internal/hook"),+ ).rejects.toThrow("Blocked hostname detected");+ await expect(validateWebhookURL("http://intranet/hook")).rejects.toThrow(+ "Blocked hostname detected",+ );+ });++ it("should reject docker internal hostnames", async () => {+ await expect(+ validateWebhookURL("http://host.docker.internal/hook"),+ ).rejects.toThrow("Blocked hostname detected");+ await expect(+ validateWebhookURL("http://gateway.docker.internal/hook"),+ ).rejects.toThrow("Blocked hostname detected");+ });++ it("should reject cloud metadata endpoints", async () => {+ await expect(+ validateWebhookURL("http://metadata.google.internal/hook"),+ ).rejects.toThrow("Blocked hostname detected");+ });++ it("should handle malformed URL encoding", async () => {+ await expect(+ validateWebhookURL("http://exam%ple.com/hook"),+ ).rejects.toThrow(/Invalid URL encoding|Invalid URL syntax/);+ });+ });+});diff --git a/worker/src/__tests__/webhooks.test.ts b/worker/src/__tests__/webhooks.test.tsindex 55055f9a5e..ba68594b41 100644--- a/worker/src/__tests__/webhooks.test.ts+++ b/worker/src/__tests__/webhooks.test.ts@@ -11,7 +11,6 @@ import { v4 } from "uuid";import {ActionExecutionStatus,JobConfigState,- JsonNested,PromptDomainSchema,WebhookActionConfigWithSecrets,} from "@langfuse/shared";@@ -219,7 +218,7 @@ describe("Webhook Integration Tests", () => {},});- await executeWebhook(webhookInput);+ await executeWebhook(webhookInput, { skipValidation: true });// Verify webhook request was madeconst requests = webhookServer.getReceivedRequests();@@ -341,9 +340,9 @@ describe("Webhook Integration Tests", () => {},};- await expect(executeWebhook(webhookInput)).rejects.toThrow(- "Action config is not a valid webhook configuration",- );+ await expect(+ executeWebhook(webhookInput, { skipValidation: true }),+ ).rejects.toThrow("Action config is not a valid webhook configuration");const execution = await prisma.automationExecution.findUnique({where: { id: executionId },@@ -406,7 +405,7 @@ describe("Webhook Integration Tests", () => {},};- await executeWebhook(webhookInput);+ await executeWebhook(webhookInput, { skipValidation: true });// Verify execution was marked as errorconst execution = await prisma.automationExecution.findUnique({@@ -480,7 +479,7 @@ describe("Webhook Integration Tests", () => {},};- await executeWebhook(webhookInput);+ await executeWebhook(webhookInput, { skipValidation: true });// Verify execution was marked as errorconst execution = await prisma.automationExecution.findUnique({@@ -573,7 +572,7 @@ describe("Webhook Integration Tests", () => {},});- await executeWebhook(webhookInput);+ await executeWebhook(webhookInput, { skipValidation: true });// Verify webhook request was made with decrypted secret headersconst requests = webhookServer.getReceivedRequests();@@ -664,7 +663,7 @@ describe("Webhook Integration Tests", () => {},});- await executeWebhook(webhookInput);+ await executeWebhook(webhookInput, { skipValidation: true });// Verify webhook request was made with decrypted secret headersconst requests = webhookServer.getReceivedRequests();@@ -743,7 +742,7 @@ describe("Webhook Integration Tests", () => {},});- await executeWebhook(webhookInput);+ await executeWebhook(webhookInput, { skipValidation: true });// Verify webhook request was made with public headersconst requests = webhookServer.getReceivedRequests();@@ -827,7 +826,7 @@ describe("Webhook Integration Tests", () => {},});- await executeWebhook(webhookInput);+ await executeWebhook(webhookInput, { skipValidation: true });// Verify webhook request was made with public headersconst requests = webhookServer.getReceivedRequests();@@ -910,7 +909,7 @@ describe("Webhook Integration Tests", () => {},});- await executeWebhook(webhookInput);+ await executeWebhook(webhookInput, { skipValidation: true });// Verify webhook request was made with valid headers onlyconst requests = webhookServer.getReceivedRequests();@@ -952,7 +951,9 @@ describe("Webhook Integration Tests", () => {};// Should not throw an error, but return gracefully- await expect(executeWebhook(webhookInput)).resolves.toBeUndefined();+ await expect(+ executeWebhook(webhookInput, { skipValidation: true }),+ ).resolves.toBeUndefined();// Verify that no execution record was created since automation doesn't existconst execution = await prisma.automationExecution.findUnique({@@ -1080,7 +1081,7 @@ describe("Webhook Integration Tests", () => {},};- await executeWebhook(webhookInput);+ await executeWebhook(webhookInput, { skipValidation: true });}// Verify trigger was disabled and lastFailingExecutionId was stored@@ -1136,7 +1137,7 @@ describe("Webhook Integration Tests", () => {},};- await executeWebhook(newWebhookInput);+ await executeWebhook(newWebhookInput, { skipValidation: true });}// Verify trigger was disabled again and lastFailingExecutionId was updateddiff --git a/worker/src/queues/webhooks.ts b/worker/src/queues/webhooks.tsindex a0cdc14edc..d4a69890a2 100644--- a/worker/src/queues/webhooks.ts+++ b/worker/src/queues/webhooks.ts@@ -10,6 +10,7 @@ import {} from "@langfuse/shared";import { decrypt, createSignatureHeader } from "@langfuse/shared/encryption";import { prisma } from "@langfuse/shared/src/db";+import { validateWebhookURL } from "@langfuse/shared/src/server";import {TQueueJobTypes,QueueName,@@ -39,7 +40,10 @@ export const webhookProcessor: Processor = async (};// TODO: Webhook outgoing API versioning-export const executeWebhook = async (input: WebhookInput) => {+export const executeWebhook = async (+ input: WebhookInput,+ options?: { skipValidation?: boolean },+) => {const { projectId, automationId } = input;try {@@ -62,6 +66,7 @@ export const executeWebhook = async (input: WebhookInput) => {await executeWebhookAction({input,automation,+ skipValidation: options?.skipValidation,});} else if (automation.action.type === "SLACK") {await executeSlackAction({@@ -89,9 +94,11 @@ export const executeWebhook = async (input: WebhookInput) => {async function executeWebhookAction({input,automation,+ skipValidation,}: {input: WebhookInput;automation: Awaited<ReturnType<typeof getAutomationById>>;+ skipValidation?: boolean;}) {if (!automation) return;@@ -184,6 +191,11 @@ async function executeWebhookAction({}, env.LANGFUSE_WEBHOOK_TIMEOUT_MS);try {+ // Skip validation when flag is set (for tests with MSW mocking)+ if (!skipValidation) {+ await validateWebhookURL(webhookConfig.url);+ }+const res = await fetch(webhookConfig.url, {method: "POST",body: webhookPayload,