Skip to content

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

fix(web): validate image URL redirects (#13501)

Tobias Wochinger290fcf2c8467
diff --git a/packages/shared/src/server/index.ts b/packages/shared/src/server/index.ts
index 0a878ca1e5..8430ad1263 100644
--- a/packages/shared/src/server/index.ts
+++ b/packages/shared/src/server/index.ts
@@ -33,6 +33,7 @@ export * from "./llm/internalTraceEvents";
export * from "./llm/compileChatMessages";
export * from "./llm/testModelCall";
export * from "./llm/baseUrlValidation";
+export * from "./outbound-url";
export * from "./llm/getInternalTracingHandler";
export * from "./utils/DatabaseReadStream";
export * from "./utils/transforms";
@@ -82,7 +83,6 @@ 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/llm/baseUrlValidation.ts b/packages/shared/src/server/llm/baseUrlValidation.ts
index 79dba3ed07..b6cbfa467e 100644
--- a/packages/shared/src/server/llm/baseUrlValidation.ts
+++ b/packages/shared/src/server/llm/baseUrlValidation.ts
@@ -3,7 +3,7 @@ import {
type OutboundUrlValidationWhitelist,
parseOutboundUrl,
validateOutboundUrlHost,
-} from "../outboundUrlValidation";
+} from "../outbound-url";
export type LlmBaseUrlValidationWhitelist = OutboundUrlValidationWhitelist;
diff --git a/packages/shared/src/server/webhooks/redirectHandler.ts b/packages/shared/src/server/outbound-url/fetch.ts
similarity index 84%
rename from packages/shared/src/server/webhooks/redirectHandler.ts
rename to packages/shared/src/server/outbound-url/fetch.ts
index fc1ab46705..11b9c41b5e 100644
--- a/packages/shared/src/server/webhooks/redirectHandler.ts
+++ b/packages/shared/src/server/outbound-url/fetch.ts
@@ -1,5 +1,4 @@
-import { validateWebhookURL } from "./validation";
-import type { WebhookValidationWhitelist } from "./validation";
+import type { OutboundUrlValidationWhitelist } from "./validation";
import { logger } from "../logger";
const SENSITIVE_REDIRECT_HEADERS = new Set([
@@ -59,26 +58,44 @@ export interface RedirectResult {
finalUrl: string;
}
-/**
- * Options for secure redirect handling
- */
-export interface RedirectOptions {
+export type RedirectUrlValidator = (
+ url: string,
+ whitelist?: OutboundUrlValidationWhitelist,
+) => Promise<void>;
+
+interface BaseRedirectOptions {
maxRedirects: number;
- skipValidation?: boolean;
- whitelist?: WebhookValidationWhitelist;
additionalSensitiveHeaders?: string[];
}
+interface RedirectValidationOptions {
+ validateUrl: RedirectUrlValidator;
+ whitelist?: OutboundUrlValidationWhitelist;
+}
+
+/**
+ * Options for secure redirect handling
+ */
+export type RedirectOptions =
+ | (BaseRedirectOptions & {
+ skipValidation: true;
+ redirectValidation?: never;
+ })
+ | (BaseRedirectOptions & {
+ skipValidation?: false;
+ redirectValidation: RedirectValidationOptions;
+ });
+
/**
* 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.
+ * target before following it. Callers provide validation so each outbound flow
+ * can enforce its own protocol, port, and whitelist rules.
*
* @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)
+ * @param redirectOptions - Configuration for redirect handling (maxRedirects, validation, 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
@@ -89,7 +106,10 @@ export interface RedirectOptions {
* const result = await fetchWithSecureRedirects(
* "https://example.com/webhook",
* { method: "POST", body: payload, headers, signal },
- * { maxRedirects: 10, skipValidation: false }
+ * {
+ * maxRedirects: 10,
+ * redirectValidation: { validateUrl: validateWebhookURL },
+ * }
* );
* console.log(`Final URL: ${result.finalUrl}`);
* console.log(`Redirects: ${result.redirectChain.length}`);
@@ -100,12 +120,7 @@ export async function fetchWithSecureRedirects(
options: RequestInit,
redirectOptions: RedirectOptions,
): Promise<RedirectResult> {
- const {
- maxRedirects,
- skipValidation = false,
- whitelist,
- additionalSensitiveHeaders = [],
- } = redirectOptions;
+ const { maxRedirects, additionalSensitiveHeaders = [] } = redirectOptions;
const sensitiveRedirectHeaders = new Set([
...SENSITIVE_REDIRECT_HEADERS,
...additionalSensitiveHeaders.map((headerName) => headerName.toLowerCase()),
@@ -196,10 +211,15 @@ export async function fetchWithSecureRedirects(
]);
}
- // Validate the redirect target URL before following
- if (!skipValidation) {
+ if (redirectOptions.skipValidation !== true) {
try {
- await validateWebhookURL(redirectUrl, whitelist);
+ // Redirect safety is domain-specific: webhooks allow HTTP(S) on 80/443,
+ // while image URLs require HTTPS. Keep the fetch helper generic and
+ // require callers to pass the validator that matches their flow.
+ await redirectOptions.redirectValidation.validateUrl(
+ redirectUrl,
+ redirectOptions.redirectValidation.whitelist,
+ );
} catch (error) {
logger.warn("Redirect validation failed", {
from: currentUrl,
diff --git a/packages/shared/src/server/outbound-url/index.ts b/packages/shared/src/server/outbound-url/index.ts
new file mode 100644
index 0000000000..0904352608
--- /dev/null
+++ b/packages/shared/src/server/outbound-url/index.ts
@@ -0,0 +1,2 @@
+export * from "./fetch";
+export * from "./validation";
diff --git a/packages/shared/src/server/outboundUrlValidation.ts b/packages/shared/src/server/outbound-url/validation.ts
similarity index 95%
rename from packages/shared/src/server/outboundUrlValidation.ts
rename to packages/shared/src/server/outbound-url/validation.ts
index be1763c1ed..7c6e33f1ca 100644
--- a/packages/shared/src/server/outboundUrlValidation.ts
+++ b/packages/shared/src/server/outbound-url/validation.ts
@@ -1,11 +1,11 @@
import dns from "node:dns/promises";
import { URL } from "node:url";
-import { logger } from "./logger";
+import { logger } from "../logger";
import {
isHostnameBlocked,
isIPBlocked,
isIPAddress,
-} from "./webhooks/ipBlocking";
+} from "../webhooks/ipBlocking";
export interface OutboundUrlValidationWhitelist {
hosts: string[];
@@ -13,6 +13,14 @@ export interface OutboundUrlValidationWhitelist {
ip_ranges: string[];
}
+export interface ValidateOutboundUrlHostOptions {
+ url: URL;
+ whitelist: OutboundUrlValidationWhitelist;
+ shouldThrowIfDnsResolutionFails: boolean;
+ logContext: string;
+ shouldSkipDnsCheckForLiteralIps: boolean;
+}
+
export async function resolveHost(hostname: string): Promise<string[]> {
// Returns every A + AAAA address.
const [v4, v6, lookup] = await Promise.allSettled([
@@ -73,13 +81,7 @@ export async function validateOutboundUrlHost({
shouldThrowIfDnsResolutionFails,
logContext,
shouldSkipDnsCheckForLiteralIps,
-}: {
- url: URL;
- whitelist: OutboundUrlValidationWhitelist;
- shouldThrowIfDnsResolutionFails: boolean;
- logContext: string;
- shouldSkipDnsCheckForLiteralIps: boolean;
-}): Promise<void> {
+}: ValidateOutboundUrlHostOptions): 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;
diff --git a/packages/shared/src/server/webhooks/validation.ts b/packages/shared/src/server/webhooks/validation.ts
index e73091f037..945a709112 100644
--- a/packages/shared/src/server/webhooks/validation.ts
+++ b/packages/shared/src/server/webhooks/validation.ts
@@ -4,7 +4,7 @@ import {
parseOutboundUrl,
resolveHost,
validateOutboundUrlHost,
-} from "../outboundUrlValidation";
+} from "../outbound-url";
export type WebhookValidationWhitelist = OutboundUrlValidationWhitelist;
export { resolveHost };
diff --git a/web/src/__tests__/server/unit/utilities.servertest.ts b/web/src/__tests__/server/unit/utilities.servertest.ts
new file mode 100644
index 0000000000..33895271ca
--- /dev/null
+++ b/web/src/__tests__/server/unit/utilities.servertest.ts
@@ -0,0 +1,119 @@
+const { validateOutboundUrlHostMock } = vi.hoisted(() => ({
+ validateOutboundUrlHostMock:
+ vi.fn<(options: { url: URL }) => Promise<void>>(),
+}));
+
+vi.mock("@langfuse/shared/src/server", async (importOriginal) => {
+ const actual = await importOriginal();
+
+ return {
+ ...(actual as object),
+ logger: {
+ debug: vi.fn(),
+ info: vi.fn(),
+ warn: vi.fn(),
+ error: vi.fn(),
+ },
+ validateOutboundUrlHost: validateOutboundUrlHostMock,
+ };
+});
+
+import {
+ isValidAndSecureUrl,
+ isValidImageUrl,
+} from "@/src/server/api/routers/utilities";
+
+const fetchMock = vi.fn<typeof fetch>();
+vi.stubGlobal("fetch", fetchMock);
+
+describe("utilities image URL validation", () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ validateOutboundUrlHostMock.mockImplementation(async ({ url }) => {
+ if (url.hostname === "169.254.169.254") {
+ throw new Error("Blocked IP address detected");
+ }
+ });
+ });
+
+ it("rejects image URLs that redirect to blocked IP literals", async () => {
+ fetchMock.mockResolvedValueOnce(
+ new Response(null, {
+ status: 302,
+ headers: { Location: "https://169.254.169.254/latest/meta-data/" },
+ }),
+ );
+
+ await expect(
+ isValidImageUrl("https://attacker.example.com/image.png"),
+ ).resolves.toBe(false);
+
+ expect(fetchMock).toHaveBeenCalledTimes(1);
+ expect(fetchMock.mock.calls[0]?.[1]).toMatchObject({
+ method: "HEAD",
+ redirect: "manual",
+ });
+ });
+
+ it("rejects pre-signed S3 URLs that redirect to blocked IP literals", async () => {
+ const s3Url =
+ "https://bucket.s3.amazonaws.com/image.png?X-Amz-Signature=signature";
+
+ fetchMock.mockResolvedValueOnce(
+ new Response(null, {
+ status: 302,
+ headers: { Location: "https://169.254.169.254/latest/meta-data/" },
+ }),
+ );
+
+ await expect(isValidImageUrl(s3Url)).resolves.toBe(false);
+
+ expect(fetchMock).toHaveBeenCalledTimes(1);
+ expect(fetchMock.mock.calls[0]?.[1]).toMatchObject({
+ method: "HEAD",
+ redirect: "manual",
+ });
+ });
+
+ it("follows redirects after validating each target", async () => {
+ fetchMock
+ .mockResolvedValueOnce(
+ new Response(null, {
+ status: 302,
+ headers: { Location: "https://images.example.com/final.png" },
+ }),
+ )
+ .mockResolvedValueOnce(
+ new Response(null, {
+ status: 200,
+ headers: { "content-type": "image/png" },
+ }),
+ );
+
+ await expect(
+ isValidImageUrl("https://attacker.example.com/image.png"),
+ ).resolves.toBe(true);
+
+ expect(fetchMock).toHaveBeenCalledTimes(2);
+ expect(validateOutboundUrlHostMock).toHaveBeenCalledWith(
+ expect.objectContaining({
+ url: expect.objectContaining({ hostname: "attacker.example.com" }),
+ }),
+ );
+ expect(validateOutboundUrlHostMock).toHaveBeenCalledWith(
+ expect.objectContaining({
+ url: expect.objectContaining({ hostname: "images.example.com" }),
+ }),
+ );
+ });
+
+ it("rejects URLs that fail shared outbound host validation", async () => {
+ validateOutboundUrlHostMock.mockRejectedValueOnce(
+ new Error("Blocked IP address detected"),
+ );
+
+ await expect(
+ isValidAndSecureUrl("https://attacker.example.com/image.png"),
+ ).resolves.toBe(false);
+ });
+});
diff --git a/web/src/server/api/routers/utilities.ts b/web/src/server/api/routers/utilities.ts
index d709cb7ba6..cee796854c 100644
--- a/web/src/server/api/routers/utilities.ts
+++ b/web/src/server/api/routers/utilities.ts
@@ -3,88 +3,36 @@ import {
authenticatedProcedure,
} from "@/src/server/api/trpc";
import { z } from "zod";
-import { promises as dns } from "dns";
-import { Address4, Address6 } from "ip-address";
-import { logger } from "@langfuse/shared/src/server";
-
-const IP_4_LOOPBACK_SUBNET = "127.0.0.0/8";
-const IP_4_LINK_LOCAL_SUBNET = "169.254.0.0/16";
-const IP_4_PRIVATE_A_SUBNET = "10.0.0.0/8";
-const IP_4_PRIVATE_B_SUBNET = "172.16.0.0/12";
-const IP_4_PRIVATE_C_SUBNET = "192.168.0.0/16";
-
-/**
- * Check if the ipAddress is a private IP address
- * This function is used to protect against Server Side Request Forgery (SSRF) attacks.
- * SSRF attacks can cause the server to make requests to internal resources that should not be accessible.
- * By checking if a ipAddress resolves to a private IP address, we can prevent such attacks.
- *
- * @param ipAddress - The ipAddress to check
- * @returns True if the ipAddress is a private IP address, false otherwise
- */
-const isPrivateIp = (ipAddress: string): boolean => {
- try {
- if (Address6.isValid(ipAddress)) {
- const address = new Address6(ipAddress);
- const isValidAddress6 = address.isLinkLocal() || address.isLoopback();
- if (isValidAddress6) return true;
- }
- if (Address4.isValid(ipAddress)) {
- const address = new Address4(ipAddress);
- const isValidAddress4 = [
- IP_4_LOOPBACK_SUBNET,
- IP_4_LINK_LOCAL_SUBNET,
- IP_4_PRIVATE_A_SUBNET,
- IP_4_PRIVATE_B_SUBNET,
- IP_4_PRIVATE_C_SUBNET,
- ].some((subnet) => address.isInSubnet(new Address4(subnet)));
- if (isValidAddress4) return true;
- }
- return false;
- } catch (error) {
- logger.info("IP parsing error:", error);
- return false;
- }
-};
-
-const resolveHostname = async (
- hostname: string,
-): Promise<{ addresses4: string[]; addresses6: string[] }> => {
- let addresses4: string[] = [];
- let addresses6: string[] = [];
-
- try {
- addresses4 = await dns.resolve4(hostname);
- } catch (error) {
- logger.info("IPv4 DNS resolution error:", error);
- }
-
- try {
- addresses6 = await dns.resolve6(hostname);
- } catch (error) {
- logger.info("IPv6 DNS resolution error:", error);
- }
-
- return { addresses4, addresses6 };
-};
-
-const isValidAndSecureUrl = async (urlString: string): Promise<boolean> => {
+import {
+ fetchWithSecureRedirects,
+ logger,
+ parseOutboundUrl,
+ validateOutboundUrlHost,
+ type ValidateOutboundUrlHostOptions,
+} from "@langfuse/shared/src/server";
+
+const MAX_IMAGE_URL_REDIRECTS = 5;
+const IMAGE_URL_VALIDATION_OPTIONS = {
+ whitelist: { hosts: [], ips: [], ip_ranges: [] },
+ shouldThrowIfDnsResolutionFails: true,
+ logContext: "Image URL",
+ shouldSkipDnsCheckForLiteralIps: true,
+} satisfies Omit<ValidateOutboundUrlHostOptions, "url">;
+
+export const isValidAndSecureUrl = async (
+ urlString: string,
+): Promise<boolean> => {
try {
- const url = new URL(urlString);
+ const url = parseOutboundUrl(urlString);
if (url.protocol !== "https:") {
return false;
}
- const hostname = new URL(url).hostname;
- const ipAddresses = await resolveHostname(hostname);
-
- // Consider unresolvable or private hostnames as invalid/unsafe
- return (
- (ipAddresses.addresses4.length === 0 ||
- ipAddresses.addresses4.every((ip) => !isPrivateIp(ip))) &&
- (ipAddresses.addresses6.length === 0 ||
- ipAddresses.addresses6.every((ip) => !isPrivateIp(ip))) &&
- (ipAddresses.addresses4.length > 0 || ipAddresses.addresses6.length > 0)
- );
+
+ await validateOutboundUrlHost({
+ url,
+ ...IMAGE_URL_VALIDATION_OPTIONS,
+ });
+ return true;
} catch (error) {
logger.info("Invalid URL:", error);
return false;
@@ -111,17 +59,47 @@ const s3UrlSchema = z.object({
}),
});
+type PresignedS3UrlValidationResult = "not-s3-url" | "valid" | "invalid";
+
const isImageContent = (response: Response): boolean => {
const contentType = response.headers.get("content-type");
return !!contentType && contentType.startsWith("image/");
};
+const fetchImageUrlWithSecureRedirects = async (
+ url: string,
+ options: RequestInit,
+): Promise<Response> => {
+ // fetchWithSecureRedirects validates redirect targets. Validate the initial
+ // image URL here so the first network request cannot target a blocked host.
+ if (!(await isValidAndSecureUrl(url))) {
+ throw new Error("Image URL failed security validation");
+ }
+
+ const { response } = await fetchWithSecureRedirects(url, options, {
+ maxRedirects: MAX_IMAGE_URL_REDIRECTS,
+ redirectValidation: {
+ validateUrl: async (redirectUrl) => {
+ if (!(await isValidAndSecureUrl(redirectUrl))) {
+ throw new Error(
+ "Image URL redirect target failed security validation",
+ );
+ }
+ },
+ },
+ });
+
+ return response;
+};
+
/**
* Validate if a URL is a valid and live pre-signed S3 URL
* @param url The pre-signed S3 URL to validate
* @returns True if the URL is valid and reachable, false otherwise
*/
-const isValidPresignedS3Url = async (url: string): Promise<boolean> => {
+const validatePresignedS3Url = async (
+ url: string,
+): Promise<PresignedS3UrlValidationResult> => {
try {
const parsedUrl = new URL(url);
@@ -134,18 +112,18 @@ const isValidPresignedS3Url = async (url: string): Promise<boolean> => {
if (!result.success) {
logger.info("Invalid pre-signed S3 URL:", result.error.message);
- return false;
+ return "not-s3-url";
}
// Perform a HEAD request to check reachability
- const response = await fetch(url, {
+ const response = await fetchImageUrlWithSecureRedirects(url, {
method: "HEAD",
signal: AbortSignal.timeout(5000),
});
// Status 200 indicates the URL is valid
if (response.ok && isImageContent(response)) {
- return true;
+ return "valid";
}
// Attempt a GET request, as most pre-signed URLs are restricted to GET requests only
@@ -154,16 +132,18 @@ const isValidPresignedS3Url = async (url: string): Promise<boolean> => {
"HEAD request returned 403, attempting GET for validation...",
);
- const getResponse = await fetch(url, {
+ const getResponse = await fetchImageUrlWithSecureRedirects(url, {
method: "GET",
signal: AbortSignal.timeout(5000),
headers: { Range: "bytes=0-1" }, // Fetch only the first byte, expected server response for valid pre-signed URLs is 206 Partial Content
});
- return getResponse.ok && isImageContent(getResponse); // 200 or 206 Partial Content indicates success
+ return getResponse.ok && isImageContent(getResponse)
+ ? "valid"
+ : "invalid"; // 200 or 206 Partial Content indicates success
}
- return false;
+ return "invalid";
} catch (error) {
if (error instanceof z.ZodError) {
logger.info("URL Validation Error:", error.message);
@@ -172,18 +152,25 @@ const isValidPresignedS3Url = async (url: string): Promise<boolean> => {
} else {
logger.info("Unknown error:", error);
}
- return false;
+ return "invalid";
}
};
-const isValidImageUrl = async (url: string): Promise<boolean> => {
+export const isValidImageUrl = async (url: string): Promise<boolean> => {
try {
// Pre-signed URLs (AWS S3) often have restricted access methods. Some only allow GET requests, others only HEAD. We need to try both.
- if (await isValidPresignedS3Url(url)) {
+ const presignedS3UrlValidationResult = await validatePresignedS3Url(url);
+ if (presignedS3UrlValidationResult === "valid") {
return true;
}
+ // If the URL looks like a pre-signed S3 URL but validation failed, do not
+ // retry it through the generic image path; that would repeat the same
+ // secure fetch and DNS checks for the same URL.
+ if (presignedS3UrlValidationResult === "invalid") {
+ return false;
+ }
- const response = await fetch(url, {
+ const response = await fetchImageUrlWithSecureRedirects(url, {
method: "HEAD",
signal: AbortSignal.timeout(5000),
});
@@ -203,11 +190,6 @@ export const utilsRouter = createTRPCRouter({
validateImgUrl: authenticatedProcedure
.input(z.string().max(2048))
.query(async ({ input: url }) => {
- const isValidUrl = await isValidAndSecureUrl(url);
- if (!isValidUrl) {
- return { isValid: false };
- }
-
const isValidImg = await isValidImageUrl(url);
return { isValid: isValidImg };
}),
diff --git a/worker/src/__tests__/webhook-redirect-headers.test.ts b/worker/src/__tests__/webhook-redirect-headers.test.ts
index 9528749ad6..2ad660ba32 100644
--- a/worker/src/__tests__/webhook-redirect-headers.test.ts
+++ b/worker/src/__tests__/webhook-redirect-headers.test.ts
@@ -1,6 +1,9 @@
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";
+import {
+ fetchWithSecureRedirects,
+ type OutboundUrlValidationWhitelist,
+} from "../../../packages/shared/src/server/outbound-url";
const fetchMock = vi.fn<typeof fetch>();
vi.stubGlobal("fetch", fetchMock);
@@ -143,4 +146,47 @@ describe("fetchWithSecureRedirects header handling", () => {
expect(finalHeaders.get("x-custom-header")).toBe("keep-me");
expect(warnSpy).not.toHaveBeenCalled();
});
+
+ it("should use custom redirect validation when provided", async () => {
+ const validateRedirectUrl =
+ vi.fn<
+ (
+ url: string,
+ whitelist?: OutboundUrlValidationWhitelist,
+ ) => Promise<void>
+ >();
+ validateRedirectUrl.mockResolvedValue(undefined);
+ const whitelist = {
+ hosts: ["other.example.com"],
+ ips: [],
+ ip_ranges: [],
+ };
+
+ 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" },
+ {
+ maxRedirects: 1,
+ redirectValidation: {
+ validateUrl: validateRedirectUrl,
+ whitelist,
+ },
+ },
+ );
+
+ expect(validateRedirectUrl).toHaveBeenCalledWith(
+ "https://other.example.com/final",
+ whitelist,
+ );
+ expect(fetchMock).toHaveBeenCalledTimes(2);
+ });
});
diff --git a/worker/src/__tests__/webhook-redirect.test.ts b/worker/src/__tests__/webhook-redirect.test.ts
index 2656b2a3f1..0266baa6c4 100644
--- a/worker/src/__tests__/webhook-redirect.test.ts
+++ b/worker/src/__tests__/webhook-redirect.test.ts
@@ -23,7 +23,7 @@ import { randomUUID } from "crypto";
* - 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/outbound-url/fetch.ts (fetchWithSecureRedirects)
* - packages/shared/src/server/webhooks/validation.ts (validateWebhookURL)
*/
diff --git a/worker/src/queues/webhooks.ts b/worker/src/queues/webhooks.ts
index d722c48824..592a5c5f8d 100644
--- a/worker/src/queues/webhooks.ts
+++ b/worker/src/queues/webhooks.ts
@@ -146,11 +146,28 @@ async function executeHttpAction({
}, env.LANGFUSE_WEBHOOK_TIMEOUT_MS);
try {
+ const whitelist = whitelistFromEnv();
+
// Skip validation when flag is set (for tests with MSW mocking)
if (!skipValidation) {
- await validateWebhookURL(url);
+ await validateWebhookURL(url, whitelist);
}
+ const redirectOptions = skipValidation
+ ? {
+ maxRedirects: env.LANGFUSE_WEBHOOK_MAX_REDIRECTS,
+ skipValidation: true as const,
+ additionalSensitiveHeaders,
+ }
+ : {
+ maxRedirects: env.LANGFUSE_WEBHOOK_MAX_REDIRECTS,
+ redirectValidation: {
+ validateUrl: validateWebhookURL,
+ whitelist,
+ },
+ additionalSensitiveHeaders,
+ };
+
const redirectResult = await fetchWithSecureRedirects(
url,
{
@@ -159,12 +176,7 @@ async function executeHttpAction({
headers,
signal: abortController.signal,
},
- {
- maxRedirects: env.LANGFUSE_WEBHOOK_MAX_REDIRECTS,
- skipValidation,
- whitelist: whitelistFromEnv(),
- additionalSensitiveHeaders,
- },
+ redirectOptions,
);
const res = redirectResult.response;