Skip to content

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

feat: add endpoints to manage project and organization memberships (#6449)

Steffen Schmitz3b4811599dc6
diff --git a/fern/apis/server/definition/memberships.yml b/fern/apis/server/definition/memberships.yml
new file mode 100644
index 0000000000..3c40016ee0
--- /dev/null
+++ b/fern/apis/server/definition/memberships.yml
@@ -0,0 +1,62 @@
+# yaml-language-server: $schema=https://raw.githubusercontent.com/fern-api/fern/main/fern.schema.json
+imports:
+ commons: ./commons.yml
+ pagination: ./utils/pagination.yml
+
+service:
+ auth: true
+ base-path: /api/public
+ endpoints:
+ getOrganizationMemberships:
+ docs: Get all memberships for the organization associated with the API key (requires organization-scoped API key)
+ method: GET
+ path: /organizations/memberships
+ response: MembershipsResponse
+
+ updateOrganizationMembership:
+ docs: Create or update a membership for the organization associated with the API key (requires organization-scoped API key)
+ method: PUT
+ path: /organizations/memberships
+ request: MembershipRequest
+ response: MembershipResponse
+
+ getProjectMemberships:
+ docs: Get all memberships for a specific project (requires organization-scoped API key)
+ method: GET
+ path: /projects/{projectId}/memberships
+ path-parameters:
+ projectId: string
+ response: MembershipsResponse
+
+ updateProjectMembership:
+ docs: Create or update a membership for a specific project (requires organization-scoped API key). The user must already be a member of the organization.
+ method: PUT
+ path: /projects/{projectId}/memberships
+ path-parameters:
+ projectId: string
+ request: MembershipRequest
+ response: MembershipResponse
+
+types:
+ MembershipRole:
+ enum:
+ - OWNER
+ - ADMIN
+ - MEMBER
+ - VIEWER
+
+ MembershipRequest:
+ properties:
+ userId: string
+ role: MembershipRole
+
+ MembershipResponse:
+ properties:
+ userId: string
+ role: MembershipRole
+ email: string
+ name: string
+
+ MembershipsResponse:
+ properties:
+ memberships: list<MembershipResponse>
\ No newline at end of file
diff --git a/web/public/generated/api/openapi.yml b/web/public/generated/api/openapi.yml
index 12c44f08d4..8017f2657d 100644
--- a/web/public/generated/api/openapi.yml
+++ b/web/public/generated/api/openapi.yml
@@ -1499,6 +1499,199 @@ paths:
application/json:
schema:
$ref: '#/components/schemas/GetMediaUploadUrlRequest'
+ /api/public/organizations/memberships:
+ get:
+ description: >-
+ Get all memberships for the organization associated with the API key
+ (requires organization-scoped API key)
+ operationId: memberships_getOrganizationMemberships
+ tags:
+ - Memberships
+ parameters: []
+ responses:
+ '200':
+ description: ''
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/MembershipsResponse'
+ '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: []
+ put:
+ description: >-
+ Create or update a membership for the organization associated with the
+ API key (requires organization-scoped API key)
+ operationId: memberships_updateOrganizationMembership
+ tags:
+ - Memberships
+ parameters: []
+ responses:
+ '200':
+ description: ''
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/MembershipResponse'
+ '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:
+ $ref: '#/components/schemas/MembershipRequest'
+ /api/public/projects/{projectId}/memberships:
+ get:
+ description: >-
+ Get all memberships for a specific project (requires organization-scoped
+ API key)
+ operationId: memberships_getProjectMemberships
+ tags:
+ - Memberships
+ parameters:
+ - name: projectId
+ in: path
+ required: true
+ schema:
+ type: string
+ responses:
+ '200':
+ description: ''
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/MembershipsResponse'
+ '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: []
+ put:
+ description: >-
+ Create or update a membership for a specific project (requires
+ organization-scoped API key). The user must already be a member of the
+ organization.
+ operationId: memberships_updateProjectMembership
+ tags:
+ - Memberships
+ parameters:
+ - name: projectId
+ in: path
+ required: true
+ schema:
+ type: string
+ responses:
+ '200':
+ description: ''
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/MembershipResponse'
+ '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:
+ $ref: '#/components/schemas/MembershipRequest'
/api/public/metrics/daily:
get:
description: Get daily metrics of the Langfuse project
@@ -5631,6 +5824,52 @@ components:
- application/xml
- application/octet-stream
description: The MIME type of the media record
+ MembershipRole:
+ title: MembershipRole
+ type: string
+ enum:
+ - OWNER
+ - ADMIN
+ - MEMBER
+ - VIEWER
+ MembershipRequest:
+ title: MembershipRequest
+ type: object
+ properties:
+ userId:
+ type: string
+ role:
+ $ref: '#/components/schemas/MembershipRole'
+ required:
+ - userId
+ - role
+ MembershipResponse:
+ title: MembershipResponse
+ type: object
+ properties:
+ userId:
+ type: string
+ role:
+ $ref: '#/components/schemas/MembershipRole'
+ email:
+ type: string
+ name:
+ type: string
+ required:
+ - userId
+ - role
+ - email
+ - name
+ MembershipsResponse:
+ title: MembershipsResponse
+ type: object
+ properties:
+ memberships:
+ type: array
+ items:
+ $ref: '#/components/schemas/MembershipResponse'
+ required:
+ - memberships
DailyMetrics:
title: DailyMetrics
type: object
diff --git a/web/public/generated/postman/collection.json b/web/public/generated/postman/collection.json
index cb184995ef..427f47edd6 100644
--- a/web/public/generated/postman/collection.json
+++ b/web/public/generated/postman/collection.json
@@ -1195,6 +1195,147 @@
}
]
},
+ {
+ "_type": "container",
+ "description": null,
+ "name": "Memberships",
+ "item": [
+ {
+ "_type": "endpoint",
+ "name": "Get Organization Memberships",
+ "request": {
+ "description": "Get all memberships for the organization associated with the API key (requires organization-scoped API key)",
+ "url": {
+ "raw": "{{baseUrl}}/api/public/organizations/memberships",
+ "host": [
+ "{{baseUrl}}"
+ ],
+ "path": [
+ "api",
+ "public",
+ "organizations",
+ "memberships"
+ ],
+ "query": [],
+ "variable": []
+ },
+ "header": [],
+ "method": "GET",
+ "auth": null,
+ "body": null
+ },
+ "response": []
+ },
+ {
+ "_type": "endpoint",
+ "name": "Update Organization Membership",
+ "request": {
+ "description": "Create or update a membership for the organization associated with the API key (requires organization-scoped API key)",
+ "url": {
+ "raw": "{{baseUrl}}/api/public/organizations/memberships",
+ "host": [
+ "{{baseUrl}}"
+ ],
+ "path": [
+ "api",
+ "public",
+ "organizations",
+ "memberships"
+ ],
+ "query": [],
+ "variable": []
+ },
+ "header": [],
+ "method": "PUT",
+ "auth": null,
+ "body": {
+ "mode": "raw",
+ "raw": "{\n \"userId\": \"example\",\n \"role\": \"OWNER\"\n}",
+ "options": {
+ "raw": {
+ "language": "json"
+ }
+ }
+ }
+ },
+ "response": []
+ },
+ {
+ "_type": "endpoint",
+ "name": "Get Project Memberships",
+ "request": {
+ "description": "Get all memberships for a specific project (requires organization-scoped API key)",
+ "url": {
+ "raw": "{{baseUrl}}/api/public/projects/:projectId/memberships",
+ "host": [
+ "{{baseUrl}}"
+ ],
+ "path": [
+ "api",
+ "public",
+ "projects",
+ ":projectId",
+ "memberships"
+ ],
+ "query": [],
+ "variable": [
+ {
+ "key": "projectId",
+ "value": "",
+ "description": null
+ }
+ ]
+ },
+ "header": [],
+ "method": "GET",
+ "auth": null,
+ "body": null
+ },
+ "response": []
+ },
+ {
+ "_type": "endpoint",
+ "name": "Update Project Membership",
+ "request": {
+ "description": "Create or update a membership for a specific project (requires organization-scoped API key). The user must already be a member of the organization.",
+ "url": {
+ "raw": "{{baseUrl}}/api/public/projects/:projectId/memberships",
+ "host": [
+ "{{baseUrl}}"
+ ],
+ "path": [
+ "api",
+ "public",
+ "projects",
+ ":projectId",
+ "memberships"
+ ],
+ "query": [],
+ "variable": [
+ {
+ "key": "projectId",
+ "value": "",
+ "description": null
+ }
+ ]
+ },
+ "header": [],
+ "method": "PUT",
+ "auth": null,
+ "body": {
+ "mode": "raw",
+ "raw": "{\n \"userId\": \"example\",\n \"role\": \"OWNER\"\n}",
+ "options": {
+ "raw": {
+ "language": "json"
+ }
+ }
+ }
+ },
+ "response": []
+ }
+ ]
+ },
{
"_type": "container",
"description": null,
diff --git a/web/src/__tests__/async/memberships-api.servertest.ts b/web/src/__tests__/async/memberships-api.servertest.ts
new file mode 100644
index 0000000000..40e3fff537
--- /dev/null
+++ b/web/src/__tests__/async/memberships-api.servertest.ts
@@ -0,0 +1,408 @@
+/** @jest-environment node */
+
+import {
+ makeZodVerifiedAPICall,
+ makeAPICall,
+} from "@/src/__tests__/test-utils";
+import { prisma } from "@langfuse/shared/src/db";
+import { z } from "zod";
+import { randomUUID } from "crypto";
+import { Role } from "@langfuse/shared";
+import {
+ createAndAddApiKeysToDb,
+ createBasicAuthHeader,
+} from "@langfuse/shared/src/server";
+
+// Schema for membership response
+const MembershipResponseSchema = z.object({
+ userId: z.string(),
+ role: z.nativeEnum(Role),
+ email: z.string().email(),
+ name: z.string().nullable(),
+});
+
+// Schema for memberships list response
+const MembershipsListSchema = z.object({
+ memberships: z.array(MembershipResponseSchema),
+});
+
+describe("Memberships APIs", () => {
+ // Create test data
+ let testOrgId: string;
+ let testProjectId: string;
+ let testUserId: string;
+ let testApiKey: string;
+ let testApiSecretKey: string;
+
+ beforeAll(async () => {
+ // Create a test organization
+ const uniqueOrgName = `Test Org ${randomUUID().substring(0, 8)}`;
+ const org = await prisma.organization.create({
+ data: { name: uniqueOrgName, cloudConfig: { plan: "Team" } },
+ });
+ testOrgId = org.id;
+
+ // Create a test project
+ const uniqueProjectName = `Test Project ${randomUUID().substring(0, 8)}`;
+ const project = await prisma.project.create({
+ data: {
+ name: uniqueProjectName,
+ orgId: testOrgId,
+ },
+ });
+ testProjectId = project.id;
+
+ // Create a test user
+ const uniqueUserEmail = `test-user-${randomUUID().substring(0, 8)}@example.com`;
+ const user = await prisma.user.create({
+ data: {
+ email: uniqueUserEmail,
+ name: `Test User ${randomUUID().substring(0, 8)}`,
+ },
+ });
+ testUserId = user.id;
+
+ // Create an organization API key
+ const apiKey = await createAndAddApiKeysToDb({
+ prisma,
+ entityId: testOrgId,
+ scope: "ORGANIZATION",
+ note: "Test API Key for Memberships API",
+ predefinedKeys: {
+ publicKey: `pk-lf-org-${randomUUID().substring(0, 8)}`,
+ secretKey: `sk-lf-org-${randomUUID().substring(0, 8)}`,
+ },
+ });
+ testApiKey = apiKey.publicKey;
+ testApiSecretKey = apiKey.secretKey;
+ });
+
+ afterAll(async () => {
+ // Clean up test data
+ await prisma.user.delete({
+ where: {
+ id: testUserId,
+ },
+ });
+ await prisma.organization.delete({
+ where: {
+ id: testOrgId,
+ },
+ });
+ });
+
+ describe("Project Memberships", () => {
+ describe("GET /api/public/projects/[projectId]/memberships", () => {
+ it("should get all project memberships with valid API key", async () => {
+ // First create an organization membership for the test user
+ const orgMembership = await prisma.organizationMembership.create({
+ data: {
+ userId: testUserId,
+ orgId: testOrgId,
+ role: Role.MEMBER,
+ },
+ });
+
+ // Then create a project membership
+ await prisma.projectMembership.create({
+ data: {
+ userId: testUserId,
+ projectId: testProjectId,
+ role: Role.VIEWER,
+ orgMembershipId: orgMembership.id,
+ },
+ });
+
+ const response = await makeZodVerifiedAPICall(
+ MembershipsListSchema,
+ "GET",
+ `/api/public/projects/${testProjectId}/memberships`,
+ undefined,
+ createBasicAuthHeader(testApiKey, testApiSecretKey),
+ 200,
+ );
+
+ expect(response.status).toBe(200);
+ expect(Array.isArray(response.body.memberships)).toBe(true);
+ expect(response.body.memberships.length).toBeGreaterThan(0);
+ expect(
+ response.body.memberships.some(
+ (membership) => membership.userId === testUserId,
+ ),
+ ).toBe(true);
+
+ const membership = response.body.memberships.find(
+ (m) => m.userId === testUserId,
+ );
+ expect(membership?.role).toBe(Role.VIEWER);
+ });
+
+ it("should return 403 when using a non-organization API key", async () => {
+ // Create a project API key
+ const projectApiKey = await createAndAddApiKeysToDb({
+ prisma,
+ entityId: testProjectId,
+ scope: "PROJECT",
+ note: "Test API Key for Memberships API",
+ predefinedKeys: {
+ publicKey: `pk-lf-project-${randomUUID().substring(0, 8)}`,
+ secretKey: `sk-lf-project-${randomUUID().substring(0, 8)}`,
+ },
+ });
+
+ const result = await makeAPICall(
+ "GET",
+ `/api/public/projects/${testProjectId}/memberships`,
+ undefined,
+ createBasicAuthHeader(
+ projectApiKey.publicKey,
+ projectApiKey.secretKey,
+ ),
+ );
+ expect(result.status).toBe(403);
+
+ // Clean up
+ await prisma.apiKey.delete({
+ where: {
+ id: projectApiKey.id,
+ },
+ });
+ });
+ });
+
+ describe("PUT /api/public/projects/[projectId]/memberships", () => {
+ it("should create a new project membership with valid API key", async () => {
+ // First ensure the user has an organization membership
+ await prisma.organizationMembership.upsert({
+ where: {
+ orgId_userId: {
+ userId: testUserId,
+ orgId: testOrgId,
+ },
+ },
+ update: {},
+ create: {
+ userId: testUserId,
+ orgId: testOrgId,
+ role: Role.MEMBER,
+ },
+ });
+
+ // Delete any existing project membership
+ await prisma.projectMembership.deleteMany({
+ where: {
+ userId: testUserId,
+ projectId: testProjectId,
+ },
+ });
+
+ const response = await makeZodVerifiedAPICall(
+ MembershipResponseSchema,
+ "PUT",
+ `/api/public/projects/${testProjectId}/memberships`,
+ {
+ userId: testUserId,
+ role: Role.ADMIN,
+ },
+ createBasicAuthHeader(testApiKey, testApiSecretKey),
+ 200,
+ );
+
+ expect(response.status).toBe(200);
+ expect(response.body.userId).toBe(testUserId);
+ expect(response.body.role).toBe(Role.ADMIN);
+
+ // Verify the membership was created in the database
+ const membership = await prisma.projectMembership.findUnique({
+ where: {
+ projectId_userId: {
+ userId: testUserId,
+ projectId: testProjectId,
+ },
+ },
+ });
+ expect(membership?.role).toBe(Role.ADMIN);
+ });
+
+ it("should update an existing project membership with valid API key", async () => {
+ const response = await makeZodVerifiedAPICall(
+ MembershipResponseSchema,
+ "PUT",
+ `/api/public/projects/${testProjectId}/memberships`,
+ {
+ userId: testUserId,
+ role: Role.OWNER,
+ },
+ createBasicAuthHeader(testApiKey, testApiSecretKey),
+ 200,
+ );
+
+ expect(response.status).toBe(200);
+ expect(response.body.userId).toBe(testUserId);
+ expect(response.body.role).toBe(Role.OWNER);
+
+ // Verify the role was updated in the database
+ const membership = await prisma.projectMembership.findUnique({
+ where: {
+ projectId_userId: {
+ userId: testUserId,
+ projectId: testProjectId,
+ },
+ },
+ });
+ expect(membership?.role).toBe(Role.OWNER);
+ });
+
+ it("should return 404 when user is not a member of the organization", async () => {
+ // Create a new user that is not a member of the organization
+ const newUser = await prisma.user.create({
+ data: {
+ email: `test-user-${randomUUID().substring(0, 8)}@example.com`,
+ name: `New Test User`,
+ },
+ });
+
+ const result = await makeAPICall(
+ "PUT",
+ `/api/public/projects/${testProjectId}/memberships`,
+ {
+ userId: newUser.id,
+ role: Role.VIEWER,
+ },
+ createBasicAuthHeader(testApiKey, testApiSecretKey),
+ );
+ expect(result.status).toBe(404);
+
+ // Clean up
+ await prisma.user.delete({
+ where: {
+ id: newUser.id,
+ },
+ });
+ });
+ });
+ });
+
+ describe("Organization Memberships", () => {
+ describe("GET /api/public/organizations/memberships", () => {
+ it("should get all organization memberships with valid API key", async () => {
+ // First ensure the membership exists
+ await prisma.organizationMembership.upsert({
+ where: {
+ orgId_userId: {
+ userId: testUserId,
+ orgId: testOrgId,
+ },
+ },
+ update: {},
+ create: {
+ userId: testUserId,
+ orgId: testOrgId,
+ role: Role.MEMBER,
+ },
+ });
+
+ const response = await makeZodVerifiedAPICall(
+ MembershipsListSchema,
+ "GET",
+ `/api/public/organizations/memberships`,
+ undefined,
+ createBasicAuthHeader(testApiKey, testApiSecretKey),
+ 200,
+ );
+
+ expect(response.status).toBe(200);
+ expect(Array.isArray(response.body.memberships)).toBe(true);
+ expect(response.body.memberships.length).toBeGreaterThan(0);
+ expect(
+ response.body.memberships.some(
+ (membership) => membership.userId === testUserId,
+ ),
+ ).toBe(true);
+ });
+ });
+
+ describe("PUT /api/public/organizations/memberships", () => {
+ it("should create a new organization membership with valid API key", async () => {
+ // First delete any existing membership
+ await prisma.organizationMembership.deleteMany({
+ where: {
+ userId: testUserId,
+ orgId: testOrgId,
+ },
+ });
+
+ const response = await makeZodVerifiedAPICall(
+ MembershipResponseSchema,
+ "PUT",
+ `/api/public/organizations/memberships`,
+ {
+ userId: testUserId,
+ role: Role.ADMIN,
+ },
+ createBasicAuthHeader(testApiKey, testApiSecretKey),
+ 200,
+ );
+
+ expect(response.status).toBe(200);
+ expect(response.body.userId).toBe(testUserId);
+ expect(response.body.role).toBe(Role.ADMIN);
+
+ // Verify the membership was created in the database
+ const membership = await prisma.organizationMembership.findUnique({
+ where: {
+ orgId_userId: {
+ userId: testUserId,
+ orgId: testOrgId,
+ },
+ },
+ });
+ expect(membership?.role).toBe(Role.ADMIN);
+ });
+
+ it("should update an existing organization membership with valid API key", async () => {
+ const response = await makeZodVerifiedAPICall(
+ MembershipResponseSchema,
+ "PUT",
+ `/api/public/organizations/memberships`,
+ {
+ userId: testUserId,
+ role: Role.OWNER,
+ },
+ createBasicAuthHeader(testApiKey, testApiSecretKey),
+ 200,
+ );
+
+ expect(response.status).toBe(200);
+ expect(response.body.userId).toBe(testUserId);
+ expect(response.body.role).toBe(Role.OWNER);
+
+ // Verify the role was updated in the database
+ const membership = await prisma.organizationMembership.findUnique({
+ where: {
+ orgId_userId: {
+ userId: testUserId,
+ orgId: testOrgId,
+ },
+ },
+ });
+ expect(membership?.role).toBe(Role.OWNER);
+ });
+
+ it("should return 404 when user does not exist", async () => {
+ const nonExistentUserId = `user-${randomUUID()}`;
+
+ const result = await makeAPICall(
+ "PUT",
+ `/api/public/organizations/memberships`,
+ {
+ userId: nonExistentUserId,
+ role: Role.VIEWER,
+ },
+ createBasicAuthHeader(testApiKey, testApiSecretKey),
+ );
+ expect(result.status).toBe(404);
+ });
+ });
+ });
+});
diff --git a/web/src/pages/api/public/organizations/memberships/index.ts b/web/src/pages/api/public/organizations/memberships/index.ts
new file mode 100644
index 0000000000..df8c4fe20b
--- /dev/null
+++ b/web/src/pages/api/public/organizations/memberships/index.ts
@@ -0,0 +1,160 @@
+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 { Role } from "@langfuse/shared";
+import { z } from "zod";
+
+import { type NextApiRequest, type NextApiResponse } from "next";
+
+// Schema for request body validation
+const MembershipSchema = z.object({
+ userId: z.string(),
+ role: z.nativeEnum(Role),
+});
+
+export default async function handler(
+ req: NextApiRequest,
+ res: NextApiResponse,
+) {
+ await runMiddleware(req, res, cors);
+
+ if (!["GET", "PUT"].includes(req.method || "")) {
+ logger.error(
+ `Method not allowed for ${req.method} on /api/public/organizations/memberships`,
+ );
+ 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.",
+ });
+ }
+
+ // Route to the appropriate handler based on HTTP method
+ try {
+ switch (req.method) {
+ case "GET":
+ return handleGet(req, res, authCheck.scope.orgId);
+ case "PUT":
+ return handlePut(req, res, authCheck.scope.orgId);
+ default:
+ // This should never happen due to the check at the beginning
+ return res.status(405).json({
+ error: "Method not allowed",
+ });
+ }
+ } catch (error) {
+ logger.error(
+ `Error handling organization memberships for ${req.method}`,
+ error,
+ );
+ return res.status(500).json({
+ error: "Internal server error",
+ });
+ }
+}
+
+// GET - Retrieve all organization memberships
+async function handleGet(
+ req: NextApiRequest,
+ res: NextApiResponse,
+ orgId: string,
+) {
+ const memberships = await prisma.organizationMembership.findMany({
+ where: {
+ orgId: orgId,
+ },
+ include: {
+ user: {
+ select: {
+ id: true,
+ email: true,
+ name: true,
+ },
+ },
+ },
+ });
+
+ return res.status(200).json({
+ memberships: memberships.map((membership) => ({
+ userId: membership.userId,
+ role: membership.role,
+ email: membership.user.email,
+ name: membership.user.name,
+ })),
+ });
+}
+
+// PUT - Update or create an organization membership
+async function handlePut(
+ req: NextApiRequest,
+ res: NextApiResponse,
+ orgId: string,
+) {
+ const validatedBody = MembershipSchema.safeParse(req.body);
+ if (!validatedBody.success) {
+ return res.status(400).json({
+ error: "Invalid request body",
+ details: validatedBody.error.errors,
+ });
+ }
+
+ // Check if user exists
+ const user = await prisma.user.findUnique({
+ where: {
+ id: validatedBody.data.userId,
+ },
+ });
+
+ if (!user) {
+ return res.status(404).json({
+ error: "User not found",
+ });
+ }
+
+ // Upsert the membership
+ const membership = await prisma.organizationMembership.upsert({
+ where: {
+ orgId_userId: {
+ orgId,
+ userId: validatedBody.data.userId,
+ },
+ },
+ update: {
+ role: validatedBody.data.role,
+ },
+ create: {
+ orgId,
+ userId: validatedBody.data.userId,
+ role: validatedBody.data.role,
+ },
+ });
+
+ return res.status(200).json({
+ userId: membership.userId,
+ role: membership.role,
+ email: user.email,
+ name: user.name,
+ });
+}
diff --git a/web/src/pages/api/public/projects/[projectId]/memberships/index.ts b/web/src/pages/api/public/projects/[projectId]/memberships/index.ts
new file mode 100644
index 0000000000..6083f1c7b9
--- /dev/null
+++ b/web/src/pages/api/public/projects/[projectId]/memberships/index.ts
@@ -0,0 +1,212 @@
+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 { Role } from "@langfuse/shared";
+import { z } from "zod";
+import { hasEntitlementBasedOnPlan } from "@/src/features/entitlements/server/hasEntitlement";
+
+import { type NextApiRequest, type NextApiResponse } from "next";
+
+// Schema for request body validation
+const MembershipSchema = z.object({
+ userId: z.string(),
+ role: z.nativeEnum(Role),
+});
+
+export default async function handler(
+ req: NextApiRequest,
+ res: NextApiResponse,
+) {
+ await runMiddleware(req, res, cors);
+
+ if (!["GET", "PUT"].includes(req.method || "")) {
+ logger.error(
+ `Method not allowed for ${req.method} on /api/public/projects/[projectId]/memberships`,
+ );
+ return res.status(405).json({
+ error: "Method not allowed",
+ });
+ }
+
+ const { projectId } = req.query;
+ if (!projectId || typeof projectId !== "string") {
+ return res.status(400).json({
+ error: "projectId is required",
+ });
+ }
+
+ // 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.",
+ });
+ }
+
+ // Check if organization has the rbac-project-roles entitlement
+ if (
+ !hasEntitlementBasedOnPlan({
+ plan: authCheck.scope.plan,
+ entitlement: "rbac-project-roles",
+ })
+ ) {
+ return res.status(403).json({
+ error: "Your plan does not include project role management.",
+ });
+ }
+
+ // Verify the project belongs to the organization
+ const project = await prisma.project.findFirst({
+ where: {
+ id: projectId,
+ orgId: authCheck.scope.orgId,
+ deletedAt: null,
+ },
+ });
+
+ if (!project) {
+ return res.status(404).json({
+ error: "Project not found or does not belong to this organization",
+ });
+ }
+
+ // Route to the appropriate handler based on HTTP method
+ try {
+ switch (req.method) {
+ case "GET":
+ return handleGet(req, res, projectId, authCheck.scope.orgId);
+ case "PUT":
+ return handlePut(req, res, projectId, authCheck.scope.orgId);
+ default:
+ // This should never happen due to the check at the beginning
+ return res.status(405).json({
+ error: "Method not allowed",
+ });
+ }
+ } catch (error) {
+ logger.error(
+ `Error handling project memberships for ${req.method} on project ${projectId}`,
+ error,
+ );
+ return res.status(500).json({
+ error: "Internal server error",
+ });
+ }
+}
+
+// GET - Retrieve all project memberships
+async function handleGet(
+ req: NextApiRequest,
+ res: NextApiResponse,
+ projectId: string,
+ orgId: string,
+) {
+ const memberships = await prisma.projectMembership.findMany({
+ where: {
+ projectId,
+ organizationMembership: {
+ orgId,
+ },
+ },
+ include: {
+ user: {
+ select: {
+ id: true,
+ email: true,
+ name: true,
+ },
+ },
+ },
+ });
+
+ return res.status(200).json({
+ memberships: memberships.map((membership) => ({
+ userId: membership.userId,
+ role: membership.role,
+ email: membership.user.email,
+ name: membership.user.name,
+ })),
+ });
+}
+
+// PUT - Update or create a project membership
+async function handlePut(
+ req: NextApiRequest,
+ res: NextApiResponse,
+ projectId: string,
+ orgId: string,
+) {
+ const validatedBody = MembershipSchema.safeParse(req.body);
+ if (!validatedBody.success) {
+ return res.status(400).json({
+ error: "Invalid request body",
+ details: validatedBody.error.errors,
+ });
+ }
+
+ // Check if user exists and is a member of the organization
+ const orgMembership = await prisma.organizationMembership.findUnique({
+ where: {
+ orgId_userId: {
+ userId: validatedBody.data.userId,
+ orgId: orgId,
+ },
+ },
+ include: {
+ user: {
+ select: {
+ email: true,
+ name: true,
+ },
+ },
+ },
+ });
+
+ if (!orgMembership) {
+ return res.status(404).json({
+ error: "User is not a member of this organization",
+ });
+ }
+
+ // Upsert the project membership
+ const membership = await prisma.projectMembership.upsert({
+ where: {
+ projectId_userId: {
+ userId: validatedBody.data.userId,
+ projectId: projectId,
+ },
+ },
+ update: {
+ role: validatedBody.data.role,
+ },
+ create: {
+ userId: validatedBody.data.userId,
+ projectId: projectId,
+ role: validatedBody.data.role,
+ orgMembershipId: orgMembership.id,
+ },
+ });
+
+ return res.status(200).json({
+ userId: membership.userId,
+ role: membership.role,
+ email: orgMembership.user.email,
+ name: orgMembership.user.name,
+ });
+}