🪢 Open source agent evals & observability: Trace, evaluate, and improve LLM applications with one open platform.
TypeScript analyticsautogenevaluationlangchainlarge-language-modelsllama-indexllmllm-evaluationllm-observabilityllmopsmonitoringobservabilityopen-sourceopenaiplaygroundprompt-engineeringprompt-managementself-hostedycombinator
feat: allow list of org api keys using org api keys (#10130)
Steffen Schmitzcb8650a3c7b5
diff --git a/fern/apis/server/definition/organizations.yml b/fern/apis/server/definition/organizations.ymlindex 49c18bdb51..abd54ae307 100644--- a/fern/apis/server/definition/organizations.yml+++ b/fern/apis/server/definition/organizations.yml@@ -59,6 +59,12 @@ service:path: /organizations/projectsresponse: OrganizationProjectsResponse+ getOrganizationApiKeys:+ docs: Get all API keys for the organization associated with the API key (requires organization-scoped API key)+ method: GET+ path: /organizations/apiKeys+ response: OrganizationApiKeysResponse+types:MembershipRole:enum:@@ -102,4 +108,18 @@ types:OrganizationProjectsResponse:properties:- projects: list<OrganizationProject>\ No newline at end of file+ projects: list<OrganizationProject>++ OrganizationApiKey:+ properties:+ id: string+ createdAt: datetime+ expiresAt: optional<datetime>+ lastUsedAt: optional<datetime>+ note: optional<string>+ publicKey: string+ displaySecretKey: string++ OrganizationApiKeysResponse:+ properties:+ apiKeys: list<OrganizationApiKey>diff --git a/web/public/generated/api/openapi.yml b/web/public/generated/api/openapi.ymlindex 9885ad97a9..b0a7b20ad4 100644--- a/web/public/generated/api/openapi.yml+++ b/web/public/generated/api/openapi.yml@@ -2922,6 +2922,49 @@ paths:schema: {}security:- BasicAuth: []+ /api/public/organizations/apiKeys:+ get:+ description: >-+ Get all API keys for the organization associated with the API key+ (requires organization-scoped API key)+ operationId: organizations_getOrganizationApiKeys+ tags:+ - Organizations+ parameters: []+ responses:+ '200':+ description: ''+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/OrganizationApiKeysResponse'+ '400':+ description: ''+ content:+ application/json:+ schema: {}+ '401':+ description: ''+ content:+ application/json:+ schema: {}+ '403':+ description: ''+ content:+ application/json:+ schema: {}+ '404':+ description: ''+ content:+ application/json:+ schema: {}+ '405':+ description: ''+ content:+ application/json:+ schema: {}+ security:+ - BasicAuth: []/api/public/projects:get:description: Get Project associated with API key@@ -7826,6 +7869,45 @@ components:$ref: '#/components/schemas/OrganizationProject'required:- projects+ OrganizationApiKey:+ title: OrganizationApiKey+ type: object+ properties:+ id:+ type: string+ createdAt:+ type: string+ format: date-time+ expiresAt:+ type: string+ format: date-time+ nullable: true+ lastUsedAt:+ type: string+ format: date-time+ nullable: true+ note:+ type: string+ nullable: true+ publicKey:+ type: string+ displaySecretKey:+ type: string+ required:+ - id+ - createdAt+ - publicKey+ - displaySecretKey+ OrganizationApiKeysResponse:+ title: OrganizationApiKeysResponse+ type: object+ properties:+ apiKeys:+ type: array+ items:+ $ref: '#/components/schemas/OrganizationApiKey'+ required:+ - apiKeysProjects:title: Projectstype: objectdiff --git a/web/public/generated/postman/collection.json b/web/public/generated/postman/collection.jsonindex 7a83f4c830..cd85390898 100644--- a/web/public/generated/postman/collection.json+++ b/web/public/generated/postman/collection.json@@ -2172,6 +2172,32 @@"body": null},"response": []+ },+ {+ "_type": "endpoint",+ "name": "Get Organization Api Keys",+ "request": {+ "description": "Get all API keys for the organization associated with the API key (requires organization-scoped API key)",+ "url": {+ "raw": "{{baseUrl}}/api/public/organizations/apiKeys",+ "host": [+ "{{baseUrl}}"+ ],+ "path": [+ "api",+ "public",+ "organizations",+ "apiKeys"+ ],+ "query": [],+ "variable": []+ },+ "header": [],+ "method": "GET",+ "auth": null,+ "body": null+ },+ "response": []}]},diff --git a/web/src/__tests__/async/organizations-api.servertest.ts b/web/src/__tests__/async/organizations-api.servertest.tsindex 2bff297e85..e82dd1cf64 100644--- a/web/src/__tests__/async/organizations-api.servertest.ts+++ b/web/src/__tests__/async/organizations-api.servertest.ts@@ -1089,4 +1089,230 @@ describe("Public Organizations API", () => {});});});++ describe("GET /api/public/organizations/apiKeys", () => {+ let testOrgId: string;+ let testApiKey: string;+ let testApiSecretKey: string;+ let secondOrgId: string;+ let secondOrgApiKey: string;+ let secondOrgApiSecretKey: string;++ beforeAll(async () => {+ // Create first test organization with API keys+ const uniqueOrgName = `Test Org ${randomUUID().substring(0, 8)}`;+ const org = await prisma.organization.create({+ data: {+ name: uniqueOrgName,+ cloudConfig: { plan: "Team" },+ metadata: {},+ },+ });+ testOrgId = org.id;++ // Create an organization API key for authentication+ const orgApiKey = await createAndAddApiKeysToDb({+ prisma,+ entityId: testOrgId,+ note: "Org API Key for testing",+ scope: "ORGANIZATION",+ });+ testApiKey = orgApiKey.publicKey;+ testApiSecretKey = orgApiKey.secretKey;++ // Create additional organization API keys to list+ await createAndAddApiKeysToDb({+ prisma,+ entityId: testOrgId,+ note: "First test key",+ scope: "ORGANIZATION",+ });++ await createAndAddApiKeysToDb({+ prisma,+ entityId: testOrgId,+ note: "Second test key",+ scope: "ORGANIZATION",+ });++ // Create second organization with its own API keys (for isolation test)+ const secondOrg = await prisma.organization.create({+ data: {+ name: `Second Test Org ${randomUUID().substring(0, 8)}`,+ cloudConfig: { plan: "Team" },+ metadata: {},+ },+ });+ secondOrgId = secondOrg.id;++ const secondOrgKey = await createAndAddApiKeysToDb({+ prisma,+ entityId: secondOrgId,+ note: "Second org API key",+ scope: "ORGANIZATION",+ });+ secondOrgApiKey = secondOrgKey.publicKey;+ secondOrgApiSecretKey = secondOrgKey.secretKey;+ });++ afterAll(async () => {+ // Clean up first org+ await prisma.apiKey.deleteMany({+ where: { orgId: testOrgId },+ });+ await prisma.organization+ .delete({+ where: { id: testOrgId },+ })+ .catch(() => {+ /* ignore if already deleted */+ });++ // Clean up second org+ await prisma.apiKey.deleteMany({+ where: { orgId: secondOrgId },+ });+ await prisma.organization+ .delete({+ where: { id: secondOrgId },+ })+ .catch(() => {+ /* ignore if already deleted */+ });+ });++ it("should successfully list organization API keys with valid org API key", async () => {+ const response = await makeZodVerifiedAPICall(+ ApiKeyListSchema,+ "GET",+ `/api/public/organizations/apiKeys`,+ undefined,+ createBasicAuthHeader(testApiKey, testApiSecretKey),+ 200,+ );++ expect(response.status).toBe(200);+ expect(Array.isArray(response.body.apiKeys)).toBe(true);+ expect(response.body.apiKeys.length).toBe(3); // Auth key + 2 test keys++ // Verify the structure of returned API keys+ const apiKeys = response.body.apiKeys;+ expect(apiKeys[0]).toHaveProperty("id");+ expect(apiKeys[0]).toHaveProperty("createdAt");+ expect(apiKeys[0]).toHaveProperty("expiresAt");+ expect(apiKeys[0]).toHaveProperty("lastUsedAt");+ expect(apiKeys[0]).toHaveProperty("note");+ expect(apiKeys[0]).toHaveProperty("publicKey");+ expect(apiKeys[0]).toHaveProperty("displaySecretKey");++ // Verify note values+ const notes = apiKeys.map((key) => key.note);+ expect(notes).toContain("Org API Key for testing");+ expect(notes).toContain("First test key");+ expect(notes).toContain("Second test key");+ });++ it("should only return API keys for authenticated organization (data isolation)", async () => {+ // Use the second org's API key to list its keys+ const response = await makeZodVerifiedAPICall(+ ApiKeyListSchema,+ "GET",+ `/api/public/organizations/apiKeys`,+ undefined,+ createBasicAuthHeader(secondOrgApiKey, secondOrgApiSecretKey),+ 200,+ );++ expect(response.status).toBe(200);+ expect(response.body.apiKeys.length).toBe(1); // Only the second org's key+ expect(response.body.apiKeys[0].note).toBe("Second org API key");++ // Verify it doesn't include keys from the first org+ const notes = response.body.apiKeys.map((key) => key.note);+ expect(notes).not.toContain("Org API Key for testing");+ expect(notes).not.toContain("First test key");+ expect(notes).not.toContain("Second test key");+ });++ it("should reject request with project API key (wrong scope)", async () => {+ // Create a project and project API key+ const project = await prisma.project.create({+ data: {+ name: `Test Project ${randomUUID().substring(0, 8)}`,+ orgId: testOrgId,+ },+ });++ const projectApiKey = await createAndAddApiKeysToDb({+ prisma,+ entityId: project.id,+ note: "Project API key",+ scope: "PROJECT",+ });++ const response = await makeAPICall(+ "GET",+ `/api/public/organizations/apiKeys`,+ undefined,+ createBasicAuthHeader(projectApiKey.publicKey, projectApiKey.secretKey),+ );++ expect(response.status).toBe(403);+ expect(response.body.error).toContain(+ "Organization-scoped API key required",+ );++ // Clean up+ await prisma.apiKey.delete({+ where: { id: projectApiKey.id },+ });+ await prisma.project.delete({+ where: { id: project.id },+ });+ });++ it("should reject request with invalid API key", async () => {+ const response = await makeAPICall(+ "GET",+ `/api/public/organizations/apiKeys`,+ undefined,+ createBasicAuthHeader("invalid-public-key", "invalid-secret-key"),+ );++ expect(response.status).toBe(401);+ });++ it("should only allow GET method", async () => {+ const response = await makeAPICall(+ "POST",+ `/api/public/organizations/apiKeys`,+ {},+ createBasicAuthHeader(testApiKey, testApiSecretKey),+ );++ expect(response.status).toBe(405);+ expect(response.body.error).toContain("Method not allowed");+ });++ it("should return API keys ordered by createdAt ascending", async () => {+ const response = await makeZodVerifiedAPICall(+ ApiKeyListSchema,+ "GET",+ `/api/public/organizations/apiKeys`,+ undefined,+ createBasicAuthHeader(testApiKey, testApiSecretKey),+ 200,+ );++ expect(response.status).toBe(200);+ const apiKeys = response.body.apiKeys;++ // Verify ordering by comparing timestamps+ for (let i = 0; i < apiKeys.length - 1; i++) {+ const currentDate = new Date(apiKeys[i].createdAt);+ const nextDate = new Date(apiKeys[i + 1].createdAt);+ expect(currentDate.getTime()).toBeLessThanOrEqual(nextDate.getTime());+ }+ });+ });});diff --git a/web/src/pages/api/public/organizations/apiKeys/index.ts b/web/src/pages/api/public/organizations/apiKeys/index.tsnew file mode 100644index 0000000000..3b2343ea43--- /dev/null+++ b/web/src/pages/api/public/organizations/apiKeys/index.ts@@ -0,0 +1,71 @@+import { ApiAuthService } from "@/src/features/public-api/server/apiAuth";+import { cors, runMiddleware } from "@/src/features/public-api/server/cors";+import { prisma } from "@langfuse/shared/src/db";+import { logger, redis } from "@langfuse/shared/src/server";+import { handleGetApiKeys } from "@/src/ee/features/admin-api/server/organizations/apiKeys";++import { type NextApiRequest, type NextApiResponse } from "next";+import { hasEntitlementBasedOnPlan } from "@/src/features/entitlements/server/hasEntitlement";++export default async function handler(+ req: NextApiRequest,+ res: NextApiResponse,+) {+ await runMiddleware(req, res, cors);++ if (req.method !== "GET") {+ logger.error(+ `Method not allowed for ${req.method} on /api/public/organizations/apiKeys`,+ );+ return res.status(405).json({+ error: "Method not allowed",+ });+ }++ // CHECK AUTH+ const authCheck = await new ApiAuthService(+ prisma,+ redis,+ ).verifyAuthHeaderAndReturnScope(req.headers.authorization);+ if (!authCheck.validKey) {+ return res.status(401).json({+ error: authCheck.error,+ });+ }+ // END CHECK AUTH++ // Check if using an organization API key+ if (+ authCheck.scope.accessLevel !== "organization" ||+ !authCheck.scope.orgId+ ) {+ return res.status(403).json({+ error:+ "Invalid API key. Organization-scoped API key required for this operation.",+ });+ }++ if (+ !hasEntitlementBasedOnPlan({+ plan: authCheck.scope.plan,+ entitlement: "admin-api",+ })+ ) {+ return res.status(403).json({+ error: "This feature is not available on your current plan.",+ });+ }++ // Route to the handler+ try {+ return handleGetApiKeys(req, res, authCheck.scope.orgId);+ } catch (error) {+ logger.error(+ `Error handling organization API keys for ${req.method}`,+ error,+ );+ return res.status(500).json({+ error: "Internal server error",+ });+ }+}