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.

feat(approvals): check the requester's access again before applying (#113118)

Yasen9d8dc2d9c2d6
diff --git a/posthog/test/repo_invariants/test_flag_ownership_relations_are_classified.py b/posthog/test/repo_invariants/test_flag_ownership_relations_are_classified.py
new file mode 100644
index 000000000000..ce6def0ee22f
--- /dev/null
+++ b/posthog/test/repo_invariants/test_flag_ownership_relations_are_classified.py
@@ -0,0 +1,30 @@
+from django.db.models.fields.reverse_related import ForeignObjectRel
+from django.test import SimpleTestCase
+
+from products.feature_flags.backend.models.feature_flag import FeatureFlag
+from products.feature_flags.backend.ownership import _OWNING_ACCESSORS, _REFERENCE_ACCESSORS
+
+
+class TestFlagOwnershipRelationsAreClassified(SimpleTestCase):
+ def test_every_relation_onto_feature_flag_is_classified(self) -> None:
+ owning = {accessor for accessor, _kind, _manager in _OWNING_ACCESSORS}
+
+ # Only a reverse relation has an accessor name; the union also holds concrete fields
+ # and generic foreign keys.
+ actual = {
+ name
+ for field in FeatureFlag._meta.get_fields()
+ if isinstance(field, ForeignObjectRel) and (name := field.get_accessor_name())
+ }
+
+ unclassified = actual - owning - _REFERENCE_ACCESSORS
+ assert not unclassified, (
+ f"These relations point at FeatureFlag but are neither owning nor a declared "
+ f"reference: {sorted(unclassified)}. Approval policies are keyed on which product "
+ f"owns a flag, and an unclassified relation makes those flags read as standalone, "
+ f"so they keep feature_flag.* coverage nobody chose. Add each to _OWNING_ACCESSORS "
+ f"or _REFERENCE_ACCESSORS in products/feature_flags/backend/ownership.py."
+ )
+
+ stale = (owning | _REFERENCE_ACCESSORS) - actual
+ assert not stale, f"These classified relations no longer exist on FeatureFlag: {sorted(stale)}"
diff --git a/products/approvals/backend/services.py b/products/approvals/backend/services.py
index 103cf53a23a7..c51b6301e605 100644
--- a/products/approvals/backend/services.py
+++ b/products/approvals/backend/services.py
@@ -1,6 +1,6 @@
import logging
from dataclasses import dataclass
-from typing import Any, Optional
+from typing import Any, Optional, cast
from django.db import transaction
from django.utils import timezone
@@ -10,7 +10,9 @@ from prometheus_client import Counter
from posthog.api.utils import ServiceRequest
from posthog.event_usage import report_user_action
from posthog.models import User
+from posthog.scopes import API_SCOPE_OBJECTS, APIScopeObject
+from products.access_control.backend.facade.user_access_control import UserAccessControl, model_to_resource
from products.approvals.backend.actions.registry import get_action
from products.approvals.backend.exceptions import (
AlreadyVotedError,
@@ -19,7 +21,13 @@ from products.approvals.backend.exceptions import (
PreconditionFailed,
ReasonRequiredError,
)
-from products.approvals.backend.models import Approval, ApprovalDecision, ChangeRequest, ChangeRequestState
+from products.approvals.backend.models import (
+ Approval,
+ ApprovalDecision,
+ ChangeRequest,
+ ChangeRequestState,
+ ValidationStatus,
+)
from products.approvals.backend.notifications import (
send_approval_applied_notification,
send_approval_decision_notification,
@@ -55,6 +63,66 @@ class RequestContext(ServiceRequest):
self.skip_opportunistic_filter_cleanup = skip_opportunistic_filter_cleanup
+def requester_still_has_access(change_request: ChangeRequest, context: dict[str, Any]) -> bool:
+ """Whether the person who raised this change request could still make it themselves.
+
+ Shared by the apply path, which refuses, and the periodic validation task, which marks the
+ request invalid and clears that mark once access returns.
+ """
+ requester = change_request.created_by
+ if requester is None:
+ # `created_by` is SET_NULL, so deleting the requester's account empties it. Nobody is
+ # left whose access can be checked, and unknown means deny, as it does everywhere else
+ # in this gate.
+ return False
+
+ access = UserAccessControl(user=requester, team=change_request.team)
+ instance = context.get("instance")
+
+ if instance is None:
+ # A create has no row yet, so only the resource axis exists. Returning True here instead
+ # would leave the create path unchecked, which is the path a revoked user most wants.
+ resource = change_request.resource_type if change_request.resource_type in API_SCOPE_OBJECTS else None
+ if resource is None:
+ return True
+ return access.check_access_level_for_resource(cast(APIScopeObject, resource), "editor")
+
+ # Both axes have to hold, the way they do for a direct write. A resource-wide control set to
+ # "none" denies the write even while the object-level level still reads as manager, so
+ # checking only the object would let the apply through where the API returns 403.
+ object_resource = model_to_resource(instance)
+ return access.check_access_level_for_object(instance, "editor") and (
+ object_resource is None or access.check_access_level_for_resource(object_resource, "editor")
+ )
+
+
+def _assert_requester_still_has_access(change_request: ChangeRequest, context: dict[str, Any]) -> None:
+ """Refuse to apply a change the requester may no longer make themselves.
+
+ Access is checked when a change request is created, because the viewset's access control
+ runs before the gate on the serializer. It is not checked again here: an apply replays the
+ write through a request shim with no authenticated user, so no permission layer runs. Without
+ this, someone who loses edit access between asking and approval still gets their change
+ landed, and approval becomes a way to outlive your own permissions.
+
+ The request is marked invalid rather than failed. The periodic validation task clears that
+ mark once access returns, so the request becomes applicable again on its own.
+ """
+ if requester_still_has_access(change_request, context):
+ return
+
+ change_request.validation_status = ValidationStatus.INVALID
+ change_request.validation_errors = {
+ "access": "The requester no longer has edit access to this resource, or their account is gone."
+ }
+ change_request.validated_at = timezone.now()
+ change_request.save(update_fields=["validation_status", "validation_errors", "validated_at"])
+ raise PreconditionFailed(
+ "The person who requested this change no longer has edit access to the resource, "
+ "so it cannot be applied. Ask them to request it again if their access is restored."
+ )
+
+
def apply_change_request(change_request: ChangeRequest, request=None) -> Any:
"""
Apply an approved change request.
@@ -93,6 +161,8 @@ def apply_change_request(change_request: ChangeRequest, request=None) -> Any:
# Let the action prepare its own context (e.g., fetch instance)
validation_context = action_class.prepare_context(change_request, base_context)
+ _assert_requester_still_has_access(change_request, validation_context)
+
current_owner_kind = action_class.derive_owner_kind(
change_request.team, change_request.resource_id, change_request.intent
)
diff --git a/products/approvals/backend/tasks.py b/products/approvals/backend/tasks.py
index 3467757d4bb5..ea89f03645be 100644
--- a/products/approvals/backend/tasks.py
+++ b/products/approvals/backend/tasks.py
@@ -1,4 +1,4 @@
-from typing import Any
+from typing import Any, Optional
from django.db import transaction
from django.utils import timezone
@@ -11,6 +11,7 @@ from posthog.scoping_audit import skip_team_scope_audit
from products.approvals.backend.experiment_policy_sync import sync_experiment_policies
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 requester_still_has_access
logger = get_logger(__name__)
@@ -34,8 +35,11 @@ def validate_pending_change_requests() -> dict[str, Any]:
checked_count = 0
errors: list[str] = []
+ # Approved requests are revalidated too. The apply-time access check only runs once a request
+ # is approved, so marking it invalid there and then never revisiting it would latch the mark
+ # exactly where it is set. `expire_old_change_requests` already spans both states.
pending_requests = ChangeRequest.objects.filter(
- state=ChangeRequestState.PENDING,
+ state__in=[ChangeRequestState.PENDING, ChangeRequestState.APPROVED],
)
for change_request in pending_requests:
@@ -57,30 +61,40 @@ def validate_pending_change_requests() -> dict[str, Any]:
"organization": change_request.organization,
}
context = action_class.prepare_context(change_request, base_context)
- is_stale = action_class.check_staleness(change_request.intent, context)
- was_stale = change_request.validation_status == ValidationStatus.STALE
- if is_stale and not was_stale:
- change_request.validation_status = ValidationStatus.STALE
- change_request.validation_errors = {
+ # Derive the status the request should hold, rather than branching per transition.
+ # Branching missed the invalid-to-valid direction, which latched a request forever
+ # once its requester lost access.
+ if action_class.check_staleness(change_request.intent, context):
+ status = ValidationStatus.STALE
+ errors_for_status: Optional[dict[str, str]] = {
"staleness": "Resource has been modified since this change request was created"
}
+ elif not requester_still_has_access(change_request, context):
+ status = ValidationStatus.INVALID
+ errors_for_status = {
+ "access": "The requester no longer has edit access to this resource, or their account is gone."
+ }
+ else:
+ status = ValidationStatus.VALID
+ errors_for_status = None
+
+ was = change_request.validation_status
+ if status != was:
+ change_request.validation_status = status
+ change_request.validation_errors = errors_for_status
change_request.validated_at = timezone.now()
change_request.save(update_fields=["validation_status", "validation_errors", "validated_at"])
- stale_count += 1
- logger.info(
- "validate_pending_change_requests.stale",
- change_request_id=str(change_request.id),
- )
- elif was_stale and not is_stale:
- change_request.validation_status = ValidationStatus.VALID
- change_request.validation_errors = None
- change_request.validated_at = timezone.now()
- change_request.save(update_fields=["validation_status", "validation_errors", "validated_at"])
- healed_count += 1
+ if status == ValidationStatus.VALID:
+ healed_count += 1
+ else:
+ stale_count += 1
logger.info(
- "validate_pending_change_requests.healed",
+ "validate_pending_change_requests.healed"
+ if status == ValidationStatus.VALID
+ else "validate_pending_change_requests.stale",
change_request_id=str(change_request.id),
+ status=status,
)
except Exception as e:
diff --git a/products/approvals/backend/tests/test_owner_operation_decision_table.py b/products/approvals/backend/tests/test_owner_operation_decision_table.py
new file mode 100644
index 000000000000..ddd1e7126596
--- /dev/null
+++ b/products/approvals/backend/tests/test_owner_operation_decision_table.py
@@ -0,0 +1,197 @@
+"""The owner x operation decision table for feature-flag approval gating.
+
+Which approval family guards a write depends on which product owns the flag. This file
+holds that mapping as data and derives every cell from the running code, so the table is
+checked rather than described.
+
+Phase 3 proved every entry point behaves alike, so this varies owner and operation over one
+entry point (the flag API) instead of multiplying by entry point.
+
+Read DECISION_TABLE as the current, pre-narrowing state: `feature_flag.*` covers every owner.
+Narrowing a family to an owner changes cells here, and that diff is the coverage change.
+"""
+
+from typing import Any, Optional
+
+from posthog.test.base import APIBaseTest
+from unittest.mock import patch
+
+from parameterized import parameterized
+
+from posthog.constants import AvailableFeature
+
+from products.approvals.backend.models import ApprovalPolicy, ChangeRequest
+from products.early_access_features.backend.models import EarlyAccessFeature
+from products.experiments.backend.models.experiment import Experiment
+from products.feature_flags.backend.models.feature_flag import FeatureFlag
+from products.feature_flags.backend.ownership import flag_owner_kind
+from products.product_tours.backend.models import ProductTour
+from products.surveys.backend.models import Survey
+
+GATED_ACTION_KEYS = ("feature_flag.enable", "feature_flag.disable", "feature_flag.update")
+
+# A flag has no owner at the moment it is created, so the create column is not a function of
+# owner. It is covered once, under `standalone`, and marked NOT_APPLICABLE elsewhere.
+NOT_APPLICABLE = "n/a"
+# The write is refused outright, so no approval question arises.
+REJECTED = "rejected"
+UNGATED = None
+
+OWNERS = (
+ "standalone",
+ "experiment",
+ "survey_owned",
+ "survey_linked",
+ "tour_owned",
+ "tour_linked",
+ "early_access",
+ "session_recording_reference",
+)
+
+OPERATIONS = ("create_active", "update_gated_field", "enable", "disable", "delete")
+
+
+def _row(*cells: Optional[str]) -> dict[str, Optional[str]]:
+ """Pair a table row with the operation names, so a row reads as a row."""
+ return dict(zip(OPERATIONS, cells, strict=True))
+
+
+# Which product the ownership derivation reports for each setup. A reference is not ownership,
+# so the linked cases and the session-recording case all derive as unowned (None).
+EXPECTED_OWNER_KIND: dict[str, Optional[str]] = {
+ "standalone": None,
+ "experiment": "experiment",
+ "survey_owned": "survey",
+ "survey_linked": None,
+ "tour_owned": "product_tour",
+ "tour_linked": None,
+ "early_access": "early_access_feature",
+ "session_recording_reference": None,
+}
+
+# Short names so each row of the table below fits on one line and the columns line up.
+ENABLE = "feature_flag.enable"
+UPDATE = "feature_flag.update"
+DISABLE = "feature_flag.disable"
+NA = NOT_APPLICABLE
+
+# The decision table. One row per owner, one column per operation, in the order OPERATIONS
+# declares. A cell names the action family that gates that write, or:
+# UNGATED nothing gates it; the write lands unreviewed
+# REJECTED the write is refused outright, so no approval question arises
+# NA not a function of owner; see the create note above
+#
+# Narrowing a family to an owner changes cells here, and that diff is the coverage change.
+# fmt: off
+DECISION_TABLE: dict[str, dict[str, Optional[str]]] = {
+ # create update enable disable delete
+ "standalone": _row(ENABLE, UPDATE, ENABLE, DISABLE, UNGATED),
+ "experiment": _row(NA, UPDATE, ENABLE, DISABLE, UNGATED),
+ "survey_owned": _row(NA, UPDATE, ENABLE, DISABLE, UNGATED),
+ "survey_linked": _row(NA, UPDATE, ENABLE, DISABLE, UNGATED),
+ "tour_owned": _row(NA, UPDATE, ENABLE, DISABLE, UNGATED),
+ "tour_linked": _row(NA, UPDATE, ENABLE, DISABLE, UNGATED),
+ "early_access": _row(NA, UPDATE, ENABLE, DISABLE, REJECTED),
+ "session_recording_reference": _row(NA, UPDATE, ENABLE, DISABLE, REJECTED),
+}
+# fmt: on
+
+CELLS = [(owner, operation) for owner in OWNERS for operation in OPERATIONS]
+
+
+@patch("products.approvals.backend.decorators._is_approvals_enabled", return_value=True)
+class TestOwnerOperationDecisionTable(APIBaseTest):
+ def setUp(self) -> None:
+ super().setUp()
+ self.organization.available_product_features = [
+ {"key": AvailableFeature.ROLE_BASED_ACCESS, "name": "role based access"}
+ ]
+ self.organization.save()
+ for action_key in GATED_ACTION_KEYS:
+ ApprovalPolicy.objects.create(
+ organization=self.organization,
+ team=self.team,
+ action_key=action_key,
+ conditions={},
+ approver_config={"quorum": 1, "users": [self.user.id]},
+ created_by=self.user,
+ )
+
+ def _flag(self, *, active: bool) -> FeatureFlag:
+ return FeatureFlag.objects.create(
+ team=self.team,
+ key="table-flag",
+ name="table-flag",
+ active=active,
+ filters={"groups": [{"properties": [], "rollout_percentage": 50}]},
+ created_by=self.user,
+ )
+
+ def _apply_owner(self, owner: str, flag: FeatureFlag) -> None:
+ if owner == "experiment":
+ Experiment.objects.create(team=self.team, name="exp", feature_flag=flag)
+ elif owner == "survey_owned":
+ Survey.objects.create(team=self.team, name="s", type="popover", targeting_flag=flag)
+ elif owner == "survey_linked":
+ Survey.objects.create(team=self.team, name="s", type="popover", linked_flag=flag)
+ elif owner == "tour_owned":
+ ProductTour.objects.create(team=self.team, name="t", internal_targeting_flag=flag)
+ elif owner == "tour_linked":
+ ProductTour.objects.create(team=self.team, name="t", linked_flag=flag)
+ elif owner == "early_access":
+ EarlyAccessFeature.objects.create(team=self.team, name="f", stage="beta", feature_flag=flag)
+ elif owner == "session_recording_reference":
+ self.team.session_recording_linked_flag = {"id": flag.id, "key": flag.key}
+ self.team.save()
+
+ def _perform(self, operation: str, flag: Optional[FeatureFlag]) -> None:
+ base = f"/api/projects/{self.team.id}/feature_flags/"
+ if operation == "create_active":
+ self.client.post(base, {"key": "born-active", "name": "born", "active": True}, format="json")
+ return
+
+ assert flag is not None
+ if operation == "update_gated_field":
+ payload: dict[str, Any] = {"filters": {"groups": [{"properties": [], "rollout_percentage": 100}]}}
+ self.client.patch(f"{base}{flag.id}/", payload, format="json")
+ elif operation == "enable":
+ self.client.patch(f"{base}{flag.id}/", {"active": True}, format="json")
+ elif operation == "disable":
+ self.client.patch(f"{base}{flag.id}/", {"active": False}, format="json")
+ elif operation == "delete":
+ self.client.patch(f"{base}{flag.id}/", {"deleted": True}, format="json")
+
+ def _assert_operation_took_effect(
+ self, operation: str, flag: Optional[FeatureFlag], expected: Optional[str]
+ ) -> None:
+ """An ungated cell must prove the write landed, or "no change request" means nothing."""
+ if operation != "delete":
+ return
+ assert flag is not None
+ deleted = FeatureFlag.objects_including_soft_deleted.get(id=flag.id).deleted
+ # An ungated delete must land, or "no change request" would prove nothing. A REJECTED
+ # cell must not.
+ assert deleted is (expected is UNGATED), f"delete landed={deleted} but the table says {expected}"
+
+ @parameterized.expand([(f"{owner}__{operation}", owner, operation) for owner, operation in CELLS])
+ def test_cell(self, _mock_enabled, _name: str, owner: str, operation: str) -> None:
+ expected = DECISION_TABLE[owner][operation]
+ if expected == NOT_APPLICABLE:
+ self.skipTest("a flag has no owner at creation; the create column is covered under standalone")
+
+ flag = None
+ if operation != "create_active":
+ # enable starts from inactive, everything else from active.
+ flag = self._flag(active=operation != "enable")
+ self._apply_owner(owner, flag)
+ flag.refresh_from_db()
+ assert flag_owner_kind(flag) == EXPECTED_OWNER_KIND[owner]
+
+ self._perform(operation, flag)
+ self._assert_operation_took_effect(operation, flag, expected)
+
+ keys = sorted(ChangeRequest.objects.filter(team=self.team).values_list("action_key", flat=True))
+ if expected is UNGATED or expected == REJECTED:
+ assert keys == [], f"{owner}/{operation} created {keys}, so it is gated after all"
+ else:
+ assert keys == [expected], f"{owner}/{operation} gated by {keys}, expected [{expected}]"
diff --git a/products/approvals/backend/tests/test_services.py b/products/approvals/backend/tests/test_services.py
index f52a153f807d..f5da0f51dcd7 100644
--- a/products/approvals/backend/tests/test_services.py
+++ b/products/approvals/backend/tests/test_services.py
@@ -7,8 +7,11 @@ from django.utils import timezone
from parameterized import parameterized
+from posthog.constants import AvailableFeature
+from posthog.models import OrganizationMembership
+
from products.approvals.backend.exceptions import ApplyFailed, InvalidStateError, PreconditionFailed
-from products.approvals.backend.models import ApprovalPolicy, ChangeRequest, ChangeRequestState
+from products.approvals.backend.models import ApprovalPolicy, ChangeRequest, ChangeRequestState, ValidationStatus
from products.approvals.backend.services import ChangeRequestService, apply_change_request
from products.experiments.backend.models.experiment import Experiment
from products.feature_flags.backend.encrypted_flag_payloads import (
@@ -18,6 +21,8 @@ from products.feature_flags.backend.encrypted_flag_payloads import (
)
from products.feature_flags.backend.models.feature_flag import FeatureFlag
+from ee.api.test.base import APILicensedTest
+
class TestApproveRejectRaceCondition(BaseTest):
def setUp(self):
@@ -251,3 +256,135 @@ class TestApplyRechecksOwnership(APIBaseTest):
assert flag.active is False
change_request.refresh_from_db()
assert change_request.state == ChangeRequestState.FAILED
+
+
+class TestApplyRechecksRequesterAccess(APILicensedTest):
+ # Access is checked when a change request is created, because the viewset's access control
+ # runs before the gate. An apply replays the write with no authenticated user, so without a
+ # second check an approval lets someone outlive their own permissions.
+
+ def setUp(self) -> None:
+ super().setUp()
+ self.organization.available_product_features = [
+ {"key": AvailableFeature.ACCESS_CONTROL, "name": AvailableFeature.ACCESS_CONTROL},
+ {"key": AvailableFeature.ROLE_BASED_ACCESS, "name": AvailableFeature.ROLE_BASED_ACCESS},
+ ]
+ self.organization.save()
+
+ def _change_request(self, flag: FeatureFlag) -> ChangeRequest:
+ return ChangeRequest.objects.create(
+ action_key="feature_flag.enable",
+ team=self.team,
+ organization=self.organization,
+ resource_type="feature_flag",
+ resource_id=str(flag.id),
+ intent={
+ "flag_id": flag.id,
+ "flag_key": flag.key,
+ "http_method": "PATCH",
+ "current_state": {"active": False},
+ "gated_changes": {"active": True},
+ "full_request_data": {"active": True},
+ "preconditions": {"version": flag.version, "updated_at": None},
+ },
+ intent_display={"description": "Enable"},
+ policy_snapshot={},
+ state=ChangeRequestState.APPROVED,
+ created_by=self.user,
+ expires_at=timezone.now() + timedelta(days=7),
+ )
+
+ def _revoke_flag_access(self) -> None:
+ self.organization_membership.level = OrganizationMembership.Level.ADMIN
+ self.organization_membership.save()
+ response = self.client.put(
+ "/api/projects/@current/resource_access_controls",
+ {"resource": "feature_flag", "access_level": "none"},
+ )
+ assert response.status_code == 200, response.content
+ self.organization_membership.level = OrganizationMembership.Level.MEMBER
+ self.organization_membership.save()
+
+ def _create_change_request(self) -> ChangeRequest:
+ # A create carries no flag_id, so nothing resolves as an instance at apply.
+ return ChangeRequest.objects.create(
+ action_key="feature_flag.enable",
+ team=self.team,
+ organization=self.organization,
+ resource_type="feature_flag",
+ resource_id=None,
+ intent={
+ "flag_id": None,
+ "flag_key": "born-active",
+ "http_method": "POST",
+ "current_state": {"active": False},
+ "gated_changes": {"active": True},
+ "full_request_data": {"key": "born-active", "name": "born", "active": True},
+ "preconditions": {"version": None, "updated_at": None},
+ },
+ intent_display={"description": "Create"},
+ policy_snapshot={},
+ state=ChangeRequestState.APPROVED,
+ created_by=self.user,
+ expires_at=timezone.now() + timedelta(days=7),
+ )
+
+ def test_apply_refuses_a_create_when_the_requester_lost_access(self) -> None:
+ change_request = self._create_change_request()
+ self._revoke_flag_access()
+
+ with self.assertRaises(PreconditionFailed):
+ apply_change_request(change_request)
+
+ assert not FeatureFlag.objects.filter(team=self.team, key="born-active").exists()
+ change_request.refresh_from_db()
+ assert change_request.validation_status == ValidationStatus.INVALID
+
+ def test_apply_refuses_when_the_requester_account_is_gone(self) -> None:
+ # created_by is SET_NULL, so offboarding the requester empties it. Nobody is left whose
+ # access can be checked, and the apply must not treat that as permission.
+ flag = FeatureFlag.objects.create(
+ team=self.team,
+ key="orphaned",
+ name="orphaned",
+ active=False,
+ filters={"groups": [{"properties": [], "rollout_percentage": 50}]},
+ created_by=self.user,
+ )
+ change_request = self._change_request(flag)
+ ChangeRequest.objects.filter(pk=change_request.pk).update(created_by=None)
+ change_request.refresh_from_db()
+
+ with self.assertRaises(PreconditionFailed):
+ apply_change_request(change_request)
+
+ flag.refresh_from_db()
+ assert flag.active is False
+
+ @parameterized.expand([("access kept", False, True), ("access revoked", True, False)])
+ def test_apply_requires_the_requester_to_still_have_access(
+ self, _name: str, revoke: bool, should_apply: bool
+ ) -> None:
+ flag = FeatureFlag.objects.create(
+ team=self.team,
+ key="access-gated",
+ name="access-gated",
+ active=False,
+ filters={"groups": [{"properties": [], "rollout_percentage": 50}]},
+ created_by=self.user,
+ )
+ change_request = self._change_request(flag)
+ if revoke:
+ self._revoke_flag_access()
+
+ if should_apply:
+ apply_change_request(change_request)
+ flag.refresh_from_db()
+ assert flag.active is True
+ else:
+ with self.assertRaises(PreconditionFailed):
+ apply_change_request(change_request)
+ flag.refresh_from_db()
+ assert flag.active is False
+ change_request.refresh_from_db()
+ assert change_request.validation_status == ValidationStatus.INVALID
diff --git a/products/approvals/backend/tests/test_tasks.py b/products/approvals/backend/tests/test_tasks.py
index 545f52c7db56..4f0b759043b0 100644
--- a/products/approvals/backend/tests/test_tasks.py
+++ b/products/approvals/backend/tests/test_tasks.py
@@ -7,8 +7,14 @@ from django.utils import timezone
from parameterized import parameterized
-from products.approvals.backend.models import ChangeRequest
+from posthog.constants import AvailableFeature
+from posthog.models import OrganizationMembership
+
+from products.approvals.backend.models import ChangeRequest, ChangeRequestState, ValidationStatus
from products.approvals.backend.tasks import expire_old_change_requests, validate_pending_change_requests
+from products.feature_flags.backend.models.feature_flag import FeatureFlag
+
+from ee.api.test.base import APILicensedTest
class TestValidatePendingChangeRequests(BaseTest):
@@ -31,14 +37,24 @@ class TestValidatePendingChangeRequests(BaseTest):
expires_at=timezone.now() + timedelta(hours=24),
)
- def test_skips_non_pending_requests(self):
- self.change_request.state = "approved"
+ @parameterized.expand(
+ [
+ # Approved is revalidated: the apply-time access check sets its mark there, so never
+ # revisiting it would latch the mark exactly where it is set.
+ ("approved", "approved", 1),
+ ("applied", "applied", 0),
+ ("rejected", "rejected", 0),
+ ("expired", "expired", 0),
+ ("failed", "failed", 0),
+ ]
+ )
+ def test_which_states_are_revalidated(self, _name, state, expected_checked):
+ self.change_request.state = state
self.change_request.save()
result = validate_pending_change_requests()
- self.assertEqual(result["checked_count"], 0)
- self.assertEqual(result["stale_count"], 0)
+ self.assertEqual(result["checked_count"], expected_checked)
@patch("products.approvals.backend.tasks.ChangeRequest.get_action_class")
def test_rechecks_already_stale_requests(self, mock_get_action):
@@ -157,3 +173,82 @@ class TestExpireOldChangeRequests(BaseTest):
mock_notification.assert_called_once()
notified_cr = mock_notification.call_args[0][0]
self.assertEqual(notified_cr.pk, self.expired_request.pk)
+
+
+class TestValidationClearsAnInvalidRequestWhenAccessReturns(APILicensedTest):
+ # Marking a request invalid is only safe if something clears it. The task derives the status
+ # rather than branching per transition, so the invalid-to-valid direction is covered too.
+
+ def setUp(self) -> None:
+ super().setUp()
+ self.organization.available_product_features = [
+ {"key": AvailableFeature.ACCESS_CONTROL, "name": AvailableFeature.ACCESS_CONTROL},
+ {"key": AvailableFeature.ROLE_BASED_ACCESS, "name": AvailableFeature.ROLE_BASED_ACCESS},
+ ]
+ self.organization.save()
+ self.flag = FeatureFlag.objects.create(
+ team=self.team,
+ key="heals",
+ name="heals",
+ active=False,
+ filters={"groups": [{"properties": [], "rollout_percentage": 50}]},
+ created_by=self.user,
+ )
+ self.change_request = ChangeRequest.objects.create(
+ action_key="feature_flag.enable",
+ team=self.team,
+ organization=self.organization,
+ resource_type="feature_flag",
+ resource_id=str(self.flag.id),
+ intent={
+ "flag_id": self.flag.id,
+ "flag_key": self.flag.key,
+ "http_method": "PATCH",
+ "gated_changes": {"active": True},
+ "full_request_data": {"active": True},
+ "preconditions": {"version": self.flag.version, "updated_at": None},
+ },
+ intent_display={"description": "Enable"},
+ policy_snapshot={},
+ state=ChangeRequestState.PENDING,
+ created_by=self.user,
+ expires_at=timezone.now() + timedelta(days=7),
+ )
+
+ def _set_flag_access(self, level: str) -> None:
+ self.organization_membership.level = OrganizationMembership.Level.ADMIN
+ self.organization_membership.save()
+ response = self.client.put(
+ "/api/projects/@current/resource_access_controls",
+ {"resource": "feature_flag", "access_level": level},
+ )
+ assert response.status_code == 200, response.content
+ self.organization_membership.level = OrganizationMembership.Level.MEMBER
+ self.organization_membership.save()
+
+ def test_invalid_clears_on_an_approved_request_too(self) -> None:
+ # The apply-time check only runs once a request is approved, so an approved request is
+ # exactly where the invalid mark gets set and must therefore be revisited.
+ ChangeRequest.objects.filter(pk=self.change_request.pk).update(state=ChangeRequestState.APPROVED)
+
+ self._set_flag_access("none")
+ validate_pending_change_requests()
+ self.change_request.refresh_from_db()
+ assert self.change_request.validation_status == ValidationStatus.INVALID
+
+ self._set_flag_access("editor")
+ validate_pending_change_requests()
+ self.change_request.refresh_from_db()
+ assert self.change_request.validation_status == ValidationStatus.VALID
+
+ def test_invalid_clears_once_access_returns(self) -> None:
+ self._set_flag_access("none")
+ validate_pending_change_requests()
+ self.change_request.refresh_from_db()
+ assert self.change_request.validation_status == ValidationStatus.INVALID
+
+ self._set_flag_access("editor")
+ validate_pending_change_requests()
+ self.change_request.refresh_from_db()
+ assert self.change_request.validation_status == ValidationStatus.VALID
+ assert self.change_request.validation_errors is None
diff --git a/products/feature_flags/backend/ownership.py b/products/feature_flags/backend/ownership.py
index 1cde62fd7305..021e9d893890 100644
--- a/products/feature_flags/backend/ownership.py
+++ b/products/feature_flags/backend/ownership.py
@@ -37,6 +37,24 @@ _OWNING_ACCESSORS: tuple[tuple[str, str, str | None], ...] = (
)
+# Relations onto FeatureFlag that deliberately do not confer ownership. Listed rather than
+# inferred, so "standalone" is a classification somebody made instead of whatever was left over.
+# `test_flag_ownership_relations_are_classified` fails when a relation appears in neither list,
+# which is what stops a new owning product being read as standalone because nobody registered it.
+_REFERENCE_ACCESSORS: frozenset[str] = frozenset(
+ {
+ # A survey or tour may point at another product's flag to target its audience.
+ "surveys_linked_flag",
+ "product_tours_linked_flag",
+ # Evaluation and override bookkeeping, not a product that owns the flag.
+ "flag_evaluation_contexts",
+ "featureflagoverride_set",
+ "featureflagdashboards_set",
+ "access",
+ }
+)
+
+
def flag_owner_kind(flag: "FeatureFlag") -> str | None:
"""Return the product that owns this flag, or None when nothing owns it.