: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
import os
import json
import uuid
import datetime
from types import SimpleNamespace
from typing import Any, cast
from urllib.parse import parse_qs, urlencode, urlparse
import pytest
import time_machine
from unittest.mock import MagicMock, patch
from django.conf import settings
from django.core import mail
from django.core.cache import cache
from django.core.exceptions import ValidationError
from django.http import HttpResponse
from django.shortcuts import redirect
from django.test import RequestFactory, override_settings
from django.utils import timezone
import jwt
import responses
import redis.exceptions as redis_exceptions
from cryptography.hazmat.primitives.asymmetric import rsa
from parameterized import parameterized
from requests import Response
from rest_framework import status
from social_core.exceptions import AuthConnectionError, AuthFailed, AuthMissingParameter, AuthTokenError
from social_django.models import UserSocialAuth
from social_django.utils import load_strategy
from posthog.api.authentication import social_identity_matches_session
from posthog.api.oidc import MultitenantOIDCAuth
from posthog.api.sso import CustomGoogleOAuth2, MultitenantSAMLAuth
from posthog.constants import AvailableFeature
from posthog.helpers.sso import GITHUB_EMAIL_LOOKUP_ERROR, UNVERIFIED_SOCIAL_EMAIL_ERROR
from posthog.models import OrganizationMembership, User
from posthog.models.activity_logging.activity_log import ActivityLog
from posthog.models.identity_provider_config import IdentityProviderConfig
from posthog.models.linked_identity_provider_config import LinkedIdentityProviderConfig
from posthog.models.organization_domain import OrganizationDomain
from posthog.redis import get_client
from posthog.session.activity import session_public_id
from ee.api.test.base import APILicensedTest
from ee.models.license import License
SAML_MOCK_SETTINGS = {
"SOCIAL_AUTH_SAML_SECURITY_CONFIG": {
"wantAttributeStatement": False, # already present in settings
"allowSingleLabelDomains": True, # to allow `http://testserver` in tests
},
"SITE_URL": "http://localhost:8000", # http://localhost:8010 is now the default, but fixtures use 8000
}
SAML_MOCK_SETTINGS["SOCIAL_AUTH_SAML_SP_ENTITY_ID"] = SAML_MOCK_SETTINGS["SITE_URL"]
GOOGLE_MOCK_SETTINGS = {
"SOCIAL_AUTH_GOOGLE_OAUTH2_KEY": "google_key",
"SOCIAL_AUTH_GOOGLE_OAUTH2_SECRET": "google_secret",
}
GITHUB_MOCK_SETTINGS = {
"SOCIAL_AUTH_GITHUB_KEY": "github_key",
"SOCIAL_AUTH_GITHUB_SECRET": "github_secret",
}
CURRENT_FOLDER = os.path.dirname(__file__)
class TestOIDCAuthentication(APILicensedTest):
def setUp(self):
super().setUp()
self.organization.available_product_features = [
{"key": AvailableFeature.OIDC, "name": "OIDC"},
{"key": AvailableFeature.SSO_ENFORCEMENT, "name": "SSO enforcement"},
]
self.organization.save()
self.domain = OrganizationDomain.objects.create(
organization=self.organization, domain="example.com", verified_at=timezone.now()
)
self.config = IdentityProviderConfig.objects.create(
organization=self.organization,
config_scope="oidc",
domain_scope="all",
oidc_issuer_url="https://idp.example.com",
oidc_client_id="example-client",
oidc_credentials={"client_secret": "example-secret"},
)
request = RequestFactory().get("/login/oidc/", {"email": "[email protected]"})
request.session = self.client.session
request.session["oidc_config_id"] = str(self.config.id)
request.session["oidc_email"] = "[email protected]"
request.session["oidc_organization_id"] = self.organization.id
self.backend = MultitenantOIDCAuth(load_strategy(request), "https://app.example.com/complete/oidc/")
@parameterized.expand([("malformed", b"not-json"), ("non_object", b"[]")])
def test_oidc_rejects_invalid_discovery_json(self, _name, content):
response = Response()
response.status_code = 200
response._content = content
with patch.object(self.backend, "request", return_value=response):
with self.assertRaises(AuthFailed):
self.backend.get_json("https://idp.example.com/.well-known/openid-configuration")
@parameterized.expand([("missing_keys", {}), ("non_list_keys", {"keys": {}}), ("non_object_key", {"keys": [None]})])
def test_oidc_rejects_invalid_jwks_document(self, _name, document):
response = Response()
response.status_code = 200
response._content = json.dumps(document).encode()
with (
patch.object(self.backend, "jwks_uri", return_value="https://idp.example.com/keys"),
patch.object(self.backend, "request", return_value=response),
):
with self.assertRaises(AuthFailed):
self.backend.get_remote_jwks_keys()
def test_oidc_rejects_malformed_id_token_header(self):
with self.assertRaises(AuthTokenError):
self.backend.find_valid_key("not-a-jwt")
@parameterized.expand(
[
("valid", None),
("issuer", {"iss": "https://other.example.com"}),
("audience", {"aud": "other-client"}),
("expired", {"exp": 1}),
("nonce", {"nonce": "wrong-nonce"}),
("authorized_party", {"azp": "other-client"}),
("multiple_audiences", {"aud": ["example-client", "other-client"]}),
]
)
def test_oidc_validates_signed_id_token(self, _name, overrides):
private_key = rsa.generate_private_key(public_exponent=65537, key_size=2048)
public_key = {**json.loads(jwt.algorithms.RSAAlgorithm.to_jwk(private_key.public_key())), "kid": "example-key"}
discovery = {
"issuer": self.config.oidc_issuer_url,
"authorization_endpoint": "https://idp.example.com/authorize",
"token_endpoint": "https://idp.example.com/token",
"jwks_uri": "https://idp.example.com/keys",
}
with patch.object(self.backend, "get_json", return_value=discovery):
nonce = parse_qs(urlparse(self.backend.auth_url()).query)["nonce"][0]
claims = {
"iss": self.config.oidc_issuer_url,
"aud": "example-client",
"sub": "example-user",
"iat": int(timezone.now().timestamp()),
"exp": int(timezone.now().timestamp()) + 60,
"nonce": nonce,
**(overrides or {}),
}
token = jwt.encode(claims, private_key, algorithm="RS256", headers={"kid": "example-key"})
with patch.object(self.backend, "get_jwks_keys", return_value=[public_key]):
if overrides:
with self.assertRaises(AuthTokenError):
self.backend.validate_and_return_id_token(token, "example-access-token")
else:
self.assertEqual(self.backend.validate_and_return_id_token(token, "example-access-token"), claims)
with self.assertRaises(AuthTokenError):
self.backend.validate_and_return_id_token(token, "example-access-token")
def _complete_oidc_login(
self, email: str, *, sub: str = "example-user", name: str = "Example User"
) -> HttpResponse:
private_key = rsa.generate_private_key(public_exponent=65537, key_size=2048)
public_key = {**json.loads(jwt.algorithms.RSAAlgorithm.to_jwk(private_key.public_key())), "kid": "example-key"}
token_response: dict[str, Any] = {}
def oidc_response(url, method="GET", *args, **kwargs):
response = Response()
response.status_code = 200
data: dict[str, Any]
if url.endswith("/.well-known/openid-configuration"):
data = {
"issuer": self.config.oidc_issuer_url,
"authorization_endpoint": "https://idp.example.com/authorize",
"token_endpoint": "https://idp.example.com/token",
"userinfo_endpoint": "https://idp.example.com/userinfo",
"jwks_uri": "https://idp.example.com/keys",
}
elif url.endswith("/keys"):
data = {"keys": [public_key]}
elif url.endswith("/userinfo"):
self.assertEqual(method, "GET")
self.assertEqual(kwargs["headers"], {"Authorization": "Bearer example-access-token"})
data = {
"sub": sub,
"email": email,
"email_verified": True,
"name": name,
}
else:
self.assertEqual(url, "https://idp.example.com/token")
self.assertEqual(method, "POST")
self.assertIn("code_verifier", kwargs["data"])
data = token_response
response._content = json.dumps(data).encode()
return response
with patch.object(MultitenantOIDCAuth, "request", side_effect=oidc_response):
response = self.client.get("/login/oidc/", {"email": email})
self.assertEqual(response.status_code, 302)
params = parse_qs(urlparse(response["Location"]).query)
claims = {
"iss": self.config.oidc_issuer_url,
"aud": "example-client",
"sub": sub,
"name": name,
"iat": int(timezone.now().timestamp()),
"exp": int(timezone.now().timestamp()) + 60,
"nonce": params["nonce"][0],
}
token_response.update(
{
"access_token": "example-access-token",
"token_type": "Bearer",
"id_token": jwt.encode(claims, private_key, algorithm="RS256", headers={"kid": "example-key"}),
}
)
return self.client.get("/complete/oidc/", {"state": params["state"][0], "code": "example-code"})
def test_oidc_login_completes_without_storing_tokens(self):
self.user.email = "[email protected]"
self.user.save()
self.client.logout()
response = self._complete_oidc_login("[email protected]")
self.assertEqual(response.status_code, 302)
self.assertEqual(self.client.session["_auth_user_id"], str(self.user.pk))
self.assertEqual(response.cookies["ph_last_login_method"].value, "oidc")
social_auth = UserSocialAuth.objects.get(user=self.user, provider="oidc")
self.assertEqual(social_auth.uid, f"{self.config.oidc_issuer_url}:example-user")
self.assertEqual(social_auth.extra_data, {})
def test_oidc_jit_provisioning_creates_user_on_verified_domain(self):
self.domain.jit_provisioning_enabled = True
self.domain.save()
self.client.logout()
user_count = User.objects.count()
response = self._complete_oidc_login("[email protected]", sub="new-user", name="New Member")
self.assertEqual(response.status_code, 302)
self.assertEqual(User.objects.count(), user_count + 1)
user = cast(User, User.objects.get(email="[email protected]"))
self.assertEqual(user.first_name, "New Member")
self.assertEqual(user.organization, self.organization)
self.assertEqual(user.team, self.team)
self.assertEqual(
cast(OrganizationMembership, user.organization_memberships.get()).level,
OrganizationMembership.Level.MEMBER,
)
self.assertEqual(self.client.session["_auth_user_id"], str(user.pk))
social_auth = UserSocialAuth.objects.get(user=user, provider="oidc")
self.assertEqual(social_auth.uid, f"{self.config.oidc_issuer_url}:new-user")
def test_oidc_jit_provisioning_disabled_does_not_provision_user(self):
self.assertFalse(self.domain.jit_provisioning_enabled)
self.client.logout()
user_count = User.objects.count()
response = self._complete_oidc_login("[email protected]", sub="new-user", name="New Member")
self.assertEqual(response.status_code, 302)
self.assertEqual(User.objects.count(), user_count)
self.assertFalse(User.objects.filter(email="[email protected]").exists())
self.assertNotIn("_auth_user_id", self.client.session)
def test_oidc_redirect_uses_pkce_and_tenant_client(self):
with patch.object(
self.backend,
"get_json",
return_value={
"issuer": self.config.oidc_issuer_url,
"authorization_endpoint": "https://idp.example.com/authorize",
"token_endpoint": "https://idp.example.com/token",
"jwks_uri": "https://idp.example.com/keys",
},
):
params = parse_qs(urlparse(self.backend.auth_url()).query)
self.assertEqual(params["client_id"], ["example-client"])
self.assertEqual(params["code_challenge_method"], ["S256"])
self.assertEqual(params["scope"], ["openid profile email"])
self.assertTrue(params["state"])
self.assertTrue(params["nonce"])
def test_oidc_rejects_another_domain(self):
self.backend.id_token = cast(Any, {"sub": "example-user"})
with patch(
"posthog.api.oidc.OpenIdConnectAuth.user_data",
return_value={
"sub": "example-user",
"email": "[email protected]",
"email_verified": True,
},
):
with self.assertRaises(AuthFailed):
self.backend.user_data("example-access-token")
@parameterized.expand([("missing", None), ("false", False), ("string", "true")])
def test_oidc_requires_verified_email_from_userinfo(self, _name, email_verified):
self.backend.id_token = cast(Any, {"sub": "example-user"})
userinfo: dict[str, Any] = {"sub": "example-user", "email": "[email protected]"}
if email_verified is not None:
userinfo["email_verified"] = email_verified
with patch("posthog.api.oidc.OpenIdConnectAuth.user_data", return_value=userinfo):
with self.assertRaises(AuthFailed):
self.backend.user_data("example-access-token")
def test_oidc_accepts_verified_email_from_userinfo(self):
self.backend.id_token = cast(Any, {"sub": "example-user"})
userinfo = {
"sub": "example-user",
"email": "[email protected]",
"email_verified": True,
}
with patch("posthog.api.oidc.OpenIdConnectAuth.user_data", return_value=userinfo):
response = self.backend.user_data("example-access-token")
self.assertEqual(self.backend.get_user_id({}, response), f"{self.config.oidc_issuer_url}:example-user")
self.assertEqual(self.backend.extra_data(None, "uid", response, {}), {})
def test_oidc_get_user_id_normalizes_issuer_url(self):
self.backend.identity_provider_config = self.config
self.config.oidc_issuer_url = "https://idp.example.com/"
self.assertEqual(self.backend.get_user_id({}, {"sub": "example-user"}), "https://idp.example.com:example-user")
def test_oidc_get_user_id_rejects_identifiers_longer_than_255_characters(self):
self.backend.identity_provider_config = self.config
issuer = self.config.oidc_issuer_url.rstrip("/")
subject = "s" * (256 - len(f"{issuer}:"))
with self.assertRaises(AuthFailed):
self.backend.get_user_id({}, {"sub": subject})
def test_oidc_rejects_userinfo_for_another_subject(self):
self.backend.id_token = cast(Any, {"sub": "example-user"})
userinfo = {
"sub": "other-user",
"email": "[email protected]",
"email_verified": True,
}
with patch("posthog.api.oidc.OpenIdConnectAuth.user_data", return_value=userinfo):
with self.assertRaises(AuthFailed):
self.backend.user_data("example-access-token")
def test_oidc_rejects_removed_entitlement(self):
self.organization.available_product_features = []
self.organization.save()
with self.assertRaises(AuthFailed):
self.backend.get_key_and_secret()
def test_oidc_rejects_unverified_domain(self):
self.domain.verified_at = None
self.domain.save()
with self.assertRaises(AuthFailed):
self.backend.auth_url()
def test_oidc_rejects_overlapping_configurations(self):
self.config.pk = uuid.uuid4()
self.config.saml_relay_state = str(uuid.uuid4())
self.config.scim_slug = str(uuid.uuid4())
self.config.save()
with self.assertRaises(AuthFailed):
self.backend.auth_url()
@parameterized.expand(
[
("mismatch", "https://idp.example.com", "https://other.example.com", False),
("configured_trailing_slash", "https://idp.example.com/", "https://idp.example.com", True),
("discovered_trailing_slash", "https://idp.example.com", "https://idp.example.com/", True),
]
)
def test_oidc_checks_discovery_issuer(self, _name, configured_issuer, discovered_issuer, accepted):
self.config.oidc_issuer_url = configured_issuer
self.config.save()
with patch.object(
self.backend,
"get_json",
return_value={
"issuer": discovered_issuer,
"authorization_endpoint": "https://idp.example.com/authorize",
"token_endpoint": "https://idp.example.com/token",
"jwks_uri": "https://idp.example.com/keys",
},
):
if accepted:
self.assertEqual(self.backend.oidc_config()["issuer"], discovered_issuer)
else:
with self.assertRaises(AuthFailed):
self.backend.oidc_config()
def test_oidc_does_not_share_discovery_between_tenants(self):
other_backend = MultitenantOIDCAuth(self.backend.strategy, self.backend.redirect_uri)
other_config = MagicMock(oidc_issuer_url="https://other.example.com")
other_backend.identity_provider_config = other_config
for backend, issuer in [
(self.backend, self.config.oidc_issuer_url),
(other_backend, other_config.oidc_issuer_url),
]:
with patch.object(
backend,
"get_json",
return_value={
"issuer": issuer,
"authorization_endpoint": f"{issuer}/authorize",
"token_endpoint": f"{issuer}/token",
"jwks_uri": f"{issuer}/keys",
},
) as get_json:
self.assertEqual(backend.oidc_config()["issuer"], issuer)
get_json.assert_called_once_with(f"{issuer}/.well-known/openid-configuration")
def test_oidc_enforcement_checks_entitlement(self):
self.domain.sso_enforcement = "oidc"
self.domain.save()
self.assertEqual(OrganizationDomain.objects.get_sso_enforcement_for_email_address("[email protected]"), "oidc")
self.organization.available_product_features = [{"key": AvailableFeature.SSO_ENFORCEMENT}]
self.organization.save()
self.assertIsNone(OrganizationDomain.objects.get_sso_enforcement_for_email_address("[email protected]"))
def test_oidc_precheck_requires_configured_and_licensed_provider(self):
self.domain.sso_enforcement = "oidc"
self.domain.save()
response = self.client.post("/api/login/precheck", {"email": "[email protected]"})
self.assertEqual(response.json()["sso_enforcement"], "oidc")
self.assertTrue(response.json()["oidc_available"])
self.config.oidc_credentials = {}
self.config.save()
response = self.client.post("/api/login/precheck", {"email": "[email protected]"})
self.assertIsNone(response.json()["sso_enforcement"])
self.assertFalse(response.json().get("oidc_available", False))
class TestEELoginPrecheckAPI(APILicensedTest):
CONFIG_AUTO_LOGIN = False
def test_login_precheck_with_enforced_sso(self):
OrganizationDomain.objects.create(
domain="witw.app",
organization=self.organization,
verified_at=timezone.now(),
sso_enforcement="google-oauth2",
)
User.objects.create_and_join(self.organization, "[email protected]", self.CONFIG_PASSWORD)
with self.settings(**GOOGLE_MOCK_SETTINGS):
response = self.client.post("/api/login/precheck", {"email": "[email protected]"})
self.assertEqual(response.status_code, status.HTTP_200_OK)
self.assertEqual(
response.json(),
{
"sso_enforcement": "google-oauth2",
"saml_available": False,
"oidc_available": False,
"webauthn_credentials": [],
"account_exists": True,
"password_login_available": True,
"social_providers": [],
},
)
def test_login_precheck_with_unverified_domain(self):
OrganizationDomain.objects.create(
domain="witw.app",
organization=self.organization,
verified_at=None, # note domain is not verified
sso_enforcement="google-oauth2",
)
with self.settings(**GOOGLE_MOCK_SETTINGS):
response = self.client.post(
"/api/login/precheck", {"email": "[email protected]"}
) # Note we didn't create a user that matches, only domain is matched
self.assertEqual(response.status_code, status.HTTP_200_OK)
self.assertEqual(
response.json(),
{
"sso_enforcement": None,
"saml_available": False,
"oidc_available": False,
"webauthn_credentials": [],
"account_exists": False,
"password_login_available": True,
"social_providers": [],
},
)
def test_login_precheck_with_inexistent_account(self):
OrganizationDomain.objects.create(
domain="anotherdomain.com",
organization=self.organization,
verified_at=timezone.now(),
sso_enforcement="github",
)
User.objects.create_and_join(self.organization, "[email protected]", self.CONFIG_PASSWORD)
with self.settings(**GITHUB_MOCK_SETTINGS):
response = self.client.post("/api/login/precheck", {"email": "[email protected]"})
self.assertEqual(response.status_code, status.HTTP_200_OK)
self.assertEqual(
response.json(),
{
"sso_enforcement": "github",
"saml_available": False,
"oidc_available": False,
"webauthn_credentials": [],
"account_exists": True,
"password_login_available": True,
"social_providers": [],
},
)
def test_login_precheck_with_enforced_sso_but_improperly_configured_sso(self):
OrganizationDomain.objects.create(
domain="witw.app",
organization=self.organization,
verified_at=timezone.now(),
sso_enforcement="google-oauth2",
)
User.objects.create_and_join(self.organization, "[email protected]", self.CONFIG_PASSWORD)
response = self.client.post(
"/api/login/precheck", {"email": "[email protected]"}
) # Note Google OAuth is not configured
self.assertEqual(response.status_code, status.HTTP_200_OK)
self.assertEqual(
response.json(),
{
"sso_enforcement": None,
"saml_available": False,
"oidc_available": False,
"webauthn_credentials": [],
"account_exists": True,
"password_login_available": True,
"social_providers": [],
},
)
class TestEEAuthenticationAPI(APILicensedTest):
CONFIG_EMAIL = "[email protected]"
def create_enforced_domain(self, **kwargs) -> OrganizationDomain:
return OrganizationDomain.objects.create(
**{
"domain": "posthog.com",
"organization": self.organization,
"verified_at": timezone.now(),
"sso_enforcement": "google-oauth2",
**kwargs,
}
)
def test_can_enforce_sso(self):
self.client.logout()
# Can log in with password with SSO configured but not enforced
with self.settings(**GOOGLE_MOCK_SETTINGS):
response = self.client.post(
"/api/login",
{"email": self.CONFIG_EMAIL, "password": self.CONFIG_PASSWORD},
)
self.assertEqual(response.status_code, status.HTTP_200_OK)
self.assertEqual(response.json(), {"success": True})
# Forcing SSO disables regular API password login
self.create_enforced_domain()
with self.settings(**GOOGLE_MOCK_SETTINGS):
response = self.client.post(
"/api/login",
{"email": self.CONFIG_EMAIL, "password": self.CONFIG_PASSWORD},
)
self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
self.assertEqual(
response.json(),
{
"type": "validation_error",
"code": "sso_enforced",
"detail": "You can only login with SSO for this account (google-oauth2).",
"attr": None,
},
)
def test_can_enforce_sso_on_cloud_enviroment(self):
self.client.logout()
License.objects.filter(pk=-1).delete() # No instance licenses
self.create_enforced_domain()
self.organization.available_product_features = [{"key": "sso_enforcement", "name": "sso_enforcement"}]
self.organization.save()
with self.settings(**GOOGLE_MOCK_SETTINGS):
response = self.client.post(
"/api/login",
{"email": self.CONFIG_EMAIL, "password": self.CONFIG_PASSWORD},
)
self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
self.assertEqual(
response.json(),
{
"type": "validation_error",
"code": "sso_enforced",
"detail": "You can only login with SSO for this account (google-oauth2).",
"attr": None,
},
)
def test_cannot_reset_password_with_enforced_sso(self):
self.create_enforced_domain()
with self.settings(
**GOOGLE_MOCK_SETTINGS,
EMAIL_HOST="localhost",
SITE_URL="https://my.posthog.net",
):
response = self.client.post("/api/reset/", {"email": "[email protected]"})
self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
self.assertEqual(
response.json(),
{
"type": "validation_error",
"code": "sso_enforced",
"detail": "Password reset is disabled because SSO login is enforced for this domain.",
"attr": None,
},
)
self.assertEqual(len(mail.outbox), 0)
def test_sso_enforcement_follows_the_account_the_typed_address_resolves_to(self):
self.client.logout()
member = User.objects.create_and_join(self.organization, "[email protected]", self.CONFIG_PASSWORD)
member.is_email_verified = True
member.save(update_fields=["is_email_verified"])
self.create_enforced_domain(domain="victim.example")
# Postgres lowercases `İ` (U+0130) to `i`, so the second address resolves to the member's account
# while its typed domain does not match the enforced one.
for typed_email in ("[email protected]", "member@vİctim.example"):
with self.subTest(email=typed_email), self.settings(**GOOGLE_MOCK_SETTINGS):
precheck = self.client.post("/api/login/precheck", {"email": typed_email})
response = self.client.post("/api/login", {"email": typed_email, "password": self.CONFIG_PASSWORD})
self.assertEqual(precheck.json()["sso_enforcement"], "google-oauth2")
self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST, response.json())
self.assertEqual(response.json()["code"], "sso_enforced")
self.assertNotIn("_auth_user_id", self.client.session)
def test_cannot_reset_password_through_a_typed_domain_that_resolves_to_an_enforced_account(self):
User.objects.create_and_join(self.organization, "[email protected]", self.CONFIG_PASSWORD)
self.create_enforced_domain(domain="victim.example")
with self.settings(**GOOGLE_MOCK_SETTINGS, EMAIL_HOST="localhost", SITE_URL="https://my.posthog.net"):
response = self.client.post("/api/reset/", {"email": "member@vİctim.example"})
self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
self.assertEqual(response.json()["code"], "sso_enforced")
self.assertEqual(len(mail.outbox), 0)
@patch("posthog.models.organization_domain.logger.warning")
def test_cannot_enforce_sso_without_a_license(self, mock_warning):
self.client.logout()
self.license.valid_until = timezone.now() - datetime.timedelta(days=1)
self.license.save()
self.create_enforced_domain()
# Enforcement is ignored
with self.settings(**GOOGLE_MOCK_SETTINGS):
response = self.client.post(
"/api/login",
{"email": self.CONFIG_EMAIL, "password": self.CONFIG_PASSWORD},
)
self.assertEqual(response.status_code, status.HTTP_200_OK)
self.assertEqual(response.json(), {"success": True})
# Attempting to use SAML fails
with self.settings(**GOOGLE_MOCK_SETTINGS):
response = self.client.get("/login/google-oauth2/")
self.assertEqual(response.status_code, status.HTTP_302_FOUND)
self.assertIn("/login?error_code=improperly_configured_sso", response.headers["Location"])
# Ensure warning is properly logged for debugging
mock_warning.assert_called_with(
"🤑🚪 SSO is enforced for domain posthog.com but the organization does not have the proper license.",
domain="posthog.com",
organization=str(self.organization.id),
)
def test_login_with_sso_resets_session(self):
with self.settings(**GOOGLE_MOCK_SETTINGS):
first_key = self.client.session.session_key
self.client.post("/login/google-oauth2/", {})
second_key = self.client.session.session_key
self.assertNotEqual(first_key, second_key)
def test_sso_login_is_throttled_per_ip(self):
cache.delete("throttle_sso_login_192.0.2.1")
self.addCleanup(cache.delete, "throttle_sso_login_192.0.2.1")
for _ in range(10):
response = self.client.get("/login/unknown-provider/", HTTP_X_FORWARDED_FOR="192.0.2.1")
self.assertEqual(response.status_code, status.HTTP_302_FOUND)
response = self.client.get("/login/unknown-provider/", HTTP_X_FORWARDED_FOR="192.0.2.1")
self.assertEqual(response.status_code, status.HTTP_429_TOO_MANY_REQUESTS)
self.assertEqual(response["Retry-After"], "60")
@patch("social_core.backends.base.BaseAuth.request")
def test_google_login_returns_to_saved_insight(self, mock_request):
UserSocialAuth.objects.create(user=self.user, provider="google-oauth2", uid="google-sub-123")
insight_url = "/project/1/insights/test-insight"
with self.settings(**GOOGLE_MOCK_SETTINGS):
response = self.client.get(f"/login/google-oauth2/?{urlencode({'next': insight_url})}")
self.assertEqual(response.status_code, status.HTTP_302_FOUND)
state = self.client.session["google-oauth2_state"]
mock_request.return_value.json.return_value = {
"access_token": "123",
"email": self.user.email,
"sub": "google-sub-123",
}
response = self.client.get(f"/complete/google-oauth2/?code=2&state={state}")
self.assertRedirects(response, insight_url, fetch_redirect_response=False)
self.assertEqual(self.client.session.get("_auth_user_id"), str(self.user.pk))
@parameterized.expand(
[
("auth_failed", AuthFailed(cast(Any, "google-oauth2"), "bad")),
("missing_parameter", AuthMissingParameter(cast(Any, "google-oauth2"), "code")),
("connection_error", AuthConnectionError(cast(Any, "google-oauth2"), "cert verify failed")),
]
)
def test_unreachable_or_misconfigured_sso_provider_redirects(self, _name, exception):
# An unreachable IdP or one whose TLS cert fails during OIDC discovery raises AuthConnectionError,
# a sibling of AuthFailed - it must redirect gracefully rather than surface as an unhandled 500.
self.client.logout()
with self.settings(**GOOGLE_MOCK_SETTINGS), patch("posthog.api.authentication.auth", side_effect=exception):
response = self.client.get("/login/google-oauth2/")
self.assertRedirects(response, "/login?error_code=improperly_configured_sso", fetch_redirect_response=False)
def test_misconfigured_provider_does_not_sign_out_the_current_session(self):
# Google isn't configured here, so the provider check fails. It has to run before the session
# is touched, otherwise a misconfigured provider signs people out.
response = self.client.get("/login/google-oauth2/")
self.assertRedirects(response, "/login?error_code=improperly_configured_sso", fetch_redirect_response=False)
self.assertTrue(self.client.session.get("_auth_user_id"))
def test_sso_reauth_keeps_the_session(self):
with self.settings(**GOOGLE_MOCK_SETTINGS):
session_key_before = self.client.session.session_key
response = self.client.get("/login/google-oauth2/?reauth=true&next=/settings/user")
self.assertEqual(response.status_code, status.HTTP_302_FOUND)
self.assertIn("accounts.google.com", response.headers["Location"])
self.assertEqual(self.client.session.session_key, session_key_before)
@patch("posthog.api.authentication.auth", return_value=redirect("/"))
def test_connect_from_oidc_flushes_the_authenticated_session(self, _mock_auth):
response = self.client.get("/login/oidc/?connect_from=posthog_code")
self.assertEqual(response.status_code, status.HTTP_302_FOUND)
self.assertNotIn("_auth_user_id", self.client.session)
@parameterized.expand([("oidc",), ("github",)])
def test_authenticated_session_cannot_attach_a_different_social_identity(self, backend_name):
request = RequestFactory().get("/complete/oidc/")
request.session = self.client.session
request.user = self.user
strategy = load_strategy(request)
with self.assertRaises(AuthFailed):
social_identity_matches_session(
strategy,
backend=SimpleNamespace(name=backend_name),
details={"email": "[email protected]"},
user=None,
)
def test_github_account_link_allows_a_different_identity_email(self):
session = self.client.session
session["next"] = "/account-connected/github-login?provider=github&connect_from=posthog_code"
session.save()
request = RequestFactory().get("/complete/github/")
request.session = session
request.user = self.user
strategy = load_strategy(request)
social_identity_matches_session(
strategy,
backend=SimpleNamespace(name="github"),
details={"email": "[email protected]"},
user=self.user,
)
@parameterized.expand(
[
("plain_path", "/settings/user", "/settings/user?error_code=improperly_configured_sso"),
(
"path_with_query",
"/settings/user?tab=danger",
"/settings/user?tab=danger&error_code=improperly_configured_sso",
),
# The error code has to stay ahead of the fragment, or the browser reads it as fragment text
# and the modal never learns the re-auth failed.
(
"path_with_fragment",
"/settings/user#danger-zone",
"/settings/user?error_code=improperly_configured_sso#danger-zone",
),
# An unusable `next` still must not land a signed-in user on /login, which drops the error code
("offsite_next", "https://evil.example.com/steal", "/?error_code=improperly_configured_sso"),
]
)
def test_failed_sso_reauth_returns_to_the_page_that_asked_for_it(self, _name, next_url, expected_location):
query = urlencode({"reauth": "true", "next": next_url})
with (
self.settings(**GOOGLE_MOCK_SETTINGS),
patch(
"posthog.api.authentication.auth",
side_effect=AuthConnectionError(cast(Any, "google-oauth2"), "unreachable"),
),
):
response = self.client.get(f"/login/google-oauth2/?{query}")
self.assertRedirects(response, expected_location, fetch_redirect_response=False)
self.assertTrue(self.client.session.get("_auth_user_id"))
def _begin_google_reauth(self, next_url: str = "/settings/user") -> str:
query = urlencode({"reauth": "true", "next": next_url, "email": self.user.email})
response = self.client.get(f"/login/google-oauth2/?{query}")
self.assertEqual(response.status_code, status.HTTP_302_FOUND)
return self.client.session["google-oauth2_state"]
@parameterized.expand(
[
("same_identity", "google-sub-123", None),
("different_identity", "unassociated-sub", "reauth_user_mismatch"),
]
)
@patch("social_core.backends.base.BaseAuth.request")
def test_popup_sso_reauth_reports_the_outcome_to_the_opener(self, _name, sub, expected_error_code, mock_request):
UserSocialAuth.objects.create(user=self.user, provider="google-oauth2", uid="google-sub-123")
with self.settings(**GOOGLE_MOCK_SETTINGS):
state = self._begin_google_reauth(next_url="/reauth/complete?attempt=a1")
mock_request.return_value.json.return_value = {
"access_token": "123",
"email": self.user.email if expected_error_code is None else "[email protected]",
"sub": sub,
}
response = self.client.get(f"/complete/google-oauth2/?code=2&state={state}")
expected_location = "/reauth/complete?attempt=a1" + (
f"&error_code={expected_error_code}" if expected_error_code else ""
)
self.assertRedirects(response, expected_location, fetch_redirect_response=False)
page = self.client.get(expected_location)
self.assertEqual(page.status_code, status.HTTP_200_OK)
self.assertContains(page, "posthog-sso-reauth")
result = {"channel": "posthog-sso-reauth", "attempt": "a1", "error_code": expected_error_code}
self.assertContains(
page, f'<script id="sso-reauth-result" type="application/json">{json.dumps(result)}</script>'
)
def test_popup_completion_page_does_not_run_an_injected_error_code(self):
response = self.client.get("/reauth/complete", {"error_code": "</script><script>alert(1)</script>"})
self.assertNotContains(response, "<script>alert(1)</script>")
@patch("social_core.backends.base.BaseAuth.request")
def test_sso_reauth_refreshes_the_sensitive_action_window(self, mock_request):
UserSocialAuth.objects.create(user=self.user, provider="google-oauth2", uid="google-sub-123")
session = self.client.session
session[settings.SESSION_STEP_UP_REQUIRED_KEY] = True
session.save()
last_reauth_at_before = session[settings.SESSION_LAST_REAUTH_AT_KEY]
session_key_before = session.session_key
with self.settings(**GOOGLE_MOCK_SETTINGS):
state = self._begin_google_reauth()
mock_request.return_value.json.return_value = {
"access_token": "123",
"email": self.user.email,
"sub": "google-sub-123",
}
response = self.client.get(f"/complete/google-oauth2/?code=2&state={state}")
self.assertRedirects(response, "/settings/user", fetch_redirect_response=False)
self.assertEqual(self.client.session.get("_auth_user_id"), str(self.user.pk))
self.assertGreater(self.client.session[settings.SESSION_LAST_REAUTH_AT_KEY], last_reauth_at_before)
self.assertIsNone(self.client.session.get(settings.SESSION_STEP_UP_REQUIRED_KEY))
login_activity = ActivityLog.objects.filter(scope="User", activity="logged_in").latest("created_at")
login_context = cast(dict, login_activity.detail)["context"]
self.assertEqual(login_context["reauth"], True)
self.assertEqual(login_context["login_method"], "Google OAuth")
# The row has to name the session the rotation created, not the one it retired.
self.assertEqual(login_activity.credential_type, "session")
self.assertEqual(
login_activity.credential_id, str(session_public_id(cast(str, self.client.session.session_key)))
)
# Opening the sensitive-action window has to retire the session id that existed before it,
# so a cookie copied earlier can't ride the window the victim just opened.
self.assertNotEqual(self.client.session.session_key, session_key_before)
self.client.cookies[settings.SESSION_COOKIE_NAME] = cast(str, session_key_before)
self.assertEqual(self.client.get("/api/users/@me/").status_code, status.HTTP_401_UNAUTHORIZED)
@patch("social_core.backends.base.BaseAuth.request")
def test_sso_reauth_refused_later_in_the_pipeline_grants_nothing(self, mock_request):
# A pipeline step that returns a response aborts the flow - domain enforcement in
# `social_create_user` does this for a member no organization admits any more. The step-up
# must not already have been granted by then.
UserSocialAuth.objects.create(user=self.user, provider="google-oauth2", uid="google-sub-123")
session = self.client.session
session[settings.SESSION_STEP_UP_REQUIRED_KEY] = True
session.save()
last_reauth_at_before = session[settings.SESSION_LAST_REAUTH_AT_KEY]
session_key_before = session.session_key
activity_count_before = ActivityLog.objects.filter(scope="User", activity="logged_in").count()
with (
self.settings(**GOOGLE_MOCK_SETTINGS),
patch(
"posthog.api.signup.social_create_user",
return_value=redirect("/login?error_code=verified_domain_required"),
),
):
state = self._begin_google_reauth()
mock_request.return_value.json.return_value = {
"access_token": "123",
"email": self.user.email,
"sub": "google-sub-123",
}
response = self.client.get(f"/complete/google-oauth2/?code=2&state={state}")
self.assertRedirects(response, "/login?error_code=verified_domain_required", fetch_redirect_response=False)
self.assertEqual(self.client.session[settings.SESSION_LAST_REAUTH_AT_KEY], last_reauth_at_before)
self.assertTrue(self.client.session.get(settings.SESSION_STEP_UP_REQUIRED_KEY))
self.assertEqual(self.client.session.session_key, session_key_before)
self.assertEqual(ActivityLog.objects.filter(scope="User", activity="logged_in").count(), activity_count_before)
@patch("social_core.backends.base.BaseAuth.request")
def test_sso_reauth_with_a_different_identity_is_rejected_without_signing_out(self, mock_request):
last_reauth_at_before = self.client.session[settings.SESSION_LAST_REAUTH_AT_KEY]
with self.settings(**GOOGLE_MOCK_SETTINGS):
state = self._begin_google_reauth()
mock_request.return_value.json.return_value = {
"access_token": "123",
"email": "[email protected]",
"sub": "unassociated-sub",
}
response = self.client.get(f"/complete/google-oauth2/?code=2&state={state}")
self.assertRedirects(response, "/settings/user?error_code=reauth_user_mismatch", fetch_redirect_response=False)
self.assertEqual(self.client.session.get("_auth_user_id"), str(self.user.pk))
self.assertEqual(self.client.session[settings.SESSION_LAST_REAUTH_AT_KEY], last_reauth_at_before)
# The stranger's identity must not have been linked to the signed-in account
self.assertFalse(UserSocialAuth.objects.filter(user=self.user).exists())
def _complete_github_login(
self,
github_id: int,
emails: list[dict[str, Any]],
emails_status: int = 200,
profile_email: str | None = None,
login_query: str = "",
) -> HttpResponse:
with (
self.settings(**GITHUB_MOCK_SETTINGS),
responses.RequestsMock(assert_all_requests_are_fired=False) as mock_github,
):
mock_github.add(responses.POST, "https://github.com/login/oauth/access_token", json={"access_token": "gh"})
mock_github.add(
responses.GET,
"https://api.github.com/user",
json={"id": github_id, "login": "octo", "name": "Octo Cat", "email": profile_email},
)
mock_github.add(responses.GET, "https://api.github.com/user/emails", json=emails, status=emails_status)
self.client.get(f"/login/github/?{login_query}")
state = self.client.session["github_state"]
response = self.client.get(f"/complete/github/?code=2&state={state}")
return response
def _complete_google_login(self, email: str, email_verified: bool | None, login_query: str = "") -> HttpResponse:
with (
self.settings(**GOOGLE_MOCK_SETTINGS),
patch("social_core.backends.base.BaseAuth.request") as mock_request,
):
self.client.get(f"/login/google-oauth2/?{login_query}")
state = self.client.session["google-oauth2_state"]
userinfo: dict[str, Any] = {"access_token": "123", "email": email, "sub": "google-sub-new"}
if email_verified is not None:
userinfo["email_verified"] = email_verified
mock_request.return_value.json.return_value = userinfo
return self.client.get(f"/complete/google-oauth2/?code=2&state={state}")
@parameterized.expand(
[
("github_unverified_primary", "github", False),
("google_unverified", "google-oauth2", False),
("github_verified_primary", "github", True),
("google_verified", "google-oauth2", True),
]
)
def test_social_login_links_an_existing_account_only_by_a_provider_verified_email(
self, _name: str, provider: str, provider_verified: bool
) -> None:
self.client.logout()
self.user.is_email_verified = False
self.user.save(update_fields=["is_email_verified"])
if provider == "github":
response = self._complete_github_login(
github_id=4242,
emails=[{"email": self.user.email, "primary": True, "verified": provider_verified}],
)
else:
response = self._complete_google_login(email=self.user.email, email_verified=provider_verified)
self.user.refresh_from_db()
is_linked = UserSocialAuth.objects.filter(user=self.user, provider=provider).exists()
if provider_verified:
self.assertEqual(self.client.session.get("_auth_user_id"), str(self.user.pk))
self.assertTrue(is_linked)
else:
self.assertTrue(response["Location"].startswith("/login?error_code=social_login_failure"))
self.assertNotIn("_auth_user_id", self.client.session)
self.assertFalse(is_linked)
self.assertTrue(self.user.check_password(cast(str, self.CONFIG_PASSWORD)))
self.assertFalse(self.user.is_email_verified)
@parameterized.expand(
[
("github_unverified", "github", False, False, 200, UNVERIFIED_SOCIAL_EMAIL_ERROR),
("github_public_email_lookup_fails", "github", False, True, 502, GITHUB_EMAIL_LOOKUP_ERROR),
("google_unverified", "google-oauth2", False, False, 200, UNVERIFIED_SOCIAL_EMAIL_ERROR),
("google_claim_missing", "google-oauth2", None, False, 200, UNVERIFIED_SOCIAL_EMAIL_ERROR),
]
)
def test_social_signup_refuses_an_email_the_provider_has_not_verified(
self,
_name: str,
provider: str,
email_verified: bool | None,
has_public_email: bool,
emails_status: int,
expected_error: str,
) -> None:
self.client.logout()
email = "[email protected]"
if provider == "github":
response = self._complete_github_login(
github_id=5151,
emails=[{"email": email, "primary": True, "verified": email_verified}],
emails_status=emails_status,
profile_email=email if has_public_email else None,
)
else:
response = self._complete_google_login(email=email, email_verified=email_verified)
location = urlparse(response["Location"])
self.assertEqual(location.path, "/login")
self.assertEqual(parse_qs(location.query)["error_detail"], [expected_error])
self.assertNotIn("_auth_user_id", self.client.session)
self.assertFalse(User.objects.filter(email=email).exists())
self.assertFalse(UserSocialAuth.objects.filter(provider=provider).exists())
@parameterized.expand(
[
("github", "github", "/settings/user"),
("github_account_connect_next", "github", "/account-connected/github-login?provider=github"),
("google", "google-oauth2", "/settings/user"),
]
)
def test_sso_reauth_with_an_unlinked_unverified_identity_grants_nothing(
self, _name: str, provider: str, next_url: str
) -> None:
last_reauth_at_before = self.client.session[settings.SESSION_LAST_REAUTH_AT_KEY]
login_query = urlencode({"reauth": "true", "next": next_url, "email": self.user.email})
if provider == "github":
response = self._complete_github_login(
github_id=6161,
emails=[{"email": self.user.email, "primary": True, "verified": False}],
login_query=login_query,
)
else:
response = self._complete_google_login(email=self.user.email, email_verified=False, login_query=login_query)
self.assertIn("error_code=social_login_failure", response["Location"])
self.assertEqual(self.client.session[settings.SESSION_LAST_REAUTH_AT_KEY], last_reauth_at_before)
self.assertFalse(UserSocialAuth.objects.filter(user=self.user, provider=provider).exists())
def test_account_connect_path_does_not_skip_verification_when_signed_out(self) -> None:
self.client.logout()
session = self.client.session
session["next"] = "/account-connected/github-login?provider=github"
session.save()
self._complete_github_login(
github_id=7171, emails=[{"email": self.user.email, "primary": True, "verified": False}]
)
self.assertNotIn("_auth_user_id", self.client.session)
self.assertFalse(UserSocialAuth.objects.filter(user=self.user, provider="github").exists())
def test_already_linked_github_identity_logs_in_without_a_verified_email(self) -> None:
self.client.logout()
UserSocialAuth.objects.create(user=self.user, provider="github", uid="4242")
self._complete_github_login(
github_id=4242, emails=[{"email": "[email protected]", "primary": True, "verified": False}]
)
self.assertEqual(self.client.session.get("_auth_user_id"), str(self.user.pk))
def test_existing_session_remains_valid_when_sso_enforced(self):
"""Test that existing password-authenticated sessions remain valid after SSO is enforced"""
self.client.logout()
# Step 1: User logs in with password (no SSO enforcement yet)
response = self.client.post(
"/api/login",
{"email": self.CONFIG_EMAIL, "password": self.CONFIG_PASSWORD},
)
self.assertEqual(response.status_code, status.HTTP_200_OK)
# Step 2: Verify user can access protected endpoints
response = self.client.get("/api/users/@me/")
self.assertEqual(response.status_code, status.HTTP_200_OK)
self.assertEqual(response.json()["email"], self.CONFIG_EMAIL)
# Step 3: Admin enforces SSO for the domain
self.create_enforced_domain()
# Step 4: User's existing session should still work
response = self.client.get("/api/users/@me/")
self.assertEqual(response.status_code, status.HTTP_200_OK)
self.assertEqual(response.json()["email"], self.CONFIG_EMAIL)
# Step 5: User logs out
self.client.logout()
# Step 6: User can no longer log in with password
with self.settings(**GOOGLE_MOCK_SETTINGS):
response = self.client.post(
"/api/login",
{"email": self.CONFIG_EMAIL, "password": self.CONFIG_PASSWORD},
)
self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
self.assertEqual(
response.json(),
{
"type": "validation_error",
"code": "sso_enforced",
"detail": "You can only login with SSO for this account (google-oauth2).",
"attr": None,
},
)
@pytest.mark.skip_on_multitenancy
@override_settings(**SAML_MOCK_SETTINGS)
class TestEESAMLAuthenticationAPI(APILicensedTest):
CONFIG_AUTO_LOGIN = False
organization_domain: OrganizationDomain = None # type: ignore
@classmethod
def setUpTestData(cls):
super().setUpTestData()
cls.organization_domain = OrganizationDomain.objects.create(
domain="posthog.com",
verified_at=timezone.now(),
organization=cls.organization,
jit_provisioning_enabled=True,
)
config = IdentityProviderConfig.objects.create(
organization=cls.organization,
saml_entity_id="http://www.okta.com/exk1ijlhixJxpyEBZ5d7",
saml_acs_url="https://idp.hogflix.io/saml",
saml_x509_cert="""MIIDqDCCApCgAwIBAgIGAXtoc3o9MA0GCSqGSIb3DQEBCwUAMIGUMQswCQYDVQQGEwJVUzETMBEG
A1UECAwKQ2FsaWZvcm5pYTEWMBQGA1UEBwwNU2FuIEZyYW5jaXNjbzENMAsGA1UECgwET2t0YTEU
MBIGA1UECwwLU1NPUHJvdmlkZXIxFTATBgNVBAMMDGRldi0xMzU1NDU1NDEcMBoGCSqGSIb3DQEJ
ARYNaW5mb0Bva3RhLmNvbTAeFw0yMTA4MjExMTIyMjNaFw0zMTA4MjExMTIzMjNaMIGUMQswCQYD
VQQGEwJVUzETMBEGA1UECAwKQ2FsaWZvcm5pYTEWMBQGA1UEBwwNU2FuIEZyYW5jaXNjbzENMAsG
A1UECgwET2t0YTEUMBIGA1UECwwLU1NPUHJvdmlkZXIxFTATBgNVBAMMDGRldi0xMzU1NDU1NDEc
MBoGCSqGSIb3DQEJARYNaW5mb0Bva3RhLmNvbTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoC
ggEBAMb1IcGzor7mGsGR0AsyzQaT0O9S1SVvdkG3z2duEU/I/a4fvaECm9xvVH7TY+RwwXcnkMst
+ZZJVkTtnUGLn0oSbcwJ1iJwWNOctaNlaJtPDLvJTJpFB857D2tU01/zPn8UpBebX8tJSIcvnvyO
Iblums97f9tlsI9GHqX5N1e1TxRg6FB2ba46mgb0EdzLtPxdYDVf8b5+V0EWp0fu5nbu5T4T+1Tq
IVj2F1xwFTdsHnzh7FP92ohRRl8WQuC1BjAJTagGmgtfxQk2MW0Ti7Dl0Ejcwcjp7ezbyOgWLBmA
fJ/Sg/MyEX11+4H+VQ8bGwIYtTM2Hc+W6gnhg4IdIfcCAwEAATANBgkqhkiG9w0BAQsFAAOCAQEA
Ef8AeVm+rbrDqil8GwZz/6mTeSHeJgsYZhJqCsaVkRPe03+NO93fRt28vlDQoz9alzA1I1ikjmfB
W/+x2dFPThR1/G4zGfF5pwU13gW1fse0/bO564f6LrmWYawL8SzwGbtelc9DxPN1X5g8Qk+j4DNm
jSjV4Oxsv3ogajnnGYGv22iBgS1qccK/cg41YkpgfP36HbiwA10xjUMv5zs97Ljep4ejp6yoKrGL
dcKmj4EG6bfcI3KY6wK46JoogXZdHDaFP+WOJNj/pJ165hYsYLcqkJktj/rEgGQmqAXWPOXHmFJb
5FPleoJTchctnzUw+QfmSsLWQ838/lUQsN7FsQ==""",
)
LinkedIdentityProviderConfig.objects.create(
organization_domain=cls.organization_domain, identity_provider_config=config
)
def _assert_saml_login_social_failure_redirect(self, response, error_detail_substring: str) -> None:
"""SocialAuthExceptionMiddleware catches AuthFailed and redirects instead of propagating."""
self.assertEqual(response.status_code, status.HTTP_302_FOUND)
parsed = urlparse(response["Location"])
self.assertEqual(parsed.path, "/login")
qs = parse_qs(parsed.query)
self.assertEqual(qs.get("error_code"), ["social_login_failure"])
self.assertIn(error_detail_substring, qs.get("error_detail", [""])[0])
# SAML Metadata
def test_can_get_saml_metadata(self):
self.client.force_login(self.user)
OrganizationMembership.objects.filter(organization=self.organization, user=self.user).update(
level=OrganizationMembership.Level.ADMIN
)
response = self.client.get("/api/saml/metadata/")
self.assertEqual(response.status_code, status.HTTP_200_OK)
self.assertTrue("/complete/saml/" in response.content.decode())
def test_need_to_be_authenticated_to_get_saml_metadata(self):
response = self.client.get("/api/saml/metadata/")
self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)
self.assertEqual(response.json(), self.unauthenticated_response())
def test_only_admins_can_get_saml_metadata(self):
self.client.force_login(self.user)
response = self.client.get("/api/saml/metadata/")
self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)
self.assertEqual(
response.json(),
self.permission_denied_response("You need to be an administrator or owner to access this resource."),
)
# Login precheck
def test_login_precheck_with_available_but_unenforced_saml(self):
response = self.client.post(
"/api/login/precheck", {"email": "[email protected]"}
) # Note Google OAuth is not configured
self.assertEqual(response.status_code, status.HTTP_200_OK)
self.assertEqual(
response.json(),
{
"sso_enforcement": None,
"saml_available": True,
"oidc_available": False,
"webauthn_credentials": [],
"account_exists": False,
"password_login_available": True,
"social_providers": [],
},
)
# 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.saml_identity_provider_configs.first()
assert config is not None
config.refresh_from_db()
second_domain = OrganizationDomain.objects.create(
domain="posthog.co.uk",
verified_at=timezone.now(),
organization=self.organization,
)
LinkedIdentityProviderConfig.objects.create(organization_domain=second_domain, 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):
self._grant_saml()
config = self.organization_domain.saml_identity_provider_configs.first()
assert config is not None
config.saml_relay_state = str(self.organization_domain.id)
config.save(update_fields=["saml_relay_state"])
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.saml_identity_provider_configs.first()
assert config is not None
config.refresh_from_db()
second_domain = OrganizationDomain.objects.create(
domain="posthog.co.uk",
verified_at=timezone.now(),
organization=self.organization,
)
LinkedIdentityProviderConfig.objects.create(organization_domain=second_domain, 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)
# Assert user is redirected to the IdP's login page
location = response.headers["Location"]
self.assertIn("https://idp.hogflix.io/saml?SAMLRequest=", location)
def test_cannot_initiate_saml_flow_with_multiple_configurations(self):
config = self.organization_domain.saml_identity_provider_configs.first()
assert config is not None
duplicate_config = IdentityProviderConfig.objects.create(
organization=self.organization,
saml_entity_id=config.saml_entity_id,
saml_acs_url=config.saml_acs_url,
saml_x509_cert=config.saml_x509_cert,
)
LinkedIdentityProviderConfig.objects.create(
organization_domain=self.organization_domain, identity_provider_config=duplicate_config
)
response = self.client.get("/login/saml/[email protected]")
self.assertRedirects(response, "/login?error_code=improperly_configured_sso", fetch_redirect_response=False)
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 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 None
config.refresh_from_db()
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(json.loads(cached), {"idp": config.saml_relay_state, "next": next_url})
def test_cannot_initiate_saml_flow_without_target_email_address(self):
"""
We need the email address to know how to route the SAML request.
"""
response = self.client.get("/login/saml/")
self.assertRedirects(response, "/login?error_code=improperly_configured_sso", fetch_redirect_response=False)
def test_cannot_initiate_saml_flow_for_unconfigured_domain(self):
"""
SAML settings have not been configured for the domain.
"""
response = self.client.get("/login/saml/[email protected]")
self.assertRedirects(response, "/login?error_code=improperly_configured_sso", fetch_redirect_response=False)
def test_cannot_initiate_saml_flow_for_unverified_domain(self):
"""
Domain is unverified.
"""
self.organization_domain.verified_at = None
self.organization_domain.save()
response = self.client.get("/login/saml/[email protected]")
self.assertRedirects(response, "/login?error_code=improperly_configured_sso", fetch_redirect_response=False)
# Finish SAML flow (i.e. actual log in)
@time_machine.travel("2021-08-25T22:09:14.252Z", tick=False) # Ensures the SAML timestamp validation passes
def test_can_login_with_saml(self):
user = User.objects.create(email="[email protected]", distinct_id=str(uuid.uuid4()))
response = self.client.get("/login/saml/[email protected]")
self.assertEqual(response.status_code, status.HTTP_302_FOUND)
_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": str(self.organization_domain.id),
},
follow=True,
format="multipart",
)
self.assertEqual(response.status_code, status.HTTP_200_OK) # because `follow=True`
self.assertRedirects(response, "/") # redirect to the home page
# Ensure proper user was assigned
_session = self.client.session
self.assertEqual(_session.get("_auth_user_id"), str(user.pk))
# Test logged in request
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"),
]
)
@time_machine.travel("2021-08-25T22:09:14.252Z", tick=False) # 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))
@time_machine.travel("2021-08-25T22:09:14.252Z", tick=False) # 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: 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("posthog.api.sso.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")
_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")
@time_machine.travel("2021-08-25T23:37:55.345Z", tick=False)
def test_saml_jit_provisioning_and_assertion_with_different_attribute_names(self):
"""
Tests JIT provisioning for creating a user account on the fly.
In addition, tests that the user can log in when the SAML response contains attribute names in one of their alternative forms.
For example in this case we receive the user's first name at `urn:oid:2.5.4.42` instead of `first_name`.
"""
response = self.client.get("/login/saml/[email protected]")
self.assertEqual(response.status_code, status.HTTP_302_FOUND)
_session = self.client.session
_session.update({"saml_state": "ONELOGIN_87856a50b5490e643b1ebef9cb5bf6e78225a3c6"})
_session.save()
with open(
os.path.join(CURRENT_FOLDER, "fixtures/saml_login_response_alt_attribute_names"),
encoding="utf_8",
) as f:
saml_response = f.read()
user_count = User.objects.count()
response = self.client.post(
"/complete/saml/",
{
"SAMLResponse": saml_response,
"RelayState": str(self.organization_domain.id),
},
format="multipart",
follow=True,
)
self.assertEqual(response.status_code, status.HTTP_200_OK) # because `follow=True`
self.assertRedirects(response, "/") # redirect to the home page
# User is created
self.assertEqual(User.objects.count(), user_count + 1)
user = cast(User, User.objects.last())
self.assertEqual(user.first_name, "PostHog")
self.assertEqual(user.email, "[email protected]")
self.assertEqual(user.organization, self.organization)
self.assertEqual(user.team, self.team)
self.assertEqual(user.organization_memberships.count(), 1)
self.assertEqual(
cast(OrganizationMembership, user.organization_memberships.first()).level,
OrganizationMembership.Level.MEMBER,
)
_session = self.client.session
self.assertEqual(_session.get("_auth_user_id"), str(user.pk))
@time_machine.travel("2021-08-25T23:37:55.345Z", tick=False)
def test_saml_jit_provisioning_with_case_insensitive_domain(self):
"""
Tests that JIT provisioning works with case-insensitive domain matching.
This verifies that users with email domains that differ only in case from
the verified domain in the system can still be provisioned automatically.
"""
# Create a new domain with uppercase characters
original_domain = self.organization_domain.domain
uppercase_email = f"engineering@{original_domain.upper()}"
response = self.client.get(f"/login/saml/?email={uppercase_email}")
self.assertEqual(response.status_code, status.HTTP_302_FOUND)
_session = self.client.session
_session.update({"saml_state": "ONELOGIN_87856a50b5490e643b1ebef9cb5bf6e78225a3c6"})
_session.save()
with open(
os.path.join(CURRENT_FOLDER, "fixtures/saml_login_response_alt_attribute_names"),
encoding="utf_8",
) as f:
saml_response = f.read()
user_count = User.objects.count()
response = self.client.post(
"/complete/saml/",
{
"SAMLResponse": saml_response,
"RelayState": str(self.organization_domain.id),
},
format="multipart",
follow=True,
)
self.assertEqual(response.status_code, status.HTTP_200_OK) # because `follow=True`
self.assertRedirects(response, "/") # redirect to the home page
# User is created despite the case difference in domain
self.assertEqual(User.objects.count(), user_count + 1)
user = cast(User, User.objects.last())
self.assertEqual(user.email, uppercase_email.lower()) # The SSO middleware will make this lowercase
self.assertEqual(user.organization, self.organization)
self.assertEqual(user.team, self.team)
self.assertEqual(user.organization_memberships.count(), 1)
self.assertEqual(
cast(OrganizationMembership, user.organization_memberships.first()).level,
OrganizationMembership.Level.MEMBER,
)
_session = self.client.session
self.assertEqual(_session.get("_auth_user_id"), str(user.pk))
@time_machine.travel("2021-08-25T22:09:14.252Z", tick=False)
def test_cannot_login_with_improperly_signed_payload(self):
config = self.organization_domain.saml_identity_provider_configs.first()
assert config is not None
config.saml_x509_cert = """MIIDPjCCAiYCCQC864/0fftWQTANBgkqhkiG9w0BAQsFADBhMQswCQYDVQQGEwJV
UzELMAkGA1UECAwCVVMxCzAJBgNVBAcMAlVTMQswCQYDVQQKDAJVUzELMAkGA1UE
CwwCVVMxCzAJBgNVBAMMAlVTMREwDwYJKoZIhvcNAQkBFgJVUzAeFw0yMTA4MjYw
MDAxMzNaFw0zMTA4MjYwMDAxMzNaMGExCzAJBgNVBAYTAlVTMQswCQYDVQQIDAJV
UzELMAkGA1UEBwwCVVMxCzAJBgNVBAoMAlVTMQswCQYDVQQLDAJVUzELMAkGA1UE
AwwCVVMxETAPBgkqhkiG9w0BCQEWAlVTMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8A
MIIBCgKCAQEA25s1++GpP9vcXKJ+SN/xdlvPYLir3yMZd/bRfolygQ4BbuzCbqKv
04AGzKfwV11HXxjtQAU/KDtXuVRa+3vZroWcK01GL1C1aH/x0Q2Wy4XZ8Ooi7NlF
MME6vbCIBmXuo4TNouE/VFTz6ntwDNopIdlGDq4M60tFeoT99eDD4OhoCSaIo0aH
2s14CzF0sec3W742yuMHCVyTDrxFzkjMel/CdoNzysvwrqvkGYtLYJn2GSUIoCpG
y6N5CaVkNpAinNSeHKP9qN/z9hSsDNgz0QuTwZ2BxfDWtwJmRJzdQ3Oeq6RlniNY
BBI71zpuQhPeAlyoBg0wG+2ikiCllGug7wIDAQABMA0GCSqGSIb3DQEBCwUAA4IB
AQB8ytXAmU4oYjANiEJVVO5LZUCx3OrY/P1OX73eoXi624yj7xvhaa7whlk1SSL/
2ks8NZNLBFJbUwShdpzR2X+7AlvsLHmodAMq2Oj5x8O+mFB/6DBl0r40NAAsuzVw
2shE4kRi4RXVB0KiyBuExry5YSVTUu8spG4/oTQYJNZFZoSfsHS2mTyprBqqca1j
yh4jGarFborxwACgg6fCiMbHVq8qlcSkRvSW03u89s3Y4mxhMX3F4AZb56ddyfMk
LERK8jfXCMVmWPTy830CtQaZX2AJyBwHG4ElP2BOZNbFAvGzrKaBmK2Ym/OJxkhx
YotAcSbU3p5bzd11wpyebYHB"""
config.save()
response = self.client.get("/login/saml/[email protected]")
self.assertEqual(response.status_code, status.HTTP_302_FOUND)
_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()
user_count = User.objects.count()
response = self.client.post(
"/complete/saml/",
{
"SAMLResponse": saml_response,
"RelayState": str(self.organization_domain.id),
},
format="multipart",
follow=False,
)
self._assert_saml_login_social_failure_redirect(response, "Signature validation failed. SAML Response rejected")
self.assertEqual(User.objects.count(), user_count)
# Test logged in request fails
response = self.client.get("/api/users/@me/")
self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)
@time_machine.travel("2021-08-25T22:09:14.252Z", tick=False)
def test_cannot_signup_with_saml_if_jit_provisioning_is_disabled(self):
self.organization_domain.jit_provisioning_enabled = False
self.organization_domain.save()
response = self.client.get("/login/saml/[email protected]")
self.assertEqual(response.status_code, status.HTTP_302_FOUND)
_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()
user_count = User.objects.count()
response = self.client.post(
"/complete/saml/",
{
"SAMLResponse": saml_response,
"RelayState": str(self.organization_domain.id),
},
format="multipart",
follow=True,
)
self.assertEqual(response.status_code, status.HTTP_200_OK) # because `follow=True`
self.assertRedirects(response, "/login?error_code=jit_not_enabled") # show the appropriate login error
# User is created
self.assertEqual(User.objects.count(), user_count)
# Test logged in request fails
response = self.client.get("/api/users/@me/")
self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)
@time_machine.travel("2021-08-25T23:53:51.000Z", tick=False)
def test_cannot_create_account_without_first_name_in_payload(self):
response = self.client.get("/login/saml/[email protected]")
self.assertEqual(response.status_code, status.HTTP_302_FOUND)
_session = self.client.session
_session.update({"saml_state": "ONELOGIN_87856a50b5490e643b1ebef9cb5bf6e78225a3c6"})
_session.save()
with open(
os.path.join(CURRENT_FOLDER, "fixtures/saml_login_response_no_first_name"),
encoding="utf_8",
) as f:
saml_response = f.read()
user_count = User.objects.count()
with self.assertRaises(ValidationError) as e:
response = self.client.post(
"/complete/saml/",
{
"SAMLResponse": saml_response,
"RelayState": str(self.organization_domain.id),
},
format="multipart",
follow=True,
)
self.assertEqual(
str(e.exception),
"{'name': ['This field is required and was not provided by the IdP.']}",
)
self.assertEqual(User.objects.count(), user_count)
@time_machine.travel("2021-08-25T22:09:14.252Z", tick=False)
def test_cannot_login_with_saml_on_unverified_domain(self):
User.objects.create(email="[email protected]", distinct_id=str(uuid.uuid4()))
response = self.client.get("/login/saml/[email protected]")
self.assertEqual(response.status_code, status.HTTP_302_FOUND)
# Note we "unverify" the domain after the initial request because we want to test the actual login process (not SAML initiation)
self.organization_domain.verified_at = None
self.organization_domain.save()
_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": str(self.organization_domain.id),
},
follow=False,
format="multipart",
)
self._assert_saml_login_social_failure_redirect(
response,
"Authentication request is invalid. Invalid RelayState.",
)
# Assert user is not logged in
response = self.client.get("/api/users/@me/")
self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)
def test_saml_can_be_enforced(self):
self.organization.available_product_features = [
{"key": AvailableFeature.SAML, "name": AvailableFeature.SAML},
{"key": AvailableFeature.SSO_ENFORCEMENT, "name": AvailableFeature.SSO_ENFORCEMENT},
]
self.organization.save()
User.objects.create_and_join(
organization=self.organization,
email="[email protected]",
password=self.CONFIG_PASSWORD,
)
# Can log in regularly with SAML configured
response = self.client.post(
"/api/login",
{"email": "[email protected]", "password": self.CONFIG_PASSWORD},
)
self.assertEqual(response.status_code, status.HTTP_200_OK)
self.assertEqual(response.json(), {"success": True})
# Forcing only SAML disables regular API password login
self.organization_domain.sso_enforcement = "saml"
self.organization_domain.save()
response = self.client.post(
"/api/login",
{"email": "[email protected]", "password": self.CONFIG_PASSWORD},
)
self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
self.assertEqual(
response.json(),
{
"type": "validation_error",
"code": "sso_enforced",
"detail": "You can only login with SSO for this account (saml).",
"attr": None,
},
)
# Login precheck returns SAML info
response = self.client.post("/api/login/precheck", {"email": "[email protected]"})
self.assertEqual(response.status_code, status.HTTP_200_OK)
self.assertEqual(
response.json(),
{
"sso_enforcement": "saml",
"saml_available": True,
"oidc_available": False,
"webauthn_credentials": [],
"account_exists": True,
"password_login_available": True,
"social_providers": [],
},
)
config = self.organization_domain.saml_identity_provider_configs.first()
assert config is not None
config.saml_x509_cert = ""
config.save()
response = self.client.post("/api/login/precheck", {"email": "[email protected]"})
self.assertEqual(
response.json(),
{
"sso_enforcement": None,
"saml_available": False,
"oidc_available": False,
"webauthn_credentials": [],
"account_exists": True,
"password_login_available": True,
"social_providers": [],
},
)
def test_cannot_use_saml_without_enterprise_license(self):
self.organization.available_product_features = [
{"key": AvailableFeature.SSO_ENFORCEMENT, "name": AvailableFeature.SSO_ENFORCEMENT}
]
self.organization.save()
# Enforcement is ignored
self.organization_domain.sso_enforcement = "saml"
self.organization_domain.save()
response = self.client.post("/api/login/precheck", {"email": self.CONFIG_EMAIL})
self.assertEqual(response.status_code, status.HTTP_200_OK)
self.assertEqual(
response.json(),
{
"sso_enforcement": None,
"saml_available": False,
"oidc_available": False,
"webauthn_credentials": [],
"account_exists": True,
"password_login_available": True,
"social_providers": [],
},
)
# Cannot start SAML flow - sso_login catches AuthFailed and redirects
response = self.client.get("/login/saml/[email protected]")
self.assertRedirects(response, "/login?error_code=improperly_configured_sso", fetch_redirect_response=False)
# Attempting to use SAML fails
_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": str(self.organization_domain.id),
},
follow=False,
format="multipart",
)
self._assert_saml_login_social_failure_redirect(
response,
"Your organization does not have the required license to use SAML.",
)
@time_machine.travel("2021-08-25T22:09:14.252Z", tick=False)
def test_saml_login_rejects_email_domain_not_matching_organization_domain(self):
from posthog.models import Organization
User.objects.create(email="[email protected]", distinct_id=str(uuid.uuid4()))
other_org = Organization.objects.create(name="Other Org")
other_org.available_product_features = [{"key": AvailableFeature.SAML, "name": AvailableFeature.SAML}]
other_org.save()
other_domain = OrganizationDomain.objects.create(
domain="other.com",
verified_at=timezone.now(),
organization=other_org,
jit_provisioning_enabled=True,
)
my_config = self.organization_domain.saml_identity_provider_configs.first()
assert my_config is not None
other_config = IdentityProviderConfig.objects.create(
organization=other_org,
saml_entity_id=my_config.saml_entity_id,
saml_acs_url=my_config.saml_acs_url,
saml_x509_cert=my_config.saml_x509_cert,
)
LinkedIdentityProviderConfig.objects.create(
organization_domain=other_domain, identity_provider_config=other_config
)
response = self.client.get("/login/saml/[email protected]")
self.assertEqual(response.status_code, status.HTTP_302_FOUND)
_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": str(other_config.saml_relay_state),
},
follow=False,
format="multipart",
)
self._assert_saml_login_social_failure_redirect(response, "does not match the configured domain")
response = self.client.get("/api/users/@me/")
self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)
# Remove after we figure out saml / xmlsec issues
# Test login with SAML on dev prod before removing
def test_xmlsec_and_lxml(self):
import lxml
import xmlsec
assert "1.3.17" == cast(str, getattr(xmlsec, "__version__", None))
assert "6.0.2" == lxml.__version__
class TestCustomGoogleOAuth2(APILicensedTest):
def setUp(self):
super().setUp()
self.google_oauth = CustomGoogleOAuth2()
self.details = {"email": "[email protected]"}
self.sub = "google-oauth2|123456789"
def _mock_strategy(self, get_params: dict[str, str]) -> object:
mock_strategy = type("MockStrategy", (), {})()
mock_strategy.request_get = lambda: get_params
mock_strategy.setting = lambda name, default=None, backend=None: default
return mock_strategy
def test_auth_extra_arguments_without_email(self):
"""Test that auth_extra_arguments returns base arguments when no email is provided."""
self.google_oauth.strategy = self._mock_strategy({}) # type: ignore[assignment] # ty: ignore[invalid-assignment]
extra_args = self.google_oauth.auth_extra_arguments()
self.assertEqual(extra_args["prompt"], "select_account")
# Should only contain base arguments from parent class, no login_hint
self.assertNotIn("login_hint", extra_args)
def test_auth_extra_arguments_with_email(self):
"""Test that auth_extra_arguments adds login_hint when email is provided."""
self.google_oauth.strategy = self._mock_strategy({"email": "[email protected]"}) # type: ignore[assignment] # ty: ignore[invalid-assignment]
extra_args = self.google_oauth.auth_extra_arguments()
self.assertEqual(extra_args["login_hint"], "[email protected]")
self.assertEqual(extra_args["prompt"], "select_account")
def test_auth_extra_arguments_reauth_does_not_force_select_account(self):
"""Test that reauth flow does not force account picker prompt."""
self.google_oauth.strategy = self._mock_strategy({"reauth": "true"}) # type: ignore[assignment] # ty: ignore[invalid-assignment]
extra_args = self.google_oauth.auth_extra_arguments()
self.assertNotIn("prompt", extra_args)
def test_auth_extra_arguments_preserves_existing_prompt(self):
"""Test that auth_extra_arguments appends select_account to existing prompt values."""
self.google_oauth.strategy = self._mock_strategy({}) # type: ignore[assignment] # ty: ignore[invalid-assignment]
with patch("posthog.api.sso.GoogleOAuth2.auth_extra_arguments", return_value={"prompt": "consent"}):
extra_args = self.google_oauth.auth_extra_arguments()
self.assertEqual(extra_args["prompt"], "consent select_account")
def test_get_user_id_existing_user_with_sub(self):
"""Test that a user with sub as uid continues using that sub."""
# Create user with sub as uid
UserSocialAuth.objects.create(provider="google-oauth2", uid=self.sub, user=self.user)
response = {"email": "[email protected]", "sub": self.sub}
uid = self.google_oauth.get_user_id(self.details, response)
self.assertEqual(uid, self.sub)
# Verify no migration occurred (count should be 1)
self.assertEqual(UserSocialAuth.objects.filter(provider="google-oauth2").count(), 1)
# Verify uid is still sub
self.assertEqual(UserSocialAuth.objects.get(provider="google-oauth2").uid, self.sub)
def test_get_user_id_migrates_email_to_sub(self):
"""Test that a user with email as uid gets migrated to using sub."""
# Create user with email as uid (legacy format)
social_auth = UserSocialAuth.objects.create(provider="google-oauth2", uid="[email protected]", user=self.user)
response = {"email": "[email protected]", "email_verified": True, "sub": self.sub}
uid = self.google_oauth.get_user_id(self.details, response)
self.assertEqual(uid, self.sub)
# Verify the uid was updated
social_auth.refresh_from_db()
self.assertEqual(social_auth.uid, self.sub)
@parameterized.expand([("unverified", False), ("claim_missing", None)])
def test_get_user_id_does_not_migrate_legacy_uid_for_an_unverified_email(
self, _name: str, email_verified: bool | None
) -> None:
social_auth = UserSocialAuth.objects.create(provider="google-oauth2", uid="[email protected]", user=self.user)
response: dict[str, Any] = {"email": "[email protected]", "sub": self.sub}
if email_verified is not None:
response["email_verified"] = email_verified
with self.assertRaises(AuthFailed):
self.google_oauth.get_user_id(self.details, response)
social_auth.refresh_from_db()
self.assertEqual(social_auth.uid, "[email protected]")
def test_get_user_id_new_user_uses_sub(self):
"""Test that a new user gets sub as uid."""
response = {"email": "[email protected]", "sub": self.sub}
uid = self.google_oauth.get_user_id(self.details, response)
self.assertEqual(uid, self.sub)
# Verify no UserSocialAuth objects were created
self.assertEqual(UserSocialAuth.objects.filter(provider="google-oauth2").count(), 0)
def test_get_user_id_missing_sub_raises_error(self):
"""Test that missing sub in response raises ValueError."""
response = {
"email": "[email protected]",
# no sub provided
}
with self.assertRaises(ValueError) as e:
self.google_oauth.get_user_id(self.details, response)
self.assertEqual(str(e.exception), "Google OAuth response missing 'sub' claim")
class TestSSOEnforcement(APILicensedTest):
"""Test SSO enforcement across different auth methods"""
CONFIG_AUTO_LOGIN = False
def setUp(self):
super().setUp()
# Create a user with the domain we'll be testing
self.test_email = "[email protected]"
self.test_user = User.objects.create_and_join(self.organization, self.test_email, self.CONFIG_PASSWORD)
@override_settings(**SAML_MOCK_SETTINGS, **GOOGLE_MOCK_SETTINGS)
def test_cannot_use_social_auth_when_saml_is_required(self):
"""Test that Google OAuth2 fails when SAML is enforced"""
from posthog.api.sso import social_auth_allowed
# Create domain with SAML enforcement
domain = OrganizationDomain.objects.create(
domain="testdomain.com",
organization=self.organization,
verified_at=timezone.now(),
sso_enforcement="saml",
)
config = IdentityProviderConfig.objects.create(
organization=self.organization,
config_scope="saml",
domain_scope="all",
saml_entity_id="https://idp.example.com",
saml_acs_url="https://idp.example.com/saml",
saml_x509_cert="test-certificate",
)
LinkedIdentityProviderConfig.objects.create(organization_domain=domain, identity_provider_config=config)
# Test that Google OAuth2 is blocked
with self.assertRaises(AuthFailed) as context:
social_auth_allowed(
backend=type("MockBackend", (), {"name": "google-oauth2"})(),
details={"email": self.test_email},
response={},
)
self.assertEqual(context.exception.args[0], "saml_sso_enforced")
# Test that GitHub is also blocked
with self.assertRaises(AuthFailed) as context:
social_auth_allowed(
backend=type("MockBackend", (), {"name": "github"})(), details={"email": self.test_email}, response={}
)
self.assertEqual(context.exception.args[0], "saml_sso_enforced")
@override_settings(**SAML_MOCK_SETTINGS, **GOOGLE_MOCK_SETTINGS)
def test_other_social_auth_blocked_with_google_enforcement(self):
"""Test other social auth methods are blocked, including saml, when Google is enforced"""
from posthog.api.sso import social_auth_allowed
OrganizationDomain.objects.create(
domain="testdomain.com",
organization=self.organization,
verified_at=timezone.now(),
sso_enforcement="google-oauth2",
)
# Test that GitHub auth is blocked
with self.assertRaises(AuthFailed) as context:
social_auth_allowed(
backend=type("MockBackend", (), {"name": "github"})(), details={"email": self.test_email}, response={}
)
self.assertEqual(context.exception.args[0], "google_sso_enforced")
# Test that SAML auth is blocked
with self.assertRaises(AuthFailed) as context:
social_auth_allowed(
backend=type("MockBackend", (), {"name": "saml"})(),
details={"email": self.test_email},
response={},
)
self.assertEqual(context.exception.args[0], "google_sso_enforced")
# Test that Google OAuth2 is allowed
try:
social_auth_allowed(
backend=type("MockBackend", (), {"name": "google-oauth2"})(),
details={"email": self.test_email},
response={},
)
except AuthFailed:
self.fail("Google OAuth2 should be allowed when Google OAuth2 is enforced")
@time_machine.travel(
"2021-08-25T22:09:14.252Z", tick=False
) # Same timestamp as other SAML tests using this fixture
@override_settings(**SAML_MOCK_SETTINGS, **GOOGLE_MOCK_SETTINGS)
def test_saml_auth_flow_blocked_when_google_oauth2_enforced(self):
"""Integration test: Verify SAML auth flow is blocked when Google OAuth2 is enforced"""
org_domain_saml = OrganizationDomain.objects.create(
domain="posthog.com",
organization=self.organization,
verified_at=timezone.now(),
sso_enforcement="google-oauth2",
)
config = IdentityProviderConfig.objects.create(
organization=self.organization,
saml_entity_id="http://www.okta.com/exk1ijlhixJxpyEBZ5d7",
saml_acs_url="https://my.posthog.app/complete/saml/",
saml_x509_cert="""MIIDqDCCApCgAwIBAgIGAXtoc3o9MA0GCSqGSIb3DQEBCwUAMIGUMQswCQYDVQQGEwJVUzETMBEG
A1UECAwKQ2FsaWZvcm5pYTEWMBQGA1UEBwwNU2FuIEZyYW5jaXNjbzENMAsGA1UECgwET2t0YTEU
MBIGA1UECwwLU1NPUHJvdmlkZXIxFTATBgNVBAMMDGRldi0xMzU1NDU1NDEcMBoGCSqGSIb3DQEJ
ARYNaW5mb0Bva3RhLmNvbTAeFw0yMTA4MjExMTIyMjNaFw0zMTA4MjExMTIzMjNaMIGUMQswCQYD
VQQGEwJVUzETMBEGA1UECAwKQ2FsaWZvcm5pYTEWMBQGA1UEBwwNU2FuIEZyYW5jaXNjbzENMAsG
A1UECgwET2t0YTEUMBIGA1UECwwLU1NPUHJvdmlkZXIxFTATBgNVBAMMDGRldi0xMzU1NDU1NDEc
MBoGCSqGSIb3DQEJARYNaW5mb0Bva3RhLmNvbTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoC
ggEBAMb1IcGzor7mGsGR0AsyzQaT0O9S1SVvdkG3z2duEU/I/a4fvaECm9xvVH7TY+RwwXcnkMst
+ZZJVkTtnUGLn0oSbcwJ1iJwWNOctaNlaJtPDLvJTJpFB857D2tU01/zPn8UpBebX8tJSIcvnvyO
Iblums97f9tlsI9GHqX5N1e1TxRg6FB2ba46mgb0EdzLtPxdYDVf8b5+V0EWp0fu5nbu5T4T+1Tq
IVj2F1xwFTdsHnzh7FP92ohRRl8WQuC1BjAJTagGmgtfxQk2MW0Ti7Dl0Ejcwcjp7ezbyOgWLBmA
fJ/Sg/MyEX11+4H+VQ8bGwIYtTM2Hc+W6gnhg4IdIfcCAwEAATANBgkqhkiG9w0BAQsFAAOCAQEA
Ef8AeVm+rbrDqil8GwZz/6mTeSHeJgsYZhJqCsaVkRPe03+NO93fRt28vlDQoz9alzA1I1ikjmfB
W/+x2dFPThR1/G4zGfF5pwU13gW1fse0/bO564f6LrmWYawL8SzwGbtelc9DxPN1X5g8Qk+j4DNm
jSjV4Oxsv3ogajnnGYGv22iBgS1qccK/cg41YkpgfP36HbiwA10xjUMv5zs97Ljep4ejp6yoKrGL
dcKmj4EG6bfcI3KY6wK46JoogXZdHDaFP+WOJNj/pJ165hYsYLcqkJktj/rEgGQmqAXWPOXHmFJb
5FPleoJTchctnzUw+QfmSsLWQ838/lUQsN7FsQ==""",
)
LinkedIdentityProviderConfig.objects.create(
organization_domain=org_domain_saml, identity_provider_config=config
)
# Set the SAML state in session (required for SAML 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()
# Attempt to complete SAML authentication
# The SAML response contains [email protected] which has google-oauth2 enforcement
response = self.client.post(
"/complete/saml/",
{
"SAMLResponse": saml_response,
"RelayState": str(org_domain_saml.id),
},
format="multipart",
follow=False, # Don't follow redirects so we can check the redirect URL
)
# Should be redirected to login with SSO enforcement error
self.assertEqual(response.status_code, status.HTTP_302_FOUND)
self.assertIn("/login?error_code=google_sso_enforced", response.headers["Location"])