Skip to content

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

10.4 KB
Raw Blame
import { cors, runMiddleware } from "@/src/features/public-api/server/cors";
import { prisma } from "@langfuse/shared/src/db";
import { logger } from "@langfuse/shared/src/server";
import { env } from "@/src/env.mjs";
import { type NextApiRequest, type NextApiResponse } from "next";
import { z } from "zod";
import { isBaseError, type Role } from "@langfuse/shared";
import { auditLog } from "@/src/features/audit-logs/auditLog";
import { assertValidOwnershipChange } from "@/src/ee/features/admin-api/server/memberships";
import { requireGatewayEnabledForRole } from "@/src/features/ai-gateway/server/availability";
import { getSfdcService } from "@/src/ee/features/sfdc-sync/server/sfdcService";
import { hasEntitlementBasedOnPlan } from "@/src/features/entitlements/server/hasEntitlement";
import { shadowAuth } from "@/src/features/public-api/server/shadowAuth";
import { writeScimError } from "@/src/features/public-api/server/writeError";
export default async function handler(
  req: NextApiRequest,
  res: NextApiResponse,
) {
  await runMiddleware(req, res, cors);

  if (req.method !== "GET" && req.method !== "POST") {
    logger.error(
      `[SCIM] Method not allowed for ${req.method} on /api/public/scim/Users`,
    );
    return res.status(405).json({
      schemas: ["urn:ietf:params:scim:api:messages:2.0:Error"],
      detail: "Method not allowed",
      status: 405,
    });
  }

  // CHECK AUTH
  const authCheck = await shadowAuth({
    req,
    action:
      req.method === "GET"
        ? "organizationMembers:read"
        : "organizationMembers:CUD",
    allowedAccessLevels: ["organization"],
  });
  if (!authCheck.success) {
    return writeScimError(res, authCheck.error);
  }
  // END CHECK AUTH

  // Gate SCIM provisioning behind the `admin-api` entitlement, matching the
  // sibling organization admin endpoints (memberships, projects, apiKeys).
  // Without this, any org-scoped key could create users and assign roles on
  // plans that do not include the feature.
  if (
    !hasEntitlementBasedOnPlan({
      plan: authCheck.scope.plan,
      entitlement: "admin-api",
    })
  ) {
    return res.status(403).json({
      schemas: ["urn:ietf:params:scim:api:messages:2.0:Error"],
      detail: "This feature is not available on your current plan.",
      status: 403,
    });
  }

  logger.info(
    `[SCIM] Received request for /api/public/scim/Users with method ${req.method} for orgId ${authCheck.scope.orgId}`,
  );

  if (req.method === "GET") {
    try {
      const { filter, startIndex = 1, count = 100 } = req.query;

      // Parse startIndex and count to integers
      const parsedStartIndex = parseInt(startIndex as string, 10) || 1;
      const parsedCount = parseInt(count as string, 10) || 100;

      let whereClause = {};
      if (filter && typeof filter === "string") {
        // Parse filter for userName eq "value"
        const match = filter.match(/userName eq "([^"]+)"/i);
        if (match && match[1]) {
          whereClause = {
            ...whereClause,
            email: match[1].toLowerCase(),
          };
        }
      }

      // Get total count for pagination
      const totalCount = await prisma.organizationMembership.count({
        where: {
          user: whereClause,
          orgId: authCheck.scope.orgId,
        },
      });

      // Get users with pagination
      const userMapping = await prisma.organizationMembership.findMany({
        where: {
          user: whereClause,
          orgId: authCheck.scope.orgId,
        },
        skip: parsedStartIndex - 1, // SCIM uses 1-based indexing
        take: parsedCount,
        select: {
          id: true,
          user: true,
        },
      });

      // Transform to SCIM format
      const scimUsers = userMapping
        .map((userMap) => userMap.user)
        .map((user) => ({
          schemas: ["urn:ietf:params:scim:schemas:core:2.0:User"],
          id: user.id,
          userName: user.email,
          name: {
            formatted: user.name,
          },
          emails: [
            {
              primary: true,
              value: user.email,
              type: "work",
            },
          ],
          meta: {
            resourceType: "User",
          },
        }));

      return res.status(200).json({
        schemas: ["urn:ietf:params:scim:api:messages:2.0:ListResponse"],
        totalResults: totalCount,
        startIndex: parsedStartIndex,
        itemsPerPage: scimUsers.length,
        Resources: scimUsers,
      });
    } catch (error) {
      logger.error("[SCIM] Error retrieving users", error);
      return res.status(500).json({
        schemas: ["urn:ietf:params:scim:api:messages:2.0:Error"],
        detail: "Internal server error",
        status: 500,
      });
    }
  }

  if (req.method === "POST") {
    try {
      let body = req.body;
      if (typeof body === "string") {
        try {
          body = JSON.parse(body);
        } catch (error) {
          logger.error("[SCIM] 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,
          });
        }
      }

      // A `password` in the request body is accepted and ignored. Setting it
      // created a usable login credential for an email address nobody had
      // verified, so an org-scoped key could pre-register an account for
      // someone else's address. Ignoring rather than rejecting is deliberate:
      // RFC 7644 3.3 lets a service provider ignore POSTed content, the
      // attribute is `returned: "never"` so no conformant client can observe
      // the difference, and Okta sends a placeholder password on every create
      // even when password sync is disabled — rejecting it would break those
      // syncs. Users authenticate via SSO, or claim the account through the
      // password-reset flow.
      const { userName, name, displayName, roles } = body;

      if (!userName) {
        logger.warn("[SCIM] userName is required for user creation");
        return res.status(400).json({
          schemas: ["urn:ietf:params:scim:api:messages:2.0:Error"],
          detail: "userName is required",
          status: 400,
        });
      }

      let role: Role = "NONE";
      if (roles && Array.isArray(roles) && roles.length > 0) {
        const roleSchema = z.array(
          z.enum(["OWNER", "ADMIN", "MEMBER", "VIEWER", "NONE", "AI_GATEWAY"]),
        );
        const parsedRoles = roleSchema.safeParse(roles);
        if (!parsedRoles.success) {
          logger.warn("[SCIM] Invalid roles provided for user creation");
          return res.status(400).json({
            schemas: ["urn:ietf:params:scim:api:messages:2.0:Error"],
            detail: `Invalid roles provided: ${JSON.stringify(roles)}, must be one of OWNER, ADMIN, MEMBER, VIEWER, NONE, AI_GATEWAY`,
            status: 400,
          });
        }
        // Use the first valid role
        role = parsedRoles.data[0];
      }

      await assertValidOwnershipChange({
        tx: prisma,
        context: authCheck.ctx,
        orgId: authCheck.scope.orgId,
        from: undefined,
        to: role,
      });
      requireGatewayEnabledForRole(authCheck.scope.orgId, 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
      // with an existing user row.
      const normalizedEmail = userName.toLowerCase();
      const existingUser = await prisma.organizationMembership.findMany({
        where: {
          user: {
            email: normalizedEmail,
          },
          orgId: authCheck.scope.orgId,
        },
      });

      if (existingUser.length > 0) {
        logger.warn(
          `[SCIM] User ${existingUser[0].userId} already exists in organization ${authCheck.scope.orgId}`,
        );
        return res.status(409).json({
          schemas: ["urn:ietf:params:scim:api:messages:2.0:Error"],
          detail: "User with this userName already exists",
          status: 409,
        });
      }

      // Create the user
      const user = await prisma.user.upsert({
        where: {
          email: normalizedEmail,
        },
        create: {
          email: normalizedEmail,
          name: name?.formatted || displayName,
          v4BetaEnabled:
            env.LANGFUSE_MIGRATION_V4_WRITE_MODE === "events_only" ||
            (env.LANGFUSE_MIGRATION_V4_WRITE_MODE === "dual" &&
              Boolean(env.NEXT_PUBLIC_LANGFUSE_CLOUD_REGION)),
        },
        update: {},
      });
      const orgMembership = await prisma.organizationMembership.create({
        data: {
          userId: user.id,
          orgId: authCheck.scope.orgId,
          role,
        },
      });
      await auditLog({
        resourceType: "orgMembership",
        resourceId: orgMembership.id,
        action: "create",
        after: orgMembership,
        apiKeyId: authCheck.scope.apiKeyId,
        orgId: authCheck.scope.orgId,
      });
      logger.info(
        `[SCIM] Assigned user ${user.id} to org ${authCheck.scope.orgId} with role ${role}`,
      );

      await getSfdcService()?.upsertUser({
        userId: user.id,
        email: user.email,
        name: user.name,
        createdAt: user.createdAt,
        // SCIM provisioning is org-admin-driven, never an organic signup.
        leadSource: "Langfuse Cloud Invite",
      });
      await getSfdcService()?.setUserRole({
        orgId: authCheck.scope.orgId,
        userId: user.id,
        email: user.email,
        role,
      });

      // Return SCIM formatted user
      return res.status(201).json({
        schemas: ["urn:ietf:params:scim:schemas:core:2.0:User"],
        id: user.id,
        userName: user.email,
        name: {
          formatted: user.name,
        },
        emails: [
          {
            primary: true,
            value: user.email,
            type: "work",
          },
        ],
        meta: {
          resourceType: "User",
          created: user.createdAt?.toISOString(),
          lastModified: user.updatedAt?.toISOString(),
        },
      });
    } 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",
        status: 500,
      });
    }
  }
}