: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(auth): preserve next url through saml relaystate (#67122)
Reece Jones83335415b230
diff --git a/ee/api/authentication.py b/ee/api/authentication.pyindex c2e2b0388bc2..c55e99678e3a 100644--- a/ee/api/authentication.py+++ b/ee/api/authentication.py@@ -1,4 +1,5 @@import re+import jsonfrom typing import Any, Literal, TypedDict, Union, castfrom django.core.exceptions import ValidationError as DjangoValidationError@@ -94,8 +95,6 @@ class MultitenantSAMLAuth(SAMLAuth):saml_logger.info("saml_auth_complete")return resultexcept Exception as e:- import json-posthoganalytics.tag("request_data", json.dumps(self.strategy.request_data()))saml_logger.warning("saml_auth_complete_failed", error=str(e))raise@@ -160,10 +159,16 @@ class MultitenantSAMLAuth(SAMLAuth):**_saml_log_context(email, instance),)auth = self._create_saml_auth(idp=self.get_idp(instance))- # Below, return_to sets the RelayState, which contains the ID of- # the `OrganizationDomain`. We use it to store the specific SAML IdP- # name, since we multiple IdPs share the same auth_complete URL.- return auth.login(return_to=str(instance.id))+ # `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.+ # 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")}+ return auth.login(return_to=json.dumps(relay_state))def _get_attr(self,diff --git a/ee/api/test/test_authentication.py b/ee/api/test/test_authentication.pyindex e2d1e4e4ed58..a4c5e01c6256 100644--- a/ee/api/test/test_authentication.py+++ b/ee/api/test/test_authentication.py@@ -1,4 +1,5 @@import os+import jsonimport uuidimport datetimefrom typing import cast@@ -379,6 +380,19 @@ class TestEESAMLAuthenticationAPI(APILicensedTest):location = response.headers["Location"]self.assertIn("https://idp.hogflix.io/saml?SAMLRequest=", location)+ 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"+ )+ self.assertEqual(response.status_code, status.HTTP_302_FOUND)++ relay_state = json.loads(parse_qs(urlparse(response.headers["Location"]).query)["RelayState"][0])+ self.assertEqual(relay_state["idp"], str(self.organization_domain.id))+ self.assertEqual(relay_state["next"], "/settings/organization/authentication")+def test_cannot_initiate_saml_flow_without_target_email_address(self):"""We need the email address to know how to route the SAML request.@@ -444,6 +458,35 @@ class TestEESAMLAuthenticationAPI(APILicensedTest):response = self.client.get("/api/users/@me/")self.assertEqual(response.status_code, status.HTTP_200_OK)+ @freeze_time("2021-08-25T22:09:14.252Z") # Ensures the SAML timestamp validation passes+ def 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.+ User.objects.create(email="[email protected]", distinct_id=str(uuid.uuid4()))++ self.client.get("/login/saml/[email protected]&next=/settings/organization/authentication")+ _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": json.dumps(+ {"idp": str(self.organization_domain.id), "next": "/settings/organization/authentication"}+ ),+ },+ format="multipart",+ )++ self.assertEqual(response.status_code, status.HTTP_302_FOUND)+ self.assertEqual(response.headers["Location"], "/settings/organization/authentication")+@freeze_time("2021-08-25T23:37:55.345Z")def test_saml_jit_provisioning_and_assertion_with_different_attribute_names(self):"""