🪢 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(api): return 503 for public auth db failures (#13866)
Peter Chen J.f2c9642e7738
diff --git a/web/src/__tests__/server/unit/create-authed-project-api-route-auth-errors.servertest.ts b/web/src/__tests__/server/unit/create-authed-project-api-route-auth-errors.servertest.tsnew file mode 100644index 0000000000..a44b2059ad--- /dev/null+++ b/web/src/__tests__/server/unit/create-authed-project-api-route-auth-errors.servertest.ts@@ -0,0 +1,165 @@+import type { NextApiRequest, NextApiResponse } from "next";+import { createMocks } from "node-mocks-http";+import { z } from "zod";++const {+ mockVerifyAuthHeaderAndReturnScope,+ mockIsPrismaException,+ mockRateLimitRequest,+ mockTraceException,+ mockCreateUnstablePublicApiAuthError,+ mockSendUnstablePublicApiErrorResponse,+} = vi.hoisted(() => ({+ mockVerifyAuthHeaderAndReturnScope: vi.fn(),+ mockIsPrismaException: vi.fn(),+ mockRateLimitRequest: vi.fn(),+ mockTraceException: vi.fn(),+ mockCreateUnstablePublicApiAuthError: vi.fn((value) => value),+ mockSendUnstablePublicApiErrorResponse: vi.fn(),+}));++vi.mock("@/src/features/public-api/server/apiAuth", () => ({+ ApiAuthService: class {+ verifyAuthHeaderAndReturnScope = mockVerifyAuthHeaderAndReturnScope;+ },+}));++vi.mock("@langfuse/shared/src/db", () => ({+ prisma: {},+}));++vi.mock("@langfuse/shared/src/server", () => ({+ redis: null,+ logger: {+ debug: vi.fn(),+ info: vi.fn(),+ warn: vi.fn(),+ error: vi.fn(),+ },+ traceException: mockTraceException,+ contextWithLangfuseProps: vi.fn(() => ({})),+ ClickHouseClientManager: {+ getInstance: () => ({+ closeAllConnections: vi.fn(async () => undefined),+ }),+ },+}));++vi.mock("@/src/features/public-api/server/RateLimitService", () => ({+ RateLimitService: {+ getInstance: () => ({+ rateLimitRequest: mockRateLimitRequest,+ }),+ },+}));++vi.mock("@/src/features/public-api/server/withMiddlewares", () => ({+ isZodError: vi.fn(() => false),+}));++vi.mock(+ "@/src/features/public-api/server/unstable-public-api-error-contract",+ () => ({+ unstablePublicEvalsErrorContract: "unstable-public-evals",+ createUnstablePublicApiAuthError: mockCreateUnstablePublicApiAuthError,+ createUnstablePublicApiRequestValidationError: vi.fn(),+ sendUnstablePublicApiErrorResponse: mockSendUnstablePublicApiErrorResponse,+ }),+);++vi.mock("@/src/env.mjs", () => ({+ env: {+ NODE_ENV: "test",+ },+}));++vi.mock("@opentelemetry/api", () => ({+ context: {+ with: vi.fn(async (_ctx, fn) => await fn()),+ },+}));++vi.mock("@/src/utils/exceptions", () => ({+ isPrismaException: mockIsPrismaException,+}));++import { createAuthedProjectAPIRoute } from "@/src/features/public-api/server/createAuthedProjectAPIRoute";++describe("createAuthedProjectAPIRoute auth error handling", () => {+ beforeEach(() => {+ vi.clearAllMocks();+ mockIsPrismaException.mockReturnValue(false);+ mockRateLimitRequest.mockResolvedValue({+ isRateLimited: () => false,+ });+ });++ async function callRoute(options?: { useUnstableErrorContract?: boolean }) {+ const handler = createAuthedProjectAPIRoute({+ name: "Test Route",+ querySchema: z.object({}),+ responseSchema: z.object({ ok: z.literal(true) }),+ errorContract: options?.useUnstableErrorContract+ ? "unstable-public-evals"+ : undefined,+ fn: async () => ({ ok: true as const }),+ });++ const { req, res } = createMocks<NextApiRequest, NextApiResponse>({+ method: "GET",+ headers: {+ authorization: "Basic test",+ },+ query: {},+ });++ await handler(req, res);++ return res;+ }++ it("returns 401 for invalid credentials", async () => {+ mockVerifyAuthHeaderAndReturnScope.mockResolvedValueOnce({+ validKey: false,+ error:+ "Invalid credentials. Confirm that you've configured the correct host.",+ });++ const res = await callRoute();++ expect(res.statusCode).toBe(401);+ expect(res._getJSONData()).toEqual({+ message:+ "Invalid credentials. Confirm that you've configured the correct host.",+ });+ });++ it("returns 503 when auth fails with a prisma exception", async () => {+ const prismaLikeError = new Error("Can't reach database server");+ mockVerifyAuthHeaderAndReturnScope.mockRejectedValueOnce(prismaLikeError);+ mockIsPrismaException.mockReturnValue(true);++ const res = await callRoute();++ expect(res.statusCode).toBe(503);+ expect(res._getJSONData()).toEqual({+ message: "Service Unavailable",+ });+ expect(mockTraceException).toHaveBeenCalledWith(prismaLikeError);+ });++ it("returns unstable auth errors and traces prisma auth failures", async () => {+ const prismaLikeError = new Error("Can't reach database server");+ mockVerifyAuthHeaderAndReturnScope.mockRejectedValueOnce(prismaLikeError);+ mockIsPrismaException.mockReturnValue(true);++ await callRoute({ useUnstableErrorContract: true });++ expect(mockTraceException).toHaveBeenCalledWith(prismaLikeError);+ expect(mockCreateUnstablePublicApiAuthError).toHaveBeenCalledWith({+ statusCode: 503,+ message: "Service Unavailable",+ });+ expect(mockSendUnstablePublicApiErrorResponse).toHaveBeenCalledTimes(1);+ });+});diff --git a/web/src/features/public-api/server/createAuthedProjectAPIRoute.ts b/web/src/features/public-api/server/createAuthedProjectAPIRoute.tsindex e626bed76c..edad539320 100644--- a/web/src/features/public-api/server/createAuthedProjectAPIRoute.ts+++ b/web/src/features/public-api/server/createAuthedProjectAPIRoute.ts@@ -16,6 +16,7 @@ import { contextWithLangfuseProps } from "@langfuse/shared/src/server";import * as opentelemetry from "@opentelemetry/api";import { env } from "@/src/env.mjs";import { isZodError } from "@/src/features/public-api/server/withMiddlewares";+import { isPrismaException } from "@/src/utils/exceptions";import {createUnstablePublicApiAuthError,createUnstablePublicApiRequestValidationError,@@ -324,8 +325,25 @@ export const createAuthedProjectAPIRoute = <routeConfig.allowInAppAgentKey === true,);} catch (error: any) {- const statusCode = error.status || 401;- const message = error.message || "Authentication failed";+ if (isPrismaException(error)) {+ traceException(error);++ if (routeConfig.errorContract === unstablePublicEvalsErrorContract) {+ return sendUnstablePublicApiErrorResponse(+ res,+ createUnstablePublicApiAuthError({+ statusCode: 503,+ message: "Service Unavailable",+ }),+ );+ }++ res.status(503).json({ message: "Service Unavailable" });+ return;+ }++ const statusCode = error.status ?? 401;+ const message = error.message ?? "Authentication failed";if (routeConfig.errorContract === unstablePublicEvalsErrorContract) {return sendUnstablePublicApiErrorResponse(