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): resolve subject denial from the subjects themselves (#86830)

Thiago Salvatore7ae03826e8d2
diff --git a/posthog/hogql/database/schema/information_schema.py b/posthog/hogql/database/schema/information_schema.py
index 4649cf6c18b5..b67afbeb95cb 100644
--- a/posthog/hogql/database/schema/information_schema.py
+++ b/posthog/hogql/database/schema/information_schema.py
@@ -1050,9 +1050,7 @@ def _can_read_data_quality(context: "HogQLContext") -> bool:
reading them is warehouse read access (either resource resolves through warehouse_objects).
Fails closed with no access-control context (service tokens, shared links).
"""
- access_control = context.database.user_access_control if context.database is not None else None
- if access_control is None:
- access_control = context.user_access_control
+ access_control = _access_control(context)
if access_control is None:
return False
return access_control.check_access_level_for_resource(
@@ -1060,6 +1058,78 @@ def _can_read_data_quality(context: "HogQLContext") -> bool:
) or access_control.check_access_level_for_resource("warehouse_table", "viewer")
+def _access_control(context: "HogQLContext") -> Any:
+ """The caller's access control, preferring the one the database was built with."""
+ from_database = context.database.user_access_control if context.database is not None else None
+ return from_database if from_database is not None else context.user_access_control
+
+
+def _denial_applies(context: "HogQLContext", denied: set[str]) -> bool:
+ """Whether the data quality gates have anything to decide for this caller.
+
+ A non-empty denial set settles it. So does an empty one held by a member of an organization with
+ access controls, because deleting the subject they were denied is what empties it -- which is the
+ case the gates withhold for. Only a caller who could never be denied a single object skips them.
+ """
+ from products.data_quality.backend.facade import api as data_quality # noqa: PLC0415
+
+ return bool(denied) or data_quality.can_be_object_denied(_access_control(context))
+
+
+def _visible_data_quality_checks(
+ context: "HogQLContext", team_id: int, checks: list[Any], denied: set[str]
+) -> list[Any]:
+ """The checks a caller may see, by the rule the REST surfaces apply.
+
+ A check is out of reach on any of three counts: its own subject is denied, the definition it
+ would run next reads one that is, or the run behind its ``last_status`` read one. The row is both
+ tenses at once, so the definition is judged by the names it resolves today and the run by the
+ identities it pinned.
+
+ Subject names come from the subjects themselves rather than the copy denormalized onto the check,
+ which only a run rewrites, so a rename cannot carry a denied subject back into a list.
+ """
+ from products.data_quality.backend.facade import api as data_quality # noqa: PLC0415
+
+ if not _denial_applies(context, denied):
+ return checks
+ recordings = data_quality.latest_run_recordings(team_id, [check.id for check in checks])
+ current_names = data_quality.resolve_subject_names(
+ team_id,
+ [
+ data_quality.subject_identity(check.subject_type, check.subject_uuid)
+ for check in checks
+ if check.subject_uuid
+ ]
+ + data_quality.pinned_subject_refs(recording.referenced_subjects for recording in recordings.values()),
+ )
+ return [
+ check
+ for check in checks
+ if not _references_denied_table(
+ [
+ current_names.get(
+ data_quality.subject_identity(check.subject_type, check.subject_uuid), check.subject_name
+ )
+ ],
+ denied,
+ )
+ and not data_quality.check_reads_denied_subject(team_id, check.check_type, check.config, denied)
+ and not _last_run_read_a_denied_subject(recordings.get(check.id), current_names, denied)
+ ]
+
+
+def _last_run_read_a_denied_subject(recording: Any, current_names: dict[Any, str], denied: set[str]) -> bool:
+ from products.data_quality.backend.facade import api as data_quality # noqa: PLC0415
+
+ # A check that never ran carries no verdict, so there is nothing here to authorize.
+ if recording is None:
+ return False
+ return data_quality.run_reads_unreadable_subject(
+ recording.check_type, recording.referenced_subjects, current_names, denied
+ )
+
+
def _data_quality_checks(context: "HogQLContext", allowed: Optional[frozenset[str]]) -> list[list[Any]]:
"""Load the team's data quality check definitions as information_schema rows (fail-soft).
@@ -1094,14 +1164,64 @@ def _data_quality_checks(context: "HogQLContext", allowed: Optional[frozenset[st
check.last_run_at.isoformat() if check.last_run_at else None,
check.created_at.isoformat(),
]
- for check in queryset
- if not _references_denied_table([check.subject_name], denied)
+ for check in _visible_data_quality_checks(context, team_id, list(queryset), denied)
]
except Exception:
logger.exception("information_schema: failed to load data quality checks", team_id=team_id)
return []
+def _without_denied_runs(team_id: int, runs: Any, denied: set[str]) -> Any:
+ """Exclude, in SQL, every run that read a subject the caller is denied.
+
+ A run is judged on the identities it pinned as it executed, by the same rule the REST routes
+ apply, so the two surfaces cannot come to different answers about the same run. Editing a check
+ therefore cannot rewrite what its history discloses, and deleting a subject cannot free its name
+ for something else to answer for it. A referencing run that pinned nothing predates the
+ recording and is withheld rather than assumed harmless.
+
+ Only the types that can read past their own subject reach the recording scan. A run of any other
+ type is readable whatever it recorded, and the aggregation this narrows runs over the team's
+ whole retained history before the window applies.
+ """
+ from products.data_quality.backend.facade import api as data_quality # noqa: PLC0415
+
+ subjects = set(runs.values_list("subject_type", "subject_uuid", "subject_name").distinct())
+ recordings = list(
+ runs.filter(check_type__in=data_quality.referencing_check_types())
+ .values_list("check_type", "referenced_subjects")
+ .distinct()
+ )
+ current_names = data_quality.resolve_subject_names(
+ team_id,
+ [data_quality.subject_identity(subject_type, subject_uuid) for subject_type, subject_uuid, _ in subjects]
+ + data_quality.pinned_subject_refs(recorded for _, recorded in recordings),
+ )
+ blocked_subjects = [
+ subject_uuid
+ for subject_type, subject_uuid, stamped in subjects
+ if _references_denied_table(
+ [current_names.get(data_quality.subject_identity(subject_type, subject_uuid), stamped)], denied
+ )
+ ]
+ if blocked_subjects:
+ runs = runs.exclude(subject_uuid__in=blocked_subjects)
+
+ blocked_recordings = Q()
+ for check_type, recorded in recordings:
+ if not data_quality.run_reads_unreadable_subject(check_type, recorded, current_names, denied):
+ continue
+ # A JSONField compares None against JSON null, not against the SQL NULL a run without a
+ # recording stores, so the two cases cannot share one lookup.
+ if recorded is None:
+ blocked_recordings |= Q(check_type=check_type, referenced_subjects__isnull=True)
+ else:
+ blocked_recordings |= Q(check_type=check_type, referenced_subjects=recorded)
+ if blocked_recordings:
+ runs = runs.exclude(blocked_recordings)
+ return runs
+
+
def _data_quality_check_runs(context: "HogQLContext", allowed: Optional[frozenset[str]]) -> list[list[Any]]:
"""Load the team's most recent check executions as information_schema rows (fail-soft).
@@ -1121,16 +1241,12 @@ def _data_quality_check_runs(context: "HogQLContext", allowed: Optional[frozense
base = base.filter(subject_name__in=allowed)
# Drop denied subjects in SQL (not by scanning rows in Python) so the window is a bounded
# LIMIT rather than a full-history scan that skips denied rows one by one. The distinct set of
- # subject names is small, so resolving which are denied is cheap; excluding them before the
- # window still drops denied rows before it applies.
- if denied:
- blocked = {
- name
- for name in base.values_list("subject_name", flat=True).distinct()
- if _references_denied_table([name], denied)
- }
- if blocked:
- base = base.exclude(subject_name__in=blocked)
+ # subjects and of referencing definitions is small, so deciding which are denied is cheap;
+ # excluding them before the window still drops denied rows before it applies.
+ # Never on the denied set alone: deleting the subject a caller was denied is what empties it,
+ # which is the case this withholds runs for.
+ if _denial_applies(context, denied):
+ base = _without_denied_runs(team_id, base, denied)
return [
[
str(run.id),
@@ -1173,9 +1289,7 @@ def _data_quality_health(context: "HogQLContext", allowed: Optional[frozenset[st
if allowed is not None:
checks_qs = checks_qs.filter(subject_name__in=allowed)
by_subject: dict[tuple[str, str], list[Any]] = defaultdict(list)
- for check in checks_qs:
- if _references_denied_table([check.subject_name], denied):
- continue
+ for check in _visible_data_quality_checks(context, team_id, list(checks_qs), denied):
# A hard-deleted subject has no id to key a rollup on, and its checks only skip.
if check.subject_uuid is None:
continue
diff --git a/products/data_modeling/backend/facade/api.py b/products/data_modeling/backend/facade/api.py
index 85ddc494a892..1082274a3da9 100644
--- a/products/data_modeling/backend/facade/api.py
+++ b/products/data_modeling/backend/facade/api.py
@@ -28,6 +28,7 @@ _LAZY = {
"get_saved_query_columns": "logic.saved_query_reads",
"get_saved_query_ids_for_nodes": "logic.saved_query_reads",
"get_saved_query_summary": "logic.saved_query_reads",
+ "saved_query_names": "logic.saved_query_reads",
"saved_query_materialized_at": "logic.saved_query_freshness",
"start_node_materialization": "logic.node_materialization",
"delete_dag_schedules": "logic.schedule_reconcile",
diff --git a/products/data_modeling/backend/logic/saved_query_reads.py b/products/data_modeling/backend/logic/saved_query_reads.py
index 070a79b3ee88..d6c05955ad38 100644
--- a/products/data_modeling/backend/logic/saved_query_reads.py
+++ b/products/data_modeling/backend/logic/saved_query_reads.py
@@ -55,6 +55,24 @@ def get_saved_query_summary(team_id: int, saved_query_id: UUID | str) -> SavedQu
)
+def saved_query_names(team_id: int, saved_query_ids: Iterable[UUID | str]) -> dict[str, str]:
+ """The current name of each saved query that still resolves. One query; anything gone is absent.
+
+ The bulk form of ``get_saved_query_summary`` for a caller that only needs names, so authorizing
+ a page of stored references costs one query rather than one per reference. Soft-deleted rows are
+ excluded for the same reason: ``soft_delete`` rewrites ``name`` to a tombstone.
+ """
+ ids = [str(saved_query_id) for saved_query_id in saved_query_ids]
+ if not ids:
+ return {}
+ rows = (
+ DataWarehouseSavedQuery.objects.filter(team_id=team_id, id__in=ids)
+ .exclude(deleted=True)
+ .values_list("id", "name")
+ )
+ return {str(saved_query_id): name for saved_query_id, name in rows}
+
+
def get_materialized_table_uri(team_id: int, saved_query_id: UUID | str) -> str | None:
"""The S3 Delta table a materialized view's rows live in, for a consumer that reads them directly.
diff --git a/products/data_quality/backend/facade/api.py b/products/data_quality/backend/facade/api.py
index 05c4e54adcbf..490b5483d7b6 100644
--- a/products/data_quality/backend/facade/api.py
+++ b/products/data_quality/backend/facade/api.py
@@ -8,10 +8,12 @@ data. ORM model classes never cross here either -- ``facade/models.py`` is their
"""
from ..logic.checks import (
+ RunRecording,
checks_for_subject,
edit_check,
empty_check_suite,
ensure_name_available,
+ latest_run_recordings,
soft_delete_check,
start_check_suite,
subject_health,
@@ -20,7 +22,7 @@ from ..logic.checks import (
)
from ..logic.compiler import compile_check, related_subject_ref
from ..logic.config import get_gate_config, set_gate_materialization_on_checks
-from ..logic.contracts import CompiledCheck, SubjectRef
+from ..logic.contracts import CompiledCheck, SubjectIdentity, SubjectRef
from ..logic.errors import CheckConfigError, CheckEditConflict, SubjectUnresolvableError
from ..logic.health import CheckStatusRow, roll_up_health
from ..logic.navigation import SubjectKey, SubjectLocation, subject_locations
@@ -28,17 +30,21 @@ 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 (
- PinnedSubject,
ReferencedSubjects,
+ can_be_object_denied,
+ check_reads_denied_subject,
check_type_reads_beyond_subject,
denied_subject_names,
is_subject_denied,
+ pinned_subject_refs,
pinned_subjects,
referenced_subject_names,
referenced_subjects,
+ referencing_check_types,
+ run_reads_unreadable_subject,
unconfirmable_subject_names,
)
-from ..logic.subjects import resolve_subject
+from ..logic.subjects import resolve_subject, resolve_subject_names, subject_identity
from ..logic.triggers import materialization_audit_mode as quality_audit_mode
from .contracts import CheckTypeInfo
@@ -48,13 +54,16 @@ __all__ = [
"CheckStatusRow",
"CheckTypeInfo",
"CompiledCheck",
- "PinnedSubject",
"ReferencedSubjects",
+ "RunRecording",
+ "SubjectIdentity",
"SubjectKey",
"SubjectLocation",
"SubjectRef",
"SubjectUnresolvableError",
"UnknownCheckTypeError",
+ "can_be_object_denied",
+ "check_reads_denied_subject",
"check_type_reads_beyond_subject",
"checks_for_subject",
"compile_check",
@@ -66,19 +75,25 @@ __all__ = [
"from_config_entry",
"get_gate_config",
"is_subject_denied",
+ "latest_run_recordings",
"list_check_types",
"notify_materialization_blocked",
+ "pinned_subject_refs",
"pinned_subjects",
"quality_audit_mode",
"referenced_subject_names",
"referenced_subjects",
+ "referencing_check_types",
"related_subject_ref",
"resolve_subject",
+ "resolve_subject_names",
"roll_up_health",
+ "run_reads_unreadable_subject",
"set_gate_materialization_on_checks",
"soft_delete_check",
"start_check_suite",
"subject_health",
+ "subject_identity",
"subject_locations",
"to_config_entry",
"unconfirmable_subject_names",
diff --git a/products/data_quality/backend/logic/checks.py b/products/data_quality/backend/logic/checks.py
index 7e92bed40827..86ac82590f55 100644
--- a/products/data_quality/backend/logic/checks.py
+++ b/products/data_quality/backend/logic/checks.py
@@ -6,6 +6,7 @@ here waits on a warehouse query.
"""
import asyncio
+from collections.abc import Iterable
from dataclasses import asdict
from datetime import UTC, datetime
from typing import Any
@@ -24,7 +25,7 @@ from posthog.temporal.common.client import sync_connect
from ..facade.contracts import CHECK_SUITE_WORKFLOW_NAME
from ..facade.enums import SubjectHealth, SubjectStatus, SubjectType, SuiteRunStatus, SuiteRunTrigger
-from ..models import DataQualityCheck, DataQualitySuiteRun
+from ..models import DataQualityCheck, DataQualityCheckRun, DataQualitySuiteRun
from .compiler import related_subject_ref
from .errors import DuplicateDefinitionError, NameConflictError, SubjectUnresolvableError
from .exceptions import CheckNameConflict
@@ -299,6 +300,37 @@ def checks_for_subject(
return queryset if include_deleted else queryset.filter(deleted=False)
+@frozen
+class RunRecording:
+ """What a run recorded about the subjects it read, for judging the row it is denormalized onto."""
+
+ check_type: str
+ referenced_subjects: list | None
+
+
+def latest_run_recordings(team_id: int, check_ids: Iterable[UUID]) -> dict[UUID, RunRecording]:
+ """What each of these checks last read, keyed by check. One query; a check never run is absent.
+
+ A check row is not purely a definition: its ``last_status`` and ``last_run_at`` come from this
+ run, so they report on whatever it read. Authorizing the row on the definition alone would serve
+ that verdict about a subject the caller was denied, once the definition stops naming it.
+ """
+ ids = list(check_ids)
+ if not ids:
+ return {}
+ latest = (
+ DataQualityCheckRun.objects.for_team(team_id)
+ .filter(quality_check_id__in=ids)
+ .order_by("quality_check_id", "-created_at")
+ .distinct("quality_check_id")
+ .values_list("quality_check_id", "check_type", "referenced_subjects")
+ )
+ return {
+ check_id: RunRecording(check_type=check_type, referenced_subjects=referenced)
+ for check_id, check_type, referenced in latest
+ }
+
+
def subject_health(team_id: int, subject_type: str, subject_uuid: str | UUID) -> SubjectHealth:
# Only enabled checks count toward health, matching the REST counts and the
# information_schema.data_quality_health table -- the three must never disagree.
diff --git a/products/data_quality/backend/logic/contracts.py b/products/data_quality/backend/logic/contracts.py
index 86b5006ac2b8..8d6c92682116 100644
--- a/products/data_quality/backend/logic/contracts.py
+++ b/products/data_quality/backend/logic/contracts.py
@@ -17,6 +17,19 @@ class Evaluation(StrEnum):
BOUNDS = "bounds"
+@dataclass(frozen=True)
+class SubjectIdentity:
+ """A subject named the way rows record it: by kind and id, never by name.
+
+ Names move. A rename rewrites one, and deleting an object frees its name for anything else to
+ take, so authorization that has to survive either keys off this instead. Hashable, so a page of
+ them resolves to current names in one lookup.
+ """
+
+ subject_type: str
+ subject_uuid: str
+
+
@dataclass(frozen=True)
class SubjectRef:
"""A resolved check subject.
diff --git a/products/data_quality/backend/logic/subject_access.py b/products/data_quality/backend/logic/subject_access.py
index 3ab15087569b..4905d33c45f3 100644
--- a/products/data_quality/backend/logic/subject_access.py
+++ b/products/data_quality/backend/logic/subject_access.py
@@ -7,7 +7,9 @@ history, or health rollup -- those carry the compiled ``config``, failed-row cou
values, which together act as a count oracle over rows the member cannot read directly.
"""
+from collections.abc import Iterable, Mapping
from typing import TYPE_CHECKING, Any, Optional
+from uuid import UUID
from posthog.hogql.database.database import Database
from posthog.hogql.database.schema.information_schema import _references_denied_table
@@ -15,6 +17,8 @@ from posthog.hogql.database.schema.information_schema import _references_denied_
from posthog.dataclasses import frozen
from posthog.exceptions_capture import capture_exception
+from ..facade.enums import SubjectType
+from .contracts import SubjectIdentity
from .registry import all_specs, get_spec
from .spec import CheckTypeSpec
from .subjects import resolve_subject, resolve_subject_by_name
@@ -41,6 +45,21 @@ def is_subject_denied(subject_name: str, denied: set[str]) -> bool:
return _references_denied_table([subject_name], denied)
+def can_be_object_denied(user_access_control: Optional["UserAccessControl"]) -> bool:
+ """Whether object-level warehouse denial can apply to this caller at all.
+
+ False for an org admin, or an organization without access controls: neither can be denied a
+ single table or view, so an empty denial set is proof of access rather than missing data. For
+ everyone else the set can also be empty *because* the subject they were denied was deleted, so
+ this -- never the emptiness of the set -- decides whether a gate applies.
+ """
+ return (
+ user_access_control is not None
+ and not user_access_control.is_organization_admin
+ and user_access_control.access_controls_supported
+ )
+
+
# A check type reads beyond its declared subject only if it overrides one of these hooks: a
# ``relationships`` check names a target subject, a ``custom_sql`` query selects arbitrary tables.
# Derived from the specs rather than hard-coded so a new referencing type can't silently slip the net.
@@ -116,14 +135,6 @@ def referenced_subject_names(team_id: int, check_type: str, config: dict[str, An
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"
@@ -146,36 +157,75 @@ def pin_referenced_subjects(team_id: int, check_type: str, config: dict[str, Any
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])))
+ pinned.append(SubjectIdentity(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:
+def pinned_subjects(recorded: Any) -> list[SubjectIdentity] | 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."""
+ recording cannot be trusted falls back to the same type-based rule as one predating it. An
+ entry is only judgeable if it can be resolved, so the type and the id are validated here rather
+ than left to raise on whichever surface reads the column."""
if not isinstance(recorded, list):
return None
- subjects = []
+ subjects: list[SubjectIdentity] = []
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))
+ if not _is_resolvable(subject_type, subject_uuid):
+ return None
+ subjects.append(SubjectIdentity(subject_type=subject_type, subject_uuid=subject_uuid))
return subjects
-def _pin_name(team_id: int, name: str) -> PinnedSubject | None:
+def pinned_subject_refs(recordings: Iterable[Any]) -> list[SubjectIdentity]:
+ """Every identity across these recordings, for one bulk name resolution over a page of runs."""
+ return [subject for recorded in recordings for subject in pinned_subjects(recorded) or []]
+
+
+def run_reads_unreadable_subject(
+ check_type: str, recorded: Any, current_names: Mapping[SubjectIdentity, str], denied: set[str]
+) -> bool:
+ """Whether a recorded run read a subject the caller cannot be shown to be allowed.
+
+ The one test every surface serving run history applies, so the REST routes and the
+ ``information_schema`` loaders cannot come to different answers about the same run. Judged from
+ the identities the run pinned as it executed: never from the definition its check carries now,
+ which an edit rewrites, and never from names, which deleting an object frees for anyone to take.
+
+ A subject missing from ``current_names`` no longer resolves, and took its denial with it, so
+ nothing left can show the caller was allowed it. A run that pinned nothing predates the
+ recording and is judged by its type instead: one that cannot read past its own subject read only
+ the subject this surface already authorized, and anything that can is withheld.
+ """
+ pinned = pinned_subjects(recorded)
+ if pinned is None:
+ return check_type_reads_beyond_subject(check_type)
+ return any((name := current_names.get(subject)) is None or is_subject_denied(name, denied) for subject in pinned)
+
+
+def _is_resolvable(subject_type: str, subject_uuid: str) -> bool:
+ try:
+ SubjectType(subject_type)
+ UUID(subject_uuid)
+ except ValueError:
+ return False
+ return True
+
+
+def _pin_name(team_id: int, name: str) -> SubjectIdentity | 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)
+ return SubjectIdentity(subject_type=str(ref.subject_type), subject_uuid=ref.subject_uuid)
def unconfirmable_subject_names(
diff --git a/products/data_quality/backend/logic/subjects.py b/products/data_quality/backend/logic/subjects.py
index e9300e4a8c64..286f33d9cccd 100644
--- a/products/data_quality/backend/logic/subjects.py
+++ b/products/data_quality/backend/logic/subjects.py
@@ -6,6 +6,7 @@ cross the product boundary. A subject that no longer resolves marks the check or
denormalized name is refreshed on every run so renames self-heal.
"""
+from collections.abc import Iterable
from uuid import UUID
from products.data_modeling.backend.facade import api as data_modeling_facade
@@ -13,7 +14,7 @@ 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
+from .contracts import SubjectIdentity, SubjectRef
_WAREHOUSE_OBJECT_SUBJECT_TYPES = {
WAREHOUSE_OBJECT_TABLE: SubjectType.TABLE,
@@ -75,6 +76,32 @@ def _resolve_view(team_id: int, subject_uuid: str | UUID) -> SubjectRef:
)
+def resolve_subject_names(team_id: int, subjects: Iterable[SubjectIdentity]) -> dict[SubjectIdentity, str]:
+ """The current name of every subject that still resolves, keyed by identity. Two queries.
+
+ Authorization has to read the name the subject carries *now*, because denial is computed from
+ the names that exist today. The name denormalized onto a check is only rewritten when the check
+ runs, so a subject renamed since would otherwise stop matching its own denial. A subject that no
+ longer resolves is absent rather than empty, so a caller can tell the two apart.
+ """
+ wanted = set(subjects)
+ view_ids = [subject.subject_uuid for subject in wanted if subject.subject_type == SubjectType.VIEW]
+ table_ids = [UUID(subject.subject_uuid) for subject in wanted if subject.subject_type == SubjectType.TABLE]
+
+ names: dict[SubjectIdentity, str] = {
+ SubjectIdentity(subject_type=SubjectType.VIEW.value, subject_uuid=saved_query_id): name
+ for saved_query_id, name in data_modeling_facade.saved_query_names(team_id, view_ids).items()
+ }
+ for table_id, name in warehouse_facade.queryable_table_names(team_id, table_ids).items():
+ names[SubjectIdentity(subject_type=SubjectType.TABLE.value, subject_uuid=str(table_id))] = name
+ return names
+
+
+def subject_identity(subject_type: str, subject_uuid: str | UUID) -> SubjectIdentity:
+ """The identity of a subject as a row records it, from whichever form the caller holds."""
+ return SubjectIdentity(subject_type=str(subject_type), subject_uuid=str(subject_uuid))
+
+
def subject_column_type(team_id: int, subject_type: str, subject_uuid: str | UUID, column_name: str) -> str | None:
"""The column's ClickHouse type, or None when the subject or the column cannot be established.
diff --git a/products/data_quality/backend/presentation/views.py b/products/data_quality/backend/presentation/views.py
index b30b1162d9de..79111707cfeb 100644
--- a/products/data_quality/backend/presentation/views.py
+++ b/products/data_quality/backend/presentation/views.py
@@ -7,12 +7,13 @@ 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
from uuid import UUID
-from django.db.models import QuerySet
+from django.db.models import Q, QuerySet
from drf_spectacular.types import OpenApiTypes
from drf_spectacular.utils import OpenApiParameter, extend_schema, extend_schema_view
@@ -48,6 +49,26 @@ from .serializers import (
_RECENT_RUNS_LIMIT = 50
+# An empty Q() matches every row, so an exclusion built by ORing clauses has to start from one that
+# matches none, or a page with nothing to withhold would withhold all of it.
+_MATCHES_NOTHING = Q(pk__in=[])
+
+
+def _current_subject_name(check: DataQualityCheck, current_names: dict[api.SubjectIdentity, str]) -> str:
+ # A hard-deleted subject nulls the FK, leaving nothing to resolve and only the name the last run
+ # stamped on the check.
+ if check.subject_uuid is None:
+ return check.subject_name
+ return current_names.get(api.subject_identity(check.subject_type, check.subject_uuid), check.subject_name)
+
+
+def _matches_recording(check_type: str, recorded: list | None) -> Q:
+ # A JSONField compares None against JSON null, not against the SQL NULL a run without a
+ # recording stores, so the two cases cannot share one lookup.
+ if recorded is None:
+ return Q(check_type=check_type, referenced_subjects__isnull=True)
+ return Q(check_type=check_type, referenced_subjects=recorded)
+
class _QualityGatedViewSet(TeamAndOrgViewSetMixin):
"""The gating every data quality surface shares, whether or not it is nested under a subject.
@@ -89,13 +110,9 @@ class _QualityGatedViewSet(TeamAndOrgViewSetMixin):
raise PermissionDenied("You need query access to work with data quality checks.")
def _can_be_object_denied(self) -> bool:
- """Whether object-level warehouse denials can apply to this caller at all.
-
- False for an org admin, or an organization without access controls: neither can be denied a
- single table or view, so an empty denial set is proof of access rather than missing data.
- """
- uac = self.user_access_control
- return uac is not None and not uac.is_organization_admin and uac.access_controls_supported
+ # Shared with the information_schema loaders, so the two surfaces agree on which callers a
+ # gate applies to as well as on what it decides.
+ return api.can_be_object_denied(self.user_access_control)
def _denied_subject_names(self) -> set[str]:
# Same denial the information_schema loaders read. Computed once per request.
@@ -133,6 +150,19 @@ class _QualityGatedViewSet(TeamAndOrgViewSetMixin):
with it, so a name that neither resolves nor is denied proves nothing either way and is
refused on the same fail-closed terms.
"""
+ # A type that cannot read past its own subject has nothing here to authorize. The verdict on
+ # one that can is a pure function of its definition, so a project-wide page parses and
+ # resolves each distinct definition once rather than once per check carrying it.
+ if not api.check_type_reads_beyond_subject(check_type):
+ return False
+ cache: dict[str, bool] = getattr(self, "_reads_unreadable_cache", {})
+ self._reads_unreadable_cache = cache
+ key = json.dumps([check_type, config], sort_keys=True, default=str)
+ if key not in cache:
+ cache[key] = self._definition_reads_unreadable_subject(check_type, config)
+ return cache[key]
+
+ def _definition_reads_unreadable_subject(self, check_type: str, config: dict) -> bool:
refs = api.referenced_subjects(self.team.id, check_type, config)
if refs.unresolved_reference:
return True
@@ -162,48 +192,84 @@ class _QualityGatedViewSet(TeamAndOrgViewSetMixin):
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 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 _denied_checks(self, checks: list[DataQualityCheck], denied: set[str]) -> set[UUID]:
+ """The ids of the checks this caller may not see, over a page of them.
- def _run_is_readable(self, run: DataQualityCheckRun) -> bool:
- """Whether every subject this run read is one the caller may read now.
+ A check is out of reach on any of three counts: its own subject is denied, the definition it
+ would run next reads one that is, or the run behind its ``last_status`` read one. The row is
+ both tenses at once -- a definition and the verdict of a past run -- so each is judged by the
+ rule for its own tense, the definition by the names it resolves today and the run by the
+ identities it pinned.
- 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.
+ Subject names come from the subjects themselves rather than from the copy denormalized onto
+ the check, which only a run rewrites, so a rename cannot carry a denied subject back into a
+ list.
"""
- 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]
+ recordings = api.latest_run_recordings(self.team_id, [check.id for check in checks])
+ subjects = [
+ api.subject_identity(check.subject_type, check.subject_uuid) for check in checks if check.subject_uuid
+ ]
+ subjects += api.pinned_subject_refs(recording.referenced_subjects for recording in recordings.values())
+ current_names = api.resolve_subject_names(self.team_id, subjects)
+ return {
+ check.id
+ for check in checks
+ if api.is_subject_denied(_current_subject_name(check, current_names), denied)
+ or self._reads_unreadable_subject(check.check_type, check.config)
+ or self._last_run_read_an_unreadable_subject(recordings.get(check.id), current_names, denied)
+ }
- 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:
+ def _last_run_read_an_unreadable_subject(
+ self, recording: api.RunRecording | None, current_names: dict[api.SubjectIdentity, str], denied: set[str]
+ ) -> bool:
+ # A check that never ran carries no verdict, so there is nothing here to authorize.
+ if recording is None:
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())
+ return api.run_reads_unreadable_subject(
+ recording.check_type, recording.referenced_subjects, current_names, denied
+ )
+
+ def _denied_definitions(self, runs: QuerySet[DataQualityCheckRun]) -> Q:
+ """Match the runs that read a subject the caller is denied.
+
+ Keyed on the identities each run pinned, so the suites reporting on it are withheld by the
+ same rule the routes serving it apply. Each distinct recording is judged once and every
+ identity resolves in one pass. A referencing run that pinned nothing is matched too, since
+ what it read cannot be established.
+
+ Only the types that can read past their own subject reach the scan. A run of any other type
+ pinned an empty list, or pinned nothing and falls back to its type, so it is readable
+ whatever it recorded -- and the aggregation this narrows runs over the team's whole history.
+ """
+ runs = runs.filter(check_type__in=api.referencing_check_types())
+ recordings = list(runs.values_list("check_type", "referenced_subjects").distinct())
+ current_names = api.resolve_subject_names(
+ self.team_id, api.pinned_subject_refs(recorded for _, recorded in recordings)
+ )
+ denied = self._denied_subject_names()
+ matched = _MATCHES_NOTHING
+ for check_type, recorded in recordings:
+ if api.run_reads_unreadable_subject(check_type, recorded, current_names, denied):
+ matched |= _matches_recording(check_type, recorded)
+ return matched
+
+ def _readable_runs(self, runs: list[DataQualityCheckRun]) -> list[DataQualityCheckRun]:
+ """Drop the runs that read a subject the caller cannot be shown to be allowed.
+
+ Every identity in the page resolves in one pass rather than one query per run, since a
+ suite re-runs the same checks over the same subjects.
+ """
+ if not self._can_be_object_denied():
+ return runs
+ current_names = api.resolve_subject_names(
+ self.team_id, api.pinned_subject_refs(run.referenced_subjects for run in runs)
+ )
+ denied = self._denied_subject_names()
+ return [
+ run
+ for run in runs
+ if not api.run_reads_unreadable_subject(run.check_type, run.referenced_subjects, current_names, denied)
+ ]
class _SubjectScopedViewSet(_QualityGatedViewSet):
@@ -270,6 +336,18 @@ class _BaseCheckViewSet(_SubjectScopedViewSet, AccessControlViewSetMixin, viewse
queryset = queryset.filter(check_type=check_type)
return queryset.order_by("-created_at")
+ def filter_queryset(self, queryset: QuerySet[DataQualityCheck]) -> QuerySet[DataQualityCheck]:
+ # The parent gate cleared this subject, but a check under it can read a second one. Its
+ # config names that subject, and its status answers questions about the rows behind it.
+ queryset = super().filter_queryset(queryset)
+ # Listing only. The routes that address one check keep answering 403 with what is wrong,
+ # which tells the caller more than the 404 that hiding the row would give them.
+ if self.action != "list":
+ return queryset
+ if not self._can_be_object_denied():
+ return queryset
+ return queryset.exclude(id__in=self._denied_checks(list(queryset), self._denied_subject_names()))
+
def get_serializer_context(self) -> dict:
return {
**super().get_serializer_context(),
@@ -362,7 +440,7 @@ class _BaseCheckViewSet(_SubjectScopedViewSet, AccessControlViewSetMixin, viewse
def run_all(self, request: Request, **kwargs) -> Response:
# Each of the subject's checks may read a further subject the member is denied, so gate on
# those too before running the batch. Only a restricted member has anything to check.
- if self._denied_subject_names():
+ if self._can_be_object_denied():
for check in api.checks_for_subject(self.team_id, self.subject_type, self.subject_uuid).filter(
enabled=True
):
@@ -399,16 +477,23 @@ class _BaseCheckViewSet(_SubjectScopedViewSet, AccessControlViewSetMixin, viewse
)
@action(methods=["GET"], detail=False, pagination_class=None)
def health(self, request: Request, **kwargs) -> Response:
- checks = api.checks_for_subject(self.team_id, self.subject_type, self.subject_uuid).filter(enabled=True)
- failing = checks.filter(last_status=CheckRunStatus.FAILED)
+ # A rollup counts the checks it covers, so it has to cover the same ones the list serves.
+ # Rolled up from the rows that survive rather than through subject_health(), which would go
+ # back to the database and count the withheld ones straight back in.
+ checks = list(api.checks_for_subject(self.team_id, self.subject_type, self.subject_uuid).filter(enabled=True))
+ if self._can_be_object_denied():
+ withheld = self._denied_checks(checks, self._denied_subject_names())
+ checks = [check for check in checks if check.id not in withheld]
return Response(
SubjectHealthSerializer(
{
"subject_type": self.subject_type,
"subject_uuid": self.subject_uuid,
- "health": api.subject_health(self.team_id, self.subject_type, self.subject_uuid),
- "checks_total": checks.count(),
- "checks_failing": failing.count(),
+ "health": api.roll_up_health(
+ api.CheckStatusRow(severity=check.severity, last_status=check.last_status) for check in checks
+ ),
+ "checks_total": len(checks),
+ "checks_failing": sum(1 for check in checks if check.last_status == CheckRunStatus.FAILED),
}
).data
)
@@ -453,6 +538,27 @@ class _BaseSuiteRunViewSet(
# information_schema, which is the cross-subject surface.
return queryset.filter(team_id=self.team_id).order_by("-created_at")
+ def filter_queryset(self, queryset: QuerySet[DataQualitySuiteRun]) -> QuerySet[DataQualitySuiteRun]:
+ """Withhold the suites whose executions read a subject the caller is denied.
+
+ The parent gate clears the declared subject, but a suite row carries passed/failed/errored/
+ skipped over every check it ran, while ``check_runs`` hands back only the readable ones.
+ Serving both names the withheld check's outcome by subtraction.
+ """
+ queryset = super().filter_queryset(queryset)
+ # check_runs is left alone on purpose: it already drops the individual runs that read a
+ # denied subject, and hiding the suite there would take the readable runs down with them.
+ if self.action not in ("list", "retrieve"):
+ return queryset
+ if not self._can_be_object_denied():
+ return queryset
+ # Only the runs behind the suites this parent serves, so answering for one subject does not
+ # walk the project's whole history.
+ runs = DataQualityCheckRun.objects.for_team(self.team_id).filter(
+ suite_run_id__in=queryset.order_by().values("id")
+ )
+ return queryset.exclude(id__in=runs.filter(self._denied_definitions(runs)).values("suite_run_id"))
+
@extend_schema(
description="Every check execution in this suite run.",
responses={200: DataQualityCheckRunSerializer(many=True)},
@@ -540,11 +646,9 @@ class DataQualityCheckOverviewViewSet(
# matched by name rather than equality, so the pass has to happen in Python; only a
# restricted member pays for it, since the denied set is empty for everyone else.
queryset = super().filter_queryset(queryset)
- denied = self._denied_subject_names()
- if not denied:
+ if not self._can_be_object_denied():
return queryset
- hidden = [check.id for check in queryset if api.is_subject_denied(check.subject_name, denied)]
- return queryset.exclude(id__in=hidden)
+ return queryset.exclude(id__in=self._denied_checks(list(queryset), self._denied_subject_names()))
@extend_schema(
description="Health rollup for every table and view in the project that has checks.",
@@ -608,40 +712,48 @@ class DataQualityRunViewSet(
either.
"""
queryset = super().filter_queryset(queryset)
- denied_uuids = self._denied_subject_uuids()
- if not denied_uuids:
+ if not self._can_be_object_denied():
return queryset
- covering_denied = (
- DataQualityCheckRun.objects.for_team(self.team_id)
- .filter(subject_uuid__in=denied_uuids)
- .values("suite_run_id")
- )
- return queryset.exclude(subject_uuid__in=denied_uuids).exclude(id__in=covering_denied)
+ runs = DataQualityCheckRun.objects.for_team(self.team_id)
+ denied_uuids = self._denied_subject_uuids()
+ if denied_uuids:
+ queryset = queryset.exclude(subject_uuid__in=denied_uuids).exclude(
+ id__in=runs.filter(subject_uuid__in=denied_uuids).values("suite_run_id")
+ )
+ # A run's declared subject is not the only one it read, so the same test the check routes
+ # apply to a definition has to reach the suites reporting on it.
+ return queryset.exclude(id__in=runs.filter(self._denied_definitions(runs)).values("suite_run_id"))
def _denied_subject_uuids(self) -> set[UUID]:
"""The ids of the subjects this caller is denied, as suite and check runs record them.
- Read from the names already denormalized onto checks and their runs rather than resolved one
- subject at a time, so a restricted member's page costs two queries instead of one per
- subject. That inherits the denormalized name's rename window, which every check-list surface
- shares.
+ Resolved from the subjects themselves rather than from the name denormalized onto a check,
+ so a subject renamed since its last run still matches its own denial.
"""
denied = self._denied_subject_names()
- if not denied:
- return set()
checks = DataQualityCheck.objects.for_team(self.team_id).values_list(
- "saved_query_id", "table_id", "subject_name"
+ "subject_type", "saved_query_id", "table_id", "subject_name"
)
- named_subjects = [(saved_query_id or table_id, name) for saved_query_id, table_id, name in checks]
+ stamped = {
+ api.subject_identity(subject_type, saved_query_id or table_id): name
+ for subject_type, saved_query_id, table_id, name in checks
+ if saved_query_id or table_id
+ }
# A hard-deleted check leaves its runs behind with the FK nulled, so its subject would drop
# out of the set above while its suites still report on it.
- named_subjects += (
- DataQualityCheckRun.objects.for_team(self.team_id)
+ stamped |= {
+ api.subject_identity(subject_type, subject_uuid): name
+ for subject_type, subject_uuid, name in DataQualityCheckRun.objects.for_team(self.team_id)
.filter(quality_check__isnull=True)
- .values_list("subject_uuid", "subject_name")
+ .values_list("subject_type", "subject_uuid", "subject_name")
.distinct()
- )
- return {uuid for uuid, name in named_subjects if uuid and api.is_subject_denied(name, denied)}
+ }
+ current_names = api.resolve_subject_names(self.team_id, stamped.keys())
+ return {
+ UUID(identity.subject_uuid)
+ for identity, name in stamped.items()
+ if api.is_subject_denied(current_names.get(identity, name), denied)
+ }
@extend_schema(
description="Run the named checks now, or every enabled check in the project when none are named. "
@@ -676,13 +788,22 @@ class DataQualityRunViewSet(
Naming a denied check is an attempt to read it, so it 403s the way the per-subject run does.
Sweeping the project is not: a denied subject is one the member cannot see at all, so its
checks are simply not part of "everything" for them.
+
+ This route is the one that actually executes a query against the subject, so it reads the
+ name from the subject itself like the listing routes do. Matching the copy stamped on the
+ check would let a table renamed since its last run be run against, and its pass/fail and
+ row counts read back.
"""
- denied = self._denied_subject_names()
- if not denied:
+ if not self._can_be_object_denied():
return checks
+ denied = self._denied_subject_names()
+ current_names = api.resolve_subject_names(
+ self.team_id,
+ [api.subject_identity(check.subject_type, check.subject_uuid) for check in checks if check.subject_uuid],
+ )
allowed = []
for check in checks:
- if api.is_subject_denied(check.subject_name, denied):
+ if api.is_subject_denied(_current_subject_name(check, current_names), denied):
if named:
raise PermissionDenied("You don't have access to a table or view this check reads.")
continue
diff --git a/products/data_quality/backend/tests/test_api.py b/products/data_quality/backend/tests/test_api.py
index 2dd37697ac80..22f3d66fc064 100644
--- a/products/data_quality/backend/tests/test_api.py
+++ b/products/data_quality/backend/tests/test_api.py
@@ -519,6 +519,49 @@ 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_listing_a_subjects_checks_leaves_out_the_ones_reading_a_denied_subject(self) -> None:
+ # The parent gate cleared "customers", but a check under it names the denied "orders" in its
+ # config, which the routes that address one check already refuse to serve.
+ allowed = self._make_view("customers")
+ 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=CheckType.CUSTOM_SQL,
+ config={"query": "SELECT 1 FROM orders"},
+ fingerprint=uuid4().hex,
+ )
+ self._deny_the_view()
+
+ listed = self.client.get(f"{self._checks_url(allowed.id)}/")
+
+ assert listed.status_code == status.HTTP_200_OK, listed.json()
+ assert listed.json()["results"] == []
+
+ def test_a_subjects_health_leaves_out_the_checks_reading_a_denied_subject(self) -> None:
+ # The rollup counts the same checks the list serves, so one the list withholds must not be
+ # counted back in here: checks_failing answers the same question one step removed.
+ allowed = self._make_view("customers")
+ 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=CheckType.CUSTOM_SQL,
+ config={"query": "SELECT 1 FROM orders"},
+ fingerprint=uuid4().hex,
+ last_status=CheckRunStatus.FAILED,
+ )
+ self._deny_the_view()
+
+ health = self.client.get(f"{self._checks_url(allowed.id)}/health/")
+
+ assert health.status_code == status.HTTP_200_OK, health.json()
+ assert health.json()["checks_total"] == 0
+ assert health.json()["checks_failing"] == 0
+ assert health.json()["health"] == "unknown"
+
@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
@@ -743,6 +786,22 @@ class TestDataQualityCheckAPI(APIBaseTest):
assert response.status_code == status.HTTP_200_OK
assert sorted(row["check_type"] for row in response.json()) == sorted(expected_types)
+ def test_a_suite_whose_run_read_a_denied_subject_is_withheld(self) -> None:
+ # The suite row carries passed/failed/errored/skipped over every check it ran, while
+ # check_runs hands back only the readable ones. Serving both names the withheld check's
+ # outcome by subtraction, so the row with the counters is the one to hold back.
+ allowed = self._make_view("customers")
+ suite = self._suite_with_two_runs(allowed)
+ self._deny_the_view()
+
+ base = self._suite_runs_url(allowed.id)
+ listed = self.client.get(f"{base}/")
+ retrieved = self.client.get(f"{base}/{suite.id}/")
+
+ assert listed.status_code == status.HTTP_200_OK, listed.json()
+ assert listed.json()["results"] == []
+ assert retrieved.status_code == status.HTTP_404_NOT_FOUND
+
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
diff --git a/products/data_quality/backend/tests/test_information_schema.py b/products/data_quality/backend/tests/test_information_schema.py
index d7d9e2855c21..ca6168e752a6 100644
--- a/products/data_quality/backend/tests/test_information_schema.py
+++ b/products/data_quality/backend/tests/test_information_schema.py
@@ -14,6 +14,7 @@ from posthog.hogql.query import execute_hogql_query
from posthog.models.team import Team
+from products.data_modeling.backend.facade.models import DataWarehouseSavedQuery
from products.data_quality.backend.facade.enums import CheckRunStatus, CheckSeverity, CheckType, SubjectType
from products.data_quality.backend.models import DataQualityCheck, DataQualityCheckRun, DataQualitySuiteRun
@@ -170,6 +171,112 @@ class TestInformationSchemaDataQuality(ClickhouseTestMixin, APIBaseTest):
assert ("orders",) not in rows
assert ("customers",) in rows
+ @parameterized.expand(
+ [
+ ("checks", "SELECT subject_name FROM system.information_schema.data_quality_checks"),
+ ("check_runs", "SELECT subject_name FROM system.information_schema.data_quality_check_runs"),
+ ("health", "SELECT subject_name FROM system.information_schema.data_quality_health"),
+ ]
+ )
+ def test_a_denied_subject_renamed_since_its_last_run_stays_hidden(self, _name: str, sql: str) -> None:
+ # The name on the check is only rewritten when the check runs, so matching denial against it
+ # serves the subject's rows for the whole window between a rename and the next run.
+ renamed = DataWarehouseSavedQuery.objects.create(
+ team=self.team, name="orders", query={"kind": "HogQLQuery", "query": "SELECT 1 AS id"}
+ )
+ stale = self._check(subject_name="orders_legacy", saved_query_id=renamed.id)
+ self._run_for(stale)
+
+ rows = self._query(sql, context=self._context(denied_tables={"orders"}))
+
+ assert rows == []
+
+ @parameterized.expand(
+ [
+ ("checks", "SELECT subject_name FROM system.information_schema.data_quality_checks"),
+ ("check_runs", "SELECT subject_name FROM system.information_schema.data_quality_check_runs"),
+ ("health", "SELECT subject_name FROM system.information_schema.data_quality_health"),
+ ]
+ )
+ def test_a_check_reading_a_denied_subject_is_hidden_from_every_table(self, _name: str, sql: str) -> None:
+ # A check on an allowed parent still names the denied subject in its config, and its status
+ # answers questions about the rows behind it.
+ reader = self._check(
+ subject_name="customers",
+ saved_query_id=uuid4(),
+ check_type=CheckType.CUSTOM_SQL,
+ column_name="",
+ config={"query": "SELECT 1 FROM orders"},
+ )
+ self._run_for(reader, check_config=reader.config)
+
+ rows = self._query(sql, context=self._context(denied_tables={"orders"}))
+
+ assert rows == []
+
+ @parameterized.expand(
+ [
+ ("checks", "SELECT subject_name FROM system.information_schema.data_quality_checks"),
+ ("health", "SELECT subject_name FROM system.information_schema.data_quality_health"),
+ ]
+ )
+ def test_a_check_whose_last_run_read_a_recreated_subject_stays_hidden(self, _name: str, sql: str) -> None:
+ # A check row is not only a definition: last_status is the verdict of its last run, over
+ # whatever that run read. Once the subject it read is deleted and its name taken by something
+ # the caller may read, the definition stops naming anything denied while the verdict remains.
+ original = DataWarehouseSavedQuery.objects.create(
+ team=self.team, name="orders_original", query={"kind": "HogQLQuery", "query": "SELECT 1 AS id"}
+ )
+ original_id = original.id
+ original.delete()
+ reader = self._check(
+ subject_name="customers",
+ saved_query_id=self.subject_uuid,
+ check_type=CheckType.CUSTOM_SQL,
+ column_name="",
+ config={"query": "SELECT 1 FROM orders"},
+ last_status=CheckRunStatus.FAILED,
+ )
+ self._run_for(
+ reader,
+ check_config=reader.config,
+ referenced_subjects=[{"subject_type": str(SubjectType.VIEW), "subject_uuid": str(original_id)}],
+ )
+
+ rows = self._query(sql, context=self._context(denied_tables={"secrets"}))
+
+ assert rows == []
+
+ def test_a_run_whose_subject_was_recreated_under_the_same_name_stays_hidden(self) -> None:
+ # Deleting a warehouse object frees its name for anyone to take. Matched by the names in its
+ # definition, the run that read the original would be served here the moment something the
+ # caller can read answers to that name -- with its failed-row count over the original's rows.
+ original = DataWarehouseSavedQuery.objects.create(
+ team=self.team, name="orders_original", query={"kind": "HogQLQuery", "query": "SELECT 1 AS id"}
+ )
+ original_id = original.id
+ original.delete()
+ reader = self._check(
+ subject_name="customers",
+ saved_query_id=uuid4(),
+ check_type=CheckType.CUSTOM_SQL,
+ column_name="",
+ config={"query": "SELECT 1 FROM orders"},
+ )
+ self._run_for(
+ reader,
+ check_config=reader.config,
+ referenced_subjects=[{"subject_type": str(SubjectType.VIEW), "subject_uuid": str(original_id)}],
+ )
+
+ # A denial the caller still has, so the gate engages: an empty denied set skips it entirely.
+ rows = self._query(
+ "SELECT subject_name FROM system.information_schema.data_quality_check_runs",
+ context=self._context(denied_tables={"secrets"}),
+ )
+
+ assert rows == []
+
def test_the_tables_are_absent_when_the_catalog_flag_is_off(self) -> None:
with patch("products.data_quality.backend.facade.flags.is_data_quality_checks_enabled", return_value=False):
listing = self._query(
diff --git a/products/data_quality/backend/tests/test_runs_api.py b/products/data_quality/backend/tests/test_runs_api.py
index 1847ea2bed75..fbb4a2fbee69 100644
--- a/products/data_quality/backend/tests/test_runs_api.py
+++ b/products/data_quality/backend/tests/test_runs_api.py
@@ -9,6 +9,7 @@ from parameterized import parameterized
from rest_framework import status
from posthog.constants import AvailableFeature
+from posthog.test.db_context_capturing import capture_db_queries
from products.access_control.backend.models.access_control import AccessControl
from products.data_modeling.backend.facade.models import DataWarehouseSavedQuery
@@ -60,17 +61,21 @@ class TestDataQualityRunAPI(APIBaseTest):
return self.client.post(self.url, body, format="json")
def _deny_orders(self) -> None:
+ self._deny(self.orders)
+
+ def _deny(self, *views: DataWarehouseSavedQuery) -> None:
self.organization.available_product_features = [
{"key": AvailableFeature.ACCESS_CONTROL, "name": AvailableFeature.ACCESS_CONTROL}
]
self.organization.save(update_fields=["available_product_features"])
- AccessControl.objects.create(
- team=self.team,
- resource="warehouse_view",
- resource_id=str(self.orders.id),
- organization_member=self.organization_membership,
- access_level="none",
- )
+ for view in views:
+ AccessControl.objects.create(
+ team=self.team,
+ resource="warehouse_view",
+ resource_id=str(view.id),
+ organization_member=self.organization_membership,
+ access_level="none",
+ )
warehouse_ac = patch(
"posthog.hogql.database.database.feature_enabled_or_false",
side_effect=lambda name, *a, **k: name == "hogql-warehouse-access-control",
@@ -137,6 +142,25 @@ class TestDataQualityRunAPI(APIBaseTest):
assert response.status_code == status.HTTP_403_FORBIDDEN
+ @parameterized.expand([("named",), ("swept",)])
+ def test_a_denied_subject_renamed_since_its_last_run_is_still_not_run_against(self, case: str) -> None:
+ # This route is the one that actually executes the query, so matching denial against the name
+ # stamped on the check would run it against the denied view for the whole window after a
+ # rename, and hand the pass/fail and row counts back through the suite report.
+ denied = self._check(self.orders, subject_name="orders_legacy")
+ self._deny_orders()
+
+ with patch(START_SUITE) as connect:
+ body = {"check_ids": [str(denied.id)]} if case == "named" else {}
+ response = self.client.post(self.url, body, format="json")
+
+ if case == "named":
+ assert response.status_code == status.HTTP_403_FORBIDDEN
+ else:
+ assert response.status_code == status.HTTP_200_OK, response.json()
+ assert response.json()["status"] == "empty"
+ connect.assert_not_called()
+
def test_the_sweep_is_gated_on_the_feature_flag(self) -> None:
with patch(FLAG, return_value=False):
assert self.client.post(self.url, {}, format="json").status_code == status.HTTP_403_FORBIDDEN
@@ -182,6 +206,50 @@ class TestDataQualityRunAPI(APIBaseTest):
assert self.client.get(f"{self.url}{denied.id}/").status_code == status.HTTP_404_NOT_FOUND
assert self.client.get(f"{self.url}{sweep.id}/").status_code == status.HTTP_404_NOT_FOUND
+ def test_history_withholds_a_suite_whose_run_read_a_denied_subject(self) -> None:
+ # The run sits on the allowed subject, so its own uuid clears the filter. What it read is in
+ # the identities it pinned, and the counters report on those rows too.
+ suite_run = self._suite_reading(self.orders)
+ self._check(self.orders)
+ self._deny_orders()
+
+ listed = self.client.get(self.url)
+
+ assert [row["id"] for row in listed.json()["results"]] == []
+ assert self.client.get(f"{self.url}{suite_run.id}/").status_code == status.HTTP_404_NOT_FOUND
+
+ def test_history_withholds_a_suite_whose_subject_was_recreated_under_the_same_name(self) -> None:
+ # Deleting "orders" frees its name, so a member can create their own and make the name resolve
+ # for them again. Matched by name, the suite reporting on the run that read the original would
+ # list, carrying its counters over rows the member still cannot read.
+ secrets = self._make_view("secrets")
+ suite_run = self._suite_reading(self.orders)
+ self._deny(self.orders, secrets)
+ self.orders.delete()
+ self._make_view("orders")
+
+ listed = self.client.get(self.url)
+
+ assert [row["id"] for row in listed.json()["results"]] == []
+ assert self.client.get(f"{self.url}{suite_run.id}/").status_code == status.HTTP_404_NOT_FOUND
+
+ def _suite_reading(self, read: DataWarehouseSavedQuery) -> DataQualitySuiteRun:
+ """A suite whose one run sits on the allowed "customers" but read another subject."""
+ suite_run = DataQualitySuiteRun.objects.for_team(self.team.id).create(team=self.team, trigger="manual")
+ DataQualityCheckRun.objects.for_team(self.team.id).create(
+ team=self.team,
+ suite_run=suite_run,
+ subject_type=SubjectType.VIEW,
+ subject_uuid=self.customers.id,
+ subject_name="customers",
+ check_type=CheckType.CUSTOM_SQL,
+ check_config={"query": f"SELECT 1 FROM {read.name}"},
+ referenced_subjects=[{"subject_type": str(SubjectType.VIEW), "subject_uuid": str(read.id)}],
+ check_fingerprint=uuid4().hex,
+ status=CheckRunStatus.FAILED,
+ )
+ return suite_run
+
def _sweep_covering(self, view: DataWarehouseSavedQuery) -> DataQualitySuiteRun:
"""A multi-subject sweep whose counters include one check run against this view."""
suite_run = DataQualitySuiteRun.objects.for_team(self.team.id).create(team=self.team, trigger="manual")
@@ -220,6 +288,67 @@ class TestDataQualityRunAPI(APIBaseTest):
assert {row["subject_name"] for row in listed.json()["results"]} == {"customers"}
assert {row["subject_uuid"] for row in health.json()} == {str(self.customers.id)}
+ def test_the_overview_hides_a_check_that_reads_a_denied_subject(self) -> None:
+ # The parent is allowed, but the config names "orders" and the status answers questions
+ # about its rows, so listing the check is a directory entry for a table the member cannot read.
+ self._check(
+ self.customers,
+ check_type=CheckType.CUSTOM_SQL,
+ column_name="",
+ config={"query": "SELECT 1 FROM orders"},
+ )
+ self._deny_orders()
+
+ listed = self.client.get(self.checks_url)
+ health = self.client.get(f"{self.checks_url}health/")
+
+ assert listed.json()["results"] == []
+ assert health.json() == []
+
+ def test_the_overview_hides_a_check_whose_last_run_read_a_recreated_subject(self) -> None:
+ # Deleting the denied "orders" empties the denial set and frees its name, so the config now
+ # names something the member may read. The status beside it is still the verdict of a run
+ # against the original, which is what the identities the run pinned still answer for.
+ reader = self._check(
+ self.customers,
+ check_type=CheckType.CUSTOM_SQL,
+ column_name="",
+ config={"query": "SELECT 1 FROM orders"},
+ last_status=CheckRunStatus.FAILED,
+ )
+ DataQualityCheckRun.objects.for_team(self.team.id).create(
+ team=self.team,
+ suite_run=DataQualitySuiteRun.objects.for_team(self.team.id).create(team=self.team, trigger="manual"),
+ quality_check=reader,
+ subject_type=SubjectType.VIEW,
+ subject_uuid=self.customers.id,
+ subject_name="customers",
+ check_type=CheckType.CUSTOM_SQL,
+ check_config=reader.config,
+ referenced_subjects=[{"subject_type": str(SubjectType.VIEW), "subject_uuid": str(self.orders.id)}],
+ check_fingerprint=reader.fingerprint,
+ status=CheckRunStatus.FAILED,
+ )
+ self._deny_orders()
+ self.orders.delete()
+ self._make_view("orders")
+
+ listed = self.client.get(self.checks_url)
+ health = self.client.get(f"{self.checks_url}health/")
+
+ assert listed.json()["results"] == []
+ assert health.json() == []
+
+ def test_the_overview_hides_a_denied_subject_renamed_since_its_last_run(self) -> None:
+ # subject_name is only rewritten when the check runs, so matching denial against it serves
+ # the subject's checks for the whole window between a rename and the next run.
+ self._check(self.orders, subject_name="orders_legacy")
+ self._deny_orders()
+
+ listed = self.client.get(self.checks_url)
+
+ assert listed.json()["results"] == []
+
def test_the_overview_leaves_out_orphans_but_keeps_their_history(self) -> None:
# An orphan has no subject page to link to, nothing to run, and no rollup to sit under, so
# showing it in the project list would be a dead row.
@@ -253,6 +382,36 @@ class TestDataQualityRunAPI(APIBaseTest):
# A view on no DAG has no node page; the row renders its name as plain text.
assert rows["customers"]["subject_node_id"] is None
+ def test_the_overview_authorizes_a_definition_once_however_many_checks_share_it(self) -> None:
+ # The overview lists every check in the project unpaginated, so authorizing a definition per
+ # row costs a query per row for every relationships check and a HogQL parse per custom_sql
+ # one. The verdict depends on the definition alone, so the extra rows must cost nothing.
+ target = self._make_view("targets")
+ config = {"to_subject_type": SubjectType.VIEW, "to_subject_uuid": str(target.id), "to_column": "id"}
+ self._deny_orders()
+ self._sharing_checks(config, count=1)
+ # Warms the instance settings and team config the first request of any test would pay for.
+ self.client.get(self.checks_url)
+
+ with capture_db_queries() as one_check:
+ assert self.client.get(self.checks_url).status_code == status.HTTP_200_OK
+ self._sharing_checks(config, count=5)
+ with capture_db_queries() as six_checks:
+ listed = self.client.get(self.checks_url)
+
+ assert len(listed.json()["results"]) == 6
+ assert len(six_checks.captured_queries) == len(one_check.captured_queries)
+
+ def _sharing_checks(self, config: dict, count: int) -> None:
+ """Checks on the allowed subject that all read the same second subject."""
+ for _ in range(count):
+ self._check(
+ self.customers,
+ check_type=CheckType.RELATIONSHIPS,
+ column_name=f"customer_{uuid4().hex[:8]}",
+ config=config,
+ )
+
def test_resolving_where_subjects_live_does_not_grow_with_the_project(self) -> None:
# The overview lists every check in the project, so a query per row is a query per table in
# the warehouse.
diff --git a/products/warehouse_sources/backend/facade/api.py b/products/warehouse_sources/backend/facade/api.py
index c40046869aad..e283b4efa205 100644
--- a/products/warehouse_sources/backend/facade/api.py
+++ b/products/warehouse_sources/backend/facade/api.py
@@ -356,6 +356,18 @@ def resolve_object_by_name(team_id: int, name: str) -> contracts.WarehouseObject
return contracts.WarehouseObjectRef(kind=kind, id=resolved.id)
+def queryable_table_names(team_id: int, table_ids: Collection[UUID]) -> dict[UUID, str]:
+ """The current name of each table that is still queryable. One query; anything gone is absent.
+
+ The bulk form of ``get_queryable_table`` for a caller that only needs names, so authorizing a
+ page of stored table references costs one query rather than one per reference.
+ """
+ if not table_ids:
+ return {}
+ rows = _DataWarehouseTable.raw_objects.queryable().filter(team_id=team_id, id__in=list(table_ids))
+ return dict(rows.values_list("id", "name"))
+
+
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]