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(impersonation): only proceed after confirmed admin OAuth2 (#66480)

Fernando Gomes95359fe2df0f
diff --git a/frontend/src/layout/navigation/ImpersonationNotice/adminLoginAs.ts b/frontend/src/layout/navigation/ImpersonationNotice/adminLoginAs.ts
index 561a42b72627..00f15f4392f8 100644
--- a/frontend/src/layout/navigation/ImpersonationNotice/adminLoginAs.ts
+++ b/frontend/src/layout/navigation/ImpersonationNotice/adminLoginAs.ts
@@ -26,16 +26,29 @@ async function ensureAdminOAuth2(): Promise<void> {
throw new Error('Popup blocked. Please allow popups for this site and try again.')
}
- await new Promise<void>((resolve) => {
+ // Resolve ONLY once the popup confirms success via `oauth2_complete`. A popup that closes
+ // without sending it means the admin session was never established — proceeding anyway would
+ // fire the impersonation POST against a stale session, which silently fails and forces a retry.
+ await new Promise<void>((resolve, reject) => {
let checkClosed: ReturnType<typeof setInterval>
+ let gracePeriodTimeout: ReturnType<typeof setTimeout> | null = null
+ let completed = false
+
+ const cleanup = (): void => {
+ clearInterval(checkClosed)
+ if (gracePeriodTimeout) {
+ clearTimeout(gracePeriodTimeout)
+ }
+ window.removeEventListener('message', handleMessage)
+ }
const handleMessage = (event: MessageEvent): void => {
if (event.origin !== window.location.origin) {
return
}
if (event.data?.type === 'oauth2_complete') {
- clearInterval(checkClosed)
- window.removeEventListener('message', handleMessage)
+ completed = true
+ cleanup()
resolve()
}
}
@@ -44,8 +57,14 @@ async function ensureAdminOAuth2(): Promise<void> {
checkClosed = setInterval(() => {
if (authWindow.closed) {
clearInterval(checkClosed)
- window.removeEventListener('message', handleMessage)
- resolve()
+ // The success message can land a tick after the popup closes — give it a brief
+ // grace period before deciding this was a cancellation.
+ gracePeriodTimeout = setTimeout(() => {
+ if (!completed) {
+ cleanup()
+ reject(new Error('Admin authentication was cancelled. Please try impersonating again.'))
+ }
+ }, 500)
}
}, 500)
})
diff --git a/frontend/src/layout/navigation/ImpersonationNotice/impersonationNoticeLogic.test.ts b/frontend/src/layout/navigation/ImpersonationNotice/impersonationNoticeLogic.test.ts
index 485adfc6fdc9..728e1b61da31 100644
--- a/frontend/src/layout/navigation/ImpersonationNotice/impersonationNoticeLogic.test.ts
+++ b/frontend/src/layout/navigation/ImpersonationNotice/impersonationNoticeLogic.test.ts
@@ -252,20 +252,12 @@ describe('impersonationNoticeLogic', () => {
openSpy.mockRestore()
})
- it('opens OAuth2 popup when auth check fails and proceeds after window closes', async () => {
+ it('opens OAuth2 popup when auth check fails and proceeds once the popup confirms success', async () => {
logic.actions.setSessionExpired({ email: '[email protected]', userId: 123, isImpersonatedUntil: null })
- let authCheckCallCount = 0
useMocks({
get: {
- '/admin/auth_check': () => {
- authCheckCallCount++
- // First call fails (triggers popup), but the login will succeed after
- if (authCheckCallCount === 1) {
- return [401, {}]
- }
- return [200, {}]
- },
+ '/admin/auth_check': () => [401, {}],
'/api/users/@me/': () => [200, MOCK_IMPERSONATED_USER],
},
post: {
@@ -273,7 +265,6 @@ describe('impersonationNoticeLogic', () => {
},
})
- // Mock window.open to return a window that closes immediately
const mockWindow = { closed: false } as Window
const openSpy = jest.spyOn(window, 'open').mockReturnValue(mockWindow)
@@ -281,9 +272,14 @@ describe('impersonationNoticeLogic', () => {
logic.actions.reImpersonate('reason', true)
})
- // Simulate the popup window closing (which resolves the promise)
+ // The popup signals a successful admin OAuth2 grant — only then may the flow proceed
await new Promise((resolve) => setTimeout(resolve, 100))
- ;(mockWindow as any).closed = true
+ window.dispatchEvent(
+ new MessageEvent('message', {
+ origin: window.location.origin,
+ data: { type: 'oauth2_complete' },
+ })
+ )
await reImpersonatePromise.toDispatchActions(['reImpersonate', 'loadUser']).toFinishAllListeners()
@@ -294,6 +290,40 @@ describe('impersonationNoticeLogic', () => {
)
openSpy.mockRestore()
})
+
+ it('fails without impersonating when the OAuth2 popup closes before confirming', async () => {
+ logic.actions.setSessionExpired({ email: '[email protected]', userId: 123, isImpersonatedUntil: null })
+
+ useMocks({
+ get: {
+ '/admin/auth_check': () => [401, {}],
+ '/api/users/@me/': () => [200, MOCK_IMPERSONATED_USER],
+ },
+ post: {
+ '/admin/login/user/:id/': () => [200, {}],
+ },
+ })
+
+ const mockWindow = { closed: false } as Window
+ const openSpy = jest.spyOn(window, 'open').mockReturnValue(mockWindow)
+
+ const reImpersonatePromise = expectLogic(logic, () => {
+ logic.actions.reImpersonate('reason', true)
+ })
+
+ // Popup closes without ever posting `oauth2_complete` — the admin session was never
+ // established, so the flow must surface a failure rather than fire the login-as POST.
+ await new Promise((resolve) => setTimeout(resolve, 100))
+ ;(mockWindow as any).closed = true
+
+ await reImpersonatePromise
+ .toDispatchActions(['reImpersonate', 'reImpersonateFailure'])
+ .toNotHaveDispatchedActions(['loadUser'])
+ .toFinishAllListeners()
+
+ expect(lemonToast.error).toHaveBeenCalled()
+ openSpy.mockRestore()
+ })
})
describe('returnToPostHog listener', () => {
@@ -537,10 +567,14 @@ describe('impersonationNoticeLogic', () => {
// Give the listener time to (incorrectly) process the message
await new Promise((resolve) => setTimeout(resolve, 100))
- // The login-as POST should NOT have been sent yet because the
- // cross-origin message was correctly ignored. Closing the popup
- // is what actually unblocks the flow.
- ;(mockWindow as any).closed = true
+ // The cross-origin message was correctly ignored, so the flow is still blocked.
+ // Only a legitimate same-origin `oauth2_complete` unblocks it.
+ window.dispatchEvent(
+ new MessageEvent('message', {
+ origin: window.location.origin,
+ data: { type: 'oauth2_complete' },
+ })
+ )
await promise.toDispatchActions(['loadUser']).toFinishAllListeners()