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.

feat(auth): gate sensitive writes on the backend and retry after re-auth (#104809)

Rafael Audibert82715bff68b0
diff --git a/.agents/skills/gating-sensitive-actions/SKILL.md b/.agents/skills/gating-sensitive-actions/SKILL.md
new file mode 100644
index 000000000000..4c7b65df5d1e
--- /dev/null
+++ b/.agents/skills/gating-sensitive-actions/SKILL.md
@@ -0,0 +1,85 @@
+---
+name: gating-sensitive-actions
+description: 'Use when deciding whether an endpoint, settings section, or UI flow should require recent authentication (re-auth), when adding `TimeSensitiveActionPermission` or its exemptions (`time_sensitive_allow_if_only_fields`, `time_sensitive_exclude_actions`, `time_sensitive_allow_actions`), when wrapping a page or settings section in `TimeSensitiveAuthenticationArea`, when an API read returns secret material, or when a write fails with `sensitive_action_required_reauth`. Carries the product decision: reads stay open, only sensitive writes need a fresh session, and the backend enforces it; organization settings are the one area gated on navigation. Covers how the frontend opens the re-auth modal and retries the failed request, and how to test a new gate. Trigger terms: re-auth, reauthenticate, reauthentication, sensitive session, fresh session, sudo mode, step-up, TimeSensitiveActionPermission, TimeSensitiveAuthenticationArea, sensitive_action_required_reauth.'
+---
+
+# Gating sensitive actions behind re-authentication
+
+A session cookie that is older than `SESSION_SENSITIVE_ACTIONS_AGE` (2 hours by default) can still read everything, but it cannot do sensitive writes until the user re-authenticates.
+This skill says which writes count as sensitive, where the gate goes, and how the UI recovers when a write is refused.
+
+## The decision
+
+These rules are settled. Do not reopen them in a feature PR.
+
+1. **Reads stay open.** Opening a page or loading a list never asks for re-auth. Only an action that changes something sensitive does.
+2. **The backend enforces the gate.** A frontend-only gate protects nothing, because anyone with the cookie can call the API directly. If an action is sensitive, its endpoint carries `TimeSensitiveActionPermission`. Adding a frontend gate instead of this is wrong.
+3. **The frontend reacts, and does not gate up front.** A write that fails with `sensitive_action_required_reauth` opens the re-auth modal. After the user re-authenticates, the same request is sent again. The user does not repeat the action.
+4. **Organization settings are the exception.** The whole organization level of settings is wrapped in `TimeSensitiveAuthenticationArea`, so it prompts on navigation. Keep it like that.
+5. **User, project, and environment settings never prompt on navigation.** There is no per-section opt-in. If reading a section feels sensitive, the fix is to stop the read from returning the secret (see below), not to gate the page.
+6. **A GET never returns a live secret that already exists.** Return a secret only in the response that creates it: new personal API keys, rolled keys, new backup codes. A later read returns metadata, a masked value, or a count. `two_factor_status` returns `backup_codes_remaining`, not the codes.
+
+## What counts as sensitive
+
+Gate a write when it does one of these:
+
+- It changes how someone signs in or proves who they are: password, email, 2FA, passkeys, backup codes.
+- It creates, rolls, or revokes a credential: personal API keys, project secret API keys, OAuth connected apps, personal integrations (GitHub, Slack), personal PostHog connections.
+- It ends sessions or deletes the account.
+- It changes who can act as the user, or what data is collected about them: allow impersonation, data opt-out.
+- It changes organization membership, roles, domains, SSO, or invites.
+
+Do not gate UI preferences and bookkeeping: theme, sidebar layout, navigation items, homepage, current team or organization, product intro flags, hedgehog config, cache refreshes such as `github_repos_refresh`.
+Exempt these explicitly, as described in the next section.
+
+## Backend: adding the gate
+
+`TimeSensitiveActionPermission` is in `posthog/permissions.py`. Read it before you change anything. The behavior to know:
+
+- It applies only to `SessionAuthentication`. Personal API keys and OAuth tokens always pass. The desktop app and MCP are therefore not affected.
+- Safe methods (GET, HEAD, OPTIONS) always pass.
+- If `step_up_required(request.session)` is set, every write is refused and the exemption lists do not apply.
+- The default permission is only `IsAuthenticated`. No mixin adds this permission, so a viewset is protected only when it lists `TimeSensitiveActionPermission` in `permission_classes`, or on the action.
+
+Add the permission to the viewset `permission_classes`, then exempt the non-sensitive writes:
+
+| Attribute | Use it for |
+| ------------------------------------- | ----------------------------------------------------------------------------------------------------------- |
+| `time_sensitive_allow_if_only_fields` | A write where every submitted field is a preference (see `UserViewSet`). A pending step-up still blocks it. |
+| `time_sensitive_allow_actions` | Named actions that skip the freshness window. A pending step-up still blocks them. |
+| `time_sensitive_exclude_actions` | Named actions that are never sensitive. They skip the step-up check too, so use this only for bookkeeping. |
+
+References: `posthog/api/user.py` (`UserViewSet`), `posthog/api/personal_api_key.py`, `posthog/api/webauthn.py`, `posthog/api/oauth/connected_apps.py`, `posthog/api/user_integration.py`.
+
+When one viewset serves both personal credentials and team-shared records, gate only the personal ones. `PersonalConnectionRecentAuthPermission` in `posthog/api/integration.py` gates `posthog` connections and leaves team integrations as they were.
+
+If a read returns a secret, change the response to a count or a masked value. Do not gate the read. Update the serializer, run `hogli build:openapi`, and change the frontend to show the secret only from the create response.
+
+## Frontend: what happens on a refused write
+
+- `handleFetch` in `frontend/src/lib/api.ts` sees the 403 with `sensitive_action_required_reauth` and calls `awaitReauthentication()` from `lib/logic/apiStatusLogic.ts`.
+- `awaitReauthentication()` opens the modal and resolves to `true` after re-auth or `false` after dismissal. When it is `true`, `handleFetch` sends the request once more and returns that response. When it is `false`, the original error reaches the caller. The global error toast ignores this error code.
+- Several requests can wait on one re-auth. Each one settles.
+- A wrong password keeps the request waiting, because the modal stays open. Only success or dismissal settles it.
+
+So 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.
+
+## Testing a new gate
+
+Add the endpoint to the parameterized cases in `TestTimeSensitivePermissions` in `posthog/api/test/test_authentication.py`:
+
+- `test_credential_writes_require_recent_authentication`: a sensitive write returns 403 with `sensitive_action_required_reauth` on a stale session.
+- `test_credential_reads_do_not_require_recent_authentication`: a read or an exempt write does not return 403.
+
+The permission runs before the handler, so placeholder IDs in the URL are enough.
+The frontend retry is covered in `frontend/src/lib/logic/apiStatusLogic.test.ts`. Do not add a per-feature frontend test for it.
+
+## Checklist
+
+- [ ] The sensitive write has `TimeSensitiveActionPermission`, and the non-sensitive writes on the same viewset are exempt.
+- [ ] No GET returns a secret that already exists.
+- [ ] No new `TimeSensitiveAuthenticationArea` outside organization settings.
+- [ ] The stale-session test cases include the new endpoint.
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index e57753021515..254945cbf16e 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -10892,6 +10892,14 @@ snapshots:
hash: v1.k794b7964.c2bdcdc0dae9ab40e695772337ae95876f4f65dee34af627210f5af55fa567e9.OrMBp-9yqlfHY7s8HIzZg8R6M2i0lPVY5q9mx__VSjk
scenes-app-settings-user--settings-user-api-keys--light:
hash: v1.k794b7964.2fcad88dd8709df220d60e553cea06b9e7af4bf32c0e98dc7c6631bba44b8822.6tMZsPffcNgEVB_bav3sBcfddnKuPexrLg2WphmxIGk
+ scenes-app-settings-user--settings-user-backup-codes-modal--dark:
+ hash: v1.k794b7964.fee174652504bedf45b5050dae77b7f38ffaac07d04c14c8c77b010d565cba97.n_drnTbGpOMa04Hy05-KZlJhx74bmdscz3V2bjDSQiw
+ scenes-app-settings-user--settings-user-backup-codes-modal--light:
+ hash: v1.k794b7964.a6d4de942462e384228d3160e0aa72ac6de80f9ae1fd544d0262b46b986c4f1f.dqZ70IdpK5mzkvC9o6S19kkXOkUeC-2p2vtwAUsWbP0
+ scenes-app-settings-user--settings-user-backup-codes-modal-generated--dark:
+ hash: v1.k794b7964.ebaed96fc7dd67f79c20a1ea701db4b94f83c25a092d18e901815d616bcfb98a.3XttF9XT00MDZeExeKWDDS3Svqh-w8JJSQk7f0i1sag
+ scenes-app-settings-user--settings-user-backup-codes-modal-generated--light:
+ hash: v1.k794b7964.9c51bd1bd794659c4b6fdf9a5612dbf375e08f30375778c77cd79caff47c5aa7.s_2QKaTg7Wc2fBiUbAXjD4TG43A37T9Bpbrj3XFCN_Q
scenes-app-settings-user--settings-user-customization--dark:
hash: v1.k794b7964.e3cb983829969c536ba751fc3ab560e00a5e04d7ae3c8b97af48a2c838777a3d.myN7aIIAXAlJSkiJ4315fH6yebYG0XL86cRebeBvYv8
scenes-app-settings-user--settings-user-customization--light:
@@ -10916,6 +10924,10 @@ snapshots:
hash: v1.k794b7964.239346cd0abcf55998302af26ff564e92f56a261f6bb43b3d2063a2404c7cbdb.NvuonbjMwGbrkFpqCPGxUx4zmuSPU_CQKSI_PEIjQpY
scenes-app-settings-user--settings-user-profile-hedgehog-avatar--light:
hash: v1.k794b7964.38fa67af25aa26dbad8e49e9e2acb0b021f755284ded1b1178b43256a47aeb05.KfjJ7Ia0xPCen9TOxy81P2LFHWKQGGDAMR80AJofFic
+ scenes-app-settings-user--settings-user-profile-stale-session--dark:
+ hash: v1.k794b7964.3b7c016ddd09e595239ead276cf9ee430ffc41ebbd80d611b21f5e8be484bcca.Ht4Lfz6Ty0dOyyhvXAHPE-gUW6Rvb8dAid1ZVaAh4sI
+ scenes-app-settings-user--settings-user-profile-stale-session--light:
+ hash: v1.k794b7964.7065458715c17c9b865c3574e941fe1ff3a9a8370f5774031d05e38033f9a919.0DsA-uuULQts_SJaYekwBuM3d5D0UcEh1o2adba-6J8
scenes-app-settings-user--settings-user-reminders-modal--dark:
hash: v1.k794b7964.d0767a8deef594f605dea9ffde6b7fc39276ba9dd2673558fbffa4452afa17a3.nAo3JBm4U0nqWPSI9hPJDAiTYAZjhytrSWTCcBeh5to
scenes-app-settings-user--settings-user-reminders-modal--light:
diff --git a/frontend/src/generated/core/api.schemas.ts b/frontend/src/generated/core/api.schemas.ts
index 4a59b8c0518c..ce2c5b3d6c59 100644
--- a/frontend/src/generated/core/api.schemas.ts
+++ b/frontend/src/generated/core/api.schemas.ts
@@ -5154,6 +5154,24 @@ export interface UserPushTokenUnregisterRequestApi {
token: string
}
+export interface TwoFactorStatusApi {
+ /** Whether the user has any 2FA method enabled. */
+ is_enabled: boolean
+ /** Number of unused backup codes. The codes themselves are only returned when they are generated. */
+ backup_codes_remaining: number
+ /**
+ * The primary 2FA method: "TOTP" or "passkey". Null when 2FA is off.
+ * @nullable
+ */
+ method: string | null
+ /** Whether the user has at least one verified passkey. */
+ has_passkeys: boolean
+ /** Whether the user has an authenticator app set up. */
+ has_totp: boolean
+ /** Whether passkeys count as a 2FA method. */
+ passkeys_enabled_for_2fa: boolean
+}
+
/**
* Request body for POST /api/users/verify_email/.
*/
diff --git a/frontend/src/generated/core/api.ts b/frontend/src/generated/core/api.ts
index c4c96259f0f9..9787e38142be 100644
--- a/frontend/src/generated/core/api.ts
+++ b/frontend/src/generated/core/api.ts
@@ -83,6 +83,7 @@ import type {
SCIMTokenResponseApi,
SharingConfigurationApi,
ToolbarEntitlementsApi,
+ TwoFactorStatusApi,
UploadedMediaApi,
UploadedMediaCreate201,
UploadedMediaCreateBody,
@@ -3301,10 +3302,13 @@ export const getUsersTwoFactorStatusRetrieveUrl = (uuid: string) => {
}
/**
- * Get current 2FA status including backup codes if enabled
+ * Get current 2FA status, including how many backup codes are left.
*/
-export const usersTwoFactorStatusRetrieve = async (uuid: string, options?: RequestInit): Promise<void> => {
- return apiMutator<void>(getUsersTwoFactorStatusRetrieveUrl(uuid), {
+export const usersTwoFactorStatusRetrieve = async (
+ uuid: string,
+ options?: RequestInit
+): Promise<TwoFactorStatusApi> => {
+ return apiMutator<TwoFactorStatusApi>(getUsersTwoFactorStatusRetrieveUrl(uuid), {
...options,
method: 'GET',
})
diff --git a/frontend/src/lib/api.ts b/frontend/src/lib/api.ts
index add0c617039a..ee669f50d842 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 } from 'lib/logic/apiStatusLogic'
+import { apiStatusLogic, awaitReauthentication } 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'
@@ -7348,6 +7348,15 @@ function xhrPost(url: string, data: FormData, options?: ApiUploadOptions): Promi
})
}
+async function isStaleSessionResponse(response: Response): Promise<boolean> {
+ try {
+ const data = await response.clone().json()
+ return data?.code === 'sensitive_action_required_reauth'
+ } catch {
+ return false
+ }
+}
+
async function handleFetch(
url: string,
method: string,
@@ -7407,6 +7416,12 @@ async function handleFetch(
}
}
+ if (response.status === 403 && !isRetry && (await isStaleSessionResponse(response))) {
+ if (await awaitReauthentication()) {
+ return await handleFetch(url, method, fetcher, true)
+ }
+ }
+
if (!response.ok) {
const duration = new Date().getTime() - startTime
const pathname = new URL(url, location.origin).pathname
diff --git a/frontend/src/lib/components/TimeSensitiveAuthentication/timeSensitiveAuthenticationLogic.ts b/frontend/src/lib/components/TimeSensitiveAuthentication/timeSensitiveAuthenticationLogic.ts
index 317e104b04fd..b8bc194044a9 100644
--- a/frontend/src/lib/components/TimeSensitiveAuthentication/timeSensitiveAuthenticationLogic.ts
+++ b/frontend/src/lib/components/TimeSensitiveAuthentication/timeSensitiveAuthenticationLogic.ts
@@ -401,9 +401,6 @@ export const timeSensitiveAuthenticationLogic = kea<timeSensitiveAuthenticationL
// Refresh the user so we know the new session expiry
actions.loadUser()
},
- submitReauthenticationFailure: () => {
- actions.resolveSensitiveAction('failure')
- },
setDismissedReauthentication: ({ value }) => {
if (value) {
posthog.capture('reauthentication_modal_dismissed')
diff --git a/frontend/src/lib/logic/apiStatusLogic.test.ts b/frontend/src/lib/logic/apiStatusLogic.test.ts
index 6deacf7044cc..8c6741c1aa86 100644
--- a/frontend/src/lib/logic/apiStatusLogic.test.ts
+++ b/frontend/src/lib/logic/apiStatusLogic.test.ts
@@ -4,6 +4,8 @@ import { expectLogic } from 'kea-test-utils'
import { lemonToast } from '@posthog/lemon-ui'
+import api from 'lib/api'
+import { timeSensitiveAuthenticationLogic } from 'lib/components/TimeSensitiveAuthentication/timeSensitiveAuthenticationLogic'
import { userLogic } from 'scenes/userLogic'
import { useMocks } from '~/mocks/jest'
@@ -123,4 +125,66 @@ describe('apiStatusLogic', () => {
errorSpy.mockRestore()
})
})
+
+ describe('writes that need a fresh session', () => {
+ const STALE_SESSION = { type: 'authentication_error', code: 'sensitive_action_required_reauth' }
+ let patchCalls: number
+
+ beforeEach(() => {
+ patchCalls = 0
+ useMocks({
+ patch: {
+ '/api/users/@me/': () => (++patchCalls === 1 ? [403, STALE_SESSION] : [200, { saved: true }]),
+ },
+ post: {
+ '/api/personal_api_keys/': () => [403, STALE_SESSION],
+ },
+ })
+ initKeaTests()
+ logic = apiStatusLogic()
+ logic.mount()
+ timeSensitiveAuthenticationLogic.mount()
+ })
+
+ it.each([
+ ['success', { value: { saved: true } }, 2],
+ ['failure', { error: expect.objectContaining({ status: 403, code: STALE_SESSION.code }) }, 1],
+ ] as const)(
+ 'on re-authentication %s, settles the write as %o after %i request(s)',
+ async (outcome, expected, calls) => {
+ const result = api.update('api/users/@me/', { notification_settings: {} }).then(
+ (value) => ({ value }),
+ (error) => ({ error })
+ )
+ await expectLogic(logic).toDispatchActions(['setTimeSensitiveAuthenticationRequired'])
+ logic.actions.resolveSensitiveAction(outcome)
+
+ expect(await result).toEqual(expected)
+ expect(patchCalls).toBe(calls)
+ }
+ )
+
+ it('settles every write waiting on the same re-authentication', async () => {
+ const first = api.update('api/users/@me/', { theme_mode: 'dark' }).catch(() => 'first settled')
+ const second = api.create('api/personal_api_keys/', {}).catch(() => 'second settled')
+ await expectLogic(logic).toDispatchActions([
+ 'setTimeSensitiveAuthenticationRequired',
+ 'setTimeSensitiveAuthenticationRequired',
+ ])
+ logic.actions.resolveSensitiveAction('failure')
+
+ expect(await Promise.all([first, second])).toEqual(['first settled', 'second settled'])
+ })
+
+ it('keeps the write waiting after a wrong password', async () => {
+ const result = api.update('api/users/@me/', { notification_settings: {} })
+ await expectLogic(logic).toDispatchActions(['setTimeSensitiveAuthenticationRequired'])
+
+ timeSensitiveAuthenticationLogic.actions.submitReauthenticationFailure(new Error('Wrong password'), {})
+ expect(patchCalls).toBe(1)
+ logic.actions.resolveSensitiveAction('success')
+
+ expect(await result).toEqual({ saved: true })
+ })
+ })
})
diff --git a/frontend/src/lib/logic/apiStatusLogic.ts b/frontend/src/lib/logic/apiStatusLogic.ts
index 41afd6ba955b..50e19195664f 100644
--- a/frontend/src/lib/logic/apiStatusLogic.ts
+++ b/frontend/src/lib/logic/apiStatusLogic.ts
@@ -4,6 +4,7 @@ import posthog from 'posthog-js'
import { lemonToast } from '@posthog/lemon-ui'
import api from 'lib/api'
+import { timeSensitiveAuthenticationLogic } from 'lib/components/TimeSensitiveAuthentication/timeSensitiveAuthenticationLogic'
import { twoFactorLogic } from 'scenes/authentication/two-factor-setup/twoFactorLogic'
import { userLogic } from 'scenes/userLogic'
@@ -43,6 +44,28 @@ export interface apiStatusLogicActions {
export type apiStatusLogicType = MakeLogicType<apiStatusLogicValues, apiStatusLogicActions>
+type SensitiveActionCallbacks = [onSuccess: () => void, onFailure: () => void]
+
+function callEach(callbacks: (() => void)[]): void {
+ for (const callback of callbacks) {
+ try {
+ callback()
+ } catch (e) {
+ posthog.captureException(e)
+ }
+ }
+}
+
+function joinSensitiveActionCallbacks(
+ pending: SensitiveActionCallbacks,
+ next: boolean | SensitiveActionCallbacks
+): SensitiveActionCallbacks {
+ if (!Array.isArray(next)) {
+ return pending
+ }
+ return [() => callEach([pending[0], next[0]]), () => callEach([pending[1], next[1]])]
+}
+
export const apiStatusLogic = kea<apiStatusLogicType>([
path(['lib', 'apiStatusLogic']),
actions({
@@ -72,7 +95,12 @@ export const apiStatusLogic = kea<apiStatusLogicType>([
// or reject: the pending checkReauthentication listener awaits them fire-and-forget.
false as boolean | [onSuccess: () => void, onFailure: () => void],
{
- setTimeSensitiveAuthenticationRequired: (_, { required }) => required,
+ // Several requests can wait on one re-authentication. A new waiter joins the pending
+ // callbacks instead of replacing them, or the replaced waiter never settles.
+ setTimeSensitiveAuthenticationRequired: (state, { required }) =>
+ Array.isArray(state) && required !== false
+ ? joinSensitiveActionCallbacks(state, required)
+ : required,
},
],
@@ -123,9 +151,7 @@ export const apiStatusLogic = kea<apiStatusLogicType>([
try {
if (response?.status === 403) {
const responseData = await response?.json()
- if (responseData.code === 'sensitive_action_required_reauth') {
- actions.setTimeSensitiveAuthenticationRequired(true)
- } else if (
+ if (
responseData.code === 'two_factor_setup_required' &&
!values.timeSensitiveAuthenticationRequired &&
!twoFactorLogic.findMounted()?.values.isTwoFactorSetupModalOpen
@@ -212,3 +238,13 @@ export const apiStatusLogic = kea<apiStatusLogicType>([
},
})),
])
+
+export function awaitReauthentication(): Promise<boolean> {
+ const logic = apiStatusLogic.findMounted()
+ if (!logic || !timeSensitiveAuthenticationLogic.findMounted()) {
+ return Promise.resolve(false)
+ }
+ return new Promise((resolve) =>
+ logic.actions.setTimeSensitiveAuthenticationRequired([() => resolve(true), () => resolve(false)])
+ )
+}
diff --git a/frontend/src/mocks/handlers.ts b/frontend/src/mocks/handlers.ts
index 0228bc3d901c..cd9810bc7017 100644
--- a/frontend/src/mocks/handlers.ts
+++ b/frontend/src/mocks/handlers.ts
@@ -190,7 +190,10 @@ export const defaultMocks: Mocks = {
pending_invites: [],
},
],
- '/api/users/@me/two_factor_status/': () => [200, { is_enabled: true, backup_codes: [], method: 'TOTP' }],
+ '/api/users/@me/two_factor_status/': () => [
+ 200,
+ { is_enabled: true, backup_codes_remaining: 0, method: 'TOTP' },
+ ],
'/api/users/@me/hedgehog_config/': {
color: null,
enabled: false,
diff --git a/frontend/src/scenes/authentication/two-factor-setup/twoFactorLogic.test.ts b/frontend/src/scenes/authentication/two-factor-setup/twoFactorLogic.test.ts
new file mode 100644
index 000000000000..6545f97f2ebc
--- /dev/null
+++ b/frontend/src/scenes/authentication/two-factor-setup/twoFactorLogic.test.ts
@@ -0,0 +1,37 @@
+import { expectLogic } from 'kea-test-utils'
+
+import { useMocks } from '~/mocks/jest'
+import { initKeaTests } from '~/test/init'
+
+import { twoFactorLogic } from './twoFactorLogic'
+
+describe('twoFactorLogic', () => {
+ it('never keeps generated backup codes hidden behind a closed modal', async () => {
+ let respond: () => void = () => {}
+ const responded = new Promise<void>((resolve) => (respond = resolve))
+ useMocks({
+ post: {
+ '/api/users/@me/two_factor_backup_codes/': async () => {
+ await responded
+ return [200, { backup_codes: ['c0ffee01'] }]
+ },
+ },
+ })
+ initKeaTests()
+ const logic = twoFactorLogic()
+ logic.mount()
+
+ logic.actions.toggleBackupCodesModal(true)
+ logic.actions.generateBackupCodes()
+ logic.actions.toggleBackupCodesModal(false)
+ respond()
+ await expectLogic(logic).toDispatchActions(['generateBackupCodesSuccess'])
+
+ expect(logic.values).toMatchObject({
+ isBackupCodesModalOpen: true,
+ generatingCodes: { backup_codes: ['c0ffee01'] },
+ })
+ logic.actions.toggleBackupCodesModal(false)
+ expect(logic.values.generatingCodes).toBeNull()
+ })
+})
diff --git a/frontend/src/scenes/authentication/two-factor-setup/twoFactorLogic.ts b/frontend/src/scenes/authentication/two-factor-setup/twoFactorLogic.ts
index 54f7b4e03c0f..0f68bf780486 100644
--- a/frontend/src/scenes/authentication/two-factor-setup/twoFactorLogic.ts
+++ b/frontend/src/scenes/authentication/two-factor-setup/twoFactorLogic.ts
@@ -11,6 +11,8 @@ import { membersLogic } from 'scenes/organization/membersLogic'
import { preflightLogic } from 'scenes/PreflightCheck/preflightLogic'
import { userLogic } from 'scenes/userLogic'
+import type { TwoFactorStatusApi } from '~/generated/core/api.schemas'
+
import type { FeatureFlagsSet } from '../../../lib/logic/featureFlagLogic'
import type { PreflightStatus, UserType } from '../../../types'
@@ -18,15 +20,6 @@ export interface TwoFactorForm {
token: string
}
-export interface TwoFactorStatus {
- is_enabled: boolean
- backup_codes: string[]
- method: string | null
- has_passkeys?: boolean
- has_totp?: boolean
- passkeys_enabled_for_2fa?: boolean
-}
-
export interface TwoFactorLogicProps {
onSuccess?: () => void
}
@@ -61,7 +54,7 @@ export interface twoFactorLogicValues {
success: boolean
} | null
startSetupLoading: boolean
- status: TwoFactorStatus | null
+ status: TwoFactorStatusApi | null
statusLoading: boolean
token: {
token: string
@@ -139,12 +132,12 @@ export interface twoFactorLogicActions {
errorObject?: any
}
loadStatusSuccess: (
- status: TwoFactorStatus | null,
+ status: TwoFactorStatusApi,
payload?: {
value: true
}
) => {
- status: TwoFactorStatus | null
+ status: TwoFactorStatusApi
payload?: {
value: true
}
@@ -244,7 +237,7 @@ export interface twoFactorLogicActions {
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface twoFactorLogicMeta {
__keaTypeGenInternalSelectorTypes: {
- is2FAEnabled: (status: TwoFactorStatus | null) => boolean
+ is2FAEnabled: (status: TwoFactorStatusApi | null) => boolean
canSwitchOrg: (user: UserType | null) => boolean
}
}
@@ -300,6 +293,16 @@ export const twoFactorLogic = kea<twoFactorLogicType>([
false,
{
toggleBackupCodesModal: (_, { open }) => open,
+ // New codes replace the old ones, so a result that lands after close reopens the modal. The
+ // user sees them once, and closing again clears them.
+ generateBackupCodesSuccess: () => true,
+ },
+ ],
+ generatingCodes: [
+ null as { backup_codes: string[] } | null,
+ {
+ // The backend only returns codes when it generates them, so they leave memory with the modal.
+ toggleBackupCodesModal: (state, { open }) => (open ? state : null),
},
],
generalError: [
@@ -319,7 +322,7 @@ export const twoFactorLogic = kea<twoFactorLogicType>([
},
],
status: [
- null as TwoFactorStatus | null,
+ null as TwoFactorStatusApi | null,
{
loadStatusSuccess: (_, { status }) => status,
generateBackupCodesSuccess: (state, { generatingCodes }) => {
@@ -328,15 +331,14 @@ export const twoFactorLogic = kea<twoFactorLogicType>([
}
return {
...state,
- // Fallback to current backup codes if generating codes fails
- backup_codes: generatingCodes?.backup_codes || state.backup_codes,
+ backup_codes_remaining: generatingCodes?.backup_codes.length ?? state.backup_codes_remaining,
}
},
},
],
}),
selectors({
- is2FAEnabled: [(s) => [s.status], (status: TwoFactorStatus | null): boolean => !!status?.is_enabled],
+ is2FAEnabled: [(s) => [s.status], (status: TwoFactorStatusApi | null): boolean => !!status?.is_enabled],
canSwitchOrg: [
(s) => [s.user],
(user: null | import('../../../types').UserType): boolean => (user?.organizations || []).length > 1,
@@ -363,10 +365,10 @@ export const twoFactorLogic = kea<twoFactorLogicType>([
},
],
status: [
- null as TwoFactorStatus | null,
+ null as TwoFactorStatusApi | null,
{
loadStatus: async () => {
- return await api.get('api/users/@me/two_factor_status/')
+ return await api.get<TwoFactorStatusApi>('api/users/@me/two_factor_status/')
},
},
],
diff --git a/frontend/src/scenes/settings/Settings.tsx b/frontend/src/scenes/settings/Settings.tsx
index 466cbd1285de..f95a1abe9033 100644
--- a/frontend/src/scenes/settings/Settings.tsx
+++ b/frontend/src/scenes/settings/Settings.tsx
@@ -167,13 +167,11 @@ export function Settings({
return () => clearTimeout(timer)
}, [selectedSectionId, isSearching])
- // Environment and project settings don't require periodic re-authentication by default,
- // so we avoid a needless re-authentication modal (see https://github.com/posthog/posthog/pull/22421).
- // The exception is sections that opt in via `requiresReauthentication` — e.g. credential
- // management — which prompt on navigation like user- and organization-level settings do.
- const requiresReauthentication =
- (selectedLevel !== 'environment' && selectedLevel !== 'project') || !!selectedSection?.requiresReauthentication
- const AuthenticationAreaComponent = requiresReauthentication ? TimeSensitiveAuthenticationArea : React.Fragment
+ // Only organization settings prompt for re-authentication on navigation. Everywhere else the backend gates
+ // sensitive writes, and a write that fails for a stale session opens the re-auth modal and retries.
+ // See the `gating-sensitive-actions` skill.
+ const AuthenticationAreaComponent =
+ selectedLevel === 'organization' ? TimeSensitiveAuthenticationArea : React.Fragment
const options: SettingOption[] = settingsInSidebar
? settings.map((s) => ({
diff --git a/frontend/src/scenes/settings/SettingsMap.tsx b/frontend/src/scenes/settings/SettingsMap.tsx
index 1d5fa1425e4f..bd7937fe7cef 100644
--- a/frontend/src/scenes/settings/SettingsMap.tsx
+++ b/frontend/src/scenes/settings/SettingsMap.tsx
@@ -1841,7 +1841,6 @@ export const SETTINGS_MAP: SettingSection[] = [
id: 'environment-secret-api-keys',
title: 'Project secret API keys',
flag: 'PROJECT_SECRET_API_KEYS',
- requiresReauthentication: true,
settings: [
{
id: 'environment-secret-api-keys',
diff --git a/frontend/src/scenes/settings/stories/SettingsUser.stories.tsx b/frontend/src/scenes/settings/stories/SettingsUser.stories.tsx
index 6403887143fb..c48de2267b42 100644
--- a/frontend/src/scenes/settings/stories/SettingsUser.stories.tsx
+++ b/frontend/src/scenes/settings/stories/SettingsUser.stories.tsx
@@ -38,6 +38,7 @@ const meta: Meta<StoryProps> = {
realm: 'cloud',
},
'/api/projects/:id/integrations': { results: [] },
+ '/api/webauthn/credentials/': [],
'/api/users/@me/login_sessions/': [
{
id: '0190a1b2-0000-7000-8000-000000000001',
@@ -116,6 +117,84 @@ export const SettingsUserProfileHedgehogAvatar: Story = {
},
}
+export const SettingsUserProfileStaleSession: Story = {
+ args: { sectionId: 'user-profile' },
+ parameters: {
+ msw: {
+ mocks: {
+ get: {
+ '/api/users/@me/': () => [
+ 200,
+ {
+ ...MOCK_DEFAULT_USER,
+ organization: {
+ ...MOCK_DEFAULT_ORGANIZATION,
+ available_product_features: getAvailableProductFeatures(),
+ },
+ sensitive_session_expires_at: '2023-05-24T00:00:00Z',
+ },
+ ],
+ },
+ },
+ },
+ },
+}
+
+const TWO_FACTOR_ENABLED_MOCKS = {
+ get: {
+ '/api/users/@me/two_factor_status/': () => [
+ 200,
+ {
+ is_enabled: true,
+ method: 'TOTP',
+ has_totp: true,
+ has_passkeys: false,
+ passkeys_enabled_for_2fa: false,
+ backup_codes_remaining: 7,
+ },
+ ],
+ },
+ post: {
+ '/api/users/@me/two_factor_backup_codes/': () => [
+ 200,
+ {
+ backup_codes: [
+ 'c0ffee01',
+ 'c0ffee02',
+ 'c0ffee03',
+ 'c0ffee04',
+ 'c0ffee05',
+ 'c0ffee06',
+ 'c0ffee07',
+ 'c0ffee08',
+ 'c0ffee09',
+ 'c0ffee10',
+ ],
+ },
+ ],
+ },
+}
+
+export const SettingsUserBackupCodesModal: Story = {
+ args: { sectionId: 'user-profile' },
+ parameters: { msw: { mocks: TWO_FACTOR_ENABLED_MOCKS } },
+ play: async ({ canvasElement }) => {
+ const canvas = within(canvasElement)
+ await userEvent.click(await canvas.findByText(/backup codes/i, { selector: 'button *' }))
+ },
+}
+
+export const SettingsUserBackupCodesModalGenerated: Story = {
+ args: { sectionId: 'user-profile' },
+ parameters: { msw: { mocks: TWO_FACTOR_ENABLED_MOCKS } },
+ play: async ({ canvasElement }) => {
+ const canvas = within(canvasElement)
+ await userEvent.click(await canvas.findByText(/backup codes/i, { selector: 'button *' }))
+ await userEvent.click(await within(document.body).findByText('Generate new codes'))
+ await within(document.body).findByText('c0ffee10')
+ },
+}
+
export const SettingsUserApiKeys: Story = {
args: { sectionId: 'user-api-keys' },
}
diff --git a/frontend/src/scenes/settings/types.ts b/frontend/src/scenes/settings/types.ts
index 37f1176ab112..b901998b3455 100644
--- a/frontend/src/scenes/settings/types.ts
+++ b/frontend/src/scenes/settings/types.ts
@@ -393,14 +393,6 @@ export interface SettingSection extends Pick<Setting, 'flag'> {
*/
hideFromNavigation?: boolean
- /**
- * When true, navigating to this section prompts for re-authentication if the sensitive
- * session has expired — matching how user- and organization-level settings behave. Use for
- * environment/project sections that manage credentials, which otherwise only surface the
- * re-auth modal reactively when a write is attempted.
- */
- requiresReauthentication?: boolean
-
/**
* Gate every setting in the section behind one billing feature. The section renders a single
* upsell when the feature is unavailable. Use this instead of a `PayGateMini` inside each
diff --git a/frontend/src/scenes/settings/user/TwoFactorSettings.tsx b/frontend/src/scenes/settings/user/TwoFactorSettings.tsx
index f63b1dbae85d..584c3245f944 100644
--- a/frontend/src/scenes/settings/user/TwoFactorSettings.tsx
+++ b/frontend/src/scenes/settings/user/TwoFactorSettings.tsx
@@ -11,7 +11,8 @@ import { userLogic } from 'scenes/userLogic'
import { UserType } from '~/types'
export function TwoFactorSettings(): JSX.Element {
- const { status, isDisable2FAModalOpen, isBackupCodesModalOpen } = useValues(twoFactorLogic)
+ const { status, isDisable2FAModalOpen, isBackupCodesModalOpen, generatingCodes, generatingCodesLoading } =
+ useValues(twoFactorLogic)
const { updateUser } = useActions(userLogic)
const { loadMemberUpdates } = useActions(membersLogic)
@@ -64,13 +65,14 @@ export function TwoFactorSettings(): JSX.Element {
)}
{isBackupCodesModalOpen && (
- <LemonModal title="Backup Codes" onClose={() => toggleBackupCodesModal(false)}>
+ <LemonModal title="Backup codes" onClose={() => toggleBackupCodesModal(false)}>
<div className="deprecated-space-y-4 max-w-md">
- {status?.backup_codes?.length ? (
+ {generatingCodes?.backup_codes.length ? (
<>
<p>
Save these backup codes in a secure location. Each code can only be used once to
- sign in if you lose access to your authentication device.
+ sign in if you lose access to your authentication device. You won't be able to see
+ them again after you close this window.
</p>
<div className="bg-primary p-4 rounded font-mono deprecated-space-y-1 relative">
<LemonButton
@@ -78,28 +80,32 @@ export function TwoFactorSettings(): JSX.Element {
size="small"
className="absolute top-4 right-4"
onClick={() => {
- void copyToClipboard(status.backup_codes.join('\n') || '', 'backup codes')
+ void copyToClipboard(
+ generatingCodes.backup_codes.join('\n'),
+ 'backup codes'
+ )
}}
>
Copy
</LemonButton>
- {status.backup_codes.map((code) => (
+ {generatingCodes.backup_codes.map((code) => (
<div key={code}>{code}</div>
))}
</div>
</>
) : (
- <div className="bg-primary p-4 rounded font-mono deprecated-space-y-1 relative">
- <p className="text-secondary mb-0">No backup codes generated</p>
- </div>
+ <p>
+ {status?.backup_codes_remaining
+ ? `You have ${status.backup_codes_remaining} unused backup ${status.backup_codes_remaining === 1 ? 'code' : 'codes'}. Backup codes are only shown once, when you generate them. Generate new codes to replace them.`
+ : "You don't have any unused backup codes. Generate codes to sign in if you lose access to your authentication device."}
+ </p>
)}
<LemonButton
type="primary"
- onClick={() => {
- generateBackupCodes()
- }}
+ onClick={() => generateBackupCodes()}
+ loading={generatingCodesLoading}
>
- {status?.backup_codes?.length ? 'Generate new codes' : 'Generate backup codes'}
+ {status?.backup_codes_remaining ? 'Generate new codes' : 'Generate backup codes'}
</LemonButton>
</div>
</LemonModal>
@@ -159,7 +165,7 @@ export function TwoFactorSettings(): JSX.Element {
size="small"
onClick={() => toggleBackupCodesModal(true)}
>
- View backup codes
+ Backup codes
</LemonButton>
<LemonButton
type="secondary"
diff --git a/posthog/api/integration.py b/posthog/api/integration.py
index f022c125f9ce..0176de84f98a 100644
--- a/posthog/api/integration.py
+++ b/posthog/api/integration.py
@@ -21,7 +21,7 @@ from drf_spectacular.utils import extend_schema, extend_schema_field, extend_sch
from prometheus_client import Counter
from rest_framework import mixins, serializers, status, viewsets
from rest_framework.exceptions import APIException, PermissionDenied, Throttled, ValidationError
-from rest_framework.permissions import IsAuthenticated
+from rest_framework.permissions import BasePermission, IsAuthenticated
from rest_framework.request import Request
from rest_framework.response import Response
from rest_framework.views import APIView
@@ -106,6 +106,7 @@ from posthog.permissions import (
TeamMemberAccessPermission,
TeamMemberLightManagementPermission,
TeamMemberStrictManagementPermission,
+ TimeSensitiveActionPermission,
)
from posthog.rate_limit import GitHubRepositoryRefreshThrottle
from posthog.tasks.email import send_integration_access_request
@@ -1240,6 +1241,24 @@ class IntegrationManagementPermission(TeamMemberStrictManagementPermission):
)
+class PersonalConnectionRecentAuthPermission(BasePermission):
+ """A `posthog` connection is the creator's personal credential, so creating or removing one needs a fresh
+ session, like the other personal integrations. Team-shared kinds keep their existing rules."""
+
+ message = TimeSensitiveActionPermission.message
+ code = TimeSensitiveActionPermission.code
+
+ def has_permission(self, request: Request, view: APIView) -> bool:
+ if getattr(view, "action", None) == "create" and request.data.get("kind") == POSTHOG_CONNECT_KIND:
+ return TimeSensitiveActionPermission().has_permission(request, view)
+ return True
+
+ def has_object_permission(self, request: Request, view: APIView, obj: object) -> bool:
+ if isinstance(obj, Integration) and obj.kind == POSTHOG_CONNECT_KIND:
+ return TimeSensitiveActionPermission().has_permission(request, view)
+ return True
+
+
@extend_schema(extensions={"x-product": "integrations"})
class IntegrationViewSet(
TeamAndOrgViewSetMixin,
@@ -1278,7 +1297,7 @@ class IntegrationViewSet(
# Side-effecting POST (emails admins) — a read-only token must not be able to trigger it.
"request_access",
]
- permission_classes = [IntegrationManagementPermission]
+ permission_classes = [IntegrationManagementPermission, PersonalConnectionRecentAuthPermission]
# LimitOffsetPagination needs a total order, or Postgres can return a row on neither side of a
# page boundary. Clients page this list to find one kind, so a dropped row reads as
# "not configured". Order oldest-first: several clients take the first row of a kind as their
@@ -1309,6 +1328,7 @@ class IntegrationViewSet(
APIScopePermission(),
AccessControlPermission(),
TeamMemberAccessPermission(),
+ PersonalConnectionRecentAuthPermission(),
]
# Adding an integration only requires project membership. Every edit and removal uses the
# viewset permission class, including the creator exception for Google account removal.
diff --git a/posthog/api/oauth/connected_apps.py b/posthog/api/oauth/connected_apps.py
index 1ba6838b2d99..3d5db9587d05 100644
--- a/posthog/api/oauth/connected_apps.py
+++ b/posthog/api/oauth/connected_apps.py
@@ -4,6 +4,7 @@ from typing import cast
from drf_spectacular.utils import extend_schema
from rest_framework import serializers, status, viewsets
+from rest_framework.permissions import IsAuthenticated
from rest_framework.request import Request
from rest_framework.response import Response
@@ -15,6 +16,7 @@ from posthog.models.oauth import (
revoke_oauth_session,
)
from posthog.models.user import User
+from posthog.permissions import TimeSensitiveActionPermission
class ConnectedAppSerializer(serializers.Serializer):
@@ -34,6 +36,7 @@ class ConnectedAppsViewSet(viewsets.ViewSet):
"""
authentication_classes = [SessionAuthentication]
+ permission_classes = [IsAuthenticated, TimeSensitiveActionPermission]
http_method_names = ["get", "post"]
@extend_schema(
diff --git a/posthog/api/test/test_authentication.py b/posthog/api/test/test_authentication.py
index 3cc123ed2142..fe77d59f06c8 100644
--- a/posthog/api/test/test_authentication.py
+++ b/posthog/api/test/test_authentication.py
@@ -56,6 +56,7 @@ from posthog.middleware import KnownLoginDeviceCookieMiddleware
from posthog.models import User
from posthog.models.activity_logging.signal_handlers import post_login
from posthog.models.instance_setting import set_instance_setting
+from posthog.models.integration import Integration
from posthog.models.oauth import OAuthAccessToken, OAuthApplication
from posthog.models.organization import Organization, OrganizationMembership
from posthog.models.organization_domain import OrganizationDomain
@@ -2343,6 +2344,77 @@ class TestTimeSensitivePermissions(APIBaseTest):
)
assert res.status_code == 200
+ @parameterized.expand(
+ [
+ ("passkey_register_begin", "post", "/api/webauthn/register/begin/"),
+ ("passkey_register_complete", "post", "/api/webauthn/register/complete/"),
+ ("passkey_rename", "patch", "/api/webauthn/credentials/1/"),
+ ("passkey_delete", "delete", "/api/webauthn/credentials/1/"),
+ ("passkey_verify", "post", "/api/webauthn/credentials/1/verify/"),
+ ("connected_app_revoke", "post", "/api/oauth/connected-apps/00000000-0000-0000-0000-000000000001/revoke/"),
+ ("github_start", "post", "/api/users/@me/integrations/github/start/"),
+ ("github_prepare_callback", "post", "/api/users/@me/integrations/github/prepare_callback/"),
+ ("github_disconnect", "delete", "/api/users/@me/integrations/github/123/"),
+ ("slack_start", "post", "/api/users/@me/integrations/slack/start/"),
+ ("slack_disconnect", "delete", "/api/users/@me/integrations/slack/U0123ABC/"),
+ ]
+ )
+ def test_credential_writes_require_recent_authentication(self, _name, method, url):
+ now = datetime.now()
+ with time_machine.travel(now + timedelta(seconds=settings.SESSION_SENSITIVE_ACTIONS_AGE + 10), tick=False):
+ res = getattr(self.client, method)(url, {}, format="json")
+ assert res.status_code == 403, res.content
+ assert res.json()["code"] == "sensitive_action_required_reauth"
+
+ @parameterized.expand(
+ [
+ ("passkey_list", "get", "/api/webauthn/credentials/"),
+ ("connected_app_list", "get", "/api/oauth/connected-apps"),
+ ("personal_integration_list", "get", "/api/users/@me/integrations/"),
+ ("github_repos_refresh", "post", "/api/users/@me/integrations/github/123/repos/refresh/"),
+ (
+ "github_install_request_cancel",
+ "delete",
+ "/api/users/@me/integrations/github/install_requests/00000000-0000-0000-0000-000000000001/",
+ ),
+ ]
+ )
+ def test_credential_reads_do_not_require_recent_authentication(self, _name, method, url):
+ now = datetime.now()
+ with time_machine.travel(now + timedelta(seconds=settings.SESSION_SENSITIVE_ACTIONS_AGE + 10), tick=False):
+ res = getattr(self.client, method)(url, {}, format="json")
+ assert res.status_code != 403, res.content
+
+ @parameterized.expand(
+ [
+ ("personal_posthog_connection", "posthog", True),
+ ("team_slack_integration", "slack", False),
+ ]
+ )
+ def test_integration_removal_needs_recent_authentication_only_for_personal_connections(
+ self, _name, kind, needs_reauth
+ ):
+ self.organization_membership.level = OrganizationMembership.Level.ADMIN
+ self.organization_membership.save()
+ integration = Integration.objects.create(team=self.team, kind=kind, config={}, created_by=self.user)
+ now = datetime.now()
+ with time_machine.travel(now + timedelta(seconds=settings.SESSION_SENSITIVE_ACTIONS_AGE + 10), tick=False):
+ res = self.client.delete(f"/api/environments/{self.team.pk}/integrations/{integration.pk}/")
+ if needs_reauth:
+ assert res.status_code == 403, res.content
+ assert res.json()["code"] == "sensitive_action_required_reauth"
+ else:
+ assert res.status_code != 403, res.content
+
+ def test_creating_a_personal_posthog_connection_needs_recent_authentication(self):
+ now = datetime.now()
+ with time_machine.travel(now + timedelta(seconds=settings.SESSION_SENSITIVE_ACTIONS_AGE + 10), tick=False):
+ res = self.client.post(
+ f"/api/environments/{self.team.pk}/integrations/", {"kind": "posthog", "config": {}}, format="json"
+ )
+ assert res.status_code == 403, res.content
+ assert res.json()["code"] == "sensitive_action_required_reauth"
+
class TestTeamSecretTokenAuthentication(APIBaseTest):
def setUp(self):
diff --git a/posthog/api/test/test_user.py b/posthog/api/test/test_user.py
index fdf9e66e8d84..ff9b48ca13eb 100644
--- a/posthog/api/test/test_user.py
+++ b/posthog/api/test/test_user.py
@@ -3570,7 +3570,7 @@ class TestUserTwoFactor(APIBaseTest):
response.json(),
{
"is_enabled": False,
- "backup_codes": [],
+ "backup_codes_remaining": 0,
"method": None,
"has_passkeys": False,
"has_totp": False,
@@ -3595,7 +3595,7 @@ class TestUserTwoFactor(APIBaseTest):
response.json(),
{
"is_enabled": True,
- "backup_codes": ["123456", "789012"],
+ "backup_codes_remaining": 2,
"method": "TOTP",
"has_passkeys": False,
"has_totp": True,
@@ -3627,7 +3627,7 @@ class TestUserTwoFactor(APIBaseTest):
response.json(),
{
"is_enabled": True,
- "backup_codes": [],
+ "backup_codes_remaining": 0,
"method": "passkey",
"has_passkeys": True,
"has_totp": False,
@@ -3668,7 +3668,7 @@ class TestUserTwoFactor(APIBaseTest):
response.json(),
{
"is_enabled": True,
- "backup_codes": ["123456"],
+ "backup_codes_remaining": 1,
"method": "TOTP",
"has_passkeys": True,
"has_totp": True,
@@ -3697,7 +3697,7 @@ class TestUserTwoFactor(APIBaseTest):
response.json(),
{
"is_enabled": False,
- "backup_codes": [],
+ "backup_codes_remaining": 0,
"method": None,
"has_passkeys": False,
"has_totp": False,
@@ -3729,7 +3729,7 @@ class TestUserTwoFactor(APIBaseTest):
response.json(),
{
"is_enabled": False,
- "backup_codes": [],
+ "backup_codes_remaining": 0,
"method": None,
"has_passkeys": True,
"has_totp": False,
diff --git a/posthog/api/user.py b/posthog/api/user.py
index 901c79aee7a7..dab96da13af0 100644
--- a/posthog/api/user.py
+++ b/posthog/api/user.py
@@ -923,6 +923,19 @@ class RevokeOtherSessionsResponseSerializer(serializers.Serializer):
revoked_count = serializers.IntegerField(help_text="Number of other login sessions that were revoked.")
+class TwoFactorStatusSerializer(serializers.Serializer):
+ is_enabled = serializers.BooleanField(help_text="Whether the user has any 2FA method enabled.")
+ backup_codes_remaining = serializers.IntegerField(
+ help_text="Number of unused backup codes. The codes themselves are only returned when they are generated."
+ )
+ method = serializers.CharField(
+ allow_null=True, help_text='The primary 2FA method: "TOTP" or "passkey". Null when 2FA is off.'
+ )
+ has_passkeys = serializers.BooleanField(help_text="Whether the user has at least one verified passkey.")
+ has_totp = serializers.BooleanField(help_text="Whether the user has an authenticator app set up.")
+ passkeys_enabled_for_2fa = serializers.BooleanField(help_text="Whether passkeys count as a 2FA method.")
+
+
class UserGithubLoginSerializer(serializers.Serializer):
github_login = serializers.CharField(
allow_null=True,
@@ -1511,9 +1524,10 @@ class UserViewSet(
return Response({"success": True})
+ @extend_schema(responses={200: TwoFactorStatusSerializer})
@action(methods=["GET"], detail=True)
def two_factor_status(self, request, **kwargs):
- """Get current 2FA status including backup codes if enabled"""
+ """Get current 2FA status, including how many backup codes are left."""
from posthog.helpers.two_factor_session import has_passkeys
user = self.get_object()
@@ -1522,9 +1536,7 @@ class UserViewSet(
user_has_passkeys = has_passkeys(user)
passkeys_enabled_for_2fa = user_has_passkeys and user.passkeys_enabled_for_2fa
- backup_codes = []
- if static_device:
- backup_codes = [token.token for token in static_device.token_set.all()]
+ backup_codes_remaining = static_device.token_set.count() if static_device else 0
# Determine 2FA method
method = None
@@ -1536,7 +1548,7 @@ class UserViewSet(
return Response(
{
"is_enabled": default_device(user) is not None or passkeys_enabled_for_2fa,
- "backup_codes": backup_codes if totp_device else [],
+ "backup_codes_remaining": backup_codes_remaining if totp_device else 0,
"method": method,
"has_passkeys": user_has_passkeys,
"has_totp": totp_device is not None,
diff --git a/posthog/api/user_integration.py b/posthog/api/user_integration.py
index d38c7b6bade8..a29ef90c1757 100644
--- a/posthog/api/user_integration.py
+++ b/posthog/api/user_integration.py
@@ -51,7 +51,7 @@ from posthog.exceptions_capture import capture_exception
from posthog.models.integration import GITHUB_REPOSITORY_REFRESH_COOLDOWN_SECONDS, GitHubIntegrationError, Integration
from posthog.models.user import User
from posthog.models.user_integration import GitHubInstallRequest, UserGitHubIntegration, UserIntegration
-from posthog.permissions import APIScopePermission
+from posthog.permissions import APIScopePermission, TimeSensitiveActionPermission
from posthog.rate_limit import UserAuthenticationThrottle
from posthog.user_permissions import UserPermissions
@@ -303,7 +303,9 @@ class UserIntegrationViewSet(viewsets.GenericViewSet):
]
authentication_classes = [OAuthAccessTokenAuthentication, PersonalAPIKeyAuthentication, SessionAuthentication]
- permission_classes = [IsAuthenticated, APIScopePermission]
+ permission_classes = [IsAuthenticated, APIScopePermission, TimeSensitiveActionPermission]
+ # Refreshing the cached repository list and dismissing a pending install request change no access.
+ time_sensitive_exclude_actions = ["github_repos_refresh", "github_install_requests_destroy"]
http_method_names = ["get", "post", "delete"]
serializer_class = UserGitHubIntegrationItemSerializer
diff --git a/posthog/api/webauthn.py b/posthog/api/webauthn.py
index d08ec07de3cc..4610a7279310 100644
--- a/posthog/api/webauthn.py
+++ b/posthog/api/webauthn.py
@@ -33,6 +33,7 @@ from posthog.passkey import (
verify_passkey_authentication_response,
verify_passkey_registration_response,
)
+from posthog.permissions import TimeSensitiveActionPermission
from posthog.rate_limit import WebAuthnSignupRegistrationThrottle
from posthog.session.activity import revoke_other_sessions_for_request
from posthog.tasks.email import send_passkey_added_email, send_passkey_removed_email
@@ -82,7 +83,7 @@ class WebAuthnRegistrationViewSet(viewsets.ViewSet):
4. POST /verify_complete - Verify assertion, mark credential as verified
"""
- permission_classes = [permissions.IsAuthenticated]
+ permission_classes = [permissions.IsAuthenticated, TimeSensitiveActionPermission]
authentication_classes = [SessionAuthentication]
@action(detail=False, methods=["POST"], url_path="begin")
@@ -629,7 +630,7 @@ class WebAuthnCredentialViewSet(viewsets.ViewSet):
Allows users to list, rename, and delete their passkeys.
"""
- permission_classes = [permissions.IsAuthenticated]
+ permission_classes = [permissions.IsAuthenticated, TimeSensitiveActionPermission]
authentication_classes = [SessionAuthentication]
def list(self, request: Request) -> Response:
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index d39f8e81834f..a21ae2c01e94 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -97170,6 +97170,24 @@ export namespace Schemas {
limit: number;
}
+ export interface TwoFactorStatus {
+ /** Whether the user has any 2FA method enabled. */
+ is_enabled: boolean;
+ /** Number of unused backup codes. The codes themselves are only returned when they are generated. */
+ backup_codes_remaining: number;
+ /**
+ * The primary 2FA method: "TOTP" or "passkey". Null when 2FA is off.
+ * @nullable
+ */
+ method: string | null;
+ /** Whether the user has at least one verified passkey. */
+ has_passkeys: boolean;
+ /** Whether the user has an authenticator app set up. */
+ has_totp: boolean;
+ /** Whether passkeys count as a 2FA method. */
+ passkeys_enabled_for_2fa: boolean;
+ }
+
export interface UnquarantineQuery {
/**
* Snapshot identifier to unquarantine