: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): let org admins accept the most-specific resolution (#95291)
Alex Lider87ae0952c5d6
diff --git a/frontend/src/generated/core/api.schemas.ts b/frontend/src/generated/core/api.schemas.tsindex d1e7828cf717..ee7d82ec2792 100644--- a/frontend/src/generated/core/api.schemas.ts+++ b/frontend/src/generated/core/api.schemas.ts@@ -4443,6 +4443,11 @@ export interface OrganizationApi {* @nullable*/readonly is_pending_deletion: boolean | null+ /**+ * When True, access controls resolve with the most specific matching rule. When False, the legacy resolution order applies.+ * @nullable+ */+ readonly uses_most_specific_access_resolution: boolean | null}/**diff --git a/frontend/src/layout/navigation-3000/sidepanel/panels/access_control/ResolutionPreview/AccessResolutionPreview.tsx b/frontend/src/layout/navigation-3000/sidepanel/panels/access_control/ResolutionPreview/AccessResolutionPreview.tsxindex 05836676481b..0775ce54618f 100644--- a/frontend/src/layout/navigation-3000/sidepanel/panels/access_control/ResolutionPreview/AccessResolutionPreview.tsx+++ b/frontend/src/layout/navigation-3000/sidepanel/panels/access_control/ResolutionPreview/AccessResolutionPreview.tsx@@ -5,6 +5,7 @@ import {LemonBanner,LemonButton,LemonCollapse,+ LemonDialog,LemonTable,LemonTableColumns,LemonTag,@@ -13,6 +14,7 @@ import {} from '@posthog/lemon-ui'import { supportLogic } from 'lib/components/Support/supportLogic'+import { organizationLogic } from 'scenes/organizationLogic'import { urls } from 'scenes/urls'import { objectRuleUrl } from '~/layout/navigation-3000/sidepanel/panels/access_control/ResourceAccessControlsV2/accessDetailLogic'@@ -109,9 +111,26 @@ const sharedColumns: LemonTableColumns<ResolutionChange> = []export function AccessResolutionPreview(): JSX.Element {- const { preview, previewLoading, previewForbidden } = useValues(resolutionPreviewLogic)- const { loadPreview } = useActions(resolutionPreviewLogic)+ const { preview, previewLoading, previewForbidden, accepted, acceptedLoading } = useValues(resolutionPreviewLogic)+ const { loadPreview, acceptResolution } = useActions(resolutionPreviewLogic)const { openSupportForm } = useActions(supportLogic)+ const { currentOrganization, isAdminOrOwner } = useValues(organizationLogic)+ // `accepted` keeps the completed state if the organization reload after the switch fails+ const alreadyEnabled = accepted || !!currentOrganization?.uses_most_specific_access_resolution++ const confirmAccept = (): void => {+ LemonDialog.open({+ title: 'Switch to the most specific rule now?',+ description: 'The changes listed here take effect right away.',+ maxWidth: '30rem',+ primaryButton: {+ children: 'Confirm',+ onClick: acceptResolution,+ 'data-attr': 'access-resolution-accept-confirm',+ },+ secondaryButton: { children: 'Cancel' },+ })+ }if (previewLoading) {return <Spinner className="text-lg" />@@ -133,6 +152,33 @@ export function AccessResolutionPreview(): JSX.Element {</LemonBanner>)}+ const footer = alreadyEnabled ? (+ <LemonBanner type="success">Migration completed.</LemonBanner>+ ) : (+ <div className="flex items-center gap-2">+ <LemonButton+ type="primary"+ onClick={confirmAccept}+ loading={acceptedLoading}+ disabledReason={isAdminOrOwner ? undefined : 'Only organization admins can switch the resolution'}+ data-attr="access-resolution-accept"+ >+ Accept the new resolution+ </LemonButton>+ <LemonButton+ type="secondary"+ onClick={() => openSupportForm({ kind: 'support' })}+ data-attr="access-resolution-keep-current"+ >+ Keep current access+ </LemonButton>+ <span className="text-muted text-xs">+ Contact support to keep the current access for all members. We will adjust your rules so everyone's+ effective access stays the same.+ </span>+ </div>+ )+if (preview.summary.total === 0) {return (<div className="flex flex-col gap-4">@@ -141,6 +187,7 @@ export function AccessResolutionPreview(): JSX.Element {No access rules resolve differently in the projects you administer. Nothing changes when the newresolution takes effect.</LemonBanner>+ {footer}</div>)}@@ -276,22 +323,7 @@ export function AccessResolutionPreview(): JSX.Element {)})}- <div className="flex items-center gap-2">- <LemonButton type="primary" disabledReason="Not available yet" data-attr="access-resolution-accept">- Accept the new resolution- </LemonButton>- <LemonButton- type="secondary"- onClick={() => openSupportForm({ kind: 'support' })}- data-attr="access-resolution-keep-current"- >- Keep current access- </LemonButton>- <span className="text-muted text-xs">- Contact support to keep the current access for all members. We will adjust your rules so everyone's- effective access stays the same.- </span>- </div>+ {footer}</div>)}diff --git a/frontend/src/layout/navigation-3000/sidepanel/panels/access_control/ResolutionPreview/resolutionPreviewLogic.ts b/frontend/src/layout/navigation-3000/sidepanel/panels/access_control/ResolutionPreview/resolutionPreviewLogic.tsindex 60aebca5a353..964fb8efa33c 100644--- a/frontend/src/layout/navigation-3000/sidepanel/panels/access_control/ResolutionPreview/resolutionPreviewLogic.ts+++ b/frontend/src/layout/navigation-3000/sidepanel/panels/access_control/ResolutionPreview/resolutionPreviewLogic.ts@@ -1,7 +1,8 @@-import { MakeLogicType, afterMount, connect, kea, path, reducers } from 'kea'+import { MakeLogicType, afterMount, connect, kea, listeners, path, reducers } from 'kea'import { loaders } from 'kea-loaders'import api from 'lib/api'+import { organizationLogic } from 'scenes/organizationLogic'import { teamLogic } from 'scenes/teamLogic'export interface ResolutionChangeSubject {@@ -49,6 +50,8 @@ export interface ResolutionPreviewResponse {// Generated by kea-typegen. Update if you're an agent, ignore if you're human.export interface resolutionPreviewLogicValues {currentTeamIdStrict: number | string // teamLogic+ accepted: boolean+ acceptedLoading: booleanpreview: ResolutionPreviewResponse | nullpreviewForbidden: booleanpreviewLoading: boolean@@ -56,6 +59,22 @@ export interface resolutionPreviewLogicValues {// Generated by kea-typegen. Update if you're an agent, ignore if you're human.export interface resolutionPreviewLogicActions {+ loadCurrentOrganization: () => any // organizationLogic+ acceptResolution: () => any+ acceptResolutionFailure: (+ error: string,+ errorObject?: any+ ) => {+ error: string+ errorObject?: any+ }+ acceptResolutionSuccess: (+ accepted: boolean,+ payload?: any+ ) => {+ accepted: boolean+ payload?: any+ }loadPreview: () => anyloadPreviewFailure: (error: string,@@ -85,7 +104,10 @@ export const resolutionPreviewLogic = kea<resolutionPreviewLogicType>(['ResolutionPreview','resolutionPreviewLogic',]),- connect(() => ({ values: [teamLogic, ['currentTeamIdStrict']] })),+ connect(() => ({+ values: [teamLogic, ['currentTeamIdStrict']],+ actions: [organizationLogic, ['loadCurrentOrganization']],+ })),loaders(({ values }) => ({preview: [null as ResolutionPreviewResponse | null,@@ -96,6 +118,15 @@ export const resolutionPreviewLogic = kea<resolutionPreviewLogicType>([),},],+ accepted: [+ false,+ {+ acceptResolution: async () => {+ await api.create(`api/projects/${values.currentTeamIdStrict}/access_control_resolution_accept`)+ return true+ },+ },+ ],})),reducers({previewForbidden: [@@ -106,6 +137,10 @@ export const resolutionPreviewLogic = kea<resolutionPreviewLogicType>([},],}),+ listeners(({ actions }) => ({+ // The organization carries the setting the page renders from+ acceptResolutionSuccess: () => actions.loadCurrentOrganization(),+ })),afterMount(({ actions }) => {actions.loadPreview()}),diff --git a/frontend/src/types.ts b/frontend/src/types.tsindex 8fdc7a6bde80..d11e11c87d16 100644--- a/frontend/src/types.ts+++ b/frontend/src/types.ts@@ -613,6 +613,7 @@ export interface OrganizationType extends OrganizationBasicType {default_experiment_stats_method: ExperimentStatsMethoddefault_anonymize_ips?: booleandefault_role_id?: string | null+ uses_most_specific_access_resolution?: boolean | null}export interface OrganizationDomainType {diff --git a/posthog/api/organization.py b/posthog/api/organization.pyindex 0869cf41cc79..39ebe9e7a649 100644--- a/posthog/api/organization.py+++ b/posthog/api/organization.py@@ -213,6 +213,7 @@ class OrganizationSerializer("is_active","is_not_active_reason","is_pending_deletion",+ "uses_most_specific_access_resolution",]read_only_fields = ["id",@@ -233,6 +234,7 @@ class OrganizationSerializer("is_ai_training_locked","is_ai_training_cta_shown","has_signed_baa",+ "uses_most_specific_access_resolution",]extra_kwargs = {"slug": {diff --git a/posthog/models/activity_logging/activity_log.py b/posthog/models/activity_logging/activity_log.pyindex ced3106af088..7dd6072e99e0 100644--- a/posthog/models/activity_logging/activity_log.py+++ b/posthog/models/activity_logging/activity_log.py@@ -360,6 +360,7 @@ field_name_overrides: dict[AuditableScope, dict[str, str]] = {"session_cookie_age": "session cookie age","default_experiment_stats_method": "default experiment stats method","is_ai_data_processing_approved": "third-party AI services",+ "uses_most_specific_access_resolution": "most-specific access resolution",},"BatchExport": {"paused": "enabled",diff --git a/products/access_control/backend/presentation/access_control_settings.py b/products/access_control/backend/presentation/access_control_settings.pyindex b5d50bf47fe6..4e0783a75d29 100644--- a/products/access_control/backend/presentation/access_control_settings.py+++ b/products/access_control/backend/presentation/access_control_settings.py@@ -57,6 +57,7 @@ from .serializers import (AccessControlMembersResponseSerializer,AccessControlObjectRulesResponseSerializer,AccessControlPropertyRulesResponseSerializer,+ AccessControlResolutionAcceptResponseSerializer,AccessControlRolesResponseSerializer,)@@ -143,6 +144,8 @@ class AccessControlSettingsViewSetMixin(_GenericViewSet):return ["access_control:read"]if request.method == "PUT" and self.action == "access_control_object_rules":return ["access_control:write"]+ if request.method == "POST" and self.action == "access_control_resolution_accept":+ return ["access_control:write"]parent = getattr(super(), "dangerously_get_required_scopes", None)return parent(request, view) if parent is not None else None@@ -216,6 +219,31 @@ class AccessControlSettingsViewSetMixin(_GenericViewSet):django_cache.set(cache_key, payload, timeout=300)return Response(payload)+ @extend_schema(exclude=True)+ @action(methods=["POST"], detail=True, url_path="access_control_resolution_accept")+ def access_control_resolution_accept(self, request: Request, *args, **kwargs) -> Response:+ """Switch the organization to most-specific access resolution.++ Organization admins only: the switch applies to every project in the organization, so+ a project admin cannot make it. The change is logged on the organization."""+ team = cast(Team, self.team) # type: ignore+ user_access_control = cast(UserAccessControl, self.user_access_control) # type: ignore+ if not user_access_control.is_organization_admin:+ raise exceptions.PermissionDenied("Only organization admins can accept the new resolution.")+ # The switch reaches every project, so a credential limited to some projects may not make it+ if get_authenticator_scoped_team_ids(request.successful_authenticator) is not None:+ raise exceptions.PermissionDenied(+ "A credential scoped to specific projects cannot accept the new resolution."+ )++ organization = team.organization+ if not organization.uses_most_specific_access_resolution:+ organization.uses_most_specific_access_resolution = True+ organization.save(update_fields=["uses_most_specific_access_resolution", "updated_at"])+ return Response(+ AccessControlResolutionAcceptResponseSerializer({"uses_most_specific_access_resolution": True}).data+ )+@extend_schema(description="The project's default access. Returns the level that applies to the project and to each ""resource type when a member or a role has no rule of their own. Also lists the resource types that accept "diff --git a/products/access_control/backend/presentation/serializers.py b/products/access_control/backend/presentation/serializers.pyindex db0dc6bb529d..0523a61f1f17 100644--- a/products/access_control/backend/presentation/serializers.py+++ b/products/access_control/backend/presentation/serializers.py@@ -275,3 +275,9 @@ class AccessControlPropertyRulesResponseSerializer(serializers.Serializer):results = AccessControlPropertyRuleSerializer(many=True, help_text="The subject's property rules, sorted by property type and name.")+++class AccessControlResolutionAcceptResponseSerializer(serializers.Serializer):+ uses_most_specific_access_resolution = serializers.BooleanField(+ help_text="Always true: the organization now resolves access with the most specific rule."+ )diff --git a/products/access_control/backend/tests/test_resolution_preview.py b/products/access_control/backend/tests/test_resolution_preview.pyindex 9a187a7c89d2..01f734fda811 100644--- a/products/access_control/backend/tests/test_resolution_preview.py+++ b/products/access_control/backend/tests/test_resolution_preview.py@@ -5,6 +5,7 @@ from django.apps import appsfrom parameterized import parameterizedfrom rest_framework import status+from posthog.models.activity_logging.activity_log import ActivityLogfrom posthog.models.organization import OrganizationMembershipfrom posthog.models.personal_api_key import PersonalAPIKeyfrom posthog.models.team.team import Team@@ -231,6 +232,65 @@ class TestResolutionPreviewAPI(BaseUserAccessControlTest):response = self.client.get("/api/projects/@current/access_control_resolution_preview")assert response.status_code == status.HTTP_200_OK+ def test_accept_requires_org_admin(self):+ self._create_access_control(resource="project", resource_id=str(self.team.id), access_level="admin")++ response = self.client.post("/api/projects/@current/access_control_resolution_accept")++ assert response.status_code == status.HTTP_403_FORBIDDEN+ self.organization.refresh_from_db()+ assert not self.organization.uses_most_specific_access_resolution++ def test_accept_rejects_project_scoped_credentials(self):+ self.membership.level = OrganizationMembership.Level.ADMIN+ self.membership.save()+ key = generate_random_token_personal()+ PersonalAPIKey.objects.create(+ label="scoped", user=self.user, secure_value=hash_key_value(key), scoped_teams=[self.team.id], scopes=["*"]+ )+ self.client.logout()++ response = self.client.post(+ f"/api/projects/{self.team.id}/access_control_resolution_accept",+ headers={"authorization": f"Bearer {key}"},+ )++ assert response.status_code == status.HTTP_403_FORBIDDEN+ self.organization.refresh_from_db()+ assert not self.organization.uses_most_specific_access_resolution++ def test_accept_switches_the_organization_and_logs_it(self):+ self.membership.level = OrganizationMembership.Level.ADMIN+ self.membership.save()++ response = self.client.post("/api/projects/@current/access_control_resolution_accept")++ assert response.status_code == status.HTTP_200_OK+ assert response.json() == {"uses_most_specific_access_resolution": True}+ self.organization.refresh_from_db()+ assert self.organization.uses_most_specific_access_resolution+ log = ActivityLog.objects.filter(scope="Organization", item_id=str(self.organization.id)).latest("created_at")+ assert log.activity == "updated"+ assert log.detail is not None+ assert any(+ change["field"] == "most-specific access resolution" and change["after"] is True+ for change in log.detail["changes"]+ )++ def test_accept_is_idempotent(self):+ self.membership.level = OrganizationMembership.Level.ADMIN+ self.membership.save()+ self.organization.uses_most_specific_access_resolution = True+ self.organization.save()+ logs_before = ActivityLog.objects.filter(scope="Organization", item_id=str(self.organization.id)).count()++ response = self.client.post("/api/projects/@current/access_control_resolution_accept")++ assert response.status_code == status.HTTP_200_OK+ assert (+ ActivityLog.objects.filter(scope="Organization", item_id=str(self.organization.id)).count() == logs_before+ )+def test_returns_changes_and_summary(self):self.membership.level = OrganizationMembership.Level.ADMINself.membership.save()diff --git a/products/platform_features/frontend/generated/api.schemas.ts b/products/platform_features/frontend/generated/api.schemas.tsindex 6d36c8b97e49..eb570d73b0b5 100644--- a/products/platform_features/frontend/generated/api.schemas.ts+++ b/products/platform_features/frontend/generated/api.schemas.ts@@ -152,6 +152,11 @@ export interface OrganizationApi {* @nullable*/readonly is_pending_deletion: boolean | null+ /**+ * When True, access controls resolve with the most specific matching rule. When False, the legacy resolution order applies.+ * @nullable+ */+ readonly uses_most_specific_access_resolution: boolean | null}export interface PaginatedOrganizationListApi {@@ -260,6 +265,11 @@ export interface PatchedOrganizationApi {* @nullable*/readonly is_pending_deletion?: boolean | null+ /**+ * When True, access controls resolve with the most specific matching rule. When False, the legacy resolution order applies.+ * @nullable+ */+ readonly uses_most_specific_access_resolution?: boolean | null}export interface OrganizationRemoveBlockedMembersResponseApi {diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 868ffb4166cf..29d65ef06703 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -57308,6 +57308,11 @@ export namespace Schemas {* @nullable*/readonly is_pending_deletion: boolean | null;+ /**+ * When True, access controls resolve with the most specific matching rule. When False, the legacy resolution order applies.+ * @nullable+ */+ readonly uses_most_specific_access_resolution: boolean | null;}export interface OrganizationAIAccessRequestResponse {@@ -69705,6 +69710,11 @@ export namespace Schemas {* @nullable*/readonly is_pending_deletion?: boolean | null;+ /**+ * When True, access controls resolve with the most specific matching rule. When False, the legacy resolution order applies.+ * @nullable+ */+ readonly uses_most_specific_access_resolution?: boolean | null;}export interface PatchedOrganizationDomain {