: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
feat(saml): support idp-initiated SAML authentication (#67209)
Reece Jones89cf411ddbdf
diff --git a/ee/api/authentication.py b/ee/api/authentication.pyindex c55e99678e3a..d60334b37fe4 100644--- a/ee/api/authentication.py+++ b/ee/api/authentication.py@@ -1,5 +1,6 @@import reimport json+import base64from typing import Any, Literal, TypedDict, Union, castfrom django.core.exceptions import ValidationError as DjangoValidationError@@ -10,6 +11,7 @@ import jwtimport structlogimport posthoganalyticsfrom jwt.algorithms import RSAAlgorithm+from onelogin.saml2.xml_utils import OneLogin_Saml2_XMLfrom rest_framework import authenticationfrom rest_framework.decorators import api_viewfrom rest_framework.exceptions import AuthenticationFailed, PermissionDenied@@ -26,6 +28,7 @@ from social_core.backends.saml import ()from social_core.exceptions import AuthFailed, AuthMissingParameterfrom social_django.models import UserSocialAuth+from social_django.strategy import DjangoStrategyfrom social_django.utils import load_backend, load_strategyfrom posthog.cloud_utils import get_cached_instance_license@@ -90,6 +93,9 @@ class MultitenantSAMLAuth(SAMLAuth):"""def auth_complete(self, *args, **kwargs):+ # attempt to recover from missing relay state in idp-initiated SAML+ self._recover_idp_initiated_relay_state()+try:result = super().auth_complete(*args, **kwargs)saml_logger.info("saml_auth_complete")@@ -99,6 +105,82 @@ class MultitenantSAMLAuth(SAMLAuth):saml_logger.warning("saml_auth_complete_failed", error=str(e))raise+ def _recover_idp_initiated_relay_state(self) -> None:+ """+ SP-initiated logins carry a RelayState holding the `OrganizationDomain` UUID, which+ is how we route an assertion to the right tenant. IdP-initiated logins don't: the IdP+ either 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.+ """+ 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")):+ return # SP-initiated: RelayState already identifies the tenant++ issuer = 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(+ # 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)+ )+ if len(matches) != 1:+ if len(matches) > 1:+ saml_logger.warning("saml_idp_initiated_ambiguous_issuer", issuer=issuer, count=len(matches))+ return++ organization_domain = matches[0]+ if not organization_domain.has_saml:+ return++ saml_logger.info(+ "saml_idp_initiated_relay_state_recovered",+ domain=organization_domain.domain,+ organization_id=str(organization_domain.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.+ strategy = cast(DjangoStrategy, self.strategy)+ mutable_post = strategy.request.POST.copy()+ mutable_post["RelayState"] = str(organization_domain.id)+ # 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:+ if not relay_state_str:+ return False+ candidate = self.parse_relay_state(relay_state_str).get("idp")+ if not candidate:+ return False+ try:+ # nosemgrep: idor-lookup-without-org (pre-auth SAML routing check by domain UUID)+ return OrganizationDomain.objects.verified_domains().filter(id=candidate).exists()+ except (DjangoValidationError, ValueError):+ return False # not a valid UUID (e.g. an IdP-supplied URL)++ @staticmethod+ def _extract_response_issuer(saml_response_b64: str) -> str | None:+ # POST-binding SAMLResponse is base64-encoded (not deflated). Parsing is XXE-safe+ # (onelogin forbids DTDs/entities); the signature is still verified afterwards.+ try:+ document = OneLogin_Saml2_XML.to_etree(base64.b64decode(saml_response_b64))+ issuer_nodes = OneLogin_Saml2_XML.query(document, "/samlp:Response/saml:Issuer")+ except Exception:+ return None+ if not issuer_nodes:+ return None+ return (OneLogin_Saml2_XML.element_text(issuer_nodes[0]) or "").strip() or None+def get_idp(self, organization_domain_or_id: Union["OrganizationDomain", str, None]) -> SAMLIdentityProvider:if organization_domain_or_id is None:saml_logger.warning("saml_idp_lookup_failed", idp_id="None")diff --git a/ee/api/test/test_authentication.py b/ee/api/test/test_authentication.pyindex a4c5e01c6256..0b89a6ee4ea1 100644--- a/ee/api/test/test_authentication.py+++ b/ee/api/test/test_authentication.py@@ -14,6 +14,7 @@ from django.core.exceptions import ValidationErrorfrom django.test import override_settingsfrom django.utils import timezone+from parameterized import parameterizedfrom rest_framework import statusfrom social_core.exceptions import AuthFailedfrom social_django.models import UserSocialAuth@@ -458,6 +459,41 @@ class TestEESAMLAuthenticationAPI(APILicensedTest):response = self.client.get("/api/users/@me/")self.assertEqual(response.status_code, status.HTTP_200_OK)+ @parameterized.expand(+ [+ # Azure AD / Entra omits RelayState entirely for IdP-initiated SSO.+ ("no_relay_state", None),+ # Other IdPs send their own RelayState (e.g. an app launch URL) that isn't our UUID.+ ("url_relay_state", "https://idp.hogflix.io/saml/launch"),+ ]+ )+ @freeze_time("2021-08-25T22:09:14.252Z") # Ensures the SAML timestamp validation passes+ def test_can_login_with_idp_initiated_saml(self, _name: str, relay_state: str | None) -> None:+ # IdP-initiated assertions don't carry the OrganizationDomain UUID in RelayState, so we+ # route to the tenant via the assertion's <Issuer> instead of rejecting it as "Invalid+ # RelayState". The fixture's Issuer matches the linked IdP config's saml_entity_id.+ user = User.objects.create(email="[email protected]", distinct_id=str(uuid.uuid4()))++ with open(+ os.path.join(CURRENT_FOLDER, "fixtures/saml_login_response"),+ encoding="utf_8",+ ) as f:+ saml_response = f.read()++ # No SP-initiated request preceded this, so there is no PostHog-issued RelayState and no+ # saml_state in the session — exactly the IdP-initiated case.+ post_data = {"SAMLResponse": saml_response}+ if relay_state is not None:+ post_data["RelayState"] = relay_state++ response = self.client.post("/complete/saml/", post_data, follow=True, format="multipart")++ self.assertEqual(response.status_code, status.HTTP_200_OK) # because `follow=True`+ self.assertRedirects(response, "/") # redirect to the home page++ _session = self.client.session+ self.assertEqual(_session.get("_auth_user_id"), str(user.pk))+@freeze_time("2021-08-25T22:09:14.252Z") # Ensures the SAML timestamp validation passesdef test_saml_login_redirects_to_next_url_from_relay_state(self):# End-to-end counterpart to test_saml_flow_carries_next_url_in_relay_state: a JSON