Skip to content

🪢 Open source agent evals & observability: Trace, evaluate, and improve LLM applications with one open platform.

fix(api): add authentication span metadata to enforceAuth (#18807)

Mark Salpeter3bd481776995
diff --git a/web/src/__tests__/server/unit/create-authed-project-api-route-auth-errors.servertest.ts b/web/src/__tests__/server/unit/create-authed-project-api-route-auth-errors.servertest.ts
index 3850f0503f..276d53c12f 100644
--- a/web/src/__tests__/server/unit/create-authed-project-api-route-auth-errors.servertest.ts
+++ b/web/src/__tests__/server/unit/create-authed-project-api-route-auth-errors.servertest.ts
@@ -77,6 +77,10 @@ vi.mock("@langfuse/shared/src/db", async () => {
vi.mock("@langfuse/shared/src/server", () => ({
redis: null,
+ instrumentAsync: vi.fn(async (_ctx, callback) =>
+ callback({ setAttribute: vi.fn() }),
+ ),
+ addUserToSpan: vi.fn(),
logger: {
debug: mockLoggerDebug,
info: mockLoggerInfo,
diff --git a/web/src/__tests__/server/unit/public-api/enforceAuth.servertest.ts b/web/src/__tests__/server/unit/public-api/enforceAuth.servertest.ts
index 9bc236e6e2..e6ee0c1276 100644
--- a/web/src/__tests__/server/unit/public-api/enforceAuth.servertest.ts
+++ b/web/src/__tests__/server/unit/public-api/enforceAuth.servertest.ts
@@ -1,14 +1,49 @@
import { type NextApiRequest } from "next";
-import { describe, expect, it } from "vitest";
+import { beforeEach, describe, expect, it, vi } from "vitest";
-import { ForbiddenError } from "@langfuse/shared";
+import { ForbiddenError, LangfuseNotFoundError } from "@langfuse/shared";
+import { prisma } from "@langfuse/shared/src/db";
+import { addUserToSpan, instrumentAsync } from "@langfuse/shared/src/server";
-import { __test } from "@/src/features/public-api/server/enforceAuth";
+import { authenticator } from "@/src/features/apiKey/server";
+import { authorize } from "@/src/features/rbac/authorize";
import {
+ __dangerouslySkipAuthz,
+ __test,
+ enforceAuth,
+} from "@/src/features/public-api/server/enforceAuth";
+import {
+ forbiddenError,
+ unauthorizedError,
type AuthorizationContext,
type BoundResource,
} from "@/src/features/auth/policy/types";
+const { authSpan } = vi.hoisted(() => ({
+ authSpan: { setAttribute: vi.fn() },
+}));
+
+vi.mock("@/src/features/apiKey/server", () => ({
+ authenticator: { authenticate: vi.fn() },
+}));
+vi.mock("@/src/features/rbac/authorize", () => ({ authorize: vi.fn() }));
+vi.mock("@langfuse/shared/src/db", () => ({
+ prisma: { project: { findUnique: vi.fn() }, $disconnect: vi.fn() },
+}));
+vi.mock("@langfuse/shared/src/server", async (importOriginal) => {
+ const actual = await importOriginal<{
+ addUserToSpan: typeof addUserToSpan;
+ }>();
+ return {
+ addUserToSpan: vi.fn(actual.addUserToSpan),
+ instrumentAsync: vi.fn(async (_ctx, callback) => callback(authSpan)),
+ redis: null,
+ ClickHouseClientManager: {
+ getInstance: () => ({ closeAllConnections: vi.fn() }),
+ },
+ };
+});
+
const { getOrgId, getProjectId } = __test;
const ORG = "org_1";
@@ -26,7 +61,16 @@ const apiKey = (
publicKey: "pk-lf-1",
scope: boundResource.projectId ? "PROJECT" : "ORGANIZATION",
presentation: "privateKey",
- organizations: [],
+ organizations: [
+ {
+ orgId: ORG,
+ projectIds: [PRJ],
+ organizationCreatedAt: "2026-01-01T00:00:00.000Z",
+ plan: "oss",
+ rateLimitOverrides: [],
+ isIngestionSuspended: false,
+ },
+ ],
boundResource,
},
policies: [],
@@ -162,3 +206,196 @@ describe.each(["x-langfuse-project-id", "langfuse-project-id"])(
});
},
);
+
+describe("enforceAuth span metadata", () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ vi.mocked(authenticator.authenticate).mockResolvedValue({
+ success: true,
+ context: projectKey(),
+ });
+ vi.mocked(authorize).mockReturnValue({ success: true });
+ });
+
+ it("retains the authenticated key and resolved targets when authorization denies access", async () => {
+ const denial = forbiddenError();
+ vi.mocked(authorize).mockReturnValue(denial);
+ const result = await enforceAuth({
+ req: req(
+ { projectId: "ignored-url-project" },
+ {
+ "x-langfuse-project-id": "ignored-header-project",
+ authorization: "Bearer untrusted-submitted-credential",
+ },
+ ),
+ action: "traces:read",
+ });
+ expect(result).toBe(denial);
+ expect(instrumentAsync).toHaveBeenCalledWith(
+ { name: "api-auth-enforce" },
+ expect.any(Function),
+ );
+ expect(addUserToSpan).toHaveBeenNthCalledWith(
+ 1,
+ { apiKeyId: "key_2", publicKey: "pk-lf-1" },
+ authSpan,
+ );
+ expect(authSpan.setAttribute.mock.calls).toEqual([
+ ["langfuse.authz.action", "traces:read"],
+ ["langfuse.api_key.id", "key_2"],
+ ["langfuse.api_key.public_key", "pk-lf-1"],
+ ["langfuse.project.id", PRJ],
+ ["langfuse.org.id", ORG],
+ ]);
+ });
+
+ it("records only the action when authentication fails", async () => {
+ const failure = unauthorizedError();
+ vi.mocked(authenticator.authenticate).mockResolvedValue(failure);
+ expect(await enforceAuth({ req: req(), action: "traces:read" })).toBe(
+ failure,
+ );
+ expect(addUserToSpan).not.toHaveBeenCalled();
+ expect(authSpan.setAttribute.mock.calls).toEqual([
+ ["langfuse.authz.action", "traces:read"],
+ ]);
+ });
+
+ it.each([
+ ["URL", { projectId: PRJ }, { "x-langfuse-project-id": "ignored" }],
+ ["header", {}, { "x-langfuse-project-id": PRJ }],
+ ])(
+ "records an organization key's %s project target",
+ async (_source, query, headers) => {
+ vi.mocked(authenticator.authenticate).mockResolvedValue({
+ success: true,
+ context: orgKey(),
+ });
+ const result = await enforceAuth({
+ req: req(query, headers),
+ action: "traces:read",
+ });
+ expect(result.success).toBe(true);
+ expect(authSpan.setAttribute.mock.calls).toEqual([
+ ["langfuse.authz.action", "traces:read"],
+ ["langfuse.api_key.id", "key_1"],
+ ["langfuse.api_key.public_key", "pk-lf-1"],
+ ["langfuse.project.id", PRJ],
+ ["langfuse.org.id", ORG],
+ ]);
+ },
+ );
+
+ it("retains a foreign project target without inventing a resolved organization", async () => {
+ vi.mocked(authenticator.authenticate).mockResolvedValue({
+ success: true,
+ context: orgKey(),
+ });
+ expect(
+ await enforceAuth({
+ req: req({ projectId: "foreign" }),
+ action: "traces:read",
+ }),
+ ).toMatchObject({
+ success: false,
+ error: expect.any(LangfuseNotFoundError),
+ });
+ expect(addUserToSpan).toHaveBeenNthCalledWith(
+ 1,
+ { apiKeyId: "key_1", publicKey: "pk-lf-1" },
+ authSpan,
+ );
+ expect(authSpan.setAttribute.mock.calls).toEqual([
+ ["langfuse.authz.action", "traces:read"],
+ ["langfuse.api_key.id", "key_1"],
+ ["langfuse.api_key.public_key", "pk-lf-1"],
+ ["langfuse.project.id", "foreign"],
+ ]);
+ });
+
+ it("omits unresolved targets when an organization key has no project", async () => {
+ vi.mocked(authenticator.authenticate).mockResolvedValue({
+ success: true,
+ context: orgKey(),
+ });
+ expect(
+ await enforceAuth({ req: req(), action: "traces:read" }),
+ ).toMatchObject({ success: false });
+ expect(authSpan.setAttribute.mock.calls).toEqual([
+ ["langfuse.authz.action", "traces:read"],
+ ["langfuse.api_key.id", "key_1"],
+ ["langfuse.api_key.public_key", "pk-lf-1"],
+ ]);
+ });
+
+ it.each([false, true])(
+ "records organization resolution with header conflict %s",
+ async (conflict) => {
+ vi.mocked(authenticator.authenticate).mockResolvedValue({
+ success: true,
+ context: orgKey(),
+ });
+ vi.mocked(authorize).mockReturnValue(forbiddenError());
+ expect(
+ await enforceAuth({
+ req: req(
+ {},
+ { "x-langfuse-organization-id": conflict ? "foreign" : ORG },
+ ),
+ action: "projects:read",
+ }),
+ ).toMatchObject({ success: false });
+ expect(authSpan.setAttribute.mock.calls).toEqual([
+ ["langfuse.authz.action", "projects:read"],
+ ["langfuse.api_key.id", "key_1"],
+ ["langfuse.api_key.public_key", "pk-lf-1"],
+ ...(conflict ? [] : [["langfuse.org.id", ORG]]),
+ ]);
+ },
+ );
+
+ it("preserves the skip-authorization action", async () => {
+ expect(
+ await enforceAuth({ req: req(), action: __dangerouslySkipAuthz }),
+ ).toMatchObject({ success: true });
+ expect(authorize).not.toHaveBeenCalled();
+ expect(authSpan.setAttribute.mock.calls).toEqual([
+ ["langfuse.authz.action", __dangerouslySkipAuthz],
+ ["langfuse.api_key.id", "key_2"],
+ ["langfuse.api_key.public_key", "pk-lf-1"],
+ ["langfuse.project.id", PRJ],
+ ["langfuse.org.id", ORG],
+ ]);
+ });
+
+ it.each([false, true])(
+ "records admin targets without API key metadata when project missing is %s",
+ async (missing) => {
+ vi.mocked(authenticator.authenticate).mockResolvedValue({
+ success: true,
+ context: adminKey(),
+ });
+ vi.mocked(prisma.project.findUnique).mockResolvedValue(
+ missing
+ ? null
+ : ({ orgId: ORG } as Awaited<
+ ReturnType<typeof prisma.project.findUnique>
+ >),
+ );
+ const result = await enforceAuth({
+ req: req({}, { "x-langfuse-project-id": PRJ }),
+ action: "traces:read",
+ isAdminApiKeyAuthAllowed: true,
+ });
+ expect(result.success).toBe(!missing);
+ const expectedMetadata: unknown[] = [[{ projectId: PRJ }, authSpan]];
+ if (!missing) expectedMetadata.push([{ orgId: ORG }, authSpan]);
+ expect(vi.mocked(addUserToSpan).mock.calls).toEqual(expectedMetadata);
+ expect(authSpan.setAttribute.mock.calls).toEqual([
+ ["langfuse.authz.action", "traces:read"],
+ ["langfuse.project.id", PRJ],
+ ...(missing ? [] : [["langfuse.org.id", ORG]]),
+ ]);
+ },
+ );
+});
diff --git a/web/src/features/public-api/server/enforceAuth.ts b/web/src/features/public-api/server/enforceAuth.ts
index af389a362a..37bdb4b553 100644
--- a/web/src/features/public-api/server/enforceAuth.ts
+++ b/web/src/features/public-api/server/enforceAuth.ts
@@ -1,4 +1,5 @@
import { type NextApiRequest } from "next";
+import { type Span } from "@opentelemetry/api";
import {
type ForbiddenError,
@@ -7,7 +8,11 @@ import {
type ServiceUnavailableError,
type UnauthorizedError,
} from "@langfuse/shared";
-import { type ApiAccessScope } from "@langfuse/shared/src/server";
+import {
+ addUserToSpan,
+ instrumentAsync,
+ type ApiAccessScope,
+} from "@langfuse/shared/src/server";
import { prisma } from "@langfuse/shared/src/db";
import {
isOrgAction,
@@ -48,24 +53,25 @@ export async function enforceAuth({
allowInAppAgentKey,
isAdminApiKeyAuthAllowed,
}: EnforceAuthParams): Promise<EnforceAuthResult> {
- const auth = await authenticator.authenticate({
- headers: req.headers,
- allowInAppAgentKey: allowInAppAgentKey,
- isAdminApiKeyAuthAllowed: isAdminApiKeyAuthAllowed,
+ return instrumentAsync({ name: "api-auth-enforce" }, async (span) => {
+ span.setAttribute("langfuse.authz.action", action);
+ 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, span);
+ case "apiKey":
+ return enforceApiKeyAuthz(context, req, action, span);
+ default:
+ return internalServerError(`Unexpected principal on the public api`);
+ }
});
- if (!auth.success) return auth;
-
- const { context } = auth;
- switch (context.principal.kind) {
- case "admin":
- return enforceAdminAuthz(context, req, action);
- case "apiKey":
- return action !== __dangerouslySkipAuthz && 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. */
@@ -73,12 +79,15 @@ async function enforceAdminAuthz(
context: AuthorizationContext,
req: NextApiRequest,
action: ApiAction,
+ span: Span,
): Promise<EnforceAuthResult> {
const projectId = getHeaderProjectId(req);
if (!projectId) return forbiddenError(`Missing '${projectIdHeader}' header`);
+ addUserToSpan({ projectId }, span);
const org = await lookupProjectOrgId(projectId);
if (!org.success) return org;
+ addUserToSpan({ orgId: org.orgId }, span);
const decision = authorizeAction(
context,
@@ -91,14 +100,34 @@ async function enforceAdminAuthz(
return access(context, org.orgId, projectId);
}
+/** enforceApiKeyAuthz records key metadata and dispatches authorization by action scope. */
+function enforceApiKeyAuthz(
+ context: AuthorizationContext,
+ req: NextApiRequest,
+ action: ApiAction,
+ span: Span,
+): EnforceAuthResult {
+ if (context.principal.kind !== "apiKey") {
+ return internalServerError(`Unexpected principal on the public api`);
+ }
+ const { apiKeyId, publicKey } = context.principal;
+ addUserToSpan({ apiKeyId, publicKey }, span);
+ if (action !== __dangerouslySkipAuthz && isOrgAction(action)) {
+ return enforceOrgAuthz(context, req, action, span);
+ }
+ return enforceProjectAuthz(context, req, action, span);
+}
+
/** enforceOrgAuthz resolves, authorizes, and scopes an organization-scoped api-key request. */
function enforceOrgAuthz(
context: AuthorizationContext,
req: NextApiRequest,
action: ApiAction,
+ span: Span,
): EnforceAuthResult {
const org = getOrgId(context, req);
if (!org.success) return org;
+ addUserToSpan({ orgId: org.orgId }, span);
const decision = authorizeAction(
context,
@@ -116,9 +145,11 @@ function enforceProjectAuthz(
context: AuthorizationContext,
req: NextApiRequest,
action: ApiAction,
+ span: Span,
): EnforceAuthResult {
const project = getProjectId(context, req);
if (!project.success) return project;
+ addUserToSpan({ projectId: project.projectId }, span);
if (!ownsProject(context.principal, project.projectId)) {
return notFoundError("Project not found or you don't have access to it");
@@ -126,6 +157,7 @@ function enforceProjectAuthz(
const orgId = getBoundOrgId(context);
if (!orgId) return internalServerError(`Missing bound org on api-key`);
+ addUserToSpan({ orgId }, span);
const decision = authorizeAction(
context,