diff --git a/docs/THREAT_MODEL.md b/docs/THREAT_MODEL.md index 8520f89..f2373af 100644 --- a/docs/THREAT_MODEL.md +++ b/docs/THREAT_MODEL.md @@ -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 @@ -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 @@ -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. diff --git a/tests/corpus/runtime/session_privacy.json b/tests/corpus/runtime/session_privacy.json new file mode 100644 index 0000000..819c231 --- /dev/null +++ b/tests/corpus/runtime/session_privacy.json @@ -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]]} + ] + } +] diff --git a/tests/test_mcp.py b/tests/test_mcp.py index c2a461c..9f5075f 100644 --- a/tests/test_mcp.py +++ b/tests/test_mcp.py @@ -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 @@ -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)})