🪢 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
security(api-keys): gate organization API key creation on the admin-api entitlement (#16596)
Steffen Schmitzc8d72e7213b0
diff --git a/web/src/__tests__/server/organizations-api-key-trpc.servertest.ts b/web/src/__tests__/server/organizations-api-key-trpc.servertest.tsindex 8b7d6101af..f5575590aa 100644--- a/web/src/__tests__/server/organizations-api-key-trpc.servertest.ts+++ b/web/src/__tests__/server/organizations-api-key-trpc.servertest.ts@@ -10,6 +10,7 @@ import { appRouter } from "@/src/server/api/root";import { createInnerTRPCContext } from "@/src/server/api/trpc";import { TRPCError } from "@trpc/server";import { createAndAddApiKeysToDb } from "@langfuse/shared/src/server";+import { randomUUID } from "crypto";describe("organization API keys trpc", () => {const organizationId = "seed-org-id";@@ -31,6 +32,9 @@ describe("organization API keys trpc", () => {});});+ // Instance admins bypass both RBAC and entitlement checks, so this session+ // cannot cover plan gating. `entitledOwnerCaller` / `unentitledOwnerCaller`+ // below are the non-admin owners used for that.const ownerSession: Session = {expires: "1",user: {@@ -130,6 +134,48 @@ describe("organization API keys trpc", () => {const unAuthedCtx = createInnerTRPCContext({ session: null, headers: {} });const unAuthedCaller = appRouter.createCaller({ ...unAuthedCtx, prisma });+ // Organization-scoped API keys are a paid feature (`admin-api` entitlement).+ // These owners are deliberately not instance admins so the plan gate applies.+ const ownerSessionOnPlan = (plan: SessionOrg["plan"]): Session => ({+ expires: "1",+ user: {+ id: "user-1",+ canCreateOrganizations: true,+ name: "Demo User",+ organizations: [+ {+ id: organizationId,+ name: "Test Organization",+ role: "OWNER",+ plan,+ cloudConfig: undefined,+ metadata: {},+ projects: [] as SessionOrg["projects"],+ } as SessionOrg,+ ],+ featureFlags: {+ excludeClickhouseRead: false,+ templateFlag: true,+ } as SessionFeatureFlags,+ admin: false,+ },+ environment: {} as any,+ });++ const callerForSession = (session: Session) =>+ appRouter.createCaller({+ ...createInnerTRPCContext({ session, headers: {} }),+ prisma,+ });++ // cloud:hobby lacks `admin-api`; cloud:team carries it.+ const unentitledOwnerCaller = callerForSession(+ ownerSessionOnPlan("cloud:hobby"),+ );+ const entitledOwnerCaller = callerForSession(+ ownerSessionOnPlan("cloud:team"),+ );+describe("organizationApiKeys.byOrganizationId", () => {it("owner can fetch organization API keys", async () => {// Create a test API key first@@ -257,6 +303,42 @@ describe("organization API keys trpc", () => {}),).rejects.toThrow(TRPCError);});++ it("owner on a plan without admin-api cannot create organization API keys", async () => {+ // Unique note so the persistence assertion stays independent of other+ // tests and of keys left behind by earlier runs.+ const note = `unentitled-create-${randomUUID()}`;++ await expect(+ unentitledOwnerCaller.organizationApiKeys.create({+ orgId: organizationId,+ note,+ }),+ ).rejects.toThrow(+ expect.objectContaining({+ code: "FORBIDDEN",+ message: expect.stringContaining("admin-api"),+ }),+ );++ // The rejection must happen before the key is persisted, otherwise the+ // plan gate would only hide a key that already works.+ await expect(+ prisma.apiKey.findFirst({ where: { orgId: organizationId, note } }),+ ).resolves.toBeNull();+ });++ it("owner on a plan with admin-api can create organization API keys", async () => {+ const apiKeyResult = await entitledOwnerCaller.organizationApiKeys.create(+ {+ orgId: organizationId,+ note: "Entitled plan key",+ },+ );++ expect(apiKeyResult.secretKey).toBeDefined();+ expect(apiKeyResult.publicKey).toBeDefined();+ });});describe("organizationApiKeys.updateNote", () => {@@ -416,5 +498,32 @@ describe("organization API keys trpc", () => {}),).rejects.toThrow(TRPCError);});++ it("owner on a plan without admin-api can still list and revoke existing keys", async () => {+ // Only creation is plan-gated. A downgraded organization must keep the+ // ability to see and revoke keys that were issued while entitled,+ // otherwise a downgrade would strand live credentials.+ const existingKey = await createAndAddApiKeysToDb({+ prisma,+ entityId: organizationId,+ scope: "ORGANIZATION",+ note: "Issued before downgrade",+ });++ const apiKeys =+ await unentitledOwnerCaller.organizationApiKeys.byOrganizationId({+ orgId: organizationId,+ });+ expect(apiKeys.map((key) => key.id)).toContain(existingKey.id);++ await unentitledOwnerCaller.organizationApiKeys.delete({+ orgId: organizationId,+ id: existingKey.id,+ });++ await expect(+ prisma.apiKey.findUnique({ where: { id: existingKey.id } }),+ ).resolves.toBeNull();+ });});});diff --git a/web/src/features/public-api/server/organizationApiKeyRouter.ts b/web/src/features/public-api/server/organizationApiKeyRouter.tsindex c6ee1a1bb5..ff9052ff69 100644--- a/web/src/features/public-api/server/organizationApiKeyRouter.ts+++ b/web/src/features/public-api/server/organizationApiKeyRouter.ts@@ -1,5 +1,6 @@import { auditLog } from "@/src/features/audit-logs/auditLog";import { throwIfNoOrganizationAccess } from "@/src/features/rbac/utils/checkOrganizationAccess";+import { throwIfNoEntitlement } from "@/src/features/entitlements/server/hasEntitlement";import {createTRPCRouter,protectedOrganizationProcedure,@@ -69,6 +70,14 @@ export const organizationApiKeysRouter = createTRPCRouter({organizationId: input.orgId,scope: "organization:CRUD_apiKeys",});+ // Issuing organization-scoped keys is a paid feature. Reads and deletes+ // stay ungated so a downgraded organization can still revoke keys that+ // were issued while it was entitled.+ throwIfNoEntitlement({+ entitlement: "admin-api",+ sessionUser: ctx.session.user,+ orgId: input.orgId,+ });const apiKeyMeta = await createAndAddApiKeysToDb({prisma: ctx.prisma,