🪢 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(auth): route org/misc direct-handler public-API auth through the policy core (#16662)
Mark Salpeterb41e1913907d
diff --git a/web/src/__tests__/server/__snapshots__/project-route-auth-parity.servertest.ts.snap b/web/src/__tests__/server/__snapshots__/public-api-auth-parity.servertest.ts.snapsimilarity index 76%rename from web/src/__tests__/server/__snapshots__/project-route-auth-parity.servertest.ts.snaprename to web/src/__tests__/server/__snapshots__/public-api-auth-parity.servertest.ts.snapindex 21f53d21e8..c59708ef73 100644--- a/web/src/__tests__/server/__snapshots__/project-route-auth-parity.servertest.ts.snap+++ b/web/src/__tests__/server/__snapshots__/public-api-auth-parity.servertest.ts.snap@@ -1,6 +1,6 @@// Vitest Snapshot v1, https://vitest.dev/guide/snapshot.html-exports[`project-route auth parity > legacy matches the main-captured baseline 1`] = `+exports[`public-api auth parity > legacy matches the main-captured baseline 1`] = `{"DELETE annotation-queues/[queueId]/assignments | admin/admin": 401,"DELETE annotation-queues/[queueId]/assignments | agent/basic": 401,@@ -30,6 +30,13 @@ exports[`project-route auth parity > legacy matches the main-captured baseline 1"DELETE datasets/[name]/runs/[runName] | org/bearer": 401,"DELETE datasets/[name]/runs/[runName] | project/basic": 404,"DELETE datasets/[name]/runs/[runName] | project/bearer": 403,+ "DELETE integrations/blob-storage/[id] | admin/admin": 401,+ "DELETE integrations/blob-storage/[id] | agent/basic": 401,+ "DELETE integrations/blob-storage/[id] | agent/bearer": 401,+ "DELETE integrations/blob-storage/[id] | org/basic": 404,+ "DELETE integrations/blob-storage/[id] | org/bearer": 401,+ "DELETE integrations/blob-storage/[id] | project/basic": 403,+ "DELETE integrations/blob-storage/[id] | project/bearer": 403,"DELETE llm-connections/[id] | admin/admin": 403,"DELETE llm-connections/[id] | agent/basic": 401,"DELETE llm-connections/[id] | agent/bearer": 401,@@ -44,6 +51,41 @@ exports[`project-route auth parity > legacy matches the main-captured baseline 1"DELETE models/[modelId]/index | org/bearer": 401,"DELETE models/[modelId]/index | project/basic": 404,"DELETE models/[modelId]/index | project/bearer": 403,+ "DELETE organizations/memberships/index | admin/admin": 401,+ "DELETE organizations/memberships/index | agent/basic": 401,+ "DELETE organizations/memberships/index | agent/bearer": 401,+ "DELETE organizations/memberships/index | org/basic": 400,+ "DELETE organizations/memberships/index | org/bearer": 401,+ "DELETE organizations/memberships/index | project/basic": 403,+ "DELETE organizations/memberships/index | project/bearer": 403,+ "DELETE projects/[projectId]/apiKeys/[apiKeyId] | admin/admin": 401,+ "DELETE projects/[projectId]/apiKeys/[apiKeyId] | agent/basic": 401,+ "DELETE projects/[projectId]/apiKeys/[apiKeyId] | agent/bearer": 401,+ "DELETE projects/[projectId]/apiKeys/[apiKeyId] | org/basic": 404,+ "DELETE projects/[projectId]/apiKeys/[apiKeyId] | org/bearer": 401,+ "DELETE projects/[projectId]/apiKeys/[apiKeyId] | project/basic": 403,+ "DELETE projects/[projectId]/apiKeys/[apiKeyId] | project/bearer": 403,+ "DELETE projects/[projectId]/index | admin/admin": 401,+ "DELETE projects/[projectId]/index | agent/basic": 401,+ "DELETE projects/[projectId]/index | agent/bearer": 401,+ "DELETE projects/[projectId]/index | org/basic": 404,+ "DELETE projects/[projectId]/index | org/bearer": 401,+ "DELETE projects/[projectId]/index | project/basic": 403,+ "DELETE projects/[projectId]/index | project/bearer": 403,+ "DELETE projects/[projectId]/memberships/index | admin/admin": 401,+ "DELETE projects/[projectId]/memberships/index | agent/basic": 401,+ "DELETE projects/[projectId]/memberships/index | agent/bearer": 401,+ "DELETE projects/[projectId]/memberships/index | org/basic": 404,+ "DELETE projects/[projectId]/memberships/index | org/bearer": 401,+ "DELETE projects/[projectId]/memberships/index | project/basic": 403,+ "DELETE projects/[projectId]/memberships/index | project/bearer": 403,+ "DELETE scim/Users/[id] | admin/admin": 401,+ "DELETE scim/Users/[id] | agent/basic": 401,+ "DELETE scim/Users/[id] | agent/bearer": 401,+ "DELETE scim/Users/[id] | org/basic": 404,+ "DELETE scim/Users/[id] | org/bearer": 401,+ "DELETE scim/Users/[id] | project/basic": 403,+ "DELETE scim/Users/[id] | project/bearer": 403,"DELETE scores/[scoreId] | admin/admin": 401,"DELETE scores/[scoreId] | agent/basic": 401,"DELETE scores/[scoreId] | agent/bearer": 401,@@ -205,6 +247,20 @@ exports[`project-route auth parity > legacy matches the main-captured baseline 1"GET experiments/index | org/bearer": 401,"GET experiments/index | project/basic": 400,"GET experiments/index | project/bearer": 403,+ "GET integrations/blob-storage/[id] | admin/admin": 401,+ "GET integrations/blob-storage/[id] | agent/basic": 401,+ "GET integrations/blob-storage/[id] | agent/bearer": 401,+ "GET integrations/blob-storage/[id] | org/basic": 404,+ "GET integrations/blob-storage/[id] | org/bearer": 401,+ "GET integrations/blob-storage/[id] | project/basic": 403,+ "GET integrations/blob-storage/[id] | project/bearer": 403,+ "GET integrations/blob-storage/index | admin/admin": 401,+ "GET integrations/blob-storage/index | agent/basic": 401,+ "GET integrations/blob-storage/index | agent/bearer": 401,+ "GET integrations/blob-storage/index | org/basic": 200,+ "GET integrations/blob-storage/index | org/bearer": 401,+ "GET integrations/blob-storage/index | project/basic": 403,+ "GET integrations/blob-storage/index | project/bearer": 403,"GET llm-connections/index | admin/admin": 403,"GET llm-connections/index | agent/basic": 401,"GET llm-connections/index | agent/bearer": 401,@@ -261,6 +317,83 @@ exports[`project-route auth parity > legacy matches the main-captured baseline 1"GET observations/index | org/bearer": 401,"GET observations/index | project/basic": 200,"GET observations/index | project/bearer": 403,+ "GET organizations/apiKeys/index | admin/admin": 401,+ "GET organizations/apiKeys/index | agent/basic": 401,+ "GET organizations/apiKeys/index | agent/bearer": 401,+ "GET organizations/apiKeys/index | org/basic": 200,+ "GET organizations/apiKeys/index | org/bearer": 401,+ "GET organizations/apiKeys/index | project/basic": 403,+ "GET organizations/apiKeys/index | project/bearer": 403,+ "GET organizations/memberships/index | admin/admin": 401,+ "GET organizations/memberships/index | agent/basic": 401,+ "GET organizations/memberships/index | agent/bearer": 401,+ "GET organizations/memberships/index | org/basic": 200,+ "GET organizations/memberships/index | org/bearer": 401,+ "GET organizations/memberships/index | project/basic": 403,+ "GET organizations/memberships/index | project/bearer": 403,+ "GET organizations/projects/index | admin/admin": 401,+ "GET organizations/projects/index | agent/basic": 401,+ "GET organizations/projects/index | agent/bearer": 401,+ "GET organizations/projects/index | org/basic": 200,+ "GET organizations/projects/index | org/bearer": 401,+ "GET organizations/projects/index | project/basic": 403,+ "GET organizations/projects/index | project/bearer": 403,+ "GET projects/[projectId]/apiKeys/index | admin/admin": 401,+ "GET projects/[projectId]/apiKeys/index | agent/basic": 401,+ "GET projects/[projectId]/apiKeys/index | agent/bearer": 401,+ "GET projects/[projectId]/apiKeys/index | org/basic": 404,+ "GET projects/[projectId]/apiKeys/index | org/bearer": 401,+ "GET projects/[projectId]/apiKeys/index | project/basic": 403,+ "GET projects/[projectId]/apiKeys/index | project/bearer": 403,+ "GET projects/[projectId]/memberships/index | admin/admin": 401,+ "GET projects/[projectId]/memberships/index | agent/basic": 401,+ "GET projects/[projectId]/memberships/index | agent/bearer": 401,+ "GET projects/[projectId]/memberships/index | org/basic": 404,+ "GET projects/[projectId]/memberships/index | org/bearer": 401,+ "GET projects/[projectId]/memberships/index | project/basic": 403,+ "GET projects/[projectId]/memberships/index | project/bearer": 403,+ "GET projects/index | admin/admin": 401,+ "GET projects/index | agent/basic": 401,+ "GET projects/index | agent/bearer": 401,+ "GET projects/index | org/basic": 403,+ "GET projects/index | org/bearer": 401,+ "GET projects/index | project/basic": 200,+ "GET projects/index | project/bearer": 403,+ "GET scim/ResourceTypes | admin/admin": 401,+ "GET scim/ResourceTypes | agent/basic": 401,+ "GET scim/ResourceTypes | agent/bearer": 401,+ "GET scim/ResourceTypes | org/basic": 200,+ "GET scim/ResourceTypes | org/bearer": 401,+ "GET scim/ResourceTypes | project/basic": 403,+ "GET scim/ResourceTypes | project/bearer": 403,+ "GET scim/Schemas | admin/admin": 401,+ "GET scim/Schemas | agent/basic": 401,+ "GET scim/Schemas | agent/bearer": 401,+ "GET scim/Schemas | org/basic": 200,+ "GET scim/Schemas | org/bearer": 401,+ "GET scim/Schemas | project/basic": 403,+ "GET scim/Schemas | project/bearer": 403,+ "GET scim/ServiceProviderConfig | admin/admin": 401,+ "GET scim/ServiceProviderConfig | agent/basic": 401,+ "GET scim/ServiceProviderConfig | agent/bearer": 401,+ "GET scim/ServiceProviderConfig | org/basic": 200,+ "GET scim/ServiceProviderConfig | org/bearer": 401,+ "GET scim/ServiceProviderConfig | project/basic": 403,+ "GET scim/ServiceProviderConfig | project/bearer": 403,+ "GET scim/Users/[id] | admin/admin": 401,+ "GET scim/Users/[id] | agent/basic": 401,+ "GET scim/Users/[id] | agent/bearer": 401,+ "GET scim/Users/[id] | org/basic": 404,+ "GET scim/Users/[id] | org/bearer": 401,+ "GET scim/Users/[id] | project/basic": 403,+ "GET scim/Users/[id] | project/bearer": 403,+ "GET scim/Users/index | admin/admin": 401,+ "GET scim/Users/index | agent/basic": 401,+ "GET scim/Users/index | agent/bearer": 401,+ "GET scim/Users/index | org/basic": 200,+ "GET scim/Users/index | org/bearer": 401,+ "GET scim/Users/index | project/basic": 403,+ "GET scim/Users/index | project/bearer": 403,"GET score-configs/[configId] | admin/admin": 401,"GET score-configs/[configId] | agent/basic": 401,"GET score-configs/[configId] | agent/bearer": 401,@@ -450,6 +583,13 @@ exports[`project-route auth parity > legacy matches the main-captured baseline 1"PATCH media/[mediaId] | org/bearer": 401,"PATCH media/[mediaId] | project/basic": 400,"PATCH media/[mediaId] | project/bearer": 403,+ "PATCH scim/Users/[id] | admin/admin": 401,+ "PATCH scim/Users/[id] | agent/basic": 401,+ "PATCH scim/Users/[id] | agent/bearer": 401,+ "PATCH scim/Users/[id] | org/basic": 404,+ "PATCH scim/Users/[id] | org/bearer": 401,+ "PATCH scim/Users/[id] | project/basic": 403,+ "PATCH scim/Users/[id] | project/bearer": 403,"PATCH score-configs/[configId] | admin/admin": 401,"PATCH score-configs/[configId] | agent/basic": 401,"PATCH score-configs/[configId] | agent/bearer": 401,@@ -583,6 +723,27 @@ exports[`project-route auth parity > legacy matches the main-captured baseline 1"POST models/index | org/bearer": 401,"POST models/index | project/basic": 400,"POST models/index | project/bearer": 403,+ "POST projects/[projectId]/apiKeys/index | admin/admin": 401,+ "POST projects/[projectId]/apiKeys/index | agent/basic": 401,+ "POST projects/[projectId]/apiKeys/index | agent/bearer": 401,+ "POST projects/[projectId]/apiKeys/index | org/basic": 404,+ "POST projects/[projectId]/apiKeys/index | org/bearer": 401,+ "POST projects/[projectId]/apiKeys/index | project/basic": 403,+ "POST projects/[projectId]/apiKeys/index | project/bearer": 403,+ "POST projects/index | admin/admin": 401,+ "POST projects/index | agent/basic": 401,+ "POST projects/index | agent/bearer": 401,+ "POST projects/index | org/basic": 400,+ "POST projects/index | org/bearer": 401,+ "POST projects/index | project/basic": 403,+ "POST projects/index | project/bearer": 403,+ "POST scim/Users/index | admin/admin": 401,+ "POST scim/Users/index | agent/basic": 401,+ "POST scim/Users/index | agent/bearer": 401,+ "POST scim/Users/index | org/basic": 400,+ "POST scim/Users/index | org/bearer": 401,+ "POST scim/Users/index | project/basic": 403,+ "POST scim/Users/index | project/bearer": 403,"POST score-configs/index | admin/admin": 401,"POST score-configs/index | agent/basic": 401,"POST score-configs/index | agent/bearer": 401,@@ -653,6 +814,13 @@ exports[`project-route auth parity > legacy matches the main-captured baseline 1"POST v2/evaluators/index | org/bearer": 401,"POST v2/evaluators/index | project/basic": 400,"POST v2/evaluators/index | project/bearer": 403,+ "PUT integrations/blob-storage/index | admin/admin": 401,+ "PUT integrations/blob-storage/index | agent/basic": 401,+ "PUT integrations/blob-storage/index | agent/bearer": 401,+ "PUT integrations/blob-storage/index | org/basic": 400,+ "PUT integrations/blob-storage/index | org/bearer": 401,+ "PUT integrations/blob-storage/index | project/basic": 403,+ "PUT integrations/blob-storage/index | project/bearer": 403,"PUT llm-connections/index | admin/admin": 403,"PUT llm-connections/index | agent/basic": 401,"PUT llm-connections/index | agent/bearer": 401,@@ -667,5 +835,33 @@ exports[`project-route auth parity > legacy matches the main-captured baseline 1"PUT models/[modelId]/index | org/bearer": 401,"PUT models/[modelId]/index | project/basic": 400,"PUT models/[modelId]/index | project/bearer": 403,+ "PUT organizations/memberships/index | admin/admin": 401,+ "PUT organizations/memberships/index | agent/basic": 401,+ "PUT organizations/memberships/index | agent/bearer": 401,+ "PUT organizations/memberships/index | org/basic": 400,+ "PUT organizations/memberships/index | org/bearer": 401,+ "PUT organizations/memberships/index | project/basic": 403,+ "PUT organizations/memberships/index | project/bearer": 403,+ "PUT projects/[projectId]/index | admin/admin": 401,+ "PUT projects/[projectId]/index | agent/basic": 401,+ "PUT projects/[projectId]/index | agent/bearer": 401,+ "PUT projects/[projectId]/index | org/basic": 404,+ "PUT projects/[projectId]/index | org/bearer": 401,+ "PUT projects/[projectId]/index | project/basic": 403,+ "PUT projects/[projectId]/index | project/bearer": 403,+ "PUT projects/[projectId]/memberships/index | admin/admin": 401,+ "PUT projects/[projectId]/memberships/index | agent/basic": 401,+ "PUT projects/[projectId]/memberships/index | agent/bearer": 401,+ "PUT projects/[projectId]/memberships/index | org/basic": 404,+ "PUT projects/[projectId]/memberships/index | org/bearer": 401,+ "PUT projects/[projectId]/memberships/index | project/basic": 403,+ "PUT projects/[projectId]/memberships/index | project/bearer": 403,+ "PUT scim/Users/[id] | admin/admin": 401,+ "PUT scim/Users/[id] | agent/basic": 401,+ "PUT scim/Users/[id] | agent/bearer": 401,+ "PUT scim/Users/[id] | org/basic": 404,+ "PUT scim/Users/[id] | org/bearer": 401,+ "PUT scim/Users/[id] | project/basic": 403,+ "PUT scim/Users/[id] | project/bearer": 403,}`;diff --git a/web/src/__tests__/server/project-route-auth-enforce-scope.servertest.ts b/web/src/__tests__/server/project-route-auth-enforce-scope.servertest.tsdeleted file mode 100644index 934f9774e6..0000000000--- a/web/src/__tests__/server/project-route-auth-enforce-scope.servertest.ts+++ /dev/null@@ -1,138 +0,0 @@-import { type NextApiRequest } from "next";--import {- createBasicAuthHeader,- createOrgProjectAndApiKey,-} from "@langfuse/shared/src/server";--import { env } from "@/src/env.mjs";-import { type VerifyAuthParams } from "@/src/features/public-api/server/createAuthedProjectAPIRoute";--// Proves the enforce mapper returns a scope byte-identical to legacy's across-// credential kinds. The parity matrix asserts status; this asserts scope-// fields. verifyAuth is imported dynamically so the authenticator singleton-// captures the admin key set in beforeAll.--type VerifyAuth = (- params: VerifyAuthParams,-) => Promise<{ validKey: true; scope: Record<string, unknown> }>;--const adminApiKey = "test-admin-api-key-enforce-scope";--let verifyAuth: VerifyAuth;-let projectId = "";-let publicKey = "";-let secretKey = "";--let originalMigration: string | undefined;-let originalAdminApiKey: string | undefined;-let originalCloudRegion: string | undefined;--const reqWith = (headers: Record<string, string | undefined>): NextApiRequest =>- ({ headers, method: "GET" }) as unknown as NextApiRequest;--const setMode = (mode: string) => {- (env as any).API_AUTH_MIGRATION = mode;-};--const dropScopeKey = ({- scope: _apiKeyScope,- ...rest-}: Record<string, unknown>) => rest;--const scopeUnderModes = async (params: VerifyAuthParams) => {- setMode("legacy");- const legacy = await verifyAuth(params);- setMode("enforce");- const enforce = await verifyAuth(params);- return { legacy: legacy.scope, enforce: enforce.scope };-};--describe("enforce maps principals to legacy-identical scopes", () => {- beforeAll(async () => {- originalMigration = (env as any).API_AUTH_MIGRATION;- originalAdminApiKey = (env as any).ADMIN_API_KEY;- originalCloudRegion = (env as any).NEXT_PUBLIC_LANGFUSE_CLOUD_REGION;- (env as any).ADMIN_API_KEY = adminApiKey;-- ({ verifyAuth } =- (await import("@/src/features/public-api/server/createAuthedProjectAPIRoute")) as unknown as {- verifyAuth: VerifyAuth;- });-- const base = await createOrgProjectAndApiKey();- projectId = base.projectId;- publicKey = base.publicKey;- secretKey = base.secretKey;- });-- afterAll(() => {- (env as any).API_AUTH_MIGRATION = originalMigration;- (env as any).ADMIN_API_KEY = originalAdminApiKey;- (env as any).NEXT_PUBLIC_LANGFUSE_CLOUD_REGION = originalCloudRegion;- });-- it("private-key basic yields a legacy-identical project scope", async () => {- const { legacy, enforce } = await scopeUnderModes({- req: reqWith({- authorization: createBasicAuthHeader(publicKey, secretKey),- }),- name: "Get Traces",- action: "traces:read",- allowedAccessLevels: ["project"],- });- expect(enforce.accessLevel).toBe("project");- expect(enforce.projectId).toBe(projectId);- expect(dropScopeKey(enforce)).toEqual(dropScopeKey(legacy));- });-- it("public-key bearer on a score-ingest route yields the scores access level", async () => {- const { legacy, enforce } = await scopeUnderModes({- req: reqWith({ authorization: `Bearer ${publicKey}` }),- name: "Create Score",- action: "scores:create",- allowedAccessLevels: ["project", "scores"],- });- expect(enforce.accessLevel).toBe("scores");- expect(dropScopeKey(enforce)).toEqual(dropScopeKey(legacy));- });-- it("admin key on self-host yields the synthesized admin scope", async () => {- (env as any).NEXT_PUBLIC_LANGFUSE_CLOUD_REGION = undefined;- const { legacy, enforce } = await scopeUnderModes({- req: reqWith({- authorization: `Bearer ${adminApiKey}`,- "x-langfuse-admin-api-key": adminApiKey,- "x-langfuse-project-id": projectId,- }),- name: "Get Models",- action: "models:read",- isAdminApiKeyAuthAllowed: true,- });- expect(enforce.apiKeyId).toBe("ADMIN_API_KEY");- expect(enforce.projectId).toBe(projectId);- expect(dropScopeKey(enforce)).toEqual(dropScopeKey(legacy));- });-- it("admin key on Langfuse Cloud is refused in legacy and enforce", async () => {- (env as any).NEXT_PUBLIC_LANGFUSE_CLOUD_REGION = "us";- const params: VerifyAuthParams = {- req: reqWith({- authorization: `Bearer ${adminApiKey}`,- "x-langfuse-admin-api-key": adminApiKey,- "x-langfuse-project-id": projectId,- }),- name: "Get Models",- action: "models:read",- isAdminApiKeyAuthAllowed: true,- };- const cloudDenial = {- status: 403,- message: "Admin API key auth is not available on Langfuse Cloud",- };- setMode("legacy");- await expect(verifyAuth(params)).rejects.toEqual(cloudDenial);- setMode("enforce");- await expect(verifyAuth(params)).rejects.toEqual(cloudDenial);- });-});diff --git a/web/src/__tests__/server/project-route-auth-parity.servertest.ts b/web/src/__tests__/server/public-api-auth-parity.servertest.tssimilarity index 80%rename from web/src/__tests__/server/project-route-auth-parity.servertest.tsrename to web/src/__tests__/server/public-api-auth-parity.servertest.tsindex b3280c6ffe..a7b771015e 100644--- a/web/src/__tests__/server/project-route-auth-parity.servertest.ts+++ b/web/src/__tests__/server/public-api-auth-parity.servertest.ts@@ -12,18 +12,18 @@ import {createOrgProjectAndApiKey,} from "@langfuse/shared/src/server";-// Pins the project-route authorization seam to legacy: sweeps every project-// public-API route across migration modes and key kinds, recording each cell's-// status. Shadow/enforce must equal legacy (cross-mode); a main-captured-// snapshot pins legacy across the refactor (cross-branch). Value is status only.+// Pins the public-API authorization seam to legacy: sweeps every route across+// migration modes and key kinds, recording each cell's status. Shadow and+// enforce must equal legacy (cross-mode); a main-captured snapshot pins legacy+// across the refactor (cross-branch). Value is status only.type HttpMethod = "GET" | "POST" | "PUT" | "PATCH" | "DELETE";type Route = { route: string; methods: HttpMethod[] };-// Project routes under test, grouped by domain. `route` is the path under+// Routes under test, grouped by domain. `route` is the path under// pages/api/public/ (import path + completeness key); `methods` are its real-// supported methods.+// supported methods. Project routes dispatch through createAuthedProjectAPIRoute.const projectRoutes: Route[] = [{ route: "traces/index", methods: ["GET", "POST", "DELETE"] },{ route: "traces/[traceId]", methods: ["GET", "DELETE"] },@@ -110,8 +110,33 @@ const projectRoutes: Route[] = [},];-// Non-project public files, subtracted from the filesystem walk before the-// completeness guard compares it to the table.+// Org and misc routes call shadowAuth directly from the handler body.+const orgRoutes: Route[] = [+ { route: "organizations/apiKeys/index", methods: ["GET"] },+ {+ route: "organizations/memberships/index",+ methods: ["GET", "PUT", "DELETE"],+ },+ { route: "organizations/projects/index", methods: ["GET"] },+ { route: "projects/index", methods: ["GET", "POST"] },+ { route: "projects/[projectId]/index", methods: ["PUT", "DELETE"] },+ { route: "projects/[projectId]/apiKeys/index", methods: ["GET", "POST"] },+ { route: "projects/[projectId]/apiKeys/[apiKeyId]", methods: ["DELETE"] },+ {+ route: "projects/[projectId]/memberships/index",+ methods: ["GET", "PUT", "DELETE"],+ },+ { route: "scim/ResourceTypes", methods: ["GET"] },+ { route: "scim/Schemas", methods: ["GET"] },+ { route: "scim/ServiceProviderConfig", methods: ["GET"] },+ { route: "scim/Users/index", methods: ["GET", "POST"] },+ { route: "scim/Users/[id]", methods: ["GET", "PUT", "PATCH", "DELETE"] },+ { route: "integrations/blob-storage/index", methods: ["GET", "PUT"] },+ { route: "integrations/blob-storage/[id]", methods: ["GET", "DELETE"] },+];++// Public files outside both tables, subtracted from the filesystem walk before+// the completeness guard compares it to the tables.const denylistPrefixes = ["health", // liveness probe"ready", // readiness probe@@ -120,10 +145,6 @@ const denylistPrefixes = ["v2/prompts", // prompt list/name handlers, own auth path"mcp", // MCP server, own auth path"otel", // ingestion handlers read the raw request stream, not drivable via node-mocks-http- "integrations", // blob-storage integration, own auth path- "organizations", // organization-scoped, not project seam- "projects", // organization-scoped, not project seam- "scim", // SCIM, own auth path"slack", // Slack OAuth, own auth path];@@ -161,6 +182,7 @@ function queryForRoute(route: string): Record<string, string> {/** getHeaders derives a key kind's header sets: org/project/agent send basic + bearer, admin sends its single triple. */function getHeaders(apiKeyKind: ApiKeyKind,+ route: string,): { headerKind: string; headers: Record<string, string> }[] {if (apiKeyKind === "admin") {return [@@ -176,9 +198,10 @@ function getHeaders(}const { publicKey, secretKey } = keys[apiKeyKind];// An org key has no bound project, so a realistic org request names its target- // via header; project/agent keys resolve their project from the key itself.+ // via header unless the URL already does; project/agent keys resolve their+ // project from the key itself.const target =- apiKeyKind === "org"+ apiKeyKind === "org" && !route.includes("[projectId]")? { "x-langfuse-project-id": fixtureProjectId }: undefined;return [@@ -222,12 +245,12 @@ async function callRoute(type Cell = { key: string; run: () => Promise<number> };/** matrixCells lists every route × method × key kind × header kind cell in source order. */-function matrixCells(): Cell[] {+function matrixCells(routes: Route[]): Cell[] {const cells: Cell[] = [];- for (const { route, methods } of projectRoutes) {+ for (const { route, methods } of routes) {for (const method of methods) {for (const apiKeyKind of apiKeyKinds) {- for (const { headerKind, headers } of getHeaders(apiKeyKind)) {+ for (const { headerKind, headers } of getHeaders(apiKeyKind, route)) {cells.push({key: `${method} ${route} | ${apiKeyKind}/${headerKind}`,run: () => callRoute(route, method, headers),@@ -242,7 +265,7 @@ function matrixCells(): Cell[] {/** runMatrix runs every cell in one mode with bounded concurrency, returning a flat status-by-cell map in source order. */async function runMatrix(mode: MigrationMode): Promise<Record<string, number>> {(env as any).API_AUTH_MIGRATION = mode;- const cells = matrixCells();+ const cells = matrixCells([...projectRoutes, ...orgRoutes]);const statuses = new Array<number>(cells.length);let next = 0;const worker = async () => {@@ -283,7 +306,13 @@ function walkRoutes(): string[] {return routes;}-describe("project-route auth parity", () => {+// Enforce cells that intentionally diverge from legacy; every other cell must match.+const enforceDivergences: Record<string, number> = {+ // org keys hold project:read, which legacy's ["project"] tier gate refused+ "GET projects/index | org/basic": 200,+};++describe("public-api auth parity", () => {beforeAll(async () => {originalMigration = (env as any).API_AUTH_MIGRATION;originalAdminApiKey = (env as any).ADMIN_API_KEY;@@ -328,17 +357,22 @@ describe("project-route auth parity", () => {expect(matrices.shadow).toEqual(matrices.legacy);});- it("enforce is byte-identical to legacy", () => {- expect(matrices.enforce).toEqual(matrices.legacy);+ it("enforce matches legacy except documented divergences", () => {+ expect(matrices.enforce).toEqual({+ ...matrices.legacy,+ ...enforceDivergences,+ });});- it("covers every project route", () => {+ it("covers every public route", () => {const denied = (route: string) =>denylistPrefixes.some((prefix) => route === prefix || route.startsWith(`${prefix}/`),);const walked = new Set(walkRoutes().filter((route) => !denied(route)));- const tabled = new Set(projectRoutes.map((r) => r.route));+ const tabled = new Set(+ [...projectRoutes, ...orgRoutes].map((r) => r.route),+ );expect(walked).toEqual(tabled);});});diff --git a/web/src/__tests__/server/shadowAuth.servertest.ts b/web/src/__tests__/server/shadowAuth.servertest.tsnew file mode 100644index 0000000000..07f6cd0f3f--- /dev/null+++ b/web/src/__tests__/server/shadowAuth.servertest.ts@@ -0,0 +1,413 @@+import { randomUUID } from "crypto";++import { type NextApiRequest } from "next";++import { prisma } from "@langfuse/shared/src/db";+import {+ createBasicAuthHeader,+ createOrgProjectAndApiKey,+ createShaHash,+ getDisplaySecretKey,+} from "@langfuse/shared/src/server";++import { env } from "@/src/env.mjs";+import { authorize } from "@/src/features/auth/policy/authorize";+import { type ShadowAuthParams } from "@/src/features/public-api/server/shadowAuth";+import {+ type AuthorizationContext,+ type OrganizationAction,+ type ProjectAction,+} from "@/src/features/auth/policy/types";++// The seam is imported dynamically so the authenticator singleton captures+// the admin key set in beforeAll.++type ShadowResult =+ | { success: true; scope: Record<string, unknown> }+ | { success: false; error: { httpCode: number; message: string } };++type ShadowAuth = (params: ShadowAuthParams) => Promise<ShadowResult>;++type Authenticator = {+ authenticate: (params: {+ headers: { authorization: string };+ }) => Promise<+ { success: true; context: AuthorizationContext } | { success: false }+ >;+};++const adminApiKey = "test-admin-api-key-direct-enforce-scope";++let shadowAuth: ShadowAuth;+let authenticator: Authenticator;+let orgId = "";+let projectId = "";+let foreignProjectId = "";+let orgAuth = "";+let projectAuth = "";+let projectPublicKey = "";++let originalMigration: string | undefined;+let originalAdminApiKey: string | undefined;+let originalCloudRegion: string | undefined;++const reqWith = (+ headers: Record<string, string | undefined>,+ query: Record<string, string> = {},+): NextApiRequest =>+ ({ headers, method: "GET", query }) as unknown as NextApiRequest;++const setMode = (mode: string) => {+ (env as any).API_AUTH_MIGRATION = mode;+};++const dropScopeKey = ({+ scope: _apiKeyScope,+ ...rest+}: Record<string, unknown>) => rest;++const orgResultUnderModes = async (+ authorization: string,+ action: OrganizationAction = "projects:read",+) => {+ const params: ShadowAuthParams = {+ req: reqWith({ authorization }),+ action,+ allowedAccessLevels: ["organization"],+ };+ setMode("legacy");+ const legacy = await shadowAuth(params);+ setMode("enforce");+ const enforce = await shadowAuth(params);+ return { legacy, enforce };+};++const projectResultUnderModes = async (+ authorization: string,+ target?: string,+) => {+ const params: ShadowAuthParams = {+ req: reqWith({ authorization, "x-langfuse-project-id": target }),+ action: "project:read",+ allowedAccessLevels: ["project"],+ };+ setMode("legacy");+ const legacy = await shadowAuth(params);+ setMode("enforce");+ const enforce = await shadowAuth(params);+ return { legacy, enforce };+};++const projectNestedUnderModes = async (+ authorization: string,+ target: string,+ action: ProjectAction = "apiKeys:read",+) => {+ const params: ShadowAuthParams = {+ req: reqWith({ authorization }, { projectId: target }),+ action,+ allowedAccessLevels: ["organization"],+ };+ setMode("legacy");+ const legacy = await shadowAuth(params);+ setMode("enforce");+ const enforce = await shadowAuth(params);+ return { legacy, enforce };+};++const resultsUnderModes = async (params: ShadowAuthParams) => {+ setMode("legacy");+ const legacy = await shadowAuth(params);+ setMode("enforce");+ const enforce = await shadowAuth(params);+ return { legacy, enforce };+};++const scopeOf = (result: ShadowResult): Record<string, unknown> => {+ if (!result.success) throw new Error(`denied with ${result.error.httpCode}`);+ return result.scope;+};++const createOrgApiKey = async (targetOrgId: string) => {+ const publicKey = `pk-lf-${randomUUID()}`;+ const secretKey = `sk-lf-${randomUUID()}`;+ await prisma.apiKey.create({+ data: {+ id: randomUUID(),+ orgId: targetOrgId,+ publicKey,+ hashedSecretKey: `test-hashed-secret-key-${randomUUID()}`,+ fastHashedSecretKey: createShaHash(secretKey, env.SALT as string),+ displaySecretKey: getDisplaySecretKey(secretKey),+ scope: "ORGANIZATION",+ },+ });+ return createBasicAuthHeader(publicKey, secretKey);+};++const createOrgWithoutProjects = async () => {+ const org = await prisma.organization.create({+ data: { id: randomUUID(), name: randomUUID() },+ });+ return { orgId: org.id, auth: await createOrgApiKey(org.id) };+};++const contextFor = async (+ authorization: string,+): Promise<AuthorizationContext> => {+ const authn = await authenticator.authenticate({+ headers: { authorization },+ });+ if (!authn.success) throw new Error("authentication failed");+ return authn.context;+};++const ownedProjectIds = (context: AuthorizationContext): string[] =>+ context.principal.kind === "apiKey"+ ? context.principal.organizations.flatMap((o) => o.projectIds)+ : [];++describe("shadowAuth maps principals to legacy-identical scopes", () => {+ beforeAll(async () => {+ originalMigration = (env as any).API_AUTH_MIGRATION;+ originalAdminApiKey = (env as any).ADMIN_API_KEY;+ originalCloudRegion = (env as any).NEXT_PUBLIC_LANGFUSE_CLOUD_REGION;+ (env as any).ADMIN_API_KEY = adminApiKey;++ ({ shadowAuth } =+ (await import("@/src/features/public-api/server/shadowAuth")) as unknown as {+ shadowAuth: ShadowAuth;+ });+ ({ authenticator } =+ (await import("@/src/features/apiKey/authenticator")) as unknown as {+ authenticator: Authenticator;+ });++ const base = await createOrgProjectAndApiKey();+ orgId = base.orgId;+ projectId = base.projectId;+ projectAuth = base.auth;+ projectPublicKey = base.publicKey;+ orgAuth = await createOrgApiKey(orgId);++ const foreign = await createOrgProjectAndApiKey();+ foreignProjectId = foreign.projectId;+ });++ afterAll(() => {+ (env as any).API_AUTH_MIGRATION = originalMigration;+ (env as any).ADMIN_API_KEY = originalAdminApiKey;+ (env as any).NEXT_PUBLIC_LANGFUSE_CLOUD_REGION = originalCloudRegion;+ });++ it("an organization key on an org route yields a legacy-identical org scope", async () => {+ const { legacy, enforce } = await orgResultUnderModes(orgAuth);+ expect(scopeOf(enforce).accessLevel).toBe("organization");+ expect(scopeOf(enforce).orgId).toBe(orgId);+ expect(scopeOf(enforce).projectId).toBeNull();+ expect(dropScopeKey(scopeOf(enforce))).toEqual(+ dropScopeKey(scopeOf(legacy)),+ );+ });++ const orgRouteActions: OrganizationAction[] = [+ "organization:CRUD_apiKeys",+ "organizationMembers:read",+ "organizationMembers:CUD",+ "projects:create",+ ];++ it.each(orgRouteActions)(+ "an organization key is authorized for %s in both modes",+ async (action) => {+ const { legacy, enforce } = await orgResultUnderModes(orgAuth, action);+ expect(scopeOf(enforce).accessLevel).toBe("organization");+ expect(dropScopeKey(scopeOf(enforce))).toEqual(+ dropScopeKey(scopeOf(legacy)),+ );+ },+ );++ it.each(orgRouteActions)(+ "a project key on an org route 403s for %s in both modes",+ async (action) => {+ const { legacy, enforce } = await orgResultUnderModes(+ projectAuth,+ action,+ );+ expect(legacy).toMatchObject({+ success: false,+ error: { httpCode: 403 },+ });+ expect(enforce).toMatchObject({+ success: false,+ error: { httpCode: 403 },+ });+ },+ );++ it("a project key on a project route yields a legacy-identical project scope", async () => {+ const { legacy, enforce } = await projectResultUnderModes(projectAuth);+ expect(scopeOf(enforce).accessLevel).toBe("project");+ expect(scopeOf(enforce).projectId).toBe(projectId);+ expect(dropScopeKey(scopeOf(enforce))).toEqual(+ dropScopeKey(scopeOf(legacy)),+ );+ });++ it("a project key on an org route 403s in both modes", async () => {+ const { legacy, enforce } = await orgResultUnderModes(projectAuth);+ expect(legacy).toMatchObject({ success: false, error: { httpCode: 403 } });+ expect(enforce).toMatchObject({ success: false, error: { httpCode: 403 } });+ });++ it("an organization key naming a project it owns on a project route 403s in legacy and authorizes its own project in enforce", async () => {+ const { legacy, enforce } = await projectResultUnderModes(+ orgAuth,+ projectId,+ );+ expect(legacy).toMatchObject({ success: false, error: { httpCode: 403 } });+ expect(scopeOf(enforce).projectId).toBe(projectId);+ expect(scopeOf(enforce).orgId).toBe(orgId);+ });++ it("an organization key naming no project 403s in both modes", async () => {+ const { legacy, enforce } = await projectResultUnderModes(orgAuth);+ expect(legacy).toMatchObject({ success: false, error: { httpCode: 403 } });+ expect(enforce).toMatchObject({ success: false, error: { httpCode: 403 } });+ });++ it("a bearer-presented project key on a project route 403s in both modes", async () => {+ const { legacy, enforce } = await projectResultUnderModes(+ `Bearer ${projectPublicKey}`,+ );+ expect(legacy).toMatchObject({ success: false, error: { httpCode: 403 } });+ expect(enforce).toMatchObject({ success: false, error: { httpCode: 403 } });+ });++ it("an organization key on a project-nested route stays org-gated in legacy and authorizes its own project in enforce", async () => {+ const { legacy, enforce } = await projectNestedUnderModes(+ orgAuth,+ projectId,+ );+ expect(scopeOf(legacy).accessLevel).toBe("organization");+ expect(scopeOf(enforce).projectId).toBe(projectId);+ expect(scopeOf(enforce).orgId).toBe(orgId);+ });++ it("an organization key on a project-nested route 404s in enforce for a project it does not own, as the legacy handler does", async () => {+ const { legacy, enforce } = await projectNestedUnderModes(+ orgAuth,+ foreignProjectId,+ );+ expect(scopeOf(legacy).accessLevel).toBe("organization");+ expect(enforce).toMatchObject({ success: false, error: { httpCode: 404 } });+ });++ it("a project key on a project-nested route 403s in both modes", async () => {+ const { legacy, enforce } = await projectNestedUnderModes(+ projectAuth,+ projectId,+ );+ expect(legacy).toMatchObject({ success: false, error: { httpCode: 403 } });+ expect(enforce).toMatchObject({ success: false, error: { httpCode: 403 } });+ });++ it("an organization key is granted project:read on a project it owns", async () => {+ const context = await contextFor(orgAuth);+ expect(ownedProjectIds(context)).toContain(projectId);+ expect(authorize(context, "project:read", { projectId }).success).toBe(+ true,+ );+ });++ it("an organization key is denied project:read on a project it does not own", async () => {+ const context = await contextFor(orgAuth);+ expect(+ authorize(context, "project:read", { projectId: foreignProjectId })+ .success,+ ).toBe(false);+ });++ it("an organization with no projects exposes no project ids to the per-project gate", async () => {+ const { auth } = await createOrgWithoutProjects();+ expect(ownedProjectIds(await contextFor(auth))).toEqual([]);+ });++ it("the admin key is refused on both dispatch families in both modes", async () => {+ const admin = `Bearer ${adminApiKey}`;+ const org = await orgResultUnderModes(admin);+ const project = await projectResultUnderModes(admin);+ expect(org.legacy).toMatchObject({+ success: false,+ error: { httpCode: 401 },+ });+ expect(org.enforce).toMatchObject({+ success: false,+ error: { httpCode: 401 },+ });+ expect(project.legacy).toMatchObject({+ success: false,+ error: { httpCode: 401 },+ });+ expect(project.enforce).toMatchObject({+ success: false,+ error: { httpCode: 401 },+ });+ });++ it("a public-key bearer on a score-ingest route yields the scores access level", async () => {+ const { legacy, enforce } = await resultsUnderModes({+ req: reqWith({ authorization: `Bearer ${projectPublicKey}` }),+ action: "scores:create",+ allowedAccessLevels: ["project", "scores"],+ });+ expect(scopeOf(enforce).accessLevel).toBe("scores");+ expect(dropScopeKey(scopeOf(enforce))).toEqual(+ dropScopeKey(scopeOf(legacy)),+ );+ });++ it("an admin key on self-host yields the synthesized admin scope", async () => {+ (env as any).NEXT_PUBLIC_LANGFUSE_CLOUD_REGION = undefined;+ const { legacy, enforce } = await resultsUnderModes({+ req: reqWith({+ authorization: `Bearer ${adminApiKey}`,+ "x-langfuse-admin-api-key": adminApiKey,+ "x-langfuse-project-id": projectId,+ }),+ action: "models:read",+ isAdminApiKeyAuthAllowed: true,+ allowedAccessLevels: ["project"],+ });+ expect(scopeOf(enforce).apiKeyId).toBe("ADMIN_API_KEY");+ expect(scopeOf(enforce).projectId).toBe(projectId);+ expect(dropScopeKey(scopeOf(enforce))).toEqual(+ dropScopeKey(scopeOf(legacy)),+ );+ });++ it("an admin key on Langfuse Cloud is refused in legacy and enforce", async () => {+ (env as any).NEXT_PUBLIC_LANGFUSE_CLOUD_REGION = "us";+ const params: ShadowAuthParams = {+ req: reqWith({+ authorization: `Bearer ${adminApiKey}`,+ "x-langfuse-admin-api-key": adminApiKey,+ "x-langfuse-project-id": projectId,+ }),+ action: "models:read",+ isAdminApiKeyAuthAllowed: true,+ allowedAccessLevels: ["project"],+ };+ const cloudDenial = {+ success: false,+ error: {+ httpCode: 403,+ message: "Admin API key auth is not available on Langfuse Cloud",+ },+ };+ const { legacy, enforce } = await resultsUnderModes(params);+ expect(legacy).toMatchObject(cloudDenial);+ expect(enforce).toMatchObject(cloudDenial);+ });+});diff --git a/web/src/__tests__/server/unit/apiKey/authenticator.servertest.ts b/web/src/__tests__/server/unit/apiKey/authenticator.servertest.tsindex d032444169..156f817255 100644--- a/web/src/__tests__/server/unit/apiKey/authenticator.servertest.ts+++ b/web/src/__tests__/server/unit/apiKey/authenticator.servertest.ts@@ -1,8 +1,12 @@import { type Redis } from "ioredis";-import { beforeEach, describe, expect, it, vi } from "vitest";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";import { type ApiKey, type PrismaClient } from "@langfuse/shared/src/db";-import { InternalServerError, UnauthorizedError } from "@langfuse/shared";+import {+ ForbiddenError,+ InternalServerError,+ UnauthorizedError,+} from "@langfuse/shared";import {AUTHZ_CONTEXT_CACHE_KEY_PREFIX,API_KEY_CACHE_KEY_PREFIX,@@ -18,6 +22,7 @@ import {import { ContextResolver } from "@/src/features/auth/policy/contextResolver";import { Verifier } from "@/src/features/apiKey/verifier";import { type ApiKeyRepository } from "@/src/features/apiKey/apiKeyRepository";+import { env } from "@/src/env.mjs";const SALT = "test-salt";const ORG = "org_1";@@ -101,9 +106,20 @@ const bearer = (token: string) => ({describe("Authenticator consolidated context cache", () => {let verifier: Verifier;+ let originalCloudRegion: string | undefined;beforeEach(() => {verifier = new Verifier(store(apiKey()), SALT);+ originalCloudRegion = env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION;+ (+ env as { NEXT_PUBLIC_LANGFUSE_CLOUD_REGION?: string }+ ).NEXT_PUBLIC_LANGFUSE_CLOUD_REGION = undefined;+ });++ afterEach(() => {+ (+ env as { NEXT_PUBLIC_LANGFUSE_CLOUD_REGION?: string }+ ).NEXT_PUBLIC_LANGFUSE_CLOUD_REGION = originalCloudRegion;});it("miss then hit: first call resolves via verify and caches; second call serves from cache without verifying", async () => {@@ -248,6 +264,25 @@ describe("Authenticator consolidated context cache", () => {}});+ it("admin key on a cloud region: 403s even when the route allows it", async () => {+ (+ env as { NEXT_PUBLIC_LANGFUSE_CLOUD_REGION?: string }+ ).NEXT_PUBLIC_LANGFUSE_CLOUD_REGION = "US";+ const auth = new Authenticator(+ new Verifier(store(apiKey()), SALT, KNOWN_SECRET),+ resolver,+ new AuthenticatorCache(fakeRedis(), SALT),+ );+ const result = await auth.authenticate({+ ...bearer(KNOWN_SECRET),+ isAdminApiKeyAuthAllowed: true,+ });+ expect(result.success).toBe(false);+ if (!result.success) {+ expect(result.error).toBeInstanceOf(ForbiddenError);+ }+ });+it("no-ops the cache when disabled", async () => {const nullCacheAuth = new Authenticator(verifier,diff --git a/web/src/__tests__/server/unit/policy/authorize.servertest.ts b/web/src/__tests__/server/unit/policy/authorize.servertest.tsindex f7025354c8..d678317969 100644--- a/web/src/__tests__/server/unit/policy/authorize.servertest.ts+++ b/web/src/__tests__/server/unit/policy/authorize.servertest.ts@@ -55,6 +55,7 @@ const ctx = (policies: Policy[]): AuthorizationContext => ({scope: "PROJECT",presentation: "privateKey",organizations: [],+ boundResource: { orgId: "org_1", projectId: "prj_1" },},policies,});diff --git a/web/src/__tests__/server/unit/policy/contextResolver.servertest.ts b/web/src/__tests__/server/unit/policy/contextResolver.servertest.tsindex 8619698b87..eb83eab067 100644--- a/web/src/__tests__/server/unit/policy/contextResolver.servertest.ts+++ b/web/src/__tests__/server/unit/policy/contextResolver.servertest.ts@@ -106,7 +106,7 @@ describe("presentation rides in the input", () => {});describe("expansion table: scope PROJECT, privateKey", () => {- it("grants the full project vocabulary over the bound project only", async () => {+ it("grants the project vocabulary less project administration over the bound project only", async () => {const ctx = await contextFor({authorization: "privateKey",apiKey: apiKey(),@@ -114,6 +114,15 @@ describe("expansion table: scope PROJECT, privateKey", () => {expect(authorize(ctx, "prompts:read", { projectId: PRJ }).success).toBe(true,);+ expect(authorize(ctx, "project:read", { projectId: PRJ }).success).toBe(+ true,+ );+ expect(authorize(ctx, "apiKeys:CUD", { projectId: PRJ }).success).toBe(+ false,+ );+ expect(authorize(ctx, "project:update", { projectId: PRJ }).success).toBe(+ false,+ );expect(authorize(ctx, "prompts:read", { projectId: OTHER_PRJ }).success,).toBe(false);@@ -128,14 +137,21 @@ describe("expansion table: scope PROJECT, privateKey", () => {});describe("expansion table: scope ORGANIZATION, privateKey", () => {- it("grants the full org vocabulary and project:read across org projects", async () => {+ it("grants the org vocabulary plus project administration over its own projects only", async () => {const ctx = await contextFor({authorization: "privateKey",apiKey: orgKey(),});+ expect(authorize(ctx, "projects:read", { orgId: ORG }).success).toBe(true);expect(authorize(ctx, "project:read", { projectId: PRJ }).success).toBe(true,);+ expect(authorize(ctx, "apiKeys:CUD", { projectId: PRJ }).success).toBe(+ true,+ );+ expect(+ authorize(ctx, "project:read", { projectId: "prj_foreign" }).success,+ ).toBe(false);expect(authorize(ctx, "traces:read", { projectId: PRJ }).success).toBe(false,);diff --git a/web/src/__tests__/server/unit/policy/enforceProjectAuth.servertest.ts b/web/src/__tests__/server/unit/policy/enforceProjectAuth.servertest.tsdeleted file mode 100644index a007070180..0000000000--- a/web/src/__tests__/server/unit/policy/enforceProjectAuth.servertest.ts+++ /dev/null@@ -1,74 +0,0 @@-import { describe, expect, it } from "vitest";--import { InvalidRequestError } from "@langfuse/shared";--import { __test } from "@/src/features/auth/policy/enforceProjectAuth";-import { type AuthorizationContext } from "@/src/features/auth/policy/types";--const { getProjectId } = __test;--const projectIdHeader = "x-langfuse-project-id";--const PRJ = "prj_1";--const projectKey = (): AuthorizationContext => ({- principal: {- kind: "apiKey",- apiKeyId: "key_1",- userId: null,- isInAppAgentKey: false,- publicKey: "pk-lf-1",- scope: "PROJECT",- presentation: "privateKey",- organizations: [],- boundResource: { projectId: PRJ },- },- policies: [],-});--const orgKey = (): AuthorizationContext => ({- principal: {- kind: "apiKey",- apiKeyId: "key_2",- userId: null,- isInAppAgentKey: false,- publicKey: "pk-lf-2",- scope: "ORGANIZATION",- presentation: "privateKey",- organizations: [],- boundResource: { orgId: "org_1" },- },- policies: [],-});--describe("getProjectId", () => {- it("resolves the bound project without a header", () => {- expect(getProjectId(projectKey(), {})).toEqual({- success: true,- projectId: PRJ,- });- });- it("resolves the bound project when the header is blank", () => {- expect(getProjectId(projectKey(), { [projectIdHeader]: "" })).toEqual({- success: true,- projectId: PRJ,- });- });- it("resolves an unbound principal from the header", () => {- expect(getProjectId(orgKey(), { [projectIdHeader]: PRJ })).toEqual({- success: true,- projectId: PRJ,- });- });- it("400s a header disagreeing with the bound project", () => {- expect(- getProjectId(projectKey(), { [projectIdHeader]: "prj_2" }),- ).toMatchObject({ success: false, error: expect.any(InvalidRequestError) });- });- it("400s when neither header nor bound project exists", () => {- expect(getProjectId(orgKey(), {})).toMatchObject({- success: false,- error: expect.any(InvalidRequestError),- });- });-});diff --git a/web/src/__tests__/server/unit/policy/shadow.servertest.ts b/web/src/__tests__/server/unit/policy/shadow.servertest.tsdeleted file mode 100644index 83e6f4a3ae..0000000000--- a/web/src/__tests__/server/unit/policy/shadow.servertest.ts+++ /dev/null@@ -1,77 +0,0 @@-import { describe, expect, it } from "vitest";--import {- diffResults,- newVerdict,- recordCoverage,- type LegacyDecision,- type NewResult,- type ParitySink,-} from "@/src/features/auth/policy/shadow";--const capture = () => {- const calls: { stat: string; tags: Record<string, string | number> }[] = [];- const sink: ParitySink = {- increment: (stat, tags) => calls.push({ stat, tags }),- span: () => undefined,- };- return { calls, sink };-};--const deny: NewResult = { success: false, error: { httpCode: 403 } };-const allow: NewResult = { success: true };--describe("diffResults — the ship-gate signal", () => {- it.each([- ["both allow", allow, { ok: true } as LegacyDecision, "match"],- ["both deny", deny, { ok: false, code: 403 } as LegacyDecision, "match"],- [- "new denies what legacy allows",- deny,- { ok: true } as LegacyDecision,- "new_denies",- ],- [- "new allows what legacy denies",- allow,- { ok: false, code: 403 } as LegacyDecision,- "new_allows",- ],- ["legacy has no gate", deny, { absent: true } as LegacyDecision, "net_new"],- ] as const)("%s", (_name, neu, legacy, result) => {- const { calls, sink } = capture();- expect(- diffResults(- neu,- legacy,- { seam: "project_route", action: "traces:read" },- sink,- ),- ).toBe(result);- expect(calls[0].tags.result).toBe(result);- });-});--describe("newVerdict maps the new result to a verdict and code", () => {- it.each([- [allow, "allow", 200],- [deny, "deny", 403],- [{ success: false, error: { httpCode: 401 } } as NewResult, "deny", 401],- [{ success: false, error: { httpCode: 400 } } as NewResult, "deny", 400],- ] as const)("%o", (result, verdict, code) => {- expect(newVerdict(result)).toEqual({ verdict, code });- });-});--describe("recordCoverage", () => {- it("counts a request against its operation", () => {- const { calls, sink } = capture();- recordCoverage("GET /api/public/v2/prompts", sink);- expect(calls).toEqual([- {- stat: "langfuse.authz.coverage",- tags: { operation: "GET /api/public/v2/prompts" },- },- ]);- });-});diff --git a/web/src/__tests__/server/unit/policy/verifyAuth.servertest.ts b/web/src/__tests__/server/unit/policy/verifyAuth.servertest.tsdeleted file mode 100644index 76271fd18f..0000000000--- a/web/src/__tests__/server/unit/policy/verifyAuth.servertest.ts+++ /dev/null@@ -1,242 +0,0 @@-import { type NextApiRequest } from "next";-import { beforeEach, describe, expect, it, vi } from "vitest";--import { ForbiddenError } from "@langfuse/shared";--const {- env,- mockLegacyVerifyAuth,- mockEnforceProjectAuth,- mockDiffResults,- mockRecordCoverage,- mockVerifyGatewayIngestionAuthorization,-} = vi.hoisted(() => ({- env: { API_AUTH_MIGRATION: "legacy" as string },- mockLegacyVerifyAuth: vi.fn(),- mockEnforceProjectAuth: vi.fn(),- mockDiffResults: vi.fn(),- mockRecordCoverage: vi.fn(),- mockVerifyGatewayIngestionAuthorization: vi.fn(),-}));--vi.mock("@/src/env.mjs", () => ({ env }));--vi.mock("@/src/features/public-api/server/verifyProjectApiKeyAuth", () => ({- verifyAuth: mockLegacyVerifyAuth,-}));--vi.mock("@/src/features/auth/policy/enforceProjectAuth", () => ({- enforceProjectAuth: mockEnforceProjectAuth,-}));--vi.mock("@/src/features/auth/policy/shadow", async (importOriginal) => ({- ...(await importOriginal<object>()),- diffResults: mockDiffResults,- recordCoverage: mockRecordCoverage,-}));--vi.mock("@/src/features/ai-gateway/server", () => ({- verifyGatewayIngestionAuthorization: mockVerifyGatewayIngestionAuthorization,-}));--import { verifyAuth } from "@/src/features/public-api/server/createAuthedProjectAPIRoute";--describe("project seam verifyAuth", () => {- const legacyScope = { scope: { projectId: "p1", accessLevel: "project" } };- const req = { headers: {}, method: "GET" } as unknown as NextApiRequest;-- const call = () =>- verifyAuth({ req, name: "Get Traces", action: "traces:read" });-- const legacyAllows = () =>- mockLegacyVerifyAuth.mockResolvedValue(legacyScope);- const legacyDenies = (status: number) =>- mockLegacyVerifyAuth.mockRejectedValue({ status, message: "legacy" });- const authzAllows = () =>- mockEnforceProjectAuth.mockResolvedValue({ success: true });- const authzDenies = () =>- mockEnforceProjectAuth.mockResolvedValue({- success: false,- error: new ForbiddenError("nope"),- });-- const principalOrg = {- orgId: "o1",- plan: "Team" as const,- rateLimitOverrides: [],- projectIds: ["p1"],- isIngestionSuspended: false,- };- const apiKeyContextResult = (presentation: "privateKey" | "publicKey") => ({- success: true as const,- projectId: "p1",- context: {- principal: {- kind: "apiKey" as const,- apiKeyId: "ak1",- userId: null,- isInAppAgentKey: false,- scope: "PROJECT" as const,- publicKey: "pk-lf-1",- presentation,- organizations: [principalOrg],- boundResource: { projectId: "p1" },- },- policies: [],- },- });- const authzAllowsApiKey = (presentation: "privateKey" | "publicKey") =>- mockEnforceProjectAuth.mockResolvedValue(apiKeyContextResult(presentation));-- beforeEach(() => {- vi.clearAllMocks();- env.API_AUTH_MIGRATION = "legacy";- });-- describe("legacy mode never runs the new pipeline", () => {- it("returns the legacy scope and skips enforceProjectAuth", async () => {- legacyAllows();- expect(await call()).toBe(legacyScope);- expect(mockEnforceProjectAuth).not.toHaveBeenCalled();- });-- it("rethrows the legacy error unchanged", async () => {- legacyDenies(403);- await expect(call()).rejects.toEqual({ status: 403, message: "legacy" });- expect(mockEnforceProjectAuth).not.toHaveBeenCalled();- });- });-- describe("gateway ingestion token opt-in", () => {- it("returns gateway authorization before selecting an API auth migration path", async () => {- const gatewayAuthorization = {- validKey: true,- scope: {- projectId: "gateway-project",- accessLevel: "project",- },- };- mockVerifyGatewayIngestionAuthorization.mockResolvedValue(- gatewayAuthorization,- );-- await expect(- verifyAuth({- req,- name: "Ingest Traces",- action: "traces:create",- allowGatewayIngestionToken: true,- }),- ).resolves.toBe(gatewayAuthorization);- expect(mockLegacyVerifyAuth).not.toHaveBeenCalled();- expect(mockEnforceProjectAuth).not.toHaveBeenCalled();- });-- it("falls through to the selected API auth path for non-gateway credentials", async () => {- mockVerifyGatewayIngestionAuthorization.mockResolvedValue(null);- legacyAllows();-- await expect(- verifyAuth({- req,- name: "Ingest Traces",- action: "traces:create",- allowGatewayIngestionToken: true,- }),- ).resolves.toBe(legacyScope);- expect(mockLegacyVerifyAuth).toHaveBeenCalledOnce();- });- });-- describe("an unrecognized mode fails safe to legacy", () => {- beforeEach(() => {- env.API_AUTH_MIGRATION = "";- });-- it("runs only legacy and skips the new pipeline and parity telemetry", async () => {- legacyAllows();- authzDenies();- expect(await call()).toBe(legacyScope);- expect(mockEnforceProjectAuth).not.toHaveBeenCalled();- expect(mockDiffResults).not.toHaveBeenCalled();- expect(mockRecordCoverage).not.toHaveBeenCalled();- });- });-- describe("shadow mode keeps responses byte-identical to legacy", () => {- beforeEach(() => {- env.API_AUTH_MIGRATION = "shadow";- });-- it("returns the legacy scope even when the new pipeline denies", async () => {- legacyAllows();- authzDenies();- expect(await call()).toBe(legacyScope);- });-- it("rethrows the legacy denial even when the new pipeline allows", async () => {- legacyDenies(401);- authzAllows();- await expect(call()).rejects.toEqual({ status: 401, message: "legacy" });- });-- it("records the parity cell and coverage counter", async () => {- legacyAllows();- authzDenies();- await call();- expect(mockRecordCoverage).toHaveBeenCalledWith("Get Traces");- expect(mockDiffResults).toHaveBeenCalledWith(- { success: false, error: expect.any(ForbiddenError) },- { ok: true },- { seam: "project_route", action: "traces:read" },- );- });- });-- describe("enforce mode is the new pipeline's sole authority", () => {- beforeEach(() => {- env.API_AUTH_MIGRATION = "enforce";- });-- it("maps a private-key principal to a legacy-shaped project scope", async () => {- authzAllowsApiKey("privateKey");- expect(await call()).toEqual({- validKey: true,- scope: {- projectId: "p1",- accessLevel: "project",- orgId: "o1",- plan: "Team",- rateLimitOverrides: [],- apiKeyId: "ak1",- publicKey: "pk-lf-1",- isIngestionSuspended: false,- isInAppAgentKey: false,- },- });- });-- it("maps a public-key presentation to the scores access level", async () => {- authzAllowsApiKey("publicKey");- expect((await call()).scope.accessLevel).toBe("scores");- });-- it("never runs legacy verify", async () => {- authzAllowsApiKey("privateKey");- await call();- expect(mockLegacyVerifyAuth).not.toHaveBeenCalled();- });-- it("throws the new pipeline's 403 when it denies", async () => {- authzDenies();- await expect(call()).rejects.toEqual({ status: 403, message: "nope" });- });-- it("does not record parity telemetry", async () => {- authzAllowsApiKey("privateKey");- await call();- expect(mockDiffResults).not.toHaveBeenCalled();- expect(mockRecordCoverage).not.toHaveBeenCalled();- });- });-});diff --git a/web/src/__tests__/server/unit/public-api/enforceAuth.servertest.ts b/web/src/__tests__/server/unit/public-api/enforceAuth.servertest.tsnew file mode 100644index 0000000000..4f3e2ea228--- /dev/null+++ b/web/src/__tests__/server/unit/public-api/enforceAuth.servertest.ts@@ -0,0 +1,124 @@+import { type NextApiRequest } from "next";+import { describe, expect, it } from "vitest";++import { ForbiddenError } from "@langfuse/shared";++import { __test } from "@/src/features/public-api/server/enforceAuth";+import {+ type AuthorizationContext,+ type BoundResource,+} from "@/src/features/auth/policy/types";++const { getOrgId, getProjectId } = __test;++const orgIdHeader = "x-langfuse-organization-id";+const projectIdHeader = "x-langfuse-project-id";++const ORG = "org_1";+const PRJ = "prj_1";++const apiKey = (+ apiKeyId: string,+ boundResource: BoundResource,+): AuthorizationContext => ({+ principal: {+ kind: "apiKey",+ apiKeyId,+ userId: null,+ isInAppAgentKey: false,+ publicKey: "pk-lf-1",+ scope: boundResource.projectId ? "PROJECT" : "ORGANIZATION",+ presentation: "privateKey",+ organizations: [],+ boundResource,+ },+ policies: [],+});++const orgKey = () => apiKey("key_1", { orgId: ORG });+const projectKey = () => apiKey("key_2", { orgId: ORG, projectId: PRJ });++const adminKey = (): AuthorizationContext => ({+ principal: { kind: "admin", userId: null },+ policies: [],+});++const req = (query = {}, headers = {}) =>+ ({ query, headers }) as unknown as NextApiRequest;++describe("getOrgId", () => {+ it("resolves the bound org without a header", () => {+ expect(getOrgId(orgKey(), req())).toEqual({ success: true, orgId: ORG });+ });+ it("resolves a project-scoped key to its own organization", () => {+ expect(getOrgId(projectKey(), req())).toEqual({+ success: true,+ orgId: ORG,+ });+ });+ it("403s a header disagreeing with the bound org", () => {+ expect(+ getOrgId(orgKey(), req({}, { [orgIdHeader]: "org_2" })),+ ).toMatchObject({ success: false, error: expect.any(ForbiddenError) });+ });+ it("403s a principal carrying no binding", () => {+ expect(getOrgId(adminKey(), req())).toMatchObject({+ success: false,+ error: expect.any(ForbiddenError),+ });+ });+});++describe("getProjectId", () => {+ it("resolves the bound project without a header", () => {+ expect(getProjectId(projectKey(), req())).toEqual({+ success: true,+ projectId: PRJ,+ });+ });+ it("resolves the bound project when the header is blank", () => {+ expect(+ getProjectId(projectKey(), req({}, { [projectIdHeader]: "" })),+ ).toEqual({ success: true, projectId: PRJ });+ });+ it("resolves an unbound principal from the header", () => {+ expect(getProjectId(orgKey(), req({}, { [projectIdHeader]: PRJ }))).toEqual(+ {+ success: true,+ projectId: PRJ,+ },+ );+ });+ it("resolves when URL, header, and bound project agree", () => {+ expect(+ getProjectId(+ projectKey(),+ req({ projectId: PRJ }, { [projectIdHeader]: PRJ }),+ ),+ ).toEqual({ success: true, projectId: PRJ });+ });+ it("403s a header disagreeing with the bound project", () => {+ expect(+ getProjectId(projectKey(), req({}, { [projectIdHeader]: "prj_2" })),+ ).toMatchObject({ success: false, error: expect.any(ForbiddenError) });+ });+ it("403s a URL disagreeing with the bound project", () => {+ expect(+ getProjectId(projectKey(), req({ projectId: "prj_2" })),+ ).toMatchObject({ success: false, error: expect.any(ForbiddenError) });+ });+ it("403s a URL disagreeing with the header", () => {+ expect(+ getProjectId(+ orgKey(),+ req({ projectId: PRJ }, { [projectIdHeader]: "prj_2" }),+ ),+ ).toMatchObject({ success: false, error: expect.any(ForbiddenError) });+ });+ it("403s when neither URL, header, nor bound project exists", () => {+ expect(getProjectId(orgKey(), req())).toMatchObject({+ success: false,+ error: expect.any(ForbiddenError),+ });+ });+});diff --git a/web/src/__tests__/server/unit/public-api/shadowAuth.servertest.ts b/web/src/__tests__/server/unit/public-api/shadowAuth.servertest.tsnew file mode 100644index 0000000000..a611e7a9bb--- /dev/null+++ b/web/src/__tests__/server/unit/public-api/shadowAuth.servertest.ts@@ -0,0 +1,402 @@+import { readFileSync } from "fs";+import { fileURLToPath } from "url";++import { type NextApiRequest } from "next";+import { beforeEach, describe, expect, it, vi } from "vitest";++import {+ ForbiddenError,+ InternalServerError,+ InvalidRequestError,+} from "@langfuse/shared";++const {+ env,+ mockVerifyScope,+ mockLegacyProjectAuth,+ mockEnforceAuth,+ mockShadowAuthDiff,+} = vi.hoisted(() => ({+ env: { API_AUTH_MIGRATION: "legacy" as string },+ mockVerifyScope: vi.fn(),+ mockLegacyProjectAuth: vi.fn(),+ mockEnforceAuth: vi.fn(),+ mockShadowAuthDiff: vi.fn(),+}));++vi.mock("@/src/env.mjs", () => ({ env }));++vi.mock("@/src/features/public-api/server/apiAuth", () => ({+ ApiAuthService: class {+ verifyAuthHeaderAndReturnScope = mockVerifyScope;+ },+}));++vi.mock("@/src/features/public-api/server/verifyProjectApiKeyAuth", () => ({+ verifyAuth: mockLegacyProjectAuth,+}));++vi.mock("@/src/features/public-api/server/enforceAuth", () => ({+ enforceAuth: mockEnforceAuth,+}));++vi.mock(+ "@/src/features/public-api/server/shadowAuthDiff",+ async (importOriginal) => ({+ ...(await importOriginal<object>()),+ shadowAuthDiff: mockShadowAuthDiff,+ }),+);++import { shadowAuth } from "@/src/features/public-api/server/shadowAuth";++const mappedFields = {+ orgId: "org_1",+ plan: "oss",+ rateLimitOverrides: [],+ apiKeyId: "key_1",+ publicKey: "pk-lf-1",+ isIngestionSuspended: false,+ isInAppAgentKey: false,+};++describe("org-family dispatch (allowedAccessLevels ['organization'])", () => {+ const orgScope = { accessLevel: "organization", orgId: "org_1" };+ const projectScope = { accessLevel: "project", projectId: "prj_1" };+ const req = { headers: {}, method: "GET" } as unknown as NextApiRequest;++ const call = () =>+ shadowAuth({+ req,+ action: "projects:read",+ allowedAccessLevels: ["organization"],+ });++ const legacyOrgKey = () =>+ mockVerifyScope.mockResolvedValue({ validKey: true, scope: orgScope });+ const legacyProjectKey = () =>+ mockVerifyScope.mockResolvedValue({ validKey: true, scope: projectScope });+ const legacyInvalid = () =>+ mockVerifyScope.mockResolvedValue({ validKey: false, error: "bad key" });+ const authzAllows = () =>+ mockEnforceAuth.mockResolvedValue({+ success: true,+ scope: { ...mappedFields, projectId: null, accessLevel: "organization" },+ });+ const authzDenies = () =>+ mockEnforceAuth.mockResolvedValue({+ success: false,+ error: new ForbiddenError("nope"),+ });++ beforeEach(() => {+ vi.clearAllMocks();+ env.API_AUTH_MIGRATION = "legacy";+ });++ describe("legacy mode never runs the new pipeline", () => {+ it("returns the legacy scope and skips enforceAuth", async () => {+ legacyOrgKey();+ expect(await call()).toEqual({ success: true, scope: orgScope });+ expect(mockEnforceAuth).not.toHaveBeenCalled();+ });++ it("returns the legacy 401 with the auth message", async () => {+ legacyInvalid();+ expect(await call()).toMatchObject({+ success: false,+ error: { httpCode: 401, message: "bad key" },+ });+ });++ it("403s a non-org key, leaving the body to the route", async () => {+ legacyProjectKey();+ expect(await call()).toMatchObject({+ success: false,+ error: { httpCode: 403, message: "Forbidden" },+ });+ });+ });++ describe("an unset migration mode falls back to legacy", () => {+ it("returns the legacy scope and skips enforceAuth", async () => {+ env.API_AUTH_MIGRATION = undefined as unknown as string;+ legacyOrgKey();+ expect(await call()).toEqual({ success: true, scope: orgScope });+ expect(mockEnforceAuth).not.toHaveBeenCalled();+ });+ });++ describe("shadow mode keeps responses byte-identical to legacy", () => {+ beforeEach(() => {+ env.API_AUTH_MIGRATION = "shadow";+ });++ it("returns the legacy scope even when the new pipeline denies", async () => {+ legacyOrgKey();+ authzDenies();+ expect(await call()).toEqual({ success: true, scope: orgScope });+ });++ it("records the parity cell", async () => {+ legacyOrgKey();+ authzDenies();+ await call();+ expect(mockShadowAuthDiff).toHaveBeenCalledWith(+ { success: false, error: expect.any(ForbiddenError) },+ { success: true, scope: orgScope },+ "projects:read",+ );+ });+ });++ describe("enforce mode decides on the new pipeline alone", () => {+ beforeEach(() => {+ env.API_AUTH_MIGRATION = "enforce";+ });++ it("returns the scope the new pipeline built, without calling legacy", async () => {+ authzAllows();+ expect(await call()).toEqual({+ success: true,+ scope: {+ ...mappedFields,+ projectId: null,+ accessLevel: "organization",+ },+ });+ expect(mockVerifyScope).not.toHaveBeenCalled();+ });++ it("passes the route's action to the new pipeline", async () => {+ authzAllows();+ await call();+ expect(mockEnforceAuth).toHaveBeenCalledWith({+ req,+ action: "projects:read",+ allowedAccessLevels: ["organization"],+ });+ });++ it("renders a new-pipeline 500 as a 500 denial", async () => {+ mockEnforceAuth.mockResolvedValue({+ success: false,+ error: new InternalServerError("unmappable principal"),+ });+ expect(await call()).toMatchObject({+ success: false,+ error: { httpCode: 500 },+ });+ });++ it("403s when the new pipeline denies, leaving the body to the route", async () => {+ authzDenies();+ expect(await call()).toMatchObject({+ success: false,+ error: { httpCode: 403, message: "nope" },+ });+ });++ it("surfaces a non-403 new denial with its own message", async () => {+ mockEnforceAuth.mockResolvedValue({+ success: false,+ error: new InvalidRequestError("no target"),+ });+ expect(await call()).toMatchObject({+ success: false,+ error: { httpCode: 400, message: "no target" },+ });+ });++ it("does not record parity telemetry", async () => {+ authzAllows();+ await call();+ expect(mockShadowAuthDiff).not.toHaveBeenCalled();+ });+ });+});++describe("project-family dispatch (allowedAccessLevels ['project'])", () => {+ const legacyScope = { scope: { projectId: "p1", accessLevel: "project" } };+ const req = { headers: {}, method: "GET" } as unknown as NextApiRequest;++ const call = () =>+ shadowAuth({+ req,+ action: "traces:read",+ allowedAccessLevels: ["project"],+ });++ const legacyAllows = () =>+ mockLegacyProjectAuth.mockResolvedValue(legacyScope);+ const legacyDenies = (status: number) =>+ mockLegacyProjectAuth.mockRejectedValue({ status, message: "legacy" });+ const authzAllows = () =>+ mockEnforceAuth.mockResolvedValue({ success: true });+ const authzDenies = () =>+ mockEnforceAuth.mockResolvedValue({+ success: false,+ error: new ForbiddenError("nope"),+ });++ const projectScope = (presentation: "privateKey" | "publicKey") => ({+ projectId: "p1",+ accessLevel: presentation === "publicKey" ? "scores" : "project",+ orgId: "o1",+ plan: "Team",+ rateLimitOverrides: [],+ apiKeyId: "ak1",+ publicKey: "pk-lf-1",+ isIngestionSuspended: false,+ isInAppAgentKey: false,+ });+ const authzAllowsApiKey = (presentation: "privateKey" | "publicKey") =>+ mockEnforceAuth.mockResolvedValue({+ success: true,+ scope: projectScope(presentation),+ });++ beforeEach(() => {+ vi.clearAllMocks();+ env.API_AUTH_MIGRATION = "legacy";+ });++ describe("legacy mode never runs the new pipeline", () => {+ it("returns the legacy scope and skips enforceAuth", async () => {+ legacyAllows();+ expect(await call()).toEqual({ success: true, scope: legacyScope.scope });+ expect(mockEnforceAuth).not.toHaveBeenCalled();+ });++ it("returns the legacy error unchanged", async () => {+ legacyDenies(403);+ expect(await call()).toMatchObject({+ success: false,+ error: { httpCode: 403, message: "legacy" },+ });+ expect(mockEnforceAuth).not.toHaveBeenCalled();+ });+ });++ describe("an unrecognized mode fails safe to legacy", () => {+ beforeEach(() => {+ env.API_AUTH_MIGRATION = "";+ });++ it("runs only legacy and skips the new pipeline and parity telemetry", async () => {+ legacyAllows();+ authzDenies();+ expect(await call()).toEqual({ success: true, scope: legacyScope.scope });+ expect(mockEnforceAuth).not.toHaveBeenCalled();+ expect(mockShadowAuthDiff).not.toHaveBeenCalled();+ });+ });++ describe("shadow mode keeps responses byte-identical to legacy", () => {+ beforeEach(() => {+ env.API_AUTH_MIGRATION = "shadow";+ });++ it("returns the legacy scope even when the new pipeline denies", async () => {+ legacyAllows();+ authzDenies();+ expect(await call()).toEqual({ success: true, scope: legacyScope.scope });+ });++ it("returns the legacy denial even when the new pipeline allows", async () => {+ legacyDenies(401);+ authzAllows();+ expect(await call()).toMatchObject({+ success: false,+ error: { httpCode: 401, message: "legacy" },+ });+ });++ it("records the parity cell", async () => {+ legacyAllows();+ authzDenies();+ await call();+ expect(mockShadowAuthDiff).toHaveBeenCalledWith(+ { success: false, error: expect.any(ForbiddenError) },+ { success: true, scope: legacyScope.scope },+ "traces:read",+ );+ });+ });++ describe("enforce mode is the new pipeline's sole authority", () => {+ beforeEach(() => {+ env.API_AUTH_MIGRATION = "enforce";+ });++ it("returns the new pipeline's project scope", async () => {+ authzAllowsApiKey("privateKey");+ expect(await call()).toEqual({+ success: true,+ scope: {+ projectId: "p1",+ accessLevel: "project",+ orgId: "o1",+ plan: "Team",+ rateLimitOverrides: [],+ apiKeyId: "ak1",+ publicKey: "pk-lf-1",+ isIngestionSuspended: false,+ isInAppAgentKey: false,+ },+ });+ });++ it("returns a scores-level scope for a public key", async () => {+ authzAllowsApiKey("publicKey");+ const result = await call();+ expect(result.success && result.scope.accessLevel).toBe("scores");+ });++ it("never runs legacy verify", async () => {+ authzAllowsApiKey("privateKey");+ await call();+ expect(mockLegacyProjectAuth).not.toHaveBeenCalled();+ });++ it("returns the new pipeline's 403 when it denies", async () => {+ authzDenies();+ expect(await call()).toMatchObject({+ success: false,+ error: { httpCode: 403, message: "nope" },+ });+ });++ it("does not record parity telemetry", async () => {+ authzAllowsApiKey("privateKey");+ await call();+ expect(mockShadowAuthDiff).not.toHaveBeenCalled();+ });+ });+});++describe("the migration-mode gate reads a declared env var", () => {+ const source = (relativeToSrc: string) =>+ readFileSync(+ fileURLToPath(new URL(`../../../../${relativeToSrc}`, import.meta.url)),+ "utf8",+ );++ it("reads only env keys env.mjs declares", () => {+ const seam = source("features/public-api/server/shadowAuth.ts");+ const schema = source("env.mjs");+ const keys = [...seam.matchAll(/\benv\.([A-Z][A-Z0-9_]*)/g)].map(+ (match) => match[1],+ );+ expect(keys.length).toBeGreaterThan(0);+ for (const key of new Set(keys)) {+ expect(schema).toMatch(new RegExp(`\\b${key}:\\s*z\\b`));+ }+ });++ it("defaults the migration mode to legacy", () => {+ expect(source("env.mjs")).toMatch(+ /API_AUTH_MIGRATION:\s*z[^;]*?\.default\("legacy"\)/,+ );+ });+});diff --git a/web/src/__tests__/server/unit/public-api/shadowAuthDiff.servertest.ts b/web/src/__tests__/server/unit/public-api/shadowAuthDiff.servertest.tsnew file mode 100644index 0000000000..77c625e2a9--- /dev/null+++ b/web/src/__tests__/server/unit/public-api/shadowAuthDiff.servertest.ts@@ -0,0 +1,56 @@+import { describe, expect, it } from "vitest";++import {+ __test,+ shadowAuthDiff,+ type LegacyDecision,+ type NewDecision,+ type Telemetry,+} from "@/src/features/public-api/server/shadowAuthDiff";++const capture = () => {+ const calls: { stat: string; tags: Record<string, string | number> }[] = [];+ const telemetry: Telemetry = {+ increment: (stat, tags) => calls.push({ stat, tags }),+ span: () => undefined,+ };+ return { calls, telemetry };+};++const deny: NewDecision = { success: false, error: { httpCode: 403 } };+const allow: NewDecision = { success: true };+const legacyAllow = {+ success: true,+ scope: { accessLevel: "project" },+} as LegacyDecision;+const legacyDeny = {+ success: false,+ error: { httpCode: 403 },+} as LegacyDecision;++describe("shadowAuthDiff — the ship-gate signal", () => {+ it.each([+ ["both allow", allow, legacyAllow, "match"],+ ["both deny", deny, legacyDeny, "match"],+ ["new denies what legacy allows", deny, legacyAllow, "new_denies"],+ ["new allows what legacy denies", allow, legacyDeny, "new_allows"],+ ["legacy has no gate", deny, { absent: true } as LegacyDecision, "net_new"],+ ] as const)("%s", (_name, newVerdict, legacyVerdict, result) => {+ const { calls, telemetry } = capture();+ expect(+ shadowAuthDiff(newVerdict, legacyVerdict, "traces:read", telemetry),+ ).toBe(result);+ expect(calls[0].tags.result).toBe(result);+ });+});++describe("newVerdict maps the new decision to a verdict and code", () => {+ it.each([+ [allow, "allow", 200],+ [deny, "deny", 403],+ [{ success: false, error: { httpCode: 401 } } as NewDecision, "deny", 401],+ [{ success: false, error: { httpCode: 400 } } as NewDecision, "deny", 400],+ ] as const)("%o", (result, verdict, code) => {+ expect(__test.newVerdict(result)).toEqual({ verdict, code });+ });+});diff --git a/web/src/__tests__/server/unit/public-api/toApiAccessScope.servertest.ts b/web/src/__tests__/server/unit/public-api/toApiAccessScope.servertest.tsnew file mode 100644index 0000000000..83436b1baa--- /dev/null+++ b/web/src/__tests__/server/unit/public-api/toApiAccessScope.servertest.ts@@ -0,0 +1,111 @@+import { describe, expect, it } from "vitest";++import { InternalServerError } from "@langfuse/shared";++import { toApiAccessScope } from "@/src/features/public-api/server/toApiAccessScope";+import { type Principal } from "@/src/features/auth/policy/types";++const scopeOrg = {+ orgId: "org_1",+ plan: "oss" as const,+ rateLimitOverrides: [],+ projectIds: ["prj_1"],+ isIngestionSuspended: false,+};++const apiKeyPrincipal = (+ scope: "ORGANIZATION" | "PROJECT",+ presentation: "privateKey" | "publicKey" = "privateKey",+): Principal => ({+ kind: "apiKey",+ apiKeyId: "key_1",+ userId: null,+ isInAppAgentKey: false,+ publicKey: "pk-lf-1",+ scope,+ presentation,+ organizations: [scopeOrg],+ boundResource:+ scope === "ORGANIZATION"+ ? { orgId: "org_1" }+ : { orgId: "org_1", projectId: "prj_1" },+});++const projectScope = {+ projectId: "prj_1",+ accessLevel: "project",+ orgId: "org_1",+ plan: "oss",+ rateLimitOverrides: [],+ apiKeyId: "key_1",+ publicKey: "pk-lf-1",+ isIngestionSuspended: false,+ isInAppAgentKey: false,+};++describe("toApiAccessScope", () => {+ it("maps an api key and its organization onto the organization scope", () => {+ expect(+ toApiAccessScope(apiKeyPrincipal("ORGANIZATION"), {+ orgId: "org_1",+ projectId: null,+ }),+ ).toEqual({+ projectId: null,+ accessLevel: "organization",+ orgId: "org_1",+ plan: "oss",+ rateLimitOverrides: [],+ apiKeyId: "key_1",+ publicKey: "pk-lf-1",+ isIngestionSuspended: false,+ isInAppAgentKey: false,+ });+ });++ it("maps an api key and its organization onto the project scope", () => {+ expect(+ toApiAccessScope(apiKeyPrincipal("PROJECT"), {+ orgId: "org_1",+ projectId: "prj_1",+ }),+ ).toEqual(projectScope);+ });++ it("maps a public-key presentation to the scores access level", () => {+ expect(+ toApiAccessScope(apiKeyPrincipal("PROJECT", "publicKey"), {+ orgId: "org_1",+ projectId: "prj_1",+ }).accessLevel,+ ).toBe("scores");+ });++ it("maps an admin principal onto the self-host admin scope", () => {+ expect(+ toApiAccessScope(+ { kind: "admin", userId: null },+ { orgId: "org_1", projectId: "prj_1" },+ ),+ ).toEqual({+ projectId: "prj_1",+ accessLevel: "project",+ orgId: "org_1",+ plan: "oss",+ rateLimitOverrides: [],+ apiKeyId: "ADMIN_API_KEY",+ publicKey: "ADMIN_API_KEY",+ isIngestionSuspended: false,+ isInAppAgentKey: false,+ });+ });++ it("500s an unmappable principal kind", () => {+ expect(() =>+ toApiAccessScope(+ { kind: "user", userId: "u_1", organizations: [] },+ { orgId: "org_1", projectId: null },+ ),+ ).toThrow(InternalServerError);+ });+});diff --git a/web/src/ee/features/admin-api/server/projects.ts b/web/src/ee/features/admin-api/server/projects.tsindex 6bebb16f7d..d96f14a901 100644--- a/web/src/ee/features/admin-api/server/projects.ts+++ b/web/src/ee/features/admin-api/server/projects.ts@@ -1,11 +1,18 @@import { type NextApiRequest, type NextApiResponse } from "next";import { prisma } from "@langfuse/shared/src/db";+import { authorize } from "@/src/features/auth/policy/authorize";+import {+ type Action,+ type AuthorizationContext,+} from "@/src/features/auth/policy/types";+// GET - Retrieve all projects in an organizationexport async function handleGetProjects(req: NextApiRequest,res: NextApiResponse,orgId: string,+ ctx?: AuthorizationContext,) {const projects = await prisma.project.findMany({where: {@@ -22,12 +29,20 @@ export async function handleGetProjects(});return res.status(200).json({- projects: projects.map((project) => ({- id: project.id,- name: project.name,- metadata: project.metadata,- createdAt: project.createdAt,- updatedAt: project.updatedAt,- })),+ projects: projects+ .filter(hasPermission(ctx, "project:read"))+ .map((project) => ({+ id: project.id,+ name: project.name,+ metadata: project.metadata,+ createdAt: project.createdAt,+ updatedAt: project.updatedAt,+ })),});}++/** hasPermission tests whether ctx permits action on a project, allowing all when ctx is absent. */+const hasPermission =+ (ctx: AuthorizationContext | undefined, action: Action) =>+ (project: { id: string }) =>+ !ctx || authorize(ctx, action, { projectId: project.id }).success;diff --git a/web/src/features/apiKey/apiKeyRepository.ts b/web/src/features/apiKey/apiKeyRepository.tsindex 5948653be6..bc7012b0e8 100644--- a/web/src/features/apiKey/apiKeyRepository.ts+++ b/web/src/features/apiKey/apiKeyRepository.ts@@ -3,10 +3,11 @@ import {type PrismaClient,prisma as defaultPrisma,} from "@langfuse/shared/src/db";-import { InternalServerError } from "@langfuse/shared";+import { type InternalServerError } from "@langfuse/shared";import { logger } from "@langfuse/shared/src/server";import {+ internalServerError,type ErrorResult,type Success,} from "@/src/features/auth/policy/types";@@ -23,12 +24,9 @@ export class ApiKeyRepository {});return { success: true, apiKey };} catch (error) {- return {- success: false,- error: new InternalServerError(- `api key lookup by fast hash failed: ${String(error)}`,- ),- };+ return internalServerError(+ `api key lookup by fast hash failed: ${String(error)}`,+ );}}@@ -40,12 +38,9 @@ export class ApiKeyRepository {});return { success: true, apiKey };} catch (error) {- return {- success: false,- error: new InternalServerError(- `api key lookup by public key failed: ${String(error)}`,- ),- };+ return internalServerError(+ `api key lookup by public key failed: ${String(error)}`,+ );}}diff --git a/web/src/features/apiKey/authenticator.ts b/web/src/features/apiKey/authenticator.tsindex ebb1a4d4ab..f5d3938577 100644--- a/web/src/features/apiKey/authenticator.ts+++ b/web/src/features/apiKey/authenticator.ts@@ -1,7 +1,12 @@import { type IncomingHttpHeaders } from "http";-import { type InternalServerError, UnauthorizedError } from "@langfuse/shared";+import {+ type ForbiddenError,+ type InternalServerError,+ type UnauthorizedError,+} from "@langfuse/shared";+import { env } from "@/src/env.mjs";import { ContextResolver } from "@/src/features/auth/policy/contextResolver";import {parseAuthorizationHeader,@@ -10,6 +15,8 @@ import {import { AuthenticatorCache } from "@/src/features/apiKey/authenticatorCache";import { Verifier, invalidCredentials } from "@/src/features/apiKey/verifier";import {+ forbiddenError,+ unauthorizedError,type AuthorizationContext,type ErrorResult,type Principal,@@ -28,20 +35,22 @@ export class Authenticator {async authenticate(params: ApiKeyAuthParams): Promise<ApiKeyAuthResults> {const credential = parseAuthorizationHeader(params.headers.authorization);if (credential.kind === "malformed") {- return {- success: false,- error: new UnauthorizedError(invalidCredentials),- };+ return unauthorizedError(invalidCredentials);+ }++ let authResult = await this.cache.get(credential);+ if (!authResult) {+ authResult = await this.verifyAndResolve(credential);}- const result =- (await this.cache.get(credential)) ??- (await this.verifyAndResolve(credential));- if (result.success) {- const denied = enforceRouteSettings(result.context.principal, params);- if (denied) return denied;+ if (authResult.success) {+ const denied = enforceRouteSettings(authResult.context.principal, params);+ if (denied) {+ return denied;+ }}- return result;++ return authResult;}/** verifyAndResolve authenticates and materializes on a cache miss, writing every cacheable outcome back to the cache. */@@ -66,24 +75,25 @@ export const authenticator = new Authenticator();function enforceRouteSettings(principal: Principal,params: ApiKeyAuthParams,-): ErrorResult<UnauthorizedError> | null {- if (principal.kind === "admin" && !params.isAdminApiKeyAuthAllowed) {- return {- success: false,- error: new UnauthorizedError("Admin API key auth is not allowed here"),- };+): ErrorResult<UnauthorizedError | ForbiddenError> | null {+ if (principal.kind === "admin") {+ if (!params.isAdminApiKeyAuthAllowed) {+ return unauthorizedError("Admin API key auth is not allowed here");+ }+ if (env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION) {+ return forbiddenError(+ "Admin API key auth is not available on Langfuse Cloud",+ );+ }}if (principal.kind === "apiKey" &&principal.isInAppAgentKey &&!params.allowInAppAgentKey) {- return {- success: false,- error: new UnauthorizedError(- "Access denied - in-app agent keys are not allowed for this endpoint",- ),- };+ return unauthorizedError(+ "Access denied - in-app agent keys are not allowed for this endpoint",+ );}return null;}@@ -98,7 +108,7 @@ export type ApiKeyAuthParams = {/** ApiKeyAuthResults is the pipeline's outcome: the resolved context, or a typed failure. */export type ApiKeyAuthResults =| Authenticated- | ErrorResult<UnauthorizedError | InternalServerError>;+ | ErrorResult<UnauthorizedError | ForbiddenError | InternalServerError>;/** Authenticated is the pipeline's success outcome: the resolved authorization context. */export type Authenticated = Success & { context: AuthorizationContext };diff --git a/web/src/features/apiKey/authenticatorCache.ts b/web/src/features/apiKey/authenticatorCache.tsindex 6e0ba8a576..756138a9e4 100644--- a/web/src/features/apiKey/authenticatorCache.ts+++ b/web/src/features/apiKey/authenticatorCache.ts@@ -15,6 +15,7 @@ import {type Authenticated,} from "@/src/features/apiKey/authenticator";import {+ unauthorizedError,type AuthorizationContext,type ErrorResult,} from "@/src/features/auth/policy/types";@@ -97,7 +98,7 @@ function toEntry(result: ApiKeyAuthResults): CachedEntry | null {/** deserialize reconstructs a cache hit from its stored row. */function deserialize(entry: CachedEntry): ResolveContextResult {if ("context" in entry) return { success: true, context: entry.context };- return { success: false, error: new UnauthorizedError(entry.unauthorized) };+ return unauthorizedError(entry.unauthorized);}/** ResolveContextResult is a cache hit: a resolved context or a replayed 401, never a 500. */diff --git a/web/src/features/apiKey/verifier.ts b/web/src/features/apiKey/verifier.tsindex 377f14af78..64b2f12af9 100644--- a/web/src/features/apiKey/verifier.ts+++ b/web/src/features/apiKey/verifier.ts@@ -1,13 +1,18 @@import crypto from "node:crypto";import { type ApiKey } from "@langfuse/shared/src/db";-import { InternalServerError, UnauthorizedError } from "@langfuse/shared";+import {+ type InternalServerError,+ type UnauthorizedError,+} from "@langfuse/shared";import { createShaHash, verifySecretKey } from "@langfuse/shared/src/server";import { env } from "@/src/env.mjs";import { type Credential } from "@/src/features/apiKey/helpers/parseAuthorizationHeader";import { ApiKeyRepository } from "@/src/features/apiKey/apiKeyRepository";import {+ internalServerError,+ unauthorizedError,type ErrorResult,type Success,} from "@/src/features/auth/policy/types";@@ -35,7 +40,7 @@ export class Verifier {if (credential.kind === "bearer") {return this.verifyBearer(credential.token);}- return unauthorized();+ return unauthorizedError(invalidCredentials);}/** verifyBasic authenticates a public:secret pair as the privateKey presentation, private key first then a slow bcrypt backfill. */@@ -49,7 +54,7 @@ export class Verifier {const bySlowHash = await this.backfillSlowHash(publicKey, secretKey);if (bySlowHash) return bySlowHash;- return unauthorized();+ return unauthorizedError(invalidCredentials);}/** verifyBearer chains admin, then public (public key), then private (fast hash). */@@ -63,7 +68,7 @@ export class Verifier {const byPrivateKey = await this.verifyPrivateKey(token);if (byPrivateKey) return byPrivateKey;- return unauthorized();+ return unauthorizedError(invalidCredentials);}/** verifyPrivateKey resolves a secret to its privateKey presentation via the fast-hash index, or null when it is not indexed there. */@@ -91,10 +96,7 @@ export class Verifier {try {valid = await verifySecretKey(secretKey, found.apiKey.hashedSecretKey);} catch (error) {- return {- success: false,- error: new InternalServerError(`slow verify failed: ${String(error)}`),- };+ return internalServerError(`slow verify failed: ${String(error)}`);}if (!valid) return null;@@ -141,11 +143,6 @@ function privateKey(apiKey: ApiKey): VerifyApiKeyResult {return { success: true, authorization: "privateKey", apiKey };}-/** unauthorized is the single 401 outcome for any unknown or malformed credential. */-function unauthorized(): ErrorResult<UnauthorizedError> {- return { success: false, error: new UnauthorizedError(invalidCredentials) };-}-/** VerifiedCredential is the presentation the resolver consumes: an api key with how it was presented, or the admin key. */type VerifiedCredential =| { authorization: "publicKey" | "privateKey"; apiKey: ApiKey }diff --git a/web/src/features/auth/policy/authorize.ts b/web/src/features/auth/policy/authorize.tsindex a67a17c748..66c418db44 100644--- a/web/src/features/auth/policy/authorize.ts+++ b/web/src/features/auth/policy/authorize.ts@@ -1,11 +1,9 @@-import { ForbiddenError } from "@langfuse/shared";-import {+ forbiddenError,wildcard,type Action,type AuthorizationContext,type Decision,- type ErrorResult,type Policy,type Resource,} from "./types";@@ -22,12 +20,12 @@ export function authorize(.filter(hasResourceId(resource));if (matches.some(hasEffect("deny"))) {- return forbidden();+ return forbiddenError();}if (matches.some(hasEffect("allow"))) {return { success: true };}- return forbidden();+ return forbiddenError();}/** hasResourceKind matches a policy of the kind that governs the checked resource. */@@ -48,8 +46,3 @@ const hasAction = (action: Action) => (p: Policy) =>/** hasEffect matches a policy of the given effect. */const hasEffect = (effect: Policy["effect"]) => (p: Policy) =>p.effect === effect;--/** forbidden builds a 403 Decision carrying the generic ForbiddenError. */-function forbidden(): ErrorResult<ForbiddenError> {- return { success: false, error: new ForbiddenError() };-}diff --git a/web/src/features/auth/policy/contextResolver.ts b/web/src/features/auth/policy/contextResolver.tsindex 8f490673f2..a0c7e15b6e 100644--- a/web/src/features/auth/policy/contextResolver.ts+++ b/web/src/features/auth/policy/contextResolver.ts@@ -1,5 +1,5 @@import { type ApiKey } from "@langfuse/shared/src/db";-import { CloudConfigSchema, InternalServerError } from "@langfuse/shared";+import { CloudConfigSchema, type InternalServerError } from "@langfuse/shared";import { apiKeyAccessRights } from "@/src/features/rbac/constants/apiKeyAccessRights";import { getOrganizationPlanServerSide } from "@/src/features/entitlements/server";@@ -9,13 +9,14 @@ import {type OrganizationWithProjects,} from "./organizationRepository";import {+ internalServerError,wildcard,type AuthorizationContext,+ type BoundResource,type ErrorResult,type Policy,type Principal,type PrincipalOrganization,- type Resource,type Success,type SystemPolicy,} from "./types";@@ -53,12 +54,9 @@ export class ContextResolver {const found = await this.loadOrganization(apiKey);if (!found.success) return found;if (!found.organization) {- return {- success: false,- error: new InternalServerError(- `verified key ${apiKey.id} resolved to no organization`,- ),- };+ return internalServerError(+ `verified key ${apiKey.id} resolved to no organization`,+ );}return {success: true,@@ -72,20 +70,12 @@ export class ContextResolver {): Promise<GetOrganizationResult> {if (apiKey.scope === "ORGANIZATION") {if (apiKey.orgId === null) {- return {- success: false,- error: new InternalServerError(`org key ${apiKey.id} has no orgId`),- };+ return internalServerError(`org key ${apiKey.id} has no orgId`);}return this.orgs.getOrganizationByOrgId(apiKey.orgId);}if (apiKey.projectId === null) {- return {- success: false,- error: new InternalServerError(- `project key ${apiKey.id} has no projectId`,- ),- };+ return internalServerError(`project key ${apiKey.id} has no projectId`);}return this.orgs.getOrganizationByProjectId(apiKey.projectId);}@@ -106,7 +96,7 @@ function materialize(scope: apiKey.scope,presentation: authorization,organizations: [org],- boundResource: boundResourceFor(apiKey),+ boundResource: boundResourceFor(apiKey, org),};const grants =@@ -126,25 +116,13 @@ function adminContext(): AuthorizationContext {};}-/** toPrincipalOrganization derives an org's `PrincipalOrganization` caps and liveness from its raw row. */-function toPrincipalOrganization(- org: OrganizationWithProjects,-): PrincipalOrganization {- const cloudConfig = getCloudConfig(org);- return {- orgId: org.id,- plan: getOrganizationPlanServerSide(cloudConfig),- rateLimitOverrides: cloudConfig?.rateLimitOverrides ?? [],- projectIds: org.projects.map((p) => p.id),- isIngestionSuspended: org.cloudFreeTierUsageThresholdState === "BLOCKED",- };-}--/** getCloudConfig parses an org's raw cloud-config json, or undefined when unset. */-function getCloudConfig(- org: OrganizationWithProjects,-): CloudConfigSchema | undefined {- return org.cloudConfig ? CloudConfigSchema.parse(org.cloudConfig) : undefined;+/** boundResourceFor is the target a request resolves against with no header: the key's org, narrowed to its project when the key is project-scoped. */+function boundResourceFor(+ apiKey: ApiKey,+ org: PrincipalOrganization,+): BoundResource {+ if (apiKey.scope === "ORGANIZATION") return { orgId: org.orgId };+ return { orgId: org.orgId, projectId: apiKey.projectId! };}/** bind fixes a resource-less SystemPolicy to the resources the principal covers, by the policy's kind. */@@ -154,35 +132,49 @@ function bind(policy: SystemPolicy, principal: Principal): Policy {: { ...policy, resources: projectResources(principal) };}+/** orgResources are the org ids an org-kind policy binds to: the bound org, or the wildcard for admin. */+function orgResources(principal: Principal): Policy["resources"] {+ if (principal.kind === "admin") return wildcard;+ return boundOrgs(principal).map((o) => o.orgId);+}+/** projectResources are the project ids a project-kind policy binds to: the bound project, the bound org's projects, or the wildcard for admin. */function projectResources(principal: Principal): Policy["resources"] {if (principal.kind === "admin") return wildcard;const bound =principal.kind === "apiKey" ? principal.boundResource : undefined;- if (bound && "projectId" in bound) return [bound.projectId];- const orgs =- bound && "orgId" in bound- ? principal.organizations.filter((o) => o.orgId === bound.orgId)- : principal.organizations;- return orgs.flatMap((o) => o.projectIds);+ if (bound?.projectId) return [bound.projectId];+ return boundOrgs(principal).flatMap((o) => o.projectIds);}-/** orgResources are the org ids an org-kind policy binds to: the bound org, or the wildcard for admin. */-function orgResources(principal: Principal): Policy["resources"] {- if (principal.kind === "admin") return wildcard;+/** boundOrgs are the principal's organizations, narrowed to the bound org when the credential bound one. */+function boundOrgs(principal: NonAdminPrincipal): PrincipalOrganization[] {const bound =principal.kind === "apiKey" ? principal.boundResource : undefined;- const orgs =- bound && "orgId" in bound- ? principal.organizations.filter((o) => o.orgId === bound.orgId)- : principal.organizations;- return orgs.map((o) => o.orgId);+ return bound+ ? principal.organizations.filter((o) => o.orgId === bound.orgId)+ : principal.organizations;+}++/** toPrincipalOrganization derives an org's `PrincipalOrganization` caps and liveness from its raw row. */+function toPrincipalOrganization(+ org: OrganizationWithProjects,+): PrincipalOrganization {+ const cloudConfig = getCloudConfig(org);+ return {+ orgId: org.id,+ plan: getOrganizationPlanServerSide(cloudConfig),+ rateLimitOverrides: cloudConfig?.rateLimitOverrides ?? [],+ projectIds: org.projects.map((p) => p.id),+ isIngestionSuspended: org.cloudFreeTierUsageThresholdState === "BLOCKED",+ };}-/** boundResourceFor is the legacy single-target a request resolves against with no header. */-function boundResourceFor(apiKey: ApiKey): Resource {- if (apiKey.scope === "ORGANIZATION") return { orgId: apiKey.orgId! };- return { projectId: apiKey.projectId! };+/** getCloudConfig parses an org's raw cloud-config json, or undefined when unset. */+function getCloudConfig(+ org: OrganizationWithProjects,+): CloudConfigSchema | undefined {+ return org.cloudConfig ? CloudConfigSchema.parse(org.cloudConfig) : undefined;}/** ResolveContextParams is a verified credential: an api key with how it was presented, or the admin key. */@@ -197,3 +189,6 @@ export type ResolveContextParams =export type Resolved =| (Success & { context: AuthorizationContext })| ErrorResult<InternalServerError>;++/** NonAdminPrincipal is a user or api-key principal, the credentials that carry organizations. */+type NonAdminPrincipal = Exclude<Principal, { kind: "admin" }>;diff --git a/web/src/features/auth/policy/enforceProjectAuth.ts b/web/src/features/auth/policy/enforceProjectAuth.tsdeleted file mode 100644index 34956cc31d..0000000000--- a/web/src/features/auth/policy/enforceProjectAuth.ts+++ /dev/null@@ -1,113 +0,0 @@-import { type IncomingHttpHeaders } from "http";--import {- type ForbiddenError,- type InternalServerError,- InvalidRequestError,- type UnauthorizedError,-} from "@langfuse/shared";--import { authorize } from "./authorize";-import { authenticator } from "@/src/features/apiKey/authenticator";-import {- type AuthorizationContext,- type ErrorResult,- type ProjectAction,- type Success,-} from "./types";--/** projectIdHeader selects the target project for keys without a bound project. */-const projectIdHeader = "x-langfuse-project-id";--/** headerValue normalizes a possibly-repeated header to its first value. */-const headerValue = (- value: string | string[] | undefined,-): string | undefined => (Array.isArray(value) ? value[0] : value);--/** enforceProjectAuth runs the new project pipeline — authenticate, its own target resolution, authorize — returning every outcome as a value; it never throws one. */-export async function enforceProjectAuth(- params: EnforceProjectAuthParams,-): Promise<ProjectAccessResult | ErrorResult<AuthError>> {- const authn = await authenticator.authenticate({- headers: params.headers,- allowInAppAgentKey: params.allowInAppAgentKey,- isAdminApiKeyAuthAllowed: params.isAdminApiKeyAuthAllowed,- });- if (!authn.success) return authn;-- const context = authn.context;- const target = getProjectId(context, params.headers);- if (!target.success) return target;-- if (params.action === undefined) {- return { success: true, context, projectId: target.projectId };- }- const decision = authorize(context, params.action, {- projectId: target.projectId,- });- if (!decision.success) {- return { success: false, error: decision.error };- }- return { success: true, context, projectId: target.projectId };-}--/** getProjectId resolves the target project as `header ?? boundResource ?? 400`; a header disagreeing with the bound project 400s. */-function getProjectId(- context: AuthorizationContext,- headers: IncomingHttpHeaders,-): ResolvedProject | ErrorResult<InvalidRequestError> {- const boundProjectId = boundProjectIdOf(context);- const header = headerValue(headers[projectIdHeader]) || undefined;- if (header && boundProjectId && header !== boundProjectId) {- return {- success: false,- error: new InvalidRequestError(- `${projectIdHeader} disagrees with the API key's project`,- ),- };- }- const projectId = header ?? boundProjectId;- if (!projectId) {- return {- success: false,- error: new InvalidRequestError(- `No project target: send ${projectIdHeader} or use a project-scoped API key`,- ),- };- }- return { success: true, projectId };-}--/** boundProjectIdOf returns the project an api key is bound to, when any. */-function boundProjectIdOf(context: AuthorizationContext): string | undefined {- if (context.principal.kind !== "apiKey") return undefined;- const bound = context.principal.boundResource;- return bound && "projectId" in bound ? bound.projectId : undefined;-}--/** EnforceProjectAuthParams is the request headers, the checked action, and the route's key-kind opt-ins. */-export type EnforceProjectAuthParams = {- headers: IncomingHttpHeaders;- action?: ProjectAction;- allowInAppAgentKey?: boolean;- isAdminApiKeyAuthAllowed?: boolean;-};--/** ProjectAccessResult is the project seam's success outcome: the resolved context and target. */-export type ProjectAccessResult = Success & {- context: AuthorizationContext;- projectId: string;-};--/** AuthError is any typed failure the project pipeline surfaces. */-export type AuthError =- | UnauthorizedError- | InvalidRequestError- | InternalServerError- | ForbiddenError;--/** ResolvedProject is project target resolution's success outcome. */-type ResolvedProject = Success & { projectId: string };--/** __test exposes module-private helpers for the colocated unit test. */-export const __test = { getProjectId };diff --git a/web/src/features/auth/policy/organizationRepository.ts b/web/src/features/auth/policy/organizationRepository.tsindex 9948e4b9a9..0cf4dc98b1 100644--- a/web/src/features/auth/policy/organizationRepository.ts+++ b/web/src/features/auth/policy/organizationRepository.ts@@ -3,9 +3,9 @@ import {type PrismaClient,prisma as defaultPrisma,} from "@langfuse/shared/src/db";-import { InternalServerError } from "@langfuse/shared";+import { type InternalServerError } from "@langfuse/shared";-import { type ErrorResult, type Success } from "./types";+import { internalServerError, type ErrorResult, type Success } from "./types";/** OrganizationRepository reads an org with its live projects, returning a null miss or an infra failure as a value. */export class OrganizationRepository {@@ -22,12 +22,9 @@ export class OrganizationRepository {});return { success: true, organization };} catch (error) {- return {- success: false,- error: new InternalServerError(- `failed to load org ${orgId}: ${String(error)}`,- ),- };+ return internalServerError(+ `failed to load org ${orgId}: ${String(error)}`,+ );}}@@ -46,12 +43,9 @@ export class OrganizationRepository {: null,};} catch (error) {- return {- success: false,- error: new InternalServerError(- `failed to load org for project ${projectId}: ${String(error)}`,- ),- };+ return internalServerError(+ `failed to load org for project ${projectId}: ${String(error)}`,+ );}}}diff --git a/web/src/features/auth/policy/shadow.ts b/web/src/features/auth/policy/shadow.tsdeleted file mode 100644index e4624e7862..0000000000--- a/web/src/features/auth/policy/shadow.ts+++ /dev/null@@ -1,113 +0,0 @@-import { getCurrentSpan, recordIncrement } from "@langfuse/shared/src/server";--/** parityStat counts one authorization decision. */-const parityStat = "langfuse.authz.parity";--/** coverageStat counts one request against its operation. */-const coverageStat = "langfuse.authz.coverage";--/** defaultSink writes to dogstatsd and the active span; tests inject a capturing fake. */-const defaultSink: ParitySink = {- increment: (stat, tags) => recordIncrement(stat, 1, tags),- span: () => getCurrentSpan(),-};--/** diffResults classifies the new pipeline's decision against legacy's, emits `langfuse.authz.parity`, and returns the result. */-export function diffResults(- neu: NewResult,- legacy: LegacyDecision,- meta: { seam: Seam; action: string },- sink: ParitySink = defaultSink,-): ParityResult {- const n = newVerdict(neu);- const l = legacyVerdict(legacy);- const result = classify(l.verdict, n.verdict);- const tags = {- seam: meta.seam,- action: meta.action,- result,- legacy_code: l.code,- new_code: n.code,- } satisfies Record<string, string | number>;- sink.increment(parityStat, tags);- sink.span()?.setAttribute(`${parityStat}.result`, result);- return result;-}--/** recordCoverage counts a request against its operation so parity zeros can be told from untested routes. */-export function recordCoverage(- operation: string,- sink: ParitySink = defaultSink,-): void {- sink.increment(coverageStat, { operation });-}--/** newVerdict reads the new pipeline's result: success allows (200), else denies with its http code. */-export function newVerdict(result: NewResult): {- verdict: Verdict;- code: number;-} {- return result.success- ? { verdict: "allow", code: 200 }- : { verdict: "deny", code: result.error.httpCode };-}--/** verdictFromStatus reads a legacy chokepoint's http status: under 400 allows, else denies. */-function verdictFromStatus(status: number): Verdict {- return status < 400 ? "allow" : "deny";-}--/** legacyFromStatus lifts a legacy chokepoint's http status into a LegacyDecision. */-export function legacyFromStatus(status: number): LegacyDecision {- return status < 400 ? { ok: true } : { ok: false, code: status };-}--/** legacyVerdict reads a legacy decision into a verdict + code. */-function legacyVerdict(legacy: LegacyDecision): {- verdict: Verdict;- code: number;-} {- if ("absent" in legacy) return { verdict: "absent", code: 0 };- const code = legacy.ok ? 200 : legacy.code;- return { verdict: verdictFromStatus(code), code };-}--/** classify names the disagreement: legacy without a gate is `net_new`, agreement is `match`, else which path is stricter. */-function classify(legacy: Verdict, neu: Verdict): ParityResult {- if (legacy === "absent") return "net_new";- if (legacy === neu) return "match";- return neu === "deny" ? "new_denies" : "new_allows";-}--/** Verdict is one path's decision at one enforcement point; legacy is `absent` only where it runs no gate. */-export type Verdict = "allow" | "deny" | "absent";--/** ParityResult is the signal: agreement, which path is stricter, or net-new enforcement legacy never gated. */-export type ParityResult = "match" | "new_denies" | "new_allows" | "net_new";--/** Seam is the enforcement point a decision came from. */-export type Seam =- | "project_route"- | "org_route"- | "ingestion_event"- | "mcp_access"- | "mcp_tool";--/** LegacyDecision is the legacy path's outcome: it allowed, it denied with an http code, or it ran no gate. */-export type LegacyDecision =- | { ok: true }- | { ok: false; code: number }- | { absent: true };--/** ParitySink is the telemetry surface, injectable so tests capture without a collector. */-export type ParitySink = {- increment: (stat: string, tags: Record<string, string | number>) => void;- span: () =>- | { setAttribute: (key: string, value: string | number) => void }- | undefined;-};--/** NewResult is the new pipeline's outcome at a decision point: a success or a typed error carrying its http code. */-export type NewResult =- | { success: true }- | { success: false; error: { httpCode: number } };diff --git a/web/src/features/auth/policy/types.ts b/web/src/features/auth/policy/types.tsindex 2cd0805c32..71a02a5c3c 100644--- a/web/src/features/auth/policy/types.ts+++ b/web/src/features/auth/policy/types.ts@@ -1,10 +1,14 @@import { type z } from "zod";import {+ ForbiddenError,+ InternalServerError,+ LangfuseNotFoundError,projectScopes,+ ServiceUnavailableError,+ UnauthorizedError,type ApiKeyScope,type CloudConfigRateLimit,- type ForbiddenError,type Plan,type ProjectScope,} from "@langfuse/shared";@@ -24,6 +28,13 @@ export const allOrganizationActions: OrganizationAction[] = [...organizationScopes,];+/** organizationActionSet is allOrganizationActions indexed for membership tests. */+const organizationActionSet: ReadonlySet<string> = new Set(organizationScopes);++/** isOrgAction reports whether an action belongs to the disjoint org vocabulary. */+export const isOrgAction = (action: Action): action is OrganizationAction =>+ organizationActionSet.has(action);+/** Wildcard is the type of the wildcard resource matcher literal. */type Wildcard = typeof wildcard;@@ -58,7 +69,7 @@ export type Principal =scope: ApiKeyScope;presentation: "publicKey" | "privateKey";organizations: PrincipalOrganization[];- boundResource?: Resource;+ boundResource: BoundResource;};/** Source describes where a policy came from: a role or an explicit grant. */@@ -73,6 +84,9 @@ type OrgResource = { orgId: string };/** Resource is the thing being checked: a bare project or an org node. */export type Resource = ProjectResource | OrgResource;+/** BoundResource is what a credential is bound to: its organization, narrowed to one project when the credential is project-scoped. */+export type BoundResource = OrgResource & { projectId?: string };+/** BasePolicy carries the origin and effect every policy shares. */type BasePolicy = {source: Source;@@ -111,3 +125,43 @@ export type ErrorResult<E> = { success: false; error: E };/** Decision is a PDP outcome: a boolean success, or a typed 403. */export type Decision = Success | ErrorResult<ForbiddenError>;++/** unauthorizedError is a 401 ErrorResult carrying an optional message. */+export const unauthorizedError = (+ message?: string,+): ErrorResult<UnauthorizedError> => ({+ success: false,+ error: new UnauthorizedError(message),+});++/** forbiddenError is a 403 ErrorResult carrying an optional message. */+export const forbiddenError = (+ message?: string,+): ErrorResult<ForbiddenError> => ({+ success: false,+ error: new ForbiddenError(message),+});++/** notFoundError is a 404 ErrorResult carrying an optional message. */+export const notFoundError = (+ message?: string,+): ErrorResult<LangfuseNotFoundError> => ({+ success: false,+ error: new LangfuseNotFoundError(message),+});++/** internalServerError is a 500 ErrorResult carrying an optional message. */+export const internalServerError = (+ message?: string,+): ErrorResult<InternalServerError> => ({+ success: false,+ error: new InternalServerError(message),+});++/** serviceUnavailableError is a 503 ErrorResult carrying an optional message. */+export const serviceUnavailableError = (+ message?: string,+): ErrorResult<ServiceUnavailableError> => ({+ success: false,+ error: new ServiceUnavailableError(message),+});diff --git a/web/src/features/blobstorage-integration/authorizeBlobStorageRequest.ts b/web/src/features/blobstorage-integration/authorizeBlobStorageRequest.tsnew file mode 100644index 0000000000..bbae78b7ac--- /dev/null+++ b/web/src/features/blobstorage-integration/authorizeBlobStorageRequest.ts@@ -0,0 +1,36 @@+import { type NextApiRequest } from "next";++import { ForbiddenError, UnauthorizedError } from "@langfuse/shared";+import { type ApiAccessScope } from "@langfuse/shared/src/server";++import { hasEntitlementBasedOnPlan } from "@/src/features/entitlements/server/hasEntitlement";+import { shadowAuth } from "@/src/features/public-api/server/shadowAuth";+import { ErrorOrgApiKeyRequired } from "@/src/features/public-api/server/writeError";++/** authorizeBlobStorageRequest gates a blob-storage request on an organization key and the blob-export entitlement, returning the verified scope. */+export async function authorizeBlobStorageRequest(+ req: NextApiRequest,+): Promise<ApiAccessScope> {+ const authCheck = await shadowAuth({+ req,+ action: "projects:read",+ allowedAccessLevels: ["organization"],+ });+ if (!authCheck.success) {+ if (authCheck.error.httpCode === 401) {+ throw new UnauthorizedError(authCheck.error.message);+ }+ throw new ForbiddenError(ErrorOrgApiKeyRequired);+ }+ if (+ !hasEntitlementBasedOnPlan({+ plan: authCheck.scope.plan,+ entitlement: "scheduled-blob-exports",+ })+ ) {+ throw new ForbiddenError(+ "scheduled-blob-exports entitlement required for this feature.",+ );+ }+ return authCheck.scope;+}diff --git a/web/src/features/public-api/server/createAuthedProjectAPIRoute.ts b/web/src/features/public-api/server/createAuthedProjectAPIRoute.tsindex af272f0221..13e5b942b1 100644--- a/web/src/features/public-api/server/createAuthedProjectAPIRoute.ts+++ b/web/src/features/public-api/server/createAuthedProjectAPIRoute.ts@@ -8,16 +8,17 @@ import {contextWithLangfuseProps,} from "@langfuse/shared/src/server";import {+ BaseError,PayloadTooLargeError,type RateLimitResource,type ApiDeprecationInfo,} from "@langfuse/shared";+import { verifyGatewayIngestionAuthorization } from "@/src/features/ai-gateway/server";import { RateLimitService } from "@/src/features/public-api/server/RateLimitService";import { type RateLimitUpgradePath } from "@/src/features/public-api/server/rateLimitUpgradePaths";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 {createStructuredPublicApiAuthError,createStructuredPublicApiRequestValidationError,@@ -27,25 +28,9 @@ import {} from "./structuredPublicApiErrorContract";import { clickHouseRouteForRequest } from "@/src/features/public-api/server/clickHouseRequestTags";import { attachDeprecation } from "@/src/features/public-api/server/deprecations";-import {- verifyAuth as verifyLegacyAuth,- type RouteAccessLevel,-} from "@/src/features/public-api/server/verifyProjectApiKeyAuth";-import {- enforceProjectAuth,- type ProjectAccessResult,-} from "@/src/features/auth/policy/enforceProjectAuth";-import {- diffResults,- legacyFromStatus,- recordCoverage,-} from "@/src/features/auth/policy/shadow";-import {- type Principal,- type ProjectAction,-} from "@/src/features/auth/policy/types";-import { prisma } from "@langfuse/shared/src/db";-import { verifyGatewayIngestionAuthorization } from "@/src/features/ai-gateway/server";+import { type RouteAccessLevel } from "@/src/features/public-api/server/verifyProjectApiKeyAuth";+import { shadowAuth } from "@/src/features/public-api/server/shadowAuth";+import { type ProjectAction } from "@/src/features/auth/policy/types";// Next's res.json uses JSON.stringify; V8 throws this when the JSON string// exceeds the engine limit. Keep this check scoped to the response write.@@ -96,8 +81,8 @@ export type AuthedProjectAPIRouteConfig<*/allowInAppAgentKey?: boolean;/**- * Accept a short-lived gateway ingestion JWT in addition to normal project- * credentials. This must only be enabled on gateway ingestion boundaries.+ * Whether a signed AI-gateway ingestion token may authorize this route ahead+ * of the API-key pipeline. Defaults to false.*/allowGatewayIngestionToken?: boolean;/**@@ -121,188 +106,6 @@ export type AuthedProjectAPIRouteConfig<}) => Promise<z.infer<TResponse>>;};-/** verifyAuth is the project seam: the new pipeline decides alone in enforce, both run for parity in shadow (byte-identical to legacy), and legacy decides alone otherwise (the default). */-export async function verifyAuth(- params: VerifyAuthParams,-): Promise<VerifyAuthResult> {- if (params.allowGatewayIngestionToken) {- const gatewayAuth = await verifyGatewayIngestionAuthorization(- params.req.headers.authorization,- params.req.headers["langfuse-gateway-authorization"],- );- if (gatewayAuth) return gatewayAuth;- }-- // enforce mode runs only the new pipeline, which is the sole authority.- if (env.API_AUTH_MIGRATION === "enforce") {- const authz = await runNewAuth(params);- if (!authz.success) {- throw { status: authz.error.httpCode, message: authz.error.message };- }- return toVerifyAuthResult(authz);- }-- // shadow mode runs both: legacy decides, the new pipeline records parity.- if (env.API_AUTH_MIGRATION === "shadow") {- const legacy = await runLegacyAuth(params);- const authz = await runNewAuth(params);- recordCoverage(params.name);- diffResults(authz, legacyFromStatus(legacy.status), {- seam: "project_route",- action: params.action,- });- if (!legacy.ok) throw legacy.error;- return legacy.auth;- }-- // legacy is the default: any other value (including a blank one) fails safe- // to the legacy path, so self-host does no new auth work.- const legacy = await runLegacyAuth(params);- if (!legacy.ok) throw legacy.error;- return legacy.auth;-}--/** runLegacyAuth runs the legacy verify and captures its throw as a value with the status it reported. */-async function runLegacyAuth(- params: VerifyAuthParams,-): Promise<LegacyDecision> {- try {- const auth = await verifyLegacyAuth(- params.req,- params.isAdminApiKeyAuthAllowed ?? false,- params.allowedAccessLevels ?? ["project"],- params.allowInAppAgentKey ?? false,- );- return { ok: true, status: 200, auth };- } catch (error) {- const status = (error as { status?: unknown }).status;- return {- ok: false,- status: typeof status === "number" ? status : 500,- error,- };- }-}--/** runNewAuth runs the new project pipeline for the request's action and route opt-ins. */-function runNewAuth(params: VerifyAuthParams) {- return enforceProjectAuth({- headers: params.req.headers,- action: params.action,- allowInAppAgentKey: params.allowInAppAgentKey,- isAdminApiKeyAuthAllowed: params.isAdminApiKeyAuthAllowed,- });-}--/** toVerifyAuthResult maps the new pipeline's principal to the legacy-shaped verified scope. */-async function toVerifyAuthResult(- authz: ProjectAccessResult,-): Promise<VerifyAuthResult> {- const { principal } = authz.context;- if (principal.kind === "admin") return adminScope(authz.projectId);- if (principal.kind !== "apiKey") {- throw {- status: 500,- message: `unexpected principal kind on the project seam: ${principal.kind}`,- };- }- return apiKeyScope(principal, authz.projectId);-}--/** apiKeyScope maps an api-key principal to its verified scope; an org key here is an invariant break. */-function apiKeyScope(- principal: ApiKeyPrincipal,- projectId: string,-): VerifyAuthResult {- // The project seam denies org keys at the PDP, so one reaching here means a- // project route granted an org-satisfiable action.- if (principal.scope !== "PROJECT") {- throw {- status: 500,- message: `org-scoped key ${principal.apiKeyId} reached the project mapper`,- };- }- const org = principal.organizations[0];- if (!org) {- throw {- status: 500,- message: `api key ${principal.apiKeyId} resolved to no organization`,- };- }- return {- validKey: true,- scope: {- projectId,- accessLevel:- principal.presentation === "publicKey" ? "scores" : "project",- orgId: org.orgId,- plan: org.plan,- rateLimitOverrides: org.rateLimitOverrides,- apiKeyId: principal.apiKeyId,- publicKey: principal.publicKey,- isIngestionSuspended: org.isIngestionSuspended,- isInAppAgentKey: principal.isInAppAgentKey,- },- };-}--/** adminScope synthesizes the legacy self-host admin scope, loading the target project's org (404 on miss); admin key auth never applies on Langfuse Cloud. */-async function adminScope(projectId: string): Promise<VerifyAuthResult> {- if (env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION) {- throw {- status: 403,- message: "Admin API key auth is not available on Langfuse Cloud",- };- }- const project = await prisma.project.findUnique({- where: { id: projectId, deletedAt: null },- select: { id: true, orgId: true },- });- if (!project) throw { status: 404, message: "Project not found" };- return {- validKey: true,- scope: {- projectId: project.id,- accessLevel: "project",- orgId: project.orgId,- plan: "oss",- rateLimitOverrides: [],- apiKeyId: "ADMIN_API_KEY",- publicKey: "ADMIN_API_KEY",- isIngestionSuspended: false,- isInAppAgentKey: false,- },- };-}--/** VerifyAuthParams is the request plus the route's action and legacy auth options. */-export type VerifyAuthParams = {- req: NextApiRequest;- name: string;- action: ProjectAction;- isAdminApiKeyAuthAllowed?: boolean;- allowedAccessLevels?: RouteAccessLevel[];- allowInAppAgentKey?: boolean;- allowGatewayIngestionToken?: boolean;-};--/** VerifyAuthResult is the verified project scope the route handler receives. */-type VerifyAuthResult = {- validKey: true;- scope: ApiAccessScopeWithOptionalApiKeyId & {- projectId: string;- accessLevel: RouteAccessLevel;- };-};--/** ApiKeyPrincipal is the api-key variant of `Principal` the mapper consumes. */-type ApiKeyPrincipal = Extract<Principal, { kind: "apiKey" }>;--/** LegacyDecision is the legacy verify captured as a value: the verified scope, or the status + error to re-throw. */-type LegacyDecision =- | { ok: true; status: 200; auth: VerifyAuthResult }- | { ok: false; status: number; error: unknown };-export const createAuthedProjectAPIRoute = <TQuery extends ZodType<any>,TBody extends ZodType<any>,@@ -336,51 +139,68 @@ export const createAuthedProjectAPIRoute = <return;}- let auth: VerifyAuthResult;+ const renderAuthError = (statusCode: number, message: string) => {+ if (routeConfig.errorContract === structuredPublicApiErrorContract) {+ return sendStructuredPublicApiErrorResponse(+ res,+ createStructuredPublicApiAuthError({ statusCode, message }),+ );+ }+ res.status(statusCode).json({ message });+ };- // Verify authentication (API key or admin API key)- try {- auth = await verifyAuth({+ // A signed AI-gateway ingestion token authorizes the project directly,+ // ahead of the API-key pipeline; an invalid one is a 401.+ let gatewayAuth: Awaited<+ ReturnType<typeof verifyGatewayIngestionAuthorization>+ > = null;+ if (routeConfig.allowGatewayIngestionToken) {+ try {+ gatewayAuth = await verifyGatewayIngestionAuthorization(+ req.headers.authorization,+ req.headers["langfuse-gateway-authorization"],+ );+ } catch (error) {+ renderAuthError(+ error instanceof BaseError ? error.httpCode : 401,+ error instanceof BaseError ? error.message : "Authentication failed",+ );+ return;+ }+ }++ // The route's action guarantees a project scope; narrow off the phantom org level.+ let auth: {+ validKey: true;+ scope: ApiAccessScopeWithOptionalApiKeyId & {+ projectId: string;+ accessLevel: RouteAccessLevel;+ };+ };++ if (gatewayAuth) {+ auth = gatewayAuth;+ } else {+ const result = await shadowAuth({req,- name: routeConfig.name,action: routeConfig.action,isAdminApiKeyAuthAllowed: routeConfig.isAdminApiKeyAuthAllowed || false,- allowedAccessLevels: routeConfig.allowedAccessLevels || ["project"],+ allowedAccessLevels: routeConfig.allowedAccessLevels ?? ["project"],allowInAppAgentKey: routeConfig.allowInAppAgentKey === true,- allowGatewayIngestionToken:- routeConfig.allowGatewayIngestionToken === true,});- } catch (error: any) {- if (isPrismaException(error)) {- traceException(error);- if (routeConfig.errorContract === structuredPublicApiErrorContract) {- return sendStructuredPublicApiErrorResponse(- res,- createStructuredPublicApiAuthError({- statusCode: 503,- message: "Service Unavailable",- }),- );- }-- res.status(503).json({ message: "Service Unavailable" });+ if (!result.success) {+ renderAuthError(result.error.httpCode, result.error.message);return;}- const statusCode = error.status ?? 401;- const message = error.message ?? "Authentication failed";-- if (routeConfig.errorContract === structuredPublicApiErrorContract) {- return sendStructuredPublicApiErrorResponse(- res,- createStructuredPublicApiAuthError({ statusCode, message }),- );- }-- res.status(statusCode).json({ message });-- return;+ auth = {+ validKey: true,+ scope: result.scope as ApiAccessScopeWithOptionalApiKeyId & {+ projectId: string;+ accessLevel: RouteAccessLevel;+ },+ };}const rateLimitResponse =@@ -459,6 +279,8 @@ export const createAuthedProjectAPIRoute = <body,req,res,+ // A gateway-token scope carries no apiKeyId; route handlers that need+ // one gate on the api-key path, so narrow to the required shape here.auth: auth as AuthHeaderValidVerificationResult & {scope: { projectId: string; accessLevel: RouteAccessLevel };},diff --git a/web/src/features/public-api/server/enforceAuth.ts b/web/src/features/public-api/server/enforceAuth.tsnew file mode 100644index 0000000000..b2f2063ee5--- /dev/null+++ b/web/src/features/public-api/server/enforceAuth.ts@@ -0,0 +1,267 @@+import { type NextApiRequest } from "next";++import {+ type ForbiddenError,+ type InternalServerError,+ type LangfuseNotFoundError,+ type UnauthorizedError,+} from "@langfuse/shared";+import { type ApiAccessScope } from "@langfuse/shared/src/server";+import { prisma } from "@langfuse/shared/src/db";++import { authorize } from "@/src/features/auth/policy/authorize";+import { authenticator } from "@/src/features/apiKey/authenticator";+import { toApiAccessScope } from "@/src/features/public-api/server/toApiAccessScope";+import {+ forbiddenError,+ internalServerError,+ isOrgAction,+ notFoundError,+ type Action,+ type AuthorizationContext,+ type ErrorResult,+ type Principal,+ type Success,+} from "@/src/features/auth/policy/types";++/** orgIdHeader selects the target org. */+const orgIdHeader = "x-langfuse-organization-id";++/** projectIdHeader selects the target project for keys without a bound project. */+const projectIdHeader = "x-langfuse-project-id";++/** enforceAuth authenticates the request and authorizes an action for the given endpoint (combines authz and authn) */+export async function enforceAuth({+ req,+ action,+ allowInAppAgentKey,+ isAdminApiKeyAuthAllowed,+}: EnforceAuthParams): Promise<EnforceAuthResult> {+ const auth = await authenticator.authenticate({+ headers: req.headers,+ allowInAppAgentKey: allowInAppAgentKey,+ isAdminApiKeyAuthAllowed: isAdminApiKeyAuthAllowed,+ });+ if (!auth.success) return auth;++ const { context } = auth;+ switch (context.principal.kind) {+ case "admin":+ return enforceAdminAuthz(context, req, action);+ case "apiKey":+ return isOrgAction(action)+ ? enforceOrgAuthz(context, req, action)+ : enforceProjectAuthz(context, req, action);+ default:+ return internalServerError(`Unexpected principal on the public api`);+ }+}++/** enforceAdminAuthz resolves, authorizes, and scopes a self-host admin-key request against its target project; the authenticator admits admin keys only on opted-in, non-Cloud routes. */+async function enforceAdminAuthz(+ context: AuthorizationContext,+ req: NextApiRequest,+ action: Action,+): Promise<EnforceAuthResult> {+ const projectId = getHeaderProjectId(req);+ if (!projectId) return forbiddenError(`Missing '${projectIdHeader}' header`);++ const org = await lookupProjectOrgId(projectId);+ if (!org.success) return org;++ const decision = authorize(context, action, { projectId });+ if (!decision.success) return decision;++ return access(context, org.orgId, projectId);+}++/** enforceOrgAuthz resolves, authorizes, and scopes an organization-scoped api-key request. */+function enforceOrgAuthz(+ context: AuthorizationContext,+ req: NextApiRequest,+ action: Action,+): EnforceAuthResult {+ const org = getOrgId(context, req);+ if (!org.success) return org;++ const decision = authorize(context, action, { orgId: org.orgId });+ if (!decision.success) return decision;++ return access(context, org.orgId);+}++/** enforceProjectAuthz resolves, authorizes, and scopes a project-scoped api-key request against its bound org; an organization key naming a project outside its org is told the project does not exist, as the route handlers do. */+function enforceProjectAuthz(+ context: AuthorizationContext,+ req: NextApiRequest,+ action: Action,+): EnforceAuthResult {+ const project = getProjectId(context, req);+ if (!project.success) return project;++ if (!ownsProject(context.principal, project.projectId)) {+ return notFoundError("Project not found or you don't have access to it");+ }++ const decision = authorize(context, action, {+ projectId: project.projectId,+ });+ if (!decision.success) return decision;++ const orgId = getBoundOrgId(context);+ if (!orgId) return internalServerError(`Missing bound org on api-key`);++ return access(context, orgId, project.projectId);+}++/** getOrgId resolves the target org the key's bound org and the header agree on. */+function getOrgId(+ context: AuthorizationContext,+ req: NextApiRequest,+): ResolvedOrg | ErrorResult<ForbiddenError> {+ const requested = [getHeaderOrgId(req), getBoundOrgId(context)];+ const orgId = first(requested);+ if (!equal(requested) || !orgId) {+ return forbiddenError();+ }++ return { success: true, orgId };+}++/** getProjectId resolves the target project the key's bound project, the URL param, and the header agree on. */+function getProjectId(+ context: AuthorizationContext,+ req: NextApiRequest,+): ResolvedProject | ErrorResult<ForbiddenError> {+ const requested = [+ getBoundProjectId(context),+ getUrlProjectId(req),+ getHeaderProjectId(req),+ ];++ const projectId = first(requested);+ if (!equal(requested) || !projectId) {+ return forbiddenError();+ }++ return { success: true, projectId };+}++/** lookupProjectOrgId reads a project's org from the database, 404ing when the project is absent. */+async function lookupProjectOrgId(+ projectId: string,+): Promise<ResolvedOrg | ErrorResult<LangfuseNotFoundError>> {+ const project = await prisma.project.findUnique({+ where: { id: projectId, deletedAt: null },+ select: { orgId: true },+ });+ if (!project) {+ return notFoundError("Project not found");+ }+ return { success: true, orgId: project.orgId };+}++/** ownsProject reports whether the project belongs to one of the key's organizations. */+const ownsProject = (principal: Principal, projectId: string) =>+ "organizations" in principal &&+ principal.organizations.some((o) => o.projectIds.includes(projectId));++/** getBoundOrgId returns the org an api key is bound to. */+function getBoundOrgId(context: AuthorizationContext): string | undefined {+ if (context.principal.kind !== "apiKey") return undefined;+ return context.principal.boundResource.orgId;+}++/** getBoundProjectId returns the project an api key is bound to, when it is project-scoped. */+function getBoundProjectId(context: AuthorizationContext): string | undefined {+ if (context.principal.kind !== "apiKey") return undefined;+ return context.principal.boundResource.projectId;+}++/** getHeaderOrgId returns the target org from the header. */+function getHeaderOrgId(req: NextApiRequest): string | undefined {+ return getHeaderValue(req.headers[orgIdHeader]) || undefined;+}++/** getHeaderProjectId returns the target project from the header. */+function getHeaderProjectId(req: NextApiRequest): string | undefined {+ return getHeaderValue(req.headers[projectIdHeader]) || undefined;+}++/** getUrlProjectId returns the target project from the URL param. */+function getUrlProjectId(req: NextApiRequest): string | undefined {+ return typeof req.query.projectId === "string"+ ? req.query.projectId+ : undefined;+}++/** getHeaderValue normalizes a possibly-repeated header to its first value. */+const getHeaderValue = (+ value: string | string[] | undefined,+): string | undefined => (Array.isArray(value) ? value[0] : value);++/** equal returns true when every defined value agrees. */+function equal(os: (string | undefined)[]): boolean {+ let prev: string | undefined;+ for (const o of os) {+ if (prev && o && prev !== o) return false;+ if (o) prev = o;+ }+ return true;+}++/** first returns the first defined value. */+function first(os: (string | undefined)[]): string | undefined {+ return os.find((o) => o !== undefined);+}++/** access is returned when the enforceAuth grants access */+function access(+ context: AuthorizationContext,+ orgId: string,+ projectId?: string,+): AccessResult {+ return {+ success: true,+ scope: toApiAccessScope(context.principal, {+ orgId: orgId,+ projectId: projectId ?? null,+ }),+ ctx: context,+ };+}++/** EnforceAuthParams is the request, the checked action, and the request's key-kind opt-ins. */+export type EnforceAuthParams = {+ req: NextApiRequest;+ action: Action;+ allowInAppAgentKey?: boolean;+ isAdminApiKeyAuthAllowed?: boolean;+};++/** AccessResult is the seam's success outcome: the resolved ApiAccessScope and the context that authorized it. */+type AccessResult = Success & {+ scope: ApiAccessScope;+ ctx: AuthorizationContext;+};++/** EnforceAuthResult is the authorized scope, or the typed error the route renders. */+export type EnforceAuthResult =+ | AccessResult+ | ErrorResult<+ | UnauthorizedError+ | InternalServerError+ | ForbiddenError+ | LangfuseNotFoundError+ >;++/** ResolvedOrg is org target resolution's success outcome. */+type ResolvedOrg = Success & { orgId: string };++/** ResolvedProject is project target resolution's success outcome. */+type ResolvedProject = Success & { projectId: string };++export const __test = {+ getOrgId,+ getProjectId,+};diff --git a/web/src/features/public-api/server/shadowAuth.ts b/web/src/features/public-api/server/shadowAuth.tsnew file mode 100644index 0000000000..662e56c9a5--- /dev/null+++ b/web/src/features/public-api/server/shadowAuth.ts@@ -0,0 +1,154 @@+import { type NextApiRequest } from "next";++import { ApiError, type BaseError } from "@langfuse/shared";+import {+ type ApiAccessLevel,+ type ApiAccessScope,+ redis,+ traceException,+} from "@langfuse/shared/src/server";+import { prisma } from "@langfuse/shared/src/db";++import { env } from "@/src/env.mjs";+import { ApiAuthService } from "@/src/features/public-api/server/apiAuth";+import {+ verifyAuth as verifyLegacyProjectAuth,+ type RouteAccessLevel,+} from "@/src/features/public-api/server/verifyProjectApiKeyAuth";+import {+ enforceAuth,+ type EnforceAuthParams,+ type EnforceAuthResult,+} from "@/src/features/public-api/server/enforceAuth";+import { shadowAuthDiff } from "@/src/features/public-api/server/shadowAuthDiff";+import {+ forbiddenError,+ serviceUnavailableError,+ unauthorizedError,+ type AuthorizationContext,+ type ErrorResult,+ type Success,+} from "@/src/features/auth/policy/types";+import { isPrismaException } from "@/src/utils/exceptions";++/** shadowAuth authorizes a public-API request under the active migration mode, returning the scope or the error to render. */+export async function shadowAuth(+ params: ShadowAuthParams,+): Promise<ShadowAuthResult> {+ if (env.API_AUTH_MIGRATION === "enforce") return enforceOnly(params);+ if (env.API_AUTH_MIGRATION === "shadow") return legacyWithShadow(params);+ return legacyOnly(params);+}++/** enforceOnly authorizes solely with the new pipeline and returns its scope or error. */+function enforceOnly(params: ShadowAuthParams): Promise<ShadowAuthResult> {+ return runNewAuth(params);+}++/** legacyWithShadow lets legacy decide while the new pipeline records parity. */+async function legacyWithShadow(+ params: ShadowAuthParams,+): Promise<ShadowAuthResult> {+ const legacyAuth = await runLegacyAuth(params);+ const newAuth = await runNewAuth(params);+ shadowAuthDiff(newAuth, legacyAuth, params.action);+ return legacyResult(legacyAuth);+}++/** legacyOnly authorizes solely with the legacy verify. */+async function legacyOnly(params: ShadowAuthParams): Promise<ShadowAuthResult> {+ return legacyResult(await runLegacyAuth(params));+}++/** runNewAuth runs the new pipeline for the request's action and route opt-ins. */+function runNewAuth(params: ShadowAuthParams): Promise<EnforceAuthResult> {+ return enforceAuth(params);+}++/** runLegacyAuth dispatches to the legacy verify the route's access levels select. */+function runLegacyAuth(params: ShadowAuthParams): Promise<LegacyDecision> {+ return isOrgFamily(params.allowedAccessLevels)+ ? runLegacyOrgAuth(params.req)+ : runLegacyProjectAuth(params);+}++/** runLegacyOrgAuth verifies the credential and its organization access level, capturing every outcome as a value. */+async function runLegacyOrgAuth(req: NextApiRequest): Promise<LegacyDecision> {+ const authCheck = await new ApiAuthService(+ prisma,+ redis,+ ).verifyAuthHeaderAndReturnScope(req.headers.authorization);+ if (!authCheck.validKey) {+ return unauthorizedError(authCheck.error);+ }+ if (+ authCheck.scope.accessLevel !== "organization" ||+ !authCheck.scope.orgId+ ) {+ return forbiddenError();+ }+ return { success: true, scope: authCheck.scope };+}++/** runLegacyProjectAuth runs the legacy project verify and captures its throw as a value: an infra 503, or the status and message it reported. */+async function runLegacyProjectAuth(+ params: ShadowAuthParams,+): Promise<LegacyDecision> {+ try {+ const auth = await verifyLegacyProjectAuth(+ params.req,+ params.isAdminApiKeyAuthAllowed ?? false,+ params.allowedAccessLevels as RouteAccessLevel[],+ params.allowInAppAgentKey ?? false,+ );+ return { success: true, scope: auth.scope };+ } catch (error) {+ if (isPrismaException(error)) {+ traceException(error);+ return serviceUnavailableError("Service Unavailable");+ }+ const status = (error as { status?: unknown }).status;+ const message = (error as { message?: unknown }).message;+ const httpCode = typeof status === "number" ? status : 401;+ return {+ success: false,+ error: new ApiError(+ typeof message === "string" ? message : "Authentication failed",+ httpCode,+ ),+ };+ }+}++/** legacyResult lifts a legacy decision into the seam's success or error value. */+function legacyResult(legacy: LegacyDecision): ShadowAuthResult {+ if (legacy.success) return { success: true, scope: legacy.scope };+ return { success: false, error: legacy.error };+}++/** isOrgFamily reports whether the route's access levels select the organization legacy verify. */+function isOrgFamily(allowedAccessLevels: ApiAccessLevel[]): boolean {+ return (+ allowedAccessLevels.length === 1 &&+ allowedAccessLevels[0] === "organization"+ );+}++/** ShadowAuthParams is enforceAuth's params plus the access levels the legacy verify gates on. */+export type ShadowAuthParams = EnforceAuthParams & {+ allowedAccessLevels: ApiAccessLevel[];+};++/** ShadowAuthAccessResult is a verified scope; the authorizing context rides along only when the new pipeline produced it. */+export type ShadowAuthAccessResult = Success & {+ scope: ApiAccessScope;+ ctx?: AuthorizationContext;+};++/** ShadowAuthResult is the verified project or organization scope, or the error the route renders. */+export type ShadowAuthResult = ShadowAuthAccessResult | ErrorResult<BaseError>;++/** LegacyDecision is the legacy verify captured as a value: the verified scope, or the error to render. */+type LegacyDecision =+ | { success: true; scope: ApiAccessScope }+ | { success: false; error: BaseError };diff --git a/web/src/features/public-api/server/shadowAuthDiff.ts b/web/src/features/public-api/server/shadowAuthDiff.tsnew file mode 100644index 0000000000..7ecaaf5d9c--- /dev/null+++ b/web/src/features/public-api/server/shadowAuthDiff.ts@@ -0,0 +1,93 @@+import {+ getCurrentSpan,+ recordIncrement,+ type ApiAccessLevel,+} from "@langfuse/shared/src/server";++/** parityStat counts one authorization decision. */+const parityStat = "langfuse.authz.parity";++/** defaultTelemetry writes to dogstatsd and the active span; tests inject a capturing fake. */+const defaultTelemetry: Telemetry = {+ increment: (stat, tags) => recordIncrement(stat, 1, tags),+ span: () => getCurrentSpan(),+};++/** shadowAuthDiff classifies the new pipeline's decision against legacy's, emits `langfuse.authz.parity`, and returns the result. */+export function shadowAuthDiff(+ newDecision: NewDecision,+ legacyDecision: LegacyDecision,+ action: string,+ telemetry: Telemetry = defaultTelemetry,+): ParityResult {+ const n = newVerdict(newDecision);+ const l = legacyVerdict(legacyDecision);+ const result = classify(l.verdict, n.verdict);+ telemetry.increment(parityStat, {+ action,+ access_level: l.accessLevel,+ result,+ legacy_code: l.code,+ new_code: n.code,+ });+ telemetry.span()?.setAttribute(`${parityStat}.result`, result);+ return result;+}++/** newVerdict reads the new decision: success allows (200), else denies with its http code. */+function newVerdict(decision: NewDecision): { verdict: Verdict; code: number } {+ return decision.success+ ? { verdict: "allow", code: 200 }+ : { verdict: "deny", code: decision.error.httpCode };+}++/** legacyVerdict reads a legacy decision into a verdict, code, and the access level it resolved. */+function legacyVerdict(decision: LegacyDecision): {+ verdict: Verdict;+ code: number;+ accessLevel: string;+} {+ if ("absent" in decision)+ return { verdict: "absent", code: 0, accessLevel: "unknown" };+ return decision.success+ ? { verdict: "allow", code: 200, accessLevel: decision.scope.accessLevel }+ : {+ verdict: "deny",+ code: decision.error.httpCode,+ accessLevel: "unknown",+ };+}++/** classify names the disagreement: legacy without a gate is `net_new`, agreement is `match`, else which path is stricter. */+function classify(legacyVerdict: Verdict, newVerdict: Verdict): ParityResult {+ if (legacyVerdict === "absent") return "net_new";+ if (legacyVerdict === newVerdict) return "match";+ return newVerdict === "deny" ? "new_denies" : "new_allows";+}++/** Verdict is one path's decision at one enforcement point; legacy is `absent` only where it runs no gate. */+type Verdict = "allow" | "deny" | "absent";++/** ParityResult is the signal: agreement, which path is stricter, or net-new enforcement legacy never gated. */+export type ParityResult = "match" | "new_denies" | "new_allows" | "net_new";++/** LegacyDecision is the legacy path's outcome: it allowed with a resolved scope, denied with a typed error, or ran no gate. */+export type LegacyDecision =+ | { success: true; scope: { accessLevel: ApiAccessLevel } }+ | { success: false; error: { httpCode: number } }+ | { absent: true };++/** Telemetry is the emit surface, injectable so tests capture without a collector. */+export type Telemetry = {+ increment: (stat: string, tags: Record<string, string | number>) => void;+ span: () =>+ | { setAttribute: (key: string, value: string | number) => void }+ | undefined;+};++/** NewDecision is the new pipeline's outcome at a decision point: a success or a typed error carrying its http code. */+export type NewDecision =+ | { success: true }+ | { success: false; error: { httpCode: number } };++export const __test = { newVerdict, legacyVerdict };diff --git a/web/src/features/public-api/server/toApiAccessScope.ts b/web/src/features/public-api/server/toApiAccessScope.tsnew file mode 100644index 0000000000..f7445376da--- /dev/null+++ b/web/src/features/public-api/server/toApiAccessScope.ts@@ -0,0 +1,74 @@+import { InternalServerError } from "@langfuse/shared";+import {+ type ApiAccessLevel,+ type ApiAccessScope,+} from "@langfuse/shared/src/server";++import { type Principal } from "@/src/features/auth/policy/types";++/** toApiAccessScope maps an authenticated principal and its resolved target onto the legacy ApiAccessScope. */+// Legacy compatibility; delete once the migration retires ApiAccessScope.+export function toApiAccessScope(+ principal: Principal,+ target: TargetResource,+): ApiAccessScope {+ if (principal.kind === "admin") return adminScope(target);+ if (principal.kind !== "apiKey") {+ throw new InternalServerError(+ `unexpected principal on the public-API seam: ${principal.kind}`,+ );+ }+ return apiKeyScope(principal, target);+}++/** adminScope is the legacy self-host admin scope for a resolved target. */+function adminScope(target: TargetResource): ApiAccessScope {+ return {+ orgId: target.orgId,+ projectId: target.projectId,+ accessLevel: "project",+ plan: "oss",+ rateLimitOverrides: [],+ apiKeyId: "ADMIN_API_KEY",+ publicKey: "ADMIN_API_KEY",+ isIngestionSuspended: false,+ isInAppAgentKey: false,+ };+}++/** apiKeyScope maps an api-key principal and its resolved target onto the ApiAccessScope. */+function apiKeyScope(+ principal: ApiKeyPrincipal,+ target: TargetResource,+): ApiAccessScope {+ const [org] = principal.organizations;+ return {+ orgId: target.orgId,+ projectId: target.projectId,+ plan: org.plan,+ rateLimitOverrides: org.rateLimitOverrides,+ apiKeyId: principal.apiKeyId,+ publicKey: principal.publicKey,+ isIngestionSuspended: org.isIngestionSuspended,+ isInAppAgentKey: principal.isInAppAgentKey,+ accessLevel: apiKeyAccessLevel(principal, target.projectId),+ };+}++/** apiKeyAccessLevel is the access level a key's presentation grants on the target. */+function apiKeyAccessLevel(+ principal: ApiKeyPrincipal,+ projectId: string | null,+): ApiAccessLevel {+ return projectId === null+ ? "organization"+ : principal.presentation === "publicKey"+ ? "scores"+ : "project";+}++/** TargetResource is the resolved org and optional project a seam maps the principal onto. */+export type TargetResource = { orgId: string; projectId: string | null };++/** ApiKeyPrincipal is the api-key variant of `Principal` the mapper consumes. */+type ApiKeyPrincipal = Extract<Principal, { kind: "apiKey" }>;diff --git a/web/src/features/public-api/server/writeError.ts b/web/src/features/public-api/server/writeError.tsnew file mode 100644index 0000000000..6f695f9b0c--- /dev/null+++ b/web/src/features/public-api/server/writeError.ts@@ -0,0 +1,33 @@+import { type NextApiResponse } from "next";++import { type BaseError } from "@langfuse/shared";++/** ErrorOrgApiKeyRequired is the 403 message when a non-organization key hits an organization-scoped operation. */+export const ErrorOrgApiKeyRequired =+ "Invalid API key. Organization-scoped API key required for this operation.";++/** writeScimError renders an auth-deny error in the SCIM error envelope. */+export function writeScimError(res: NextApiResponse, error: BaseError): void {+ return res.status(error.httpCode).json({+ schemas: ["urn:ietf:params:scim:api:messages:2.0:Error"],+ detail: error.httpCode === 403 ? ErrorOrgApiKeyRequired : error.message,+ status: error.httpCode,+ });+}++/** writeOrgError renders an auth-deny error in the organization error envelope. */+export function writeOrgError(res: NextApiResponse, error: BaseError): void {+ return res.status(error.httpCode).json({+ error: error.httpCode === 403 ? ErrorOrgApiKeyRequired : error.message,+ });+}++/** writeProjectError renders an auth-deny error in the project error envelope. */+export function writeProjectError(+ res: NextApiResponse,+ error: BaseError,+): void {+ return res.status(error.httpCode).json({+ message: error.httpCode === 403 ? ErrorOrgApiKeyRequired : error.message,+ });+}diff --git a/web/src/features/rbac/constants/apiKeyAccessRights.ts b/web/src/features/rbac/constants/apiKeyAccessRights.tsindex 481359d36d..2432c9b047 100644--- a/web/src/features/rbac/constants/apiKeyAccessRights.ts+++ b/web/src/features/rbac/constants/apiKeyAccessRights.ts@@ -1,12 +1,30 @@import {allOrganizationActions,allProjectActions,+ type ProjectAction,type SystemPolicy,} from "@/src/features/auth/policy/types";/** ApiKeyRole is the policy layer's role vocabulary for an API key, decoupled from the DB `ApiKeyScope` enum. */export type ApiKeyRole = "PROJECT" | "ORGANIZATION" | "SCORES_INGEST" | "ADMIN";+/** orgKeyProjectActions are the project-kind actions an ORGANIZATION key holds against its own projects. */+const orgKeyProjectActions: ProjectAction[] = [+ "project:read",+ "apiKeys:read",+ "apiKeys:CUD",+ "projectMembers:read",+ "projectMembers:CUD",+ "project:update",+ "project:delete",+];++/** projectKeyActions is the project vocabulary a PROJECT key holds, less the project-administration actions reserved for ORGANIZATION keys and the session user. */+const projectKeyActions: ProjectAction[] = allProjectActions.filter(+ (action) =>+ action === "project:read" || !orgKeyProjectActions.includes(action),+);+/** apiKeyAccessRights maps each `ApiKeyRole` to its resource-less grants; the resolver binds each to the key's project/org, or the wildcard for ADMIN. */export const apiKeyAccessRights: Record<ApiKeyRole, SystemPolicy[]> = {PROJECT: [@@ -14,7 +32,7 @@ export const apiKeyAccessRights: Record<ApiKeyRole, SystemPolicy[]> = {kind: "project",source: { kind: "role", id: "PROJECT" },effect: "allow",- actions: allProjectActions,+ actions: projectKeyActions,},],ORGANIZATION: [@@ -28,7 +46,7 @@ export const apiKeyAccessRights: Record<ApiKeyRole, SystemPolicy[]> = {kind: "project",source: { kind: "role", id: "ORGANIZATION" },effect: "allow",- actions: ["project:read"],+ actions: orgKeyProjectActions,},],SCORES_INGEST: [diff --git a/web/src/features/rbac/constants/organizationAccessRights.ts b/web/src/features/rbac/constants/organizationAccessRights.tsindex 844d4aa863..3b96945b1f 100644--- a/web/src/features/rbac/constants/organizationAccessRights.ts+++ b/web/src/features/rbac/constants/organizationAccessRights.ts@@ -1,6 +1,7 @@import { type Role } from "@langfuse/shared/src/db";export const organizationScopes = [+ "projects:read","projects:create","projects:transfer_org","organization:CRUD_apiKeys",diff --git a/web/src/pages/api/public/integrations/blob-storage/[id].ts b/web/src/pages/api/public/integrations/blob-storage/[id].tsindex 6bacd9b2ad..917ec9ffa8 100644--- a/web/src/pages/api/public/integrations/blob-storage/[id].ts+++ b/web/src/pages/api/public/integrations/blob-storage/[id].ts@@ -1,18 +1,11 @@-import { ApiAuthService } from "@/src/features/public-api/server/apiAuth";import { withMiddlewares } from "@/src/features/public-api/server/withMiddlewares";import { prisma } from "@langfuse/shared/src/db";-import { redis } from "@langfuse/shared/src/server";import { type NextApiRequest, type NextApiResponse } from "next";-import { hasEntitlementBasedOnPlan } from "@/src/features/entitlements/server/hasEntitlement";import { auditLog } from "@/src/features/audit-logs/auditLog";-import {- InvalidRequestError,- LangfuseNotFoundError,- UnauthorizedError,- ForbiddenError,-} from "@langfuse/shared";+import { InvalidRequestError, LangfuseNotFoundError } from "@langfuse/shared";import type { BlobStorageIntegrationStatusResponseType } from "@/src/features/public-api/types/blob-storage-integrations";import { deriveSyncStatus } from "@/src/features/blobstorage-integration/deriveSyncStatus";+import { authorizeBlobStorageRequest } from "@/src/features/blobstorage-integration/authorizeBlobStorageRequest";export default withMiddlewares({GET: handleGetBlobStorageIntegrationStatus,@@ -23,36 +16,8 @@ async function handleDeleteBlobStorageIntegration(req: NextApiRequest,res: NextApiResponse,) {- // CHECK AUTH- const authCheck = await new ApiAuthService(- prisma,- redis,- ).verifyAuthHeaderAndReturnScope(req.headers.authorization);- if (!authCheck.validKey) {- throw new UnauthorizedError(authCheck.error ?? "Unauthorized");- }-- // Check if using an organization API key- if (- authCheck.scope.accessLevel !== "organization" ||- !authCheck.scope.orgId- ) {- throw new ForbiddenError(- "Organization-scoped API key required for this operation.",- );- }+ const scope = await authorizeBlobStorageRequest(req);- // Check scheduled-blob-exports entitlement- if (- !hasEntitlementBasedOnPlan({- plan: authCheck.scope.plan,- entitlement: "scheduled-blob-exports",- })- ) {- throw new ForbiddenError(- "scheduled-blob-exports entitlement required for this feature.",- );- }const { id } = req.query;if (!id || typeof id !== "string") {@@ -69,7 +34,7 @@ async function handleDeleteBlobStorageIntegration(},});- if (!integration || integration.project.orgId !== authCheck.scope.orgId) {+ if (!integration || integration.project.orgId !== scope.orgId) {throw new LangfuseNotFoundError("Blob storage integration not found");}@@ -83,8 +48,8 @@ async function handleDeleteBlobStorageIntegration(resourceType: "blobStorageIntegration",resourceId: integration.projectId,projectId: integration.projectId,- orgId: authCheck.scope.orgId,- apiKeyId: authCheck.scope.apiKeyId,+ orgId: scope.orgId,+ apiKeyId: scope.apiKeyId,});return res.status(200).json({@@ -96,33 +61,7 @@ async function handleGetBlobStorageIntegrationStatus(req: NextApiRequest,res: NextApiResponse,) {- const authCheck = await new ApiAuthService(- prisma,- redis,- ).verifyAuthHeaderAndReturnScope(req.headers.authorization);- if (!authCheck.validKey) {- throw new UnauthorizedError(authCheck.error ?? "Unauthorized");- }-- if (- authCheck.scope.accessLevel !== "organization" ||- !authCheck.scope.orgId- ) {- throw new ForbiddenError(- "Organization-scoped API key required for this operation.",- );- }-- if (- !hasEntitlementBasedOnPlan({- plan: authCheck.scope.plan,- entitlement: "scheduled-blob-exports",- })- ) {- throw new ForbiddenError(- "scheduled-blob-exports entitlement required for this feature.",- );- }+ const scope = await authorizeBlobStorageRequest(req);const { id } = req.query;if (!id || typeof id !== "string") {@@ -138,7 +77,7 @@ async function handleGetBlobStorageIntegrationStatus(},});- if (!integration || integration.project.orgId !== authCheck.scope.orgId) {+ if (!integration || integration.project.orgId !== scope.orgId) {throw new LangfuseNotFoundError("Blob storage integration not found");}diff --git a/web/src/pages/api/public/integrations/blob-storage/index.ts b/web/src/pages/api/public/integrations/blob-storage/index.tsindex 435ee13838..89e50eb3e7 100644--- a/web/src/pages/api/public/integrations/blob-storage/index.ts+++ b/web/src/pages/api/public/integrations/blob-storage/index.ts@@ -1,9 +1,6 @@-import { ApiAuthService } from "@/src/features/public-api/server/apiAuth";import { withMiddlewares } from "@/src/features/public-api/server/withMiddlewares";import { prisma } from "@langfuse/shared/src/db";-import { redis } from "@langfuse/shared/src/server";import { type NextApiRequest, type NextApiResponse } from "next";-import { hasEntitlementBasedOnPlan } from "@/src/features/entitlements/server/hasEntitlement";import {CreateBlobStorageIntegrationRequest,toInternalExportSource,@@ -13,12 +10,11 @@ import {import {type ObservationFieldGroupFull,LangfuseNotFoundError,- UnauthorizedError,- ForbiddenError,} from "@langfuse/shared";import { upsertBlobStorageIntegration } from "@/src/features/blobstorage-integration/service";import { resolveExportSource } from "@/src/features/analytics-integrations/server/exportSource";import { auditLog } from "@/src/features/audit-logs/auditLog";+import { authorizeBlobStorageRequest } from "@/src/features/blobstorage-integration/authorizeBlobStorageRequest";export default withMiddlewares({GET: handleGetBlobStorageIntegrations,@@ -29,40 +25,11 @@ async function handleGetBlobStorageIntegrations(req: NextApiRequest,res: NextApiResponse,) {- // CHECK AUTH- const authCheck = await new ApiAuthService(- prisma,- redis,- ).verifyAuthHeaderAndReturnScope(req.headers.authorization);- if (!authCheck.validKey) {- throw new UnauthorizedError(authCheck.error ?? "Unauthorized");- }-- // Check if using an organization API key- if (- authCheck.scope.accessLevel !== "organization" ||- !authCheck.scope.orgId- ) {- throw new ForbiddenError(- "Organization-scoped API key required for this operation.",- );- }-- // Check scheduled-blob-exports entitlement- if (- !hasEntitlementBasedOnPlan({- plan: authCheck.scope.plan,- entitlement: "scheduled-blob-exports",- })- ) {- throw new ForbiddenError(- "scheduled-blob-exports entitlement required for this feature.",- );- }+ const scope = await authorizeBlobStorageRequest(req);// Get all projects for the organizationconst projects = await prisma.project.findMany({- where: { orgId: authCheck.scope.orgId },+ where: { orgId: scope.orgId },select: { id: true },});@@ -112,36 +79,7 @@ async function handleUpsertBlobStorageIntegration(req: NextApiRequest,res: NextApiResponse,) {- // CHECK AUTH- const authCheck = await new ApiAuthService(- prisma,- redis,- ).verifyAuthHeaderAndReturnScope(req.headers.authorization);- if (!authCheck.validKey) {- throw new UnauthorizedError(authCheck.error ?? "Unauthorized");- }-- // Check if using an organization API key- if (- authCheck.scope.accessLevel !== "organization" ||- !authCheck.scope.orgId- ) {- throw new ForbiddenError(- "Organization-scoped API key required for this operation.",- );- }-- // Check scheduled-blob-exports entitlement- if (- !hasEntitlementBasedOnPlan({- plan: authCheck.scope.plan,- entitlement: "scheduled-blob-exports",- })- ) {- throw new ForbiddenError(- "scheduled-blob-exports entitlement required for this feature.",- );- }+ const scope = await authorizeBlobStorageRequest(req);// Validate request bodyconst validatedData = CreateBlobStorageIntegrationRequest.parse(req.body);@@ -151,7 +89,7 @@ async function handleUpsertBlobStorageIntegration(where: { id: validatedData.projectId },select: { id: true, orgId: true, createdAt: true },});- if (!project || project.orgId !== authCheck.scope.orgId) {+ if (!project || project.orgId !== scope.orgId) {throw new LangfuseNotFoundError("Project not found");}@@ -187,8 +125,8 @@ async function handleUpsertBlobStorageIntegration(action: "update",resourceType: "blobStorageIntegration",resourceId: validatedData.projectId,- apiKeyId: authCheck.scope.apiKeyId,- orgId: authCheck.scope.orgId,+ apiKeyId: scope.apiKeyId,+ orgId: scope.orgId,});const integration = await upsertBlobStorageIntegration({diff --git a/web/src/pages/api/public/organizations/apiKeys/index.ts b/web/src/pages/api/public/organizations/apiKeys/index.tsindex ef515c2244..d47d7191af 100644--- a/web/src/pages/api/public/organizations/apiKeys/index.ts+++ b/web/src/pages/api/public/organizations/apiKeys/index.ts@@ -1,9 +1,9 @@-import { ApiAuthService } from "@/src/features/public-api/server/apiAuth";import { cors, runMiddleware } from "@/src/features/public-api/server/cors";-import { prisma } from "@langfuse/shared/src/db";-import { logger, redis } from "@langfuse/shared/src/server";+import { logger } from "@langfuse/shared/src/server";import { RateLimitService } from "@/src/features/public-api/server/RateLimitService";import { handleGetApiKeys } from "@/src/ee/features/admin-api/server/organizations/apiKeys";+import { shadowAuth } from "@/src/features/public-api/server/shadowAuth";+import { writeOrgError } from "@/src/features/public-api/server/writeError";import { type NextApiRequest, type NextApiResponse } from "next";import { hasEntitlementBasedOnPlan } from "@/src/features/entitlements/server/hasEntitlement";@@ -24,28 +24,16 @@ export default async function handler(}// CHECK AUTH- const authCheck = await new ApiAuthService(- prisma,- redis,- ).verifyAuthHeaderAndReturnScope(req.headers.authorization);- if (!authCheck.validKey) {- return res.status(401).json({- error: authCheck.error,- });+ const authCheck = await shadowAuth({+ req,+ action: "organization:CRUD_apiKeys",+ allowedAccessLevels: ["organization"],+ });+ if (!authCheck.success) {+ return writeOrgError(res, authCheck.error);}// END CHECK AUTH- // Check if using an organization API key- if (- authCheck.scope.accessLevel !== "organization" ||- !authCheck.scope.orgId- ) {- return res.status(403).json({- error:- "Invalid API key. Organization-scoped API key required for this operation.",- });- }-if (!hasEntitlementBasedOnPlan({plan: authCheck.scope.plan,diff --git a/web/src/pages/api/public/organizations/memberships/index.ts b/web/src/pages/api/public/organizations/memberships/index.tsindex 9d8830b9ed..42e38b2514 100644--- a/web/src/pages/api/public/organizations/memberships/index.ts+++ b/web/src/pages/api/public/organizations/memberships/index.ts@@ -1,13 +1,13 @@-import { ApiAuthService } from "@/src/features/public-api/server/apiAuth";import { cors, runMiddleware } from "@/src/features/public-api/server/cors";-import { prisma } from "@langfuse/shared/src/db";-import { logger, redis } from "@langfuse/shared/src/server";+import { logger } from "@langfuse/shared/src/server";import { RateLimitService } from "@/src/features/public-api/server/RateLimitService";import {handleGetMemberships,handleUpdateMembership,handleDeleteMembership,} from "@/src/ee/features/admin-api/server/memberships";+import { shadowAuth } from "@/src/features/public-api/server/shadowAuth";+import { writeOrgError } from "@/src/features/public-api/server/writeError";import { type NextApiRequest, type NextApiResponse } from "next";import { hasEntitlementBasedOnPlan } from "@/src/features/entitlements/server/hasEntitlement";@@ -28,28 +28,19 @@ export default async function handler(}// CHECK AUTH- const authCheck = await new ApiAuthService(- prisma,- redis,- ).verifyAuthHeaderAndReturnScope(req.headers.authorization);- if (!authCheck.validKey) {- return res.status(401).json({- error: authCheck.error,- });+ const authCheck = await shadowAuth({+ req,+ action:+ req.method === "GET"+ ? "organizationMembers:read"+ : "organizationMembers:CUD",+ allowedAccessLevels: ["organization"],+ });+ if (!authCheck.success) {+ return writeOrgError(res, authCheck.error);}// END CHECK AUTH- // Check if using an organization API key- if (- authCheck.scope.accessLevel !== "organization" ||- !authCheck.scope.orgId- ) {- return res.status(403).json({- error:- "Invalid API key. Organization-scoped API key required for this operation.",- });- }-if (!hasEntitlementBasedOnPlan({plan: authCheck.scope.plan,diff --git a/web/src/pages/api/public/organizations/projects/index.ts b/web/src/pages/api/public/organizations/projects/index.tsindex 114f6b9c90..00413070a2 100644--- a/web/src/pages/api/public/organizations/projects/index.ts+++ b/web/src/pages/api/public/organizations/projects/index.ts@@ -1,23 +1,12 @@-import { type IncomingHttpHeaders } from "http";--import { ApiAuthService } from "@/src/features/public-api/server/apiAuth";import { cors, runMiddleware } from "@/src/features/public-api/server/cors";-import { prisma } from "@langfuse/shared/src/db";-import { logger, redis } from "@langfuse/shared/src/server";+import { logger } from "@langfuse/shared/src/server";import { RateLimitService } from "@/src/features/public-api/server/RateLimitService";import { handleGetProjects } from "@/src/ee/features/admin-api/server/projects";+import { shadowAuth } from "@/src/features/public-api/server/shadowAuth";+import { writeOrgError } from "@/src/features/public-api/server/writeError";import { type NextApiRequest, type NextApiResponse } from "next";import { hasEntitlementBasedOnPlan } from "@/src/features/entitlements/server/hasEntitlement";-import { env } from "@/src/env.mjs";-import { authenticator } from "@/src/features/apiKey/authenticator";-import { authorize } from "@/src/features/auth/policy/authorize";-import {- diffResults,- legacyFromStatus,- recordCoverage,- type NewResult,-} from "@/src/features/auth/policy/shadow";export default async function handler(req: NextApiRequest,@@ -35,28 +24,16 @@ export default async function handler(}// CHECK AUTH- const authCheck = await new ApiAuthService(- prisma,- redis,- ).verifyAuthHeaderAndReturnScope(req.headers.authorization);- if (!authCheck.validKey) {- return res.status(401).json({- error: authCheck.error,- });+ const authCheck = await shadowAuth({+ req,+ action: "projects:read",+ allowedAccessLevels: ["organization"],+ });+ if (!authCheck.success) {+ return writeOrgError(res, authCheck.error);}// END CHECK AUTH- // Check if using an organization API key- if (- authCheck.scope.accessLevel !== "organization" ||- !authCheck.scope.orgId- ) {- return res.status(403).json({- error:- "Invalid API key. Organization-scoped API key required for this operation.",- });- }-if (!hasEntitlementBasedOnPlan({plan: authCheck.scope.plan,@@ -68,25 +45,6 @@ export default async function handler(});}- // Route the project:read decision through the policy core. Legacy skips the- // pipeline; shadow records parity without changing behavior; enforce gates.- if (env.API_AUTH_MIGRATION !== "legacy") {- const authz = await authorizeOrgProjectsRead(req.headers);- if (env.API_AUTH_MIGRATION === "shadow") {- recordCoverage("List Projects");- diffResults(authz, legacyFromStatus(200), {- seam: "org_route",- action: "project:read",- });- }- if (env.API_AUTH_MIGRATION === "enforce" && !authz.success) {- return res.status(403).json({- error:- "Invalid API key. Organization-scoped API key required for this operation.",- });- }- }-const rateLimitCheck = await RateLimitService.getInstance().rateLimitRequest(authCheck.scope,"public-api",@@ -97,7 +55,7 @@ export default async function handler(// Route to the appropriate handler based on HTTP methodtry {- return handleGetProjects(req, res, authCheck.scope.orgId);+ return handleGetProjects(req, res, authCheck.scope.orgId, authCheck.ctx);} catch (error) {logger.error(`Error handling organization projects for ${req.method}`,@@ -108,26 +66,3 @@ export default async function handler(});}}--/** authorizeOrgProjectsRead resolves the request's context and checks project:read across the org's projects (vacuously allowing an org with none). */-async function authorizeOrgProjectsRead(- headers: IncomingHttpHeaders,-): Promise<NewResult> {- const authn = await authenticator.authenticate({ headers });- if (!authn.success) {- return { success: false, error: { httpCode: authn.error.httpCode } };- }- const context = authn.context;- const orgProjectIds =- context.principal.kind === "apiKey"- ? context.principal.organizations.flatMap((o) => o.projectIds)- : [];- const allowed =- orgProjectIds.length === 0 ||- orgProjectIds.some(- (projectId) => authorize(context, "project:read", { projectId }).success,- );- return allowed- ? { success: true }- : { success: false, error: { httpCode: 403 } };-}diff --git a/web/src/pages/api/public/projects/[projectId]/apiKeys/[apiKeyId].ts b/web/src/pages/api/public/projects/[projectId]/apiKeys/[apiKeyId].tsindex 7699fb5cc5..21eb540618 100644--- a/web/src/pages/api/public/projects/[projectId]/apiKeys/[apiKeyId].ts+++ b/web/src/pages/api/public/projects/[projectId]/apiKeys/[apiKeyId].ts@@ -1,7 +1,6 @@import { type NextApiRequest, type NextApiResponse } from "next";import { prisma } from "@langfuse/shared/src/db";-import { logger, redis } from "@langfuse/shared/src/server";-import { ApiAuthService } from "@/src/features/public-api/server/apiAuth";+import { logger } from "@langfuse/shared/src/server";import { cors, runMiddleware } from "@/src/features/public-api/server/cors";import { RateLimitService } from "@/src/features/public-api/server/RateLimitService";import {@@ -9,6 +8,8 @@ import {handleDeleteApiKey,} from "@/src/ee/features/admin-api/server/projects/projectById/apiKeys/apiKeyById";import { hasEntitlementBasedOnPlan } from "@/src/features/entitlements/server/hasEntitlement";+import { shadowAuth } from "@/src/features/public-api/server/shadowAuth";+import { writeProjectError } from "@/src/features/public-api/server/writeError";export default async function handler(req: NextApiRequest,@@ -22,28 +23,21 @@ export default async function handler(return;}- // CHECK AUTH- const authCheck = await new ApiAuthService(- prisma,- redis,- ).verifyAuthHeaderAndReturnScope(req.headers.authorization);- if (!authCheck.validKey) {- return res.status(401).json({- message: authCheck.error,- });+ const authCheck = await shadowAuth({+ req,+ action: "apiKeys:CUD",+ allowedAccessLevels: ["organization"],+ });+ if (!authCheck.success) {+ return writeProjectError(res, authCheck.error);}- // Check if using an organization API key- if (- authCheck.scope.accessLevel !== "organization" ||- !authCheck.scope.orgId- ) {- return res.status(403).json({- message:- "Invalid API key. Organization-scoped API key required for this operation.",- });+ const params = validateQueryParams(req.query);+ if (!params) {+ return res.status(400).json({ message: "Invalid request parameters" });}- // END CHECK AUTH++ const { projectId, apiKeyId } = params;if (!hasEntitlementBasedOnPlan({@@ -65,13 +59,6 @@ export default async function handler(return rateLimitCheck.sendRestResponseIfLimited(res);}- const params = validateQueryParams(req.query);- if (!params) {- return res.status(400).json({ message: "Invalid request parameters" });- }-- const { projectId, apiKeyId } = params;-// Check if project exists and belongs to the organizationconst project = await prisma.project.findFirst({where: {diff --git a/web/src/pages/api/public/projects/[projectId]/apiKeys/index.ts b/web/src/pages/api/public/projects/[projectId]/apiKeys/index.tsindex f6cafd54a9..de51c36f15 100644--- a/web/src/pages/api/public/projects/[projectId]/apiKeys/index.ts+++ b/web/src/pages/api/public/projects/[projectId]/apiKeys/index.ts@@ -1,7 +1,6 @@import { type NextApiRequest, type NextApiResponse } from "next";import { prisma } from "@langfuse/shared/src/db";-import { logger, redis } from "@langfuse/shared/src/server";-import { ApiAuthService } from "@/src/features/public-api/server/apiAuth";+import { logger } from "@langfuse/shared/src/server";import { cors, runMiddleware } from "@/src/features/public-api/server/cors";import { RateLimitService } from "@/src/features/public-api/server/RateLimitService";import {@@ -10,6 +9,8 @@ import {handleCreateApiKey,} from "@/src/ee/features/admin-api/server/projects/projectById/apiKeys";import { hasEntitlementBasedOnPlan } from "@/src/features/entitlements/server/hasEntitlement";+import { shadowAuth } from "@/src/features/public-api/server/shadowAuth";+import { writeProjectError } from "@/src/features/public-api/server/writeError";export default async function handler(req: NextApiRequest,@@ -23,28 +24,19 @@ export default async function handler(return;}- // CHECK AUTH- const authCheck = await new ApiAuthService(- prisma,- redis,- ).verifyAuthHeaderAndReturnScope(req.headers.authorization);- if (!authCheck.validKey) {- return res.status(401).json({- message: authCheck.error,- });+ const authCheck = await shadowAuth({+ req,+ action: req.method === "GET" ? "apiKeys:read" : "apiKeys:CUD",+ allowedAccessLevels: ["organization"],+ });+ if (!authCheck.success) {+ return writeProjectError(res, authCheck.error);}- // Check if using an organization API key- if (- authCheck.scope.accessLevel !== "organization" ||- !authCheck.scope.orgId- ) {- return res.status(403).json({- message:- "Invalid API key. Organization-scoped API key required for this operation.",- });+ const projectId = validateQueryAndExtractId(req.query);+ if (!projectId) {+ return res.status(400).json({ message: "Invalid project ID" });}- // END CHECK AUTHif (!hasEntitlementBasedOnPlan({@@ -66,11 +58,6 @@ export default async function handler(return rateLimitCheck.sendRestResponseIfLimited(res);}- const projectId = validateQueryAndExtractId(req.query);- if (!projectId) {- return res.status(400).json({ message: "Invalid project ID" });- }-// Check if project exists and belongs to the organizationconst project = await prisma.project.findFirst({where: {diff --git a/web/src/pages/api/public/projects/[projectId]/index.ts b/web/src/pages/api/public/projects/[projectId]/index.tsindex 29700a762b..b8321fc5da 100644--- a/web/src/pages/api/public/projects/[projectId]/index.ts+++ b/web/src/pages/api/public/projects/[projectId]/index.ts@@ -1,13 +1,14 @@-import { ApiAuthService } from "@/src/features/public-api/server/apiAuth";import { cors, runMiddleware } from "@/src/features/public-api/server/cors";import { prisma } from "@langfuse/shared/src/db";-import { logger, redis } from "@langfuse/shared/src/server";+import { logger } from "@langfuse/shared/src/server";import {handleUpdateProject,handleDeleteProject,} from "@/src/ee/features/admin-api/server/projects/projectById";import { hasEntitlementBasedOnPlan } from "@/src/features/entitlements/server/hasEntitlement";import { type NextApiRequest, type NextApiResponse } from "next";+import { shadowAuth } from "@/src/features/public-api/server/shadowAuth";+import { writeProjectError } from "@/src/features/public-api/server/writeError";export default async function handler(req: NextApiRequest,@@ -29,25 +30,13 @@ export default async function handler(}// CHECK AUTH- const authCheck = await new ApiAuthService(- prisma,- redis,- ).verifyAuthHeaderAndReturnScope(req.headers.authorization);- if (!authCheck.validKey) {- return res.status(401).json({- message: authCheck.error,- });- }-- // Check if using an organization API key- if (- authCheck.scope.accessLevel !== "organization" ||- !authCheck.scope.orgId- ) {- return res.status(403).json({- message:- "Invalid API key. Organization-scoped API key required for this operation.",- });+ const authCheck = await shadowAuth({+ req,+ action: req.method === "PUT" ? "project:update" : "project:delete",+ allowedAccessLevels: ["organization"],+ });+ if (!authCheck.success) {+ return writeProjectError(res, authCheck.error);}// END CHECK AUTHdiff --git a/web/src/pages/api/public/projects/[projectId]/memberships/index.ts b/web/src/pages/api/public/projects/[projectId]/memberships/index.tsindex 170c2129fe..2203a80ee0 100644--- a/web/src/pages/api/public/projects/[projectId]/memberships/index.ts+++ b/web/src/pages/api/public/projects/[projectId]/memberships/index.ts@@ -1,7 +1,6 @@-import { ApiAuthService } from "@/src/features/public-api/server/apiAuth";import { cors, runMiddleware } from "@/src/features/public-api/server/cors";import { prisma } from "@langfuse/shared/src/db";-import { logger, redis } from "@langfuse/shared/src/server";+import { logger } from "@langfuse/shared/src/server";import { hasEntitlementBasedOnPlan } from "@/src/features/entitlements/server/hasEntitlement";import {handleGetMemberships,@@ -10,6 +9,8 @@ import {} from "@/src/ee/features/admin-api/server/projects/projectById/memberships";import { type NextApiRequest, type NextApiResponse } from "next";+import { shadowAuth } from "@/src/features/public-api/server/shadowAuth";+import { writeOrgError } from "@/src/features/public-api/server/writeError";export default async function handler(req: NextApiRequest,@@ -34,28 +35,16 @@ export default async function handler(}// CHECK AUTH- const authCheck = await new ApiAuthService(- prisma,- redis,- ).verifyAuthHeaderAndReturnScope(req.headers.authorization);- if (!authCheck.validKey) {- return res.status(401).json({- error: authCheck.error,- });+ const authCheck = await shadowAuth({+ req,+ action: req.method === "GET" ? "projectMembers:read" : "projectMembers:CUD",+ allowedAccessLevels: ["organization"],+ });+ if (!authCheck.success) {+ return writeOrgError(res, authCheck.error);}// END CHECK AUTH- // Check if using an organization API key- if (- authCheck.scope.accessLevel !== "organization" ||- !authCheck.scope.orgId- ) {- return res.status(403).json({- error:- "Invalid API key. Organization-scoped API key required for this operation.",- });- }-// Check if organization has the rbac-project-roles entitlementif (!hasEntitlementBasedOnPlan({diff --git a/web/src/pages/api/public/projects/index.ts b/web/src/pages/api/public/projects/index.tsindex d74fe3ce6d..bcc2afd545 100644--- a/web/src/pages/api/public/projects/index.ts+++ b/web/src/pages/api/public/projects/index.ts@@ -1,10 +1,15 @@-import { ApiAuthService } from "@/src/features/public-api/server/apiAuth";import { cors, runMiddleware } from "@/src/features/public-api/server/cors";import { prisma } from "@langfuse/shared/src/db";-import { logger, redis } from "@langfuse/shared/src/server";+import { logger } from "@langfuse/shared/src/server";import { handleCreateProject } from "@/src/ee/features/admin-api/server/projects/createProject";import { type NextApiRequest, type NextApiResponse } from "next";import { hasEntitlementBasedOnPlan } from "@/src/features/entitlements/server/hasEntitlement";+import { shadowAuth } from "@/src/features/public-api/server/shadowAuth";+import { writeProjectError } from "@/src/features/public-api/server/writeError";++/** projectKeyRequired is the 403 body when the project-scoped GET receives a non-project key. */+const projectKeyRequired =+ "Invalid API key. Are you using an organization key?";export default async function handler(req: NextApiRequest,@@ -19,27 +24,20 @@ export default async function handler(return res.status(405).json({ message: "Method not allowed" });}- // CHECK AUTH- const authCheck = await new ApiAuthService(- prisma,- redis,- ).verifyAuthHeaderAndReturnScope(req.headers.authorization);- if (!authCheck.validKey) {- return res.status(401).json({- message: authCheck.error,- });- }- // END CHECK AUTH-if (req.method === "GET") {- if (- authCheck.scope.accessLevel !== "project" ||- !authCheck.scope.projectId- ) {- return res.status(403).json({- message: "Invalid API key. Are you using an organization key?",+ const auth = await shadowAuth({+ req,+ action: "project:read",+ allowedAccessLevels: ["project"],+ });+ if (!auth.success) {+ const status = auth.error.httpCode;+ return res.status(status).json({+ message: status === 403 ? projectKeyRequired : auth.error.message,});}+ // project:read guarantees a project-scoped key, so projectId is always set.+ const projectId = auth.scope.projectId as string;try {// Do not apply rate limits as it can break applications on lower tier plans when using auth_check in prod@@ -58,7 +56,7 @@ export default async function handler(},},where: {- id: authCheck.scope.projectId,+ id: projectId,deletedAt: null,},});@@ -84,15 +82,13 @@ export default async function handler(}if (req.method === "POST") {- // Check if using an organization API key- if (- authCheck.scope.accessLevel !== "organization" ||- !authCheck.scope.orgId- ) {- return res.status(403).json({- message:- "Invalid API key. Organization-scoped API key required for this operation.",- });+ const authCheck = await shadowAuth({+ req,+ action: "projects:create",+ allowedAccessLevels: ["organization"],+ });+ if (!authCheck.success) {+ return writeProjectError(res, authCheck.error);}if (diff --git a/web/src/pages/api/public/scim/ResourceTypes.ts b/web/src/pages/api/public/scim/ResourceTypes.tsindex 92666fd875..c2f56fab40 100644--- a/web/src/pages/api/public/scim/ResourceTypes.ts+++ b/web/src/pages/api/public/scim/ResourceTypes.ts@@ -1,7 +1,7 @@-import { ApiAuthService } from "@/src/features/public-api/server/apiAuth";import { cors, runMiddleware } from "@/src/features/public-api/server/cors";-import { prisma } from "@langfuse/shared/src/db";-import { logger, redis } from "@langfuse/shared/src/server";+import { logger } from "@langfuse/shared/src/server";+import { shadowAuth } from "@/src/features/public-api/server/shadowAuth";+import { writeScimError } from "@/src/features/public-api/server/writeError";import { type NextApiRequest, type NextApiResponse } from "next";@@ -23,32 +23,16 @@ export default async function handler(}// CHECK AUTH- const authCheck = await new ApiAuthService(- prisma,- redis,- ).verifyAuthHeaderAndReturnScope(req.headers.authorization);- if (!authCheck.validKey) {- return res.status(401).json({- schemas: ["urn:ietf:params:scim:api:messages:2.0:Error"],- detail: authCheck.error,- status: 401,- });+ const authCheck = await shadowAuth({+ req,+ action: "organizationMembers:read",+ allowedAccessLevels: ["organization"],+ });+ if (!authCheck.success) {+ return writeScimError(res, authCheck.error);}// END CHECK AUTH- // Check if using an organization API key- if (- authCheck.scope.accessLevel !== "organization" ||- !authCheck.scope.orgId- ) {- return res.status(403).json({- schemas: ["urn:ietf:params:scim:api:messages:2.0:Error"],- detail:- "Invalid API key. Organization-scoped API key required for this operation.",- status: 403,- });- }-// Return the resource typesreturn res.status(200).json({schemas: ["urn:ietf:params:scim:api:messages:2.0:ListResponse"],diff --git a/web/src/pages/api/public/scim/Schemas.ts b/web/src/pages/api/public/scim/Schemas.tsindex eb79f250fa..0152a809eb 100644--- a/web/src/pages/api/public/scim/Schemas.ts+++ b/web/src/pages/api/public/scim/Schemas.ts@@ -1,7 +1,7 @@-import { ApiAuthService } from "@/src/features/public-api/server/apiAuth";import { cors, runMiddleware } from "@/src/features/public-api/server/cors";-import { prisma } from "@langfuse/shared/src/db";-import { logger, redis } from "@langfuse/shared/src/server";+import { logger } from "@langfuse/shared/src/server";+import { shadowAuth } from "@/src/features/public-api/server/shadowAuth";+import { writeScimError } from "@/src/features/public-api/server/writeError";import { type NextApiRequest, type NextApiResponse } from "next";@@ -23,32 +23,16 @@ export default async function handler(}// CHECK AUTH- const authCheck = await new ApiAuthService(- prisma,- redis,- ).verifyAuthHeaderAndReturnScope(req.headers.authorization);- if (!authCheck.validKey) {- return res.status(401).json({- schemas: ["urn:ietf:params:scim:api:messages:2.0:Error"],- detail: authCheck.error,- status: 401,- });+ const authCheck = await shadowAuth({+ req,+ action: "organizationMembers:read",+ allowedAccessLevels: ["organization"],+ });+ if (!authCheck.success) {+ return writeScimError(res, authCheck.error);}// END CHECK AUTH- // Check if using an organization API key- if (- authCheck.scope.accessLevel !== "organization" ||- !authCheck.scope.orgId- ) {- return res.status(403).json({- schemas: ["urn:ietf:params:scim:api:messages:2.0:Error"],- detail:- "Invalid API key. Organization-scoped API key required for this operation.",- status: 403,- });- }-// Return the schemasreturn res.status(200).json({schemas: ["urn:ietf:params:scim:api:messages:2.0:ListResponse"],diff --git a/web/src/pages/api/public/scim/ServiceProviderConfig.ts b/web/src/pages/api/public/scim/ServiceProviderConfig.tsindex fd96fe6501..99c2b8b012 100644--- a/web/src/pages/api/public/scim/ServiceProviderConfig.ts+++ b/web/src/pages/api/public/scim/ServiceProviderConfig.ts@@ -1,7 +1,7 @@-import { ApiAuthService } from "@/src/features/public-api/server/apiAuth";import { cors, runMiddleware } from "@/src/features/public-api/server/cors";-import { prisma } from "@langfuse/shared/src/db";-import { logger, redis } from "@langfuse/shared/src/server";+import { logger } from "@langfuse/shared/src/server";+import { shadowAuth } from "@/src/features/public-api/server/shadowAuth";+import { writeScimError } from "@/src/features/public-api/server/writeError";import { type NextApiRequest, type NextApiResponse } from "next";@@ -23,32 +23,16 @@ export default async function handler(}// CHECK AUTH- const authCheck = await new ApiAuthService(- prisma,- redis,- ).verifyAuthHeaderAndReturnScope(req.headers.authorization);- if (!authCheck.validKey) {- return res.status(401).json({- schemas: ["urn:ietf:params:scim:api:messages:2.0:Error"],- detail: authCheck.error,- status: 401,- });+ const authCheck = await shadowAuth({+ req,+ action: "organizationMembers:read",+ allowedAccessLevels: ["organization"],+ });+ if (!authCheck.success) {+ return writeScimError(res, authCheck.error);}// END CHECK AUTH- // Check if using an organization API key- if (- authCheck.scope.accessLevel !== "organization" ||- !authCheck.scope.orgId- ) {- return res.status(403).json({- schemas: ["urn:ietf:params:scim:api:messages:2.0:Error"],- detail:- "Invalid API key. Organization-scoped API key required for this operation.",- status: 403,- });- }-// Return the service provider configurationreturn res.status(200).json({schemas: ["urn:ietf:params:scim:schemas:core:2.0:ServiceProviderConfig"],diff --git a/web/src/pages/api/public/scim/Users/[id].ts b/web/src/pages/api/public/scim/Users/[id].tsindex 885d23631b..b2992bd5a0 100644--- a/web/src/pages/api/public/scim/Users/[id].ts+++ b/web/src/pages/api/public/scim/Users/[id].ts@@ -1,12 +1,13 @@-import { ApiAuthService } from "@/src/features/public-api/server/apiAuth";import { cors, runMiddleware } from "@/src/features/public-api/server/cors";import { auditLog } from "@/src/features/audit-logs/auditLog";import { Prisma, prisma, type User, type Role } from "@langfuse/shared/src/db";-import { logger, redis } from "@langfuse/shared/src/server";+import { logger } from "@langfuse/shared/src/server";import { z } from "zod";import { type NextApiRequest, type NextApiResponse } from "next";import { getSfdcService } from "@/src/ee/features/sfdc-sync/server";import { hasEntitlementBasedOnPlan } from "@/src/features/entitlements/server/hasEntitlement";+import { shadowAuth } from "@/src/features/public-api/server/shadowAuth";+import { writeScimError } from "@/src/features/public-api/server/writeError";// Parse the first valid role from a SCIM `roles` array. Returns undefined when// the attribute is absent, empty, or unparsable, which the provisioning logic@@ -356,32 +357,19 @@ export default async function handler(}// CHECK AUTH- const authCheck = await new ApiAuthService(- prisma,- redis,- ).verifyAuthHeaderAndReturnScope(req.headers.authorization);- if (!authCheck.validKey) {- return res.status(401).json({- schemas: ["urn:ietf:params:scim:api:messages:2.0:Error"],- detail: authCheck.error,- status: 401,- });+ const authCheck = await shadowAuth({+ req,+ action:+ req.method === "GET"+ ? "organizationMembers:read"+ : "organizationMembers:CUD",+ allowedAccessLevels: ["organization"],+ });+ if (!authCheck.success) {+ return writeScimError(res, authCheck.error);}// END CHECK AUTH- // Check if using an organization API key- if (- authCheck.scope.accessLevel !== "organization" ||- !authCheck.scope.orgId- ) {- return res.status(403).json({- schemas: ["urn:ietf:params:scim:api:messages:2.0:Error"],- detail:- "Invalid API key. Organization-scoped API key required for this operation.",- status: 403,- });- }-// Gate SCIM provisioning behind the `admin-api` entitlement, matching the// sibling organization admin endpoints (memberships, projects, apiKeys).// Without this, any org-scoped key could mutate memberships and roles ondiff --git a/web/src/pages/api/public/scim/Users/index.ts b/web/src/pages/api/public/scim/Users/index.tsindex 32707fdde4..5df9d2f70b 100644--- a/web/src/pages/api/public/scim/Users/index.ts+++ b/web/src/pages/api/public/scim/Users/index.ts@@ -1,7 +1,6 @@-import { ApiAuthService } from "@/src/features/public-api/server/apiAuth";import { cors, runMiddleware } from "@/src/features/public-api/server/cors";import { prisma } from "@langfuse/shared/src/db";-import { logger, redis } from "@langfuse/shared/src/server";+import { logger } from "@langfuse/shared/src/server";import { type NextApiRequest, type NextApiResponse } from "next";import { z } from "zod";@@ -9,6 +8,8 @@ import { type Role } from "@langfuse/shared";import { auditLog } from "@/src/features/audit-logs/auditLog";import { getSfdcService } from "@/src/ee/features/sfdc-sync/server";import { hasEntitlementBasedOnPlan } from "@/src/features/entitlements/server/hasEntitlement";+import { shadowAuth } from "@/src/features/public-api/server/shadowAuth";+import { writeScimError } from "@/src/features/public-api/server/writeError";export default async function handler(req: NextApiRequest,@@ -28,32 +29,19 @@ export default async function handler(}// CHECK AUTH- const authCheck = await new ApiAuthService(- prisma,- redis,- ).verifyAuthHeaderAndReturnScope(req.headers.authorization);- if (!authCheck.validKey) {- return res.status(401).json({- schemas: ["urn:ietf:params:scim:api:messages:2.0:Error"],- detail: authCheck.error,- status: 401,- });+ const authCheck = await shadowAuth({+ req,+ action:+ req.method === "GET"+ ? "organizationMembers:read"+ : "organizationMembers:CUD",+ allowedAccessLevels: ["organization"],+ });+ if (!authCheck.success) {+ return writeScimError(res, authCheck.error);}// END CHECK AUTH- // Check if using an organization API key- if (- authCheck.scope.accessLevel !== "organization" ||- !authCheck.scope.orgId- ) {- return res.status(403).json({- schemas: ["urn:ietf:params:scim:api:messages:2.0:Error"],- detail:- "Invalid API key. Organization-scoped API key required for this operation.",- status: 403,- });- }-// Gate SCIM provisioning behind the `admin-api` entitlement, matching the// sibling organization admin endpoints (memberships, projects, apiKeys).// Without this, any org-scoped key could create users and assign roles on