Skip to content

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

feat(self-hosted): allow managing LLM connections with ADMIN_API_KEY (#10041)

Hassieb Pakzad7ad6a8a2450f
diff --git a/fern/apis/organizations/definition/organizations.yml b/fern/apis/organizations/definition/organizations.yml
index 7092e4bd90..5ca96bd5a2 100644
--- a/fern/apis/organizations/definition/organizations.yml
+++ b/fern/apis/organizations/definition/organizations.yml
@@ -14,7 +14,7 @@ service:
errors:
- commons.UnauthorizedError
- commons.MethodNotAllowedError
-
+
create:
docs: Create a new organization
method: POST
@@ -32,7 +32,7 @@ service:
- commons.Error
- commons.UnauthorizedError
- commons.MethodNotAllowedError
-
+
getById:
docs: Get organization by ID
method: GET
@@ -44,7 +44,7 @@ service:
- commons.Error
- commons.UnauthorizedError
- commons.MethodNotAllowedError
-
+
update:
docs: Update an organization
method: PUT
@@ -64,7 +64,7 @@ service:
- commons.Error
- commons.UnauthorizedError
- commons.MethodNotAllowedError
-
+
delete:
docs: Delete an organization
method: DELETE
@@ -137,6 +137,18 @@ types:
metadata:
type: map<string, unknown>
docs: Metadata for the organization
+ projects: list<OrganizationProject>
+
+ OrganizationProject:
+ docs: Project belonging to an organization
+ properties:
+ id: string
+ name: string
+ metadata:
+ type: optional<map<string, unknown>>
+ docs: Metadata for the project
+ createdAt: datetime
+ updatedAt: datetime
DeleteOrganizationResponse:
docs: Response for successful organization deletion
diff --git a/web/public/generated/organizations-api/openapi.yml b/web/public/generated/organizations-api/openapi.yml
index 39c9fde397..3689f11524 100644
--- a/web/public/generated/organizations-api/openapi.yml
+++ b/web/public/generated/organizations-api/openapi.yml
@@ -455,11 +455,41 @@ components:
type: object
additionalProperties: true
description: Metadata for the organization
+ projects:
+ type: array
+ items:
+ $ref: '#/components/schemas/OrganizationProject'
required:
- id
- name
- createdAt
- metadata
+ - projects
+ OrganizationProject:
+ title: OrganizationProject
+ type: object
+ description: Project belonging to an organization
+ properties:
+ id:
+ type: string
+ name:
+ type: string
+ metadata:
+ type: object
+ additionalProperties: true
+ nullable: true
+ description: Metadata for the project
+ createdAt:
+ type: string
+ format: date-time
+ updatedAt:
+ type: string
+ format: date-time
+ required:
+ - id
+ - name
+ - createdAt
+ - updatedAt
DeleteOrganizationResponse:
title: DeleteOrganizationResponse
type: object
diff --git a/web/src/__tests__/admin-api-key-auth.servertest.ts b/web/src/__tests__/admin-api-key-auth.servertest.ts
new file mode 100644
index 0000000000..05d3c02ca3
--- /dev/null
+++ b/web/src/__tests__/admin-api-key-auth.servertest.ts
@@ -0,0 +1,281 @@
+import { type NextApiRequest } from "next";
+import { verifyAuth } from "@/src/features/public-api/server/createAuthedProjectAPIRoute";
+import { prisma } from "@langfuse/shared/src/db";
+import { env } from "@/src/env.mjs";
+import {
+ createOrgProjectAndApiKey,
+ hashSecretKey,
+ getDisplaySecretKey,
+} from "@langfuse/shared/src/server";
+
+describe("Admin API Key Authentication", () => {
+ const ADMIN_API_KEY = "test-admin-key-123";
+
+ // Store original env value to restore after tests
+ const originalAdminApiKey = env.ADMIN_API_KEY;
+ const originalCloudRegion = env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION;
+
+ let projectId: string;
+ let orgId: string;
+ let auth: string;
+
+ beforeAll(() => {
+ // Set up env for admin API key tests
+ (env as any).ADMIN_API_KEY = ADMIN_API_KEY;
+ (env as any).NEXT_PUBLIC_LANGFUSE_CLOUD_REGION = undefined;
+ });
+
+ afterAll(() => {
+ // Restore original env values
+ (env as any).ADMIN_API_KEY = originalAdminApiKey;
+ (env as any).NEXT_PUBLIC_LANGFUSE_CLOUD_REGION = originalCloudRegion;
+ });
+
+ beforeEach(async () => {
+ // Create a new project and API key for each test
+ const result = await createOrgProjectAndApiKey();
+ projectId = result.projectId;
+ orgId = result.orgId;
+ auth = result.auth;
+ });
+
+ describe("Basic Auth (isAdminApiKeyAuthAllowed = false)", () => {
+ it("should successfully authenticate with valid basic auth", async () => {
+ // auth from beforeEach contains a valid API key
+ const mockReq = {
+ headers: {
+ authorization: auth,
+ },
+ } as NextApiRequest;
+
+ const result = await verifyAuth(mockReq, false);
+
+ expect(result.validKey).toBe(true);
+ expect(result.scope.projectId).toBe(projectId);
+ expect(result.scope.accessLevel).toBe("project");
+ });
+
+ it("should throw error when basic auth fails", async () => {
+ const mockReq = {
+ headers: {
+ authorization: "Basic invalid",
+ },
+ } as NextApiRequest;
+
+ await expect(verifyAuth(mockReq, false)).rejects.toEqual({
+ status: 401,
+ message: expect.stringContaining(""),
+ });
+ });
+
+ it("should throw error when projectId is missing", async () => {
+ // Create an org-level key (generate unique values to avoid conflicts)
+ const timestamp = Date.now();
+ const uniqueId = `org-api-key-${timestamp}`;
+ const publicKey = `pk-org-key-${timestamp}`;
+ const secretKey = `sk-org-key-${timestamp}`;
+
+ await prisma.apiKey.create({
+ data: {
+ id: uniqueId,
+ publicKey,
+ hashedSecretKey: await hashSecretKey(secretKey),
+ displaySecretKey: getDisplaySecretKey(secretKey),
+ note: "org key",
+ organization: {
+ connect: { id: orgId },
+ },
+ },
+ });
+
+ const mockReq = {
+ headers: {
+ authorization:
+ "Basic " +
+ Buffer.from(`${publicKey}:${secretKey}`).toString("base64"),
+ },
+ } as NextApiRequest;
+
+ await expect(verifyAuth(mockReq, false)).rejects.toMatchObject({
+ status: 401,
+ message: expect.stringContaining(""),
+ });
+ });
+ });
+
+ describe("Admin API Key Auth (isAdminApiKeyAuthAllowed = true)", () => {
+ it("should successfully authenticate with valid admin API key", async () => {
+ const mockReq = {
+ headers: {
+ authorization: `Bearer ${ADMIN_API_KEY}`,
+ "x-langfuse-admin-api-key": ADMIN_API_KEY,
+ "x-langfuse-project-id": projectId,
+ },
+ } as NextApiRequest;
+
+ const result = await verifyAuth(mockReq, true);
+
+ expect(result.validKey).toBe(true);
+ expect(result.scope.projectId).toBe(projectId);
+ expect(result.scope.orgId).toBe(orgId);
+ expect(result.scope.apiKeyId).toBe("ADMIN_API_KEY");
+ expect(result.scope.publicKey).toBe("ADMIN_API_KEY");
+ expect(result.scope.accessLevel).toBe("project");
+ });
+
+ it("should fall back to basic auth when no Bearer header", async () => {
+ const mockReq = {
+ headers: {
+ authorization: auth,
+ },
+ } as NextApiRequest;
+
+ const result = await verifyAuth(mockReq, true);
+
+ expect(result.validKey).toBe(true);
+ expect(result.scope.projectId).toBe(projectId);
+ expect(result.scope.apiKeyId).not.toBe("ADMIN_API_KEY");
+ });
+
+ it("should fall back to basic auth when no x-langfuse-admin-api-key header", async () => {
+ const mockReq = {
+ headers: {
+ authorization: auth,
+ },
+ } as NextApiRequest;
+
+ const result = await verifyAuth(mockReq, true);
+
+ expect(result.validKey).toBe(true);
+ expect(result.scope.projectId).toBe(projectId);
+ });
+
+ it("should fail on Langfuse Cloud", async () => {
+ (env as any).NEXT_PUBLIC_LANGFUSE_CLOUD_REGION = "prod-us";
+
+ const mockReq = {
+ headers: {
+ authorization: `Bearer ${ADMIN_API_KEY}`,
+ "x-langfuse-admin-api-key": ADMIN_API_KEY,
+ "x-langfuse-project-id": projectId,
+ },
+ } as NextApiRequest;
+
+ await expect(verifyAuth(mockReq, true)).rejects.toEqual({
+ status: 403,
+ message: "Admin API key auth is not available on Langfuse Cloud",
+ });
+
+ (env as any).NEXT_PUBLIC_LANGFUSE_CLOUD_REGION = undefined;
+ });
+
+ it("should fail when ADMIN_API_KEY is not configured", async () => {
+ (env as any).ADMIN_API_KEY = undefined;
+
+ const mockReq = {
+ headers: {
+ authorization: "Bearer some-key",
+ "x-langfuse-admin-api-key": "some-key",
+ "x-langfuse-project-id": projectId,
+ },
+ } as NextApiRequest;
+
+ await expect(verifyAuth(mockReq, true)).rejects.toEqual({
+ status: 500,
+ message: "Admin API key is not configured on this instance",
+ });
+
+ (env as any).ADMIN_API_KEY = ADMIN_API_KEY;
+ });
+
+ it("should fail with invalid Bearer token", async () => {
+ const mockReq = {
+ headers: {
+ authorization: "Bearer wrong-key",
+ "x-langfuse-admin-api-key": ADMIN_API_KEY,
+ "x-langfuse-project-id": projectId,
+ },
+ } as NextApiRequest;
+
+ await expect(verifyAuth(mockReq, true)).rejects.toEqual({
+ status: 401,
+ message: "Invalid admin API key",
+ });
+ });
+
+ it("should fail with invalid x-langfuse-admin-api-key header", async () => {
+ const mockReq = {
+ headers: {
+ authorization: `Bearer ${ADMIN_API_KEY}`,
+ "x-langfuse-admin-api-key": "wrong-key",
+ "x-langfuse-project-id": projectId,
+ },
+ } as NextApiRequest;
+
+ await expect(verifyAuth(mockReq, true)).rejects.toEqual({
+ status: 401,
+ message: "Invalid admin API key",
+ });
+ });
+
+ it("should fail when both admin key headers don't match ADMIN_API_KEY", async () => {
+ const mockReq = {
+ headers: {
+ authorization: "Bearer different-key-1",
+ "x-langfuse-admin-api-key": "different-key-2",
+ "x-langfuse-project-id": projectId,
+ },
+ } as NextApiRequest;
+
+ await expect(verifyAuth(mockReq, true)).rejects.toEqual({
+ status: 401,
+ message: "Invalid admin API key",
+ });
+ });
+
+ it("should fail without x-langfuse-project-id header", async () => {
+ const mockReq = {
+ headers: {
+ authorization: `Bearer ${ADMIN_API_KEY}`,
+ "x-langfuse-admin-api-key": ADMIN_API_KEY,
+ },
+ } as NextApiRequest;
+
+ await expect(verifyAuth(mockReq, true)).rejects.toEqual({
+ status: 400,
+ message:
+ "x-langfuse-project-id header is required for admin API key authentication",
+ });
+ });
+
+ it("should fail with non-existent project", async () => {
+ const mockReq = {
+ headers: {
+ authorization: `Bearer ${ADMIN_API_KEY}`,
+ "x-langfuse-admin-api-key": ADMIN_API_KEY,
+ "x-langfuse-project-id": "non-existent-project",
+ },
+ } as NextApiRequest;
+
+ await expect(verifyAuth(mockReq, true)).rejects.toEqual({
+ status: 404,
+ message: "Project not found",
+ });
+ });
+
+ it("should fall back to basic auth successfully after admin auth not attempted", async () => {
+ const mockReq = {
+ headers: {
+ authorization: auth,
+ "x-langfuse-project-id": projectId,
+ },
+ } as NextApiRequest;
+
+ const result = await verifyAuth(mockReq, true);
+
+ expect(result.validKey).toBe(true);
+ expect(result.scope.projectId).toBe(projectId);
+ expect(result.scope.apiKeyId).not.toBe("ADMIN_API_KEY");
+ });
+ });
+});
diff --git a/web/src/__tests__/async/organizations-api.servertest.ts b/web/src/__tests__/async/organizations-api.servertest.ts
index 31dcd7d51e..2bff297e85 100644
--- a/web/src/__tests__/async/organizations-api.servertest.ts
+++ b/web/src/__tests__/async/organizations-api.servertest.ts
@@ -12,12 +12,22 @@ import {
createBasicAuthHeader,
} from "@langfuse/shared/src/server";
+// Schema for organization project response
+const OrganizationProjectSchema = z.object({
+ id: z.string(),
+ name: z.string(),
+ metadata: z.record(z.string(), z.unknown()).nullable(),
+ createdAt: z.string().datetime(),
+ updatedAt: z.string().datetime(),
+});
+
// Schema for organization response
const OrganizationResponseSchema = z.object({
id: z.string(),
name: z.string(),
createdAt: z.string().datetime(),
metadata: z.object({}),
+ projects: z.array(OrganizationProjectSchema),
});
// Schema for multiple organizations response
@@ -82,6 +92,9 @@ describe("Admin Organizations API", () => {
});
expect(response.body.id).toBeDefined();
expect(response.body.createdAt).toBeDefined();
+ expect(response.body.projects).toBeDefined();
+ expect(Array.isArray(response.body.projects)).toBe(true);
+ expect(response.body.projects).toHaveLength(0);
// Verify the organization was actually created in the database
const org = await prisma.organization.findUnique({
@@ -219,6 +232,11 @@ describe("Admin Organizations API", () => {
response.body.organizations.find((org) => org.id === testOrgId)
?.metadata,
).toEqual({ tier: "testing", users: 5 });
+ // Verify projects field is present for all organizations
+ response.body.organizations.forEach((org) => {
+ expect(org.projects).toBeDefined();
+ expect(Array.isArray(org.projects)).toBe(true);
+ });
});
it("should return 401 when no authorization header is provided", async () => {
@@ -264,6 +282,54 @@ describe("Admin Organizations API", () => {
expect(response.status).toBe(200);
expect(response.body.id).toBe(testOrgId);
expect(response.body.metadata).toEqual({ tier: "testing", users: 5 });
+ expect(response.body.projects).toBeDefined();
+ expect(Array.isArray(response.body.projects)).toBe(true);
+ });
+
+ it("should return projects when organization has projects", async () => {
+ // Create a test organization with a project
+ const uniqueOrgName = `Test Org ${randomUUID().substring(0, 8)}`;
+ const org = await prisma.organization.create({
+ data: { name: uniqueOrgName, metadata: { tier: "testing" } },
+ });
+
+ // Create a project for this organization
+ const projectName = `Test Project ${randomUUID().substring(0, 8)}`;
+ const project = await prisma.project.create({
+ data: {
+ name: projectName,
+ orgId: org.id,
+ metadata: { environment: "test" },
+ },
+ });
+
+ // Get the organization via API
+ const response = await makeZodVerifiedAPICall(
+ OrganizationResponseSchema,
+ "GET",
+ `/api/admin/organizations/${org.id}`,
+ undefined,
+ `Bearer ${ADMIN_API_KEY}`,
+ 200,
+ );
+
+ expect(response.status).toBe(200);
+ expect(response.body.id).toBe(org.id);
+ expect(response.body.projects).toBeDefined();
+ expect(Array.isArray(response.body.projects)).toBe(true);
+ expect(response.body.projects.length).toBe(1);
+ expect(response.body.projects[0].id).toBe(project.id);
+ expect(response.body.projects[0].name).toBe(projectName);
+ expect(response.body.projects[0].metadata).toEqual({
+ environment: "test",
+ });
+ expect(response.body.projects[0].createdAt).toBeDefined();
+ expect(response.body.projects[0].updatedAt).toBeDefined();
+
+ // Clean up
+ await prisma.organization.delete({
+ where: { id: org.id },
+ });
});
it("should return 404 when getting a non-existent organization", async () => {
@@ -745,15 +811,6 @@ describe("Admin Organizations API", () => {
});
});
-// Schema for organization project response
-const OrganizationProjectSchema = z.object({
- id: z.string(),
- name: z.string(),
- metadata: z.record(z.string(), z.unknown()).nullable(),
- createdAt: z.string().datetime(),
- updatedAt: z.string().datetime(),
-});
-
// Schema for organization projects list response
const OrganizationProjectsListSchema = z.object({
projects: z.array(OrganizationProjectSchema),
diff --git a/web/src/__tests__/test-utils.ts b/web/src/__tests__/test-utils.ts
index 2fbed7341d..8be051f1df 100644
--- a/web/src/__tests__/test-utils.ts
+++ b/web/src/__tests__/test-utils.ts
@@ -203,6 +203,7 @@ export async function makeAPICall<T = IngestionAPIResponse>(
url: string,
body?: unknown,
auth?: string,
+ customHeaders?: Record<string, string>,
): Promise<{ body: T; status: number }> {
const finalUrl = `http://localhost:3000${url.startsWith("/") ? url : `/${url}`}`;
const authorization =
@@ -213,6 +214,7 @@ export async function makeAPICall<T = IngestionAPIResponse>(
Accept: "application/json",
"Content-Type": "application/json;charset=UTF-8",
Authorization: authorization,
+ ...customHeaders,
},
...(method !== "GET" &&
body !== undefined && { body: JSON.stringify(body) }),
diff --git a/web/src/ee/features/admin-api/server/adminApiAuth.ts b/web/src/ee/features/admin-api/server/adminApiAuth.ts
index 7b52e26e21..5350511926 100644
--- a/web/src/ee/features/admin-api/server/adminApiAuth.ts
+++ b/web/src/ee/features/admin-api/server/adminApiAuth.ts
@@ -8,15 +8,26 @@ export interface AdminAuthResult {
error?: string;
}
+export interface AdminAuthOptions {
+ isAllowedOnLangfuseCloud?: boolean;
+}
+
export class AdminApiAuthService {
static verifyAdminAuthFromAuthString = (
authString: string,
- enforceLangfuseCloudOnly = true,
+ options: AdminAuthOptions = {},
): AdminAuthResult => {
- if (enforceLangfuseCloudOnly && !env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION) {
+ const { isAllowedOnLangfuseCloud = false } = options;
+
+ // Block access on Langfuse Cloud unless explicitly allowed
+ if (
+ !isAllowedOnLangfuseCloud &&
+ env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION &&
+ env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION !== "DEV" // exclude dev and CI environments
+ ) {
return {
isAuthorized: false,
- error: "Only accessible on Langfuse Cloud",
+ error: "Not accessible on Langfuse Cloud",
};
}
@@ -44,14 +55,13 @@ export class AdminApiAuthService {
/**
* Verifies if the request is authorized to access admin APIs
- * @param req The Next.js API request
- * @param enforceLangfuseCloudOnly Whether to check if the NEXT_PUBLIC_LANGFUSE_CLOUD_REGION is set (default: true)
+ * @param headers The incoming HTTP headers
+ * @param options Admin auth options
* @returns An object with isAuthorized flag and optional error message
*/
-
private static verifyAdminAuthFromHeader(
headers: IncomingHttpHeaders,
- enforceLangfuseCloudOnly = true,
+ options: AdminAuthOptions = {},
): AdminAuthResult {
// Check bearer token
const { authorization } = headers;
@@ -63,7 +73,7 @@ export class AdminApiAuthService {
}
return AdminApiAuthService.verifyAdminAuthFromAuthString(
authorization,
- enforceLangfuseCloudOnly,
+ options,
);
}
@@ -71,17 +81,17 @@ export class AdminApiAuthService {
* Middleware function to handle admin authentication in Next.js API routes
* @param req The Next.js API request
* @param res The Next.js API response
- * @param enforceLangfuseCloudOnly Whether to check if the NEXT_PUBLIC_LANGFUSE_CLOUD_REGION is set (default: true)
+ * @param options Admin auth options. By default, blocks access on Langfuse Cloud (isAllowedOnLangfuseCloud: false)
* @returns true if authorized, false otherwise (and sets appropriate response)
*/
public static handleAdminAuth(
req: NextApiRequest,
res: NextApiResponse,
- enforceLangfuseCloudOnly = true,
+ options: AdminAuthOptions = {},
): boolean {
const authResult = AdminApiAuthService.verifyAdminAuthFromHeader(
req.headers,
- enforceLangfuseCloudOnly,
+ options,
);
if (!authResult.isAuthorized) {
diff --git a/web/src/ee/features/admin-api/server/organizations/index.ts b/web/src/ee/features/admin-api/server/organizations/index.ts
index df85f05e60..65e3ab8ebe 100644
--- a/web/src/ee/features/admin-api/server/organizations/index.ts
+++ b/web/src/ee/features/admin-api/server/organizations/index.ts
@@ -14,12 +14,25 @@ export async function handleGetOrganizations(
name: true,
createdAt: true,
metadata: true,
+ projects: {
+ select: {
+ id: true,
+ name: true,
+ metadata: true,
+ createdAt: true,
+ updatedAt: true,
+ },
+ where: {
+ deletedAt: null,
+ },
+ },
},
});
return res.status(200).json({
organizations: organizations.map((org) => ({
...org,
metadata: org.metadata ?? {},
+ projects: org.projects,
})),
});
}
@@ -58,6 +71,24 @@ export async function handleCreateOrganization(
name,
metadata,
},
+ select: {
+ id: true,
+ name: true,
+ createdAt: true,
+ metadata: true,
+ projects: {
+ select: {
+ id: true,
+ name: true,
+ metadata: true,
+ createdAt: true,
+ updatedAt: true,
+ },
+ where: {
+ deletedAt: null,
+ },
+ },
+ },
});
// Log the organization creation
@@ -78,5 +109,6 @@ export async function handleCreateOrganization(
name: organization.name,
createdAt: organization.createdAt,
metadata: organization.metadata ?? {},
+ projects: organization.projects,
});
}
diff --git a/web/src/ee/features/admin-api/server/organizations/organizationById.ts b/web/src/ee/features/admin-api/server/organizations/organizationById.ts
index 09d5e45189..238bf6bbb3 100644
--- a/web/src/ee/features/admin-api/server/organizations/organizationById.ts
+++ b/web/src/ee/features/admin-api/server/organizations/organizationById.ts
@@ -32,6 +32,18 @@ export async function handleGetOrganizationById(
name: true,
createdAt: true,
metadata: true,
+ projects: {
+ select: {
+ id: true,
+ name: true,
+ metadata: true,
+ createdAt: true,
+ updatedAt: true,
+ },
+ where: {
+ deletedAt: null,
+ },
+ },
},
});
@@ -42,6 +54,7 @@ export async function handleGetOrganizationById(
return res.status(200).json({
...organization,
metadata: organization.metadata ?? {},
+ projects: organization.projects,
});
}
@@ -89,6 +102,24 @@ export async function handleUpdateOrganization(
const updatedOrganization = await prisma.organization.update({
where: { id: organizationId },
data: { name, metadata },
+ select: {
+ id: true,
+ name: true,
+ createdAt: true,
+ metadata: true,
+ projects: {
+ select: {
+ id: true,
+ name: true,
+ metadata: true,
+ createdAt: true,
+ updatedAt: true,
+ },
+ where: {
+ deletedAt: null,
+ },
+ },
+ },
});
// Log the update
@@ -110,6 +141,7 @@ export async function handleUpdateOrganization(
name: updatedOrganization.name,
createdAt: updatedOrganization.createdAt,
metadata: updatedOrganization.metadata ?? {},
+ projects: updatedOrganization.projects,
});
}
diff --git a/web/src/features/public-api/server/createAuthedProjectAPIRoute.ts b/web/src/features/public-api/server/createAuthedProjectAPIRoute.ts
index 8058c199aa..6f81533bce 100644
--- a/web/src/features/public-api/server/createAuthedProjectAPIRoute.ts
+++ b/web/src/features/public-api/server/createAuthedProjectAPIRoute.ts
@@ -1,3 +1,4 @@
+import crypto from "node:crypto";
import { type NextApiRequest, type NextApiResponse } from "next";
import { type ZodType, type z } from "zod/v4";
import { ApiAuthService } from "@/src/features/public-api/server/apiAuth";
@@ -25,6 +26,20 @@ type RouteConfig<
responseSchema: TResponse;
successStatusCode?: number;
rateLimitResource?: z.infer<typeof RateLimitResource>; // defaults to public-api
+ /**
+ * Allow authentication via ADMIN_API_KEY for self-hosted instances only.
+ * When enabled, the endpoint will accept admin API key authentication in addition to regular API keys.
+ *
+ * Admin API key authentication requires:
+ * - Authorization: Bearer <ADMIN_API_KEY>
+ * - x-langfuse-admin-api-key: <ADMIN_API_KEY> (must match exactly for redundancy)
+ * - x-langfuse-project-id: <project-id> (target project)
+ *
+ * This authentication method is ONLY available when NEXT_PUBLIC_LANGFUSE_CLOUD_REGION is not set (self-hosted).
+ *
+ * @default false
+ */
+ isAdminApiKeyAuthAllowed?: boolean;
fn: (params: {
query: z.infer<TQuery>;
body: z.infer<TBody>;
@@ -36,6 +51,186 @@ type RouteConfig<
}) => Promise<z.infer<TResponse>>;
};
+/**
+ * Verifies regular API key authentication using ApiAuthService.
+ *
+ * This function handles standard project API key authentication with Basic auth.
+ * Returns an auth scope object with project-level access.
+ *
+ * @param authHeader - The Authorization header from the request
+ * @returns An auth scope object with project-level access
+ * @throws Error with appropriate message if authentication fails
+ */
+async function verifyBasicAuth(authHeader: string | undefined): Promise<
+ AuthHeaderValidVerificationResult & {
+ scope: { projectId: string; accessLevel: "project" };
+ }
+> {
+ const regularAuth = await new ApiAuthService(
+ prisma,
+ redis,
+ ).verifyAuthHeaderAndReturnScope(authHeader);
+
+ if (!regularAuth.validKey) {
+ throw { status: 401, message: regularAuth.error };
+ }
+
+ if (regularAuth.scope.accessLevel !== "project") {
+ throw {
+ status: 401,
+ message: "Access denied - need to use basic auth with secret key",
+ };
+ }
+
+ if (!regularAuth.scope.projectId) {
+ throw {
+ status: 401,
+ message:
+ "Project ID not found for API token. Are you using an organization key?",
+ };
+ }
+
+ return regularAuth as AuthHeaderValidVerificationResult & {
+ scope: { projectId: string; accessLevel: "project" };
+ };
+}
+
+/**
+ * Verifies admin API key authentication for self-hosted instances.
+ *
+ * This function checks if the request contains valid admin API key credentials:
+ * 1. Authorization header must be Bearer token format with ADMIN_API_KEY value
+ * 2. x-langfuse-admin-api-key header must match ADMIN_API_KEY env var exactly (for redundancy)
+ * 3. x-langfuse-project-id header must be present and specify a valid project ID
+ * 4. NEXT_PUBLIC_LANGFUSE_CLOUD_REGION must NOT be set (self-hosted instances only)
+ *
+ * The ADMIN_API_KEY must be set as an environment variable on the server.
+ * This authentication method is intended for administrative operations on self-hosted instances.
+ *
+ * @param req - The Next.js API request
+ * @returns An auth scope object if successful, null if admin auth is not being attempted
+ * @throws Error with appropriate status code if admin auth fails
+ */
+async function verifyAdminApiKeyAuth(req: NextApiRequest): Promise<
+ | (AuthHeaderValidVerificationResult & {
+ scope: { projectId: string; accessLevel: "project" };
+ })
+ | null
+> {
+ const authHeader = req.headers.authorization;
+ const adminApiKeyHeader = req.headers["x-langfuse-admin-api-key"];
+ const projectIdHeader = req.headers["x-langfuse-project-id"];
+
+ // If not attempting admin auth, return null to proceed with regular auth
+ if (!authHeader?.startsWith("Bearer ") || !adminApiKeyHeader) return null;
+
+ // Verify this is a self-hosted instance (not Langfuse Cloud)
+ if (env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION) {
+ throw {
+ status: 403,
+ message: "Admin API key auth is not available on Langfuse Cloud",
+ };
+ }
+
+ // Verify ADMIN_API_KEY is configured
+ const adminApiKey = env.ADMIN_API_KEY;
+ if (!adminApiKey) {
+ throw {
+ status: 500,
+ message: "Admin API key is not configured on this instance",
+ };
+ }
+
+ // Extract Bearer token
+ const bearerToken = authHeader.replace("Bearer ", "");
+
+ // Verify both the Bearer token and header match the ADMIN_API_KEY
+ try {
+ // timingSafeEqual throws on different input lengths, handle accordingly
+ const bearerTokenEqual = crypto.timingSafeEqual(
+ Buffer.from(bearerToken),
+ Buffer.from(adminApiKey),
+ );
+ const headerEqual = crypto.timingSafeEqual(
+ Buffer.from(String(adminApiKeyHeader)),
+ Buffer.from(adminApiKey),
+ );
+ const isEqual = bearerTokenEqual && headerEqual;
+
+ if (!isEqual) throw Error();
+ } catch {
+ throw { status: 401, message: "Invalid admin API key" };
+ }
+
+ // Verify project ID header is present
+ if (!projectIdHeader || typeof projectIdHeader !== "string") {
+ throw {
+ status: 400,
+ message:
+ "x-langfuse-project-id header is required for admin API key authentication",
+ };
+ }
+
+ // Verify project exists
+ const project = await prisma.project.findUnique({
+ where: { id: projectIdHeader, deletedAt: null },
+ select: { id: true, orgId: true },
+ });
+
+ if (!project) {
+ throw { status: 404, message: "Project not found" };
+ }
+
+ // Return auth scope matching the regular auth structure
+ return {
+ validKey: true,
+ scope: {
+ projectId: project.id,
+ accessLevel: "project" as const,
+ orgId: project.orgId,
+ plan: "oss",
+ rateLimitOverrides: [],
+ apiKeyId: "ADMIN_API_KEY", // Special identifier for audit logging
+ publicKey: "ADMIN_API_KEY",
+ isIngestionSuspended: false,
+ },
+ };
+}
+
+/**
+ * Verifies authentication for API routes with support for both basic and admin API key auth.
+ *
+ * This is the main authentication entry point that delegates to either admin or basic auth
+ * based on the configuration and request headers.
+ *
+ * @param req - The Next.js API request
+ * @param isAdminApiKeyAuthAllowed - Whether to allow admin API key authentication
+ * @returns An auth scope object with project-level access
+ * @throws Error with appropriate status code if authentication fails
+ */
+export async function verifyAuth(
+ req: NextApiRequest,
+ isAdminApiKeyAuthAllowed: boolean,
+): Promise<
+ AuthHeaderValidVerificationResult & {
+ scope: { projectId: string; accessLevel: "project" };
+ }
+> {
+ if (isAdminApiKeyAuthAllowed) {
+ // Try admin API key authentication first
+ const adminAuth = await verifyAdminApiKeyAuth(req);
+ if (adminAuth) {
+ // Admin auth succeeded
+ return adminAuth;
+ }
+ // Admin auth not attempted, fall back to basic auth
+ return await verifyBasicAuth(req.headers.authorization);
+ }
+
+ // Only basic auth is allowed
+ return await verifyBasicAuth(req.headers.authorization);
+}
+
export const createAuthedProjectAPIRoute = <
TQuery extends ZodType<any>,
TBody extends ZodType<any>,
@@ -44,25 +239,22 @@ export const createAuthedProjectAPIRoute = <
routeConfig: RouteConfig<TQuery, TBody, TResponse>,
): ((req: NextApiRequest, res: NextApiResponse) => Promise<void>) => {
return async (req: NextApiRequest, res: NextApiResponse) => {
- const auth = await new ApiAuthService(
- prisma,
- redis,
- ).verifyAuthHeaderAndReturnScope(req.headers.authorization);
- if (!auth.validKey) {
- res.status(401).json({ message: auth.error });
- return;
- }
- if (auth.scope.accessLevel !== "project") {
- res.status(401).json({
- message: "Access denied - need to use basic auth with secret key",
- });
- return;
- }
- if (!auth.scope.projectId) {
- res.status(401).json({
- message:
- "Project ID not found for API token. Are you using an organization key?",
- });
+ let auth: AuthHeaderValidVerificationResult & {
+ scope: { projectId: string; accessLevel: "project" };
+ };
+
+ // Verify authentication (basic or admin API key)
+ try {
+ auth = await verifyAuth(
+ req,
+ routeConfig.isAdminApiKeyAuthAllowed || false,
+ );
+ } catch (error: any) {
+ const statusCode = error.status || 401;
+ const message = error.message || "Authentication failed";
+
+ res.status(statusCode).json({ message });
+
return;
}
diff --git a/web/src/pages/api/admin/api-keys/index.ts b/web/src/pages/api/admin/api-keys/index.ts
index 8da5c65ccc..c5aa6afc3c 100644
--- a/web/src/pages/api/admin/api-keys/index.ts
+++ b/web/src/pages/api/admin/api-keys/index.ts
@@ -6,7 +6,7 @@ import { ApiAuthService } from "@/src/features/public-api/server/apiAuth";
import { AdminApiAuthService } from "@/src/ee/features/admin-api/server/adminApiAuth";
/*
-This API route is used by Langfuse Cloud to delete API keys for a project. It will return 403 for self-hosters.
+This API route is used by Langfuse Cloud to delete API keys for a project.
We will work on admin APIs in the future. See the discussion here: https://github.com/orgs/langfuse/discussions/3243
*/
@@ -36,7 +36,11 @@ export default async function handler(
return;
}
- if (!AdminApiAuthService.handleAdminAuth(req, res)) {
+ if (
+ !AdminApiAuthService.handleAdminAuth(req, res, {
+ isAllowedOnLangfuseCloud: true,
+ })
+ ) {
return;
}
diff --git a/web/src/pages/api/admin/bullmq/index.ts b/web/src/pages/api/admin/bullmq/index.ts
index d9db374033..13f149ef62 100644
--- a/web/src/pages/api/admin/bullmq/index.ts
+++ b/web/src/pages/api/admin/bullmq/index.ts
@@ -53,7 +53,11 @@ export default async function handler(
return;
}
- if (!AdminApiAuthService.handleAdminAuth(req, res, false)) {
+ if (
+ !AdminApiAuthService.handleAdminAuth(req, res, {
+ isAllowedOnLangfuseCloud: true,
+ })
+ ) {
return;
}
diff --git a/web/src/pages/api/admin/evals.ts b/web/src/pages/api/admin/evals.ts
index 2fe71275fb..16619f8ac7 100644
--- a/web/src/pages/api/admin/evals.ts
+++ b/web/src/pages/api/admin/evals.ts
@@ -29,7 +29,11 @@ export default async function handler(
return;
}
- if (!AdminApiAuthService.handleAdminAuth(req, res, false)) {
+ if (
+ !AdminApiAuthService.handleAdminAuth(req, res, {
+ isAllowedOnLangfuseCloud: true,
+ })
+ ) {
return;
}
diff --git a/web/src/pages/api/admin/organizations/[organizationId]/apiKeys/[apiKeyId].ts b/web/src/pages/api/admin/organizations/[organizationId]/apiKeys/[apiKeyId].ts
index b1cbe3adf7..395f8df263 100644
--- a/web/src/pages/api/admin/organizations/[organizationId]/apiKeys/[apiKeyId].ts
+++ b/web/src/pages/api/admin/organizations/[organizationId]/apiKeys/[apiKeyId].ts
@@ -19,8 +19,8 @@ export default async function handler(
return;
}
- // Verify admin API authentication, but allow non-langfuse cloud use-cases
- if (!AdminApiAuthService.handleAdminAuth(req, res, false)) {
+ // Verify admin API authentication, only allow on self-hosted (not on Langfuse Cloud)
+ if (!AdminApiAuthService.handleAdminAuth(req, res)) {
return;
}
diff --git a/web/src/pages/api/admin/organizations/[organizationId]/apiKeys/index.ts b/web/src/pages/api/admin/organizations/[organizationId]/apiKeys/index.ts
index ffae5a14f4..40afffe13e 100644
--- a/web/src/pages/api/admin/organizations/[organizationId]/apiKeys/index.ts
+++ b/web/src/pages/api/admin/organizations/[organizationId]/apiKeys/index.ts
@@ -20,8 +20,8 @@ export default async function handler(
return;
}
- // Verify admin API authentication, but allow non-langfuse cloud use-cases
- if (!AdminApiAuthService.handleAdminAuth(req, res, false)) {
+ // Verify admin API authentication, only allow on self-hosted (not on Langfuse Cloud)
+ if (!AdminApiAuthService.handleAdminAuth(req, res)) {
return;
}
diff --git a/web/src/pages/api/admin/organizations/[organizationId]/index.ts b/web/src/pages/api/admin/organizations/[organizationId]/index.ts
index f4f7d6d3d6..894bc8a1a4 100644
--- a/web/src/pages/api/admin/organizations/[organizationId]/index.ts
+++ b/web/src/pages/api/admin/organizations/[organizationId]/index.ts
@@ -14,8 +14,8 @@ export default async function handler(
res: NextApiResponse,
) {
try {
- // Verify admin API authentication, but allow non-langfuse cloud use-cases
- if (!AdminApiAuthService.handleAdminAuth(req, res, false)) {
+ // Verify admin API authentication, only allow on self-hosted (not on Langfuse Cloud)
+ if (!AdminApiAuthService.handleAdminAuth(req, res)) {
return;
}
diff --git a/web/src/pages/api/admin/organizations/index.ts b/web/src/pages/api/admin/organizations/index.ts
index 17e5660b5a..ecfe640d03 100644
--- a/web/src/pages/api/admin/organizations/index.ts
+++ b/web/src/pages/api/admin/organizations/index.ts
@@ -18,8 +18,8 @@ export default async function handler(
return;
}
- // Verify admin API authentication, but allow non-langfuse cloud use-cases
- if (!AdminApiAuthService.handleAdminAuth(req, res, false)) {
+ // Verify admin API authentication, only allow on self-hosted (not on Langfuse Cloud)
+ if (!AdminApiAuthService.handleAdminAuth(req, res)) {
return;
}
diff --git a/web/src/pages/api/public/llm-connections/index.ts b/web/src/pages/api/public/llm-connections/index.ts
index bbf8b95e5b..9b34cf602a 100644
--- a/web/src/pages/api/public/llm-connections/index.ts
+++ b/web/src/pages/api/public/llm-connections/index.ts
@@ -17,6 +17,7 @@ export default withMiddlewares({
name: "Get LLM Connections",
querySchema: GetLlmConnectionsV1Query,
responseSchema: GetLlmConnectionsV1Response,
+ isAdminApiKeyAuthAllowed: true,
fn: async ({ query, auth }) => {
const { limit, page } = query;
@@ -72,6 +73,7 @@ export default withMiddlewares({
name: "Upsert LLM Connection",
bodySchema: PutLlmConnectionV1Body,
responseSchema: PutLlmConnectionV1Response,
+ isAdminApiKeyAuthAllowed: true,
fn: async ({ body, auth, res }) => {
const projectId = auth.scope.projectId;
diff --git a/web/src/server/api/trpc.ts b/web/src/server/api/trpc.ts
index 6cc1be9bbc..13c283121c 100644
--- a/web/src/server/api/trpc.ts
+++ b/web/src/server/api/trpc.ts
@@ -587,7 +587,6 @@ const enforceAdminAuth = t.middleware(async (opts) => {
const adminAuthResult = AdminApiAuthService.verifyAdminAuthFromAuthString(
result.data.adminApiKey,
- false,
);
if (!adminAuthResult.isAuthorized) {