Skip to content

πŸͺ’ Open source agent evals & observability: Trace, evaluate, and improve LLM applications with one open platform.

fix(scim): stop PUT role downgrade and audit SCIM membership mutations (#14083)

Steffen Schmitz6aac9e72b3eb
diff --git a/web/src/__tests__/server/scim-api.servertest.ts b/web/src/__tests__/server/scim-api.servertest.ts
index 67d0485f8b..cc3f1e114a 100644
--- a/web/src/__tests__/server/scim-api.servertest.ts
+++ b/web/src/__tests__/server/scim-api.servertest.ts
@@ -851,6 +851,129 @@ describe("SCIM API", () => {
expect(orgMemberships[0].role).toBe("MEMBER");
});
+ it("should create the membership with NONE when no roles are provided (PUT active:true)", async () => {
+ await prisma.organizationMembership.deleteMany({
+ where: { userId: testUserId, orgId: orgId },
+ });
+
+ const response = await makeAPICall(
+ "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),
+ );
+ expect(response.status).toBe(200);
+
+ const membership = await prisma.organizationMembership.findFirst({
+ where: { userId: testUserId, orgId: orgId },
+ });
+ expect(membership).not.toBeNull();
+ expect(membership!.role).toBe("NONE");
+
+ // Provisioning a new membership writes a create audit entry.
+ const auditLogs = await prisma.auditLog.findMany({
+ where: {
+ resourceType: "orgMembership",
+ resourceId: membership!.id,
+ action: "create",
+ orgId: orgId,
+ },
+ });
+ expect(auditLogs.length).toBe(1);
+ expect(auditLogs[0].apiKeyId).not.toBeNull();
+ expect(auditLogs[0].userId).toBeNull();
+ expect(auditLogs[0].after).toContain(membership!.id);
+ });
+
+ it("should NOT modify an existing member's role when no roles are provided (PUT active:true, no downgrade)", async () => {
+ // Simulate a real, elevated member (the role someone set in-app or via
+ // the create flow).
+ await prisma.organizationMembership.updateMany({
+ where: { userId: testUserId, orgId: orgId },
+ data: { role: "MEMBER" },
+ });
+ const before = await prisma.organizationMembership.findFirst({
+ where: { userId: testUserId, orgId: orgId },
+ });
+ expect(before?.role).toBe("MEMBER");
+
+ // A periodic IdP full-sync re-sends active:true WITHOUT roles β€” it must
+ // not touch the existing role.
+ 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);
+
+ const after = await prisma.organizationMembership.findMany({
+ where: { userId: testUserId, orgId: orgId },
+ });
+ expect(after.length).toBe(1);
+ expect(after[0].role).toBe("MEMBER");
+ expect(after[0].id).toBe(before!.id);
+
+ // No-op must not write an audit log entry.
+ const auditLogs = await prisma.auditLog.findMany({
+ where: {
+ resourceType: "orgMembership",
+ resourceId: before!.id,
+ orgId: orgId,
+ },
+ });
+ expect(auditLogs.length).toBe(0);
+ });
+
+ it("should write a delete audit log when PUT active:false deprovisions a membership", async () => {
+ const before = await prisma.organizationMembership.findFirst({
+ where: { userId: testUserId, orgId: orgId },
+ });
+ expect(before).not.toBeNull();
+
+ const response = await makeAPICall(
+ "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),
+ );
+ expect(response.status).toBe(200);
+
+ const remaining = await prisma.organizationMembership.findMany({
+ where: { userId: testUserId, orgId: orgId },
+ });
+ expect(remaining.length).toBe(0);
+
+ const auditLogs = await prisma.auditLog.findMany({
+ where: {
+ resourceType: "orgMembership",
+ resourceId: before!.id,
+ action: "delete",
+ orgId: orgId,
+ },
+ });
+ expect(auditLogs.length).toBe(1);
+ expect(auditLogs[0].apiKeyId).not.toBeNull();
+ expect(auditLogs[0].before).toContain(before!.id);
+ });
+
it("should return 400 when SCIM schema is missing", async () => {
const result = await makeAPICall(
"PUT",
@@ -922,6 +1045,87 @@ describe("SCIM API", () => {
expect(orgMemberships.length).toBe(0);
});
+ it("should write a delete audit log when DELETE removes a membership", async () => {
+ const before = await prisma.organizationMembership.findFirst({
+ where: { userId: testUserId, orgId: orgId },
+ });
+ expect(before).not.toBeNull();
+
+ try {
+ await makeAPICall(
+ "DELETE",
+ `/api/public/scim/Users/${testUserId}`,
+ undefined,
+ createBasicAuthHeader(orgApiKey, orgSecretKey),
+ );
+ } catch (_e) {
+ // ignore
+ }
+
+ const auditLogs = await prisma.auditLog.findMany({
+ where: {
+ resourceType: "orgMembership",
+ resourceId: before!.id,
+ action: "delete",
+ orgId: orgId,
+ },
+ });
+ expect(auditLogs.length).toBe(1);
+ expect(auditLogs[0].apiKeyId).not.toBeNull();
+ expect(auditLogs[0].before).toContain(before!.id);
+ });
+
+ it("should capture cascade-deleted project memberships in the delete audit before payload", async () => {
+ // Seeded project that belongs to seed-org-id.
+ const seededProjectId = "7a88fb47-b4e2-43b8-a06c-a5ce950dc53a";
+ const orgMembership =
+ await prisma.organizationMembership.findFirstOrThrow({
+ where: { userId: testUserId, orgId: orgId },
+ });
+ // Give the user project-level access. This row is cascade-deleted when
+ // the org membership is removed, so the audit before payload is the
+ // only place it can be preserved.
+ await prisma.projectMembership.create({
+ data: {
+ orgMembershipId: orgMembership.id,
+ projectId: seededProjectId,
+ userId: testUserId,
+ role: "VIEWER",
+ },
+ });
+
+ try {
+ await makeAPICall(
+ "DELETE",
+ `/api/public/scim/Users/${testUserId}`,
+ undefined,
+ createBasicAuthHeader(orgApiKey, orgSecretKey),
+ );
+ } catch (_e) {
+ // ignore
+ }
+
+ // The cascaded project membership is gone from the DB...
+ const remainingProjectMemberships =
+ await prisma.projectMembership.findMany({
+ where: { userId: testUserId },
+ });
+ expect(remainingProjectMemberships.length).toBe(0);
+
+ // ...but recoverable from the delete audit before payload.
+ const auditLog = await prisma.auditLog.findFirst({
+ where: {
+ resourceType: "orgMembership",
+ resourceId: orgMembership.id,
+ action: "delete",
+ orgId: orgId,
+ },
+ });
+ expect(auditLog).not.toBeNull();
+ expect(auditLog!.before).toContain("ProjectMemberships");
+ expect(auditLog!.before).toContain(seededProjectId);
+ });
+
it("should return 404 when user does not exist", async () => {
const nonExistentUserId = randomUUID();
const result = await makeAPICall(
@@ -935,6 +1139,129 @@ describe("SCIM API", () => {
});
});
+ describe("PATCH /api/public/scim/Users/{id}", () => {
+ const patchAuth = () => createBasicAuthHeader(orgApiKey, orgSecretKey);
+ const provisionOp = {
+ schemas: ["urn:ietf:params:scim:api:messages:2.0:PatchOp"],
+ Operations: [{ op: "replace", value: { active: true } }],
+ };
+ const deprovisionOp = {
+ schemas: ["urn:ietf:params:scim:api:messages:2.0:PatchOp"],
+ Operations: [{ op: "replace", value: { active: false } }],
+ };
+
+ beforeEach(async () => {
+ 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 not modify an existing member's role on PATCH active:true (no-op, no audit)", async () => {
+ await prisma.organizationMembership.updateMany({
+ where: { userId: testUserId, orgId: orgId },
+ data: { role: "MEMBER" },
+ });
+ const before = await prisma.organizationMembership.findFirst({
+ where: { userId: testUserId, orgId: orgId },
+ });
+
+ const result = await makeAPICall(
+ "PATCH",
+ `/api/public/scim/Users/${testUserId}`,
+ provisionOp,
+ patchAuth(),
+ );
+ expect(result.status).toBe(200);
+
+ const after = await prisma.organizationMembership.findMany({
+ where: { userId: testUserId, orgId: orgId },
+ });
+ expect(after.length).toBe(1);
+ expect(after[0].role).toBe("MEMBER");
+
+ const auditLogs = await prisma.auditLog.findMany({
+ where: {
+ resourceType: "orgMembership",
+ resourceId: before!.id,
+ orgId: orgId,
+ },
+ });
+ expect(auditLogs.length).toBe(0);
+ });
+
+ it("should write a create audit log when PATCH active:true provisions a missing membership", async () => {
+ await prisma.organizationMembership.deleteMany({
+ where: { userId: testUserId, orgId: orgId },
+ });
+
+ const result = await makeAPICall(
+ "PATCH",
+ `/api/public/scim/Users/${testUserId}`,
+ provisionOp,
+ patchAuth(),
+ );
+ expect(result.status).toBe(200);
+
+ const membership = await prisma.organizationMembership.findFirst({
+ where: { userId: testUserId, orgId: orgId },
+ });
+ expect(membership).not.toBeNull();
+ expect(membership!.role).toBe("NONE");
+
+ const auditLogs = await prisma.auditLog.findMany({
+ where: {
+ resourceType: "orgMembership",
+ resourceId: membership!.id,
+ action: "create",
+ orgId: orgId,
+ },
+ });
+ expect(auditLogs.length).toBe(1);
+ expect(auditLogs[0].apiKeyId).not.toBeNull();
+ });
+
+ it("should write a delete audit log when PATCH active:false deprovisions a membership", async () => {
+ const before = await prisma.organizationMembership.findFirst({
+ where: { userId: testUserId, orgId: orgId },
+ });
+ expect(before).not.toBeNull();
+
+ const result = await makeAPICall(
+ "PATCH",
+ `/api/public/scim/Users/${testUserId}`,
+ deprovisionOp,
+ patchAuth(),
+ );
+ // PATCH ends by delegating to handleGet, so after a successful
+ // deprovision the user is no longer a member and the endpoint responds
+ // 404. The deprovision (and its audit log) still happened β€” asserted
+ // below. (PUT active:false returns 200 instead; this PATCH quirk is
+ // pre-existing and out of scope here.)
+ expect(result.status).toBe(404);
+
+ const remaining = await prisma.organizationMembership.findMany({
+ where: { userId: testUserId, orgId: orgId },
+ });
+ expect(remaining.length).toBe(0);
+
+ const auditLogs = await prisma.auditLog.findMany({
+ where: {
+ resourceType: "orgMembership",
+ resourceId: before!.id,
+ action: "delete",
+ orgId: orgId,
+ },
+ });
+ expect(auditLogs.length).toBe(1);
+ expect(auditLogs[0].before).toContain(before!.id);
+ });
+ });
+
describe("Last OWNER protection", () => {
// Each scenario needs a fresh organization with exactly one OWNER so we
// can exercise the guard without interfering with the seeded OWNER on
@@ -1047,6 +1374,74 @@ describe("SCIM API", () => {
expect(remaining[0].role).toBe("OWNER");
});
+ it("PUT active:true with a lower role rejects demoting the only remaining OWNER", async () => {
+ const result = await makeAPICall(
+ "PUT",
+ `/api/public/scim/Users/${scopedOwnerUserId}`,
+ {
+ 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",
+ );
+
+ const remaining = await prisma.organizationMembership.findMany({
+ where: { userId: scopedOwnerUserId, orgId: scopedOrgId },
+ });
+ expect(remaining.length).toBe(1);
+ expect(remaining[0].role).toBe("OWNER");
+ });
+
+ it("PUT active:true with a lower role allows demoting an OWNER when another OWNER remains", async () => {
+ const secondOwner = await prisma.user.create({
+ data: {
+ email: `owner2.${randomUUID().substring(0, 8)}@example.com`,
+ name: "Second Owner",
+ },
+ });
+ await prisma.organizationMembership.create({
+ data: {
+ userId: secondOwner.id,
+ orgId: scopedOrgId,
+ role: "OWNER",
+ },
+ });
+
+ try {
+ const result = await makeAPICall(
+ "PUT",
+ `/api/public/scim/Users/${scopedOwnerUserId}`,
+ {
+ 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({
+ where: { userId: scopedOwnerUserId, orgId: scopedOrgId },
+ });
+ expect(demoted?.role).toBe("MEMBER");
+ } finally {
+ await prisma.organizationMembership.deleteMany({
+ where: { userId: secondOwner.id, orgId: scopedOrgId },
+ });
+ await prisma.user.deleteMany({ where: { id: secondOwner.id } });
+ }
+ });
+
it("DELETE allows removing an OWNER when another OWNER remains", async () => {
const secondOwner = await prisma.user.create({
data: {
diff --git a/web/src/pages/api/public/scim/Users/[id].ts b/web/src/pages/api/public/scim/Users/[id].ts
index 5a250b01e6..195364afa3 100644
--- a/web/src/pages/api/public/scim/Users/[id].ts
+++ b/web/src/pages/api/public/scim/Users/[id].ts
@@ -1,10 +1,231 @@
import { ApiAuthService } from "@/src/features/public-api/server/apiAuth";
import { cors, runMiddleware } from "@/src/features/public-api/server/cors";
+import { auditLog } from "@/src/features/audit-logs/auditLog";
import { Prisma, 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";
+// Parse the first valid role from a SCIM `roles` array. Returns undefined when
+// the attribute is absent, empty, or unparsable, which the provisioning logic
+// treats as "no explicit role requested".
+function parseScimRole(roles: unknown): Role | undefined {
+ if (!Array.isArray(roles) || roles.length === 0) {
+ return undefined;
+ }
+ const parsed = z
+ .array(z.enum(["OWNER", "ADMIN", "MEMBER", "VIEWER", "NONE"]))
+ .safeParse(roles);
+ return parsed.success ? parsed.data[0] : undefined;
+}
+
+type ProvisionOutcome =
+ | { kind: "created"; role: Role }
+ | { kind: "updated"; role: Role }
+ | { kind: "unchanged"; role: Role };
+
+// Provision a user into an organization in response to a SCIM `active: true`.
+//
+// Behaviour:
+// - role provided β†’ set the membership to that role (create if missing,
+// update if it differs). An explicit role is always honoured.
+// - role omitted β†’ create the membership with the default NONE role when it
+// is missing, but leave an existing membership untouched. This is what keeps
+// a periodic IdP full-sync (which omits roles) from resetting a member's role
+// back to NONE.
+//
+// Writes an audit log entry only when state actually changes (create/update),
+// never for a no-op.
+// 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,
+ role,
+}: {
+ res: NextApiResponse;
+ userId: string;
+ orgId: string;
+ apiKeyId: string;
+ role?: Role;
+}): Promise<ProvisionOutcome | null> {
+ // 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
+ // taken outside the transaction could race a concurrent promotion or
+ // 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.
+ const applyRoleToExisting = async (
+ targetRole: Role,
+ ): Promise<ProvisionOutcome | "missing" | null> => {
+ try {
+ const result = await prisma.$transaction(
+ async (tx) => {
+ const current = await tx.organizationMembership.findUnique({
+ where: { orgId_userId: { orgId, userId } },
+ });
+ if (!current) {
+ return { t: "missing" as const };
+ }
+ 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 };
+ }
+ }
+ const updated = await tx.organizationMembership.update({
+ where: { orgId_userId: { orgId, userId } },
+ data: { role: targetRole },
+ });
+ return { t: "updated" as const, before: current, after: updated };
+ },
+ { isolationLevel: Prisma.TransactionIsolationLevel.Serializable },
+ );
+
+ if (result.t === "missing") {
+ return "missing";
+ }
+ 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",
+ resourceId: result.after.id,
+ action: "update",
+ before: result.before,
+ after: result.after,
+ apiKeyId,
+ orgId,
+ });
+ return { kind: "updated", role: targetRole };
+ } catch (error) {
+ // Serialization failure (P2034) from a concurrent membership change;
+ // surface as 409 so the SCIM client retries.
+ if (
+ error instanceof Prisma.PrismaClientKnownRequestError &&
+ error.code === "P2034"
+ ) {
+ logger.warn(
+ `[SCIM] Concurrent role update conflict for user ${userId} in org ${orgId}`,
+ );
+ 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;
+ }
+ };
+
+ const existing = await prisma.organizationMembership.findUnique({
+ where: { orgId_userId: { orgId, userId } },
+ });
+ if (existing) {
+ // No explicit role requested β†’ leave the membership untouched.
+ if (role === undefined) {
+ return { kind: "unchanged", role: existing.role };
+ }
+ const applied = await applyRoleToExisting(role);
+ if (applied !== "missing") {
+ return applied;
+ }
+ // Membership vanished between the read and the transaction (concurrent
+ // deprovision) β€” fall through to the create path below.
+ }
+
+ // 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";
+ try {
+ const created = await prisma.organizationMembership.create({
+ data: { userId, orgId, role: roleToCreate },
+ });
+ await auditLog({
+ resourceType: "orgMembership",
+ resourceId: created.id,
+ action: "create",
+ after: created,
+ apiKeyId,
+ orgId,
+ });
+ return { kind: "created", role: roleToCreate };
+ } catch (error) {
+ // A concurrent provisioning request created the row first. Apply the
+ // requested role onto it (if any), keeping the periodic sync idempotent.
+ if (
+ error instanceof Prisma.PrismaClientKnownRequestError &&
+ error.code === "P2002"
+ ) {
+ if (role === undefined) {
+ return { kind: "unchanged", role: roleToCreate };
+ }
+ const applied = await applyRoleToExisting(role);
+ // "missing" here means the row vanished again right after the conflict;
+ // don't loop β€” report the request as applied with no changes, like the
+ // pre-existing fallback did. The next sync converges.
+ return applied === "missing"
+ ? { kind: "unchanged", role: roleToCreate }
+ : applied;
+ }
+ throw error;
+ }
+}
+
+// Single place for the SCIM provisioning log line so PUT and PATCH stay
+// consistent.
+function logScimProvision(
+ outcome: ProvisionOutcome,
+ userId: string,
+ orgId: string,
+ via: "PUT" | "PATCH",
+) {
+ switch (outcome.kind) {
+ case "created":
+ logger.info(
+ `[SCIM] Provisioned user ${userId} in org ${orgId} with role ${outcome.role} via ${via}`,
+ );
+ break;
+ case "updated":
+ logger.info(
+ `[SCIM] Updated role for user ${userId} in org ${orgId} to ${outcome.role} via ${via}`,
+ );
+ break;
+ case "unchanged":
+ logger.info(
+ `[SCIM] User ${userId} already a member of org ${orgId}; no changes via ${via}`,
+ );
+ break;
+ }
+}
+
// Mirrors the tRPC `deleteMembership` invariant. Wraps the owner-count check
// and the membership delete in a single Serializable transaction so two
// concurrent SCIM deprovision requests cannot both pass the guard and orphan
@@ -14,31 +235,41 @@ async function deprovisionOrReject(
res: NextApiResponse,
userId: string,
orgId: string,
+ apiKeyId: string,
): Promise<boolean> {
try {
const outcome = await prisma.$transaction(
async (tx) => {
const membership = await tx.organizationMembership.findUnique({
where: { orgId_userId: { orgId, userId } },
- select: { role: true },
+ // Capture the project memberships that Postgres cascade-deletes with
+ // this row (ProjectMembership.organizationMembership is onDelete:
+ // Cascade) so the audit `before` preserves which projects the user
+ // could access. They are unrecoverable once the delete commits, and
+ // this keeps parity with the tRPC deleteMembership audit entry.
+ include: { ProjectMemberships: true },
});
- if (membership?.role === "OWNER") {
+ // Already absent: nothing to delete. Idempotent success, no audit.
+ 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 "lastOwner" as const;
+ return { result: "lastOwner" as const };
}
}
- await tx.organizationMembership.deleteMany({
- where: { userId, orgId },
+ await tx.organizationMembership.delete({
+ where: { orgId_userId: { orgId, userId } },
});
- return "deleted" as const;
+ return { result: "deleted" as const, membership };
},
{ isolationLevel: Prisma.TransactionIsolationLevel.Serializable },
);
- if (outcome === "lastOwner") {
+ if (outcome.result === "lastOwner") {
logger.warn(
`[SCIM] Refused to remove last OWNER ${userId} from org ${orgId}`,
);
@@ -50,6 +281,18 @@ async function deprovisionOrReject(
});
return false;
}
+
+ // Only audit when a membership was actually removed.
+ if (outcome.result === "deleted") {
+ await auditLog({
+ resourceType: "orgMembership",
+ resourceId: outcome.membership.id,
+ action: "delete",
+ before: outcome.membership,
+ apiKeyId,
+ orgId,
+ });
+ }
return true;
} catch (error) {
// Postgres maps a serialization failure to Prisma error code P2034 ("could
@@ -140,13 +383,31 @@ export default async function handler(
try {
switch (req.method) {
case "PATCH":
- return handlePatch(req, res, user, authCheck.scope.orgId);
+ return handlePatch(
+ req,
+ res,
+ user,
+ authCheck.scope.orgId,
+ authCheck.scope.apiKeyId,
+ );
case "PUT":
- return handlePut(req, res, user, authCheck.scope.orgId);
+ return handlePut(
+ req,
+ res,
+ user,
+ authCheck.scope.orgId,
+ authCheck.scope.apiKeyId,
+ );
case "GET":
return handleGet(req, res, user, authCheck.scope.orgId);
case "DELETE":
- return handleDelete(req, res, user, authCheck.scope.orgId);
+ return handleDelete(
+ req,
+ res,
+ user,
+ authCheck.scope.orgId,
+ authCheck.scope.apiKeyId,
+ );
default:
// This should never happen due to the check at the beginning
return res.status(405).json({
@@ -222,6 +483,7 @@ async function handlePatch(
res: NextApiResponse,
user: User,
orgId: string,
+ apiKeyId: string,
) {
let body = req.body;
@@ -279,27 +541,21 @@ async function handlePatch(
typeof op.value.active === "boolean"
) {
if (op.value.active) {
- // 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: "NONE",
- },
- update: {},
+ // 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,
});
- logger.info(
- `[SCIM] Provisioned user ${user.id} in org ${orgId} via PATCH`,
- );
+ 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))) {
+ if (!(await deprovisionOrReject(res, user.id, orgId, apiKeyId))) {
return;
}
logger.info(
@@ -329,6 +585,7 @@ async function handlePut(
res: NextApiResponse,
user: User,
orgId: string,
+ apiKeyId: string,
) {
let body = req.body;
@@ -364,45 +621,30 @@ async function handlePut(
});
}
- // Handle active status for provisioning/deprovisioning
+ // Handle active status for provisioning/deprovisioning.
+ //
+ // `active: true` ensures the user is provisioned. An explicit `roles` value is
+ // honoured (the membership is created or updated to that role). When `roles`
+ // is omitted we create a default NONE membership if one is missing but leave
+ // an existing membership untouched β€” so a periodic IdP full-sync that omits
+ // roles cannot reset an existing member's role back to NONE.
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,
- },
+ const outcome = await provisionMembership({
+ res,
+ userId: user.id,
+ orgId,
+ apiKeyId,
+ role: parseScimRole(body.roles),
});
- logger.info(
- `[SCIM] Provisioned user ${user.id} in org ${orgId} with role ${role} via PUT`,
- );
+ // 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))) {
+ if (!(await deprovisionOrReject(res, user.id, orgId, apiKeyId))) {
return;
}
logger.info(
@@ -435,9 +677,10 @@ async function handleDelete(
res: NextApiResponse,
user: User,
orgId: string,
+ apiKeyId: string,
) {
// Deprovision atomically: check + delete in one Serializable txn.
- if (!(await deprovisionOrReject(res, user.id, orgId))) {
+ if (!(await deprovisionOrReject(res, user.id, orgId, apiKeyId))) {
return;
}
logger.info(`[SCIM] Removed user ${user.id} from org ${orgId} via DELETE`);