🪢 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 PUT operations on SCIM users endpoint (#8236)
Steffen Schmitze3b23ea5ec0e
diff --git a/web/src/__tests__/async/scim-api.servertest.ts b/web/src/__tests__/async/scim-api.servertest.tsindex 7d8616f241..2dd8458de5 100644--- a/web/src/__tests__/async/scim-api.servertest.ts+++ b/web/src/__tests__/async/scim-api.servertest.ts@@ -18,16 +18,20 @@ const ScimUserSchema = z.object({schemas: z.array(z.string()),id: z.string(),userName: z.string(),- name: z.object({- formatted: z.string().nullable(),- }),- emails: z.array(- z.object({- primary: z.boolean(),- value: z.string(),- type: z.string(),- }),- ),+ name: z+ .object({+ formatted: z.string().nullable(),+ })+ .optional(),+ emails: z+ .array(+ z.object({+ primary: z.boolean(),+ value: z.string(),+ type: z.string(),+ }),+ )+ .optional(),meta: z.object({resourceType: z.string(),created: z.string().optional(),@@ -533,6 +537,45 @@ describe("SCIM API", () => {expect(result.body.detail).toContain("userName is required");});+ it("should create a new user with specified role", async () => {+ const uniqueEmail = `test.user.${randomUUID().substring(0, 8)}@example.com`;+ const response = await makeZodVerifiedAPICall(+ ScimUserSchema,+ "POST",+ "/api/public/scim/Users",+ {+ userName: uniqueEmail,+ name: {+ formatted: "Test User With Role",+ },+ emails: [+ {+ primary: true,+ value: uniqueEmail,+ type: "work",+ },+ ],+ active: true,+ roles: ["ADMIN"],+ },+ createBasicAuthHeader(orgApiKey, orgSecretKey),+ 201,+ );++ expect(response.status).toBe(201);+ expect(response.body.userName).toBe(uniqueEmail);+ expect(response.body.name.formatted).toBe("Test User With Role");++ testUserId = response.body.id;++ // Verify the user was created with the specified role+ const orgMemberships = await prisma.organizationMembership.findMany({+ where: { userId: testUserId, orgId: orgId },+ });+ expect(orgMemberships.length).toBe(1);+ expect(orgMemberships[0].role).toBe("ADMIN");+ });+it("should return 409 when user with the same userName already exists", async () => {const uniqueEmail = `test.user.${randomUUID().substring(0, 8)}@example.com`;@@ -617,6 +660,147 @@ describe("SCIM API", () => {});});+ describe("PUT /api/public/scim/Users/{id}", () => {+ beforeEach(async () => {+ // Create a test user+ const uniqueEmail = `test.user.${randomUUID().substring(0, 8)}@example.com`;+ const user = await prisma.user.create({+ data: {+ email: uniqueEmail,+ name: "Test User",+ },+ });+ await prisma.organizationMembership.create({+ data: {+ userId: user.id,+ orgId: orgId,+ role: "NONE",+ },+ });+ testUserId = user.id;+ });++ it("should deactivate a user when active is false", async () => {+ const response = await makeZodVerifiedAPICall(+ ScimUserSchema,+ "PUT",+ `/api/public/scim/Users/${testUserId}`,+ {+ schemas: ["urn:ietf:params:scim:schemas:core:2.0:User"],+ id: testUserId,+ userName: "[email protected]",+ active: false,+ },+ createBasicAuthHeader(orgApiKey, orgSecretKey),+ 200,+ );++ expect(response.status).toBe(200);+ expect(response.body.id).toBe(testUserId);++ // Verify the user was removed from the organization+ const orgMemberships = await prisma.organizationMembership.findMany({+ where: { userId: testUserId, orgId: orgId },+ });+ expect(orgMemberships.length).toBe(0);+ });++ it("should reactivate a user when active is true", async () => {+ // First deactivate the user+ await prisma.organizationMembership.deleteMany({+ where: { userId: testUserId, orgId: orgId },+ });++ const response = await makeZodVerifiedAPICall(+ ScimUserSchema,+ "PUT",+ `/api/public/scim/Users/${testUserId}`,+ {+ schemas: ["urn:ietf:params:scim:schemas:core:2.0:User"],+ id: testUserId,+ userName: "[email protected]",+ active: true,+ },+ createBasicAuthHeader(orgApiKey, orgSecretKey),+ 200,+ );++ expect(response.status).toBe(200);+ expect(response.body.id).toBe(testUserId);++ // Verify the user was re-added to the organization with default role+ const orgMemberships = await prisma.organizationMembership.findMany({+ where: { userId: testUserId, orgId: orgId },+ });+ expect(orgMemberships.length).toBe(1);+ expect(orgMemberships[0].role).toBe("NONE");+ });++ it("should reactivate a user with specified role", async () => {+ // First deactivate the user+ await prisma.organizationMembership.deleteMany({+ where: { userId: testUserId, orgId: orgId },+ });++ const response = await makeZodVerifiedAPICall(+ ScimUserSchema,+ "PUT",+ `/api/public/scim/Users/${testUserId}`,+ {+ schemas: ["urn:ietf:params:scim:schemas:core:2.0:User"],+ id: testUserId,+ userName: "[email protected]",+ active: true,+ roles: ["MEMBER"],+ },+ createBasicAuthHeader(orgApiKey, orgSecretKey),+ 200,+ );++ expect(response.status).toBe(200);+ expect(response.body.id).toBe(testUserId);++ // Verify the user was re-added to the organization with specified role+ const orgMemberships = await prisma.organizationMembership.findMany({+ where: { userId: testUserId, orgId: orgId },+ });+ expect(orgMemberships.length).toBe(1);+ expect(orgMemberships[0].role).toBe("MEMBER");+ });++ it("should return 400 when SCIM schema is missing", async () => {+ const result = await makeAPICall(+ "PUT",+ `/api/public/scim/Users/${testUserId}`,+ {+ id: testUserId,+ userName: "[email protected]",+ active: false,+ },+ createBasicAuthHeader(orgApiKey, orgSecretKey),+ );+ expect(result.status).toBe(400);+ expect(result.body.detail).toContain("schemas");+ });++ it("should return 404 when user does not exist", async () => {+ const nonExistentUserId = randomUUID();+ const result = await makeAPICall(+ "PUT",+ `/api/public/scim/Users/${nonExistentUserId}`,+ {+ schemas: ["urn:ietf:params:scim:schemas:core:2.0:User"],+ id: nonExistentUserId,+ userName: "[email protected]",+ active: false,+ },+ createBasicAuthHeader(orgApiKey, orgSecretKey),+ );+ expect(result.status).toBe(404);+ expect(result.body.detail).toContain("User not found");+ });+ });+describe("DELETE /api/public/scim/Users/{id}", () => {beforeEach(async () => {// Create a test userdiff --git a/web/src/pages/api/public/scim/Users/[id].ts b/web/src/pages/api/public/scim/Users/[id].tsindex e482fd3e35..68a3c068fa 100644--- a/web/src/pages/api/public/scim/Users/[id].ts+++ b/web/src/pages/api/public/scim/Users/[id].ts@@ -1,9 +1,8 @@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 { type User } from "@langfuse/shared";+import { prisma, type User, type Role } from "@langfuse/shared/src/db";import { logger, redis } from "@langfuse/shared/src/server";-+import { z } from "zod";import { type NextApiRequest, type NextApiResponse } from "next";export default async function handler(@@ -12,7 +11,7 @@ export default async function handler() {await runMiddleware(req, res, cors);- if (!["GET", "DELETE", "PATCH"].includes(req.method || "")) {+ if (!["GET", "DELETE", "PATCH", "PUT"].includes(req.method || "")) {logger.error(`Method not allowed for ${req.method} on /api/public/scim/Users/[id]`,);@@ -54,20 +53,14 @@ export default async function handler(`Received request for /api/public/scim/Users/[id] with method ${req.method} for orgId ${authCheck.scope.orgId} and userId ${req.query.id}`,);- const orgMembership = await prisma.organizationMembership.findFirst({+ // First, check if the user exists in the system at all+ const user = await prisma.user.findUnique({where: {- orgId: authCheck.scope.orgId,- user: {- id: req.query.id as string,- },- },- select: {- id: true,- user: true,+ id: req.query.id as string,},});- if (!orgMembership?.user) {+ if (!user) {return res.status(404).json({schemas: ["urn:ietf:params:scim:api:messages:2.0:Error"],detail: "User not found",@@ -79,16 +72,13 @@ export default async function handler(try {switch (req.method) {case "PATCH":- return handlePatch(req, res, orgMembership.user, authCheck.scope.orgId);+ return handlePatch(req, res, user, authCheck.scope.orgId);+ case "PUT":+ return handlePut(req, res, user, authCheck.scope.orgId);case "GET":- return handleGet(req, res, orgMembership.user);+ return handleGet(req, res, user, authCheck.scope.orgId);case "DELETE":- return handleDelete(- req,- res,- orgMembership.user,- authCheck.scope.orgId,- );+ return handleDelete(req, res, user, authCheck.scope.orgId);default:// This should never happen due to the check at the beginningreturn res.status(405).json({@@ -115,7 +105,24 @@ async function handleGet(req: NextApiRequest,res: NextApiResponse,user: User,+ orgId: string,) {+ // For GET operations, verify the user is a member of the organization+ const orgMembership = await prisma.organizationMembership.findFirst({+ where: {+ orgId: orgId,+ userId: user.id,+ },+ });++ if (!orgMembership) {+ return res.status(404).json({+ schemas: ["urn:ietf:params:scim:api:messages:2.0:Error"],+ detail: "User not found in organization",+ status: 404,+ });+ }+// Transform to SCIM formatreturn res.status(200).json({schemas: ["urn:ietf:params:scim:schemas:core:2.0:User"],@@ -241,7 +248,109 @@ async function handlePatch(}}- return handleGet(req, res, user);+ return handleGet(req, res, user, orgId);+}++// PUT - Update user details+async function handlePut(+ req: NextApiRequest,+ res: NextApiResponse,+ user: User,+ orgId: string,+) {+ let body = req.body;++ // Check if body is a string and parse it+ if (typeof body === "string") {+ try {+ body = JSON.parse(body);+ } catch (error) {+ logger.warn("Failed to parse JSON body", error);+ return res.status(400).json({+ schemas: ["urn:ietf:params:scim:api:messages:2.0:Error"],+ detail: "Invalid JSON body",+ status: 400,+ });+ }+ }++ // Validate that it's a SCIM user object+ if (+ !body.schemas ||+ !Array.isArray(body.schemas) ||+ !body.schemas.includes("urn:ietf:params:scim:schemas:core:2.0:User")+ ) {+ logger.warn(+ "Invalid request body. Must include 'schemas' with 'urn:ietf:params:scim:schemas:core:2.0:User'.",+ body,+ );+ return res.status(400).json({+ schemas: ["urn:ietf:params:scim:api:messages:2.0:Error"],+ detail:+ "Invalid request body. Must include 'schemas' with 'urn:ietf:params:scim:schemas:core:2.0:User'.",+ status: 400,+ });+ }++ // Handle active status for provisioning/deprovisioning+ if (typeof body.active === "boolean") {+ if (body.active) {+ // Determine role from roles array if provided+ let role: Role = "NONE";+ if (body.roles && Array.isArray(body.roles) && body.roles.length > 0) {+ const roleSchema = z.array(+ z.enum(["OWNER", "ADMIN", "MEMBER", "VIEWER", "NONE"]),+ );+ const parsedRoles = roleSchema.safeParse(body.roles);+ if (parsedRoles.success) {+ // Use the first valid role+ role = parsedRoles.data[0];+ }+ }++ // Provision the user by adding them to the organization+ await prisma.organizationMembership.upsert({+ where: {+ orgId_userId: {+ orgId: orgId,+ userId: user.id,+ },+ },+ create: {+ userId: user.id,+ orgId: orgId,+ role: role,+ },+ update: {+ role: role,+ },+ });+ } else {+ // Deprovision the user by removing them from the organization+ await prisma.organizationMembership.deleteMany({+ where: {+ userId: user.id,+ orgId: orgId,+ },+ });+ }+ }++ // For PUT operations, we could also update other user attributes like name+ // if they are provided in the request body. For now, matching the existing+ // feature set which only handles active status changes.++ // Return SCIM formatted user (abbreviated)+ return res.status(200).json({+ schemas: ["urn:ietf:params:scim:schemas:core:2.0:User"],+ id: user.id,+ userName: user.email,+ meta: {+ resourceType: "User",+ created: user.createdAt?.toISOString(),+ lastModified: user.updatedAt?.toISOString(),+ },+ });}// DELETE - Remove user from organizationdiff --git a/web/src/pages/api/public/scim/Users/index.ts b/web/src/pages/api/public/scim/Users/index.tsindex 734766dac3..3898f2a054 100644--- a/web/src/pages/api/public/scim/Users/index.ts+++ b/web/src/pages/api/public/scim/Users/index.ts@@ -139,10 +139,10 @@ export default async function handler(if (req.method === "POST") {try {- const body = req.body;+ let body = req.body;if (typeof body === "string") {try {- req.body = JSON.parse(body);+ body = JSON.parse(body);} catch (error) {logger.error("Failed to parse JSON body", error);return res.status(400).json({@@ -153,7 +153,7 @@ export default async function handler(}}- const { userName, name, password, displayName, roles } = req.body;+ const { userName, name, password, displayName, roles } = body;if (!userName) {logger.warn("userName is required for SCIM user creation");