🪢 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: allow Bearer auth on POST scores API (#13064)
Valery Meleshkind2d56f033742
diff --git a/packages/shared/src/server/auth/types.ts b/packages/shared/src/server/auth/types.tsindex 40605a6316..3f67ba09d3 100644--- a/packages/shared/src/server/auth/types.ts+++ b/packages/shared/src/server/auth/types.ts@@ -54,9 +54,11 @@ export type AuthHeaderValidVerificationResultIngestion = {scope: ApiAccessScopeIngestion;};+export type ApiAccessLevel = "organization" | "project" | "scores";+type BaseApiAccessScope = {projectId: string | null;- accessLevel: "organization" | "project" | "scores";+ accessLevel: ApiAccessLevel;};type ApiAccessScopeMetadata = {diff --git a/web/src/__tests__/server/scores-api-v1.servertest.ts b/web/src/__tests__/server/scores-api-v1.servertest.tsindex 4b7c9ee2e3..e314afc5fa 100644--- a/web/src/__tests__/server/scores-api-v1.servertest.ts+++ b/web/src/__tests__/server/scores-api-v1.servertest.ts@@ -4,6 +4,7 @@ import {createTrace,createSessionScore,getScoresByIds,+ getScoreById,} from "@langfuse/shared/src/server";import {createObservationsCh,@@ -1304,4 +1305,121 @@ describe("/api/public/scores API Endpoint", () => {});});});++ describe("Bearer auth (public key only)", () => {+ it("should create a score via POST /api/public/scores with Bearer public key", async () => {+ const { projectId, publicKey } = await createOrgProjectAndApiKey();+ const traceId = v4();+ const trace = createTrace({ id: traceId, project_id: projectId });+ await createTracesCh([trace]);++ const scoreId = v4();+ const response = await makeAPICall(+ "POST",+ "/api/public/scores",+ {+ id: scoreId,+ traceId,+ name: "feedback",+ value: 1,+ },+ `Bearer ${publicKey}`,+ );++ expect(response.status).toBe(200);+ expect(response.body).toHaveProperty("id", scoreId);++ await waitForExpect(async () => {+ const score = await getScoreById({ projectId, scoreId });+ expect(score).toBeDefined();+ expect(score!.id).toBe(scoreId);+ expect(score!.traceId).toBe(traceId);+ expect(score!.name).toBe("feedback");+ expect(score!.value).toBe(1);+ });+ });++ it("should reject GET /api/public/scores with Bearer public key", async () => {+ const { publicKey } = await createOrgProjectAndApiKey();++ const response = await makeAPICall(+ "GET",+ "/api/public/scores",+ undefined,+ `Bearer ${publicKey}`,+ );++ expect(response.status).toBe(401);+ });++ it("should reject GET /api/public/scores/:scoreId with Bearer public key", async () => {+ const { publicKey } = await createOrgProjectAndApiKey();++ const response = await makeAPICall(+ "GET",+ `/api/public/scores/${v4()}`,+ undefined,+ `Bearer ${publicKey}`,+ );++ expect(response.status).toBe(401);+ });++ it("should reject DELETE /api/public/scores/:scoreId with Bearer public key", async () => {+ const { publicKey } = await createOrgProjectAndApiKey();++ const response = await makeAPICall(+ "DELETE",+ `/api/public/scores/${v4()}`,+ undefined,+ `Bearer ${publicKey}`,+ );++ expect(response.status).toBe(401);+ });++ it("should reject POST /api/public/scores with invalid Bearer token", async () => {+ const response = await makeAPICall(+ "POST",+ "/api/public/scores",+ {+ traceId: v4(),+ name: "feedback",+ value: 1,+ },+ `Bearer pk-invalid-key-that-does-not-exist`,+ );++ expect(response.status).toBe(401);+ });++ it("should reject Bearer public key on non-scores endpoints", async () => {+ const { publicKey } = await createOrgProjectAndApiKey();++ const [tracesRes, observationsRes, sessionsRes] = await Promise.all([+ makeAPICall(+ "GET",+ "/api/public/traces",+ undefined,+ `Bearer ${publicKey}`,+ ),+ makeAPICall(+ "GET",+ "/api/public/observations",+ undefined,+ `Bearer ${publicKey}`,+ ),+ makeAPICall(+ "GET",+ "/api/public/sessions",+ undefined,+ `Bearer ${publicKey}`,+ ),+ ]);++ expect(tracesRes.status).toBe(401);+ expect(observationsRes.status).toBe(401);+ expect(sessionsRes.status).toBe(401);+ });+ });});diff --git a/web/src/features/public-api/server/createAuthedProjectAPIRoute.ts b/web/src/features/public-api/server/createAuthedProjectAPIRoute.tsindex ae5aef0af0..fcc0504466 100644--- a/web/src/features/public-api/server/createAuthedProjectAPIRoute.ts+++ b/web/src/features/public-api/server/createAuthedProjectAPIRoute.ts@@ -6,6 +6,7 @@ import { prisma } from "@langfuse/shared/src/db";import {redis,type AuthHeaderValidVerificationResult,+ type ApiAccessLevel,traceException,logger,} from "@langfuse/shared/src/server";@@ -15,6 +16,9 @@ import { contextWithLangfuseProps } from "@langfuse/shared/src/server";import * as opentelemetry from "@opentelemetry/api";import { env } from "@/src/env.mjs";+/** Access levels that can be accepted by project-scoped API routes. */+type RouteAccessLevel = Exclude<ApiAccessLevel, "organization">;+type RouteConfig<TQuery extends ZodType<any>,TBody extends ZodType<any>,@@ -40,30 +44,41 @@ type RouteConfig<* @default false*/isAdminApiKeyAuthAllowed?: boolean;+ /**+ * Access levels accepted for this route. Defaults to ["project"] (Basic auth only).+ * Set to ["project", "scores"] to also allow Bearer auth with a public key+ * (which receives accessLevel "scores").+ */+ allowedAccessLevels?: RouteAccessLevel[];fn: (params: {query: z.infer<TQuery>;body: z.infer<TBody>;req: NextApiRequest;res: NextApiResponse;auth: AuthHeaderValidVerificationResult & {- scope: { projectId: string; accessLevel: "project" };+ scope: { projectId: string; accessLevel: RouteAccessLevel };};}) => Promise<z.infer<TResponse>>;};/**- * Verifies regular API key authentication using ApiAuthService.+ * Verifies API key authentication (Basic or Bearer) using ApiAuthService.*- * This function handles standard project API key authentication with Basic auth.- * Returns an auth scope object with project-level access.+ * Delegates to ApiAuthService.verifyAuthHeaderAndReturnScope which handles+ * both Basic auth (public + secret key) and Bearer auth (public key only).+ * The caller controls which access levels are accepted via allowedAccessLevels.** @param authHeader - The Authorization header from the request- * @returns An auth scope object with project-level access+ * @param allowedAccessLevels - Access levels to accept (default: ["project"])+ * @returns An auth scope object with the verified access level* @throws Error with appropriate message if authentication fails*/-async function verifyBasicAuth(authHeader: string | undefined): Promise<+async function verifyApiKeyAuth(+ authHeader: string | undefined,+ allowedAccessLevels: RouteAccessLevel[] = ["project"],+): Promise<AuthHeaderValidVerificationResult & {- scope: { projectId: string; accessLevel: "project" };+ scope: { projectId: string; accessLevel: RouteAccessLevel };}> {const regularAuth = await new ApiAuthService(@@ -75,10 +90,14 @@ async function verifyBasicAuth(authHeader: string | undefined): Promise<throw { status: 401, message: regularAuth.error };}- if (regularAuth.scope.accessLevel !== "project") {+ if (+ !(allowedAccessLevels as ApiAccessLevel[]).includes(+ regularAuth.scope.accessLevel,+ )+ ) {throw {status: 401,- message: "Access denied - need to use basic auth with secret key",+ message: "Access denied - insufficient permissions for this endpoint",};}@@ -91,7 +110,7 @@ async function verifyBasicAuth(authHeader: string | undefined): Promise<}return regularAuth as AuthHeaderValidVerificationResult & {- scope: { projectId: string; accessLevel: "project" };+ scope: { projectId: string; accessLevel: RouteAccessLevel };};}@@ -198,22 +217,25 @@ async function verifyAdminApiKeyAuth(req: NextApiRequest): Promise<}/**- * Verifies authentication for API routes with support for both basic and admin API key auth.+ * Verifies authentication for API routes with support for both regular API key+ * auth (Basic or Bearer) and admin API key auth.*- * This is the main authentication entry point that delegates to either admin or basic auth- * based on the configuration and request headers.+ * This is the main authentication entry point that delegates to either admin+ * or regular API key auth based on the configuration and request headers.** @param req - The Next.js API request* @param isAdminApiKeyAuthAllowed - Whether to allow admin API key authentication- * @returns An auth scope object with project-level access+ * @param allowedAccessLevels - Access levels to accept for regular API key auth+ * @returns An auth scope object with the verified access level* @throws Error with appropriate status code if authentication fails*/export async function verifyAuth(req: NextApiRequest,isAdminApiKeyAuthAllowed: boolean,+ allowedAccessLevels: RouteAccessLevel[] = ["project"],): Promise<AuthHeaderValidVerificationResult & {- scope: { projectId: string; accessLevel: "project" };+ scope: { projectId: string; accessLevel: RouteAccessLevel };}> {if (isAdminApiKeyAuthAllowed) {@@ -223,12 +245,15 @@ export async function verifyAuth(// Admin auth succeededreturn adminAuth;}- // Admin auth not attempted, fall back to basic auth- return await verifyBasicAuth(req.headers.authorization);+ // Admin auth not attempted, fall back to regular API key auth+ return await verifyApiKeyAuth(+ req.headers.authorization,+ allowedAccessLevels,+ );}- // Only basic auth is allowed- return await verifyBasicAuth(req.headers.authorization);+ // Only regular API key auth is allowed+ return await verifyApiKeyAuth(req.headers.authorization, allowedAccessLevels);}export const createAuthedProjectAPIRoute = <@@ -240,14 +265,15 @@ export const createAuthedProjectAPIRoute = <): ((req: NextApiRequest, res: NextApiResponse) => Promise<void>) => {return async (req: NextApiRequest, res: NextApiResponse) => {let auth: AuthHeaderValidVerificationResult & {- scope: { projectId: string; accessLevel: "project" };+ scope: { projectId: string; accessLevel: RouteAccessLevel };};- // Verify authentication (basic or admin API key)+ // Verify authentication (API key or admin API key)try {auth = await verifyAuth(req,routeConfig.isAdminApiKeyAuthAllowed || false,+ routeConfig.allowedAccessLevels || ["project"],);} catch (error: any) {const statusCode = error.status || 401;@@ -294,7 +320,7 @@ export const createAuthedProjectAPIRoute = <req,res,auth: auth as AuthHeaderValidVerificationResult & {- scope: { projectId: string; accessLevel: "project" };+ scope: { projectId: string; accessLevel: RouteAccessLevel };},});diff --git a/web/src/pages/api/public/scores/index.ts b/web/src/pages/api/public/scores/index.tsindex 64890c4226..1dbebe4fac 100644--- a/web/src/pages/api/public/scores/index.ts+++ b/web/src/pages/api/public/scores/index.ts@@ -14,6 +14,7 @@ import {logger,processEventBatch,} from "@langfuse/shared/src/server";+import { ForbiddenError } from "@langfuse/shared";import { ScoresApiService } from "@/src/features/public-api/server/scores-api-service";export default withMiddlewares({@@ -21,7 +22,14 @@ export default withMiddlewares({name: "Create Score",bodySchema: PostScoresBodyV1,responseSchema: PostScoresResponseV1,+ allowedAccessLevels: ["project", "scores"],fn: async ({ body, auth, res }) => {+ if (auth.scope.isIngestionSuspended) {+ throw new ForbiddenError(+ "Ingestion suspended: Usage threshold exceeded. Please upgrade your plan.",+ );+ }+const event = {id: v4(),type: eventTypes.SCORE_CREATE,