🪢 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 org api key management via admin api (#6437)
Steffen Schmitz64827a0c9d39
diff --git a/fern/apis/organizations/definition/organizations.yml b/fern/apis/organizations/definition/organizations.ymlindex 8255402a5e..6b28fbb3ae 100644--- a/fern/apis/organizations/definition/organizations.yml+++ b/fern/apis/organizations/definition/organizations.yml@@ -71,6 +71,51 @@ service:- commons.UnauthorizedError- commons.MethodNotAllowedError+ # API Key endpoints+ getApiKeys:+ docs: Get all API keys for an organization+ method: GET+ path: /organizations/{organizationId}/apiKeys+ path-parameters:+ organizationId: string+ response: ApiKeyList+ errors:+ - commons.Error+ - commons.UnauthorizedError+ - commons.MethodNotAllowedError++ createApiKey:+ docs: Create a new API key for an organization+ method: POST+ path: /organizations/{organizationId}/apiKeys+ path-parameters:+ organizationId: string+ request:+ name: CreateApiKeyRequest+ body:+ properties:+ note:+ type: optional<string>+ docs: Optional note for the API key+ response: ApiKeyResponse+ errors:+ - commons.Error+ - commons.UnauthorizedError+ - commons.MethodNotAllowedError++ deleteApiKey:+ docs: Delete an API key for an organization+ method: DELETE+ path: /organizations/{organizationId}/apiKeys/{apiKeyId}+ path-parameters:+ organizationId: string+ apiKeyId: string+ response: DeleteOrganizationResponse+ errors:+ - commons.Error+ - commons.UnauthorizedError+ - commons.MethodNotAllowedError+types:Organizations:docs: List of organizations@@ -83,8 +128,34 @@ types:id: stringname: stringcreatedAt: datetime-+DeleteOrganizationResponse:docs: Response for successful organization deletionproperties:success: boolean++ ApiKeyList:+ docs: List of API keys for an organization+ properties:+ apiKeys: list<ApiKeySummary>++ ApiKeySummary:+ docs: Summary of an API key+ properties:+ id: string+ createdAt: datetime+ expiresAt: optional<datetime>+ lastUsedAt: optional<datetime>+ note: optional<string>+ publicKey: string+ displaySecretKey: string++ ApiKeyResponse:+ docs: Response for API key creation+ properties:+ id: string+ createdAt: datetime+ publicKey: string+ secretKey: string+ displaySecretKey: string+ note: optional<string>diff --git a/packages/shared/src/server/auth/apiKeys.ts b/packages/shared/src/server/auth/apiKeys.tsindex 20809efcb8..f6f4bba41f 100644--- a/packages/shared/src/server/auth/apiKeys.ts+++ b/packages/shared/src/server/auth/apiKeys.ts@@ -38,7 +38,7 @@ export function createShaHash(privateKey: string, salt: string): string {export async function createAndAddApiKeysToDb(p: {prisma: PrismaClient;- projectId: string;+ entityId: string;scope: ApiKeyScope;note?: string;predefinedKeys?: {@@ -60,9 +60,12 @@ export async function createAndAddApiKeysToDb(p: {const hashFromProvidedKey = createShaHash(sk, salt);+ const entity =+ p.scope === "PROJECT" ? { projectId: p.entityId } : { orgId: p.entityId };+const apiKey = await p.prisma.apiKey.create({data: {- projectId: p.projectId,+ ...entity,publicKey: pk,hashedSecretKey: hashedSk,displaySecretKey: displaySk,diff --git a/web/public/generated/organizations-api/openapi.yml b/web/public/generated/organizations-api/openapi.ymlindex a17d5cd386..7449dfd642 100644--- a/web/public/generated/organizations-api/openapi.yml+++ b/web/public/generated/organizations-api/openapi.yml@@ -261,6 +261,153 @@ paths:schema:type: stringsecurity: *ref_0+ /api/admin/organizations/{organizationId}/apiKeys:+ get:+ description: Get all API keys for an organization+ operationId: organizations_getApiKeys+ tags:+ - Organizations+ parameters:+ - name: organizationId+ in: path+ required: true+ schema:+ type: string+ responses:+ '200':+ description: ''+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/ApiKeyList'+ '400':+ description: ''+ content:+ application/json:+ schema:+ type: string+ '401':+ description: ''+ content:+ application/json:+ schema:+ type: string+ '403':+ description: ''+ content:+ application/json:+ schema:+ type: string+ '405':+ description: ''+ content:+ application/json:+ schema:+ type: string+ security: *ref_0+ post:+ description: Create a new API key for an organization+ operationId: organizations_createApiKey+ tags:+ - Organizations+ parameters:+ - name: organizationId+ in: path+ required: true+ schema:+ type: string+ responses:+ '200':+ description: ''+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/ApiKeyResponse'+ '400':+ description: ''+ content:+ application/json:+ schema:+ type: string+ '401':+ description: ''+ content:+ application/json:+ schema:+ type: string+ '403':+ description: ''+ content:+ application/json:+ schema:+ type: string+ '405':+ description: ''+ content:+ application/json:+ schema:+ type: string+ security: *ref_0+ requestBody:+ required: true+ content:+ application/json:+ schema:+ type: object+ properties:+ note:+ type: string+ nullable: true+ description: Optional note for the API key+ /api/admin/organizations/{organizationId}/apiKeys/{apiKeyId}:+ delete:+ description: Delete an API key for an organization+ operationId: organizations_deleteApiKey+ tags:+ - Organizations+ parameters:+ - name: organizationId+ in: path+ required: true+ schema:+ type: string+ - name: apiKeyId+ in: path+ required: true+ schema:+ type: string+ responses:+ '200':+ description: ''+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/DeleteOrganizationResponse'+ '400':+ description: ''+ content:+ application/json:+ schema:+ type: string+ '401':+ description: ''+ content:+ application/json:+ schema:+ type: string+ '403':+ description: ''+ content:+ application/json:+ schema:+ type: string+ '405':+ description: ''+ content:+ application/json:+ schema:+ type: string+ security: *ref_0components:schemas:Organizations:@@ -299,6 +446,72 @@ components:type: booleanrequired:- success+ ApiKeyList:+ title: ApiKeyList+ type: object+ description: List of API keys for an organization+ properties:+ apiKeys:+ type: array+ items:+ $ref: '#/components/schemas/ApiKeySummary'+ required:+ - apiKeys+ ApiKeySummary:+ title: ApiKeySummary+ type: object+ description: Summary of an API key+ 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+ ApiKeyResponse:+ title: ApiKeyResponse+ type: object+ description: Response for API key creation+ properties:+ id:+ type: string+ createdAt:+ type: string+ format: date-time+ publicKey:+ type: string+ secretKey:+ type: string+ displaySecretKey:+ type: string+ note:+ type: string+ nullable: true+ required:+ - id+ - createdAt+ - publicKey+ - secretKey+ - displaySecretKeysecuritySchemes:BearerAuth:type: httpdiff --git a/web/public/generated/organizations-postman/collection.json b/web/public/generated/organizations-postman/collection.jsonindex d54763e96b..25419732d8 100644--- a/web/public/generated/organizations-postman/collection.json+++ b/web/public/generated/organizations-postman/collection.json@@ -193,6 +193,119 @@"body": null},"response": []+ },+ {+ "_type": "endpoint",+ "name": "Get Api Keys",+ "request": {+ "description": "Get all API keys for an organization",+ "url": {+ "raw": "{{baseUrl}}/api/admin/organizations/:organizationId/apiKeys",+ "host": [+ "{{baseUrl}}"+ ],+ "path": [+ "api",+ "admin",+ "organizations",+ ":organizationId",+ "apiKeys"+ ],+ "query": [],+ "variable": [+ {+ "key": "organizationId",+ "value": "",+ "description": null+ }+ ]+ },+ "header": [],+ "method": "GET",+ "auth": null,+ "body": null+ },+ "response": []+ },+ {+ "_type": "endpoint",+ "name": "Create Api Key",+ "request": {+ "description": "Create a new API key for an organization",+ "url": {+ "raw": "{{baseUrl}}/api/admin/organizations/:organizationId/apiKeys",+ "host": [+ "{{baseUrl}}"+ ],+ "path": [+ "api",+ "admin",+ "organizations",+ ":organizationId",+ "apiKeys"+ ],+ "query": [],+ "variable": [+ {+ "key": "organizationId",+ "value": "",+ "description": null+ }+ ]+ },+ "header": [],+ "method": "POST",+ "auth": null,+ "body": {+ "mode": "raw",+ "raw": "{\n \"note\": \"example\"\n}",+ "options": {+ "raw": {+ "language": "json"+ }+ }+ }+ },+ "response": []+ },+ {+ "_type": "endpoint",+ "name": "Delete Api Key",+ "request": {+ "description": "Delete an API key for an organization",+ "url": {+ "raw": "{{baseUrl}}/api/admin/organizations/:organizationId/apiKeys/:apiKeyId",+ "host": [+ "{{baseUrl}}"+ ],+ "path": [+ "api",+ "admin",+ "organizations",+ ":organizationId",+ "apiKeys",+ ":apiKeyId"+ ],+ "query": [],+ "variable": [+ {+ "key": "organizationId",+ "value": "",+ "description": null+ },+ {+ "key": "apiKeyId",+ "value": "",+ "description": null+ }+ ]+ },+ "header": [],+ "method": "DELETE",+ "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 a3560a4d05..87589233ba 100644--- a/web/src/__tests__/async/organizations-api.servertest.ts+++ b/web/src/__tests__/async/organizations-api.servertest.ts@@ -25,6 +25,31 @@ const DeleteResponseSchema = z.object({success: z.boolean(),});+// Schema for API key response+const ApiKeyResponseSchema = z.object({+ id: z.string(),+ createdAt: z.string().datetime(),+ publicKey: z.string(),+ secretKey: z.string(),+ displaySecretKey: z.string(),+ note: z.string().optional().nullable(),+});++// Schema for API key list response+const ApiKeyListSchema = z.object({+ apiKeys: z.array(+ z.object({+ id: z.string(),+ createdAt: z.string().datetime(),+ expiresAt: z.string().datetime().nullable(),+ lastUsedAt: z.string().datetime().nullable(),+ note: z.string().nullable(),+ publicKey: z.string(),+ displaySecretKey: z.string(),+ }),+ ),+});+describe("Admin Organizations API", () => {const ADMIN_API_KEY = process.env.ADMIN_API_KEY;@@ -408,6 +433,254 @@ describe("Admin Organizations API", () => {});});+ describe("GET /api/admin/organizations/[organizationId]/apiKeys", () => {+ let testOrgId: string;++ beforeAll(async () => {+ // Create a test organization+ const uniqueOrgName = `Test Org ${randomUUID().substring(0, 8)}`;+ const org = await prisma.organization.create({+ data: { name: uniqueOrgName },+ });+ testOrgId = org.id;++ // Create a test API key for the organization+ await prisma.apiKey.create({+ data: {+ orgId: testOrgId,+ publicKey: `pk-lf-test-${randomUUID()}`,+ hashedSecretKey: "hashed-secret",+ displaySecretKey: "sk-lf-test...1234",+ note: "Test API Key",+ scope: "ORGANIZATION",+ },+ });+ });++ afterAll(async () => {+ // Clean up test organization and its API keys+ await prisma.apiKey.deleteMany({+ where: { orgId: testOrgId },+ });+ await prisma.organization+ .delete({+ where: { id: testOrgId },+ })+ .catch(() => {+ /* ignore if already deleted */+ });+ });++ it("should get all API keys for an organization with valid admin authentication", async () => {+ const response = await makeZodVerifiedAPICall(+ ApiKeyListSchema,+ "GET",+ `/api/admin/organizations/${testOrgId}/apiKeys`,+ undefined,+ `Bearer ${ADMIN_API_KEY}`,+ 200,+ );++ expect(response.status).toBe(200);+ expect(Array.isArray(response.body.apiKeys)).toBe(true);+ expect(response.body.apiKeys.length).toBeGreaterThan(0);+ expect(response.body.apiKeys[0].note).toBe("Test API Key");+ });++ it("should return 404 when getting API keys for a non-existent organization", async () => {+ const nonExistentId = randomUUID();+ const result = await makeAPICall(+ "GET",+ `/api/admin/organizations/${nonExistentId}/apiKeys`,+ undefined,+ `Bearer ${ADMIN_API_KEY}`,+ );++ expect(result.status).toBe(404);+ expect(result.body.error).toContain("Organization not found");+ });+ });++ describe("POST /api/admin/organizations/[organizationId]/apiKeys", () => {+ let testOrgId: string;++ beforeEach(async () => {+ // Create a test organization+ const uniqueOrgName = `Test Org ${randomUUID().substring(0, 8)}`;+ const org = await prisma.organization.create({+ data: { name: uniqueOrgName },+ });+ testOrgId = org.id;+ });++ afterEach(async () => {+ // Clean up test API keys and organization+ await prisma.apiKey.deleteMany({+ where: { orgId: testOrgId },+ });+ await prisma.organization+ .delete({+ where: { id: testOrgId },+ })+ .catch(() => {+ /* ignore if already deleted */+ });+ });++ it("should create a new API key for an organization with valid admin authentication", async () => {+ const response = await makeZodVerifiedAPICall(+ ApiKeyResponseSchema,+ "POST",+ `/api/admin/organizations/${testOrgId}/apiKeys`,+ {+ note: "Test API Key",+ },+ `Bearer ${ADMIN_API_KEY}`,+ 201,+ );++ expect(response.status).toBe(201);+ expect(response.body.publicKey).toMatch(/^pk-lf-/);+ expect(response.body.secretKey).toMatch(/^sk-lf-/);+ expect(response.body.note).toBe("Test API Key");++ // Verify the API key was actually created in the database+ const apiKey = await prisma.apiKey.findUnique({+ where: { id: response.body.id },+ });+ expect(apiKey).not.toBeNull();+ expect(apiKey?.orgId).toBe(testOrgId);+ expect(apiKey?.scope).toBe("ORGANIZATION");+ });++ it("should return 404 when creating an API key for a non-existent organization", async () => {+ const nonExistentId = randomUUID();+ const result = await makeAPICall(+ "POST",+ `/api/admin/organizations/${nonExistentId}/apiKeys`,+ {+ note: "Test API Key",+ },+ `Bearer ${ADMIN_API_KEY}`,+ );++ expect(result.status).toBe(404);+ expect(result.body.error).toContain("Organization not found");+ });++ it("should return 401 when no authorization header is provided", async () => {+ const result = await makeAPICall(+ "POST",+ `/api/admin/organizations/${testOrgId}/apiKeys`,+ {+ note: "Test API Key",+ },+ );++ expect(result.status).toBe(401);+ expect(result.body.error).toContain("Unauthorized");+ });+ });++ describe("DELETE /api/admin/organizations/[organizationId]/apiKeys/[apiKeyId]", () => {+ let testOrgId: string;+ let testApiKeyId: string;++ beforeEach(async () => {+ // Create a test organization+ const uniqueOrgName = `Test Org ${randomUUID().substring(0, 8)}`;+ const org = await prisma.organization.create({+ data: { name: uniqueOrgName },+ });+ testOrgId = org.id;++ // Create a test API key for the organization+ const apiKey = await prisma.apiKey.create({+ data: {+ orgId: testOrgId,+ publicKey: `pk-lf-test-${randomUUID()}`,+ hashedSecretKey: "hashed-secret",+ displaySecretKey: "sk-lf-test...1234",+ note: "Test API Key",+ scope: "ORGANIZATION",+ },+ });+ testApiKeyId = apiKey.id;+ });++ afterEach(async () => {+ // Clean up test organization and its API keys+ await prisma.apiKey.deleteMany({+ where: { orgId: testOrgId },+ });+ await prisma.organization+ .delete({+ where: { id: testOrgId },+ })+ .catch(() => {+ /* ignore if already deleted */+ });+ });++ it("should delete an API key with valid admin authentication", async () => {+ const response = await makeZodVerifiedAPICall(+ DeleteResponseSchema,+ "DELETE",+ `/api/admin/organizations/${testOrgId}/apiKeys/${testApiKeyId}`,+ undefined,+ `Bearer ${ADMIN_API_KEY}`,+ 200,+ );++ expect(response.status).toBe(200);+ expect(response.body).toMatchObject({+ success: true,+ });++ // Verify the API key was actually deleted from the database+ const apiKey = await prisma.apiKey.findUnique({+ where: { id: testApiKeyId },+ });+ expect(apiKey).toBeNull();+ });++ it("should return 404 when deleting a non-existent API key", async () => {+ const nonExistentId = randomUUID();+ const result = await makeAPICall(+ "DELETE",+ `/api/admin/organizations/${testOrgId}/apiKeys/${nonExistentId}`,+ undefined,+ `Bearer ${ADMIN_API_KEY}`,+ );++ expect(result.status).toBe(404);+ expect(result.body.error).toContain("API key not found");+ });++ it("should return 404 when deleting an API key for a non-existent organization", async () => {+ const nonExistentId = randomUUID();+ const result = await makeAPICall(+ "DELETE",+ `/api/admin/organizations/${nonExistentId}/apiKeys/${testApiKeyId}`,+ undefined,+ `Bearer ${ADMIN_API_KEY}`,+ );++ expect(result.status).toBe(404);+ expect(result.body.error).toContain("Organization not found");+ });++ it("should return 401 when no authorization header is provided", async () => {+ const result = await makeAPICall(+ "DELETE",+ `/api/admin/organizations/${testOrgId}/apiKeys/${testApiKeyId}`,+ );++ expect(result.status).toBe(401);+ expect(result.body.error).toContain("Unauthorized");+ });+ });+it("should return 405 for non-supported methods", async () => {const result = await makeAPICall("PATCH",diff --git a/web/src/features/public-api/server/apiAuth.ts b/web/src/features/public-api/server/apiAuth.tsindex fa4023dc78..fa72fd9dbe 100644--- a/web/src/features/public-api/server/apiAuth.ts+++ b/web/src/features/public-api/server/apiAuth.ts@@ -82,12 +82,20 @@ export class ApiAuthService {await this.invalidate(apiKeys, `project ${projectId}`);}- async deleteApiKey(id: string, projectId: string, scope: ApiKeyScope) {+ /**+ * Deletes an API key from the database and invalidates it in Redis if available.+ * @param id - The ID of the API key to delete.+ * @param entityId - The ID of the entity (project or organization) to which the API key belongs.+ * @param scope - The scope of the API key (either "PROJECT" or "ORGANIZATION").+ */+ async deleteApiKey(id: string, entityId: string, scope: ApiKeyScope) {+ const entity =+ scope === "PROJECT" ? { projectId: entityId } : { orgId: entityId };// Make sure the API key exists and belongs to the project the user has access toconst apiKey = await this.prisma.apiKey.findFirstOrThrow({where: {+ ...entity,id: id,- projectId: projectId,scope,},});diff --git a/web/src/features/public-api/server/projectApiKeyRouter.ts b/web/src/features/public-api/server/projectApiKeyRouter.tsindex 5f8a566d55..c0eeedb0ae 100644--- a/web/src/features/public-api/server/projectApiKeyRouter.ts+++ b/web/src/features/public-api/server/projectApiKeyRouter.ts@@ -58,7 +58,7 @@ export const projectApiKeysRouter = createTRPCRouter({const apiKeyMeta = await createAndAddApiKeysToDb({prisma: ctx.prisma,- projectId: input.projectId,+ entityId: input.projectId,note: input.note,scope: "PROJECT",});diff --git a/web/src/initialize.ts b/web/src/initialize.tsindex 9c1373003e..a5c24e89e4 100644--- a/web/src/initialize.ts+++ b/web/src/initialize.ts@@ -72,7 +72,7 @@ if (env.LANGFUSE_INIT_ORG_ID) {) {await createAndAddApiKeysToDb({prisma,- projectId: env.LANGFUSE_INIT_PROJECT_ID,+ entityId: env.LANGFUSE_INIT_PROJECT_ID,note: "Provisioned API Key",scope: "PROJECT",predefinedKeys: {diff --git a/web/src/pages/api/admin/organizations/[organizationId]/apiKeys/[apiKeyId].ts b/web/src/pages/api/admin/organizations/[organizationId]/apiKeys/[apiKeyId].tsnew file mode 100644index 0000000000..a08d190a5d--- /dev/null+++ b/web/src/pages/api/admin/organizations/[organizationId]/apiKeys/[apiKeyId].ts@@ -0,0 +1,113 @@+import { type NextApiRequest, type NextApiResponse } from "next";+import { prisma } from "@langfuse/shared/src/db";+import { logger, redis } from "@langfuse/shared/src/server";+import { AdminApiAuthService } from "@/src/features/admin-api/server/adminApiAuth";+import { auditLog } from "@/src/features/audit-logs/auditLog";+import { z } from "zod";+import { ApiAuthService } from "@/src/features/public-api/server/apiAuth";++const validateQueryParams = (+ query: unknown,+): { organizationId: string; apiKeyId: string } | null => {+ const inputQuerySchema = z.object({+ organizationId: z.string(),+ apiKeyId: z.string(),+ });+ const validation = inputQuerySchema.safeParse(query);+ if (!validation.success) {+ return null;+ }+ return validation.data;+};++export default async function handler(+ req: NextApiRequest,+ res: NextApiResponse,+) {+ try {+ if (req.method !== "DELETE") {+ 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;+ }++ const params = validateQueryParams(req.query);+ if (!params) {+ return res.status(400).json({ error: "Invalid request parameters" });+ }++ const { organizationId, apiKeyId } = params;++ // Check if organization exists+ const organization = await prisma.organization.findUnique({+ where: { id: organizationId },+ });++ if (!organization) {+ return res.status(404).json({ error: "Organization not found" });+ }++ // Handle different HTTP methods+ switch (req.method) {+ case "DELETE":+ return await handleDelete(req, res, organizationId, apiKeyId);+ default:+ res.status(405).json({ error: "Method Not Allowed" });+ return;+ }+ } catch (e) {+ logger.error("Failed to process organization API key request", e);+ res.status(500).json({ error: "Internal server error" });+ }+}++async function handleDelete(+ req: NextApiRequest,+ res: NextApiResponse,+ organizationId: string,+ apiKeyId: string,+) {+ // Check if API key exists and belongs to the organization+ const apiKey = await prisma.apiKey.findFirst({+ where: {+ id: apiKeyId,+ orgId: organizationId,+ scope: "ORGANIZATION",+ },+ });++ if (!apiKey) {+ return res.status(404).json({ error: "API key not found" });+ }++ // Delete the API key+ const deleted = await new ApiAuthService(prisma, redis).deleteApiKey(+ apiKeyId,+ organizationId,+ "ORGANIZATION",+ );++ if (!deleted) {+ return res.status(500).json({ error: "Failed to delete API key" });+ }++ // Log the API key deletion+ await auditLog({+ resourceType: "apiKey",+ resourceId: apiKeyId,+ action: "delete",+ orgId: organizationId,+ orgRole: "ADMIN",+ apiKeyId: "ADMIN_KEY",+ });++ logger.info(+ `Deleted API key ${apiKeyId} for organization ${organizationId} via admin API`,+ );++ return res.status(200).json({ success: true });+}diff --git a/web/src/pages/api/admin/organizations/[organizationId]/apiKeys/index.ts b/web/src/pages/api/admin/organizations/[organizationId]/apiKeys/index.tsnew file mode 100644index 0000000000..b367b81e3e--- /dev/null+++ b/web/src/pages/api/admin/organizations/[organizationId]/apiKeys/index.ts@@ -0,0 +1,136 @@+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 { auditLog } from "@/src/features/audit-logs/auditLog";+import { z } from "zod";+import { createAndAddApiKeysToDb } from "@langfuse/shared/src/server/auth/apiKeys";++const validateQueryAndExtractId = (query: unknown): string | null => {+ const inputQuerySchema = z.object({+ organizationId: z.string(),+ });+ const validation = inputQuerySchema.safeParse(query);+ if (!validation.success) {+ return null;+ }+ return validation.data.organizationId;+};++export default async function handler(+ req: NextApiRequest,+ res: NextApiResponse,+) {+ try {+ if (req.method !== "POST" && req.method !== "GET") {+ 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;+ }++ const organizationId = validateQueryAndExtractId(req.query);+ if (!organizationId) {+ return res.status(400).json({ error: "Invalid organization ID" });+ }++ // Check if organization exists+ const organization = await prisma.organization.findUnique({+ where: { id: organizationId },+ });++ if (!organization) {+ return res.status(404).json({ error: "Organization not found" });+ }++ // Handle different HTTP methods+ switch (req.method) {+ case "GET":+ return await handleGet(req, res, organizationId);+ case "POST":+ return await handlePost(req, res, organizationId);+ default:+ res.status(405).json({ error: "Method Not Allowed" });+ return;+ }+ } catch (e) {+ logger.error("Failed to process organization API key request", e);+ res.status(500).json({ error: "Internal server error" });+ }+}++async function handleGet(+ req: NextApiRequest,+ res: NextApiResponse,+ organizationId: string,+) {+ const apiKeys = await prisma.apiKey.findMany({+ where: {+ orgId: organizationId,+ scope: "ORGANIZATION",+ },+ select: {+ id: true,+ createdAt: true,+ expiresAt: true,+ lastUsedAt: true,+ note: true,+ publicKey: true,+ displaySecretKey: true,+ },+ orderBy: {+ createdAt: "asc",+ },+ });++ return res.status(200).json({ apiKeys });+}++async function handlePost(+ req: NextApiRequest,+ res: NextApiResponse,+ organizationId: string,+) {+ // Validate the request body+ const createApiKeySchema = z.object({+ note: z.string().optional(),+ });++ const validationResult = createApiKeySchema.safeParse(req.body);++ if (!validationResult.success) {+ return res.status(400).json({+ error: "Invalid request body",+ details: validationResult.error.format(),+ });+ }++ const { note } = validationResult.data;++ // Create the API key+ const apiKeyMeta = await createAndAddApiKeysToDb({+ prisma,+ entityId: organizationId, // Using organizationId as projectId for organization scoped keys+ note,+ scope: "ORGANIZATION",+ });++ // Log the API key creation+ await auditLog({+ resourceType: "apiKey",+ resourceId: apiKeyMeta.id,+ action: "create",+ orgId: organizationId,+ orgRole: "ADMIN",+ apiKeyId: "ADMIN_KEY",+ });++ logger.info(+ `Created API key ${apiKeyMeta.id} for organization ${organizationId} via admin API`,+ );++ return res.status(201).json(apiKeyMeta);+}diff --git a/web/src/pages/api/admin/organizations/[organizationId].ts b/web/src/pages/api/admin/organizations/[organizationId]/index.tssimilarity index 100%rename from web/src/pages/api/admin/organizations/[organizationId].tsrename to web/src/pages/api/admin/organizations/[organizationId]/index.tsdiff --git a/web/src/pages/api/admin/organizations/index.ts b/web/src/pages/api/admin/organizations/index.tsindex dd853aac59..8273f5751e 100644--- a/web/src/pages/api/admin/organizations/index.ts+++ b/web/src/pages/api/admin/organizations/index.ts@@ -10,7 +10,6 @@ export default async function handler(res: NextApiResponse,) {try {- // Allow only POST requestsif (req.method !== "POST" && req.method !== "GET") {res.status(405).json({ error: "Method Not Allowed" });return;