: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
feat(devex): give facade views one object access hook and fail closed (#127980)
Julian Bez4f93dfcbb692
diff --git a/.semgrep/rules/devex/facade-views-read-object-not-dangerously-get-object.py b/.semgrep/rules/devex/facade-views-read-object-not-dangerously-get-object.pynew file mode 100644index 000000000000..6d70da977472--- /dev/null+++ b/.semgrep/rules/devex/facade-views-read-object-not-dangerously-get-object.py@@ -0,0 +1,18 @@+# Test cases for facade-views-read-object-not-dangerously-get-object.+# ruff: noqa+++class ExportViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):+ # ruleid: facade-views-read-object-not-dangerously-get-object+ def dangerously_get_object(self) -> ExportRecord:+ export = get_export(self.team_id, self.kwargs["pk"])+ self.check_object_permissions(self.request, export)+ return export+++class RunViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):+ records_have_object_access_rules = False++ # ok: facade-views-read-object-not-dangerously-get-object+ def read_object(self) -> RunRecord | None:+ return get_run(self.team_id, self.kwargs["pk"])diff --git a/.semgrep/rules/devex/facade-views-read-object-not-dangerously-get-object.yaml b/.semgrep/rules/devex/facade-views-read-object-not-dangerously-get-object.yamlnew file mode 100644index 000000000000..36bf4396c00a--- /dev/null+++ b/.semgrep/rules/devex/facade-views-read-object-not-dangerously-get-object.yaml@@ -0,0 +1,31 @@+rules:+ - id: facade-views-read-object-not-dangerously-get-object+ message: |+ `dangerously_get_object()` skips the object permission checks of `TeamAndOrgViewSetMixin`,+ so each override has to call `check_object_permissions` itself, and nothing makes it adapt+ a facade contract for `AccessControlPermission`.++ A view that reads through a facade overrides `read_object()` instead. The mixin's+ `get_object()` then runs the object permission checks on the record and returns it. Also+ define `object_access_ref(record)` to return the record's `ObjectAccessRef`, or set+ `records_have_object_access_rules = False` when no access rule can name one record.+ See "Who owns RBAC?" in `products/architecture.md`.+ severity: ERROR+ languages: [python]+ paths:+ include:+ - 'products/**'+ exclude:+ - '**/test/**'+ - '**/tests/**'+ - '**/test_*.py'+ - '**/*_test.py'+ # Workflow templates are INTERNAL to access control, and their own permission class+ # reads the template's scope from the returned object.+ - 'products/workflows/backend/presentation/views/hog_flow_template.py'+ patterns:+ - pattern: |+ def dangerously_get_object(...):+ ...+ metadata:+ category: best-practicediff --git a/posthog/api/routing.py b/posthog/api/routing.pyindex 2f91cd446ad6..40f1adccae2b 100644--- a/posthog/api/routing.py+++ b/posthog/api/routing.py@@ -52,6 +52,7 @@ from posthog.queryset_paging import stable_queryset_orderingfrom posthog.scopes import APIScopeObjectOrNotSupportedfrom posthog.user_permissions import UserPermissions+from products.access_control.backend.facade.contracts import ObjectAccessReffrom products.access_control.backend.facade.user_access_control import UserAccessControlif TYPE_CHECKING:@@ -245,6 +246,11 @@ class TeamAndOrgViewSetMixin(_GenericViewSet):# PostHogAutoSchema reads the same mapping to type the OpenAPI path parameters.path_parameters: dict[str, PathParameterType | PathParameter] = {}+ # Set to False on a view whose read_object() records have no access rules of their own, for+ # example when the scope object is not an access-control resource. AccessControlPermission then+ # skips the object check for those records. Otherwise it needs object_access_ref().+ records_have_object_access_rules: bool = True+@classmethoddef _check_path_parameters(cls) -> None:for name, declared in cls.path_parameters.items():@@ -268,7 +274,7 @@ class TeamAndOrgViewSetMixin(_GenericViewSet):super().__init_subclass__(**kwargs)protected_methods = {"get_queryset": "Use safely_get_queryset instead",- "get_object": "Use safely_get_object instead",+ "get_object": "Use safely_get_object, or read_object for a view without a queryset, instead","get_permissions": "Add additional 'permission_classes' via the class attribute instead. Or in exceptional use cases use dangerously_get_permissions instead","get_authenticators": "Add additional 'authentication_classes' via the class attribute instead",}@@ -554,6 +560,22 @@ class TeamAndOrgViewSetMixin(_GenericViewSet):def safely_get_object(self, queryset: QuerySet) -> Any:raise NotImplementedError()+ def read_object(self) -> Any:+ """+ Fetch the record in the URL, for a view that reads through a facade and has no queryset.+ The facade must filter by team. Return None when no record matches, which becomes a 404.+ get_object() runs the object permission checks on the record and returns it.+ """+ raise NotImplementedError()++ def object_access_ref(self, record: Any) -> ObjectAccessRef:+ """The access-control reference for a record that read_object() returned."""+ raise NotImplementedError(+ f"{type(self).__name__}.read_object() returned a {type(record).__name__}, which object access "+ "control cannot check. Define object_access_ref() to return its ObjectAccessRef, or set "+ "records_have_object_access_rules = False when no access rule can name one record."+ )+def get_object(self):"""We don't want to allow generic overriding of get_object as under the hood it does@@ -565,6 +587,16 @@ class TeamAndOrgViewSetMixin(_GenericViewSet):except NotImplementedError:pass+ try:+ record = self.read_object()+ except NotImplementedError:+ pass+ else:+ if record is None:+ raise NotFound()+ self.check_object_permissions(self.request, record)+ return record+queryset = self.filter_queryset(self.get_queryset())try:diff --git a/posthog/api/test/test_routing.py b/posthog/api/test/test_routing.pyindex 05d50b304b3e..0d7d35fbf204 100644--- a/posthog/api/test/test_routing.py+++ b/posthog/api/test/test_routing.py@@ -349,8 +349,9 @@ class TestTeamAndOrgViewSetMixin(APIBaseTest):def get_object(self):pass- assert (- str(e.value) == "Method get_object is protected and should not be overridden. Use safely_get_object instead"+ assert str(e.value) == (+ "Method get_object is protected and should not be overridden. "+ "Use safely_get_object, or read_object for a view without a queryset, instead")diff --git a/posthog/permissions.py b/posthog/permissions.pyindex 4056d867bb9a..6961093c7eb5 100644--- a/posthog/permissions.py+++ b/posthog/permissions.py@@ -1259,10 +1259,15 @@ class AccessControlPermission(ScopeBasePermission):if not required_level:return True- if isinstance(object, ObjectAccessRef):+ if isinstance(object, Model):+ has_access = uac.check_access_level_for_object(object, required_level=required_level)+ elif isinstance(object, ObjectAccessRef):has_access = uac.check_access_level_for_ref(object, required_level=required_level)+ elif not view.records_have_object_access_rules:+ # has_permission already checked the resource-level rules, and no rule names one record.+ return Trueelse:- has_access = uac.check_access_level_for_object(object, required_level=required_level)+ has_access = uac.check_access_level_for_ref(view.object_access_ref(object), required_level=required_level)if not has_access:self.message = f"You do not have {required_level} access to this resource."diff --git a/posthog/test/test_permissions.py b/posthog/test/test_permissions.pyindex eb8a0aa74722..acc63235c6a3 100644--- a/posthog/test/test_permissions.py+++ b/posthog/test/test_permissions.py@@ -1,8 +1,10 @@import jsonfrom datetime import timedelta+from types import SimpleNamespacefrom typing import castfrom uuid import uuid4+import pytestfrom posthog.test.base import BaseTestfrom unittest.mock import Mock, PropertyMock, patch@@ -175,14 +177,19 @@ class TestAccessControlPermission(BaseTest):# Should NOT have permissionassert self.permission.has_permission(request, view) is False- def _as_target(self, notebook, target: str):+ def _as_target(self, notebook, target: str, view):if target == "model":return notebook- return ObjectAccessRef(- resource="notebook", id=str(notebook.id), team_id=self.team.id, created_by_id=notebook.created_by_id+ if target == "ref":+ return ObjectAccessRef(+ resource="notebook", id=str(notebook.id), team_id=self.team.id, created_by_id=notebook.created_by_id+ )+ view.object_access_ref = lambda record: ObjectAccessRef(+ resource="notebook", id=record.id, team_id=record.team_id, created_by_id=record.created_by_id)+ return SimpleNamespace(id=str(notebook.id), team_id=self.team.id, created_by_id=notebook.created_by_id)- @parameterized.expand([("model",), ("ref",)])+ @parameterized.expand([("model",), ("ref",), ("record",)])def test_has_object_permission_with_specific_access(self, target):"""Test object-level permission when user has specific access to the object"""# Set resource-level access to "none"@@ -200,9 +207,11 @@ class TestAccessControlPermission(BaseTest):view = self._create_real_view(action="retrieve", pk=str(self.notebook_1.id))# Should have object permission for notebook_1- assert self.permission.has_object_permission(request, view, self._as_target(self.notebook_1, target)) is True+ assert (+ self.permission.has_object_permission(request, view, self._as_target(self.notebook_1, target, view)) is True+ )- @parameterized.expand([("model",), ("ref",)])+ @parameterized.expand([("model",), ("ref",), ("record",)])def test_has_object_permission_without_specific_access(self, target):"""Test object-level permission when user lacks specific access to the object"""# Set resource-level access to "none"@@ -212,7 +221,22 @@ class TestAccessControlPermission(BaseTest):view = self._create_real_view(action="retrieve", pk=str(self.notebook_2.id))# Should NOT have object permission for notebook_2- assert self.permission.has_object_permission(request, view, self._as_target(self.notebook_2, target)) is False+ assert (+ self.permission.has_object_permission(request, view, self._as_target(self.notebook_2, target, view))+ is False+ )++ def test_has_object_permission_on_a_record_without_a_ref(self):+ self._create_access_control(resource="notebook", access_level="none")+ request = self._create_mock_request()+ view = self._create_real_view(action="retrieve", pk=str(self.notebook_2.id))+ record = SimpleNamespace(id=str(self.notebook_2.id), team_id=self.team.id, created_by_id=None)++ with pytest.raises(NotImplementedError, match="object_access_ref"):+ self.permission.has_object_permission(request, view, record)++ view.records_have_object_access_rules = False+ assert self.permission.has_object_permission(request, view, record) is Truedef test_has_permission_for_create_action_with_none_resource_access(self):"""Test that create actions are blocked when user has 'none' resource access"""diff --git a/products/access_control/backend/facade/contracts.py b/products/access_control/backend/facade/contracts.pyindex c755f088a98b..d76157418adf 100644--- a/products/access_control/backend/facade/contracts.py+++ b/products/access_control/backend/facade/contracts.py@@ -79,7 +79,7 @@ class FallbackParent:class ObjectAccessRef:"""The fields object-level access control reads from one object, without the model.- A view that serves a facade contract passes this to `check_object_permissions` in place of a+ A view that serves a facade contract returns this from `object_access_ref()` in place of amodel instance. Resolution needs the resource, the object id, and the creator. A resource thatinherits access from a parent object through a foreign key (`RESOURCE_FALLBACK_MAP`) also needs`fallback_parent`, read off that foreign key. Without it the check raises, because resolutiondiff --git a/products/access_control/backend/facade/user_access_control.py b/products/access_control/backend/facade/user_access_control.pyindex bba5c70d8062..5102fb46645d 100644--- a/products/access_control/backend/facade/user_access_control.py+++ b/products/access_control/backend/facade/user_access_control.py@@ -390,6 +390,17 @@ def _fallback_parent_fk(model: type[Model], parent_resource: APIScopeObject) ->return None+def _require_model_instance(obj: object, ref_method: str) -> None:+ # model_to_resource() returns None for an object it cannot classify, and the object checks read+ # None as "no access control applies". A facade contract would pass every check without this guard.+ if isinstance(obj, Model):+ return+ raise TypeError(+ f"Expected a Django model instance, got {type(obj).__name__}. For an object held as a "+ f"contract, build an ObjectAccessRef and call {ref_method}() instead."+ )++def fallback_parent_object_id(obj: Model, parent_resource: APIScopeObject) -> Optional[str]:"""Id of the object `obj` falls back to for access, or None when it has no such parent.@@ -883,6 +894,7 @@ class UserAccessControl:explicit: If True, only return explicit access controls (no fallback to default)specific_only: If True, only consider access controls with roles or organization members"""+ _require_model_instance(obj, "access_level_for_ref")resource = resource or model_to_resource(obj)org_membership = self._organization_membership@@ -994,6 +1006,7 @@ class UserAccessControl:Returns true or false if access controls are applied, otherwise None"""+ _require_model_instance(obj, "check_access_level_for_ref")resource = model_to_resource(obj)if not resource:@@ -1039,6 +1052,7 @@ class UserAccessControl:3. The user is an org admin4. The user has "manager" access to the resource"""+ _require_model_instance(obj, "check_can_modify_access_levels_for_ref")if self._is_creator(obj):# TODO: Should this always be the case, even for projects?diff --git a/products/access_control/backend/presentation/access_control.py b/products/access_control/backend/presentation/access_control.pyindex f4154711fafd..f64d6ea688c7 100644--- a/products/access_control/backend/presentation/access_control.py+++ b/products/access_control/backend/presentation/access_control.py@@ -736,6 +736,9 @@ class UserAccessControlSerializerMixin(serializers.Serializer):if not user_access_control.access_controls_supported:continueobj_for_check = getattr(self.instance, "team", self.instance)+ if obj_for_check is None:+ # A global record (team=None) belongs to no project, so no project-level field rule applies.+ continuehas_access = user_access_control.check_access_level_for_object(obj_for_check, required_level)else:has_access = user_access_control.check_access_level_for_resource(resource, required_level)diff --git a/products/access_control/backend/tests/test_user_access_control.py b/products/access_control/backend/tests/test_user_access_control.pyindex dd3d5a029ccd..8a303bb5d8de 100644--- a/products/access_control/backend/tests/test_user_access_control.py+++ b/products/access_control/backend/tests/test_user_access_control.py@@ -1227,16 +1227,25 @@ class TestUserAccessControlSpecificAccessLevelForObject(BaseUserAccessControlTesaccess_level = uac.specific_access_level_for_object(self.dashboard)assert access_level is None- def test_returns_none_for_unsupported_model(self):- """Test that returns None for unsupported models"""-- class UnsupportedModel:- def __init__(self):+ @parameterized.expand(+ [+ ("specific_access_level_for_object", lambda uac, obj: uac.specific_access_level_for_object(obj)),+ ("access_level_for_object", lambda uac, obj: uac.access_level_for_object(obj)),+ ("check_access_level_for_object", lambda uac, obj: uac.check_access_level_for_object(obj, "viewer")),+ (+ "check_can_modify_access_levels_for_object",+ lambda uac, obj: uac.check_can_modify_access_levels_for_object(obj),+ ),+ ]+ )+ def test_raises_for_an_object_that_is_not_a_model(self, _name, call):+ class DashboardContract:+ def __init__(self, created_by_id: int):self.id = 1+ self.created_by_id = created_by_id- unsupported_obj = UnsupportedModel()- access_level = self.user_access_control.specific_access_level_for_object(unsupported_obj) # type: ignore- assert access_level is None+ with pytest.raises(TypeError, match="ObjectAccessRef"):+ call(self.user_access_control, DashboardContract(created_by_id=self.user.id))def test_member_specific_access_control(self):"""Test that member-specific access controls are detected"""diff --git a/products/architecture.md b/products/architecture.mdindex 0c2d83f55a6c..4b240fa740f0 100644--- a/products/architecture.md+++ b/products/architecture.md@@ -451,16 +451,16 @@ If both presentation and logic need the same utility (caching, permissions, etc.User RBAC stays on the **viewset** — it depends on the authenticated `request`/`user`, which the facade doesn't have (facades also run from Celery, CLIs, and other products). Declare it the standard way: `scope_object` plus `scope_object_read_actions`/`scope_object_write_actions`, and let the shared permission classes (`APIScopePermission`, `AccessControlPermission`) on `TeamAndOrgViewSetMixin` enforce API-scope and resource access. See `products/visual_review/backend/presentation/views.py`.A view that fetches a contract from the facade has no model instance for DRF's `get_object()` to check.-It still checks object access through the same permission stack, with an `ObjectAccessRef` from `products/access_control/backend/facade/contracts.py` in place of the instance:+It still checks object access through the same permission stack:-- Override `safely_get_object()` to fetch the contract through the facade. `TeamAndOrgViewSetMixin` forbids overriding `get_object()` itself.-- Build `ObjectAccessRef(resource=..., id=..., team_id=..., created_by_id=...)` from the contract and return it. Return `None` for a missing object, which becomes a 404.-- The mixin's `get_object()` then calls `check_object_permissions` on the reference. Every permission class on the view runs, and `AccessControlPermission` resolves the object's access from the reference.-- `LogEntryMixin` and `AppMetricsMixin` read only `.id` from `get_object()`, so they keep working without the model.-- An action that needs the contract itself can fetch it, build the reference, and call `self.check_object_permissions(self.request, ref)` directly.+- Override `read_object()` to fetch the contract through the facade, filtered by team. Return `None` for a missing object, which becomes a 404. `TeamAndOrgViewSetMixin` forbids overriding `get_object()` itself.+- The mixin's `get_object()` calls `check_object_permissions` on the contract and returns the contract. Actions, `LogEntryMixin`, `AppMetricsMixin` and DRF's detail `OPTIONS` metadata get the contract from `get_object()`.+- `AccessControlPermission` needs an `ObjectAccessRef` (`products/access_control/backend/facade/contracts.py`) to resolve the object's access. Override `object_access_ref(record)` to build it from the contract. Set `fallback_parent` when the resource inherits access from a parent object (`RESOURCE_FALLBACK_MAP`).+- When no access rule can name one record, for example when `scope_object` is not an access-control resource, set `records_have_object_access_rules = False` instead.+- A view that does neither fails closed: the object check raises.Do not call `AccessControlPermission` methods by hand, and do not pass `UserAccessControl` or a required level into the facade.-A resource that inherits access from a parent object (`RESOURCE_FALLBACK_MAP`) needs the model instance, and a reference for it raises.+`UserAccessControl` object methods take a model instance only. They raise on a contract.The facade owns **tenant scoping** (`team_id` enforced via `for_team(team_id)` / a `ProductTeamModel` fail-closed manager) and **domain invariants** (state machines, idempotency) — these must hold for every caller, so they live below the HTTP boundary; user RBAC must not. Keeping RBAC in the shared DRF stack also lets cross-cutting permission tests enforce it consistently across products.diff --git a/products/batch_exports/backend/presentation/views/batch_export/backfills.py b/products/batch_exports/backend/presentation/views/batch_export/backfills.pyindex 9246c3b81a5b..768ee3f068cf 100644--- a/products/batch_exports/backend/presentation/views/batch_export/backfills.py+++ b/products/batch_exports/backend/presentation/views/batch_export/backfills.py@@ -101,6 +101,8 @@ class BatchExportBackfillViewSet(TeamAndOrgViewSetMixin, mixins.RetrieveModelMix"batch_export_id": PathParameter(type=UUID, description="The BatchExport this backfill belongs to."),}scope_object = "batch_export"+ # batch_export is not an access-control resource, so no rule names one backfill.+ records_have_object_access_rules = Falseserializer_class = BatchExportBackfillSerializerpagination_class = BackfillsCursorPagination# The paginator reads the ordering through this filter, and the facade applies it.@@ -111,19 +113,11 @@ class BatchExportBackfillViewSet(TeamAndOrgViewSetMixin, mixins.RetrieveModelMixdef _get_export_id(self) -> UUID:return self.kwargs["parent_lookup_batch_export_id"]- def dangerously_get_object(self) -> contracts.BatchExportBackfillDetail:- # The mixin's get_object() reads through a queryset, which this view no longer has, so the- # backfill is read through the facade instead. That skips the mixin's team filter and object- # permission check, so both happen here: the facade filters by team and export, and- # check_object_permissions runs on the contract.+ def read_object(self) -> contracts.BatchExportBackfillDetail:try:- backfill = batch_exports_api.get_batch_export_backfill(- self.team_id, self._get_export_id(), self.kwargs["pk"]- )+ return batch_exports_api.get_batch_export_backfill(self.team_id, self._get_export_id(), self.kwargs["pk"])except contracts.BatchExportBackfillNotFoundError as e:raise NotFound(*e.args) from e- self.check_object_permissions(self.request, backfill)- return backfilldef list(self, request: request.Request, *args: Any, **kwargs: Any) -> response.Response:export_id = self._get_export_id()diff --git a/products/batch_exports/backend/presentation/views/batch_export/exports.py b/products/batch_exports/backend/presentation/views/batch_export/exports.pyindex a048e176ba20..95c6fc05cf00 100644--- a/products/batch_exports/backend/presentation/views/batch_export/exports.py+++ b/products/batch_exports/backend/presentation/views/batch_export/exports.py@@ -667,21 +667,16 @@ class BatchExportViewSet(TeamAndOrgViewSetMixin, LogEntryMixin, viewsets.ModelViserializer_class = BatchExportSerializerpagination_class = FacadeLimitOffsetPaginationlog_source = "batch_exports"+ # batch_export is not an access-control resource, so no rule names one export.+ records_have_object_access_rules = False- def dangerously_get_object(self) -> contracts.BatchExportConfiguration:- # The mixin's get_object() reads through a queryset, which this view does not have, so the- # export is read through the facade instead. That skips the mixin's team filter and object- # permission check, so both happen here: the facade filters by team, and- # check_object_permissions runs on the contract. `logs` reads the export through here too.- export_id = self.kwargs["pk"]+ def read_object(self) -> contracts.BatchExportConfiguration:try:- batch_export = batch_exports_api.get_batch_export(- self.team_id, export_id, include_latest_runs=self.action == "retrieve"+ return batch_exports_api.get_batch_export(+ self.team_id, self.kwargs["pk"], include_latest_runs=self.action == "retrieve")except BatchExportNotFoundError as e:raise NotFound(*e.args) from e- self.check_object_permissions(self.request, batch_export)- return batch_exportdef list(self, request: request.Request, *args: typing.Any, **kwargs: typing.Any) -> response.Response:return facade_page_response(diff --git a/products/batch_exports/backend/presentation/views/batch_export/runs.py b/products/batch_exports/backend/presentation/views/batch_export/runs.pyindex 67651020be91..f744d361658c 100644--- a/products/batch_exports/backend/presentation/views/batch_export/runs.py+++ b/products/batch_exports/backend/presentation/views/batch_export/runs.py@@ -165,6 +165,8 @@ class BatchExportRunViewSet(TeamAndOrgViewSetMixin, LogEntryMixin, mixins.Retrie"batch_export_id": PathParameter(type=UUID, description="The `BatchExport` this run belongs to."),}scope_object = "batch_export"+ # batch_export is not an access-control resource, so no rule names one run.+ records_have_object_access_rules = Falseserializer_class = BatchExportRunSerializerpagination_class = RunsCursorPagination# The paginator reads the ordering through this filter, and the facade applies it.@@ -206,17 +208,11 @@ class BatchExportRunViewSet(TeamAndOrgViewSetMixin, LogEntryMixin, mixins.Retriestatuses=statuses, created=contracts.DatetimeRange(start=after_datetime, end=before_datetime))- def dangerously_get_object(self) -> contracts.BatchExportRunDetail:- # The mixin's get_object() reads through a queryset, which this view no longer has, so the- # run is read through the facade instead. That skips the mixin's team filter and object- # permission check, so both happen here: the facade filters by team and export, and- # check_object_permissions runs on the contract. `logs` reads the run through here too.+ def read_object(self) -> contracts.BatchExportRunDetail:try:- run = batch_exports_api.get_batch_export_run(self.team_id, self._get_export_id(), self.kwargs["pk"])+ return batch_exports_api.get_batch_export_run(self.team_id, self._get_export_id(), self.kwargs["pk"])except contracts.BatchExportRunNotFoundError as e:raise NotFound(*e.args) from e- self.check_object_permissions(self.request, run)- return rundef list(self, request: request.Request, *args: Any, **kwargs: Any) -> response.Response:export_id = self._get_export_id()diff --git a/products/batch_exports/backend/presentation/views/file_download.py b/products/batch_exports/backend/presentation/views/file_download.pyindex d548fbe98dbe..987803cc54af 100644--- a/products/batch_exports/backend/presentation/views/file_download.py+++ b/products/batch_exports/backend/presentation/views/file_download.py@@ -370,6 +370,8 @@ def _to_file_download_request(validated_data: dict[str, Any]) -> contracts.FileDclass FileDownloadBatchExportOnDemandViewSet(TeamAndOrgViewSetMixin, LogEntryMixin, viewsets.GenericViewSet):path_parameters = {"pk": PathParameter(type=UUID, description="A UUID string identifying this batch export run.")}scope_object = "batch_export"+ # batch_export is not an access-control resource, so no rule names one run.+ records_have_object_access_rules = Falseserializer_class = FileDownloadBatchExportOnDemandSerializerpagination_class = FacadeLimitOffsetPaginationlog_source = "batch_exports"@@ -387,18 +389,11 @@ class FileDownloadBatchExportOnDemandViewSet(TeamAndOrgViewSetMixin, LogEntryMixreturn [BatchExportsCountRowsBurstRateThrottle(), BatchExportsCountRowsSustainedRateThrottle()]return super().get_throttles()- def dangerously_get_object(self) -> contracts.FileDownloadRun:- # The mixin's get_object() reads through a queryset, which this view does not have, so the- # run is read through the facade instead. That skips the mixin's team filter and object- # permission check, so both happen here: the facade filters by team, and- # check_object_permissions runs on the contract. `logs` reads the run through here too.- run_id = self.kwargs["pk"]+ def read_object(self) -> contracts.FileDownloadRun:try:- run = batch_exports_api.get_file_download_run(self.team_id, run_id)+ return batch_exports_api.get_file_download_run(self.team_id, self.kwargs["pk"])except contracts.FileDownloadNotFoundError as e:raise NotFound(*e.args) from e- self.check_object_permissions(self.request, run)- return rundef list(self, request, *args, **kwargs) -> response.Response:return facade_page_response(diff --git a/products/messaging/backend/presentation/views/message_templates.py b/products/messaging/backend/presentation/views/message_templates.pyindex 8945dc955ccb..b01b358b5cdb 100644--- a/products/messaging/backend/presentation/views/message_templates.py+++ b/products/messaging/backend/presentation/views/message_templates.py@@ -979,6 +979,8 @@ class MessageTemplatesViewSet(# A project secret API key can only send. Template CRUD stays session/personal API key/OAuth only.psak_allowed_actions = ["send"]transactional_email_send_actions = ("send",)+ # Access rules on hog_flow name workflow ids, never template ids, so no rule names one template.+ records_have_object_access_rules = Falseserializer_class = MessageTemplateSerializer@@ -987,16 +989,14 @@ class MessageTemplatesViewSet(return transactional_email_throttles()return super().get_throttles()- def dangerously_get_object(self) -> MessageTemplateRow:+ def read_object(self) -> MessageTemplateRow | None:# Team scoping happens in the facade lookup, because the view has no queryset to filter.# DRF's detail OPTIONS metadata also calls get_object(), so the lookup must live here.try:# A send never reads the tags, so it skips their queries.- template = get_template(self.team_id, self.kwargs["pk"], with_tags=self.action != "send")+ return get_template(self.team_id, self.kwargs["pk"], with_tags=self.action != "send")except MessageTemplateMissing:- raise NotFound()- self.check_object_permissions(self.request, template)- return template+ return Nonedef _with_creators(self, templates: Sequence[MessageTemplateRow]) -> list[SimpleNamespace]:creator_ids = {template.created_by_id for template in templates if template.created_by_id}@@ -1258,10 +1258,19 @@ class MessagingSendViewSet(TransactionalEmailSendMixin, TeamAndOrgViewSetMixin,authentication_classes = [ProjectSecretAPIKeyAuthentication]psak_allowed_actions = ["email"]transactional_email_send_actions = ("email",)+ # Access rules on hog_flow name workflow ids, never template ids, so no rule names one template.+ records_have_object_access_rules = Falsedef get_throttles(self):return transactional_email_throttles()+ def read_object(self) -> MessageTemplateRow | None:+ # The `email` action names its template in the request body, not in the URL.+ try:+ return get_template(self.team_id, self.request.validated_data["template_id"], with_tags=False)+ except MessageTemplateMissing:+ return None+def handle_exception(self, exc: Exception) -> Response:response = super().handle_exception(exc)if isinstance(response.data, dict):@@ -1291,11 +1300,7 @@ class MessagingSendViewSet(TransactionalEmailSendMixin, TeamAndOrgViewSetMixin,with transactional_email_stage("feature_flag"):self._require_transactional_email_flag()with transactional_email_stage("template_lookup"):- try:- template = get_template(self.team_id, request.validated_data["template_id"], with_tags=False)- except MessageTemplateMissing:- raise NotFound()- self.check_object_permissions(request, template)+ template = self.get_object()return self._queue_transactional_email(request, template, route="send_email")def _send_code_email(self, request: Any) -> Response:diff --git a/products/signals/backend/presentation/scout_rubrics.py b/products/signals/backend/presentation/scout_rubrics.pyindex afdc4ecbb066..49e09521e3cc 100644--- a/products/signals/backend/presentation/scout_rubrics.py+++ b/products/signals/backend/presentation/scout_rubrics.py@@ -209,21 +209,21 @@ class SignalScoutRubricViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):scope_object = "signal_scout"lookup_field = "id"pagination_class = None+ # signal_scout is not an access-control resource, so no rule names one rubric.+ records_have_object_access_rules = Falsedef dangerously_get_required_scopes(self, request: Request, view: APIView) -> list[str]:return ["signal_scout:read" if getattr(view, "action", None) == "retrieve" else "signal_scout:write"]- def get_rubric(self, config_id: str) -> ScoutRubricDocument:+ def read_object(self) -> ScoutRubricDocument:try:- document = get_scout_rubric(self.team_id, config_id)+ return get_scout_rubric(self.team_id, self.kwargs["id"])except ScoutRubricNotFound:raise exceptions.NotFound() from None- self.check_object_permissions(self.request, document)- return document@extend_schema(responses={200: ScoutRubricDocumentSerializer}, operation_id="signals_scout_rubrics_retrieve")def retrieve(self, request: Request, id: str, **kwargs: object) -> Response:- return rubric_response(self.get_rubric(id))+ return rubric_response(self.get_object())@extend_schema(request=ScoutRubricSaveSerializer,@@ -231,7 +231,7 @@ class SignalScoutRubricViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):operation_id="signals_scout_rubrics_update",)def update(self, request: Request, id: str, **kwargs: object) -> Response:- document = self.get_rubric(id)+ document = self.get_object()serializer = ScoutRubricSaveSerializer(data=request.data)serializer.is_valid(raise_exception=True)adopt_generation_id = serializer.validated_data.get("adopt_generation_id")@@ -251,7 +251,7 @@ class SignalScoutRubricViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):)@action(detail=True, methods=["post"])def generate(self, request: Request, id: str, **kwargs: object) -> Response:- document = self.get_rubric(id)+ document = self.get_object()user_id = request.user.pkif user_id is None:raise exceptions.NotAuthenticated()diff --git a/products/subscriptions/backend/presentation/views.py b/products/subscriptions/backend/presentation/views.pyindex 9d9fda2bd943..9dadf0b9d6ca 100644--- a/products/subscriptions/backend/presentation/views.py+++ b/products/subscriptions/backend/presentation/views.py@@ -1399,6 +1399,8 @@ class SubscriptionDeliveryViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSescope_object = "subscription"serializer_class = SubscriptionDeliverySerializerpagination_class = SubscriptionDeliveryCursorPagination+ # subscription is not an access-control resource, and a delivery has no access rules of its own.+ records_have_object_access_rules = Falsedef get_serializer_context(self) -> dict:context = super().get_serializer_context()@@ -1434,9 +1436,9 @@ class SubscriptionDeliveryViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSe),)- def retrieve(self, request: Request, **kwargs: object) -> Response:+ def read_object(self) -> contracts.SubscriptionDeliveryRecord:try:- delivery = api.get_subscription_delivery(+ return api.get_subscription_delivery(team_id=self.team_id,subscription_id=self.kwargs.get("parent_lookup_subscription_id"),delivery_id=self.kwargs["pk"],@@ -1446,6 +1448,6 @@ class SubscriptionDeliveryViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSeraise Http404except contracts.SubscriptionNotFoundError:raise Http404("No SubscriptionDelivery matches the given query.")- # A delivery has no access rules of its own, so the object checks pass it as they pass the row.- self.check_object_permissions(request, delivery)- return Response(self.get_serializer(delivery).data)++ def retrieve(self, request: Request, **kwargs: object) -> Response:+ return Response(self.get_serializer(self.get_object()).data)