: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: apply correct permissions on team viewset (#59277)
Reece Jonesd4f7586ef5ec
diff --git a/frontend/src/generated/core/api.schemas.ts b/frontend/src/generated/core/api.schemas.tsindex dd61180625c9..444048edd42f 100644--- a/frontend/src/generated/core/api.schemas.ts+++ b/frontend/src/generated/core/api.schemas.ts@@ -570,10 +570,7 @@ export const AvailableSetupTaskIdsEnumApi = {} as const/**- * Like `ProjectBasicSerializer`, but also works as a drop-in replacement for `TeamBasicSerializer` by way of-passthrough fields. This allows the meaning of `Team` to change from "project" to "environment" without breaking-backward compatibility of the REST API.-Do not use this in greenfield endpoints!+ * Mixin for serializers to add user access control fields*/export interface ProjectBackwardCompatApi {readonly id: number@@ -1366,10 +1363,7 @@ export type PatchedProjectBackwardCompatApiProductIntentsItem = {}/**- * Like `ProjectBasicSerializer`, but also works as a drop-in replacement for `TeamBasicSerializer` by way of-passthrough fields. This allows the meaning of `Team` to change from "project" to "environment" without breaking-backward compatibility of the REST API.-Do not use this in greenfield endpoints!+ * Mixin for serializers to add user access control fields*/export interface PatchedProjectBackwardCompatApi {readonly id?: numberdiff --git a/frontend/src/generated/core/api.zod.ts b/frontend/src/generated/core/api.zod.tsindex 80598829e4b0..4995bee45cf1 100644--- a/frontend/src/generated/core/api.zod.ts+++ b/frontend/src/generated/core/api.zod.ts@@ -378,9 +378,7 @@ export const OrganizationsProjectsCreateBody = /* @__PURE__ */ zodlogs_settings: zod.unknown().optional(),proactive_tasks_enabled: zod.boolean().nullish(),})- .describe(- 'Like `ProjectBasicSerializer`, but also works as a drop-in replacement for `TeamBasicSerializer` by way of\npassthrough fields. This allows the meaning of `Team` to change from \"project\" to \"environment\" without breaking\nbackward compatibility of the REST API.\nDo not use this in greenfield endpoints!'- )+ .describe('Mixin for serializers to add user access control fields')/*** Replace a project and its settings. Prefer the PATCH endpoint for partial updates — PUT requires every writable field to be provided.@@ -570,9 +568,7 @@ export const OrganizationsProjectsUpdateBody = /* @__PURE__ */ zodlogs_settings: zod.unknown().optional(),proactive_tasks_enabled: zod.boolean().nullish(),})- .describe(- 'Like `ProjectBasicSerializer`, but also works as a drop-in replacement for `TeamBasicSerializer` by way of\npassthrough fields. This allows the meaning of `Team` to change from \"project\" to \"environment\" without breaking\nbackward compatibility of the REST API.\nDo not use this in greenfield endpoints!'- )+ .describe('Mixin for serializers to add user access control fields')/*** Update one or more of a project's settings. Only the fields included in the request body are changed.@@ -764,9 +760,7 @@ export const OrganizationsProjectsPartialUpdateBody = /* @__PURE__ */ zodlogs_settings: zod.unknown().optional(),proactive_tasks_enabled: zod.boolean().nullish(),})- .describe(- 'Like `ProjectBasicSerializer`, but also works as a drop-in replacement for `TeamBasicSerializer` by way of\npassthrough fields. This allows the meaning of `Team` to change from \"project\" to \"environment\" without breaking\nbackward compatibility of the REST API.\nDo not use this in greenfield endpoints!'- )+ .describe('Mixin for serializers to add user access control fields')/*** Projects for the current organization.@@ -970,9 +964,7 @@ export const OrganizationsProjectsAddProductIntentPartialUpdateBody = /* @__PURElogs_settings: zod.unknown().optional(),proactive_tasks_enabled: zod.boolean().nullish(),})- .describe(- 'Like `ProjectBasicSerializer`, but also works as a drop-in replacement for `TeamBasicSerializer` by way of\npassthrough fields. This allows the meaning of `Team` to change from \"project\" to \"environment\" without breaking\nbackward compatibility of the REST API.\nDo not use this in greenfield endpoints!'- )+ .describe('Mixin for serializers to add user access control fields')/*** Projects for the current organization.@@ -1168,9 +1160,7 @@ export const OrganizationsProjectsChangeOrganizationCreateBody = /* @__PURE__ */logs_settings: zod.unknown().optional(),proactive_tasks_enabled: zod.boolean().nullish(),})- .describe(- 'Like `ProjectBasicSerializer`, but also works as a drop-in replacement for `TeamBasicSerializer` by way of\npassthrough fields. This allows the meaning of `Team` to change from \"project\" to \"environment\" without breaking\nbackward compatibility of the REST API.\nDo not use this in greenfield endpoints!'- )+ .describe('Mixin for serializers to add user access control fields')/*** Projects for the current organization.@@ -1386,9 +1376,7 @@ export const OrganizationsProjectsCompleteProductOnboardingPartialUpdateBody = /logs_settings: zod.unknown().optional(),proactive_tasks_enabled: zod.boolean().nullish(),})- .describe(- 'Like `ProjectBasicSerializer`, but also works as a drop-in replacement for `TeamBasicSerializer` by way of\npassthrough fields. This allows the meaning of `Team` to change from \"project\" to \"environment\" without breaking\nbackward compatibility of the REST API.\nDo not use this in greenfield endpoints!'- )+ .describe('Mixin for serializers to add user access control fields')/*** Projects for the current organization.@@ -1600,9 +1588,7 @@ export const OrganizationsProjectsDeleteSecretTokenBackupPartialUpdateBody = /*logs_settings: zod.unknown().optional(),proactive_tasks_enabled: zod.boolean().nullish(),})- .describe(- 'Like `ProjectBasicSerializer`, but also works as a drop-in replacement for `TeamBasicSerializer` by way of\npassthrough fields. This allows the meaning of `Team` to change from \"project\" to \"environment\" without breaking\nbackward compatibility of the REST API.\nDo not use this in greenfield endpoints!'- )+ .describe('Mixin for serializers to add user access control fields')/*** Projects for the current organization.@@ -1818,9 +1804,7 @@ export const OrganizationsProjectsGenerateConversationsPublicTokenCreateBody = /logs_settings: zod.unknown().optional(),proactive_tasks_enabled: zod.boolean().nullish(),})- .describe(- 'Like `ProjectBasicSerializer`, but also works as a drop-in replacement for `TeamBasicSerializer` by way of\npassthrough fields. This allows the meaning of `Team` to change from \"project\" to \"environment\" without breaking\nbackward compatibility of the REST API.\nDo not use this in greenfield endpoints!'- )+ .describe('Mixin for serializers to add user access control fields')/*** Projects for the current organization.@@ -2012,9 +1996,7 @@ export const OrganizationsProjectsResetTokenPartialUpdateBody = /* @__PURE__ */logs_settings: zod.unknown().optional(),proactive_tasks_enabled: zod.boolean().nullish(),})- .describe(- 'Like `ProjectBasicSerializer`, but also works as a drop-in replacement for `TeamBasicSerializer` by way of\npassthrough fields. This allows the meaning of `Team` to change from \"project\" to \"environment\" without breaking\nbackward compatibility of the REST API.\nDo not use this in greenfield endpoints!'- )+ .describe('Mixin for serializers to add user access control fields')/*** Projects for the current organization.@@ -2218,9 +2200,7 @@ export const OrganizationsProjectsRotateSecretTokenPartialUpdateBody = /* @__PURlogs_settings: zod.unknown().optional(),proactive_tasks_enabled: zod.boolean().nullish(),})- .describe(- 'Like `ProjectBasicSerializer`, but also works as a drop-in replacement for `TeamBasicSerializer` by way of\npassthrough fields. This allows the meaning of `Team` to change from \"project\" to \"environment\" without breaking\nbackward compatibility of the REST API.\nDo not use this in greenfield endpoints!'- )+ .describe('Mixin for serializers to add user access control fields')export const dashboardTemplatesUpdateBodyTemplateNameMax = 400diff --git a/posthog/api/project.py b/posthog/api/project.pyindex 2fcd83712822..b90a8bf276f1 100644--- a/posthog/api/project.py+++ b/posthog/api/project.py@@ -17,7 +17,7 @@ from posthog.schema import ProductKeyfrom posthog.api.routing import TeamAndOrgViewSetMixinfrom posthog.api.shared import ProjectBackwardCompatBasicSerializerfrom posthog.api.team import (- TEAM_CONFIG_FIELDS_SET,+ TEAM_CONFIG_MEMBER_FIELDS_SET,TeamSerializer,get_or_mint_live_events_token,handle_conversations_token_on_update,@@ -47,6 +47,7 @@ from posthog.models.product_intent.product_intent import ()from posthog.models.project import Projectfrom posthog.models.team.setup_tasks import SetupTaskId+from posthog.models.team.team import Teamfrom posthog.models.team.util import actions_that_require_current_teamfrom posthog.models.utils import UUIDTfrom posthog.permissions import (@@ -58,6 +59,11 @@ from posthog.permissions import (TeamMemberStrictManagementPermission,get_organization_from_view,)+from posthog.rbac.user_access_control import (+ UserAccessControlSerializerMixin,+ get_field_access_control_map,+ resource_to_display_name,+)from posthog.scopes import APIScopeObjectOrNotSupportedfrom posthog.tasks.tasks import delete_project_data_and_notify_taskfrom posthog.user_permissions import UserPermissions, UserPermissionsSerializerMixin@@ -80,7 +86,11 @@ class ProjectSerializer(serializers.ModelSerializer):read_only_fields = ["id", "organization_id", "created_at"]-class ProjectBackwardCompatSerializer(ProjectBackwardCompatBasicSerializer, UserPermissionsSerializerMixin):+class ProjectBackwardCompatSerializer(+ UserAccessControlSerializerMixin,+ ProjectBackwardCompatBasicSerializer,+ UserPermissionsSerializerMixin,+):effective_membership_level = serializers.SerializerMethodField() # Compat with TeamSerializerhas_group_types = serializers.SerializerMethodField() # Compat with TeamSerializergroup_types = serializers.SerializerMethodField() # Compat with TeamSerializer@@ -426,7 +436,26 @@ class ProjectBackwardCompatSerializer(ProjectBackwardCompatBasicSerializer, Userreturn TeamSerializer.validate_proactive_tasks_enabled(cast(TeamSerializer, self), value)def validate(self, attrs: Any) -> Any:- attrs = validate_team_attrs(attrs, self.context["view"], self.context["request"], self.instance)+ attrs = validate_team_attrs(attrs, self.context["view"], self.instance)++ if self.instance:+ field_mappings = get_field_access_control_map(Team)+ user_access_control = self.user_access_control+ if field_mappings and user_access_control is not None:+ team = self.instance.passthrough_team+ for field_name in attrs:+ if field_name not in field_mappings:+ continue+ resource, required_level = field_mappings[field_name]+ if resource == "project":+ has_access = user_access_control.check_access_level_for_object(team, required_level)+ else:+ has_access = user_access_control.check_access_level_for_resource(resource, required_level)+ if not has_access:+ display_name = resource_to_display_name(resource)+ raise serializers.ValidationError(+ {field_name: f"You need {required_level} access to {display_name} to modify this field."}+ )return super().validate(attrs)def create(self, validated_data: dict[str, Any], **kwargs) -> Project:@@ -680,17 +709,14 @@ class ProjectViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixin, viewsetsif mixin_result is not None:return mixin_result- # If the request only contains config fields, require read:team scope- # Otherwise, require write:team scope (handled by APIScopePermission)- # NOTE: This downgrade only applies to session-based auth (browser users).- # All other auth methods (API keys, OAuth tokens, etc.) must have project:write- # to modify any fields, preserving the semantic meaning of read-only API keys.+ # See TeamViewSet.dangerously_get_required_scopes for the rationale. Only downgrade+ # to project:read when every field is a member-safe team config field; anything else+ # falls through to project:write so admin-only settings require admin object access.if self.action == "partial_update":is_session_auth = isinstance(request.successful_authenticator, SessionAuthentication)if is_session_auth:request_fields = set(request.data.keys())- non_team_config_fields = request_fields - TEAM_CONFIG_FIELDS_SET- if not non_team_config_fields:+ if request_fields and request_fields.issubset(TEAM_CONFIG_MEMBER_FIELDS_SET):return ["project:read"]# Fall back to the default behaviordiff --git a/posthog/api/team.py b/posthog/api/team.pyindex 6b40098e422e..c35b76956354 100644--- a/posthog/api/team.py+++ b/posthog/api/team.py@@ -226,6 +226,25 @@ TEAM_CONFIG_FIELDS = (TEAM_CONFIG_FIELDS_SET = set(TEAM_CONFIG_FIELDS)+TEAM_CONFIG_MEMBER_FIELDS = (+ "completed_snippet_onboarding",+ "has_completed_onboarding_for",+ "onboarding_tasks",+ "session_recording_opt_in",+ "autocapture_exceptions_opt_in",+ "autocapture_web_vitals_opt_in",+ "autocapture_web_vitals_allowed_metrics",+ "surveys_opt_in",+ "primary_dashboard",+)+TEAM_CONFIG_MEMBER_FIELDS_SET = set(TEAM_CONFIG_MEMBER_FIELDS)++TEAM_CONFIG_ADMIN_FIELDS_SET: set[str] = (TEAM_CONFIG_FIELDS_SET - TEAM_CONFIG_MEMBER_FIELDS_SET) | {+ "is_demo",+ "app_urls",+ "access_control",+}+class TeamRevenueAnalyticsConfigSerializer(serializers.ModelSerializer, UserAccessControlSerializerMixin):events = serializers.JSONField(required=False)@@ -1124,7 +1143,7 @@ class TeamSerializer(serializers.ModelSerializer, UserPermissionsSerializerMixinraise exceptions.PermissionDenied("Proactive tasks can only be enabled for authorized teams.")def validate(self, attrs: Any) -> Any:- attrs = validate_team_attrs(attrs, self.context["view"], self.context["request"], self.instance)+ attrs = validate_team_attrs(attrs, self.context["view"], self.instance)return super().validate(attrs)def create(self, validated_data: dict[str, Any], **kwargs) -> Team:@@ -1478,8 +1497,6 @@ class TeamViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixin, viewsets.Moif mixin_result is not None:return mixin_result- # If the request only contains config fields, require read:team scope- # Otherwise, require write:team scope (handled by APIScopePermission)# NOTE: This downgrade only applies to session-based auth (browser users).# All other auth methods (API keys, OAuth tokens, etc.) must have project:write# to modify any fields, preserving the semantic meaning of read-only API keys.@@ -1487,8 +1504,7 @@ class TeamViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixin, viewsets.Mois_session_auth = isinstance(request.successful_authenticator, SessionAuthentication)if is_session_auth:request_fields = set(request.data.keys())- non_team_config_fields = request_fields - TEAM_CONFIG_FIELDS_SET- if not non_team_config_fields:+ if request_fields and request_fields.issubset(TEAM_CONFIG_MEMBER_FIELDS_SET):return ["project:read"]# Team-level config actions that any member should be able to edit via the UI.@@ -2039,8 +2055,18 @@ def handle_conversations_token_on_update(def validate_team_attrs(- attrs: dict[str, Any], view: TeamAndOrgViewSetMixin, request: request.Request, instance: Team | Project | None+ attrs: dict[str, Any], view: TeamAndOrgViewSetMixin, instance: Team | Project | None) -> dict[str, Any]:+ if instance is not None:+ admin_fields_touched = TEAM_CONFIG_ADMIN_FIELDS_SET & attrs.keys()+ if admin_fields_touched:+ team_for_check = instance if isinstance(instance, Team) else instance.passthrough_team+ level = view.user_permissions.team(team_for_check).effective_membership_level+ if level is None or level < OrganizationMembership.Level.ADMIN:+ raise exceptions.PermissionDenied(+ "Only project admins can modify these settings: " + ", ".join(sorted(admin_fields_touched))+ )+if "primary_dashboard" in attrs:if not instance:raise exceptions.ValidationError(diff --git a/posthog/api/test/test_team.py b/posthog/api/test/test_team.pyindex 2faa2340d6c2..40130c032208 100644--- a/posthog/api/test/test_team.py+++ b/posthog/api/test/test_team.py@@ -19,7 +19,12 @@ from rest_framework import status, testfrom temporalio.service import RPCErrorfrom posthog.api.oauth.test_dcr import generate_rsa_key-from posthog.api.team import _default_data_color_theme_id, _reset_default_data_color_theme_id_cache+from posthog.api.team import (+ TEAM_CONFIG_FIELDS_SET,+ TEAM_CONFIG_MEMBER_FIELDS_SET,+ _default_data_color_theme_id,+ _reset_default_data_color_theme_id_cache,+)from posthog.api.test.batch_exports.conftest import start_test_workerfrom posthog.constants import AvailableFeaturefrom posthog.models import ActivityLog@@ -52,6 +57,13 @@ def team_api_test_factory():class TestTeamAPI(APIBaseTest, QueryMatchingTest):"""Tests for /api/environments/."""+ def setUp(self):+ super().setUp()+ OrganizationMembership.objects.filter(pk=self.organization_membership.pk).update(+ level=OrganizationMembership.Level.ADMIN+ )+ self.organization_membership.refresh_from_db()+def _assert_activity_log(self, expected: list[dict], team_id: int | None = None) -> None:if not team_id:team_id = self.team.pk@@ -489,9 +501,11 @@ def team_api_test_factory():mock_delete_task_team: MagicMock,mock_delete_task_project: MagicMock,):- self.organization_membership.level = OrganizationMembership.Level.ADMIN- self.organization_membership.save()-+ # NOTE: the factory-level setUp already bumps to ADMIN (without firing the+ # "membership level changed" event because it uses .update() to bypass signals),+ # so this test no longer needs to bump the level itself. It also no longer asserts+ # the membership-level-changed capture event since the bump now happens before+ # `mock_capture` is patched.team: Team = Team.objects.create_with_data(initiating_user=self.user, organization=self.organization)team_pk = team.pk@@ -503,12 +517,6 @@ def team_api_test_factory():# Team deletion happens async in the (mocked) Celery task, so team still exists# We only verify the task was queued correctlyexpected_capture_calls = [- call(- distinct_id=self.user.distinct_id,- event="membership level changed",- properties={"new_level": 8, "previous_level": 1, "$set": mock.ANY},- groups=mock.ANY,- ),call(distinct_id=self.user.distinct_id,event="team deleted",@@ -788,6 +796,8 @@ def team_api_test_factory():)def test_reset_token_insufficient_privileges(self):+ self.organization_membership.level = OrganizationMembership.Level.MEMBER+ self.organization_membership.save()self.team.api_token = "xyz"self.team.save()@@ -1023,6 +1033,8 @@ def team_api_test_factory():)def test_rotate_secret_token_insufficient_privileges(self):+ self.organization_membership.level = OrganizationMembership.Level.MEMBER+ self.organization_membership.save()self.team.secret_api_token = "phs_JVRb8fNi0XyIKGgUCyi29ZJUOXEr6NF2dKBy5Ws8XVeF11C"self.team.secret_api_token_backup = Noneself.team.save()@@ -1034,6 +1046,8 @@ def team_api_test_factory():self.assertIsNone(self.team.secret_api_token_backup)def test_delete_secret_token_backup_insufficient_privileges(self):+ self.organization_membership.level = OrganizationMembership.Level.MEMBER+ self.organization_membership.save()self.team.secret_api_token = "phs_JVRb8fNi0XyIKGgUCyi29ZJUOXEr6NF2dKBy5Ws8XVeF11C"self.team.secret_api_token_backup = "phs_ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"self.team.save()@@ -2079,6 +2093,8 @@ def team_api_test_factory():assert settings["widget_color"] == "#123456"def test_generate_conversations_public_token_requires_admin(self):+ self.organization_membership.level = OrganizationMembership.Level.MEMBER+ self.organization_membership.save()response = self.client.post(f"/api/environments/{self.team.id}/generate_conversations_public_token/")assert response.status_code == status.HTTP_403_FORBIDDEN@@ -2249,25 +2265,26 @@ def team_api_test_factory():model.refresh_from_db()self.assertEqual(model.name, "New Team Name")- def test_session_auth_member_can_still_update_config_fields(self):- """Session-based auth (browser users) with member role should still be able to update config fields.-- This test ensures we didn't break existing UI behavior while fixing the API key issue.+ def test_session_auth_member_can_still_update_member_safe_config_fields(self):+ """Session-based auth (browser users) with member role can still update member-safe+ config fields (the onboarding-style toggles the UI does not gate behind+ TeamMembershipLevel.Admin). Admin-only fields are tested separately in+ test_team_admin_authorization_vulnerability.py."""self.organization_membership.level = OrganizationMembership.Level.MEMBERself.organization_membership.save()response = self.client.patch("/api/environments/@current/",- {"timezone": "Europe/Lisbon", "session_recording_opt_in": True},+ {"session_recording_opt_in": True, "surveys_opt_in": True},)self.assertEqual(response.status_code, status.HTTP_200_OK)# Verify changes were madeself.team.refresh_from_db()- self.assertEqual(self.team.timezone, "Europe/Lisbon")self.assertEqual(self.team.session_recording_opt_in, True)+ self.assertEqual(self.team.surveys_opt_in, True)@override_settings(DEBUG=True)def test_update_proactive_tasks_enabled_true_creates_signal_source_config(self):@@ -3039,7 +3056,11 @@ class TestTeamAPI(team_api_test_factory()): # type: ignoreself.assertEqual(self.team.timezone, "UTC")self.assertEqual(self.team.session_recording_opt_in, False)- def test_team_member_can_write_to_team_config_without_access_control(self):+ def test_team_member_can_write_to_member_safe_team_config_without_access_control(self):+ # Member-safe team config (e.g. session_recording_opt_in, which onboarding flips) must+ # remain writable by org MEMBERs even without paid access control. Admin-only fields+ # like `timezone` are exercised separately in+ # posthog/api/test/test_team_admin_authorization_vulnerability.py.self.organization_membership.level = OrganizationMembership.Level.MEMBERself.organization_membership.save()@@ -3053,18 +3074,34 @@ class TestTeamAPI(team_api_test_factory()): # type: ignoreresponse = self.client.patch("/api/environments/@current/",- {"timezone": "Europe/Lisbon", "session_recording_opt_in": True},+ {"session_recording_opt_in": True, "surveys_opt_in": True},)self.assertEqual(response.status_code, status.HTTP_200_OK)response_data = response.json()- self.assertEqual(response_data["timezone"], "Europe/Lisbon")self.assertEqual(response_data["session_recording_opt_in"], True)+ self.assertEqual(response_data["surveys_opt_in"], True)# Verify changes were madeself.team.refresh_from_db()- self.assertEqual(self.team.timezone, "Europe/Lisbon")self.assertEqual(self.team.session_recording_opt_in, True)+ self.assertEqual(self.team.surveys_opt_in, True)++ def test_team_member_cannot_write_to_admin_team_config_without_access_control(self):+ # Regression test for the admin-authorization bypass: members must NOT be able to+ # change admin-only settings via the API even when the org has no paid access control,+ # because the frontend gates these settings behind TeamMembershipLevel.Admin.+ self.organization_membership.level = OrganizationMembership.Level.MEMBER+ self.organization_membership.save()++ response = self.client.patch(+ "/api/environments/@current/",+ {"timezone": "Europe/Lisbon"},+ )+ self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)++ self.team.refresh_from_db()+ self.assertNotEqual(self.team.timezone, "Europe/Lisbon")def test_team_admin_can_write_to_team_patch_with_access_control(self):self.organization_membership.level = OrganizationMembership.Level.ADMIN@@ -3130,7 +3167,9 @@ class TestTeamAPI(team_api_test_factory()): # type: ignoreself.assertEqual(self.team.timezone, "UTC")self.assertEqual(self.team.session_recording_opt_in, False)- def test_team_member_can_write_to_team_patch_without_access_control(self):+ def test_team_member_can_write_to_member_safe_team_patch_without_access_control(self):+ # See test_team_member_can_write_to_member_safe_team_config_without_access_control above:+ # member-safe fields stay writable; admin-only fields (timezone) are covered separately.self.organization_membership.level = OrganizationMembership.Level.MEMBERself.organization_membership.save()@@ -3144,14 +3183,14 @@ class TestTeamAPI(team_api_test_factory()): # type: ignoreresponse = self.client.patch("/api/environments/@current/",- {"timezone": "Europe/Lisbon", "session_recording_opt_in": True},+ {"session_recording_opt_in": True, "surveys_opt_in": True},)self.assertEqual(response.status_code, status.HTTP_200_OK)# Verify changes were madeself.team.refresh_from_db()- self.assertEqual(self.team.timezone, "Europe/Lisbon")self.assertEqual(self.team.session_recording_opt_in, True)+ self.assertEqual(self.team.surveys_opt_in, True)@freeze_time("2025-01-01T00:00:00Z")def test_settings_as_of_requires_at_param(self):@@ -3417,3 +3456,259 @@ class TestGetOrMintLiveEventsToken(APIBaseTest):with override_settings(SECRET_KEY="completely-different-rotated-secret"):token_new_secret = get_or_mint_live_events_token(self.team, self.user.id)assert token_old_secret != token_new_secret+++# Sensitive Team/Project settings the frontend gates behind+# `TeamMembershipLevel.Admin` AND that ordinary members are not expected to flip+# from any onboarding/dashboard surface. Each tuple is+# (field, value_to_patch, attr_on_team_to_assert).+# Values are chosen to differ from the Team-model default so a successful PATCH would+# observably change the persisted state.+_ADMIN_GATED_TEAM_CONFIG_FIELDS: list[tuple[str, Any, str]] = [+ ("timezone", "Europe/Lisbon", "timezone"),+ ("anonymize_ips", True, "anonymize_ips"),+ ("autocapture_opt_out", True, "autocapture_opt_out"),+ ("data_attributes", ["data-cy"], "data_attributes"),+ ("week_start_day", 1, "week_start_day"),+ ("path_cleaning_filters", [{"alias": "x", "regex": "/x/.*"}], "path_cleaning_filters"),+ # capture_console_log_opt_in defaults to True, so patch with False to observe change.+ ("capture_console_log_opt_in", False, "capture_console_log_opt_in"),+ ("heatmaps_opt_in", True, "heatmaps_opt_in"),+ ("recording_domains", ["https://evil.example.com"], "recording_domains"),+ ("session_recording_sample_rate", "0.5", "session_recording_sample_rate"),+ # capture_dead_clicks defaults to False so True is observable. Exposed by+ # TeamSerializer but NOT by ProjectBackwardCompatSerializer — env-only.+ ("capture_dead_clicks", True, "capture_dead_clicks"),+]++# Subset of _ADMIN_GATED_TEAM_CONFIG_FIELDS that are also patchable via /api/projects/+# (i.e. listed in ProjectBackwardCompatSerializer.Meta.fields). Fields like+# `capture_dead_clicks` and `onboarding_tasks` exist on Team but are not exposed by the+# project serializer, so they're not part of the projects-side attack surface and don't+# belong in the projects-side regression set.+_ADMIN_GATED_TEAM_CONFIG_FIELDS_FOR_PROJECTS: list[tuple[str, Any, str]] = [+ f for f in _ADMIN_GATED_TEAM_CONFIG_FIELDS if f[0] != "capture_dead_clicks"+]++# Settings ordinary members are EXPECTED to flip from the UI today (onboarding flow,+# dashboards, primary-dashboard pinning, etc.). These should keep working for MEMBER+# after the fix — captured as positive regression tests so the security fix doesn't+# silently break onboarding for invitees.+_MEMBER_SAFE_TEAM_CONFIG_FIELDS: list[tuple[str, Any, str]] = [+ ("session_recording_opt_in", True, "session_recording_opt_in"),+ ("autocapture_exceptions_opt_in", True, "autocapture_exceptions_opt_in"),+ ("autocapture_web_vitals_opt_in", True, "autocapture_web_vitals_opt_in"),+ ("surveys_opt_in", True, "surveys_opt_in"),+ ("has_completed_onboarding_for", {"product_analytics": True}, "has_completed_onboarding_for"),+ ("completed_snippet_onboarding", True, "completed_snippet_onboarding"),+]++# Subset of _MEMBER_SAFE_TEAM_CONFIG_FIELDS that are also exposed by the project serializer.+# `onboarding_tasks` isn't in ProjectBackwardCompatSerializer.Meta.fields, so it can't be+# patched through /api/projects/ regardless of permissions.+_MEMBER_SAFE_TEAM_CONFIG_FIELDS_FOR_PROJECTS: list[tuple[str, Any, str]] = [+ f for f in _MEMBER_SAFE_TEAM_CONFIG_FIELDS if f[0] != "onboarding_tasks"+]++# Fields the frontend treats as admin-only that previously lacked a+# `@field_access_control` annotation on the model. Captured as a regression so+# anyone removing the decorator (or adding a new admin-UI-gated field without one)+# gets a failing test pointing at the right place.+_UNANNOTATED_SENSITIVE_FIELDS: list[tuple[str, Any, str]] = [+ ("is_demo", True, "is_demo"),+ ("app_urls", ["https://evil.example.com"], "app_urls"),+]+++class TestTeamAdminFieldAuthorization(APIBaseTest):+ def setUp(self) -> None:+ super().setUp()+ # Demote the auto-logged-in user to a plain MEMBER. The frontend would hide+ # every setting below behind useRestrictedArea(Admin), so the API must reject too.+ self.organization_membership.level = OrganizationMembership.Level.MEMBER+ self.organization_membership.save()++ @parameterized.expand([(f[0], f[1], f[2]) for f in _ADMIN_GATED_TEAM_CONFIG_FIELDS])+ def test_member_cannot_patch_admin_gated_field_via_environments(+ self, field: str, value: Any, team_attr: str+ ) -> None:+ # Every field in this list is a TEAM_CONFIG_FIELD that is NOT a member-safe field.+ assert field in TEAM_CONFIG_FIELDS_SET, f"{field} not in TEAM_CONFIG_FIELDS_SET"+ assert field not in TEAM_CONFIG_MEMBER_FIELDS_SET, (+ f"{field} is in TEAM_CONFIG_MEMBER_FIELDS_SET — if intentionally member-safe, move"+ " it to _MEMBER_SAFE_TEAM_CONFIG_FIELDS instead."+ )++ response = self.client.patch("/api/environments/@current/", {field: value}, format="json")++ assert response.status_code == status.HTTP_403_FORBIDDEN, (+ f"Expected 403 Forbidden for MEMBER patching admin-gated field {field!r}, "+ f"got {response.status_code}: {response.json()}"+ )+ self.team.refresh_from_db()+ assert getattr(self.team, team_attr) != value, (+ f"Field {field!r} was persisted by a MEMBER (value={value!r}) — admin-only setting was modified."+ )++ @parameterized.expand([(f[0], f[1], f[2]) for f in _ADMIN_GATED_TEAM_CONFIG_FIELDS_FOR_PROJECTS])+ def test_member_cannot_patch_admin_gated_field_via_projects(self, field: str, value: Any, team_attr: str) -> None:+ response = self.client.patch(f"/api/projects/{self.project.id}/", {field: value}, format="json")++ assert response.status_code == status.HTTP_403_FORBIDDEN, (+ f"Expected 403 Forbidden for MEMBER patching admin-gated field {field!r} via /api/projects/, "+ f"got {response.status_code}: {response.json()}"+ )+ self.team.refresh_from_db()+ assert getattr(self.team, team_attr) != value, (+ f"Field {field!r} was persisted via /api/projects/ by a MEMBER (value={value!r}) — "+ "ProjectBackwardCompatSerializer is bypassing field-level access control."+ )++ @parameterized.expand(_UNANNOTATED_SENSITIVE_FIELDS)+ def test_member_cannot_patch_unannotated_sensitive_field_via_environments(+ self, field: str, value: Any, team_attr: str+ ) -> None:+ response = self.client.patch("/api/environments/@current/", {field: value}, format="json")++ assert response.status_code == status.HTTP_403_FORBIDDEN, (+ f"Expected 403 Forbidden for MEMBER patching unannotated sensitive field {field!r}, "+ f"got {response.status_code}: {response.json()}"+ )+ self.team.refresh_from_db()+ assert getattr(self.team, team_attr) != value, (+ f"Unannotated field {field!r} was persisted by a MEMBER (value={value!r}). "+ "Add @field_access_control on the Team model."+ )++ @parameterized.expand(_UNANNOTATED_SENSITIVE_FIELDS)+ def test_member_cannot_patch_unannotated_sensitive_field_via_projects(+ self, field: str, value: Any, team_attr: str+ ) -> None:+ response = self.client.patch(f"/api/projects/{self.project.id}/", {field: value}, format="json")++ assert response.status_code == status.HTTP_403_FORBIDDEN, (+ f"Expected 403 Forbidden for MEMBER patching unannotated sensitive field {field!r} via /api/projects/, "+ f"got {response.status_code}: {response.json()}"+ )+ self.team.refresh_from_db()+ assert getattr(self.team, team_attr) != value++ @parameterized.expand(_MEMBER_SAFE_TEAM_CONFIG_FIELDS)+ def test_member_can_still_patch_member_safe_field_via_environments(+ self, field: str, value: Any, team_attr: str+ ) -> None:+ assert field in TEAM_CONFIG_MEMBER_FIELDS_SET, (+ f"{field} is not declared member-safe in TEAM_CONFIG_MEMBER_FIELDS_SET. "+ "If onboarding / dashboards rely on it, add it there; otherwise remove from this test list."+ )+ response = self.client.patch("/api/environments/@current/", {field: value}, format="json")+ assert response.status_code == status.HTTP_200_OK, (+ f"MEMBER unexpectedly blocked from patching member-safe field {field!r}: "+ f"status={response.status_code}, body={response.json()}. "+ "This would break onboarding / dashboard flows for invitee users."+ )+ self.team.refresh_from_db()+ assert getattr(self.team, team_attr) == value++ @parameterized.expand(_MEMBER_SAFE_TEAM_CONFIG_FIELDS_FOR_PROJECTS)+ def test_member_can_still_patch_member_safe_field_via_projects(+ self, field: str, value: Any, team_attr: str+ ) -> None:+ response = self.client.patch(f"/api/projects/{self.project.id}/", {field: value}, format="json")+ assert response.status_code == status.HTTP_200_OK, (+ f"MEMBER unexpectedly blocked from patching member-safe field {field!r} via /api/projects/: "+ f"status={response.status_code}, body={response.json()}."+ )+ self.team.refresh_from_db()+ assert getattr(self.team, team_attr) == value++ def test_mixed_member_and_admin_fields_is_rejected_for_member(self) -> None:+ # A member request that bundles a member-safe field with an admin-only field must+ # be rejected as a whole — otherwise an attacker could hide admin writes behind a+ # legitimate-looking onboarding patch.+ response = self.client.patch(+ "/api/environments/@current/",+ {"surveys_opt_in": True, "timezone": "Europe/Lisbon"},+ format="json",+ )+ assert response.status_code == status.HTTP_403_FORBIDDEN, (+ f"Mixed member-safe + admin-only patch should be rejected: "+ f"status={response.status_code}, body={response.json()}"+ )+ self.team.refresh_from_db()+ assert self.team.timezone != "Europe/Lisbon"+ # Even the safe field must not be applied when the request is rejected.+ assert self.team.surveys_opt_in is not True++ def _enable_access_control_with_member_level(self) -> None:+ self.organization.available_product_features = [+ {"key": AvailableFeature.ACCESS_CONTROL, "name": AvailableFeature.ACCESS_CONTROL}+ ]+ self.organization.save()+ # Default project access for the org is "member" (not "admin"). The user is a MEMBER.+ AccessControl.objects.create(+ team=self.team,+ resource="project",+ resource_id=str(self.team.id),+ access_level="member",+ )++ def test_member_with_member_access_control_is_blocked_on_environments_for_admin_field(self) -> None:+ # Baseline: the existing field_access_control mixin enforces on /api/environments/+ # when access_control is on. timezone is field_access_control(..., "project", "admin").+ self._enable_access_control_with_member_level()++ response = self.client.patch("/api/environments/@current/", {"timezone": "Europe/Lisbon"}, format="json")++ assert response.status_code != status.HTTP_200_OK, (+ "Regression: /api/environments/ should reject MEMBER-level project access for "+ "field_access_control('project','admin') fields like timezone."+ )+ self.team.refresh_from_db()+ assert self.team.timezone != "Europe/Lisbon"++ def test_member_with_member_access_control_is_blocked_on_projects_for_admin_field(self) -> None:+ # /api/projects/ must also enforce: ProjectBackwardCompatSerializer now mixes in+ # UserAccessControlSerializerMixin (with a Team-aware validate override).+ self._enable_access_control_with_member_level()++ response = self.client.patch(f"/api/projects/{self.project.id}/", {"timezone": "Europe/Lisbon"}, format="json")++ assert response.status_code == status.HTTP_403_FORBIDDEN, (+ f"/api/projects/ failed to enforce field_access_control on 'timezone' for a MEMBER "+ f"(status={response.status_code}, body={response.json()}). "+ "ProjectBackwardCompatSerializer needs UserAccessControlSerializerMixin."+ )+ self.team.refresh_from_db()+ assert self.team.timezone != "Europe/Lisbon"++ def _personal_api_key(self, scopes: list[str]) -> str:+ token = generate_random_token_personal()+ PersonalAPIKey.objects.create(+ label="ro",+ user=self.user,+ secure_value=hash_key_value(token),+ scopes=scopes,+ )+ return token++ def test_read_only_personal_api_key_cannot_patch_team_config(self) -> None:+ token = self._personal_api_key(["project:read"])++ response = self.client.patch(+ "/api/environments/@current/",+ {"timezone": "Europe/Lisbon"},+ format="json",+ headers={"authorization": f"Bearer {token}"},+ )++ assert response.status_code in (status.HTTP_401_UNAUTHORIZED, status.HTTP_403_FORBIDDEN), (+ f"Read-only personal API key was allowed to patch team config: status={response.status_code}, "+ f"body={response.json()}. The session-auth scope downgrade must remain session-only."+ )++ def test_member_cannot_delete_team(self) -> None:+ # Create a second team in the same project so the org isn't left team-less.+ other = Team.objects.create(organization=self.organization, project=self.project, name="other")+ response = self.client.delete(f"/api/environments/{other.id}/")+ assert response.status_code == status.HTTP_403_FORBIDDENdiff --git a/posthog/models/team/team.py b/posthog/models/team/team.pyindex 342ddde24382..2de3d3eb8056 100644--- a/posthog/models/team/team.py+++ b/posthog/models/team/team.py@@ -304,7 +304,9 @@ class Team(UUIDTClassicModel):default=generate_random_token_project,validators=[MinLengthValidator(10, "Project's API token must be at least 10 characters long!")],)- app_urls: ArrayField = ArrayField(models.CharField(max_length=200, null=True), default=list, blank=True)+ app_urls: ArrayField = field_access_control(+ ArrayField(models.CharField(max_length=200, null=True), default=list, blank=True), "project", "admin"+ )name = models.CharField(max_length=200,default="Default project",@@ -493,7 +495,7 @@ class Team(UUIDTClassicModel):models.CharField(null=True, blank=True, max_length=24), "project", "admin")signup_token = models.CharField(max_length=200, null=True, blank=True)- is_demo = models.BooleanField(default=False)+ is_demo = field_access_control(models.BooleanField(default=False), "project", "admin")# DEPRECATED - do not useaccess_control = models.BooleanField(default=False)diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 05b01b2f2353..277276aa0f36 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -28504,10 +28504,7 @@ export namespace Schemas {} as const;/**- * Like `ProjectBasicSerializer`, but also works as a drop-in replacement for `TeamBasicSerializer` by way of- passthrough fields. This allows the meaning of `Team` to change from "project" to "environment" without breaking- backward compatibility of the REST API.- Do not use this in greenfield endpoints!+ * Mixin for serializers to add user access control fields*/export interface PatchedProjectBackwardCompat {readonly id?: number;@@ -31376,10 +31373,7 @@ export namespace Schemas {};/**- * Like `ProjectBasicSerializer`, but also works as a drop-in replacement for `TeamBasicSerializer` by way of- passthrough fields. This allows the meaning of `Team` to change from "project" to "environment" without breaking- backward compatibility of the REST API.- Do not use this in greenfield endpoints!+ * Mixin for serializers to add user access control fields*/export interface ProjectBackwardCompat {readonly id: number;diff --git a/services/mcp/src/generated/core/api.ts b/services/mcp/src/generated/core/api.tsindex 5764a93a5978..5e314669eeac 100644--- a/services/mcp/src/generated/core/api.ts+++ b/services/mcp/src/generated/core/api.ts@@ -265,9 +265,7 @@ export const OrganizationsProjectsPartialUpdateBody = /* @__PURE__ */ zodlogs_settings: zod.unknown().optional(),proactive_tasks_enabled: zod.boolean().nullish(),})- .describe(- 'Like `ProjectBasicSerializer`, but also works as a drop-in replacement for `TeamBasicSerializer` by way of\npassthrough fields. This allows the meaning of `Team` to change from "project" to "environment" without breaking\nbackward compatibility of the REST API.\nDo not use this in greenfield endpoints!'- )+ .describe('Mixin for serializers to add user access control fields')export const SubscriptionsListParams = /* @__PURE__ */ zod.object({project_id: zod