🪢 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
chore: refactor authentication for admin apis (#6417)
Steffen Schmitzbd651e81b772
diff --git a/.github/workflows/pipeline.yml b/.github/workflows/pipeline.ymlindex 6d3cd142c7..1d8f758e8b 100644--- a/.github/workflows/pipeline.yml+++ b/.github/workflows/pipeline.yml@@ -213,6 +213,7 @@ jobs:echo "LANGFUSE_INGESTION_QUEUE_DELAY_MS=1" >> .envecho "LANGFUSE_INGESTION_CLICKHOUSE_WRITE_INTERVAL_MS=1" >> .envecho "LANGFUSE_TRACE_DELETE_CONCURRENCY=100" >> .env+ echo "ADMIN_API_KEY=admin-api-key" >> .env- name: Run dev containersrun: |docker compose -f docker-compose.dev${{ matrix.blob-provider }}.yml up -ddiff --git a/packages/shared/prisma/generated/types.ts b/packages/shared/prisma/generated/types.tsindex 54ed1ef5be..533f3fc931 100644--- a/packages/shared/prisma/generated/types.ts+++ b/packages/shared/prisma/generated/types.ts@@ -4,6 +4,11 @@ export type Generated<T> = T extends ColumnType<infer S, infer I, infer U>: ColumnType<T, T | undefined, T>;export type Timestamp = ColumnType<Date, Date | string, Date | string>;+export const ApiKeyScope = {+ ORGANIZATION: "ORGANIZATION",+ PROJECT: "PROJECT"+} as const;+export type ApiKeyScope = (typeof ApiKeyScope)[keyof typeof ApiKeyScope];export const Role = {OWNER: "OWNER",ADMIN: "ADMIN",@@ -158,7 +163,9 @@ export type ApiKey = {display_secret_key: string;last_used_at: Timestamp | null;expires_at: Timestamp | null;- project_id: string;+ project_id: string | null;+ organization_id: string | null;+ scope: Generated<ApiKeyScope>;};export type AuditLog = {id: string;diff --git a/packages/shared/prisma/migrations/20250410145712_add_organization_scoped_api_keys/migration.sql b/packages/shared/prisma/migrations/20250410145712_add_organization_scoped_api_keys/migration.sqlnew file mode 100644index 0000000000..e6b64a548a--- /dev/null+++ b/packages/shared/prisma/migrations/20250410145712_add_organization_scoped_api_keys/migration.sql@@ -0,0 +1,13 @@+-- CreateEnum+CREATE TYPE "ApiKeyScope" AS ENUM ('ORGANIZATION', 'PROJECT');++-- AlterTable+ALTER TABLE "api_keys" ADD COLUMN "organization_id" TEXT,+ADD COLUMN "scope" "ApiKeyScope" NOT NULL DEFAULT 'PROJECT',+ALTER COLUMN "project_id" DROP NOT NULL;++-- CreateIndex+CREATE INDEX "api_keys_organization_id_idx" ON "api_keys"("organization_id");++-- AddForeignKey+ALTER TABLE "api_keys" ADD CONSTRAINT "api_keys_organization_id_fkey" FOREIGN KEY ("organization_id") REFERENCES "organizations"("id") ON DELETE CASCADE ON UPDATE CASCADE;diff --git a/packages/shared/prisma/schema.prisma b/packages/shared/prisma/schema.prismaindex d3a144e1f1..52e0a1ab43 100644--- a/packages/shared/prisma/schema.prisma+++ b/packages/shared/prisma/schema.prisma@@ -108,6 +108,7 @@ model Organization {organizationMemberships OrganizationMembership[]projects Project[]MembershipInvitation MembershipInvitation[]+ ApiKey ApiKey[]@@map("organizations")}@@ -156,19 +157,28 @@ model Project {@@map("projects")}+enum ApiKeyScope {+ ORGANIZATION+ PROJECT+}+model ApiKey {- id String @id @unique @default(cuid())- createdAt DateTime @default(now()) @map("created_at")+ id String @id @unique @default(cuid())+ createdAt DateTime @default(now()) @map("created_at")note String?- publicKey String @unique @map("public_key")- hashedSecretKey String @unique @map("hashed_secret_key")- fastHashedSecretKey String? @unique @map("fast_hashed_secret_key")- displaySecretKey String @map("display_secret_key")- lastUsedAt DateTime? @map("last_used_at")- expiresAt DateTime? @map("expires_at")- projectId String @map("project_id")- project Project @relation(fields: [projectId], references: [id], onDelete: Cascade)-+ publicKey String @unique @map("public_key")+ hashedSecretKey String @unique @map("hashed_secret_key")+ fastHashedSecretKey String? @unique @map("fast_hashed_secret_key")+ displaySecretKey String @map("display_secret_key")+ lastUsedAt DateTime? @map("last_used_at")+ expiresAt DateTime? @map("expires_at")+ projectId String? @map("project_id")+ project Project? @relation(fields: [projectId], references: [id], onDelete: Cascade)+ orgId String? @map("organization_id")+ organization Organization? @relation(fields: [orgId], references: [id], onDelete: Cascade)+ scope ApiKeyScope @default(PROJECT) @map("scope")++ @@index(orgId)@@index(projectId)@@index(publicKey)@@index(hashedSecretKey)diff --git a/packages/shared/prisma/seed.ts b/packages/shared/prisma/seed.tsindex 1b98871b87..4158b86263 100644--- a/packages/shared/prisma/seed.ts+++ b/packages/shared/prisma/seed.ts@@ -181,6 +181,7 @@ async function main() {publicKey: seedApiKey.public,hashedSecretKey: await hashSecretKey(seedApiKey.secret),displaySecretKey: getDisplaySecretKey(seedApiKey.secret),+ scope: "PROJECT",project: {connect: {id: project1.id,@@ -242,6 +243,7 @@ async function main() {publicKey: secondKey.public,hashedSecretKey: await hashSecretKey(secondKey.secret),displaySecretKey: getDisplaySecretKey(secondKey.secret),+ scope: "PROJECT",project: {connect: {id: project2.id,diff --git a/packages/shared/scripts/load-seed.ts b/packages/shared/scripts/load-seed.tsindex d720cb39c1..10ac1e8a7d 100644--- a/packages/shared/scripts/load-seed.ts+++ b/packages/shared/scripts/load-seed.ts@@ -58,6 +58,7 @@ const prepareProjectsAndApiKeys = async (publicKey: `pk-${Math.random().toString(36).substr(2, 9)}`,hashedSecretKey: sk,displaySecretKey: getDisplaySecretKey(sk),+ scope: "PROJECT",project: {connect: {id: projectId,diff --git a/packages/shared/src/server/auth/apiKeys.ts b/packages/shared/src/server/auth/apiKeys.tsindex 8522464fa4..20809efcb8 100644--- a/packages/shared/src/server/auth/apiKeys.ts+++ b/packages/shared/src/server/auth/apiKeys.ts@@ -1,4 +1,4 @@-import { PrismaClient } from "@prisma/client";+import { PrismaClient, ApiKeyScope } from "@prisma/client";import { compare, hash } from "bcryptjs";import { randomUUID } from "crypto";import * as crypto from "crypto";@@ -39,6 +39,7 @@ export function createShaHash(privateKey: string, salt: string): string {export async function createAndAddApiKeysToDb(p: {prisma: PrismaClient;projectId: string;+ scope: ApiKeyScope;note?: string;predefinedKeys?: {secretKey: string;@@ -67,6 +68,7 @@ export async function createAndAddApiKeysToDb(p: {displaySecretKey: displaySk,fastHashedSecretKey: hashFromProvidedKey,note: p.note,+ scope: p.scope,},});diff --git a/packages/shared/src/server/auth/types.ts b/packages/shared/src/server/auth/types.tsindex a740e4a419..ed79e0c3f1 100644--- a/packages/shared/src/server/auth/types.ts+++ b/packages/shared/src/server/auth/types.ts@@ -1,8 +1,9 @@import z from "zod";import { Plan, plans } from "../../features/entitlements/plans";import { CloudConfigRateLimit } from "../../interfaces/rate-limits";+import { ApiKeyScope } from "../../";-export const OrgEnrichedApiKey = z.object({+const ApiKeyBaseSchema = z.object({id: z.string(),note: z.string().nullable(),publicKey: z.string(),@@ -10,7 +11,6 @@ export const OrgEnrichedApiKey = z.object({createdAt: z.string().datetime().nullable(),lastUsedAt: z.string().datetime().nullable(),expiresAt: z.string().datetime().nullable(),- projectId: z.string(),fastHashedSecretKey: z.string(),hashedSecretKey: z.string(),orgId: z.string(),@@ -18,6 +18,17 @@ export const OrgEnrichedApiKey = z.object({rateLimitOverrides: CloudConfigRateLimit.nullish(),});+export const OrgEnrichedApiKey = z.discriminatedUnion("scope", [+ ApiKeyBaseSchema.extend({+ scope: z.literal(ApiKeyScope.ORGANIZATION),+ projectId: z.null(),+ }),+ ApiKeyBaseSchema.extend({+ scope: z.literal(ApiKeyScope.PROJECT),+ projectId: z.string(),+ }),+]);+export const API_KEY_NON_EXISTENT = "api-key-non-existent";export const CachedApiKey = z.union([@@ -38,8 +49,8 @@ export type AuthHeaderValidVerificationResult = {};export type ApiAccessScope = {- projectId: string;- accessLevel: "all" | "scores";+ projectId: string | null;+ accessLevel: "organization" | "project" | "scores";orgId: string;plan: Plan;rateLimitOverrides: z.infer<typeof CloudConfigRateLimit>;diff --git a/packages/shared/src/server/ingestion/processEventBatch.ts b/packages/shared/src/server/ingestion/processEventBatch.tsindex b09643c32c..3abcb71b5f 100644--- a/packages/shared/src/server/ingestion/processEventBatch.ts+++ b/packages/shared/src/server/ingestion/processEventBatch.ts@@ -98,13 +98,20 @@ export const processEventBatch = async (recordDistribution("langfuse.ingestion.event_distribution", input.length);currentSpan?.setAttribute("langfuse.ingestion.batch_size", input.length);- currentSpan?.setAttribute("langfuse.project.id", authCheck.scope.projectId);+ currentSpan?.setAttribute(+ "langfuse.project.id",+ authCheck.scope.projectId ?? "",+ );currentSpan?.setAttribute("langfuse.org.id", authCheck.scope.orgId);currentSpan?.setAttribute("langfuse.org.plan", authCheck.scope.plan);/*************** VALIDATION ***************/+ if (!authCheck.scope.projectId) {+ throw new UnauthorizedError("Missing project ID");+ }+const validationErrors: { id: string; error: unknown }[] = [];const authenticationErrors: { id: string; error: unknown }[] = [];@@ -245,7 +252,13 @@ export const processEventBatch = async (eventBodyId: sortedBatchByEventBodyId[id].eventBodyId,fileKey: sortedBatchByEventBodyId[id].key,},- authCheck,+ authCheck: authCheck as {+ validKey: true;+ scope: {+ projectId: string;+ accessLevel: "project" | "scores";+ };+ },},},{ delay: getDelay(delay) },@@ -272,11 +285,11 @@ const isAuthorized = (if (event.type === eventTypes.SCORE_CREATE) {return (authScope.scope.accessLevel === "scores" ||- authScope.scope.accessLevel === "all"+ authScope.scope.accessLevel === "project");}- return authScope.scope.accessLevel === "all";+ return authScope.scope.accessLevel === "project";};/**diff --git a/packages/shared/src/server/queues.ts b/packages/shared/src/server/queues.tsindex 6454632903..1c3d691dbe 100644--- a/packages/shared/src/server/queues.ts+++ b/packages/shared/src/server/queues.ts@@ -17,7 +17,6 @@ export const IngestionEvent = z.object({validKey: z.literal(true),scope: z.object({projectId: z.string(),- accessLevel: z.enum(["all", "scores"]),}),}),});diff --git a/packages/shared/src/server/test-utils/org-factory.ts b/packages/shared/src/server/test-utils/org-factory.tsindex 7355871cc6..a9c0306f81 100644--- a/packages/shared/src/server/test-utils/org-factory.ts+++ b/packages/shared/src/server/test-utils/org-factory.ts@@ -47,6 +47,7 @@ export const createOrgProjectAndApiKey = async (publicKey: publicKey,hashedSecretKey: await hashSecretKey(secretKey),displaySecretKey: getDisplaySecretKey(secretKey),+ scope: "PROJECT",},});diff --git a/web/src/__tests__/api-auth.servertest.ts b/web/src/__tests__/api-auth.servertest.tsindex 5e8c6ea758..a4e47282f6 100644--- a/web/src/__tests__/api-auth.servertest.ts+++ b/web/src/__tests__/api-auth.servertest.ts@@ -327,6 +327,124 @@ describe("Authenticate API calls", () => {});});+ it("should handle non-scoped key format gracefully and fallback to prisma", async () => {+ await createAPIKey();++ // update the organization with a cloud config+ await prisma.organization.update({+ where: { id: "seed-org-id" },+ data: {+ cloudConfig: {+ rateLimitOverrides: [+ {+ resource: "public-api",+ points: 1000,+ durationInSec: 60,+ },+ {+ resource: "ingestion",+ },+ ],+ },+ },+ });++ // first auth will generate the fast hashed api key+ await new ApiAuthService(prisma, redis).verifyAuthHeaderAndReturnScope(+ "Basic cGstbGYtMTIzNDU2Nzg5MDpzay1sZi0xMjM0NTY3ODkw",+ );++ const apiKey = await prisma.apiKey.findUnique({+ where: { publicKey: "pk-lf-1234567890" },+ });++ expect(apiKey).not.toBeNull();+ expect(apiKey?.fastHashedSecretKey).not.toBeNull();++ // Manually add a non-scoped key to Redis (missing the scope property)+ const nonScopedKey = {+ id: "seed-api-key",+ note: "seeded key",+ publicKey: "pk-lf-1234567890",+ displaySecretKey: "sk-lf-...7890",+ createdAt: new Date().toISOString(),+ lastUsedAt: null,+ expiresAt: null,+ fastHashedSecretKey: apiKey?.fastHashedSecretKey,+ hashedSecretKey: apiKey?.hashedSecretKey,+ orgId: "seed-org-id",+ plan: "cloud:team",+ projectId: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",+ // scope property is intentionally missing+ };++ // Add the non-scoped key to Redis+ await redis.set(+ `api-key:${apiKey?.fastHashedSecretKey}`,+ JSON.stringify(nonScopedKey),+ "EX",+ 3600, // 1 hour TTL+ );++ // Verify the key is in Redis+ const cachedKey = await redis.get(+ `api-key:${apiKey?.fastHashedSecretKey}`,+ );+ expect(cachedKey).not.toBeNull();++ // Parse should fail because the scope is missing+ expect(() => {+ OrgEnrichedApiKey.parse(JSON.parse(cachedKey!));+ }).toThrow("invalid_union_discriminator");++ // Auth should still succeed by falling back to Postgres+ const verification = await new ApiAuthService(+ prisma,+ redis,+ ).verifyAuthHeaderAndReturnScope(+ "Basic cGstbGYtMTIzNDU2Nzg5MDpzay1sZi0xMjM0NTY3ODkw",+ );++ expect(verification.validKey).toBe(true);++ // The invalid key should be removed from Redis+ const cachedKeyAfterAuth = await redis.get(+ `api-key:${apiKey?.fastHashedSecretKey}`,+ );++ // A new valid key should be added to Redis after fallback to Postgres+ expect(cachedKeyAfterAuth).not.toBeNull();++ // The new key should be properly formatted with a scope+ const parsed = OrgEnrichedApiKey.parse(JSON.parse(cachedKeyAfterAuth!));++ expect(parsed).toEqual({+ ...apiKey,+ orgId: "seed-org-id",+ plan: "cloud:hobby",+ scope: "PROJECT", // Now the scope is present+ projectId: "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a",+ rateLimitOverrides: [+ {+ resource: "public-api",+ points: 1000,+ durationInSec: 60,+ },+ {+ resource: "ingestion",+ },+ ],+ createdAt: apiKey?.createdAt.toISOString(),+ });++ await prisma.organization.update({+ where: { id: "seed-org-id" },+ data: {+ cloudConfig: Prisma.JsonNull,+ },+ });+ });+it("searching for non-existing key stores flag in redis and fails auth", async () => {// key does not exist in database@@ -432,6 +550,7 @@ describe("Authenticate API calls", () => {projectId: expect.any(String),orgId: "seed-org-id",plan: "cloud:hobby",+ scope: "PROJECT",});});@@ -523,11 +642,13 @@ describe("Authenticate API calls", () => {orgId: "seed-org-id",plan: "cloud:hobby",createdAt: apiKey?.createdAt.toISOString(),+ scope: "PROJECT",});await new ApiAuthService(prisma, redis).deleteApiKey(apiKey?.id!,apiKey?.projectId!,+ "PROJECT",);const deletedApiKey = await prisma.apiKey.findUnique({diff --git a/web/src/__tests__/async/organizations-api.servertest.ts b/web/src/__tests__/async/organizations-api.servertest.tsnew file mode 100644index 0000000000..5c11768347--- /dev/null+++ b/web/src/__tests__/async/organizations-api.servertest.ts@@ -0,0 +1,113 @@+/** @jest-environment node */++import {+ makeZodVerifiedAPICall,+ makeAPICall,+} from "@/src/__tests__/test-utils";+import { prisma } from "@langfuse/shared/src/db";+import { z } from "zod";+import { randomUUID } from "crypto";++// Schema for organization response+const OrganizationResponseSchema = z.object({+ id: z.string(),+ name: z.string(),+ createdAt: z.string().datetime(),+});++describe("Admin Organizations API", () => {+ const ADMIN_API_KEY = process.env.ADMIN_API_KEY;++ describe("POST /api/admin/organizations", () => {+ it("should create a new organization with valid admin authentication", async () => {+ const uniqueOrgName = `Test Org ${randomUUID().substring(0, 8)}`;++ const response = await makeZodVerifiedAPICall(+ OrganizationResponseSchema,+ "POST",+ "/api/admin/organizations",+ {+ name: uniqueOrgName,+ },+ `Bearer ${ADMIN_API_KEY}`,+ 201, // Expected status code is 201 Created+ );++ expect(response.status).toBe(201);+ expect(response.body).toMatchObject({+ name: uniqueOrgName,+ });+ expect(response.body.id).toBeDefined();+ expect(response.body.createdAt).toBeDefined();++ // Verify the organization was actually created in the database+ const org = await prisma.organization.findUnique({+ where: { id: response.body.id },+ });+ expect(org).not.toBeNull();+ expect(org?.name).toBe(uniqueOrgName);+ });++ it("should return 401 when no authorization header is provided", async () => {+ const uniqueOrgName = `Test Org ${randomUUID().substring(0, 8)}`;++ const result = await makeAPICall("POST", "/api/admin/organizations", {+ name: uniqueOrgName,+ });+ expect(result.status).toBe(401);+ expect(result.body.error).toContain("Unauthorized");+ });++ it("should return 401 when invalid admin API key is provided", async () => {+ const uniqueOrgName = `Test Org ${randomUUID().substring(0, 8)}`;++ const result = await makeAPICall(+ "POST",+ "/api/admin/organizations",+ {+ name: uniqueOrgName,+ },+ "Bearer invalid-admin-key",+ );+ expect(result.status).toBe(401);+ expect(result.body.error).toContain("Unauthorized");+ });++ it("should return 400 when organization name is too short", async () => {+ const result = await makeAPICall(+ "POST",+ "/api/admin/organizations",+ {+ name: "A", // Short name+ },+ `Bearer ${ADMIN_API_KEY}`,+ );+ expect(result.status).toBe(400);+ expect(result.body.error).toContain("Invalid request body");+ });++ it("should return 400 when organization name is too long", async () => {+ const result = await makeAPICall(+ "POST",+ "/api/admin/organizations",+ {+ name: "A".repeat(31), // More than 30 characters+ },+ `Bearer ${ADMIN_API_KEY}`,+ );+ expect(result.status).toBe(400);+ expect(result.body.error).toContain("Invalid request body");+ });++ it("should return 405 for non-POST methods", async () => {+ const result = await makeAPICall(+ "GET",+ "/api/admin/organizations",+ undefined,+ `Bearer ${ADMIN_API_KEY}`,+ );+ expect(result.status).toBe(405);+ expect(result.body.error).toContain("Method Not Allowed");+ });+ });+});diff --git a/web/src/__tests__/rate-limit.servertest.ts b/web/src/__tests__/rate-limit.servertest.tsindex 735a4e2ee4..6d247e6da8 100644--- a/web/src/__tests__/rate-limit.servertest.ts+++ b/web/src/__tests__/rate-limit.servertest.ts@@ -44,7 +44,7 @@ describe("RateLimitService", () => {orgId: orgId,plan: "cloud:hobby" as const,projectId: "test-project-id",- accessLevel: "all" as const,+ accessLevel: "project" as const,rateLimitOverrides: [],},consumedPoints: 1,@@ -66,7 +66,7 @@ describe("RateLimitService", () => {orgId: orgId,plan: "cloud:hobby" as const,projectId: "test-project-id",- accessLevel: "all" as const,+ accessLevel: "project" as const,rateLimitOverrides: [],};@@ -99,7 +99,7 @@ describe("RateLimitService", () => {orgId: orgId,plan: "cloud:hobby" as const,projectId: "test-project-id",- accessLevel: "all" as const,+ accessLevel: "project" as const,rateLimitOverrides: [],};@@ -125,7 +125,7 @@ describe("RateLimitService", () => {orgId: orgId,plan: "cloud:hobby" as const,projectId: "test-project-id",- accessLevel: "all" as const,+ accessLevel: "project" as const,rateLimitOverrides: [{ resource: "public-api" as const, points: 100, durationInSec: 2 },],@@ -175,7 +175,7 @@ describe("RateLimitService", () => {orgId: orgId,plan: "cloud:hobby" as const,projectId: "test-project-id",- accessLevel: "all" as const,+ accessLevel: "project" as const,rateLimitOverrides: [{ resource: "public-api" as const, points: 5, durationInSec: 60 },],@@ -206,7 +206,7 @@ describe("RateLimitService", () => {orgId: orgId,plan: "cloud:hobby" as const,projectId: "test-project-id",- accessLevel: "all" as const,+ accessLevel: "project" as const,rateLimitOverrides: [{ resource: "public-api" as const, points: 5, durationInSec: 10 },],@@ -232,7 +232,7 @@ describe("RateLimitService", () => {orgId: orgId,plan: "cloud:hobby" as const,projectId: "test-project-id",- accessLevel: "all" as const,+ accessLevel: "project" as const,rateLimitOverrides: [{ resource: "public-api" as const, points: 5, durationInSec: 10 },],@@ -251,7 +251,7 @@ describe("RateLimitService", () => {orgId: orgId,plan: "cloud:hobby" as const,projectId: "test-project-id",- accessLevel: "all" as const,+ accessLevel: "project" as const,rateLimitOverrides: [{ resource: "ingestion" as const, points: null, durationInSec: null },],@@ -270,7 +270,7 @@ describe("RateLimitService", () => {// orgId: orgId,// plan: "cloud:hobby" as const,// projectId: "test-project-id",- // accessLevel: "all" as const,+ // accessLevel: "project" as const,// rateLimitOverrides: [// { resource: "public-api" as const, points: 5, durationInSec: 10 },// ],@@ -289,7 +289,7 @@ describe("RateLimitService", () => {orgId: orgId,plan: "oss" as const,projectId: "test-project-id",- accessLevel: "all" as const,+ accessLevel: "project" as const,rateLimitOverrides: [],};diff --git a/web/src/features/admin-api/server/adminApiAuth.ts b/web/src/features/admin-api/server/adminApiAuth.tsnew file mode 100644index 0000000000..01a5a99e6e--- /dev/null+++ b/web/src/features/admin-api/server/adminApiAuth.ts@@ -0,0 +1,88 @@+import { env } from "@/src/env.mjs";+import { logger } from "@langfuse/shared/src/server";+import { type NextApiRequest, type NextApiResponse } from "next";++export interface AdminAuthResult {+ isAuthorized: boolean;+ error?: string;+}++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)+ * @returns An object with isAuthorized flag and optional error message+ */+ private static verifyAdminAuth(+ req: NextApiRequest,+ enforceLangfuseCloudOnly = true,+ ): AdminAuthResult {+ // Check if we're in Langfuse cloud environment (optional)+ if (enforceLangfuseCloudOnly && !env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION) {+ return {+ isAuthorized: false,+ error: "Only accessible on Langfuse Cloud",+ };+ }++ // Check if ADMIN_API_KEY is set+ if (!env.ADMIN_API_KEY) {+ logger.error("ADMIN_API_KEY is not set");+ return {+ isAuthorized: false,+ error: "ADMIN_API_KEY is not set",+ };+ }++ // Check bearer token+ const { authorization } = req.headers;+ if (!authorization) {+ return {+ isAuthorized: false,+ error: "Unauthorized: No authorization header provided",+ };+ }++ const [scheme, token] = authorization.split(" ");+ if (scheme !== "Bearer" || !token || token !== env.ADMIN_API_KEY) {+ return {+ isAuthorized: false,+ error: "Unauthorized: Invalid token",+ };+ }++ return {+ isAuthorized: true,+ };+ }++ /**+ * 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)+ * @returns true if authorized, false otherwise (and sets appropriate response)+ */+ public static handleAdminAuth(+ req: NextApiRequest,+ res: NextApiResponse,+ enforceLangfuseCloudOnly = true,+ ): boolean {+ const authResult = AdminApiAuthService.verifyAdminAuth(+ req,+ enforceLangfuseCloudOnly,+ );++ if (!authResult.isAuthorized) {+ if (authResult.error?.startsWith("Unauthorized")) {+ res.status(401).json({ error: authResult.error });+ } else {+ res.status(403).json({ error: authResult.error });+ }+ return false;+ }++ return true;+ }+}diff --git a/web/src/features/projects/server/projectsRouter.ts b/web/src/features/projects/server/projectsRouter.tsindex b195b7f0e9..476b567c53 100644--- a/web/src/features/projects/server/projectsRouter.ts+++ b/web/src/features/projects/server/projectsRouter.ts@@ -175,6 +175,7 @@ export const projectsRouter = createTRPCRouter({await ctx.prisma.apiKey.deleteMany({where: {projectId: input.projectId,+ scope: "PROJECT",},});diff --git a/web/src/features/prompts/server/handlers/promptVersionHandler.ts b/web/src/features/prompts/server/handlers/promptVersionHandler.tsindex a238c648e7..816d7547a4 100644--- a/web/src/features/prompts/server/handlers/promptVersionHandler.ts+++ b/web/src/features/prompts/server/handlers/promptVersionHandler.ts@@ -2,7 +2,7 @@ import { logger } from "@langfuse/shared/src/server";import { z } from "zod";import { withMiddlewares } from "@/src/features/public-api/server/withMiddlewares";-import { createAuthedAPIRoute } from "@/src/features/public-api/server/createAuthedAPIRoute";+import { createAuthedProjectAPIRoute } from "@/src/features/public-api/server/createAuthedProjectAPIRoute";import { updatePrompt } from "@/src/features/prompts/server/actions/updatePrompts";import { LangfuseNotFoundError } from "@langfuse/shared";import { auditLog } from "@/src/features/audit-logs/auditLog";@@ -16,7 +16,7 @@ const UpdatePromptBodySchema = z.object({});export const promptVersionHandler = withMiddlewares({- PATCH: createAuthedAPIRoute({+ PATCH: createAuthedProjectAPIRoute({name: "Update Prompt",bodySchema: UpdatePromptBodySchema,responseSchema: z.any(),diff --git a/web/src/features/prompts/server/utils/authorizePromptRequest.ts b/web/src/features/prompts/server/utils/authorizePromptRequest.tsindex 9cbea2ed6d..d169e500ca 100644--- a/web/src/features/prompts/server/utils/authorizePromptRequest.ts+++ b/web/src/features/prompts/server/utils/authorizePromptRequest.ts@@ -2,7 +2,10 @@ import { ApiAuthService } from "@/src/features/public-api/server/apiAuth";import { type NextApiRequest } from "next";import { UnauthorizedError, ForbiddenError } from "@langfuse/shared";import { prisma } from "@langfuse/shared/src/db";-import { redis } from "@langfuse/shared/src/server";+import {+ type AuthHeaderValidVerificationResult,+ redis,+} from "@langfuse/shared/src/server";export async function authorizePromptRequestOrThrow(req: NextApiRequest) {const authCheck = await new ApiAuthService(@@ -10,9 +13,14 @@ export async function authorizePromptRequestOrThrow(req: NextApiRequest) {redis,).verifyAuthHeaderAndReturnScope(req.headers.authorization);if (!authCheck.validKey) throw new UnauthorizedError(authCheck.error);- if (authCheck.scope.accessLevel !== "all")+ if (authCheck.scope.accessLevel !== "project")throw new ForbiddenError(`Access denied - need to use basic auth with secret key to ${req.method} prompts`,);- return authCheck;+ if (!authCheck.scope.projectId) {+ throw new ForbiddenError(`No valid projectId found for auth token`);+ }+ return authCheck as AuthHeaderValidVerificationResult & {+ scope: { projectId: string; accessLevel: "project" };+ };}diff --git a/web/src/features/public-api/components/ApiKeyList.tsx b/web/src/features/public-api/components/ApiKeyList.tsxindex 23d288a8ac..2763b9a9dd 100644--- a/web/src/features/public-api/components/ApiKeyList.tsx+++ b/web/src/features/public-api/components/ApiKeyList.tsx@@ -34,7 +34,7 @@ export function ApiKeyList(props: { projectId: string }) {scope: "apiKeys:read",});- const apiKeys = api.apiKeys.byProjectId.useQuery(+ const apiKeys = api.projectApiKeys.byProjectId.useQuery({projectId: props.projectId,},@@ -131,8 +131,8 @@ function DeleteApiKeyButton(props: { projectId: string; apiKeyId: string }) {});const utils = api.useUtils();- const mutDeleteApiKey = api.apiKeys.delete.useMutation({- onSuccess: () => utils.apiKeys.invalidate(),+ const mutDeleteApiKey = api.projectApiKeys.delete.useMutation({+ onSuccess: () => utils.projectApiKeys.invalidate(),});const [open, setOpen] = useState(false);@@ -191,9 +191,9 @@ function ApiKeyNote({projectId: string;}) {const utils = api.useUtils();- const updateNote = api.apiKeys.updateNote.useMutation({+ const updateNote = api.projectApiKeys.updateNote.useMutation({onSuccess: () => {- utils.apiKeys.invalidate();+ utils.projectApiKeys.invalidate();},});const hasEditAccess = useHasProjectAccess({diff --git a/web/src/features/public-api/components/CreateApiKeyButton.tsx b/web/src/features/public-api/components/CreateApiKeyButton.tsxindex b123e071fc..b5ec7dad7f 100644--- a/web/src/features/public-api/components/CreateApiKeyButton.tsx+++ b/web/src/features/public-api/components/CreateApiKeyButton.tsx@@ -23,8 +23,8 @@ export function CreateApiKeyButton(props: { projectId: string }) {scope: "apiKeys:CUD",});- const mutCreateApiKey = api.apiKeys.create.useMutation({- onSuccess: () => utils.apiKeys.invalidate(),+ const mutCreateApiKey = api.projectApiKeys.create.useMutation({+ onSuccess: () => utils.projectApiKeys.invalidate(),});const [open, setOpen] = useState(false);const [generatedKeys, setGeneratedKeys] = useState<{diff --git a/web/src/features/public-api/server/apiAuth.ts b/web/src/features/public-api/server/apiAuth.tsindex 688c055644..fa4023dc78 100644--- a/web/src/features/public-api/server/apiAuth.ts+++ b/web/src/features/public-api/server/apiAuth.ts@@ -14,6 +14,7 @@ import {type PrismaClient,type ApiKey,type Prisma,+ type ApiKeyScope,} from "@langfuse/shared/src/db";import { isPrismaException } from "@/src/utils/exceptions";import { type Redis } from "ioredis";@@ -56,9 +57,14 @@ export class ApiAuthService {async invalidateOrgApiKeys(orgId: string) {const apiKeys = await this.prisma.apiKey.findMany({where: {- project: {- orgId: orgId,- },+ OR: [+ {+ project: {+ orgId: orgId,+ },+ },+ { orgId },+ ],},});@@ -69,18 +75,20 @@ export class ApiAuthService {const apiKeys = await this.prisma.apiKey.findMany({where: {projectId: projectId,+ scope: "PROJECT",},});await this.invalidate(apiKeys, `project ${projectId}`);}- async deleteApiKey(id: string, projectId: string) {+ async deleteApiKey(id: string, projectId: string, scope: ApiKeyScope) {// Make sure the API key exists and belongs to the project the user has access toconst apiKey = await this.prisma.apiKey.findFirstOrThrow({where: {id: id,projectId: projectId,+ scope,},});if (!apiKey) {@@ -130,7 +138,10 @@ export class ApiAuthService {if (!apiKey || !apiKey.fastHashedSecretKey) {const slowKey = await this.prisma.apiKey.findUnique({where: { publicKey },- include: { project: { include: { organization: true } } },+ include: {+ project: { include: { organization: true } },+ organization: true,+ },});if (!slowKey) {@@ -165,7 +176,7 @@ export class ApiAuthService {fastHashedSecretKey: shaKey,},});- finalApiKey = convertToRedisRepresentation({+ finalApiKey = this.convertToRedisRepresentation({...slowKey,fastHashedSecretKey: shaKey,});@@ -176,7 +187,7 @@ export class ApiAuthService {throw new Error("Invalid credentials");}- addUserToSpan({ projectId: finalApiKey.projectId });+ addUserToSpan({ projectId: finalApiKey.projectId ?? "" });const plan = finalApiKey.plan;@@ -185,15 +196,19 @@ export class ApiAuthService {throw new Error("Invalid credentials");}+ const accessLevel =+ finalApiKey.scope === "ORGANIZATION" ? "organization" : "project";+return {validKey: true,scope: {projectId: finalApiKey.projectId,- accessLevel: "all",+ accessLevel,orgId: finalApiKey.orgId,plan: plan,rateLimitOverrides: finalApiKey.rateLimitOverrides ?? [],apiKeyId: finalApiKey.id,+ scope: finalApiKey.scope,},};}@@ -203,21 +218,26 @@ export class ApiAuthService {const dbKey = await this.findDbKeyOrThrow(publicKey);- addUserToSpan({ projectId: dbKey.projectId });+ if (dbKey.scope === "ORGANIZATION") {+ throw new Error(+ "Unauthorized: Cannot use organization key with bearer auth",+ );+ }++ addUserToSpan({ projectId: dbKey.projectId ?? "" });- const cloudConfig = dbKey.project.organization.cloudConfig- ? CloudConfigSchema.parse(dbKey.project.organization.cloudConfig)- : undefined;+ const { orgId, cloudConfig } = this.extractOrgIdAndCloudConfig(dbKey);return {validKey: true,scope: {projectId: dbKey.projectId,accessLevel: "scores",- orgId: dbKey.project.organization.id,+ orgId,plan: getOrganizationPlanServerSide(cloudConfig),rateLimitOverrides: cloudConfig?.rateLimitOverrides ?? [],apiKeyId: dbKey.id,+ scope: dbKey.scope,},};}@@ -245,7 +265,7 @@ export class ApiAuthService {});}- extractBasicAuthCredentials(basicAuthHeader: string): {+ private extractBasicAuthCredentials(basicAuthHeader: string): {username: string;password: string;} {@@ -257,10 +277,13 @@ export class ApiAuthService {return { username, password };}- async findDbKeyOrThrow(publicKey: string) {+ private async findDbKeyOrThrow(publicKey: string) {const dbKey = await this.prisma.apiKey.findUnique({where: { publicKey },- include: { project: { include: { organization: true } } },+ include: {+ project: { include: { organization: true } },+ organization: true,+ },});if (!dbKey) {logger.info("No api key found for public key:", publicKey);@@ -269,7 +292,7 @@ export class ApiAuthService {return dbKey;}- async fetchApiKeyAndAddToRedis(hash: string) {+ private async fetchApiKeyAndAddToRedis(hash: string) {// first get the API key from redis, this does not throwconst redisApiKey = await this.fetchApiKeyFromRedis(hash);@@ -289,7 +312,10 @@ export class ApiAuthService {// if redis not available or object not found, try the databaseconst apiKeyAndOrganisation = await this.prisma.apiKey.findUnique({where: { fastHashedSecretKey: hash },- include: { project: { include: { organization: true } } },+ include: {+ project: { include: { organization: true } },+ organization: true,+ },});// add the key to redis for future use if available, this does not throw@@ -297,15 +323,15 @@ export class ApiAuthService {if (apiKeyAndOrganisation && apiKeyAndOrganisation.fastHashedSecretKey) {await this.addApiKeyToRedis(hash,- convertToRedisRepresentation(apiKeyAndOrganisation),+ this.convertToRedisRepresentation(apiKeyAndOrganisation),);}return apiKeyAndOrganisation- ? convertToRedisRepresentation(apiKeyAndOrganisation)+ ? this.convertToRedisRepresentation(apiKeyAndOrganisation): null;}- async addApiKeyToRedis(+ private async addApiKeyToRedis(hash: string,newApiKey: z.infer<typeof OrgEnrichedApiKey> | typeof API_KEY_NON_EXISTENT,) {@@ -325,7 +351,7 @@ export class ApiAuthService {}}- async fetchApiKeyFromRedis(hash: string) {+ private async fetchApiKeyFromRedis(hash: string) {if (!this.redis || env.LANGFUSE_CACHE_API_KEY_ENABLED !== "true") {return null;}@@ -361,47 +387,101 @@ export class ApiAuthService {}}- createRedisKey(hash: string) {+ private createRedisKey(hash: string) {return `api-key:${hash}`;}-}-export const convertToRedisRepresentation = (- apiKeyAndOrganisation: ApiKey & {- project: {- id: string;+ private extractOrgIdAndCloudConfig(+ apiKeyAndOrganisation: ApiKey & {+ project: {+ id: string;+ organization: {+ id: string;+ name: string;+ createdAt: Date;+ updatedAt: Date;+ cloudConfig: Prisma.JsonValue;+ };+ } | null;+ } & {organization: {id: string;name: string;createdAt: Date;updatedAt: Date;cloudConfig: Prisma.JsonValue;- };- };- },-) => {- const {- project: {- organization: { id: orgId, cloudConfig: cloudConfig },+ } | null;},- } = apiKeyAndOrganisation;-- const parsedCloudConfig = cloudConfig- ? CloudConfigSchema.parse(cloudConfig)- : undefined;-- const newApiKey = OrgEnrichedApiKey.parse({- ...apiKeyAndOrganisation,- createdAt: apiKeyAndOrganisation.createdAt?.toISOString(),- orgId,- plan: getOrganizationPlanServerSide(parsedCloudConfig),- rateLimitOverrides: parsedCloudConfig?.rateLimitOverrides,- });-- if (!orgId) {- logger.error("No organization found for key");- throw new Error("Invalid credentials");+ ) {+ const orgId =+ apiKeyAndOrganisation.project?.organization.id ??+ apiKeyAndOrganisation.organization?.id;+ const rawCloudConfig =+ apiKeyAndOrganisation.project?.organization.cloudConfig ??+ apiKeyAndOrganisation.organization?.cloudConfig;++ if (!orgId) {+ logger.error(+ `No organization found for key: ${apiKeyAndOrganisation.publicKey}`,+ );+ throw new Error("Invalid credentials: No organization found for key");+ }++ const cloudConfig = rawCloudConfig+ ? CloudConfigSchema.parse(rawCloudConfig)+ : undefined;++ return {+ orgId,+ cloudConfig,+ };}- return newApiKey;-};+ /**+ * Converts the API key and organization to a Redis representation.+ * For project-scoped API keys, it includes the project ID and organization.+ * For organization-scoped API keys, it includes only the organization.+ * @param apiKeyAndOrganisation+ */+ private convertToRedisRepresentation(+ apiKeyAndOrganisation: ApiKey & {+ project: {+ id: string;+ organization: {+ id: string;+ name: string;+ createdAt: Date;+ updatedAt: Date;+ cloudConfig: Prisma.JsonValue;+ };+ } | null;+ } & {+ organization: {+ id: string;+ name: string;+ createdAt: Date;+ updatedAt: Date;+ cloudConfig: Prisma.JsonValue;+ } | null;+ },+ ) {+ const { orgId, cloudConfig } = this.extractOrgIdAndCloudConfig(+ apiKeyAndOrganisation,+ );++ const newApiKey = OrgEnrichedApiKey.parse({+ ...apiKeyAndOrganisation,+ createdAt: apiKeyAndOrganisation.createdAt?.toISOString(),+ orgId,+ plan: getOrganizationPlanServerSide(cloudConfig),+ rateLimitOverrides: cloudConfig?.rateLimitOverrides,+ });++ if (!orgId) {+ logger.error("No organization found for key");+ throw new Error("Invalid credentials");+ }++ return newApiKey;+ }+}diff --git a/web/src/features/public-api/server/createAuthedAPIRoute.ts b/web/src/features/public-api/server/createAuthedProjectAPIRoute.tssimilarity index 84%rename from web/src/features/public-api/server/createAuthedAPIRoute.tsrename to web/src/features/public-api/server/createAuthedProjectAPIRoute.tsindex aa18ec6932..127fe32fdb 100644--- a/web/src/features/public-api/server/createAuthedAPIRoute.ts+++ b/web/src/features/public-api/server/createAuthedProjectAPIRoute.ts@@ -28,11 +28,13 @@ type RouteConfig<body: z.infer<TBody>;req: NextApiRequest;res: NextApiResponse;- auth: AuthHeaderValidVerificationResult;+ auth: AuthHeaderValidVerificationResult & {+ scope: { projectId: string; accessLevel: "project" };+ };}) => Promise<z.infer<TResponse>>;};-export const createAuthedAPIRoute = <+export const createAuthedProjectAPIRoute = <TQuery extends ZodType<any>,TBody extends ZodType<any>,TResponse extends ZodType<any>,@@ -48,12 +50,19 @@ export const createAuthedAPIRoute = <res.status(401).json({ message: auth.error });return;}- if (auth.scope.accessLevel !== "all") {+ 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?",+ });+ return;+ }const rateLimitResponse =await RateLimitService.getInstance().rateLimitRequest(@@ -85,7 +94,9 @@ export const createAuthedAPIRoute = <body,req,res,- auth,+ auth: auth as AuthHeaderValidVerificationResult & {+ scope: { projectId: string; accessLevel: "project" };+ },});if (env.NODE_ENV === "development" && routeConfig.responseSchema) {diff --git a/web/src/features/public-api/server/apiKeyRouter.ts b/web/src/features/public-api/server/projectApiKeyRouter.tssimilarity index 96%rename from web/src/features/public-api/server/apiKeyRouter.tsrename to web/src/features/public-api/server/projectApiKeyRouter.tsindex 3ca02eb580..5f8a566d55 100644--- a/web/src/features/public-api/server/apiKeyRouter.ts+++ b/web/src/features/public-api/server/projectApiKeyRouter.ts@@ -9,7 +9,7 @@ import { ApiAuthService } from "@/src/features/public-api/server/apiAuth";import { redis } from "@langfuse/shared/src/server";import { createAndAddApiKeysToDb } from "@langfuse/shared/src/server/auth/apiKeys";-export const apiKeysRouter = createTRPCRouter({+export const projectApiKeysRouter = createTRPCRouter({byProjectId: protectedProjectProcedure.input(z.object({@@ -26,6 +26,7 @@ export const apiKeysRouter = createTRPCRouter({return ctx.prisma.apiKey.findMany({where: {projectId: input.projectId,+ scope: "PROJECT",},select: {id: true,@@ -59,6 +60,7 @@ export const apiKeysRouter = createTRPCRouter({prisma: ctx.prisma,projectId: input.projectId,note: input.note,+ scope: "PROJECT",});await auditLog({@@ -128,6 +130,7 @@ export const apiKeysRouter = createTRPCRouter({return await new ApiAuthService(ctx.prisma, redis).deleteApiKey(input.id,input.projectId,+ "PROJECT",);}),});diff --git a/web/src/features/setup/components/SetupPage.tsx b/web/src/features/setup/components/SetupPage.tsxindex 36408436aa..9ead03e346 100644--- a/web/src/features/setup/components/SetupPage.tsx+++ b/web/src/features/setup/components/SetupPage.tsx@@ -242,12 +242,12 @@ const TracingSetup = ({hasAnyTrace?: boolean;}) => {const [apiKeys, setApiKeys] = useState<- RouterOutput["apiKeys"]["create"] | null+ RouterOutput["projectApiKeys"]["create"] | null>(null);const utils = api.useUtils();- const mutCreateApiKey = api.apiKeys.create.useMutation({+ const mutCreateApiKey = api.projectApiKeys.create.useMutation({onSuccess: (data) => {- utils.apiKeys.invalidate();+ utils.projectApiKeys.invalidate();setApiKeys(data);showChat();},diff --git a/web/src/initialize.ts b/web/src/initialize.tsindex fc3434d8b8..9c1373003e 100644--- a/web/src/initialize.ts+++ b/web/src/initialize.ts@@ -74,6 +74,7 @@ if (env.LANGFUSE_INIT_ORG_ID) {prisma,projectId: env.LANGFUSE_INIT_PROJECT_ID,note: "Provisioned API Key",+ scope: "PROJECT",predefinedKeys: {secretKey: env.LANGFUSE_INIT_PROJECT_SECRET_KEY,publicKey: env.LANGFUSE_INIT_PROJECT_PUBLIC_KEY,diff --git a/web/src/pages/api/admin/api-keys/index.ts b/web/src/pages/api/admin/api-keys/index.tsindex ec8299397a..80c111c723 100644--- a/web/src/pages/api/admin/api-keys/index.ts+++ b/web/src/pages/api/admin/api-keys/index.ts@@ -2,8 +2,8 @@ import { type NextApiRequest, type NextApiResponse } from "next";import { z } from "zod";import { prisma } from "@langfuse/shared/src/db";import { logger, redis } from "@langfuse/shared/src/server";-import { env } from "@/src/env.mjs";import { ApiAuthService } from "@/src/features/public-api/server/apiAuth";+import { AdminApiAuthService } from "@/src/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.@@ -36,29 +36,7 @@ export default async function handler(return;}- if (!env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION) {- res.status(403).json({ error: "Only accessible on Langfuse cloud" });- return;- }-- // check if ADMIN_API_KEY is set- if (!env.ADMIN_API_KEY) {- logger.error("ADMIN_API_KEY is not set");- res.status(500).json({ error: "ADMIN_API_KEY is not set" });- return;- }-- // check bearer token- const { authorization } = req.headers;- if (!authorization) {- res- .status(401)- .json({ error: "Unauthorized: No authorization header provided" });- return;- }- const [scheme, token] = authorization.split(" ");- if (scheme !== "Bearer" || !token || token !== env.ADMIN_API_KEY) {- res.status(401).json({ error: "Unauthorized: Invalid token" });+ if (!AdminApiAuthService.handleAdminAuth(req, res)) {return;}@@ -80,6 +58,7 @@ export default async function handler(projectId: {in: body.data.projectIds,},+ scope: "PROJECT",},});@@ -88,6 +67,7 @@ export default async function handler(projectId: {in: body.data.projectIds,},+ scope: "PROJECT",},});@@ -109,6 +89,7 @@ export default async function handler(projectId: {in: body.data.projectIds,},+ scope: "PROJECT",},});diff --git a/web/src/pages/api/admin/bullmq/index.ts b/web/src/pages/api/admin/bullmq/index.tsindex b21118d76d..ed3321e45a 100644--- a/web/src/pages/api/admin/bullmq/index.ts+++ b/web/src/pages/api/admin/bullmq/index.ts@@ -1,7 +1,7 @@import { type NextApiRequest, type NextApiResponse } from "next";import { z } from "zod";import { logger, QueueName, getQueue } from "@langfuse/shared/src/server";-import { env } from "@/src/env.mjs";+import { AdminApiAuthService } from "@/src/features/admin-api/server/adminApiAuth";/*This API route is used by Langfuse Cloud to retry failed bullmq jobs.@@ -34,35 +34,13 @@ export default async function handler(res: NextApiResponse,) {try {- // allow only POST requests+ // allow only POST and GET requestsif (req.method !== "POST" && req.method !== "GET") {res.status(405).json({ error: "Method Not Allowed" });return;}- if (!env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION) {- res.status(403).json({ error: "Only accessible on Langfuse cloud" });- return;- }-- // check if ADMIN_API_KEY is set- if (!env.ADMIN_API_KEY) {- logger.error("ADMIN_API_KEY is not set");- res.status(500).json({ error: "ADMIN_API_KEY is not set" });- return;- }-- // check bearer token- const { authorization } = req.headers;- if (!authorization) {- res- .status(401)- .json({ error: "Unauthorized: No authorization header provided" });- return;- }- const [scheme, token] = authorization.split(" ");- if (scheme !== "Bearer" || !token || token !== env.ADMIN_API_KEY) {- res.status(401).json({ error: "Unauthorized: Invalid token" });+ 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.tsnew file mode 100644index 0000000000..6b457e7718--- /dev/null+++ b/web/src/pages/api/admin/organizations/index.ts@@ -0,0 +1,69 @@+import { type NextApiRequest, type NextApiResponse } from "next";+import { prisma } from "@langfuse/shared/src/db";+import { logger } from "@langfuse/shared/src/server";+import { AdminApiAuthService } from "@/src/features/admin-api/server/adminApiAuth";+import { organizationNameSchema } from "@/src/features/organizations/utils/organizationNameSchema";+import { auditLog } from "@/src/features/audit-logs/auditLog";++export default async function handler(+ req: NextApiRequest,+ res: NextApiResponse,+) {+ try {+ // Allow only POST requests+ if (req.method !== "POST") {+ res.status(405).json({ error: "Method Not Allowed" });+ return;+ }++ // Verify admin API authentication, but allow non-langfuse cloud use-cases+ if (!AdminApiAuthService.handleAdminAuth(req, res, false)) {+ return;+ }++ // For POST requests, create a new organization+ if (req.method === "POST") {+ // Validate the request body using the organizationNameSchema+ const validationResult = organizationNameSchema.safeParse(req.body);++ if (!validationResult.success) {+ res.status(400).json({+ error: "Invalid request body",+ details: validationResult.error.format(),+ });+ return;+ }++ const { name } = validationResult.data;++ // Create the organization in the database+ const organization = await prisma.organization.create({+ data: {+ name,+ },+ });++ // Log the organization creation+ await auditLog({+ resourceType: "organization",+ resourceId: organization.id,+ action: "create",+ orgId: organization.id,+ orgRole: "ADMIN",+ after: organization,+ apiKeyId: "ADMIN_KEY",+ });++ logger.info(`Created organization ${organization.id} via admin API`);++ return res.status(201).json({+ id: organization.id,+ name: organization.name,+ createdAt: organization.createdAt,+ });+ }+ } catch (e) {+ logger.error("Failed to process organization request", e);+ res.status(500).json({ error: "Internal server error" });+ }+}diff --git a/web/src/pages/api/public/annotation-queues/[queueId].ts b/web/src/pages/api/public/annotation-queues/[queueId].tsindex b8811f3c26..565673022f 100644--- a/web/src/pages/api/public/annotation-queues/[queueId].ts+++ b/web/src/pages/api/public/annotation-queues/[queueId].ts@@ -1,6 +1,6 @@import { prisma } from "@langfuse/shared/src/db";import { withMiddlewares } from "@/src/features/public-api/server/withMiddlewares";-import { createAuthedAPIRoute } from "@/src/features/public-api/server/createAuthedAPIRoute";+import { createAuthedProjectAPIRoute } from "@/src/features/public-api/server/createAuthedProjectAPIRoute";import {GetAnnotationQueueByIdQuery,GetAnnotationQueueByIdResponse,@@ -8,7 +8,7 @@ import {import { LangfuseNotFoundError } from "@langfuse/shared";export default withMiddlewares({- GET: createAuthedAPIRoute({+ GET: createAuthedProjectAPIRoute({name: "Get annotation queue by ID",querySchema: GetAnnotationQueueByIdQuery,responseSchema: GetAnnotationQueueByIdResponse,diff --git a/web/src/pages/api/public/annotation-queues/[queueId]/items/[itemId].ts b/web/src/pages/api/public/annotation-queues/[queueId]/items/[itemId].tsindex 67dd8c11c3..91bcba5f30 100644--- a/web/src/pages/api/public/annotation-queues/[queueId]/items/[itemId].ts+++ b/web/src/pages/api/public/annotation-queues/[queueId]/items/[itemId].ts@@ -1,6 +1,6 @@import { prisma } from "@langfuse/shared/src/db";import { withMiddlewares } from "@/src/features/public-api/server/withMiddlewares";-import { createAuthedAPIRoute } from "@/src/features/public-api/server/createAuthedAPIRoute";+import { createAuthedProjectAPIRoute } from "@/src/features/public-api/server/createAuthedProjectAPIRoute";import {GetAnnotationQueueItemByIdQuery,GetAnnotationQueueItemByIdResponse,@@ -13,7 +13,7 @@ import { LangfuseNotFoundError } from "@langfuse/shared";import { AnnotationQueueStatus } from "@langfuse/shared";export default withMiddlewares({- GET: createAuthedAPIRoute({+ GET: createAuthedProjectAPIRoute({name: "Get annotation queue item by ID",querySchema: GetAnnotationQueueItemByIdQuery,responseSchema: GetAnnotationQueueItemByIdResponse,@@ -54,7 +54,7 @@ export default withMiddlewares({};},}),- PATCH: createAuthedAPIRoute({+ PATCH: createAuthedProjectAPIRoute({name: "Update annotation queue item",querySchema: GetAnnotationQueueItemByIdQuery,bodySchema: UpdateAnnotationQueueItemBody,@@ -114,7 +114,7 @@ export default withMiddlewares({};},}),- DELETE: createAuthedAPIRoute({+ DELETE: createAuthedProjectAPIRoute({name: "Delete annotation queue item",querySchema: DeleteAnnotationQueueItemQuery,responseSchema: DeleteAnnotationQueueItemResponse,diff --git a/web/src/pages/api/public/annotation-queues/[queueId]/items/index.ts b/web/src/pages/api/public/annotation-queues/[queueId]/items/index.tsindex d5bf96a6c9..17d2efb95a 100644--- a/web/src/pages/api/public/annotation-queues/[queueId]/items/index.ts+++ b/web/src/pages/api/public/annotation-queues/[queueId]/items/index.ts@@ -1,6 +1,6 @@import { prisma } from "@langfuse/shared/src/db";import { withMiddlewares } from "@/src/features/public-api/server/withMiddlewares";-import { createAuthedAPIRoute } from "@/src/features/public-api/server/createAuthedAPIRoute";+import { createAuthedProjectAPIRoute } from "@/src/features/public-api/server/createAuthedProjectAPIRoute";import {GetAnnotationQueueItemsQuery,GetAnnotationQueueItemsResponse,@@ -11,7 +11,7 @@ import { LangfuseNotFoundError } from "@langfuse/shared";import { AnnotationQueueStatus } from "@langfuse/shared";export default withMiddlewares({- GET: createAuthedAPIRoute({+ GET: createAuthedProjectAPIRoute({name: "Get annotation queue items",querySchema: GetAnnotationQueueItemsQuery,responseSchema: GetAnnotationQueueItemsResponse,@@ -81,7 +81,7 @@ export default withMiddlewares({};},}),- POST: createAuthedAPIRoute({+ POST: createAuthedProjectAPIRoute({name: "Create annotation queue item",querySchema: GetAnnotationQueueItemsQuery,bodySchema: CreateAnnotationQueueItemBody,diff --git a/web/src/pages/api/public/annotation-queues/index.ts b/web/src/pages/api/public/annotation-queues/index.tsindex e1b51c7087..3163a973d4 100644--- a/web/src/pages/api/public/annotation-queues/index.ts+++ b/web/src/pages/api/public/annotation-queues/index.ts@@ -1,6 +1,6 @@import { prisma } from "@langfuse/shared/src/db";import { withMiddlewares } from "@/src/features/public-api/server/withMiddlewares";-import { createAuthedAPIRoute } from "@/src/features/public-api/server/createAuthedAPIRoute";+import { createAuthedProjectAPIRoute } from "@/src/features/public-api/server/createAuthedProjectAPIRoute";import {GetAnnotationQueuesQuery,GetAnnotationQueuesResponse,@@ -8,7 +8,7 @@ import {export default withMiddlewares({// NOTE: Post API requires entitlement check- GET: createAuthedAPIRoute({+ GET: createAuthedProjectAPIRoute({name: "Get annotation queues",querySchema: GetAnnotationQueuesQuery,responseSchema: GetAnnotationQueuesResponse,diff --git a/web/src/pages/api/public/comments/[commentId].ts b/web/src/pages/api/public/comments/[commentId].tsindex 3f2c2cd5cd..1ebc372ff7 100644--- a/web/src/pages/api/public/comments/[commentId].ts+++ b/web/src/pages/api/public/comments/[commentId].ts@@ -1,6 +1,6 @@import { prisma } from "@langfuse/shared/src/db";import { withMiddlewares } from "@/src/features/public-api/server/withMiddlewares";-import { createAuthedAPIRoute } from "@/src/features/public-api/server/createAuthedAPIRoute";+import { createAuthedProjectAPIRoute } from "@/src/features/public-api/server/createAuthedProjectAPIRoute";import { LangfuseNotFoundError } from "@langfuse/shared";import {GetCommentV1Query,@@ -8,7 +8,7 @@ import {} from "@/src/features/public-api/types/comments";export default withMiddlewares({- GET: createAuthedAPIRoute({+ GET: createAuthedProjectAPIRoute({name: "Get Comment",querySchema: GetCommentV1Query,responseSchema: GetCommentV1Response,diff --git a/web/src/pages/api/public/comments/index.ts b/web/src/pages/api/public/comments/index.tsindex 6b9bb49de8..f9ad32a44c 100644--- a/web/src/pages/api/public/comments/index.ts+++ b/web/src/pages/api/public/comments/index.ts@@ -1,5 +1,5 @@import { withMiddlewares } from "@/src/features/public-api/server/withMiddlewares";-import { createAuthedAPIRoute } from "@/src/features/public-api/server/createAuthedAPIRoute";+import { createAuthedProjectAPIRoute } from "@/src/features/public-api/server/createAuthedProjectAPIRoute";import {GetCommentsV1Query,GetCommentsV1Response,@@ -13,7 +13,7 @@ import { LangfuseNotFoundError } from "@langfuse/shared";import { auditLog } from "@/src/features/audit-logs/auditLog";export default withMiddlewares({- POST: createAuthedAPIRoute({+ POST: createAuthedProjectAPIRoute({name: "Create Comment",bodySchema: PostCommentsV1Body,responseSchema: PostCommentsV1Response,@@ -48,7 +48,7 @@ export default withMiddlewares({return { id: comment.id };},}),- GET: createAuthedAPIRoute({+ GET: createAuthedProjectAPIRoute({name: "Get Comments",querySchema: GetCommentsV1Query,responseSchema: GetCommentsV1Response,diff --git a/web/src/pages/api/public/dataset-items/[datasetItemId].ts b/web/src/pages/api/public/dataset-items/[datasetItemId].tsindex 69859301fd..023b87e107 100644--- a/web/src/pages/api/public/dataset-items/[datasetItemId].ts+++ b/web/src/pages/api/public/dataset-items/[datasetItemId].ts@@ -1,6 +1,6 @@import { prisma } from "@langfuse/shared/src/db";import { withMiddlewares } from "@/src/features/public-api/server/withMiddlewares";-import { createAuthedAPIRoute } from "@/src/features/public-api/server/createAuthedAPIRoute";+import { createAuthedProjectAPIRoute } from "@/src/features/public-api/server/createAuthedProjectAPIRoute";import {GetDatasetItemV1Query,GetDatasetItemV1Response,@@ -12,7 +12,7 @@ import { LangfuseNotFoundError } from "@langfuse/shared";import { auditLog } from "@/src/features/audit-logs/auditLog";export default withMiddlewares({- GET: createAuthedAPIRoute({+ GET: createAuthedProjectAPIRoute({name: "Get Dataset Item",querySchema: GetDatasetItemV1Query,responseSchema: GetDatasetItemV1Response,@@ -46,7 +46,7 @@ export default withMiddlewares({});},}),- DELETE: createAuthedAPIRoute({+ DELETE: createAuthedProjectAPIRoute({name: "Delete Dataset Item",querySchema: DeleteDatasetItemV1Query,responseSchema: DeleteDatasetItemV1Response,diff --git a/web/src/pages/api/public/dataset-items/index.ts b/web/src/pages/api/public/dataset-items/index.tsindex 0bdd04b375..4821cd77a2 100644--- a/web/src/pages/api/public/dataset-items/index.ts+++ b/web/src/pages/api/public/dataset-items/index.ts@@ -1,6 +1,6 @@import { prisma } from "@langfuse/shared/src/db";import { withMiddlewares } from "@/src/features/public-api/server/withMiddlewares";-import { createAuthedAPIRoute } from "@/src/features/public-api/server/createAuthedAPIRoute";+import { createAuthedProjectAPIRoute } from "@/src/features/public-api/server/createAuthedProjectAPIRoute";import { v4 as uuidv4 } from "uuid";import {GetDatasetItemsV1Query,@@ -18,7 +18,7 @@ import { logger } from "@langfuse/shared/src/server";import { auditLog } from "@/src/features/audit-logs/auditLog";export default withMiddlewares({- POST: createAuthedAPIRoute({+ POST: createAuthedProjectAPIRoute({name: "Create Dataset Item",bodySchema: PostDatasetItemsV1Body,responseSchema: PostDatasetItemsV1Response,@@ -111,7 +111,7 @@ export default withMiddlewares({});},}),- GET: createAuthedAPIRoute({+ GET: createAuthedProjectAPIRoute({name: "Get Dataset Items",querySchema: GetDatasetItemsV1Query,responseSchema: GetDatasetItemsV1Response,diff --git a/web/src/pages/api/public/dataset-run-items.ts b/web/src/pages/api/public/dataset-run-items.tsindex b6ce632405..dfcc25d187 100644--- a/web/src/pages/api/public/dataset-run-items.ts+++ b/web/src/pages/api/public/dataset-run-items.ts@@ -1,6 +1,6 @@import { prisma } from "@langfuse/shared/src/db";import { withMiddlewares } from "@/src/features/public-api/server/withMiddlewares";-import { createAuthedAPIRoute } from "@/src/features/public-api/server/createAuthedAPIRoute";+import { createAuthedProjectAPIRoute } from "@/src/features/public-api/server/createAuthedProjectAPIRoute";import {PostDatasetRunItemsV1Body,PostDatasetRunItemsV1Response,@@ -11,7 +11,7 @@ import { addDatasetRunItemsToEvalQueue } from "@/src/ee/features/evals/server/adimport { getObservationById } from "@langfuse/shared/src/server";export default withMiddlewares({- POST: createAuthedAPIRoute({+ POST: createAuthedProjectAPIRoute({name: "Create Dataset Run Item",bodySchema: PostDatasetRunItemsV1Body,responseSchema: PostDatasetRunItemsV1Response,diff --git a/web/src/pages/api/public/datasets.ts b/web/src/pages/api/public/datasets.tsindex 61989df814..7dbeae1d02 100644--- a/web/src/pages/api/public/datasets.ts+++ b/web/src/pages/api/public/datasets.ts@@ -1,6 +1,6 @@import { prisma } from "@langfuse/shared/src/db";import { withMiddlewares } from "@/src/features/public-api/server/withMiddlewares";-import { createAuthedAPIRoute } from "@/src/features/public-api/server/createAuthedAPIRoute";+import { createAuthedProjectAPIRoute } from "@/src/features/public-api/server/createAuthedProjectAPIRoute";import {GetDatasetsV1Query,GetDatasetsV1Response,@@ -9,7 +9,7 @@ import {} from "@/src/features/public-api/types/datasets";export default withMiddlewares({- POST: createAuthedAPIRoute({+ POST: createAuthedProjectAPIRoute({name: "Create or Update Dataset",bodySchema: PostDatasetsV1Body,responseSchema: PostDatasetsV1Response,@@ -42,7 +42,7 @@ export default withMiddlewares({};},}),- GET: createAuthedAPIRoute({+ GET: createAuthedProjectAPIRoute({name: "Get Datasets",querySchema: GetDatasetsV1Query,responseSchema: GetDatasetsV1Response,diff --git a/web/src/pages/api/public/datasets/[name]/index.ts b/web/src/pages/api/public/datasets/[name]/index.tsindex 3ade617dac..a04bd1e792 100644--- a/web/src/pages/api/public/datasets/[name]/index.ts+++ b/web/src/pages/api/public/datasets/[name]/index.ts@@ -1,6 +1,6 @@import { prisma } from "@langfuse/shared/src/db";import { withMiddlewares } from "@/src/features/public-api/server/withMiddlewares";-import { createAuthedAPIRoute } from "@/src/features/public-api/server/createAuthedAPIRoute";+import { createAuthedProjectAPIRoute } from "@/src/features/public-api/server/createAuthedProjectAPIRoute";import {GetDatasetV1Query,GetDatasetV1Response,@@ -9,7 +9,7 @@ import {import { LangfuseNotFoundError } from "@langfuse/shared";export default withMiddlewares({- GET: createAuthedAPIRoute({+ GET: createAuthedProjectAPIRoute({name: "Get Dataset",querySchema: GetDatasetV1Query,responseSchema: GetDatasetV1Response,diff --git a/web/src/pages/api/public/datasets/[name]/runs/[runName].ts b/web/src/pages/api/public/datasets/[name]/runs/[runName].tsindex 2b52cfe5d2..4aaa902f54 100644--- a/web/src/pages/api/public/datasets/[name]/runs/[runName].ts+++ b/web/src/pages/api/public/datasets/[name]/runs/[runName].ts@@ -8,12 +8,12 @@ import {transformDbDatasetRunToAPIDatasetRun,} from "@/src/features/public-api/types/datasets";import { withMiddlewares } from "@/src/features/public-api/server/withMiddlewares";-import { createAuthedAPIRoute } from "@/src/features/public-api/server/createAuthedAPIRoute";+import { createAuthedProjectAPIRoute } from "@/src/features/public-api/server/createAuthedProjectAPIRoute";import { ApiError, LangfuseNotFoundError } from "@langfuse/shared";import { auditLog } from "@/src/features/audit-logs/auditLog";export default withMiddlewares({- GET: createAuthedAPIRoute({+ GET: createAuthedProjectAPIRoute({name: "get-dataset-run",querySchema: GetDatasetRunV1Query,responseSchema: GetDatasetRunV1Response,@@ -58,7 +58,7 @@ export default withMiddlewares({};},}),- DELETE: createAuthedAPIRoute({+ DELETE: createAuthedProjectAPIRoute({name: "delete-dataset-run",querySchema: DeleteDatasetRunV1Query,responseSchema: DeleteDatasetRunV1Response,diff --git a/web/src/pages/api/public/datasets/[name]/runs/index.ts b/web/src/pages/api/public/datasets/[name]/runs/index.tsindex 82e24efdbd..314e20344f 100644--- a/web/src/pages/api/public/datasets/[name]/runs/index.ts+++ b/web/src/pages/api/public/datasets/[name]/runs/index.ts@@ -5,11 +5,11 @@ import {transformDbDatasetRunToAPIDatasetRun,} from "@/src/features/public-api/types/datasets";import { withMiddlewares } from "@/src/features/public-api/server/withMiddlewares";-import { createAuthedAPIRoute } from "@/src/features/public-api/server/createAuthedAPIRoute";+import { createAuthedProjectAPIRoute } from "@/src/features/public-api/server/createAuthedProjectAPIRoute";import { LangfuseNotFoundError } from "@langfuse/shared";export default withMiddlewares({- GET: createAuthedAPIRoute({+ GET: createAuthedProjectAPIRoute({name: "get-dataset-runs",querySchema: GetDatasetRunsV1Query,responseSchema: GetDatasetRunsV1Response,diff --git a/web/src/pages/api/public/events.ts b/web/src/pages/api/public/events.tsindex 2faf4e0700..d2390ea0a2 100644--- a/web/src/pages/api/public/events.ts+++ b/web/src/pages/api/public/events.ts@@ -3,7 +3,7 @@ import {PostEventsV1Response,} from "@/src/features/public-api/types/events";import { withMiddlewares } from "@/src/features/public-api/server/withMiddlewares";-import { createAuthedAPIRoute } from "@/src/features/public-api/server/createAuthedAPIRoute";+import { createAuthedProjectAPIRoute } from "@/src/features/public-api/server/createAuthedProjectAPIRoute";import {eventTypes,logger,@@ -12,7 +12,7 @@ import {import { v4 } from "uuid";export default withMiddlewares({- POST: createAuthedAPIRoute({+ POST: createAuthedProjectAPIRoute({name: "Create Event",bodySchema: PostEventsV1Body,responseSchema: PostEventsV1Response,diff --git a/web/src/pages/api/public/generations.ts b/web/src/pages/api/public/generations.tsindex 0f4f5afbfd..a8d88f80b6 100644--- a/web/src/pages/api/public/generations.ts+++ b/web/src/pages/api/public/generations.ts@@ -5,7 +5,7 @@ import {PatchGenerationsV1Response,} from "@/src/features/public-api/types/generations";import { withMiddlewares } from "@/src/features/public-api/server/withMiddlewares";-import { createAuthedAPIRoute } from "@/src/features/public-api/server/createAuthedAPIRoute";+import { createAuthedProjectAPIRoute } from "@/src/features/public-api/server/createAuthedProjectAPIRoute";import {eventTypes,logger,@@ -14,7 +14,7 @@ import {import { v4 } from "uuid";export default withMiddlewares({- POST: createAuthedAPIRoute({+ POST: createAuthedProjectAPIRoute({name: "Create Generation (Legacy)",bodySchema: PostGenerationsV1Body,responseSchema: PostGenerationsV1Response,@@ -50,7 +50,7 @@ export default withMiddlewares({return { id: event.body.id };},}),- PATCH: createAuthedAPIRoute({+ PATCH: createAuthedProjectAPIRoute({name: "Patch Generation (Legacy)",bodySchema: PatchGenerationsV1Body,responseSchema: PatchGenerationsV1Response,diff --git a/web/src/pages/api/public/ingestion.ts b/web/src/pages/api/public/ingestion.tsindex ee58706c09..6261489a24 100644--- a/web/src/pages/api/public/ingestion.ts+++ b/web/src/pages/api/public/ingestion.ts@@ -78,6 +78,11 @@ export default async function handler(if (!authCheck.validKey) {throw new UnauthorizedError(authCheck.error);}+ if (!authCheck.scope.projectId) {+ throw new UnauthorizedError(+ "Missing projectId in scope. Are you using an organization key?",+ );+ }try {const rateLimitCheck =diff --git a/web/src/pages/api/public/media/[mediaId].ts b/web/src/pages/api/public/media/[mediaId].tsindex 2f37e24040..b682d4b3a1 100644--- a/web/src/pages/api/public/media/[mediaId].ts+++ b/web/src/pages/api/public/media/[mediaId].ts@@ -7,7 +7,7 @@ import {GetMediaResponseSchema,PatchMediaBodySchema,} from "@/src/features/media/validation";-import { createAuthedAPIRoute } from "@/src/features/public-api/server/createAuthedAPIRoute";+import { createAuthedProjectAPIRoute } from "@/src/features/public-api/server/createAuthedProjectAPIRoute";import { withMiddlewares } from "@/src/features/public-api/server/withMiddlewares";import {ForbiddenError,@@ -18,12 +18,12 @@ import { Prisma, prisma } from "@langfuse/shared/src/db";import { recordIncrement, recordHistogram } from "@langfuse/shared/src/server";export default withMiddlewares({- GET: createAuthedAPIRoute({+ GET: createAuthedProjectAPIRoute({name: "Get Media data",querySchema: GetMediaQuerySchema,responseSchema: GetMediaResponseSchema,fn: async ({ query, auth }) => {- if (auth.scope.accessLevel !== "all") throw new ForbiddenError();+ if (auth.scope.accessLevel !== "project") throw new ForbiddenError();const { projectId } = auth.scope;const { mediaId } = query;@@ -66,7 +66,7 @@ export default withMiddlewares({},}),- PATCH: createAuthedAPIRoute({+ PATCH: createAuthedProjectAPIRoute({name: "Update Media Uploaded At",querySchema: z.object({mediaId: z.string(),@@ -75,7 +75,7 @@ export default withMiddlewares({responseSchema: z.void(),rateLimitResource: "ingestion",fn: async ({ query, body, auth }) => {- if (auth.scope.accessLevel !== "all") throw new ForbiddenError();+ if (auth.scope.accessLevel !== "project") throw new ForbiddenError();const { projectId } = auth.scope;const { mediaId } = query;diff --git a/web/src/pages/api/public/media/index.ts b/web/src/pages/api/public/media/index.tsindex c89334b3f3..59876366a2 100644--- a/web/src/pages/api/public/media/index.ts+++ b/web/src/pages/api/public/media/index.ts@@ -9,7 +9,7 @@ import {GetMediaUploadUrlResponseSchema,type MediaContentType,} from "@/src/features/media/validation";-import { createAuthedAPIRoute } from "@/src/features/public-api/server/createAuthedAPIRoute";+import { createAuthedProjectAPIRoute } from "@/src/features/public-api/server/createAuthedProjectAPIRoute";import { withMiddlewares } from "@/src/features/public-api/server/withMiddlewares";import {ForbiddenError,@@ -20,14 +20,14 @@ import { prisma } from "@langfuse/shared/src/db";import { logger, instrumentAsync } from "@langfuse/shared/src/server";export default withMiddlewares({- POST: createAuthedAPIRoute({+ POST: createAuthedProjectAPIRoute({name: "Get Media Upload URL",bodySchema: GetMediaUploadUrlQuerySchema,responseSchema: GetMediaUploadUrlResponseSchema,successStatusCode: 201,rateLimitResource: "ingestion",fn: async ({ body, auth }) => {- if (auth.scope.accessLevel !== "all") throw new ForbiddenError();+ if (auth.scope.accessLevel !== "project") throw new ForbiddenError();const { projectId } = auth.scope;const {diff --git a/web/src/pages/api/public/metrics/daily.ts b/web/src/pages/api/public/metrics/daily.tsindex d7e408a277..f4082d6fa8 100644--- a/web/src/pages/api/public/metrics/daily.ts+++ b/web/src/pages/api/public/metrics/daily.ts@@ -3,14 +3,14 @@ import {GetMetricsDailyV1Response,} from "@/src/features/public-api/types/metrics";import { withMiddlewares } from "@/src/features/public-api/server/withMiddlewares";-import { createAuthedAPIRoute } from "@/src/features/public-api/server/createAuthedAPIRoute";+import { createAuthedProjectAPIRoute } from "@/src/features/public-api/server/createAuthedProjectAPIRoute";import {generateDailyMetrics,getDailyMetricsCount,} from "@/src/features/public-api/server/dailyMetrics";export default withMiddlewares({- GET: createAuthedAPIRoute({+ GET: createAuthedProjectAPIRoute({name: "Get Daily Metrics",querySchema: GetMetricsDailyV1Query,responseSchema: GetMetricsDailyV1Response,diff --git a/web/src/pages/api/public/models/[modelId]/index.ts b/web/src/pages/api/public/models/[modelId]/index.tsindex d6cc5ef61f..8aae6ca42a 100644--- a/web/src/pages/api/public/models/[modelId]/index.ts+++ b/web/src/pages/api/public/models/[modelId]/index.ts@@ -1,6 +1,6 @@import { prisma } from "@langfuse/shared/src/db";import { withMiddlewares } from "@/src/features/public-api/server/withMiddlewares";-import { createAuthedAPIRoute } from "@/src/features/public-api/server/createAuthedAPIRoute";+import { createAuthedProjectAPIRoute } from "@/src/features/public-api/server/createAuthedProjectAPIRoute";import {DeleteModelV1Query,DeleteModelV1Response,@@ -12,7 +12,7 @@ import { LangfuseNotFoundError } from "@langfuse/shared";import { auditLog } from "@/src/features/audit-logs/auditLog";export default withMiddlewares({- GET: createAuthedAPIRoute({+ GET: createAuthedProjectAPIRoute({name: "Get model definitions",querySchema: GetModelV1Query,responseSchema: GetModelV1Response,@@ -42,7 +42,7 @@ export default withMiddlewares({return prismaToApiModelDefinition(model);},}),- DELETE: createAuthedAPIRoute({+ DELETE: createAuthedProjectAPIRoute({name: "Delete model",querySchema: DeleteModelV1Query,responseSchema: DeleteModelV1Response,diff --git a/web/src/pages/api/public/models/index.ts b/web/src/pages/api/public/models/index.tsindex 3e26ecb0ad..bba9fed75e 100644--- a/web/src/pages/api/public/models/index.ts+++ b/web/src/pages/api/public/models/index.ts@@ -1,6 +1,6 @@import { prisma } from "@langfuse/shared/src/db";import { withMiddlewares } from "@/src/features/public-api/server/withMiddlewares";-import { createAuthedAPIRoute } from "@/src/features/public-api/server/createAuthedAPIRoute";+import { createAuthedProjectAPIRoute } from "@/src/features/public-api/server/createAuthedProjectAPIRoute";import {GetModelsV1Query,GetModelsV1Response,@@ -13,7 +13,7 @@ import { isValidPostgresRegex } from "@/src/features/models/server/isValidPostgrimport { auditLog } from "@/src/features/audit-logs/auditLog";export default withMiddlewares({- GET: createAuthedAPIRoute({+ GET: createAuthedProjectAPIRoute({name: "Get model definitions",querySchema: GetModelsV1Query,responseSchema: GetModelsV1Response,@@ -67,7 +67,7 @@ export default withMiddlewares({};},}),- POST: createAuthedAPIRoute({+ POST: createAuthedProjectAPIRoute({name: "Create custom model definition",bodySchema: PostModelsV1Body,responseSchema: PostModelsV1Response,diff --git a/web/src/pages/api/public/observations/[observationId].ts b/web/src/pages/api/public/observations/[observationId].tsindex 19aa79de1f..7f56d3a336 100644--- a/web/src/pages/api/public/observations/[observationId].ts+++ b/web/src/pages/api/public/observations/[observationId].ts@@ -5,12 +5,12 @@ import {transformDbToApiObservation,} from "@/src/features/public-api/types/observations";import { withMiddlewares } from "@/src/features/public-api/server/withMiddlewares";-import { createAuthedAPIRoute } from "@/src/features/public-api/server/createAuthedAPIRoute";+import { createAuthedProjectAPIRoute } from "@/src/features/public-api/server/createAuthedProjectAPIRoute";import { LangfuseNotFoundError } from "@langfuse/shared";import { getObservationById } from "@langfuse/shared/src/server";export default withMiddlewares({- GET: createAuthedAPIRoute({+ GET: createAuthedProjectAPIRoute({name: "Get Observation",querySchema: GetObservationV1Query,responseSchema: GetObservationV1Response,diff --git a/web/src/pages/api/public/observations/index.ts b/web/src/pages/api/public/observations/index.tsindex b4a8e1a7c8..71337fb02b 100644--- a/web/src/pages/api/public/observations/index.ts+++ b/web/src/pages/api/public/observations/index.ts@@ -1,7 +1,7 @@import { prisma } from "@langfuse/shared/src/db";import { withMiddlewares } from "@/src/features/public-api/server/withMiddlewares";-import { createAuthedAPIRoute } from "@/src/features/public-api/server/createAuthedAPIRoute";+import { createAuthedProjectAPIRoute } from "@/src/features/public-api/server/createAuthedProjectAPIRoute";import {GetObservationsV1Query,@@ -14,7 +14,7 @@ import {} from "@/src/features/public-api/server/observations";export default withMiddlewares({- GET: createAuthedAPIRoute({+ GET: createAuthedProjectAPIRoute({name: "Get Observations",querySchema: GetObservationsV1Query,responseSchema: GetObservationsV1Response,diff --git a/web/src/pages/api/public/otel/v1/metrics/index.ts b/web/src/pages/api/public/otel/v1/metrics/index.tsindex df1e51842d..652460ad12 100644--- a/web/src/pages/api/public/otel/v1/metrics/index.ts+++ b/web/src/pages/api/public/otel/v1/metrics/index.ts@@ -1,5 +1,5 @@import { withMiddlewares } from "@/src/features/public-api/server/withMiddlewares";-import { createAuthedAPIRoute } from "@/src/features/public-api/server/createAuthedAPIRoute";+import { createAuthedProjectAPIRoute } from "@/src/features/public-api/server/createAuthedProjectAPIRoute";import { z } from "zod";export const config = {@@ -9,7 +9,7 @@ export const config = {};export default withMiddlewares({- POST: createAuthedAPIRoute({+ POST: createAuthedProjectAPIRoute({name: "OTel Metrics",querySchema: z.any(),responseSchema: z.any(),diff --git a/web/src/pages/api/public/otel/v1/traces/index.ts b/web/src/pages/api/public/otel/v1/traces/index.tsindex ccc5986a68..5f661b6fcb 100644--- a/web/src/pages/api/public/otel/v1/traces/index.ts+++ b/web/src/pages/api/public/otel/v1/traces/index.ts@@ -1,5 +1,5 @@import { withMiddlewares } from "@/src/features/public-api/server/withMiddlewares";-import { createAuthedAPIRoute } from "@/src/features/public-api/server/createAuthedAPIRoute";+import { createAuthedProjectAPIRoute } from "@/src/features/public-api/server/createAuthedProjectAPIRoute";import {type IngestionEventType,logger,@@ -17,7 +17,7 @@ export const config = {};export default withMiddlewares({- POST: createAuthedAPIRoute({+ POST: createAuthedProjectAPIRoute({name: "OTel Traces",querySchema: z.any(),responseSchema: z.any(),diff --git a/web/src/pages/api/public/projects.ts b/web/src/pages/api/public/projects.tsindex 53b5f73b9a..92fe5f3e31 100644--- a/web/src/pages/api/public/projects.ts+++ b/web/src/pages/api/public/projects.ts@@ -17,10 +17,16 @@ export default async function handler(prisma,redis,).verifyAuthHeaderAndReturnScope(req.headers.authorization);- if (!authCheck.validKey)+ if (!authCheck.validKey) {return res.status(401).json({message: authCheck.error,});+ }+ if (authCheck.scope.accessLevel === "project" || !authCheck.scope.projectId) {+ return res+ .status(403)+ .json({ message: "Invalid API key. Are you using an organization key?" });+ }// END CHECK AUTHif (req.method === "GET") {diff --git a/web/src/pages/api/public/prompts.ts b/web/src/pages/api/public/prompts.tsindex 70b6fa1e08..a5115df7ca 100644--- a/web/src/pages/api/public/prompts.ts+++ b/web/src/pages/api/public/prompts.ts@@ -42,10 +42,14 @@ export default async function handler().verifyAuthHeaderAndReturnScope(req.headers.authorization);if (!authCheck.validKey) throw new UnauthorizedError(authCheck.error);- if (authCheck.scope.accessLevel !== "all")+ if (+ authCheck.scope.accessLevel !== "project" ||+ !authCheck.scope.projectId+ ) {throw new ForbiddenError(- `Access denied - need to use basic auth with secret key to ${req.method} prompts`,+ `Access denied: Bearer auth and org api keys are not allowed to access`,);+ }await telemetry();diff --git a/web/src/pages/api/public/score-configs/[configId].ts b/web/src/pages/api/public/score-configs/[configId].tsindex 0c93152e29..f4c8849505 100644--- a/web/src/pages/api/public/score-configs/[configId].ts+++ b/web/src/pages/api/public/score-configs/[configId].ts@@ -1,4 +1,4 @@-import { createAuthedAPIRoute } from "@/src/features/public-api/server/createAuthedAPIRoute";+import { createAuthedProjectAPIRoute } from "@/src/features/public-api/server/createAuthedProjectAPIRoute";import { withMiddlewares } from "@/src/features/public-api/server/withMiddlewares";import {GetScoreConfigQuery,@@ -10,7 +10,7 @@ import { prisma } from "@langfuse/shared/src/db";import { traceException } from "@langfuse/shared/src/server";export default withMiddlewares({- GET: createAuthedAPIRoute({+ GET: createAuthedProjectAPIRoute({name: "Get a Score Config",querySchema: GetScoreConfigQuery,responseSchema: GetScoreConfigResponse,diff --git a/web/src/pages/api/public/score-configs/index.ts b/web/src/pages/api/public/score-configs/index.tsindex 633ae203e8..3c5a0c5086 100644--- a/web/src/pages/api/public/score-configs/index.ts+++ b/web/src/pages/api/public/score-configs/index.ts@@ -1,7 +1,7 @@import { v4 } from "uuid";import { type z } from "zod";-import { createAuthedAPIRoute } from "@/src/features/public-api/server/createAuthedAPIRoute";+import { createAuthedProjectAPIRoute } from "@/src/features/public-api/server/createAuthedProjectAPIRoute";import { withMiddlewares } from "@/src/features/public-api/server/withMiddlewares";import { isBooleanDataType } from "@/src/features/scores/lib/helpers";import {@@ -30,7 +30,7 @@ const inflateConfigBody = (body: z.infer<typeof PostScoreConfigBody>) => {};export default withMiddlewares({- POST: createAuthedAPIRoute({+ POST: createAuthedProjectAPIRoute({name: "Create Score Config",bodySchema: PostScoreConfigBody,responseSchema: PostScoreConfigResponse,@@ -59,7 +59,7 @@ export default withMiddlewares({return validateDbScoreConfig(config);},}),- GET: createAuthedAPIRoute({+ GET: createAuthedProjectAPIRoute({name: "Get Score Configs",querySchema: GetScoreConfigsQuery,responseSchema: GetScoreConfigsResponse,diff --git a/web/src/pages/api/public/scores/[scoreId].ts b/web/src/pages/api/public/scores/[scoreId].tsindex 46b5d145f3..2c78d7217a 100644--- a/web/src/pages/api/public/scores/[scoreId].ts+++ b/web/src/pages/api/public/scores/[scoreId].ts@@ -1,4 +1,4 @@-import { createAuthedAPIRoute } from "@/src/features/public-api/server/createAuthedAPIRoute";+import { createAuthedProjectAPIRoute } from "@/src/features/public-api/server/createAuthedProjectAPIRoute";import { withMiddlewares } from "@/src/features/public-api/server/withMiddlewares";import {DeleteScoreQuery,@@ -19,7 +19,7 @@ import { QueueJobs } from "@langfuse/shared/src/server";import { randomUUID } from "crypto";export default withMiddlewares({- GET: createAuthedAPIRoute({+ GET: createAuthedProjectAPIRoute({name: "Get Score",querySchema: GetScoreQuery,responseSchema: GetScoreResponse,@@ -41,7 +41,7 @@ export default withMiddlewares({return parsedScore.data;},}),- DELETE: createAuthedAPIRoute({+ DELETE: createAuthedProjectAPIRoute({name: "Delete Score",querySchema: DeleteScoreQuery,responseSchema: DeleteScoreResponse,diff --git a/web/src/pages/api/public/scores/index.ts b/web/src/pages/api/public/scores/index.tsindex 8b9d88be91..e79f496f59 100644--- a/web/src/pages/api/public/scores/index.ts+++ b/web/src/pages/api/public/scores/index.ts@@ -1,6 +1,6 @@import { v4 } from "uuid";-import { createAuthedAPIRoute } from "@/src/features/public-api/server/createAuthedAPIRoute";+import { createAuthedProjectAPIRoute } from "@/src/features/public-api/server/createAuthedProjectAPIRoute";import { withMiddlewares } from "@/src/features/public-api/server/withMiddlewares";import {GetScoresQuery,@@ -20,7 +20,7 @@ import {} from "@/src/features/public-api/server/scores";export default withMiddlewares({- POST: createAuthedAPIRoute({+ POST: createAuthedProjectAPIRoute({name: "Create Score",bodySchema: PostScoresBody,responseSchema: PostScoresResponse,@@ -49,7 +49,7 @@ export default withMiddlewares({return { id: event.body.id };},}),- GET: createAuthedAPIRoute({+ GET: createAuthedProjectAPIRoute({name: "/api/public/scores",querySchema: GetScoresQuery,responseSchema: GetScoresResponse,diff --git a/web/src/pages/api/public/sessions/[sessionId].ts b/web/src/pages/api/public/sessions/[sessionId].tsindex d6adfccf05..208f140700 100644--- a/web/src/pages/api/public/sessions/[sessionId].ts+++ b/web/src/pages/api/public/sessions/[sessionId].ts@@ -4,12 +4,12 @@ import {GetSessionV1Response,} from "@/src/features/public-api/types/sessions";import { withMiddlewares } from "@/src/features/public-api/server/withMiddlewares";-import { createAuthedAPIRoute } from "@/src/features/public-api/server/createAuthedAPIRoute";+import { createAuthedProjectAPIRoute } from "@/src/features/public-api/server/createAuthedProjectAPIRoute";import { LangfuseNotFoundError } from "@langfuse/shared";import { getTracesBySessionId } from "@langfuse/shared/src/server";export default withMiddlewares({- GET: createAuthedAPIRoute({+ GET: createAuthedProjectAPIRoute({name: "Get Session",querySchema: GetSessionV1Query,responseSchema: GetSessionV1Response,diff --git a/web/src/pages/api/public/sessions/index.ts b/web/src/pages/api/public/sessions/index.tsindex 1cd4f366e7..d6ce26470b 100644--- a/web/src/pages/api/public/sessions/index.ts+++ b/web/src/pages/api/public/sessions/index.ts@@ -4,10 +4,10 @@ import {GetSessionsV1Response,} from "@/src/features/public-api/types/sessions";import { withMiddlewares } from "@/src/features/public-api/server/withMiddlewares";-import { createAuthedAPIRoute } from "@/src/features/public-api/server/createAuthedAPIRoute";+import { createAuthedProjectAPIRoute } from "@/src/features/public-api/server/createAuthedProjectAPIRoute";export default withMiddlewares({- GET: createAuthedAPIRoute({+ GET: createAuthedProjectAPIRoute({name: "Get Sessions",querySchema: GetSessionsV1Query,responseSchema: GetSessionsV1Response,diff --git a/web/src/pages/api/public/spans.ts b/web/src/pages/api/public/spans.tsindex 5b179adcd2..8490dbdcb1 100644--- a/web/src/pages/api/public/spans.ts+++ b/web/src/pages/api/public/spans.ts@@ -5,7 +5,7 @@ import {PostSpansV1Response,} from "@/src/features/public-api/types/spans";import { withMiddlewares } from "@/src/features/public-api/server/withMiddlewares";-import { createAuthedAPIRoute } from "@/src/features/public-api/server/createAuthedAPIRoute";+import { createAuthedProjectAPIRoute } from "@/src/features/public-api/server/createAuthedProjectAPIRoute";import {eventTypes,logger,@@ -14,7 +14,7 @@ import {import { v4 } from "uuid";export default withMiddlewares({- POST: createAuthedAPIRoute({+ POST: createAuthedProjectAPIRoute({name: "Create Span (Legacy)",bodySchema: PostSpansV1Body,responseSchema: PostSpansV1Response,@@ -46,7 +46,7 @@ export default withMiddlewares({return { id: event.body.id };},}),- PATCH: createAuthedAPIRoute({+ PATCH: createAuthedProjectAPIRoute({name: "Update Span (Legacy)",bodySchema: PatchSpansV1Body,responseSchema: PatchSpansV1Response,diff --git a/web/src/pages/api/public/traces/[traceId].ts b/web/src/pages/api/public/traces/[traceId].tsindex 0fffa23c31..21ce5cfa5e 100644--- a/web/src/pages/api/public/traces/[traceId].ts+++ b/web/src/pages/api/public/traces/[traceId].ts@@ -1,4 +1,4 @@-import { createAuthedAPIRoute } from "@/src/features/public-api/server/createAuthedAPIRoute";+import { createAuthedProjectAPIRoute } from "@/src/features/public-api/server/createAuthedProjectAPIRoute";import { withMiddlewares } from "@/src/features/public-api/server/withMiddlewares";import { transformDbToApiObservation } from "@/src/features/public-api/types/observations";import {@@ -26,7 +26,7 @@ import { auditLog } from "@/src/features/audit-logs/auditLog";import { TRPCError } from "@trpc/server";export default withMiddlewares({- GET: createAuthedAPIRoute({+ GET: createAuthedProjectAPIRoute({name: "Get Single Trace",querySchema: GetTraceV1Query,responseSchema: GetTraceV1Response,@@ -136,7 +136,7 @@ export default withMiddlewares({},}),- DELETE: createAuthedAPIRoute({+ DELETE: createAuthedProjectAPIRoute({name: "Delete Single Trace",querySchema: DeleteTraceV1Query,responseSchema: DeleteTraceV1Response,diff --git a/web/src/pages/api/public/traces/index.ts b/web/src/pages/api/public/traces/index.tsindex 4d93138e99..f241053c4f 100644--- a/web/src/pages/api/public/traces/index.ts+++ b/web/src/pages/api/public/traces/index.ts@@ -7,7 +7,7 @@ import {DeleteTracesV1Response,} from "@/src/features/public-api/types/traces";import { withMiddlewares } from "@/src/features/public-api/server/withMiddlewares";-import { createAuthedAPIRoute } from "@/src/features/public-api/server/createAuthedAPIRoute";+import { createAuthedProjectAPIRoute } from "@/src/features/public-api/server/createAuthedProjectAPIRoute";import { processEventBatch } from "@langfuse/shared/src/server";import {@@ -28,7 +28,7 @@ import { randomUUID } from "crypto";import { auditLog } from "@/src/features/audit-logs/auditLog";export default withMiddlewares({- POST: createAuthedAPIRoute({+ POST: createAuthedProjectAPIRoute({name: "Create Trace (Legacy)",bodySchema: PostTracesV1Body,responseSchema: PostTracesV1Response, // Adjust this if you have a specific response schema@@ -60,7 +60,7 @@ export default withMiddlewares({},}),- GET: createAuthedAPIRoute({+ GET: createAuthedProjectAPIRoute({name: "Get Traces",querySchema: GetTracesV1Query,responseSchema: GetTracesV1Response,@@ -101,7 +101,7 @@ export default withMiddlewares({},}),- DELETE: createAuthedAPIRoute({+ DELETE: createAuthedProjectAPIRoute({name: "Delete Multiple Traces",bodySchema: DeleteTracesV1Body,responseSchema: DeleteTracesV1Response,diff --git a/web/src/pages/api/public/v2/datasets/[datasetName]/index.ts b/web/src/pages/api/public/v2/datasets/[datasetName]/index.tsindex 47f83c1a14..79cf069af6 100644--- a/web/src/pages/api/public/v2/datasets/[datasetName]/index.ts+++ b/web/src/pages/api/public/v2/datasets/[datasetName]/index.ts@@ -4,11 +4,11 @@ import {GetDatasetV2Response,} from "@/src/features/public-api/types/datasets";import { withMiddlewares } from "@/src/features/public-api/server/withMiddlewares";-import { createAuthedAPIRoute } from "@/src/features/public-api/server/createAuthedAPIRoute";+import { createAuthedProjectAPIRoute } from "@/src/features/public-api/server/createAuthedProjectAPIRoute";import { LangfuseNotFoundError } from "@langfuse/shared";export default withMiddlewares({- GET: createAuthedAPIRoute({+ GET: createAuthedProjectAPIRoute({name: "get-dataset",querySchema: GetDatasetV2Query,responseSchema: GetDatasetV2Response,diff --git a/web/src/pages/api/public/v2/datasets/index.ts b/web/src/pages/api/public/v2/datasets/index.tsindex 3982d95f58..8a3152af8a 100644--- a/web/src/pages/api/public/v2/datasets/index.ts+++ b/web/src/pages/api/public/v2/datasets/index.ts@@ -6,11 +6,11 @@ import {PostDatasetsV2Response,} from "@/src/features/public-api/types/datasets";import { withMiddlewares } from "@/src/features/public-api/server/withMiddlewares";-import { createAuthedAPIRoute } from "@/src/features/public-api/server/createAuthedAPIRoute";+import { createAuthedProjectAPIRoute } from "@/src/features/public-api/server/createAuthedProjectAPIRoute";import { auditLog } from "@/src/features/audit-logs/auditLog";export default withMiddlewares({- POST: createAuthedAPIRoute({+ POST: createAuthedProjectAPIRoute({name: "Create Dataset",bodySchema: PostDatasetsV2Body,responseSchema: PostDatasetsV2Response,@@ -49,7 +49,7 @@ export default withMiddlewares({return dataset;},}),- GET: createAuthedAPIRoute({+ GET: createAuthedProjectAPIRoute({name: "Get Datasets",querySchema: GetDatasetsV2Query,responseSchema: GetDatasetsV2Response,diff --git a/web/src/server/api/root.ts b/web/src/server/api/root.tsindex ffc7fe62a5..fcf22c60c2 100644--- a/web/src/server/api/root.ts+++ b/web/src/server/api/root.ts@@ -4,7 +4,7 @@ import { generationsRouter } from "./routers/generations";import { scoresRouter } from "./routers/scores";import { dashboardRouter } from "@/src/features/dashboard/server/dashboard-router";import { projectsRouter } from "@/src/features/projects/server/projectsRouter";-import { apiKeysRouter } from "@/src/features/public-api/server/apiKeyRouter";+import { projectApiKeysRouter } from "@/src/features/public-api/server/projectApiKeyRouter";import { membersRouter } from "@/src/features/rbac/server/membersRouter";import { userRouter } from "@/src/server/api/routers/users";import { datasetRouter } from "@/src/features/datasets/server/dataset-router";@@ -55,7 +55,7 @@ export const appRouter = createTRPCRouter({organizations: organizationsRouter,projects: projectsRouter,users: userRouter,- apiKeys: apiKeysRouter,+ projectApiKeys: projectApiKeysRouter,members: membersRouter,datasets: datasetRouter,cloudBilling: cloudBillingRouter,diff --git a/worker/src/__tests__/experimentsService.test.ts b/worker/src/__tests__/experimentsService.test.tsindex bb96845a1e..8c93956fdb 100644--- a/worker/src/__tests__/experimentsService.test.ts+++ b/worker/src/__tests__/experimentsService.test.ts@@ -414,7 +414,7 @@ describe("create experiment job calls with langfuse server side tracing", asyncvalidKey: true,scope: expect.objectContaining({projectId: mockEvent.projectId,- accessLevel: "all",+ accessLevel: "project",}),}),}),diff --git a/worker/src/ee/evaluation/evalService.ts b/worker/src/ee/evaluation/evalService.tsindex 1d259c1d14..ccc1576ef8 100644--- a/worker/src/ee/evaluation/evalService.ts+++ b/worker/src/ee/evaluation/evalService.ts@@ -517,7 +517,6 @@ export const evaluate = async ({validKey: true,scope: {projectId: event.projectId,- accessLevel: "scores",},},},diff --git a/worker/src/ee/experiments/experimentService.ts b/worker/src/ee/experiments/experimentService.tsindex cc3302a3c2..a27c6c6d2a 100644--- a/worker/src/ee/experiments/experimentService.ts+++ b/worker/src/ee/experiments/experimentService.ts@@ -283,7 +283,7 @@ export const createExperimentJob = async ({validKey: true as const,scope: {projectId: event.projectId,- accessLevel: "all",+ accessLevel: "project",} as any,},};diff --git a/worker/src/scripts/refill-ingestion-events.ts b/worker/src/scripts/refill-ingestion-events.tsindex 54b9accd84..dd7ddee4e9 100644--- a/worker/src/scripts/refill-ingestion-events.ts+++ b/worker/src/scripts/refill-ingestion-events.ts@@ -73,7 +73,7 @@ const main = async () => {validKey: true as const,scope: {projectId: projectId,- accessLevel: "all" as const,+ accessLevel: "project" as const,},},},