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): show the read-only toast only for clicked writes (#112246)

Steven Shultsa2baf1d1c351
diff --git a/frontend/src/initKea.ts b/frontend/src/initKea.ts
index e0ebcb612ba6..9b219c3fecf1 100644
--- a/frontend/src/initKea.ts
+++ b/frontend/src/initKea.ts
@@ -202,7 +202,8 @@ export function initKea({
// owning UI surfaces them itself: load actions (AccessDenied scene gates) and the
// self-handled write actions above. Other writes keep the generic toast, since
// most write flows have no failure handling of their own. Read-only impersonation
- // uses the distinct `impersonation_read_only` code and still toasts.
+ // uses the distinct `impersonation_read_only` code, which apiStatusLogic toasts only
+ // when a click, an Enter key press, or a form submit started the request.
const isAccessDenied =
isAccessDeniedError(error) && (isLoadAction || ACCESS_DENIED_SELF_HANDLED.has(String(actionKey)))
if (
@@ -220,6 +221,7 @@ export function initKea({
// with this code is form validation (e.g. inviting an outside-domain email)
// and must keep the generic error toast.
const isVerifiedDomainError = error.code === 'verified_domain_required' && error.status === 403
+ const isReadOnlyImpersonationError = error.code === 'impersonation_read_only'
const isFeatureFlagDuplicateKey =
error.code === 'unique' &&
error.attr === 'key' &&
@@ -242,6 +244,7 @@ export function initKea({
isTwoFactorError ||
isSensitiveActionError ||
isVerifiedDomainError ||
+ isReadOnlyImpersonationError ||
isFeatureFlagDuplicateKey ||
isHasDependentsError
) {
diff --git a/frontend/src/lib/api.ts b/frontend/src/lib/api.ts
index 5b32879c3c8e..08891c82f200 100644
--- a/frontend/src/lib/api.ts
+++ b/frontend/src/lib/api.ts
@@ -17,7 +17,7 @@ import {
} from 'lib/api-error'
import { ActivityLogProps } from 'lib/components/ActivityLog/ActivityLog'
import { ActivityLogItem } from 'lib/components/ActivityLog/humanizeActivity'
-import { apiStatusLogic, awaitReauthentication } from 'lib/logic/apiStatusLogic'
+import { apiStatusLogic, awaitReauthentication, isUserActionInProgress } from 'lib/logic/apiStatusLogic'
import { getBackendHost, getStoredSession, isOAuthMode, refreshAccessToken } from 'lib/oauth/oauthClient'
import { objectClean } from 'lib/utils/objects'
import { toParams } from 'lib/utils/url'
@@ -7266,7 +7266,8 @@ async function handleFetch(
url: string,
method: string,
fetcher: () => Promise<Response>,
- isRetry = false
+ isRetry = false,
+ startedByUserAction = isUserActionInProgress()
): Promise<Response> {
const startTime = new Date().getTime()
@@ -7278,7 +7279,7 @@ async function handleFetch(
error = e
}
- apiStatusLogic.findMounted()?.actions.onApiResponse(response?.clone(), error)
+ apiStatusLogic.findMounted()?.actions.onApiResponse(response?.clone(), error, startedByUserAction)
if (error || !response) {
if (error && (error as any).name === 'AbortError') {
@@ -7317,13 +7318,13 @@ async function handleFetch(
if (response.status === 401 && isOAuthMode() && !isRetry) {
const refreshed = await refreshAccessToken()
if (refreshed) {
- return await handleFetch(url, method, fetcher, true)
+ return await handleFetch(url, method, fetcher, true, startedByUserAction)
}
}
if (response.status === 403 && !isRetry && (await isStaleSessionResponse(response))) {
if (await awaitReauthentication()) {
- return await handleFetch(url, method, fetcher, true)
+ return await handleFetch(url, method, fetcher, true, startedByUserAction)
}
}
diff --git a/frontend/src/lib/logic/apiStatusLogic.test.ts b/frontend/src/lib/logic/apiStatusLogic.test.ts
index d376d4a768bc..77d261cfdb3a 100644
--- a/frontend/src/lib/logic/apiStatusLogic.test.ts
+++ b/frontend/src/lib/logic/apiStatusLogic.test.ts
@@ -1,5 +1,8 @@
import { MOCK_DEFAULT_ORGANIZATION, MOCK_DEFAULT_USER } from 'lib/api.mock'
+import { MakeLogicType, kea, path } from 'kea'
+import { loaders } from 'kea-loaders'
+import { router } from 'kea-router'
import { expectLogic } from 'kea-test-utils'
import { lemonToast } from '@posthog/lemon-ui'
@@ -94,33 +97,140 @@ describe('apiStatusLogic', () => {
describe('read-only impersonation 403 handling', () => {
const READ_ONLY_DETAIL = 'This action is not allowed during read-only user impersonation.'
+ let errorSpy: jest.SpyInstance
- it('surfaces the block reason as a toast', async () => {
+ beforeEach(() => {
+ useMocks({
+ patch: {
+ '/api/users/@me/': () => [403, { code: 'impersonation_read_only', detail: READ_ONLY_DETAIL }],
+ },
+ })
initKeaTests()
logic = apiStatusLogic()
logic.mount()
+ errorSpy = jest.spyOn(lemonToast, 'error').mockReturnValue('toast-id')
+ })
- const errorSpy = jest.spyOn(lemonToast, 'error').mockReturnValue('toast-id')
- const mockResponse = {
- status: 403,
- ok: false,
- json: () => Promise.resolve({ code: 'impersonation_read_only', detail: READ_ONLY_DETAIL }),
- } as unknown as Response
+ afterEach(() => {
+ jest.restoreAllMocks()
+ document.body.innerHTML = ''
+ })
- await expectLogic(logic, () => {
- logic.actions.onApiResponse(mockResponse)
- }).toFinishAllListeners()
+ const blockedWrite = (): Promise<unknown> => api.update('api/users/@me/', {}).catch(() => null)
+
+ const loaderThatWrites = async (): Promise<void> => {
+ const writeLogic = kea<MakeLogicType<{ savedUser: null }, { saveUser: () => void }>>([
+ path(['lib', 'logic', 'apiStatusLogic', 'test', 'writeLogic']),
+ loaders({
+ savedUser: [
+ null,
+ {
+ saveUser: async () => {
+ await api.update('api/users/@me/', {})
+ return null
+ },
+ },
+ ],
+ }),
+ ])
+ writeLogic.mount()
+ await expectLogic(writeLogic, () => writeLogic.actions.saveUser()).toDispatchActions(['saveUserFailure'])
+ }
+
+ const clickThatWrites = async (tag: 'button' | 'a', beforeWrite?: () => void): Promise<void> => {
+ const element = document.createElement(tag)
+ if (tag === 'a') {
+ element.setAttribute('href', '#')
+ }
+ document.body.appendChild(element)
+ let write: Promise<unknown> = Promise.resolve()
+ element.addEventListener('click', (event) => {
+ event.preventDefault()
+ beforeWrite?.()
+ write = blockedWrite()
+ })
+ element.click()
+ await write
+ }
+
+ // LemonFormDialog submits from its own keydown handler, with no click or submit event. On a link,
+ // a real browser writes from the click that follows the keydown, which jsdom does not fire.
+ const keyThatWrites = async (
+ key: string,
+ tag: 'input' | 'a' = 'input',
+ init: KeyboardEventInit = {}
+ ): Promise<void> => {
+ const element = document.createElement(tag)
+ if (tag === 'a') {
+ element.setAttribute('href', '?tab=other')
+ }
+ document.body.appendChild(element)
+ let write: Promise<unknown> = Promise.resolve()
+ element.addEventListener('keydown', () => {
+ write = blockedWrite()
+ })
+ element.dispatchEvent(new KeyboardEvent('keydown', { key, bubbles: true, ...init }))
+ await write
+ }
+
+ it.each([
+ ['a button click', () => clickThatWrites('button')],
+ [
+ 'a click that only changed the search params',
+ () =>
+ clickThatWrites('button', () =>
+ router.actions.replace(router.values.location.pathname, { tab: 'other' })
+ ),
+ ],
+ [
+ 'a form submit without a button',
+ async () => {
+ const form = document.createElement('form')
+ document.body.appendChild(form)
+ let write: Promise<unknown> = Promise.resolve()
+ form.addEventListener('submit', (event) => {
+ event.preventDefault()
+ write = blockedWrite()
+ })
+ form.requestSubmit()
+ await write
+ },
+ ],
+ ['Enter in a dialog input', () => keyThatWrites('Enter')],
+ [
+ 'an Enter that confirms an IME composition',
+ () => keyThatWrites('Enter', 'input', { isComposing: true, keyCode: 229 }),
+ ],
+ ])('toasts when %s starts the blocked write', async (_name, run) => {
+ await run()
+ await expectLogic(logic).toFinishAllListeners()
expect(errorSpy).toHaveBeenCalledWith(READ_ONLY_DETAIL, { hideButton: true })
- errorSpy.mockRestore()
})
- it('does not toast for unrelated 403s', async () => {
- initKeaTests()
- logic = apiStatusLogic()
- logic.mount()
+ it.each([
+ ['no click started it', blockedWrite],
+ ['a kea loader sent it', loaderThatWrites],
+ ['typing in an input started it', () => keyThatWrites('a')],
+ ['Enter on a link started it', () => keyThatWrites('Enter', 'a')],
+ ['a link click started it', () => clickThatWrites('a')],
+ ['the click navigated first', () => clickThatWrites('button', () => router.actions.push('/elsewhere'))],
+ [
+ 'a click finished before it started',
+ async () => {
+ document.body.click()
+ await new Promise((resolve) => setTimeout(resolve, 0))
+ await blockedWrite()
+ },
+ ],
+ ])('does not toast when %s', async (_name, run) => {
+ await run()
+ await expectLogic(logic).toFinishAllListeners()
+
+ expect(errorSpy).not.toHaveBeenCalled()
+ })
- const errorSpy = jest.spyOn(lemonToast, 'error').mockReturnValue('toast-id')
+ it('does not toast for unrelated 403s', async () => {
const mockResponse = {
status: 403,
ok: false,
@@ -128,11 +238,10 @@ describe('apiStatusLogic', () => {
} as unknown as Response
await expectLogic(logic, () => {
- logic.actions.onApiResponse(mockResponse)
+ logic.actions.onApiResponse(mockResponse, undefined, true)
}).toFinishAllListeners()
expect(errorSpy).not.toHaveBeenCalled()
- errorSpy.mockRestore()
})
})
diff --git a/frontend/src/lib/logic/apiStatusLogic.ts b/frontend/src/lib/logic/apiStatusLogic.ts
index 9f5e3e537cdb..f1e7f67a35fa 100644
--- a/frontend/src/lib/logic/apiStatusLogic.ts
+++ b/frontend/src/lib/logic/apiStatusLogic.ts
@@ -1,4 +1,5 @@
-import { MakeLogicType, actions, kea, listeners, path, reducers } from 'kea'
+import { MakeLogicType, actions, afterMount, kea, listeners, path, reducers } from 'kea'
+import { router } from 'kea-router'
import posthog from 'posthog-js'
import { lemonToast } from '@posthog/lemon-ui'
@@ -21,10 +22,12 @@ export interface apiStatusLogicValues {
export interface apiStatusLogicActions {
onApiResponse: (
response?: Response,
- error?: any
+ error?: any,
+ startedByUserAction?: boolean
) => {
error: any
response: Response | undefined
+ startedByUserAction: boolean
}
resolveSensitiveAction: (outcome: 'failure' | 'success') => {
outcome: 'failure' | 'success'
@@ -45,6 +48,20 @@ export interface apiStatusLogicActions {
export type apiStatusLogicType = MakeLogicType<apiStatusLogicValues, apiStatusLogicActions>
+// True from the start of a click, an Enter key press, or a form submit until the browser finishes
+// that task, so it covers the handlers, the kea listeners they dispatch, and their microtasks.
+// A request that starts in this span counts as one the user asked for. A request that starts
+// after an `await`, such as a debounced save, does not.
+let userActionInProgress = false
+let userActionPathname: string | null = null
+
+export function isUserActionInProgress(): boolean {
+ // A click that navigates mounts a new scene, and the writes that scene sends are not what
+ // the user clicked. The router stores the new location before any `locationChanged`
+ // listener runs, so compare paths.
+ return userActionInProgress && router.values.location.pathname === userActionPathname
+}
+
type SensitiveActionCallbacks = [onSuccess: () => void, onFailure: () => void]
function callEach(callbacks: (() => void)[]): void {
@@ -70,7 +87,11 @@ function joinSensitiveActionCallbacks(
export const apiStatusLogic = kea<apiStatusLogicType>([
path(['lib', 'apiStatusLogic']),
actions({
- onApiResponse: (response?: Response, error?: any) => ({ response, error }),
+ onApiResponse: (response?: Response, error?: any, startedByUserAction?: boolean) => ({
+ response,
+ error,
+ startedByUserAction: !!startedByUserAction,
+ }),
resolveSensitiveAction: (outcome: 'success' | 'failure') => ({ outcome }),
setInternetConnectionIssue: (issue: boolean) => ({ issue }),
setTimeSensitiveAuthenticationRequired: (
@@ -136,7 +157,7 @@ export const apiStatusLogic = kea<apiStatusLogicType>([
posthog.captureException(e)
}
},
- onApiResponse: async ({ response, error }, breakpoint) => {
+ onApiResponse: async ({ response, error, startedByUserAction }, breakpoint) => {
if (error || !response?.status) {
await breakpoint(50)
// Likely CORS headers errors (i.e. request failing without reaching Django))
@@ -196,7 +217,7 @@ export const apiStatusLogic = kea<apiStatusLogicType>([
autoClose: false,
}
)
- } else if (responseData.code === 'impersonation_read_only') {
+ } else if (responseData.code === 'impersonation_read_only' && startedByUserAction) {
lemonToast.error(
typeof responseData.detail === 'string' && responseData.detail
? responseData.detail
@@ -242,6 +263,48 @@ export const apiStatusLogic = kea<apiStatusLogicType>([
}
},
})),
+ afterMount(({ cache }) => {
+ cache.disposables.add(() => {
+ // `click` also fires for keyboard activation of buttons. Enter counts on its own because
+ // some forms, such as LemonFormDialog, submit from a keydown handler. Other keys do not
+ // submit. An Enter that confirms an IME composition still counts: the flag lasts only for
+ // that Enter's own task, so it can only toast for a write that this Enter started.
+ const onUserAction = (event: Event): void => {
+ if (event.type === 'keydown' && (event as KeyboardEvent).key !== 'Enter') {
+ return
+ }
+ // Activating a link is navigation, not a write. A button inside a link is still a button.
+ const control = (event.target as Element | null)?.closest?.('button, a[href]')
+ if (control?.matches('a[href]')) {
+ return
+ }
+ // Re-adding the key runs the previous cleanup, so set the flag after it.
+ cache.disposables.add(
+ () => {
+ const timeout = window.setTimeout(() => {
+ userActionInProgress = false
+ }, 0)
+ return () => {
+ window.clearTimeout(timeout)
+ userActionInProgress = false
+ }
+ },
+ 'endUserAction',
+ { pauseOnPageHidden: false }
+ )
+ userActionInProgress = true
+ userActionPathname = router.values.location.pathname
+ }
+ window.addEventListener('click', onUserAction, { capture: true })
+ window.addEventListener('submit', onUserAction, { capture: true })
+ window.addEventListener('keydown', onUserAction, { capture: true })
+ return () => {
+ window.removeEventListener('click', onUserAction, { capture: true })
+ window.removeEventListener('submit', onUserAction, { capture: true })
+ window.removeEventListener('keydown', onUserAction, { capture: true })
+ }
+ })
+ }),
])
export function awaitReauthentication(): Promise<boolean> {