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
10 changes: 10 additions & 0 deletions docs/DESIGN.md
Original file line number Diff line number Diff line change
Expand Up @@ -393,6 +393,16 @@ most 513 rows, including one extra to detect an oversized set. History is
process-local and expires after
`window_seconds`. Verified-catalog queries on a cohort source are refused.

To permit filtered cohorts, include an eligible source in
`"cohort_id_filter_sources": ["salaries"]` in the same configuration. This
option requires an `aggregate_only` policy on SQLite or PostgreSQL and a
stable integer identifier on a trusted base table. It permits one direct
comparison (`=`, `<>`, `<`, `<=`, `>`, or `>=`) between that identifier
and an integer literal. MCP validates the predicate in the checked SQL and
uses it for both the membership read and the aggregate in the same snapshot.
Other caller-selected filters are refused. The same cohort history covers
filtered and unfiltered queries.

### Aggregate cohort history for embedded applications

`sqlguardllm.session_limits.AggregateCohorts` is an experimental Python
Expand Down
6 changes: 6 additions & 0 deletions docs/es/THREAT_MODEL.md
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,12 @@ si obtienen las identidades de las filas y el agregado de la misma instantánea.
El historial compara los conjuntos dentro de una sesión, un origen y una ventana.
Los servidores MCP y proxy incorporados aplican sus restricciones de conjunto fijo.

En SQLite y PostgreSQL, las fuentes de agregados con historial pueden habilitar
una [comparación directa sobre su identificador entero](../DESIGN.md#mcp-row-budgets).
La lectura de integrantes y el cálculo del agregado usan la misma instantánea.
MCP aplica el umbral de diferencia a los conjuntos con y sin filtro que se
consultaron en la sesión.

## Diferenciales de parser encontrados

Lugares donde el árbol de sqlglot no decía lo que haría el motor real. Cada uno se corrigió y tiene un caso en el corpus.
Expand Down
10 changes: 9 additions & 1 deletion src/sqlguardllm/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -856,10 +856,12 @@ def _read_row_budgets(path: Path) -> RowBudgets:
"keyset_page_limit",
"fixed_aggregate_sources",
"cohorts",
"cohort_id_filter_sources",
}:
raise ValueError(
"expected row_budget and window_seconds, with optional reject_offset and "
"keyset_columns, keyset_page_limit and fixed_aggregate_sources"
"keyset_columns, keyset_page_limit, fixed_aggregate_sources, cohorts "
"and cohort_id_filter_sources"
)
limits = data["row_budget"]
if not isinstance(limits, dict) or not limits:
Expand All @@ -872,6 +874,11 @@ 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")
id_filters = data.get("cohort_id_filter_sources", [])
if not isinstance(id_filters, list) or not all(
isinstance(source, str) for source in id_filters
):
raise ValueError("cohort_id_filter_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):
Expand All @@ -893,6 +900,7 @@ def _read_row_budgets(path: Path) -> RowBudgets:
keyset_page_limit=data.get("keyset_page_limit", 0),
fixed_aggregate_sources=fixed_aggregate_sources,
cohorts=cohorts,
cohort_id_filter_sources=id_filters,
)
except (OSError, ValueError) as exc:
raise _UsageError(f"invalid row budget file: {exc}") from None
Expand Down
19 changes: 17 additions & 2 deletions src/sqlguardllm/mcp_server.py
Original file line number Diff line number Diff line change
Expand Up @@ -1014,13 +1014,28 @@ def _run_query(
def budget_session() -> str | None:
return self._session_id() if self._explicit_resolver else self._session_object(ctx)

if (
self.row_budgets is not None
and self.row_budgets.uses_cohort_id_filters(decision.tables)
and (
self.engine.dialect.name not in {"sqlite", "postgresql"}
or not all(
self._marker(self.compiled.aggregate_only.keys(), self._resolve(source))
for source in decision.tables
)
)
):
raise ToolError(
"cohort_unavailable: filtered cohorts require aggregate_only "
"on SQLite or PostgreSQL"
)
if self.row_budgets is not None and not self.row_budgets.permits_aggregate_shape(
sql, self.dialect, decision.tables
):
message = (
"Este origen requiere agregados sobre el conjunto completo de filas permitido."
"La forma de este agregado no está permitida para este origen."
if self.language == "es"
else "This source requires aggregates over the full set of permitted rows."
else "This aggregate shape is not allowed for this source."
)
raise ToolError(f"aggregate_shape_restricted: {message}")
if self.row_budgets is not None and not self.row_budgets.permits_offset(
Expand Down
42 changes: 40 additions & 2 deletions src/sqlguardllm/session_limits.py
Original file line number Diff line number Diff line change
Expand Up @@ -99,6 +99,7 @@ def __init__(
fixed_aggregate_sources: Iterable[str] = (),
cohorts: Mapping[str, tuple[str, int]] | None = None,
cohort_max_members: int = 512,
cohort_id_filter_sources: Iterable[str] = (),
) -> None:
if type(reject_offset) is not bool:
raise ValueError("reject_offset must be true or false")
Expand Down Expand Up @@ -139,6 +140,9 @@ def __init__(
raise ValueError("cohorts must name fixed_aggregate_sources and an id column")
self._cohort_columns[name] = column
minimums[name] = minimum
self._cohort_id_filters = {source.casefold() for source in cohort_id_filter_sources}
if not self._cohort_id_filters <= self._cohort_columns.keys():
raise ValueError("cohort_id_filter_sources must name sources configured in cohorts")
self._cohort_max = cohort_max_members
self._cohorts = (
AggregateCohorts(minimums, window_seconds, max_members=cohort_max_members)
Expand Down Expand Up @@ -266,7 +270,7 @@ def matches_cursor(columns: exp.Expr, bounds: exp.Expr) -> bool:
return True

def permits_aggregate_shape(self, sql: str, dialect: str, tables: Iterable[str]) -> bool:
"""Require direct whole-cohort aggregates on explicitly configured sources."""
"""Require direct aggregate projections and an eligible cohort selector."""
if not self._fixed_aggregate_sources:
return True
if not self._covered_tables(tables).intersection(self._fixed_aggregate_sources):
Expand All @@ -276,7 +280,9 @@ def permits_aggregate_shape(self, sql: str, dialect: str, tables: Iterable[str])
except SqlglotError:
return False
if not isinstance(statement, exp.Select) or any(
value for key, value in statement.args.items() if key not in {"from_", "expressions"}
value
for key, value in statement.args.items()
if key not in {"from_", "expressions", "where"}
):
return False
source = statement.args.get("from_")
Expand All @@ -291,6 +297,9 @@ def permits_aggregate_shape(self, sql: str, dialect: str, tables: Iterable[str])
return False
if table.name.casefold() not in self._fixed_aggregate_sources:
return False
where = statement.args.get("where")
if where is not None and not self._permits_cohort_filter(where, table, dialect):
return False
for projection in statement.expressions:
target = projection.this if isinstance(projection, exp.Alias) else projection
if not isinstance(target, (exp.Count, exp.Sum, exp.Avg)):
Expand All @@ -307,6 +316,31 @@ def permits_aggregate_shape(self, sql: str, dialect: str, tables: Iterable[str])
return False
return bool(statement.expressions)

def _permits_cohort_filter(self, where: exp.Where, table: exp.Table, dialect: str) -> bool:
source = table.name.casefold()
if dialect not in {"sqlite", "postgres"} or source not in self._cohort_id_filters:
return False
predicate = where.this.unnest()
if not isinstance(predicate, (exp.EQ, exp.NEQ, exp.LT, exp.LTE, exp.GT, exp.GTE)):
return False
column = predicate.this.unnest()
literal = predicate.expression.unnest()
if not isinstance(column, exp.Column) or not isinstance(column.this, exp.Identifier):
return False
expected = self._cohort_columns[source].lower()
name = column.name if column.this.quoted and dialect == "postgres" else column.name.lower()
return bool(
name == expected
and (not column.table or column.table.casefold() == table.alias_or_name.casefold())
and not column.db
and not column.catalog
and isinstance(literal, exp.Literal)
and literal.is_int
)

def uses_cohort_id_filters(self, tables: Iterable[str]) -> bool:
return bool(self._covered_tables(tables) & self._cohort_id_filters)

@property
def has_cohorts(self) -> bool:
"""Whether cross-request cohort checks are configured."""
Expand Down Expand Up @@ -335,6 +369,10 @@ def membership_sql(self, sql: str, dialect: str, source: str) -> str | None:
query = exp.select(exp.column(self._cohort_columns[source])).from_(origin.this.copy())
where = statement.args.get("where")
if where is not None:
if source in self._cohort_id_filters and not self._permits_cohort_filter(
where, origin.this, dialect
):
return None
query = query.where(where.this.copy())
# Read one extra id to distinguish an exact fit from an incomplete cohort.
return query.limit(self.cohort_limit(source) + 1).sql(dialect=dialect)
Expand Down
40 changes: 40 additions & 0 deletions tests/engines/test_row_budget_engines.py
Original file line number Diff line number Diff line change
Expand Up @@ -121,6 +121,46 @@ async def verify_fixed_aggregate() -> None:
)

anyio.run(verify_fixed_aggregate)
with engine.begin() as conn:
conn.exec_driver_sql(
f"INSERT INTO public.{table} SELECT id, 'x' FROM generate_series(4, 8) AS id"
)
filtered_server = create_server(
Policy(
dialect="postgres",
tables={f"public.{table}"},
aggregate_only={f"public.{table}": 2},
),
engine,
row_budgets=RowBudgets(
{table: 8},
60,
fixed_aggregate_sources=[table],
cohorts={table: ("id", 2)},
cohort_id_filter_sources=[table],
),
single_session=True,
)

async def verify_filtered_cohort() -> None:
sql = f"SELECT COUNT(*) FROM public.{table}"
with anyio.fail_after(30):
async with Client(filtered_server) as client:
total = await client.call_tool("query", {"sql": sql})
near = await client.call_tool("query", {"sql": sql + " WHERE id <= 7"})
separate = await client.call_tool("query", {"sql": sql + " WHERE id <= 5"})
assert total.structured_content is not None
assert total.structured_content["rows"] == [[8]]
assert near.is_error and near.structured_content is None
assert any(
"differencing:" in item.text
for item in near.content
if isinstance(item, TextContent)
), near.content
assert separate.structured_content is not None
assert separate.structured_content["rows"] == [[5]]

anyio.run(verify_filtered_cohort)
finally:
with engine.begin() as conn:
conn.exec_driver_sql(f"DROP TABLE IF EXISTS public.{table}")
Expand Down
35 changes: 35 additions & 0 deletions tests/test_mcp.py
Original file line number Diff line number Diff line change
Expand Up @@ -1025,6 +1025,41 @@ def record_read(_conn: Any, _cursor: Any, statement: str, *_args: Any) -> None:
engine.dispose()


def test_filtered_cohorts_compare_actual_sqlite_memberships(url: str, db_path: Path) -> None:
for ident in range(4, 9):
_add_salary(db_path, ident)
budgets = RowBudgets(
{"salaries": 100},
60,
fixed_aggregate_sources=["salaries"],
cohorts={"salaries": ("id", 2)},
cohort_id_filter_sources=["salaries"],
)
server = create_server(make_policy(), url, row_budgets=budgets, single_session=True)
sql = "SELECT COUNT(*) FROM salaries"
assert call(server, "query", {"sql": sql})["rows"] == [[8]]
assert call_error(server, "query", {"sql": sql + " WHERE id <= 7"}).startswith("differencing:")
assert call(server, "query", {"sql": sql + " WHERE id <= 5"})["rows"] == [[5]]
assert call_error(server, "query", {"sql": sql + " WHERE amount > 10"}).startswith(
"aggregate_shape_restricted:"
)


def test_filtered_cohorts_require_aggregate_only(url: str) -> None:
budgets = RowBudgets(
{"salaries": 100},
60,
fixed_aggregate_sources=["salaries"],
cohorts={"salaries": ("id", 2)},
cohort_id_filter_sources=["salaries"],
)
server = create_server(
make_policy(aggregate_only={}), url, row_budgets=budgets, single_session=True
)
query = {"sql": "SELECT COUNT(*) FROM salaries WHERE id <= 2"}
assert call_error(server, "query", query).startswith("cohort_unavailable:")


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)})
Loading