diff --git a/CHANGELOG.md b/CHANGELOG.md index 1ab28ff..678fd21 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -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**. diff --git a/docs/DESIGN.md b/docs/DESIGN.md index dfec7b4..ab07384 100644 --- a/docs/DESIGN.md +++ b/docs/DESIGN.md @@ -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 diff --git a/docs/THREAT_MODEL.md b/docs/THREAT_MODEL.md index a2c711e..8520f89 100644 --- a/docs/THREAT_MODEL.md +++ b/docs/THREAT_MODEL.md @@ -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 @@ -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). diff --git a/src/sqlguardllm/cli.py b/src/sqlguardllm/cli.py index a010bd3..9d40b83 100644 --- a/src/sqlguardllm/cli.py +++ b/src/sqlguardllm/cli.py @@ -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 " @@ -871,6 +872,19 @@ 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"], @@ -878,6 +892,7 @@ def _read_row_budgets(path: Path) -> RowBudgets: 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 diff --git a/src/sqlguardllm/mcp_server.py b/src/sqlguardllm/mcp_server.py index 911a20f..608e1ec 100644 --- a/src/sqlguardllm/mcp_server.py +++ b/src/sqlguardllm/mcp_server.py @@ -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 @@ -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): @@ -1060,6 +1066,9 @@ 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: @@ -1067,11 +1076,13 @@ def budget_session() -> str | None: 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 @@ -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]: diff --git a/src/sqlguardllm/proxy.py b/src/sqlguardllm/proxy.py index cc87f17..e8a5034 100644 --- a/src/sqlguardllm/proxy.py +++ b/src/sqlguardllm/proxy.py @@ -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 diff --git a/src/sqlguardllm/session_limits.py b/src/sqlguardllm/session_limits.py index 5ca8269..c333b78 100644 --- a/src/sqlguardllm/session_limits.py +++ b/src/sqlguardllm/session_limits.py @@ -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 @@ -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") @@ -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]] = {} @@ -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) diff --git a/tests/test_mcp.py b/tests/test_mcp.py index a298c05..0fe2408 100644 --- a/tests/test_mcp.py +++ b/tests/test_mcp.py @@ -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)}) diff --git a/tests/test_proxy.py b/tests/test_proxy.py index 3e7c9e9..af241fe 100644 --- a/tests/test_proxy.py +++ b/tests/test_proxy.py @@ -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, + )