Skip to content

🪢 Open source agent evals & observability: Trace, evaluate, and improve LLM applications with one open platform.

feat: allow the creation and deletion of projects using an org api key (#6438)

Steffen Schmitz4b36ff8752d7
diff --git a/fern/apis/server/definition/projects.yml b/fern/apis/server/definition/projects.yml
index a5a3273455..624cb25313 100644
--- a/fern/apis/server/definition/projects.yml
+++ b/fern/apis/server/definition/projects.yml
@@ -11,6 +11,27 @@ service:
method: GET
path: /projects
response: Projects
+
+ create:
+ docs: Create a new project (requires organization-scoped API key)
+ method: POST
+ path: /projects
+ request:
+ name: CreateProjectRequest
+ body:
+ properties:
+ name: string
+ response: Project
+
+ delete:
+ docs: Delete a project by ID (requires organization-scoped API key). Project deletion is processed asynchronously.
+ method: DELETE
+ path: /projects/{projectId}
+ path-parameters:
+ projectId: string
+ response:
+ status-code: 202
+ type: ProjectDeletionResponse
types:
Projects:
@@ -21,3 +42,8 @@ types:
properties:
id: string
name: string
+
+ ProjectDeletionResponse:
+ properties:
+ success: boolean
+ message: string
diff --git a/web/public/generated/api/openapi.yml b/web/public/generated/api/openapi.yml
index d6cf893132..f413c4c93b 100644
--- a/web/public/generated/api/openapi.yml
+++ b/web/public/generated/api/openapi.yml
@@ -2014,6 +2014,105 @@ paths:
schema: {}
security:
- BasicAuth: []
+ post:
+ description: Create a new project (requires organization-scoped API key)
+ operationId: projects_create
+ tags:
+ - Projects
+ parameters: []
+ responses:
+ '200':
+ description: ''
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/Project'
+ '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:
+ name:
+ type: string
+ required:
+ - name
+ /api/public/projects/{projectId}:
+ delete:
+ description: >-
+ Delete a project by ID (requires organization-scoped API key). Project
+ deletion is processed asynchronously.
+ operationId: projects_delete
+ tags:
+ - Projects
+ parameters:
+ - name: projectId
+ in: path
+ required: true
+ schema:
+ type: string
+ responses:
+ '202':
+ description: ''
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/ProjectDeletionResponse'
+ '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
@@ -5369,6 +5468,17 @@ components:
required:
- id
- name
+ ProjectDeletionResponse:
+ title: ProjectDeletionResponse
+ type: object
+ properties:
+ success:
+ type: boolean
+ message:
+ type: string
+ required:
+ - success
+ - message
PromptMetaListResponse:
title: PromptMetaListResponse
type: object
diff --git a/web/public/generated/postman/collection.json b/web/public/generated/postman/collection.json
index 160145374d..bb52619a2f 100644
--- a/web/public/generated/postman/collection.json
+++ b/web/public/generated/postman/collection.json
@@ -1558,6 +1558,71 @@
"body": null
},
"response": []
+ },
+ {
+ "_type": "endpoint",
+ "name": "Create",
+ "request": {
+ "description": "Create a new project (requires organization-scoped API key)",
+ "url": {
+ "raw": "{{baseUrl}}/api/public/projects",
+ "host": [
+ "{{baseUrl}}"
+ ],
+ "path": [
+ "api",
+ "public",
+ "projects"
+ ],
+ "query": [],
+ "variable": []
+ },
+ "header": [],
+ "method": "POST",
+ "auth": null,
+ "body": {
+ "mode": "raw",
+ "raw": "{\n \"name\": \"example\"\n}",
+ "options": {
+ "raw": {
+ "language": "json"
+ }
+ }
+ }
+ },
+ "response": []
+ },
+ {
+ "_type": "endpoint",
+ "name": "Delete",
+ "request": {
+ "description": "Delete a project by ID (requires organization-scoped API key). Project deletion is processed asynchronously.",
+ "url": {
+ "raw": "{{baseUrl}}/api/public/projects/:projectId",
+ "host": [
+ "{{baseUrl}}"
+ ],
+ "path": [
+ "api",
+ "public",
+ "projects",
+ ":projectId"
+ ],
+ "query": [],
+ "variable": [
+ {
+ "key": "projectId",
+ "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.ts
index 2737f93a21..95d5c059a4 100644
--- a/web/src/__tests__/async/projects-api.servertest.ts
+++ b/web/src/__tests__/async/projects-api.servertest.ts
@@ -5,7 +5,12 @@ import {
makeAPICall,
} from "@/src/__tests__/test-utils";
import { z } from "zod";
-import { createBasicAuthHeader } from "@langfuse/shared/src/server";
+import {
+ createAndAddApiKeysToDb,
+ createBasicAuthHeader,
+} from "@langfuse/shared/src/server";
+import { prisma } from "@langfuse/shared/src/db";
+import { randomUUID } from "crypto";
// Schema for project response
const ProjectResponseSchema = z.object({
@@ -17,6 +22,18 @@ const ProjectResponseSchema = z.object({
),
});
+// Schema for project creation response
+const ProjectCreationResponseSchema = z.object({
+ id: z.string(),
+ name: z.string(),
+});
+
+// Schema for project deletion response
+const ProjectDeletionResponseSchema = z.object({
+ success: z.boolean(),
+ message: z.string(),
+});
+
describe("Public Projects API", () => {
// Test variables
const projectId = "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a";
@@ -25,6 +42,20 @@ describe("Public Projects API", () => {
const projectSecretKey = "sk-lf-1234567890";
const invalidApiKey = "pk-lf-invalid";
const invalidSecretKey = "sk-lf-invalid";
+ const orgApiKey = `pk-lf-org-${randomUUID().substring(0, 8)}`;
+ const orgSecretKey = `sk-lf-org-${randomUUID().substring(0, 8)}`;
+
+ beforeAll(async () => {
+ await createAndAddApiKeysToDb({
+ prisma,
+ entityId: "seed-org-id",
+ scope: "ORGANIZATION",
+ predefinedKeys: {
+ publicKey: orgApiKey,
+ secretKey: orgSecretKey,
+ },
+ });
+ });
describe("GET /api/public/projects", () => {
it("should return project data with valid project API key authentication", async () => {
@@ -58,7 +89,7 @@ describe("Public Projects API", () => {
it("should return 405 for non-GET methods", async () => {
const result = await makeAPICall(
- "POST",
+ "PUT", // Changed from POST to PUT since we now support POST
"/api/public/projects",
{},
createBasicAuthHeader(projectApiKey, projectSecretKey),
@@ -87,4 +118,224 @@ describe("Public Projects API", () => {
expect(secretKeyResult.status).toBe(401);
});
});
+
+ describe("POST /api/public/projects", () => {
+ // Clean up test projects after each test
+ afterEach(async () => {
+ // Delete any test projects created during tests
+ await prisma.project.deleteMany({
+ where: {
+ name: {
+ startsWith: "Test Project",
+ },
+ },
+ });
+ });
+
+ it("should create a new project with valid organization API key", async () => {
+ const uniqueProjectName = `Test Project ${randomUUID().substring(0, 8)}`;
+
+ const response = await makeZodVerifiedAPICall(
+ ProjectCreationResponseSchema,
+ "POST",
+ "/api/public/projects",
+ {
+ name: uniqueProjectName,
+ },
+ createBasicAuthHeader(orgApiKey, orgSecretKey),
+ 201, // Expected status code is 201 Created
+ );
+
+ expect(response.status).toBe(201);
+ expect(response.body).toMatchObject({
+ name: uniqueProjectName,
+ });
+ expect(response.body.id).toBeDefined();
+
+ // Verify the project was actually created in the database
+ const project = await prisma.project.findUnique({
+ where: { id: response.body.id },
+ });
+ expect(project).not.toBeNull();
+ expect(project?.name).toBe(uniqueProjectName);
+ });
+
+ it("should return 403 when using project API key instead of organization API key", async () => {
+ const uniqueProjectName = `Test Project ${randomUUID().substring(0, 8)}`;
+
+ const result = await makeAPICall(
+ "POST",
+ "/api/public/projects",
+ {
+ name: uniqueProjectName,
+ },
+ 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 uniqueProjectName = `Test Project ${randomUUID().substring(0, 8)}`;
+
+ const result = await makeAPICall(
+ "POST",
+ "/api/public/projects",
+ {
+ name: uniqueProjectName,
+ },
+ createBasicAuthHeader(invalidApiKey, invalidSecretKey),
+ );
+ expect(result.status).toBe(401);
+ expect(result.body.message).toContain("Invalid credentials");
+ });
+
+ it("should return 400 when project name is invalid", async () => {
+ // Test with a name that's too short
+ const shortNameResult = await makeAPICall(
+ "POST",
+ "/api/public/projects",
+ {
+ name: "AB", // Too short
+ },
+ createBasicAuthHeader(orgApiKey, orgSecretKey),
+ );
+ expect(shortNameResult.status).toBe(400);
+ expect(shortNameResult.body.message).toContain("Invalid project name");
+
+ // Test with a name that's too long
+ const longNameResult = await makeAPICall(
+ "POST",
+ "/api/public/projects",
+ {
+ name: "A".repeat(61), // Too long (more than 60 characters)
+ },
+ createBasicAuthHeader(orgApiKey, orgSecretKey),
+ );
+ expect(longNameResult.status).toBe(400);
+ expect(longNameResult.body.message).toContain("Invalid project name");
+ });
+
+ it("should return 409 when project name already exists in the organization", async () => {
+ const uniqueProjectName = `Test Project ${randomUUID().substring(0, 8)}`;
+
+ // First create a project
+ await makeAPICall(
+ "POST",
+ "/api/public/projects",
+ {
+ name: uniqueProjectName,
+ },
+ createBasicAuthHeader(orgApiKey, orgSecretKey),
+ );
+
+ // Try to create another project with the same name
+ const duplicateResult = await makeAPICall(
+ "POST",
+ "/api/public/projects",
+ {
+ name: uniqueProjectName,
+ },
+ createBasicAuthHeader(orgApiKey, orgSecretKey),
+ );
+ expect(duplicateResult.status).toBe(409);
+ expect(duplicateResult.body.message).toContain("already exists");
+ });
+ });
+
+ describe("DELETE /api/public/projects/[projectId]", () => {
+ let testProjectId: string;
+
+ beforeEach(async () => {
+ // Create a test project to delete
+ const uniqueProjectName = `Test Project ${randomUUID().substring(0, 8)}`;
+ const project = await prisma.project.create({
+ data: {
+ name: uniqueProjectName,
+ orgId: "seed-org-id", // Same org ID used for the API key
+ },
+ });
+ testProjectId = project.id;
+ });
+
+ afterEach(async () => {
+ // Clean up any remaining test projects
+ await prisma.project.deleteMany({
+ where: {
+ id: testProjectId,
+ },
+ });
+ });
+
+ it("should delete a project with valid organization API key", async () => {
+ const response = await makeZodVerifiedAPICall(
+ ProjectDeletionResponseSchema,
+ "DELETE",
+ `/api/public/projects/${testProjectId}`,
+ undefined,
+ createBasicAuthHeader(orgApiKey, orgSecretKey),
+ 202, // Expected status code is 202 Accepted
+ );
+
+ expect(response.status).toBe(202);
+ expect(response.body.success).toBe(true);
+ expect(response.body.message).toContain("being processed asynchronously");
+
+ // Verify the project was marked as deleted in the database
+ const project = await prisma.project.findUnique({
+ where: { id: testProjectId },
+ });
+ expect(project).not.toBeNull();
+ expect(project?.deletedAt).not.toBeNull();
+ });
+
+ it("should return 403 when using project API key instead of organization API key", async () => {
+ const result = await makeAPICall(
+ "DELETE",
+ `/api/public/projects/${testProjectId}`,
+ 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/${testProjectId}`,
+ undefined,
+ 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 result = await makeAPICall(
+ "DELETE",
+ `/api/public/projects/${nonExistentProjectId}`,
+ 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/${testProjectId}`,
+ undefined,
+ createBasicAuthHeader(orgApiKey, orgSecretKey),
+ );
+ expect(result.status).toBe(405);
+ expect(result.body.message).toContain("Method not allowed");
+ });
+ });
});
diff --git a/web/src/pages/api/public/projects.ts b/web/src/pages/api/public/projects.ts
deleted file mode 100644
index 87ff6fee1f..0000000000
--- a/web/src/pages/api/public/projects.ts
+++ /dev/null
@@ -1,68 +0,0 @@
-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 { isPrismaException } from "@/src/utils/exceptions";
-import { logger, redis } from "@langfuse/shared/src/server";
-
-import { type NextApiRequest, type NextApiResponse } from "next";
-
-export default async function handler(
- req: NextApiRequest,
- res: NextApiResponse,
-) {
- await runMiddleware(req, res, cors);
-
- // CHECK AUTH
- const authCheck = await new ApiAuthService(
- prisma,
- redis,
- ).verifyAuthHeaderAndReturnScope(req.headers.authorization);
- 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 AUTH
-
- if (req.method === "GET") {
- try {
- // Do not apply rate limits as it can break applications on lower tier plans when using auth_check in prod
-
- const projects = await prisma.project.findMany({
- select: {
- id: true,
- name: true,
- },
- where: {
- id: authCheck.scope.projectId,
- // deletedAt: null, // here we want to include deleted projects and grey them in the UI.
- },
- });
-
- return res.status(200).json({
- data: projects.map((project) => ({
- id: project.id,
- name: project.name,
- })),
- });
- } catch (error) {
- logger.error(error);
- if (isPrismaException(error)) {
- return res.status(500).json({
- error: "Internal Server Error",
- });
- }
- return res.status(500).json({ message: "Internal server error" });
- }
- } else {
- logger.error(
- `Method not allowed for ${req.method} on /api/public/projects`,
- );
- return res.status(405).json({ message: "Method not allowed" });
- }
-}
diff --git a/web/src/pages/api/public/projects/[projectId]/index.ts b/web/src/pages/api/public/projects/[projectId]/index.ts
new file mode 100644
index 0000000000..3510e5a0f8
--- /dev/null
+++ b/web/src/pages/api/public/projects/[projectId]/index.ts
@@ -0,0 +1,121 @@
+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,
+ QueueJobs,
+ ProjectDeleteQueue,
+} from "@langfuse/shared/src/server";
+import { randomUUID } from "crypto";
+
+import { type NextApiRequest, type NextApiResponse } from "next";
+
+export default async function handler(
+ req: NextApiRequest,
+ res: NextApiResponse,
+) {
+ await runMiddleware(req, res, cors);
+
+ const { projectId } = req.query;
+
+ if (typeof projectId !== "string") {
+ return res.status(400).json({ message: "Invalid project ID" });
+ }
+
+ if (req.method !== "DELETE") {
+ logger.error(
+ `Method not allowed for ${req.method} on /api/public/projects/${projectId}`,
+ );
+ return res.status(405).json({ message: "Method not allowed" });
+ }
+
+ // 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
+
+ try {
+ // 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",
+ });
+ }
+
+ // API keys need to be deleted from cache. Otherwise, they will still be valid.
+ await new ApiAuthService(prisma, redis).invalidateProjectApiKeys(projectId);
+
+ // Delete API keys from DB
+ await prisma.apiKey.deleteMany({
+ where: {
+ projectId: projectId,
+ scope: "PROJECT",
+ },
+ });
+
+ // Mark project as deleted
+ await prisma.project.update({
+ where: {
+ id: projectId,
+ orgId: authCheck.scope.orgId,
+ },
+ data: {
+ deletedAt: new Date(),
+ },
+ });
+
+ // Queue project deletion job
+ const projectDeleteQueue = ProjectDeleteQueue.getInstance();
+ if (!projectDeleteQueue) {
+ logger.error("ProjectDeleteQueue is not available");
+ return res.status(500).json({
+ message: "Internal server error",
+ });
+ }
+
+ await projectDeleteQueue.add(QueueJobs.ProjectDelete, {
+ timestamp: new Date(),
+ id: randomUUID(),
+ payload: {
+ projectId: projectId,
+ orgId: authCheck.scope.orgId,
+ },
+ name: QueueJobs.ProjectDelete,
+ });
+
+ return res.status(202).json({
+ success: true,
+ message:
+ "Project deletion has been initiated and is being processed asynchronously",
+ });
+ } catch (error) {
+ logger.error("Failed to delete project", error);
+ return res.status(500).json({ message: "Internal server error" });
+ }
+}
diff --git a/web/src/pages/api/public/projects/index.ts b/web/src/pages/api/public/projects/index.ts
new file mode 100644
index 0000000000..56c953d663
--- /dev/null
+++ b/web/src/pages/api/public/projects/index.ts
@@ -0,0 +1,127 @@
+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 { type NextApiRequest, type NextApiResponse } from "next";
+import { projectNameSchema } from "@/src/features/auth/lib/projectNameSchema";
+
+export default async function handler(
+ req: NextApiRequest,
+ res: NextApiResponse,
+) {
+ await runMiddleware(req, res, cors);
+
+ if (req.method !== "GET" && req.method !== "POST") {
+ logger.error(
+ `Method not allowed for ${req.method} on /api/public/projects`,
+ );
+ return res.status(405).json({ message: "Method not allowed" });
+ }
+
+ // CHECK AUTH
+ const authCheck = await new ApiAuthService(
+ prisma,
+ redis,
+ ).verifyAuthHeaderAndReturnScope(req.headers.authorization);
+ if (!authCheck.validKey) {
+ return res.status(401).json({
+ message: authCheck.error,
+ });
+ }
+ // END CHECK AUTH
+
+ if (req.method === "GET") {
+ if (
+ authCheck.scope.accessLevel !== "project" ||
+ !authCheck.scope.projectId
+ ) {
+ return res.status(403).json({
+ message: "Invalid API key. Are you using an organization key?",
+ });
+ }
+
+ try {
+ // Do not apply rate limits as it can break applications on lower tier plans when using auth_check in prod
+
+ const projects = await prisma.project.findMany({
+ select: {
+ id: true,
+ name: true,
+ },
+ where: {
+ id: authCheck.scope.projectId,
+ // deletedAt: null, // here we want to include deleted projects and grey them in the UI.
+ },
+ });
+
+ return res.status(200).json({
+ data: projects.map((project) => ({
+ id: project.id,
+ name: project.name,
+ })),
+ });
+ } catch (error) {
+ logger.error(error);
+ return res.status(500).json({ message: "Internal server error" });
+ }
+ }
+
+ if (req.method === "POST") {
+ // 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.",
+ });
+ }
+
+ try {
+ const { name } = req.body;
+
+ // Validate project name
+ try {
+ projectNameSchema.parse({ name });
+ } catch (error) {
+ return res.status(400).json({
+ message:
+ "Invalid project name length. Should be between 3 and 30 characters.",
+ });
+ }
+
+ // Check if project with this name already exists in the organization
+ const existingProject = await prisma.project.findFirst({
+ where: {
+ name,
+ orgId: authCheck.scope.orgId,
+ },
+ });
+
+ if (existingProject) {
+ return res.status(409).json({
+ message:
+ "A project with this name already exists in your organization",
+ });
+ }
+
+ // Create the project
+ const project = await prisma.project.create({
+ data: {
+ name,
+ orgId: authCheck.scope.orgId,
+ },
+ });
+
+ return res.status(201).json({
+ id: project.id,
+ name: project.name,
+ });
+ } catch (error) {
+ logger.error("Failed to create project", error);
+ return res.status(500).json({ message: "Internal server error" });
+ }
+ }
+}