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.

fix(auth): send rejected sso invites to login instead of a 500 (#121168)

Alex Lider25b12f6b980c
diff --git a/frontend/src/scenes/authentication/shared/loginErrorMessages.tsx b/frontend/src/scenes/authentication/shared/loginErrorMessages.tsx
index 09c55e3fbd68..f7d32e51c323 100644
--- a/frontend/src/scenes/authentication/shared/loginErrorMessages.tsx
+++ b/frontend/src/scenes/authentication/shared/loginErrorMessages.tsx
@@ -42,6 +42,11 @@ export const ERROR_MESSAGES: Record<string, string | JSX.Element> = {
"You signed in with a different account. Please try again with the account you're logged in as.",
invalid_invite:
'This invite link is no longer valid. It may have expired or been revoked. Please ask your administrator for a new invite.',
+ invite_email_mismatch:
+ 'This invite was sent to a different email address. Log in with that address, or ask your administrator for a new invite.',
+ invite_already_member: "You're already a member of this organization. Log in to continue.",
+ invite_email_taken:
+ 'An account with this email address already belongs to this organization. Log in with that account to continue.',
social_login_failure: 'Login failed. Please try again or contact your administrator.',
access_blocked:
"We couldn't sign you in. If you think this is a mistake, contact support and quote the code access_blocked.",
diff --git a/posthog/api/test/test_signup.py b/posthog/api/test/test_signup.py
index f4d35575d677..65f1cbc80b92 100644
--- a/posthog/api/test/test_signup.py
+++ b/posthog/api/test/test_signup.py
@@ -1529,6 +1529,20 @@ class TestSignupAPI(APIBaseTest):
self.assertTrue(OrganizationInvite.objects.filter(id=invite.id).exists())
self.assertFalse(User.objects.filter(email="[email protected]").exists())
+ @mock.patch("social_core.backends.base.BaseAuth.request")
+ @mock.patch("posthog.api.authentication.get_instance_available_sso_providers")
+ @pytest.mark.ee
+ def test_sso_invite_for_another_email_redirects_to_login(self, mock_sso_providers, mock_request):
+ mock_sso_providers.return_value = {"google-oauth2": True}
+ org = Organization.objects.create(name="Test org")
+ invite = OrganizationInvite.objects.create(organization=org, target_email="[email protected]")
+
+ response = self._complete_sso_with_invite_id(mock_request, str(invite.id), "[email protected]")
+
+ self.assertRedirects(response, "/login?error_code=invite_email_mismatch")
+ self.assertTrue(OrganizationInvite.objects.filter(id=invite.id).exists())
+ self.assertFalse(User.objects.filter(email="[email protected]").exists())
+
@mock.patch("social_core.backends.base.BaseAuth.request")
@mock.patch("posthog.api.authentication.get_instance_available_sso_providers")
@pytest.mark.ee
diff --git a/posthog/helpers/sso.py b/posthog/helpers/sso.py
index 0f18a1d91d42..e3543fefe2aa 100644
--- a/posthog/helpers/sso.py
+++ b/posthog/helpers/sso.py
@@ -46,21 +46,26 @@ def is_sso_reauth_complete(request: HttpRequest) -> bool:
return getattr(request, "session", {}).get("reauth") == "true"
-def _with_error_code(url: str, error_code: str) -> str:
- """Attach `error_code` to a relative URL, keeping it ahead of any fragment.
+def _with_error_code(url: str, error_code: str, error_detail: str | None = None) -> str:
+ """Attach `error_code`, and `error_detail` when given, to a relative URL, keeping them ahead of any fragment.
`next` is the whole path the modal was opened from, fragment included, and a query string placed
after the `#` reads as fragment text - leaving the frontend with no error code to report.
"""
path, fragment_separator, fragment = url.partition("#")
joiner = "&" if "?" in path else "?"
- # url is either a literal or a same-origin path validated by get_safe_next_url, and the error code
- # is urlencoded, so this is a redirect target, not HTML
+ params = {"error_code": error_code}
+ if error_detail:
+ params["error_detail"] = error_detail
+ # url is either a literal or a same-origin path validated by get_safe_next_url, and the params
+ # are urlencoded, so this is a redirect target, not HTML
# nosemgrep: python.flask.security.audit.directly-returned-format-string.directly-returned-format-string
- return f"{path}{joiner}{urlencode({'error_code': error_code})}{fragment_separator}{fragment}"
+ return f"{path}{joiner}{urlencode(params)}{fragment_separator}{fragment}"
-def sso_failure_redirect_url(request: HttpRequest, error_code: str, is_reauth: bool | None = None) -> str:
+def sso_failure_redirect_url(
+ request: HttpRequest, error_code: str, is_reauth: bool | None = None, *, error_detail: str | None = None
+) -> str:
"""Where to send the browser when an SSO flow fails.
A re-auth still has a valid session, so it goes back to the page that opened the modal with the
@@ -72,6 +77,6 @@ def sso_failure_redirect_url(request: HttpRequest, error_code: str, is_reauth: b
if is_reauth:
next_url = get_safe_next_url(request.GET.get("next") or getattr(request, "session", {}).get("next"), request)
- return _with_error_code(next_url or "/", error_code)
+ return _with_error_code(next_url or "/", error_code, error_detail)
- return _with_error_code("/login", error_code)
+ return _with_error_code("/login", error_code, error_detail)
diff --git a/posthog/helpers/tests/test_sso.py b/posthog/helpers/tests/test_sso.py
new file mode 100644
index 000000000000..15bc8af8c086
--- /dev/null
+++ b/posthog/helpers/tests/test_sso.py
@@ -0,0 +1,12 @@
+from django.test import RequestFactory, SimpleTestCase
+
+from posthog.helpers.sso import sso_failure_redirect_url
+
+
+class TestSsoFailureRedirectUrl(SimpleTestCase):
+ def test_error_detail_stays_ahead_of_the_fragment_on_reauth(self):
+ request = RequestFactory().get("/complete/google-oauth2/", {"next": "/settings/user?tab=security#section"})
+
+ url = sso_failure_redirect_url(request, "social_login_failure", is_reauth=True, error_detail="Nope.")
+
+ self.assertEqual(url, "/settings/user?tab=security&error_code=social_login_failure&error_detail=Nope.#section")
diff --git a/posthog/middleware.py b/posthog/middleware.py
index b9b15620af04..a8a95453f5bf 100644
--- a/posthog/middleware.py
+++ b/posthog/middleware.py
@@ -10,7 +10,6 @@ from datetime import UTC, datetime, timedelta
from enum import StrEnum
from ipaddress import ip_address, ip_network
from typing import Optional, cast
-from urllib.parse import urlencode
from django.conf import settings
from django.contrib.auth import BACKEND_SESSION_KEY, logout
@@ -34,6 +33,7 @@ from django_prometheus.middleware import Metrics
from loginas.utils import is_impersonated_session, restore_original_login
from opentelemetry import trace
from prometheus_client import Counter, Histogram
+from rest_framework.exceptions import ValidationError
from social_core.backends.utils import load_backends
from social_core.exceptions import AuthCanceled, AuthException, AuthFailed
from statshog.defaults.django import statsd
@@ -1424,6 +1424,14 @@ class SocialAuthExceptionMiddleware:
_AUTH_FAILED_PREFIX = "Authentication failed: "
+ # `OrganizationInvite.validate()` codes mapped to login page error codes.
+ _INVITE_ERROR_CODES = {
+ "expired": "invalid_invite",
+ "invalid_recipient": "invite_email_mismatch",
+ "user_already_member": "invite_already_member",
+ "existing_email_address": "invite_email_taken",
+ }
+
def __init__(self, get_response):
self.get_response = get_response
@@ -1456,12 +1464,23 @@ class SocialAuthExceptionMiddleware:
# Handle any other social auth exception by passing the error detail to the frontend
if isinstance(exception, AuthException):
error_detail = self._get_error_detail(exception)
- url = sso_failure_redirect_url(request, "social_login_failure")
- separator = "&" if "?" in url else "?"
- return redirect(f"{url}{separator}{urlencode({'error_detail': error_detail})}")
+ return redirect(sso_failure_redirect_url(request, "social_login_failure", error_detail=error_detail))
+
+ # The social auth pipeline validates invites with DRF exceptions. The callback is a plain
+ # Django view, so without this branch they render the 500 page.
+ if isinstance(exception, ValidationError):
+ error_code = self._INVITE_ERROR_CODES.get(self._error_code(exception), "social_login_failure")
+ return redirect(sso_failure_redirect_url(request, error_code))
return None
+ def _error_code(self, exception: ValidationError) -> str:
+ # `OrganizationInvite.validate()` raises ValidationError("message", code=...), which DRF stores
+ # as a one-element list. Any other shape gets the generic login message.
+ codes = exception.get_codes()
+ first = codes[0] if isinstance(codes, list) and codes else None
+ return first if isinstance(first, str) else "unknown"
+
def _get_error_detail(self, exception: AuthException) -> str:
error_detail = str(exception).strip()
diff --git a/posthog/test/test_middleware.py b/posthog/test/test_middleware.py
index cc56fe152585..3c019f27a76e 100644
--- a/posthog/test/test_middleware.py
+++ b/posthog/test/test_middleware.py
@@ -26,6 +26,7 @@ from loginas import settings as la_settings
from parameterized import parameterized
from prometheus_client import REGISTRY
from rest_framework import status
+from rest_framework.exceptions import ValidationError
from social_core.backends.base import BaseAuth
from social_core.exceptions import AuthCanceled, AuthFailed, AuthMissingParameter
@@ -44,7 +45,7 @@ from posthog.middleware import (
)
from posthog.models.activity_logging.activity_log import ActivityLog
from posthog.models.organization import Organization, OrganizationMembership
-from posthog.models.organization_invite import OrganizationInvite
+from posthog.models.organization_invite import InviteExpiredException, OrganizationInvite
from posthog.models.team import Team
from posthog.models.user import User
from posthog.run_mode import derive_run_mode
@@ -2507,6 +2508,36 @@ class TestSocialAuthExceptionMiddleware(SimpleTestCase):
AuthFailed(_social_auth_backend(), "access_blocked"),
"/login?error_code=access_blocked",
),
+ (
+ "expired_invite",
+ "/complete/google-oauth2/",
+ InviteExpiredException(),
+ "/login?error_code=invalid_invite",
+ ),
+ (
+ "invite_for_another_email",
+ "/complete/google-oauth2/",
+ ValidationError("This invite is intended for another email address.", code="invalid_recipient"),
+ "/login?error_code=invite_email_mismatch",
+ ),
+ (
+ "already_a_member",
+ "/complete/google-oauth2/",
+ ValidationError("You already are a member of this organization.", code="user_already_member"),
+ "/login?error_code=invite_already_member",
+ ),
+ (
+ "invite_email_already_in_org",
+ "/complete/saml/",
+ ValidationError("Another user with this email already belongs.", code="existing_email_address"),
+ "/login?error_code=invite_email_taken",
+ ),
+ (
+ "unknown_validation_code",
+ "/complete/google-oauth2/",
+ ValidationError("Something else.", code="something_else"),
+ "/login?error_code=social_login_failure",
+ ),
]
)
def test_redirects_with_expected_url(self, _name, path, exception, expected_url):