Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,10 @@ Sections used: Added, Changed, Deprecated (an API that still works but will be r

## [Unreleased]

### Added

- **Cross-query aggregate differencing check (experimental, #220).** `cohorts` in the MCP row-budget file compares the row ids behind each whole-cohort aggregate with those already served to the same session and refuses near-duplicates with `differencing`, or `cohort_unavailable` when it cannot check.

## [1.1.0] - 2026-12-03

A minor release. The stable API (the guard, the violation codes, the policy schema, the CLI and HTTP protocol v1) only gains optional fields and options; everything new below is experimental and may change in a minor release ([STABILITY](docs/STABILITY.md)). The one default that changed is under **Changed**.
Expand Down
15 changes: 15 additions & 0 deletions docs/DESIGN.md
Original file line number Diff line number Diff line change
Expand Up @@ -375,6 +375,21 @@ single-table SELECTs that project only `COUNT(*)`, `COUNT(column)`,
`SUM(column)` or `AVG(column)`. Requests with caller-selected filters,
subqueries or grouping are refused with `aggregate_shape_restricted`.

Add `"cohorts": {"salaries": {"id_column": "id", "min_difference": 5}}` (the
table must also be in `fixed_aggregate_sources`) to make the MCP server compare
cohorts across requests. Before each aggregate it lists the ids of the rows the
aggregate covers, in the same transaction (`REPEATABLE READ` on PostgreSQL, the
snapshot of a read-only transaction on MySQL, Oracle and SQLite), keeps only
keyed digests of them in memory, and refuses with `differencing` when the new
set differs from one already served to the same session by fewer than
`min_difference` rows. For example `SUM(salary)` followed by the same query
after one person joined would reveal that person's salary; the second request
is refused. Asking twice for exactly the same rows is refused too. If the ids
cannot be listed, the session is unknown, the cohort is larger than 512 ids, or
the backend is SQL Server (no snapshot guarantee), the answer is
`cohort_unavailable`. History is process-local and expires after
`window_seconds`. Verified-catalog queries on a cohort source are refused.

### Aggregate cohort history for embedded applications

`sqlguardllm.session_limits.AggregateCohorts` is an experimental Python
Expand Down
14 changes: 10 additions & 4 deletions docs/THREAT_MODEL.md
Original file line number Diff line number Diff line change
Expand Up @@ -166,8 +166,11 @@ Keep the cohort stable over the reporting interval and review all views, tools
and credentials that can expose the same data. This restriction operates on
each request and offers limited protection when the data changes between
requests, when another source exposes the same records, or when results can be
combined across identities. It does not compare cohort membership across
requests.
combined across identities. Add `cohorts` to the row-budget file and the MCP
server also compares the member ids of each aggregate with those already served
to the same session, refusing near-duplicates with `differencing` (limits: ids
only up to 512 per cohort, process-local history, no SQL Server, no protection
across sessions or identities; see [DESIGN](DESIGN.md#mcp-row-budgets)).

Aunque cada resultado cumpla un tamaño mínimo de grupo, los agregados de dos
conjuntos de filas casi idénticos pueden revelar información sobre las pocas
Expand All @@ -186,5 +189,8 @@ Mantén estable la población durante el periodo de reporte y revisa todas las
vistas, herramientas y credenciales que pueden exponer los mismos datos. La
restricción se aplica a cada consulta y ofrece protección limitada si los datos
cambian, si otro origen expone los mismos registros o si se combinan resultados
de distintas identidades. La comparación de integrantes entre consultas sigue
pendiente.
de distintas identidades. Con `cohorts` en el archivo de presupuestos, el
servidor MCP también compara los identificadores de cada agregado con los ya
entregados a la misma sesión y rechaza los casi idénticos con `differencing`
(límites: hasta 512 identificadores por población, historial en el proceso, sin
SQL Server, sin protección entre sesiones o identidades).
15 changes: 15 additions & 0 deletions src/sqlguardllm/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -855,6 +855,7 @@ def _read_row_budgets(path: Path) -> RowBudgets:
"keyset_columns",
"keyset_page_limit",
"fixed_aggregate_sources",
"cohorts",
}:
raise ValueError(
"expected row_budget and window_seconds, with optional reject_offset and "
Expand All @@ -871,13 +872,27 @@ def _read_row_budgets(path: Path) -> RowBudgets:
isinstance(source, str) for source in fixed_aggregate_sources
):
raise ValueError("fixed_aggregate_sources must be an array of table names")
raw_cohorts = data.get("cohorts", {})
cohorts: dict[str, tuple[str, int]] = {}
if not isinstance(raw_cohorts, dict):
raise ValueError("cohorts must be an object")
for table, entry in raw_cohorts.items():
if (
not isinstance(entry, dict)
or set(entry) != {"id_column", "min_difference"}
or not isinstance(entry["id_column"], str)
or type(entry["min_difference"]) is not int
):
raise ValueError("each cohort needs exactly id_column and min_difference")
cohorts[table] = entry["id_column"], entry["min_difference"]
return RowBudgets(
limits,
data["window_seconds"],
reject_offset=data.get("reject_offset", False),
keyset_columns=keyset_columns,
keyset_page_limit=data.get("keyset_page_limit", 0),
fixed_aggregate_sources=fixed_aggregate_sources,
cohorts=cohorts,
)
except (OSError, ValueError) as exc:
raise _UsageError(f"invalid row budget file: {exc}") from None
Expand Down
47 changes: 44 additions & 3 deletions src/sqlguardllm/mcp_server.py
Original file line number Diff line number Diff line change
Expand Up @@ -349,7 +349,9 @@ def _violation_text(
)


def _begin_read_only(conn: Connection, timeout: float) -> Callable[[], None]:
def _begin_read_only(
conn: Connection, timeout: float, *, snapshot: bool = False
) -> Callable[[], None]:
"""Make the open transaction read-only and bounded in time, as far as the backend allows.

Returns a function that undoes per-query settings before the connection goes back to the
Expand All @@ -364,7 +366,11 @@ def _begin_read_only(conn: Connection, timeout: float) -> Callable[[], None]:
dbapi.set_progress_handler(lambda: int(time.monotonic() > deadline), 1000)
return lambda: dbapi.set_progress_handler(None, 0)
if backend == "postgresql":
conn.exec_driver_sql("SET TRANSACTION READ ONLY")
conn.exec_driver_sql(
"SET TRANSACTION ISOLATION LEVEL REPEATABLE READ READ ONLY"
if snapshot
else "SET TRANSACTION READ ONLY"
)
conn.exec_driver_sql(f"SET LOCAL statement_timeout = {millis}")
elif backend in ("mysql", "mariadb"):
if getattr(conn.dialect, "is_mariadb", False):
Expand Down Expand Up @@ -1060,18 +1066,23 @@ def budget_session() -> str | None:
except SQLAlchemyError as exc:
raise self._unavailable(exc) from None
plan_warnings: list[str] = []
cohort_source = (
self.row_budgets.cohort_source(decision.tables) if self.row_budgets else None
)
started = time.monotonic()
try:
if binds is None:
# no_parameters: percent signs in LIKE patterns reach the driver untouched.
conn = conn.execution_options(no_parameters=True)
transaction = conn.begin()
try:
restore = _begin_read_only(conn, self.timeout)
restore = _begin_read_only(conn, self.timeout, snapshot=cohort_source is not None)
try:
plan_warnings = self._check_cost(
conn, run_sql, binds, explained=bound_sql or None
)
if cohort_source is not None:
self._admit_cohort(conn, run_sql, binds, cohort_source, budget_session())
result = (
conn.exec_driver_sql(run_sql)
if binds is None
Expand Down Expand Up @@ -1122,6 +1133,36 @@ def budget_session() -> str | None:
sql, explanation, columns, serialized_rows, truncated, plan_warnings=plan_warnings
)

def _admit_cohort(
self, conn: Any, run_sql: str, binds: Any, source: str, session: str | None
) -> None:
"""Refuse an aggregate whose row set nearly equals one this session already saw."""
budgets = self.row_budgets
assert budgets is not None
listing = (
budgets.membership_sql(run_sql, self.compiled.output_dialect_name, source)
if binds is None
else None
)
refusal = "cohort_unavailable"
if listing is not None and conn.dialect.name != "mssql": # no snapshot guarantee there
ids = conn.exec_driver_sql(listing).fetchmany(budgets.cohort_limit(source) + 1)
refusal = budgets.admit_cohort(session, source, [row[0] for row in ids]) or ""
if refusal:
if self.language == "es":
message = (
"Este agregado se parece demasiado a otro ya entregado en la sesión."
if refusal == "differencing"
else "No se pudo comprobar el conjunto de filas de este agregado."
)
else:
message = (
"This aggregate is too close to one already delivered in this session."
if refusal == "differencing"
else "The row set of this aggregate could not be checked."
)
raise _CostRefused(f"{refusal}: {message}")

# Verified queries (experimental) ----------------------------------------------------------

def _verified(self) -> tuple[Catalog, str | None]:
Expand Down
2 changes: 2 additions & 0 deletions src/sqlguardllm/proxy.py
Original file line number Diff line number Diff line change
Expand Up @@ -347,6 +347,8 @@ def __init__(
self._context = context # set by the operator at startup, never by a tool argument
self._log = log or (lambda message: print(message, file=sys.stderr))
self._strict = strict or config.strict
if row_budgets is not None and row_budgets.has_cohorts:
raise ValueError("cohorts are only enforced by the MCP server, not by the proxy")
self._row_budgets = row_budgets
self._reported = False
self._verified = False
Expand Down
68 changes: 68 additions & 0 deletions src/sqlguardllm/session_limits.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@

from __future__ import annotations

import hashlib
import os
import threading
from collections.abc import Callable, Iterable, Mapping
from itertools import islice
Expand Down Expand Up @@ -95,6 +97,8 @@ def __init__(
keyset_columns: Mapping[str, str] | None = None,
keyset_page_limit: int = 0,
fixed_aggregate_sources: Iterable[str] = (),
cohorts: Mapping[str, tuple[str, int]] | None = None,
cohort_max_members: int = 512,
) -> None:
if type(reject_offset) is not bool:
raise ValueError("reject_offset must be true or false")
Expand Down Expand Up @@ -125,6 +129,23 @@ def __init__(
self._fixed_aggregate_sources = {source.casefold() for source in fixed_aggregate_sources}
if not self._fixed_aggregate_sources <= self._limits.keys():
raise ValueError("fixed_aggregate_sources must name budgeted tables")
self._cohort_columns: dict[str, str] = {}
minimums: dict[str, int] = {}
for table, (column, minimum) in (cohorts or {}).items():
name = table.casefold() if isinstance(table, str) else ""
if name not in self._fixed_aggregate_sources or not (
isinstance(column, str) and column.isidentifier()
):
raise ValueError("cohorts must name fixed_aggregate_sources and an id column")
self._cohort_columns[name] = column
minimums[name] = minimum
self._cohort_max = cohort_max_members
self._cohorts = (
AggregateCohorts(minimums, window_seconds, max_members=cohort_max_members)
if minimums
else None
)
self._cohort_key = os.urandom(32)
self._window = window_seconds
self._usage: dict[tuple[str, str], tuple[float, int]] = {}
self._page_usage: dict[tuple[str, str], tuple[float, int]] = {}
Expand Down Expand Up @@ -286,6 +307,53 @@ def permits_aggregate_shape(self, sql: str, dialect: str, tables: Iterable[str])
return False
return bool(statement.expressions)

@property
def has_cohorts(self) -> bool:
"""Whether cross-request cohort checks are configured."""
return bool(self._cohort_columns)

def cohort_source(self, tables: Iterable[str]) -> str | None:
"""Return the cohort-tracked source a read touches, if any."""
found = self._covered_tables(tables) & self._cohort_columns.keys()
return next(iter(found)) if len(found) == 1 else None

def cohort_limit(self, source: str) -> int:
"""Largest cohort the history can hold for ``source``."""
return self._cohort_max

def membership_sql(self, sql: str, dialect: str, source: str) -> str | None:
"""Build the query listing the row ids an aggregate over ``source`` covers."""
try:
statement = sqlglot.parse_one(sql, read=dialect)
except SqlglotError:
return None
origin = statement.args.get("from_") if isinstance(statement, exp.Select) else None
if not isinstance(origin, exp.From) or not isinstance(origin.this, exp.Table):
return None
if origin.this.name.casefold() != source or statement.args.get("joins"):
return None
query = exp.select(exp.column(self._cohort_columns[source])).from_(origin.this.copy())
where = statement.args.get("where")
if where is not None:
query = query.where(where.this.copy())
return query.sql(dialect=dialect)

def admit_cohort(
self, session: str | None, source: str, values: Iterable[object]
) -> Literal["differencing", "cohort_unavailable"] | None:
"""Digest the member ids and compare them with this session's earlier cohorts."""
if self._cohorts is None or not session:
return "cohort_unavailable"
tokens = [
hashlib.blake2b(
f"{source}\0{type(value).__name__}\0{value}".encode(),
key=self._cohort_key,
digest_size=32,
).digest()
for value in values
]
return self._cohorts.admit(session, source, tokens)

def exhausted(self, session: str, tables: Iterable[str]) -> bool:
"""Check whether a source is already at its limit before executing a read."""
covered = self._covered_tables(tables)
Expand Down
50 changes: 50 additions & 0 deletions tests/test_mcp.py
Original file line number Diff line number Diff line change
Expand Up @@ -915,3 +915,53 @@ async def go() -> Any:
description = tools["explain_query"].description or ""
assert "does not return the SQL" in description
assert "the SQL that would actually run" not in description


def _cohort_server(url: str, minimum: int = 2) -> MCPServer[Any]:
return create_server(
make_policy(),
url,
row_budgets=RowBudgets(
{"salaries": 100},
60,
fixed_aggregate_sources=["salaries"],
cohorts={"salaries": ("id", minimum)},
),
single_session=True,
)


def _add_salary(db_path: Path, ident: int, amount: int = 50) -> None:
with sqlite3.connect(db_path) as conn:
conn.execute("INSERT INTO salaries VALUES (?, 'it', ?)", (ident, amount))


def test_cohort_refuses_a_total_that_differs_by_one_person(url: str, db_path: Path) -> None:
server = _cohort_server(url)
total = {"sql": "SELECT SUM(amount) AS total FROM salaries"}
assert call(server, "query", total)["rows"] == [[600]]
_add_salary(db_path, 42, 5000) # one more person: the next total would reveal their salary
assert call_error(server, "query", total).startswith("differencing:")


def test_cohort_allows_a_clearly_different_group(url: str, db_path: Path) -> None:
server = _cohort_server(url)
total = {"sql": "SELECT COUNT(*) AS members FROM salaries"}
assert call(server, "query", total)["rows"] == [[3]]
_add_salary(db_path, 42)
_add_salary(db_path, 43)
assert call(server, "query", total)["rows"] == [[5]]


def test_cohort_repeating_the_same_group_is_refused(url: str) -> None:
# Documented trade-off: a second look at the very same rows adds nothing and would
# let a client probe how the history behaves, so it is refused like any near-duplicate.
server = _cohort_server(url)
total = {"sql": "SELECT SUM(amount) AS total FROM salaries"}
assert call(server, "query", total)["rows"] == [[600]]
assert call_error(server, "query", total).startswith("differencing:")


def test_cohort_config_must_name_a_fixed_source() -> None:
with pytest.raises(ValueError, match="fixed_aggregate_sources"):
RowBudgets({"salaries": 5}, 60, cohorts={"salaries": ("id", 2)})
23 changes: 23 additions & 0 deletions tests/test_proxy.py
Original file line number Diff line number Diff line change
Expand Up @@ -525,3 +525,26 @@ def test_proxy_checks_fixed_aggregate_shape_before_forwarding() -> None:
assert text_of(result).startswith("aggregate_shape_restricted:")
assert result["result"]["structuredContent"] == {"code": "aggregate_shape_restricted"}
assert upstream.tool_calls() == []


def test_proxy_refuses_cohort_budgets_it_cannot_enforce() -> None:
class IdleUpstream:
def request(self, method: str, params: Any) -> dict[str, Any]:
return {}

def notify(self, method: str, params: Any = None) -> None:
return None

def close(self) -> None:
return None

budgets = RowBudgets(
{"invoices": 2}, 60, fixed_aggregate_sources=["invoices"], cohorts={"invoices": ("id", 2)}
)
with pytest.raises(ValueError, match="only enforced by the MCP server"):
Proxy(
Guard(Policy(dialect="postgres", tables={"invoices"})),
MAP,
IdleUpstream(),
row_budgets=budgets,
)
Loading