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(auth): let a blocked organization's members reach the pages that free them (#100754)

Yasen2699ba716d41
diff --git a/frontend/src/scenes/organizationLogic.test.ts b/frontend/src/scenes/organizationLogic.test.ts
index 66939d206d5c..9d55d4a9224e 100644
--- a/frontend/src/scenes/organizationLogic.test.ts
+++ b/frontend/src/scenes/organizationLogic.test.ts
@@ -1,7 +1,10 @@
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'
@@ -117,4 +120,62 @@ describe('organizationLogic', () => {
expect(logic.values.currentOrganization).toBeNull()
})
})
+
+ describe('redirecting away from a blocked organization', () => {
+ const mountWith = (organization: Partial<OrganizationType>): void => {
+ window.POSTHOG_APP_CONTEXT = {
+ current_user: { organization: { id: 'WXYZ', ...organization } },
+ } as unknown as AppContext
+ initKeaTests()
+ logic = organizationLogic()
+ logic.mount()
+ }
+
+ 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 the Stripe return route',
+ { 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',
+ ],
+ ])('%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>)
+ 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')
+ })
+
+ it('still blocks a link into a project the organization owns', async () => {
+ mountWith({ is_active: false, teams: [{ id: 424242 }] } 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')
+ })
+ })
})
diff --git a/frontend/src/scenes/organizationLogic.tsx b/frontend/src/scenes/organizationLogic.tsx
index 43dde60d098c..7abbd398b820 100644
--- a/frontend/src/scenes/organizationLogic.tsx
+++ b/frontend/src/scenes/organizationLogic.tsx
@@ -11,6 +11,7 @@ import { dayjs } from 'lib/dayjs'
import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'
import { isUserLoggedIn } from 'lib/utils/getAppContext'
import { getAppContext } from 'lib/utils/getAppContext'
+import { removeProjectIdIfPresent } from 'lib/utils/kea-router'
import { sidePanelStateLogic } from '~/layout/navigation-3000/sidepanel/sidePanelStateLogic'
import { AvailableFeature, OrganizationType } from '~/types'
@@ -18,6 +19,40 @@ import { AvailableFeature, OrganizationType } from '~/types'
import { urls } from './urls'
import { userLogic } from './userLogic'
+/** Mirrors `ALLOWED_WHILE_BLOCKED` in `posthog/middleware.py`. Change one and change the other. */
+const ALLOWED_WHILE_BLOCKED: Record<string, string[]> = {
+ '/organization-pending-deletion': ['/organization-pending-deletion', '/signup/'],
+ '/organization-deactivated': [
+ '/organization-deactivated',
+ '/signup/',
+ '/organization/billing',
+ '/billing/authorization_status',
+ ],
+}
+
+/**
+ * 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.
+ */
+function pathLeavesCurrentOrganization(organization: OrganizationType | null, pathname: string): boolean {
+ const teams = organization?.teams
+ if (!teams) {
+ return false
+ }
+ const projectId = pathname.match(/^\/project\/([^/]+)/)?.[1]
+ return projectId !== undefined && !teams.some((team) => String(team.id) === projectId)
+}
+
+function organizationBlockPage(organization: OrganizationType | null): string | null {
+ if (organization?.is_pending_deletion) {
+ return '/organization-pending-deletion'
+ }
+ if (organization?.is_active === false) {
+ return '/organization-deactivated'
+ }
+ return null
+}
+
export type OrganizationUpdatePayload = Partial<
Pick<
OrganizationType,
@@ -344,15 +379,17 @@ export const organizationLogic = kea<organizationLogicType>([
}
},
locationChanged: ({ pathname }) => {
- // Redirect to pending deletion page if organization deletion is in progress
- if (values.currentOrganization?.is_pending_deletion && pathname !== urls.organizationPendingDeletion()) {
- router.actions.replace(urls.organizationPendingDeletion())
+ const blockPage = organizationBlockPage(values.currentOrganization)
+ if (blockPage === null || pathLeavesCurrentOrganization(values.currentOrganization, pathname)) {
return
}
- // Redirect to deactivated page if organization is inactive (client-side navigation)
- if (values.currentOrganization?.is_active === false && pathname !== urls.organizationDeactivated()) {
- router.actions.replace(urls.organizationDeactivated())
+ // 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()
diff --git a/posthog/middleware.py b/posthog/middleware.py
index b99c392a8a68..ec7eb6e6a146 100644
--- a/posthog/middleware.py
+++ b/posthog/middleware.py
@@ -47,7 +47,7 @@ from posthog.geoip import get_geoip_properties
from posthog.helpers.impersonation import get_original_user_from_session
from posthog.helpers.sso import sso_failure_redirect_url
from posthog.helpers.user_devices import set_known_device_cookie
-from posthog.models import Team, User
+from posthog.models import Organization, Team, User
from posthog.models.activity_logging.utils import (
ACTIVITY_LOG_CLIENT_HEADER,
ACTIVITY_LOG_CLIENT_MAX_LENGTH,
@@ -1473,9 +1473,43 @@ class SocialAuthExceptionMiddleware:
return error_detail
-class ActiveOrganizationMiddleware:
+# Page prefixes kept per block, keyed by the page that explains it. An invite targets the inviting
+# organization, which this check never judges. Settling the balance is how a member lifts a
+# deactivation; no payment restores a pending deletion. `organizationLogic` holds the same table.
+ALLOWED_WHILE_BLOCKED: dict[str, tuple[str, ...]] = {
+ "/organization-pending-deletion": ("/organization-pending-deletion", "/signup/"),
+ "/organization-deactivated": (
+ "/organization-deactivated",
+ "/signup/",
+ "/organization/billing",
+ "/billing/authorization_status",
+ ),
+}
+
+
+def organization_block_page(organization: Organization) -> Optional[str]:
+ """The page explaining why this organization is closed to its members, or None when it is open.
+
+ Only an explicit `False` deactivates. `is_active` is nullable, but the migration that added it
+ backfilled every row to `True` and operators write `False` explicitly, so a null means "never
+ deactivated".
"""
- Middleware to verify that the current authenticated session is attached to an active organization (is_active = None or True)
+ if organization.is_pending_deletion:
+ return "/organization-pending-deletion"
+ if organization.is_active is False:
+ return "/organization-deactivated"
+ return None
+
+
+class ActiveOrganizationMiddleware:
+ """Keep members out of an organization that is deactivated or pending deletion.
+
+ Runs after `AutoProjectMiddleware`, which switches the user into the organization a
+ `/project/<id>` URL names, so this middleware needs no path parsing of its own.
+ `test_middleware.py` pins the order.
+
+ This is UX, not enforcement: every `/api` path is skipped, and `ActiveOrganizationPermission`
+ is what holds the API.
"""
_IGNORED_PATHS = ("/logout", "/api", "/admin")
@@ -1492,26 +1526,21 @@ class ActiveOrganizationMiddleware:
return self.get_response(request)
user = cast(User, request.user)
+ organization = user.current_organization
- if user.current_organization is None:
+ if organization is None:
return self.get_response(request)
- # Check pending deletion first — takes priority over is_active
- if user.current_organization.is_pending_deletion:
- return (
- self.get_response(request)
- if request.path == "/organization-pending-deletion"
- else redirect("/organization-pending-deletion")
- )
+ block_page = organization_block_page(organization)
- if user.current_organization.is_active is not False:
- return redirect("/") if request.path == "/organization-deactivated" else self.get_response(request)
+ if block_page is None:
+ # A member sitting on a block page has been let back in.
+ return redirect("/") if request.path in ALLOWED_WHILE_BLOCKED else self.get_response(request)
- return (
- self.get_response(request)
- if request.path == "/organization-deactivated"
- else redirect("/organization-deactivated")
- )
+ if any(request.path.startswith(allowed) for allowed in ALLOWED_WHILE_BLOCKED[block_page]):
+ return self.get_response(request)
+
+ return redirect(block_page)
# Session key used to mark an impersonation session as read-only
diff --git a/posthog/settings/web.py b/posthog/settings/web.py
index d7c8584a4fe9..dbf16b613dff 100644
--- a/posthog/settings/web.py
+++ b/posthog/settings/web.py
@@ -201,10 +201,12 @@ MIDDLEWARE = [
"posthog.middleware.ImpersonationReadOnlyMiddleware",
"posthog.middleware.ImpersonationBlockedPathsMiddleware",
"django.middleware.clickjacking.XFrameOptionsMiddleware",
- "posthog.middleware.ActiveOrganizationMiddleware",
"posthog.middleware.CsvNeverCacheMiddleware",
"axes.middleware.AxesMiddleware",
"posthog.middleware.AutoProjectMiddleware",
+ # Must stay after AutoProjectMiddleware, which switches the user into the organization a
+ # `/project/<id>` URL names. Ahead of it, the check judges the organization being left.
+ "posthog.middleware.ActiveOrganizationMiddleware",
"posthog.middleware.CHQueries",
"django_prometheus.middleware.PrometheusAfterMiddleware",
"posthog.middleware.PostHogTokenCookieMiddleware",
diff --git a/posthog/test/test_middleware.py b/posthog/test/test_middleware.py
index 20e29e1c7e37..b1838a41279b 100644
--- a/posthog/test/test_middleware.py
+++ b/posthog/test/test_middleware.py
@@ -28,6 +28,7 @@ from posthog.api.test.test_organization import create_organization
from posthog.api.test.test_team import create_team
from posthog.middleware import CSPMiddleware, app_csp_header_name, per_request_logging_context_middleware
from posthog.models.organization import Organization
+from posthog.models.organization_invite import OrganizationInvite
from posthog.models.team import Team
from posthog.models.user import User
from posthog.settings import SITE_URL
@@ -1818,6 +1819,53 @@ class TestActiveOrganizationMiddleware(APIBaseTest):
if expected_location:
self.assertEqual(response.headers["Location"], expected_location)
+ @parameterized.expand(
+ [
+ ("deactivated_keeps_invites", "is_active", "/signup/{invite_id}", status.HTTP_200_OK),
+ ("deactivated_keeps_billing", "is_active", "/organization/billing", status.HTTP_200_OK),
+ ("deactivated_keeps_stripe_return", "is_active", "/billing/authorization_status", status.HTTP_200_OK),
+ ("pending_deletion_keeps_invites", "is_pending_deletion", "/signup/{invite_id}", status.HTTP_200_OK),
+ ("pending_deletion_drops_billing", "is_pending_deletion", "/organization/billing", status.HTTP_302_FOUND),
+ (
+ "pending_deletion_drops_stripe_return",
+ "is_pending_deletion",
+ "/billing/authorization_status",
+ status.HTTP_302_FOUND,
+ ),
+ ]
+ )
+ def test_blocked_organization_page_access(
+ self, _name: str, blocking_field: str, path_template: str, expected_status: int
+ ) -> None:
+ inviting_org = Organization.objects.create(name="Inviting Org")
+ invite = OrganizationInvite.objects.create(organization=inviting_org, target_email=self.user.email)
+
+ setattr(self.organization, blocking_field, blocking_field == "is_pending_deletion")
+ self.organization.save()
+
+ response = self.client.get(path_template.format(invite_id=invite.id))
+ self.assertEqual(response.status_code, expected_status)
+
+ def test_link_into_another_active_organization_loads(self):
+ active_org = Organization.objects.create(name="Active Org")
+ active_team = Team.objects.create(organization=active_org, name="Active Team")
+ self.user.organizations.add(active_org)
+
+ self.organization.is_active = False
+ self.organization.save()
+
+ response = self.client.get(f"/project/{active_team.pk}/dashboard")
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+
+ def test_runs_after_the_middleware_that_switches_project(self):
+ # The block check reads `current_organization`, so it only sees the organization a
+ # `/project/<id>` URL names once AutoProjectMiddleware has switched the user into it.
+ middleware = list(settings.MIDDLEWARE)
+ self.assertLess(
+ middleware.index("posthog.middleware.AutoProjectMiddleware"),
+ middleware.index("posthog.middleware.ActiveOrganizationMiddleware"),
+ )
+
class TestActivityLoggingMiddleware(APIBaseTest):
def setUp(self):