: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
feat(rbac): migrate unaffected organizations to most-specific resolution (#94555)
Alex Liderf45dc1a60bb0
diff --git a/products/access_control/backend/facade/most_specific_migration.py b/products/access_control/backend/facade/most_specific_migration.pynew file mode 100644index 000000000000..d274c4ea0d84--- /dev/null+++ b/products/access_control/backend/facade/most_specific_migration.py@@ -0,0 +1,129 @@+"""Finds the organizations still on the legacy access resolution that the most-specific+resolution does not affect, and switches them over.++An organization is not affected when it has no access rules, or when every rule resolves+the same under both resolutions on every team (see `resolution_preview`). Organizations+that resolve differently, and organizations the preview cannot evaluate, are reported and+stay on the legacy resolution.+"""++from collections import Counter, defaultdict+from collections.abc import Iterable+from datetime import datetime+from itertools import batched+from uuid import UUID++from django.db.models import Exists, OuterRef, QuerySet+from django.utils import timezone++from posthog.dataclasses import frozen+from posthog.models.organization import Organization++from products.access_control.backend.facade.resolution_preview import ResolutionChange, iter_resolution_changes+from products.access_control.backend.models.access_control import AccessControl++_UPDATE_BATCH_SIZE = 500+++@frozen+class OrganizationChanges:+ """How many rules on an organization resolve differently, across its evaluated teams."""++ id: UUID+ name: str+ teams: int+ changes: int+ gains: int+ loses: int+++@frozen+class OrganizationRef:+ id: UUID+ name: str+++@frozen+class MigrationCandidates:+ """Every organization still on the legacy resolution, sorted by what the switch would do."""++ # When the classification started. Rules written after this may invalidate it.+ found_at: datetime+ divergent: list[OrganizationChanges]+ unchanged: list[OrganizationChanges]+ unevaluated: list[OrganizationRef]+ without_rules: list[UUID]++ @property+ def unaffected_ids(self) -> list[UUID]:+ return [org.id for org in self.unchanged] + self.without_rules+++def _pending_organizations() -> QuerySet[Organization]:+ # The column is nullable and NULL means legacy, so exclude True rather than filter False+ return Organization.objects.exclude(uses_most_specific_access_resolution=True)+++def find_organizations_to_migrate() -> MigrationCandidates:+ found_at = timezone.now()+ names: dict[UUID, str] = {}+ teams_by_org: Counter[UUID] = Counter()+ changes_by_org: defaultdict[UUID, list[ResolutionChange]] = defaultdict(list)+ for team, changes in iter_resolution_changes(only_pending=True):+ names[team.organization_id] = team.organization.name+ teams_by_org[team.organization_id] += 1+ changes_by_org[team.organization_id].extend(changes)++ evaluated = [+ OrganizationChanges(+ id=org_id,+ name=names[org_id],+ teams=teams_by_org[org_id],+ changes=len(changes),+ gains=sum(change.direction == "gains" for change in changes),+ loses=sum(change.direction == "loses" for change in changes),+ )+ for org_id, changes in changes_by_org.items()+ ]+ divergent = sorted((org for org in evaluated if org.changes > 0), key=lambda org: org.changes, reverse=True)+ unchanged = sorted((org for org in evaluated if org.changes == 0), key=lambda org: str(org.id))++ organizations_with_rules = AccessControl.objects.values("team__organization_id")+ unevaluated = [+ OrganizationRef(id=org_id, name=name)+ for org_id, name in _pending_organizations()+ .filter(id__in=organizations_with_rules)+ .exclude(id__in=changes_by_org.keys())+ .order_by("id")+ .values_list("id", "name")+ ]+ without_rules = list(+ _pending_organizations().exclude(id__in=organizations_with_rules).order_by("id").values_list("id", flat=True)+ )+ return MigrationCandidates(+ found_at=found_at,+ divergent=divergent,+ unchanged=unchanged,+ unevaluated=unevaluated,+ without_rules=without_rules,+ )+++def enable_most_specific_resolution(organization_ids: Iterable[UUID], *, rules_unchanged_since: datetime) -> int:+ """Switch the given organizations to the most-specific resolution. Returns the number of+ rows updated. Batched so one run never holds a long lock on the organization table.++ An organization whose access rules were written at or after `rules_unchanged_since` is+ left alone: the classification that approved it no longer describes its rules.+ """+ rules_written_since = AccessControl.objects.filter(+ team__organization_id=OuterRef("id"), updated_at__gte=rules_unchanged_since+ )+ updated = 0+ for batch in batched(organization_ids, _UPDATE_BATCH_SIZE, strict=False):+ updated += (+ Organization.objects.filter(id__in=batch)+ .exclude(Exists(rules_written_since))+ .update(uses_most_specific_access_resolution=True)+ )+ return updateddiff --git a/products/access_control/backend/facade/resolution_preview.py b/products/access_control/backend/facade/resolution_preview.pyindex 85dd7964a009..25936aa963b6 100644--- a/products/access_control/backend/facade/resolution_preview.py+++ b/products/access_control/backend/facade/resolution_preview.py@@ -6,8 +6,8 @@ rules and every resource that has resource-level rows. Return one change recordscope) pair whose level differs. Members are never enumerated: members with the same applicablerules resolve identically, so one subject-level record covers all of them.-Read-only. Nothing here changes enforcement. The settings preview page and the divergent-org-sweep command are the only callers.+Read-only. Nothing here changes enforcement. The settings preview page and the+migration command are the only callers."""from collections.abc import Iterator@@ -382,16 +382,21 @@ def build_resolution_preview(team: Team, user_access_control: UserAccessControl)return changes-def iter_resolution_changes(organization_id: Optional[str] = None) -> "Iterator[tuple[Team, list[ResolutionChange]]]":+def iter_resolution_changes(+ organization_id: Optional[str] = None, *, only_pending: bool = False+) -> "Iterator[tuple[Team, list[ResolutionChange]]]":"""Yield (team, changes) for every team with access rules, ordered by organization.Resolution is evaluated as one acting active member per organization; teams of- organizations with no active member are skipped.+ organizations with no active member are skipped. With `only_pending`, organizations+ already on the most-specific resolution are skipped too: they are migrated already."""team_ids = AccessControl.objects.values_list("team_id", flat=True).distinct()teams = Team.objects.filter(id__in=team_ids).select_related("organization").order_by("organization_id")if organization_id is not None:teams = teams.filter(organization_id=organization_id)+ if only_pending:+ teams = teams.exclude(organization__uses_most_specific_access_resolution=True)acting_membership_by_org: dict[str, Optional[OrganizationMembership]] = {}for team in teams.iterator():diff --git a/products/access_control/backend/management/commands/migrate_to_most_specific_access.py b/products/access_control/backend/management/commands/migrate_to_most_specific_access.pyindex bab9ed9e594e..090717e3e1f2 100644--- a/products/access_control/backend/management/commands/migrate_to_most_specific_access.py+++ b/products/access_control/backend/management/commands/migrate_to_most_specific_access.py@@ -2,60 +2,55 @@ from typing import Anyfrom django.core.management.base import BaseCommand-from posthog.models.organization import Organization--from products.access_control.backend.facade.resolution_preview import iter_resolution_changes-from products.access_control.backend.models.access_control import AccessControl+from products.access_control.backend.facade.most_specific_migration import (+ MigrationCandidates,+ enable_most_specific_resolution,+ find_organizations_to_migrate,+)class Command(BaseCommand):- help = (- "Report readiness for most-specific access resolution across organizations that have access "- "rules: those that resolve differently first, then those where nothing changes, then those "- "that could not be evaluated (no active member to resolve as). Organizations with no rules "- "cannot resolve differently and are omitted. Read-only for now; migration comes later, so "- "--dry-run and a plain run print the same report."- )+ help = "Switch organizations that the most-specific access resolution does not affect over to it"def add_arguments(self, parser: Any) -> None:parser.add_argument("--dry-run", action="store_true", help="Report only, migrate nothing")def handle(self, *args: Any, **options: Any) -> None:- totals: dict[Any, dict[str, int]] = {}- names: dict[Any, str] = {}-- for team, changes in iter_resolution_changes():- org_id = team.organization_id- names[org_id] = team.organization.name- counts = totals.setdefault(org_id, {"teams": 0, "changes": 0, "gains": 0, "loses": 0})- counts["teams"] += 1- counts["changes"] += len(changes)- counts["gains"] += sum(1 for change in changes if change.direction == "gains")- counts["loses"] += sum(1 for change in changes if change.direction == "loses")-- divergent = {org_id: counts for org_id, counts in totals.items() if counts["changes"] > 0}- unchanged = {org_id: counts for org_id, counts in totals.items() if counts["changes"] == 0}-- self.stdout.write(f"{len(divergent)} organizations resolve differently")- for org_id, counts in sorted(divergent.items(), key=lambda item: -item[1]["changes"]):+ candidates = find_organizations_to_migrate()+ self._report(candidates)++ unaffected_ids = candidates.unaffected_ids+ if options["dry_run"]:+ self.stdout.write(f"Dry run: {len(unaffected_ids)} organizations would be migrated")+ return+ updated = enable_most_specific_resolution(unaffected_ids, rules_unchanged_since=candidates.found_at)+ self.stdout.write(f"Migrated {updated} organizations")+ if updated < len(unaffected_ids):+ self.stdout.write(+ f"{len(unaffected_ids) - updated} organizations skipped because their rules changed during the run"+ )++ def _report(self, candidates: MigrationCandidates) -> None:+ self.stdout.write(+ f"{len(candidates.divergent)} organizations resolve differently (stay on the legacy resolution)"+ )+ for org in candidates.divergent:self.stdout.write(- f"{org_id}\t{names[org_id]}\tteams={counts['teams']}\t"- f"changes={counts['changes']}\tgains={counts['gains']}\tloses={counts['loses']}"+ f"{org.id}\t{org.name}\tteams={org.teams}\tchanges={org.changes}\tgains={org.gains}\tloses={org.loses}")self.stdout.write("")- self.stdout.write(f"{len(unchanged)} organizations where nothing changes")- for org_id, counts in sorted(unchanged.items(), key=lambda item: str(item[0])):- self.stdout.write(f"{org_id}\t{names[org_id]}\tteams={counts['teams']}")-- # Organizations with rules that yielded no evaluation: no active member to resolve as- unevaluated = dict(- Organization.objects.filter(teams__id__in=AccessControl.objects.values("team_id"))- .exclude(id__in=totals.keys())- .distinct()- .values_list("id", "name")+ self.stdout.write(f"{len(candidates.unchanged)} organizations with rules where nothing changes")+ for org in candidates.unchanged:+ self.stdout.write(f"{org.id}\t{org.name}\tteams={org.teams}")++ self.stdout.write("")+ self.stdout.write(+ f"{len(candidates.unevaluated)} organizations could not be evaluated (no active member, stay on the legacy resolution)")+ for ref in candidates.unevaluated:+ self.stdout.write(f"{ref.id}\t{ref.name}")++ self.stdout.write("")+ self.stdout.write(f"{len(candidates.without_rules)} organizations with no access rules")self.stdout.write("")- self.stdout.write(f"{len(unevaluated)} organizations could not be evaluated (no active member)")- for org_id, name in sorted(unevaluated.items(), key=lambda item: str(item[0])):- self.stdout.write(f"{org_id}\t{name}")diff --git a/products/access_control/backend/tests/test_migrate_to_most_specific_access.py b/products/access_control/backend/tests/test_migrate_to_most_specific_access.pynew file mode 100644index 000000000000..6e88c9218f49--- /dev/null+++ b/products/access_control/backend/tests/test_migrate_to_most_specific_access.py@@ -0,0 +1,112 @@+from io import StringIO++import pytest++from django.core.management import call_command++from posthog.constants import AvailableFeature+from posthog.models.organization import Organization+from posthog.models.team.team import Team+from posthog.models.user import User++from products.access_control.backend.facade.most_specific_migration import (+ enable_most_specific_resolution,+ find_organizations_to_migrate,+)+from products.access_control.backend.models.access_control import AccessControl+from products.access_control.backend.tests.test_user_access_control import BaseUserAccessControlTest+from products.dashboards.backend.models.dashboard import Dashboard+++class TestMigrateToMostSpecificAccess(BaseUserAccessControlTest):+ def setUp(self) -> None:+ super().setUp()+ # self.organization resolves differently: the resource-level editor row beats the+ # object's own viewer row under the legacy resolution only+ self.organization.uses_most_specific_access_resolution = False+ self.organization.save()+ dashboard = Dashboard.objects.create(team=self.team, created_by=self.user, name="Growth KPIs")+ self._create_access_control(resource="dashboard", resource_id=str(dashboard.id), access_level="viewer")+ self._create_access_control(resource="dashboard", access_level="editor")++ self.unchanged_organization = self._create_legacy_organization("Unchanged org")+ team = Team.objects.create(organization=self.unchanged_organization, name="Unchanged team")+ User.objects.create_and_join(self.unchanged_organization, "[email protected]", "testtest")+ AccessControl.objects.create(team=team, resource="dashboard", access_level="viewer")++ self.unevaluated_organization = self._create_legacy_organization("No member org")+ team = Team.objects.create(organization=self.unevaluated_organization, name="No member team")+ AccessControl.objects.create(team=team, resource="dashboard", access_level="viewer")++ self.organization_without_rules = self._create_legacy_organization("No rules org")++ def _create_legacy_organization(self, name: str) -> Organization:+ return Organization.objects.create(+ name=name,+ uses_most_specific_access_resolution=False,+ available_product_features=[+ {"key": AvailableFeature.ACCESS_CONTROL, "name": AvailableFeature.ACCESS_CONTROL}+ ],+ )++ def _resolution_flags(self) -> dict[str, bool]:+ return {+ org.name: org.uses_most_specific_access_resolution+ for org in Organization.objects.filter(+ id__in=[+ self.organization.id,+ self.unchanged_organization.id,+ self.unevaluated_organization.id,+ self.organization_without_rules.id,+ ]+ )+ }++ def test_migrates_only_organizations_the_change_does_not_affect(self) -> None:+ out = StringIO()+ call_command("migrate_to_most_specific_access", stdout=out)++ assert self._resolution_flags() == {+ self.organization.name: False,+ "Unchanged org": True,+ "No member org": False,+ "No rules org": True,+ }+ assert f"{self.organization.id}\t{self.organization.name}\tteams=1\tchanges=1" in out.getvalue()+ assert f"{self.unevaluated_organization.id}\tNo member org" in out.getvalue()++ def test_dry_run_reports_but_migrates_nothing(self) -> None:+ out = StringIO()+ call_command("migrate_to_most_specific_access", "--dry-run", stdout=out)++ assert self._resolution_flags() == {+ self.organization.name: False,+ "Unchanged org": False,+ "No member org": False,+ "No rules org": False,+ }+ assert "would be migrated" in out.getvalue()++ def test_rules_written_after_the_classification_block_the_switch(self) -> None:+ candidates = find_organizations_to_migrate()+ team = self.unchanged_organization.teams.get()+ AccessControl.objects.create(team=team, resource="insight", access_level="editor")++ updated = enable_most_specific_resolution(candidates.unaffected_ids, rules_unchanged_since=candidates.found_at)++ assert updated == 1 # only "No rules org"+ assert self._resolution_flags() == {+ self.organization.name: False,+ "Unchanged org": False,+ "No member org": False,+ "No rules org": True,+ }++ def test_skips_organizations_already_on_most_specific_resolution(self) -> None:+ self.unchanged_organization.uses_most_specific_access_resolution = True+ self.unchanged_organization.save()+ out = StringIO()+ call_command("migrate_to_most_specific_access", stdout=out)++ assert "Unchanged org" not in out.getvalue()