🪢 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(web): add support for AWS Bedrock API Keys (Bearer Tokens) (#13098)
Tobias Wochinger9c6e749c9732
diff --git a/.env.dev.example b/.env.dev.exampleindex 86ba24b29a..9983c8c9d3 100644--- a/.env.dev.example+++ b/.env.dev.example@@ -153,6 +153,7 @@ LANGFUSE_AI_FEATURES_PROJECT_ID=7a88fb47-b4e2-43b8-a06c-a5ce950dc53a# Langfuse AI Bedrock credentialsAWS_ACCESS_KEY_ID="A123456789"AWS_SECRET_ACCESS_KEY="SAK123456789"+LANGFUSE_LLM_CONNECTION_BEDROCK_API_KEY="1234567890abcdef"LANGFUSE_AWS_BEDROCK_REGION="eu-west-1"LANGFUSE_AWS_BEDROCK_MODEL="eu.anthropic.claude-3-haiku-20240307-v1:0"diff --git a/.github/workflows/pipeline.yml b/.github/workflows/pipeline.ymlindex b179a47b11..c951021331 100644--- a/.github/workflows/pipeline.yml+++ b/.github/workflows/pipeline.yml@@ -442,6 +442,7 @@ jobs:LANGFUSE_LLM_CONNECTION_BEDROCK_ACCESS_KEY_ID: ${{ secrets.LANGFUSE_LLM_CONNECTION_BEDROCK_ACCESS_KEY_ID }}LANGFUSE_LLM_CONNECTION_BEDROCK_SECRET_ACCESS_KEY: ${{ secrets.LANGFUSE_LLM_CONNECTION_BEDROCK_SECRET_ACCESS_KEY }}LANGFUSE_LLM_CONNECTION_BEDROCK_REGION: ${{ secrets.LANGFUSE_LLM_CONNECTION_BEDROCK_REGION }}+ LANGFUSE_LLM_CONNECTION_BEDROCK_API_KEY: ${{ secrets.LANGFUSE_LLM_CONNECTION_BEDROCK_API_KEY }}LANGFUSE_LLM_CONNECTION_VERTEXAI_KEY: ${{ secrets.LANGFUSE_LLM_CONNECTION_VERTEXAI_KEY }}LANGFUSE_LLM_CONNECTION_GOOGLEAISTUDIO_KEY: ${{ secrets.LANGFUSE_LLM_CONNECTION_GOOGLEAISTUDIO_KEY }}diff --git a/packages/shared/src/interfaces/customLLMProviderConfigSchemas.ts b/packages/shared/src/interfaces/customLLMProviderConfigSchemas.tsindex b765621fb7..db5f399247 100644--- a/packages/shared/src/interfaces/customLLMProviderConfigSchemas.ts+++ b/packages/shared/src/interfaces/customLLMProviderConfigSchemas.ts@@ -11,12 +11,25 @@ export const VERTEXAI_USE_DEFAULT_CREDENTIALS =export const BedrockConfigSchema = z.object({ region: z.string() });export type BedrockConfig = z.infer<typeof BedrockConfigSchema>;-export const BedrockCredentialSchema = z+export const BedrockAccessKeysSchema = z.object({- accessKeyId: z.string(),- secretAccessKey: z.string(),+ accessKeyId: z.string().min(1),+ secretAccessKey: z.string().min(1),})- .optional();+ .strict();+export type BedrockAccessKeys = z.infer<typeof BedrockAccessKeysSchema>;++export const BedrockApiKeySchema = z+ .object({+ apiKey: z.string().min(1),+ })+ .strict();+export type BedrockApiKey = z.infer<typeof BedrockApiKeySchema>;++export const BedrockCredentialSchema = z.union([+ BedrockAccessKeysSchema,+ BedrockApiKeySchema,+]);export type BedrockCredential = z.infer<typeof BedrockCredentialSchema>;export const VertexAIConfigSchema = zdiff --git a/packages/shared/src/server/llm/fetchLLMCompletion.ts b/packages/shared/src/server/llm/fetchLLMCompletion.tsindex e217ccd727..f7b519ad8f 100644--- a/packages/shared/src/server/llm/fetchLLMCompletion.ts+++ b/packages/shared/src/server/llm/fetchLLMCompletion.ts@@ -19,6 +19,7 @@ import { IterableReadableStream } from "@langchain/core/utils/stream";import { ChatOpenAI, AzureChatOpenAI } from "@langchain/openai";import { env } from "../../env";import GCPServiceAccountKeySchema, {+ BedrockAccessKeysSchema,BedrockConfigSchema,BedrockCredentialSchema,VertexAIConfigSchema,@@ -90,6 +91,52 @@ const googleProviderOptionsSchema = z}).optional();+// For using Bedrock API key in Bearer token format+const createBedrockBearerAuth = (token: string) => ({+ clientOptions: {+ token: { token },+ authSchemePreference: ["httpBearerAuth"],+ },+});++export function resolveBedrockAuth(params: {+ secretKey: string;+ allowDefaultCredentials: boolean;+}): {+ credentials?: z.infer<typeof BedrockAccessKeysSchema>;+ clientOptions?: {+ token: { token: string };+ authSchemePreference: string[];+ };+} {+ const { secretKey, allowDefaultCredentials } = params;++ if (+ secretKey === BEDROCK_USE_DEFAULT_CREDENTIALS &&+ allowDefaultCredentials+ ) {+ return {};+ }++ try {+ const parsedCredential = BedrockCredentialSchema.parse(+ JSON.parse(secretKey),+ );++ if ("apiKey" in parsedCredential) {+ return createBedrockBearerAuth(parsedCredential.apiKey);+ }++ return {+ credentials: parsedCredential,+ };+ } catch {+ throw new Error(+ "Invalid Bedrock credentials. Expected AWS access key JSON or a Bedrock API key.",+ );+ }+}+type ProcessTracedEvents = () => Promise<void>;type LLMCompletionParams = {@@ -363,16 +410,16 @@ export async function fetchLLMCompletion(// Handle both explicit credentials and default provider chain// Only allow default provider chain in self-hosted or internal AI featuresconst isSelfHosted = !isLangfuseCloud;- const credentials =- apiKey === BEDROCK_USE_DEFAULT_CREDENTIALS &&- (isSelfHosted || shouldUseLangfuseAPIKey)- ? undefined // undefined = use AWS SDK default credential provider chain- : BedrockCredentialSchema.parse(JSON.parse(apiKey));+ const { credentials, clientOptions } = resolveBedrockAuth({+ secretKey: apiKey,+ allowDefaultCredentials: isSelfHosted || shouldUseLangfuseAPIKey,+ });chatModel = new ChatBedrockConverse({model: modelParams.model,region,credentials,+ clientOptions,temperature: modelParams.temperature,maxTokens: modelParams.max_tokens,topP: modelParams.top_p,diff --git a/web/src/__tests__/server/llm-api-key.servertest.ts b/web/src/__tests__/server/llm-api-key.servertest.tsindex 69f8273f89..8c6ec2b7b7 100644--- a/web/src/__tests__/server/llm-api-key.servertest.ts+++ b/web/src/__tests__/server/llm-api-key.servertest.ts@@ -9,11 +9,13 @@ jest.mock("@langfuse/shared/src/server", () => {});import type { Session } from "next-auth";-import { LLMAdapter } from "@langfuse/shared";+import { BEDROCK_USE_DEFAULT_CREDENTIALS, LLMAdapter } from "@langfuse/shared";+import { env } from "@/src/env.mjs";import { prisma } from "@langfuse/shared/src/db";import { appRouter } from "@/src/server/api/root";import { createInnerTRPCContext } from "@/src/server/api/trpc";import { decrypt, encrypt } from "@langfuse/shared/encryption";+import { AuthMethod } from "@/src/features/llm-api-key/types";import {createOrgProjectAndApiKey,fetchLLMCompletion,@@ -140,6 +142,49 @@ describe("llmApiKey.all RPC", () => {expect(llmApiKeys[0].displaySecretKey).toMatch(/^...[a-zA-Z0-9]{4}$/);});+ it("should create a Bedrock llm api key with a Bedrock API key", async () => {+ const secret = "bedrock-api-key-1234";++ await caller.llmApiKey.create({+ projectId,+ secretKey: JSON.stringify({ apiKey: secret }),+ provider: "bedrock",+ adapter: LLMAdapter.Bedrock,+ customModels: ["us.anthropic.claude-3-5-sonnet-20240620-v1:0"],+ withDefaultModels: false,+ config: { region: "us-east-1" },+ });++ const llmApiKey = await prisma.llmApiKeys.findFirstOrThrow({+ where: {+ projectId,+ provider: "bedrock",+ },+ });++ expect(decrypt(llmApiKey.secretKey)).toBe(+ JSON.stringify({+ apiKey: secret,+ }),+ );+ expect(llmApiKey.displaySecretKey).toBe("...1234");+ expect(llmApiKey.config).toEqual({ region: "us-east-1" });+ });++ it("should reject creating a Bedrock key with invalid secret key JSON", async () => {+ await expect(+ caller.llmApiKey.create({+ projectId,+ secretKey: JSON.stringify({ unknownField: "value" }),+ provider: "bedrock",+ adapter: LLMAdapter.Bedrock,+ customModels: ["us.anthropic.claude-3-5-sonnet-20240620-v1:0"],+ withDefaultModels: false,+ config: { region: "us-east-1" },+ }),+ ).rejects.toThrow("Invalid Bedrock credentials");+ });+it("should block creating an llm api key with a localhost base URL", async () => {await expect(caller.llmApiKey.create({@@ -199,6 +244,87 @@ describe("llmApiKey.all RPC", () => {expect(secretKey).toBeUndefined();});+ it("should derive the Bedrock auth method in llmApiKey.all without returning secrets", async () => {+ await prisma.llmApiKeys.createMany({+ data: [+ {+ projectId,+ provider: "bedrock-access",+ adapter: LLMAdapter.Bedrock,+ secretKey: encrypt(+ JSON.stringify({+ accessKeyId: "AKIAIOSFODNN7EXAMPLE",+ secretAccessKey: "wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY",+ }),+ ),+ displaySecretKey: "...MPLE",+ customModels: ["us.anthropic.claude-3-5-sonnet-20240620-v1:0"],+ withDefaultModels: false,+ extraHeaderKeys: [],+ config: { region: "us-east-1" },+ },+ {+ projectId,+ provider: "bedrock-api",+ adapter: LLMAdapter.Bedrock,+ secretKey: encrypt(+ JSON.stringify({+ apiKey: "bedrock-api-key-1234",+ }),+ ),+ displaySecretKey: "...1234",+ customModels: ["us.anthropic.claude-3-5-sonnet-20240620-v1:0"],+ withDefaultModels: false,+ extraHeaderKeys: [],+ config: { region: "us-east-1" },+ },+ {+ projectId,+ provider: "bedrock-default",+ adapter: LLMAdapter.Bedrock,+ secretKey: encrypt(BEDROCK_USE_DEFAULT_CREDENTIALS),+ displaySecretKey: "Default AWS credentials",+ customModels: ["us.anthropic.claude-3-5-sonnet-20240620-v1:0"],+ withDefaultModels: false,+ extraHeaderKeys: [],+ config: { region: "us-east-1" },+ },+ {+ projectId,+ provider: "openai",+ adapter: LLMAdapter.OpenAI,+ secretKey: encrypt("sk-test"),+ displaySecretKey: "...test",+ customModels: [],+ withDefaultModels: true,+ extraHeaderKeys: [],+ },+ ],+ });++ const { data: llmApiKeys } = await caller.llmApiKey.all({+ projectId,+ });++ expect(+ llmApiKeys.find((key) => key.provider === "bedrock-access")?.authMethod,+ ).toBe(AuthMethod.AccessKeys);+ expect(+ llmApiKeys.find((key) => key.provider === "bedrock-api")?.authMethod,+ ).toBe(AuthMethod.ApiKey);+ expect(+ llmApiKeys.find((key) => key.provider === "bedrock-default")?.authMethod,+ ).toBe(AuthMethod.DefaultCredentials);+ expect(+ llmApiKeys.find((key) => key.provider === "openai")?.authMethod,+ ).toBeUndefined();+ expect(+ llmApiKeys.every(+ (key) => key.secretKey === undefined && key.extraHeaders === undefined,+ ),+ ).toBe(true);+ });+it("should require llmApiKeys:create access for testing a new llm api key", async () => {const memberCaller = createCallerForProjectRole("MEMBER");@@ -448,6 +574,287 @@ describe("llmApiKey.all RPC", () => {expect(updatedKeys[0].withDefaultModels).toBe(newWithDefaultModels);});+ it("should update a Bedrock Access key auth to a Bedrock API key", async () => {+ const provider = "bedrock";++ await caller.llmApiKey.create({+ projectId,+ provider,+ adapter: LLMAdapter.Bedrock,+ secretKey: JSON.stringify({+ accessKeyId: "AKIAIOSFODNN7EXAMPLE",+ secretAccessKey: "wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY",+ }),+ customModels: ["us.anthropic.claude-3-5-sonnet-20240620-v1:0"],+ withDefaultModels: false,+ config: { region: "us-east-1" },+ });++ const existingKey = await prisma.llmApiKeys.findFirstOrThrow({+ where: {+ projectId,+ provider,+ },+ });++ await caller.llmApiKey.update({+ id: existingKey.id,+ projectId,+ provider,+ adapter: LLMAdapter.Bedrock,+ secretKey: JSON.stringify({ apiKey: "bedrock-api-key-5678" }),+ customModels: ["us.anthropic.claude-3-5-sonnet-20240620-v1:0"],+ withDefaultModels: false,+ config: { region: "eu-west-1" },+ });++ const updatedKey = await prisma.llmApiKeys.findUniqueOrThrow({+ where: { id: existingKey.id },+ });++ expect(decrypt(updatedKey.secretKey)).toBe(+ JSON.stringify({+ apiKey: "bedrock-api-key-5678",+ }),+ );+ expect(updatedKey.displaySecretKey).toBe("...5678");+ expect(updatedKey.config).toEqual({ region: "eu-west-1" });+ });++ it("should update a Bedrock API key auth to Access keys", async () => {+ const provider = "bedrock";++ await caller.llmApiKey.create({+ projectId,+ provider,+ adapter: LLMAdapter.Bedrock,+ secretKey: JSON.stringify({ apiKey: "bedrock-api-key-1234" }),+ customModels: ["us.anthropic.claude-3-5-sonnet-20240620-v1:0"],+ withDefaultModels: false,+ config: { region: "us-east-1" },+ });++ const existingKey = await prisma.llmApiKeys.findFirstOrThrow({+ where: { projectId, provider },+ });++ await caller.llmApiKey.update({+ id: existingKey.id,+ projectId,+ provider,+ adapter: LLMAdapter.Bedrock,+ secretKey: JSON.stringify({+ accessKeyId: "AKIAIOSFODNN7EXAMPLE",+ secretAccessKey: "wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY",+ }),+ customModels: ["us.anthropic.claude-3-5-sonnet-20240620-v1:0"],+ withDefaultModels: false,+ config: { region: "eu-west-1" },+ });++ const updatedKey = await prisma.llmApiKeys.findUniqueOrThrow({+ where: { id: existingKey.id },+ });++ expect(decrypt(updatedKey.secretKey)).toBe(+ JSON.stringify({+ accessKeyId: "AKIAIOSFODNN7EXAMPLE",+ secretAccessKey: "wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY",+ }),+ );+ expect(updatedKey.displaySecretKey).toBe("...EKEY");+ expect(updatedKey.config).toEqual({ region: "eu-west-1" });+ });++ it("should update a Bedrock DefaultCredentials key to explicit Access keys", async () => {+ const provider = "bedrock";+ const originalRegion = env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION;++ try {+ // Simulate self-hosted to allow default credentials+ (env as any).NEXT_PUBLIC_LANGFUSE_CLOUD_REGION = undefined;++ await caller.llmApiKey.create({+ projectId,+ provider,+ adapter: LLMAdapter.Bedrock,+ secretKey: BEDROCK_USE_DEFAULT_CREDENTIALS,+ customModels: ["us.anthropic.claude-3-5-sonnet-20240620-v1:0"],+ withDefaultModels: false,+ config: { region: "us-east-1" },+ });++ const existingKey = await prisma.llmApiKeys.findFirstOrThrow({+ where: { projectId, provider },+ });++ expect(decrypt(existingKey.secretKey)).toBe(+ BEDROCK_USE_DEFAULT_CREDENTIALS,+ );+ expect(existingKey.displaySecretKey).toBe("Default AWS credentials");++ await caller.llmApiKey.update({+ id: existingKey.id,+ projectId,+ provider,+ adapter: LLMAdapter.Bedrock,+ secretKey: JSON.stringify({+ accessKeyId: "AKIAIOSFODNN7EXAMPLE",+ secretAccessKey: "wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY",+ }),+ customModels: ["us.anthropic.claude-3-5-sonnet-20240620-v1:0"],+ withDefaultModels: false,+ config: { region: "eu-west-1" },+ });++ const updatedKey = await prisma.llmApiKeys.findUniqueOrThrow({+ where: { id: existingKey.id },+ });++ expect(decrypt(updatedKey.secretKey)).toBe(+ JSON.stringify({+ accessKeyId: "AKIAIOSFODNN7EXAMPLE",+ secretAccessKey: "wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY",+ }),+ );+ expect(updatedKey.displaySecretKey).toBe("...EKEY");+ expect(updatedKey.config).toEqual({ region: "eu-west-1" });+ } finally {+ (env as any).NEXT_PUBLIC_LANGFUSE_CLOUD_REGION = originalRegion;+ }+ });++ it("should update a Bedrock DefaultCredentials key to a Bedrock API key", async () => {+ const provider = "bedrock";+ const originalRegion = env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION;++ try {+ // Simulate self-hosted to allow default credentials+ (env as any).NEXT_PUBLIC_LANGFUSE_CLOUD_REGION = undefined;++ await caller.llmApiKey.create({+ projectId,+ provider,+ adapter: LLMAdapter.Bedrock,+ secretKey: BEDROCK_USE_DEFAULT_CREDENTIALS,+ customModels: ["us.anthropic.claude-3-5-sonnet-20240620-v1:0"],+ withDefaultModels: false,+ config: { region: "us-east-1" },+ });++ const existingKey = await prisma.llmApiKeys.findFirstOrThrow({+ where: { projectId, provider },+ });++ await caller.llmApiKey.update({+ id: existingKey.id,+ projectId,+ provider,+ adapter: LLMAdapter.Bedrock,+ secretKey: JSON.stringify({ apiKey: "bedrock-api-key-9999" }),+ customModels: ["us.anthropic.claude-3-5-sonnet-20240620-v1:0"],+ withDefaultModels: false,+ config: { region: "eu-west-1" },+ });++ const updatedKey = await prisma.llmApiKeys.findUniqueOrThrow({+ where: { id: existingKey.id },+ });++ expect(decrypt(updatedKey.secretKey)).toBe(+ JSON.stringify({ apiKey: "bedrock-api-key-9999" }),+ );+ expect(updatedKey.displaySecretKey).toBe("...9999");+ expect(updatedKey.config).toEqual({ region: "eu-west-1" });+ } finally {+ (env as any).NEXT_PUBLIC_LANGFUSE_CLOUD_REGION = originalRegion;+ }+ });++ it("should reject updating a Bedrock key back to DefaultCredentials on cloud", async () => {+ const provider = "bedrock";++ await caller.llmApiKey.create({+ projectId,+ provider,+ adapter: LLMAdapter.Bedrock,+ secretKey: JSON.stringify({+ accessKeyId: "AKIAIOSFODNN7EXAMPLE",+ secretAccessKey: "wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY",+ }),+ customModels: ["us.anthropic.claude-3-5-sonnet-20240620-v1:0"],+ withDefaultModels: false,+ config: { region: "us-east-1" },+ });++ const existingKey = await prisma.llmApiKeys.findFirstOrThrow({+ where: { projectId, provider },+ });++ await expect(+ caller.llmApiKey.update({+ id: existingKey.id,+ projectId,+ provider,+ adapter: LLMAdapter.Bedrock,+ secretKey: BEDROCK_USE_DEFAULT_CREDENTIALS,+ customModels: ["us.anthropic.claude-3-5-sonnet-20240620-v1:0"],+ withDefaultModels: false,+ config: { region: "eu-west-1" },+ }),+ ).rejects.toThrow(+ "Default AWS credentials are only allowed for Bedrock in self-hosted deployments",+ );+ });++ it("should update a Bedrock Access key auth back to DefaultCredentials (self-hosted)", async () => {+ const provider = "bedrock";+ const originalRegion = env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION;++ await caller.llmApiKey.create({+ projectId,+ provider,+ adapter: LLMAdapter.Bedrock,+ secretKey: JSON.stringify({+ accessKeyId: "AKIAIOSFODNN7EXAMPLE",+ secretAccessKey: "wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY",+ }),+ customModels: ["us.anthropic.claude-3-5-sonnet-20240620-v1:0"],+ withDefaultModels: false,+ config: { region: "us-east-1" },+ });++ const existingKey = await prisma.llmApiKeys.findFirstOrThrow({+ where: { projectId, provider },+ });++ try {+ // Simulate self-hosted deployment where default credentials are allowed+ (env as any).NEXT_PUBLIC_LANGFUSE_CLOUD_REGION = undefined;++ await caller.llmApiKey.update({+ id: existingKey.id,+ projectId,+ provider,+ adapter: LLMAdapter.Bedrock,+ secretKey: BEDROCK_USE_DEFAULT_CREDENTIALS,+ customModels: ["us.anthropic.claude-3-5-sonnet-20240620-v1:0"],+ withDefaultModels: false,+ config: { region: "eu-west-1" },+ });+ } finally {+ (env as any).NEXT_PUBLIC_LANGFUSE_CLOUD_REGION = originalRegion;+ }++ const updatedKey = await prisma.llmApiKeys.findUniqueOrThrow({+ where: { id: existingKey.id },+ });++ expect(decrypt(updatedKey.secretKey)).toBe(BEDROCK_USE_DEFAULT_CREDENTIALS);+ expect(updatedKey.displaySecretKey).toBe("Default AWS credentials");+ expect(updatedKey.config).toEqual({ region: "eu-west-1" });+ });+it("should update only the secret key", async () => {const secret = "test-secret";const provider = "openai";diff --git a/web/src/__tests__/server/llm-connections-api.servertest.ts b/web/src/__tests__/server/llm-connections-api.servertest.tsindex 3b255af343..ffaad4062f 100644--- a/web/src/__tests__/server/llm-connections-api.servertest.ts+++ b/web/src/__tests__/server/llm-connections-api.servertest.ts@@ -577,6 +577,26 @@ describe("/api/public/llm-connections API Endpoints", () => {expect(bedrockResponse.body.adapter).toBe(LLMAdapter.Bedrock);expect(bedrockResponse.body.config).toEqual({ region: "us-east-1" });+ const bedrockApiKeyResponse = await makeZodVerifiedAPICall(+ PutLlmConnectionV1Response,+ "PUT",+ "/api/public/llm-connections",+ {+ provider: generateUniqueProvider("test-bedrock-api-key"),+ adapter: LLMAdapter.Bedrock,+ secretKey: JSON.stringify({ apiKey: "bedrock-api-key-1234" }),+ config: { region: "us-east-1" },+ },+ auth,+ 201,+ );+ expect(bedrockApiKeyResponse.status).toBe(201);+ expect(bedrockApiKeyResponse.body.adapter).toBe(LLMAdapter.Bedrock);+ expect(bedrockApiKeyResponse.body.displaySecretKey).toBe("...1234");+ expect(bedrockApiKeyResponse.body.config).toEqual({+ region: "us-east-1",+ });+// VertexAI works with or without configconst vertexResponse = await makeZodVerifiedAPICall(PutLlmConnectionV1Response,@@ -904,6 +924,41 @@ describe("/api/public/llm-connections API Endpoints", () => {expect(dbConnection?.config).toEqual({ region: "us-east-1" });});+ it("should create Bedrock connection with a Bedrock API key", async () => {+ const createData = {+ provider: generateUniqueProvider("bedrock-api-key-config-test"),+ adapter: LLMAdapter.Bedrock,+ secretKey: JSON.stringify({ apiKey: "bedrock-api-key-9876" }),+ config: {+ region: "us-west-2",+ },+ };++ const response = await makeZodVerifiedAPICall(+ PutLlmConnectionV1Response,+ "PUT",+ "/api/public/llm-connections",+ createData,+ auth,+ 201,+ );++ expect(response.status).toBe(201);+ expect(response.body.displaySecretKey).toBe("...9876");+ expect(response.body.config).toEqual({ region: "us-west-2" });++ const dbConnection = await prisma.llmApiKeys.findUnique({+ where: {+ projectId_provider: {+ projectId,+ provider: createData.provider,+ },+ },+ });++ expect(dbConnection?.displaySecretKey).toBe("...9876");+ });+it("should reject Bedrock connection without config", async () => {const createData = {provider: generateUniqueProvider("bedrock-no-config"),@@ -954,6 +1009,48 @@ describe("/api/public/llm-connections API Endpoints", () => {);});+ it("should reject Bedrock connection with default credentials sentinel on cloud", async () => {+ const createData = {+ provider: generateUniqueProvider("bedrock-default-creds"),+ adapter: LLMAdapter.Bedrock,+ secretKey: "__BEDROCK_DEFAULT_CREDENTIALS__",+ config: { region: "us-east-1" },+ };++ const response = await makeAPICall(+ "PUT",+ "/api/public/llm-connections",+ createData,+ auth,+ );++ expect(response.status).toBe(400);+ expect(JSON.stringify(response.body)).toContain(+ "Default AWS credentials are only allowed for Bedrock in self-hosted deployments",+ );+ });++ it("should reject Bedrock connection with invalid credential JSON", async () => {+ const createData = {+ provider: generateUniqueProvider("bedrock-invalid-creds"),+ adapter: LLMAdapter.Bedrock,+ secretKey: JSON.stringify({ unknownField: "value" }),+ config: { region: "us-east-1" },+ };++ const response = await makeAPICall(+ "PUT",+ "/api/public/llm-connections",+ createData,+ auth,+ );++ expect(response.status).toBe(400);+ expect(JSON.stringify(response.body)).toContain(+ "Invalid Bedrock credentials",+ );+ });+it("should create VertexAI connection with location config", async () => {const createData = {provider: generateUniqueProvider("vertexai-config-test"),diff --git a/web/src/features/llm-api-key/server/router.ts b/web/src/features/llm-api-key/server/router.tsindex 12ef416413..19355a6f84 100644--- a/web/src/features/llm-api-key/server/router.ts+++ b/web/src/features/llm-api-key/server/router.ts@@ -1,8 +1,11 @@import { z } from "zod";import { auditLog } from "@/src/features/audit-logs/auditLog";import {+ AuthMethod,CreateLlmApiKey,UpdateLlmApiKey,+ SafeLlmApiKeySchema,+ type BedrockAuthMethod,} from "@/src/features/llm-api-key/types";import { throwIfNoProjectAccess } from "@/src/features/rbac/utils/checkProjectAccess";import {@@ -12,11 +15,11 @@ import {} from "@/src/server/api/trpc";import {type ChatMessage,- LLMApiKeySchema,ChatMessageRole,supportedModels,GCPServiceAccountKeySchema,BedrockConfigSchema,+ BedrockCredentialSchema,VertexAIConfigSchema,BEDROCK_USE_DEFAULT_CREDENTIALS,VERTEXAI_USE_DEFAULT_CREDENTIALS,@@ -50,6 +53,40 @@ export function getDisplaySecretKey(secretKey: string) {: "..." + secretKey.slice(-4);}+export function validateBedrockSecretKey(secretKey: string) {+ if (secretKey === BEDROCK_USE_DEFAULT_CREDENTIALS) {+ return;+ }++ try {+ BedrockCredentialSchema.parse(JSON.parse(secretKey));+ } catch {+ throw new Error(+ "Invalid Bedrock credentials. Expected a JSON object with either {accessKeyId, secretAccessKey} or {apiKey}.",+ );+ }+}++function getBedrockAuthMethod(+ secretKey: string,+): BedrockAuthMethod | undefined {+ if (secretKey === BEDROCK_USE_DEFAULT_CREDENTIALS) {+ return AuthMethod.DefaultCredentials;+ }++ try {+ const parsed = BedrockCredentialSchema.parse(JSON.parse(secretKey));+ return parsed && "apiKey" in parsed+ ? AuthMethod.ApiKey+ : AuthMethod.AccessKeys;+ } catch (error) {+ logger.warn("Failed to derive Bedrock auth method from stored secret", {+ error,+ });+ return undefined;+ }+}+type TestLLMConnectionParams = {adapter: LLMAdapter;provider: string;@@ -180,6 +217,18 @@ export const llmApiKeyRouter = createTRPCRouter({}}+ if (input.adapter === LLMAdapter.Bedrock) {+ try {+ validateBedrockSecretKey(input.secretKey);+ } catch (e) {+ throw new TRPCError({+ code: "BAD_REQUEST",+ message:+ e instanceof Error ? e.message : "Invalid Bedrock credentials.",+ });+ }+ }+if (input.secretKey === VERTEXAI_USE_DEFAULT_CREDENTIALS) {if (isLangfuseCloud || input.adapter !== LLMAdapter.VertexAI) {throw new TRPCError({@@ -381,35 +430,39 @@ export const llmApiKeyRouter = createTRPCRouter({scope: "llmApiKeys:read",});- const apiKeys = z- .array(- LLMApiKeySchema.extend({- secretKey: z.undefined(),- extraHeaders: z.undefined(),- }),- )- .parse(- await ctx.prisma.llmApiKeys.findMany({- // we must not return the secret key AND extra headers via the API, hence not selected- select: {- id: true,- createdAt: true,- updatedAt: true,- provider: true,- displaySecretKey: true,- projectId: true,- adapter: true,- baseURL: true,- customModels: true,- withDefaultModels: true,- extraHeaderKeys: true,- config: true,- },- where: {- projectId: input.projectId,- },- }),- );+ const storedApiKeys = await ctx.prisma.llmApiKeys.findMany({+ // secretKey is selected server-side only to derive a safe auth-method enum for Bedrock+ select: {+ id: true,+ createdAt: true,+ updatedAt: true,+ provider: true,+ displaySecretKey: true,+ projectId: true,+ adapter: true,+ baseURL: true,+ customModels: true,+ withDefaultModels: true,+ extraHeaderKeys: true,+ config: true,+ secretKey: true,+ },+ where: {+ projectId: input.projectId,+ },+ });++ const apiKeys = z.array(SafeLlmApiKeySchema).parse(+ storedApiKeys.map(({ secretKey, ...apiKey }) => ({+ ...apiKey,+ secretKey: undefined,+ extraHeaders: undefined,+ authMethod:+ apiKey.adapter === LLMAdapter.Bedrock+ ? getBedrockAuthMethod(decrypt(secretKey))+ : undefined,+ })),+ );const count = await ctx.prisma.llmApiKeys.count({where: {@@ -593,6 +646,18 @@ export const llmApiKeyRouter = createTRPCRouter({}}+ if (input.secretKey && input.adapter === LLMAdapter.Bedrock) {+ try {+ validateBedrockSecretKey(input.secretKey);+ } catch (e) {+ throw new TRPCError({+ code: "BAD_REQUEST",+ message:+ e instanceof Error ? e.message : "Invalid Bedrock credentials.",+ });+ }+ }+if (input.secretKey === VERTEXAI_USE_DEFAULT_CREDENTIALS) {if (isLangfuseCloud || input.adapter !== LLMAdapter.VertexAI) {throw new TRPCError({diff --git a/web/src/features/llm-api-key/types.ts b/web/src/features/llm-api-key/types.tsindex b96747bb03..62c7f4ba10 100644--- a/web/src/features/llm-api-key/types.ts+++ b/web/src/features/llm-api-key/types.ts@@ -3,6 +3,7 @@ import {LLMAdapter,BedrockConfigSchema,VertexAIConfigSchema,+ LLMApiKeySchema,} from "@langfuse/shared";export const LlmApiKeySchema = z.object({@@ -33,3 +34,25 @@ export const UpdateLlmApiKey = LlmApiKeySchema.extend({),id: z.string(),});++export const AuthMethod = {+ ApiKey: "api-key",+ AccessKeys: "access-keys",+ DefaultCredentials: "default-credentials",+} as const;++export const BedrockAuthMethodSchema = z.enum([+ AuthMethod.ApiKey,+ AuthMethod.AccessKeys,+ AuthMethod.DefaultCredentials,+]);++export type BedrockAuthMethod = z.infer<typeof BedrockAuthMethodSchema>;++export const SafeLlmApiKeySchema = LLMApiKeySchema.extend({+ secretKey: z.undefined(),+ extraHeaders: z.undefined(),+ authMethod: BedrockAuthMethodSchema.optional(),+});++export type SafeLlmApiKey = z.infer<typeof SafeLlmApiKeySchema>;diff --git a/web/src/features/public-api/components/CreateLLMApiKeyForm.tsx b/web/src/features/public-api/components/CreateLLMApiKeyForm.tsxindex f868bc1e2b..d5a43579a3 100644--- a/web/src/features/public-api/components/CreateLLMApiKeyForm.tsx+++ b/web/src/features/public-api/components/CreateLLMApiKeyForm.tsx@@ -2,11 +2,11 @@ import { useFieldArray, useForm } from "react-hook-form";import { useState } from "react";import { zodResolver } from "@hookform/resolvers/zod";import {+ type BedrockApiKey,+ type BedrockAccessKeys,type BedrockConfig,- type BedrockCredential,type VertexAIConfig,LLMAdapter,- type LlmApiKeys,BEDROCK_USE_DEFAULT_CREDENTIALS,VERTEXAI_USE_DEFAULT_CREDENTIALS,} from "@langfuse/shared";@@ -31,20 +31,61 @@ import {SelectValue,} from "@/src/components/ui/select";import { Switch } from "@/src/components/ui/switch";-import { api } from "@/src/utils/api";+import { Tabs, TabsList, TabsTrigger } from "@/src/components/ui/tabs";+import { api, type RouterOutputs } from "@/src/utils/api";import { cn } from "@/src/utils/tailwind";import { usePostHogClientCapture } from "@/src/features/posthog-analytics/usePostHogClientCapture";import { type useUiCustomization } from "@/src/ee/features/ui-customization/useUiCustomization";import { DialogFooter } from "@/src/components/ui/dialog";import { DialogBody } from "@/src/components/ui/dialog";import { env } from "@/src/env.mjs";+import {+ AuthMethod,+ BedrockAuthMethodSchema,+ type BedrockAuthMethod,+} from "@/src/features/llm-api-key/types";const isLangfuseCloud = Boolean(env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION);const isCustomModelsRequired = (adapter: LLMAdapter) =>adapter === LLMAdapter.Azure || adapter === LLMAdapter.Bedrock;-const createFormSchema = (mode: "create" | "update") =>+const hasText = (value?: string) => Boolean(value?.trim());++/**+ * Whether the selected auth method matches the existing one (i.e. credentials+ * can be preserved on update). DefaultCredentials is grouped with AccessKeys+ * because both use SigV4-based authentication via the AWS SDK.+ */+const isMatchingBedrockAuthMethod = (+ newAuthMethod: BedrockAuthMethod,+ existingAuthMethod?: BedrockAuthMethod,+): boolean =>+ (newAuthMethod === AuthMethod.ApiKey &&+ existingAuthMethod === AuthMethod.ApiKey) ||+ (newAuthMethod === AuthMethod.AccessKeys &&+ (existingAuthMethod === AuthMethod.AccessKeys ||+ existingAuthMethod === AuthMethod.DefaultCredentials));++type LlmApiKeyListItem = RouterOutputs["llmApiKey"]["all"]["data"][number];++const getInitialBedrockAuthMethod = (params: {+ mode: "create" | "update";+ existingAuthMethod?: BedrockAuthMethod;+}): BedrockAuthMethod => {+ if (params.mode === "update") {+ return params.existingAuthMethod === AuthMethod.ApiKey+ ? AuthMethod.ApiKey+ : AuthMethod.AccessKeys;+ }++ return AuthMethod.AccessKeys;+};++const createFormSchema = (params: {+ mode: "create" | "update";+ existingAuthMethod?: BedrockAuthMethod;+}) =>z.object({secretKey: z.string().optional(),@@ -61,47 +102,80 @@ const createFormSchema = (mode: "create" | "update") =>customModels: z.array(z.object({ value: z.string().min(1) })),awsAccessKeyId: z.string().optional(),awsSecretAccessKey: z.string().optional(),+ bedrockApiKey: z.string().optional(),+ authMethod: BedrockAuthMethodSchema,awsRegion: z.string().optional(),vertexAILocation: z.string().optional(),extraHeaders: z.array(z.object({key: z.string().min(1),- value: mode === "create" ? z.string().min(1) : z.string().optional(),+ value:+ params.mode === "create"+ ? z.string().min(1)+ : z.string().optional(),}),),})- // 1) Bedrock validation - credentials required in create mode- .refine(- (data) => {- if (data.adapter !== LLMAdapter.Bedrock) return true;+ .superRefine((data, ctx) => {+ if (data.adapter !== LLMAdapter.Bedrock) return;- // In update mode, credentials are optional (existing ones are preserved)- if (mode === "update") {- // Only validate region is present- return data.awsRegion;+ const hasRegion = hasText(data.awsRegion);+ const hasAccessKeyId = hasText(data.awsAccessKeyId);+ const hasSecretAccessKey = hasText(data.awsSecretAccessKey);+ const hasBedrockApiKey = hasText(data.bedrockApiKey);+ const hasAnyAccessKeys = hasAccessKeyId || hasSecretAccessKey;+ const { authMethod } = data;+ const isUpdatingCurrentAuthMethod =+ params.mode === "update" &&+ isMatchingBedrockAuthMethod(authMethod, params.existingAuthMethod);++ if (!hasRegion) {+ ctx.addIssue({+ code: "custom",+ message: "AWS region is required.",+ path: ["awsRegion"],+ });+ }++ if (authMethod === AuthMethod.AccessKeys) {+ if (isUpdatingCurrentAuthMethod && !hasAnyAccessKeys) {+ return;}- // In create mode, validate credentials- // For cloud deployments, AWS credentials are required- if (isLangfuseCloud) {- return (- data.awsAccessKeyId && data.awsSecretAccessKey && data.awsRegion- );+ if (!isLangfuseCloud && !hasAnyAccessKeys) {+ return;}- // For self-hosted deployments, only region is required- return data.awsRegion;- },- {- message:- mode === "update"- ? "AWS region is required."- : isLangfuseCloud- ? "AWS credentials are required for Bedrock"- : "AWS region is required.",- path: ["adapter"],- },- )+ if (!hasAccessKeyId) {+ ctx.addIssue({+ code: "custom",+ message: "AWS Access Key ID is required.",+ path: ["awsAccessKeyId"],+ });+ }++ if (!hasSecretAccessKey) {+ ctx.addIssue({+ code: "custom",+ message: "AWS Secret Access Key is required.",+ path: ["awsSecretAccessKey"],+ });+ }+ return;+ }++ if (isUpdatingCurrentAuthMethod && !hasBedrockApiKey) {+ return;+ }++ if (!hasBedrockApiKey) {+ ctx.addIssue({+ code: "custom",+ message: "Bedrock API key is required.",+ path: ["bedrockApiKey"],+ });+ }+ }).refine((data) => {if (isCustomModelsRequired(data.adapter)) {@@ -134,7 +208,7 @@ const createFormSchema = (mode: "create" | "update") =>if (data.adapter !== LLMAdapter.VertexAI) return true;// In update mode, credentials are optional (existing ones are preserved)- if (mode === "update") return true;+ if (params.mode === "update") return true;// secretKey is required (either JSON key or VERTEXAI_USE_DEFAULT_CREDENTIALS sentinel)return !!data.secretKey;@@ -150,7 +224,7 @@ const createFormSchema = (mode: "create" | "update") =>(data) =>data.adapter === LLMAdapter.Bedrock ||data.adapter === LLMAdapter.VertexAI ||- mode === "update" ||+ params.mode === "update" ||data.secretKey,{message: "Secret key is required.",@@ -173,7 +247,7 @@ interface CreateLLMApiKeyFormProps {onSuccess: () => void;customization: ReturnType<typeof useUiCustomization>;mode?: "create" | "update";- existingKey?: LlmApiKeys;+ existingKey?: LlmApiKeyListItem;}export function CreateLLMApiKeyForm({@@ -222,7 +296,10 @@ export function CreateLLMApiKeyForm({}};- const formSchema = createFormSchema(mode);+ const formSchema = createFormSchema({+ mode,+ existingAuthMethod: existingKey?.authMethod,+ });const form = useForm({resolver: zodResolver(formSchema),@@ -254,6 +331,11 @@ export function CreateLLMApiKeyForm({: "",awsAccessKeyId: "",awsSecretAccessKey: "",+ bedrockApiKey: "",+ authMethod: getInitialBedrockAuthMethod({+ mode,+ existingAuthMethod: existingKey.authMethod,+ }),}: {adapter: defaultAdapter,@@ -267,10 +349,22 @@ export function CreateLLMApiKeyForm({awsRegion: "",awsAccessKeyId: "",awsSecretAccessKey: "",+ bedrockApiKey: "",+ authMethod: getInitialBedrockAuthMethod({+ mode,+ }),},});const currentAdapter = form.watch("adapter");+ const currentAuthMethod = form.watch("authMethod");+ const isKeepingCurrentBedrockAuthMethod =+ mode === "update" &&+ currentAdapter === LLMAdapter.Bedrock &&+ isMatchingBedrockAuthMethod(currentAuthMethod, existingKey?.authMethod);+ const isUsingDefaultAwsCredentialsForCurrentAuthMethod =+ currentAuthMethod === AuthMethod.AccessKeys &&+ existingKey?.authMethod === AuthMethod.DefaultCredentials;const hasAdvancedSettings = (adapter: LLMAdapter) =>adapter === LLMAdapter.OpenAI ||@@ -313,7 +407,7 @@ export function CreateLLMApiKeyForm({{currentAdapter === LLMAdapter.Bedrock && (<FormDescription className="text-dark-yellow">{- "For Bedrock, the model name is the Bedrock Inference Profile ID, e.g. 'eu.anthropic.claude-3-5-sonnet-20240620-v1:0'"+ "For Bedrock, the model name is the Bedrock Inference Profile ID, e.g. 'eu.anthropic.claude-sonnet-4-6'"}</FormDescription>)}@@ -434,33 +528,31 @@ export function CreateLLMApiKeyForm({let config: BedrockConfig | VertexAIConfig | undefined;if (currentAdapter === LLMAdapter.Bedrock) {- // In update mode, only update credentials if provided- if (mode === "update") {- // Only update secretKey if both credentials are provided- if (values.awsAccessKeyId && values.awsSecretAccessKey) {- const credentials: BedrockCredential = {- accessKeyId: values.awsAccessKeyId,- secretAccessKey: values.awsSecretAccessKey,- };- secretKey = JSON.stringify(credentials);- } else {- // Keep existing credentials by not setting secretKey- secretKey = undefined;- }- } else {- // In create mode, handle as before- if (- !isLangfuseCloud &&- (!values.awsAccessKeyId || !values.awsSecretAccessKey)- ) {- secretKey = BEDROCK_USE_DEFAULT_CREDENTIALS;- } else {- const credentials: BedrockCredential = {- accessKeyId: values.awsAccessKeyId ?? "",- secretAccessKey: values.awsSecretAccessKey ?? "",- };- secretKey = JSON.stringify(credentials);- }+ const shouldPreserveExistingBedrockCredentials =+ mode === "update" &&+ isMatchingBedrockAuthMethod(values.authMethod, existingKey?.authMethod);++ switch (values.authMethod) {+ case AuthMethod.ApiKey:+ secretKey =+ shouldPreserveExistingBedrockCredentials && !values.bedrockApiKey+ ? undefined+ : JSON.stringify({+ apiKey: values.bedrockApiKey!,+ } satisfies BedrockApiKey);+ break;+ case AuthMethod.AccessKeys:+ if (!values.awsAccessKeyId && !values.awsSecretAccessKey) {+ secretKey = shouldPreserveExistingBedrockCredentials+ ? undefined+ : BEDROCK_USE_DEFAULT_CREDENTIALS;+ } else {+ secretKey = JSON.stringify({+ accessKeyId: values.awsAccessKeyId!,+ secretAccessKey: values.awsSecretAccessKey!,+ } satisfies BedrockAccessKeys);+ }+ break;}config = {@@ -623,6 +715,48 @@ export function CreateLLMApiKeyForm({{/* API Key or AWS Credentials or Vertex AI Credentials */}{currentAdapter === LLMAdapter.Bedrock ? (<>+ <FormField+ control={form.control}+ name="authMethod"+ render={({ field }) => (+ <FormItem>+ <FormLabel>Authentication Method</FormLabel>+ <FormDescription>+ Select how Langfuse should authenticate to Bedrock.+ </FormDescription>+ <FormControl>+ <Tabs+ value={field.value}+ onValueChange={(value) =>+ field.onChange(value as BedrockAuthMethod)+ }+ className="w-full"+ >+ <TabsList+ className={cn(+ "grid h-auto w-full gap-1",+ "grid-cols-2",+ )}+ >+ <TabsTrigger+ value={AuthMethod.AccessKeys}+ className="text-xs"+ >+ AWS access keys+ </TabsTrigger>+ <TabsTrigger+ value={AuthMethod.ApiKey}+ className="text-xs"+ >+ API key+ </TabsTrigger>+ </TabsList>+ </Tabs>+ </FormControl>+ <FormMessage />+ </FormItem>+ )}+ /><FormFieldcontrol={form.control}name="awsRegion"@@ -657,110 +791,175 @@ export function CreateLLMApiKeyForm({</FormItem>)}/>- <FormField- control={form.control}- name="awsAccessKeyId"- render={({ field }) => (- <FormItem>- <FormLabel>- AWS Access Key ID- {!isLangfuseCloud && (- <span className="text-muted-foreground font-normal">- {" "}- (optional)- </span>- )}- </FormLabel>- <FormDescription>- {mode === "update"- ? "Leave empty to keep existing credentials. To update, provide both Access Key ID and Secret Access Key."- : isLangfuseCloud- ? "These should be long-lived credentials for an AWS user with `bedrock:InvokeModel` permission."- : "For self-hosted deployments, AWS credentials are optional. When omitted, authentication will use the AWS SDK default credential provider chain."}- </FormDescription>- <FormControl>- <Input- {...field}- placeholder={- mode === "update"- ? existingKey?.displaySecretKey ===- "Default AWS credentials"- ? "Using default AWS credentials"- : "•••••••• (existing credentials preserved if empty)"- : undefined- }- autoComplete="off"- data-1p-ignore- />- </FormControl>- <FormMessage />- </FormItem>- )}- />- <FormField- control={form.control}- name="awsSecretAccessKey"- render={({ field }) => (- <FormItem>- <FormLabel>- AWS Secret Access Key- {!isLangfuseCloud && (- <span className="text-muted-foreground font-normal">- {" "}- (optional)- </span>- )}- </FormLabel>- <FormControl>- <Input- {...field}- type="password"- placeholder={- mode === "update"- ? existingKey?.displaySecretKey ===- "Default AWS credentials"- ? "Using default AWS credentials"- : existingKey?.displaySecretKey- ? `${existingKey.displaySecretKey} (preserved if empty)`- : "•••••••• (existing credentials preserved if empty)"- : undefined- }- autoComplete="new-password"- data-1p-ignore- />- </FormControl>- <FormMessage />- </FormItem>- )}- />- {!isLangfuseCloud && (- <div className="text-muted-foreground space-y-2 border-l-2 border-blue-200 pl-4 text-sm">- <p>- <strong>Default credential provider chain:</strong> When AWS- credentials are omitted, the system will automatically check- for credentials in this order:- </p>- <ul className="ml-2 list-inside list-disc space-y-1">- <li>- Environment variables (AWS_ACCESS_KEY_ID,- AWS_SECRET_ACCESS_KEY)- </li>- <li>AWS credentials file (~/.aws/credentials)</li>- <li>IAM roles for EC2 instances</li>- <li>IAM roles for ECS tasks</li>- </ul>- <p>- <a- href="https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/setting-credentials-node.html"- target="_blank"- rel="noopener noreferrer"- className="text-blue-600 underline hover:text-blue-800"- >- Learn more about AWS credential providers →- </a>- </p>- </div>+ {currentAuthMethod === AuthMethod.ApiKey && (+ <FormField+ control={form.control}+ name="bedrockApiKey"+ render={({ field }) => (+ <FormItem>+ <FormLabel>Bedrock API Key</FormLabel>+ <FormDescription>+ {mode === "update" ? (+ <>+ Use{" "}+ <a+ href="https://docs.aws.amazon.com/bedrock/latest/userguide/api-keys.html"+ target="_blank"+ rel="noopener noreferrer"+ className="text-blue-600 underline hover:text-blue-800"+ >+ Amazon Bedrock API keys+ </a>{" "}+ to replace the current authentication.+ </>+ ) : (+ <>+ Use{" "}+ <a+ href="https://docs.aws.amazon.com/bedrock/latest/userguide/api-keys.html"+ target="_blank"+ rel="noopener noreferrer"+ className="text-blue-600 underline hover:text-blue-800"+ >+ Amazon Bedrock API keys+ </a>+ .+ </>+ )}+ </FormDescription>+ <FormControl>+ <Input+ {...field}+ type="password"+ placeholder={+ mode === "update"+ ? isKeepingCurrentBedrockAuthMethod &&+ existingKey?.displaySecretKey+ ? `${existingKey.displaySecretKey} (preserved unless replaced)`+ : "Enter Bedrock API key"+ : undefined+ }+ autoComplete="new-password"+ data-1p-ignore+ />+ </FormControl>+ <FormMessage />+ </FormItem>+ )}+ />+ )}+ {currentAuthMethod === AuthMethod.AccessKeys && (+ <>+ <FormField+ control={form.control}+ name="awsAccessKeyId"+ render={({ field }) => (+ <FormItem>+ <FormLabel>+ AWS Access Key ID+ {!isLangfuseCloud && (+ <span className="text-muted-foreground font-normal">+ {" "}+ (optional)+ </span>+ )}+ </FormLabel>+ <FormDescription>+ {mode === "update"+ ? isKeepingCurrentBedrockAuthMethod+ ? "Leave empty to keep existing credentials. To update, provide both Access Key ID and Secret Access Key."+ : "Provide both Access Key ID and Secret Access Key."+ : isLangfuseCloud+ ? "These should be long-lived credentials for an AWS user with `bedrock:InvokeModel` permission."+ : "For self-hosted deployments, AWS credentials are optional. When omitted, authentication will use the AWS SDK default credential provider chain."}+ </FormDescription>+ <FormControl>+ <Input+ {...field}+ placeholder={+ mode === "update"+ ? isUsingDefaultAwsCredentialsForCurrentAuthMethod+ ? "Using default AWS credentials"+ : isKeepingCurrentBedrockAuthMethod+ ? "•••••••• (existing credentials preserved if empty)"+ : "Enter AWS access key ID"+ : undefined+ }+ autoComplete="off"+ data-1p-ignore+ />+ </FormControl>+ <FormMessage />+ </FormItem>+ )}+ />+ <FormField+ control={form.control}+ name="awsSecretAccessKey"+ render={({ field }) => (+ <FormItem>+ <FormLabel>+ AWS Secret Access Key+ {!isLangfuseCloud && (+ <span className="text-muted-foreground font-normal">+ {" "}+ (optional)+ </span>+ )}+ </FormLabel>+ <FormControl>+ <Input+ {...field}+ type="password"+ placeholder={+ mode === "update"+ ? isUsingDefaultAwsCredentialsForCurrentAuthMethod+ ? "Using default AWS credentials"+ : isKeepingCurrentBedrockAuthMethod &&+ existingKey?.displaySecretKey+ ? `${existingKey.displaySecretKey} (preserved if empty)`+ : "Enter AWS secret access key"+ : undefined+ }+ autoComplete="new-password"+ data-1p-ignore+ />+ </FormControl>+ <FormMessage />+ </FormItem>+ )}+ />+ </>)}+ {!isLangfuseCloud &&+ currentAuthMethod === AuthMethod.AccessKeys && (+ <div className="text-muted-foreground space-y-2 border-l-2 border-blue-200 pl-4 text-sm">+ <p>+ <strong>Default credential provider chain:</strong> When+ AWS credentials are omitted, the system will automatically+ check for credentials in this order:+ </p>+ <ul className="ml-2 list-inside list-disc space-y-1">+ <li>+ Environment variables (AWS_ACCESS_KEY_ID,+ AWS_SECRET_ACCESS_KEY)+ </li>+ <li>AWS credentials file (~/.aws/credentials)</li>+ <li>IAM roles for EC2 instances</li>+ <li>IAM roles for ECS tasks</li>+ </ul>+ <p>+ <a+ href="https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/setting-credentials-node.html"+ target="_blank"+ rel="noopener noreferrer"+ className="text-blue-600 underline hover:text-blue-800"+ >+ Learn more about AWS credential providers →+ </a>+ </p>+ </div>+ )}</>) : currentAdapter === LLMAdapter.VertexAI ? (<>diff --git a/web/src/features/public-api/components/LLMApiKeyList.tsx b/web/src/features/public-api/components/LLMApiKeyList.tsxindex 0a86af6632..7359816c3d 100644--- a/web/src/features/public-api/components/LLMApiKeyList.tsx+++ b/web/src/features/public-api/components/LLMApiKeyList.tsx@@ -135,12 +135,7 @@ export function LlmApiKeyList(props: { projectId: string }) {onClick={(e) => e.stopPropagation()}><UpdateLLMApiKeyDialog- apiKey={{- ...apiKey,- secretKey: apiKey.displaySecretKey,- extraHeaders: apiKey.extraHeaderKeys.join(","),- config: apiKey.config ?? null,- }}+ apiKey={apiKey}projectId={props.projectId}open={editingKeyId === apiKey.id}onOpenChange={(open: boolean) => {diff --git a/web/src/features/public-api/components/UpdateLLMApiKeyDialog.tsx b/web/src/features/public-api/components/UpdateLLMApiKeyDialog.tsxindex 91b84dd5b8..a977ed0892 100644--- a/web/src/features/public-api/components/UpdateLLMApiKeyDialog.tsx+++ b/web/src/features/public-api/components/UpdateLLMApiKeyDialog.tsx@@ -9,9 +9,11 @@ import {} from "@/src/components/ui/dialog";import { CreateLLMApiKeyForm } from "./CreateLLMApiKeyForm";import { useUiCustomization } from "@/src/ee/features/ui-customization/useUiCustomization";-import { type LlmApiKeys } from "@langfuse/shared";import { useHasProjectAccess } from "@/src/features/rbac/utils/checkProjectAccess";import { PencilIcon } from "lucide-react";+import { type RouterOutputs } from "@/src/utils/api";++type LlmApiKeyListItem = RouterOutputs["llmApiKey"]["all"]["data"][number];export function UpdateLLMApiKeyDialog({apiKey,@@ -19,7 +21,7 @@ export function UpdateLLMApiKeyDialog({open,onOpenChange,}: {- apiKey: LlmApiKeys;+ apiKey: LlmApiKeyListItem;projectId: string;open?: boolean;onOpenChange?: (open: boolean) => void;diff --git a/web/src/features/public-api/types/llm-connections.ts b/web/src/features/public-api/types/llm-connections.tsindex 84efe04cc0..510fedb909 100644--- a/web/src/features/public-api/types/llm-connections.ts+++ b/web/src/features/public-api/types/llm-connections.ts@@ -1,6 +1,13 @@import { z } from "zod";-import { paginationZod, LLMAdapter, type JSONValue } from "@langfuse/shared";-import { BedrockConfigSchema, VertexAIConfigSchema } from "@langfuse/shared";+import {+ paginationZod,+ LLMAdapter,+ type JSONValue,+ BedrockConfigSchema,+ BedrockCredentialSchema,+ BEDROCK_USE_DEFAULT_CREDENTIALS,+ VertexAIConfigSchema,+} from "@langfuse/shared";// Base LLM connection response schema - strict to prevent secret leakageexport const LlmConnectionResponse = z@@ -60,28 +67,49 @@ export const PutLlmConnectionV1Body = PutLlmConnectionV1BodyBase.superRefine(// Bedrock requires config with regionif (!config) {ctx.addIssue({- code: z.ZodIssueCode.custom,+ code: "custom",message:"Config is required for Bedrock adapter. Expected: { region: string }",path: ["config"],});return;}- const result = BedrockConfigSchema.safeParse(config);- if (!result.success) {+ const configResult = BedrockConfigSchema.safeParse(config);+ if (!configResult.success) {ctx.addIssue({- code: z.ZodIssueCode.custom,- message: `Invalid Bedrock config: ${result.error.issues.map((e) => e.message).join(", ")}. Expected: { region: string }`,+ code: "custom",+ message: `Invalid Bedrock config: ${configResult.error.issues.map((e) => e.message).join(", ")}. Expected: { region: string }`,path: ["config"],});}++ // Validate secretKey is either the default-credentials sentinel or valid credential JSON+ if (data.secretKey !== BEDROCK_USE_DEFAULT_CREDENTIALS) {+ const credResult = BedrockCredentialSchema.safeParse(+ (() => {+ try {+ return JSON.parse(data.secretKey);+ } catch {+ return undefined;+ }+ })(),+ );+ if (!credResult.success) {+ ctx.addIssue({+ code: "custom",+ message:+ "Invalid Bedrock credentials. Expected a JSON object with either {accessKeyId, secretAccessKey} or {apiKey}.",+ path: ["secretKey"],+ });+ }+ }} else if (adapter === LLMAdapter.VertexAI) {// VertexAI config is optional, but if provided must be validif (config) {const result = VertexAIConfigSchema.safeParse(config);if (!result.success) {ctx.addIssue({- code: z.ZodIssueCode.custom,+ code: "custom",message: `Invalid VertexAI config: ${result.error.issues.map((e) => e.message).join(", ")}. Expected: { location: string }`,path: ["config"],});@@ -91,7 +119,7 @@ export const PutLlmConnectionV1Body = PutLlmConnectionV1BodyBase.superRefine(// Other adapters should not have configif (config && Object.keys(config).length > 0) {ctx.addIssue({- code: z.ZodIssueCode.custom,+ code: "custom",message: `Config is not supported for ${adapter} adapter. Remove the config field.`,path: ["config"],});diff --git a/web/src/pages/api/public/llm-connections/index.ts b/web/src/pages/api/public/llm-connections/index.tsindex 2386e416b7..bdff918cd9 100644--- a/web/src/pages/api/public/llm-connections/index.ts+++ b/web/src/pages/api/public/llm-connections/index.ts@@ -11,8 +11,13 @@ 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 {+ InvalidRequestError,+ BEDROCK_USE_DEFAULT_CREDENTIALS,+ LLMAdapter,+} from "@langfuse/shared";import { validateLlmConnectionBaseURL } from "@langfuse/shared/src/server";+import { env } from "@/src/env.mjs";export default withMiddlewares({GET: createAuthedProjectAPIRoute({@@ -102,6 +107,16 @@ export default withMiddlewares({}}+ const isLangfuseCloud = Boolean(env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION);++ if (body.secretKey === BEDROCK_USE_DEFAULT_CREDENTIALS) {+ if (isLangfuseCloud || body.adapter !== LLMAdapter.Bedrock) {+ throw new InvalidRequestError(+ "Default AWS credentials are only allowed for Bedrock in self-hosted deployments.",+ );+ }+ }+const llmConnectionBody = {adapter: body.adapter,secretKey: encrypt(body.secretKey),diff --git a/worker/src/__tests__/fetchLLMCompletion-bedrock-auth.test.ts b/worker/src/__tests__/fetchLLMCompletion-bedrock-auth.test.tsnew file mode 100644index 0000000000..893732e376--- /dev/null+++ b/worker/src/__tests__/fetchLLMCompletion-bedrock-auth.test.ts@@ -0,0 +1,74 @@+import { describe, expect, it } from "vitest";+import { BEDROCK_USE_DEFAULT_CREDENTIALS } from "@langfuse/shared";+import { resolveBedrockAuth } from "@langfuse/shared/src/server";++describe("resolveBedrockAuth", () => {+ it("uses bearer token auth when Bedrock secret contains a Bedrock API key", () => {+ expect(+ resolveBedrockAuth({+ secretKey: JSON.stringify({+ apiKey: "bedrock-api-key-1234",+ }),+ allowDefaultCredentials: true,+ }),+ ).toEqual({+ clientOptions: {+ token: { token: "bedrock-api-key-1234" },+ authSchemePreference: ["httpBearerAuth"],+ },+ });+ });++ it("keeps SigV4 auth when Bedrock secret contains AWS access keys", () => {+ expect(+ resolveBedrockAuth({+ secretKey: JSON.stringify({+ accessKeyId: "AKIAIOSFODNN7EXAMPLE",+ secretAccessKey: "wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY",+ }),+ allowDefaultCredentials: true,+ }),+ ).toEqual({+ credentials: {+ accessKeyId: "AKIAIOSFODNN7EXAMPLE",+ secretAccessKey: "wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY",+ },+ });+ });++ it("preserves the default credential provider chain sentinel behavior", () => {+ expect(+ resolveBedrockAuth({+ secretKey: BEDROCK_USE_DEFAULT_CREDENTIALS,+ allowDefaultCredentials: true,+ }),+ ).toEqual({});+ });++ it("throws when sentinel is used but default credentials are not allowed", () => {+ expect(() =>+ resolveBedrockAuth({+ secretKey: BEDROCK_USE_DEFAULT_CREDENTIALS,+ allowDefaultCredentials: false,+ }),+ ).toThrow("Invalid Bedrock credentials");+ });++ it("throws on invalid JSON secret key", () => {+ expect(() =>+ resolveBedrockAuth({+ secretKey: "not-valid-json",+ allowDefaultCredentials: false,+ }),+ ).toThrow("Invalid Bedrock credentials");+ });++ it("throws on JSON that does not match any credential schema", () => {+ expect(() =>+ resolveBedrockAuth({+ secretKey: JSON.stringify({ unknownField: "value" }),+ allowDefaultCredentials: false,+ }),+ ).toThrow("Invalid Bedrock credentials");+ });+});diff --git a/worker/src/__tests__/llmConnections.test.ts b/worker/src/__tests__/llmConnections.test.tsindex a77fef1709..b08d0193f4 100644--- a/worker/src/__tests__/llmConnections.test.ts+++ b/worker/src/__tests__/llmConnections.test.ts@@ -35,6 +35,7 @@ import { z } from "zod";* - LANGFUSE_LLM_CONNECTION_BEDROCK_ACCESS_KEY_ID* - LANGFUSE_LLM_CONNECTION_BEDROCK_SECRET_ACCESS_KEY* - LANGFUSE_LLM_CONNECTION_BEDROCK_REGION+ * - LANGFUSE_LLM_CONNECTION_BEDROCK_API_KEY* - LANGFUSE_LLM_CONNECTION_VERTEXAI_KEY* - LANGFUSE_LLM_CONNECTION_GOOGLEAISTUDIO_KEY*/@@ -744,6 +745,105 @@ describe("LLM Connection Tests", () => {}, 30_000);});+ describe("Bedrock (API Key)", () => {+ const MODEL = "eu.anthropic.claude-sonnet-4-5-20250929-v1:0";++ const checkEnvVars = () => {+ if (!process.env.LANGFUSE_LLM_CONNECTION_BEDROCK_API_KEY) {+ throw new Error(+ "LANGFUSE_LLM_CONNECTION_BEDROCK_API_KEY not set. " ++ "This test requires a valid Bedrock API key to verify bearer-token auth. " ++ "Set the environment variable to run this test.",+ );+ }+ if (!process.env.LANGFUSE_LLM_CONNECTION_BEDROCK_REGION) {+ throw new Error(+ "LANGFUSE_LLM_CONNECTION_BEDROCK_REGION not set. " ++ "This test requires a valid AWS region (e.g., 'us-east-1') to verify the Bedrock LLM connection. " ++ "Set the environment variable to run this test.",+ );+ }+ };++ const getApiKey = () => {+ checkEnvVars();+ return JSON.stringify({+ apiKey: process.env.LANGFUSE_LLM_CONNECTION_BEDROCK_API_KEY!,+ });+ };++ const getConfig = () => ({+ region: process.env.LANGFUSE_LLM_CONNECTION_BEDROCK_REGION!,+ });++ test("simple completion", async () => {+ checkEnvVars();++ const completion = await fetchLLMCompletion({+ streaming: false,+ messages: [+ {+ role: "user",+ content: "What is 2+2? Answer only with the number.",+ type: ChatMessageType.PublicAPICreated,+ },+ ],+ modelParams: {+ provider: "bedrock",+ adapter: LLMAdapter.Bedrock,+ model: MODEL,+ temperature: 0,+ max_tokens: 10,+ },+ llmConnection: {+ secretKey: encrypt(getApiKey()),+ config: getConfig(),+ },+ });++ expect(typeof completion).toBe("string");+ expect(completion).toContain("4");+ }, 30_000);++ test("streaming completion", async () => {+ checkEnvVars();++ const stream = await fetchLLMCompletion({+ streaming: true,+ messages: [+ {+ role: "user",+ content: "What is 2+2? Answer only with the number.",+ type: ChatMessageType.PublicAPICreated,+ },+ ],+ modelParams: {+ provider: "bedrock",+ adapter: LLMAdapter.Bedrock,+ model: MODEL,+ temperature: 0,+ max_tokens: 10,+ },+ llmConnection: {+ secretKey: encrypt(getApiKey()),+ config: getConfig(),+ },+ });++ const decoder = new TextDecoder();+ let fullResponse = "";+ let chunkCount = 0;++ for await (const chunk of stream) {+ fullResponse += decoder.decode(chunk);+ chunkCount++;+ }++ expect(chunkCount).toBeGreaterThan(0);+ expect(fullResponse).toContain("4");+ }, 30_000);+ });+describe("VertexAI", () => {const MODEL = "gemini-2.0-flash";