Skip to content

: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.

chore: invert org-domain idp-config lookup for idp logic (#88789)

Reece Jones2f29a566461f
diff --git a/ee/api/authentication.py b/ee/api/authentication.py
index a2f44e154347..dffeb5a67aa6 100644
--- a/ee/api/authentication.py
+++ b/ee/api/authentication.py
@@ -1,7 +1,7 @@
import re
import json
import base64
-from typing import Any, Literal, TypedDict, Union, cast
+from typing import Any, Literal, TypedDict, cast
from uuid import UUID
from django.core.exceptions import ValidationError as DjangoValidationError
@@ -190,25 +190,20 @@ class MultitenantSAMLAuth(SAMLAuth):
return None
return (OneLogin_Saml2_XML.element_text(issuer_nodes[0]) or "").strip() or None
- def get_idp(self, organization_domain_or_id: Union["OrganizationDomain", str, None]) -> SAMLIdentityProvider:
- if organization_domain_or_id is None:
+ def get_idp(self, identity_provider_config_or_id: IdentityProviderConfig | str | None) -> SAMLIdentityProvider:
+ if identity_provider_config_or_id is None:
saml_logger.warning("saml_idp_lookup_failed", idp_id="None")
raise AuthFailed(self, "Authentication request is invalid. Invalid RelayState.")
- if isinstance(organization_domain_or_id, OrganizationDomain):
- try:
- idp_config = organization_domain_or_id.saml_identity_provider_configs.get()
- except IdentityProviderConfig.DoesNotExist:
- raise AuthFailed(self, "SAML not configured for this domain.")
- except IdentityProviderConfig.MultipleObjectsReturned:
- raise AuthFailed(self, "Multiple SAML configurations apply to this domain.")
+ if isinstance(identity_provider_config_or_id, IdentityProviderConfig):
+ idp_config = identity_provider_config_or_id
else:
try:
# nosemgrep: idor-lookup-without-org (pre-auth SAML flow, lookup by config identifier on verified configs)
idp_config = (
IdentityProviderConfig.objects.filter(
has_verified_organization_domain_q(),
- saml_relay_state=organization_domain_or_id,
+ saml_relay_state=identity_provider_config_or_id,
)
.distinct()
.get()
@@ -218,7 +213,7 @@ class MultitenantSAMLAuth(SAMLAuth):
IdentityProviderConfig.MultipleObjectsReturned,
DjangoValidationError,
):
- saml_logger.warning("saml_idp_lookup_failed", idp_id=str(organization_domain_or_id))
+ saml_logger.warning("saml_idp_lookup_failed", idp_id=str(identity_provider_config_or_id))
raise AuthFailed(self, "Authentication request is invalid. Invalid RelayState.")
if not idp_config.organization.is_feature_available(AvailableFeature.SAML):
@@ -243,29 +238,26 @@ class MultitenantSAMLAuth(SAMLAuth):
)
def auth_url(self):
- """
- Overridden to use the config from the relevant OrganizationDomain
- Get the URL to which we must redirect in order to
- authenticate the user
- """
email = self.strategy.request_data().get("email")
if not email:
raise AuthMissingParameter(self, "email")
- instance = OrganizationDomain.objects.get_verified_for_email_address(email=email)
-
- if not instance or not instance.saml_identity_provider_configs.exists():
+ idp_configs = list(IdentityProviderConfig.objects.saml_for_email(email)[:2])
+ if len(idp_configs) == 0:
saml_logger.warning("saml_not_configured", **_saml_log_context(email))
raise AuthFailed(self, "SAML not configured for this user.")
+ if len(idp_configs) > 1:
+ saml_logger.warning("saml_multiple_configs", **_saml_log_context(email))
+ raise AuthFailed(self, "Multiple SAML configurations found for this user.")
+ idp_config = idp_configs[0]
saml_logger.info(
"saml_auth_redirect",
- domain=instance.domain,
- organization_id=str(instance.organization_id),
- **_saml_log_context(email, instance.organization_id),
+ organization_id=str(idp_config.organization_id),
+ **_saml_log_context(email, idp_config.organization_id),
)
- identity_provider = self.get_idp(instance)
+ identity_provider = self.get_idp(idp_config)
auth = self._create_saml_auth(idp=identity_provider)
# `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
diff --git a/ee/api/test/test_authentication.py b/ee/api/test/test_authentication.py
index 30aefc458247..ebbb2375eb12 100644
--- a/ee/api/test/test_authentication.py
+++ b/ee/api/test/test_authentication.py
@@ -650,6 +650,23 @@ class TestEESAMLAuthenticationAPI(APILicensedTest):
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 in RelayState
diff --git a/posthog/api/authentication.py b/posthog/api/authentication.py
index 5500b7dce86a..3f97f9044781 100644
--- a/posthog/api/authentication.py
+++ b/posthog/api/authentication.py
@@ -68,7 +68,7 @@ from posthog.helpers.two_factor_session import (
)
from posthog.helpers.user_devices import has_valid_known_device_cookie
from posthog.helpers.verified_domain_enforcement import VERIFIED_DOMAIN_REQUIRED_ERROR, resolve_login_organization
-from posthog.models import OrganizationDomain, User
+from posthog.models import IdentityProviderConfig, OrganizationDomain, User
from posthog.models.activity_logging import signal_handlers # imported for its signal receivers too
from posthog.models.webauthn_credential import WebauthnCredential
from posthog.passkey import generate_passkey_authentication_options, verify_passkey_authentication_response
@@ -437,7 +437,7 @@ class LoginPrecheckSerializer(serializers.Serializer):
for cred in credentials
]
- saml_available = OrganizationDomain.objects.get_is_saml_available_for_email(email)
+ saml_available = IdentityProviderConfig.objects.get_is_saml_available_for_email(email)
return {
"sso_enforcement": OrganizationDomain.objects.get_sso_enforcement_for_email_address(email),
diff --git a/posthog/api/id_jag.py b/posthog/api/id_jag.py
index 8021c4fc0d34..de43d52f193b 100644
--- a/posthog/api/id_jag.py
+++ b/posthog/api/id_jag.py
@@ -8,6 +8,7 @@ to us, or get a personal API token to programmatically access our API.
"""
import uuid
+from dataclasses import field
from datetime import UTC, datetime, timedelta
from typing import Any, TypedDict, cast
@@ -21,7 +22,8 @@ from oauth2_provider.utils import jwk_from_pem
from rest_framework import status
from posthog.constants import AvailableFeature
-from posthog.models.organization_domain import OrganizationDomain
+from posthog.dataclasses import frozen
+from posthog.models.identity_provider_config import IdentityProviderConfig
from posthog.models.user import User
from posthog.scopes import get_oauth_scopes_supported
from posthog.security.url_validation import is_url_allowed
@@ -112,6 +114,20 @@ class IdJagClaims(TypedDict, total=False):
exp: int
+@frozen
+class _VerifiedIdJag:
+ claims: IdJagClaims
+ provider_name: str
+ identity_provider_config: IdentityProviderConfig
+
+
+@frozen
+class IssuedAccessToken:
+ access_token: str = field(repr=False)
+ granted_scopes: list[str]
+ expires_in_seconds: int
+
+
def _get_site_url() -> str:
"""The deployment's public URL — used as `aud` for inbound ID-JAGs and as
`iss`/`aud` for the access tokens we mint. Stripped of trailing slash so
@@ -233,12 +249,11 @@ def _get_scopes(id_jag_scopes: list[str], requested_scopes: list[str] | None) ->
return intersected
-def _verify_and_extract_id_jag_token(assertion: str) -> tuple[IdJagClaims, str, "OrganizationDomain"]:
+def _verify_and_extract_id_jag_token(assertion: str) -> _VerifiedIdJag:
"""
Verifies the provided ID-JAG token against the IdP's JWKS and returns the
claims, the provider name we stamp into the issued access token's `sub`,
- and the `OrganizationDomain` row that owns the trusted IdP config (used to
- bind the issued access token to a single organization).
+ and the IdP configuration that binds the token to one organization.
Raises `IdJagError` (with the right RFC 6749 error code) on every documented
failure mode at https://xaa.dev/docs/error-codes
@@ -269,7 +284,7 @@ def _verify_and_extract_id_jag_token(assertion: str) -> tuple[IdJagClaims, str,
id_jag_email = unverified_claims.get("email") or unverified_claims.get("sub") or ""
- resolution = OrganizationDomain.objects.get_verified_for_email_address_and_issuer(id_jag_email, issuer)
+ resolution = IdentityProviderConfig.objects.get_id_jag_for_request(id_jag_email, issuer)
if resolution.organization_domain is None or resolution.identity_provider_config is None or resolution.error:
# Do not echo the specific reason — see GENERIC_ID_JAG_REJECTION.
logger.info(
@@ -280,10 +295,10 @@ def _verify_and_extract_id_jag_token(assertion: str) -> tuple[IdJagClaims, str,
)
raise InvalidGrantError(GENERIC_ID_JAG_REJECTION)
- org_domain = resolution.organization_domain
idp_config = resolution.identity_provider_config
+ organization_domain = resolution.organization_domain
expected_issuer = (idp_config.id_jag_issuer_url or "").rstrip("/")
- provider_name = org_domain.domain
+ provider_name = organization_domain.domain
try:
jwks_client = _get_jwks_client(expected_issuer, jwks_url=idp_config.id_jag_jwks_url or None)
@@ -385,22 +400,22 @@ def _verify_and_extract_id_jag_token(assertion: str) -> tuple[IdJagClaims, str,
verified_email = claims.get("email") or claims.get("sub") or ""
- # The user must be an active member of the *specific* organization whose
- # OrganizationDomain pinned this IdP — not merely a member of any org that
- # also verified this domain. The issued access token is scoped to
- # `org_domain.organization_id` downstream, so membership must be enforced
- # on that exact org.
+ # Membership must match the configuration's organization because the access token is scoped to it.
is_member = User.objects.filter(
is_active=True,
email__iexact=verified_email,
- organization_membership__organization_id=org_domain.organization.pk,
+ organization_membership__organization_id=idp_config.organization_id,
).exists()
if not is_member:
raise InvalidGrantError(
"ID-JAG sub is not an active member of the organization that owns this IdP configuration"
)
- return claims, provider_name, org_domain
+ return _VerifiedIdJag(
+ claims=claims,
+ provider_name=provider_name,
+ identity_provider_config=idp_config,
+ )
def _construct_access_token_payload(
@@ -471,32 +486,40 @@ def _parse_scope_list(value: str | list[str] | None) -> list[str]:
def issue_access_token(
assertion: str, requested_scope: str | list[str] | None, request_client_id: str | None
-) -> tuple[str, list[str], int]:
+) -> IssuedAccessToken:
"""
Validate an ID-JAG `assertion` and mint an access token. Pulled out of the
view so the same path is exercised by tests, batch tools, and the HTTP
- handler. Returns `(access_token, granted_scopes, expires_in_seconds)`.
+ handler.
"""
- claims, provider_name, org_domain = _verify_and_extract_id_jag_token(assertion)
+ verified_id_jag = _verify_and_extract_id_jag_token(assertion)
- organization = org_domain.organization
+ organization = verified_id_jag.identity_provider_config.organization
if not organization.is_feature_available(AvailableFeature.XAA_AUTHENTICATION):
raise AccessDeniedError("ID-JAG (XAA) is not enabled for this organization")
- if request_client_id and request_client_id != claims.get("client_id"):
+ if request_client_id and request_client_id != verified_id_jag.claims.get("client_id"):
raise InvalidGrantError("ID-JAG client_id doesn't match the authenticating client")
- id_jag_scopes = _parse_scope_list(claims.get("scope"))
+ id_jag_scopes = _parse_scope_list(verified_id_jag.claims.get("scope"))
parsed_requested = _parse_scope_list(requested_scope) if requested_scope is not None else None
known_scopes = set(get_oauth_scopes_supported())
sanitized_id_jag_scopes = [s for s in id_jag_scopes if s in known_scopes]
granted = _get_scopes(sanitized_id_jag_scopes, parsed_requested)
- verified_email = claims.get("email") or claims.get("sub") or ""
+ verified_email = verified_id_jag.claims.get("email") or verified_id_jag.claims.get("sub") or ""
payload = _construct_access_token_payload(
- claims, provider_name, granted, organization.pk, cast(str, verified_email)
+ verified_id_jag.claims,
+ verified_id_jag.provider_name,
+ granted,
+ organization.pk,
+ cast(str, verified_email),
)
token = _construct_access_token(payload)
- return token, granted, settings.ID_JAG_ACCESS_TOKEN_TTL_SECONDS
+ return IssuedAccessToken(
+ access_token=token,
+ granted_scopes=granted,
+ expires_in_seconds=settings.ID_JAG_ACCESS_TOKEN_TTL_SECONDS,
+ )
diff --git a/posthog/api/oauth/views.py b/posthog/api/oauth/views.py
index 9e9a6d1b4e13..b0aa84d732d2 100644
--- a/posthog/api/oauth/views.py
+++ b/posthog/api/oauth/views.py
@@ -1764,9 +1764,7 @@ class OAuthTokenView(TokenView):
request_client_id = request.POST.get("client_id")
try:
- token, granted, expires_in_seconds = id_jag.issue_access_token(
- assertion, requested_scope, request_client_id
- )
+ issued_access_token = id_jag.issue_access_token(assertion, requested_scope, request_client_id)
except id_jag.IdJagError as e:
logger.info("id_jag_token_rejected", error=e.error_code, description=e.description)
self._capture_token_rejected(id_jag.JWT_BEARER_GRANT_TYPE, request_client_id or "", e.error_code)
@@ -1784,8 +1782,8 @@ class OAuthTokenView(TokenView):
properties={
"grant_type": id_jag.JWT_BEARER_GRANT_TYPE,
"client_id": request_client_id or "",
- "granted_scopes": " ".join(granted),
- "granted_scope_count": len(granted),
+ "granted_scopes": " ".join(issued_access_token.granted_scopes),
+ "granted_scope_count": len(issued_access_token.granted_scopes),
"$process_person_profile": False,
**(get_region_info() or {}),
},
@@ -1793,10 +1791,10 @@ class OAuthTokenView(TokenView):
return JsonResponse(
{
- "access_token": token,
+ "access_token": issued_access_token.access_token,
"token_type": "Bearer",
- "expires_in": expires_in_seconds,
- "scope": " ".join(granted),
+ "expires_in": issued_access_token.expires_in_seconds,
+ "scope": " ".join(issued_access_token.granted_scopes),
}
)
diff --git a/posthog/api/test/test_id_jag.py b/posthog/api/test/test_id_jag.py
index 6ee814f0a231..7badcd25f432 100644
--- a/posthog/api/test/test_id_jag.py
+++ b/posthog/api/test/test_id_jag.py
@@ -50,6 +50,7 @@ _AS_PRIVATE_KEY_PEM = generate_rsa_private_key_pem()
_IDP_ISSUER = "https://idp.example.com"
_VERIFIED_DOMAIN = "example.com"
_PROVIDER_NAME = _VERIFIED_DOMAIN
+_IDP_CONFIG_NAME = "Example IdP"
_SITE_URL = "https://posthog.test"
_AUTH_SERVER_URL = _SITE_URL
_RESOURCE_URL = _SITE_URL
@@ -124,7 +125,9 @@ class TestIdJagTokenEndpoint(APIBaseTest):
domain=_VERIFIED_DOMAIN,
verified_at=timezone.now(),
)
- config = IdentityProviderConfig.objects.create(organization=cls.organization, id_jag_issuer_url=_IDP_ISSUER)
+ config = IdentityProviderConfig.objects.create(
+ organization=cls.organization, name=_IDP_CONFIG_NAME, id_jag_issuer_url=_IDP_ISSUER
+ )
LinkedIdentityProviderConfig.objects.create(organization_domain=domain, identity_provider_config=config)
def setUp(self) -> None:
@@ -663,17 +666,19 @@ class TestIdJagTokenEndpoint(APIBaseTest):
# that the domain isn't bound at all.
self.assertEqual(resp.json()["error_description"], "ID-JAG could not be verified")
- def test_issuer_match_is_slash_normalized(self) -> None:
- # Store the issuer without trailing slash; ID-JAG carries one. The
- # comparison must succeed because we rstrip on both sides — otherwise
- # legitimate IdPs that always include a trailing slash on `iss` would
- # be impossible to bind.
+ @parameterized.expand(
+ [
+ (_IDP_ISSUER, f"{_IDP_ISSUER}/"),
+ (f"{_IDP_ISSUER}///", _IDP_ISSUER),
+ ]
+ )
+ def test_issuer_match_is_slash_normalized(self, configured_issuer: str, assertion_issuer: str) -> None:
domain = OrganizationDomain.objects.get(domain=_VERIFIED_DOMAIN)
config = domain.identity_provider_configs_for_scope(ConfigScope.ID_JAG).first()
- config.id_jag_issuer_url = _IDP_ISSUER
+ config.id_jag_issuer_url = configured_issuer
config.save()
- assertion = _make_id_jag(issuer=_IDP_ISSUER + "/")
+ assertion = _make_id_jag(issuer=assertion_issuer)
resp = self._post_token({"grant_type": JWT_BEARER_GRANT_TYPE, "assertion": assertion})
self.assertEqual(resp.status_code, status.HTTP_200_OK)
@@ -756,14 +761,14 @@ class TestIdJagTokenEndpoint(APIBaseTest):
def test_issue_access_token_helper(self) -> None:
assertion = _make_id_jag()
- token, granted, expires_in = issue_access_token(
+ issued_access_token = issue_access_token(
assertion, requested_scope="feature_flag:read", request_client_id=_RESOURCE_CLIENT_ID
)
- self.assertEqual(granted, ["feature_flag:read"])
- self.assertEqual(expires_in, 300)
+ self.assertEqual(issued_access_token.granted_scopes, ["feature_flag:read"])
+ self.assertEqual(issued_access_token.expires_in_seconds, 300)
# Token decodable with the AS public key.
jwt.decode(
- token,
+ issued_access_token.access_token,
_public_key_for(_AS_PRIVATE_KEY_PEM),
algorithms=["RS256"],
audience=_RESOURCE_URL,
diff --git a/posthog/models/identity_provider_config.py b/posthog/models/identity_provider_config.py
index 9dbdbc93e10f..ff1946cd3242 100644
--- a/posthog/models/identity_provider_config.py
+++ b/posthog/models/identity_provider_config.py
@@ -1,11 +1,13 @@
import uuid
-from typing import TYPE_CHECKING, cast
+from typing import TYPE_CHECKING, Optional, cast
from django.contrib.postgres.fields import ArrayField
from django.db import models
import structlog
+from posthog.constants import AvailableFeature
+from posthog.dataclasses import frozen
from posthog.models.activity_logging.model_activity import ModelActivityMixin
from posthog.models.utils import UUIDModel
@@ -23,6 +25,13 @@ class DomainScope(models.TextChoices):
DEFAULT_DOMAIN_SCOPE = DomainScope.SELECTED
+@frozen
+class IDJagIdentityProviderResolution:
+ organization_domain: Optional["OrganizationDomain"]
+ identity_provider_config: Optional["IdentityProviderConfig"]
+ error: Optional[str]
+
+
def has_verified_organization_domain_q() -> models.Q:
return models.Q(linked_identity_provider_configs__organization_domain__verified_at__isnull=False) | models.Q(
domain_scope=DomainScope.ALL, organization__domains__verified_at__isnull=False
@@ -49,6 +58,86 @@ def saml_configured_q() -> models.Q:
)
+class IdentityProviderConfigQuerySet(models.QuerySet["IdentityProviderConfig"]):
+ def for_scope(self, config_scope: str) -> "IdentityProviderConfigQuerySet":
+ return self.filter(models.Q(config_scope=config_scope) | models.Q(config_scope__isnull=True))
+
+ def with_verified_domain_for_email(self, email: str) -> "IdentityProviderConfigQuerySet":
+ if "@" not in email:
+ return self.none()
+
+ domain = email.rsplit("@", 1)[-1]
+ explicitly_linked = models.Q(
+ linked_identity_provider_configs__organization_domain__domain__iexact=domain,
+ linked_identity_provider_configs__organization_domain__verified_at__isnull=False,
+ )
+ organization_wide = models.Q(
+ domain_scope=DomainScope.ALL,
+ organization__domains__domain__iexact=domain,
+ organization__domains__verified_at__isnull=False,
+ )
+ return self.filter(explicitly_linked | organization_wide).distinct()
+
+ def saml_for_email(self, email: str) -> "IdentityProviderConfigQuerySet":
+ return self.for_scope(ConfigScope.SAML).filter(saml_configured_q()).with_verified_domain_for_email(email)
+
+
+class IdentityProviderConfigManager(models.Manager["IdentityProviderConfig"]):
+ def get_queryset(self) -> IdentityProviderConfigQuerySet:
+ return IdentityProviderConfigQuerySet(self.model, using=self._db)
+
+ def saml_for_email(self, email: str) -> IdentityProviderConfigQuerySet:
+ return self.get_queryset().saml_for_email(email)
+
+ def get_id_jag_for_request(self, email: str, issuer: str) -> IDJagIdentityProviderResolution:
+ normalized_issuer = (issuer or "").rstrip("/")
+ issuer_configs = (
+ self.get_queryset()
+ .for_scope(ConfigScope.ID_JAG)
+ .annotate(
+ normalized_id_jag_issuer_url=models.Func(
+ "id_jag_issuer_url",
+ models.Value("/"),
+ function="RTRIM",
+ output_field=models.CharField(),
+ )
+ )
+ .filter(normalized_id_jag_issuer_url=normalized_issuer)
+ )
+
+ matching: list[tuple[IdentityProviderConfig, OrganizationDomain]] = []
+ if "@" in email:
+ domain = email.rsplit("@", 1)[-1]
+ for config in issuer_configs:
+ verified_domains = config.organization_domains.filter(domain__iexact=domain, verified_at__isnull=False)
+ matching.extend((config, organization_domain) for organization_domain in verified_domains)
+
+ if not matching:
+ return IDJagIdentityProviderResolution(
+ organization_domain=None,
+ identity_provider_config=None,
+ error="ID-JAG email domain is not a verified domain associated with this IdP configuration",
+ )
+
+ if len(matching) > 1:
+ return IDJagIdentityProviderResolution(
+ organization_domain=None,
+ identity_provider_config=None,
+ error="ID-JAG configuration is ambiguous: multiple configurations match this request",
+ )
+
+ config, organization_domain = matching[0]
+ return IDJagIdentityProviderResolution(
+ organization_domain=organization_domain,
+ identity_provider_config=config,
+ error=None,
+ )
+
+ def get_is_saml_available_for_email(self, email: str) -> bool:
+ configs = self.get_queryset().saml_for_email(email).select_related("organization")
+ return any(config.organization.is_feature_available(AvailableFeature.SAML) for config in configs)
+
+
class IdentityProviderConfig(ModelActivityMixin, UUIDModel):
"""
Identity provider (IdP) configuration for an organization.
@@ -62,6 +151,8 @@ class IdentityProviderConfig(ModelActivityMixin, UUIDModel):
IdP columns on `OrganizationDomain` are no longer written to — they're frozen.
"""
+ objects = IdentityProviderConfigManager()
+
organization = models.ForeignKey(
"posthog.Organization", on_delete=models.CASCADE, related_name="identity_provider_configs"
)
diff --git a/posthog/models/organization_domain.py b/posthog/models/organization_domain.py
index 0c95e7ec97f1..f0169eaaba0b 100644
--- a/posthog/models/organization_domain.py
+++ b/posthog/models/organization_domain.py
@@ -9,7 +9,6 @@ import structlog
import dns.resolver
from posthog.constants import AvailableFeature
-from posthog.dataclasses import frozen
from posthog.dns_utils import dnssec_resolver
from posthog.models import Organization
from posthog.models.activity_logging.model_activity import ModelActivityMixin
@@ -28,23 +27,6 @@ def generate_verification_challenge() -> str:
return secrets.token_urlsafe(32)
-@frozen
-class IDJagIdentityProviderResolution:
- organization_domain: Optional["OrganizationDomain"]
- identity_provider_config: Optional[IdentityProviderConfig]
- error: Optional[str]
-
-
-def resolves_to_identity_provider_config_q(
- configs: models.QuerySet[IdentityProviderConfig],
-) -> models.Q:
- explicitly_linked = LinkedIdentityProviderConfig.objects.filter(
- organization_domain=models.OuterRef("pk"), identity_provider_config__in=configs
- )
- organization_wide = configs.filter(domain_scope=DomainScope.ALL, organization_id=models.OuterRef("organization_id"))
- return models.Q(models.Exists(explicitly_linked)) | models.Q(models.Exists(organization_wide))
-
-
class OrganizationDomainManager(models.Manager):
def verified_domains(self):
# TODO: Verification becomes stale on Cloud if not reverified after a certain period.
@@ -62,87 +44,6 @@ class OrganizationDomainManager(models.Manager):
domain = email[email.index("@") + 1 :]
return self.verified_domains().filter(domain__iexact=domain).first()
- def get_verified_for_email_address_and_issuer(self, email: str, issuer: str) -> IDJagIdentityProviderResolution:
- if "@" not in email:
- return IDJagIdentityProviderResolution(
- organization_domain=None,
- identity_provider_config=None,
- error="ID-JAG sub email domain is not a verified domain for any PostHog organization",
- )
- domain = email[email.index("@") + 1 :].lower()
- normalized_issuer = (issuer or "").rstrip("/")
-
- verified_for_domain = list(self.verified_domains().filter(domain__iexact=domain))
- if not verified_for_domain:
- return IDJagIdentityProviderResolution(
- organization_domain=None,
- identity_provider_config=None,
- error="ID-JAG sub email domain is not a verified domain for any PostHog organization",
- )
-
- configured = [
- (organization_domain, config)
- for organization_domain in verified_for_domain
- for config in organization_domain.identity_provider_configs_for_scope(ConfigScope.ID_JAG)
- if (config.id_jag_issuer_url or "").rstrip("/")
- ]
- if not configured:
- return IDJagIdentityProviderResolution(
- organization_domain=None,
- identity_provider_config=None,
- error="ID-JAG is not configured for this domain (id_jag_issuer_url is unset)",
- )
-
- matching = [
- (organization_domain, config)
- for organization_domain, config in configured
- if (config.id_jag_issuer_url or "").rstrip("/") == normalized_issuer
- ]
- if not matching:
- return IDJagIdentityProviderResolution(
- organization_domain=None,
- identity_provider_config=None,
- error="ID-JAG iss does not match the IdP configured for this email's domain",
- )
-
- if len(matching) > 1:
- return IDJagIdentityProviderResolution(
- organization_domain=None,
- identity_provider_config=None,
- error="ID-JAG configuration is ambiguous: multiple OrganizationDomains share this (domain, issuer)",
- )
-
- organization_domain, config = matching[0]
- return IDJagIdentityProviderResolution(
- organization_domain=organization_domain,
- identity_provider_config=config,
- error=None,
- )
-
- def get_is_saml_available_for_email(self, email: str) -> bool:
- """
- Returns whether SAML is available for a specific email address.
- """
- domain = email[email.index("@") + 1 :]
- saml_configs = IdentityProviderConfig.objects.filter(
- models.Q(config_scope=ConfigScope.SAML) | models.Q(config_scope__isnull=True)
- ).filter(saml_configured_q())
- query = (
- self.verified_domains()
- .filter(domain__iexact=domain)
- .filter(resolves_to_identity_provider_config_q(saml_configs))
- .values_list("organization__available_product_features", flat=True)
- .first()
- )
-
- if query is None:
- return False
-
- for feature in query:
- if feature.get("key") == AvailableFeature.SAML:
- return True
- return False
-
def get_sso_enforcement_for_email_address(
self, email: str, organization: Organization | None = None
) -> Optional[str]:
diff --git a/posthog/test/test_identity_provider_config.py b/posthog/test/test_identity_provider_config.py
index ab5fd6c6e198..1dafcd836ab4 100644
--- a/posthog/test/test_identity_provider_config.py
+++ b/posthog/test/test_identity_provider_config.py
@@ -110,7 +110,7 @@ class TestIdentityProviderConfig(BaseTest):
domain._complete_verification()
self._link(domain, config)
- assert OrganizationDomain.objects.get_is_saml_available_for_email("[email protected]")
+ assert IdentityProviderConfig.objects.get_is_saml_available_for_email("[email protected]")
LinkedIdentityProviderConfig.objects.filter(organization_domain=domain).delete()
- assert not OrganizationDomain.objects.get_is_saml_available_for_email("[email protected]")
+ assert not IdentityProviderConfig.objects.get_is_saml_available_for_email("[email protected]")