🪢 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(blob-storage): harden endpoint connection validation (#13694)
Tobias Wochingerd56791bd9165
diff --git a/.env.dev.example b/.env.dev.exampleindex 239001ad2a..94dc024559 100644--- a/.env.dev.example+++ b/.env.dev.example@@ -154,6 +154,10 @@ LANGFUSE_AI_FEATURES_PROJECT_ID=7a88fb47-b4e2-43b8-a06c-a5ce950dc53a# LANGFUSE_LLM_CONNECTION_WHITELISTED_HOST=localhost# LANGFUSE_LLM_CONNECTION_WHITELISTED_IPS=127.0.0.1,::1# LANGFUSE_LLM_CONNECTION_WHITELISTED_IP_SEGMENTS=127.0.0.0/8+# Self-hosted only: allow internal hosts/IPs for user-configured blob storage endpoints.+# LANGFUSE_BLOB_STORAGE_ENDPOINT_WHITELISTED_HOST=localhost+# LANGFUSE_BLOB_STORAGE_ENDPOINT_WHITELISTED_IPS=127.0.0.1,::1+# LANGFUSE_BLOB_STORAGE_ENDPOINT_WHITELISTED_IP_SEGMENTS=127.0.0.0/8# Langfuse AI Bedrock credentialsAWS_ACCESS_KEY_ID="A123456789"diff --git a/.env.prod.example b/.env.prod.exampleindex 6a8f94215e..50e7518894 100644--- a/.env.prod.example+++ b/.env.prod.example@@ -312,6 +312,10 @@ LANGFUSE_ENABLE_BLOB_STORAGE_FILE_LOG=true# LANGFUSE_LLM_CONNECTION_WHITELISTED_HOST=# LANGFUSE_LLM_CONNECTION_WHITELISTED_IPS=# LANGFUSE_LLM_CONNECTION_WHITELISTED_IP_SEGMENTS=+# Self-hosted only: allow internal hosts/IPs for user-configured blob storage endpoints.+# LANGFUSE_BLOB_STORAGE_ENDPOINT_WHITELISTED_HOST=+# LANGFUSE_BLOB_STORAGE_ENDPOINT_WHITELISTED_IPS=+# LANGFUSE_BLOB_STORAGE_ENDPOINT_WHITELISTED_IP_SEGMENTS=# LANGFUSE_CACHE_MODEL_MATCH_ENABLED=# LANGFUSE_CACHE_MODEL_MATCH_TTL_SECONDS=diff --git a/packages/shared/package.json b/packages/shared/package.jsonindex 61934914a3..d7f48d33d0 100644--- a/packages/shared/package.json+++ b/packages/shared/package.json@@ -104,6 +104,7 @@"@react-email/render": "^1.2.1","@slack/oauth": "3.0.5","@slack/web-api": "^7.15.0",+ "@smithy/node-http-handler": "4.5.1","@types/bcryptjs": "^2.4.6","ajv": "^8.18.0","ajv-formats": "^3.0.1",diff --git a/packages/shared/src/env.ts b/packages/shared/src/env.tsindex 96ea12fee6..729f03f4fb 100644--- a/packages/shared/src/env.ts+++ b/packages/shared/src/env.ts@@ -333,6 +333,24 @@ const EnvSchema = z.object({.transform((s) =>s ? s.split(",").map((s) => s.toLowerCase().trim()) : [],),+ LANGFUSE_BLOB_STORAGE_ENDPOINT_WHITELISTED_IPS: z+ .string()+ .optional()+ .transform((s) =>+ s ? s.split(",").map((s) => s.toLowerCase().trim()) : [],+ ),+ LANGFUSE_BLOB_STORAGE_ENDPOINT_WHITELISTED_IP_SEGMENTS: z+ .string()+ .optional()+ .transform((s) =>+ s ? s.split(",").map((s) => s.toLowerCase().trim()) : [],+ ),+ LANGFUSE_BLOB_STORAGE_ENDPOINT_WHITELISTED_HOST: z+ .string()+ .optional()+ .transform((s) =>+ s ? s.split(",").map((s) => s.toLowerCase().trim()) : [],+ ),SLACK_CLIENT_ID: z.string().optional(),SLACK_CLIENT_SECRET: z.string().optional(),SLACK_STATE_SECRET: z.string().optional(),diff --git a/packages/shared/src/server/index.ts b/packages/shared/src/server/index.tsindex 1583d1edb2..409b0d3f5e 100644--- a/packages/shared/src/server/index.ts+++ b/packages/shared/src/server/index.ts@@ -34,6 +34,7 @@ export * from "./llm/compileChatMessages";export * from "./llm/testModelCall";export * from "./llm/baseUrlValidation";export * from "./outbound-url";+export * from "./services/blobStorageEndpointValidation";export * from "./llm/getInternalTracingHandler";export * from "./utils/DatabaseReadStream";export * from "./utils/transforms";diff --git a/packages/shared/src/server/outbound-url/connection.ts b/packages/shared/src/server/outbound-url/connection.tsindex 63d2897c9b..68af4620ff 100644--- a/packages/shared/src/server/outbound-url/connection.ts+++ b/packages/shared/src/server/outbound-url/connection.ts@@ -1,5 +1,8 @@import dns from "node:dns";-import { Agent } from "undici";+import { Agent as HttpAgent } from "node:http";+import { Agent as HttpsAgent } from "node:https";+import type { LookupFunction } from "node:net";+import { Agent as UndiciAgent } from "undici";import type { OutboundUrlValidationWhitelist } from "./validation";import { validateOutboundResolvedIp } from "./validation";@@ -16,27 +19,16 @@ const DEFAULT_OUTBOUND_URL_VALIDATION_WHITELIST: OutboundUrlValidationWhitelistip_ranges: [],};-type DnsLookupCallback = (- err: NodeJS.ErrnoException | null,- address: string | dns.LookupAddress[],- family?: number,-) => void;-type DnsLookup = (- hostname: string,- options: dns.LookupOptions,- callback: DnsLookupCallback,-) => void;-export interface OutboundUrlConnectionValidationOptions {whitelist?: OutboundUrlValidationWhitelist;logContext?: string;}-type RequestInitWithUndiciDispatcher = RequestInit & {- dispatcher?: Agent;-};--const secureOutboundDispatchersByPolicy = new Map<string, Agent>();+const secureOutboundDispatchersByPolicy = new Map<string, UndiciAgent>();+const secureOutboundHttpAgentsByPolicy = new Map<+ string,+ { httpAgent: HttpAgent; httpsAgent: HttpsAgent }+>();export function addSecureOutboundConnectionValidation(options: RequestInit,@@ -45,13 +37,13 @@ export function addSecureOutboundConnectionValidation(return {...options,dispatcher: getSecureOutboundDispatcher(validationOptions),- } as RequestInitWithUndiciDispatcher;+ } as RequestInit & { dispatcher: UndiciAgent };}-function createSecureOutboundLookup(+export function createSecureOutboundLookup(validationOptions: OutboundUrlConnectionValidationOptions,- lookup: typeof dns.lookup = dns.lookup,-): DnsLookup {+ lookup: LookupFunction = dns.lookup,+): LookupFunction {return (hostname, options, callback) => {lookup(hostname, options, (err, address, family) => {if (err) {@@ -75,33 +67,77 @@ function createSecureOutboundLookup(};}+export function getSecureOutboundHttpAgents(+ validationOptions: OutboundUrlConnectionValidationOptions,+ options: { maxSockets?: number } = {},+) {+ const policyKey = JSON.stringify({+ validation: getConnectionValidationPolicyKey(validationOptions),+ maxSockets: options.maxSockets,+ });+ return getOrCreatePolicyResource(+ secureOutboundHttpAgentsByPolicy,+ policyKey,+ "HTTP agent",+ () => {+ const lookup = createSecureOutboundLookup(validationOptions);+ return {+ httpAgent: new HttpAgent({+ keepAlive: true,+ lookup,+ maxSockets: options.maxSockets,+ }),+ httpsAgent: new HttpsAgent({+ keepAlive: true,+ lookup,+ maxSockets: options.maxSockets,+ }),+ };+ },+ );+}+function getSecureOutboundDispatcher(validationOptions: OutboundUrlConnectionValidationOptions,-): Agent {+): UndiciAgent {const policyKey = getConnectionValidationPolicyKey(validationOptions);- const existingDispatcher = secureOutboundDispatchersByPolicy.get(policyKey);- if (existingDispatcher) return existingDispatcher;-- if (secureOutboundDispatchersByPolicy.size >= OUTBOUND_AGENT_POLICY_LIMIT) {- // Do not evict existing Agents: they own socket pools and may still have- // in-flight streaming responses. Evicting without closing leaks resources,- // while closing/destroying can break unrelated requests. Exceeding this- // small policy count is unexpected and should fail closed.+ return getOrCreatePolicyResource(+ secureOutboundDispatchersByPolicy,+ policyKey,+ "connection",+ () =>+ new UndiciAgent({+ connect: {+ // This lookup runs at socket connection time, so DNS rebinding between+ // the earlier URL validation and the actual HTTP connection is blocked.+ lookup: createSecureOutboundLookup(validationOptions),+ },+ }),+ );+}++function getOrCreatePolicyResource<T>(+ cache: Map<string, T>,+ policyKey: string,+ resourceName: string,+ createResource: () => T,+): T {+ const existingResource = cache.get(policyKey);+ if (existingResource) return existingResource;++ if (cache.size >= OUTBOUND_AGENT_POLICY_LIMIT) {+ // Do not evict existing resources: Agents/Dispatchers own socket pools and+ // may still have in-flight streaming responses. Evicting without closing+ // leaks resources, while closing/destroying can break unrelated requests.+ // Exceeding this small policy count is unexpected and should fail closed.throw new Error(- `Maximum secure outbound connection policy count (${OUTBOUND_AGENT_POLICY_LIMIT}) exceeded`,+ `Maximum secure outbound ${resourceName} policy count (${OUTBOUND_AGENT_POLICY_LIMIT}) exceeded`,);}- const dispatcher = new Agent({- connect: {- // This lookup runs at socket connection time, so DNS rebinding between- // the earlier URL validation and the actual HTTP connection is blocked.- lookup: createSecureOutboundLookup(validationOptions),- },- });-- secureOutboundDispatchersByPolicy.set(policyKey, dispatcher);- return dispatcher;+ const resource = createResource();+ cache.set(policyKey, resource);+ return resource;}function validateConnectionTimeLookupResult(diff --git a/packages/shared/src/server/outbound-url/index.ts b/packages/shared/src/server/outbound-url/index.tsindex 0904352608..dcd4ebea96 100644--- a/packages/shared/src/server/outbound-url/index.ts+++ b/packages/shared/src/server/outbound-url/index.ts@@ -1,2 +1,3 @@+export * from "./connection";export * from "./fetch";export * from "./validation";diff --git a/packages/shared/src/server/services/StorageService.ts b/packages/shared/src/server/services/StorageService.tsindex f6783a4f44..9edd175b6f 100644--- a/packages/shared/src/server/services/StorageService.ts+++ b/packages/shared/src/server/services/StorageService.ts@@ -9,11 +9,14 @@ import {} from "@aws-sdk/client-s3";import { Upload } from "@aws-sdk/lib-storage";import { getSignedUrl } from "@aws-sdk/s3-request-presigner";+import { NodeHttpHandler } from "@smithy/node-http-handler";import {BlobSASPermissions,BlobServiceClient,ContainerClient,StorageSharedKeyCredential,+ newPipeline,+ type RequestPolicyFactory,} from "@azure/storage-blob";import { Storage, Bucket, GetSignedUrlConfig } from "@google-cloud/storage";import { logger } from "../logger";@@ -26,6 +29,10 @@ import * as objectstorage from "oci-objectstorage";import * as common from "oci-common";import { UploadManager as OciUploadManager } from "oci-objectstorage";import { URL } from "node:url";+import {+ getSecureOutboundHttpAgents,+ type OutboundUrlConnectionValidationOptions,+} from "../outbound-url";export interface S3SseConfig {serverSideEncryption?: string;@@ -85,6 +92,64 @@ function handleStorageError(err: unknown, operation: string): never {throw new Error(`Failed to ${operation}`, { cause: err });}+function createS3RequestHandler(+ connectionValidation?: OutboundUrlConnectionValidationOptions,+): NodeHttpHandler {+ const maxSockets = env.LANGFUSE_S3_CONCURRENT_WRITES;++ if (!connectionValidation) {+ return new NodeHttpHandler({+ httpsAgent: { maxSockets },+ });+ }++ const { httpAgent, httpsAgent } = getSecureOutboundHttpAgents(+ connectionValidation,+ { maxSockets },+ );++ return new NodeHttpHandler({+ httpAgent,+ httpsAgent,+ });+}++function createAzureBlobPipeline(+ sharedKeyCredential: StorageSharedKeyCredential,+ connectionValidation?: OutboundUrlConnectionValidationOptions,+): ReturnType<typeof newPipeline> {+ const pipeline = newPipeline(sharedKeyCredential);++ if (connectionValidation) {+ pipeline.factories.push(+ createSecureAzureBlobRequestPolicyFactory(connectionValidation),+ );+ }++ return pipeline;+}++function createSecureAzureBlobRequestPolicyFactory(+ connectionValidation: OutboundUrlConnectionValidationOptions,+): RequestPolicyFactory {+ const { httpAgent, httpsAgent } = getSecureOutboundHttpAgents(+ connectionValidation,+ { maxSockets: env.LANGFUSE_S3_CONCURRENT_WRITES },+ );++ return {+ create(nextPolicy) {+ return {+ sendRequest(request) {+ request.agent =+ new URL(request.url).protocol === "http:" ? httpAgent : httpsAgent;+ return nextPolicy.sendRequest(request);+ },+ };+ },+ };+}+export interface StorageService {uploadFile(params: UploadFile): Promise<void>;@@ -136,6 +201,7 @@ export class StorageServiceFactory {* @param params.googleCloudCredentials - Google Cloud Storage credentials JSON string or path to credentials file* @param params.awsSse - Server-side encryption method (e.g., "aws:kms")* @param params.awsSseKmsKeyId - SSE KMS Key ID when using KMS encryption+ * @param params.connectionValidation - Optional connection-time DNS/IP validation for user-controlled endpoints.*/public static getInstance(params: {accessKeyId: string | undefined;@@ -151,6 +217,7 @@ export class StorageServiceFactory {googleCloudCredentials?: string;awsSse: string | undefined;awsSseKmsKeyId: string | undefined;+ connectionValidation?: OutboundUrlConnectionValidationOptions;}): StorageService {if (params.useAzureBlob !== undefined@@ -164,7 +231,11 @@ export class StorageServiceFactory {? params.useGoogleCloudStorage: env.LANGFUSE_USE_GOOGLE_CLOUD_STORAGE === "true") {- // Use provided credentials or fall back to environment variable+ // connectionValidation is intentionally not applied here: GCS is selected+ // by deployment env for Langfuse-owned storage, not by user-configured+ // blob storage integrations. Those callers force useGoogleCloudStorage to+ // false. Add SDK-specific connection-time validation before exposing GCS+ // as a user-configurable blob export endpoint.const googleParams = {...params,googleCloudCredentials:@@ -178,6 +249,8 @@ export class StorageServiceFactory {? params.useOCIObjectStorage: env.LANGFUSE_USE_OCI_NATIVE_OBJECT_STORAGE === "true") {+ // Same as GCS above: OCI is currently deployment-configured internal+ // storage only, not a user-controlled blob integration endpoint.return new OCIObjectStorageService(params);}return new S3StorageService(params);@@ -198,6 +271,7 @@ class AzureBlobStorageService implements StorageService {externalEndpoint?: string | undefined;region: string | undefined;forcePathStyle: boolean;+ connectionValidation?: OutboundUrlConnectionValidationOptions;}) {const { accessKeyId, secretAccessKey, endpoint, externalEndpoint } = params;if (!accessKeyId || !secretAccessKey || !endpoint) {@@ -211,10 +285,12 @@ class AzureBlobStorageService implements StorageService {accessKeyId,secretAccessKey,);- const blobServiceClient = new BlobServiceClient(- endpoint,+ const pipeline = createAzureBlobPipeline(sharedKeyCredential,+ params.connectionValidation,);++ const blobServiceClient = new BlobServiceClient(endpoint, pipeline);this.container = params.bucketName;this.client = blobServiceClient.getContainerClient(this.container);}@@ -492,6 +568,7 @@ class S3StorageService implements StorageService {forcePathStyle: boolean;awsSse: string | undefined;awsSseKmsKeyId: string | undefined;+ connectionValidation?: OutboundUrlConnectionValidationOptions;}) {// Use accessKeyId and secretAccessKey if provided or fallback to default credentialsconst { accessKeyId, secretAccessKey } = params;@@ -503,6 +580,8 @@ class S3StorageService implements StorageService {}: undefined;+ const requestHandler = createS3RequestHandler(params.connectionValidation);+// Create the main client for S3 operations using the internal endpointthis.client = new S3Client({credentials,@@ -513,11 +592,7 @@ class S3StorageService implements StorageService {// composite CRC32 header, which GCS's S3-compat layer rejects with 412.requestChecksumCalculation: "WHEN_REQUIRED",responseChecksumValidation: "WHEN_REQUIRED",- requestHandler: {- httpsAgent: {- maxSockets: env.LANGFUSE_S3_CONCURRENT_WRITES,- },- },+ requestHandler,});// Create a separate client for generating presigned URLs@@ -531,11 +606,7 @@ class S3StorageService implements StorageService {forcePathStyle: params.forcePathStyle,requestChecksumCalculation: "WHEN_REQUIRED",responseChecksumValidation: "WHEN_REQUIRED",- requestHandler: {- httpsAgent: {- maxSockets: env.LANGFUSE_S3_CONCURRENT_WRITES,- },- },+ requestHandler,}): this.client;diff --git a/packages/shared/src/server/services/blobStorageEndpointValidation.ts b/packages/shared/src/server/services/blobStorageEndpointValidation.tsnew file mode 100644index 0000000000..48746e750b--- /dev/null+++ b/packages/shared/src/server/services/blobStorageEndpointValidation.ts@@ -0,0 +1,112 @@+import { env } from "../../env";+import {+ type OutboundUrlConnectionValidationOptions,+ type OutboundUrlValidationWhitelist,+ parseOutboundUrl,+ validateOutboundUrlHost,+} from "../outbound-url";++export const BLOB_STORAGE_ENDPOINT_VALIDATION_LOG_CONTEXT =+ "Blob storage endpoint";++const STRICT_BLOB_STORAGE_ENDPOINT_WHITELIST: OutboundUrlValidationWhitelist = {+ hosts: [],+ ips: [],+ ip_ranges: [],+};++export function blobStorageEndpointWhitelistFromEnv(): OutboundUrlValidationWhitelist {+ if (env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION) {+ return STRICT_BLOB_STORAGE_ENDPOINT_WHITELIST;+ }++ return {+ hosts: env.LANGFUSE_BLOB_STORAGE_ENDPOINT_WHITELISTED_HOST || [],+ ips: env.LANGFUSE_BLOB_STORAGE_ENDPOINT_WHITELISTED_IPS || [],+ ip_ranges: env.LANGFUSE_BLOB_STORAGE_ENDPOINT_WHITELISTED_IP_SEGMENTS || [],+ };+}++export async function validateBlobStorageEndpoint(+ endpoint: string,+ whitelist: OutboundUrlValidationWhitelist = blobStorageEndpointWhitelistFromEnv(),+): Promise<void> {+ const effectiveWhitelist = getEffectiveWhitelist(whitelist);++ if (!isBlobStorageEndpointValidationEnabled(effectiveWhitelist)) {+ return;+ }++ const url = parseOutboundUrl(endpoint);++ if (!["https:", "http:"].includes(url.protocol)) {+ throw new Error("Only HTTP and HTTPS protocols are allowed");+ }++ if (env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION && url.protocol !== "https:") {+ throw new Error(+ "Only HTTPS blob storage endpoints are allowed on Langfuse Cloud",+ );+ }++ try {+ await validateOutboundUrlHost({+ url,+ whitelist: effectiveWhitelist,+ logContext: BLOB_STORAGE_ENDPOINT_VALIDATION_LOG_CONTEXT,+ // Public IP literals are valid storage endpoints after blocklist checks and+ // should not require a reverse DNS path to exist at save time.+ shouldSkipDnsCheckForLiteralIps: true,+ });+ } catch (error) {+ const message =+ error instanceof Error ? error.message : "Validation failed";+ throw new Error(`${message}${getSelfHostedWhitelistGuidance()}`);+ }+}++export function blobStorageEndpointConnectionValidationOptions(+ whitelist: OutboundUrlValidationWhitelist = blobStorageEndpointWhitelistFromEnv(),+): OutboundUrlConnectionValidationOptions | undefined {+ const effectiveWhitelist = getEffectiveWhitelist(whitelist);++ if (!isBlobStorageEndpointValidationEnabled(effectiveWhitelist)) {+ return undefined;+ }++ return {+ whitelist: effectiveWhitelist,+ logContext: BLOB_STORAGE_ENDPOINT_VALIDATION_LOG_CONTEXT,+ };+}++function getEffectiveWhitelist(+ whitelist: OutboundUrlValidationWhitelist,+): OutboundUrlValidationWhitelist {+ return env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION+ ? STRICT_BLOB_STORAGE_ENDPOINT_WHITELIST+ : whitelist;+}++function isBlobStorageEndpointValidationEnabled(+ whitelist: OutboundUrlValidationWhitelist,+): boolean {+ if (env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION) return true;++ // Compatibility rollout: self-hosted deployments may already point blob+ // exports at private MinIO/Azure endpoints. Keep the stricter SSRF/rebind+ // validation opt-in until operators configure the dedicated allowlist envs.+ // TODO(next major): enforce blob storage endpoint validation for self-hosted+ // deployments even when no allowlist env is configured.+ return (+ whitelist.hosts.length > 0 ||+ whitelist.ips.length > 0 ||+ whitelist.ip_ranges.length > 0+ );+}++function getSelfHostedWhitelistGuidance(): string {+ if (env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION) return "";++ return " For self-hosted deployments with internal blob storage endpoints, configure LANGFUSE_BLOB_STORAGE_ENDPOINT_WHITELISTED_HOST, LANGFUSE_BLOB_STORAGE_ENDPOINT_WHITELISTED_IPS, or LANGFUSE_BLOB_STORAGE_ENDPOINT_WHITELISTED_IP_SEGMENTS.";+}diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex 45f2a8a148..1976ae7c0c 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -221,6 +221,9 @@ importers:'@slack/web-api':specifier: ^7.15.0version: 7.15.1+ '@smithy/node-http-handler':+ specifier: 4.5.1+ version: 4.5.1'@types/bcryptjs':specifier: ^2.4.6version: 2.4.6diff --git a/web/src/__tests__/server/blob-storage-integration-api.servertest.ts b/web/src/__tests__/server/blob-storage-integration-api.servertest.tsindex 24da5fb575..b3ccf6f97c 100644--- a/web/src/__tests__/server/blob-storage-integration-api.servertest.ts+++ b/web/src/__tests__/server/blob-storage-integration-api.servertest.ts@@ -440,7 +440,7 @@ describe("Blob Storage Integrations API", () => {...validBlobStorageConfig,projectId: testProject1Id,type: "AZURE_BLOB_STORAGE" as const,- endpoint: "https://myaccount.blob.core.windows.net",+ endpoint: "https://example.com",};const response = await makeZodVerifiedAPICall(@@ -454,9 +454,7 @@ describe("Blob Storage Integrations API", () => {expect(response.status).toBe(200);expect(response.body.type).toBe("AZURE_BLOB_STORAGE");- expect(response.body.endpoint).toBe(- "https://myaccount.blob.core.windows.net",- );+ expect(response.body.endpoint).toBe("https://example.com");});it("should reject invalid Azure container names", async () => {@@ -464,7 +462,7 @@ describe("Blob Storage Integrations API", () => {...validBlobStorageConfig,projectId: testProject1Id,type: "AZURE_BLOB_STORAGE" as const,- endpoint: "https://myaccount.blob.core.windows.net",+ endpoint: "https://example.com",bucketName: "Feedback N8N Bot",};diff --git a/web/src/__tests__/server/blob-storage-integration-trpc.servertest.ts b/web/src/__tests__/server/blob-storage-integration-trpc.servertest.tsindex f77f2b11b6..6f3730fe8d 100644--- a/web/src/__tests__/server/blob-storage-integration-trpc.servertest.ts+++ b/web/src/__tests__/server/blob-storage-integration-trpc.servertest.ts@@ -16,6 +16,7 @@ import {LEGACY_BLOB_EXPORT_CUTOFF,} from "@langfuse/shared";import { env } from "@/src/env.mjs";+import { env as sharedEnv } from "@langfuse/shared/src/env";const MS_PER_DAY = 24 * 60 * 60 * 1000;const PRE_CUTOFF = new Date(LEGACY_BLOB_EXPORT_CUTOFF.getTime() - MS_PER_DAY);@@ -343,6 +344,69 @@ describe("Blob Storage Integration tRPC Router", () => {});});+ describe("endpoint validation", () => {+ const originalAllowedIps =+ sharedEnv.LANGFUSE_BLOB_STORAGE_ENDPOINT_WHITELISTED_IPS;+ const originalSharedCloudRegion =+ sharedEnv.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION;++ beforeEach(() => {+ sharedEnv.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION = undefined;+ });++ afterEach(() => {+ sharedEnv.LANGFUSE_BLOB_STORAGE_ENDPOINT_WHITELISTED_IPS =+ originalAllowedIps;+ sharedEnv.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION = originalSharedCloudRegion;+ });++ it.each(["S3_COMPATIBLE", "AZURE_BLOB_STORAGE"] as const)(+ "rejects %s endpoints that target blocked IP ranges when validation is enabled",+ async (type) => {+ sharedEnv.LANGFUSE_BLOB_STORAGE_ENDPOINT_WHITELISTED_IPS = [+ "203.0.113.10",+ ];+ const { caller, project } = await prepare();++ await expect(+ caller.blobStorageIntegration.update({+ projectId: project.id,+ ...baseConfig,+ type,+ endpoint: "http://127.0.0.1:9000",+ }),+ ).rejects.toMatchObject({ code: "BAD_REQUEST" });+ },+ );++ it("allows endpoints when their IP is whitelisted", async () => {+ const { env: validationEnv } =+ await import("../../../../packages/shared/src/env");+ const { validateBlobStorageEndpoint } =+ await import("../../../../packages/shared/src/server/services/blobStorageEndpointValidation");+ const originalValidationCloudRegion =+ validationEnv.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION;+ const originalValidationAllowedIps =+ validationEnv.LANGFUSE_BLOB_STORAGE_ENDPOINT_WHITELISTED_IPS;++ try {+ validationEnv.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION = undefined;+ validationEnv.LANGFUSE_BLOB_STORAGE_ENDPOINT_WHITELISTED_IPS = [+ "127.0.0.1",+ ];++ await expect(+ validateBlobStorageEndpoint("http://127.0.0.1:9000"),+ ).resolves.not.toThrow();+ } finally {+ validationEnv.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION =+ originalValidationCloudRegion;+ validationEnv.LANGFUSE_BLOB_STORAGE_ENDPOINT_WHITELISTED_IPS =+ originalValidationAllowedIps;+ }+ });+ });+describe("exportFieldGroups", () => {it("stores a custom subset and round-trips via get", async () => {const { caller, project } = await prepare();diff --git a/web/src/features/blobstorage-integration/blobstorage-integration-router.ts b/web/src/features/blobstorage-integration/blobstorage-integration-router.tsindex 6558ec5f0c..a79034b998 100644--- a/web/src/features/blobstorage-integration/blobstorage-integration-router.ts+++ b/web/src/features/blobstorage-integration/blobstorage-integration-router.ts@@ -20,6 +20,8 @@ import {BlobStorageIntegrationProcessingQueue,QueueJobs,StorageServiceFactory,+ blobStorageEndpointConnectionValidationOptions,+ validateBlobStorageEndpoint,} from "@langfuse/shared/src/server";import { randomUUID } from "crypto";import { decrypt } from "@langfuse/shared/encryption";@@ -325,6 +327,10 @@ export const blobStorageIntegrationRouter = createTRPCRouter({? decrypt(encryptedSecretAccessKey): undefined;+ if (endpoint) {+ await validateBlobStorageEndpoint(endpoint);+ }+// Create storage service with provided configurationconst storageService = StorageServiceFactory.getInstance({accessKeyId: accessKeyId || undefined,@@ -340,6 +346,8 @@ export const blobStorageIntegrationRouter = createTRPCRouter({awsSse: undefined,awsSseKmsKeyId: undefined,externalEndpoint: undefined,+ connectionValidation:+ blobStorageEndpointConnectionValidationOptions(),});// Create a test filediff --git a/web/src/features/blobstorage-integration/service.ts b/web/src/features/blobstorage-integration/service.tsindex bcb865a3cb..c1bab226f7 100644--- a/web/src/features/blobstorage-integration/service.ts+++ b/web/src/features/blobstorage-integration/service.ts@@ -9,6 +9,7 @@ import {} from "@langfuse/shared";import { encrypt } from "@langfuse/shared/encryption";import { env } from "@/src/env.mjs";+import { validateBlobStorageEndpoint } from "@langfuse/shared/src/server";type UpsertBlobStorageIntegrationInput = {type: BlobStorageIntegrationType;@@ -64,6 +65,16 @@ export async function upsertBlobStorageIntegration(params: {const canUseHostCredentials =isSelfHosted && data.type === BlobStorageIntegrationType.S3;+ if (data.endpoint) {+ try {+ await validateBlobStorageEndpoint(data.endpoint);+ } catch (error) {+ throw new InvalidRequestError(+ `Invalid blob storage endpoint: ${error instanceof Error ? error.message : "Endpoint validation failed"}`,+ );+ }+ }+if (!canUseHostCredentials && !data.accessKeyId) {throw new InvalidRequestError("Access Key ID and Secret Access Key are required",diff --git a/worker/src/__tests__/blobStorageIntegrationProcessing.test.ts b/worker/src/__tests__/blobStorageIntegrationProcessing.test.tsindex 6cee6a1160..e5e0c23b17 100644--- a/worker/src/__tests__/blobStorageIntegrationProcessing.test.ts+++ b/worker/src/__tests__/blobStorageIntegrationProcessing.test.ts@@ -1,4 +1,20 @@-import { expect, it, describe, beforeAll, beforeEach, afterEach } from "vitest";+import {+ expect,+ it,+ describe,+ beforeAll,+ beforeEach,+ afterEach,+ afterAll,+ vi,+} from "vitest";++const originalCloudRegion = vi.hoisted(() => {+ const cloudRegion = process.env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION;+ delete process.env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION;+ return cloudRegion;+});+import { env } from "../env";import { randomUUID } from "crypto";import {@@ -71,6 +87,14 @@ describe("BlobStorageIntegrationProcessingJob", () => {});});+ afterAll(() => {+ if (originalCloudRegion) {+ process.env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION = originalCloudRegion;+ } else {+ delete process.env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION;+ }+ });+afterEach(async () => {// Clean up all files created during this testif (!s3Prefix) return;diff --git a/worker/src/__tests__/storageservice.test.ts b/worker/src/__tests__/storageservice.test.tsindex 64315e71ce..e29e1bee3d 100644--- a/worker/src/__tests__/storageservice.test.ts+++ b/worker/src/__tests__/storageservice.test.ts@@ -15,6 +15,12 @@ import {const { Readable } = require("stream");+const describeIfConnectionValidationSupported =+ env.LANGFUSE_USE_OCI_NATIVE_OBJECT_STORAGE === "true" ||+ env.LANGFUSE_USE_GOOGLE_CLOUD_STORAGE === "true"+ ? describe.skip+ : describe;+describe("StorageService", () => {let storageService: StorageService;let storageServiceWithExternalEndpoint: StorageService;@@ -298,4 +304,68 @@ describe("StorageService", () => {const file = await storageService.download(fileName);expect(file).toBe(data);});++ describeIfConnectionValidationSupported("connection validation", () => {+ test("uploadJson succeeds when the storage endpoint host is whitelisted", async () => {+ expect(env.LANGFUSE_S3_EVENT_UPLOAD_ENDPOINT).toBeDefined();+ if (!env.LANGFUSE_S3_EVENT_UPLOAD_ENDPOINT) return;++ const fileName = `${s3Prefix}${randomUUID()}.json`;+ const data = [{ hello: "validated world" }];+ const endpointHost = new URL(env.LANGFUSE_S3_EVENT_UPLOAD_ENDPOINT)+ .hostname;+ const storageServiceWithConnectionValidation =+ StorageServiceFactory.getInstance({+ accessKeyId: env.LANGFUSE_S3_EVENT_UPLOAD_ACCESS_KEY_ID,+ secretAccessKey: env.LANGFUSE_S3_EVENT_UPLOAD_SECRET_ACCESS_KEY,+ bucketName: env.LANGFUSE_S3_EVENT_UPLOAD_BUCKET,+ endpoint: env.LANGFUSE_S3_EVENT_UPLOAD_ENDPOINT,+ region: env.LANGFUSE_S3_EVENT_UPLOAD_REGION,+ forcePathStyle:+ env.LANGFUSE_S3_EVENT_UPLOAD_FORCE_PATH_STYLE === "true",+ connectionValidation: {+ whitelist: { hosts: [endpointHost], ips: [], ip_ranges: [] },+ logContext: "Blob storage endpoint",+ },+ });++ await storageServiceWithConnectionValidation.uploadJson(fileName, data);++ const file =+ await storageServiceWithConnectionValidation.download(fileName);+ expect(JSON.parse(file)).toEqual(data);+ });++ test("uploadJson fails when connection-time validation blocks the endpoint IP", async () => {+ const blockedStorageService = StorageServiceFactory.getInstance({+ accessKeyId: env.LANGFUSE_S3_EVENT_UPLOAD_ACCESS_KEY_ID,+ secretAccessKey: env.LANGFUSE_S3_EVENT_UPLOAD_SECRET_ACCESS_KEY,+ bucketName: env.LANGFUSE_S3_EVENT_UPLOAD_BUCKET,+ endpoint: "http://localhost:1",+ region: env.LANGFUSE_S3_EVENT_UPLOAD_REGION,+ forcePathStyle:+ env.LANGFUSE_S3_EVENT_UPLOAD_FORCE_PATH_STYLE === "true",+ awsSse: undefined,+ awsSseKmsKeyId: undefined,+ connectionValidation: {+ whitelist: { hosts: [], ips: [], ip_ranges: [] },+ logContext: "Blob storage endpoint",+ },+ });++ const error = await blockedStorageService+ .uploadJson("test.json", [])+ .catch((err: unknown) => err);++ const expectedMessage =+ env.LANGFUSE_USE_AZURE_BLOB === "true"+ ? "Failed to upload JSON to Azure Blob Storage"+ : "Failed to upload JSON to S3";+ expect(error).toBeInstanceOf(Error);+ expect((error as Error).message).toBe(expectedMessage);+ expect((error as Error).cause).toMatchObject({+ message: "Blocked IP address detected",+ });+ }, 20_000);+ });});diff --git a/worker/src/features/blobstorage/handleBlobStorageIntegrationProjectJob.ts b/worker/src/features/blobstorage/handleBlobStorageIntegrationProjectJob.tsindex aaef03cc65..dd7c36d395 100644--- a/worker/src/features/blobstorage/handleBlobStorageIntegrationProjectJob.ts+++ b/worker/src/features/blobstorage/handleBlobStorageIntegrationProjectJob.ts@@ -21,6 +21,8 @@ import {getProjectAdminEmails,enrichObservationWithModelData,createModelCache,+ blobStorageEndpointConnectionValidationOptions,+ validateBlobStorageEndpoint,} from "@langfuse/shared/src/server";import {BlobStorageIntegrationType,@@ -243,6 +245,9 @@ const processBlobStorageExport = async (config: {awsSse: undefined,awsSseKmsKeyId: undefined,useAzureBlob: config.type === BlobStorageIntegrationType.AZURE_BLOB_STORAGE,+ useGoogleCloudStorage: false, // Not supported in blob storage integration+ useOCIObjectStorage: false, // Not supported in blob storage integration+ connectionValidation: blobStorageEndpointConnectionValidationOptions(),});try {@@ -431,6 +436,13 @@ export const handleBlobStorageIntegrationProjectJob = async (}try {+ // Preflight the persisted integration endpoint once per job inside the+ // export error path. StorageService connection-time validation remains the+ // DNS-rebinding defense for each SDK connection.+ if (blobStorageIntegration.endpoint) {+ await validateBlobStorageEndpoint(blobStorageIntegration.endpoint);+ }+// Process the export based on the integration configuration// Convert v4 (events table) latency/time_to_first_token from ms to seconds// for integrations created on or after 2026-04-01. Before this date, v4 blob