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(flags): require project admin to edit default release conditions (#73294)

Gustavo H. Strassburger5ebcf665afe5
diff --git a/frontend/src/generated/core/api.ts b/frontend/src/generated/core/api.ts
index 529edd4faf68..114ea750bb72 100644
--- a/frontend/src/generated/core/api.ts
+++ b/frontend/src/generated/core/api.ts
@@ -856,7 +856,8 @@ export const getOrganizationsProjectsDefaultEvaluationContextsRetrieveUrl = (org
}
/**
- * Manage default evaluation contexts for a project.
+ * Manage default evaluation contexts for a project. Members can read; writing requires
+ * project admin, matching the admin-only settings UI.
*/
export const organizationsProjectsDefaultEvaluationContextsRetrieve = async (
organizationId: string,
@@ -877,7 +878,8 @@ export const getOrganizationsProjectsDefaultEvaluationContextsCreateUrl = (organ
}
/**
- * Manage default evaluation contexts for a project.
+ * Manage default evaluation contexts for a project. Members can read; writing requires
+ * project admin, matching the admin-only settings UI.
*/
export const organizationsProjectsDefaultEvaluationContextsCreate = async (
organizationId: string,
@@ -901,7 +903,8 @@ export const getOrganizationsProjectsDefaultEvaluationContextsDestroyUrl = (orga
}
/**
- * Manage default evaluation contexts for a project.
+ * Manage default evaluation contexts for a project. Members can read; writing requires
+ * project admin, matching the admin-only settings UI.
*/
export const organizationsProjectsDefaultEvaluationContextsDestroy = async (
organizationId: string,
@@ -919,7 +922,8 @@ export const getOrganizationsProjectsDefaultReleaseConditionsRetrieveUrl = (orga
}
/**
- * Manage default release conditions for new feature flags in this project.
+ * Manage default release conditions for new feature flags in this project. Members can read;
+ * writing requires project admin, matching the admin-only settings UI.
*/
export const organizationsProjectsDefaultReleaseConditionsRetrieve = async (
organizationId: string,
@@ -940,7 +944,8 @@ export const getOrganizationsProjectsDefaultReleaseConditionsUpdateUrl = (organi
}
/**
- * Manage default release conditions for new feature flags in this project.
+ * Manage default release conditions for new feature flags in this project. Members can read;
+ * writing requires project admin, matching the admin-only settings UI.
*/
export const organizationsProjectsDefaultReleaseConditionsUpdate = async (
organizationId: string,
diff --git a/frontend/src/generated/core/api.zod.ts b/frontend/src/generated/core/api.zod.ts
index 5b5cb2fe36b7..dd7672286d81 100644
--- a/frontend/src/generated/core/api.zod.ts
+++ b/frontend/src/generated/core/api.zod.ts
@@ -4012,7 +4012,8 @@ export const OrganizationsProjectsCompleteProductOnboardingPartialUpdateBody = /
.describe('Mixin for serializers to add user access control fields')
/**
- * Manage default evaluation contexts for a project.
+ * Manage default evaluation contexts for a project. Members can read; writing requires
+ * project admin, matching the admin-only settings UI.
*/
export const organizationsProjectsDefaultEvaluationContextsCreateBodyNameMax = 200
@@ -4635,7 +4636,8 @@ export const OrganizationsProjectsDefaultEvaluationContextsCreateBody = /* @__PU
.describe('Mixin for serializers to add user access control fields')
/**
- * Manage default release conditions for new feature flags in this project.
+ * Manage default release conditions for new feature flags in this project. Members can read;
+ * writing requires project admin, matching the admin-only settings UI.
*/
export const organizationsProjectsDefaultReleaseConditionsUpdateBodyNameMax = 200
diff --git a/frontend/src/scenes/feature-flags/DefaultEvaluationContexts.tsx b/frontend/src/scenes/feature-flags/DefaultEvaluationContexts.tsx
index 0da3372b0b71..47a746752794 100644
--- a/frontend/src/scenes/feature-flags/DefaultEvaluationContexts.tsx
+++ b/frontend/src/scenes/feature-flags/DefaultEvaluationContexts.tsx
@@ -64,7 +64,12 @@ export function DefaultEvaluationContexts(): JSX.Element | null {
type="success"
icon={<IconBolt />}
closable
- onClose={() => removeContext(ctx.name)}
+ disabledReason={restrictedReason}
+ onClose={() => {
+ if (!restrictedReason) {
+ removeContext(ctx.name)
+ }
+ }}
>
{ctx.name}
</LemonTag>
diff --git a/posthog/api/project.py b/posthog/api/project.py
index 6271dae8d262..26b094f0f9cb 100644
--- a/posthog/api/project.py
+++ b/posthog/api/project.py
@@ -1395,9 +1395,10 @@ class ProjectViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixin, viewsets
if request_fields and request_fields.issubset(downgradable_fields):
return ["project:read"]
- # Team-level config actions that any member should be able to edit via the UI.
- # Only downgrade for session auth to preserve read-only API key semantics.
- if self.action in ("default_release_conditions", "default_evaluation_contexts"):
+ # Team-level config actions members can read via the UI. Only downgrade for session auth to
+ # preserve read-only API key semantics; writes are still gated to admins by the action's
+ # TeamMemberStrictManagementPermission.
+ if self.action in ("default_evaluation_contexts",):
is_session_auth = isinstance(request.successful_authenticator, SessionAuthentication)
if is_session_auth:
return ["project:read"]
@@ -1652,11 +1653,12 @@ class ProjectViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixin, viewsets
@action(
methods=["GET", "PUT"],
detail=True,
- permission_classes=[TeamMemberLightManagementPermission],
+ permission_classes=[TeamMemberStrictManagementPermission],
url_path="default_release_conditions",
)
def default_release_conditions(self, request: request.Request, id: str, **kwargs) -> response.Response:
- """Manage default release conditions for new feature flags in this project."""
+ """Manage default release conditions for new feature flags in this project. Members can read;
+ writing requires project admin, matching the admin-only settings UI."""
return team_default_release_conditions_view(self.get_object().passthrough_team, request)
@action(
@@ -1672,10 +1674,11 @@ class ProjectViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixin, viewsets
@action(
methods=["GET", "POST", "DELETE"],
detail=True,
- permission_classes=[IsAuthenticated],
+ permission_classes=[TeamMemberStrictManagementPermission],
)
def default_evaluation_contexts(self, request: request.Request, id: str, **kwargs) -> response.Response:
- """Manage default evaluation contexts for a project."""
+ """Manage default evaluation contexts for a project. Members can read; writing requires
+ project admin, matching the admin-only settings UI."""
return team_default_evaluation_contexts_view(self.get_object().passthrough_team, request, self.user_permissions)
@extend_schema(
diff --git a/posthog/api/team.py b/posthog/api/team.py
index a57f8dc7d4b0..0104eb633c0c 100644
--- a/posthog/api/team.py
+++ b/posthog/api/team.py
@@ -1,6 +1,5 @@
import re
import json
-import math
import secrets
from datetime import timedelta
from functools import cached_property
@@ -90,12 +89,7 @@ from posthog.utils import (
)
from products.customer_analytics.backend.facade.team_extension import TeamCustomerAnalyticsConfig
-from products.feature_flags.backend.models import TeamFeatureFlagDefaultsConfig
-from products.feature_flags.backend.models.evaluation_context import (
- EvaluationContext,
- TeamDefaultEvaluationContext,
- normalize_context_name,
-)
+from products.feature_flags.backend.models.evaluation_context import EvaluationContext, normalize_context_name
from products.logs.backend.models import TeamLogsConfig
from products.signals.backend.models import SignalSourceConfig
from products.workflows.backend.models.team_workflows_config import EmailTrackingConsentMode, TeamWorkflowsConfig
@@ -187,108 +181,6 @@ def handle_logs_config(request: request.Request, team: Team) -> response.Respons
return response.Response(TeamLogsConfigSerializer(config).data)
-def handle_default_evaluation_contexts(
- request: request.Request, team: Team, user_permissions: UserPermissions
-) -> response.Response:
- """Shared handler for the default_evaluation_contexts action — exposed under both the
- team/environment and project routers so /api/projects/ and /api/environments/ cannot drift apart.
- Manage default evaluation contexts for a team."""
- # Feature flags persist contexts under the project root team (RootTeamMixin), so scope
- # context lookups to the root team — otherwise flag-used contexts are invisible from
- # child environments.
- root_team = team.parent_team or team
-
- if request.method == "GET":
- defaults = TeamDefaultEvaluationContext.objects.filter(team=root_team).select_related("evaluation_context")
- defaults_data = [{"id": d.id, "name": d.evaluation_context.name} for d in defaults]
- all_contexts_qs = list(
- EvaluationContext.objects.filter(team=root_team)
- .values_list("name", "hidden_from_suggestions")
- .order_by("name")
- )
- all_contexts = [name for name, hidden in all_contexts_qs if not hidden]
- hidden_contexts = [name for name, hidden in all_contexts_qs if hidden]
- return response.Response(
- {
- "default_evaluation_contexts": defaults_data,
- "available_contexts": all_contexts,
- "hidden_contexts": hidden_contexts,
- "enabled": team.default_evaluation_contexts_enabled,
- }
- )
-
- elif request.method == "POST":
- context_name = request.data.get("context_name", "")
- if not isinstance(context_name, str):
- return response.Response({"error": "context_name must be a string"}, status=400)
- context_name = normalize_context_name(context_name)
- if not context_name:
- return response.Response({"error": "context_name is required"}, status=400)
- if len(context_name) > 255:
- return response.Response({"error": "context_name must be at most 255 characters"}, status=400)
-
- with transaction.atomic():
- existing = list(TeamDefaultEvaluationContext.objects.filter(team=root_team).select_for_update())
- if len(existing) >= 10:
- return response.Response({"error": "Maximum of 10 default evaluation contexts allowed"}, status=400)
-
- ctx, _ = EvaluationContext.objects.get_or_create(name=context_name, team=root_team)
- if ctx.hidden_from_suggestions:
- level = user_permissions.team(team).effective_membership_level
- if level is not None and level >= OrganizationMembership.Level.ADMIN:
- ctx.hidden_from_suggestions = False
- ctx.save(update_fields=["hidden_from_suggestions"])
- default_ctx, created = TeamDefaultEvaluationContext.objects.get_or_create(
- team=root_team, evaluation_context=ctx
- )
-
- if created:
- report_user_action(
- cast(User, request.user),
- "default evaluation context added",
- {"team_id": team.id, "context_name": context_name},
- team=team,
- request=request,
- )
-
- return response.Response(
- {
- "id": default_ctx.id,
- "name": ctx.name,
- "created": created,
- "hidden_from_suggestions": ctx.hidden_from_suggestions,
- }
- )
-
- else: # DELETE
- context_name = request.data.get("context_name", "") or request.GET.get("context_name", "")
- if not isinstance(context_name, str):
- return response.Response({"error": "context_name must be a string"}, status=400)
- context_name = normalize_context_name(context_name)
- if not context_name:
- return response.Response({"error": "context_name is required"}, status=400)
-
- with transaction.atomic():
- try:
- ctx = EvaluationContext.objects.get(name=context_name, team=root_team)
- deleted_count, _ = TeamDefaultEvaluationContext.objects.filter(
- team=root_team, evaluation_context=ctx
- ).delete()
-
- if deleted_count > 0:
- report_user_action(
- cast(User, request.user),
- "default evaluation context removed",
- {"team_id": team.id, "context_name": context_name},
- team=team,
- request=request,
- )
-
- return response.Response({"success": True})
- except EvaluationContext.DoesNotExist:
- return response.Response({"error": "Evaluation context not found"}, status=404)
-
-
def handle_evaluation_context_suggestions(request: request.Request, team: Team) -> response.Response:
"""Shared handler for the evaluation_context_suggestions action — exposed under both the
team/environment and project routers so /api/projects/ and /api/environments/ cannot drift apart.
@@ -1945,10 +1837,6 @@ class TeamViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixin, viewsets.Mo
lookup_field = "id"
ordering = "-created_by"
- # Actions whose scope is downgraded to project:read for session auth on all methods.
- # TeamMemberLightManagementPermission still applies, so DELETE requires admin.
- MEMBER_READABLE_CONFIG_ACTIONS = ("default_release_conditions", "default_evaluation_contexts")
-
# Actions whose GET is downgraded to project:read for session auth; mutating methods stay on project:write/admin.
GET_DOWNGRADE_ACTIONS = ("evaluation_context_suggestions",)
@@ -1995,13 +1883,6 @@ class TeamViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixin, viewsets.Mo
if request_fields and request_fields.issubset(downgradable_fields):
return ["project:read"]
- # Team-level config actions that any member should be able to edit via the UI.
- # Only downgrade for session auth to preserve read-only API key semantics.
- if self.action in self.MEMBER_READABLE_CONFIG_ACTIONS:
- is_session_auth = isinstance(request.successful_authenticator, SessionAuthentication)
- if is_session_auth:
- return ["project:read"]
-
# Read-only access for member-readable actions — only downgrade GET, not writes.
if self.action in self.GET_DOWNGRADE_ACTIONS and request.method == "GET":
is_session_auth = isinstance(request.successful_authenticator, SessionAuthentication)
@@ -2160,56 +2041,6 @@ class TeamViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixin, viewsets.Mo
)
return response.Response(TeamSerializer(team, context=self.get_serializer_context()).data)
- @action(
- methods=["GET", "PUT"],
- detail=True,
- permission_classes=[TeamMemberLightManagementPermission],
- url_path="default_release_conditions",
- )
- def default_release_conditions(self, request: request.Request, id: str, **kwargs) -> response.Response:
- """Manage default release conditions for new feature flags in this team."""
- team = self.get_object()
- config = get_or_create_team_extension(team, TeamFeatureFlagDefaultsConfig)
-
- if request.method == "GET":
- return response.Response({"enabled": config.enabled, "default_groups": config.default_groups})
-
- # PUT: update the config
- enabled = request.data.get("enabled", config.enabled)
- default_groups = request.data.get("default_groups", config.default_groups)
-
- if not isinstance(default_groups, list):
- return response.Response({"error": "default_groups must be a list"}, status=400)
-
- for i, group in enumerate(default_groups):
- if not isinstance(group, dict):
- return response.Response({"error": f"Group at index {i} must be an object"}, status=400)
- if "properties" not in group or not isinstance(group["properties"], list):
- return response.Response(
- {"error": f"Group at index {i} must have a 'properties' list"},
- status=400,
- )
- rollout = group.get("rollout_percentage")
- if rollout is not None and (
- not isinstance(rollout, (int, float)) or math.isnan(rollout) or rollout < 0 or rollout > 100
- ):
- return response.Response(
- {"error": f"Group at index {i} has invalid rollout_percentage (must be 0-100 or null)"},
- status=400,
- )
-
- config.enabled = enabled
- config.default_groups = default_groups
- config.save()
-
- report_user_action(
- request.user,
- "default release conditions updated",
- {"team_id": team.id, "enabled": enabled, "group_count": len(default_groups)},
- )
-
- return response.Response({"enabled": config.enabled, "default_groups": config.default_groups})
-
@action(
methods=["GET", "PATCH"],
detail=True,
@@ -2260,15 +2091,6 @@ class TeamViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixin, viewsets.Mo
return response.Response(TeamExperimentsConfigSerializer(config).data)
- @action(
- methods=["GET", "POST", "DELETE"],
- detail=True,
- permission_classes=[IsAuthenticated],
- )
- def default_evaluation_contexts(self, request: request.Request, id: str, **kwargs) -> response.Response:
- """Manage default evaluation contexts for a team."""
- return handle_default_evaluation_contexts(request, self.get_object(), self.user_permissions)
-
@extend_schema(
methods=["POST"],
request=EvaluationContextSuggestionRequestSerializer,
diff --git a/posthog/api/test/test_team_default_release_conditions.py b/posthog/api/test/test_team_default_release_conditions.py
index 5540682dc7c6..ef1e1d3a90da 100644
--- a/posthog/api/test/test_team_default_release_conditions.py
+++ b/posthog/api/test/test_team_default_release_conditions.py
@@ -113,7 +113,7 @@ class TestTeamDefaultReleaseConditions(APIBaseTest):
self.assertEqual(response.status_code, status.HTTP_200_OK)
self.assertIsNone(response.json()["default_groups"][0]["rollout_percentage"])
- def test_non_admin_can_read_and_write(self):
+ def test_non_admin_can_read_but_not_write(self):
self.organization_membership.level = OrganizationMembership.Level.MEMBER
self.organization_membership.save()
@@ -121,7 +121,7 @@ class TestTeamDefaultReleaseConditions(APIBaseTest):
self.assertEqual(response.status_code, status.HTTP_200_OK)
response = self.client.put(self.url, {"enabled": True, "default_groups": []}, format="json")
- self.assertEqual(response.status_code, status.HTTP_200_OK)
+ self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)
def test_get_returns_previously_saved_config(self):
config = get_or_create_team_extension(self.team, TeamFeatureFlagDefaultsConfig)
diff --git a/products/feature_flags/backend/api/test/test_feature_flag_default_evaluation_contexts.py b/products/feature_flags/backend/api/test/test_feature_flag_default_evaluation_contexts.py
index f80bd0218ca8..c4b8bda98b65 100644
--- a/products/feature_flags/backend/api/test/test_feature_flag_default_evaluation_contexts.py
+++ b/products/feature_flags/backend/api/test/test_feature_flag_default_evaluation_contexts.py
@@ -354,31 +354,12 @@ class TestEvaluationContextSuggestions(APIBaseTest):
self.assertIn("production", data["available_contexts"])
self.assertNotIn("production", data["hidden_contexts"])
- def test_member_adding_hidden_context_as_default_does_not_unhide_it(self):
- ctx = self._create_context("production")
- ctx.hidden_from_suggestions = True
- ctx.save()
-
- self.organization_membership.level = OrganizationMembership.Level.MEMBER
- self.organization_membership.save()
-
- response = self.client.post(self.get_url, {"context_name": "production"}, format="json")
- self.assertEqual(response.status_code, status.HTTP_200_OK)
- self.assertTrue(response.json()["created"])
-
- ctx.refresh_from_db()
- self.assertTrue(ctx.hidden_from_suggestions)
-
- data = self.client.get(self.get_url).json()
- self.assertNotIn("production", data["available_contexts"])
- self.assertIn("production", data["hidden_contexts"])
-
- def test_member_can_post_but_not_delete_default_evaluation_contexts(self):
+ def test_member_cannot_write_default_evaluation_contexts(self):
self.organization_membership.level = OrganizationMembership.Level.MEMBER
self.organization_membership.save()
response = self.client.post(self.get_url, {"context_name": "production"}, format="json")
- self.assertEqual(response.status_code, status.HTTP_200_OK)
+ self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)
response = self.client.delete(self.get_url, {"context_name": "production"}, format="json")
self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)