:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(auth): don't sign people out when SSO re-auth fails (#79752)
Reece Jones9a5dc77721cf
diff --git a/ee/api/test/test_authentication.py b/ee/api/test/test_authentication.pyindex 9921a58d78f8..988c6287ebe4 100644--- a/ee/api/test/test_authentication.py+++ b/ee/api/test/test_authentication.py@@ -3,14 +3,16 @@ import jsonimport uuidimport datetimefrom typing import Any, cast-from urllib.parse import parse_qs, urlparse+from urllib.parse import parse_qs, urlencode, urlparseimport pytestfrom freezegun.api import freeze_timefrom unittest.mock import patch+from django.conf import settingsfrom django.core import mailfrom django.core.exceptions import ValidationError+from django.shortcuts import redirectfrom django.test import override_settingsfrom django.utils import timezone@@ -21,6 +23,7 @@ from social_django.models import UserSocialAuthfrom posthog.constants import AvailableFeaturefrom posthog.models import OrganizationMembership, User+from posthog.models.activity_logging.activity_log import ActivityLogfrom posthog.models.identity_provider_config import IdentityProviderConfigfrom posthog.models.organization_domain import OrganizationDomain@@ -288,6 +291,149 @@ class TestEEAuthenticationAPI(APILicensedTest):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)++ @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) -> str:+ response = self.client.get(f"/login/google-oauth2/?reauth=true&next=/settings/user&email={self.user.email}")+ self.assertEqual(response.status_code, status.HTTP_302_FOUND)+ return self.client.session["google-oauth2_state"]++ @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")++ # 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 test_existing_session_remains_valid_when_sso_enforced(self):"""Test that existing password-authenticated sessions remain valid after SSO is enforced"""self.client.logout()diff --git a/frontend/src/lib/components/TimeSensitiveAuthentication/timeSensitiveAuthenticationLogic.test.ts b/frontend/src/lib/components/TimeSensitiveAuthentication/timeSensitiveAuthenticationLogic.test.tsindex 26476441ffe0..4aafc4952f41 100644--- a/frontend/src/lib/components/TimeSensitiveAuthentication/timeSensitiveAuthenticationLogic.test.ts+++ b/frontend/src/lib/components/TimeSensitiveAuthentication/timeSensitiveAuthenticationLogic.test.ts@@ -1,9 +1,13 @@import { MOCK_DEFAULT_USER } from 'lib/api.mock'+import { router } from 'kea-router'import { expectLogic } from 'kea-test-utils'+import { lemonToast } from '@posthog/lemon-ui'+import { dayjs } from 'lib/dayjs'import { apiStatusLogic } from 'lib/logic/apiStatusLogic'+import { ERROR_MESSAGES } from 'scenes/authentication/shared/loginErrorMessages'import { userLogic } from 'scenes/userLogic'import { initKeaTests } from '~/test/init'@@ -18,12 +22,14 @@ describe('timeSensitiveAuthenticationLogic', () => {beforeEach(() => {initKeaTests()+ jest.spyOn(lemonToast, 'error').mockImplementation(() => null as any)logic = timeSensitiveAuthenticationLogic()logic.mount()})afterEach(() => {logic.unmount()+ jest.restoreAllMocks()})describe('initial state', () => {@@ -152,4 +158,24 @@ describe('timeSensitiveAuthenticationLogic', () => {await expectLogic(logic).toMatchValues({ showAuthenticationModal: false })})})++ describe('failed SSO re-authentication', () => {+ it('should report the error the backend sent back and drop it from the URL', async () => {+ router.actions.push('/settings/user', { error_code: 'reauth_user_mismatch' })++ logic.actions.showSsoReauthenticationError()++ expect(lemonToast.error).toHaveBeenCalledWith(ERROR_MESSAGES.reauth_user_mismatch)+ expect(router.values.searchParams).toEqual({})+ })++ it('should leave unrelated query params alone', async () => {+ router.actions.push('/settings/user', { tab: 'danger-zone' })++ logic.actions.showSsoReauthenticationError()++ expect(lemonToast.error).not.toHaveBeenCalled()+ expect(router.values.searchParams).toEqual({ tab: 'danger-zone' })+ })+ })})diff --git a/frontend/src/lib/components/TimeSensitiveAuthentication/timeSensitiveAuthenticationLogic.ts b/frontend/src/lib/components/TimeSensitiveAuthentication/timeSensitiveAuthenticationLogic.tsindex f2c964fb7076..bd9787a41a87 100644--- a/frontend/src/lib/components/TimeSensitiveAuthentication/timeSensitiveAuthenticationLogic.ts+++ b/frontend/src/lib/components/TimeSensitiveAuthentication/timeSensitiveAuthenticationLogic.ts@@ -3,17 +3,21 @@ import {type UserVerificationRequirement,startAuthentication,} from '@simplewebauthn/browser'-import { MakeLogicType, actions, connect, kea, listeners, path, reducers, selectors } from 'kea'+import { MakeLogicType, actions, afterMount, connect, kea, listeners, path, reducers, selectors } from 'kea'import { forms } from 'kea-forms'import type { DeepPartial, DeepPartialMap, FieldName, ValidationErrorType } from 'kea-forms'import { loaders } from 'kea-loaders'+import { router } from 'kea-router'import { subscriptions } from 'kea-subscriptions'import posthog from 'posthog-js'+import { lemonToast } from '@posthog/lemon-ui'+import api, { ApiError } from 'lib/api'import { Dayjs, dayjs } from 'lib/dayjs'import { apiStatusLogic } from 'lib/logic/apiStatusLogic'import { PrecheckResponseType } from 'scenes/authentication/login/loginLogic'+import { ERROR_MESSAGES } from 'scenes/authentication/shared/loginErrorMessages'import { userLogic } from 'scenes/userLogic'import type { UserType } from '../../../types'@@ -154,6 +158,9 @@ export interface timeSensitiveAuthenticationLogicActions {setTotpAvailable: (available: boolean) => {available: boolean}+ showSsoReauthenticationError: () => {+ value: true+ }submitReauthentication: () => {value: boolean}@@ -211,6 +218,7 @@ export const timeSensitiveAuthenticationLogic = kea<timeSensitiveAuthenticationLsetDismissedReauthentication: (value: boolean) => ({ value }),setRequiresTwoFactor: (value: boolean) => ({ value }),checkReauthentication: true,+ showSsoReauthenticationError: true,beginPasskey2FA: true,checkPasskeysAvailable: true,setTotpAvailable: (available: boolean) => ({ available }),@@ -404,6 +412,16 @@ export const timeSensitiveAuthenticationLogic = kea<timeSensitiveAuthenticationLposthog.capture('reauthentication_modal_dismissed')}},+ showSsoReauthenticationError: () => {+ // A failed SSO re-auth keeps the session and comes back to the page that opened the modal,+ // carrying the reason as a query param (see posthog.helpers.sso.sso_failure_redirect_url).+ const { error_code, error_detail, ...remainingParams } = router.values.searchParams+ if (!error_code || !(error_code in ERROR_MESSAGES)) {+ return+ }+ lemonToast.error(ERROR_MESSAGES[error_code])+ router.actions.replace(router.values.location.pathname, remainingParams, router.values.hashParams)+ },checkReauthentication: () => {if (values.sensitiveSessionExpiresAt.diff(dayjs(), 'seconds') < LOOKAHEAD_EXPIRY_SECONDS) {// Here we try to offer a better UX by forcing re-authentication if they are about to timeout@@ -419,4 +437,7 @@ export const timeSensitiveAuthenticationLogic = kea<timeSensitiveAuthenticationL}},})),+ afterMount(({ actions }) => {+ actions.showSsoReauthenticationError()+ }),])diff --git a/frontend/src/scenes/authentication/shared/loginErrorMessages.tsx b/frontend/src/scenes/authentication/shared/loginErrorMessages.tsxindex ead46c1369a1..58a1e76f254a 100644--- a/frontend/src/scenes/authentication/shared/loginErrorMessages.tsx+++ b/frontend/src/scenes/authentication/shared/loginErrorMessages.tsx@@ -35,6 +35,8 @@ export const ERROR_MESSAGES: Record<string, string | JSX.Element> = {verified_domain_required:"Your organization only allows members with a verified email domain. Contact your organization's admin for access.",oauth_cancelled: "Sign in was cancelled. Please try again when you're ready.",+ reauth_user_mismatch:+ "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.',social_login_failure: 'Login failed. Please try again or contact your administrator.',diff --git a/posthog/api/authentication.py b/posthog/api/authentication.pyindex 22553b850eaf..c6858516ccdc 100644--- a/posthog/api/authentication.py+++ b/posthog/api/authentication.py@@ -50,12 +50,14 @@ from webauthn.helpers.structs import AuthenticatorTransport, PublicKeyCredentialfrom posthog.api.email_verification import EmailVerifier, is_email_verification_disabledfrom posthog.caching.login_device_cache import check_and_cache_login_device+from posthog.constants import AUTH_BACKEND_DISPLAY_NAMESfrom posthog.email import is_email_availablefrom posthog.event_usage import report_user_logged_in, report_user_password_resetfrom posthog.exceptions_capture import capture_exceptionfrom posthog.geoip import get_geoip_propertiesfrom posthog.helpers.dev_login import is_dev_login_allowedfrom posthog.helpers.email_utils import EmailLookupHandler+from posthog.helpers.sso import get_safe_next_url, is_sso_reauth_begin, sso_failure_redirect_urlfrom posthog.helpers.two_factor_session import (CODE_MAX_ATTEMPTS,LOGIN_CODE_VERIFICATION_COUNTER,@@ -67,7 +69,7 @@ from posthog.helpers.two_factor_session import (from posthog.helpers.user_devices import has_valid_known_device_cookiefrom posthog.helpers.verified_domain_enforcement import VERIFIED_DOMAIN_REQUIRED_ERROR, resolve_login_organizationfrom posthog.models import OrganizationDomain, User-from posthog.models.activity_logging import signal_handlers # noqa: F401+from posthog.models.activity_logging import signal_handlers # imported for its signal receivers toofrom posthog.models.webauthn_credential import WebauthnCredentialfrom posthog.passkey import generate_passkey_authentication_options, verify_passkey_authentication_responsefrom posthog.rate_limit import (@@ -130,12 +132,22 @@ def axes_locked_out(*args, **kwargs):def sso_login(request: HttpRequest, backend: str) -> HttpResponse:+ sso_providers = get_instance_available_sso_providers()+ # because SAML is configured at the domain-level, we have to assume it's enabled for someone in the instance+ sso_providers["saml"] = settings.EE_AVAILABLE++ is_reauth = is_sso_reauth_begin(request)++ # Checked before any session mutation below, so a misconfigured provider can never sign anyone out.+ if backend not in sso_providers:+ return redirect(sso_failure_redirect_url(request, "invalid_sso_provider", is_reauth=is_reauth))++ if not sso_providers[backend]:+ return redirect(sso_failure_redirect_url(request, "improperly_configured_sso", is_reauth=is_reauth))+# The one known `connect_from` value is "posthog_code" - what PH Code uses when linking GH profile to PostHog userconnect_from = (request.GET.get("connect_from") or "").strip()- if not connect_from:- # This is the default case - for regular login, we flush the session (log out)- request.session.flush()- else:+ if connect_from:# For linking a social provider, we keep the session and set the next URL to /account-connected/github-login# (see frontend AccountConnected). QueryDict must be copied before mutation (GET is often immutable).query_dict = request.GET.copy()@@ -143,16 +155,12 @@ def sso_login(request: HttpRequest, backend: str) -> HttpResponse:f"/account-connected/github-login?{urlencode({'provider': backend, 'connect_from': connect_from})}")request.GET = query_dict # type: ignore[assignment] # ty: ignore[invalid-assignment]-- sso_providers = get_instance_available_sso_providers()- # because SAML is configured at the domain-level, we have to assume it's enabled for someone in the instance- sso_providers["saml"] = settings.EE_AVAILABLE-- if backend not in sso_providers:- return redirect(f"/login?error_code=invalid_sso_provider")-- if not sso_providers[backend]:- return redirect("/login?error_code=improperly_configured_sso")+ elif not is_reauth:+ # This is the default case - for regular login, we flush the session (log out)+ request.session.flush()+ # Re-auth keeps the session: the user is already signed in, and flushing here would sign them out+ # before the IdP is even contacted, so any hiccup in the round trip would strand them at /login.+ # `social_reauth_complete` grants the step-up on the way back in.try:return auth(request, backend)@@ -160,7 +168,7 @@ def sso_login(request: HttpRequest, backend: str) -> HttpResponse:# AuthConnectionError covers an unreachable IdP or a TLS cert that fails during OIDC discovery -# it's a sibling of AuthFailed (not a subclass), so it would otherwise surface as an unhandled 500.logger.warning("SSO login failed, redirecting to login page", exc_info=e)- return redirect("/login?error_code=improperly_configured_sso")+ return redirect(sso_failure_redirect_url(request, "improperly_configured_sso", is_reauth=is_reauth))class TwoFactorRequired(APIException):@@ -179,17 +187,6 @@ class CodeBasedVerificationRequired(APIException):super().__init__(detail=detail, code=self.default_code)-def get_safe_next_url(next_url: str | None, request: Request) -> str | None:- """Return next_url only when it's a safe same-origin/relative redirect target, else None.-- The value is embedded into emailed verification links, so an unvalidated next- would be an open-redirect / phishing vector.- """- if next_url and url_has_allowed_host_and_scheme(next_url, allowed_hosts={request.get_host()}):- return next_url- return None--def is_email_verified_for_login(user: User, next_url: str | None = None) -> bool:"""Send a verification email when the login policy requires it.@@ -1278,6 +1275,88 @@ class PasswordResetTokenGenerator(DefaultPasswordResetTokenGenerator):password_reset_token_generator = PasswordResetTokenGenerator()+def _sso_reauth_request(strategy: DjangoStrategy) -> HttpRequest | None:+ """The request behind a step-up re-auth of an already signed-in session, or None if it isn't one."""+ if strategy.session_get("reauth") != "true":+ return None++ request = strategy.request+ if not request or not request.user.is_authenticated:+ return None++ return request+++def social_reauth(+ strategy: DjangoStrategy,+ backend,+ details: dict[str, Any] | None = None,+ user: User | None = None,+ social: Any = None,+ **kwargs,+) -> None:+ """Turn away a step-up re-auth that isn't the signed-in user.++ Runs right after `social_user`, so a mismatched identity is rejected before `associate_user` can+ link it to the signed-in account or `social_create_user` can provision anything. The step-up+ itself is granted at the end of the pipeline, by `social_reauth_complete`.+ """+ request = _sso_reauth_request(strategy)+ if not request:+ return++ # An identity that isn't associated with anyone yet resolves to whoever is signed in, so without+ # an email check `associate_user` would silently link a stranger's IdP account to this account.+ identity_email = ((details or {}).get("email") or "").lower()+ identity_is_signed_in_user = (+ user is not None and user.pk == request.user.pk and (social is not None or identity_email == user.email.lower())+ )++ if not identity_is_signed_in_user:+ logger.warning(+ "SSO re-authentication identity mismatch",+ backend=getattr(backend, "name", ""),+ session_user_id=request.user.pk,+ )+ raise AuthFailed(backend, "reauth_user_mismatch")+++def social_reauth_complete(strategy: DjangoStrategy, backend, user: User | None = None, **kwargs) -> None:+ """Grant the step-up, once every other pipeline step has accepted the flow.++ `sso_login` doesn't flush the session for a re-auth, which means `do_complete` takes its+ already-authenticated path and never calls `login()` - so the freshness stamp and the audit entry+ that `login()` would have triggered have to happen here, or the modal would reopen forever.++ This runs last because a step that returns a response aborts the pipeline - domain enforcement in+ `social_create_user` does exactly that - and a refused re-auth must not leave a fresh window, a+ cleared step-up flag, or a `logged_in` entry behind.+ """+ request = _sso_reauth_request(strategy)+ if not request or user is None or user.pk != request.user.pk:+ return++ # Rotate the key the way `login()` would on a fresh sign-in. A step-up window is exactly what a+ # copied session cookie wants, so the identifier that existed before it has to stop working. The+ # session data - and with it the signed-in user - survives the rotation.+ request.session.cycle_key()+ request.session[settings.SESSION_LAST_REAUTH_AT_KEY] = time.time()+ request.session.pop(settings.SESSION_STEP_UP_REQUIRED_KEY, None)++ backend_name = getattr(backend, "name", "")+ try:+ signal_handlers.log_login_activity(+ user,+ request,+ login_method=str(AUTH_BACKEND_DISPLAY_NAMES.get(backend_name, "Unknown")),+ reauth=True,+ )+ except Exception as e:+ # Matching `log_user_login_activity`: a failed audit write must not fail the re-auth itself+ logger.exception("Failed to log SSO re-authentication activity", user_id=user.id, error=e)+ capture_exception(e)++def social_login_notification(strategy: DjangoStrategy, backend, user: User | None = None, is_new: bool = False, **kwargs):diff --git a/posthog/helpers/sso.py b/posthog/helpers/sso.pynew file mode 100644index 000000000000..c2913f55b7a2--- /dev/null+++ b/posthog/helpers/sso.py@@ -0,0 +1,72 @@+from urllib.parse import urlencode++from django.http import HttpRequest+from django.utils.http import url_has_allowed_host_and_scheme+++def get_safe_next_url(next_url: str | None, request: HttpRequest) -> str | None:+ """Return next_url only when it's a safe same-origin/relative redirect target, else None.++ The value is embedded into emailed verification links, so an unvalidated next+ would be an open-redirect / phishing vector.+ """+ if next_url and url_has_allowed_host_and_scheme(next_url, allowed_hosts={request.get_host()}):+ return next_url+ return None+++def _is_authenticated(request: HttpRequest) -> bool:+ # Not every request reaching these helpers has been through AuthenticationMiddleware+ user = getattr(request, "user", None)+ return bool(user and user.is_authenticated)+++def is_sso_reauth_begin(request: HttpRequest) -> bool:+ """Whether an outgoing SSO flow is a step-up re-auth of the session that's already signed in.++ The re-authentication modal appends `reauth=true` to the provider link (see+ TimeSensitiveAuthentication.tsx).+ """+ return _is_authenticated(request) and request.GET.get("reauth") == "true"+++def is_sso_reauth_complete(request: HttpRequest) -> bool:+ """Same question on the way back from the IdP, where the flag lives in the session.++ `do_auth` copies it there on the way out, per `SOCIAL_AUTH_FIELDS_STORED_IN_SESSION`, and clears+ it when the flow didn't ask for a re-auth.+ """+ if not _is_authenticated(request):+ return False+ 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.++ `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+ # 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}"+++def sso_failure_redirect_url(request: HttpRequest, error_code: str, is_reauth: bool | 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+ error attached. /login is wrong for it even as a fallback: the frontend bounces a signed-in user+ off that route (sceneLogic's `onlyUnauthenticated` handling) and drops the error code on the way.+ """+ if is_reauth is None:+ is_reauth = is_sso_reauth_complete(request)++ 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("/login", error_code)diff --git a/posthog/middleware.py b/posthog/middleware.pyindex caf16b1f69bb..9b8e31f4c257 100644--- a/posthog/middleware.py+++ b/posthog/middleware.py@@ -44,6 +44,7 @@ from posthog.constants import AUTH_BACKEND_KEYSfrom posthog.event_usage import get_event_source, get_mcp_properties, sanitize_header_valuefrom posthog.geoip import get_geoip_propertiesfrom posthog.helpers.impersonation import get_original_user_from_session+from posthog.helpers.sso import sso_failure_redirect_urlfrom posthog.helpers.user_devices import set_known_device_cookiefrom posthog.models import Team, Userfrom posthog.models.activity_logging.utils import (@@ -1232,7 +1233,7 @@ class SocialAuthExceptionMiddleware:# Handle AuthCanceled (user cancelled OAuth flow)if isinstance(exception, AuthCanceled):- return redirect("/login?error_code=oauth_cancelled")+ return redirect(sso_failure_redirect_url(request, "oauth_cancelled"))# Handle AuthFailed with specific error codes that have dedicated frontend messagesif isinstance(exception, AuthFailed) and len(exception.args) >= 1:@@ -1243,14 +1244,16 @@ class SocialAuthExceptionMiddleware:"github_sso_enforced","gitlab_sso_enforced","sso_enforced",+ "reauth_user_mismatch",):- return redirect(f"/login?error_code={error}")+ return redirect(sso_failure_redirect_url(request, error))# Handle any other social auth exception by passing the error detail to the frontendif isinstance(exception, AuthException):error_detail = self._get_error_detail(exception)- params = urlencode({"error_code": "social_login_failure", "error_detail": error_detail})- return redirect(f"/login?{params}")+ 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 Nonediff --git a/posthog/models/activity_logging/signal_handlers.py b/posthog/models/activity_logging/signal_handlers.pyindex f032b980916c..2b62b6849e64 100644--- a/posthog/models/activity_logging/signal_handlers.py+++ b/posthog/models/activity_logging/signal_handlers.py@@ -139,38 +139,61 @@ def _determine_login_method(request, was_impersonated):return login_method+def log_login_activity(+ user,+ request: HttpRequest,+ *,+ login_method: str,+ reauth: bool,+ was_impersonated: bool = False,+ log_user=None,+ item_id: str | None = None,+) -> None:+ """Write the `logged_in` audit entry.++ Also called directly for an SSO step-up re-auth, which keeps its session and so never fires+ `user_logged_in` (see `posthog.api.authentication.social_reauth`).+ """+ organization_id = user.current_organization_id++ if organization_id is None:+ logger.info("Skipping login activity log - user has no organization", user_id=user.id)+ return++ log_activity(+ organization_id=organization_id,+ team_id=None,+ user=log_user or user,+ item_id=item_id or str(user.id),+ scope="User",+ activity="logged_in",+ detail=Detail(+ name=user.email,+ changes=[],+ context=UserLoginContext(+ login_method=login_method,+ ip_address=get_ip_address(request),+ user_agent=get_short_user_agent(request),+ reauth=reauth,+ ),+ ),+ was_impersonated=was_impersonated,+ )++@receiver(user_logged_in)def log_user_login_activity(sender, user, request: HttpRequest, **kwargs): # noqa: ARG001try:was_impersonated, log_user, item_id, _ = _detect_impersonation_for_login(user, request)- ip_address = get_ip_address(request)- user_agent = get_short_user_agent(request)- reauth = request.session.get("reauth") == "true"- organization_id = user.current_organization_id-- if organization_id is None:- logger.info("Skipping login activity log - user has no organization", user_id=user.id)- return-- log_activity(- organization_id=organization_id,- team_id=None,- user=log_user,- item_id=item_id,- scope="User",- activity="logged_in",- detail=Detail(- name=user.email,- changes=[],- context=UserLoginContext(- login_method=_determine_login_method(request, was_impersonated),- ip_address=ip_address,- user_agent=user_agent,- reauth=reauth,- ),- ),+ log_login_activity(+ user,+ request,+ login_method=_determine_login_method(request, was_impersonated),+ reauth=request.session.get("reauth") == "true",was_impersonated=was_impersonated,+ log_user=log_user,+ item_id=item_id,)except Exception as e:logger.exception("Failed to log user login activity", user_id=user.id, error=e)diff --git a/posthog/settings/web.py b/posthog/settings/web.pyindex e14c814de74d..4d19774bafa3 100644--- a/posthog/settings/web.py+++ b/posthog/settings/web.py@@ -286,12 +286,17 @@ SOCIAL_AUTH_PIPELINE = ("social_core.pipeline.social_auth.auth_allowed","ee.api.authentication.social_auth_allowed","social_core.pipeline.social_auth.social_user",+ # Must stay ahead of association/provisioning so a mismatched re-auth identity is rejected first+ "posthog.api.authentication.social_reauth","social_core.pipeline.social_auth.associate_by_email","posthog.api.signup.social_create_user","social_core.pipeline.social_auth.associate_user","social_core.pipeline.social_auth.load_extra_data","social_core.pipeline.user.user_details","posthog.api.authentication.social_login_notification",+ # Must stay last: it grants the step-up window, so every step that can still refuse the re-auth+ # has to have run first+ "posthog.api.authentication.social_reauth_complete",)SOCIAL_AUTH_STRATEGY = "social_django.strategy.DjangoStrategy"