sourcebot icon indicating copy to clipboard operation
sourcebot copied to clipboard

feat: add SCIM 2.0 user provisioning (EE)

Open brendan-kellam opened this issue 5 months ago β€’ 1 comments

Adds a SCIM 2.0 server (EE, gated by the new scim entitlement) so an identity provider (Okta, Entra) can provision and deprovision Sourcebot members.

Scope

  • /scim/v2 Users endpoints: discovery, list+filter, create, get, replace, PATCH (active toggle), delete. Groups deferred.
  • Deprovisioning soft-deactivates the membership (new UserToOrg.isActive): forces logout via sessionVersion and revokes API/OAuth tokens, but preserves the row so the IdP can reactivate.
  • Org-scoped ScimToken (bearer auth via withScimAuth); managed under Settings β†’ Security.
  • JIT auto-join is suppressed once SCIM is enabled (IdP is the source of truth).

Note: the scim entitlement must be added to the lighthouse entitlements list and deployed before online licenses will grant it.

πŸ€– Generated with Claude Code

brendan-kellam avatar Jun 13 '26 00:06 brendan-kellam

Review Change Stack

No actionable comments were generated in the recent review. πŸŽ‰

ℹ️ Recent review info
βš™οΈ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: c8ca0fc7-dae9-4363-a98a-339d7d98c4b5

πŸ“₯ Commits

Reviewing files that changed from the base of the PR and between 260b7894556aec435b5d5e3dfe86cbf8d439f23b and 2234f8dbd5f6679cb819b42af48c19b0113b2bfc.

πŸ“’ Files selected for processing (1)
  • CHANGELOG.md
βœ… Files skipped from review due to trivial changes (1)
  • CHANGELOG.md

Walkthrough

This PR implements an EE SCIM 2.0 server for automated user provisioning and deprovisioning via identity providers. It adds SCIM-specific database columns (isScimEnabled, isActive, scimExternalId, ScimToken), a new structured membership service layer with transactional operations, SCIM 2.0 API routes with bearer-token authentication, server actions for token management, SCIM-aware gating across onboarding and settings flows, and a complete security settings UI for SCIM control and token provisioning.

Changes

EE SCIM 2.0 Provisioning Server and Membership Service Refactor

Layer / File(s) Summary
Database schema and shared SCIM primitives
CHANGELOG.md, packages/db/prisma/migrations/.../migration.sql, packages/db/prisma/schema.prisma, packages/shared/src/constants.ts, packages/shared/src/crypto.ts, packages/shared/src/entitlements.ts, packages/shared/src/index.server.ts, packages/web/src/lib/errorCodes.ts, docs/api-reference/sourcebot-public.openapi.json
Migration adds isScimEnabled to Org, isActive/scimExternalId to UserToOrg, and a new ScimToken table with indexes. Prisma schema reflects these. Shared crypto gains generateScimToken; SCIM_TOKEN_PREFIX constant and scim entitlement literal are added; MEMBERSHIP_MANAGED_BY_IDP error code is introduced. Public OpenAPI schema adds isActive field to user list items.
Membership service layer
packages/web/src/features/membership/membership.service.ts, packages/web/src/features/membership/membership.service.test.ts, packages/web/src/features/membership/errors.ts, packages/web/src/features/membership/logger.ts, packages/web/src/features/membership/utils.ts
Creates membership.service.ts with ensureActiveMember, removeMember, setMemberRole, setMemberActive all running in Serializable transactions with seat-cap enforcement, last-active-owner protection, and credential revocation on deactivation/removal. Adds error factory helpers, getDefaultMemberRole, orgHasAvailability, and a 347-line Vitest test suite covering all membership operations.
SCIM protocol layer
packages/web/src/ee/features/scim/constants.ts, packages/web/src/ee/features/scim/mapper.ts, packages/web/src/ee/features/scim/schemas.ts, packages/web/src/ee/features/scim/schemas.test.ts, packages/web/src/ee/features/scim/withScimAuth.ts, packages/web/src/ee/features/audit/types.ts
Adds SCIM 2.0 URN constants, toScimUser/toScimListResponse/scimJson/scimError mapper helpers, Zod schemas for create/replace/patch with coerceActive/resolveEmail/parseScimPatchOperations/parseScimFilter, static discovery documents (service provider config, user resource type, user schema definition), and withScimAuth bearer-token auth middleware that enforces the scim entitlement and org-level kill switch. Audit types extended to support scim_token actors/targets/metadata.
SCIM 2.0 API route handlers
packages/web/next.config.mjs, packages/web/src/app/api/(server)/ee/scim/v2/ResourceTypes/route.ts, Schemas/route.ts, ServiceProviderConfig/route.ts, Users/route.ts, Users/[id]/route.ts
Adds a Next.js rewrite /scim/v2/:path* β†’ /api/ee/scim/v2/:path* and route handlers for SCIM discovery endpoints, Users GET (filtered/paginated list by email or externalId), and POST (find-or-create with conflict detection, reactivation, and new-member creation logic), and Users/[id] GET/PUT/PATCH/DELETE for membership state CRUD with name/email/active updates.
SCIM server actions and token management
packages/web/src/ee/features/scim/actions.ts, packages/web/src/features/scim/utils.ts
Adds owner+entitlement-gated server actions: getScimBaseUrl, getIsScimEnabled, setScimEnabled (with audit trail), generateScimToken (duplicate-name check, persist hashed token, audit), revokeScimToken (404 guard, delete by hash, audit), and getScimTokens (list with timestamps). Adds isScimEnabled utility combining entitlement check and org flag.
Membership actions module refactor
packages/web/src/features/membership/actions/{members.ts,invites.ts,accountRequests.ts,index.ts}, packages/web/src/ee/features/membership/actions.ts, packages/web/src/features/membership/onCreateUser.ts
Creates features/membership/actions/ modules replacing deleted userManagement/actions.ts, ee/features/userManagement/actions.ts, app/invite/actions.ts, and lib/authUtils.ts. All invite/join/account-request flows now block when SCIM is enabled. onCreateUser hook moved into membership module with first-user owner bootstrap and SCIM-aware auto-join suppression. EE membership actions for role promotion/demotion added to ee/features/membership/actions.ts.
Auth middleware SCIM deactivation gating
packages/web/src/middleware/withAuth.ts, packages/web/src/middleware/withAuth.test.ts
getAuthContext sets role to undefined when membership.isActive is false, denying deactivated members through all auth checks (sessions, API keys, bearer tokens). Test suite updates all existing membership mocks to include isActive/scimExternalId and adds explicit test cases verifying deactivated-member denial across authentication methods.
Security settings SCIM UI
packages/web/src/app/(app)/settings/security/components/scimEnabledSettingsCard.tsx, scimProvisioningSettings.tsx, scimUpsellCard.tsx, inviteLinkEnabledSettingsCard.tsx, memberApprovalRequiredSettingsCard.tsx, settings/security/page.tsx, settings/components/settingsCard.tsx
Adds ScimEnabledSettingsCard (switch + confirmation dialog), ScimProvisioningSettings (base URL copy, token create/revoke with dialogs), and ScimUpsellCard. Existing security setting cards gain optional scimManaged prop to show ManagedByScimBadge and disable controls when SCIM is active. Security page renders SCIM section conditionally on entitlement and shows token management when enabled. BasicSettingsCard gains optional badge prop.
Membership UI and onboarding SCIM gating
packages/web/src/features/membership/components/{notProvisionedCard.tsx,managedByScimBadge.tsx,managedByScimNotice.tsx,deactivatedMemberBadge.tsx,submitJoinRequestCard.tsx,joinOrganizationCard.tsx,pendingApprovalCard.tsx}, packages/web/src/app/(app)/layout.tsx, settings/members/page.tsx, settings/members/components/membersList.tsx, app/invite/page.tsx, app/redeem/page.tsx, app/components/logoutEscapeHatch.tsx
Adds NotProvisionedCard (account-not-provisioned state), ManagedByScimBadge, DeactivatedMemberBadge, ManagedByScimNotice, SubmitJoinRequestCard, and JoinOrganizationCard (moved from app). App layout inserts SCIM check returning NotProvisionedCard before membership-gating logic. Members page shows ManagedByScimNotice instead of invite UI when SCIM is active. MembersList renders SCIM/deactivated badges and sinks inactive members to the bottom. Invite and redeem pages return NotProvisionedCard when SCIM is enabled. LogoutEscapeHatch converted to client component with client-side signOut.
Active membership filtering across APIs and billing
packages/web/src/middleware/withAuth.ts, packages/web/src/app/api/(server)/ee/users/route.ts, ee/askmcp/callback/route.ts, ee/chat/[chatId]/searchMembers/route.ts, settings/license/page.tsx, features/billing/actions.ts, features/billing/servicePing.ts, features/chat/actions.ts, openapi/publicApiSchemas.ts, lib/posthogEvents.ts
All Prisma queries filtering userToOrg memberships now include isActive: true constraint; seat-count calculations and member-listing endpoints exclude deactivated members. Public user API responses include isActive field. UpsellSource type adds 'scim_settings'.

Sequence Diagram

sequenceDiagram
  participant IdP as Identity Provider<br/>(Okta/Entra)
  participant SCIMRoute as SCIM API Route<br/>(/scim/v2/Users)
  participant withScimAuth as withScimAuth<br/>Middleware
  participant MembershipService as membership.service
  participant Database as Prisma Database

  IdP->>SCIMRoute: POST /scim/v2/Users<br/>(Bearer sbscim_...)
  SCIMRoute->>withScimAuth: authenticate(request)
  withScimAuth->>Database: lookup ScimToken by hash
  withScimAuth->>withScimAuth: verify scim entitlement<br/>+ org.isScimEnabled
  alt auth failed
    withScimAuth-->>IdP: 401/403 SCIM Error
  else auth success
    withScimAuth-->>SCIMRoute: ScimAuthContext
    SCIMRoute->>Database: find/create User by email
    SCIMRoute->>Database: check userToOrg membership
    alt user already active
      SCIMRoute-->>IdP: 409 Conflict
    else user inactive
      SCIMRoute->>MembershipService: setMemberActive(true)
      MembershipService->>Database: Serializable tx<br/>update isActive
      SCIMRoute-->>IdP: 200 + SCIM User
    else no membership
      SCIMRoute->>MembershipService: ensureActiveMember()
      MembershipService->>Database: Serializable tx<br/>create + cleanup invites
      SCIMRoute-->>IdP: 201 + SCIM User<br/>+ Location header
    end
  end

Estimated code review effort

🎯 5 (Critical) | ⏱️ ~120 minutes

Possibly related PRs

  • sourcebot-dev/sourcebot#988: Directly related β€” the main PR relocates multi-owner implementation by removing ee/features/userManagement/actions.ts and adding the same promoteToOwner/demoteToMember server actions in ee/features/membership/actions.ts.
  • sourcebot-dev/sourcebot#1168: Directly related β€” the credential revocation logic in revokeAllUserAuthCredentials within membership.service.ts (session version increment, API-key/OAuth token deletion) overlaps with the mechanism introduced for org member removal.
  • sourcebot-dev/sourcebot#1224: Both PRs extend ALL_ENTITLEMENTS in packages/shared/src/entitlements.ts, adding different feature entitlements ("scim" vs "ask") that power downstream feature gating.

Suggested reviewers

  • msukkari
πŸš₯ Pre-merge checks | βœ… 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
βœ… Passed checks (4 passed)
Check name Status Explanation
Description Check βœ… Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check βœ… Passed The title clearly and concisely describes the main feature: adding SCIM 2.0 user provisioning for the Enterprise Edition.
Linked Issues check βœ… Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check βœ… Passed Check skipped because no linked issues were found for this pull request.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
πŸ§ͺ Generate unit tests (beta)
  • [ ] Create PR with unit tests
  • [ ] Commit unit tests in branch brendan/scim-user-provisioning

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❀️ Share

Comment @coderabbitai help to get the list of available commands.

coderabbitai[bot] avatar Jun 13 '26 00:06 coderabbitai[bot]

Preview deployment for your docs. Learn more about Mintlify Previews.

Project Status Preview Updated (UTC)
sourcebot 🟒 Ready View Preview Jun 24, 2026, 3:13 AM

πŸ’‘ Tip: Enable Workflows to automatically generate PRs for you.

mintlify[bot] avatar Jun 24 '26 03:06 mintlify[bot]