: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(navigation): route project-wide 403s to the access denied screen (#129813)
Rafael Audibert52b27a61ddab
diff --git a/frontend/snapshots.yml b/frontend/snapshots.ymlindex a4d5b6b47d54..b2e9b2b93e52 100644--- a/frontend/snapshots.yml+++ b/frontend/snapshots.yml@@ -11335,7 +11335,7 @@ snapshots:scenes-app-engineering-analytics-workflows--workflow-list-scoped-to-merge-queue--light:hash: v1.k794b7964.5f510d936c2a4b2cedfa3b285c271894781f8f2156bf88946364364557aa64d6.iXYaJ6uq4SH82W73bZN2f3EnOZKe2um1gZbcTUPV9vcscenes-app-error-project-access-denied--default--dark:- hash: v1.k794b7964.6d58f8cb9ef390270f74ef07d5104b7f42d70bb51ca35f3fdb6556bab46581ce.GP8NrKkdhrAlKBIiXl3b5ydJgg0KsSjEWj1UHG2muTo+ hash: v1.k794b7964.080a85c7b91f938b83350a0fa94884a90476378b9bcd505d4f7dcafed2922120.uVdAVlYvgdx4CtDdmcY5-BQFpaNNDYQMNWtWl9DMl-Ascenes-app-error-project-access-denied--default--light:hash: v1.k794b7964.ee17782476b4edf595d41079265e08ab682437c139a7121f6e66754d9df7688a.V-welVxF6fbpF4UwH8H38xQFWXaRiBBYRbQCEDD8JMMscenes-app-error-project-unavailable--access-revoked--dark:diff --git a/frontend/src/layout/ErrorProjectAccessDenied.tsx b/frontend/src/layout/ErrorProjectAccessDenied.tsxindex c06fa06322dd..ea61e511ff6b 100644--- a/frontend/src/layout/ErrorProjectAccessDenied.tsx+++ b/frontend/src/layout/ErrorProjectAccessDenied.tsx@@ -1,12 +1,77 @@+import { useActions, useValues } from 'kea'+import posthog from 'posthog-js'+import { useState } from 'react'++import { LemonButton } from '@posthog/lemon-ui'+import { AccessDenied } from 'lib/components/AccessDenied'import { NotFound } from 'lib/components/NotFound'+import { useOnMountEffect } from 'lib/hooks/useOnMountEffect'import { getAppContext } from 'lib/utils/getAppContext'+import { teamLogic } from 'scenes/teamLogic'+import { userLogic } from 'scenes/userLogic'++import { usersRetrieve } from '~/generated/core/api'export function ErrorProjectAccessDenied(): JSX.Element {+ const { user } = useValues(userLogic)+ const { logout } = useActions(userLogic)+ const { isCurrentProjectAccessDenied } = useValues(teamLogic)+ const [signedInEmail, setSignedInEmail] = useState(user?.email)// Staff keep the impersonation shortcut, which NotFound renders from the same app context.- if (getAppContext()?.suggested_users_with_access) {+ const showsImpersonationShortcut = !!getAppContext()?.suggested_users_with_access++ useOnMountEffect(() => {+ if (showsImpersonationShortcut) {+ return+ }+ // pinned: analytics event name and property values, renaming breaks dashboards+ posthog.capture('project access denied shown', {+ cause: isCurrentProjectAccessDenied ? 'access_lost' : 'refused_link',+ })+ // Another tab may have signed in as someone else. `loadUser()` would null the user on failure and+ // blank the app, so read the email into local state instead.+ if (isCurrentProjectAccessDenied) {+ usersRetrieve('@me')+ .then((signedInUser) => setSignedInEmail(signedInUser.email))+ .catch(() => {})+ }+ })++ if (showsImpersonationShortcut) {return <NotFound object="project" />}- return <AccessDenied reason="This link points to a project you're not a member of." />+ return (+ <AccessDenied+ reason={+ <>+ <span>+ {isCurrentProjectAccessDenied+ ? "You don't have access to this project."+ : "This link points to a project you're not a member of."}+ </span>+ {signedInEmail ? (+ <>+ {' '}+ You're signed in as <strong>{signedInEmail}</strong>.+ </>+ ) : null}+ </>+ }+ >+ <LemonButton+ type="secondary"+ className="mt-4"+ data-attr="project-access-denied-sign-in-different-account"+ onClick={() => {+ // pinned: analytics event name, renaming breaks dashboards+ posthog.capture('project access denied sign in with different account clicked')+ logout(true)+ }}+ >+ Sign in with a different account+ </LemonButton>+ </AccessDenied>+ )}diff --git a/frontend/src/lib/api-error.ts b/frontend/src/lib/api-error.tsindex e9c650f46a85..2a815ff8bde4 100644--- a/frontend/src/lib/api-error.ts+++ b/frontend/src/lib/api-error.ts@@ -112,6 +112,9 @@ export function isScopeNotFoundMessage(message: unknown): boolean {return typeof message === 'string' && SCOPE_NOT_FOUND_DETAILS.has(message)}+/** DRF `detail` of the project membership 403s in posthog/permissions.py. Keep in sync with the backend. */+export const PROJECT_ACCESS_DENIED_DETAIL = "You don't have access to the project."+/** DRF code of a security access rule refusal (products/security). Keep in sync with the backend. */export const ACCESS_BLOCKED_ERROR_CODE = 'access_blocked'diff --git a/frontend/src/lib/components/AccessDenied/index.tsx b/frontend/src/lib/components/AccessDenied/index.tsxindex ffd2e3a1b5ca..2c63698e200b 100644--- a/frontend/src/lib/components/AccessDenied/index.tsx+++ b/frontend/src/lib/components/AccessDenied/index.tsx@@ -17,9 +17,10 @@ export interface AccessDeniedProps {/** Custom explanation of *why* access is denied. Rendered in place of the default first sentence; the support-link tail stays. */reason?: ReactNodeinline?: boolean+ children?: ReactNode}-export function AccessDenied({ object, reason, inline = false }: AccessDeniedProps): JSX.Element {+export function AccessDenied({ object, reason, inline = false, children }: AccessDeniedProps): JSX.Element {const { openSupportForm } = useActions(supportLogic)const handleClickSupport = (): void => {@@ -49,6 +50,7 @@ export function AccessDenied({ object, reason, inline = false }: AccessDeniedPro<Link onClick={handleClickSupport}>support</Link> if you think this is a mistake.</p>)}+ {children}</div>)}diff --git a/frontend/src/lib/logic/apiStatusLogic.test.ts b/frontend/src/lib/logic/apiStatusLogic.test.tsindex 77d261cfdb3a..bcefaa16896a 100644--- a/frontend/src/lib/logic/apiStatusLogic.test.ts+++ b/frontend/src/lib/logic/apiStatusLogic.test.ts@@ -1,4 +1,4 @@-import { MOCK_DEFAULT_ORGANIZATION, MOCK_DEFAULT_USER } from 'lib/api.mock'+import { MOCK_DEFAULT_ORGANIZATION, MOCK_DEFAULT_USER, MOCK_TEAM_ID } from 'lib/api.mock'import { MakeLogicType, kea, path } from 'kea'import { loaders } from 'kea-loaders'@@ -9,6 +9,7 @@ import { lemonToast } from '@posthog/lemon-ui'import api from 'lib/api'import { timeSensitiveAuthenticationLogic } from 'lib/components/TimeSensitiveAuthentication/timeSensitiveAuthenticationLogic'+import { teamLogic } from 'scenes/teamLogic'import { userLogic } from 'scenes/userLogic'import { useMocks } from '~/mocks/jest'@@ -306,4 +307,49 @@ describe('apiStatusLogic', () => {expect(await result).toEqual({ saved: true })})})++ describe('project access lost mid-session', () => {+ const PROJECT_DENIED = { code: 'permission_denied', detail: "You don't have access to the project." }++ beforeEach(() => {+ initKeaTests()+ logic = apiStatusLogic()+ logic.mount()+ })++ test.each([+ [+ 'an environments endpoint of the current project',+ `/api/environments/${MOCK_TEAM_ID}/dashboards/`,+ PROJECT_DENIED,+ true,+ ],+ [+ 'a projects endpoint of the current project',+ `/api/projects/${MOCK_TEAM_ID}/signals/reports/`,+ PROJECT_DENIED,+ true,+ ],+ ['an endpoint of another project', '/api/projects/12345/dashboards/', PROJECT_DENIED, false],+ [+ 'a resource-level denial',+ `/api/projects/${MOCK_TEAM_ID}/insights/1/`,+ { code: 'permission_denied', detail: 'You do not have viewer access to this resource.' },+ false,+ ],+ ])('handles a 403 from %s', async (_, path, body, expected) => {+ const mockResponse = {+ status: 403,+ ok: false,+ url: `http://localhost${path}`,+ json: () => Promise.resolve(body),+ } as unknown as Response++ await expectLogic(logic, () => {+ logic.actions.onApiResponse(mockResponse)+ }).toFinishAllListeners()++ expect(teamLogic.values.isCurrentProjectAccessDenied).toBe(expected)+ })+ })})diff --git a/frontend/src/lib/logic/apiStatusLogic.ts b/frontend/src/lib/logic/apiStatusLogic.tsindex f1e7f67a35fa..fb9d5d926205 100644--- a/frontend/src/lib/logic/apiStatusLogic.ts+++ b/frontend/src/lib/logic/apiStatusLogic.ts@@ -5,9 +5,10 @@ import posthog from 'posthog-js'import { lemonToast } from '@posthog/lemon-ui'import api from 'lib/api'-import { ACCESS_BLOCKED_ERROR_CODE } from 'lib/api-error'+import { ACCESS_BLOCKED_ERROR_CODE, PROJECT_ACCESS_DENIED_DETAIL } from 'lib/api-error'import { timeSensitiveAuthenticationLogic } from 'lib/components/TimeSensitiveAuthentication/timeSensitiveAuthenticationLogic'import { twoFactorLogic } from 'scenes/authentication/two-factor-setup/twoFactorLogic'+import { teamLogic } from 'scenes/teamLogic'import { userLogic } from 'scenes/userLogic'// Generated by kea-typegen. Update if you're an agent, ignore if you're human.@@ -62,6 +63,32 @@ export function isUserActionInProgress(): boolean {return userActionInProgress && router.values.location.pathname === userActionPathname}+const PROJECT_API_PATH = /^\/api\/(?:projects|environments)\/([^/]+)\//++function isCurrentProjectAccessDenial(url: string, responseData: any): boolean {+ if (responseData?.detail !== PROJECT_ACCESS_DENIED_DETAIL) {+ return false+ }+ const currentTeam = teamLogic.findMounted()?.values.currentTeam+ if (!currentTeam || !url) {+ return false+ }+ let pathname: string+ try {+ pathname = new URL(url, window.location.origin).pathname+ } catch {+ return false+ }+ const projectInPath = pathname.match(PROJECT_API_PATH)?.[1]+ return !!projectInPath && [String(currentTeam.id), String(currentTeam.project_id)].includes(projectInPath)+}++function markCurrentProjectAccessDenied(url: string, responseData: any): void {+ if (isCurrentProjectAccessDenial(url, responseData)) {+ teamLogic.findMounted()?.actions.currentProjectAccessDenied()+ }+}+type SensitiveActionCallbacks = [onSuccess: () => void, onFailure: () => void]function callEach(callbacks: (() => void)[]): void {@@ -173,6 +200,7 @@ export const apiStatusLogic = kea<apiStatusLogicType>([try {if (response?.status === 403) {const responseData = await response?.json()+ markCurrentProjectAccessDenied(response.url, responseData)if (responseData.code === 'two_factor_setup_required' &&!values.timeSensitiveAuthenticationRequired &&diff --git a/frontend/src/scenes/sceneLogic.test.tsx b/frontend/src/scenes/sceneLogic.test.tsxindex d260008672d4..72b69cd9ca60 100644--- a/frontend/src/scenes/sceneLogic.test.tsx+++ b/frontend/src/scenes/sceneLogic.test.tsx@@ -646,6 +646,27 @@ describe('sceneLogic', () => {})+ it('renders the project access denied scene for project pages, not account settings, once the server refuses the current project', async () => {+ router.actions.push(urls.eventDefinitions())+ await expectLogic(logic).delay(1)+ expect(logic.values.activeSceneId).toEqual(Scene.DataManagement)+ const projectScene = logic.values.activeExportedScene+ const projectSceneLogic = projectScene?.logic?.(projectScene.paramsToProps?.(logic.values.sceneParams) ?? {})+ expect(projectSceneLogic?.isMounted()).toBe(true)++ teamLogic.actions.currentProjectAccessDenied()+ expect(logic.values.activeSceneId).toEqual(Scene.ErrorProjectAccessDenied)+ expect(projectSceneLogic?.isMounted()).toBe(false)++ router.actions.push(urls.settings('user'))+ await expectLogic(logic).delay(1)+ expect(logic.values.activeSceneId).toEqual(Scene.Settings)++ router.actions.push(urls.settings('project'))+ await expectLogic(logic).delay(1)+ expect(logic.values.activeSceneId).toEqual(Scene.ErrorProjectAccessDenied)+ })+it("shows the project access denied scene, not onboarding, when the user's own project is not onboarded", async () => {const priorAppContext = window.POSTHOG_APP_CONTEXTtry {diff --git a/frontend/src/scenes/sceneLogic.tsx b/frontend/src/scenes/sceneLogic.tsxindex b3a2d1eb43fa..11ae49d9152e 100644--- a/frontend/src/scenes/sceneLogic.tsx+++ b/frontend/src/scenes/sceneLogic.tsx@@ -76,6 +76,19 @@ interface MountedSceneLogic {unmount: () => void}+function unmountSceneLogic(cache: Record<string, any>): void {+ const mountedLogic: MountedSceneLogic | null = cache.mountedSceneLogic+ if (!mountedLogic) {+ return+ }+ try {+ mountedLogic.unmount()+ } catch (error) {+ console.error('Error unmounting previous scene logic:', error)+ }+ cache.mountedSceneLogic = null+}+// A failed load must fail the scene, because code that builds queries from an empty taxonomy returns wrong results.function loadCoreFilterDefinitionsFor(sceneId: string, loggedIn: boolean): Promise<void> {const sceneConfig = sceneConfigurations[sceneId]@@ -197,6 +210,22 @@ function isRefusedProjectPath(pathname: string): boolean {return !!refusedProject && getProjectIdentifierInPath(pathname) === refusedProject}+function isAccountSettingsPath(pathname: string): boolean {+ return /^\/settings\/(user|organization)/.test(removeProjectIdIfPresent(pathname))+}++function isProjectAccessDenied(sceneId: string, pathname: string, isCurrentProjectAccessDenied: boolean): boolean {+ if (!sceneConfigurations[sceneId]?.projectBased) {+ return false+ }+ // The server refused the project this address names and served the user's own one, so the page+ // cannot load. Once the address bar names a project we do serve, the scene loads as usual.+ if (isRefusedProjectPath(pathname)) {+ return true+ }+ return isCurrentProjectAccessDenied && !isAccountSettingsPath(pathname)+}+function isFirstProjectWithoutData(user: UserType): boolean {const { currentTeam, hasOnboardedAnyProduct } = teamLogic.valuesreturn (@@ -421,6 +450,7 @@ export interface sceneLogicMeta {activeSceneId: (sceneId: string | null,isCurrentTeamUnavailable: boolean,+ isCurrentProjectAccessDenied: boolean,location: {hash: stringpathname: string@@ -617,15 +647,22 @@ export const sceneLogic = kea<sceneLogicType>([{ resultEqualityCheck: equal },],activeSceneId: [- (s) => [s.sceneId, teamLogic.selectors.isCurrentTeamUnavailable, router.selectors.location],- (sceneId: string | null, isCurrentTeamUnavailable: boolean, location: { pathname: string }) => {+ (s) => [+ s.sceneId,+ teamLogic.selectors.isCurrentTeamUnavailable,+ teamLogic.selectors.isCurrentProjectAccessDenied,+ router.selectors.location,+ ],+ (+ sceneId: string | null,+ isCurrentTeamUnavailable: boolean,+ isCurrentProjectAccessDenied: boolean,+ location: { pathname: string }+ ) => {const appContext = getAppContext()const effectiveResourceAccessControl = appContext?.effective_resource_access_control- // The server refused the project this address names and served the user's own one,- // so the page cannot load. Once the address bar names a project we do serve, the- // scene loads as usual.- if (sceneId && sceneConfigurations[sceneId]?.projectBased && isRefusedProjectPath(location.pathname)) {+ if (sceneId && isProjectAccessDenied(sceneId, location.pathname, isCurrentProjectAccessDenied)) {return Scene.ErrorProjectAccessDenied}@@ -785,6 +822,11 @@ export const sceneLogic = kea<sceneLogicType>([],}),listeners(({ values, actions, cache, props, selectors }) => ({+ [teamLogic.actionTypes.currentProjectAccessDenied]: () => {+ if (values.activeSceneId === Scene.ErrorProjectAccessDenied) {+ unmountSceneLogic(cache)+ }+ },// A homepage pointing at a deleted object answers every `/` and Home with a not-found screen,// and the picker that would change it sits behind that screen. Drop the setting instead.resetUnavailableHomepage: ({ pathname }) => {@@ -872,7 +914,8 @@ export const sceneLogic = kea<sceneLogicType>([}let newLogicErrored = false- if (exportedScene?.logic) {+ // A scene behind the access denied screen would keep loading and polling the refused project.+ if (exportedScene?.logic && values.activeSceneId !== Scene.ErrorProjectAccessDenied) {try {const builtLogicProps = { ...exportedScene?.paramsToProps?.(params) }const mountedLogic = cache.mountedSceneLogic@@ -910,15 +953,7 @@ export const sceneLogic = kea<sceneLogicType>([newLogicErrored = true}} else {- const mountedLogic = cache.mountedSceneLogic- if (mountedLogic) {- try {- mountedLogic.unmount()- } catch (error) {- console.error('Error unmounting previous scene logic:', error)- }- cache.mountedSceneLogic = null- }+ unmountSceneLogic(cache)}if (newLogicErrored) {diff --git a/frontend/src/scenes/teamLogic.tsx b/frontend/src/scenes/teamLogic.tsxindex f1bdf9d5a599..b927235fbbc4 100644--- a/frontend/src/scenes/teamLogic.tsx+++ b/frontend/src/scenes/teamLogic.tsx@@ -130,6 +130,7 @@ export interface teamLogicValues {customerAnalyticsConfig: CustomerAnalyticsConfigdemoOnlyProject: booleanhasOnboardedAnyProduct: boolean+ isCurrentProjectAccessDenied: booleanisCurrentTeamUnavailable: booleanisTeamTokenResetAvailable: booleanteamBeingDeleted: TeamType | null@@ -234,6 +235,9 @@ export interface teamLogicActions {is_demo: boolean}}+ currentProjectAccessDenied: () => {+ value: true+ }deleteSecretTokenBackup: () => anydeleteSecretTokenBackupFailure: (error: string,@@ -392,11 +396,13 @@ export const teamLogic = kea<teamLogicType>([],})),actions({+ currentProjectAccessDenied: true,deleteTeam: (team: TeamType) => ({ team }),deleteTeamSuccess: true,deleteTeamFailure: true,}),reducers({+ isCurrentProjectAccessDenied: [false, { currentProjectAccessDenied: () => true }],teamBeingDeleted: [null as TeamType | null,{