Skip to content

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

security: validate webhook reditrects (#11256)

Max Deichmann6bcf0fad2c0d
diff --git a/packages/shared/src/server/index.ts b/packages/shared/src/server/index.ts
index 071cb05309..0887737f94 100644
--- a/packages/shared/src/server/index.ts
+++ b/packages/shared/src/server/index.ts
@@ -71,6 +71,7 @@ export * from "./redis/meteringDataPostgresExportQueue";
export * from "./redis/notificationQueue";
export * from "./webhooks/validation";
export * from "./webhooks/ipBlocking";
+export * from "./webhooks/redirectHandler";
export * from "./redis/experimentCreateQueue";
export * from "./redis/dlqRetryQueue";
export * from "./redis/entityChangeQueue";
diff --git a/packages/shared/src/server/webhooks/redirectHandler.ts b/packages/shared/src/server/webhooks/redirectHandler.ts
new file mode 100644
index 0000000000..c03e5aae58
--- /dev/null
+++ b/packages/shared/src/server/webhooks/redirectHandler.ts
@@ -0,0 +1,213 @@
+import { validateWebhookURL } from "./validation";
+import type { WebhookValidationWhitelist } from "./validation";
+import { logger } from "../logger";
+
+/**
+ * Custom error for redirect validation failures
+ */
+export class RedirectValidationError extends Error {
+ constructor(
+ message: string,
+ public redirectUrl: string,
+ public redirectDepth: number,
+ ) {
+ super(
+ `Redirect validation failed at depth ${redirectDepth} for url ${redirectUrl}: ${message}`,
+ );
+ this.name = "RedirectValidationError";
+ }
+}
+
+/**
+ * Custom error for exceeding maximum redirect depth
+ */
+export class MaxRedirectsExceededError extends Error {
+ constructor(
+ public maxRedirects: number,
+ public redirectChain: string[],
+ ) {
+ super(
+ `Maximum redirects (${maxRedirects}) exceeded. Chain: ${redirectChain.join(" → ")}`,
+ );
+ this.name = "MaxRedirectsExceededError";
+ }
+}
+
+/**
+ * Custom error for circular redirect detection
+ */
+export class CircularRedirectError extends Error {
+ constructor(public redirectChain: string[]) {
+ super(`Circular redirect detected: ${redirectChain.join(" → ")}`);
+ this.name = "CircularRedirectError";
+ }
+}
+
+/**
+ * Result of following redirects with validation
+ */
+export interface RedirectResult {
+ response: Response;
+ redirectChain: string[];
+ finalUrl: string;
+}
+
+/**
+ * Options for secure redirect handling
+ */
+export interface RedirectOptions {
+ maxRedirects: number;
+ skipValidation?: boolean;
+ whitelist?: WebhookValidationWhitelist;
+}
+
+/**
+ * Fetches a URL with manual redirect handling and validation at each step.
+ *
+ * This function prevents SSRF attacks via redirects by validating each redirect
+ * target before following it. It uses the same validation logic as the initial
+ * URL validation, checking for blocked hostnames, private IPs, and other SSRF vectors.
+ *
+ * @param url - The initial URL to fetch
+ * @param options - Fetch options (method, body, headers, signal, etc.)
+ * @param redirectOptions - Configuration for redirect handling (maxRedirects, skipValidation, whitelist)
+ * @returns Promise resolving to the final response, redirect chain, and final URL
+ * @throws RedirectValidationError if a redirect target fails validation
+ * @throws MaxRedirectsExceededError if redirect depth exceeds maxRedirects
+ * @throws CircularRedirectError if a redirect loop is detected
+ *
+ * @example
+ * ```typescript
+ * const result = await fetchWithSecureRedirects(
+ * "https://example.com/webhook",
+ * { method: "POST", body: payload, headers, signal },
+ * { maxRedirects: 10, skipValidation: false }
+ * );
+ * console.log(`Final URL: ${result.finalUrl}`);
+ * console.log(`Redirects: ${result.redirectChain.length}`);
+ * ```
+ */
+export async function fetchWithSecureRedirects(
+ url: string,
+ options: RequestInit,
+ redirectOptions: RedirectOptions,
+): Promise<RedirectResult> {
+ const { maxRedirects, skipValidation = false, whitelist } = redirectOptions;
+
+ // Track redirect chain for loop detection and logging
+ const redirectChain: string[] = [];
+ let currentUrl = url;
+ let redirectDepth = 0;
+
+ // Force manual redirect handling to prevent automatic following
+ const fetchOptions: RequestInit = {
+ ...options,
+ redirect: "manual",
+ };
+
+ while (redirectDepth <= maxRedirects) {
+ logger.debug("Fetching URL with manual redirect handling", {
+ url: currentUrl,
+ redirectDepth,
+ maxRedirects,
+ });
+
+ // Fetch the current URL
+ const response = await fetch(currentUrl, fetchOptions);
+
+ // Check if this is a redirect response (3xx status codes)
+ const isRedirect =
+ response.status >= 300 &&
+ response.status < 400 &&
+ response.status !== 304; // 304 Not Modified is not a redirect
+
+ if (!isRedirect) {
+ // This is the final response, return it
+ logger.debug("Received non-redirect response", {
+ url: currentUrl,
+ status: response.status,
+ redirectDepth,
+ });
+
+ return {
+ response,
+ redirectChain,
+ finalUrl: currentUrl,
+ };
+ }
+
+ // Extract the Location header for the redirect target
+ const location = response.headers.get("Location");
+
+ if (!location) {
+ throw new Error(
+ `Redirect response (${response.status}) missing Location header at ${currentUrl}`,
+ );
+ }
+
+ // Resolve relative URLs against the current URL
+ let redirectUrl: string;
+ try {
+ const resolvedUrl = new URL(location, currentUrl);
+ redirectUrl = resolvedUrl.toString();
+ } catch (error) {
+ throw new Error(
+ `Invalid redirect URL "${location}" at ${currentUrl}: ${error instanceof Error ? error.message : "Unknown error"}`,
+ );
+ }
+
+ logger.debug("Redirect detected", {
+ from: currentUrl,
+ to: redirectUrl,
+ status: response.status,
+ redirectDepth,
+ });
+
+ // Check for circular redirects
+ if (redirectChain.includes(redirectUrl)) {
+ throw new CircularRedirectError([...redirectChain, redirectUrl]);
+ }
+
+ // Add current URL to redirect chain before following
+ redirectChain.push(currentUrl);
+
+ // Check if we've hit the redirect limit
+ if (redirectDepth >= maxRedirects) {
+ throw new MaxRedirectsExceededError(maxRedirects, [
+ ...redirectChain,
+ redirectUrl,
+ ]);
+ }
+
+ // Validate the redirect target URL before following
+ if (!skipValidation) {
+ try {
+ await validateWebhookURL(redirectUrl, whitelist);
+ } catch (error) {
+ logger.warn("Redirect validation failed", {
+ from: currentUrl,
+ to: redirectUrl,
+ redirectDepth,
+ error: error instanceof Error ? error.message : "Unknown error",
+ });
+
+ throw new RedirectValidationError(
+ error instanceof Error ? error.message : "Validation failed",
+ redirectUrl,
+ redirectDepth,
+ );
+ }
+ }
+
+ // Follow the redirect
+ currentUrl = redirectUrl;
+ redirectDepth++;
+ }
+
+ // This should never be reached due to the check inside the loop,
+ // but included for completeness
+ throw new MaxRedirectsExceededError(maxRedirects, [
+ ...redirectChain,
+ currentUrl,
+ ]);
+}
diff --git a/packages/shared/src/server/webhooks/validation.ts b/packages/shared/src/server/webhooks/validation.ts
index 9b3ec9d0ea..aff53d83f6 100644
--- a/packages/shared/src/server/webhooks/validation.ts
+++ b/packages/shared/src/server/webhooks/validation.ts
@@ -34,7 +34,7 @@ export interface WebhookValidationWhitelist {
ip_ranges: string[];
}
-function whitelistFromEnv(): WebhookValidationWhitelist {
+export function whitelistFromEnv(): WebhookValidationWhitelist {
return {
hosts: env.LANGFUSE_WEBHOOK_WHITELISTED_HOST || [],
ips: env.LANGFUSE_WEBHOOK_WHITELISTED_IPS || [],
diff --git a/worker/src/__tests__/webhook-redirect.test.ts b/worker/src/__tests__/webhook-redirect.test.ts
new file mode 100644
index 0000000000..2656b2a3f1
--- /dev/null
+++ b/worker/src/__tests__/webhook-redirect.test.ts
@@ -0,0 +1,452 @@
+import { describe, it, expect, beforeAll, afterAll, beforeEach } from "vitest";
+import { setupServer } from "msw/node";
+import { http, HttpResponse } from "msw";
+import { executeWebhook } from "../queues/webhooks";
+import { prisma } from "@langfuse/shared/src/db";
+import { encrypt } from "@langfuse/shared/encryption";
+import {
+ ActionExecutionStatus,
+ JobConfigState,
+ PromptDomainSchema,
+} from "@langfuse/shared";
+import type { WebhookInput } from "@langfuse/shared/src/server";
+import { randomUUID } from "crypto";
+
+/**
+ * Webhook Redirect Functional Tests
+ *
+ * These tests verify that the webhook system correctly follows HTTP redirects
+ * and handles edge cases like circular redirects, max depth, etc.
+ *
+ * NOTE: Security validation (blocking private IPs, localhost, etc.) is tested separately in:
+ * - worker/src/__tests__/ip-blocking.test.ts
+ * - worker/src/__tests__/webhook-validation.test.ts
+ *
+ * The redirect validation implementation is in:
+ * - packages/shared/src/server/webhooks/redirectHandler.ts (fetchWithSecureRedirects)
+ * - packages/shared/src/server/webhooks/validation.ts (validateWebhookURL)
+ */
+
+// Mock server to handle HTTP redirects
+const server = setupServer();
+
+describe("Webhook Redirect Functional Tests", () => {
+ beforeAll(() => {
+ server.listen({ onUnhandledRequest: "bypass" });
+ });
+
+ afterAll(() => {
+ server.close();
+ });
+
+ beforeEach(() => {
+ server.resetHandlers();
+ });
+
+ // Helper function to create test automation with webhook action
+ async function createTestAutomation(webhookUrl: string) {
+ const projectId = randomUUID();
+ const orgId = randomUUID();
+ const actionId = randomUUID();
+ const triggerId = randomUUID();
+ const automationId = randomUUID();
+ const promptId = randomUUID();
+ const executionId = randomUUID();
+
+ // Create org first
+ await prisma.organization.create({
+ data: {
+ id: orgId,
+ name: `Test Org ${orgId}`,
+ },
+ });
+
+ // Create project
+ await prisma.project.create({
+ data: {
+ id: projectId,
+ name: `Test Project ${projectId}`,
+ orgId,
+ },
+ });
+
+ // Create prompt (matching webhooks.test.ts structure)
+ await prisma.prompt.create({
+ data: {
+ id: promptId,
+ projectId,
+ name: "test-prompt",
+ version: 1,
+ type: "text",
+ prompt: { text: "Hello {{name}}" },
+ createdBy: "test-user",
+ },
+ });
+
+ // Create trigger
+ await prisma.trigger.create({
+ data: {
+ id: triggerId,
+ projectId,
+ eventSource: "prompt-version",
+ eventActions: ["created"],
+ filter: [],
+ status: JobConfigState.ACTIVE,
+ },
+ });
+
+ // Create webhook action with proper config structure
+ const secretKey = encrypt("test-secret-key");
+ const displaySecretKey = "test-***-key";
+ await prisma.action.create({
+ data: {
+ id: actionId,
+ projectId,
+ type: "WEBHOOK",
+ config: {
+ type: "WEBHOOK",
+ url: webhookUrl,
+ headers: {},
+ apiVersion: { prompt: "v1" },
+ secretKey,
+ displaySecretKey,
+ },
+ },
+ });
+
+ // Create automation
+ await prisma.automation.create({
+ data: {
+ id: automationId,
+ projectId,
+ triggerId,
+ actionId,
+ name: "Test Automation",
+ },
+ });
+
+ return {
+ projectId,
+ orgId,
+ actionId,
+ triggerId,
+ automationId,
+ promptId,
+ executionId,
+ };
+ }
+
+ // Helper function to cleanup test data
+ async function cleanupTestData(projectId: string, orgId: string) {
+ await prisma.automationExecution.deleteMany({ where: { projectId } });
+ await prisma.automation.deleteMany({ where: { projectId } });
+ await prisma.action.deleteMany({ where: { projectId } });
+ await prisma.trigger.deleteMany({ where: { projectId } });
+ await prisma.prompt.deleteMany({ where: { projectId } });
+ await prisma.project.delete({ where: { id: projectId } });
+ await prisma.organization.delete({ where: { id: orgId } });
+ }
+
+ // Helper function to prepare webhook input with execution record
+ async function prepareWebhookExecution(
+ automation: Awaited<ReturnType<typeof createTestAutomation>>,
+ ) {
+ const {
+ projectId,
+ automationId,
+ executionId,
+ promptId,
+ triggerId,
+ actionId,
+ } = automation;
+
+ // Get the full prompt for the payload
+ const fullPrompt = await prisma.prompt.findUnique({
+ where: { id: promptId },
+ });
+
+ const input: WebhookInput = {
+ projectId,
+ automationId,
+ executionId,
+ payload: {
+ prompt: PromptDomainSchema.parse(fullPrompt),
+ action: "created",
+ type: "prompt-version",
+ },
+ };
+
+ // Create execution record
+ await prisma.automationExecution.create({
+ data: {
+ id: executionId,
+ projectId,
+ triggerId,
+ automationId,
+ actionId,
+ status: ActionExecutionStatus.PENDING,
+ sourceId: executionId,
+ input,
+ },
+ });
+
+ return input;
+ }
+
+ describe("Legitimate Redirects", () => {
+ it("should follow single redirect to valid public URL", async () => {
+ const automation = await createTestAutomation(
+ "https://redirector.example.com/step1",
+ );
+
+ let step1Called = false;
+ let step2Called = false;
+
+ server.use(
+ http.post("https://redirector.example.com/step1", () => {
+ step1Called = true;
+ return new Response(null, {
+ status: 302,
+ headers: { Location: "https://final.example.com/webhook" },
+ });
+ }),
+ http.post("https://final.example.com/webhook", () => {
+ step2Called = true;
+ return HttpResponse.json({ success: true }, { status: 200 });
+ }),
+ );
+
+ const input = await prepareWebhookExecution(automation);
+
+ await executeWebhook(input, { skipValidation: true });
+
+ expect(step1Called).toBe(true);
+ expect(step2Called).toBe(true);
+
+ const execution = await prisma.automationExecution.findFirst({
+ where: { id: automation.executionId, projectId: automation.projectId },
+ });
+
+ expect(execution).toBeDefined();
+ expect(execution?.status).toBe(ActionExecutionStatus.COMPLETED);
+
+ await cleanupTestData(automation.projectId, automation.orgId);
+ });
+
+ it("should follow multiple redirects to valid URLs", async () => {
+ const automation = await createTestAutomation(
+ "https://redirector.example.com/step1",
+ );
+
+ const callOrder: string[] = [];
+
+ server.use(
+ http.post("https://redirector.example.com/step1", () => {
+ callOrder.push("step1");
+ return new Response(null, {
+ status: 302,
+ headers: { Location: "https://redirector.example.com/step2" },
+ });
+ }),
+ http.post("https://redirector.example.com/step2", () => {
+ callOrder.push("step2");
+ return new Response(null, {
+ status: 302,
+ headers: { Location: "https://redirector.example.com/step3" },
+ });
+ }),
+ http.post("https://redirector.example.com/step3", () => {
+ callOrder.push("step3");
+ return HttpResponse.json({ success: true }, { status: 200 });
+ }),
+ );
+
+ const input = await prepareWebhookExecution(automation);
+
+ await executeWebhook(input, { skipValidation: true });
+
+ expect(callOrder).toEqual(["step1", "step2", "step3"]);
+
+ const execution = await prisma.automationExecution.findFirst({
+ where: { id: automation.executionId, projectId: automation.projectId },
+ });
+
+ expect(execution).toBeDefined();
+ expect(execution?.status).toBe(ActionExecutionStatus.COMPLETED);
+
+ await cleanupTestData(automation.projectId, automation.orgId);
+ });
+
+ it("should handle no redirects (direct response)", async () => {
+ const automation = await createTestAutomation(
+ "https://direct.example.com/webhook",
+ );
+
+ let called = false;
+
+ server.use(
+ http.post("https://direct.example.com/webhook", () => {
+ called = true;
+ return HttpResponse.json({ success: true }, { status: 200 });
+ }),
+ );
+
+ const input = await prepareWebhookExecution(automation);
+
+ await executeWebhook(input, { skipValidation: true });
+
+ expect(called).toBe(true);
+
+ const execution = await prisma.automationExecution.findFirst({
+ where: { id: automation.executionId, projectId: automation.projectId },
+ });
+
+ expect(execution).toBeDefined();
+ expect(execution?.status).toBe(ActionExecutionStatus.COMPLETED);
+
+ await cleanupTestData(automation.projectId, automation.orgId);
+ });
+
+ it("should resolve relative URL redirects correctly", async () => {
+ const automation = await createTestAutomation(
+ "https://relative-redirect.example.com/start",
+ );
+
+ let finalCalled = false;
+
+ server.use(
+ http.post("https://relative-redirect.example.com/start", () => {
+ return new Response(null, {
+ status: 302,
+ headers: { Location: "/final" }, // Relative URL
+ });
+ }),
+ http.post("https://relative-redirect.example.com/final", () => {
+ finalCalled = true;
+ return HttpResponse.json({ success: true }, { status: 200 });
+ }),
+ );
+
+ const input = await prepareWebhookExecution(automation);
+
+ await executeWebhook(input, { skipValidation: true });
+
+ expect(finalCalled).toBe(true);
+
+ const execution = await prisma.automationExecution.findFirst({
+ where: { id: automation.executionId, projectId: automation.projectId },
+ });
+
+ expect(execution).toBeDefined();
+ expect(execution?.status).toBe(ActionExecutionStatus.COMPLETED);
+
+ await cleanupTestData(automation.projectId, automation.orgId);
+ });
+ });
+
+ describe("Edge Cases", () => {
+ it("should fail when max redirect depth exceeded", async () => {
+ const automation = await createTestAutomation(
+ "https://infinite-redirect.example.com/step0",
+ );
+
+ // Create 11 redirects (exceeds default max of 10)
+ const handlers = [];
+ for (let i = 0; i < 11; i++) {
+ const currentStep = i;
+ const nextStep = i + 1;
+ handlers.push(
+ http.post(
+ `https://infinite-redirect.example.com/step${currentStep}`,
+ () => {
+ return new Response(null, {
+ status: 302,
+ headers: {
+ Location: `https://infinite-redirect.example.com/step${nextStep}`,
+ },
+ });
+ },
+ ),
+ );
+ }
+
+ server.use(...handlers);
+
+ const input = await prepareWebhookExecution(automation);
+
+ await executeWebhook(input, { skipValidation: true });
+
+ const execution = await prisma.automationExecution.findFirst({
+ where: { id: automation.executionId, projectId: automation.projectId },
+ });
+
+ expect(execution).toBeDefined();
+ expect(execution?.status).toBe(ActionExecutionStatus.ERROR);
+ expect(execution?.error).toContain("Maximum redirects");
+
+ await cleanupTestData(automation.projectId, automation.orgId);
+ });
+
+ it("should detect and block circular redirects", async () => {
+ const automation = await createTestAutomation(
+ "https://circular.example.com/a",
+ );
+
+ server.use(
+ http.post("https://circular.example.com/a", () => {
+ return new Response(null, {
+ status: 302,
+ headers: { Location: "https://circular.example.com/b" },
+ });
+ }),
+ http.post("https://circular.example.com/b", () => {
+ return new Response(null, {
+ status: 302,
+ headers: { Location: "https://circular.example.com/a" },
+ });
+ }),
+ );
+
+ const input = await prepareWebhookExecution(automation);
+
+ await executeWebhook(input, { skipValidation: true });
+
+ const execution = await prisma.automationExecution.findFirst({
+ where: { id: automation.executionId, projectId: automation.projectId },
+ });
+
+ expect(execution).toBeDefined();
+ expect(execution?.status).toBe(ActionExecutionStatus.ERROR);
+ expect(execution?.error).toContain("Circular redirect detected");
+
+ await cleanupTestData(automation.projectId, automation.orgId);
+ });
+
+ it("should fail on missing Location header in redirect response", async () => {
+ const automation = await createTestAutomation(
+ "https://broken-redirect.example.com/hook",
+ );
+
+ server.use(
+ http.post("https://broken-redirect.example.com/hook", () => {
+ // Return 302 without Location header
+ return new Response(null, { status: 302 });
+ }),
+ );
+
+ const input = await prepareWebhookExecution(automation);
+
+ await executeWebhook(input, { skipValidation: true });
+
+ const execution = await prisma.automationExecution.findFirst({
+ where: { id: automation.executionId, projectId: automation.projectId },
+ });
+
+ expect(execution).toBeDefined();
+ expect(execution?.status).toBe(ActionExecutionStatus.ERROR);
+ expect(execution?.error).toContain("missing Location header");
+
+ await cleanupTestData(automation.projectId, automation.orgId);
+ });
+ });
+});
diff --git a/worker/src/__tests__/webhook-validation.test.ts b/worker/src/__tests__/webhook-validation.test.ts
index d5ccb0cab9..8773a8e24a 100644
--- a/worker/src/__tests__/webhook-validation.test.ts
+++ b/worker/src/__tests__/webhook-validation.test.ts
@@ -123,9 +123,11 @@ describe("Webhook URL Validation", () => {
});
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 tests
await expect(
- validateWebhookURL("http://internal.company.com/hook"),
- ).rejects.toThrow(/Blocked hostname detected|DNS lookup failed/);
+ validateWebhookURL("http://service.internal/hook"),
+ ).rejects.toThrow("Blocked hostname detected");
await expect(
validateWebhookURL("http://app.internal/hook"),
).rejects.toThrow("Blocked hostname detected");
diff --git a/worker/src/env.ts b/worker/src/env.ts
index ecd8d6c85e..321c069e49 100644
--- a/worker/src/env.ts
+++ b/worker/src/env.ts
@@ -341,6 +341,7 @@ const EnvSchema = z.object({
.positive()
.default(5),
LANGFUSE_WEBHOOK_TIMEOUT_MS: z.coerce.number().positive().default(10000),
+ LANGFUSE_WEBHOOK_MAX_REDIRECTS: z.coerce.number().positive().default(10),
LANGFUSE_ENTITY_CHANGE_QUEUE_PROCESSING_CONCURRENCY: z.coerce
.number()
.positive()
diff --git a/worker/src/queues/webhooks.ts b/worker/src/queues/webhooks.ts
index 14bb0fec39..a4d9df1998 100644
--- a/worker/src/queues/webhooks.ts
+++ b/worker/src/queues/webhooks.ts
@@ -13,7 +13,11 @@ 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 {
+ validateWebhookURL,
+ whitelistFromEnv,
+ fetchWithSecureRedirects,
+} from "@langfuse/shared/src/server";
import {
TQueueJobTypes,
QueueName,
@@ -145,12 +149,33 @@ async function executeHttpAction({
await validateWebhookURL(url);
}
- const res = await fetch(url, {
- method: "POST",
- body: payload,
- headers,
- signal: abortController.signal,
- });
+ const redirectResult = await fetchWithSecureRedirects(
+ url,
+ {
+ method: "POST",
+ body: payload,
+ headers,
+ signal: abortController.signal,
+ },
+ {
+ maxRedirects: env.LANGFUSE_WEBHOOK_MAX_REDIRECTS,
+ skipValidation,
+ whitelist: whitelistFromEnv(),
+ },
+ );
+
+ const res = redirectResult.response;
+
+ // Log redirect chain if any redirects occurred (security audit trail)
+ if (redirectResult.redirectChain.length > 0) {
+ logger.info("Webhook followed redirects", {
+ actionId: automation.action.id,
+ initialUrl: url,
+ finalUrl: redirectResult.finalUrl,
+ redirectCount: redirectResult.redirectChain.length,
+ redirectChain: redirectResult.redirectChain,
+ });
+ }
httpStatus = res.status;
responseBody = await res.text();