: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(auth): keep blocked organization members on the block page (#108151)
Yasen9f28af801231
diff --git a/frontend/src/scenes/organizationLogic.test.ts b/frontend/src/scenes/organizationLogic.test.tsindex 9d55d4a9224e..d133a1a203a3 100644--- a/frontend/src/scenes/organizationLogic.test.ts+++ b/frontend/src/scenes/organizationLogic.test.ts@@ -1,10 +1,7 @@import { MOCK_DEFAULT_ORGANIZATION } from 'lib/api.mock'-import { router } from 'kea-router'import { expectLogic } from 'kea-test-utils'-import { removeProjectIdIfPresent } from 'lib/utils/kea-router'-import { useMocks } from '~/mocks/jest'import { initKeaTests } from '~/test/init'@@ -132,50 +129,34 @@ describe('organizationLogic', () => {}test.each([- ['deactivated keeps an invite link', { is_active: false }, '/signup/abc', '/signup/abc'],- ['deactivated keeps billing', { is_active: false }, '/organization/billing', '/organization/billing'],+ ['deactivated keeps an invite link', { is_active: false }, '/signup/abc', true],+ ['deactivated keeps billing', { is_active: false }, '/organization/billing', true],+ ['deactivated keeps the Stripe return route', { is_active: false }, '/billing/authorization_status', true],[- 'deactivated keeps the Stripe return route',+ 'deactivated keeps its own page under a project prefix',{ is_active: false },- '/billing/authorization_status',- '/billing/authorization_status',- ],- ['deactivated drops the app', { is_active: false }, '/dashboard', '/organization-deactivated'],- ['pending deletion keeps an invite link', { is_pending_deletion: true }, '/signup/abc', '/signup/abc'],- [- 'pending deletion drops billing',- { is_pending_deletion: true },- '/organization/billing',- '/organization-pending-deletion',+ '/project/1/organization-deactivated',+ true,],- ])('%s', async (_name, organization, pathname, expected) => {- mountWith(organization)- await expectLogic(logic).toDispatchActions(['loadCurrentOrganizationSuccess'])-- router.actions.push(pathname)-- await expectLogic(router).toDispatchActions(['push'])- // The router writes back a `/project/<id>` prefix, so compare on the route.- expect(removeProjectIdIfPresent(router.values.location.pathname)).toBe(expected)- })- it("keeps a client-side link into another organization's project", async () => {- mountWith({ is_active: false, teams: [{ id: 1 }] } as unknown as Partial<OrganizationType>)+ ['deactivated drops the app', { is_active: false }, '/dashboard', false],+ ['pending deletion keeps an invite link', { is_pending_deletion: true }, '/signup/abc', true],+ ['pending deletion drops billing', { is_pending_deletion: true }, '/organization/billing', false],+ ])('%s', async (_name, organization, pathname, open) => {+ mountWith(organization as unknown as Partial<OrganizationType>)await expectLogic(logic).toDispatchActions(['loadCurrentOrganizationSuccess'])- router.actions.push('/project/424242/dashboard')-- await expectLogic(router).toDispatchActions(['push'])- expect(router.values.location.pathname).toBe('/project/424242/dashboard')+ expect(logic.values.isPathOpenWhileBlocked(pathname)).toBe(open)})- it('still blocks a link into a project the organization owns', async () => {- mountWith({ is_active: false, teams: [{ id: 424242 }] } as unknown as Partial<OrganizationType>)+ test.each([+ ["another organization's project", [{ id: 1 }], true],+ ['a project the organization owns', [{ id: 424242 }], false],+ ['a project while the team list is unknown', undefined, false],+ ])('a link into %s leaves the organization: %s', async (_name, teams, leaves) => {+ mountWith({ is_active: false, teams } as unknown as Partial<OrganizationType>)await expectLogic(logic).toDispatchActions(['loadCurrentOrganizationSuccess'])- router.actions.push('/project/424242/dashboard')-- await expectLogic(router).toDispatchActions(['push'])- expect(removeProjectIdIfPresent(router.values.location.pathname)).toBe('/organization-deactivated')+ expect(logic.values.isPathInAnotherOrganization('/project/424242/dashboard')).toBe(leaves)})})})diff --git a/frontend/src/scenes/organizationLogic.tsx b/frontend/src/scenes/organizationLogic.tsxindex 8cfb6773cd5b..ff5b00aa5d54 100644--- a/frontend/src/scenes/organizationLogic.tsx+++ b/frontend/src/scenes/organizationLogic.tsx@@ -1,7 +1,5 @@import { MakeLogicType, actions, afterMount, connect, kea, listeners, path, reducers, selectors } from 'kea'import { loaders } from 'kea-loaders'-import { router } from 'kea-router'-import type { LocationChangedPayload } from 'kea-router/lib/types'import posthog from 'posthog-js'import api, { ApiConfig, ApiError } from 'lib/api'@@ -32,7 +30,7 @@ const ALLOWED_WHILE_BLOCKED: Record<string, string[]> = {/*** A client-side push reaches no server, so `AutoProjectMiddleware` never resolves the destination's- * organization. Defer to the page load. False while the team list is unknown, which keeps the block on.+ * organization. Only a page load can. False while the team list is unknown, which keeps the block on.*/function pathLeavesCurrentOrganization(organization: OrganizationType | null, pathname: string): boolean {const teams = organization?.teams@@ -77,12 +75,15 @@ export type OrganizationUpdatePayload = Partial<export interface organizationLogicValues {hasAvailableFeature: (feature: AvailableFeature, currentUsage?: number | undefined) => boolean // userLogiccurrentOrganization: OrganizationType | null+ currentOrganizationBlockPage: string | nullcurrentOrganizationId: stringcurrentOrganizationLoading: booleanisAdminOrOwner: boolean | nullisCurrentOrganizationNew: booleanisCurrentOrganizationUnavailable: booleanisNotActiveReason: string | null+ isPathInAnotherOrganization: (pathname: string) => boolean+ isPathOpenWhileBlocked: (pathname: string) => booleanmigrateAccessControlVersionLoading: booleanorganizationBeingDeleted: string | nullprojectCreationForbiddenReason: string | null@@ -90,27 +91,6 @@ export interface organizationLogicValues {// Generated by kea-typegen. Update if you're an agent, ignore if you're human.export interface organizationLogicActions {- locationChanged: ({- method,- pathname,- search,- searchParams,- hash,- hashParams,- initial,- url,- routerState,- }: LocationChangedPayload) => {- hash: string- hashParams: Record<string, any>- initial: boolean- method: 'POP' | 'PUSH' | 'REPLACE'- pathname: string- routerState: Record<string, any>- search: string- searchParams: Record<string, any>- url: string- } // routerloadUser: (resetOnFailure?: boolean | undefined) => {resetOnFailure: boolean | undefined} // userLogic@@ -216,6 +196,9 @@ export interface organizationLogicMeta {isAdminOrOwner: (currentOrganization: OrganizationType | null) => boolean | nullisCurrentOrganizationNew: (currentOrganization: OrganizationType | null) => booleanisNotActiveReason: (currentOrganization: OrganizationType | null) => string | null+ currentOrganizationBlockPage: (currentOrganization: OrganizationType | null) => string | null+ isPathOpenWhileBlocked: (currentOrganizationBlockPage: string | null) => (pathname: string) => boolean+ isPathInAnotherOrganization: (currentOrganization: OrganizationType | null) => (pathname: string) => boolean}}@@ -238,7 +221,7 @@ export const organizationLogic = kea<organizationLogicType>([}),connect(() => ({values: [userLogic, ['hasAvailableFeature']],- actions: [userLogic, ['loadUser'], router, ['locationChanged']],+ actions: [userLogic, ['loadUser']],})),reducers({organizationBeingDeleted: [@@ -375,26 +358,38 @@ export const organizationLogic = kea<organizationLogicType>([(currentOrganization: OrganizationType | null): string | null =>currentOrganization?.is_not_active_reason ?? null,],+ currentOrganizationBlockPage: [+ (s) => [s.currentOrganization],+ (currentOrganization: OrganizationType | null): string | null => organizationBlockPage(currentOrganization),+ ],+ isPathOpenWhileBlocked: [+ (s) => [s.currentOrganizationBlockPage],+ (currentOrganizationBlockPage: string | null) =>+ (pathname: string): boolean => {+ if (currentOrganizationBlockPage === null) {+ return true+ }+ // Compare on the route: the pathname can carry a `/project/<id>` prefix, and the block+ // page must still count as open with that prefix, or the redirect to it never settles.+ const route = removeProjectIdIfPresent(pathname)+ return ALLOWED_WHILE_BLOCKED[currentOrganizationBlockPage].some((allowed) =>+ route.startsWith(allowed)+ )+ },+ ],+ isPathInAnotherOrganization: [+ (s) => [s.currentOrganization],+ (currentOrganization: OrganizationType | null) =>+ (pathname: string): boolean =>+ pathLeavesCurrentOrganization(currentOrganization, pathname),+ ],}),- listeners(({ actions, values }) => ({+ listeners(({ actions }) => ({loadCurrentOrganizationSuccess: ({ currentOrganization }) => {if (currentOrganization) {ApiConfig.setCurrentOrganizationId(currentOrganization.id)}},- locationChanged: ({ pathname }) => {- const blockPage = organizationBlockPage(values.currentOrganization)- if (blockPage === null || pathLeavesCurrentOrganization(values.currentOrganization, pathname)) {- return- }- // Compare on the route: the pathname can carry a `/project/<id>` prefix, and then the- // replace below never matches its own destination.- const route = removeProjectIdIfPresent(pathname)- if (ALLOWED_WHILE_BLOCKED[blockPage].some((allowed) => route.startsWith(allowed))) {- return- }- router.actions.replace(blockPage)- },createOrganizationSuccess: () => {sidePanelStateLogic.findMounted()?.actions.closeSidePanel()window.location.href = urls.onboarding()diff --git a/frontend/src/scenes/sceneLogic.test.tsx b/frontend/src/scenes/sceneLogic.test.tsxindex 9c1a53d64676..35ebe420ef12 100644--- a/frontend/src/scenes/sceneLogic.test.tsx+++ b/frontend/src/scenes/sceneLogic.test.tsx@@ -1,4 +1,4 @@-import { MOCK_USER_UUID } from 'lib/api.mock'+import { MOCK_DEFAULT_ORGANIZATION, MOCK_DEFAULT_PROJECT, MOCK_DEFAULT_TEAM, MOCK_USER_UUID } from 'lib/api.mock'import { kea, path } from 'kea'import { router } from 'kea-router'@@ -16,7 +16,14 @@ import { urls } from 'scenes/urls'import * as exporterViewLogic from '~/exporter/exporterViewLogic'import { useMocks } from '~/mocks/jest'import { initKeaTests } from '~/test/init'-import { AccessControlLevel, AccessControlResourceType, ActivityTab, type AppContext } from '~/types'+import {+ AccessControlLevel,+ AccessControlResourceType,+ ActivityTab,+ type AppContext,+ type OrganizationType,+ type TeamType,+} from '~/types'import { sceneLogic } from './sceneLogic'import type { testLogicType } from './sceneLogic.testType'@@ -38,6 +45,8 @@ const testScenes: Record<string, () => any> = {[Scene.Billing]: sceneImport,[Scene.DataManagement]: sceneImport,[Scene.OrganizationCreateFirst]: sceneImport,+ [Scene.OrganizationDeactivated]: sceneImport,+ [Scene.OrganizationPendingDeletion]: sceneImport,[Scene.PasswordResetComplete]: sceneImport,[Scene.ProjectCreateFirst]: sceneImport,[Scene.Settings]: sceneImport,@@ -601,4 +610,109 @@ describe('sceneLogic', () => {})})++ describe('a blocked organization', () => {+ let priorAppContext: AppContext | undefined++ beforeEach(() => {+ priorAppContext = window.POSTHOG_APP_CONTEXT+ })++ afterEach(() => {+ window.POSTHOG_APP_CONTEXT = priorAppContext as AppContext+ })++ const notOnboarded: Partial<TeamType> = {+ ingested_event: false,+ completed_snippet_onboarding: false,+ has_completed_onboarding_for: {},+ }++ it.each([+ [+ 'keeps a deactivated member on the block page after a client-side link',+ { is_active: false },+ {},+ urls.eventDefinitions(),+ urls.organizationDeactivated(),+ Scene.OrganizationDeactivated,+ ],+ [+ 'sends a deactivated member on an unknown path to the block page',+ { is_active: false },+ {},+ '/no-such-page',+ urls.organizationDeactivated(),+ Scene.OrganizationDeactivated,+ ],+ [+ 'opens billing for a deactivated member',+ { is_active: false },+ {},+ urls.organizationBilling(),+ urls.organizationBilling(),+ Scene.Billing,+ ],+ [+ 'keeps a pending-deletion member off onboarding when the project has no events',+ { is_pending_deletion: true },+ notOnboarded,+ urls.eventDefinitions(),+ urls.organizationPendingDeletion(),+ Scene.OrganizationPendingDeletion,+ ],+ ])('%s', async (_name, organization, team, target, expectedRoute, expectedScene) => {+ logic.unmount()+ initKeaTests(true, { ...MOCK_DEFAULT_TEAM, ...team }, MOCK_DEFAULT_PROJECT, {+ ...MOCK_DEFAULT_ORGANIZATION,+ teams: [MOCK_DEFAULT_TEAM],+ ...organization,+ } as OrganizationType)+ await expectLogic(teamLogic).toDispatchActions(['loadCurrentTeamSuccess'])+ featureFlagLogic.mount()+ logic = sceneLogic.build({ scenes: testScenes })+ logic.mount()++ router.actions.push(target)+ await expectLogic(logic).delay(1)++ expect(removeProjectIdIfPresent(router.values.location.pathname)).toEqual(expectedRoute)+ expect(logic.values.sceneId).toEqual(expectedScene)+ })++ it.each([urls.organizationDeactivated(), urls.organizationPendingDeletion()])(+ 'lets a member whose organization is open leave %s',+ async (blockPage) => {+ router.actions.push(blockPage)+ await expectLogic(logic).delay(1)++ expect(removeProjectIdIfPresent(router.values.location.pathname)).toEqual(urls.projectHomepage())+ }+ )++ it("loads the page for a deactivated member's link into another organization's project", async () => {+ logic.unmount()+ initKeaTests(true, MOCK_DEFAULT_TEAM, MOCK_DEFAULT_PROJECT, {+ ...MOCK_DEFAULT_ORGANIZATION,+ teams: [MOCK_DEFAULT_TEAM],+ is_active: false,+ } as OrganizationType)+ await expectLogic(teamLogic).toDispatchActions(['loadCurrentTeamSuccess'])+ featureFlagLogic.mount()+ logic = sceneLogic.build({ scenes: testScenes })+ logic.mount()+ await expectLogic(logic).delay(1)+ const originalLocation = Object.getOwnPropertyDescriptor(window, 'location')!+ Object.defineProperty(window, 'location', { configurable: true, value: { ...window.location, href: '' } })+ try {+ router.actions.push('/project/424242/dashboard')+ await expectLogic(logic).delay(1)++ expect(window.location.href).toEqual('/project/424242/dashboard')+ expect(logic.values.sceneId).toEqual(Scene.OrganizationDeactivated)+ } finally {+ Object.defineProperty(window, 'location', originalLocation)+ }+ })+ })})diff --git a/frontend/src/scenes/sceneLogic.tsx b/frontend/src/scenes/sceneLogic.tsxindex 5309a1709009..c973de618515 100644--- a/frontend/src/scenes/sceneLogic.tsx+++ b/frontend/src/scenes/sceneLogic.tsx@@ -86,6 +86,30 @@ const tabToPersistableSnapshot = (tab: SceneTab): SceneTab => {}}+/**+ * Moves a member of a blocked organization off a path the block closes. Returns true when it navigated.+ */+function leaveBlockedOrganizationPath(): boolean {+ const { currentOrganizationBlockPage, isPathInAnotherOrganization, isPathOpenWhileBlocked } =+ organizationLogic.values+ if (!currentOrganizationBlockPage) {+ return false+ }+ const { pathname, search, hash } = router.values.location+ if (isPathInAnotherOrganization(pathname)) {+ // The client keeps the blocked organization's project whatever the URL says, so the scene would+ // read that project's data. A page load lets the server switch the member into the project's+ // organization, or send them to the block page.+ window.location.href = pathname + search + hash+ return true+ }+ if (isPathOpenWhileBlocked(pathname)) {+ return false+ }+ router.actions.replace(currentOrganizationBlockPage)+ return true+}+// `/` and `/home` both resolve the configured homepage through this, so anything asking whether a// location is the homepage has to derive it the same way.const homepageTargetPathname = (homepage: SceneTab): string => {@@ -872,6 +896,24 @@ export const sceneLogic = kea<sceneLogicType>([return}+ if (organizationLogic.values.currentOrganizationBlockPage) {+ // Decide the block here. A redirect from a `locationChanged` listener does not hold,+ // because this route handler still opens the scene of the original URL after that+ // listener runs. The onboarding and project-creation redirects below stay off: they+ // only lead to pages that are closed while blocked, so they loop against the block page.+ if (!leaveBlockedOrganizationPath()) {+ actions.loadScene(sceneId, sceneKey, params, method)+ }+ return+ }++ if (sceneId === Scene.OrganizationDeactivated || sceneId === Scene.OrganizationPendingDeletion) {+ // The organization is open again, so let the member back in, as the server does. The server+ // only matches the bare block path, and the router writes it with a `/project/<id>` prefix.+ router.actions.replace(urls.projectRoot())+ return+ }+if (sceneId !== Scene.InviteSignup) {// Redirect to org/project creation if there's no org/project respectively, unless using inviteif (organizationLogic.values.isCurrentOrganizationUnavailable) {@@ -1119,6 +1161,10 @@ export const sceneLogic = kea<sceneLogicType>([}mapping['/*'] = (_, __, { method }) => {+ // This route skips `openScene`, so it applies the organization block itself, as the server does.+ if (leaveBlockedOrganizationPath()) {+ return+ }return actions.loadScene(Scene.Error404, undefined, emptySceneParams, method)}