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.

fix(data-quality): withhold suite check runs that read a denied subject (#86542)

Thiago Salvatoreb7130587088f
diff --git a/products/data_quality/backend/facade/api.py b/products/data_quality/backend/facade/api.py
index a94ab43fd613..05c4e54adcbf 100644
--- a/products/data_quality/backend/facade/api.py
+++ b/products/data_quality/backend/facade/api.py
@@ -27,7 +27,17 @@ from ..logic.navigation import SubjectKey, SubjectLocation, subject_locations
from ..logic.notifications import notify_materialization_blocked
from ..logic.registry import UnknownCheckTypeError, list_check_types
from ..logic.serialization import compute_fingerprint, from_config_entry, to_config_entry
-from ..logic.subject_access import denied_subject_names, is_subject_denied, referenced_subject_names
+from ..logic.subject_access import (
+ PinnedSubject,
+ ReferencedSubjects,
+ check_type_reads_beyond_subject,
+ denied_subject_names,
+ is_subject_denied,
+ pinned_subjects,
+ referenced_subject_names,
+ referenced_subjects,
+ unconfirmable_subject_names,
+)
from ..logic.subjects import resolve_subject
from ..logic.triggers import materialization_audit_mode as quality_audit_mode
from .contracts import CheckTypeInfo
@@ -38,11 +48,14 @@ __all__ = [
"CheckStatusRow",
"CheckTypeInfo",
"CompiledCheck",
+ "PinnedSubject",
+ "ReferencedSubjects",
"SubjectKey",
"SubjectLocation",
"SubjectRef",
"SubjectUnresolvableError",
"UnknownCheckTypeError",
+ "check_type_reads_beyond_subject",
"checks_for_subject",
"compile_check",
"compute_fingerprint",
@@ -55,8 +68,10 @@ __all__ = [
"is_subject_denied",
"list_check_types",
"notify_materialization_blocked",
+ "pinned_subjects",
"quality_audit_mode",
"referenced_subject_names",
+ "referenced_subjects",
"related_subject_ref",
"resolve_subject",
"roll_up_health",
@@ -66,6 +81,7 @@ __all__ = [
"subject_health",
"subject_locations",
"to_config_entry",
+ "unconfirmable_subject_names",
"upsert_check",
"validate_check",
]
diff --git a/products/data_quality/backend/logic/runner.py b/products/data_quality/backend/logic/runner.py
index a84fede1eab1..389e9acd2b7b 100644
--- a/products/data_quality/backend/logic/runner.py
+++ b/products/data_quality/backend/logic/runner.py
@@ -29,7 +29,7 @@ from .compiler import compile_check, related_subject_ref
from .contracts import CompiledCheck, Evaluation
from .notifications import notify_check_started_failing
from .staged_audit import StagedSubjectOverride, build_staged_database
-from .subject_access import check_type_reads_beyond_subject
+from .subject_access import check_type_reads_beyond_subject, pin_referenced_subjects
from .subjects import resolve_subject
QUERY_TYPE = "data_quality_check"
@@ -330,6 +330,7 @@ def _record_run(
column_name=check.column_name,
check_config=check.config,
check_severity=check.severity,
+ referenced_subjects=pin_referenced_subjects(check.team_id, check.check_type, check.config),
status=outcome.status,
failed_row_count=outcome.failed_row_count,
observed_value=outcome.observed_value,
diff --git a/products/data_quality/backend/logic/subject_access.py b/products/data_quality/backend/logic/subject_access.py
index b4849a1e85b7..3ab15087569b 100644
--- a/products/data_quality/backend/logic/subject_access.py
+++ b/products/data_quality/backend/logic/subject_access.py
@@ -12,9 +12,12 @@ from typing import TYPE_CHECKING, Any, Optional
from posthog.hogql.database.database import Database
from posthog.hogql.database.schema.information_schema import _references_denied_table
+from posthog.dataclasses import frozen
+from posthog.exceptions_capture import capture_exception
+
from .registry import all_specs, get_spec
from .spec import CheckTypeSpec
-from .subjects import resolve_subject
+from .subjects import resolve_subject, resolve_subject_by_name
if TYPE_CHECKING:
from posthog.models import Team, User
@@ -76,7 +79,19 @@ def check_reads_denied_subject(team_id: int, check_type: str, config: dict[str,
return any(is_subject_denied(name, denied) for name in referenced_subject_names(team_id, check_type, config))
-def referenced_subject_names(team_id: int, check_type: str, config: dict[str, Any]) -> list[str]:
+@frozen
+class ReferencedSubjects:
+ """What a check reads besides its declared subject, and whether that could be established.
+
+ ``unresolved_reference`` is the part a name list cannot carry: a ``relationships`` target that no
+ longer resolves leaves no name behind, so a caller matching names alone would read "references
+ nothing" from a subject that was deleted out from under the denial set."""
+
+ names: tuple[str, ...]
+ unresolved_reference: bool
+
+
+def referenced_subjects(team_id: int, check_type: str, config: dict[str, Any]) -> ReferencedSubjects:
"""Every warehouse name a check reads *besides* its declared subject.
A ``relationships`` check names a second subject and a ``custom_sql`` query selects from arbitrary
@@ -86,8 +101,97 @@ def referenced_subject_names(team_id: int, check_type: str, config: dict[str, An
spec = get_spec(check_type)
parsed = spec.parse_config(config)
names = list(spec.referenced_table_names(parsed))
+ unresolved = False
if related := spec.related_subject_ref(parsed):
ref = resolve_subject(team_id, related[0], related[1])
if ref.exists:
names.append(ref.name)
- return names
+ else:
+ unresolved = True
+ return ReferencedSubjects(names=tuple(names), unresolved_reference=unresolved)
+
+
+def referenced_subject_names(team_id: int, check_type: str, config: dict[str, Any]) -> list[str]:
+ """The names from :func:`referenced_subjects`, for callers that only report or match on them."""
+ return list(referenced_subjects(team_id, check_type, config).names)
+
+
+@frozen
+class PinnedSubject:
+ """One subject a run read besides its own, as the identity recorded alongside the run."""
+
+ subject_type: str
+ subject_uuid: str
+
+
+_SUBJECT_TYPE_KEY = "subject_type"
+_SUBJECT_UUID_KEY = "subject_uuid"
+
+
+def pin_referenced_subjects(team_id: int, check_type: str, config: dict[str, Any]) -> list[dict[str, str]] | None:
+ """The identities of the subjects this run reads besides its own, to record alongside the run.
+
+ Names cannot carry this. Deleting a warehouse object frees its name, so a recorded name starts
+ naming whatever a member creates in its place, and history read back by name hands them what the
+ run read over an object they were denied. An identity survives that: the reused name resolves to
+ a different id, and the recorded id stops resolving.
+
+ ``None`` when the references cannot be established at all, so a reader falls back to judging the
+ run by its type rather than reading an empty list as "read nothing".
+ """
+ try:
+ spec = get_spec(check_type)
+ parsed = spec.parse_config(config)
+ pinned = [
+ subject for name in spec.referenced_table_names(parsed) if (subject := _pin_name(team_id, name)) is not None
+ ]
+ if related := spec.related_subject_ref(parsed):
+ pinned.append(PinnedSubject(subject_type=str(related[0]), subject_uuid=str(related[1])))
+ except Exception as err:
+ capture_exception(err)
+ return None
+ return [{_SUBJECT_TYPE_KEY: subject.subject_type, _SUBJECT_UUID_KEY: subject.subject_uuid} for subject in pinned]
+
+
+def pinned_subjects(recorded: Any) -> list[PinnedSubject] | None:
+ """The identities a run recorded, or None when it recorded nothing judgeable.
+
+ A malformed entry reads as nothing recorded rather than as an empty list, so a run whose
+ recording cannot be trusted falls back to the same type-based rule as one predating it."""
+ if not isinstance(recorded, list):
+ return None
+ subjects = []
+ for entry in recorded:
+ if not isinstance(entry, dict):
+ return None
+ subject_type, subject_uuid = entry.get(_SUBJECT_TYPE_KEY), entry.get(_SUBJECT_UUID_KEY)
+ if not isinstance(subject_type, str) or not isinstance(subject_uuid, str):
+ return None
+ subjects.append(PinnedSubject(subject_type=subject_type, subject_uuid=subject_uuid))
+ return subjects
+
+
+def _pin_name(team_id: int, name: str) -> PinnedSubject | None:
+ ref = resolve_subject_by_name(team_id, name)
+ if ref is None:
+ return None
+ return PinnedSubject(subject_type=str(ref.subject_type), subject_uuid=ref.subject_uuid)
+
+
+def unconfirmable_subject_names(
+ team: "Team",
+ user: "User",
+ names: tuple[str, ...],
+ user_access_control: Optional["UserAccessControl"] = None,
+) -> set[str]:
+ """The referenced names this caller can neither resolve nor be shown to have been denied.
+
+ Deleting a warehouse object takes its denial with it: the name leaves the database the caller
+ can resolve *and* the denial set that is rebuilt from the objects that still exist, so a run
+ that once read a denied table starts reading as harmless. Neither state proves access, so both
+ are reported and the caller fails them closed -- the same stance ``_require_parent_subject_access``
+ already takes for the subject a check hangs off."""
+ if not names:
+ return set()
+ database = Database.create_for(team=team, user=user, user_access_control=user_access_control)
+ return {name for name in names if not database.has_table(name) and not database.is_table_access_denied(name)}
diff --git a/products/data_quality/backend/logic/subjects.py b/products/data_quality/backend/logic/subjects.py
index 195a7674fc33..af0996440dc3 100644
--- a/products/data_quality/backend/logic/subjects.py
+++ b/products/data_quality/backend/logic/subjects.py
@@ -10,10 +10,16 @@ from uuid import UUID
from products.data_modeling.backend.facade import api as data_modeling_facade
from products.warehouse_sources.backend.facade import api as warehouse_facade
+from products.warehouse_sources.backend.facade.contracts import WAREHOUSE_OBJECT_TABLE, WAREHOUSE_OBJECT_VIEW
from ..facade.enums import SubjectType
from .contracts import SubjectRef
+_WAREHOUSE_OBJECT_SUBJECT_TYPES = {
+ WAREHOUSE_OBJECT_TABLE: SubjectType.TABLE,
+ WAREHOUSE_OBJECT_VIEW: SubjectType.VIEW,
+}
+
def resolve_subject(team_id: int, subject_type: str, subject_uuid: str | UUID) -> SubjectRef:
"""Look the subject up in its owning product. Never raises for a missing subject."""
@@ -23,6 +29,26 @@ def resolve_subject(team_id: int, subject_type: str, subject_uuid: str | UUID) -
return _resolve_view(team_id, subject_uuid)
+def resolve_subject_by_name(team_id: int, name: str) -> SubjectRef | None:
+ """The subject a query reaches under this name, or None when the name is no warehouse object.
+
+ The inverse of :func:`resolve_subject`, for pinning what a run read while it still names the
+ right object. None is not a failure: only warehouse tables and saved queries carry object-level
+ access control, so a name that reaches neither has no identity worth recording.
+ """
+ resolved = warehouse_facade.resolve_object_by_name(team_id, name)
+ if resolved is None:
+ return None
+ kind = _WAREHOUSE_OBJECT_SUBJECT_TYPES[resolved.kind]
+ return SubjectRef(
+ subject_type=kind,
+ subject_uuid=str(resolved.id),
+ name=name,
+ queryable_name=name,
+ exists=True,
+ )
+
+
def _resolve_table(team_id: int, subject_uuid: str | UUID) -> SubjectRef:
table = warehouse_facade.get_queryable_table(UUID(str(subject_uuid)), team_id)
if table is None:
diff --git a/products/data_quality/backend/migrations/0006_dataqualitycheckrun_referenced_subjects.py b/products/data_quality/backend/migrations/0006_dataqualitycheckrun_referenced_subjects.py
new file mode 100644
index 000000000000..074e871c3a19
--- /dev/null
+++ b/products/data_quality/backend/migrations/0006_dataqualitycheckrun_referenced_subjects.py
@@ -0,0 +1,21 @@
+# Generated by Django 5.2.17 on 2026-08-26 14:54
+
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("data_quality", "0005_free_deleted_check_names"),
+ ]
+
+ operations = [
+ migrations.AddField(
+ model_name="dataqualitycheckrun",
+ name="referenced_subjects",
+ field=models.JSONField(
+ blank=True,
+ help_text="Subjects this run read besides its own, as {subject_type, subject_uuid} entries. Null for runs recorded before references were pinned.",
+ null=True,
+ ),
+ ),
+ ]
diff --git a/products/data_quality/backend/migrations/max_migration.txt b/products/data_quality/backend/migrations/max_migration.txt
index 20e6e6a0e758..179a1cb55a1d 100644
--- a/products/data_quality/backend/migrations/max_migration.txt
+++ b/products/data_quality/backend/migrations/max_migration.txt
@@ -1 +1 @@
-0005_free_deleted_check_names
+0006_dataqualitycheckrun_referenced_subjects
diff --git a/products/data_quality/backend/models/check_run.py b/products/data_quality/backend/models/check_run.py
index e36f517b9ca6..5fc80332bb94 100644
--- a/products/data_quality/backend/models/check_run.py
+++ b/products/data_quality/backend/models/check_run.py
@@ -117,6 +117,17 @@ class DataQualityCheckRun(TeamScopedRootMixin, CreatedMetaFields, UpdatedMetaFie
blank=True,
help_text="Severity this run was judged at. Null for runs recorded before snapshots.",
)
+ # Identities, not names: a deleted warehouse object frees its name for anyone to take, so a name
+ # recorded here would stop naming what the run read the moment someone reused it. Null means
+ # "recorded before runs pinned this"; an empty list means "read nothing beyond its subject".
+ referenced_subjects = models.JSONField(
+ null=True,
+ blank=True,
+ help_text=(
+ "Subjects this run read besides its own, as {subject_type, subject_uuid} entries. "
+ "Null for runs recorded before references were pinned."
+ ),
+ )
status = models.CharField(max_length=16, choices=[(s.value, s.value) for s in CheckRunStatus])
failed_row_count = models.BigIntegerField(
diff --git a/products/data_quality/backend/presentation/views.py b/products/data_quality/backend/presentation/views.py
index af09e1c8607d..b30b1162d9de 100644
--- a/products/data_quality/backend/presentation/views.py
+++ b/products/data_quality/backend/presentation/views.py
@@ -7,7 +7,6 @@ serialize the result. Nothing here runs a check -- every trigger hands off to Te
a suite-run handle to poll.
"""
-import json
from collections import defaultdict
from collections.abc import Callable
from typing import ClassVar, cast
@@ -122,51 +121,89 @@ class _QualityGatedViewSet(TeamAndOrgViewSetMixin):
self._denied_subjects_cache = cached
return cached
- def _reads_denied_subject(self, check_type: str, config: dict, denied: set[str]) -> bool:
- """Whether this definition reads a subject the caller is denied.
+ def _reads_unreadable_subject(self, check_type: str, config: dict) -> bool:
+ """Whether this definition reads a subject the caller cannot be shown to be allowed.
The parent is not the only subject a check reads: a relationships check names a second
subject and a custom_sql query selects arbitrary tables, both run by the worker with team
scope only. Authorize them too, or a check on an allowed subject is a count oracle over a
denied one.
+
+ A denied name is only the case where the subject still exists. Deleting it takes its denial
+ with it, so a name that neither resolves nor is denied proves nothing either way and is
+ refused on the same fail-closed terms.
"""
- return any(
- api.is_subject_denied(name, denied)
- for name in api.referenced_subject_names(self.team.id, check_type, config)
- )
+ refs = api.referenced_subjects(self.team.id, check_type, config)
+ if refs.unresolved_reference:
+ return True
+ if any(api.is_subject_denied(name, self._denied_subject_names()) for name in refs.names):
+ return True
+ return bool(self._unconfirmable_names(refs.names))
+
+ def _unconfirmable_names(self, names: tuple[str, ...]) -> set[str]:
+ # Memoized per request: the lookup rebuilds the caller's HogQL database, and a suite re-runs
+ # the same definitions.
+ cache: dict[str, bool] = getattr(self, "_unconfirmable_cache", {})
+ self._unconfirmable_cache = cache
+ unseen = tuple(name for name in names if name not in cache)
+ if unseen:
+ unconfirmable = api.unconfirmable_subject_names(
+ self.team,
+ cast(User, self.request.user),
+ unseen,
+ user_access_control=self.user_access_control,
+ )
+ cache.update({name: name in unconfirmable for name in unseen})
+ return {name for name in names if cache[name]}
def _require_referenced_subject_access(self, check_type: str, config: dict) -> None:
- denied = self._denied_subject_names()
- if not denied:
+ if not self._can_be_object_denied():
return
- if self._reads_denied_subject(check_type, config, denied):
+ if self._reads_unreadable_subject(check_type, config):
raise PermissionDenied("You don't have access to a table or view this check reads.")
def _readable_runs(self, runs: list[DataQualityCheckRun]) -> list[DataQualityCheckRun]:
- """Drop the runs whose definition read a subject the caller is denied.
+ """Drop the runs that read a subject the caller cannot be shown to be allowed."""
+ if not self._can_be_object_denied():
+ return runs
+ return [run for run in runs if self._run_is_readable(run)]
+
+ def _run_is_readable(self, run: DataQualityCheckRun) -> bool:
+ """Whether every subject this run read is one the caller may read now.
- Judged from the definition each run executed, not the one its check carries now, so editing
- a check cannot retroactively expose or hide its history. Runs older than the config snapshot
- fall back to their check; one that predates it and has lost its check is withheld, since what
- it read cannot be established.
+ Judged from the identities the run pinned as it executed, never from the definition its
+ check carries now, so editing a check cannot retroactively expose the history it used to
+ read -- and never from names, which a deleted object frees for anyone to take.
+
+ A run that pinned nothing predates that recording. It falls back to its type: one that
+ cannot read past its own subject read only the parent this surface already authorized, and
+ anything that can is withheld, since there is no longer evidence of what it reached.
"""
- denied = self._denied_subject_names()
- if not denied:
- return runs
- verdicts: dict[str, bool] = {}
- readable = []
- for run in runs:
- config = run.check_config if run.check_config is not None else getattr(run.quality_check, "config", None)
- if config is None:
- continue
- # One verdict per definition: a suite re-runs the same checks, and resolving a
- # relationships target costs a query.
- cache_key = f"{run.check_type}:{json.dumps(config, sort_keys=True, default=str)}"
- if cache_key not in verdicts:
- verdicts[cache_key] = self._reads_denied_subject(run.check_type, config, denied)
- if not verdicts[cache_key]:
- readable.append(run)
- return readable
+ pinned = api.pinned_subjects(run.referenced_subjects)
+ if pinned is None:
+ return not api.check_type_reads_beyond_subject(run.check_type)
+ return all(self._pinned_subject_is_readable(subject) for subject in pinned)
+
+ def _pinned_subject_is_readable(self, subject: api.PinnedSubject) -> bool:
+ # Memoized per request: a suite re-runs the same checks over the same subjects, and each
+ # resolution costs a query.
+ cache: dict[tuple[str, str], bool] = getattr(self, "_pinned_subject_cache", {})
+ self._pinned_subject_cache = cache
+ key = (subject.subject_type, subject.subject_uuid)
+ if key not in cache:
+ cache[key] = self._resolves_to_a_readable_subject(subject)
+ return cache[key]
+
+ def _resolves_to_a_readable_subject(self, subject: api.PinnedSubject) -> bool:
+ try:
+ ref = api.resolve_subject(self.team.id, subject.subject_type, subject.subject_uuid)
+ except ValueError:
+ return False
+ # A subject that no longer resolves took its denial with it, so nothing left can show the
+ # caller was allowed the object this run read.
+ if not ref.exists:
+ return False
+ return not api.is_subject_denied(ref.name, self._denied_subject_names())
class _SubjectScopedViewSet(_QualityGatedViewSet):
@@ -423,8 +460,13 @@ class _BaseSuiteRunViewSet(
@action(methods=["GET"], detail=True, url_path="check_runs", pagination_class=None)
def check_runs(self, request: Request, **kwargs) -> Response:
suite_run = self.get_object()
- runs = DataQualityCheckRun.objects.for_team(self.team_id).filter(suite_run=suite_run).order_by("-created_at")
- return Response(DataQualityCheckRunSerializer(runs, many=True).data)
+ runs = list(
+ DataQualityCheckRun.objects.for_team(self.team_id)
+ .filter(suite_run=suite_run)
+ .select_related("quality_check")
+ .order_by("-created_at")
+ )
+ return Response(DataQualityCheckRunSerializer(self._readable_runs(runs), many=True).data)
def _parent_id_parameter(name: str, description: str) -> Callable[[type], type]:
diff --git a/products/data_quality/backend/tests/test_api.py b/products/data_quality/backend/tests/test_api.py
index e6df73f35c97..7c04ddc97857 100644
--- a/products/data_quality/backend/tests/test_api.py
+++ b/products/data_quality/backend/tests/test_api.py
@@ -58,8 +58,9 @@ class TestDataQualityCheckAPI(APIBaseTest):
def _checks_url(self, saved_query_id) -> str:
return f"/api/projects/{self.team.id}/warehouse_saved_queries/{saved_query_id}/checks"
- def _suite_runs_url(self) -> str:
- return f"/api/projects/{self.team.id}/warehouse_saved_queries/{self.view.id}/check_suite_runs"
+ def _suite_runs_url(self, saved_query_id=None) -> str:
+ parent = saved_query_id or self.view.id
+ return f"/api/projects/{self.team.id}/warehouse_saved_queries/{parent}/check_suite_runs"
def _gate_url(self) -> str:
return f"/api/projects/{self.team.id}/data_warehouse/data_quality_gate/"
@@ -93,6 +94,9 @@ class TestDataQualityCheckAPI(APIBaseTest):
team=self.team, name=name, query={"kind": "HogQLQuery", "query": "SELECT 1 AS id"}
)
+ def _pinned(self, *views: DataWarehouseSavedQuery) -> list[dict[str, str]]:
+ return [{"subject_type": str(SubjectType.VIEW), "subject_uuid": str(view.id)} for view in views]
+
def test_the_whole_surface_is_gated_on_the_feature_flag(self) -> None:
with patch(FLAG, return_value=False):
assert self.client.get(f"{self.url}/").status_code == status.HTTP_403_FORBIDDEN
@@ -515,10 +519,12 @@ class TestDataQualityCheckAPI(APIBaseTest):
check_runs = self.client.get(f"{base}/{mine.id}/check_runs/")
assert [row["subject_name"] for row in check_runs.json()] == ["orders"]
- def test_editing_a_check_does_not_unlock_the_history_it_used_to_read(self) -> None:
+ @parameterized.expand([("pinned", True), ("recorded before pinning", False)])
+ def test_editing_a_check_does_not_unlock_the_history_it_used_to_read(self, _name: str, pinned: bool) -> None:
# Authorizing history against the definition the check carries *now* lets a member point a
# check that reads the denied "orders" at something harmless and then read what it recorded:
- # the compiled query, the failed-row count and the observed value.
+ # the compiled query, the failed-row count and the observed value. A run that pinned no
+ # references is judged by its type rather than by the edited check.
allowed = self._make_view("customers")
reads_orders = {"query": "SELECT 1 FROM orders"}
check = DataQualityCheck.objects.for_team(self.team.id).create(
@@ -539,6 +545,7 @@ class TestDataQualityCheckAPI(APIBaseTest):
subject_name="customers",
check_type=CheckType.CUSTOM_SQL,
check_config=reads_orders,
+ referenced_subjects=self._pinned(self.view) if pinned else None,
check_fingerprint=check.fingerprint,
status=CheckRunStatus.FAILED,
failed_row_count=3,
@@ -663,6 +670,190 @@ class TestDataQualityCheckAPI(APIBaseTest):
check.refresh_from_db()
assert check.check_type == CheckType.NOT_NULL
+ def _suite_with_two_runs(self, allowed: DataWarehouseSavedQuery) -> DataQualitySuiteRun:
+ suite = DataQualitySuiteRun.objects.for_team(self.team.id).create(
+ team=self.team, trigger="manual", subject_type=SubjectType.VIEW, subject_uuid=allowed.id
+ )
+ for check_type, config, name, referenced in (
+ (CheckType.NOT_NULL, {}, "reads_only_the_parent", []),
+ (CheckType.CUSTOM_SQL, {"query": "SELECT 1 FROM orders"}, "reads_the_denied_view", self._pinned(self.view)),
+ ):
+ check = DataQualityCheck.objects.for_team(self.team.id).create(
+ team=self.team,
+ name=name,
+ subject_type=SubjectType.VIEW,
+ saved_query_id=allowed.id,
+ subject_name="customers",
+ check_type=check_type,
+ column_name="total" if check_type == CheckType.NOT_NULL else "",
+ config=config,
+ fingerprint=uuid4().hex,
+ )
+ DataQualityCheckRun.objects.for_team(self.team.id).create(
+ team=self.team,
+ suite_run=suite,
+ quality_check=check,
+ subject_type=SubjectType.VIEW,
+ subject_uuid=allowed.id,
+ subject_name="customers",
+ check_type=check_type,
+ check_config=config,
+ referenced_subjects=referenced,
+ check_fingerprint=check.fingerprint,
+ status=CheckRunStatus.FAILED,
+ failed_row_count=3,
+ compiled_query="SELECT * FROM orders",
+ )
+ return suite
+
+ @parameterized.expand(
+ [
+ ("denied_member", True, [CheckType.NOT_NULL]),
+ ("allowed_member", False, [CheckType.CUSTOM_SQL, CheckType.NOT_NULL]),
+ ]
+ )
+ def test_suite_check_runs_withhold_a_run_that_read_a_denied_subject(
+ self, _name: str, deny: bool, expected_types: list[str]
+ ) -> None:
+ # A run carries its compiled query, failed-row count and observed value. A check on an allowed
+ # parent whose custom_sql reads the denied "orders" would disclose all three here, which is
+ # what the check-level routes refuse. The rest of the suite stays readable.
+ allowed = self._make_view("customers")
+ suite = self._suite_with_two_runs(allowed)
+ if deny:
+ self._deny_the_view()
+
+ response = self.client.get(f"{self._suite_runs_url(allowed.id)}/{suite.id}/check_runs/")
+
+ assert response.status_code == status.HTTP_200_OK
+ assert sorted(row["check_type"] for row in response.json()) == sorted(expected_types)
+
+ def test_a_run_whose_definition_is_unknown_is_judged_by_its_type(self) -> None:
+ # Predating the pinned references, so there is nothing recorded to judge. A type that cannot
+ # reach past its own subject read only the parent this surface already authorized; one that
+ # can is withheld, since the current definition is not evidence of what the run executed.
+ allowed = self._make_view("customers")
+ suite = self._suite_with_two_runs(allowed)
+ DataQualityCheckRun.objects.for_team(self.team.id).filter(suite_run=suite).update(
+ check_config=None, referenced_subjects=None, quality_check=None
+ )
+ self._deny_the_view()
+
+ response = self.client.get(f"{self._suite_runs_url(allowed.id)}/{suite.id}/check_runs/")
+
+ assert response.status_code == status.HTTP_200_OK
+ assert [row["check_type"] for row in response.json()] == [CheckType.NOT_NULL]
+
+ @parameterized.expand([("relationships",), ("custom_sql",)])
+ def test_deleting_a_referenced_subject_does_not_hand_its_history_over(self, check_type: str) -> None:
+ # Deletion takes the denial with it: the denial set is rebuilt from the objects that still
+ # exist, so a deleted subject stops looking denied. The run pinned what it read, and an
+ # identity that no longer resolves is no proof the caller was allowed it.
+ allowed = self._make_view("customers")
+ config: dict = (
+ {"query": "SELECT 1 FROM orders"}
+ if check_type == CheckType.CUSTOM_SQL
+ else {"to_subject_type": SubjectType.VIEW, "to_subject_uuid": str(self.view.id), "to_column": "id"}
+ )
+ check = DataQualityCheck.objects.for_team(self.team.id).create(
+ team=self.team,
+ subject_type=SubjectType.VIEW,
+ saved_query_id=allowed.id,
+ subject_name="customers",
+ check_type=check_type,
+ column_name="" if check_type == CheckType.CUSTOM_SQL else "customer_id",
+ config=config,
+ fingerprint=uuid4().hex,
+ )
+ suite = DataQualitySuiteRun.objects.for_team(self.team.id).create(
+ team=self.team, trigger="manual", subject_type=SubjectType.VIEW, subject_uuid=allowed.id
+ )
+ DataQualityCheckRun.objects.for_team(self.team.id).create(
+ team=self.team,
+ suite_run=suite,
+ quality_check=check,
+ subject_type=SubjectType.VIEW,
+ subject_uuid=allowed.id,
+ subject_name="customers",
+ check_type=check_type,
+ check_config=config,
+ referenced_subjects=self._pinned(self.view),
+ check_fingerprint=check.fingerprint,
+ status=CheckRunStatus.FAILED,
+ failed_row_count=3,
+ compiled_query="SELECT * FROM orders",
+ )
+ self._deny_the_view()
+ self.view.delete()
+
+ suite_runs = self.client.get(f"{self._suite_runs_url(allowed.id)}/{suite.id}/check_runs/")
+ history = self.client.get(f"{self._checks_url(allowed.id)}/{check.id}/runs/")
+
+ # The suite route filters, since it serves runs from many checks. The per-check route refuses,
+ # since the one definition it serves is the one that cannot be established.
+ assert suite_runs.status_code == status.HTTP_200_OK
+ assert suite_runs.json() == []
+ assert history.status_code == status.HTTP_403_FORBIDDEN
+
+ def test_reusing_a_deleted_subjects_name_does_not_hand_its_history_over(self) -> None:
+ # Deleting a view frees its name, so a member can create their own "orders" and make the name
+ # resolve for them again. Judged by name, the run that read the denied "orders" would then
+ # read as harmless and hand over its compiled query and failed-row count.
+ allowed = self._make_view("customers")
+ reads_orders = {"query": "SELECT 1 FROM orders"}
+ suite = DataQualitySuiteRun.objects.for_team(self.team.id).create(
+ team=self.team, trigger="manual", subject_type=SubjectType.VIEW, subject_uuid=allowed.id
+ )
+ DataQualityCheckRun.objects.for_team(self.team.id).create(
+ team=self.team,
+ suite_run=suite,
+ subject_type=SubjectType.VIEW,
+ subject_uuid=allowed.id,
+ subject_name="customers",
+ check_type=CheckType.CUSTOM_SQL,
+ check_config=reads_orders,
+ referenced_subjects=self._pinned(self.view),
+ check_fingerprint=uuid4().hex,
+ status=CheckRunStatus.FAILED,
+ failed_row_count=3,
+ compiled_query="SELECT * FROM orders",
+ )
+ self._deny_the_view()
+ self.view.delete()
+ self._make_view("orders")
+
+ response = self.client.get(f"{self._suite_runs_url(allowed.id)}/{suite.id}/check_runs/")
+
+ assert response.status_code == status.HTTP_200_OK
+ assert response.json() == []
+
+ def test_a_run_that_read_an_allowed_subject_stays_visible_to_a_restricted_member(self) -> None:
+ # Failing closed on identity must not swallow the history a restricted member may read: the
+ # run pinned a view they are allowed, so being denied a different one changes nothing here.
+ allowed = self._make_view("customers")
+ suite = DataQualitySuiteRun.objects.for_team(self.team.id).create(
+ team=self.team, trigger="manual", subject_type=SubjectType.VIEW, subject_uuid=allowed.id
+ )
+ DataQualityCheckRun.objects.for_team(self.team.id).create(
+ team=self.team,
+ suite_run=suite,
+ subject_type=SubjectType.VIEW,
+ subject_uuid=allowed.id,
+ subject_name="customers",
+ check_type=CheckType.CUSTOM_SQL,
+ check_config={"query": "SELECT 1 FROM customers"},
+ referenced_subjects=self._pinned(allowed),
+ check_fingerprint=uuid4().hex,
+ status=CheckRunStatus.FAILED,
+ failed_row_count=3,
+ )
+ self._deny_the_view()
+
+ response = self.client.get(f"{self._suite_runs_url(allowed.id)}/{suite.id}/check_runs/")
+
+ assert response.status_code == status.HTTP_200_OK
+ assert [row["check_type"] for row in response.json()] == [CheckType.CUSTOM_SQL]
+
@parameterized.expand(
[
("run", lambda self, url, check: self.client.post(f"{url}/{check.id}/run/")),
diff --git a/products/data_quality/backend/tests/test_runner.py b/products/data_quality/backend/tests/test_runner.py
index be55b26caadc..5fa6bbefc11d 100644
--- a/products/data_quality/backend/tests/test_runner.py
+++ b/products/data_quality/backend/tests/test_runner.py
@@ -272,6 +272,32 @@ class TestCheckRunner(BaseTest):
run = DataQualityCheckRun.objects.for_team(self.team.id).get(quality_check=check)
assert run.check_config == {"min": 1}
assert run.check_severity == CheckSeverity.WARN
+ # An empty list, never null: a type that cannot reach past its own subject has to read as
+ # "read nothing" rather than as history nobody can judge.
+ assert run.referenced_subjects == []
+
+ @parameterized.expand([("custom_sql", CheckType.CUSTOM_SQL), ("relationships", CheckType.RELATIONSHIPS)])
+ def test_a_run_pins_the_subjects_it_read_beyond_its_own(self, _name, check_type: CheckType) -> None:
+ # Recording the name would stop naming what the run read the moment the object is deleted and
+ # somebody takes the name back, which is how history over a denied subject gets handed over.
+ target = DataWarehouseSavedQuery.objects.create(
+ team=self.team, name="customers", query={"kind": "HogQLQuery", "query": "SELECT 1 AS id"}
+ )
+ is_custom_sql = check_type == CheckType.CUSTOM_SQL
+ check = self._check(
+ check_type=check_type,
+ column_name="" if is_custom_sql else "customer_id",
+ config=(
+ {"query": "SELECT 1 FROM customers"}
+ if is_custom_sql
+ else {"to_subject_type": SubjectType.VIEW, "to_subject_uuid": str(target.id), "to_column": "id"}
+ ),
+ )
+ with patch(RUNNER_QUERY, return_value=_Response(["failure_count", "observed_value"], [0, 0])):
+ run_check(check, self.suite_run, self.team)
+
+ run = DataQualityCheckRun.objects.for_team(self.team.id).get(quality_check=check)
+ assert run.referenced_subjects == [{"subject_type": SubjectType.VIEW, "subject_uuid": str(target.id)}]
@parameterized.expand([("custom_sql", CheckType.CUSTOM_SQL), ("relationships", CheckType.RELATIONSHIPS)])
def test_an_automated_referencing_check_without_an_author_errors_without_running(
diff --git a/products/warehouse_sources/backend/facade/api.py b/products/warehouse_sources/backend/facade/api.py
index 8909eb3e5d28..25abe2308425 100644
--- a/products/warehouse_sources/backend/facade/api.py
+++ b/products/warehouse_sources/backend/facade/api.py
@@ -43,6 +43,7 @@ from products.warehouse_sources.backend.models.table import DataWarehouseTable a
# Framework-free helper transforms — re-exported as the public helper surface.
from products.warehouse_sources.backend.models.util import (
clickhouse_columns_to_dwh_columns,
+ get_view_or_table_by_name as _get_view_or_table_by_name,
motherduck_columns_to_dwh_columns,
mysql_column_to_dwh_column,
mysql_columns_to_dwh_columns,
@@ -67,6 +68,7 @@ __all__ = [
"source_locations_for_tables",
"get_table",
"get_queryable_table",
+ "resolve_object_by_name",
"list_tables_for_source",
"list_jobs_for_source",
"list_column_statistics",
@@ -331,6 +333,27 @@ def get_queryable_table(table_id: UUID, team_id: int) -> contracts.DataWarehouse
return _to_table(table) if table is not None else None
+def resolve_object_by_name(team_id: int, name: str) -> contracts.WarehouseObjectRef | None:
+ """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.
+
+ For a caller recording what a query read: the identity survives the name being freed and taken
+ by something else, which is what makes it usable as evidence later.
+ """
+ resolved = _get_view_or_table_by_name(team_id, name)
+ if resolved is None:
+ return None
+ kind = (
+ contracts.WAREHOUSE_OBJECT_TABLE
+ if isinstance(resolved, _DataWarehouseTable)
+ else contracts.WAREHOUSE_OBJECT_VIEW
+ )
+ return contracts.WarehouseObjectRef(kind=kind, id=resolved.id)
+
+
def list_tables_for_source(source_id: UUID, team_id: int) -> list[contracts.DataWarehouseTable]:
qs = _DataWarehouseTable.objects.filter(team_id=team_id, external_data_source_id=source_id).exclude(deleted=True)
return [_to_table(t) for t in qs]
diff --git a/products/warehouse_sources/backend/facade/contracts.py b/products/warehouse_sources/backend/facade/contracts.py
index 4343349a4ea5..7ca2d6af76ec 100644
--- a/products/warehouse_sources/backend/facade/contracts.py
+++ b/products/warehouse_sources/backend/facade/contracts.py
@@ -145,6 +145,22 @@ class TableSourceLocation:
schema_id: UUID
+WAREHOUSE_OBJECT_TABLE = "table"
+WAREHOUSE_OBJECT_VIEW = "view"
+
+
+@dataclass(frozen=True)
+class WarehouseObjectRef:
+ """Which warehouse object a queryable name resolves to, for a caller that must record identity.
+
+ ``kind`` is ``WAREHOUSE_OBJECT_TABLE`` or ``WAREHOUSE_OBJECT_VIEW``, since a name reaches either
+ a warehouse table or a saved query and the two are stored apart.
+ """
+
+ kind: str
+ id: UUID
+
+
# --- Job ---