: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
feat(auth): keep the pending write alive through sso re-auth (#104823)
Rafael Audibert32319502a1f3
diff --git a/.agents/skills/gating-sensitive-actions/SKILL.md b/.agents/skills/gating-sensitive-actions/SKILL.mdindex 4c7b65df5d1e..36dcc88d2384 100644--- a/.agents/skills/gating-sensitive-actions/SKILL.md+++ b/.agents/skills/gating-sensitive-actions/SKILL.md@@ -65,7 +65,13 @@ If a read returns a secret, change the response to a count or a masked value. DoSo a feature does not need its own handling. Do not catch `sensitive_action_required_reauth` in a logic, and do not call `checkReauthentication()` before a write that `handleFetch` can retry.A pre-emptive `checkReauthentication()` is correct only when the flow cannot be retried from the start, for example when it redirects the page before a write can fail.-Limitation: SSO and social login re-auth redirect the whole page, so the pending request is lost. The user repeats the action after they come back. Password and passkey re-auth happen in the page, so the retry works.+SSO and social login re-auth run in a popup, so the page and its pending request stay alive.+The popup returns to `/reauth/complete` (`sso_reauth_complete` in `posthog/api/authentication.py`), which reports the outcome on the `posthog-sso-reauth` `BroadcastChannel` and closes.+The channel is used instead of `window.opener`, because our `Cross-Origin-Opener-Policy` cuts the opener link once the popup visits the identity provider.+Each popup carries a random `attempt` ID in `next`, and the page echoes it back. The listener ignores any message that does not match the attempt it started, because anyone can open the completion page.+The popup waits for the opener to acknowledge the message before it closes, with a 2-second fallback, because closing right after posting can drop the message.+SAML stays on the full-page redirect. Its identity provider posts back cross-site without the session cookie, so the backend runs a fresh login that can switch accounts, and a popup would hide that switch and retry the write as the other account.+When the browser blocks the popup, the modal also falls back to the full-page redirect. Both paths still lose the pending request.## Testing a new gatediff --git a/ee/api/test/test_authentication.py b/ee/api/test/test_authentication.pyindex 792cc12011b0..a3731c6d8bfd 100644--- a/ee/api/test/test_authentication.py+++ b/ee/api/test/test_authentication.py@@ -828,11 +828,49 @@ class TestEEAuthenticationAPI(APILicensedTest):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}")+ 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")diff --git a/frontend/src/lib/components/SocialLoginButton/SocialLoginButton.tsx b/frontend/src/lib/components/SocialLoginButton/SocialLoginButton.tsxindex 77a9bd1185ae..688fb02b2905 100644--- a/frontend/src/lib/components/SocialLoginButton/SocialLoginButton.tsx+++ b/frontend/src/lib/components/SocialLoginButton/SocialLoginButton.tsx@@ -18,10 +18,11 @@ import { getSocialLoginUrl } from './socialLoginUrl'interface SocialLoginLinkProps {provider: SSOProviderextraQueryParams?: Record<string, string>+ onProviderClick?: (provider: SSOProvider) => voidchildren: JSX.Element}-function SocialLoginLink({ provider, extraQueryParams, children }: SocialLoginLinkProps): JSX.Element {+function SocialLoginLink({ provider, extraQueryParams, onProviderClick, children }: SocialLoginLinkProps): JSX.Element {const { searchParams } = useValues(router)const loginUrl = getSocialLoginUrl(provider, extraQueryParams, searchParams)@@ -29,7 +30,19 @@ function SocialLoginLink({ provider, extraQueryParams, children }: SocialLoginLireturn (// eslint-disable-next-line react/forbid-elements- <a className="block" href={loginUrl} {...(iframed ? { target: '_blank', rel: 'noopener' } : {})}>+ <a+ className="block"+ href={loginUrl}+ onClick={+ onProviderClick+ ? (event) => {+ event.preventDefault()+ onProviderClick(provider)+ }+ : undefined+ }+ {...(iframed && !onProviderClick ? { target: '_blank', rel: 'noopener' } : {})}+ >{children}</a>)@@ -38,12 +51,14 @@ function SocialLoginLink({ provider, extraQueryParams, children }: SocialLoginLiinterface SocialLoginButtonProps {provider: SSOProviderextraQueryParams?: Record<string, string>+ onProviderClick?: (provider: SSOProvider) => voidisLastUsed?: boolean}export function SocialLoginButton({provider,extraQueryParams,+ onProviderClick,isLastUsed,}: SocialLoginButtonProps): JSX.Element | null {const { preflight } = useValues(preflightLogic)@@ -53,7 +68,7 @@ export function SocialLoginButton({}return (- <SocialLoginLink provider={provider} extraQueryParams={extraQueryParams}>+ <SocialLoginLink provider={provider} extraQueryParams={extraQueryParams} onProviderClick={onProviderClick}><div className="relative"><LemonButtonsize="large"@@ -119,6 +134,7 @@ interface SocialLoginButtonsProps {topDivider?: booleanbottomDivider?: booleanextraQueryParams?: Record<string, string>+ onProviderClick?: (provider: SSOProvider) => voidlastUsedProvider?: LoginMethodshowPasskey?: boolean/**@@ -142,6 +158,7 @@ export function SocialLoginButtons({lastUsedProvider,showPasskey = false,restrictToProviders,+ onProviderClick,...props}: SocialLoginButtonsProps): JSX.Element | null {const { preflight, socialAuthAvailable } = useValues(preflightLogic)@@ -174,6 +191,7 @@ export function SocialLoginButtons({key={provider}provider={provider as SSOProvider}isLastUsed={lastUsedProvider === provider}+ onProviderClick={onProviderClick}{...props}/>))}@@ -197,12 +215,17 @@ export function SSOEnforcedLoginButton({provider,email,extraQueryParams,+ onProviderClick,actionText = 'Log in',isLastUsed,...props}: SSOEnforcedLoginButtonProps): JSX.Element {return (- <SocialLoginLink provider={provider} extraQueryParams={{ ...extraQueryParams, email }}>+ <SocialLoginLink+ provider={provider}+ extraQueryParams={{ ...extraQueryParams, email }}+ onProviderClick={onProviderClick}+ ><LemonButtonclassName="btn-bridge relative"data-attr="sso-login"diff --git a/frontend/src/lib/components/TimeSensitiveAuthentication/TimeSensitiveAuthentication.tsx b/frontend/src/lib/components/TimeSensitiveAuthentication/TimeSensitiveAuthentication.tsxindex 382d4f60a7f2..2687843b5239 100644--- a/frontend/src/lib/components/TimeSensitiveAuthentication/TimeSensitiveAuthentication.tsx+++ b/frontend/src/lib/components/TimeSensitiveAuthentication/TimeSensitiveAuthentication.tsx@@ -22,9 +22,8 @@ export function TimeSensitiveAuthenticationModal(): JSX.Element {passkeysAvailable,totpAvailable,} = useValues(timeSensitiveAuthenticationLogic)- const { submitReauthentication, setDismissedReauthentication, beginPasskey2FA } = useActions(- timeSensitiveAuthenticationLogic- )+ const { submitReauthentication, setDismissedReauthentication, beginPasskey2FA, beginSsoReauthentication } =+ useActions(timeSensitiveAuthenticationLogic)const ssoEnforcement = precheckResponse?.sso_enforcementconst showPassword = !ssoEnforcement && user?.has_password@@ -50,6 +49,7 @@ export function TimeSensitiveAuthenticationModal(): JSX.Element {email={user!.email}size="medium"extraQueryParams={extraQueryParams}+ onProviderClick={beginSsoReauthentication}/></span>) : showPassword ? (@@ -137,6 +137,7 @@ export function TimeSensitiveAuthenticationModal(): JSX.Element {className="mt-4"caption={showPassword ? 'Or re-authenticate with' : undefined}extraQueryParams={extraQueryParams}+ onProviderClick={beginSsoReauthentication}showPasskey={true}/>{precheckResponse?.saml_available ? (@@ -145,6 +146,7 @@ export function TimeSensitiveAuthenticationModal(): JSX.Element {email={user!.email}size="medium"extraQueryParams={extraQueryParams}+ onProviderClick={beginSsoReauthentication}/>) : null}{precheckResponse?.oidc_available ? (@@ -153,6 +155,7 @@ export function TimeSensitiveAuthenticationModal(): JSX.Element {email={user!.email}size="medium"extraQueryParams={extraQueryParams}+ onProviderClick={beginSsoReauthentication}/>) : null}</div>diff --git a/frontend/src/lib/components/TimeSensitiveAuthentication/timeSensitiveAuthenticationLogic.test.ts b/frontend/src/lib/components/TimeSensitiveAuthentication/timeSensitiveAuthenticationLogic.test.tsindex 7621e7154984..92bd2939c2d5 100644--- a/frontend/src/lib/components/TimeSensitiveAuthentication/timeSensitiveAuthenticationLogic.test.ts+++ b/frontend/src/lib/components/TimeSensitiveAuthentication/timeSensitiveAuthenticationLogic.test.ts@@ -174,6 +174,55 @@ describe('timeSensitiveAuthenticationLogic', () => {})})+ describe('SSO re-authentication in a popup', () => {+ const startPopupAttempt = (): string => {+ const open = jest.spyOn(window, 'open').mockReturnValue({} as Window)+ logic.actions.beginSsoReauthentication('google-oauth2')+ const next = new URL(open.mock.calls[0][0] as string, location.origin).searchParams.get('next')!+ return new URL(next, location.origin).searchParams.get('attempt')!+ }++ it.each([+ ['success', 'own', null, true, false],+ ['failure', 'own', 'reauth_user_mismatch', false, true],+ ['a message from another attempt', 'other', null, false, false],+ ])(+ 'on %s, settles the waiting write only when it succeeded',+ async (_, source, errorCode, settled, toasted) => {+ const onSuccess = jest.fn()+ apiStatusLogic.actions.setTimeSensitiveAuthenticationRequired([onSuccess, jest.fn()])+ const attempt = startPopupAttempt()++ const popup = new BroadcastChannel('posthog-sso-reauth')+ const acknowledgment = new Promise((resolve) => (popup.onmessage = (event) => resolve(event.data)))+ popup.postMessage({+ type: 'sso_reauth_complete',+ attempt: source === 'own' ? attempt : 'someone-else',+ error_code: errorCode,+ })+ await expectLogic(logic).toDispatchActions(['ssoReauthenticationFinished'])++ expect(onSuccess).toHaveBeenCalledTimes(settled ? 1 : 0)+ expect(logic.values.showAuthenticationModal).toBe(!settled)+ expect(lemonToast.error).toHaveBeenCalledTimes(toasted ? 1 : 0)+ if (source === 'own') {+ // The popup waits for this before it closes, so the result is never dropped+ expect(await acknowledgment).toEqual({ type: 'sso_reauth_received', attempt })+ }+ popup.close()+ }+ )+ it('keeps SAML on the full-page redirect', () => {+ const open = jest.spyOn(window, 'open')+ // jsdom reports the page navigation as not implemented+ jest.spyOn(console, 'error').mockImplementation(() => {})++ logic.actions.beginSsoReauthentication('saml')++ expect(open).not.toHaveBeenCalled()+ })+ })+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' })diff --git a/frontend/src/lib/components/TimeSensitiveAuthentication/timeSensitiveAuthenticationLogic.ts b/frontend/src/lib/components/TimeSensitiveAuthentication/timeSensitiveAuthenticationLogic.tsindex b8bc194044a9..bd553f3131cc 100644--- a/frontend/src/lib/components/TimeSensitiveAuthentication/timeSensitiveAuthenticationLogic.ts+++ b/frontend/src/lib/components/TimeSensitiveAuthentication/timeSensitiveAuthenticationLogic.ts@@ -16,11 +16,13 @@ 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 { uuid } from 'lib/utils/dom'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'+import type { SSOProvider, UserType } from '../../../types'+import { getSocialLoginUrl } from '../SocialLoginButton/socialLoginUrl'import { modalInterruptionTrackingLogic } from './modalInterruptionTrackingLogic'export interface ReauthenticationForm {@@ -35,6 +37,10 @@ export interface TwoFAMethodsResponse {export const LOOKAHEAD_EXPIRY_SECONDS = 60 * 5+// Must match `sso_reauth_complete` in posthog/api/authentication.py.+const SSO_REAUTH_COMPLETE_PATH = '/reauth/complete'+const SSO_REAUTH_CHANNEL = 'posthog-sso-reauth'+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.export interface timeSensitiveAuthenticationLogicValues {timeSensitiveAuthenticationRequired: boolean | [onSuccess: () => void, onFailure: () => void] // apiStatusLogic@@ -97,6 +103,9 @@ export interface timeSensitiveAuthenticationLogicActions {value: true}}+ beginSsoReauthentication: (provider: SSOProvider) => {+ provider: SSOProvider+ }checkPasskeysAvailable: () => {value: true}@@ -164,6 +173,13 @@ export interface timeSensitiveAuthenticationLogicActions {showSsoReauthenticationError: () => {value: true}+ ssoReauthenticationFinished: (+ attempt: string,+ errorCode: string | null+ ) => {+ attempt: string+ errorCode: string | null+ }submitReauthentication: () => {value: boolean}@@ -227,6 +243,8 @@ export const timeSensitiveAuthenticationLogic = kea<timeSensitiveAuthenticationLsetRequiresTwoFactor: (value: boolean) => ({ value }),checkReauthentication: true,showSsoReauthenticationError: true,+ beginSsoReauthentication: (provider: SSOProvider) => ({ provider }),+ ssoReauthenticationFinished: (attempt: string, errorCode: string | null) => ({ attempt, errorCode }),beginPasskey2FA: true,checkPasskeysAvailable: true,setTotpAvailable: (available: boolean) => ({ available }),@@ -388,7 +406,7 @@ export const timeSensitiveAuthenticationLogic = kea<timeSensitiveAuthenticationL},})),- listeners(({ actions, values }) => ({+ listeners(({ actions, values, cache }) => ({submitReauthenticationSuccess: () => {posthog.capture('reauthentication_completed')actions.resolveSensitiveAction('success')@@ -407,6 +425,51 @@ export const timeSensitiveAuthenticationLogic = kea<timeSensitiveAuthenticationLactions.resolveSensitiveAction('failure')}},+ beginSsoReauthentication: ({ provider }) => {+ const params = { email: values.user?.email || '', reauth: 'true' }+ const redirectInPage = (): void => {+ window.location.href = getSocialLoginUrl(provider, {+ ...params,+ next: location.href.replace(location.origin, ''),+ })+ }+ // SAML posts back cross-site without the session cookie, so the backend runs a fresh login that can+ // switch accounts. In a popup that switch would be invisible and the pending write would retry as+ // the other account.+ if (provider === 'saml') {+ redirectInPage()+ return+ }+ cache.ssoReauthAttempt = uuid()+ // A popup keeps this page, and the request waiting on re-auth, alive.+ const popup = window.open(+ getSocialLoginUrl(+ provider,+ { ...params, next: `${SSO_REAUTH_COMPLETE_PATH}?attempt=${cache.ssoReauthAttempt}` },+ {}+ ),+ 'posthog-sso-reauth',+ 'popup,width=600,height=700'+ )+ if (!popup) {+ redirectInPage()+ }+ },+ ssoReauthenticationFinished: ({ attempt, errorCode }) => {+ // Anyone can open the completion page, and every tab hears it. Only the attempt this tab started counts.+ if (!cache.ssoReauthAttempt || attempt !== cache.ssoReauthAttempt) {+ return+ }+ cache.ssoReauthAttempt = null+ cache.ssoReauthChannel.postMessage({ type: 'sso_reauth_received', attempt })+ if (errorCode) {+ lemonToast.error(ERROR_MESSAGES[errorCode] ?? ERROR_MESSAGES.social_login_failure)+ return+ }+ posthog.capture('reauthentication_completed', { method: 'sso_popup' })+ actions.resolveSensitiveAction('success')+ actions.loadUser()+ },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).@@ -432,7 +495,22 @@ export const timeSensitiveAuthenticationLogic = kea<timeSensitiveAuthenticationL}},})),- afterMount(({ actions }) => {+ afterMount(({ actions, cache }) => {actions.showSsoReauthenticationError()+ cache.disposables.add(+ () => {+ const channel = new BroadcastChannel(SSO_REAUTH_CHANNEL)+ cache.ssoReauthChannel = channel+ channel.onmessage = (event: MessageEvent) => {+ if (event.data?.type === 'sso_reauth_complete') {+ actions.ssoReauthenticationFinished(String(event.data.attempt), event.data.error_code ?? null)+ }+ }+ return () => channel.close()+ },+ 'ssoReauthChannel',+ // The popup reports back while this tab can be hidden behind it.+ { pauseOnPageHidden: false }+ )}),])diff --git a/posthog/api/authentication.py b/posthog/api/authentication.pyindex a6a5e4afcf47..edca5cf6eb21 100644--- a/posthog/api/authentication.py+++ b/posthog/api/authentication.py@@ -22,7 +22,7 @@ from django.core.signing import BadSignaturefrom django.db import transactionfrom django.db.models import F, Qfrom django.http import Http404, HttpRequest, HttpResponse, JsonResponse-from django.shortcuts import redirect+from django.shortcuts import redirect, renderfrom django.utils import timezonefrom django.utils.http import url_has_allowed_host_and_schemefrom django.views.decorators.http import require_http_methods@@ -206,6 +206,24 @@ def sso_login(request: HttpRequest, backend: str) -> HttpResponse:return redirect(sso_failure_redirect_url(request, "improperly_configured_sso", is_reauth=is_reauth))+SSO_REAUTH_CHANNEL = "posthog-sso-reauth"+++@require_http_methods(["GET"])+def sso_reauth_complete(request: HttpRequest) -> HttpResponse:+ return render(+ request,+ "sso_reauth_complete.html",+ {+ "result": {+ "channel": SSO_REAUTH_CHANNEL,+ "attempt": request.GET.get("attempt") or None,+ "error_code": request.GET.get("error_code") or None,+ }+ },+ )++class TwoFactorRequired(APIException):status_code = 401default_detail = "2FA is required."diff --git a/posthog/templates/sso_reauth_complete.html b/posthog/templates/sso_reauth_complete.htmlnew file mode 100644index 000000000000..77d4fb20dfe5--- /dev/null+++ b/posthog/templates/sso_reauth_complete.html@@ -0,0 +1,47 @@+<!DOCTYPE html>+<html lang="en">+ <head>+ <meta charset="UTF-8">+ <meta name="viewport" content="width=device-width, initial-scale=1.0">+ <title>PostHog</title>+ <style>+ body {+ font-family: -apple-system, BlinkMacSystemFont, 'Inter', 'Segoe UI', 'Roboto', 'Helvetica Neue', helvetica, arial, sans-serif;+ display: flex;+ align-items: center;+ justify-content: center;+ min-height: 100vh;+ margin: 0;+ background: #fafaf9;+ color: #1d1f27;+ }++ @media (prefers-color-scheme: dark) {+ body {+ background: #1d1f27;+ color: #fff;+ }+ }+ </style>+ </head>+ <body>+ <p>You can close this window and go back to PostHog.</p>+ {{ result|json_script:"sso-reauth-result" }}+ <script nonce="{{ request.csp_nonce }}">+ const result = JSON.parse(document.getElementById('sso-reauth-result').textContent)+ const channel = new BroadcastChannel(result.channel)+ const finish = () => {+ channel.close()+ window.close()+ }+ // Closing right after posting can drop the message, so wait for the opener to confirm it arrived.+ channel.onmessage = (event) => {+ if (event.data?.type === 'sso_reauth_received' && event.data.attempt === result.attempt) {+ finish()+ }+ }+ channel.postMessage({ type: 'sso_reauth_complete', attempt: result.attempt, error_code: result.error_code })+ setTimeout(finish, 2000)+ </script>+ </body>+</html>diff --git a/posthog/urls.py b/posthog/urls.pyindex 3873b23122ad..275206e0fb9c 100644--- a/posthog/urls.py+++ b/posthog/urls.py@@ -335,6 +335,7 @@ urlpatterns = [opt_slash_path(".well-known/http-message-signatures-directory", http_message_signatures_directory),# authopt_slash_path("logout", authentication.logout, name="logout"),+ opt_slash_path("reauth/complete", authentication.sso_reauth_complete, name="sso_reauth_complete"),path("login/<str:backend>/", authentication.sso_login, name="social_begin"), # overrides from `social_django.urls` to validate proper license