: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(data-quality): gate notification recipients on the subjects the check reads (#101253)
Thiago Salvatore436d4491deb0
diff --git a/posthog/hogql/database/database.py b/posthog/hogql/database/database.pyindex 67fd872379d7..ba7aa41d11ee 100644--- a/posthog/hogql/database/database.py+++ b/posthog/hogql/database/database.py@@ -673,11 +673,21 @@ def _unentitled_system_tables(team: Team) -> set[str]:return {name for name, feature in required_features.items() if not organization.is_feature_available(feature)}+def unentitled_system_tables(team: Team) -> frozenset[str]:+ """The system tables this team's organization is not entitled to.++ Organization-wide, so a caller deciding for many principals reads it once and hands it to+ :func:`system_table_denials` for each of them.+ """+ return frozenset(_unentitled_system_tables(team))++def _compute_system_table_access_decision(team: Team,user: Optional[User | SyntheticUser | SharedLinkUser],user_access_control: Optional[UserAccessControl] = None,allowed_system_tables: Collection[str] | None = None,+ unentitled: Collection[str] | None = None,) -> tuple[Optional[UserAccessControl], set[str]]:"""Decide which scoped system tables to hide, doing the access-control I/O here so the build phasecan apply the result without querying. Returns the warmed UserAccessControl (preloaded, so later@@ -706,7 +716,7 @@ def _compute_system_table_access_decision(# Applies to every principal below, admins included - an entitlement the organization does not# have cannot be granted by a role.- unentitled = _unentitled_system_tables(team)+ unentitled = set(unentitled) if unentitled is not None else _unentitled_system_tables(team)# Anonymous or synthetic principal: keep only access-controlled tables its scopes cover (none for shared link / team token).if user is None or isinstance(user, SyntheticUser | SharedLinkUser):@@ -745,14 +755,20 @@ def _compute_system_table_access_decision(def system_table_denials(- team: Team, user: User, user_access_control: Optional[UserAccessControl] = None+ team: Team,+ user: User,+ user_access_control: Optional[UserAccessControl] = None,+ *,+ unentitled: Collection[str] | None = None,) -> frozenset[str]:"""The bare names of the ``system.*`` tables this user may not read.Runs the access-control and entitlement checks that ``create_for`` would run, and nothing else,- so a caller that only needs the answer does not pay for a whole database build.+ so a caller that only needs the answer does not pay for a whole database build. Pass+ ``unentitled`` from :func:`unentitled_system_tables` to read the organization's entitlements once+ across many users."""- return frozenset(_compute_system_table_access_decision(team, user, user_access_control)[1])+ return frozenset(_compute_system_table_access_decision(team, user, user_access_control, unentitled=unentitled)[1])class Database(BaseModel):diff --git a/products/data_modeling/backend/logic/saved_query_reads.py b/products/data_modeling/backend/logic/saved_query_reads.pyindex 30e098bfc996..ff48482ee20e 100644--- a/products/data_modeling/backend/logic/saved_query_reads.py+++ b/products/data_modeling/backend/logic/saved_query_reads.py@@ -110,17 +110,25 @@ def _resolve_allowed_saved_query_ids()-def backing_table_ids_by_saved_query(team_id: int) -> dict[UUID, UUID]:+def backing_table_ids_by_saved_query(team_id: int, *, table_ids: Collection[UUID] | None = None) -> dict[UUID, UUID]:"""Private backing table ids mapped to their saved query ids. One query.Includes soft-deleted saved queries because deleting a view leaves its backing table behind.The URL predicate deliberately matches the HogQL catalog's private-backing-table exclusion.++ ``table_ids`` narrows the lookup to the tables a caller asked about, so a caller holding a+ handful of tables does not load the team's whole view list. ``None`` asks about every table; an+ empty collection asks about none."""+ if table_ids is not None and not table_ids:+ return {}saved_queries = (DataWarehouseSavedQuery.objects.filter(team_id=team_id, table__isnull=False).select_related("table").only("id", "team_id", "table_id", "table__url_pattern"))+ if table_ids is not None:+ saved_queries = saved_queries.filter(table_id__in=table_ids)return {saved_query.table_id: saved_query.idfor saved_query in saved_queriesdiff --git a/products/data_quality/backend/logic/notifications.py b/products/data_quality/backend/logic/notifications.pyindex 5b051ce5a906..5bf3b12e302d 100644--- a/products/data_quality/backend/logic/notifications.py+++ b/products/data_quality/backend/logic/notifications.py@@ -10,6 +10,8 @@ from uuid import UUIDimport structlog+from posthog.hogql.database.database import unentitled_system_tables+from posthog.models import Team, Userfrom products.access_control.backend.facade.user_access_control import UserAccessControl@@ -29,15 +31,13 @@ from ..models import DataQualityCheck, DataQualityCheckRun, DataQualitySuiteRunfrom .checks import checks_for_subjectfrom .flags import is_data_quality_checks_enabled_for_team_idfrom .subject_access import (- DenialContextKey,+ NoticeReferences,ReferenceGate,- SubjectMetadata,- caller_denial_context,can_be_object_denied,- denial_context_key,+ notice_references,+ reference_gate,referenced_subject_names,referencing_check_types,- subject_metadata,)from .subjects import resolve_subject@@ -83,8 +83,8 @@ class _WarehouseSubjectResolver(RecipientsResolver):# database build the referenced-subject gate runs) so a single failing check doesn't rebuild# it -- and its membership, role, and access-control lookups -- once per pass.self._access: dict[int, UserAccessControl] = access_cache if access_cache is not None else {}- self._gates: dict[DenialContextKey, ReferenceGate] = {}- self._subject_metadata: SubjectMetadata | None = None+ self._references: NoticeReferences | None = None+ self._unentitled: frozenset[str] | None = Nonedef _access_of(self, user: User) -> UserAccessControl:access = self._access.get(user.id)@@ -101,18 +101,11 @@ class _WarehouseSubjectResolver(RecipientsResolver):def resolve(self, target_type: TargetType, target_id: str, team_id: int | None) -> list[int]:user_ids = super().resolve(target_type, target_id, team_id)- user_ids = self.filter_by_access_control(user_ids, "query", self._team)- if self._subject_type == SubjectType.METRIC:- user_ids = self.filter_by_access_control(user_ids, "data_catalog", self._team)return self._filter_by_subject_access(user_ids)def _filter_by_subject_access(self, user_ids: list[int]) -> list[int]:# Both gates below are per-member, so they share one member query, one access-control object# and one denial snapshot each rather than a pass apiece.- if not self._object_gate_applies() and not self._reference_gate_applies():- return user_ids-- # No warehouse access control means no denials, so skip the per-member work entirely.if not self._access_controls_supported(user_ids):return user_ids@@ -128,13 +121,19 @@ class _WarehouseSubjectResolver(RecipientsResolver):def _may_receive(self, user: User) -> bool:access = self._access_of(user)+ if not access.check_access_level_for_resource("query", "viewer"):+ return False+ if self._subject_type == SubjectType.METRIC and not access.check_access_level_for_resource(+ "data_catalog", "viewer"+ ):+ return Falseif self._object_gate_applies() and not self._has_object_access(access):return Falseif not self._reference_gate_applies():return Trueif self._references_unknown and can_be_object_denied(access):return False- return self._gate_of(user).admits(self._executed_references, self._referenced_names)+ return self._gate_of(user).admits(self._notice_references())def _has_object_access(self, access: UserAccessControl) -> bool:object_id = UUID(self._subject_uuid)@@ -145,17 +144,23 @@ class _WarehouseSubjectResolver(RecipientsResolver):)return object_id in allowed_ids+ def _notice_references(self) -> NoticeReferences:+ if self._references is None:+ self._references = notice_references(+ self._team.id, executed_references=self._executed_references, names=self._referenced_names+ )+ return self._references+def _gate_of(self, user: User) -> ReferenceGate:- access = self._access_of(user)- key = denial_context_key(self._team, user, access)- gate = self._gates.get(key)- if gate is None:- if self._subject_metadata is None:- self._subject_metadata = subject_metadata(self._team.id)- context = caller_denial_context(self._team, user, access, metadata=self._subject_metadata)- gate = ReferenceGate(readable=context.readable, matcher=context.matcher)- self._gates[key] = gate- return gate+ if self._unentitled is None:+ self._unentitled = unentitled_system_tables(self._team)+ return reference_gate(+ self._team,+ user,+ self._access_of(user),+ references=self._notice_references(),+ unentitled=self._unentitled,+ )def notify_check_started_failing(diff --git a/products/data_quality/backend/logic/subject_access.py b/products/data_quality/backend/logic/subject_access.pyindex fb02d5b55180..19e81d32dea0 100644--- a/products/data_quality/backend/logic/subject_access.py+++ b/products/data_quality/backend/logic/subject_access.py@@ -12,8 +12,9 @@ know is absent from that snapshot and therefore out of reach."""import json-from collections.abc import Sequence+from collections.abc import Collection, Sequencefrom dataclasses import field+from functools import cachefrom itertools import batchedfrom typing import TYPE_CHECKING, Any, Optional, TypeVarfrom uuid import UUID@@ -22,6 +23,7 @@ from django.db.models import Exists, OuterRef, Q, QuerySetfrom posthog.hogql.database.database import Database, system_table_denialsfrom posthog.hogql.database.schema.information_schema import DeniedTableMatcher+from posthog.hogql.database.schema.system import SystemTablesfrom posthog.dataclasses import frozenfrom posthog.exceptions_capture import capture_exception@@ -46,6 +48,7 @@ if TYPE_CHECKING:_SUBJECT_TYPE_KEY = "subject_type"_SUBJECT_UUID_KEY = "subject_uuid"+_SYSTEM_SCHEMA = SystemTables().name_RunQS = TypeVar("_RunQS", bound=QuerySet)_CHECK_VISIBILITY_BATCH_SIZE = 200_CHECK_VISIBILITY_FIELDS = ("id", "subject_type", "table_id", "saved_query_id", "metric_id", "check_type", "config")@@ -116,59 +119,85 @@ class DenialContext:@frozen-class ReferenceGate:- """Decides whether one person may be told a check failed.-- A check can read tables other than the one it is defined on: a ``custom_sql`` check reads- whatever its query selects, and a ``relationships`` check reads the table it points at. The- failure count in the notification therefore says something about every one of those tables, so- a person who may not read one of them must not get the notification.+class NoticeReferences:+ """The subjects one notification's failure count says something about, besides its own subject.- Holds the two things that answer this: the tables, views and metrics the person may read, and- a matcher for the table names they are denied.+ A ``custom_sql`` check reads whatever its query selects and a ``relationships`` check reads the+ table it points at, so the count is an oracle over those too. Resolved once per notice and held+ up against every recipient, because resolving a name to the object it reaches costs the same+ queries whoever is asking.- Both come from the person's :class:`DenialContextKey` and from nothing else, so one gate can- serve every person whose key is equal. The :class:`DenialContext` it is built from cannot be- shared that way, because that also holds the HogQL database built for one specific person.+ ``identities`` are the subjects that resolve to a warehouse object, either pinned by the run or+ resolved from the definition's names. ``unresolved_names`` are the rest: ``system.*`` tables,+ PostHog tables, and names that no longer reach anything."""- readable: ReadableSubjects- matcher: DeniedTableMatcher = field(compare=False)+ identities: tuple[SubjectIdentity, ...]+ unresolved_names: tuple[str, ...]- def admits(self, executed_references: Sequence[dict[str, str]], names: Sequence[str]) -> bool:- readable_references = all(- self.readable.contains(ref[_SUBJECT_TYPE_KEY], ref[_SUBJECT_UUID_KEY]) for ref in executed_references- )- if not readable_references:- return False- return not self.matcher.matches(names)+def notice_references(+ team_id: int, *, executed_references: Sequence[dict[str, str]] = (), names: Sequence[str] = ()+) -> NoticeReferences:+ """Resolve what a notice reads into identities, keeping the names that reach no object."""+ pinned = _pin_names(team_id, names)+ identities = [+ SubjectIdentity(subject_type=ref[_SUBJECT_TYPE_KEY], subject_uuid=ref[_SUBJECT_UUID_KEY])+ for ref in executed_references+ ]+ identities.extend(pinned.values())+ return NoticeReferences(+ identities=tuple(identities),+ unresolved_names=tuple(name for name in names if name not in pinned),+ )-@frozen-class DenialContextKey:- """What one person is allowed to read, reduced to something a cache can key on.- Working out which table names a person is denied is expensive, because it builds a HogQL- database for them. These four values are the only things about the person that the answer- depends on, so two people on the same team with equal keys are denied exactly the same names.+@frozen+class ReferenceGate:+ """Decides whether one person may be told a check failed.- A surface that has to check hundreds of people can therefore resolve one :class:`DenialContext`- per distinct key instead of one per person.+ Holds the two things that answer this over a :class:`NoticeReferences`: the subjects among those+ the person may read, and a matcher for the names they are denied."""- allowed_table_ids: frozenset[UUID]- allowed_view_ids: frozenset[UUID]- can_read_catalog: bool- denied_system_tables: frozenset[str]+ readable: ReadableSubjects+ matcher: DeniedTableMatcher = field(compare=False)++ def admits(self, references: NoticeReferences) -> bool:+ if not all(self.readable.contains(ref.subject_type, ref.subject_uuid) for ref in references.identities):+ return False+ return not self.matcher.matches(references.unresolved_names)-def denial_context_key(team: "Team", user: "User", user_access_control: "UserAccessControl") -> DenialContextKey:- """Reads the key for one person. Runs a few Postgres queries and builds no HogQL database."""- return DenialContextKey(- allowed_table_ids=warehouse_facade.allowed_table_ids(team.id, user_access_control),- allowed_view_ids=data_modeling_facade.allowed_saved_query_ids(team.id, user_access_control),- can_read_catalog=user_access_control.check_access_level_for_resource("data_catalog", "viewer"),- denied_system_tables=system_table_denials(team, user, user_access_control),+def reference_gate(+ team: "Team",+ user: "User",+ user_access_control: "UserAccessControl",+ *,+ references: NoticeReferences,+ unentitled: Collection[str] | None = None,+) -> ReferenceGate:+ """One person's access to the subjects a single check reads. A few narrow queries, no build.++ Cost tracks what the check reads, not what the team owns, so a project with thousands of+ warehouse tables costs the same as one with three.+ """+ referenced: dict[str, set[UUID]] = {SubjectType.TABLE: set(), SubjectType.VIEW: set()}+ for reference in references.identities:+ # A run pins its references into an unrestricted JSON column, so one that does not parse is+ # left out of the lookup and fails closed in ``ReadableSubjects.contains``.+ if reference.subject_type in referenced and (identifier := _as_uuid(reference.subject_uuid)) is not None:+ referenced[reference.subject_type].add(identifier)+ return ReferenceGate(+ readable=ReadableSubjects(+ table_ids=warehouse_facade.allowed_table_ids(+ team.id, user_access_control, ids=referenced[SubjectType.TABLE]+ ),+ view_ids=data_modeling_facade.allowed_saved_query_ids(+ team.id, user_access_control, ids=referenced[SubjectType.VIEW]+ ),+ ),+ matcher=DeniedTableMatcher(system_table_denials(team, user, user_access_control, unentitled=unentitled)),)@@ -525,10 +554,7 @@ def pin_referenced_subjects(references = referenced_subjects(team_id, check_type, config, subject=subject)if not references.names and references.related_subject is None:return []- backing_tables = data_modeling_facade.backing_table_ids_by_saved_query(team_id)- pinned = [- identity for name in references.names if (identity := _pin_name(team_id, name, backing_tables)) is not None- ]+ pinned = list(_pin_names(team_id, references.names).values())if references.related_subject is not None:pinned.append(references.related_subject)except Exception as err:@@ -589,10 +615,47 @@ def memoized_definition_verdict(return verdicts[key]-def _pin_name(team_id: int, name: str, backing_tables: dict[UUID, UUID]) -> SubjectIdentity | None:- ref = resolve_subject_by_name(team_id, name)- if ref is None:+def _as_uuid(value: str) -> UUID | None:+ try:+ return UUID(value)+ except ValueError:return None+++def _pin_names(team_id: int, names: Sequence[str]) -> dict[str, SubjectIdentity]:+ resolved = {name: ref for name in names if (ref := _resolve_pinnable(team_id, name)) is not None}+ backing_tables = _backing_tables_of(team_id, resolved.values())+ return {name: _pin_identity(ref, backing_tables) for name, ref in resolved.items()}+++def _resolve_pinnable(team_id: int, name: str) -> SubjectRef | None:+ """The warehouse object this name reaches, or None when the name carries its own denial instead.++ A ``system.*`` table is never pinned. Resolution rewrites a dotted name to an underscored one,+ so ``system.annotations`` would otherwise reach a warehouse table a member happened to call+ ``system_annotations``, and the member's denial of the system table would go unread.+ """+ if _is_system_table_name(name):+ return None+ return resolve_subject_by_name(team_id, name)+++def _backing_tables_of(team_id: int, refs: Collection[SubjectRef]) -> dict[UUID, UUID]:+ table_ids = {UUID(ref.subject_uuid) for ref in refs if ref.subject_type == SubjectType.TABLE}+ return data_modeling_facade.backing_table_ids_by_saved_query(team_id, table_ids=table_ids)+++def _pin_identity(ref: SubjectRef, backing_tables: dict[UUID, UUID]) -> SubjectIdentity:if ref.subject_type == SubjectType.TABLE and (saved_query_id := backing_tables.get(UUID(ref.subject_uuid))):return SubjectIdentity(subject_type=str(SubjectType.VIEW), subject_uuid=str(saved_query_id))return SubjectIdentity(subject_type=str(ref.subject_type), subject_uuid=ref.subject_uuid)+++def _is_system_table_name(name: str) -> bool:+ schema, separator, leaf = name.partition(".")+ return bool(separator) and schema.lower() == _SYSTEM_SCHEMA and leaf in _system_table_names()+++@cache+def _system_table_names() -> frozenset[str]:+ return frozenset(SystemTables().children)diff --git a/products/data_quality/backend/tests/test_notifications.py b/products/data_quality/backend/tests/test_notifications.pyindex 5ae934cda27b..18eaa6c1300a 100644--- a/products/data_quality/backend/tests/test_notifications.py+++ b/products/data_quality/backend/tests/test_notifications.py@@ -271,29 +271,15 @@ class TestDataQualityNotifications(BaseTest):assert create_notification.call_args.args[0].resource_type == "warehouse_objects"- @patch("products.notifications.backend.resolvers.UserAccessControl")- def test_members_without_query_access_do_not_get_the_failing_row_count(self, mock_uac_cls) -> None:+ @parameterized.expand([("view_subject", SubjectType.VIEW), ("metric_subject", SubjectType.METRIC)])+ def test_members_without_query_access_do_not_get_the_failing_row_count(self, _name, subject_type: str) -> None:# The body's failing-row count is a count oracle over warehouse rows the run-history API gates# behind query access, so a member with warehouse access but no query access must be dropped.- self.organization.available_product_features = [{"key": AvailableFeature.ACCESS_CONTROL}]- self.organization.save()+ self._enable_access_controls()denied = User.objects.create_and_join(self.organization, "[email protected]", "password")+ self._deny_resource("query", denied)+ check = self._check(**self._metric_subject() if subject_type == SubjectType.METRIC else {})- class FakeUAC:- def __init__(self, user, team) -> None:- self._user_id = user.id-- @property- def access_controls_supported(self) -> bool:- return True-- def check_access_level_for_resource(self, resource, level) -> bool:- # Everyone can see warehouse objects; only the denied user lacks query access.- return resource != "query" or self._user_id != denied.id-- mock_uac_cls.side_effect = FakeUAC-- check = self._check()resolved = self._resolver_for(check).resolve(TargetType.TEAM, str(self.team.id), self.team.id)assert self.user.id in resolved@@ -419,52 +405,169 @@ class TestDataQualityNotifications(BaseTest):assert self.user.id in resolvedassert blocked.id not in resolved- def _custom_sql_check_reading_orders(self) -> DataQualityCheck:+ def _deny_resource(self, resource: str, member: User, resource_id: str | None = None) -> None:+ AccessControl.objects.create(+ team=self.team,+ resource=resource,+ resource_id=resource_id,+ organization_member=OrganizationMembership.objects.get(organization=self.organization, user=member),+ access_level="none",+ )+ cache.clear()++ def _metric_subject(self) -> dict:+ metric = Metric.objects.for_team(self.team.id).create(+ team=self.team, name="signups", definition={"kind": "HogQLQuery", "query": "SELECT 1 AS id"}+ )+ return {+ "subject_type": SubjectType.METRIC,+ "saved_query_id": None,+ "metric_id": metric.id,+ "subject_name": "signups",+ "check_type": CheckType.ROW_COUNT,+ "column_name": "",+ "config": {"min": 1},+ }++ def _check_reading(self, denied_kind: str, blocked: User) -> DataQualityCheck:customers = DataWarehouseSavedQuery.objects.create(team=self.team, name="customers", query={"kind": "HogQLQuery", "query": "SELECT 1 AS id"})+ if denied_kind == "stripe_table":+ source = ExternalDataSource.objects.create(team=self.team, source_type="Stripe")+ charges = DataWarehouseTable.objects.create(+ team=self.team,+ name="stripe_charges",+ format=DataWarehouseTable.TableFormat.Parquet,+ url_pattern="s3://bucket/charges",+ external_data_source=source,+ )+ self._deny_resource("warehouse_table", blocked, str(charges.id))+ reads = "stripe.charges"+ elif denied_kind == "backing_table":+ matview = DataWarehouseSavedQuery.objects.create(+ team=self.team, name="daily_orders", query={"kind": "HogQLQuery", "query": "SELECT 1 AS id"}+ )+ backing_table = DataWarehouseTable.objects.create(+ team=self.team,+ name=matview.name,+ format=DataWarehouseTable.TableFormat.Parquet,+ url_pattern=f"s3://bucket/{matview.folder_path}/{matview.normalized_name}",+ )+ matview.table = backing_table+ matview.is_materialized = True+ matview.save(update_fields=["table", "is_materialized"])+ self._deny_resource("warehouse_view", blocked, str(matview.id))+ reads = backing_table.name+ elif denied_kind == "direct_table_shadowing_a_view":+ DataWarehouseTable.objects.create(+ team=self.team,+ name=self.view.name,+ format=DataWarehouseTable.TableFormat.Parquet,+ url_pattern="s3://bucket/orders",+ external_data_source=ExternalDataSource.objects.create(+ team=self.team, source_type="Postgres", access_method=ExternalDataSource.AccessMethod.DIRECT+ ),+ )+ self._deny_resource("warehouse_view", blocked, str(self.view.id))+ reads = self.view.name+ else:+ if denied_kind == "warehouse_table_shadowing_a_system_table":+ DataWarehouseTable.objects.create(+ team=self.team,+ name="system_annotations",+ format=DataWarehouseTable.TableFormat.Parquet,+ url_pattern="s3://bucket/system_annotations",+ )+ self._deny_resource("annotation", blocked)+ reads = "system.annotations"return self._check(saved_query_id=customers.id,subject_name="customers",check_type=CheckType.CUSTOM_SQL,column_name="",- config={"query": "SELECT 1 FROM orders"},+ config={"query": f"SELECT 1 FROM {reads}"},)- def test_members_with_equal_access_share_one_warehouse_database_build(self) -> None:- denied_first = User.objects.create_and_join(self.organization, "[email protected]", "password")- denied_second = User.objects.create_and_join(self.organization, "[email protected]", "password")- allowed_first = User.objects.create_and_join(self.organization, "[email protected]", "password")- allowed_second = User.objects.create_and_join(self.organization, "[email protected]", "password")- self._deny_view_for_member(self.view, denied_first)- self._deny_view_for_member(self.view, denied_second)+ def test_a_reference_that_does_not_parse_withholds_the_notification(self) -> None:+ # referenced_subjects is an unrestricted JSON column, so a run can pin an entry that is not a+ # uuid. That must drop the recipient, never abort the notice for everyone.+ self._enable_access_controls()+ member = User.objects.create_and_join(self.organization, "[email protected]", "password")check = self._custom_sql_check_reading_orders()+ resolver = _WarehouseSubjectResolver(+ self.team,+ check.subject_type,+ str(check.subject_uuid),+ executed_references=[{"subject_type": str(SubjectType.VIEW), "subject_uuid": "not-a-uuid"}],+ )- with patch.object(Database, "create_for", side_effect=Database.create_for) as build:- resolved = self._resolver_for(check).resolve(TargetType.TEAM, str(self.team.id), self.team.id)+ resolved = resolver.resolve(TargetType.TEAM, str(self.team.id), self.team.id)- assert build.call_count == 2- assert {allowed_first.id, allowed_second.id, self.user.id} <= set(resolved)- assert denied_first.id not in resolved- assert denied_second.id not in resolved+ assert member.id not in resolved+ assert self.user.id not in resolved- def test_org_admins_share_one_warehouse_database_build(self) -> None:- first_admin = User.objects.create_and_join(- self.organization, "[email protected]", "password", level=OrganizationMembership.Level.ADMIN+ def _custom_sql_check_reading_orders(self) -> DataQualityCheck:+ customers = DataWarehouseSavedQuery.objects.create(+ team=self.team, name="customers", query={"kind": "HogQLQuery", "query": "SELECT 1 AS id"})- second_admin = User.objects.create_and_join(- self.organization, "[email protected]", "password", level=OrganizationMembership.Level.ADMIN+ return self._check(+ saved_query_id=customers.id,+ subject_name="customers",+ check_type=CheckType.CUSTOM_SQL,+ column_name="",+ config={"query": "SELECT 1 FROM orders"},)- self.organization_membership.level = OrganizationMembership.Level.ADMIN- self.organization_membership.save(update_fields=["level"])- self._enable_access_controls()++ def test_the_gate_costs_what_the_check_reads_not_what_the_team_owns(self) -> None:+ allowed = User.objects.create_and_join(self.organization, "[email protected]", "password")+ denied = User.objects.create_and_join(self.organization, "[email protected]", "password")+ self._deny_view_for_member(self.view, denied)check = self._custom_sql_check_reading_orders()with patch.object(Database, "create_for", side_effect=Database.create_for) as build:- resolved = self._resolver_for(check).resolve(TargetType.TEAM, str(self.team.id), self.team.id)+ with CaptureQueriesContext(connection) as small_team:+ resolved = self._resolver_for(check).resolve(TargetType.TEAM, str(self.team.id), self.team.id)++ build.assert_not_called()+ assert {allowed.id, self.user.id} <= set(resolved)+ assert denied.id not in resolved- assert build.call_count == 1- assert {first_admin.id, second_admin.id, self.user.id} <= set(resolved)+ for index in range(20):+ DataWarehouseSavedQuery.objects.create(+ team=self.team, name=f"unrelated_view_{index}", query={"kind": "HogQLQuery", "query": "SELECT 1 AS id"}+ )+ DataWarehouseTable.objects.create(+ team=self.team,+ name=f"unrelated_table_{index}",+ format="Parquet",+ url_pattern=f"s3://bucket/unrelated_{index}",+ )+ cache.clear()++ with CaptureQueriesContext(connection) as large_team:+ self._resolver_for(check).resolve(TargetType.TEAM, str(self.team.id), self.team.id)++ assert len(large_team.captured_queries) == len(small_team.captured_queries)++ @parameterized.expand(+ [+ ("dotted_source_table", "stripe_table"),+ ("materialized_view_backing_table", "backing_table"),+ ("denied_system_table", "system_table"),+ ("warehouse_table_shadowing_a_system_table", "warehouse_table_shadowing_a_system_table"),+ ("direct_table_shadowing_a_view", "direct_table_shadowing_a_view"),+ ]+ )+ def test_a_reference_the_member_cannot_read_withholds_the_notification(self, _name, denied_kind: str) -> None:+ self._enable_access_controls()+ blocked = User.objects.create_and_join(self.organization, f"blocked-{denied_kind}@test.com", "password")+ check = self._check_reading(denied_kind, blocked)++ resolved = self._resolver_for(check).resolve(TargetType.TEAM, str(self.team.id), self.team.id)++ assert self.user.id in resolved+ assert blocked.id not in resolveddef test_a_relationship_target_keeps_its_name_for_notification_filtering(self) -> None:check = self._check(diff --git a/products/data_quality/backend/tests/test_subject_access.py b/products/data_quality/backend/tests/test_subject_access.pyindex cd4821c11d16..ef39441b0196 100644--- a/products/data_quality/backend/tests/test_subject_access.py+++ b/products/data_quality/backend/tests/test_subject_access.py@@ -181,6 +181,40 @@ class TestMetricSubjectAccess(BaseTest):("view", str(self.extra_view.id)),}+ def test_a_warehouse_table_named_after_a_system_table_is_not_pinned(self) -> None:+ shadow = DataWarehouseTable.objects.create(+ team=self.team,+ name="system_annotations",+ format=DataWarehouseTable.TableFormat.Parquet,+ url_pattern="s3://bucket/system_annotations",+ )++ pinned = pin_referenced_subjects(+ self.team.id,+ "custom_sql",+ {"query": "SELECT * FROM {metric} WHERE amount < (SELECT 1 FROM system.annotations)"},+ subject=self.subject,+ )++ assert pinned is not None+ assert ("table", str(shadow.id)) not in {(ref["subject_type"], ref["subject_uuid"]) for ref in pinned}++ def test_a_direct_connection_table_does_not_shadow_the_view_of_the_same_name(self) -> None:+ DataWarehouseTable.objects.create(+ team=self.team,+ name=self.extra_view.name,+ format=DataWarehouseTable.TableFormat.Parquet,+ url_pattern="s3://bucket/thresholds",+ external_data_source=ExternalDataSource.objects.create(+ team=self.team, source_type="Postgres", access_method=ExternalDataSource.AccessMethod.DIRECT+ ),+ )++ pinned = pin_referenced_subjects(self.team.id, "custom_sql", self.config, subject=self.subject)++ assert pinned is not None+ assert ("view", str(self.extra_view.id)) in {(ref["subject_type"], ref["subject_uuid"]) for ref in pinned}+@parameterized.expand([("allowed", set(), True), ("denied", {"revenue_rows"}, False)])def test_readable_metric_identity_controls_history(self, _name: str, denied: set[str], expected: bool) -> None:check, suite = self._check_and_suite()diff --git a/products/data_quality/backend/tests/test_subjects.py b/products/data_quality/backend/tests/test_subjects.pyindex cf7f98e1ef79..9c1a35b06c26 100644--- a/products/data_quality/backend/tests/test_subjects.py+++ b/products/data_quality/backend/tests/test_subjects.py@@ -165,7 +165,7 @@ class TestReadableSubjectSnapshot(BaseTest):assert backing_table.id not in readable.table_ids- def test_backing_table_map_includes_soft_deleted_views_in_one_query(self) -> None:+ def test_backing_table_map_includes_soft_deleted_views_and_narrows_to_the_tables_asked_about(self) -> None:view, backing_table = self._materialized_view()view.deleted = Trueview.save(update_fields=["deleted"])@@ -182,6 +182,16 @@ class TestReadableSubjectSnapshot(BaseTest):backing_tables = data_modeling_facade.backing_table_ids_by_saved_query(self.team.id)assert backing_tables == {backing_table.id: view.id}+ with self.assertNumQueries(1):+ assert data_modeling_facade.backing_table_ids_by_saved_query(+ self.team.id, table_ids={backing_table.id}+ ) == {backing_table.id: view.id}+ with self.assertNumQueries(1):+ assert (+ data_modeling_facade.backing_table_ids_by_saved_query(self.team.id, table_ids={source_table.id}) == {}+ )+ with self.assertNumQueries(0):+ assert data_modeling_facade.backing_table_ids_by_saved_query(self.team.id, table_ids=set()) == {}def test_shared_metadata_keeps_recipient_permissions_separate(self) -> None:allowed = self._table("allowed")diff --git a/products/warehouse_sources/backend/facade/api.py b/products/warehouse_sources/backend/facade/api.pyindex 112069cff56c..8014ff82c79c 100644--- a/products/warehouse_sources/backend/facade/api.py+++ b/products/warehouse_sources/backend/facade/api.py@@ -347,13 +347,14 @@ def resolve_object_by_name(team_id: int, name: str) -> contracts.WarehouseObject"""The warehouse table or saved query a query reaches under this name, else None.Resolves the dotted source forms (``stripe.charges``) the same way a query does, and skips- soft-deleted rows and orphans of a deleted source. None means the name reaches neither, so it- carries no object-level access control -- a PostHog table such as ``events``, or nothing at all.+ soft-deleted rows, orphans of a deleted source, and direct-connection tables the default HogQL+ scope hides. None means the name reaches neither, so it carries no object-level access control+ -- a PostHog table such as ``events``, or nothing at all.For a caller recording what a query read: the identity survives the name being freed and takenby something else, which is what makes it usable as evidence later."""- resolved = _get_view_or_table_by_name(team_id, name)+ resolved = _get_view_or_table_by_name(team_id, name, exclude_direct_access=True)if resolved is None:return Nonekind = (diff --git a/products/warehouse_sources/backend/models/util.py b/products/warehouse_sources/backend/models/util.pyindex 8e6f0fe95850..9aa9f81b1538 100644--- a/products/warehouse_sources/backend/models/util.py+++ b/products/warehouse_sources/backend/models/util.py@@ -35,8 +35,12 @@ class DatabaseFieldFactory(Protocol):def __call__(self, *args: Any, **kwargs: Any) -> DatabaseField: ...-def get_view_or_table_by_name(team, name) -> Union["DataWarehouseSavedQuery", "DataWarehouseTable", None]:+def get_view_or_table_by_name(+ team, name, exclude_direct_access: bool = False+) -> Union["DataWarehouseSavedQuery", "DataWarehouseTable", None]:+ """``exclude_direct_access`` drops direct-connection tables, which the default HogQL scope hides."""from products.data_modeling.backend.facade.models import DataWarehouseSavedQuery+ from products.warehouse_sources.backend.models.external_data_source import ExternalDataSourcefrom products.warehouse_sources.backend.models.table import DataWarehouseTabletable_names = [name]@@ -48,13 +52,13 @@ def get_view_or_table_by_name(team, name) -> Union["DataWarehouseSavedQuery", "D# Support both `_` suffixed source prefix and without - e.g. postgres_table_name and postgrestable_nametable_names = [f"{chain[1]}_{chain[0]}_{chain[2]}", f"{chain[1]}{chain[0]}_{chain[2]}"]+ # `queryable()` ignores soft-deleted tables and orphans of a soft-deleted source.+ tables = DataWarehouseTable.objects.queryable().filter(team=team, name__in=table_names)+ if exclude_direct_access:+ tables = tables.exclude(external_data_source__access_method=ExternalDataSource.AccessMethod.DIRECT)table: DataWarehouseSavedQuery | DataWarehouseTable | None = (- # `queryable()` ignores soft-deleted tables and orphans of a soft-deleted source.- DataWarehouseTable.objects.queryable()- .filter(team=team, name__in=table_names)# Deterministic resolution when more than one live table matches: newest wins.- .order_by("-created_at")- .first()+ tables.order_by("-created_at").first())if table is None:table = DataWarehouseSavedQuery.objects.exclude(deleted=True).filter(team=team, name=name).first()