Skip to content

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

fix(llm-connections): validate new LLM base URLs (#13073)

Hassieb Pakzaddcb5dbf528a6
diff --git a/.env.dev.example b/.env.dev.example
index 35d0034a46..86ba24b29a 100644
--- a/.env.dev.example
+++ b/.env.dev.example
@@ -145,6 +145,11 @@ LANGFUSE_AI_FEATURES_SECRET_KEY="sk-lf-1234567890"
LANGFUSE_AI_FEATURES_HOST="http://localhost:3000"
LANGFUSE_AI_FEATURES_PROJECT_ID=7a88fb47-b4e2-43b8-a06c-a5ce950dc53a
+# Self-hosted only: allow internal LLM proxy hosts/IPs for LLM connection base URLs.
+# 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
+
# Langfuse AI Bedrock credentials
AWS_ACCESS_KEY_ID="A123456789"
AWS_SECRET_ACCESS_KEY="SAK123456789"
diff --git a/.env.prod.example b/.env.prod.example
index 8c43b4a717..b026ddda99 100644
--- a/.env.prod.example
+++ b/.env.prod.example
@@ -299,6 +299,10 @@ LANGFUSE_ENABLE_BLOB_STORAGE_FILE_LOG=true
# Admin API
# ADMIN_API_KEY=
+# Self-hosted only: allow internal LLM proxy hosts/IPs for LLM connection base URLs.
+# LANGFUSE_LLM_CONNECTION_WHITELISTED_HOST=
+# LANGFUSE_LLM_CONNECTION_WHITELISTED_IPS=
+# LANGFUSE_LLM_CONNECTION_WHITELISTED_IP_SEGMENTS=
# LANGFUSE_CACHE_MODEL_MATCH_ENABLED=
# LANGFUSE_CACHE_MODEL_MATCH_TTL_SECONDS=
diff --git a/packages/shared/src/env.ts b/packages/shared/src/env.ts
index 6e1166d873..5a98e3f3a1 100644
--- a/packages/shared/src/env.ts
+++ b/packages/shared/src/env.ts
@@ -261,6 +261,24 @@ const EnvSchema = z.object({
.transform((s) =>
s ? s.split(",").map((s) => s.toLowerCase().trim()) : [],
),
+ LANGFUSE_LLM_CONNECTION_WHITELISTED_IPS: z
+ .string()
+ .optional()
+ .transform((s) =>
+ s ? s.split(",").map((s) => s.toLowerCase().trim()) : [],
+ ),
+ LANGFUSE_LLM_CONNECTION_WHITELISTED_IP_SEGMENTS: z
+ .string()
+ .optional()
+ .transform((s) =>
+ s ? s.split(",").map((s) => s.toLowerCase().trim()) : [],
+ ),
+ LANGFUSE_LLM_CONNECTION_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.ts
index db38d10eb4..a8b31b5f49 100644
--- a/packages/shared/src/server/index.ts
+++ b/packages/shared/src/server/index.ts
@@ -30,6 +30,7 @@ export * from "./llm/utils";
export * from "./llm/types";
export * from "./llm/compileChatMessages";
export * from "./llm/testModelCall";
+export * from "./llm/baseUrlValidation";
export * from "./llm/getInternalTracingHandler";
export * from "./utils/DatabaseReadStream";
export * from "./utils/transforms";
diff --git a/packages/shared/src/server/llm/baseUrlValidation.ts b/packages/shared/src/server/llm/baseUrlValidation.ts
new file mode 100644
index 0000000000..8ec60505d1
--- /dev/null
+++ b/packages/shared/src/server/llm/baseUrlValidation.ts
@@ -0,0 +1,133 @@
+import { URL } from "node:url";
+import { env } from "../../env";
+import { logger } from "../logger";
+import {
+ isHostnameBlocked,
+ isIPBlocked,
+ isIPAddress,
+} from "../webhooks/ipBlocking";
+import { resolveHost } from "../webhooks/validation";
+
+export interface LlmBaseUrlValidationWhitelist {
+ hosts: string[];
+ ips: string[];
+ ip_ranges: string[];
+}
+
+export function llmBaseUrlWhitelistFromEnv(): LlmBaseUrlValidationWhitelist {
+ if (env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION) {
+ return {
+ hosts: [],
+ ips: [],
+ ip_ranges: [],
+ };
+ }
+
+ return {
+ hosts: env.LANGFUSE_LLM_CONNECTION_WHITELISTED_HOST || [],
+ ips: env.LANGFUSE_LLM_CONNECTION_WHITELISTED_IPS || [],
+ ip_ranges: env.LANGFUSE_LLM_CONNECTION_WHITELISTED_IP_SEGMENTS || [],
+ };
+}
+
+export async function validateLlmConnectionBaseURL(
+ urlString: string,
+ whitelist: LlmBaseUrlValidationWhitelist = llmBaseUrlWhitelistFromEnv(),
+): Promise<void> {
+ const effectiveWhitelist = env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION
+ ? {
+ hosts: [],
+ ips: [],
+ ip_ranges: [],
+ }
+ : whitelist;
+
+ let url: URL;
+ try {
+ url = new URL(normalizeURL(urlString));
+ } catch {
+ throw new Error("Invalid URL syntax");
+ }
+
+ if (!["https:", "http:"].includes(url.protocol)) {
+ throw new Error("Only HTTP and HTTPS protocols are allowed");
+ }
+
+ const hostname = normalizeHostname(url.hostname);
+
+ if (effectiveWhitelist.hosts.includes(hostname)) {
+ return;
+ }
+
+ if (isHostnameBlocked(hostname)) {
+ throw new Error("Blocked hostname detected");
+ }
+
+ if (env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION && url.protocol !== "https:") {
+ throw new Error("Only HTTPS base URLs are allowed on Langfuse Cloud");
+ }
+
+ if (isIPAddress(hostname)) {
+ if (
+ isIPBlocked(
+ hostname,
+ effectiveWhitelist.ips,
+ effectiveWhitelist.ip_ranges,
+ )
+ ) {
+ logger.warn(
+ `LLM base URL validation blocked IP address in hostname: ${hostname}`,
+ );
+ throw new Error("Blocked IP address detected");
+ }
+
+ return;
+ }
+
+ let ips: string[];
+ try {
+ ips = await resolveHost(hostname);
+ } catch {
+ // DNS resolution is best-effort here so valid custom gateways do not fail at write time.
+ return;
+ }
+
+ for (const ip of ips) {
+ if (isIPBlocked(ip, effectiveWhitelist.ips, effectiveWhitelist.ip_ranges)) {
+ logger.warn(
+ `LLM base URL validation blocked resolved IP address: ${ip} for hostname: ${hostname}`,
+ );
+ throw new Error("Blocked IP address detected");
+ }
+ }
+}
+
+function normalizeURL(urlString: string): string {
+ let normalized = urlString.trim();
+
+ try {
+ normalized = decodeURIComponent(normalized);
+ } catch {
+ throw new Error("Invalid URL encoding");
+ }
+
+ try {
+ normalized = normalized.normalize("NFC");
+ } catch {
+ throw new Error("Invalid unicode in URL");
+ }
+
+ return normalized;
+}
+
+function normalizeHostname(hostname: string): string {
+ let normalized = hostname.toLowerCase();
+
+ try {
+ normalized = new URL(`http://${normalized}`).hostname;
+ } catch {
+ // Keep the original hostname so URL parsing can fail consistently elsewhere.
+ }
+
+ return normalized;
+}
diff --git a/packages/shared/src/server/webhooks/ipBlocking.ts b/packages/shared/src/server/webhooks/ipBlocking.ts
index 55db0c60c2..548b9c10b8 100644
--- a/packages/shared/src/server/webhooks/ipBlocking.ts
+++ b/packages/shared/src/server/webhooks/ipBlocking.ts
@@ -50,12 +50,14 @@ export function isIPBlocked(
whiteListedIpSegments: string[],
): boolean {
try {
+ const cleanedIp = normalizeIPAddress(ipString);
+
// Check if IP is in whitelist first
- if (whitelistedIPs.includes(ipString.toLowerCase().trim())) {
+ if (whitelistedIPs.includes(cleanedIp)) {
return false;
}
- const ip = ipaddr.parse(ipString);
+ const ip = ipaddr.parse(cleanedIp);
const whitelistedSegments = whiteListedIpSegments.map((cidr) => {
const [addr, bits] = cidr.split("/");
@@ -87,8 +89,7 @@ export function isIPBlocked(
* Check if a string is an IP address
*/
export function isIPAddress(hostname: string): boolean {
- // Remove brackets from IPv6 addresses
- const cleaned = hostname.replace(/^\[|\]$/g, "");
+ const cleaned = normalizeIPAddress(hostname);
try {
ipaddr.parse(cleaned);
@@ -137,3 +138,10 @@ export function isHostnameBlocked(hostname: string): boolean {
return false;
}
+
+function normalizeIPAddress(ipString: string): string {
+ return ipString
+ .toLowerCase()
+ .trim()
+ .replace(/^\[|\]$/g, "");
+}
diff --git a/web/src/__tests__/server/llm-api-key.servertest.ts b/web/src/__tests__/server/llm-api-key.servertest.ts
index 72b8a96c75..69f8273f89 100644
--- a/web/src/__tests__/server/llm-api-key.servertest.ts
+++ b/web/src/__tests__/server/llm-api-key.servertest.ts
@@ -13,7 +13,7 @@ import { LLMAdapter } from "@langfuse/shared";
import { prisma } from "@langfuse/shared/src/db";
import { appRouter } from "@/src/server/api/root";
import { createInnerTRPCContext } from "@/src/server/api/trpc";
-import { decrypt } from "@langfuse/shared/encryption";
+import { decrypt, encrypt } from "@langfuse/shared/encryption";
import {
createOrgProjectAndApiKey,
fetchLLMCompletion,
@@ -140,6 +140,18 @@ describe("llmApiKey.all RPC", () => {
expect(llmApiKeys[0].displaySecretKey).toMatch(/^...[a-zA-Z0-9]{4}$/);
});
+ it("should block creating an llm api key with a localhost base URL", async () => {
+ await expect(
+ caller.llmApiKey.create({
+ projectId,
+ secretKey: "test-secret",
+ provider: "openai",
+ adapter: LLMAdapter.OpenAI,
+ baseURL: "http://localhost:11434/v1",
+ }),
+ ).rejects.toThrow("Invalid base URL: Blocked hostname detected");
+ });
+
it("should create and get an llm api key", async () => {
const secret = "test-secret";
const provider = "openai";
@@ -201,7 +213,7 @@ describe("llmApiKey.all RPC", () => {
).rejects.toThrow("User does not have access to this resource or action");
});
- it("should require llmApiKeys:create access for testing an existing llm api key", async () => {
+ it("should require llmApiKeys:update access for testing an existing llm api key", async () => {
await caller.llmApiKey.create({
projectId,
provider: "openai",
@@ -261,6 +273,31 @@ describe("llmApiKey.all RPC", () => {
expect(mockFetchLLMCompletion).not.toHaveBeenCalled();
});
+ it("should allow testing an existing connection with an unchanged localhost base URL", async () => {
+ const connection = await prisma.llmApiKeys.create({
+ data: {
+ projectId,
+ provider: "local-ollama",
+ adapter: LLMAdapter.OpenAI,
+ secretKey: encrypt("sk-existing"),
+ displaySecretKey: "...ting",
+ baseURL: "http://localhost:11434/v1",
+ customModels: ["llama3.1"],
+ withDefaultModels: true,
+ },
+ });
+
+ const result = await caller.llmApiKey.testUpdate({
+ id: connection.id,
+ projectId,
+ provider: "local-ollama",
+ adapter: LLMAdapter.OpenAI,
+ });
+
+ expect(result).toEqual({ success: true });
+ expect(mockFetchLLMCompletion).toHaveBeenCalledTimes(1);
+ });
+
it("should allow testUpdate without a new secret key when the base URL is unchanged", async () => {
const existingExtraHeaders = {
Authorization: "Bearer stored-token",
diff --git a/web/src/__tests__/server/llm-connections-api.servertest.ts b/web/src/__tests__/server/llm-connections-api.servertest.ts
index 7ed62d51c2..3b255af343 100644
--- a/web/src/__tests__/server/llm-connections-api.servertest.ts
+++ b/web/src/__tests__/server/llm-connections-api.servertest.ts
@@ -354,6 +354,25 @@ describe("/api/public/llm-connections API Endpoints", () => {
expect(response.body.extraHeaderKeys).toEqual([]);
});
+ it("should reject creating a connection with a localhost baseURL", async () => {
+ const response = await makeAPICall(
+ "PUT",
+ "/api/public/llm-connections",
+ {
+ provider: generateUniqueProvider("local-openai"),
+ adapter: LLMAdapter.OpenAI,
+ secretKey: "sk-local",
+ baseURL: "http://localhost:11434/v1",
+ },
+ auth,
+ );
+
+ expect(response.status).toBe(400);
+ expect(response.body.message).toBe(
+ "Invalid baseURL: Blocked hostname detected",
+ );
+ });
+
it("should update existing connection (upsert)", async () => {
const existingProvider = generateUniqueProvider("existing-provider");
diff --git a/web/src/features/llm-api-key/server/router.ts b/web/src/features/llm-api-key/server/router.ts
index 33f7971b3f..12ef416413 100644
--- a/web/src/features/llm-api-key/server/router.ts
+++ b/web/src/features/llm-api-key/server/router.ts
@@ -33,6 +33,7 @@ import {
blockEvaluatorConfigsInTx,
EvaluatorBlockSource,
finalizeBlockedEvaluatorConfigBlocks,
+ validateLlmConnectionBaseURL,
} from "@langfuse/shared/src/server";
import { env } from "@/src/env.mjs";
import { TRPCError } from "@trpc/server";
@@ -130,6 +131,27 @@ async function testLLMConnection(
}
}
+async function validateBaseURLForWrite(params: {
+ baseURL?: string | null;
+ errorPrefix?: string;
+}): Promise<void> {
+ if (!params.baseURL) {
+ return;
+ }
+
+ try {
+ await validateLlmConnectionBaseURL(params.baseURL);
+ } catch (error) {
+ throw new TRPCError({
+ code: "BAD_REQUEST",
+ message:
+ error instanceof Error
+ ? `${params.errorPrefix ?? "Invalid base URL"}: ${error.message}`
+ : (params.errorPrefix ?? "Invalid base URL"),
+ });
+ }
+}
+
export const llmApiKeyRouter = createTRPCRouter({
create: protectedProjectProcedureWithoutTracing
.input(CreateLlmApiKey)
@@ -141,6 +163,10 @@ export const llmApiKeyRouter = createTRPCRouter({
scope: "llmApiKeys:create",
});
+ await validateBaseURLForWrite({
+ baseURL: input.baseURL,
+ });
+
// Validate that default credentials sentinel is only allowed for Bedrock/VertexAI in self-hosted deployments
const isLangfuseCloud = Boolean(env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION);
@@ -406,6 +432,17 @@ export const llmApiKeyRouter = createTRPCRouter({
scope: "llmApiKeys:create",
});
+ if (input.baseURL) {
+ try {
+ await validateLlmConnectionBaseURL(input.baseURL);
+ } catch (error) {
+ return {
+ success: false,
+ error: error instanceof Error ? error.message : "Invalid base URL",
+ };
+ }
+ }
+
return testLLMConnection({
adapter: input.adapter,
provider: input.provider,
@@ -454,6 +491,10 @@ export const llmApiKeyRouter = createTRPCRouter({
});
}
+ if (input.baseURL && isBaseURLChanged) {
+ await validateLlmConnectionBaseURL(input.baseURL);
+ }
+
const secretKey = hasNewSecretKey
? (input.secretKey as string)
: decrypt(existingKey.secretKey);
@@ -531,6 +572,16 @@ export const llmApiKeyRouter = createTRPCRouter({
// Validate that default credentials sentinel is only allowed for Bedrock/VertexAI in self-hosted deployments
const isLangfuseCloud = Boolean(env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION);
+ const isBaseURLChanged =
+ input.baseURL !== undefined
+ ? input.baseURL !== existingKey.baseURL
+ : false;
+
+ if (input.baseURL && isBaseURLChanged) {
+ await validateBaseURLForWrite({
+ baseURL: input.baseURL,
+ });
+ }
if (input.secretKey === BEDROCK_USE_DEFAULT_CREDENTIALS) {
if (isLangfuseCloud || input.adapter !== LLMAdapter.Bedrock) {
diff --git a/web/src/pages/api/public/llm-connections/index.ts b/web/src/pages/api/public/llm-connections/index.ts
index 78572f9127..2386e416b7 100644
--- a/web/src/pages/api/public/llm-connections/index.ts
+++ b/web/src/pages/api/public/llm-connections/index.ts
@@ -11,6 +11,8 @@ import {
import { encrypt } from "@langfuse/shared/encryption";
import { getDisplaySecretKey } from "@/src/features/llm-api-key/server/router";
import { auditLog } from "@/src/features/audit-logs/auditLog";
+import { InvalidRequestError } from "@langfuse/shared";
+import { validateLlmConnectionBaseURL } from "@langfuse/shared/src/server";
export default withMiddlewares({
GET: createAuthedProjectAPIRoute({
@@ -85,11 +87,21 @@ export default withMiddlewares({
provider: body.provider,
},
},
- select: { id: true },
+ select: { id: true, baseURL: true },
});
const isUpdate = Boolean(existingConnection);
+ if (body.baseURL && body.baseURL !== existingConnection?.baseURL) {
+ try {
+ await validateLlmConnectionBaseURL(body.baseURL);
+ } catch (error) {
+ throw new InvalidRequestError(
+ `Invalid baseURL: ${error instanceof Error ? error.message : "Unknown error"}`,
+ );
+ }
+ }
+
const llmConnectionBody = {
adapter: body.adapter,
secretKey: encrypt(body.secretKey),
diff --git a/worker/src/__tests__/llm-base-url-validation.test.ts b/worker/src/__tests__/llm-base-url-validation.test.ts
new file mode 100644
index 0000000000..01300805de
--- /dev/null
+++ b/worker/src/__tests__/llm-base-url-validation.test.ts
@@ -0,0 +1,111 @@
+import { afterEach, describe, expect, it } from "vitest";
+import {
+ validateLlmConnectionBaseURL,
+ type LlmBaseUrlValidationWhitelist,
+} from "../../../packages/shared/src/server/llm/baseUrlValidation";
+import { env } from "../../../packages/shared/src/env";
+
+const originalCloudRegion = env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION;
+const originalAllowedHosts = env.LANGFUSE_LLM_CONNECTION_WHITELISTED_HOST;
+const originalAllowedIps = env.LANGFUSE_LLM_CONNECTION_WHITELISTED_IPS;
+const originalAllowedIpSegments =
+ env.LANGFUSE_LLM_CONNECTION_WHITELISTED_IP_SEGMENTS;
+
+describe("LLM base URL validation", () => {
+ afterEach(() => {
+ (env as any).NEXT_PUBLIC_LANGFUSE_CLOUD_REGION = originalCloudRegion;
+ (env as any).LANGFUSE_LLM_CONNECTION_WHITELISTED_HOST =
+ originalAllowedHosts;
+ (env as any).LANGFUSE_LLM_CONNECTION_WHITELISTED_IPS = originalAllowedIps;
+ (env as any).LANGFUSE_LLM_CONNECTION_WHITELISTED_IP_SEGMENTS =
+ originalAllowedIpSegments;
+ });
+
+ it("should reject localhost by default for self-hosted instances", async () => {
+ (env as any).NEXT_PUBLIC_LANGFUSE_CLOUD_REGION = undefined;
+
+ await expect(
+ validateLlmConnectionBaseURL("http://localhost:11434/v1"),
+ ).rejects.toThrow("Blocked hostname detected");
+ });
+
+ it("should allow explicitly allowlisted localhost hosts for self-hosted instances", async () => {
+ (env as any).NEXT_PUBLIC_LANGFUSE_CLOUD_REGION = undefined;
+
+ const whitelist: LlmBaseUrlValidationWhitelist = {
+ hosts: ["localhost"],
+ ips: [],
+ ip_ranges: [],
+ };
+
+ await expect(
+ validateLlmConnectionBaseURL("http://localhost:11434/v1", whitelist),
+ ).resolves.not.toThrow();
+ });
+
+ it("should allow explicitly allowlisted IPv6 localhost literals for self-hosted instances", async () => {
+ (env as any).NEXT_PUBLIC_LANGFUSE_CLOUD_REGION = undefined;
+
+ const whitelist: LlmBaseUrlValidationWhitelist = {
+ hosts: [],
+ ips: ["::1"],
+ ip_ranges: [],
+ };
+
+ await expect(
+ validateLlmConnectionBaseURL("http://[::1]:11434/v1", whitelist),
+ ).resolves.not.toThrow();
+ });
+
+ it("should allow explicitly allowlisted IPv6 CIDR ranges for self-hosted instances", async () => {
+ (env as any).NEXT_PUBLIC_LANGFUSE_CLOUD_REGION = undefined;
+
+ const whitelist: LlmBaseUrlValidationWhitelist = {
+ hosts: [],
+ ips: [],
+ ip_ranges: ["::1/128"],
+ };
+
+ await expect(
+ validateLlmConnectionBaseURL("http://[::1]:11434/v1", whitelist),
+ ).resolves.not.toThrow();
+ });
+
+ it("should ignore self-host allowlists on Langfuse Cloud", async () => {
+ (env as any).NEXT_PUBLIC_LANGFUSE_CLOUD_REGION = "US";
+
+ const whitelist: LlmBaseUrlValidationWhitelist = {
+ hosts: ["localhost"],
+ ips: ["127.0.0.1"],
+ ip_ranges: ["127.0.0.0/8"],
+ };
+
+ await expect(
+ validateLlmConnectionBaseURL("https://localhost/v1", whitelist),
+ ).rejects.toThrow("Blocked hostname detected");
+ });
+
+ it("should allow public HTTPS URLs on Langfuse Cloud", async () => {
+ (env as any).NEXT_PUBLIC_LANGFUSE_CLOUD_REGION = "US";
+
+ await expect(
+ validateLlmConnectionBaseURL("https://1.1.1.1/v1"),
+ ).resolves.not.toThrow();
+ });
+
+ it("should allow unresolved public hostnames by default", async () => {
+ (env as any).NEXT_PUBLIC_LANGFUSE_CLOUD_REGION = undefined;
+
+ await expect(
+ validateLlmConnectionBaseURL("https://gateway.invalid/v1"),
+ ).resolves.not.toThrow();
+ });
+
+ it("should reject non-HTTPS URLs on Langfuse Cloud", async () => {
+ (env as any).NEXT_PUBLIC_LANGFUSE_CLOUD_REGION = "US";
+
+ await expect(
+ validateLlmConnectionBaseURL("http://1.1.1.1/v1"),
+ ).rejects.toThrow("Only HTTPS base URLs are allowed on Langfuse Cloud");
+ });
+});