: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
fix(health): hide health issues for resources a member cannot access (#95295)
James Gill0cda5667e65c
diff --git a/posthog/api/health_issue.py b/posthog/api/health_issue.pyindex ba950b28b47c..01cf84217aea 100644--- a/posthog/api/health_issue.py+++ b/posthog/api/health_issue.py@@ -1,6 +1,6 @@import refrom datetime import datetime, timedelta-from typing import Any+from typing import TYPE_CHECKING, Anyfrom zoneinfo import ZoneInfofrom django.db.models import Case, Count, Q, QuerySet, When@@ -18,6 +18,7 @@ from rest_framework import serializersfrom rest_framework.decorators import actionfrom rest_framework.mixins import ListModelMixin, RetrieveModelMixinfrom rest_framework.pagination import LimitOffsetPagination+from rest_framework.permissions import BasePermissionfrom rest_framework.request import Requestfrom rest_framework.response import Responsefrom rest_framework.status import HTTP_202_ACCEPTED, HTTP_400_BAD_REQUEST@@ -26,9 +27,13 @@ from rest_framework.viewsets import GenericViewSetfrom posthog.api.routing import TeamAndOrgViewSetMixinfrom posthog.exceptions_capture import capture_exceptionfrom posthog.models.health_issue import HealthIssue+from posthog.permissions import is_service_authfrom posthog.rate_limit import HealthIssueRefreshThrottlefrom posthog.utils import relative_date_parse+if TYPE_CHECKING:+ from products.access_control.backend.facade.user_access_control import UserAccessControl+@extend_schema_field(OpenApiTypes.OBJECT)class HealthIssuePayloadField(serializers.JSONField):@@ -269,6 +274,39 @@ VALID_STATUSES = {choice.value for choice in HealthIssue.Status}VALID_SEVERITIES = {choice.value for choice in HealthIssue.Severity}+def _kinds_hidden_by_access_control(request: Request, user_access_control: "UserAccessControl") -> set[str]:+ """Check kinds whose declared access-controlled resource this user cannot view."""+ # Lazy import: same reentrancy reason as HealthIssueDetailSerializer._content.+ from posthog.temporal.health_checks.framework import access_controlled_resources_by_kind # noqa: PLC0415++ # Service credentials are gated by API scope + project membership (see+ # AccessControlPermission); UserAccessControl can't evaluate their synthetic users.+ if is_service_auth(request):+ return set()++ return {+ kind+ for kind, resource in access_controlled_resources_by_kind().items()+ if not user_access_control.check_access_level_for_resource(resource, "viewer")+ }+++class HealthIssueResourceAccessPermission(BasePermission):+ """Denies an issue whose check declared an access-controlled resource the user cannot view.++ `health_issue` is not itself an access-controlled resource, but issue payloads+ and rendered titles/summaries embed metadata about resources that are (source+ pipeline names, view names). List and summary hide such kinds in+ `safely_get_queryset`; this covers retrieve and the object actions with the+ same 403 that `AccessControlPermission` returns on the resource's own endpoints.+ """++ message = "You do not have viewer access to this resource."++ def has_object_permission(self, request: Request, view, obj: HealthIssue) -> bool:+ return obj.kind not in _kinds_hidden_by_access_control(request, view.user_access_control)++def _issue_counts(queryset: QuerySet) -> dict[str, Any]:by_severity = {row["severity"]: row["count"] for row in queryset.order_by().values("severity").annotate(count=Count("id"))@@ -328,6 +366,7 @@ class HealthIssueViewSet(TeamAndOrgViewSetMixin, ListModelMixin, RetrieveModelMiqueryset = HealthIssue.objects.all()serializer_class = HealthIssueSerializerpagination_class = HealthIssuePagination+ permission_classes = [HealthIssueResourceAccessPermission]def get_serializer_class(self):if self.action == "retrieve":@@ -373,6 +412,15 @@ class HealthIssueViewSet(TeamAndOrgViewSetMixin, ListModelMixin, RetrieveModelMiif dismissed_filter is not None:queryset = queryset.filter(dismissed=dismissed_filter.lower() == "true")+ # Collection reads only: detail routes keep the issue loadable so+ # HealthIssueResourceAccessPermission can deny them with a 403, mirroring+ # how routing._filter_queryset_by_access_level defers non-list actions+ # to the permission layer.+ if not self.detail:+ hidden_kinds = _kinds_hidden_by_access_control(self.request, self.user_access_control)+ if hidden_kinds:+ queryset = queryset.exclude(kind__in=hidden_kinds)+return queryset@action(methods=["POST"], detail=True)diff --git a/posthog/api/test/test_health_issue.py b/posthog/api/test/test_health_issue.pyindex cf2481863806..9b0138f2e60a 100644--- a/posthog/api/test/test_health_issue.py+++ b/posthog/api/test/test_health_issue.py@@ -11,10 +11,13 @@ from parameterized import parameterizedfrom rest_framework import statusfrom posthog.api.health_issue import HealthIssueSerializer+from posthog.constants import AvailableFeaturefrom posthog.models.health_issue import HealthIssue+from posthog.models.organization import OrganizationMembershipfrom posthog.models.team import Teamfrom posthog.redis import get_client+from products.access_control.backend.models.access_control import AccessControlfrom products.growth.backend.constants import github_sdk_versions_key@@ -424,6 +427,95 @@ class TestHealthIssueAPI(APIBaseTest):self.assertEqual(response.status_code, status.HTTP_405_METHOD_NOT_ALLOWED)+class TestHealthIssueAccessControl(APIBaseTest):+ def _url(self, path: str = "") -> str:+ return f"/api/environments/{self.team.id}/health_issues{path}"++ def _create_issue(self, kind: str, unique_hash: str) -> HealthIssue:+ return HealthIssue.objects.create(+ team=self.team,+ kind=kind,+ severity=HealthIssue.Severity.WARNING,+ payload={"pipeline_name": "salesforce sync", "error": "credentials expired"},+ unique_hash=unique_hash,+ )++ def setUp(self):+ super().setUp()+ self.organization.available_product_features = [+ {"key": AvailableFeature.ACCESS_CONTROL, "name": AvailableFeature.ACCESS_CONTROL}+ ]+ self.organization.save()++ @parameterized.expand(+ [+ ("external_data_failure", "external_data_source"),+ ("materialized_view_failure", "warehouse_objects"),+ ]+ )+ def test_restricted_member_does_not_see_kind_in_list(self, kind, resource):+ self._create_issue(kind=kind, unique_hash="h1")+ self._create_issue(kind="sdk_outdated", unique_hash="h2")+ AccessControl.objects.create(team=self.team, resource=resource, access_level="none")++ response = self.client.get(self._url())+ self.assertEqual(response.status_code, status.HTTP_200_OK)+ self.assertEqual([result["kind"] for result in response.json()["results"]], ["sdk_outdated"])++ def test_restricted_member_summary_excludes_hidden_kind(self):+ self._create_issue(kind="external_data_failure", unique_hash="h1")+ self._create_issue(kind="sdk_outdated", unique_hash="h2")+ AccessControl.objects.create(team=self.team, resource="external_data_source", access_level="none")++ response = self.client.get(self._url("/summary"))+ self.assertEqual(response.status_code, status.HTTP_200_OK)+ self.assertEqual(response.json()["unsnoozed"]["total"], 1)+ self.assertEqual(response.json()["unsnoozed"]["by_kind"], {"sdk_outdated": 1})++ @parameterized.expand(+ [+ ("retrieve", lambda client, url: client.get(url)),+ ("resolve", lambda client, url: client.post(f"{url}/resolve")),+ ("dismiss", lambda client, url: client.patch(url, {"dismissed": True})),+ ("snooze", lambda client, url: client.patch(url, {"snoozed_until": "P7D"})),+ ]+ )+ def test_restricted_member_object_action_returns_403(self, _name, request):+ issue = self._create_issue(kind="external_data_failure", unique_hash="h1")+ AccessControl.objects.create(team=self.team, resource="external_data_source", access_level="none")++ response = request(self.client, self._url(f"/{issue.id}"))+ self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)+ self.assertEqual(response.json()["detail"], "You do not have viewer access to this resource.")++ @parameterized.expand([("system_default", None), ("explicit_viewer", "viewer")])+ def test_member_with_viewer_access_sees_declared_kind(self, _name, access_level):+ issue = self._create_issue(kind="external_data_failure", unique_hash="h1")+ if access_level:+ AccessControl.objects.create(team=self.team, resource="external_data_source", access_level=access_level)++ list_response = self.client.get(self._url())+ self.assertEqual(list_response.status_code, status.HTTP_200_OK)+ self.assertEqual([result["id"] for result in list_response.json()["results"]], [str(issue.id)])++ retrieve_response = self.client.get(self._url(f"/{issue.id}"))+ self.assertEqual(retrieve_response.status_code, status.HTTP_200_OK)+ self.assertEqual(retrieve_response.json()["summary"], "salesforce sync is failing to sync")++ def test_org_admin_sees_hidden_kind_despite_none_default(self):+ issue = self._create_issue(kind="external_data_failure", unique_hash="h1")+ AccessControl.objects.create(team=self.team, resource="external_data_source", access_level="none")+ self.organization_membership.level = OrganizationMembership.Level.ADMIN+ self.organization_membership.save()++ list_response = self.client.get(self._url())+ self.assertEqual(list_response.status_code, status.HTTP_200_OK)+ self.assertEqual([result["id"] for result in list_response.json()["results"]], [str(issue.id)])++ retrieve_response = self.client.get(self._url(f"/{issue.id}"))+ self.assertEqual(retrieve_response.status_code, status.HTTP_200_OK)++class TestSnoozeDurationField(SimpleTestCase):@parameterized.expand([diff --git a/posthog/temporal/health_checks/framework.py b/posthog/temporal/health_checks/framework.pyindex 471ae1f0f0bc..8cff336c092c 100644--- a/posthog/temporal/health_checks/framework.py+++ b/posthog/temporal/health_checks/framework.py@@ -9,6 +9,7 @@ from django.conf import settingsfrom posthog.clickhouse.query_tagging import Productfrom posthog.job_owners import JobOwnersfrom posthog.models.health_issue import HealthIssue+from posthog.scopes import APIScopeObjectfrom posthog.temporal.health_checks.detectors import DEFAULT_EXECUTION_POLICY, HealthExecutionPolicyfrom posthog.temporal.health_checks.models import DEFAULT_ACTIVE_SINCE_DAYS, HealthCheckResultfrom posthog.temporal.health_checks.registry import _DETECT_FNS, HEALTH_CHECKS, ensure_registry_loaded@@ -152,6 +153,7 @@ class HealthCheckRegistration:active_since_days: int | Noneproduct: Product | Noneremediation: Remediation | None+ access_controlled_resource: APIScopeObject | Nonedef __post_init__(self) -> None:# A fraction, not a percent: 50 here would silently skip the rollout filter and hit every team.@@ -184,6 +186,7 @@ def _register_health_check(cls: type[HealthCheck]) -> None:active_since_days=cls.active_since_days,product=cls.product,remediation=cls.remediation,+ access_controlled_resource=cls.access_controlled_resource,)HEALTH_CHECKS[cls.kind] = registration@@ -218,6 +221,19 @@ class HealthCheck:# Be descriptive — each half doubles as a prompt for its audience.remediation: Remediation | None = None+ # The access-controlled resource this check's issue payloads describe (an+ # `ACCESS_CONTROL_RESOURCES` entry, e.g. "external_data_source"). Set it when+ # payloads embed metadata about that resource — names, keys, errors — so the+ # Health API hides the check's issues from members whose access to the+ # resource is restricted. None means every team member sees the issues.+ #+ # Two limits. The gate is resource-level only: an `AccessControl` deny scoped+ # to one object's `resource_id` is not consulted, so a member barred from a+ # single source or view still sees its issues. And only the Health API reads+ # this field: the Signals inbox emitter does not, so a check that also+ # overrides `render_signal` still publishes its payload there.+ access_controlled_resource: APIScopeObject | None = None+def __init_subclass__(cls, **kwargs: object) -> None:super().__init_subclass__(**kwargs)if not hasattr(cls, "name") or not hasattr(cls, "kind"):@@ -283,6 +299,20 @@ def render_alert_for_issue(issue: HealthIssue) -> AlertContent:return check_cls.render_alert(issue)+def access_controlled_resources_by_kind() -> dict[str, APIScopeObject]:+ """Map check kind → the access-controlled resource its payloads describe.++ Only kinds that declare `access_controlled_resource` appear; every other+ kind is visible to all team members.+ """+ ensure_registry_loaded()+ return {+ kind: registration.access_controlled_resource+ for kind, registration in HEALTH_CHECKS.items()+ if registration.access_controlled_resource is not None+ }++def remediation_for_kind(kind: str) -> Remediation | None:"""Return the static, kind-level remediation guide, or None if there isn't one.diff --git a/posthog/temporal/health_checks/tests/test_framework.py b/posthog/temporal/health_checks/tests/test_framework.pyindex 6f17d6644378..3c8e72040fe4 100644--- a/posthog/temporal/health_checks/tests/test_framework.py+++ b/posthog/temporal/health_checks/tests/test_framework.py@@ -3,7 +3,12 @@ from typing import Anyimport pytestfrom posthog.job_owners import JobOwners-from posthog.temporal.health_checks.framework import HealthCheckRegistration+from posthog.temporal.health_checks.framework import HealthCheckRegistration, access_controlled_resources_by_kind++from products.access_control.backend.facade.user_access_control import (+ ACCESS_CONTROL_RESOURCES,+ RESOURCE_INHERITANCE_MAP,+)def _registration(**overrides: Any) -> HealthCheckRegistration:@@ -20,6 +25,7 @@ def _registration(**overrides: Any) -> HealthCheckRegistration:"active_since_days": 90,"product": None,"remediation": None,+ "access_controlled_resource": None,}fields.update(overrides)return HealthCheckRegistration(**fields)@@ -51,3 +57,12 @@ def test_accepts_fractional_values(field: str, value: float) -> None:def test_rejects_out_of_range_fractions(field: str, value: float) -> None:with pytest.raises(ValueError, match=field):_registration(**{field: value})+++def test_declared_access_controlled_resources_have_access_controls() -> None:+ # A resource outside these sets resolves to the "editor" default, which+ # satisfies "viewer" and silently leaves the check's issues visible to+ # every member.+ valid = set(ACCESS_CONTROL_RESOURCES) | set(RESOURCE_INHERITANCE_MAP)+ for kind, resource in access_controlled_resources_by_kind().items():+ assert resource in valid, f"{kind} declares {resource!r}, which has no resource-level access controls"diff --git a/products/data_warehouse/backend/temporal/health_checks/external_data_failure.py b/products/data_warehouse/backend/temporal/health_checks/external_data_failure.pyindex 5447b6c3a12e..25af7b877795 100644--- a/products/data_warehouse/backend/temporal/health_checks/external_data_failure.py+++ b/products/data_warehouse/backend/temporal/health_checks/external_data_failure.py@@ -46,6 +46,8 @@ class ExternalDataFailureCheck(HealthCheck):policy = DEFAULT_EXECUTION_POLICYschedule = "15 7 * * *"active_since_days = 30+ # Payloads carry source pipeline names and errors.+ access_controlled_resource = "external_data_source"remediation = Remediation(human="""Open the Pipeline status page (Data pipeline / Data warehouse → Sources). Find the failingdiff --git a/products/data_warehouse/backend/temporal/health_checks/materialized_view_failure.py b/products/data_warehouse/backend/temporal/health_checks/materialized_view_failure.pyindex ef823944db47..dcc78001e79d 100644--- a/products/data_warehouse/backend/temporal/health_checks/materialized_view_failure.py+++ b/products/data_warehouse/backend/temporal/health_checks/materialized_view_failure.py@@ -23,6 +23,8 @@ class MaterializedViewFailureCheck(HealthCheck):policy = DEFAULT_EXECUTION_POLICYschedule = "30 7 * * *"active_since_days = 30+ # Payloads carry materialized view names and errors.+ access_controlled_resource = "warehouse_objects"remediation = Remediation(human="""Open Data modeling (the Data warehouse / data modeling section). Find the failing view, open