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.

chore(error-tracking): route product lookups through facades (#105818)

posthog[bot]e06f91dafa34
diff --git a/products/access_control/backend/facade/api.py b/products/access_control/backend/facade/api.py
index 03b7b8491b82..ee4827c1b077 100644
--- a/products/access_control/backend/facade/api.py
+++ b/products/access_control/backend/facade/api.py
@@ -30,7 +30,7 @@ from posthog.models import Organization, OrganizationMembership, PropertyDefinit
from posthog.models.user import User
from posthog.scopes import API_SCOPE_OBJECTS, INTERNAL_API_SCOPE_OBJECTS, APIScopeObject
-from products.access_control.backend.models.role import Role
+from products.access_control.backend.models.role import Role, RoleMembership
from ..models.access_control import AccessControl
from ..models.property_access_control import PropertyAccessControl
@@ -290,6 +290,26 @@ def object_ids_restricted_from_any_member(
return {resource_id for resource_id in restricted if resource_id}
+def role_belongs_to_organization(*, role_id: str | UUID, organization_id: UUID) -> bool:
+ """Whether the role is a role of that organization.
+
+ For a caller that accepts a role id from a request and must not let it name a role of
+ another organization.
+ """
+ return Role.objects.filter(id=role_id, organization_id=organization_id).exists()
+
+
+def valid_role_member_user_ids(*, role_id: str | UUID) -> list[int]:
+ """Ids of the users the role grants access to.
+
+ A membership whose organization member moved to another organization no longer grants
+ anything, so it is left out.
+ """
+ return list(
+ RoleMembership.objects.filter(role_id=role_id).valid_for_authorization().values_list("user_id", flat=True)
+ )
+
+
# --- Write API ---
diff --git a/products/access_control/backend/tests/test_api.py b/products/access_control/backend/tests/test_api.py
index 8703af27f645..be4a69d5ce3e 100644
--- a/products/access_control/backend/tests/test_api.py
+++ b/products/access_control/backend/tests/test_api.py
@@ -12,7 +12,9 @@ from products.access_control.backend.facade.api import (
InvalidObjectAccessControlError,
every_member_has_resource_access,
object_ids_restricted_from_any_member,
+ role_belongs_to_organization,
set_object_access_control,
+ valid_role_member_user_ids,
)
from products.access_control.backend.facade.user_access_control import UserAccessControl
from products.access_control.backend.models.access_control import AccessControl
@@ -226,3 +228,24 @@ class TestObjectIdsRestrictedFromAnyMember(BaseTest):
self.organization.available_product_features = []
self.organization.save()
assert self._restricted() == set()
+
+
+class TestRoleReads(BaseTest):
+ def setUp(self) -> None:
+ super().setUp()
+ self.role = Role.objects.create(name="Support", organization=self.organization)
+ self.other_organization = Organization.objects.create(name="Other")
+
+ def test_role_belongs_only_to_its_own_organization(self) -> None:
+ assert role_belongs_to_organization(role_id=self.role.id, organization_id=self.organization.id)
+ assert not role_belongs_to_organization(role_id=self.role.id, organization_id=self.other_organization.id)
+
+ def test_member_ids_leave_out_a_membership_from_another_organization(self) -> None:
+ self.role.members.add(self.user)
+ assert valid_role_member_user_ids(role_id=self.role.id) == [self.user.id]
+
+ outsider = User.objects.create_and_join(self.other_organization, "[email protected]", "testtest")
+ outside_membership = OrganizationMembership.objects.get(user=outsider, organization=self.other_organization)
+ RoleMembership.objects.create(role=self.role, user=outsider, organization_member=outside_membership)
+
+ assert valid_role_member_user_ids(role_id=self.role.id) == [self.user.id]
diff --git a/products/cohorts/backend/facade/__init__.py b/products/cohorts/backend/facade/__init__.py
new file mode 100644
index 000000000000..e69de29bb2d1
diff --git a/products/cohorts/backend/facade/api.py b/products/cohorts/backend/facade/api.py
new file mode 100644
index 000000000000..4df48091761e
--- /dev/null
+++ b/products/cohorts/backend/facade/api.py
@@ -0,0 +1,18 @@
+"""
+Facade API for cohorts.
+
+This is the module that other apps should import from. It accepts plain inputs and
+returns contract DTOs or primitives, never ORM instances or QuerySets.
+"""
+
+from __future__ import annotations
+
+from products.cohorts.backend.models.cohort import Cohort
+
+
+def cohort_exists_for_team(*, team_id: int, cohort_id: int) -> bool:
+ """Whether the team owns that cohort.
+
+ A soft-deleted cohort still counts, so a caller that holds a reference to one keeps it.
+ """
+ return Cohort.objects.filter(team_id=team_id, id=cohort_id).exists()
diff --git a/products/cohorts/backend/test/test_facade_api.py b/products/cohorts/backend/test/test_facade_api.py
new file mode 100644
index 000000000000..b8c3faf76fe8
--- /dev/null
+++ b/products/cohorts/backend/test/test_facade_api.py
@@ -0,0 +1,20 @@
+from posthog.test.base import BaseTest
+
+from posthog.models.team import Team
+
+from products.cohorts.backend.facade.api import cohort_exists_for_team
+from products.cohorts.backend.models.cohort import Cohort
+
+
+class TestCohortExistsForTeam(BaseTest):
+ def test_a_cohort_is_only_visible_to_its_own_team(self) -> None:
+ cohort = Cohort.objects.create(team=self.team, name="Churn risk")
+ other_team = Team.objects.create(organization=self.organization, name="Other")
+
+ assert cohort_exists_for_team(team_id=self.team.id, cohort_id=cohort.id)
+ assert not cohort_exists_for_team(team_id=other_team.id, cohort_id=cohort.id)
+
+ def test_a_soft_deleted_cohort_still_counts(self) -> None:
+ cohort = Cohort.objects.create(team=self.team, name="Churn risk", deleted=True)
+
+ assert cohort_exists_for_team(team_id=self.team.id, cohort_id=cohort.id)
diff --git a/products/error_tracking/backend/facade/api.py b/products/error_tracking/backend/facade/api.py
index 90c67656d3c6..9d0c512afc84 100644
--- a/products/error_tracking/backend/facade/api.py
+++ b/products/error_tracking/backend/facade/api.py
@@ -13,7 +13,7 @@ import posthoganalytics
from posthog.event_usage import groups
-from products.access_control.backend.models.role import RoleMembership
+from products.access_control.backend.facade.api import valid_role_member_user_ids
from .. import logic, weekly_digest, weekly_digest_delivery
from ..indexed_embedding import EMBEDDING_TABLES
@@ -112,11 +112,7 @@ def _to_issue(issue) -> contracts.ErrorTrackingIssue:
def _to_issue_assignment_notification(assignment) -> contracts.ErrorTrackingIssueAssignmentNotification:
role_member_user_ids: list[int] = []
if assignment.role_id:
- role_member_user_ids = list(
- RoleMembership.objects.filter(role=assignment.role)
- .valid_for_authorization()
- .values_list("user_id", flat=True)
- )
+ role_member_user_ids = valid_role_member_user_ids(role_id=assignment.role_id)
issue = assignment.issue
return contracts.ErrorTrackingIssueAssignmentNotification(
diff --git a/products/error_tracking/backend/logic/issue_mutations.py b/products/error_tracking/backend/logic/issue_mutations.py
index 4597b202bc5b..2446a3230f82 100644
--- a/products/error_tracking/backend/logic/issue_mutations.py
+++ b/products/error_tracking/backend/logic/issue_mutations.py
@@ -16,8 +16,8 @@ from posthog.models.organization import OrganizationMembership
from posthog.models.user import User
from posthog.tasks.email import send_error_tracking_issue_assigned
-from products.access_control.backend.models.role import Role
-from products.cohorts.backend.models.cohort import Cohort
+from products.access_control.backend.facade.api import role_belongs_to_organization
+from products.cohorts.backend.facade.api import cohort_exists_for_team
from products.error_tracking.backend.logic import ErrorTrackingIssueNotFoundError, get_issue
from products.error_tracking.backend.logic.lifecycle_events import (
ISSUE_ASSIGNED_EVENT,
@@ -246,12 +246,11 @@ def split_issue(
def set_issue_cohort(team_id: int, issue_id: UUID, cohort_id: int) -> None:
issue = _get_issue(team_id, issue_id)
- cohort = Cohort.objects.filter(team_id=team_id, id=cohort_id).first()
- if cohort is None:
+ if not cohort_exists_for_team(team_id=team_id, cohort_id=cohort_id):
raise CohortNotFoundError
# Upsert cohort_id as a cohort might have been soft deleted.
# nosemgrep: idor-lookup-without-team (cohort scoped to team before use)
- ErrorTrackingIssueCohort.objects.update_or_create(issue=issue, defaults={"cohort_id": cohort.id})
+ ErrorTrackingIssueCohort.objects.update_or_create(issue=issue, defaults={"cohort_id": cohort_id})
def assign_issue(
@@ -373,7 +372,7 @@ def _assign_one(
if not OrganizationMembership.objects.filter(user_id=assignee["id"], organization=organization).exists():
raise AssigneeValidationError("Assignee user does not belong to this organization.")
elif assignee["type"] == "role":
- if not Role.objects.filter(id=assignee["id"], organization=organization).exists():
+ if not role_belongs_to_organization(role_id=assignee["id"], organization_id=organization.id):
raise AssigneeValidationError("Assignee role does not belong to this organization.")
serialized_assignment_after = {
diff --git a/products/error_tracking/backend/logic/recommendations/alerts.py b/products/error_tracking/backend/logic/recommendations/alerts.py
index 23a6a9a39d48..8bd4d81c3f7d 100644
--- a/products/error_tracking/backend/logic/recommendations/alerts.py
+++ b/products/error_tracking/backend/logic/recommendations/alerts.py
@@ -5,7 +5,7 @@ from typing import Any
from django.db.models import Q
-from products.cdp.backend.models.hog_functions.hog_function import HogFunction, HogFunctionType
+from products.cdp.backend.facade.models import HogFunction, HogFunctionType
from .base import Recommendation