Skip to content

feat: add SCIM /User endpoints - #2731

Closed
xlgmokha wants to merge 70 commits into
supabase:masterfrom
xlgmokha:auth-1367
Closed

xlgmokha wants to merge 70 commits into
supabase:masterfrom
xlgmokha:auth-1367

Conversation

@xlgmokha

@xlgmokha xlgmokha commented Aug 25, 2026 •

Copy link
Copy Markdown
Contributor

What kind of change does this PR introduce?

Feature. Add SCIM endpoints for core User schema.

What is the current behavior?

These endpoints do not exist yet.

What is the new behavior?

Adds:

Method Path Description
GET /scim/v2/Users List / paginate / sort SCIM users
GET /scim/v2/Users/{id} Get a specific SCIM user
POST /scim/v2/Users Create a new SCIM user
PUT /scim/v2/Users/{id} Replace a specific SCIM user
DELETE /scim/v2/Users/{id} Delete (soft) a specific SCIM user
GET /scim/v2/ResourceTypes/{id} Resource Type endpoint for User resource
GET /scim/v2/Schemas/{id} Schema description endpoint for User schema

Additional context

  • The /Users endpoints authenticate with a bearer SCIM token. Tokens are stored hashed in the new scim_tokens table, are revocable (revoked_at) and expirable (expires_at), and resolve to an sso_provider_id that scopes every query to a single tenant.
  • The new /ResourceTypes/{id} and /Schemas/{id} routes are discovery metadata and are unauthenticated, consistent with the existing /ServiceProviderConfig, /ResourceTypes, and /Schemas endpoints.
  • All SCIM routes stay behind the existing requireScimServerEnabled gate.
  • New migrations add the scim_users and scim_tokens tables. A user's SCIM payload is stored as a JSONB resource column and deletes are soft using deleted_at.
  • PATCH and filtering are not implemented yet. List rejects any filter parameter.

@xlgmokha xlgmokha self-assigned this Aug 25, 2026
@xlgmokha
xlgmokha marked this pull request as ready for review August 25, 2026 23:22
@xlgmokha
xlgmokha requested a review from a team as a code owner August 25, 2026 23:23

func (r *userRepository) Delete(ctx context.Context, id string) error {
var ids []string
if err := r.db.WithContext(ctx).RawQuery("UPDATE scim_users SET deleted_at = now() WHERE sso_provider_id = ? AND deleted_at IS NULL AND id = ? RETURNING id", r.tenant(ctx), id).All(&ids); err != nil {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Severity: MEDIUM

The SCIM DELETE path only sets scim_users.deleted_at; it does not disable the linked auth.users account or revoke its sessions. Once a SCIM record is associated through user_id, a deprovisioning request can report success while that user continues authenticating and using existing sessions.
Helpful? Add 👍 / 👎

💡 Fix Suggestion

Suggestion: The Delete method must also revoke the linked auth user's active sessions and optionally disable the auth.users account after soft-deleting the SCIM record. To accomplish this:

  1. Modify the SQL query to also RETURNING id, user_id so the linked auth user's UUID is retrieved.
  2. Create a small local struct (e.g., deletedScimUser { ID string; UserID *string }) to hold both returned columns.
  3. Wrap the entire operation in a database transaction (r.db.WithContext(ctx).Transaction(...)) so the SCIM soft-delete and session/account actions are atomic.
  4. If user_id is not NULL after the soft-delete, parse it as a uuid.UUID and call models.Logout(tx, userID) to immediately delete all active sessions for that user, preventing continued use of existing tokens.
  5. Optionally (but recommended for complete deprovisioning), also load the auth user via models.FindUserByID(tx, userID, false) and call user.Ban(tx, duration) or set banned_until to a far-future date so new logins are also blocked even if sessions are somehow restored.
  6. Add the necessary imports: github.com/gofrs/uuid and github.com/supabase/auth/internal/models to the file's import block.

This change is constrained to the Delete method but involves multiple new package imports, transaction handling, and two separate database model operations, making it a multi-step change that should be reviewed holistically rather than as a single-line patch.

}

var rows []scimUser
if err := r.db.WithContext(ctx).RawQuery("UPDATE scim_users SET resource = jsonb_set(?::jsonb, '{active}', coalesce(?::jsonb -> 'active', to_jsonb(active))), updated_at = now() WHERE sso_provider_id = ? AND deleted_at IS NULL AND id = ? RETURNING id, resource, active, created_at, updated_at", string(resource), string(resource), r.tenant(ctx), id).All(&rows); err != nil {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Severity: MEDIUM

An authenticated SCIM client can PUT active:false; this SQL only rewrites scim_users.resource and the generated SCIM active value, without propagating deactivation to the linked auth.users account or its sessions. The user can therefore continue logging in and using existing sessions despite SCIM deprovisioning.
Helpful? Add 👍 / 👎

💡 Fix Suggestion

Suggestion: The Replace function must propagate deactivation to the linked auth.users account and invalidate sessions when active: false is set. The fix requires the following coordinated changes:

  1. Add user_id to the scimUser struct in models.go so the linked auth user ID is available after the SQL update:

    type scimUser struct {
        ID        string    `db:"id"`
        UserID    *string   `db:"user_id"`  // add this
        Resource  []byte    `db:"resource"`
        Active    bool      `db:"active"`
        ...
    }
  2. Extend the SQL RETURNING clause in Replace to also return user_id:

    ... RETURNING id, user_id, resource, active, created_at, updated_at
  3. Wrap the whole Replace body in a transaction and, after a successful update, check if the result has Active == false and a non-null UserID. If so:

    • Use models.FindUserByID(tx, uuid.FromStringOrNil(*rows[0].UserID), ...) to fetch the linked auth.users record.
    • Call authUser.Ban(tx, 87600*time.Hour) (or a sentinel "forever" duration) to set banned_until on the auth user, preventing future logins.
    • Call models.Logout(tx, authUser.ID) to delete all active sessions for that user, invalidating any existing tokens.
  4. Handle the re-activation case symmetrically: if Active == true, lift the ban by calling authUser.Ban(tx, 0) (zero duration clears the ban per the existing Ban implementation).

This ensures that SCIM deprovisioning (active: false) is immediately enforced at the auth layer, both preventing new logins and terminating existing sessions.

}

var rows []scimUser
if err := r.db.WithContext(ctx).RawQuery("INSERT INTO scim_users (sso_provider_id, resource) VALUES (?, ?) RETURNING id, resource, active, created_at, updated_at", r.tenant(ctx), resource).All(&rows); err != nil {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Severity: MEDIUM

userName and other fields from an authenticated SCIM POST are persisted without a user_id association. This creates only a shadow scim_users row, so the Auth identity is not bound to SCIM lifecycle operations; subsequent deprovisioning can leave the corresponding account and sessions usable.
Helpful? Add 👍 / 👎

💡 Fix Suggestion

Suggestion: The Create function inserts into scim_users with only (sso_provider_id, resource), never populating the user_id foreign key column defined in the migration. This severs the SCIM lifecycle from the actual auth.users identity, meaning SCIM deprovisioning (DELETE or active: false) only updates the isolated scim_users shadow row and leaves the underlying account and sessions intact.

To fix this properly, several coordinated changes are required:

  1. During SCIM user creation (Create): After inserting the scim_users row, look up or create the corresponding auth.users record (matched by email / userName), then update scim_users.user_id to bind the two rows. The INSERT (or a follow-up UPDATE) must include user_id.

  2. Update the scimUser model (models.go): Add a UserID *string (nullable) db:"user_id" field and propagate it through Get, List, Create, Replace, and Delete queries.

  3. During SCIM user deletion (Delete): After soft-deleting the scim_users row, use the stored user_id to ban or disable the linked auth.users record and revoke all of its active sessions.

  4. During Replace when active: false: Similarly use user_id to disable the auth.users account and invalidate sessions, mirroring the deprovisioning path.

These changes span models.go, user_repository.go (multiple methods), and likely the auth.users management layer, making this a multi-file architectural fix rather than a single-line correction.

xlgmokha added a commit that referenced this pull request Aug 27, 2026
## What kind of change does this PR introduce?

Feature. Add `scim_users` and `scim_tokens` tables.

## What is the current behavior?

These tables do not exist.

## What is the new behavior?

These tables are added to support the SCIM API.

## Additional context

Extracted from #2731
@xlgmokha
xlgmokha marked this pull request as draft September 1, 2026 17:27
@xlgmokha xlgmokha closed this Sep 1, 2026
@xlgmokha
xlgmokha deleted the auth-1367 branch September 1, 2026 20:20
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant