: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
fix(saml): use opaque token for saml relay state (#123641)
Reece Jonese2ad511e2902
diff --git a/ee/api/authentication.py b/ee/api/authentication.pyindex 18af63b4ee54..99c0ad5514bf 100644--- a/ee/api/authentication.py+++ b/ee/api/authentication.py@@ -2,7 +2,7 @@ import reimport jsonimport base64from typing import Any, Literal, TypedDict, cast-from uuid import UUID+from uuid import UUID, uuid4from django.core.exceptions import ValidationError as DjangoValidationErrorfrom django.http.response import HttpResponse@@ -11,6 +11,7 @@ from django.urls.base import reverseimport jwtimport structlogimport posthoganalytics+import redis.exceptions as redis_exceptionsfrom jwt.algorithms import RSAAlgorithmfrom onelogin.saml2.xml_utils import OneLogin_Saml2_XMLfrom rest_framework import authentication@@ -42,6 +43,7 @@ from posthog.models.activity_logging.utils import ActivityCredentialMixinfrom posthog.models.identity_provider_config import IdentityProviderConfig, has_verified_organization_domain_qfrom posthog.models.organization import OrganizationMembershipfrom posthog.models.organization_domain import OrganizationDomain+from posthog.redis import get_clientfrom ee import settingsfrom ee.api.vercel.types import VercelClaims, VercelSystemClaims, VercelUser, VercelUserClaims@@ -88,6 +90,41 @@ def saml_metadata_view(request, *args, **kwargs):return HttpResponse(content=metadata, content_type="text/xml")+# OASIS SAML bindings cap RelayState at 80 bytes; the cache TTL only needs to outlast the IdP round trip.+SAML_RELAY_STATE_CACHE_TTL_SECONDS = 60 * 10+++def _saml_relay_state_cache_key(key: str) -> str:+ return f"saml_relay_state:{key}"+++def _relay_state_from_json(raw: str | bytes) -> dict[str, Any] | None:+ try:+ state = json.loads(raw)+ except ValueError:+ return None+ return state if isinstance(state, dict) else None+++def _store_saml_relay_state(state: dict[str, Any]) -> str:+ key = str(uuid4())+ try:+ get_client().setex(_saml_relay_state_cache_key(key), SAML_RELAY_STATE_CACHE_TTL_SECONDS, json.dumps(state))+ except redis_exceptions.RedisError:+ # Sessions are DB-backed, so a Redis outage must not block login. Send the pre-cache JSON+ # instead: the IdP may refuse it above the RelayState cap, but failing the flow is worse.+ return json.dumps(state)+ return key+++def _load_saml_relay_state(key: str) -> dict[str, Any] | None:+ try:+ raw = get_client().get(_saml_relay_state_cache_key(key))+ except redis_exceptions.RedisError:+ return None+ return _relay_state_from_json(raw) if raw else None++class MultitenantSAMLAuth(SAMLAuth):"""Implements our own version of SAML auth that supports multitenancy. Instead of relying on instance-based config via env vars,@@ -160,6 +197,12 @@ class MultitenantSAMLAuth(SAMLAuth):# 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 parse_relay_state(self, relay_state_str: str) -> dict:+ # A miss still routes the pre-cache JSON payload, an IdP-supplied value, or an expired key+ # through the base parser, which sends the last two to the IdP-initiated recovery.+ stored = _load_saml_relay_state(relay_state_str)+ return stored if stored is not None else super().parse_relay_state(relay_state_str)+def _relay_state_points_to_config(self, relay_state_str: str | None) -> bool:if not relay_state_str:return False@@ -270,7 +313,7 @@ class MultitenantSAMLAuth(SAMLAuth):# 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": identity_provider.name, "next": self.data.get("next")}- return auth.login(return_to=json.dumps(relay_state))+ return auth.login(return_to=_store_saml_relay_state(relay_state))def _get_attr(self,diff --git a/ee/api/test/test_authentication.py b/ee/api/test/test_authentication.pyindex 5b3fa526c740..c25e1a86b13c 100644--- a/ee/api/test/test_authentication.py+++ b/ee/api/test/test_authentication.py@@ -21,6 +21,7 @@ from django.utils import timezoneimport jwtimport responses+import redis.exceptions as redis_exceptionsfrom cryptography.hazmat.primitives.asymmetric import rsafrom parameterized import parameterizedfrom requests import Response@@ -38,6 +39,7 @@ from posthog.models.activity_logging.activity_log import ActivityLogfrom posthog.models.identity_provider_config import IdentityProviderConfigfrom posthog.models.linked_identity_provider_config import LinkedIdentityProviderConfigfrom posthog.models.organization_domain import OrganizationDomain+from posthog.redis import get_clientfrom posthog.session.activity import session_public_idfrom ee.api.authentication import CustomGoogleOAuth2, MultitenantSAMLAuth@@ -1364,21 +1366,23 @@ class TestEESAMLAuthenticationAPI(APILicensedTest):def test_saml_flow_carries_next_url_in_relay_state(self):# The session cookie is SameSite=Lax, so it's dropped on the IdP's cross-site POST- # back to /complete/saml/. The `next` redirect must therefore travel in RelayState- # (echoed back by the IdP) rather than the session, or re-auth lands the user on `/`.- response = self.client.get(- "/login/saml/[email protected]&next=/settings/organization/authentication"- )+ # back to /complete/saml/. The `next` redirect must therefore travel alongside RelayState+ # rather than in the session, or re-auth lands the user on `/`.+ next_url = "/oauth/authorize?" + "&".join(f"param_{i}=value_{i}" for i in range(20))+ response = self.client.get("/login/saml/", {"email": "[email protected]", "next": next_url})self.assertEqual(response.status_code, status.HTTP_302_FOUND)config = self.organization_domain.saml_identity_provider_configs.first()assert config is not Noneconfig.refresh_from_db()- relay_state = json.loads(parse_qs(urlparse(response.headers["Location"]).query)["RelayState"][0])+ relay_state = parse_qs(urlparse(response.headers["Location"]).query)["RelayState"][0]+ # OASIS SAML bindings cap RelayState at 80 bytes, so a long `next` cannot travel in it.+ self.assertLessEqual(len(relay_state), 80)+ cached = get_client().get(f"saml_relay_state:{relay_state}")+ assert cached is not None# 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")+ self.assertEqual(json.loads(cached), {"idp": config.saml_relay_state, "next": next_url})def test_cannot_initiate_saml_flow_without_target_email_address(self):"""@@ -1482,9 +1486,56 @@ class TestEESAMLAuthenticationAPI(APILicensedTest):@time_machine.travel("2021-08-25T22:09:14.252Z", tick=False) # 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- # RelayState carrying `next` (as the IdP echoes it back) must land the user on that page- # rather than `/`, since the SameSite=Lax session cookie is dropped on this cross-site POST.+ # End-to-end counterpart to test_saml_flow_carries_next_url_in_relay_state: the opaque+ # RelayState the IdP echoes back must resolve to the state stored before the redirect and+ # land the user on `next` rather than `/`, since the SameSite=Lax session cookie is dropped+ # on this cross-site POST.+ User.objects.create(email="[email protected]", distinct_id=str(uuid.uuid4()))++ initiate = self.client.get(+ "/login/saml/[email protected]&next=/settings/organization/authentication"+ )+ relay_state = parse_qs(urlparse(initiate.headers["Location"]).query)["RelayState"][0]+ _session = self.client.session+ _session.update({"saml_state": "ONELOGIN_87856a50b5490e643b1ebef9cb5bf6e78225a3c6"})+ _session.save()++ with open(os.path.join(CURRENT_FOLDER, "fixtures/saml_login_response"), encoding="utf_8") as f:+ saml_response = f.read()++ response = self.client.post(+ "/complete/saml/",+ {"SAMLResponse": saml_response, "RelayState": relay_state},+ format="multipart",+ )++ self.assertEqual(response.status_code, status.HTTP_302_FOUND)+ self.assertEqual(response.headers["Location"], "/settings/organization/authentication")++ def test_relay_state_parses_when_redis_is_unavailable(self):+ # A Redis outage must not turn a SAML callback into a 500: the legacy payload needs no cache,+ # and a value that misses the cache keeps routing through the base parser.+ auth = object.__new__(MultitenantSAMLAuth)+ legacy = {"idp": str(self.organization_domain.id), "next": "/settings/organization/authentication"}++ with patch("ee.api.authentication.get_client", side_effect=redis_exceptions.ConnectionError("down")):+ self.assertEqual(auth.parse_relay_state(json.dumps(legacy)), legacy)+ self.assertEqual(+ auth.parse_relay_state("https://idp.hogflix.io/launch"), {"idp": "https://idp.hogflix.io/launch"}+ )++ def test_relay_state_parses_when_the_cached_value_is_not_json(self):+ # A relay state outlives its cache entry and arrives back as a bare UUID, which is not JSON.+ # Anything unreadable there must fall through to the base parser instead of raising.+ auth = object.__new__(MultitenantSAMLAuth)+ key = "0b5f9c4e-2f1f-4b1d-9d3e-6f1c2a4b5c6d"+ get_client().setex(f"saml_relay_state:{key}", 60, "not json")+ self.assertEqual(auth.parse_relay_state(key), {"idp": key})++ @time_machine.travel("2021-08-25T22:09:14.252Z", tick=False) # Ensures the SAML timestamp validation passes+ def test_saml_login_accepts_a_json_relay_state_from_a_login_started_before_a_deploy(self):+ # A login started on the previous release comes back with the JSON RelayState that release+ # sent, so a deploy mid-flight must not strand the user.User.objects.create(email="[email protected]", distinct_id=str(uuid.uuid4()))self.client.get("/login/saml/[email protected]&next=/settings/organization/authentication")