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(approvals): deny a write the gate cannot classify (#110763)

Yasen9862743bb65d
diff --git a/products/approvals/backend/decorators.py b/products/approvals/backend/decorators.py
index eddf7dfe0c33..5c579077eb32 100644
--- a/products/approvals/backend/decorators.py
+++ b/products/approvals/backend/decorators.py
@@ -559,6 +559,7 @@ def approval_gate(action_refs: Union[type, str, list]):
# would satisfy a single policy while the other policies' gated fields sail through
# unapproved. Gating on only the first match reopens exactly that bypass.
matches: list[tuple[Any, Any]] = []
+ detection_failed = False
for action_class in actions:
try:
if action_class.detect(request, self, *args, **kwargs):
@@ -571,11 +572,19 @@ def approval_gate(action_refs: Union[type, str, list]):
extra={"action": action_class.key, "error": str(e)},
exc_info=True,
)
+ detection_failed = True
- if not matches:
+ if detection_failed:
+ # Unknown means deny. Carrying on would read a broken detect() as "no policy
+ # applies", which silently disables the policy that action implements.
+ result = GateResult(
+ action="error",
+ error_message="Could not determine whether this change needs approval. Try again.",
+ )
+ elif not matches:
return method(self, *args, **kwargs)
- if len(matches) > 1:
+ elif len(matches) > 1:
# A single ChangeRequest can only carry one action's approval, but the apply path
# replays the whole payload — so we cannot safely gate a change that needs approval
# under several policies at once. Reject it (fail closed) and tell the caller to
diff --git a/products/approvals/backend/exceptions.py b/products/approvals/backend/exceptions.py
index a26e81415f3d..d66e8795d1dc 100644
--- a/products/approvals/backend/exceptions.py
+++ b/products/approvals/backend/exceptions.py
@@ -28,6 +28,15 @@ class PolicyEvaluationError(ApprovalException):
pass
+class ApprovalDetectionFailed(ApprovalException):
+ """Raised when the gate cannot tell whether a change needs approval.
+
+ Detection reads the change through each action's ``detect``. When one of those raises, the
+ answer is unknown, not "no policy applies". Treating it as the latter lets a bug in one action
+ silently disable the policy it implements, so the write is refused instead.
+ """
+
+
class ApprovalRequired(ApprovalException):
"""
Raised when an action requires approval.
diff --git a/products/approvals/backend/mixins.py b/products/approvals/backend/mixins.py
index 16d536499bd5..99d8af706366 100644
--- a/products/approvals/backend/mixins.py
+++ b/products/approvals/backend/mixins.py
@@ -1,7 +1,7 @@
from rest_framework import status
from rest_framework.response import Response
-from products.approvals.backend.exceptions import ApprovalRequired, PolicyConflict
+from products.approvals.backend.exceptions import ApprovalDetectionFailed, ApprovalRequired, PolicyConflict
from products.approvals.backend.serializers import ChangeRequestSerializer
@@ -31,6 +31,20 @@ class ApprovalHandlingMixin:
status=status.HTTP_409_CONFLICT,
)
+ if isinstance(exc, ApprovalDetectionFailed):
+ # The gate refused because it could not classify the change, which is a server-side
+ # failure rather than a rejected request. Carry the reason, or the caller sees a bare
+ # 500 and cannot tell a refusal from a crash.
+ return Response(
+ {
+ "detail": str(exc),
+ "code": "approval_detection_failed",
+ "status": "approval_detection_failed",
+ "message": str(exc),
+ },
+ status=status.HTTP_500_INTERNAL_SERVER_ERROR,
+ )
+
if isinstance(exc, PolicyConflict):
return Response(
{
diff --git a/products/approvals/backend/scheduled_changes.py b/products/approvals/backend/scheduled_changes.py
index 8835a02ce2c1..ff0d3ee63819 100644
--- a/products/approvals/backend/scheduled_changes.py
+++ b/products/approvals/backend/scheduled_changes.py
@@ -16,7 +16,7 @@ from django.db import transaction
from django.http import HttpRequest
from products.approvals.backend import decorators
-from products.approvals.backend.exceptions import ApprovalRequired, PolicyConflict
+from products.approvals.backend.exceptions import ApprovalDetectionFailed, ApprovalRequired, PolicyConflict
from products.approvals.backend.models import ChangeRequest, ChangeRequestState, ValidationStatus
from products.approvals.backend.notifications import send_approval_expired_notification
from products.approvals.backend.services import apply_change_request
@@ -117,11 +117,14 @@ def _detect_gated_action(flag: "FeatureFlag", payload: dict[str, Any], user) ->
policy = decorators._check_policy_for_action(action_class, team, organization)
if policy:
return _GatedAction(action_class, policy, serializer, http_request, gate_args)
- except Exception:
+ except Exception as e:
+ # Unknown means deny. A schedule saved here fires later with no approver watching, so
+ # a detection failure must stop it being saved rather than pass it through ungated.
logger.exception(
"Error detecting action for scheduled change",
extra={"action": action_class.key, "flag_id": flag.id},
)
+ raise ApprovalDetectionFailed("Could not determine whether this change needs approval. Try again.") from e
return None
diff --git a/products/approvals/backend/tests/test_decorators.py b/products/approvals/backend/tests/test_decorators.py
index 6330edc1e680..c9ba22cfb647 100644
--- a/products/approvals/backend/tests/test_decorators.py
+++ b/products/approvals/backend/tests/test_decorators.py
@@ -103,6 +103,34 @@ class TestApprovalGateFailsClosed(_ApprovalGateFixtures):
flag.refresh_from_db()
assert flag.active is False
+ def test_a_detect_that_raises_blocks_the_write(self, _mock_enabled):
+ flag = self._create_disabled_flag()
+ self._create_enable_policy()
+ request = self._drf_request({"active": True})
+ serializer = self._serializer(
+ flag,
+ {"active": True},
+ {
+ "request": request,
+ "team_id": self.team.id,
+ "project_id": self.team.project_id,
+ "get_team": lambda: self.team,
+ "get_organization": lambda: self.organization,
+ },
+ )
+
+ # A broken detect() leaves the gate unable to answer. Reading that as "no policy applies"
+ # would disable the very policy this action implements.
+ with patch(
+ "products.approvals.backend.actions.feature_flags.EnableFeatureFlagAction.detect",
+ side_effect=RuntimeError("boom"),
+ ):
+ with self.assertRaises(APIException):
+ serializer.save()
+
+ flag.refresh_from_db()
+ assert flag.active is False
+
def test_gate_passes_through_when_no_policy(self, _mock_enabled):
flag = self._create_disabled_flag()
request = self._drf_request({"active": True})
diff --git a/products/approvals/backend/tests/test_scheduled_change_gating.py b/products/approvals/backend/tests/test_scheduled_change_gating.py
index ae9ceb30c989..d8b8eb44feb1 100644
--- a/products/approvals/backend/tests/test_scheduled_change_gating.py
+++ b/products/approvals/backend/tests/test_scheduled_change_gating.py
@@ -232,6 +232,32 @@ class TestScheduledChangeGating(APIBaseTest):
assert response.json()["code"] == "policy_conflict"
assert ScheduledChange.objects.filter(record_id=str(flag.id)).count() == 0
+ def test_scheduled_change_is_refused_when_detection_fails(self, _mock_enabled):
+ # A schedule saved past a failed detection fires later with no approver watching, so a
+ # detect() that raises must stop the row being saved rather than let it through ungated.
+ self._enable_policy()
+ flag = self._disabled_flag()
+
+ with patch(
+ "products.approvals.backend.actions.feature_flags.EnableFeatureFlagAction.detect",
+ side_effect=RuntimeError("boom"),
+ ):
+ response = self.client.post(
+ f"/api/projects/{self.team.id}/scheduled_changes/",
+ {
+ "record_id": str(flag.id),
+ "model_name": "FeatureFlag",
+ "payload": {"operation": "update_status", "value": True},
+ "scheduled_at": (timezone.now() + timedelta(hours=1)).isoformat(),
+ },
+ format="json",
+ )
+
+ assert response.status_code == 500, response.content
+ assert response.json()["code"] == "approval_detection_failed"
+ assert "needs approval" in response.json()["detail"]
+ assert ScheduledChange.objects.filter(record_id=str(flag.id)).count() == 0
+
def test_scheduled_change_without_policy_applies_normally(self, _mock_enabled):
flag = self._disabled_flag()
diff --git a/products/feature_flags/backend/api/organization_feature_flag.py b/products/feature_flags/backend/api/organization_feature_flag.py
index 39ba7a858261..e92883905445 100644
--- a/products/feature_flags/backend/api/organization_feature_flag.py
+++ b/products/feature_flags/backend/api/organization_feature_flag.py
@@ -31,7 +31,7 @@ from products.access_control.backend.facade.user_access_control import (
UserAccessControl,
access_level_satisfied_for_resource,
)
-from products.approvals.backend.exceptions import ApprovalRequired, PolicyConflict
+from products.approvals.backend.exceptions import ApprovalDetectionFailed, ApprovalRequired, PolicyConflict
from products.approvals.backend.scheduled_changes import gate_scheduled_change
from products.approvals.backend.transactions import gated_atomic
from products.cohorts.backend.models.cohort import Cohort, CohortOrEmpty
@@ -1679,10 +1679,11 @@ class OrganizationFeatureFlagView(
created_by=user,
change_request=change_request,
)
- except (PolicyConflict, ApprovalRequired):
+ except (PolicyConflict, ApprovalRequired, ApprovalDetectionFailed):
# The copied change can't be gated with a fresh single CR on the target — it either
- # matches multiple policies (PolicyConflict) or would bind an already-approved
- # duplicate (ApprovalRequired). Skip it (fail closed) rather than copy it ungated or
+ # matches multiple policies (PolicyConflict), would bind an already-approved
+ # duplicate (ApprovalRequired), or could not be classified at all
+ # (ApprovalDetectionFailed). Skip it (fail closed) rather than copy it ungated or
# riding on an unrelated approval — mirroring the permission skip above, we don't
# fail the whole copy over one schedule.
logger.warning(