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): bind an approval to the ownership it was reviewed under (#113116)

Yasen9368a60cadae
diff --git a/products/approvals/backend/actions/base.py b/products/approvals/backend/actions/base.py
index 2d0846219d6b..52cb33210a49 100644
--- a/products/approvals/backend/actions/base.py
+++ b/products/approvals/backend/actions/base.py
@@ -102,6 +102,21 @@ class BaseAction(ABC):
"""
pass
+ @classmethod
+ def derive_owner_kind(
+ cls,
+ team,
+ resource_id: Optional[str],
+ intent_data: dict[str, Any],
+ ) -> Optional[str]:
+ """Classify which product owns the resource this change targets.
+
+ Called once when the change request is created and again before it applies, so the two
+ answers can be compared. Return None to opt out: the classification is then not recorded
+ and the apply path has nothing to compare.
+ """
+ return None
+
@classmethod
def check_staleness(
cls,
diff --git a/products/approvals/backend/actions/feature_flags.py b/products/approvals/backend/actions/feature_flags.py
index 47fcf5f4823f..708f870661ff 100644
--- a/products/approvals/backend/actions/feature_flags.py
+++ b/products/approvals/backend/actions/feature_flags.py
@@ -7,8 +7,10 @@ from django.db.models import Model
from products.approvals.backend.actions.base import BaseAction
from products.approvals.backend.exceptions import ApplyFailed, PreconditionFailed
+from products.approvals.backend.ownership import OWNER_KIND_UNOWNED
from products.feature_flags.backend.api.feature_flag import FeatureFlagSerializer
from products.feature_flags.backend.models.feature_flag import FeatureFlag
+from products.feature_flags.backend.ownership import flag_owner_kind
def _to_wire_form(value: Any) -> Any:
@@ -109,6 +111,25 @@ def _check_version_staleness(intent_data: dict[str, Any], context: Optional[dict
return False
+def _derive_flag_owner_kind(team, resource_id: Optional[str], intent_data: dict[str, Any]) -> Optional[str]:
+ """Classify the flag this change targets, for the ownership record on the change request.
+
+ A create has no flag yet, so there is nothing to classify and nothing to re-verify; the same
+ is true once a flag can no longer be resolved. Both return None rather than a wrong answer.
+ """
+ flag_id = intent_data.get("flag_id") or resource_id
+ if not flag_id:
+ return None
+
+ try:
+ # nosemgrep: idor-lookup-without-team (project_id comes from the change request's own team)
+ flag = FeatureFlag.objects.get(id=flag_id, team__project_id=team.project_id)
+ except (FeatureFlag.DoesNotExist, ValueError, TypeError):
+ return None
+
+ return flag_owner_kind(flag) or OWNER_KIND_UNOWNED
+
+
def _resolve_existing_flag(change_request) -> Optional[FeatureFlag]:
"""Find the flag a change request operates on, if it already exists.
@@ -190,6 +211,15 @@ class FeatureFlagActionBase(BaseAction):
# Subclasses define the target state
target_active_state: bool
+ @classmethod
+ def derive_owner_kind(
+ cls,
+ team,
+ resource_id: Optional[str],
+ intent_data: dict[str, Any],
+ ) -> Optional[str]:
+ return _derive_flag_owner_kind(team, resource_id, intent_data)
+
@classmethod
def get_target_filter(cls, intent_data: dict[str, Any]) -> dict[str, Any]:
return _flag_target_filter(intent_data)
@@ -431,6 +461,15 @@ class UpdateFeatureFlagAction(BaseAction):
intent_fields = ["rollout_percentage"]
+ @classmethod
+ def derive_owner_kind(
+ cls,
+ team,
+ resource_id: Optional[str],
+ intent_data: dict[str, Any],
+ ) -> Optional[str]:
+ return _derive_flag_owner_kind(team, resource_id, intent_data)
+
@classmethod
def get_target_filter(cls, intent_data: dict[str, Any]) -> dict[str, Any]:
return _flag_target_filter(intent_data)
diff --git a/products/approvals/backend/decorators.py b/products/approvals/backend/decorators.py
index 5c579077eb32..7731b34e760e 100644
--- a/products/approvals/backend/decorators.py
+++ b/products/approvals/backend/decorators.py
@@ -171,6 +171,7 @@ def _create_change_request(
intent=_json_safe(intent_data),
intent_display=_json_safe(display_data),
policy_snapshot=_json_safe(policy_snapshot),
+ owner_kind=action_class.derive_owner_kind(team, resource_id, intent_data),
created_by=user,
state=ChangeRequestState.PENDING,
expires_at=expires_at,
diff --git a/products/approvals/backend/migrations/0004_changerequest_owner_kind.py b/products/approvals/backend/migrations/0004_changerequest_owner_kind.py
new file mode 100644
index 000000000000..9d7c3f2d378a
--- /dev/null
+++ b/products/approvals/backend/migrations/0004_changerequest_owner_kind.py
@@ -0,0 +1,15 @@
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("approvals", "0003_alter_approvalpolicy_organization_and_more"),
+ ]
+
+ operations = [
+ migrations.AddField(
+ model_name="changerequest",
+ name="owner_kind",
+ field=models.CharField(blank=True, max_length=64, null=True),
+ ),
+ ]
diff --git a/products/approvals/backend/migrations/max_migration.txt b/products/approvals/backend/migrations/max_migration.txt
index de80a294a9c3..f41c883bbef5 100644
--- a/products/approvals/backend/migrations/max_migration.txt
+++ b/products/approvals/backend/migrations/max_migration.txt
@@ -1 +1 @@
-0003_alter_approvalpolicy_organization_and_more
+0004_changerequest_owner_kind
diff --git a/products/approvals/backend/models.py b/products/approvals/backend/models.py
index 9f331d4ba656..c2533bb7b753 100644
--- a/products/approvals/backend/models.py
+++ b/products/approvals/backend/models.py
@@ -43,6 +43,11 @@ class ChangeRequest(UUIDModel, CreatedMetaFields, UpdatedMetaFields):
policy_snapshot = models.JSONField()
+ # Which product owned the resource when this request was created. Re-derived at apply and
+ # refused on a mismatch, so an approval binds to the ownership the approvers reviewed.
+ # NULL means no classification was recorded, which an apply treats as nothing to check.
+ owner_kind = models.CharField(max_length=64, null=True, blank=True)
+
validation_status = models.CharField(
max_length=16,
choices=ValidationStatus,
diff --git a/products/approvals/backend/ownership.py b/products/approvals/backend/ownership.py
new file mode 100644
index 000000000000..b03c3548d9f6
--- /dev/null
+++ b/products/approvals/backend/ownership.py
@@ -0,0 +1,18 @@
+from typing import Optional
+
+# A recorded classification meaning "nothing owned this resource". It is distinct from NULL,
+# which means no classification was recorded at all: a request created before the column
+# existed, or an action that does not classify ownership. Those must still apply.
+OWNER_KIND_UNOWNED = "unowned"
+
+
+def owner_kind_changed(recorded: Optional[str], current: Optional[str]) -> bool:
+ """Whether the owner recorded when a change request was created still holds.
+
+ An absent classification on either side is not a change. That keeps requests created
+ before the column existed applying exactly as they did, and leaves actions that do not
+ classify ownership unaffected.
+ """
+ if recorded is None or current is None:
+ return False
+ return recorded != current
diff --git a/products/approvals/backend/services.py b/products/approvals/backend/services.py
index 3e384a16e52a..103cf53a23a7 100644
--- a/products/approvals/backend/services.py
+++ b/products/approvals/backend/services.py
@@ -5,6 +5,8 @@ from typing import Any, Optional
from django.db import transaction
from django.utils import timezone
+from prometheus_client import Counter
+
from posthog.api.utils import ServiceRequest
from posthog.event_usage import report_user_action
from posthog.models import User
@@ -22,9 +24,20 @@ from products.approvals.backend.notifications import (
send_approval_applied_notification,
send_approval_decision_notification,
)
+from products.approvals.backend.ownership import owner_kind_changed
logger = logging.getLogger(__name__)
+# Approved changes refused at apply because a different product owns the resource now. This is
+# the blast radius of binding an approval to the ownership it was reviewed under: every increment
+# is a change an approver said yes to that did not land. recorded/current carry owner kinds, which
+# are a closed set, so the label stays bounded.
+OWNERSHIP_MISMATCH_COUNTER = Counter(
+ "posthog_approvals_apply_ownership_mismatch_total",
+ "Approved change requests refused at apply because the resource owner changed",
+ labelnames=["action", "recorded", "current"],
+)
+
class RequestContext(ServiceRequest):
"""The request shim an apply replays a serializer write under.
@@ -80,6 +93,28 @@ 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)
+ current_owner_kind = action_class.derive_owner_kind(
+ change_request.team, change_request.resource_id, change_request.intent
+ )
+ if owner_kind_changed(change_request.owner_kind, current_owner_kind):
+ # The approvers reviewed this change against one owner, and a different product owns the
+ # resource now. Which policy applies is keyed on that owner, so applying would land a
+ # change nobody with the current owner's policy ever saw.
+ OWNERSHIP_MISMATCH_COUNTER.labels(
+ action=change_request.action_key,
+ recorded=change_request.owner_kind,
+ current=current_owner_kind,
+ ).inc()
+ change_request.state = ChangeRequestState.FAILED
+ change_request.apply_error = (
+ f"Ownership changed since this request was created: {change_request.owner_kind} -> {current_owner_kind}"
+ )
+ change_request.save()
+ raise PreconditionFailed(
+ "This resource now belongs to a different product than when the change was requested. "
+ "Request the change again so the right approvers review it."
+ )
+
is_valid, errors = action_class.validate_intent(
change_request.intent,
context=validation_context,
diff --git a/products/approvals/backend/tests/test_decorators.py b/products/approvals/backend/tests/test_decorators.py
index c9ba22cfb647..450ffcc8dfe2 100644
--- a/products/approvals/backend/tests/test_decorators.py
+++ b/products/approvals/backend/tests/test_decorators.py
@@ -237,6 +237,7 @@ class TestChangeRequestIntentIsJsonSafe(APIBaseTest):
action_class.key = "feature_flag.update"
action_class.version = 1
action_class.resource_type = "feature_flag"
+ action_class.derive_owner_kind.return_value = None
return _create_change_request(
action_class=action_class,
diff --git a/products/approvals/backend/tests/test_services.py b/products/approvals/backend/tests/test_services.py
index 02cf07df64fb..f52a153f807d 100644
--- a/products/approvals/backend/tests/test_services.py
+++ b/products/approvals/backend/tests/test_services.py
@@ -7,9 +7,10 @@ from django.utils import timezone
from parameterized import parameterized
-from products.approvals.backend.exceptions import ApplyFailed, InvalidStateError
+from products.approvals.backend.exceptions import ApplyFailed, InvalidStateError, PreconditionFailed
from products.approvals.backend.models import ApprovalPolicy, ChangeRequest, ChangeRequestState
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 (
REDACTED_PAYLOAD_VALUE,
FlagPayloadCodec,
@@ -188,3 +189,65 @@ class TestApplyApprovedEncryptedPayloads(APIBaseTest):
flag.refresh_from_db()
assert flag.active is False
assert flag.filters["payloads"]["true"] == stored_payload
+
+
+class TestApplyRechecksOwnership(APIBaseTest):
+ # A change request records which product owned the flag when it was raised. Which policy
+ # applies is keyed on that owner, so an apply under a different owner would land a change the
+ # current owner's approvers never saw.
+
+ def _flag(self) -> FeatureFlag:
+ return FeatureFlag.objects.create(team=self.team, key="gated", name="gated", active=False, created_by=self.user)
+
+ def _change_request(self, flag: FeatureFlag, owner_kind: str | None) -> 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),
+ owner_kind=owner_kind,
+ 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),
+ )
+
+ @parameterized.expand(
+ [
+ ("adopted by an experiment after the request", "unowned", True, False),
+ ("released by its experiment after the request", "experiment", False, False),
+ ("owner unchanged", "unowned", False, True),
+ ("still owned by the same experiment", "experiment", True, True),
+ ("never classified", None, True, True),
+ ]
+ )
+ def test_apply_refuses_when_the_owner_changed(
+ self, _name: str, recorded: str | None, owned_now: bool, should_apply: bool
+ ) -> None:
+ flag = self._flag()
+ change_request = self._change_request(flag, recorded)
+ if owned_now:
+ Experiment.objects.create(team=self.team, name="exp", feature_flag=flag)
+
+ 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.state == ChangeRequestState.FAILED