🪢 Open source agent evals & observability: Trace, evaluate, and improve LLM applications with one open platform.
TypeScript analyticsautogenevaluationlangchainlarge-language-modelsllama-indexllmllm-evaluationllm-observabilityllmopsmonitoringobservabilityopen-sourceopenaiplaygroundprompt-engineeringprompt-managementself-hostedycombinator
fix(web): require secret key for LLM test base URL changes (#13055)
Hassieb Pakzad7527bb0d84bc
diff --git a/web/src/__tests__/server/llm-api-key.servertest.ts b/web/src/__tests__/server/llm-api-key.servertest.tsindex 0e8e4f027b..72b8a96c75 100644--- a/web/src/__tests__/server/llm-api-key.servertest.ts+++ b/web/src/__tests__/server/llm-api-key.servertest.ts@@ -1,12 +1,25 @@/** @jest-environment node */+jest.mock("@langfuse/shared/src/server", () => {+ const actual = jest.requireActual("@langfuse/shared/src/server");+ return {+ ...actual,+ fetchLLMCompletion: jest.fn(),+ };+});+import type { Session } from "next-auth";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 { createOrgProjectAndApiKey } from "@langfuse/shared/src/server";+import {+ createOrgProjectAndApiKey,+ fetchLLMCompletion,+} from "@langfuse/shared/src/server";++const mockFetchLLMCompletion = jest.mocked(fetchLLMCompletion);describe("llmApiKey.all RPC", () => {let projectId: string;@@ -49,6 +62,7 @@ describe("llmApiKey.all RPC", () => {const setup = await createOrgProjectAndApiKey();projectId = setup.projectId;orgId = setup.orgId;+ mockFetchLLMCompletion.mockReset().mockResolvedValue({});session = {expires: "1",@@ -187,7 +201,7 @@ describe("llmApiKey.all RPC", () => {).rejects.toThrow("User does not have access to this resource or action");});- it("should require llmApiKeys:update access for testing an existing llm api key", async () => {+ it("should require llmApiKeys:create access for testing an existing llm api key", async () => {await caller.llmApiKey.create({projectId,provider: "openai",@@ -216,6 +230,116 @@ describe("llmApiKey.all RPC", () => {).rejects.toThrow("User does not have access to this resource or action");});+ it("should block testUpdate when the base URL changes without a new secret key", async () => {+ await caller.llmApiKey.create({+ projectId,+ provider: "openai",+ adapter: LLMAdapter.OpenAI,+ secretKey: "sk-original",+ baseURL: "https://api.openai.com/v1",+ });++ const existingKey = await prisma.llmApiKeys.findFirstOrThrow({+ where: {+ projectId,+ provider: "openai",+ },+ });++ const result = await caller.llmApiKey.testUpdate({+ id: existingKey.id,+ projectId,+ provider: "openai",+ adapter: LLMAdapter.OpenAI,+ baseURL: "https://attacker.example.com/v1",+ });++ expect(result).toEqual({+ success: false,+ error: "Secret key is required when changing the base URL",+ });+ expect(mockFetchLLMCompletion).not.toHaveBeenCalled();+ });++ it("should allow testUpdate without a new secret key when the base URL is unchanged", async () => {+ const existingExtraHeaders = {+ Authorization: "Bearer stored-token",+ "X-Custom-Header": "stored-value",+ };++ await caller.llmApiKey.create({+ projectId,+ provider: "openai",+ adapter: LLMAdapter.OpenAI,+ secretKey: "sk-original",+ baseURL: "https://api.openai.com/v1",+ extraHeaders: existingExtraHeaders,+ });++ const existingKey = await prisma.llmApiKeys.findFirstOrThrow({+ where: {+ projectId,+ provider: "openai",+ },+ });++ const result = await caller.llmApiKey.testUpdate({+ id: existingKey.id,+ projectId,+ provider: "openai",+ adapter: LLMAdapter.OpenAI,+ baseURL: "https://api.openai.com/v1",+ });++ expect(result).toEqual({ success: true });+ expect(mockFetchLLMCompletion).toHaveBeenCalledTimes(1);+ const llmConnection = mockFetchLLMCompletion.mock.calls[0][0].llmConnection;+ expect(llmConnection.baseURL).toBe("https://api.openai.com/v1");+ expect(decrypt(llmConnection.secretKey)).toBe("sk-original");+ expect(JSON.parse(decrypt(llmConnection.extraHeaders))).toEqual(+ existingExtraHeaders,+ );+ });++ it("should allow testUpdate when the base URL changes and a new secret key is provided", async () => {+ const existingExtraHeaders = {+ Authorization: "Bearer stored-token",+ "X-Custom-Header": "stored-value",+ };++ await caller.llmApiKey.create({+ projectId,+ provider: "openai",+ adapter: LLMAdapter.OpenAI,+ secretKey: "sk-original",+ baseURL: "https://api.openai.com/v1",+ extraHeaders: existingExtraHeaders,+ });++ const existingKey = await prisma.llmApiKeys.findFirstOrThrow({+ where: {+ projectId,+ provider: "openai",+ },+ });++ const result = await caller.llmApiKey.testUpdate({+ id: existingKey.id,+ projectId,+ provider: "openai",+ adapter: LLMAdapter.OpenAI,+ secretKey: "sk-rotated",+ baseURL: "https://new-endpoint.example.com/v1",+ });++ expect(result).toEqual({ success: true });+ expect(mockFetchLLMCompletion).toHaveBeenCalledTimes(1);+ const llmConnection = mockFetchLLMCompletion.mock.calls[0][0].llmConnection;+ expect(llmConnection.baseURL).toBe("https://new-endpoint.example.com/v1");+ expect(decrypt(llmConnection.secretKey)).toBe("sk-rotated");+ expect(llmConnection.extraHeaders).toBeUndefined();+ });+it("should create and update an llm api key", async () => {const secret = "test-secret";const provider = "openai";diff --git a/web/src/features/llm-api-key/server/router.ts b/web/src/features/llm-api-key/server/router.tsindex fa81773e09..33f7971b3f 100644--- a/web/src/features/llm-api-key/server/router.ts+++ b/web/src/features/llm-api-key/server/router.ts@@ -442,25 +442,37 @@ export const llmApiKeyRouter = createTRPCRouter({});}- const decryptedSecretKey =- input.secretKey !== undefined &&- input.secretKey !== "" &&- input.secretKey !== null- ? input.secretKey- : decrypt(existingKey.secretKey);+ const hasNewSecretKey =+ typeof input.secretKey === "string" && input.secretKey.length > 0;+ const baseURL = input.baseURL ?? existingKey.baseURL;+ const isBaseURLChanged = baseURL !== existingKey.baseURL;++ if (isBaseURLChanged && !hasNewSecretKey) {+ throw new TRPCError({+ code: "BAD_REQUEST",+ message: "Secret key is required when changing the base URL",+ });+ }++ const secretKey = hasNewSecretKey+ ? (input.secretKey as string)+ : decrypt(existingKey.secretKey);// Merge existing key with provided input, giving priority to input- const secretKey = decryptedSecretKey;const adapter = input.adapter ?? (existingKey.adapter as LLMAdapter);const provider = input.provider ?? existingKey.provider;- const baseURL = input.baseURL ?? existingKey.baseURL;const customModels = input.customModels ?? existingKey.customModels;const config = input.config ?? existingKey.config;++ // Never reuse stored headers across a destination change.const extraHeaders =- input.extraHeaders ??- (existingKey.extraHeaders- ? decryptAndParseExtraHeaders(existingKey.extraHeaders)- : undefined);+ input.extraHeaders !== undefined+ ? input.extraHeaders+ : isBaseURLChanged+ ? undefined+ : existingKey.extraHeaders+ ? decryptAndParseExtraHeaders(existingKey.extraHeaders)+ : undefined;return testLLMConnection({adapter,