🪢 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
feat(blobstorage): auto-disable export on outbound-URL/SSRF validation rejections (LFE-10927) (#15087)
Niklas Semmler716398e21a60
diff --git a/packages/shared/src/server/services/blobStorageEndpointValidation.test.ts b/packages/shared/src/server/services/blobStorageEndpointValidation.test.tsnew file mode 100644index 0000000000..12e6020dbd--- /dev/null+++ b/packages/shared/src/server/services/blobStorageEndpointValidation.test.ts@@ -0,0 +1,61 @@+import { describe, it, expect } from "vitest";+import { OutboundUrlValidationError, parseOutboundUrl } from "../outbound-url";+import { validateBlobStorageEndpoint } from "./blobStorageEndpointValidation";++// Non-empty whitelist turns on validation in a non-cloud (DEV) deployment; the+// entries are an *allow* list, so an endpoint outside them is still checked.+const enablingWhitelist = { hosts: [], ips: [], ip_ranges: ["203.0.113.0/24"] };++describe("outbound-url validation error typing", () => {+ it("parseOutboundUrl throws a typed error with a specific code", () => {+ try {+ parseOutboundUrl("http://user:[email protected]");+ throw new Error("expected throw");+ } catch (error) {+ expect(error).toBeInstanceOf(OutboundUrlValidationError);+ expect((error as OutboundUrlValidationError).code).toBe(+ "url-credentials-not-allowed",+ );+ }+ });+});++describe("validateBlobStorageEndpoint", () => {+ it("rejects a disallowed protocol as a typed validation error", async () => {+ await expect(+ validateBlobStorageEndpoint("ftp://blob.example.com", enablingWhitelist),+ ).rejects.toMatchObject({+ name: "OutboundUrlValidationError",+ code: "protocol-not-allowed",+ });+ });++ it("rejects a blocked private IP and preserves the code through the guidance re-wrap", async () => {+ let caught: unknown;+ try {+ await validateBlobStorageEndpoint("http://10.0.0.1", enablingWhitelist);+ } catch (error) {+ caught = error;+ }+ expect(caught).toBeInstanceOf(OutboundUrlValidationError);+ expect((caught as OutboundUrlValidationError).code).toBe("blocked-ip");+ // The catch appends self-hosted guidance to the single authoritative+ // message and does NOT chain `cause` (downstream formatters prefer a+ // cause's message and would otherwise drop the guidance / duplicate text).+ expect((caught as Error).message).toContain("Blocked IP address detected");+ expect((caught as Error).message).toContain(+ "LANGFUSE_BLOB_STORAGE_ENDPOINT_WHITELISTED_HOST",+ );+ expect((caught as Error).cause).toBeUndefined();+ });++ it("no-ops when validation is disabled (empty whitelist, non-cloud)", async () => {+ await expect(+ validateBlobStorageEndpoint("http://10.0.0.1", {+ hosts: [],+ ips: [],+ ip_ranges: [],+ }),+ ).resolves.toBeUndefined();+ });+});diff --git a/packages/shared/src/server/services/blobStorageEndpointValidation.ts b/packages/shared/src/server/services/blobStorageEndpointValidation.tsindex 689702c698..34234c6ed8 100644--- a/packages/shared/src/server/services/blobStorageEndpointValidation.ts+++ b/packages/shared/src/server/services/blobStorageEndpointValidation.ts@@ -2,6 +2,7 @@ import { env } from "../../env";import {type OutboundUrlConnectionValidationOptions,type OutboundUrlValidationWhitelist,+ OutboundUrlValidationError,parseOutboundUrl,validateOutboundUrlHost,} from "../outbound-url";@@ -47,11 +48,15 @@ export async function validateBlobStorageEndpoint(const url = parseOutboundUrl(endpoint);if (!["https:", "http:"].includes(url.protocol)) {- throw new Error("Only HTTP and HTTPS protocols are allowed");+ throw new OutboundUrlValidationError(+ "protocol-not-allowed",+ "Only HTTP and HTTPS protocols are allowed",+ );}if (isLangfuseCloudEndpointValidationEnabled() && url.protocol !== "https:") {- throw new Error(+ throw new OutboundUrlValidationError(+ "https-required","Only HTTPS blob storage endpoints are allowed on Langfuse Cloud",);}@@ -66,9 +71,21 @@ export async function validateBlobStorageEndpoint(shouldSkipDnsCheckForLiteralIps: true,});} catch (error) {- const message =- error instanceof Error ? error.message : "Validation failed";- throw new Error(`${message}${getSelfHostedWhitelistGuidance()}`);+ // Re-wrap to append self-hosted guidance while preserving the validation+ // `code` so the worker's customer-fault classifier still recognises the+ // rejection. Do not chain `cause`: the guidance-suffixed message is the+ // authoritative one, and downstream formatters (worker+ // extractStorageErrorMessage, tRPC getErrorMessage) prefer a cause's+ // message and would otherwise drop the guidance / duplicate the text.+ // Unexpected non-validation errors pass through untouched so they are not+ // misclassified as customer faults.+ if (error instanceof OutboundUrlValidationError) {+ throw new OutboundUrlValidationError(+ error.code,+ `${error.message}${getSelfHostedWhitelistGuidance()}`,+ );+ }+ throw error;}}diff --git a/worker/src/features/blobstorage/handleBlobStorageIntegrationProjectJob.ts b/worker/src/features/blobstorage/handleBlobStorageIntegrationProjectJob.tsindex a54534bda1..30b8c37f31 100644--- a/worker/src/features/blobstorage/handleBlobStorageIntegrationProjectJob.ts+++ b/worker/src/features/blobstorage/handleBlobStorageIntegrationProjectJob.ts@@ -46,7 +46,10 @@ import {} from "./abortClassification";import { isSigtermReceived } from "../health";import { TimedGzip, ZLIB_DEFAULT_LEVEL, type GzipStats } from "./gzipStream";-import { isCustomerFaultError } from "./isCustomerFaultError";+import {+ BLOB_INTEGRATION_DISABLED_METRIC,+ classifyCustomerFault,+} from "./isCustomerFaultError";import { ByteCounter, TimedByteCounter } from "./byteCounters";import { WORKER_HOST_ID } from "../../utils/hostId";import {@@ -1513,8 +1516,11 @@ export const handleBlobStorageIntegrationProjectJob = async (// 0-based, so the final attempt is attempts - 1.const isFinalAttempt =(job.attemptsMade ?? 0) >= (job.opts?.attempts ?? 1) - 1;+ // The reason bucket doubles as the disable decision (defined => disable) and+ // as the tag on the disable log + metric below.+ const customerFaultReason = classifyCustomerFault(error);const disableForCustomerFault =- isFinalAttempt && isCustomerFaultError(error);+ isFinalAttempt && customerFaultReason !== undefined;// True only for the worker that actually flips enabled true→false, so the// "disabled" email (which bypasses the cooldown) is sent exactly once and@@ -1543,8 +1549,14 @@ export const handleBlobStorageIntegrationProjectJob = async (disableClaimRan = true;persistedDisable = count === 1;if (persistedDisable) {+ // Tag by reason so SSRF/abuse disables (ssrf_blocked_endpoint) can be+ // separated from customer misconfig, and a mass-disable regression is+ // visible as a spike in the non-SSRF buckets after rollout.+ const reason = customerFaultReason ?? "unknown";+ recordIncrement(BLOB_INTEGRATION_DISABLED_METRIC, 1, { reason });logger.warn(- `[BLOB INTEGRATION] Disabled blob storage integration for project ${projectId} after a customer-config/credential failure: ${errorMessage}`,+ `[BLOB INTEGRATION] Disabled blob storage integration for project ${projectId} after a customer fault (reason=${reason}): ${errorMessage}`,+ { blobStorageDisableReason: reason, projectId },);}}diff --git a/worker/src/features/blobstorage/isCustomerFaultError.test.ts b/worker/src/features/blobstorage/isCustomerFaultError.test.tsindex 3f1922b145..d9303495e6 100644--- a/worker/src/features/blobstorage/isCustomerFaultError.test.ts+++ b/worker/src/features/blobstorage/isCustomerFaultError.test.ts@@ -1,5 +1,9 @@import { describe, it, expect } from "vitest";-import { isCustomerFaultError } from "./isCustomerFaultError";+import { OutboundUrlValidationError } from "@langfuse/shared/src/server";+import {+ classifyCustomerFault,+ isCustomerFaultError,+} from "./isCustomerFaultError";// Builds the wrapper the handler actually sees: StorageService.handleStorageError// rethrows SDK errors as `new Error("Failed to ...", { cause: sdkError })`.@@ -151,6 +155,55 @@ describe("isCustomerFaultError", () => {});});+ describe("customer_fault — outbound-URL / SSRF validation rejection", () => {+ it.each([+ "blocked-ip",+ "blocked-hostname",+ "invalid-syntax",+ "invalid-encoding",+ "https-required",+ "protocol-not-allowed",+ "url-credentials-not-allowed",+ ] as const)(+ "classifies a %s validation rejection as customer_fault",+ (code) => {+ const err = new OutboundUrlValidationError(code, "blocked");+ expect(isCustomerFaultError(err)).toBe(true);+ expect(isCustomerFaultError(wrapped(err))).toBe(true);+ },+ );++ it("classifies dns-lookup-failed as other, not customer_fault", () => {+ // Resolvability depends on runtime resolver state, not the endpoint+ // config: a transient DNS outage across the retry window must not+ // permanently disable a working integration. Keep it investigable,+ // consistent with the network EAI_AGAIN case above.+ const err = new OutboundUrlValidationError(+ "dns-lookup-failed",+ "DNS lookup failed for host.example",+ );+ expect(isCustomerFaultError(err)).toBe(false);+ expect(isCustomerFaultError(wrapped(err))).toBe(false);+ });++ it("classifies a validation rejection re-wrapped with guidance (code preserved) as customer_fault", () => {+ // Mirrors validateBlobStorageEndpoint's catch: a new typed error carrying+ // the same deterministic code, with no `cause` chained.+ const rewrapped = new OutboundUrlValidationError(+ "blocked-ip",+ "Blocked IP address detected For self-hosted deployments ...",+ );+ expect(isCustomerFaultError(wrapped(rewrapped))).toBe(true);+ });++ it("does NOT classify a code-less error that merely shares the message as customer_fault", () => {+ // Classification is code-based, not message-based: a bare 'DNS lookup+ // failed' Error (e.g. some future unrelated throw site) stays investigable.+ const err = new Error("DNS lookup failed for host.example");+ expect(isCustomerFaultError(wrapped(err))).toBe(false);+ });+ });+describe("cause-chain traversal", () => {it("finds a customer fault nested several causes deep", () => {const root = s3Error("InvalidAccessKeyId", 403);@@ -167,3 +220,73 @@ describe("isCustomerFaultError", () => {});});});++describe("classifyCustomerFault — disable reason buckets", () => {+ it.each([+ ["blocked-ip", "ssrf_blocked_endpoint"],+ ["blocked-hostname", "ssrf_blocked_endpoint"],+ ["invalid-syntax", "invalid_endpoint_url"],+ ["invalid-encoding", "invalid_endpoint_url"],+ ["https-required", "invalid_endpoint_url"],+ ["protocol-not-allowed", "invalid_endpoint_url"],+ ["url-credentials-not-allowed", "invalid_endpoint_url"],+ ] as const)("maps outbound-url %s to %s", (code, reason) => {+ const err = new OutboundUrlValidationError(code, "blocked");+ expect(classifyCustomerFault(err)).toBe(reason);+ expect(classifyCustomerFault(wrapped(err))).toBe(reason);+ });++ it.each(["InvalidAccessKeyId", "AccessDenied", "SignatureDoesNotMatch"])(+ "maps S3 auth code %s to credentials",+ (code) => {+ expect(classifyCustomerFault(wrapped(s3Error(code, 403)))).toBe(+ "credentials",+ );+ },+ );++ it.each(["AuthenticationFailed", "InsufficientAccountPermissions"])(+ "maps Azure auth code %s to credentials",+ (code) => {+ expect(classifyCustomerFault(wrapped(azureError(code, 403)))).toBe(+ "credentials",+ );+ },+ );++ it("maps a bare 401 and GCS forbidden to credentials", () => {+ const unauthorized = new Error("Unauthorized");+ Object.assign(unauthorized, { $metadata: { httpStatusCode: 401 } });+ expect(classifyCustomerFault(wrapped(unauthorized))).toBe("credentials");+ expect(classifyCustomerFault(wrapped(gcsError(403, "forbidden")))).toBe(+ "credentials",+ );+ });++ it.each([+ ["NoSuchBucket", 404],+ ["InvalidBucketName", 400],+ ["ContainerNotFound", 404],+ ["InvalidResourceName", 400],+ ] as const)("maps %s to bucket_or_container", (code, status) => {+ // extractErrorCodes reads .name/.Code/.code, so the code bucket is+ // provider-agnostic here — the s3Error shape is enough to exercise it.+ expect(classifyCustomerFault(wrapped(s3Error(code, status)))).toBe(+ "bucket_or_container",+ );+ });++ it("returns undefined for non-disabling errors (dns-lookup-failed, transient)", () => {+ expect(+ classifyCustomerFault(+ new OutboundUrlValidationError(+ "dns-lookup-failed",+ "DNS lookup failed",+ ),+ ),+ ).toBeUndefined();+ const transient = new Error("network EAI_AGAIN");+ Object.assign(transient, { code: "EAI_AGAIN" });+ expect(classifyCustomerFault(wrapped(transient))).toBeUndefined();+ });+});diff --git a/worker/src/features/blobstorage/isCustomerFaultError.ts b/worker/src/features/blobstorage/isCustomerFaultError.tsindex c40753570b..f468f79691 100644--- a/worker/src/features/blobstorage/isCustomerFaultError.ts+++ b/worker/src/features/blobstorage/isCustomerFaultError.ts@@ -7,9 +7,25 @@// retrying. Errors arrive wrapped via `new Error(..., { cause })`// (StorageService.handleStorageError), so we walk the cause chain.+// Counter for integrations auto-disabled after a terminal customer fault, tagged+// by `reason`. Lets a rollout regression (a classifier bug mass-disabling+// working integrations) show up as a spike in the non-SSRF buckets against a+// near-zero baseline, separately from expected SSRF/abuse disables.+export const BLOB_INTEGRATION_DISABLED_METRIC =+ "langfuse.blobstorage.integration_disabled.count";++// Coarse cause bucket for a disable, for logs/metrics. `ssrf_blocked_endpoint`+// is the SSRF-guard rejection (endpoint resolves to a blocked host/IP) — the+// "likely abuse" bucket to watch — while the rest are customer misconfiguration.+export type CustomerFaultReason =+ | "ssrf_blocked_endpoint"+ | "invalid_endpoint_url"+ | "credentials"+ | "bucket_or_container";+// AWS SDK v3 sets `.name`/`.Code`; Azure RestError sets `.code`. S3-compatible// providers (incl. GCS S3-interop) surface the S3 codes.-const CUSTOMER_FAULT_ERROR_CODES = new Set<string>([+const CREDENTIAL_FAULT_CODES = new Set<string>([// S3 — auth & credentials"InvalidAccessKeyId","SignatureDoesNotMatch",@@ -17,9 +33,6 @@ const CUSTOMER_FAULT_ERROR_CODES = new Set<string>(["AllAccessDisabled","AccountProblem","AuthorizationHeaderMalformed",- // S3 — bucket & path- "NoSuchBucket",- "InvalidBucketName",// Azure — auth & credentials"AuthenticationFailed","AuthorizationFailure",@@ -27,11 +40,37 @@ const CUSTOMER_FAULT_ERROR_CODES = new Set<string>(["InvalidAuthenticationInfo","AccountIsDisabled","InsufficientAccountPermissions",+]);++const BUCKET_FAULT_CODES = new Set<string>([+ // S3 — bucket & path+ "NoSuchBucket",+ "InvalidBucketName",// Azure — container & path"ContainerNotFound","InvalidResourceName",]);+// Langfuse outbound-URL / SSRF validation rejections (OutboundUrlValidationError+// from @langfuse/shared/.../outbound-url), split by cause. Every code here is a+// deterministic property of the endpoint config, so it is safe to auto-disable+// on. We deliberately omit `dns-lookup-failed`: resolvability depends on runtime+// resolver state, not the config, so a transient DNS outage across the retry+// window must not permanently disable a working integration. secureLlmFetch+// makes the same distinction (dns-lookup-failed -> "endpoint-unreachable").+const SSRF_BLOCKED_OUTBOUND_URL_CODES = new Set<string>([+ "blocked-hostname",+ "blocked-ip",+]);++const INVALID_URL_OUTBOUND_URL_CODES = new Set<string>([+ "invalid-syntax",+ "invalid-encoding",+ "https-required",+ "protocol-not-allowed",+ "url-credentials-not-allowed",+]);+// GCS JSON-API reasons (only reachable via a GCS-native client; S3-interop uses// the S3 codes above). Narrow on purpose: object-level notFound stays `other`.const CUSTOMER_FAULT_GCS_REASONS = new Set<string>(["forbidden"]);@@ -87,22 +126,57 @@ function extractGcsReasons(err: object): string[] {.filter((r): r is string => typeof r === "string");}-function isCustomerFaultLink(err: object): boolean {- if (extractErrorCodes(err).some((c) => CUSTOMER_FAULT_ERROR_CODES.has(c))) {- return true;+// Duck-type on `.name` (survives cross-package module duplication where+// `instanceof` is unreliable) rather than importing the class, then map the+// deterministic code to a reason; transient reasons like `dns-lookup-failed`+// return undefined so they stay non-disabling.+function classifyOutboundUrlFault(+ err: object,+): CustomerFaultReason | undefined {+ if ((err as { name?: unknown }).name !== "OutboundUrlValidationError") {+ return undefined;}+ const code = (err as { code?: unknown }).code;+ if (typeof code !== "string") return undefined;+ if (SSRF_BLOCKED_OUTBOUND_URL_CODES.has(code)) return "ssrf_blocked_endpoint";+ if (INVALID_URL_OUTBOUND_URL_CODES.has(code)) return "invalid_endpoint_url";+ return undefined;+}++function classifyCustomerFaultLink(+ err: object,+): CustomerFaultReason | undefined {+ const outbound = classifyOutboundUrlFault(err);+ if (outbound) return outbound;++ const codes = extractErrorCodes(err);+ if (codes.some((c) => CREDENTIAL_FAULT_CODES.has(c))) return "credentials";+ if (codes.some((c) => BUCKET_FAULT_CODES.has(c)))+ return "bucket_or_container";+// 401 = credentials rejected: unambiguous, so it trips without a code. A bare// 403/404 does not (e.g. clock-skew RequestTimeTooSkewed is a 403).- if (extractHttpStatus(err) === 401) return true;+ if (extractHttpStatus(err) === 401) return "credentials";if (extractGcsReasons(err).some((r) => CUSTOMER_FAULT_GCS_REASONS.has(r))) {- return true;+ return "credentials";}- return false;+ return undefined;}-export function isCustomerFaultError(error: unknown): boolean {+// Returns the deterministic customer-fault reason for the first matching link in+// the cause chain, or undefined when nothing qualifies (retry-worthy / infra /+// transient). The handler disables on any defined reason and tags the disable+// log + metric with it.+export function classifyCustomerFault(+ error: unknown,+): CustomerFaultReason | undefined {for (const link of errorCauseChain(error)) {- if (isCustomerFaultLink(link)) return true;+ const reason = classifyCustomerFaultLink(link);+ if (reason) return reason;}- return false;+ return undefined;+}++export function isCustomerFaultError(error: unknown): boolean {+ return classifyCustomerFault(error) !== undefined;}