:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
chore: use idp config as source of truth for domain-id fields (#78527)
Reece Jonesf5e8aeec6b88
diff --git a/ee/api/authentication.py b/ee/api/authentication.pyindex d60334b37fe4..b81ce0f82e6c 100644--- a/ee/api/authentication.py+++ b/ee/api/authentication.py@@ -2,6 +2,7 @@ import reimport jsonimport base64from typing import Any, Literal, TypedDict, Union, cast+from uuid import UUIDfrom django.core.exceptions import ValidationError as DjangoValidationErrorfrom django.http.response import HttpResponse@@ -34,6 +35,7 @@ from social_django.utils import load_backend, load_strategyfrom posthog.cloud_utils import get_cached_instance_licensefrom posthog.constants import AvailableFeaturefrom posthog.exceptions_capture import capture_exception+from posthog.models.identity_provider_config import IdentityProviderConfigfrom posthog.models.organization import OrganizationMembershipfrom posthog.models.organization_domain import OrganizationDomain@@ -45,7 +47,7 @@ from ee.api.vercel.utils import get_vercel_jwkssaml_logger = structlog.get_logger("posthog.auth.saml")-def _saml_log_context(email: str, organization_domain: OrganizationDomain | None = None) -> dict[str, Any]:+def _saml_log_context(email: str, organization_id: UUID | None = None) -> dict[str, Any]:from posthog.models.user import Userctx: dict[str, Any] = {@@ -57,10 +59,8 @@ def _saml_log_context(email: str, organization_domain: OrganizationDomain | Noneuser = User.objects.filter(email__iexact=email).first()if user:ctx["user_id"] = str(user.id)- if organization_domain:- membership = user.organization_memberships.filter(- organization_id=organization_domain.organization_id,- ).first()+ if organization_id:+ membership = user.organization_memberships.filter(organization_id=organization_id).first()ctx["membership_level"] = membership.get_level_display() if membership else "none"else:ctx["user_id"] = "unknown"@@ -107,66 +107,75 @@ class MultitenantSAMLAuth(SAMLAuth):def _recover_idp_initiated_relay_state(self) -> None:"""- SP-initiated logins carry a RelayState holding the `OrganizationDomain` UUID, which+ SP-initiated logins carry a RelayState holding the linked IdP config's identifier, whichis how we route an assertion to the right tenant. IdP-initiated logins don't: the IdPeither omits RelayState (Azure AD) or sends its own value (e.g. an app URL). When the- RelayState doesn't map to a verified domain, recover the tenant from the Response's- <Issuer> (the IdP entity ID, stored on the linked `IdentityProviderConfig` as- `saml_entity_id`) and inject a RelayState so the rest of the flow — including signature- validation — proceeds unchanged.+ RelayState doesn't map to a config, recover the tenant from the Response's <Issuer> (the+ IdP entity ID, stored on the `IdentityProviderConfig` as `saml_entity_id`) and inject a+ RelayState so the rest of the flow proceeds unchanged."""data = self.strategy.request_data()saml_response = data.get("SAMLResponse")if not saml_response:return- if self._relay_state_points_to_domain(data.get("RelayState")):+ if self._relay_state_points_to_config(data.get("RelayState")):return # SP-initiated: RelayState already identifies the tenantissuer = self._extract_response_issuer(saml_response)if not issuer:return- # `saml_entity_id` has no uniqueness constraint, so only act on an unambiguous match —- # never guess which tenant an unsolicited assertion belongs to. The IdP config is the- # source of truth for SAML settings, so match the issuer against its `saml_entity_id`.- matches = list(+ # `saml_entity_id` has no uniqueness constraint, so only act on an unambiguous config —+ # never guess which tenant an unsolicited assertion belongs to. The config can be linked+ # to multiple domains, so resolve it before choosing a RelayState.+ configs = list(# nosemgrep: idor-lookup-without-org (pre-auth SAML routing by IdP entity id; the assertion signature is verified afterwards)- OrganizationDomain.objects.verified_domains().filter(identity_provider_config__saml_entity_id=issuer)+ IdentityProviderConfig.objects.filter(+ saml_entity_id=issuer,+ domains__verified_at__isnull=False,+ ).distinct())- if len(matches) != 1:- if len(matches) > 1:- saml_logger.warning("saml_idp_initiated_ambiguous_issuer", issuer=issuer, count=len(matches))+ if len(configs) != 1:+ if len(configs) > 1:+ saml_logger.warning("saml_idp_initiated_ambiguous_issuer", issuer=issuer, count=len(configs))return- organization_domain = matches[0]- if not organization_domain.has_saml:+ idp_config = configs[0]+ relay_state = idp_config.saml_relay_state+ if not idp_config.has_saml or not relay_state:returnsaml_logger.info("saml_idp_initiated_relay_state_recovered",- domain=organization_domain.domain,- organization_id=str(organization_domain.organization_id),+ identity_provider_config_id=str(idp_config.id),+ organization_id=str(idp_config.organization_id),)- # Inject the resolved RelayState so the standard flow routes (and labels the response- # with) the correct tenant. Work on a mutable copy via the public QueryDict API.+ # Inject the config identifier so the standard flow can route the response to the tenant.strategy = cast(DjangoStrategy, self.strategy)mutable_post = strategy.request.POST.copy()- mutable_post["RelayState"] = str(organization_domain.id)+ mutable_post["RelayState"] = relay_state# django-stubs types request.POST as immutable; reassigning it is valid at runtime.strategy.request.POST = mutable_post # type: ignore[assignment] # ty: ignore[invalid-assignment]- def _relay_state_points_to_domain(self, relay_state_str: str | None) -> bool:+ def _relay_state_points_to_config(self, relay_state_str: str | None) -> bool:if not relay_state_str:return Falsecandidate = self.parse_relay_state(relay_state_str).get("idp")if not candidate:return Falsetry:- # nosemgrep: idor-lookup-without-org (pre-auth SAML routing check by domain UUID)- return OrganizationDomain.objects.verified_domains().filter(id=candidate).exists()+ # nosemgrep: idor-lookup-without-org (pre-auth SAML routing check by IdP config identifier)+ return (+ IdentityProviderConfig.objects.filter(+ saml_relay_state=candidate,+ domains__verified_at__isnull=False,+ )+ .distinct()+ .exists()+ )except (DjangoValidationError, ValueError):- return False # not a valid UUID (e.g. an IdP-supplied URL)+ return False # malformed or IdP-supplied value@staticmethoddef _extract_response_issuer(saml_response_b64: str) -> str | None:@@ -186,32 +195,43 @@ class MultitenantSAMLAuth(SAMLAuth):saml_logger.warning("saml_idp_lookup_failed", idp_id="None")raise AuthFailed(self, "Authentication request is invalid. Invalid RelayState.")- try:- organization_domain = (- organization_domain_or_id- if isinstance(organization_domain_or_id, OrganizationDomain)- # nosemgrep: idor-lookup-without-org (pre-auth SAML flow, lookup by UUID on verified domains)- else OrganizationDomain.objects.verified_domains().get(id=organization_domain_or_id)- )- except (OrganizationDomain.DoesNotExist, DjangoValidationError):- saml_logger.warning("saml_idp_lookup_failed", idp_id=str(organization_domain_or_id))- raise AuthFailed(self, "Authentication request is invalid. Invalid RelayState.")-- if not organization_domain.organization.is_feature_available(AvailableFeature.SAML):+ if isinstance(organization_domain_or_id, OrganizationDomain):+ idp_config = organization_domain_or_id.idp_config+ else:+ try:+ # nosemgrep: idor-lookup-without-org (pre-auth SAML flow, lookup by config identifier on verified configs)+ idp_config = (+ IdentityProviderConfig.objects.filter(+ saml_relay_state=organization_domain_or_id,+ domains__verified_at__isnull=False,+ )+ .distinct()+ .get()+ )+ except (+ IdentityProviderConfig.DoesNotExist,+ IdentityProviderConfig.MultipleObjectsReturned,+ DjangoValidationError,+ ):+ saml_logger.warning("saml_idp_lookup_failed", idp_id=str(organization_domain_or_id))+ raise AuthFailed(self, "Authentication request is invalid. Invalid RelayState.")++ if not idp_config.organization.is_feature_available(AvailableFeature.SAML):saml_logger.warning("saml_license_missing",- domain=organization_domain.domain,- organization_id=str(organization_domain.organization_id),+ organization_id=str(idp_config.organization_id),)raise AuthFailed(self,"Your organization does not have the required license to use SAML.",)- idp_config = organization_domain.idp_config+ if not idp_config.saml_relay_state:+ raise AuthFailed(self, "Authentication request is invalid. Invalid RelayState.")+return SAMLIdentityProvider(self,- str(organization_domain.id),+ idp_config.saml_relay_state,entity_id=idp_config.saml_entity_id,url=idp_config.saml_acs_url,x509cert=idp_config.saml_x509_cert,@@ -238,18 +258,18 @@ class MultitenantSAMLAuth(SAMLAuth):"saml_auth_redirect",domain=instance.domain,organization_id=str(instance.organization_id),- **_saml_log_context(email, instance),+ **_saml_log_context(email, instance.organization_id),)auth = self._create_saml_auth(idp=self.get_idp(instance))# `return_to` sets the RelayState, a value the IdP echoes back in its POST to the# (shared) auth_complete URL. The session cookie is SameSite=Lax and so is dropped on# the IdP's cross-site POST, which would otherwise lose `next` and send the user to `/`;# carrying it in RelayState lets the base `auth_complete` recover it for the post-login- # redirect. `idp` carries the OrganizationDomain id since multiple IdPs share the URL.+ # redirect. `idp` carries the linked config identifier since multiple IdPs share the URL.# We deliberately omit the session key that upstream `SAMLAuth.auth_url` also packs into# RelayState: it would be disclosed to the (potentially attacker-controlled) IdP in the# redirect, and `next` alone is enough to recover the redirect without it.- relay_state = {"idp": str(instance.id), "next": self.data.get("next")}+ relay_state = {"idp": instance.idp_config.saml_relay_state, "next": self.data.get("next")}return auth.login(return_to=json.dumps(relay_state))def _get_attr(@@ -339,9 +359,9 @@ class MultitenantSAMLAuth(SAMLAuth):raise AuthFailed(self, "Authentication request is invalid. Missing IdP identifier.")try:- # nosemgrep: idor-lookup-without-org (pre-auth SAML validation, UUID from IdP round-trip)- organization_domain = OrganizationDomain.objects.verified_domains().get(id=idp_name)- except (OrganizationDomain.DoesNotExist, DjangoValidationError):+ # nosemgrep: idor-lookup-without-org (pre-auth SAML validation, config identifier from IdP round-trip)+ idp_config = IdentityProviderConfig.objects.get(saml_relay_state=idp_name)+ except (IdentityProviderConfig.DoesNotExist, DjangoValidationError):saml_logger.warning("saml_email_domain_validation_failed",reason="invalid_idp",@@ -350,17 +370,35 @@ class MultitenantSAMLAuth(SAMLAuth):)raise AuthFailed(self, "Authentication request is invalid. Invalid IdP identifier.")- if email.split("@")[-1].lower() != organization_domain.domain.lower():+ # A config can back several verified domains, and an assertion is valid for any of them.+ configured_domains = {+ domain.lower()+ for domain in idp_config.domains.filter(verified_at__isnull=False).values_list("domain", flat=True)+ }+ if email.rsplit("@", 1)[-1].lower() in configured_domains:+ return++ if not configured_domains:+ # SAML stays gated behind domain verification, so a config that backs none can't+ # authorize anyone, whatever its RelayState resolves to.saml_logger.warning(- "saml_email_domain_mismatch",- configured_domain=organization_domain.domain,- organization_id=str(organization_domain.organization_id),- **_saml_log_context(email, organization_domain),- )- raise AuthFailed(- self,- "Authentication failed. The email domain from your identity provider does not match the configured domain.",+ "saml_email_domain_validation_failed",+ reason="no_verified_domain",+ idp_id=str(idp_name),+ **_saml_log_context(email),)+ raise AuthFailed(self, "Authentication request is invalid. Invalid IdP identifier.")++ saml_logger.warning(+ "saml_email_domain_mismatch",+ configured_domains=sorted(configured_domains),+ organization_id=str(idp_config.organization_id),+ **_saml_log_context(email, idp_config.organization_id),+ )+ raise AuthFailed(+ self,+ "Authentication failed. The email domain from your identity provider does not match the configured domain.",+ )def get_user_id(self, details, response):"""diff --git a/ee/api/scim/README.md b/ee/api/scim/README.mdindex 71179185099e..822b8413e75e 100644--- a/ee/api/scim/README.md+++ b/ee/api/scim/README.md@@ -6,11 +6,14 @@ SCIM 2.0 (System for Cross-domain Identity Management) enables automated user pr## Architecture-### Domain-Level Tenancy--- SCIM configuration stored on `OrganizationDomain` model (follows SAML pattern)-- Each domain has unique bearer token for authentication-- URL structure: `/scim/v2/{domain_id}/Users`+### IdP-Config-Level Tenancy++- SCIM configuration is stored on the `IdentityProviderConfig`+- Each identity provider configuration has a bearer token and `scim_slug` for authentication+- URL structure: `/scim/v2/{scim_slug}/Users`, where `scim_slug` comes from the `IdentityProviderConfig`+- The config is the SCIM tenant: it can back several `OrganizationDomain` rows, and a request names+ none of them, so requests are scoped by the config's organization. SCIM still requires at least+ one verified domain on the config- Ensures tenant isolation matching existing SAML implementation### User Provisioning Strategy@@ -38,7 +41,22 @@ SCIM 2.0 (System for Cross-domain Identity Management) enables automated user pr### Models-- `posthog/models/organization_domain.py` - Added `scim_enabled`, `scim_bearer_token` fields+- `posthog/models/identity_provider_config.py` - Stores `scim_enabled`, `scim_bearer_token`, and `scim_slug`+- `ee/models/scim_provisioned_user.py` - One provisioning record per (user, config)+- `ee/models/scim_request_log.py` - Request log per config, listed per domain in the UI++Both carry a legacy `organization_domain` from when SCIM was addressed per domain. Provisioning+records are attributed to their config by migration `ee.0058`; request logs by the+`backfill_scim_request_log_config` command, which runs outside the deploy because that table grows+with every SCIM request:++```bash+python manage.py backfill_scim_request_log_config --dry-run+python manage.py backfill_scim_request_log_config --batch-size 1000 --sleep 0.1+```++It is resumable and safe to re-run. Until it has finished, the per-domain log listing reads both+keys, so no history is hidden while it works.### Core SCIM Implementation (`ee/api/scim/`)@@ -69,23 +87,23 @@ SCIM 2.0 (System for Cross-domain Identity Management) enables automated user pr### SCIM Endpoints (IdP Integration)```text-GET /scim/v2/{domain_id}/Users # List users-POST /scim/v2/{domain_id}/Users # Create user-GET /scim/v2/{domain_id}/Users/{id} # Get user-PUT /scim/v2/{domain_id}/Users/{id} # Replace user-PATCH /scim/v2/{domain_id}/Users/{id} # Update user-DELETE /scim/v2/{domain_id}/Users/{id} # Deactivate user--GET /scim/v2/{domain_id}/Groups # List groups-POST /scim/v2/{domain_id}/Groups # Create group-GET /scim/v2/{domain_id}/Groups/{id} # Get group-PUT /scim/v2/{domain_id}/Groups/{id} # Replace group-PATCH /scim/v2/{domain_id}/Groups/{id} # Update group-DELETE /scim/v2/{domain_id}/Groups/{id} # Delete group--GET /scim/v2/{domain_id}/ServiceProviderConfig # Provider capabilities-GET /scim/v2/{domain_id}/ResourceTypes # Resource types-GET /scim/v2/{domain_id}/Schemas # SCIM schemas+GET /scim/v2/{scim_slug}/Users # List users+POST /scim/v2/{scim_slug}/Users # Create user+GET /scim/v2/{scim_slug}/Users/{id} # Get user+PUT /scim/v2/{scim_slug}/Users/{id} # Replace user+PATCH /scim/v2/{scim_slug}/Users/{id} # Update user+DELETE /scim/v2/{scim_slug}/Users/{id} # Deactivate user++GET /scim/v2/{scim_slug}/Groups # List groups+POST /scim/v2/{scim_slug}/Groups # Create group+GET /scim/v2/{scim_slug}/Groups/{id} # Get group+PUT /scim/v2/{scim_slug}/Groups/{id} # Replace group+PATCH /scim/v2/{scim_slug}/Groups/{id} # Update group+DELETE /scim/v2/{scim_slug}/Groups/{id} # Delete group++GET /scim/v2/{scim_slug}/ServiceProviderConfig # Provider capabilities+GET /scim/v2/{scim_slug}/ResourceTypes # Resource types+GET /scim/v2/{scim_slug}/Schemas # SCIM schemas```### Management Endpoints (PostHog UI)@@ -114,7 +132,7 @@ Successful response includes the one-time bearer token and SCIM base URL:"id": "<domain_id>","domain": "example.com","scim_enabled": true,- "scim_base_url": "https://app.posthog.com/scim/v2/<domain_id>",+ "scim_base_url": "https://app.posthog.com/scim/v2/<scim_slug>","scim_bearer_token": "<plain_token_once>",...}@@ -135,10 +153,11 @@ Response mirrors JIT disabling: `scim_enabled` becomes `false` and no token is r## Authentication Flow1. IdP makes request to SCIM endpoint with `Authorization: Bearer {token}`-2. `SCIMBearerTokenAuthentication` extracts domain_id from URL-3. Retrieves `OrganizationDomain` and validates token (hashed comparison)-4. Returns domain as `request.auth` for tenant scoping-5. Views filter all queries by `organization_domain.organization`+2. `SCIMBearerTokenAuthentication` extracts `scim_slug` from the URL+3. Retrieves the `IdentityProviderConfig` with that slug, requires SCIM enabled on at least one+ verified domain, and validates the token (hashed comparison)+4. Returns the config as `request.auth` for tenant scoping+5. Views filter all queries by `config.organization`## PATCH Operations Support@@ -238,10 +257,11 @@ org.save()Get the bearer token and base URL from Settings → Authentication domains or via Django shell:```python-token = enable_scim_for_domain(domain)+config = domain.identity_provider_config+token = enable_scim_for_config(config)print(f"Bearer Token: {token}")-scim_url = get_scim_base_url(domain)+scim_url = get_scim_base_url(config)print(f"SCIM Base URL: {scim_url}")```@@ -250,7 +270,7 @@ print(f"SCIM Base URL: {scim_url}")### Create User (New)```json-POST /scim/v2/{domain_id}/Users+POST /scim/v2/{scim_slug}/Users{"userName": "[email protected]","name": {"givenName": "Alice", "familyName": "Smith"},@@ -275,7 +295,7 @@ If user exists in another org:### Update User```json-PATCH /scim/v2/{domain_id}/Users/{id}+PATCH /scim/v2/{scim_slug}/Users/{id}{"Operations": [{"op": "replace", "value": {"name": {"givenName": "Alicia"}}}@@ -288,7 +308,7 @@ PATCH /scim/v2/{domain_id}/Users/{id}### Deactivate User```json-PATCH /scim/v2/{domain_id}/Users/{id}+PATCH /scim/v2/{scim_slug}/Users/{id}{"Operations": [{"op": "replace", "value": {"active": false}}@@ -303,7 +323,7 @@ PATCH /scim/v2/{domain_id}/Users/{id}### Create Group```json-POST /scim/v2/{domain_id}/Groups+POST /scim/v2/{scim_slug}/Groups{"displayName": "Engineering","members": [{"value": "user-id"}]@@ -318,7 +338,7 @@ POST /scim/v2/{domain_id}/Groups### Update Group Members```json-PATCH /scim/v2/{domain_id}/Groups/{id}+PATCH /scim/v2/{scim_slug}/Groups/{id}{"Operations": [{"op": "replace", "value": {"members": [{"value": "user-id-1"}, {"value": "user-id-2"}]}}@@ -365,7 +385,7 @@ pytest ee/api/scim/test/test_groups_api.py### OneLogin1. Go to Applications → Applications → Add App → Search for **"SCIM Provisioner with SAML (SCIM v2 full SAML)"**-2. SCIM Base URL: For cloud, use `https://app.posthog.com/scim/v2/{domain_id}`. For local testing, use your ngrok URL, e.g. `https://<ngrok-subdomain>.ngrok.io/scim/v2/{domain_id}`. The `{domain_id}` can be copied directly from the SCIM configuration screen in PostHog.+2. SCIM Base URL: Use the `scim_base_url` returned by the OrganizationDomain API. It includes the `scim_slug` configured on the linked identity provider configuration.3. Bearer Token: Paste the generated Bearer Token from PostHog. It's only shown on first enable or when regenerating.4. Enable provisioning in the Configuration and Provisioning tabs (otherwise, OneLogin won't push any updates).5. In "Rules", you can sync Role membership by: - Mapping OneLogin roles or groups directly to existing groups in PostHog (by matching names), or - Mapping OneLogin roles/groups that will be upserted in PostHog as neededdiff --git a/ee/api/scim/auth.py b/ee/api/scim/auth.pyindex 398a70d67bf4..f11162888c14 100644--- a/ee/api/scim/auth.py+++ b/ee/api/scim/auth.py@@ -9,33 +9,33 @@ from rest_framework.authentication import BaseAuthenticationfrom rest_framework.request import Requestfrom posthog.constants import AvailableFeature-from posthog.models.organization_domain import OrganizationDomain+from posthog.models.identity_provider_config import IdentityProviderConfigclass SCIMAuthToken:"""- Wrapper class to make OrganizationDomain compatible with DRF's authentication system.+ Wrapper class to make IdentityProviderConfig compatible with DRF's authentication system.DRF expects request.user to have is_authenticated property."""- def __init__(self, domain: OrganizationDomain):- self.domain = domain+ def __init__(self, config: IdentityProviderConfig):+ self.config = configself.is_authenticated = Trueself.is_active = Trueself.pk = None # SCIM auth doesn't have a user PKself.id = Nonedef __str__(self):- return f"SCIMAuth({self.domain.domain})"+ return f"SCIMAuth({self.config.scim_slug})"class SCIMBearerTokenAuthentication(BaseAuthentication):"""SCIM authentication using bearer tokens.- Each OrganizationDomain has its own SCIM bearer token for tenant isolation.+ Each IdentityProviderConfig has its own SCIM bearer token and `scim_slug` for tenant isolation."""- def authenticate(self, request: Request) -> Optional[tuple[SCIMAuthToken, OrganizationDomain]]:+ def authenticate(self, request: Request) -> Optional[tuple[SCIMAuthToken, IdentityProviderConfig]]:if not request.path.startswith("/scim/"):return None@@ -45,41 +45,36 @@ class SCIMBearerTokenAuthentication(BaseAuthentication):if not token:raise exceptions.NotAuthenticated("Bearer token required for SCIM endpoints")- # Extract domain_id from URL path (e.g., /scim/v2/{domain_id}/Users)- domain_id = self._extract_domain_id_from_path(request.path)- if not domain_id:+ # Extract the config slug from the URL path (e.g., /scim/v2/{scim_slug}/Users)+ scim_slug = self._extract_scim_slug_from_path(request.path)+ if not scim_slug:raise exceptions.AuthenticationFailed("Invalid SCIM URL format")try:- # nosemgrep: idor-lookup-without-org (SCIM bearer token auth, domain_id is tenant identifier)- domain = OrganizationDomain.objects.select_related("identity_provider_config").get(id=domain_id)- except OrganizationDomain.DoesNotExist:- raise exceptions.AuthenticationFailed("Invalid organization domain")-- # Read the linked IdP config directly (the source of truth) rather than through the- # empty-config fallback, so a domain with no config fails clearly here instead of falling- # through to a misleading "Invalid bearer token" on a null hash below.- #- # The domain must also be verified: SCIM can be enabled on a config independently of any- # domain (the config API has no verification gate), so re-check verification here to keep- # provisioning gated behind a verified domain.- config = domain.identity_provider_config- if not domain.is_verified or config is None or not config.has_scim:- raise exceptions.AuthenticationFailed("SCIM not configured for this domain")-- if not domain.organization.is_feature_available(AvailableFeature.SCIM):+ # nosemgrep: idor-lookup-without-org (SCIM bearer token auth, config slug is tenant identifier)+ config = IdentityProviderConfig.objects.select_related("organization").get(scim_slug=scim_slug)+ except IdentityProviderConfig.DoesNotExist:+ raise exceptions.AuthenticationFailed("Invalid SCIM slug")++ hashed_token = config.scim_bearer_token+ # SCIM stays gated behind domain verification, which the config API doesn't check. Any of the+ # config's verified domains admits the request — it names a config, not one of the domains+ # behind it — so the config, and its organization, is what scopes the request from here.+ if not config.has_scim or not hashed_token or not config.domains.filter(verified_at__isnull=False).exists():+ raise exceptions.AuthenticationFailed("SCIM is not enabled on a verified domain for this configuration")++ if not config.organization.is_feature_available(AvailableFeature.SCIM):raise exceptions.AuthenticationFailed("Your organization does not have the required license to use SCIM")- # Verify the bearer token matches the stored hashed token (sourced from the IdP config)- if not check_password(token, config.scim_bearer_token):+ if not check_password(token, hashed_token):raise exceptions.AuthenticationFailed("Invalid bearer token")- return (SCIMAuthToken(domain), domain)+ return (SCIMAuthToken(config), config)- def _extract_domain_id_from_path(self, path: str) -> Optional[str]:+ def _extract_scim_slug_from_path(self, path: str) -> Optional[str]:"""- Extract domain UUID from SCIM URL path.- Expected format: /scim/v2/{domain_id}/Users or /scim/v2/{domain_id}/Groups+ Extract the IdP config slug from the SCIM URL path.+ Expected format: /scim/v2/{scim_slug}/Users or /scim/v2/{scim_slug}/Groups"""parts = path.strip("/").split("/")if len(parts) >= 3 and parts[0] == "scim" and parts[1] == "v2":diff --git a/ee/api/scim/group.py b/ee/api/scim/group.pyindex 04f1feba3fba..eeb494764123 100644--- a/ee/api/scim/group.py+++ b/ee/api/scim/group.py@@ -9,7 +9,7 @@ from django_scim.adapters import SCIMGroupfrom scim2_filter_parser.attr_paths import AttrPathfrom posthog.models import OrganizationMembership, User-from posthog.models.organization_domain import OrganizationDomain+from posthog.models.identity_provider_config import IdentityProviderConfigfrom ee.models.rbac.role import Role, RoleMembership@@ -52,22 +52,22 @@ class PostHogSCIMGroup(SCIMGroup):return [{"value": str(rm.user.id),- "$ref": f"/scim/v2/{self._organization_domain.id}/Users/{rm.user.id}",+ "$ref": f"/scim/v2/{self._config.scim_slug}/Users/{rm.user.id}","display": rm.user.email,}for rm in role_memberships]- def __init__(self, obj: Role, organization_domain: OrganizationDomain):+ def __init__(self, obj: Role, config: IdentityProviderConfig):super().__init__(obj)- self._organization_domain = organization_domain+ self._config = config@classmethoddef resource_type_dict(cls, request=None) -> dict:return {"id": cls.resource_type,"name": cls.resource_type,- "endpoint": f"/scim/v2/{request.auth.id if request and request.auth else '{domain_id}'}/Groups",+ "endpoint": f"/scim/v2/{request.auth.scim_slug if request and request.auth else '{scim_slug}'}/Groups","schema": constants.SchemaURI.GROUP,}@@ -82,12 +82,12 @@ class PostHogSCIMGroup(SCIMGroup):"members": self.members,"meta": {"resourceType": self.resource_type,- "location": f"/scim/v2/{self._organization_domain.id}/Groups/{self.id}",+ "location": f"/scim/v2/{self._config.scim_slug}/Groups/{self.id}",},}@classmethod- def from_dict(cls, data: dict, organization_domain: OrganizationDomain) -> "PostHogSCIMGroup":+ def from_dict(cls, data: dict, config: IdentityProviderConfig) -> "PostHogSCIMGroup":"""Create or update a Role from SCIM Group data.Upserts role by name matching.@@ -100,15 +100,15 @@ class PostHogSCIMGroup(SCIMGroup):# Upsert role by namerole, created = Role.objects.get_or_create(name=display_name,- organization=organization_domain.organization,+ organization=config.organization,defaults={"created_by": None},)# Handle member updates if providedif "members" in data:- cls._update_members(role, data["members"], organization_domain)+ cls._update_members(role, data["members"], config)- return cls(role, organization_domain)+ return cls(role, config)@staticmethoddef _parse_member_id(raw_member_id) -> str | None:@@ -130,15 +130,13 @@ class PostHogSCIMGroup(SCIMGroup):return None@staticmethod- def _assign_role_member(role: Role, user_pk: int, organization_domain: OrganizationDomain) -> None:+ def _assign_role_member(role: Role, user_pk: int, config: IdentityProviderConfig) -> None:try:user = User.objects.get(id=user_pk)except User.DoesNotExist:return- org_membership = OrganizationMembership.objects.filter(- user=user, organization=organization_domain.organization- ).first()+ org_membership = OrganizationMembership.objects.filter(user=user, organization=config.organization).first()if not org_membership:return@@ -146,7 +144,7 @@ class PostHogSCIMGroup(SCIMGroup):RoleMembership.objects.get_or_create(role=role, user=user, defaults={"organization_member": org_membership})@classmethod- def _update_members(cls, role: Role, members_data: list[dict], organization_domain: OrganizationDomain) -> None:+ def _update_members(cls, role: Role, members_data: list[dict], config: IdentityProviderConfig) -> None:"""Update role membership based on SCIM members list."""@@ -162,7 +160,7 @@ class PostHogSCIMGroup(SCIMGroup):to_remove = current_user_ids - member_user_idsfor raw_member_id in to_add:- cls._assign_role_member(role, int(raw_member_id), organization_domain)+ cls._assign_role_member(role, int(raw_member_id), config)RoleMembership.objects.filter(role=role, user__id__in=to_remove).delete()@@ -181,7 +179,7 @@ class PostHogSCIMGroup(SCIMGroup):self.obj.save()members_data = data.get("members", [])- self._update_members(self.obj, members_data, self._organization_domain)+ self._update_members(self.obj, members_data, self._config)def delete(self) -> None:"""@@ -208,7 +206,7 @@ class PostHogSCIMGroup(SCIMGroup):raise ValueError("Complex filtered paths for members are not supported")else:members_data: list[dict] = cast(list[dict], value if isinstance(value, list) else [value])- self._update_members(self.obj, members_data, self._organization_domain)+ self._update_members(self.obj, members_data, self._config)def handle_add(self, path: AttrPath, value: Union[str, list, dict], operation: dict) -> None:"""@@ -242,7 +240,7 @@ class PostHogSCIMGroup(SCIMGroup):parsed = self._parse_member_id(member_data.get("value"))if parsed is None:continue- self._assign_role_member(self.obj, int(parsed), self._organization_domain)+ self._assign_role_member(self.obj, int(parsed), self._config)def handle_remove(self, path: AttrPath, value: Union[str, list, dict], operation: dict) -> None:"""@@ -283,5 +281,5 @@ class PostHogSCIMGroup(SCIMGroup):RoleMembership.objects.filter(role=self.obj).delete()@classmethod- def get_queryset_for_organization(cls, organization_domain: OrganizationDomain) -> QuerySet[Role]:- return Role.objects.filter(organization=organization_domain.organization).order_by("id")+ def get_queryset_for_organization(cls, config: IdentityProviderConfig) -> QuerySet[Role]:+ return Role.objects.filter(organization=config.organization).order_by("id")diff --git a/ee/api/scim/test/test_groups_api.py b/ee/api/scim/test/test_groups_api.pyindex bdeda1b7b737..76095c6f58ff 100644--- a/ee/api/scim/test/test_groups_api.py+++ b/ee/api/scim/test/test_groups_api.py@@ -38,11 +38,12 @@ class TestSCIMGroupsAPI(APILicensedTest):# Generate SCIM tokentoken = generate_scim_token()self.plain_token = token.plain- config = IdentityProviderConfig.objects.create(+ self.config = IdentityProviderConfig.objects.create(organization=self.organization, scim_enabled=True, scim_bearer_token=token.hashed)- self.domain.identity_provider_config = config+ self.domain.identity_provider_config = self.configself.domain.save()+ self.config.refresh_from_db()self.scim_headers = {"HTTP_AUTHORIZATION": f"Bearer {self.plain_token}"}self.client.credentials(**self.scim_headers)diff --git a/ee/api/scim/test/test_scim_api.py b/ee/api/scim/test/test_scim_api.pyindex 579db0760d68..800be6162471 100644--- a/ee/api/scim/test/test_scim_api.py+++ b/ee/api/scim/test/test_scim_api.py@@ -9,6 +9,7 @@ from posthog.models.organization_domain import OrganizationDomainfrom ee.api.scim.auth import generate_scim_tokenfrom ee.api.scim.user import PostHogSCIMUser+from ee.api.scim.utils import get_scim_base_urlfrom ee.api.test.base import APILicensedTestfrom ee.models.rbac.role import Role@@ -36,14 +37,52 @@ class TestSCIMAPI(APILicensedTest):# Generate SCIM tokentoken = generate_scim_token()self.plain_token = token.plain- config = IdentityProviderConfig.objects.create(+ self.config = IdentityProviderConfig.objects.create(organization=self.organization, scim_enabled=True, scim_bearer_token=token.hashed)- self.domain.identity_provider_config = config+ self.domain.identity_provider_config = self.configself.domain.save()+ self.config.refresh_from_db()self.scim_headers = {"HTTP_AUTHORIZATION": f"Bearer {self.plain_token}"}+ def test_scim_base_url_uses_linked_config_slug(self):+ assert get_scim_base_url(self.config).endswith(f"/scim/v2/{self.config.scim_slug}")++ def test_scim_uses_config_slug(self):+ self.config.scim_slug = "custom-scim-slug"+ self.config.save(update_fields=["scim_slug"])+ OrganizationDomain.objects.create(+ organization=self.organization,+ domain="example.co.uk",+ verified_at="2024-01-01T00:00:00Z",+ identity_provider_config=self.config,+ )+ self.client.credentials(**self.scim_headers)++ response = self.client.get("/scim/v2/custom-scim-slug/Users")+ assert response.status_code == status.HTTP_200_OK++ response = self.client.get(f"/scim/v2/{self.domain.id}/Users")+ assert response.status_code == status.HTTP_403_FORBIDDEN++ def test_discovery_and_resource_urls_use_the_same_config_slug(self):+ # The tenant an authenticated SCIM request resolves to is the config, so every URL a+ # response hands back has to carry its slug. An IdP that follows ResourceTypes discovery+ # gets a 403 the moment that endpoint advertises something else, such as a domain UUID.+ self.config.scim_slug = "custom-scim-slug"+ self.config.save(update_fields=["scim_slug"])+ self.client.credentials(**self.scim_headers)++ resource_types = self.client.get("/scim/v2/custom-scim-slug/ResourceTypes").json()+ users = self.client.get("/scim/v2/custom-scim-slug/Users").json()++ assert {resource["endpoint"] for resource in resource_types["Resources"]} == {+ "/scim/v2/custom-scim-slug/Users",+ "/scim/v2/custom-scim-slug/Groups",+ }+ assert users["Resources"][0]["meta"]["location"].startswith("/scim/v2/custom-scim-slug/Users/")+def test_invalid_token(self):self.client.credentials(HTTP_AUTHORIZATION="Bearer invalid_token")response = self.client.get(f"/scim/v2/{self.domain.id}/Users")@@ -55,8 +94,8 @@ class TestSCIMAPI(APILicensedTest):assert "detail" in datadef test_domain_without_idp_config_is_rejected(self):- # A domain with no linked IdP config must be rejected by SCIM auth (the no-config case is- # handled explicitly, not by falling through to check_password against a null hash).+ # A domain with no linked IdP config has no SCIM endpoint of its own: its id is not a config+ # slug, so even a valid token from another config in the same organization is rejected.unconfigured = OrganizationDomain.objects.create(organization=self.organization,domain="no-config.example.com",@@ -67,9 +106,9 @@ class TestSCIMAPI(APILicensedTest):response = self.client.get(f"/scim/v2/{unconfigured.id}/Users")assert response.status_code == status.HTTP_403_FORBIDDEN- def test_unverified_domain_is_rejected(self):- # SCIM can be enabled on a config independently of any domain, so an unverified domain with- # a SCIM-enabled config must still be rejected — provisioning stays gated behind verification.+ def test_config_without_a_verified_domain_is_rejected(self):+ # SCIM can be enabled on a config independently of any domain, so a config whose only domain+ # is unverified must still be rejected — provisioning stays gated behind verification.token = generate_scim_token()plain_token = token.plainunverified = OrganizationDomain.objects.create(@@ -276,11 +315,12 @@ class TestSCIMEmailDomainValidation(APILicensedTest):token = generate_scim_token()self.plain_token = token.plain- config = IdentityProviderConfig.objects.create(+ self.config = IdentityProviderConfig.objects.create(organization=self.organization, scim_enabled=True, scim_bearer_token=token.hashed)- self.domain.identity_provider_config = config+ self.domain.identity_provider_config = self.configself.domain.save()+ self.config.refresh_from_db()self.scim_headers = {"HTTP_AUTHORIZATION": f"Bearer {self.plain_token}"}@@ -301,7 +341,7 @@ class TestSCIMEmailDomainValidation(APILicensedTest):with self.assertRaises(ValueError, msg="does not match any verified domain"):PostHogSCIMUser.from_dict(self._scim_user_data("[email protected]"),- self.domain,+ self.config,)assert not OrganizationMembership.objects.filter(user=other_user, organization=self.organization).exists()@@ -313,7 +353,7 @@ class TestSCIMEmailDomainValidation(APILicensedTest):scim_user = PostHogSCIMUser.from_dict(self._scim_user_data("[email protected]"),- self.domain,+ self.config,)assert scim_user.obj.email == "[email protected]"@@ -322,7 +362,7 @@ class TestSCIMEmailDomainValidation(APILicensedTest):def test_from_dict_allows_creating_new_user_with_matching_domain(self):scim_user = PostHogSCIMUser.from_dict(self._scim_user_data("[email protected]"),- self.domain,+ self.config,)assert scim_user.obj.email == "[email protected]"@@ -335,7 +375,7 @@ class TestSCIMEmailDomainValidation(APILicensedTest):scim_user = PostHogSCIMUser.from_dict(self._scim_user_data("[email protected]"),- self.domain,+ self.config,)assert scim_user.obj.email == "[email protected]"@@ -349,7 +389,7 @@ class TestSCIMEmailDomainValidation(APILicensedTest):with self.assertRaises(ValueError, msg="does not match any verified domain"):PostHogSCIMUser.from_dict(self._scim_user_data("[email protected]"),- self.domain,+ self.config,)assert not User.objects.filter(email="[email protected]").exists()@@ -357,7 +397,7 @@ class TestSCIMEmailDomainValidation(APILicensedTest):with self.assertRaises(ValueError, msg="does not match any verified domain"):PostHogSCIMUser.from_dict(self._scim_user_data("[email protected]"),- self.domain,+ self.config,)assert not User.objects.filter(email="[email protected]").exists()@@ -445,7 +485,7 @@ class TestSCIMEmailDomainValidation(APILicensedTest):SCIMProvisionedUser.objects.create(user=user,- organization_domain=self.domain,+ identity_provider_config=self.config,username="[email protected]",active=True,)@@ -516,11 +556,12 @@ class TestSCIMAuditLogging(APILicensedTest):token = generate_scim_token()self.plain_token = token.plain- config = IdentityProviderConfig.objects.create(+ self.config = IdentityProviderConfig.objects.create(organization=self.organization, scim_enabled=True, scim_bearer_token=token.hashed)- self.domain.identity_provider_config = config+ self.domain.identity_provider_config = self.configself.domain.save()+ self.config.refresh_from_db()self.scim_headers = {"HTTP_AUTHORIZATION": f"Bearer {self.plain_token}"}@@ -591,7 +632,7 @@ class TestSCIMAuditLogging(APILicensedTest):assert log.user is Noneassert log.organization_id == self.organization.idassert log.detail is not None- assert log.detail.get("context", {}).get("organization_domain") == "example.com"+ assert log.detail.get("context", {}).get("identity_provider_config_id") == str(self.config.id)class TestSCIMGroupAuditLogging(APILicensedTest):@@ -613,11 +654,12 @@ class TestSCIMGroupAuditLogging(APILicensedTest):token = generate_scim_token()self.plain_token = token.plain- config = IdentityProviderConfig.objects.create(+ self.config = IdentityProviderConfig.objects.create(organization=self.organization, scim_enabled=True, scim_bearer_token=token.hashed)- self.domain.identity_provider_config = config+ self.domain.identity_provider_config = self.configself.domain.save()+ self.config.refresh_from_db()self.scim_headers = {"HTTP_AUTHORIZATION": f"Bearer {self.plain_token}"}@@ -684,4 +726,4 @@ class TestSCIMGroupAuditLogging(APILicensedTest):assert log.user is Noneassert log.organization_id == self.organization.idassert log.detail is not None- assert log.detail.get("context", {}).get("organization_domain") == "example.com"+ assert log.detail.get("context", {}).get("identity_provider_config_id") == str(self.config.id)diff --git a/ee/api/scim/test/test_scim_legacy_records.py b/ee/api/scim/test/test_scim_legacy_records.pynew file mode 100644index 000000000000..c04d3eea04b8--- /dev/null+++ b/ee/api/scim/test/test_scim_legacy_records.py@@ -0,0 +1,253 @@+from importlib import import_module+from types import SimpleNamespace++from django.apps import apps+from django.db import connection++from parameterized import parameterized+from rest_framework import status++from posthog.constants import AvailableFeature+from posthog.models import OrganizationMembership, User+from posthog.models.identity_provider_config import IdentityProviderConfig+from posthog.models.organization_domain import OrganizationDomain++from ee.api.scim.auth import generate_scim_token+from ee.api.test.base import APILicensedTest+from ee.models.scim_provisioned_user import SCIMProvisionedUser++backfill_scim_provisioned_user_config = import_module(+ "ee.migrations.0058_backfill_scim_provisioned_user_config"+).backfill_scim_provisioned_user_config+++class TestSCIMRecordsWrittenBeforeConfigs(APILicensedTest):+ # SCIM used to be addressed per domain, so provisioning records were keyed on the domain. Those+ # records have to keep resolving, or the IdP re-provisions people it has already provisioned.++ def setUp(self):+ super().setUp()+ features = self.organization.available_product_features or []+ features.append({"key": AvailableFeature.SCIM, "name": "SCIM"})+ self.organization.available_product_features = features+ self.organization.save()++ self.domain = OrganizationDomain.objects.create(+ organization=self.organization,+ domain="example.com",+ verified_at="2024-01-01T00:00:00Z",+ )+ token = generate_scim_token()+ self.config = IdentityProviderConfig.objects.create(+ organization=self.organization, scim_enabled=True, scim_bearer_token=token.hashed+ )+ self.domain.identity_provider_config = self.config+ self.domain.save()+ self.config.refresh_from_db()++ self.provisioned = User.objects.create_user(+ email="[email protected]", password=None, first_name="Already", is_email_verified=True+ )+ OrganizationMembership.objects.create(+ user=self.provisioned, organization=self.organization, level=OrganizationMembership.Level.MEMBER+ )+ self.legacy_record = self._provision_keyed_on_domain(self.provisioned, "already.okta.username", self.domain)+ backfill_scim_provisioned_user_config(apps, SimpleNamespace(connection=connection))++ # The IdP keeps calling the URL it was configured with, which is the domain's id.+ self.scim_url = f"/scim/v2/{self.domain.id}"+ self.client.credentials(HTTP_AUTHORIZATION=f"Bearer {token.plain}")++ def _provision_keyed_on_domain(self, user: User, username: str, domain: OrganizationDomain) -> SCIMProvisionedUser:+ return SCIMProvisionedUser.objects.create(+ user=user,+ organization_domain=domain,+ identity_provider=SCIMProvisionedUser.IdentityProvider.OKTA,+ username=username,+ active=True,+ )++ def test_the_url_the_idp_was_configured_with_still_authenticates(self):+ assert self.config.scim_slug == str(self.domain.id)+ assert self.client.get(f"{self.scim_url}/Users").status_code == status.HTTP_200_OK++ def test_record_keeps_its_username(self):+ response = self.client.get(f"{self.scim_url}/Users/{self.provisioned.id}")+ assert response.json()["userName"] == "already.okta.username"++ def test_record_is_found_by_username_filter(self):+ response = self.client.get(f'{self.scim_url}/Users?filter=userName eq "already.okta.username"')+ assert [resource["id"] for resource in response.json()["Resources"]] == [str(self.provisioned.id)]++ def test_user_is_not_provisioned_a_second_time(self):+ response = self.client.post(+ f"{self.scim_url}/Users",+ data={+ "schemas": ["urn:ietf:params:scim:schemas:core:2.0:User"],+ "userName": "already.okta.username",+ "emails": [{"value": "[email protected]", "primary": True}],+ "active": True,+ },+ content_type="application/scim+json",+ )+ assert response.status_code == status.HTTP_409_CONFLICT+ assert SCIMProvisionedUser.objects.filter(user=self.provisioned).count() == 1++ def test_deprovisioning_reaches_the_record(self):+ response = self.client.patch(+ f"{self.scim_url}/Users/{self.provisioned.id}",+ data={+ "schemas": ["urn:ietf:params:scim:api:messages:2.0:PatchOp"],+ "Operations": [{"op": "replace", "path": "active", "value": False}],+ },+ content_type="application/scim+json",+ )+ assert response.status_code == status.HTTP_200_OK+ self.legacy_record.refresh_from_db()+ assert self.legacy_record.active is False+ assert not OrganizationMembership.objects.filter(user=self.provisioned, organization=self.organization).exists()++ def test_record_written_after_the_backfill_is_claimed_not_duplicated(self):+ # A pod still running the pre-config code writes domain-keyed records for the length of a+ # rolling deploy. The backfill has already run by then, so only the write path can adopt them.+ late = User.objects.create_user(+ email="[email protected]", password=None, first_name="Late", is_email_verified=True+ )+ OrganizationMembership.objects.create(+ user=late, organization=self.organization, level=OrganizationMembership.Level.MEMBER+ )+ self._provision_keyed_on_domain(late, "late.okta", self.domain)++ response = self.client.post(+ f"{self.scim_url}/Users",+ data={+ "schemas": ["urn:ietf:params:scim:schemas:core:2.0:User"],+ "userName": "late.okta",+ "emails": [{"value": "[email protected]", "primary": True}],+ "active": True,+ },+ content_type="application/scim+json",+ )++ assert response.status_code == status.HTTP_409_CONFLICT+ assert SCIMProvisionedUser.objects.filter(user=late).count() == 1+ assert self.client.get(f"{self.scim_url}/Users/{late.id}").json()["userName"] == "late.okta"++ @parameterized.expand(+ [+ ("deactivate", {"op": "replace", "path": "active", "value": False}),+ ("reactivate", {"op": "add", "path": "active", "value": True}),+ ("rename", {"op": "replace", "path": "name.givenName", "value": "Renamed"}),+ ("change_email", {"op": "replace", "path": "emails", "value": [{"value": "[email protected]"}]}),+ ]+ )+ def test_patch_preserves_the_stored_username(self, _name: str, operation: dict):+ # The active toggles write the username back from the record they can find. Reading the+ # wrong one replaces the IdP's immutable id with the user's email, and the IdP stops+ # matching the user it provisioned.+ response = self.client.patch(+ f"{self.scim_url}/Users/{self.provisioned.id}",+ data={"schemas": ["urn:ietf:params:scim:api:messages:2.0:PatchOp"], "Operations": [operation]},+ content_type="application/scim+json",+ )++ assert response.status_code == status.HTTP_200_OK+ self.legacy_record.refresh_from_db()+ assert self.legacy_record.username == "already.okta.username"++ def test_patch_username_still_replaces_it(self):+ response = self.client.patch(+ f"{self.scim_url}/Users/{self.provisioned.id}",+ data={+ "schemas": ["urn:ietf:params:scim:api:messages:2.0:PatchOp"],+ "Operations": [{"op": "replace", "path": "userName", "value": "renamed.okta"}],+ },+ content_type="application/scim+json",+ )++ assert response.status_code == status.HTTP_200_OK+ self.legacy_record.refresh_from_db()+ assert self.legacy_record.username == "renamed.okta"++ def test_another_configs_records_are_out_of_scope(self):+ # An organization can run several IdPs, each with its own config. Once a record belongs to+ # one of them, moving the domain under another must not hand over the users: a config that+ # never provisioned someone can neither read the id its IdP knows them by nor deprovision+ # them. The domain-keyed fallback only ever covers records no config has claimed.+ second_token = generate_scim_token()+ second_config = IdentityProviderConfig.objects.create(+ organization=self.organization,+ scim_enabled=True,+ scim_bearer_token=second_token.hashed,+ scim_slug="second-config-slug",+ saml_relay_state="second-config-relay",+ )+ self.domain.identity_provider_config = second_config+ self.domain.save()+ self.client.credentials(HTTP_AUTHORIZATION=f"Bearer {second_token.plain}")++ read = self.client.get(f"/scim/v2/second-config-slug/Users/{self.provisioned.id}")+ deprovision = self.client.delete(f"/scim/v2/second-config-slug/Users/{self.provisioned.id}")++ assert read.json()["userName"] == "[email protected]" # its own view of the user, not the other config's+ assert deprovision.status_code == status.HTTP_204_NO_CONTENT+ assert SCIMProvisionedUser.objects.filter(pk=self.legacy_record.pk).exists()++ def test_claiming_a_second_unclaimed_record_does_not_surface_the_constraint(self):+ # Two domains of one config can each hold an unclaimed record for the same user. Claiming+ # one takes (user, config), so the next write's attempt on the other hits the unique+ # constraint — concurrently on a rolling deploy, or in sequence as here. It has to converge+ # on the winner rather than surfacing an IntegrityError as a 500 to the IdP.+ second_domain = OrganizationDomain.objects.create(+ organization=self.organization,+ domain="partner.example.com",+ verified_at="2024-01-01T00:00:00Z",+ identity_provider_config=self.config,+ )+ sibling = self._provision_keyed_on_domain(self.provisioned, "already.partner.username", second_domain)+ SCIMProvisionedUser.objects.filter(pk=self.legacy_record.pk).update(identity_provider_config=self.config)++ for username in ("first.write", "second.write"):+ response = self.client.patch(+ f"{self.scim_url}/Users/{self.provisioned.id}",+ data={+ "schemas": ["urn:ietf:params:scim:api:messages:2.0:PatchOp"],+ "Operations": [{"op": "replace", "path": "userName", "value": username}],+ },+ content_type="application/scim+json",+ )+ assert response.status_code == status.HTTP_200_OK, response.json()++ self.legacy_record.refresh_from_db()+ sibling.refresh_from_db()+ assert self.legacy_record.username == "second.write"+ assert sibling.identity_provider_config_id is None+ assert (+ SCIMProvisionedUser.objects.filter(user=self.provisioned, identity_provider_config=self.config).count() == 1+ )++ def test_write_does_not_collide_with_a_record_the_backfill_skipped(self):+ # One user provisioned through two domains of one config keeps a second record on its domain+ # key. Claiming that one for the config would trip the (user, config) unique constraint.+ second_domain = OrganizationDomain.objects.create(+ organization=self.organization,+ domain="partner.example.com",+ verified_at="2024-01-01T00:00:00Z",+ identity_provider_config=self.config,+ )+ skipped = self._provision_keyed_on_domain(self.provisioned, "already.partner.username", second_domain)++ response = self.client.patch(+ f"{self.scim_url}/Users/{self.provisioned.id}",+ data={+ "schemas": ["urn:ietf:params:scim:api:messages:2.0:PatchOp"],+ "Operations": [{"op": "replace", "path": "userName", "value": "renamed.okta"}],+ },+ content_type="application/scim+json",+ )++ assert response.status_code == status.HTTP_200_OK+ self.legacy_record.refresh_from_db()+ skipped.refresh_from_db()+ assert self.legacy_record.username == "renamed.okta"+ assert skipped.identity_provider_config_id is Nonediff --git a/ee/api/scim/test/test_scim_request_log.py b/ee/api/scim/test/test_scim_request_log.pyindex adf1a8663968..4b2b45c24c06 100644--- a/ee/api/scim/test/test_scim_request_log.py+++ b/ee/api/scim/test/test_scim_request_log.py@@ -38,11 +38,12 @@ class TestSCIMRequestLogCapture(APILicensedTest):)token = generate_scim_token()self.plain_token = token.plain- config = IdentityProviderConfig.objects.create(+ self.config = IdentityProviderConfig.objects.create(organization=self.organization, scim_enabled=True, scim_bearer_token=token.hashed)- self.domain.identity_provider_config = config+ self.domain.identity_provider_config = self.configself.domain.save()+ self.config.refresh_from_db()def test_get_request_creates_log(self):response = self.client.get(@@ -50,7 +51,7 @@ class TestSCIMRequestLogCapture(APILicensedTest):)assert response.status_code == status.HTTP_200_OK- logs = SCIMRequestLog.objects.filter(organization_domain=self.domain)+ logs = SCIMRequestLog.objects.filter(identity_provider_config=self.config)assert logs.count() == 1log = logs.first()@@ -75,14 +76,14 @@ class TestSCIMRequestLogCapture(APILicensedTest):headers={"authorization": f"Bearer {self.plain_token}"},)- log = SCIMRequestLog.objects.filter(organization_domain=self.domain).first()+ log = SCIMRequestLog.objects.filter(identity_provider_config=self.config).first()assert log is not Noneassert log.request_body is not Noneassert "[email protected]" not in str(log.request_body)def test_authorization_header_is_fully_masked(self):self.client.get(f"/scim/v2/{self.domain.id}/Users", headers={"authorization": f"Bearer {self.plain_token}"})- log = SCIMRequestLog.objects.filter(organization_domain=self.domain).first()+ log = SCIMRequestLog.objects.filter(identity_provider_config=self.config).first()assert log is not Noneauth_header = log.request_headers.get("Authorization", "")assert self.plain_token not in auth_header@@ -92,14 +93,14 @@ class TestSCIMRequestLogCapture(APILicensedTest):self.client.get(f"/scim/v2/{self.domain.id}/ServiceProviderConfig", headers={"authorization": f"Bearer {self.plain_token}"})- log = SCIMRequestLog.objects.filter(organization_domain=self.domain).first()+ log = SCIMRequestLog.objects.filter(identity_provider_config=self.config).first()assert log is not Noneassert log.response_body is not Noneassert "schemas" in log.response_bodydef test_duration_is_tracked(self):self.client.get(f"/scim/v2/{self.domain.id}/Users", headers={"authorization": f"Bearer {self.plain_token}"})- log = SCIMRequestLog.objects.filter(organization_domain=self.domain).first()+ log = SCIMRequestLog.objects.filter(identity_provider_config=self.config).first()assert log is not Noneassert log.duration_ms is not Noneassert isinstance(log.duration_ms, int)@@ -109,15 +110,17 @@ class TestSCIMRequestLogCapture(APILicensedTest):class TestSCIMRequestLogCleanup(TestCase):def setUp(self):self.organization = Organization.objects.create(name="Test Org")+ self.config = IdentityProviderConfig.objects.create(organization=self.organization, scim_enabled=True)self.domain = OrganizationDomain.objects.create(organization=self.organization,domain="cleanup-test.com",verified_at=timezone.now(),+ identity_provider_config=self.config,)def _create_log(self, age_days: int) -> SCIMRequestLog:log = SCIMRequestLog.objects.create(- organization_domain=self.domain,+ identity_provider_config=self.config,request_method="GET",request_path="/scim/v2/test/Users",request_headers={},@@ -141,12 +144,23 @@ class TestSCIMRequestLogCleanup(TestCase):exists = SCIMRequestLog.objects.filter(id=log.id).exists()assert exists != should_be_deleted+ def test_deleting_the_config_leaves_the_history_behind(self):+ # The log is the record of what an IdP did to org memberships, so it outlives the+ # configuration it was written against and ages out on its own retention window.+ log = self._create_log(1)+ self.config.delete()++ log.refresh_from_db()++ assert log.identity_provider_config_id is None+ assert log.request_path == "/scim/v2/test/Users"+def test_cleanup_batches_deletes(self):for _ in range(5):self._create_log(200)with patch("ee.tasks.scim_request_log_cleanup.CLEANUP_BATCH_SIZE", 2):cleanup_old_scim_request_logs()- assert SCIMRequestLog.objects.filter(organization_domain=self.domain).count() == 0+ assert SCIMRequestLog.objects.filter(identity_provider_config=self.config).count() == 0class TestSCIMLogsEndpoint(APILicensedTest):@@ -160,15 +174,17 @@ class TestSCIMLogsEndpoint(APILicensedTest):self.organization.available_product_features = featuresself.organization.save()+ self.config = IdentityProviderConfig.objects.create(organization=self.organization, scim_enabled=True)self.domain = OrganizationDomain.objects.create(organization=self.organization,domain="example.com",verified_at="2024-01-01T00:00:00Z",+ identity_provider_config=self.config,)def _create_log(self, **kwargs) -> SCIMRequestLog:defaults = {- "organization_domain": self.domain,+ "identity_provider_config": self.config,"request_method": "GET","request_path": "/scim/v2/test/Users","request_headers": {},@@ -194,6 +210,20 @@ class TestSCIMLogsEndpoint(APILicensedTest):response = self.client.get(f"/api/organizations/{self.organization.id}/domains/{self.domain.id}/scim/logs")assert response.status_code == status.HTTP_403_FORBIDDEN+ def test_logs_written_before_the_move_to_configs_are_still_listed(self):+ # Requests are logged against the config now, but an admin opening a domain's SCIM logs has+ # to keep seeing the history logged against the domain itself.+ OrganizationMembership.objects.filter(user=self.user, organization=self.organization).update(+ level=OrganizationMembership.Level.ADMIN+ )+ self._create_log(identity_provider_config=None, organization_domain=self.domain)+ self._create_log()++ response = self.client.get(f"/api/organizations/{self.organization.id}/domains/{self.domain.id}/scim/logs")++ assert response.status_code == status.HTTP_200_OK+ assert response.json()["count"] == 2+def test_search_by_path(self):OrganizationMembership.objects.filter(user=self.user, organization=self.organization).update(level=OrganizationMembership.Level.ADMINdiff --git a/ee/api/scim/test/test_users_api.py b/ee/api/scim/test/test_users_api.pyindex 14a3dfe1c6a8..1e3fc084b1d4 100644--- a/ee/api/scim/test/test_users_api.py+++ b/ee/api/scim/test/test_users_api.py@@ -36,11 +36,12 @@ class TestSCIMUsersAPI(APILicensedTest):# Generate SCIM tokentoken = generate_scim_token()self.plain_token = token.plain- config = IdentityProviderConfig.objects.create(+ self.config = IdentityProviderConfig.objects.create(organization=self.organization, scim_enabled=True, scim_bearer_token=token.hashed)- self.domain.identity_provider_config = config+ self.domain.identity_provider_config = self.configself.domain.save()+ self.config.refresh_from_db()self.scim_headers = {"HTTP_AUTHORIZATION": f"Bearer {self.plain_token}"}self.client.credentials(**self.scim_headers)@@ -66,7 +67,7 @@ class TestSCIMUsersAPI(APILicensedTest):)SCIMProvisionedUser.objects.create(user=user_a,- organization_domain=self.domain,+ identity_provider_config=self.config,username="[email protected]",identity_provider=SCIMProvisionedUser.IdentityProvider.OTHER,active=True,@@ -80,7 +81,7 @@ class TestSCIMUsersAPI(APILicensedTest):)SCIMProvisionedUser.objects.create(user=user_b,- organization_domain=self.domain,+ identity_provider_config=self.config,username="[email protected]",identity_provider=SCIMProvisionedUser.IdentityProvider.OTHER,active=True,@@ -178,7 +179,7 @@ class TestSCIMUsersAPI(APILicensedTest):assert membership.level == OrganizationMembership.Level.MEMBER# Verify SCIM provisioned user record was created- scim_user = SCIMProvisionedUser.objects.get(user=user, organization_domain=self.domain)+ scim_user = SCIMProvisionedUser.objects.get(user=user, identity_provider_config=self.config)assert scim_user.username == "[email protected]"assert scim_user.active is Trueassert scim_user.identity_provider == SCIMProvisionedUser.IdentityProvider.OTHER@@ -213,7 +214,7 @@ class TestSCIMUsersAPI(APILicensedTest):assert OrganizationMembership.objects.filter(user=existing_user, organization=other_org).exists()# Verify SCIM provisioned user record was created for this domain- scim_user = SCIMProvisionedUser.objects.get(user=existing_user, organization_domain=self.domain)+ scim_user = SCIMProvisionedUser.objects.get(user=existing_user, identity_provider_config=self.config)assert scim_user.active is Truedef test_repeated_post_returns_409_for_already_provisioned_user(self):@@ -258,6 +259,39 @@ class TestSCIMUsersAPI(APILicensedTest):# User should have only one membershipassert OrganizationMembership.objects.filter(user=first_user, organization=self.organization).count() == 1+ def test_linking_another_verified_domain_does_not_reprovision_users(self):+ # Provisioning records key on the config, so a config that starts backing a second verified+ # domain still recognizes the users it has already provisioned. Keying them on one of the+ # config's domains instead would let the pick move and provision everyone a second time.+ user_data = {+ "schemas": ["urn:ietf:params:scim:schemas:core:2.0:User"],+ "userName": "[email protected]",+ "name": {"givenName": "Multi", "familyName": "Domain"},+ "emails": [{"value": "[email protected]", "primary": True}],+ "active": True,+ }+ assert (+ self.client.post(+ f"/scim/v2/{self.domain.id}/Users", data=user_data, content_type="application/scim+json"+ ).status_code+ == status.HTTP_201_CREATED+ )++ OrganizationDomain.objects.create(+ organization=self.organization,+ domain="partner.example.com",+ verified_at="2024-01-01T00:00:00Z",+ identity_provider_config=self.config,+ )++ response = self.client.post(+ f"/scim/v2/{self.domain.id}/Users", data=user_data, content_type="application/scim+json"+ )++ assert response.status_code == status.HTTP_409_CONFLICT+ user = User.objects.get(email="[email protected]")+ assert SCIMProvisionedUser.objects.filter(user=user, identity_provider_config=self.config).count() == 1+def test_get_user(self):user = User.objects.create_user(email="[email protected]", password=None, first_name="Test", last_name="User", is_email_verified=True@@ -294,7 +328,7 @@ class TestSCIMUsersAPI(APILicensedTest):# Create SCIM provisioned user recordSCIMProvisionedUser.objects.create(user=user,- organization_domain=self.domain,+ identity_provider_config=self.config,username="[email protected]",identity_provider=SCIMProvisionedUser.IdentityProvider.OTHER,active=True,@@ -319,7 +353,7 @@ class TestSCIMUsersAPI(APILicensedTest):assert user.is_active is True # User is still active globally# Verify SCIM provisioned user record still exists but is marked inactive- scim_user = SCIMProvisionedUser.objects.get(user=user, organization_domain=self.domain)+ scim_user = SCIMProvisionedUser.objects.get(user=user, identity_provider_config=self.config)assert scim_user.active is Falsedef test_delete_user(self):@@ -332,7 +366,7 @@ class TestSCIMUsersAPI(APILicensedTest):# Create SCIM provisioned user recordSCIMProvisionedUser.objects.create(user=user,- organization_domain=self.domain,+ identity_provider_config=self.config,username="[email protected]",identity_provider=SCIMProvisionedUser.IdentityProvider.OTHER,active=True,@@ -346,7 +380,7 @@ class TestSCIMUsersAPI(APILicensedTest):assert not OrganizationMembership.objects.filter(user=user, organization=self.organization).exists()# Verify SCIM provisioned user record was deleted- assert not SCIMProvisionedUser.objects.filter(user=user, organization_domain=self.domain).exists()+ assert not SCIMProvisionedUser.objects.filter(user=user, identity_provider_config=self.config).exists()def test_put_user(self):user = User.objects.create_user(@@ -358,7 +392,7 @@ class TestSCIMUsersAPI(APILicensedTest):# Create SCIM provisioned user recordSCIMProvisionedUser.objects.create(user=user,- organization_domain=self.domain,+ identity_provider_config=self.config,username="[email protected]",identity_provider=SCIMProvisionedUser.IdentityProvider.OTHER,active=True,@@ -383,7 +417,7 @@ class TestSCIMUsersAPI(APILicensedTest):assert user.email == "[email protected]"# Verify SCIM provisioned user was updated- scim_user = SCIMProvisionedUser.objects.get(user=user, organization_domain=self.domain)+ scim_user = SCIMProvisionedUser.objects.get(user=user, identity_provider_config=self.config)assert scim_user.username == "[email protected]"assert scim_user.active is True@@ -401,14 +435,14 @@ class TestSCIMUsersAPI(APILicensedTest):)SCIMProvisionedUser.objects.create(user=user,- organization_domain=self.domain,+ identity_provider_config=self.config,username="[email protected]",identity_provider=SCIMProvisionedUser.IdentityProvider.OTHER,active=True,)# DeactivateOrganizationMembership.objects.filter(user=user, organization=self.organization).delete()- SCIMProvisionedUser.objects.filter(user=user, organization_domain=self.domain).update(active=False)+ SCIMProvisionedUser.objects.filter(user=user, identity_provider_config=self.config).update(active=False)assert not OrganizationMembership.objects.filter(user=user, organization=self.organization).exists()put_data = {@@ -426,7 +460,7 @@ class TestSCIMUsersAPI(APILicensedTest):assert response.status_code == status.HTTP_200_OKassert response.json()["active"] is Trueassert OrganizationMembership.objects.filter(user=user, organization=self.organization).exists()- scim_user = SCIMProvisionedUser.objects.get(user=user, organization_domain=self.domain)+ scim_user = SCIMProvisionedUser.objects.get(user=user, identity_provider_config=self.config)assert scim_user.active is Truedef test_put_user_not_found(self):@@ -629,7 +663,7 @@ class TestSCIMUsersAPI(APILicensedTest):)SCIMProvisionedUser.objects.create(user=user,- organization_domain=self.domain,+ identity_provider_config=self.config,username="[email protected]",identity_provider=SCIMProvisionedUser.IdentityProvider.OTHER,active=False,@@ -688,7 +722,7 @@ class TestSCIMUsersAPI(APILicensedTest):)SCIMProvisionedUser.objects.create(user=user,- organization_domain=self.domain,+ identity_provider_config=self.config,username="[email protected]",identity_provider=SCIMProvisionedUser.IdentityProvider.OTHER,active=False,@@ -717,14 +751,14 @@ class TestSCIMUsersAPI(APILicensedTest):)SCIMProvisionedUser.objects.create(user=user,- organization_domain=self.domain,+ identity_provider_config=self.config,username="[email protected]",identity_provider=SCIMProvisionedUser.IdentityProvider.OTHER,active=True,)# DeactivateOrganizationMembership.objects.filter(user=user, organization=self.organization).delete()- SCIMProvisionedUser.objects.filter(user=user, organization_domain=self.domain).update(active=False)+ SCIMProvisionedUser.objects.filter(user=user, identity_provider_config=self.config).update(active=False)assert not OrganizationMembership.objects.filter(user=user, organization=self.organization).exists()patch_data = {@@ -739,7 +773,7 @@ class TestSCIMUsersAPI(APILicensedTest):assert response.status_code == status.HTTP_200_OKassert response.json()["active"] is Trueassert OrganizationMembership.objects.filter(user=user, organization=self.organization).exists()- scim_user = SCIMProvisionedUser.objects.get(user=user, organization_domain=self.domain)+ scim_user = SCIMProvisionedUser.objects.get(user=user, identity_provider_config=self.config)assert scim_user.active is Truedef test_patch_add_user_given_name_with_dotted_path(self):@@ -962,7 +996,7 @@ class TestSCIMUsersAPI(APILicensedTest):for i in range(3):SCIMProvisionedUser.objects.create(user=User.objects.get(email=f"paguser{i}@example.com"),- organization_domain=self.domain,+ identity_provider_config=self.config,username=f"paguser{i}@example.com",identity_provider=SCIMProvisionedUser.IdentityProvider.OTHER,active=True,@@ -1013,7 +1047,7 @@ class TestSCIMUsersAPI(APILicensedTest):)SCIMProvisionedUser.objects.create(user=user,- organization_domain=self.domain,+ identity_provider_config=self.config,username="[email protected]",identity_provider=SCIMProvisionedUser.IdentityProvider.OTHER,active=True,@@ -1055,7 +1089,7 @@ class TestSCIMUsersAPI(APILicensedTest):)SCIMProvisionedUser.objects.create(user=user_b,- organization_domain=self.domain,+ identity_provider_config=self.config,username="[email protected]",identity_provider=SCIMProvisionedUser.IdentityProvider.OTHER,active=True,@@ -1091,7 +1125,7 @@ class TestSCIMUsersAPI(APILicensedTest):)SCIMProvisionedUser.objects.create(user=owner,- organization_domain=self.domain,+ identity_provider_config=self.config,username="[email protected]",identity_provider=SCIMProvisionedUser.IdentityProvider.OTHER,active=True,diff --git a/ee/api/scim/user.py b/ee/api/scim/user.pyindex c8a81bcec0e3..0bd27671d2a7 100644--- a/ee/api/scim/user.py+++ b/ee/api/scim/user.py@@ -8,6 +8,7 @@ from django_scim.adapters import SCIMUserfrom scim2_filter_parser.attr_paths import AttrPathfrom posthog.models import Organization, OrganizationMembership, User+from posthog.models.identity_provider_config import IdentityProviderConfigfrom posthog.models.organization_domain import OrganizationDomainfrom ee.models.rbac.role import RoleMembership@@ -15,7 +16,7 @@ from ee.models.scim_provisioned_user import SCIMProvisionedUserclass SCIMUserConflict(Exception):- """User is already SCIM-provisioned for this organization domain."""+ """User is already SCIM-provisioned for this identity provider configuration."""def _validate_email_domain_is_verified(email: str, organization: Organization) -> None:@@ -36,7 +37,7 @@ def _validate_email_domain_is_verified(email: str, organization: Organization) -class PostHogSCIMUser(SCIMUser):"""Adapter to map SCIM User schema to PostHog User model.- Handles user provisioning scoped to a specific OrganizationDomain.+ Handles user provisioning scoped to a specific IdentityProviderConfig."""resource_type = "User"@@ -75,30 +76,24 @@ class PostHogSCIMUser(SCIMUser):@propertydef user_name(self) -> str:- scim_user = SCIMProvisionedUser.objects.filter(- user=self.obj, organization_domain=self._organization_domain- ).first()+ scim_user = SCIMProvisionedUser.objects.record_for(user=self.obj, config=self._config)return scim_user.username if scim_user else self.obj.email@propertydef identity_provider(self) -> str:- scim_user = SCIMProvisionedUser.objects.filter(- user=self.obj, organization_domain=self._organization_domain- ).first()+ scim_user = SCIMProvisionedUser.objects.record_for(user=self.obj, config=self._config)return scim_user.identity_provider if scim_user else SCIMProvisionedUser.IdentityProvider.OTHER@propertydef active(self) -> bool:# A user is "active" in SCIM context if they have membership in this org- if not hasattr(self, "_organization_domain"):+ if not hasattr(self, "_config"):return self.obj.is_active- return OrganizationMembership.objects.filter(- user=self.obj, organization=self._organization_domain.organization- ).exists()+ return OrganizationMembership.objects.filter(user=self.obj, organization=self._config.organization).exists()- def __init__(self, obj: User, organization_domain: OrganizationDomain):+ def __init__(self, obj: User, config: IdentityProviderConfig):super().__init__(obj)- self._organization_domain = organization_domain+ self._config = config@staticmethoddef _extract_email_from_value(emails: list[dict]) -> Optional[str]:@@ -116,7 +111,7 @@ class PostHogSCIMUser(SCIMUser):return {"id": cls.resource_type,"name": cls.resource_type,- "endpoint": f"/scim/v2/{request.auth.id if request and request.auth else '{domain_id}'}/Users",+ "endpoint": f"/scim/v2/{request.auth.scim_slug if request and request.auth else '{scim_slug}'}/Users","schema": constants.SchemaURI.USER,}@@ -133,7 +128,7 @@ class PostHogSCIMUser(SCIMUser):"active": self.active,"meta": {"resourceType": self.resource_type,- "location": f"/scim/v2/{self._organization_domain.id}/Users/{self.id}",+ "location": f"/scim/v2/{self._config.scim_slug}/Users/{self.id}",},}@@ -141,12 +136,12 @@ class PostHogSCIMUser(SCIMUser):base_dict["displayName"] = self.display_namerole_memberships = RoleMembership.objects.filter(- user=self.obj, role__organization=self._organization_domain.organization+ user=self.obj, role__organization=self._config.organization).select_related("role")base_dict["groups"] = [{"value": str(rm.role.id),- "$ref": f"/scim/v2/{self._organization_domain.id}/Groups/{rm.role.id}",+ "$ref": f"/scim/v2/{self._config.scim_slug}/Groups/{rm.role.id}","display": rm.role.name,}for rm in role_memberships@@ -158,7 +153,7 @@ class PostHogSCIMUser(SCIMUser):def from_dict(cls,data: dict,- organization_domain: OrganizationDomain,+ config: IdentityProviderConfig,identity_provider: SCIMProvisionedUser.IdentityProvider = SCIMProvisionedUser.IdentityProvider.OTHER,) -> "PostHogSCIMUser":"""@@ -177,16 +172,14 @@ class PostHogSCIMUser(SCIMUser):with transaction.atomic():user = User.objects.filter(email__iexact=email).first()- # Check if already SCIM-provisioned for this org domain- if user and SCIMProvisionedUser.objects.filter(user=user, organization_domain=organization_domain).exists():+ # Check if already SCIM-provisioned for this IdP config+ if user and SCIMProvisionedUser.objects.record_for(user=user, config=config) is not None:raise SCIMUserConflict()if user:- is_member = OrganizationMembership.objects.filter(- user=user, organization=organization_domain.organization- ).exists()+ is_member = OrganizationMembership.objects.filter(user=user, organization=config.organization).exists()if not is_member:- _validate_email_domain_is_verified(email, organization_domain.organization)+ _validate_email_domain_is_verified(email, config.organization)if first_name:user.first_name = first_name@@ -194,7 +187,7 @@ class PostHogSCIMUser(SCIMUser):user.last_name = last_nameuser.save()else:- _validate_email_domain_is_verified(email, organization_domain.organization)+ _validate_email_domain_is_verified(email, config.organization)# Create new user with no password (they'll use SAML)user = User.objects.create_user(email=email, password=None, first_name=first_name, last_name=last_name, is_email_verified=True@@ -203,19 +196,19 @@ class PostHogSCIMUser(SCIMUser):# Ensure user has membership in this organizationOrganizationMembership.objects.get_or_create(user=user,- organization=organization_domain.organization,+ organization=config.organization,defaults={"level": OrganizationMembership.Level.MEMBER},)# Set current org/team if this is their first orgif not user.current_organization:- user.current_organization = organization_domain.organization- user.current_team = organization_domain.organization.teams.first()+ user.current_organization = config.organization+ user.current_team = config.organization.teams.first()user.save()- SCIMProvisionedUser.objects.update_or_create(+ SCIMProvisionedUser.objects.upsert(user=user,- organization_domain=organization_domain,+ config=config,defaults={"identity_provider": identity_provider,"username": user_name,@@ -223,7 +216,7 @@ class PostHogSCIMUser(SCIMUser):},)- return cls(user, organization_domain)+ return cls(user, config)def put(self, data: dict) -> None:"""@@ -245,18 +238,18 @@ class PostHogSCIMUser(SCIMUser):if existing_user_with_email:raise ValueError("Email belongs to another user")- _validate_email_domain_is_verified(email, self._organization_domain.organization)+ _validate_email_domain_is_verified(email, self._config.organization)# Org must also own the current email domain to prevent cross-tenant account takeover- _validate_email_domain_is_verified(self.obj.email, self._organization_domain.organization)+ _validate_email_domain_is_verified(self.obj.email, self._config.organization)self.obj.first_name = name_data.get("givenName", "")self.obj.last_name = name_data.get("familyName", "")self.obj.email = emailself.obj.save()- SCIMProvisionedUser.objects.update_or_create(+ SCIMProvisionedUser.objects.upsert(user=self.obj,- organization_domain=self._organization_domain,+ config=self._config,defaults={"username": user_name,"active": is_active,@@ -268,7 +261,7 @@ class PostHogSCIMUser(SCIMUser):# Adding org membership to reactivate the userOrganizationMembership.objects.get_or_create(user=self.obj,- organization=self._organization_domain.organization,+ organization=self._config.organization,defaults={"level": OrganizationMembership.Level.MEMBER},)else:@@ -279,7 +272,7 @@ class PostHogSCIMUser(SCIMUser):# canonical current-org/team cleanup run. Tolerate an already-removed membership so# deprovisioning stays idempotent.try:- self.obj.leave(organization=self._organization_domain.organization)+ self.obj.leave(organization=self._config.organization)except OrganizationMembership.DoesNotExist:pass@@ -289,10 +282,7 @@ class PostHogSCIMUser(SCIMUser):"""self._leave_organization()- SCIMProvisionedUser.objects.filter(- user=self.obj,- organization_domain=self._organization_domain,- ).update(active=False)+ SCIMProvisionedUser.objects.for_config(self._config).filter(user=self.obj).update(active=False)def delete(self) -> None:"""@@ -300,10 +290,7 @@ class PostHogSCIMUser(SCIMUser):"""self._leave_organization()- SCIMProvisionedUser.objects.filter(- user=self.obj,- organization_domain=self._organization_domain,- ).delete()+ SCIMProvisionedUser.objects.for_config(self._config).filter(user=self.obj).delete()def handle_replace(self, path: AttrPath, value: Union[str, list, dict], operation: dict) -> None:"""@@ -324,13 +311,13 @@ class PostHogSCIMUser(SCIMUser):else:OrganizationMembership.objects.get_or_create(user=self.obj,- organization=self._organization_domain.organization,+ organization=self._config.organization,defaults={"level": OrganizationMembership.Level.MEMBER},)- SCIMProvisionedUser.objects.update_or_create(+ SCIMProvisionedUser.objects.upsert(user=self.obj,- organization_domain=self._organization_domain,+ config=self._config,defaults={"active": True,"username": self.user_name,@@ -359,15 +346,15 @@ class PostHogSCIMUser(SCIMUser):if email:if User.objects.filter(email__iexact=email).exclude(id=self.obj.id).exists():raise ValueError("Email belongs to another user")- _validate_email_domain_is_verified(email, self._organization_domain.organization)+ _validate_email_domain_is_verified(email, self._config.organization)# Org must also own the current email domain to prevent cross-tenant account takeover- _validate_email_domain_is_verified(self.obj.email, self._organization_domain.organization)+ _validate_email_domain_is_verified(self.obj.email, self._config.organization)self.obj.email = emailelif attr_name == "userName" and isinstance(value, str):- SCIMProvisionedUser.objects.update_or_create(+ SCIMProvisionedUser.objects.upsert(user=self.obj,- organization_domain=self._organization_domain,+ config=self._config,defaults={"username": value,"active": True,@@ -389,13 +376,13 @@ class PostHogSCIMUser(SCIMUser):if attr_name == "active" and value:OrganizationMembership.objects.get_or_create(user=self.obj,- organization=self._organization_domain.organization,+ organization=self._config.organization,defaults={"level": OrganizationMembership.Level.MEMBER},)- SCIMProvisionedUser.objects.update_or_create(+ SCIMProvisionedUser.objects.upsert(user=self.obj,- organization_domain=self._organization_domain,+ config=self._config,defaults={"active": True,"username": self.user_name,@@ -425,16 +412,16 @@ class PostHogSCIMUser(SCIMUser):if email:if User.objects.filter(email__iexact=email).exclude(id=self.obj.id).exists():raise ValueError("Email belongs to another user")- _validate_email_domain_is_verified(email, self._organization_domain.organization)+ _validate_email_domain_is_verified(email, self._config.organization)# Org must also own the current email domain to prevent cross-tenant account takeover- _validate_email_domain_is_verified(self.obj.email, self._organization_domain.organization)+ _validate_email_domain_is_verified(self.obj.email, self._config.organization)self.obj.email = emailself.obj.save()elif attr_name == "userName" and isinstance(value, str):- SCIMProvisionedUser.objects.update_or_create(+ SCIMProvisionedUser.objects.upsert(user=self.obj,- organization_domain=self._organization_domain,+ config=self._config,defaults={"username": value,"active": True,@@ -469,7 +456,5 @@ class PostHogSCIMUser(SCIMUser):raise ValueError("Email is required and cannot be removed")@classmethod- def get_queryset_for_organization(cls, organization_domain: OrganizationDomain) -> QuerySet[User]:- return User.objects.filter(organization_membership__organization=organization_domain.organization).order_by(- "id"- )+ def get_queryset_for_organization(cls, config: IdentityProviderConfig) -> QuerySet[User]:+ return User.objects.filter(organization_membership__organization=config.organization).order_by("id")diff --git a/ee/api/scim/utils.py b/ee/api/scim/utils.pyindex a9d4a8555a15..9873c38169ce 100644--- a/ee/api/scim/utils.py+++ b/ee/api/scim/utils.py@@ -1,9 +1,10 @@from typing import Any+from django.conf import settings+from rest_framework.request import Requestfrom posthog.models.identity_provider_config import IdentityProviderConfig-from posthog.models.organization_domain import OrganizationDomainfrom ee.models.scim_provisioned_user import SCIMProvisionedUser@@ -124,14 +125,11 @@ def regenerate_scim_token_for_config(config: IdentityProviderConfig) -> str:return token.plain-def get_scim_base_url(domain: OrganizationDomain, request=None) -> str:+def get_scim_base_url(config: IdentityProviderConfig) -> str:"""- Get the SCIM base URL for a domain.+ Get the SCIM base URL for an IdentityProviderConfig."""- from django.conf import settings-- base_url = settings.SITE_URL- return f"{base_url}/scim/v2/{domain.id}"+ return f"{settings.SITE_URL}/scim/v2/{config.scim_slug}"def detect_identity_provider(request: Request) -> SCIMProvisionedUser.IdentityProvider:diff --git a/ee/api/scim/views.py b/ee/api/scim/views.pyindex 039f6eea9c24..eb0dc34cd666 100644--- a/ee/api/scim/views.py+++ b/ee/api/scim/views.py@@ -21,7 +21,7 @@ from scim2_filter_parser.transpilers.django_q_object import get_queryfrom posthog.exceptions_capture import capture_exceptionfrom posthog.models import Userfrom posthog.models.activity_logging.activity_log import ActivityContextBase, Detail, log_activity-from posthog.models.organization_domain import OrganizationDomain+from posthog.models.identity_provider_config import IdentityProviderConfigfrom ee.api.scim.auth import SCIMBearerTokenAuthenticationfrom ee.api.scim.group import PostHogSCIMGroup@@ -81,7 +81,7 @@ def _build_scim_list_response(start_index: int,count: int,adapter_cls: type[PostHogSCIMUser] | type[PostHogSCIMGroup],- organization_domain: "OrganizationDomain",+ config: IdentityProviderConfig,) -> dict:total_results = queryset.count()@@ -90,7 +90,7 @@ def _build_scim_list_response(else:offset = start_index - 1page = queryset[offset : offset + count]- resources = [adapter_cls(obj, organization_domain).to_dict() for obj in page]+ resources = [adapter_cls(obj, config).to_dict() for obj in page]return {"schemas": [constants.SchemaURI.LIST_RESPONSE],@@ -104,13 +104,13 @@ def _build_scim_list_response(@dataclasses.dataclass(frozen=True)class SCIMContext(ActivityContextBase):identity_provider: str = ""- organization_domain: str = ""+ identity_provider_config_id: str = ""scim_username: str = ""def _log_scim_activity(*,- organization_domain: OrganizationDomain,+ config: IdentityProviderConfig,activity: str,user_id: str,user_email: str,@@ -118,7 +118,7 @@ def _log_scim_activity() -> None:idp = detect_identity_provider(request)log_activity(- organization_id=organization_domain.organization_id,+ organization_id=config.organization_id,team_id=None,user=None,was_impersonated=False,@@ -129,7 +129,7 @@ def _log_scim_activity(name=user_email,context=SCIMContext(identity_provider=idp.value,- organization_domain=organization_domain.domain,+ identity_provider_config_id=str(config.id),scim_username=request.data.get("userName", ""),),),@@ -138,14 +138,14 @@ def _log_scim_activity(def _log_scim_group_activity(*,- organization_domain: OrganizationDomain,+ config: IdentityProviderConfig,activity: str,role: Role,request: Request,) -> None:idp = detect_identity_provider(request)log_activity(- organization_id=organization_domain.organization_id,+ organization_id=config.organization_id,team_id=None,user=None,was_impersonated=False,@@ -156,7 +156,7 @@ def _log_scim_group_activity(name=role.name,context=SCIMContext(identity_provider=idp.value,- organization_domain=organization_domain.domain,+ identity_provider_config_id=str(config.id),),),)@@ -208,10 +208,10 @@ class SCIMBaseView(APIView):"response_status": response.status_code,}- organization_domain = None+ config = Noneif drf_request.auth:- organization_domain = cast(OrganizationDomain, drf_request.auth)- log_data["organization_domain"] = organization_domain.domain+ config = cast(IdentityProviderConfig, drf_request.auth)+ log_data["identity_provider_config_id"] = str(config.id)masked_body = Noneif drf_request.method in ("POST", "PUT", "PATCH"):@@ -226,10 +226,10 @@ class SCIMBaseView(APIView):logger.info("scim_request", **log_data)- if organization_domain is not None:+ if config is not None:try:SCIMRequestLog.objects.create(- organization_domain=organization_domain,+ identity_provider_config=config,request_method=drf_request.method or "",request_path=drf_request.get_full_path(),request_headers=mask_headers(dict(drf_request.headers)),@@ -271,24 +271,23 @@ class PostHogUserFilterQuery(UserFilterQuery):@classmethoddef search(cls, filter_query: str, request: Request) -> QuerySet[User]:- org_domain = cast(OrganizationDomain, request.auth)+ config = cast(IdentityProviderConfig, request.auth)if "userName" in filter_query:# userName is stored in SCIMProvisionedUser, not User# UserFilterQuery only queries User model, so use scim2-filter-parser directlyscim_attr_map = {("userName", None, None): "username"}q_obj = get_query(filter_query, scim_attr_map)- scim_user_ids = SCIMProvisionedUser.objects.filter(- q_obj,- organization_domain=org_domain,- ).values_list("user_id", flat=True)+ scim_user_ids = (+ SCIMProvisionedUser.objects.for_config(config).filter(q_obj).values_list("user_id", flat=True)+ )return User.objects.filter(id__in=scim_user_ids).order_by("id")raw_queryset = super().search(filter_query, request)user_ids = [user.id for user in raw_queryset]return User.objects.filter(id__in=user_ids,- organization_membership__organization=org_domain.organization,+ organization_membership__organization=config.organization,).order_by("id")@@ -299,17 +298,17 @@ class PostHogGroupFilterQuery(GroupFilterQuery):def search(cls, filter_query: str, request: Request) -> QuerySet[Role]:raw_queryset = super().search(filter_query, request)# Filter results to only include roles from the specified organization- org_domain = cast(OrganizationDomain, request.auth)+ config = cast(IdentityProviderConfig, request.auth)role_ids = [role.id for role in raw_queryset]return Role.objects.filter(id__in=role_ids,- organization=org_domain.organization,+ organization=config.organization,).order_by("id")class SCIMUsersView(SCIMBaseView):- def get(self, request: Request, domain_id: str) -> Response:- organization_domain = cast(OrganizationDomain, request.auth)+ def get(self, request: Request, scim_slug: str) -> Response:+ config = cast(IdentityProviderConfig, request.auth)filter_param = request.query_params.get("filter")try:@@ -329,24 +328,24 @@ class SCIMUsersView(SCIMBaseView):additional_properties={"scim_operation": "filter_users","filter": filter_param,- "domain_id": domain_id,- "organization_id": organization_domain.organization.id,+ "scim_slug": scim_slug,+ "organization_id": config.organization_id,},)queryset = User.objects.none()else:- queryset = PostHogSCIMUser.get_queryset_for_organization(organization_domain)+ queryset = PostHogSCIMUser.get_queryset_for_organization(config)- return Response(_build_scim_list_response(queryset, start_index, count, PostHogSCIMUser, organization_domain))+ return Response(_build_scim_list_response(queryset, start_index, count, PostHogSCIMUser, config))- def post(self, request: Request, domain_id: str) -> Response:- organization_domain = cast(OrganizationDomain, request.auth)+ def post(self, request: Request, scim_slug: str) -> Response:+ config = cast(IdentityProviderConfig, request.auth)try:identity_provider = detect_identity_provider(request)- scim_user = PostHogSCIMUser.from_dict(request.data, organization_domain, identity_provider)+ scim_user = PostHogSCIMUser.from_dict(request.data, config, identity_provider)_log_scim_activity(- organization_domain=organization_domain,+ config=config,activity="scim_provisioned",user_id=scim_user.id,user_email=scim_user.obj.email,@@ -363,8 +362,8 @@ class SCIMUsersView(SCIMBaseView):e,additional_properties={"scim_operation": "create_user",- "domain_id": domain_id,- "organization_id": organization_domain.organization.id,+ "scim_slug": scim_slug,+ "organization_id": config.organization_id,"request_data": request.data,},)@@ -376,15 +375,16 @@ class SCIMUsersView(SCIMBaseView):class SCIMUserDetailView(SCIMBaseView):def get_object(self, user_id: int) -> PostHogSCIMUser:- organization_domain = cast(OrganizationDomain, self.request.auth)+ config = cast(IdentityProviderConfig, self.request.auth)user = User.objects.filter(- Q(organization_membership__organization=organization_domain.organization)- | Q(scim_provisions__organization_domain=organization_domain),+ Q(organization_membership__organization=config.organization)+ | Q(scim_provisions__identity_provider_config=config)+ | Q(scim_provisions__organization_domain__identity_provider_config=config),id=user_id,).first()if not user:raise User.DoesNotExist()- return PostHogSCIMUser(user, organization_domain)+ return PostHogSCIMUser(user, config)def handle_exception(self, exc):if isinstance(exc, User.DoesNotExist):@@ -394,17 +394,17 @@ class SCIMUserDetailView(SCIMBaseView):)return super().handle_exception(exc)- def get(self, request: Request, domain_id: str, user_id: int) -> Response:+ def get(self, request: Request, scim_slug: str, user_id: int) -> Response:scim_user = self.get_object(user_id)return Response(scim_user.to_dict())- def put(self, request: Request, domain_id: str, user_id: int) -> Response:+ def put(self, request: Request, scim_slug: str, user_id: int) -> Response:scim_user = self.get_object(user_id)- organization_domain = cast(OrganizationDomain, request.auth)+ config = cast(IdentityProviderConfig, request.auth)try:scim_user.put(request.data)_log_scim_activity(- organization_domain=organization_domain,+ config=config,activity="scim_replaced",user_id=str(user_id),user_email=scim_user.obj.email,@@ -417,8 +417,8 @@ class SCIMUserDetailView(SCIMBaseView):additional_properties={"scim_operation": "replace_user","user_id": user_id,- "domain_id": domain_id,- "organization_id": cast(OrganizationDomain, request.auth).organization.id,+ "scim_slug": scim_slug,+ "organization_id": cast(IdentityProviderConfig, request.auth).organization_id,"request_data": request.data,},)@@ -427,15 +427,15 @@ class SCIMUserDetailView(SCIMBaseView):status=status.HTTP_400_BAD_REQUEST,)- def patch(self, request: Request, domain_id: str, user_id: int) -> Response:+ def patch(self, request: Request, scim_slug: str, user_id: int) -> Response:scim_user = self.get_object(user_id)- organization_domain = cast(OrganizationDomain, request.auth)+ config = cast(IdentityProviderConfig, request.auth)try:operations = request.data.get("Operations", [])operations = normalize_scim_operations(operations)scim_user.handle_operations(operations)_log_scim_activity(- organization_domain=organization_domain,+ config=config,activity="scim_updated",user_id=str(user_id),user_email=scim_user.obj.email,@@ -448,8 +448,8 @@ class SCIMUserDetailView(SCIMBaseView):additional_properties={"scim_operation": "update_user","user_id": user_id,- "domain_id": domain_id,- "organization_id": cast(OrganizationDomain, request.auth).organization.id,+ "scim_slug": scim_slug,+ "organization_id": cast(IdentityProviderConfig, request.auth).organization_id,"request_data": request.data,},)@@ -458,13 +458,13 @@ class SCIMUserDetailView(SCIMBaseView):status=status.HTTP_400_BAD_REQUEST,)- def delete(self, request: Request, domain_id: str, user_id: int) -> Response:+ def delete(self, request: Request, scim_slug: str, user_id: int) -> Response:scim_user = self.get_object(user_id)user_email = scim_user.obj.emailscim_user.delete()- organization_domain = cast(OrganizationDomain, request.auth)+ config = cast(IdentityProviderConfig, request.auth)_log_scim_activity(- organization_domain=organization_domain,+ config=config,activity="scim_deprovisioned",user_id=str(user_id),user_email=user_email,@@ -474,8 +474,8 @@ class SCIMUserDetailView(SCIMBaseView):class SCIMGroupsView(SCIMBaseView):- def get(self, request: Request, domain_id: str) -> Response:- organization_domain = cast(OrganizationDomain, request.auth)+ def get(self, request: Request, scim_slug: str) -> Response:+ config = cast(IdentityProviderConfig, request.auth)filter_param = request.query_params.get("filter")try:@@ -495,22 +495,22 @@ class SCIMGroupsView(SCIMBaseView):additional_properties={"scim_operation": "filter_groups","filter": filter_param,- "domain_id": domain_id,- "organization_id": organization_domain.organization.id,+ "scim_slug": scim_slug,+ "organization_id": config.organization_id,},)queryset = Role.objects.none()else:- queryset = PostHogSCIMGroup.get_queryset_for_organization(organization_domain)+ queryset = PostHogSCIMGroup.get_queryset_for_organization(config)- return Response(_build_scim_list_response(queryset, start_index, count, PostHogSCIMGroup, organization_domain))+ return Response(_build_scim_list_response(queryset, start_index, count, PostHogSCIMGroup, config))- def post(self, request: Request, domain_id: str) -> Response:- organization_domain = cast(OrganizationDomain, request.auth)+ def post(self, request: Request, scim_slug: str) -> Response:+ config = cast(IdentityProviderConfig, request.auth)try:- scim_group = PostHogSCIMGroup.from_dict(request.data, organization_domain)+ scim_group = PostHogSCIMGroup.from_dict(request.data, config)_log_scim_group_activity(- organization_domain=organization_domain,+ config=config,activity="scim_provisioned",role=scim_group.obj,request=request,@@ -521,8 +521,8 @@ class SCIMGroupsView(SCIMBaseView):e,additional_properties={"scim_operation": "create_group",- "domain_id": domain_id,- "organization_id": organization_domain.organization.id,+ "scim_slug": scim_slug,+ "organization_id": config.organization_id,"request_data": request.data,},)@@ -534,11 +534,11 @@ class SCIMGroupsView(SCIMBaseView):class SCIMGroupDetailView(SCIMBaseView):def get_object(self, group_id: str) -> PostHogSCIMGroup:- organization_domain = cast(OrganizationDomain, self.request.auth)- role = Role.objects.filter(id=group_id, organization=organization_domain.organization).first()+ config = cast(IdentityProviderConfig, self.request.auth)+ role = Role.objects.filter(id=group_id, organization=config.organization).first()if not role:raise Role.DoesNotExist()- return PostHogSCIMGroup(role, organization_domain)+ return PostHogSCIMGroup(role, config)def handle_exception(self, exc):if isinstance(exc, Role.DoesNotExist):@@ -548,16 +548,16 @@ class SCIMGroupDetailView(SCIMBaseView):)return super().handle_exception(exc)- def get(self, request: Request, domain_id: str, group_id: str) -> Response:+ def get(self, request: Request, scim_slug: str, group_id: str) -> Response:scim_group = self.get_object(group_id)return Response(scim_group.to_dict())- def put(self, request: Request, domain_id: str, group_id: str) -> Response:+ def put(self, request: Request, scim_slug: str, group_id: str) -> Response:scim_group = self.get_object(group_id)try:scim_group.put(request.data)_log_scim_group_activity(- organization_domain=cast(OrganizationDomain, request.auth),+ config=cast(IdentityProviderConfig, request.auth),activity="scim_replaced",role=scim_group.obj,request=request,@@ -569,8 +569,8 @@ class SCIMGroupDetailView(SCIMBaseView):additional_properties={"scim_operation": "replace_group","group_id": group_id,- "domain_id": domain_id,- "organization_id": cast(OrganizationDomain, request.auth).organization.id,+ "scim_slug": scim_slug,+ "organization_id": cast(IdentityProviderConfig, request.auth).organization_id,"request_data": request.data,},)@@ -579,13 +579,13 @@ class SCIMGroupDetailView(SCIMBaseView):status=status.HTTP_400_BAD_REQUEST,)- def patch(self, request: Request, domain_id: str, group_id: str) -> Response:+ def patch(self, request: Request, scim_slug: str, group_id: str) -> Response:scim_group = self.get_object(group_id)try:operations = request.data.get("Operations", [])scim_group.handle_operations(operations)_log_scim_group_activity(- organization_domain=cast(OrganizationDomain, request.auth),+ config=cast(IdentityProviderConfig, request.auth),activity="scim_updated",role=scim_group.obj,request=request,@@ -597,8 +597,8 @@ class SCIMGroupDetailView(SCIMBaseView):additional_properties={"scim_operation": "update_group","group_id": group_id,- "domain_id": domain_id,- "organization_id": cast(OrganizationDomain, request.auth).organization.id,+ "scim_slug": scim_slug,+ "organization_id": cast(IdentityProviderConfig, request.auth).organization_id,"request_data": request.data,},)@@ -607,14 +607,14 @@ class SCIMGroupDetailView(SCIMBaseView):status=status.HTTP_400_BAD_REQUEST,)- def delete(self, request: Request, domain_id: str, group_id: str) -> Response:+ def delete(self, request: Request, scim_slug: str, group_id: str) -> Response:scim_group = self.get_object(group_id)- organization_domain = cast(OrganizationDomain, request.auth)+ config = cast(IdentityProviderConfig, request.auth)# Log before delete: Role.delete() runs inside a transaction, which causes# log_activity to defer via on_commit. The outer test transaction never commits,# but more importantly the role row is gone by the time on_commit fires in prod._log_scim_group_activity(- organization_domain=organization_domain,+ config=config,activity="scim_deprovisioned",role=scim_group.obj,request=request,@@ -624,7 +624,7 @@ class SCIMGroupDetailView(SCIMBaseView):class SCIMServiceProviderConfigView(SCIMBaseView):- def get(self, request: Request, domain_id: str) -> Response:+ def get(self, request: Request, scim_slug: str) -> Response:return Response({"schemas": [constants.SchemaURI.SERVICE_PROVIDER_CONFIG],@@ -649,7 +649,7 @@ class SCIMServiceProviderConfigView(SCIMBaseView):class SCIMResourceTypesView(SCIMBaseView):- def get(self, request: Request, domain_id: str) -> Response:+ def get(self, request: Request, scim_slug: str) -> Response:return Response({"schemas": [constants.SchemaURI.LIST_RESPONSE],@@ -663,7 +663,7 @@ class SCIMResourceTypesView(SCIMBaseView):class SCIMSchemasView(SCIMBaseView):- def get(self, request: Request, domain_id: str) -> Response:+ def get(self, request: Request, scim_slug: str) -> Response:return Response({"schemas": [constants.SchemaURI.LIST_RESPONSE],diff --git a/ee/api/test/test_authentication.py b/ee/api/test/test_authentication.pyindex 0fa00d31397d..9921a58d78f8 100644--- a/ee/api/test/test_authentication.py+++ b/ee/api/test/test_authentication.py@@ -24,7 +24,7 @@ from posthog.models import OrganizationMembership, Userfrom posthog.models.identity_provider_config import IdentityProviderConfigfrom posthog.models.organization_domain import OrganizationDomain-from ee.api.authentication import CustomGoogleOAuth2+from ee.api.authentication import CustomGoogleOAuth2, MultitenantSAMLAuthfrom ee.api.test.base import APILicensedTestfrom ee.models.license import License@@ -429,6 +429,71 @@ class TestEESAMLAuthenticationAPI(APILicensedTest):# Initiate SAML flow+ def _grant_saml(self) -> None:+ if self.organization.is_feature_available(AvailableFeature.SAML):+ return+ self.organization.available_product_features = [+ *(self.organization.available_product_features or []),+ {"key": AvailableFeature.SAML, "name": AvailableFeature.SAML},+ ]+ self.organization.save()++ def test_saml_config_can_back_multiple_verified_domains(self):+ self._grant_saml()++ config = self.organization_domain.identity_provider_config+ assert config is not None+ config.refresh_from_db()+ OrganizationDomain.objects.create(+ domain="posthog.co.uk",+ verified_at=timezone.now(),+ organization=self.organization,+ identity_provider_config=config,+ )++ auth = object.__new__(MultitenantSAMLAuth)+ idp = auth.get_idp(config.saml_relay_state)++ self.assertEqual(idp.name, config.saml_relay_state)++ def test_relay_state_minted_before_the_move_to_configs_still_resolves(self):+ # A login redirected while SAML routed on domain ids comes back after the switch to config+ # identifiers. The identifier in flight has to keep resolving or the user lands on an error.+ self._grant_saml()+ config = self.organization_domain.identity_provider_config+ assert config is not None+ config.refresh_from_db()++ auth = object.__new__(MultitenantSAMLAuth)+ idp = auth.get_idp(str(self.organization_domain.id))++ self.assertEqual(idp.entity_id, config.saml_entity_id)++ def test_saml_assertion_accepts_any_verified_domain_on_the_config(self):+ # An assertion carries the config's identifier, not a domain, so it is valid for every domain+ # the config backs. Checking the email against a single one of them locks out everyone on the+ # others.+ self._grant_saml()+ config = self.organization_domain.identity_provider_config+ assert config is not None+ config.refresh_from_db()+ OrganizationDomain.objects.create(+ domain="posthog.co.uk",+ verified_at=timezone.now(),+ organization=self.organization,+ identity_provider_config=config,+ )++ auth = object.__new__(MultitenantSAMLAuth)+ details = auth.get_user_details(+ {+ "idp_name": config.saml_relay_state,+ "attributes": {"email": ["[email protected]"]},+ }+ )++ self.assertEqual(details["email"], "[email protected]")+def test_can_initiate_saml_flow(self):response = self.client.get("/login/saml/[email protected]")self.assertEqual(response.status_code, status.HTTP_302_FOUND)@@ -446,8 +511,13 @@ class TestEESAMLAuthenticationAPI(APILicensedTest):)self.assertEqual(response.status_code, status.HTTP_302_FOUND)+ config = self.organization_domain.identity_provider_config+ assert config is not None+ config.refresh_from_db()relay_state = json.loads(parse_qs(urlparse(response.headers["Location"]).query)["RelayState"][0])- self.assertEqual(relay_state["idp"], str(self.organization_domain.id))+ # The identifier comes off the IdP config. It currently equals the domain's id, so asserting+ # against the domain would pass just as well if this regressed to reading the domain.+ self.assertEqual(relay_state["idp"], config.saml_relay_state)self.assertEqual(relay_state["next"], "/settings/organization/authentication")def test_cannot_initiate_saml_flow_without_target_email_address(self):diff --git a/ee/management/commands/backfill_scim_request_log_config.py b/ee/management/commands/backfill_scim_request_log_config.pynew file mode 100644index 000000000000..a6b08abf960c--- /dev/null+++ b/ee/management/commands/backfill_scim_request_log_config.py@@ -0,0 +1,141 @@+"""Attribute pre-existing SCIM request logs to the IdP config that now owns the SCIM endpoint.++Usage:+ python manage.py backfill_scim_request_log_config --dry-run+ python manage.py backfill_scim_request_log_config+ python manage.py backfill_scim_request_log_config --organization-id <uuid> --sleep 0.1++SCIM authenticates against an `IdentityProviderConfig`, so requests are logged against it. Rows+logged while SCIM was addressed per domain carry only `organization_domain`, and a config-scoped+query would see a tenant's history start at the deploy. Until this has run, the SCIM log endpoint+matches both keys, so nothing is hidden while the sweep is in progress.++This is a command rather than a migration because the table holds one row per SCIM request and can+be far too large to sweep inside a deploy. Each batch commits on its own, so the sweep can be+stopped and restarted: rows already carrying a config are skipped, and `--start-after` resumes from+the last id a previous run reported.+"""++import time+from argparse import ArgumentParser+from typing import Any+from uuid import UUID++from django.core.management.base import BaseCommand+from django.db.models import OuterRef, Subquery++import structlog++from posthog.models.organization_domain import OrganizationDomain++from ee.models.scim_request_log import SCIMRequestLog++logger = structlog.get_logger(__name__)++DEFAULT_BATCH_SIZE = 1000+PROGRESS_EVERY_BATCHES = 20+++class Command(BaseCommand):+ help = "Backfill SCIMRequestLog.identity_provider_config from each row's organization domain."++ def add_arguments(self, parser: ArgumentParser) -> None:+ parser.add_argument(+ "--batch-size",+ type=int,+ default=DEFAULT_BATCH_SIZE,+ help=f"Rows updated per transaction (default: {DEFAULT_BATCH_SIZE}).",+ )+ parser.add_argument(+ "--sleep",+ type=float,+ default=0.0,+ help="Seconds to pause between batches, to keep replicas and IO headroom comfortable.",+ )+ parser.add_argument(+ "--organization-id",+ type=str,+ help="Only sweep logs belonging to this organization, for a staged rollout.",+ )+ parser.add_argument(+ "--start-after",+ type=str,+ help="Resume after this log id, as reported by a previous run.",+ )+ parser.add_argument(+ "--dry-run",+ action="store_true",+ help="Report how many rows would be filled, without writing.",+ )++ def handle(self, *args: Any, **options: Any) -> None:+ batch_size: int = options["batch_size"]+ sleep_seconds: float = options["sleep"]+ organization_id: str | None = options.get("organization_id")+ dry_run: bool = options["dry_run"]+ last_id: UUID | None = UUID(options["start_after"]) if options.get("start_after") else None++ pending = SCIMRequestLog.objects.filter(+ identity_provider_config__isnull=True,+ organization_domain__identity_provider_config__isnull=False,+ )+ if organization_id:+ pending = pending.filter(organization_domain__organization_id=organization_id)++ if dry_run:+ self.stdout.write(self.style.WARNING(f"Dry run: {pending.count()} row(s) would be filled"))+ self._report_unattributable(organization_id)+ return++ config_of_domain = Subquery(+ OrganizationDomain.objects.filter(pk=OuterRef("organization_domain_id")).values(+ "identity_provider_config_id"+ )[:1]+ )++ started_at = time.monotonic()+ updated = 0+ batches = 0++ while True:+ # Walking the primary key keeps the scan forward-only, so the cost doesn't grow with the+ # rows already swept, and a row the update can't fill (its domain lost the config link+ # mid-sweep) can't be picked up again into an endless loop.+ batch_query = pending.order_by("id")+ if last_id is not None:+ batch_query = batch_query.filter(id__gt=last_id)++ batch = list(batch_query.values_list("id", flat=True)[:batch_size])+ if not batch:+ break++ last_id = batch[-1]+ updated += SCIMRequestLog.objects.filter(id__in=batch).update(identity_provider_config=config_of_domain)+ batches += 1++ if batches % PROGRESS_EVERY_BATCHES == 0:+ self.stdout.write(f"{updated} row(s) filled · resume after {last_id}")++ if sleep_seconds:+ time.sleep(sleep_seconds)++ duration = time.monotonic() - started_at+ logger.info("scim_request_log_config_backfilled", rows=updated, duration_seconds=round(duration, 2))+ self.stdout.write(self.style.SUCCESS(f"Filled {updated} row(s) in {duration:.1f}s"))+ self._report_unattributable(organization_id)++ def _report_unattributable(self, organization_id: str | None) -> None:+ # A domain unlinked from its config leaves logs with nothing to attribute them to. They stay+ # reachable through the domain, which is why the SCIM log endpoint still matches both keys.+ orphaned = SCIMRequestLog.objects.filter(+ identity_provider_config__isnull=True,+ organization_domain__identity_provider_config__isnull=True,+ )+ if organization_id:+ orphaned = orphaned.filter(organization_domain__organization_id=organization_id)++ count = orphaned.count()+ if count:+ self.stdout.write(+ self.style.WARNING(f"{count} row(s) left on their domain key: that domain has no linked IdP config")+ )diff --git a/ee/management/commands/test/test_backfill_scim_request_log_config.py b/ee/management/commands/test/test_backfill_scim_request_log_config.pynew file mode 100644index 000000000000..96c58b57c1a6--- /dev/null+++ b/ee/management/commands/test/test_backfill_scim_request_log_config.py@@ -0,0 +1,111 @@+from io import StringIO++from posthog.test.base import BaseTest++from django.core.management import call_command++from posthog.models import Organization+from posthog.models.identity_provider_config import IdentityProviderConfig+from posthog.models.organization_domain import OrganizationDomain++from ee.models.scim_request_log import SCIMRequestLog+++class TestBackfillSCIMRequestLogConfig(BaseTest):+ def setUp(self):+ super().setUp()+ self.config = IdentityProviderConfig.objects.create(organization=self.organization, scim_enabled=True)+ self.domain = OrganizationDomain.objects.create(+ organization=self.organization,+ domain="example.com",+ verified_at="2024-01-01T00:00:00Z",+ identity_provider_config=self.config,+ )+ self.unlinked_domain = OrganizationDomain.objects.create(+ organization=self.organization,+ domain="unlinked.example.com",+ verified_at="2024-01-01T00:00:00Z",+ )++ def _create_log(self, domain: OrganizationDomain, **kwargs) -> SCIMRequestLog:+ return SCIMRequestLog.objects.create(+ organization_domain=domain,+ request_method="GET",+ request_path="/scim/v2/slug/Users",+ request_headers={},+ response_status=200,+ identity_provider="okta",+ **kwargs,+ )++ def _run(self, **options) -> str:+ out = StringIO()+ call_command("backfill_scim_request_log_config", stdout=out, **options)+ return out.getvalue()++ def test_fills_the_config_from_the_logged_domain(self):+ log = self._create_log(self.domain)++ self._run(batch_size=1)++ log.refresh_from_db()+ assert log.identity_provider_config_id == self.config.id++ def test_leaves_a_log_whose_domain_has_no_config_on_its_domain_key(self):+ log = self._create_log(self.unlinked_domain)++ output = self._run()++ log.refresh_from_db()+ assert log.identity_provider_config_id is None+ assert "1 row(s) left on their domain key" in output++ def test_dry_run_reports_without_writing(self):+ log = self._create_log(self.domain)++ output = self._run(dry_run=True)++ log.refresh_from_db()+ assert log.identity_provider_config_id is None+ assert "1 row(s) would be filled" in output++ def test_rerun_is_a_no_op_and_does_not_move_rows_between_tenants(self):+ other_config = IdentityProviderConfig.objects.create(organization=self.organization, scim_enabled=True)+ already_attributed = self._create_log(self.domain, identity_provider_config=other_config)+ pending = self._create_log(self.domain)++ self._run()+ self._run()++ already_attributed.refresh_from_db()+ pending.refresh_from_db()+ assert already_attributed.identity_provider_config_id == other_config.id+ assert pending.identity_provider_config_id == self.config.id++ def test_organization_scope_limits_the_sweep(self):+ other_organization = Organization.objects.create(name="Other Org")+ other_config = IdentityProviderConfig.objects.create(organization=other_organization, scim_enabled=True)+ other_domain = OrganizationDomain.objects.create(+ organization=other_organization,+ domain="other.example.com",+ verified_at="2024-01-01T00:00:00Z",+ identity_provider_config=other_config,+ )+ mine = self._create_log(self.domain)+ theirs = self._create_log(other_domain)++ self._run(organization_id=str(self.organization.id))++ mine.refresh_from_db()+ theirs.refresh_from_db()+ assert mine.identity_provider_config_id == self.config.id+ assert theirs.identity_provider_config_id is None++ def test_start_after_resumes_past_earlier_rows(self):+ logs = sorted([self._create_log(self.domain) for _ in range(3)], key=lambda log: log.id)++ self._run(start_after=str(logs[0].id))++ for log in logs:+ log.refresh_from_db()+ assert [log.identity_provider_config_id for log in logs] == [None, self.config.id, self.config.id]diff --git a/ee/migrations/0055_scim_records_identity_provider_config.py b/ee/migrations/0055_scim_records_identity_provider_config.pynew file mode 100644index 000000000000..d2877d8597f4--- /dev/null+++ b/ee/migrations/0055_scim_records_identity_provider_config.py@@ -0,0 +1,38 @@+import django.db.models.deletion+from django.db import migrations, models+++class Migration(migrations.Migration):+ dependencies = [+ ("ee", "0054_backfill_llm_playground_access_control"),+ ("posthog", "1226_identityproviderconfig_and_more"),+ ]++ operations = [+ # `db_index=False` keeps the column add from building a blocking index; the composite+ # indexes that serve config-scoped reads are built concurrently in 0057.+ migrations.AddField(+ model_name="scimprovisioneduser",+ name="identity_provider_config",+ field=models.ForeignKey(+ blank=True,+ db_index=False,+ null=True,+ on_delete=django.db.models.deletion.CASCADE,+ related_name="scim_provisioned_users",+ to="posthog.identityproviderconfig",+ ),+ ),+ migrations.AddField(+ model_name="scimrequestlog",+ name="identity_provider_config",+ field=models.ForeignKey(+ blank=True,+ db_index=False,+ null=True,+ on_delete=django.db.models.deletion.SET_NULL,+ related_name="scim_request_logs",+ to="posthog.identityproviderconfig",+ ),+ ),+ ]diff --git a/ee/migrations/0056_scim_records_organization_domain_nullable.py b/ee/migrations/0056_scim_records_organization_domain_nullable.pynew file mode 100644index 000000000000..90c238fe745b--- /dev/null+++ b/ee/migrations/0056_scim_records_organization_domain_nullable.py@@ -0,0 +1,49 @@+import django.db.models.deletion+from django.db import migrations, models++# SCIM records are keyed by IdP config now, so nothing fills `organization_domain` on new rows.+# Django's own AlterField for a NOT NULL drop rebuilds the column's foreign key, which revalidates+# every existing row while holding a lock — on ee_scimrequestlog that is the whole request history.+# The catalog flip alone is what's needed, so run it as SQL and leave AlterField to model state.+# Dropping NOT NULL on its own is a catalog update: no table scan, no row rewrite.+DROP_NOT_NULL = [+ migrations.RunSQL(+ sql=f'ALTER TABLE "{table}" ALTER COLUMN "organization_domain_id" DROP NOT NULL;',+ reverse_sql=f'ALTER TABLE "{table}" ALTER COLUMN "organization_domain_id" SET NOT NULL;',+ )+ for table in ("ee_scimprovisioneduser", "ee_scimrequestlog")+]+++class Migration(migrations.Migration):+ dependencies = [("ee", "0055_scim_records_identity_provider_config")]++ operations = [+ migrations.SeparateDatabaseAndState(+ state_operations=[+ migrations.AlterField(+ model_name="scimprovisioneduser",+ name="organization_domain",+ field=models.ForeignKey(+ blank=True,+ null=True,+ on_delete=django.db.models.deletion.CASCADE,+ related_name="scim_provisioned_users",+ to="posthog.organizationdomain",+ ),+ ),+ migrations.AlterField(+ model_name="scimrequestlog",+ name="organization_domain",+ field=models.ForeignKey(+ blank=True,+ null=True,+ on_delete=django.db.models.deletion.CASCADE,+ related_name="scim_request_logs",+ to="posthog.organizationdomain",+ ),+ ),+ ],+ database_operations=DROP_NOT_NULL,+ ),+ ]diff --git a/ee/migrations/0057_scim_records_identity_provider_config_indexes.py b/ee/migrations/0057_scim_records_identity_provider_config_indexes.pynew file mode 100644index 000000000000..8a9d4ea745f9--- /dev/null+++ b/ee/migrations/0057_scim_records_identity_provider_config_indexes.py@@ -0,0 +1,36 @@+from django.db import migrations, models++from posthog.migration_helpers import CreateIndexConcurrently, SafeAddIndexConcurrently+++class Migration(migrations.Migration):+ # CONCURRENTLY takes SHARE UPDATE EXCLUSIVE, so none of these block a reader or a writer, and+ # PostgreSQL cannot run them inside a transaction.+ atomic = False++ dependencies = [("ee", "0056_scim_records_organization_domain_nullable")]++ operations = [+ SafeAddIndexConcurrently(+ model_name="scimprovisioneduser",+ index=models.Index(+ fields=["identity_provider_config", "username"],+ name="ee_scimprov_identit_3a28d7_idx",+ ),+ ),+ SafeAddIndexConcurrently(+ model_name="scimrequestlog",+ index=models.Index(+ fields=["identity_provider_config", "-created_at"],+ name="ee_scimrequ_identit_975d6d_idx",+ ),+ ),+ # The index behind the unique constraint 0059 attaches. Building it here rather than under+ # ADD CONSTRAINT is what keeps that constraint off the table's readers and writers.+ CreateIndexConcurrently(+ index_name="unique_user_identity_provider_config",+ table_name="ee_scimprovisioneduser",+ columns="(user_id, identity_provider_config_id)",+ unique=True,+ ),+ ]diff --git a/ee/migrations/0058_backfill_scim_provisioned_user_config.py b/ee/migrations/0058_backfill_scim_provisioned_user_config.pynew file mode 100644index 000000000000..b851b04d0c4b--- /dev/null+++ b/ee/migrations/0058_backfill_scim_provisioned_user_config.py@@ -0,0 +1,92 @@+from typing import Any++from django.db import migrations+from django.db.models import Count, OuterRef, Subquery++import structlog++logger = structlog.get_logger(__name__)++CHUNK_SIZE = 1000+++def _ids_to_leave_on_their_domain_key(pending: Any) -> list[Any]:+ # One user provisioned through two domains of one config holds two records for what is now a+ # single tenant. Keep the oldest on the config and leave the rest on their domain key, so the+ # unique constraint added in 0060 holds without this dropping anyone's record.+ duplicate_groups = (+ pending.values("user_id", "organization_domain__identity_provider_config")+ .annotate(rows=Count("id"))+ .filter(rows__gt=1)+ )++ skipped: list[Any] = []+ for group in duplicate_groups:+ group_ids = list(+ pending.filter(+ user_id=group["user_id"],+ organization_domain__identity_provider_config=group["organization_domain__identity_provider_config"],+ )+ .order_by("created_at", "id")+ .values_list("id", flat=True)+ )+ for row_id in group_ids[1:]:+ logger.warning(+ "scim_provisioned_user_duplicate_for_identity_provider_config",+ scim_provisioned_user_id=str(row_id),+ identity_provider_config_id=str(group["organization_domain__identity_provider_config"]),+ )+ skipped.extend(group_ids[1:])+ return skipped+++def backfill_scim_provisioned_user_config(apps: Any, schema_editor: Any) -> None:+ # Provisioning records are keyed by the SCIM tenant, which is now the IdP config rather than the+ # domain the endpoint used to be addressed by. Rows written before that move have to carry the+ # config too, otherwise SCIM sees an already-provisioned user as new and provisions them twice.+ #+ # This table holds one row per provisioned user per tenant, so it stays in the deploy: the+ # unique constraint two migrations later depends on it having run. Updates are set-based and+ # take row locks only — no reader or writer of the table waits on this.+ SCIMProvisionedUser = apps.get_model("ee", "SCIMProvisionedUser")+ OrganizationDomain = apps.get_model("posthog", "OrganizationDomain")+ db_alias = schema_editor.connection.alias++ pending = SCIMProvisionedUser.objects.using(db_alias).filter(+ identity_provider_config__isnull=True,+ organization_domain__identity_provider_config__isnull=False,+ )+ claimable = pending.exclude(id__in=_ids_to_leave_on_their_domain_key(pending))++ config_of_domain = Subquery(+ OrganizationDomain.objects.using(db_alias)+ .filter(pk=OuterRef("organization_domain_id"))+ .values("identity_provider_config_id")[:1]+ )++ # Walking the primary key keeps the scan forward-only and each statement small.+ last_id = None+ while True:+ batch_query = claimable.order_by("id")+ if last_id is not None:+ batch_query = batch_query.filter(id__gt=last_id)++ batch = list(batch_query.values_list("id", flat=True)[:CHUNK_SIZE])+ if not batch:+ break++ last_id = batch[-1]+ SCIMProvisionedUser.objects.using(db_alias).filter(id__in=batch).update(+ identity_provider_config=config_of_domain+ )+++class Migration(migrations.Migration):+ dependencies = [("ee", "0057_scim_records_identity_provider_config_indexes")]++ operations = [+ migrations.RunPython(+ backfill_scim_provisioned_user_config,+ reverse_code=migrations.RunPython.noop,+ ),+ ]diff --git a/ee/migrations/0059_scimprovisioneduser_unique_config.py b/ee/migrations/0059_scimprovisioneduser_unique_config.pynew file mode 100644index 000000000000..d1ab45db99ac--- /dev/null+++ b/ee/migrations/0059_scimprovisioneduser_unique_config.py@@ -0,0 +1,45 @@+from django.db import migrations, models+++class Migration(migrations.Migration):+ dependencies = [("ee", "0058_backfill_scim_provisioned_user_config")]++ operations = [+ migrations.SeparateDatabaseAndState(+ state_operations=[+ migrations.AddConstraint(+ model_name="scimprovisioneduser",+ constraint=models.UniqueConstraint(+ fields=("user", "identity_provider_config"),+ name="unique_user_identity_provider_config",+ ),+ ),+ ],+ database_operations=[+ migrations.RunSQL(+ # Promotes the index 0057 built concurrently. Postgres only updates the catalog+ # here, so the ACCESS EXCLUSIVE lock is taken and released without any scan.+ # Guarded so a bin/migrate retry, or a database that already carries the+ # constraint, is a no-op rather than an error.+ sql="""+ DO $$+ BEGIN+ IF NOT EXISTS (+ SELECT 1 FROM pg_constraint+ WHERE conname = 'unique_user_identity_provider_config'+ AND conrelid = 'ee_scimprovisioneduser'::regclass+ ) THEN+ ALTER TABLE ee_scimprovisioneduser+ ADD CONSTRAINT unique_user_identity_provider_config+ UNIQUE USING INDEX unique_user_identity_provider_config;+ END IF;+ END $$;+ """,+ reverse_sql=(+ "ALTER TABLE ee_scimprovisioneduser "+ "DROP CONSTRAINT IF EXISTS unique_user_identity_provider_config;"+ ),+ ),+ ],+ ),+ ]diff --git a/ee/migrations/max_migration.txt b/ee/migrations/max_migration.txtindex b1b3900d4598..612f9b628861 100644--- a/ee/migrations/max_migration.txt+++ b/ee/migrations/max_migration.txt@@ -1 +1 @@-0054_backfill_llm_playground_access_control+0059_scimprovisioneduser_unique_configdiff --git a/ee/migrations/test/test_migration_0058.py b/ee/migrations/test/test_migration_0058.pynew file mode 100644index 000000000000..e68c05216f8a--- /dev/null+++ b/ee/migrations/test/test_migration_0058.py@@ -0,0 +1,70 @@+import importlib+from types import SimpleNamespace++from posthog.test.base import BaseTest++from django.apps import apps+from django.db import connection++from posthog.models.identity_provider_config import IdentityProviderConfig+from posthog.models.organization_domain import OrganizationDomain+from posthog.models.user import User++from ee.models.scim_provisioned_user import SCIMProvisionedUser++migration_module = importlib.import_module("ee.migrations.0058_backfill_scim_provisioned_user_config")+backfill_scim_provisioned_user_config = migration_module.backfill_scim_provisioned_user_config++SCHEMA_EDITOR = SimpleNamespace(connection=connection)+++class TestBackfillSCIMProvisionedUserConfig(BaseTest):+ def setUp(self):+ super().setUp()+ self.config = IdentityProviderConfig.objects.create(organization=self.organization, scim_enabled=True)+ self.domain = OrganizationDomain.objects.create(+ organization=self.organization,+ domain="example.com",+ verified_at="2024-01-01T00:00:00Z",+ identity_provider_config=self.config,+ )+ self.provisioned_user = User.objects.create_user(+ email="[email protected]", password=None, first_name="Provisioned"+ )++ def _create_record(self, user: User, domain: OrganizationDomain) -> SCIMProvisionedUser:+ return SCIMProvisionedUser.objects.create(+ user=user,+ organization_domain=domain,+ identity_provider=SCIMProvisionedUser.IdentityProvider.OKTA,+ username=user.email,+ )++ def test_backfills_the_config_linked_to_the_record_domain(self):+ record = self._create_record(self.provisioned_user, self.domain)++ backfill_scim_provisioned_user_config(apps, SCHEMA_EDITOR)++ record.refresh_from_db()+ assert record.identity_provider_config_id == self.config.id++ def test_leaves_a_second_record_for_the_same_config_on_its_domain_key(self):+ # Two domains sharing a config used to serve SCIM separately, so one user can hold a record+ # per domain. Claiming both for the config would break the unique constraint added in 0059.+ second_domain = OrganizationDomain.objects.create(+ organization=self.organization,+ domain="partner.example.com",+ verified_at="2024-01-01T00:00:00Z",+ identity_provider_config=self.config,+ )+ first_record = self._create_record(self.provisioned_user, self.domain)+ second_record = self._create_record(self.provisioned_user, second_domain)++ backfill_scim_provisioned_user_config(apps, SCHEMA_EDITOR)++ first_record.refresh_from_db()+ second_record.refresh_from_db()+ assert [first_record.identity_provider_config_id, second_record.identity_provider_config_id] == [+ self.config.id,+ None,+ ]diff --git a/ee/models/scim_provisioned_user.py b/ee/models/scim_provisioned_user.pyindex ebc1a7ecb661..0b045c920ad9 100644--- a/ee/models/scim_provisioned_user.py+++ b/ee/models/scim_provisioned_user.py@@ -1,7 +1,76 @@-from django.db import models+from typing import TYPE_CHECKING, Any++from django.db import IntegrityError, models, transaction++import structlogfrom posthog.models.utils import UpdatedMetaFields, UUIDModel+if TYPE_CHECKING:+ from posthog.models.identity_provider_config import IdentityProviderConfig+ from posthog.models.user import User++logger = structlog.get_logger(__name__)+++class SCIMProvisionedUserManager(models.Manager["SCIMProvisionedUser"]):+ def for_config(self, config: "IdentityProviderConfig") -> models.QuerySet["SCIMProvisionedUser"]:+ """+ Every record belonging to a SCIM tenant: the ones keyed on the config, plus the ones still+ unclaimed on a domain it backs. A record another config already holds stays out of scope+ even when they share a domain — an organization can run several IdPs, and one must not read+ or deprovision another's users.+ """+ return self.filter(+ models.Q(identity_provider_config=config)+ | models.Q(+ identity_provider_config__isnull=True,+ organization_domain__identity_provider_config=config,+ )+ )++ def record_for(self, *, user: "User", config: "IdentityProviderConfig") -> "SCIMProvisionedUser | None":+ records = self.for_config(config).filter(user=user).order_by("id")+ return records.filter(identity_provider_config=config).first() or records.first()++ def upsert(+ self, *, user: "User", config: "IdentityProviderConfig", defaults: dict[str, Any]+ ) -> "SCIMProvisionedUser":+ """+ One record per (user, tenant). A record still keyed on a domain is claimed for the config+ rather than joined by a second one, so a user provisioned just before the config move isn't+ provisioned again after it.+ """+ self._claim_record_keyed_on_a_domain(user=user, config=config)+ # `update_or_create` locks the row it finds and retries its own read if a concurrent insert+ # beats it, so the create side of this needs no handling here.+ record, _ = self.update_or_create(user=user, identity_provider_config=config, defaults=defaults)+ return record++ def _claim_record_keyed_on_a_domain(self, *, user: "User", config: "IdentityProviderConfig") -> None:+ unclaimed = (+ self.for_config(config).filter(user=user, identity_provider_config__isnull=True).order_by("id").first()+ )+ if unclaimed is None:+ return++ try:+ # The `isnull` filter makes a claim of the same record by a concurrent request a no-op+ # instead of an overwrite, and the savepoint keeps a lost race from poisoning the+ # transaction the caller is midway through.+ with transaction.atomic():+ self.filter(pk=unclaimed.pk, identity_provider_config__isnull=True).update(+ identity_provider_config=config+ )+ except IntegrityError:+ # Someone else already holds (user, config) — their own record, or another domain-keyed+ # one they claimed first. Theirs wins, and `update_or_create` below finds it.+ logger.warning(+ "scim_provisioned_user_claim_lost",+ scim_provisioned_user_id=str(unclaimed.pk),+ identity_provider_config_id=str(config.pk),+ )+class SCIMProvisionedUser(UUIDModel, UpdatedMetaFields):class IdentityProvider(models.TextChoices):@@ -11,9 +80,28 @@ class SCIMProvisionedUser(UUIDModel, UpdatedMetaFields):ONELOGIN = "onelogin", "OneLogin"OTHER = "other", "Other"+ objects: SCIMProvisionedUserManager = SCIMProvisionedUserManager()+user = models.ForeignKey("posthog.User", on_delete=models.CASCADE, related_name="scim_provisions")+ # The SCIM tenant is the `IdentityProviderConfig` that owns the bearer token and the `scim_slug`+ # in the endpoint URL, so provisioning records hang off it.+ identity_provider_config = models.ForeignKey(+ "posthog.IdentityProviderConfig",+ on_delete=models.CASCADE,+ related_name="scim_provisioned_users",+ null=True,+ blank=True,+ db_index=False,+ )+ # Legacy tenant key, kept until the column is dropped. Don't write it: a SCIM request names a+ # config, and a config can back several domains, so there is no one domain to attribute a+ # record to. Migration ee.0058 copied the config onto the rows that have one.organization_domain = models.ForeignKey(- "posthog.OrganizationDomain", on_delete=models.CASCADE, related_name="scim_provisioned_users"+ "posthog.OrganizationDomain",+ on_delete=models.CASCADE,+ related_name="scim_provisioned_users",+ null=True,+ blank=True,)identity_provider = models.CharField(max_length=50, choices=IdentityProvider)@@ -27,8 +115,13 @@ class SCIMProvisionedUser(UUIDModel, UpdatedMetaFields):models.UniqueConstraint(fields=["user", "organization_domain"],name="unique_user_organization_domain",- )+ ),+ models.UniqueConstraint(+ fields=["user", "identity_provider_config"],+ name="unique_user_identity_provider_config",+ ),]indexes = [models.Index(fields=["organization_domain", "username"]),+ models.Index(fields=["identity_provider_config", "username"]),]diff --git a/ee/models/scim_request_log.py b/ee/models/scim_request_log.pyindex 094e43e3408f..e06c8b20c171 100644--- a/ee/models/scim_request_log.py+++ b/ee/models/scim_request_log.py@@ -6,10 +6,29 @@ SCIM_REQUEST_LOG_RETENTION_DAYS = 180class SCIMRequestLog(UUIDModel):+ # The `IdentityProviderConfig` the request authenticated against — the SCIM tenant. Deleting a+ # config must not erase the record of what its IdP did to org memberships, which is the artifact+ # an investigation after an IdP or admin-session compromise starts from, so the row outlives it+ # and ages out on the retention window instead. It drops out of the per-domain listing at that+ # point: with the config gone there is no domain left to list it under.+ identity_provider_config = models.ForeignKey(+ "posthog.IdentityProviderConfig",+ on_delete=models.SET_NULL,+ related_name="scim_request_logs",+ null=True,+ blank=True,+ db_index=False,+ )+ # Legacy tenant key. Don't write it: a SCIM request names a config, and a config can back+ # several domains. Rows logged before the move are attributed to their config by the+ # `backfill_scim_request_log_config` command, which runs outside the deploy because this table+ # is large; until it has, the per-domain log listing reads this column so no history is hidden.organization_domain = models.ForeignKey("posthog.OrganizationDomain",on_delete=models.CASCADE,related_name="scim_request_logs",+ null=True,+ blank=True,)request_method = models.CharField(max_length=10)@@ -27,5 +46,6 @@ class SCIMRequestLog(UUIDModel):class Meta:indexes = [models.Index(fields=["organization_domain", "-created_at"]),+ models.Index(fields=["identity_provider_config", "-created_at"]),]ordering = ["-created_at", "-id"]diff --git a/ee/urls.py b/ee/urls.pyindex e095c787d379..1d72be477d32 100644--- a/ee/urls.py+++ b/ee/urls.py@@ -244,29 +244,29 @@ urlpatterns: list[Any] = [vercel_connect.VercelConnectLinkViewSet.as_view({"get": "session_info"}),),path("webhooks/vercel", csrf_exempt(vercel_webhooks.vercel_webhook), name="vercel_webhooks"),- path("scim/v2/<uuid:domain_id>/Users", csrf_exempt(scim_views.SCIMUsersView.as_view()), name="scim_users"),+ path("scim/v2/<str:scim_slug>/Users", csrf_exempt(scim_views.SCIMUsersView.as_view()), name="scim_users"),path(- "scim/v2/<uuid:domain_id>/Users/<int:user_id>",+ "scim/v2/<str:scim_slug>/Users/<int:user_id>",csrf_exempt(scim_views.SCIMUserDetailView.as_view()),name="scim_user_detail",),- path("scim/v2/<uuid:domain_id>/Groups", csrf_exempt(scim_views.SCIMGroupsView.as_view()), name="scim_groups"),+ path("scim/v2/<str:scim_slug>/Groups", csrf_exempt(scim_views.SCIMGroupsView.as_view()), name="scim_groups"),path(- "scim/v2/<uuid:domain_id>/Groups/<uuid:group_id>",+ "scim/v2/<str:scim_slug>/Groups/<uuid:group_id>",csrf_exempt(scim_views.SCIMGroupDetailView.as_view()),name="scim_group_detail",),path(- "scim/v2/<uuid:domain_id>/ServiceProviderConfig",+ "scim/v2/<str:scim_slug>/ServiceProviderConfig",csrf_exempt(scim_views.SCIMServiceProviderConfigView.as_view()),name="scim_service_provider_config",),path(- "scim/v2/<uuid:domain_id>/ResourceTypes",+ "scim/v2/<str:scim_slug>/ResourceTypes",csrf_exempt(scim_views.SCIMResourceTypesView.as_view()),name="scim_resource_types",),- path("scim/v2/<uuid:domain_id>/Schemas", csrf_exempt(scim_views.SCIMSchemasView.as_view()), name="scim_schemas"),+ path("scim/v2/<str:scim_slug>/Schemas", csrf_exempt(scim_views.SCIMSchemasView.as_view()), name="scim_schemas"),# Stripe Projects provisioning (APP 0.1d)path("api/partners/stripe/", include("ee.partners.stripe.api.provisioning.urls")),# Agentic provisioning (partner account/resource provisioning + deep-link login)diff --git a/posthog/admin/inlines/scim_provisioned_user_inline.py b/posthog/admin/inlines/scim_provisioned_user_inline.pyindex 884c3e806bca..7bdd03010da4 100644--- a/posthog/admin/inlines/scim_provisioned_user_inline.py+++ b/posthog/admin/inlines/scim_provisioned_user_inline.py@@ -11,8 +11,24 @@ class SCIMProvisionedUserInline(admin.TabularInline):model = SCIMProvisionedUserextra = 0- fields = ("organization_domain", "identity_provider", "username", "active", "created_at")- readonly_fields = ("organization_domain", "identity_provider", "username", "active", "created_at")+ # Both FKs stay in readonly_fields so the change page renders them as plain text instead of a+ # <select> that loads every config and domain per row.+ fields = (+ "identity_provider_config",+ "organization_domain",+ "identity_provider",+ "username",+ "active",+ "created_at",+ )+ readonly_fields = (+ "identity_provider_config",+ "organization_domain",+ "identity_provider",+ "username",+ "active",+ "created_at",+ )can_delete = Trueshow_change_link = Falseverbose_name = "SCIM provisioned user"diff --git a/posthog/api/identity_provider_config.py b/posthog/api/identity_provider_config.pyindex 6659101129e2..fcfbd6552f1e 100644--- a/posthog/api/identity_provider_config.py+++ b/posthog/api/identity_provider_config.py@@ -215,6 +215,19 @@ class IdentityProviderConfigViewSet(TeamAndOrgViewSetMixin, ModelViewSet):_capture_idp_config_event(request, self.get_object(), "updated", {"fields": sorted(request.data.keys())})return res+ def destroy(self, request: request.Request, *args: Any, **kwargs: Any) -> response.Response:+ config = cast(IdentityProviderConfig, self.get_object())+ # Deleting a config takes every SCIM provisioning record with it, and with them the IdP's+ # immutable-id mapping for those users — the next sync provisions everyone again. Make that+ # reachable only after the domain is explicitly unlinked, so it can't ride along on a+ # misdirected request against a live configuration.+ if config.domains.exists():+ raise exceptions.ValidationError(+ "This configuration is linked to a domain. Unlink it from the domain before deleting it.",+ code="linked_to_domain",+ )+ return super().destroy(request, *args, **kwargs)+@extend_schema(request=None, responses=SCIMTokenResponseSerializer)@action(methods=["POST"], detail=True, url_path="scim/token")def scim_token(self, request: Request, **kwargs: Any) -> response.Response:diff --git a/posthog/api/organization_domain.py b/posthog/api/organization_domain.pyindex c2e4ad33102c..36cf666b504b 100644--- a/posthog/api/organization_domain.py+++ b/posthog/api/organization_domain.py@@ -143,9 +143,10 @@ class OrganizationDomainSerializer(serializers.ModelSerializer):return super().update(instance, validated_data)def get_scim_base_url(self, obj: OrganizationDomain) -> str | None:- if not obj.has_scim:+ config = obj.identity_provider_config+ if config is None or not config.has_scim or not config.scim_slug:return None- return get_scim_base_url(obj, self.context.get("request"))+ return get_scim_base_url(config)class SCIMRequestLogSerializer(serializers.ModelSerializer):@@ -208,7 +209,8 @@ class OrganizationDomainViewset(TeamAndOrgViewSetMixin, ModelViewSet):scope_object = "organization"serializer_class = OrganizationDomainSerializerpermission_classes = [OrganizationAdminWritePermissions, TimeSensitiveActionPermission]- queryset = OrganizationDomain.objects.order_by("domain").all()+ # Every serialized domain reads its linked config (SAML/SCIM/ID-JAG state, SCIM base URL).+ queryset = OrganizationDomain.objects.select_related("identity_provider_config").order_by("domain").all()@action(methods=["POST"], detail=True)def verify(self, request: request.Request, **kw) -> response.Response:@@ -301,7 +303,14 @@ class OrganizationDomainViewset(TeamAndOrgViewSetMixin, ModelViewSet):raise exceptions.PermissionDenied("Only organization admins can view SCIM logs.")domain: OrganizationDomain = self.get_object()- queryset = SCIMRequestLog.objects.filter(organization_domain=domain)+ # SCIM authenticates against the linked IdP config, so its requests are logged against the+ # config. Match the domain too: rows logged before the move carry only that until the+ # `backfill_scim_request_log_config` command reaches them, and a domain that was later+ # unlinked from its config keeps nothing else to find its history by.+ scope = Q(organization_domain=domain)+ if domain.identity_provider_config_id is not None:+ scope |= Q(identity_provider_config_id=domain.identity_provider_config_id)+ queryset = SCIMRequestLog.objects.filter(scope)queryset = SCIMRequestLogFilter(request.query_params, queryset=queryset).qspaginator = SCIMRequestLogPagination()diff --git a/posthog/api/signup.py b/posthog/api/signup.pyindex ad5d4140fc10..3b787dbbe406 100644--- a/posthog/api/signup.py+++ b/posthog/api/signup.py@@ -35,6 +35,7 @@ from posthog.exceptions_capture import capture_exceptionfrom posthog.helpers.email_utils import EmailValidationHelper, reject_plus_addressed_email, validate_display_namefrom posthog.helpers.verified_domain_enforcement import resolve_login_organizationfrom posthog.models import InviteExpiredException, Organization, OrganizationDomain, OrganizationInvite, Team, User+from posthog.models.identity_provider_config import IdentityProviderConfigfrom posthog.models.organization_invite import INVITE_DAYS_VALIDITYfrom posthog.models.webauthn_credential import WebauthnCredentialfrom posthog.permissions import CanCreateOrg@@ -813,13 +814,17 @@ class CompanyNameForm(forms.Form):emailOptIn = forms.BooleanField(required=False)-def lookup_invite_for_saml(email: str, organization_domain_id: str) -> Optional[OrganizationInvite]:- # nosemgrep: idor-lookup-without-org (ID from SAML response)- organization_domain = OrganizationDomain.objects.get(id=organization_domain_id)- if not organization_domain:+def lookup_invite_for_saml(email: str, saml_relay_state: str) -> Optional[OrganizationInvite]:+ # The assertion round-trips the IdP config's `saml_relay_state`, which the SAML backend has+ # already resolved to a config to validate the response. Resolve the organization the same way:+ # the identifier holds a domain id on configs created before it moved onto the config, and that+ # domain may since have been deleted out from under a config its siblings still back.+ # nosemgrep: idor-lookup-without-org (identifier from an already-verified SAML response)+ config = IdentityProviderConfig.objects.filter(saml_relay_state=saml_relay_state).first()+ if config is None:return Nonereturn (- OrganizationInvite.objects.filter(target_email=email, organization=organization_domain.organization)+ OrganizationInvite.objects.filter(target_email=email, organization_id=config.organization_id).order_by("-created_at").first())@@ -975,10 +980,10 @@ def social_create_user(or details.get("username"))- # Handle SAML invites (organization_domain_id is the relay_state)- organization_domain_id = kwargs.get("response", {}).get("idp_name")- if not invite_id and organization_domain_id:- invite = lookup_invite_for_saml(email, organization_domain_id)+ # Handle SAML invites (idp_name is the IdP config's relay state)+ saml_relay_state = kwargs.get("response", {}).get("idp_name")+ if not invite_id and saml_relay_state:+ invite = lookup_invite_for_saml(email, saml_relay_state)invite_id = invite.id if invite else None# Domain enforcement: refuse blocked members — blocked admins still get a gated session.diff --git a/posthog/api/test/test_identity_provider_config.py b/posthog/api/test/test_identity_provider_config.pyindex 22d6fad187a3..240dc22f580d 100644--- a/posthog/api/test/test_identity_provider_config.py+++ b/posthog/api/test/test_identity_provider_config.py@@ -1,9 +1,11 @@from posthog.test.base import APIBaseTest+from django.utils import timezone+from rest_framework import statusfrom posthog.constants import AvailableFeature-from posthog.models import IdentityProviderConfig, Organization, OrganizationMembership+from posthog.models import IdentityProviderConfig, Organization, OrganizationDomain, OrganizationMembershipclass TestIdentityProviderConfigAPI(APIBaseTest):@@ -163,3 +165,40 @@ class TestIdentityProviderConfigAPI(APIBaseTest):{"id_jag_issuer_url": "http://169.254.169.254/latest/meta-data"},)self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)++ # Deletion++ def test_cannot_delete_a_config_a_domain_still_uses(self):+ # Deleting a config drops every SCIM provisioning record hanging off it, and with them the+ # IdP's immutable-id mapping. That has to take an explicit unlink first.+ self._make_admin()+ config = IdentityProviderConfig.objects.create(organization=self.organization)+ OrganizationDomain.objects.create(+ organization=self.organization,+ domain="linked.example.com",+ verified_at=timezone.now(),+ identity_provider_config=config,+ )++ response = self.client.delete(f"/api/organizations/@current/identity_provider_configs/{config.id}/")++ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)+ self.assertEqual(response.json()["code"], "linked_to_domain")+ self.assertTrue(IdentityProviderConfig.objects.filter(id=config.id).exists())++ def test_can_delete_a_config_once_no_domain_uses_it(self):+ self._make_admin()+ config = IdentityProviderConfig.objects.create(organization=self.organization)+ domain = OrganizationDomain.objects.create(+ organization=self.organization,+ domain="unlinked.example.com",+ verified_at=timezone.now(),+ identity_provider_config=config,+ )+ domain.identity_provider_config = None+ domain.save()++ response = self.client.delete(f"/api/organizations/@current/identity_provider_configs/{config.id}/")++ self.assertEqual(response.status_code, status.HTTP_204_NO_CONTENT)+ self.assertFalse(IdentityProviderConfig.objects.filter(id=config.id).exists())diff --git a/posthog/api/test/test_signup.py b/posthog/api/test/test_signup.pyindex 83cf7ed5bc7f..017060a7812b 100644--- a/posthog/api/test/test_signup.py+++ b/posthog/api/test/test_signup.py@@ -19,7 +19,7 @@ from django.utils import timezonefrom parameterized import parameterizedfrom rest_framework import status-from posthog.api.signup import _save_session_with_recovery, process_social_invite_signup+from posthog.api.signup import _save_session_with_recovery, lookup_invite_for_saml, process_social_invite_signupfrom posthog.cloud_utils import TEST_clear_instance_license_cachefrom posthog.constants import AvailableFeaturefrom posthog.models import Organization, Team, User@@ -3365,3 +3365,49 @@ class TestSignupResendInvite(APIBaseTest):# Bob still has a fresh bucketbob_ok = self.client.post("/api/signup/resend-invite", {"email": "[email protected]"})self.assertEqual(bob_ok.status_code, status.HTTP_200_OK)+++class TestSAMLInviteLookup(APIBaseTest):+ def _saml_identifier_for(self, *domains: str) -> str:+ config = IdentityProviderConfig.objects.create(+ organization=self.organization, saml_entity_id="e", saml_acs_url="a", saml_x509_cert="c"+ )+ for domain in domains:+ OrganizationDomain.objects.create(+ organization=self.organization,+ domain=domain,+ verified_at=timezone.now(),+ identity_provider_config=config,+ )+ config.refresh_from_db()+ assert config.saml_relay_state is not None+ return config.saml_relay_state++ def test_finds_the_invite_for_the_config_that_signed_the_assertion(self):+ identifier = self._saml_identifier_for("saml-invite.example.com")+ invite = OrganizationInvite.objects.create(+ organization=self.organization, target_email="[email protected]"+ )++ found = lookup_invite_for_saml("[email protected]", identifier)++ assert found is not None+ assert found.id == invite.id++ def test_finds_it_when_the_identifier_no_longer_matches_a_domain(self):+ # The identifier holds a domain id on configs created before it moved onto the config, and+ # that domain can be deleted while sibling domains keep the config in service. Resolving the+ # organization through the domain raises DoesNotExist here, which 500s the SSO signup.+ identifier = self._saml_identifier_for("first.example.com", "second.example.com")+ OrganizationDomain.objects.get(domain="first.example.com").delete()+ invite = OrganizationInvite.objects.create(+ organization=self.organization, target_email="[email protected]"+ )++ found = lookup_invite_for_saml("[email protected]", identifier)++ assert found is not None+ assert found.id == invite.id++ def test_unknown_identifier_returns_nothing(self):+ assert lookup_invite_for_saml("[email protected]", "not-an-identifier") is Nonediff --git a/posthog/migrations/1299_alter_identityproviderconfig_saml_relay_state.py b/posthog/migrations/1299_alter_identityproviderconfig_saml_relay_state.pynew file mode 100644index 000000000000..82b9953081f4--- /dev/null+++ b/posthog/migrations/1299_alter_identityproviderconfig_saml_relay_state.py@@ -0,0 +1,38 @@+from django.db import migrations++from posthog.migration_helpers import CreateIndexConcurrently++TABLE = "posthog_identityproviderconfig"+# Django's own names for the indexes behind `unique=True` on a varchar field, so the schema matches+# what it would have built and no later migration sees drift.+UNIQUE_INDEX = "posthog_identityproviderconfig_saml_relay_state_a35fb61b_uniq"+LIKE_INDEX = "posthog_identityproviderconfig_saml_relay_state_a35fb61b_like"+++class Migration(migrations.Migration):+ # Named for the AlterField it started life as; that state change now lands in 1300, and this+ # builds the indexes behind it. Renaming the file would strand every database that has already+ # applied it, so the name stays.+ # `saml_relay_state` routes SAML logins, so this table is read on the auth path. Django's+ # AlterField would build both indexes under ACCESS EXCLUSIVE, and every read arriving behind it+ # would wait; CONCURRENTLY takes SHARE UPDATE EXCLUSIVE, which blocks neither. 1300 then+ # promotes the unique index to the constraint in a single catalog update.+ atomic = False++ dependencies = [+ ("posthog", "1298_user_stripped_alias_index"),+ ]++ operations = [+ CreateIndexConcurrently(+ index_name=UNIQUE_INDEX,+ table_name=TABLE,+ columns="(saml_relay_state)",+ unique=True,+ ),+ CreateIndexConcurrently(+ index_name=LIKE_INDEX,+ table_name=TABLE,+ columns="(saml_relay_state varchar_pattern_ops)",+ ),+ ]diff --git a/posthog/migrations/1300_identityproviderconfig_saml_relay_state_unique.py b/posthog/migrations/1300_identityproviderconfig_saml_relay_state_unique.pynew file mode 100644index 000000000000..d9c7bc37ef7e--- /dev/null+++ b/posthog/migrations/1300_identityproviderconfig_saml_relay_state_unique.py@@ -0,0 +1,41 @@+from django.db import migrations, models+++class Migration(migrations.Migration):+ dependencies = [+ ("posthog", "1299_alter_identityproviderconfig_saml_relay_state"),+ ]++ operations = [+ migrations.SeparateDatabaseAndState(+ state_operations=[+ migrations.AlterField(+ model_name="identityproviderconfig",+ name="saml_relay_state",+ field=models.CharField(blank=True, max_length=36, null=True, unique=True),+ ),+ ],+ database_operations=[+ migrations.RunSQL(+ # Promotes the index 1293 built concurrently. Postgres only updates the+ # catalog here, so the ACCESS EXCLUSIVE lock is taken and released without any+ # scan. Guarded so a bin/migrate retry, or a database that already carries the+ # constraint, is a no-op rather than an error.+ sql="""+ DO $$+ BEGIN+ IF NOT EXISTS (+ SELECT 1 FROM pg_constraint+ WHERE conname = 'posthog_identityproviderconfig_saml_relay_state_a35fb61b_uniq' AND conrelid = 'posthog_identityproviderconfig'::regclass+ ) THEN+ ALTER TABLE posthog_identityproviderconfig+ ADD CONSTRAINT posthog_identityproviderconfig_saml_relay_state_a35fb61b_uniq+ UNIQUE USING INDEX posthog_identityproviderconfig_saml_relay_state_a35fb61b_uniq;+ END IF;+ END $$;+ """,+ reverse_sql="ALTER TABLE posthog_identityproviderconfig DROP CONSTRAINT IF EXISTS posthog_identityproviderconfig_saml_relay_state_a35fb61b_uniq;",+ ),+ ],+ ),+ ]diff --git a/posthog/migrations/max_migration.txt b/posthog/migrations/max_migration.txtindex cfed6ad50b9e..a8dfbcdf3c29 100644--- a/posthog/migrations/max_migration.txt+++ b/posthog/migrations/max_migration.txt@@ -1 +1 @@-1298_user_stripped_alias_index+1300_identityproviderconfig_saml_relay_state_uniquediff --git a/posthog/models/activity_logging/activity_log.py b/posthog/models/activity_logging/activity_log.pyindex 736df80099d1..8cb3107f5d4f 100644--- a/posthog/models/activity_logging/activity_log.py+++ b/posthog/models/activity_logging/activity_log.py@@ -538,13 +538,18 @@ field_exclusions: dict[AuditableScope, list[str]] = {"OrganizationDomain": ["organization","scim_provisioned_users",+ "scim_request_logs",# Internal link to the IdP config mirror; the mirrored fields themselves are already logged"identity_provider_config",],"IdentityProviderConfig": ["organization",- # Reverse relation from `OrganizationDomain.identity_provider_config`; not a plain field diff.+ # Reverse relations, not plain field diffs — and diffing them reads every related row, which+ # for SCIM request logs is the tenant's whole request history."domains",+ "linked_identity_provider_configs",+ "scim_provisioned_users",+ "scim_request_logs",],"Subscription": [# Scheduler-derived field; keep it out of user-facing change diffs even when anotherdiff --git a/posthog/models/identity_provider_config.py b/posthog/models/identity_provider_config.pyindex 0d16e00399a6..b60ebf8793c2 100644--- a/posthog/models/identity_provider_config.py+++ b/posthog/models/identity_provider_config.py@@ -1,5 +1,8 @@+from collections.abc import Collection+from typing import Any+from django.contrib.postgres.fields import ArrayField-from django.db import models+from django.db import models, transactionimport structlog@@ -48,12 +51,15 @@ class IdentityProviderConfig(ModelActivityMixin, UUIDModel):updated_at = models.DateTimeField(auto_now=True)# ---- SAML attributes ----- # Field shapes intentionally mirror `OrganizationDomain` (including nullability) so- # values can be copied verbatim while domains remain the source of truth.+ # Field shapes mirror `OrganizationDomain` (including nullability) so existing values can be+ # migrated from the legacy domain columns without coercion.saml_entity_id = models.CharField(max_length=512, blank=True, null=True)saml_acs_url = models.CharField(max_length=512, blank=True, null=True)saml_x509_cert = models.TextField(blank=True, null=True)- saml_relay_state = models.CharField(max_length=36, blank=True, null=True)+ # Round-trips through the IdP as RelayState to route an assertion back to this config, and is+ # also the prefix of every `UserSocialAuth.uid` issued through it. Changing the value on a+ # config already in use orphans those identities, so it is assigned once and never edited.+ saml_relay_state = models.CharField(max_length=36, blank=True, null=True, unique=True)# ---- SCIM attributes ----scim_slug = models.CharField(max_length=36, blank=True, null=True, unique=True)@@ -84,12 +90,57 @@ class IdentityProviderConfig(ModelActivityMixin, UUIDModel):help_text="Allowed ID-JAG client IDs. Empty list allows any client_id.",)+ _IDENTIFIER_FIELDS = ("saml_relay_state", "scim_slug")+ _loaded_identifier_values: dict[str, str | None]+class Meta:verbose_name = "identity provider config"def __str__(self) -> str:return self.name or str(self.id)+ @classmethod+ def from_db(cls, db: str | None, field_names: Collection[str], values: Collection[Any]) -> "IdentityProviderConfig":+ instance = super().from_db(db, field_names, values)+ instance._loaded_identifier_values = {+ field: getattr(instance, field) for field in cls._IDENTIFIER_FIELDS if field in field_names+ }+ return instance++ def save(self, *args: Any, **kwargs: Any) -> None:+ if self._state.adding:+ super().save(*args, **kwargs)+ self._loaded_identifier_values = {field: getattr(self, field) for field in self._IDENTIFIER_FIELDS}+ return++ update_fields = kwargs.get("update_fields")+ fields_to_preserve = [+ field+ for field in self._IDENTIFIER_FIELDS+ if getattr(self, field) is None+ and (+ (update_fields is not None and field not in update_fields)+ or (update_fields is None and getattr(self, "_loaded_identifier_values", {}).get(field) is None)+ )+ ]++ if fields_to_preserve:+ with transaction.atomic():+ persisted = type(self).objects.select_for_update().values(*fields_to_preserve).get(pk=self.pk)+ for field in fields_to_preserve:+ setattr(self, field, persisted[field])+ super().save(*args, **kwargs)+ else:+ super().save(*args, **kwargs)++ saved_identifier_fields = set(fields_to_preserve)+ if update_fields is None:+ saved_identifier_fields.update(self._IDENTIFIER_FIELDS)+ else:+ saved_identifier_fields.update(field for field in self._IDENTIFIER_FIELDS if field in update_fields)+ for field in saved_identifier_fields:+ self._loaded_identifier_values[field] = getattr(self, field)+@propertydef has_saml(self) -> bool:"""diff --git a/posthog/models/organization_domain.py b/posthog/models/organization_domain.pyindex 5c59ca7288e1..6d48cf44a3b4 100644--- a/posthog/models/organization_domain.py+++ b/posthog/models/organization_domain.py@@ -334,9 +334,14 @@ class OrganizationDomain(ModelActivityMixin, UUIDTModel):identifier = str(self.pk)updates = {field: identifier for field in ("saml_relay_state", "scim_slug") if not getattr(config, field)}if updates:- IdentityProviderConfig.objects.filter(pk=config.pk).update(**updates)for field, value in updates.items():setattr(config, field, value)+ config.save(update_fields=list(updates))++ cached_config = self._state.fields_cache.get("identity_provider_config")+ if cached_config is not None:+ for field, value in updates.items():+ setattr(cached_config, field, value)@propertydef is_verified(self) -> bool:diff --git a/posthog/test/test_identity_provider_config.py b/posthog/test/test_identity_provider_config.pyindex 83c45fbdf781..7227381579c7 100644--- a/posthog/test/test_identity_provider_config.py+++ b/posthog/test/test_identity_provider_config.py@@ -60,6 +60,45 @@ class TestIdentityProviderConfig(BaseTest):assert config.saml_relay_state == str(domain.pk)assert config.scim_slug == str(domain.pk)+ def test_linking_config_preserves_identifiers_on_stale_partial_save(self):+ config = IdentityProviderConfig.objects.create(organization=self.organization)+ stale_config = IdentityProviderConfig.objects.get(pk=config.pk)+ domain = self._create_domain(identity_provider_config=config)++ stale_config.saml_entity_id = "entity-id"+ stale_config.save(update_fields=["saml_entity_id"])+ stale_config.refresh_from_db()++ assert stale_config.saml_relay_state == str(domain.pk)+ assert stale_config.scim_slug == str(domain.pk)++ def test_linking_config_preserves_identifiers_on_stale_full_save(self):+ config = IdentityProviderConfig.objects.create(organization=self.organization)+ stale_config = IdentityProviderConfig.objects.get(pk=config.pk)+ domain = self._create_domain(identity_provider_config=config)++ stale_config.scim_enabled = True+ stale_config.save()+ stale_config.refresh_from_db()++ assert stale_config.saml_relay_state == str(domain.pk)+ assert stale_config.scim_slug == str(domain.pk)++ def test_explicitly_clearing_identifiers_persists_null(self):+ config = IdentityProviderConfig.objects.create(+ organization=self.organization,+ saml_relay_state="relay-state",+ scim_slug="scim-slug",+ )++ config.saml_relay_state = None+ config.scim_slug = None+ config.save()+ config.refresh_from_db()++ assert config.saml_relay_state is None+ assert config.scim_slug is None+def test_saving_legacy_idp_columns_does_not_create_or_link_config(self):# The domain<->config dual-write mirror has been removed: writing the legacy underscore# columns must no longer auto-create or link an IdentityProviderConfig.