🪢 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 management of project api keys via API (#6457)
Steffen Schmitz2e40330df8b6
diff --git a/fern/apis/server/definition/projects.yml b/fern/apis/server/definition/projects.ymlindex 624cb25313..eb583f9c18 100644--- a/fern/apis/server/definition/projects.yml+++ b/fern/apis/server/definition/projects.yml@@ -32,6 +32,39 @@ service:response:status-code: 202type: ProjectDeletionResponse++ # API Key endpoints+ getApiKeys:+ docs: Get all API keys for a project (requires organization-scoped API key)+ method: GET+ path: /projects/{projectId}/apiKeys+ path-parameters:+ projectId: string+ response: ApiKeyList++ createApiKey:+ docs: Create a new API key for a project (requires organization-scoped API key)+ method: POST+ path: /projects/{projectId}/apiKeys+ path-parameters:+ projectId: string+ request:+ name: CreateApiKeyRequest+ body:+ properties:+ note:+ type: optional<string>+ docs: Optional note for the API key+ response: ApiKeyResponse++ deleteApiKey:+ docs: Delete an API key for a project (requires organization-scoped API key)+ method: DELETE+ path: /projects/{projectId}/apiKeys/{apiKeyId}+ path-parameters:+ projectId: string+ apiKeyId: string+ response: ApiKeyDeletionResponsetypes:Projects:@@ -47,3 +80,34 @@ types:properties:success: booleanmessage: string++ ApiKeyList:+ docs: List of API keys for a project+ 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>++ ApiKeyDeletionResponse:+ docs: Response for API key deletion+ properties:+ success: booleandiff --git a/web/public/generated/api/openapi.yml b/web/public/generated/api/openapi.ymlindex 8017f2657d..8d74105934 100644--- a/web/public/generated/api/openapi.yml+++ b/web/public/generated/api/openapi.yml@@ -2306,6 +2306,161 @@ paths:schema: {}security:- BasicAuth: []+ /api/public/projects/{projectId}/apiKeys:+ get:+ description: Get all API keys for a project (requires organization-scoped API key)+ operationId: projects_getApiKeys+ tags:+ - Projects+ parameters:+ - name: projectId+ in: path+ required: true+ schema:+ type: string+ responses:+ '200':+ description: ''+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/ApiKeyList'+ '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: []+ post:+ description: >-+ Create a new API key for a project (requires organization-scoped API+ key)+ operationId: projects_createApiKey+ tags:+ - Projects+ parameters:+ - name: projectId+ in: path+ required: true+ schema:+ type: string+ responses:+ '200':+ description: ''+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/ApiKeyResponse'+ '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: []+ requestBody:+ required: true+ content:+ application/json:+ schema:+ type: object+ properties:+ note:+ type: string+ nullable: true+ description: Optional note for the API key+ /api/public/projects/{projectId}/apiKeys/{apiKeyId}:+ delete:+ description: Delete an API key for a project (requires organization-scoped API key)+ operationId: projects_deleteApiKey+ tags:+ - Projects+ parameters:+ - name: projectId+ 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/ApiKeyDeletionResponse'+ '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/v2/prompts/{name}/versions/{version}:patch:description: Update labels for a specific prompt version@@ -6071,6 +6226,81 @@ components:required:- success- message+ ApiKeyList:+ title: ApiKeyList+ type: object+ description: List of API keys for a project+ 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+ - displaySecretKey+ ApiKeyDeletionResponse:+ title: ApiKeyDeletionResponse+ type: object+ description: Response for API key deletion+ properties:+ success:+ type: boolean+ required:+ - successPromptMetaListResponse:title: PromptMetaListResponsetype: objectdiff --git a/web/public/generated/postman/collection.json b/web/public/generated/postman/collection.jsonindex 427f47edd6..8ed64b4e90 100644--- a/web/public/generated/postman/collection.json+++ b/web/public/generated/postman/collection.json@@ -1764,6 +1764,119 @@"body": null},"response": []+ },+ {+ "_type": "endpoint",+ "name": "Get Api Keys",+ "request": {+ "description": "Get all API keys for a project (requires organization-scoped API key)",+ "url": {+ "raw": "{{baseUrl}}/api/public/projects/:projectId/apiKeys",+ "host": [+ "{{baseUrl}}"+ ],+ "path": [+ "api",+ "public",+ "projects",+ ":projectId",+ "apiKeys"+ ],+ "query": [],+ "variable": [+ {+ "key": "projectId",+ "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 a project (requires organization-scoped API key)",+ "url": {+ "raw": "{{baseUrl}}/api/public/projects/:projectId/apiKeys",+ "host": [+ "{{baseUrl}}"+ ],+ "path": [+ "api",+ "public",+ "projects",+ ":projectId",+ "apiKeys"+ ],+ "query": [],+ "variable": [+ {+ "key": "projectId",+ "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 a project (requires organization-scoped API key)",+ "url": {+ "raw": "{{baseUrl}}/api/public/projects/:projectId/apiKeys/:apiKeyId",+ "host": [+ "{{baseUrl}}"+ ],+ "path": [+ "api",+ "public",+ "projects",+ ":projectId",+ "apiKeys",+ ":apiKeyId"+ ],+ "query": [],+ "variable": [+ {+ "key": "projectId",+ "value": "",+ "description": null+ },+ {+ "key": "apiKeyId",+ "value": "",+ "description": null+ }+ ]+ },+ "header": [],+ "method": "DELETE",+ "auth": null,+ "body": null+ },+ "response": []}]},diff --git a/web/src/__tests__/async/projects-api.servertest.ts b/web/src/__tests__/async/projects-api.servertest.tsindex 95d5c059a4..00699721d4 100644--- a/web/src/__tests__/async/projects-api.servertest.ts+++ b/web/src/__tests__/async/projects-api.servertest.ts@@ -34,7 +34,38 @@ const ProjectDeletionResponseSchema = z.object({message: z.string(),});-describe("Public Projects API", () => {+// Schema for API keys response+const ApiKeysResponseSchema = z.object({+ apiKeys: z.array(+ z.object({+ id: z.string(),+ createdAt: z.string().or(z.date()),+ expiresAt: z.string().or(z.date()).nullable(),+ lastUsedAt: z.string().or(z.date()).nullable(),+ note: z.string().nullable(),+ publicKey: z.string(),+ displaySecretKey: z.string().nullable(),+ }),+ ),+});++// Schema for API key creation response+const ApiKeyCreationResponseSchema = z.object({+ id: z.string(),+ publicKey: z.string(),+ secretKey: z.string(),+ displaySecretKey: z.string(),+ note: z.string().nullable(),+ createdAt: z.string().or(z.date()),+ expiresAt: z.string().or(z.date()).optional(),+});++// Schema for API key deletion response+const ApiKeyDeletionResponseSchema = z.object({+ success: z.boolean(),+});++describe("Projects API", () => {// Test variablesconst projectId = "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a";const projectName = "Seed Project";@@ -338,4 +369,273 @@ describe("Public Projects API", () => {expect(result.body.message).toContain("Method not allowed");});});++ describe("GET /api/public/projects/[projectId]/apiKeys", () => {+ it("should return API keys with valid organization API key authentication", async () => {+ const response = await makeZodVerifiedAPICall(+ ApiKeysResponseSchema,+ "GET",+ `/api/public/projects/${projectId}/apiKeys`,+ undefined,+ createBasicAuthHeader(orgApiKey, orgSecretKey),+ 200, // Expected status code is 200 OK+ );++ expect(response.status).toBe(200);+ expect(response.body.apiKeys.length).toBeGreaterThanOrEqual(1);+ expect(response.body.apiKeys[0]).toHaveProperty("id");+ expect(response.body.apiKeys[0]).toHaveProperty("publicKey");+ });++ it("should return 401 when invalid API keys are provided", async () => {+ const result = await makeAPICall(+ "GET",+ `/api/public/projects/${projectId}/apiKeys`,+ undefined,+ createBasicAuthHeader(invalidApiKey, invalidSecretKey),+ );+ expect(result.status).toBe(401);+ expect(result.body.message).toBeDefined();+ });++ it("should return 403 when using project API key instead of organization API key", async () => {+ const result = await makeAPICall(+ "GET",+ `/api/public/projects/${projectId}/apiKeys`,+ undefined,+ createBasicAuthHeader(projectApiKey, projectSecretKey),+ );+ expect(result.status).toBe(403);+ expect(result.body.message).toContain(+ "Organization-scoped API key required",+ );+ });++ it("should return 404 when project does not exist", async () => {+ const nonExistentProjectId = randomUUID();+ const result = await makeAPICall(+ "GET",+ `/api/public/projects/${nonExistentProjectId}/apiKeys`,+ undefined,+ createBasicAuthHeader(orgApiKey, orgSecretKey),+ );+ expect(result.status).toBe(404);+ expect(result.body.message).toContain("Project not found");+ });++ it("should return 405 for non-GET/POST methods", async () => {+ const result = await makeAPICall(+ "PUT",+ `/api/public/projects/${projectId}/apiKeys`,+ {},+ createBasicAuthHeader(orgApiKey, orgSecretKey),+ );+ expect(result.status).toBe(405);+ expect(result.body.message).toContain("Method Not Allowed");+ });+ });++ describe("POST /api/public/projects/[projectId]/apiKeys", () => {+ let createdApiKeyId: string;++ afterEach(async () => {+ // Clean up any API keys created during tests+ if (createdApiKeyId) {+ await prisma.apiKey.deleteMany({+ where: {+ id: createdApiKeyId,+ },+ });+ createdApiKeyId = "";+ }+ });++ it("should create a new API key with valid organization API key", async () => {+ const note = `Test API Key ${randomUUID().substring(0, 8)}`;++ const response = await makeZodVerifiedAPICall(+ ApiKeyCreationResponseSchema,+ "POST",+ `/api/public/projects/${projectId}/apiKeys`,+ {+ note,+ },+ createBasicAuthHeader(orgApiKey, orgSecretKey),+ 201, // Expected status code is 201 Created+ );++ expect(response.status).toBe(201);+ expect(response.body).toHaveProperty("id");+ expect(response.body).toHaveProperty("publicKey");+ expect(response.body).toHaveProperty("secretKey");+ expect(response.body.note).toBe(note);++ // Store the created API key ID for cleanup+ createdApiKeyId = response.body.id;++ // 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?.note).toBe(note);+ expect(apiKey?.projectId).toBe(projectId);+ expect(apiKey?.scope).toBe("PROJECT");+ });++ it("should return 403 when using project API key instead of organization API key", async () => {+ const note = `Test API Key ${randomUUID().substring(0, 8)}`;++ const result = await makeAPICall(+ "POST",+ `/api/public/projects/${projectId}/apiKeys`,+ {+ note,+ },+ createBasicAuthHeader(projectApiKey, projectSecretKey),+ );+ expect(result.status).toBe(403);+ expect(result.body.message).toContain(+ "Organization-scoped API key required",+ );+ });++ it("should return 401 when invalid API keys are provided", async () => {+ const note = `Test API Key ${randomUUID().substring(0, 8)}`;++ const result = await makeAPICall(+ "POST",+ `/api/public/projects/${projectId}/apiKeys`,+ {+ note,+ },+ createBasicAuthHeader(invalidApiKey, invalidSecretKey),+ );+ expect(result.status).toBe(401);+ expect(result.body.message).toBeDefined();+ });++ it("should return 404 when project does not exist", async () => {+ const nonExistentProjectId = randomUUID();+ const note = `Test API Key ${randomUUID().substring(0, 8)}`;++ const result = await makeAPICall(+ "POST",+ `/api/public/projects/${nonExistentProjectId}/apiKeys`,+ {+ note,+ },+ createBasicAuthHeader(orgApiKey, orgSecretKey),+ );+ expect(result.status).toBe(404);+ expect(result.body.message).toContain("Project not found");+ });+ });++ describe("DELETE /api/public/projects/[projectId]/apiKeys/[apiKeyId]", () => {+ let deleteTestApiKeyId: string;++ beforeEach(async () => {+ // Create a test API key to delete+ const apiKeyMeta = await createAndAddApiKeysToDb({+ prisma,+ entityId: projectId,+ scope: "PROJECT",+ note: `Delete Test API Key ${randomUUID().substring(0, 8)}`,+ });+ deleteTestApiKeyId = apiKeyMeta.id;+ });++ afterEach(async () => {+ // Clean up any remaining test API keys+ try {+ await prisma.apiKey.deleteMany({+ where: {+ id: deleteTestApiKeyId,+ },+ });+ } catch (error) {+ // Ignore errors if the API key was already deleted by the test+ }+ });++ it("should delete an API key with valid organization API key", async () => {+ const response = await makeZodVerifiedAPICall(+ ApiKeyDeletionResponseSchema,+ "DELETE",+ `/api/public/projects/${projectId}/apiKeys/${deleteTestApiKeyId}`,+ undefined,+ createBasicAuthHeader(orgApiKey, orgSecretKey),+ 200, // Expected status code is 200 OK+ );++ expect(response.status).toBe(200);+ expect(response.body.success).toBe(true);++ // Verify the API key was actually deleted from the database+ const apiKey = await prisma.apiKey.findUnique({+ where: { id: deleteTestApiKeyId },+ });+ expect(apiKey).toBeNull();+ });++ it("should return 403 when using project API key instead of organization API key", async () => {+ const result = await makeAPICall(+ "DELETE",+ `/api/public/projects/${projectId}/apiKeys/${deleteTestApiKeyId}`,+ undefined,+ createBasicAuthHeader(projectApiKey, projectSecretKey),+ );+ expect(result.status).toBe(403);+ expect(result.body.message).toContain(+ "Organization-scoped API key required",+ );+ });++ it("should return 401 when invalid API keys are provided", async () => {+ const result = await makeAPICall(+ "DELETE",+ `/api/public/projects/${projectId}/apiKeys/${deleteTestApiKeyId}`,+ undefined,+ createBasicAuthHeader(invalidApiKey, invalidSecretKey),+ );+ expect(result.status).toBe(401);+ expect(result.body.message).toBeDefined();+ });++ it("should return 404 when API key does not exist", async () => {+ const nonExistentApiKeyId = randomUUID();+ const result = await makeAPICall(+ "DELETE",+ `/api/public/projects/${projectId}/apiKeys/${nonExistentApiKeyId}`,+ undefined,+ createBasicAuthHeader(orgApiKey, orgSecretKey),+ );+ expect(result.status).toBe(404);+ expect(result.body.message).toContain("API key not found");+ });++ it("should return 404 when project does not exist", async () => {+ const nonExistentProjectId = randomUUID();+ const result = await makeAPICall(+ "DELETE",+ `/api/public/projects/${nonExistentProjectId}/apiKeys/${deleteTestApiKeyId}`,+ undefined,+ createBasicAuthHeader(orgApiKey, orgSecretKey),+ );+ expect(result.status).toBe(404);+ expect(result.body.message).toContain("Project not found");+ });++ it("should return 405 for non-DELETE methods", async () => {+ const result = await makeAPICall(+ "GET",+ `/api/public/projects/${projectId}/apiKeys/${deleteTestApiKeyId}`,+ undefined,+ createBasicAuthHeader(orgApiKey, orgSecretKey),+ );+ expect(result.status).toBe(405);+ expect(result.body.message).toContain("Method Not Allowed");+ });+ });});diff --git a/web/src/pages/api/admin/organizations/[organizationId]/apiKeys/index.ts b/web/src/pages/api/admin/organizations/[organizationId]/apiKeys/index.tsindex b367b81e3e..07c7274d44 100644--- a/web/src/pages/api/admin/organizations/[organizationId]/apiKeys/index.ts+++ b/web/src/pages/api/admin/organizations/[organizationId]/apiKeys/index.ts@@ -113,7 +113,7 @@ async function handlePost(// Create the API keyconst apiKeyMeta = await createAndAddApiKeysToDb({prisma,- entityId: organizationId, // Using organizationId as projectId for organization scoped keys+ entityId: organizationId,note,scope: "ORGANIZATION",});diff --git a/web/src/pages/api/admin/organizations/apiKey.ts b/web/src/pages/api/admin/organizations/apiKey.tsdeleted file mode 100644index e69de29bb2..0000000000diff --git a/web/src/pages/api/public/projects/[projectId]/apiKeys/[apiKeyId].ts b/web/src/pages/api/public/projects/[projectId]/apiKeys/[apiKeyId].tsnew file mode 100644index 0000000000..0597f4a5cc--- /dev/null+++ b/web/src/pages/api/public/projects/[projectId]/apiKeys/[apiKeyId].ts@@ -0,0 +1,146 @@+import { type NextApiRequest, type NextApiResponse } from "next";+import { prisma } from "@langfuse/shared/src/db";+import { logger, redis } from "@langfuse/shared/src/server";+import { ApiAuthService } from "@/src/features/public-api/server/apiAuth";+import { auditLog } from "@/src/features/audit-logs/auditLog";+import { z } from "zod";+import { cors, runMiddleware } from "@/src/features/public-api/server/cors";++const validateQueryParams = (+ query: unknown,+): { projectId: string; apiKeyId: string } | null => {+ const inputQuerySchema = z.object({+ projectId: 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,+) {+ await runMiddleware(req, res, cors);++ try {+ if (req.method !== "DELETE") {+ res.status(405).json({ message: "Method Not Allowed" });+ return;+ }++ // CHECK AUTH+ const authCheck = await new ApiAuthService(+ prisma,+ redis,+ ).verifyAuthHeaderAndReturnScope(req.headers.authorization);+ if (!authCheck.validKey) {+ return res.status(401).json({+ message: authCheck.error,+ });+ }++ // Check if using an organization API key+ if (+ authCheck.scope.accessLevel !== "organization" ||+ !authCheck.scope.orgId+ ) {+ return res.status(403).json({+ message:+ "Invalid API key. Organization-scoped API key required for this operation.",+ });+ }+ // END CHECK AUTH++ const params = validateQueryParams(req.query);+ if (!params) {+ return res.status(400).json({ message: "Invalid request parameters" });+ }++ const { projectId, apiKeyId } = params;++ // Check if project exists and belongs to the organization+ const project = await prisma.project.findFirst({+ where: {+ id: projectId,+ orgId: authCheck.scope.orgId,+ },+ });++ if (!project) {+ return res+ .status(404)+ .json({ message: "Project not found or you don't have access to it" });+ }++ // Handle different HTTP methods+ switch (req.method) {+ case "DELETE":+ return await handleDelete(+ req,+ res,+ projectId,+ apiKeyId,+ authCheck.scope.orgId,+ );+ default:+ res.status(405).json({ message: "Method Not Allowed" });+ return;+ }+ } catch (e) {+ logger.error("Failed to process project API key request", e);+ res.status(500).json({ message: "Internal server error" });+ }+}++async function handleDelete(+ req: NextApiRequest,+ res: NextApiResponse,+ projectId: string,+ apiKeyId: string,+ orgId: string,+) {+ // Check if API key exists and belongs to the project+ const apiKey = await prisma.apiKey.findFirst({+ where: {+ id: apiKeyId,+ projectId,+ scope: "PROJECT",+ },+ });++ if (!apiKey) {+ return res.status(404).json({ message: "API key not found" });+ }++ // Delete the API key+ const deleted = await new ApiAuthService(prisma, redis).deleteApiKey(+ apiKeyId,+ projectId,+ "PROJECT",+ );++ if (!deleted) {+ return res.status(500).json({ message: "Failed to delete API key" });+ }++ // Log the API key deletion+ await auditLog({+ resourceType: "apiKey",+ resourceId: apiKeyId,+ action: "delete",+ orgId: orgId,+ projectId: projectId,+ orgRole: "ADMIN",+ apiKeyId: "ORG_KEY",+ });++ logger.info(+ `Deleted API key ${apiKeyId} for project ${projectId} via public API`,+ );++ return res.status(200).json({ success: true });+}diff --git a/web/src/pages/api/public/projects/[projectId]/apiKeys/index.ts b/web/src/pages/api/public/projects/[projectId]/apiKeys/index.tsnew file mode 100644index 0000000000..ce43228424--- /dev/null+++ b/web/src/pages/api/public/projects/[projectId]/apiKeys/index.ts@@ -0,0 +1,164 @@+import { type NextApiRequest, type NextApiResponse } from "next";+import { prisma } from "@langfuse/shared/src/db";+import { logger, redis } from "@langfuse/shared/src/server";+import { ApiAuthService } from "@/src/features/public-api/server/apiAuth";+import { auditLog } from "@/src/features/audit-logs/auditLog";+import { z } from "zod";+import { cors, runMiddleware } from "@/src/features/public-api/server/cors";+import { createAndAddApiKeysToDb } from "@langfuse/shared/src/server/auth/apiKeys";++const validateQueryAndExtractId = (query: unknown): string | null => {+ const inputQuerySchema = z.object({+ projectId: z.string(),+ });+ const validation = inputQuerySchema.safeParse(query);+ if (!validation.success) {+ return null;+ }+ return validation.data.projectId;+};++export default async function handler(+ req: NextApiRequest,+ res: NextApiResponse,+) {+ await runMiddleware(req, res, cors);++ try {+ if (req.method !== "POST" && req.method !== "GET") {+ res.status(405).json({ message: "Method Not Allowed" });+ return;+ }++ // CHECK AUTH+ const authCheck = await new ApiAuthService(+ prisma,+ redis,+ ).verifyAuthHeaderAndReturnScope(req.headers.authorization);+ if (!authCheck.validKey) {+ return res.status(401).json({+ message: authCheck.error,+ });+ }++ // Check if using an organization API key+ if (+ authCheck.scope.accessLevel !== "organization" ||+ !authCheck.scope.orgId+ ) {+ return res.status(403).json({+ message:+ "Invalid API key. Organization-scoped API key required for this operation.",+ });+ }+ // END CHECK AUTH++ const projectId = validateQueryAndExtractId(req.query);+ if (!projectId) {+ return res.status(400).json({ message: "Invalid project ID" });+ }++ // Check if project exists and belongs to the organization+ const project = await prisma.project.findFirst({+ where: {+ id: projectId,+ orgId: authCheck.scope.orgId,+ },+ });++ if (!project) {+ return res+ .status(404)+ .json({ message: "Project not found or you don't have access to it" });+ }++ // Handle different HTTP methods+ switch (req.method) {+ case "GET":+ return await handleGet(req, res, projectId);+ case "POST":+ return await handlePost(req, res, projectId, authCheck.scope.orgId);+ default:+ res.status(405).json({ message: "Method Not Allowed" });+ return;+ }+ } catch (e) {+ logger.error("Failed to process project API key request", e);+ res.status(500).json({ message: "Internal server error" });+ }+}++async function handleGet(+ req: NextApiRequest,+ res: NextApiResponse,+ projectId: string,+) {+ const apiKeys = await prisma.apiKey.findMany({+ where: {+ projectId,+ scope: "PROJECT",+ },+ 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,+ projectId: string,+ orgId: 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({+ message: "Invalid request body",+ details: validationResult.error.format(),+ });+ }++ const { note } = validationResult.data;++ // Create the API key+ const apiKeyMeta = await createAndAddApiKeysToDb({+ prisma,+ entityId: projectId,+ note,+ scope: "PROJECT",+ });++ // Log the API key creation+ await auditLog({+ resourceType: "apiKey",+ resourceId: apiKeyMeta.id,+ action: "create",+ orgId: orgId,+ projectId: projectId,+ orgRole: "ADMIN",+ apiKeyId: "ORG_KEY",+ });++ logger.info(+ `Created API key ${apiKeyMeta.id} for project ${projectId} via public API`,+ );++ return res.status(201).json(apiKeyMeta);+}