🪢 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
fix(scim): require ownership permission for SCIM OWNER changes (#18884)
Mark Salpeter387d3040ee3f
diff --git a/web/src/__tests__/server/scim-api.servertest.ts b/web/src/__tests__/server/scim-api.servertest.tsindex e9d48dfa07..6c72cb5f6b 100644--- a/web/src/__tests__/server/scim-api.servertest.ts+++ b/web/src/__tests__/server/scim-api.servertest.ts@@ -10,6 +10,41 @@ import {import { prisma } from "@langfuse/shared/src/db";import { OrganizationId, SystemRoleId, UserId } from "@langfuse/shared/rbac";import { randomUUID } from "crypto";+import { createMocks } from "node-mocks-http";+import { type NextApiRequest, type NextApiResponse } from "next";+import scimUsersRoute from "@/src/pages/api/public/scim/Users";+import scimUserRoute from "@/src/pages/api/public/scim/Users/[id]";+import { env } from "@/src/env.mjs";++vi.mock("@/src/env.mjs", async (importOriginal) => {+ const actual = await importOriginal<{ env: typeof env }>();+ return { ...actual, env: { ...actual.env } };+});++/** callScimRoute invokes a SCIM route handler in-process with an API key header. */+const callScimRoute = async (+ route: typeof scimUsersRoute,+ {+ method,+ authorization,+ userId,+ body,+ }: {+ method: "POST" | "PUT" | "PATCH" | "DELETE";+ authorization: string;+ userId?: string;+ body?: unknown;+ },+) => {+ const { req, res } = createMocks<NextApiRequest, NextApiResponse>({+ method,+ headers: { authorization },+ query: { id: userId },+ body: body as Record<string, unknown>,+ });+ await route(req, res);+ return { status: res.statusCode, body: String(res._getData()) };+};// Schema for SCIM User responseconst ScimUserSchema = z.object({@@ -1273,8 +1308,10 @@ describe("SCIM API", () => {let scopedOwnerUserId: string;let scopedOrgPublicKey: string;let scopedOrgSecretKey: string;+ const originalMode = env.API_AUTH_MIGRATION;beforeEach(async () => {+ Object.assign(env, { API_AUTH_MIGRATION: "enforce" });const org = await prisma.organization.create({data: {name: `scim-last-owner-${randomUUID().substring(0, 8)}`,@@ -1311,22 +1348,23 @@ describe("SCIM API", () => {});afterEach(async () => {+ Object.assign(env, { API_AUTH_MIGRATION: originalMode });await prisma.user.deleteMany({ where: { id: scopedOwnerUserId } });await prisma.organization.deleteMany({ where: { id: scopedOrgId } });});it("DELETE rejects removing the only remaining OWNER", async () => {- const result = await makeAPICall<{ detail: string }>(- "DELETE",- `/api/public/scim/Users/${scopedOwnerUserId}`,- undefined,- createBasicAuthHeader(scopedOrgPublicKey, scopedOrgSecretKey),- );+ const result = await callScimRoute(scimUserRoute, {+ method: "DELETE",+ authorization: createBasicAuthHeader(+ scopedOrgPublicKey,+ scopedOrgSecretKey,+ ),+ userId: scopedOwnerUserId,+ });expect(result.status).toBe(403);- expect(String(result.body.detail).toLowerCase()).toContain(- "last owner",- );+ expect(result.body.toLowerCase()).toContain("last owner");const remaining = await prisma.organizationMembership.findMany({where: { userId: scopedOwnerUserId, orgId: scopedOrgId },@@ -1336,22 +1374,23 @@ describe("SCIM API", () => {});it("PUT active:false rejects removing the only remaining OWNER", async () => {- const result = await makeAPICall<{ detail: string }>(- "PUT",- `/api/public/scim/Users/${scopedOwnerUserId}`,- {+ const result = await callScimRoute(scimUserRoute, {+ method: "PUT",+ authorization: createBasicAuthHeader(+ scopedOrgPublicKey,+ scopedOrgSecretKey,+ ),+ userId: scopedOwnerUserId,+ body: {schemas: ["urn:ietf:params:scim:schemas:core:2.0:User"],id: scopedOwnerUserId,userName: "[email protected]",active: false,},- createBasicAuthHeader(scopedOrgPublicKey, scopedOrgSecretKey),- );+ });expect(result.status).toBe(403);- expect(String(result.body.detail).toLowerCase()).toContain(- "last owner",- );+ expect(result.body.toLowerCase()).toContain("last owner");const remaining = await prisma.organizationMembership.findMany({where: { userId: scopedOwnerUserId, orgId: scopedOrgId },@@ -1361,20 +1400,21 @@ describe("SCIM API", () => {});it("PATCH active:false rejects removing the only remaining OWNER", async () => {- const result = await makeAPICall<{ detail: string }>(- "PATCH",- `/api/public/scim/Users/${scopedOwnerUserId}`,- {+ const result = await callScimRoute(scimUserRoute, {+ method: "PATCH",+ authorization: createBasicAuthHeader(+ scopedOrgPublicKey,+ scopedOrgSecretKey,+ ),+ userId: scopedOwnerUserId,+ body: {schemas: ["urn:ietf:params:scim:api:messages:2.0:PatchOp"],Operations: [{ op: "replace", value: { active: false } }],},- createBasicAuthHeader(scopedOrgPublicKey, scopedOrgSecretKey),- );+ });expect(result.status).toBe(403);- expect(String(result.body.detail).toLowerCase()).toContain(- "last owner",- );+ expect(result.body.toLowerCase()).toContain("last owner");const remaining = await prisma.organizationMembership.findMany({where: { userId: scopedOwnerUserId, orgId: scopedOrgId },@@ -1384,23 +1424,24 @@ describe("SCIM API", () => {});it("PUT active:true with a lower role rejects demoting the only remaining OWNER", async () => {- const result = await makeAPICall<{ detail: string }>(- "PUT",- `/api/public/scim/Users/${scopedOwnerUserId}`,- {+ const result = await callScimRoute(scimUserRoute, {+ method: "PUT",+ authorization: createBasicAuthHeader(+ scopedOrgPublicKey,+ scopedOrgSecretKey,+ ),+ userId: scopedOwnerUserId,+ body: {schemas: ["urn:ietf:params:scim:schemas:core:2.0:User"],id: scopedOwnerUserId,userName: "[email protected]",active: true,roles: ["MEMBER"],},- createBasicAuthHeader(scopedOrgPublicKey, scopedOrgSecretKey),- );+ });expect(result.status).toBe(403);- expect(String(result.body.detail).toLowerCase()).toContain(- "last owner",- );+ expect(result.body.toLowerCase()).toContain("last owner");const remaining = await prisma.organizationMembership.findMany({where: { userId: scopedOwnerUserId, orgId: scopedOrgId },@@ -1425,18 +1466,21 @@ describe("SCIM API", () => {});try {- const result = await makeAPICall(- "PUT",- `/api/public/scim/Users/${scopedOwnerUserId}`,- {+ const result = await callScimRoute(scimUserRoute, {+ method: "PUT",+ authorization: createBasicAuthHeader(+ scopedOrgPublicKey,+ scopedOrgSecretKey,+ ),+ userId: scopedOwnerUserId,+ body: {schemas: ["urn:ietf:params:scim:schemas:core:2.0:User"],id: scopedOwnerUserId,userName: "[email protected]",active: true,roles: ["MEMBER"],},- createBasicAuthHeader(scopedOrgPublicKey, scopedOrgSecretKey),- );+ });expect(result.status).toBe(200);const demoted = await prisma.organizationMembership.findFirst({@@ -1467,12 +1511,14 @@ describe("SCIM API", () => {});try {- const result = await makeAPICall(- "DELETE",- `/api/public/scim/Users/${secondOwner.id}`,- undefined,- createBasicAuthHeader(scopedOrgPublicKey, scopedOrgSecretKey),- );+ const result = await callScimRoute(scimUserRoute, {+ method: "DELETE",+ authorization: createBasicAuthHeader(+ scopedOrgPublicKey,+ scopedOrgSecretKey,+ ),+ userId: secondOwner.id,+ });expect(result.status).toBe(204);const memberships = await prisma.organizationMembership.findMany({@@ -1775,3 +1821,224 @@ describe("SCIM API", () => {});});});++describe("SCIM ownership boundary", () => {+ let orgId: string;+ let ownerId: string;+ let secondOwnerId: string;+ let memberId: string;+ let adminAuth: string;+ let ownerAuth: string;+ const createdEmails: string[] = [];+ const originalMode = env.API_AUTH_MIGRATION;++ beforeEach(async () => {+ Object.assign(env, { API_AUTH_MIGRATION: "enforce" });+ const org = await prisma.organization.create({+ data: { name: randomUUID(), cloudConfig: { plan: "Team" } },+ });+ orgId = org.id;+ const [owner, secondOwner, member] = await Promise.all(+ (["OWNER", "OWNER", "MEMBER"] as const).map((role) =>+ prisma.user.create({+ data: {+ email: `${randomUUID()}@example.com`,+ organizationMemberships: { create: { orgId, role } },+ },+ }),+ ),+ );+ ownerId = owner!.id;+ secondOwnerId = secondOwner!.id;+ memberId = member!.id;+ const [adminKey, ownerKey] = await Promise.all(+ (["ADMIN", "LEGACY_ORGANIZATION_API_KEY"] as const).map((role) =>+ createApiKey(prisma, {+ owner: OrganizationId(orgId),+ role: SystemRoleId(role),+ createdBy: UserId(ownerId),+ }),+ ),+ );+ adminAuth = createBasicAuthHeader(adminKey!.publicKey, adminKey!.secretKey);+ ownerAuth = createBasicAuthHeader(ownerKey!.publicKey, ownerKey!.secretKey);+ });++ afterEach(async () => {+ Object.assign(env, { API_AUTH_MIGRATION: originalMode });+ await prisma.auditLog.deleteMany({ where: { orgId } });+ await prisma.organization.delete({ where: { id: orgId } });+ await prisma.user.deleteMany({+ where: {+ OR: [+ { id: { in: [ownerId, secondOwnerId, memberId] } },+ { email: { in: createdEmails.splice(0) } },+ ],+ },+ });+ });++ const call = async (+ route: typeof scimUsersRoute,+ method: "POST" | "PUT" | "PATCH" | "DELETE",+ body?: unknown,+ userId?: string,+ ) =>+ (+ await callScimRoute(route, {+ method,+ authorization: adminAuth,+ userId,+ body,+ })+ ).status;+ const putUser = (userId: string, roles: string[]) =>+ call(+ scimUserRoute,+ "PUT",+ {+ schemas: ["urn:ietf:params:scim:schemas:core:2.0:User"],+ active: true,+ roles,+ },+ userId,+ );+ const roleOf = async (userId: string) =>+ (+ await prisma.organizationMembership.findUnique({+ where: { orgId_userId: { orgId, userId } },+ })+ )?.role;++ it("rejects an ADMIN key creating an OWNER via POST", async () => {+ const email = `${randomUUID()}@example.com`;+ createdEmails.push(email);+ const status = await call(scimUsersRoute, "POST", {+ schemas: ["urn:ietf:params:scim:schemas:core:2.0:User"],+ userName: email,+ roles: ["OWNER"],+ });+ expect(status).toBe(403);+ expect(+ await prisma.organizationMembership.count({+ where: { orgId, user: { email } },+ }),+ ).toBe(0);+ });++ it("rejects ownership changes without an authorization context", async () => {+ Object.assign(env, { API_AUTH_MIGRATION: "legacy" });+ const legacyKey = await createApiKey(prisma, {+ owner: OrganizationId(orgId),+ role: SystemRoleId("LEGACY_ORGANIZATION_API_KEY"),+ createdBy: UserId(ownerId),+ });+ const { status } = await callScimRoute(scimUserRoute, {+ method: "PUT",+ authorization: createBasicAuthHeader(+ legacyKey.publicKey,+ legacyKey.secretKey,+ ),+ userId: ownerId,+ body: {+ schemas: ["urn:ietf:params:scim:schemas:core:2.0:User"],+ active: true,+ roles: ["MEMBER"],+ },+ });+ expect(status).toBe(403);+ expect(await roleOf(ownerId)).toBe("OWNER");+ });++ it("rejects an ADMIN key demoting an OWNER via PUT", async () => {+ expect(await putUser(ownerId, ["MEMBER"])).toBe(403);+ expect(await roleOf(ownerId)).toBe("OWNER");+ });++ it("rejects an ADMIN key promoting a member to OWNER via PUT", async () => {+ expect(await putUser(memberId, ["OWNER"])).toBe(403);+ expect(await roleOf(memberId)).toBe("MEMBER");+ });++ it("rejects an ADMIN key provisioning a non-member as OWNER via PUT", async () => {+ const outsider = await prisma.user.create({+ data: { email: `${randomUUID()}@example.com` },+ });+ createdEmails.push(outsider.email!);+ expect(await putUser(outsider.id, ["OWNER"])).toBe(403);+ expect(await roleOf(outsider.id)).toBeUndefined();+ });++ it.each([+ ["DELETE", undefined],+ [+ "PATCH",+ {+ schemas: ["urn:ietf:params:scim:api:messages:2.0:PatchOp"],+ Operations: [{ op: "replace", value: { active: false } }],+ },+ ],+ [+ "PUT",+ {+ schemas: ["urn:ietf:params:scim:schemas:core:2.0:User"],+ active: false,+ },+ ],+ ] as const)(+ "rejects an ADMIN key deprovisioning an OWNER via %s",+ async (method, body) => {+ expect(await call(scimUserRoute, method, body, ownerId)).toBe(403);+ expect(await roleOf(ownerId)).toBe("OWNER");+ },+ );++ it("lets a key with ownership permission grant OWNER via POST and PUT", async () => {+ const email = `${randomUUID()}@example.com`;+ createdEmails.push(email);+ const created = await callScimRoute(scimUsersRoute, {+ method: "POST",+ authorization: ownerAuth,+ body: {+ schemas: ["urn:ietf:params:scim:schemas:core:2.0:User"],+ userName: email,+ roles: ["OWNER"],+ },+ });+ expect(created.status).toBe(201);+ expect(+ await prisma.organizationMembership.findFirst({+ where: { orgId, user: { email } },+ }),+ ).toMatchObject({ role: "OWNER" });++ const promoted = await callScimRoute(scimUserRoute, {+ method: "PUT",+ authorization: ownerAuth,+ userId: memberId,+ body: {+ schemas: ["urn:ietf:params:scim:schemas:core:2.0:User"],+ active: true,+ roles: ["OWNER"],+ },+ });+ expect(promoted.status).toBe(200);+ expect(await roleOf(memberId)).toBe("OWNER");+ });++ it("lets an ADMIN key manage non-owner members", async () => {+ const email = `${randomUUID()}@example.com`;+ createdEmails.push(email);+ expect(+ await call(scimUsersRoute, "POST", {+ schemas: ["urn:ietf:params:scim:schemas:core:2.0:User"],+ userName: email,+ roles: ["ADMIN"],+ }),+ ).toBe(201);+ expect(await putUser(memberId, ["ADMIN"])).toBe(200);+ expect(await roleOf(memberId)).toBe("ADMIN");+ expect(await call(scimUserRoute, "DELETE", undefined, memberId)).toBe(204);+ expect(await roleOf(memberId)).toBeUndefined();+ });+});diff --git a/web/src/ee/features/admin-api/server/memberships.ts b/web/src/ee/features/admin-api/server/memberships.tsindex 96c6c22b4e..006ac039f3 100644--- a/web/src/ee/features/admin-api/server/memberships.ts+++ b/web/src/ee/features/admin-api/server/memberships.ts@@ -81,7 +81,6 @@ export async function handleUpdateMembership(}const membership = await prisma.$transaction(async (tx) => {- await lockOrganization(tx, orgId);const before = await tx.organizationMembership.findUnique({where: { orgId_userId: { orgId, userId: validatedBody.data.userId } },});@@ -149,7 +148,6 @@ export async function handleDeleteMembership(}const deleted = await prisma.$transaction(async (tx) => {- await lockOrganization(tx, orgId);const before = await tx.organizationMembership.findUnique({where: { orgId_userId: { orgId, userId: validatedBody.data.userId } },});@@ -196,11 +194,6 @@ export async function handleDeleteMembership(});}-/** lockOrganization serializes membership API mutations before reading owner state. */-async function lockOrganization(tx: Prisma.TransactionClient, orgId: string) {- await tx.$queryRaw`SELECT id FROM organizations WHERE id = ${orgId} FOR UPDATE`;-}-function assertAuthorizeMembershipChange(context: AuthorizationContext,orgId: string,@@ -215,8 +208,8 @@ function assertAuthorizeMembershipChange(if (!membershipAccess.success) throw membershipAccess.error;}-/** assertValidOwnershipChange checks ownership permission and preserves an owner under the organization lock. */-async function assertValidOwnershipChange({+/** assertValidOwnershipChange checks ownership permission and keeps at least one owner. */+export async function assertValidOwnershipChange({tx,context,orgId,@@ -224,7 +217,7 @@ async function assertValidOwnershipChange({to,}: {tx: Prisma.TransactionClient;- context: AuthorizationContext;+ context: AuthorizationContext | undefined;orgId: string;from: Role | undefined;to?: Role;@@ -237,10 +230,12 @@ async function assertValidOwnershipChange({}}+/** assertAuthorizeOwnershipChange throws unless the context may grant, change, or remove the OWNER role. */function assertAuthorizeOwnershipChange(- context: AuthorizationContext,+ context: AuthorizationContext | undefined,orgId: string,) {+ if (!context) throw new ForbiddenError();const organization = OrganizationId(orgId);const ownershipAccess = authorize(context,@@ -251,15 +246,14 @@ function assertAuthorizeOwnershipChange(if (!ownershipAccess.success) throw ownershipAccess.error;}-/** assertOtherOwners requires another owner before removing ownership under the organization lock. */+/** assertOtherOwners locks the organization's owner rows and requires another owner before removing ownership. */async function assertOtherOwners(tx: Prisma.TransactionClient, orgId: string) {- const ownerCount = await tx.organizationMembership.count({- where: {- orgId,- role: Role.OWNER,- },- });- if (ownerCount < 2) {+ const owners = await tx.$queryRaw<{ id: string }[]>`+ SELECT id FROM organization_memberships+ WHERE org_id = ${orgId} AND role = 'OWNER'+ FOR UPDATE+ `;+ if (owners.length < 2) {throw new ForbiddenError("Cannot remove the last owner of an organization. Assign new owner or delete organization.",);diff --git a/web/src/pages/api/public/scim/Users/[id].ts b/web/src/pages/api/public/scim/Users/[id].tsindex 22fcd50b24..d23febf0ca 100644--- a/web/src/pages/api/public/scim/Users/[id].ts+++ b/web/src/pages/api/public/scim/Users/[id].ts@@ -2,9 +2,12 @@ import { cors, runMiddleware } from "@/src/features/public-api/server/cors";import { auditLog } from "@/src/features/audit-logs/server";import { Prisma, prisma, type User, type Role } from "@langfuse/shared/src/db";import { logger } from "@langfuse/shared/src/server";+import { isBaseError, LangfuseConflictError } from "@langfuse/shared";import { z } from "zod";import { type NextApiRequest, type NextApiResponse } from "next";+import { assertValidOwnershipChange } from "@/src/ee/features/admin-api/server/memberships";import { getSfdcService } from "@/src/ee/features/sfdc-sync/server";+import { type AuthorizationContext } from "@/src/features/auth/policy/types";import { hasEntitlementBasedOnPlan } from "@/src/features/entitlements/server";import { shadowAuth, writeScimError } from "@/src/features/public-api/server";@@ -39,23 +42,21 @@ type ProvisionOutcome =// Writes an audit log entry and fires the SFDC membership sync only when state// actually changes (create/update), never for a no-op — so a periodic IdP// full-sync that re-PUTs every member does not ping SFDC on every cycle.-// Returns the provisioning outcome, or null when the request was rejected and-// the response has already been written (e.g. last-OWNER demotion → 403).async function provisionMembership({- res,userId,orgId,apiKeyId,email,role,+ ctx,}: {- res: NextApiResponse;userId: string;orgId: string;apiKeyId: string;email: string | null;role?: Role;-}): Promise<ProvisionOutcome | null> {+ ctx: AuthorizationContext | undefined;+}): Promise<ProvisionOutcome> {// Apply an explicit role to an existing membership. The membership is// re-read INSIDE the Serializable transaction so the no-op check, the// last-OWNER guard, and the update all act on the same snapshot — a read@@ -63,10 +64,10 @@ async function provisionMembership({// deprovision past the guard (Postgres SSI only protects reads made within// the transaction). Returns "missing" when the membership disappeared before// the transaction started, so the caller can fall through to the create- // path; returns null when the request was rejected and the response written.+ // path.const applyRoleToExisting = async (targetRole: Role,- ): Promise<ProvisionOutcome | "missing" | null> => {+ ): Promise<ProvisionOutcome | "missing"> => {try {const result = await prisma.$transaction(async (tx) => {@@ -79,18 +80,13 @@ async function provisionMembership({if (current.role === targetRole) {return { t: "unchanged" as const, role: current.role };}- // Enforce the org-wide "at least one OWNER" invariant, mirroring- // deprovisionOrReject and the tRPC updateOrgMembership path, so- // demoting the last OWNER cannot orphan the org and two concurrent- // demotions cannot both pass the check.- if (current.role === "OWNER" && targetRole !== "OWNER") {- const ownerCount = await tx.organizationMembership.count({- where: { orgId, role: "OWNER" },- });- if (ownerCount <= 1) {- return { t: "lastOwner" as const };- }- }+ await assertValidOwnershipChange({+ tx,+ context: ctx,+ orgId,+ from: current.role,+ to: targetRole,+ });const updated = await tx.organizationMembership.update({where: { orgId_userId: { orgId, userId } },data: { role: targetRole },@@ -106,18 +102,6 @@ async function provisionMembership({if (result.t === "unchanged") {return { kind: "unchanged", role: result.role };}- if (result.t === "lastOwner") {- logger.warn(- `[SCIM] Refused to demote last OWNER ${userId} in org ${orgId}`,- );- res.status(403).json({- schemas: ["urn:ietf:params:scim:api:messages:2.0:Error"],- detail:- "Cannot remove the last owner of an organization. Assign new owner or delete organization.",- status: 403,- });- return null;- }await auditLog({resourceType: "orgMembership",@@ -142,15 +126,9 @@ async function provisionMembership({error instanceof Prisma.PrismaClientKnownRequestError &&error.code === "P2034") {- logger.warn(- `[SCIM] Concurrent role update conflict for user ${userId} in org ${orgId}`,+ throw new LangfuseConflictError(+ "Concurrent update conflict for this user. Please retry.",);- res.status(409).json({- schemas: ["urn:ietf:params:scim:api:messages:2.0:Error"],- detail: "Concurrent update conflict for this user. Please retry.",- status: 409,- });- return null;}throw error;}@@ -173,8 +151,14 @@ async function provisionMembership({}// Missing → create with the explicit role when provided, otherwise NONE.- // Creating a membership never removes an existing OWNER, so no guard needed.const roleToCreate: Role = role ?? "NONE";+ await assertValidOwnershipChange({+ tx: prisma,+ context: ctx,+ orgId,+ from: undefined,+ to: roleToCreate,+ });try {const created = await prisma.organizationMembership.create({data: { userId, orgId, role: roleToCreate },@@ -248,16 +232,14 @@ function logScimProvision(// concurrent SCIM deprovision requests cannot both pass the guard and orphan// the org.// Audits and syncs the removal to SFDC only when a membership was-// actually deleted, never for a no-op (already absent). Returns false (with-// the response already written) when the caller must stop; returns true after-// the membership has been removed.+// actually deleted, never for a no-op (already absent).async function deprovisionOrReject(- res: NextApiResponse,userId: string,orgId: string,apiKeyId: string,email: string | null,-): Promise<boolean> {+ ctx: AuthorizationContext | undefined,+): Promise<void> {try {const outcome = await prisma.$transaction(async (tx) => {@@ -274,14 +256,12 @@ async function deprovisionOrReject(if (!membership) {return { result: "noop" as const };}- if (membership.role === "OWNER") {- const ownerCount = await tx.organizationMembership.count({- where: { orgId, role: "OWNER" },- });- if (ownerCount <= 1) {- return { result: "lastOwner" as const };- }- }+ await assertValidOwnershipChange({+ tx,+ context: ctx,+ orgId,+ from: membership.role,+ });await tx.organizationMembership.delete({where: { orgId_userId: { orgId, userId } },});@@ -290,19 +270,6 @@ async function deprovisionOrReject({ isolationLevel: Prisma.TransactionIsolationLevel.Serializable },);- if (outcome.result === "lastOwner") {- logger.warn(- `[SCIM] Refused to remove last OWNER ${userId} from org ${orgId}`,- );- res.status(403).json({- schemas: ["urn:ietf:params:scim:api:messages:2.0:Error"],- detail:- "Cannot remove the last owner of an organization. Assign new owner or delete organization.",- status: 403,- });- return false;- }-// Only audit and sync when a membership was actually removed.if (outcome.result === "deleted") {await auditLog({@@ -315,7 +282,6 @@ async function deprovisionOrReject(});await getSfdcService()?.removeUser({ orgId, userId, email });}- return true;} catch (error) {// Postgres maps a serialization failure to Prisma error code P2034 ("could// not serialize access due to concurrent update"). Surface as 409 so the@@ -324,15 +290,9 @@ async function deprovisionOrReject(error instanceof Prisma.PrismaClientKnownRequestError &&error.code === "P2034") {- logger.warn(- `[SCIM] Concurrent deprovision conflict for user ${userId} in org ${orgId}`,+ throw new LangfuseConflictError(+ "Concurrent deprovision conflict for this user. Please retry.",);- res.status(409).json({- schemas: ["urn:ietf:params:scim:api:messages:2.0:Error"],- detail: "Concurrent deprovision conflict for this user. Please retry.",- status: 409,- });- return false;}throw error;}@@ -409,30 +369,33 @@ export default async function handler(try {switch (req.method) {case "PATCH":- return handlePatch(+ return await handlePatch(req,res,user,authCheck.scope.orgId,authCheck.scope.apiKeyId,+ authCheck.ctx,);case "PUT":- return handlePut(+ return await handlePut(req,res,user,authCheck.scope.orgId,authCheck.scope.apiKeyId,+ authCheck.ctx,);case "GET":return handleGet(req, res, user, authCheck.scope.orgId);case "DELETE":- return handleDelete(+ return await handleDelete(req,res,user,authCheck.scope.orgId,authCheck.scope.apiKeyId,+ authCheck.ctx,);default:// This should never happen due to the check at the beginning@@ -447,6 +410,9 @@ export default async function handler(`[SCIM] Error handling user ${req.query.id} for ${req.method}`,error,);+ if (isBaseError(error)) {+ return writeScimError(res, error);+ }return res.status(500).json({schemas: ["urn:ietf:params:scim:api:messages:2.0:Error"],detail: "Internal server error",@@ -521,6 +487,7 @@ async function handlePatch(user: User,orgId: string,apiKeyId: string,+ ctx: AuthorizationContext | undefined,) {let body = req.body;@@ -581,29 +548,16 @@ async function handlePatch(// PATCH PatchOp values only carry `active` (no roles), so this always// creates a NONE membership when missing and is a no-op otherwise.const outcome = await provisionMembership({- res,userId: user.id,orgId,apiKeyId,email: user.email,+ ctx,});- if (!outcome) {- return;- }logScimProvision(outcome, user.id, orgId, "PATCH");} else {// Deprovision atomically: check + delete in one Serializable txn.- if (- !(await deprovisionOrReject(- res,- user.id,- orgId,- apiKeyId,- user.email,- ))- ) {- return;- }+ await deprovisionOrReject(user.id, orgId, apiKeyId, user.email, ctx);logger.info(`[SCIM] Deprovisioned user ${user.id} from org ${orgId} via PATCH`,);@@ -632,6 +586,7 @@ async function handlePut(user: User,orgId: string,apiKeyId: string,+ ctx: AuthorizationContext | undefined,) {let body = req.body;@@ -685,25 +640,17 @@ async function handlePut(if (typeof body.active === "boolean") {if (body.active) {const outcome = await provisionMembership({- res,userId: user.id,orgId,apiKeyId,email: user.email,role: parseScimRole(body.roles),+ ctx,});- // null → request rejected (e.g. last-OWNER demotion); response written.- if (!outcome) {- return;- }logScimProvision(outcome, user.id, orgId, "PUT");} else {// Deprovision atomically: check + delete in one Serializable txn.- if (- !(await deprovisionOrReject(res, user.id, orgId, apiKeyId, user.email))- ) {- return;- }+ await deprovisionOrReject(user.id, orgId, apiKeyId, user.email, ctx);logger.info(`[SCIM] Deprovisioned user ${user.id} from org ${orgId} via PUT`,);@@ -735,14 +682,13 @@ async function handleDelete(user: User,orgId: string,apiKeyId: string,+ ctx: AuthorizationContext | undefined,) {if (!(await requireOrgMembership(res, orgId, user.id))) {return;}// Deprovision atomically: check + delete in one Serializable txn.- if (!(await deprovisionOrReject(res, user.id, orgId, apiKeyId, user.email))) {- return;- }+ await deprovisionOrReject(user.id, orgId, apiKeyId, user.email, ctx);logger.info(`[SCIM] Removed user ${user.id} from org ${orgId} via DELETE`);// Return empty response with 204 No Content.diff --git a/web/src/pages/api/public/scim/Users/index.ts b/web/src/pages/api/public/scim/Users/index.tsindex b45cbfb1d6..38727d052f 100644--- a/web/src/pages/api/public/scim/Users/index.ts+++ b/web/src/pages/api/public/scim/Users/index.ts@@ -4,8 +4,9 @@ import { logger } from "@langfuse/shared/src/server";import { type NextApiRequest, type NextApiResponse } from "next";import { z } from "zod";-import { type Role } from "@langfuse/shared";+import { isBaseError, type Role } from "@langfuse/shared";import { auditLog } from "@/src/features/audit-logs/server";+import { assertValidOwnershipChange } from "@/src/ee/features/admin-api/server/memberships";import { getSfdcService } from "@/src/ee/features/sfdc-sync/server";import { hasEntitlementBasedOnPlan } from "@/src/features/entitlements/server";import { shadowAuth, writeScimError } from "@/src/features/public-api/server";@@ -197,6 +198,14 @@ export default async function handler(role = parsedRoles.data[0];}+ await assertValidOwnershipChange({+ tx: prisma,+ context: authCheck.ctx,+ orgId: authCheck.scope.orgId,+ from: undefined,+ to: role,+ });+// Check if user already exists. Normalize the email to lowercase to// stay consistent with the upsert below; otherwise a case-variant// userName slips past the duplicate check and the upsert can collide@@ -290,6 +299,9 @@ export default async function handler(});} catch (error) {logger.error("[SCIM] Failed to create user", error);+ if (isBaseError(error)) {+ return writeScimError(res, error);+ }return res.status(500).json({schemas: ["urn:ietf:params:scim:api:messages:2.0:Error"],detail: "Internal server error",