: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(toolbar): allow toolbar auth during impersonation sessions (#72974)
Ben Smithf38ee405e3c5
diff --git a/frontend/src/toolbar/bar/toolbarLogic.ts b/frontend/src/toolbar/bar/toolbarLogic.tsindex cbdd287807c4..929249e4f88e 100644--- a/frontend/src/toolbar/bar/toolbarLogic.ts+++ b/frontend/src/toolbar/bar/toolbarLogic.ts@@ -196,12 +196,12 @@ export interface toolbarLogicActions {} // toolbarConfigLogicsetOAuthTokens: (accessToken: string,- refreshToken: string,+ refreshToken: string | null,clientId: string) => {accessToken: stringclientId: string- refreshToken: string+ refreshToken: string | null} // toolbarConfigLogiccompleteGracefulExit: () => {value: truediff --git a/frontend/src/toolbar/toolbarAuth.ts b/frontend/src/toolbar/toolbarAuth.tsindex 45c8cf4a00e7..f0158adfd7ef 100644--- a/frontend/src/toolbar/toolbarAuth.ts+++ b/frontend/src/toolbar/toolbarAuth.ts@@ -90,7 +90,16 @@ export async function withTokenRefresh(// `response?.status` (not `response.status`) so a non-Response value from a customer-page// `fetch` wrapper can't throw here — callers that don't route through `safeFetch` stay safe too.- if (response?.status !== 401 || !accessToken || !refreshToken || !clientId || !uiHost) {+ if (response?.status !== 401 || !accessToken || !clientId || !uiHost) {+ return response+ }++ // Refresh-less tokens (impersonation-minted, refresh-less by design) can't be refreshed —+ // a 401 means the short-lived access token has expired, so prompt the user to re-authenticate.+ if (!refreshToken) {+ toolbarLogger.warn('auth', 'Access token expired and no refresh token available, re-authentication required')+ lemonToast.error('Please re-authenticate to continue using the toolbar.')+ toolbarConfigLogic.actions.tokenExpired()return response}diff --git a/frontend/src/toolbar/toolbarConfigLogic.test.ts b/frontend/src/toolbar/toolbarConfigLogic.test.tsindex cb58791f1454..95061572322f 100644--- a/frontend/src/toolbar/toolbarConfigLogic.test.ts+++ b/frontend/src/toolbar/toolbarConfigLogic.test.ts@@ -439,6 +439,25 @@ describe('toolbar toolbarConfigLogic', () => {})})+ it('restores a stored access token that has no refresh token (impersonation)', () => {+ localStorage.setItem(+ OAUTH_LOCALSTORAGE_KEY,+ JSON.stringify({+ accessToken: 'stored-access',+ clientId: 'stored-client',+ uiHost: 'http://localhost',+ })+ )+ const logic = toolbarConfigLogic.build({ apiURL: 'http://localhost' })+ logic.mount()++ expectLogic(logic).toMatchValues({+ accessToken: 'stored-access',+ refreshToken: null,+ isAuthenticated: true,+ })+ })+it('discards stored OAuth tokens when uiHost does not match', () => {localStorage.setItem(OAUTH_LOCALSTORAGE_KEY,@@ -908,6 +927,29 @@ describe('toolbar toolbarConfigLogic', () => {expect(logic.values.isAuthenticated).toBe(false)})+ it('calls tokenExpired on 401 when there is no refresh token, without attempting a refresh', async () => {+ const logic = toolbarConfigLogic.build({+ apiURL: 'http://localhost',+ accessToken: 'imp-access',+ clientId: 'client-id',+ })+ logic.mount()++ let refreshAttempted = false+ ;(global.fetch as jest.Mock).mockImplementation((url: string) => {+ if (url.includes('toolbar_oauth_refresh')) {+ refreshAttempted = true+ }+ return Promise.resolve({ ok: false, status: 401, json: () => Promise.resolve({}) })+ })++ await toolbarFetch('/api/projects/@current/actions/')++ expect(refreshAttempted).toBe(false)+ expect(logic.values.accessToken).toBeNull()+ expect(logic.values.isAuthenticated).toBe(false)+ })+it('does not retry when response is not 401', async () => {const logic = toolbarConfigLogic.build({apiURL: 'http://localhost',@@ -1027,6 +1069,32 @@ describe('toolbar toolbarConfigLogic', () => {expect(body.get('redirect_uri')).toBe('https://us.posthog.com/toolbar_oauth/callback')})+ it('authenticates when the token response has no refresh token (impersonation)', async () => {+ window.history.pushState({}, '', '/#__posthog_toolbar=code:abc,client_id:xyz')+ ;(global.fetch as jest.Mock).mockImplementation((url: string) => {+ if (typeof url === 'string' && url.endsWith('/toolbar_oauth/check')) {+ return Promise.resolve({ ok: true, status: 200 })+ }+ // Impersonation-minted tokens are refresh-less by design.+ return Promise.resolve({+ ok: true,+ status: 200,+ json: () => Promise.resolve({ access_token: 'imp-access', expires_in: 1800 }),+ })+ })++ const logic = toolbarConfigLogic.build({+ posthog: { config: { ui_host: 'https://us.posthog.com' } } as any,+ } as any)+ logic.mount()++ await expectLogic(logic).delay(0).toMatchValues({+ accessToken: 'imp-access',+ refreshToken: null,+ isAuthenticated: true,+ })+ })+it('does not trigger temporaryToken migration during code exchange', async () => {window.history.pushState({}, '', '/#__posthog_toolbar=code:abc,client_id:xyz')mockTokenExchangeSuccess()diff --git a/frontend/src/toolbar/toolbarConfigLogic.ts b/frontend/src/toolbar/toolbarConfigLogic.tsindex 630bfd9d867c..123589490860 100644--- a/frontend/src/toolbar/toolbarConfigLogic.ts+++ b/frontend/src/toolbar/toolbarConfigLogic.ts@@ -103,12 +103,12 @@ export interface toolbarConfigLogicActions {}setOAuthTokens: (accessToken: string,- refreshToken: string,+ refreshToken: string | null,clientId: string) => {accessToken: stringclientId: string- refreshToken: string+ refreshToken: string | null}showButton: () => {value: true@@ -156,7 +156,7 @@ export const toolbarConfigLogic = kea<toolbarConfigLogicType>([showButton: true,hideButton: true,persistConfig: true,- setOAuthTokens: (accessToken: string, refreshToken: string, clientId: string) => ({+ setOAuthTokens: (accessToken: string, refreshToken: string | null, clientId: string) => ({accessToken,refreshToken,clientId,@@ -585,7 +585,7 @@ export function canonicalizeApiHost(candidate: string | undefined | null): strin// ---------------------------------------------------------------------------type TokenActions = {- setOAuthTokens: (accessToken: string, refreshToken: string, clientId: string) => void+ setOAuthTokens: (accessToken: string, refreshToken: string | null, clientId: string) => voidsetAuthStatus: (status: 'idle' | 'checking' | 'authenticating' | 'error') => void}type CheckActions = TokenActions & {@@ -618,14 +618,17 @@ function restoreOAuthTokens(return}const { accessToken, refreshToken, clientId, uiHost: storedUiHost } = parsed as Record<string, unknown>- // Validate every field is a non-empty string — guards against a third-party script+ // Validate the required fields are non-empty strings — guards against a third-party script// writing garbage (or an older version writing a different shape) that would later- // blow up on fetch header construction.+ // blow up on fetch header construction. refreshToken is optional (impersonation-minted+ // tokens are refresh-less); when present it must be a non-empty string, otherwise it's+ // normalized to null below.+ const storedRefreshToken = asNonEmptyString(refreshToken)+ const refreshTokenValid = refreshToken == null || storedRefreshToken !== nullif (typeof accessToken !== 'string' ||!accessToken ||- typeof refreshToken !== 'string' ||- !refreshToken ||+ !refreshTokenValid ||typeof clientId !== 'string' ||!clientId) {@@ -670,7 +673,7 @@ function restoreOAuthTokens(localStorage.removeItem(OAUTH_LOCALSTORAGE_KEY)return}- actions.setOAuthTokens(accessToken, refreshToken, clientId)+ actions.setOAuthTokens(accessToken, storedRefreshToken, clientId)}/**@@ -884,9 +887,14 @@ async function exchangeCodeForTokens(const data = await res.json().catch(() => null)const access = asNonEmptyString(data?.access_token)const refresh = asNonEmptyString(data?.refresh_token)- if (access && refresh) {+ // A refresh token is optional: impersonation-minted tokens are refresh-less by design+ // (they can't outlive the admin's impersonation session), so require only the access+ // token here. Without a refresh token the short-lived access token is used until it+ // expires, at which point the user re-authenticates.+ if (access) {toolbarPosthogJS.capture('toolbar oauth exchange', {status: 'success',+ has_refresh_token: !!refresh,duration_ms: Math.round(performance.now() - startTime),})actions.setOAuthTokens(access, refresh, clientId)