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
15 changes: 13 additions & 2 deletions docs/THREAT_MODEL.md
Original file line number Diff line number Diff line change
Expand Up @@ -160,7 +160,7 @@ aggregates over the entire cohort defined by trusted policy, including its row
filters. It refuses caller-selected subsets with `aggregate_shape_restricted`.
Combine it with `aggregate_only` to enforce the minimum group size. Two supported
aggregates over the same cohort can both succeed in one session, subject to the
row budget. See the [configuration example](DESIGN.md#mcp-row-budgets).
row budget, when cohort history is disabled. See the [configuration example](DESIGN.md#mcp-row-budgets).

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
Expand All @@ -183,7 +183,7 @@ confianza, incluidos sus filtros por fila. Rechaza los subconjuntos elegidos por
el solicitante con `aggregate_shape_restricted`. Combínalo con
`aggregate_only` para exigir el tamaño mínimo de grupo. Dos agregados admitidos
sobre la misma población pueden ejecutarse en una sola sesión si hay saldo en
el presupuesto. Consulta el [ejemplo de configuración](DESIGN.md#mcp-row-budgets).
el presupuesto y el historial de conjuntos está desactivado. Consulta el [ejemplo de configuración](DESIGN.md#mcp-row-budgets).

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
Expand All @@ -194,3 +194,14 @@ 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).


The [proxy's local cohort connection](PROXY.md#cohort-protected-aggregate-reads)
can apply the same check before returning aggregates. The runtime corpus
exercises row-budget exhaustion, session identification, paging restrictions,
fixed aggregate shapes and cohort differences in one session at a time.

La [conexión local del proxy](es/PROXY.md#agregados-protegidos-por-el-historial-de-conjuntos)
aplica el mismo control antes de entregar los agregados. El corpus de
ejecución cubre el presupuesto agotado, la identificación de sesión, la
paginación, la forma de los agregados y la comparación dentro de cada sesión.
66 changes: 66 additions & 0 deletions tests/corpus/runtime/session_privacy.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
[
{
"id": "mcp-row-budget-exhausted",
"budget": {"row_budget": {"branches": 1}, "window_seconds": 60},
"steps": [
{"sql": "SELECT id FROM branches ORDER BY id LIMIT 1", "rows": [[1]]},
{"sql": "SELECT id FROM branches ORDER BY id LIMIT 1", "code": "row_budget_exceeded"}
]
},
{
"id": "mcp-budget-session-unavailable",
"budget": {"row_budget": {"branches": 2}, "window_seconds": 60},
"session": null,
"steps": [
{"sql": "SELECT id FROM branches ORDER BY id LIMIT 1", "code": "row_budget_unavailable"}
]
},
{
"id": "mcp-offset-pagination",
"budget": {"row_budget": {"branches": 2}, "window_seconds": 60, "reject_offset": true},
"steps": [
{"sql": "SELECT id FROM branches ORDER BY id LIMIT 1 OFFSET 0", "rows": [[1]]},
{"sql": "SELECT id FROM branches ORDER BY id LIMIT 1 OFFSET 1", "code": "paging_detected"}
]
},
{
"id": "mcp-fixed-cohort-shape",
"budget": {
"row_budget": {"salaries": 8},
"window_seconds": 60,
"fixed_aggregate_sources": ["salaries"]
},
"steps": [
{"sql": "SELECT SUM(amount) FROM salaries WHERE id <= 5", "code": "aggregate_shape_restricted"}
]
},
{
"id": "mcp-filtered-cohort-unavailable",
"policy": {"aggregate_only": {}},
"budget": {
"row_budget": {"salaries": 8},
"window_seconds": 60,
"fixed_aggregate_sources": ["salaries"],
"cohorts": {"salaries": {"id_column": "id", "min_difference": 2}},
"cohort_id_filter_sources": ["salaries"]
},
"steps": [
{"sql": "SELECT SUM(amount) FROM salaries WHERE id <= 5", "code": "cohort_unavailable"}
]
},
{
"id": "mcp-filtered-cohort-difference",
"budget": {
"row_budget": {"salaries": 8},
"window_seconds": 60,
"fixed_aggregate_sources": ["salaries"],
"cohorts": {"salaries": {"id_column": "id", "min_difference": 2}},
"cohort_id_filter_sources": ["salaries"]
},
"steps": [
{"sql": "SELECT SUM(amount) FROM salaries", "rows": [[850]]},
{"sql": "SELECT SUM(amount) FROM salaries WHERE id <= 7", "code": "differencing"},
{"sql": "SELECT SUM(amount) FROM salaries WHERE id <= 5", "rows": [[700]]}
]
}
]
41 changes: 40 additions & 1 deletion tests/test_mcp.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@
from sqlalchemy import create_engine, event

from sqlguardllm import AuditLog, Policy
from sqlguardllm.cli import main
from sqlguardllm.cli import _read_row_budgets, main
from sqlguardllm.mcp_server import _begin_read_only, _jsonable, create_server
from sqlguardllm.result_delivery import ResultPolicy
from sqlguardllm.session_limits import RowBudgets
Expand Down Expand Up @@ -1060,6 +1060,45 @@ def test_filtered_cohorts_require_aggregate_only(url: str) -> None:
assert call_error(server, "query", query).startswith("cohort_unavailable:")


_PRIVACY_CASES = json.loads(
(Path(__file__).parent / "corpus/runtime/session_privacy.json").read_text(encoding="utf-8")
)


@pytest.mark.parametrize("case", _PRIVACY_CASES, ids=[case["id"] for case in _PRIVACY_CASES])
def test_session_privacy_corpus(
case: dict[str, Any], url: str, db_path: Path, tmp_path: Path
) -> None:
for ident in range(4, 9):
_add_salary(db_path, ident)
budget_file = tmp_path / "budget.json"
budget_file.write_text(json.dumps(case["budget"]), encoding="utf-8")
session = case.get("session", "corpus-reader")
server = create_server(
make_policy(**case.get("policy", {})),
url,
row_budgets=_read_row_budgets(budget_file),
session_id=lambda: session,
)

async def run() -> None:
async with Client(server) as client:
for step in case["steps"]:
result = await client.call_tool("query", {"sql": step["sql"]})
if "code" in step:
assert result.is_error and result.structured_content is None
assert (
text(result)
.removeprefix("Error executing tool query: ")
.startswith(step["code"] + ":")
)
else:
assert not result.is_error and result.structured_content is not None
assert result.structured_content["rows"] == step["rows"]

anyio.run(run)


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