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
14 changes: 12 additions & 2 deletions docs/DESIGN.md
Original file line number Diff line number Diff line change
Expand Up @@ -403,6 +403,16 @@ 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.

Use `sqlguardllm proxy --row-budgets budgets.json --cohort-db-env NAME`
with a map containing only guarded SQL tools. Set `NAME` to the name of an
environment variable that holds a read-only URL for the database that supplies
the protected aggregates. The proxy executes those queries through its local
MCP engine, which computes membership and the aggregate in one snapshot.
Each call to a protected source accepts only the mapped SQL argument. Other
guarded queries can still run on the configured upstream. The proxy removes
the database URL variable from the upstream process environment and returns
only the protected result rows or a privacy refusal code.

### Aggregate cohort history for embedded applications

`sqlguardllm.session_limits.AggregateCohorts` is an experimental Python
Expand All @@ -418,5 +428,5 @@ in the active window. At capacity it refuses new cohorts and retains all
live comparisons. State is process-local. Applications
must enforce minimum group size and stable identities separately. Comparisons
do not span identities, workers or windows, or cover inference from combinations
of several queries. Built-in MCP and proxy execution still use their separate
fixed-cohort restrictions.
of several queries. Built-in MCP execution and the proxy's local cohort route use the same
history through the row-budget configuration.
11 changes: 11 additions & 0 deletions docs/PROXY.md
Original file line number Diff line number Diff line change
Expand Up @@ -64,3 +64,14 @@ Want it set up for you? [`sqlguardllm protect`](PROTECT.md) finds the server in
## Examples

Maps for common servers are in [`examples/proxy/`](https://github.com/jmmana/sqlguardllm/tree/main/examples/proxy): `dbhub.yaml`, `postgres-mcp-pro.yaml` and a `sqlserver.yaml` template. Tool names change between releases of these servers: list the tools of your version and adjust the map. The table above records the real-server checks for these maps. The unit tests also use a fake upstream.


### Cohort-protected aggregate reads

A proxy can enforce the cohort history by running protected aggregates through
the local read-only database connection. Configure `cohorts` in
`--row-budgets` and pass `--cohort-db-env` with the name of the environment
variable that holds that connection URL. Install the `mcp` extra and use a map
without passthrough tools. The configured database is authoritative for these
sources. The proxy sends other mapped reads to the upstream tool as usual.
See the [configuration details](DESIGN.md#mcp-row-budgets).
10 changes: 10 additions & 0 deletions docs/es/PROXY.md
Original file line number Diff line number Diff line change
Expand Up @@ -58,3 +58,13 @@ La política, `--role`, `--context`, `--language`, `--audit-log` y `--audit-sql`
## Ejemplos

Hay mapas para servidores habituales en [`examples/proxy/`](https://github.com/jmmana/sqlguardllm/tree/main/examples/proxy): `dbhub.yaml`, `postgres-mcp-pro.yaml` y una plantilla `sqlserver.yaml`. Los nombres de herramientas cambian entre versiones de estos servidores: lista las herramientas de tu versión y ajusta el mapa. La tabla anterior registra las comprobaciones de estos mapas con servidores reales. Las pruebas unitarias también usan un servidor simulado.


### Agregados protegidos por el historial de conjuntos

Configura `cohorts` en `--row-budgets` y pasa a `--cohort-db-env` el nombre
de la variable que contiene la URL de solo lectura de la base de datos de
los agregados protegidos. Instala el extra `mcp` y usa un mapa sin herramientas
de paso directo. El proxy calcula esos agregados en la conexión local y
envía las demás consultas mapeadas al servidor ascendente.
Consulta los [detalles de configuración](../DESIGN.md#mcp-row-budgets).
61 changes: 59 additions & 2 deletions src/sqlguardllm/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@
import os
import sys
import tempfile
from collections.abc import Callable, Sequence
from collections.abc import Callable, Mapping, Sequence
from pathlib import Path
from typing import Any, TextIO

Expand Down Expand Up @@ -248,6 +248,11 @@ def _parser() -> argparse.ArgumentParser:
type=Path,
help="JSON file with row budgets for mapped tools that return structured rows",
)
proxy.add_argument(
"--cohort-db-env",
metavar="NAME",
help="environment variable with the read-only database URL for cohort comparisons",
)
proxy.add_argument("--language", choices=LANGUAGES, default="en", help="message language")
_add_audit_options(proxy)

Expand Down Expand Up @@ -964,6 +969,35 @@ def _run_mcp(
return EXIT_OK


def _proxy_cohort_reader(
policy: Policy,
database: str,
context: Mapping[str, Any] | None,
budgets: RowBudgets,
language: str,
) -> Callable[[str], dict[str, Any]]:
import anyio # noqa: PLC0415
from mcp import Client # noqa: PLC0415

from sqlguardllm.mcp_server import create_server # noqa: PLC0415

server = create_server(
policy,
database,
context=context,
language=language,
row_budgets=budgets,
single_session=True,
)

async def query(sql: str) -> dict[str, Any]:
async with Client(server) as client:
result = await client.call_tool("query", {"sql": sql})
return result.model_dump(by_alias=True)

return lambda sql: anyio.run(query, sql)


def _proxy(
args: argparse.Namespace, upstream: list[str], stdin: TextIO, stdout: TextIO, stderr: TextIO
) -> int:
Expand Down Expand Up @@ -995,8 +1029,30 @@ def _proxy(
f"but the policy uses {policy.dialect!r}"
)
row_budgets = _read_row_budgets(args.row_budgets) if args.row_budgets is not None else None
cohort_reader = None
upstream_env = None
if row_budgets is not None and row_budgets.has_cohorts:
if tool_map.passthrough:
raise _UsageError("proxy cohort budgets require a map without passthrough tools")
db_env = args.cohort_db_env
database = os.environ.get(db_env) if db_env else None
if not db_env or not database:
raise _UsageError("proxy cohort budgets require --cohort-db-env with a database URL")
try:
cohort_reader = _proxy_cohort_reader(
policy, database, context, row_budgets, args.language
)
except ImportError as exc:
raise _UsageError('proxy cohort budgets need pip install "sqlguardllm[mcp]"') from exc
except ValueError as exc:
raise _UsageError(str(exc)) from None
upstream_env = {
key: value for key, value in os.environ.items() if key.casefold() != db_env.casefold()
}
elif args.cohort_db_env:
raise _UsageError("--cohort-db-env requires cohorts in --row-budgets")
try: # never echo the upstream command: it often holds a database password
server = StdioUpstream(upstream)
server = StdioUpstream(upstream, env=upstream_env)
except OSError as exc:
raise _UsageError(f"cannot start the upstream server: {exc.strerror or 'error'}") from None
proxy = Proxy(
Expand All @@ -1006,6 +1062,7 @@ def _proxy(
context,
log=lambda message: print(message, file=stderr),
row_budgets=row_budgets,
cohort_reader=cohort_reader,
)
return proxy.serve(stdin, stdout)

Expand Down
67 changes: 57 additions & 10 deletions src/sqlguardllm/proxy.py
Original file line number Diff line number Diff line change
Expand Up @@ -166,7 +166,13 @@ def close(self) -> None: ...
class StdioUpstream:
"""An MCP server started as a child process and spoken to over stdio."""

def __init__(self, argv: Sequence[str], timeout: float | None = _DEFAULT_TIMEOUT) -> None:
def __init__(
self,
argv: Sequence[str],
timeout: float | None = _DEFAULT_TIMEOUT,
*,
env: Mapping[str, str] | None = None,
) -> None:
"""Start the server.

Args:
Expand All @@ -185,6 +191,7 @@ def __init__(self, argv: Sequence[str], timeout: float | None = _DEFAULT_TIMEOUT
encoding="utf-8",
errors="replace",
bufsize=1,
env=env,
)
self._timeout = timeout
self._lines: queue.Queue[str | None] = queue.Queue()
Expand Down Expand Up @@ -330,6 +337,7 @@ def __init__(
*,
strict: bool = False,
row_budgets: RowBudgets | None = None,
cohort_reader: Callable[[str], dict[str, Any]] | None = None,
) -> None:
if guard.policy.sensitive_tables or guard.policy.untrusted_columns:
raise ProxyConfigError(
Expand All @@ -348,7 +356,13 @@ def __init__(
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")
if cohort_reader is None:
raise ProxyConfigError("proxy cohort budgets require a local cohort database")
if config.passthrough:
raise ProxyConfigError(
"proxy cohort budgets require a map without passthrough tools"
)
self._cohort_reader = cohort_reader
self._row_budgets = row_budgets
self._reported = False
self._verified = False
Expand Down Expand Up @@ -539,6 +553,13 @@ def reply(result: dict[str, Any]) -> dict[str, Any]:
if not result.ok or result.sql is None:
return reply(_tool_error(_violation_text(result.violations)))
budgets = self._row_budgets
cohort_source = budgets.cohort_source(result.tables) if budgets is not None else None
if cohort_source is not None:
if arguments.keys() != {sql_arg}:
return reply(
_privacy_error("cohort_unavailable", "the cohort tool accepts only SQL")
)
return reply(self._cohort_result(sql))
if budgets is not None and not budgets.permits_aggregate_shape(
sql, self.guard.policy.dialect, result.tables
):
Expand Down Expand Up @@ -575,15 +596,41 @@ def reply(result: dict[str, Any]) -> dict[str, Any]:
return reply(
_privacy_error("row_budget_exceeded", "the session row budget was exceeded")
)
# Return only the charged row payload. An upstream text block or extra field may contain
# additional data outside the supported row format.
return reply(self._rows_result(rows))

def _cohort_result(self, sql: str) -> dict[str, Any]:
assert self._cohort_reader is not None
try:
outcome = self._cohort_reader(sql)
except Exception:
return _privacy_error("cohort_unavailable", "the cohort query could not be checked")
if outcome.get("isError"):
for item in outcome.get("content") or []:
if not isinstance(item, dict) or not isinstance(item.get("text"), str):
continue
message = item["text"].removeprefix("Error executing tool query: ")
code, sep, _ = message.partition(":")
if sep and code in {
"differencing",
"aggregate_shape_restricted",
"row_budget_exceeded",
"paging_detected",
}:
return _privacy_error(code, "the cohort query was refused")
return _privacy_error("cohort_unavailable", "the cohort query could not be checked")
data = outcome.get("structuredContent")
rows = data.get("rows") if isinstance(data, dict) else None
if not isinstance(rows, list) or not all(isinstance(row, list) for row in rows):
return _privacy_error("cohort_unavailable", "the cohort query returned invalid rows")
return self._rows_result(rows)

@staticmethod
def _rows_result(rows: list[Any]) -> dict[str, Any]:
payload = {"rows": rows}
return reply(
{
"content": [{"type": "text", "text": json.dumps(payload, ensure_ascii=False)}],
"structuredContent": payload,
}
)
return {
"content": [{"type": "text", "text": json.dumps(payload, ensure_ascii=False)}],
"structuredContent": payload,
}

# Transport -------------------------------------------------------------------------------

Expand Down
96 changes: 95 additions & 1 deletion tests/test_proxy.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

import io
import json
import sqlite3
import sys
import textwrap
from pathlib import Path
Expand Down Expand Up @@ -541,10 +542,103 @@ def close(self) -> 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"):
with pytest.raises(ValueError, match="require a local cohort database"):
Proxy(
Guard(Policy(dialect="postgres", tables={"invoices"})),
MAP,
IdleUpstream(),
row_budgets=budgets,
)
with pytest.raises(ValueError, match="without passthrough tools"):
Proxy(
Guard(Policy(dialect="postgres", tables={"invoices"})),
MAP,
IdleUpstream(),
row_budgets=budgets,
cohort_reader=lambda _: {},
)


def test_proxy_cli_routes_cohorts_to_its_database(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
pytest.importorskip("mcp")
pytest.importorskip("sqlalchemy")

database = tmp_path / "local.sqlite"
with sqlite3.connect(database) as conn:
conn.execute("CREATE TABLE salaries (id INTEGER PRIMARY KEY, amount INTEGER)")
conn.executemany("INSERT INTO salaries VALUES (?, ?)", [(i, 10 * i) for i in range(1, 9)])
policy = tmp_path / "policy.json"
policy.write_text(
json.dumps({"dialect": "sqlite", "tables": ["salaries"], "aggregate_only": {"salaries": 2}})
)
tool_map = tmp_path / "map.json"
tool_map.write_text(json.dumps({"sql_tools": {"execute_sql": {"sql_arg": "sql"}}}))
budgets = tmp_path / "budget.json"
budgets.write_text(
json.dumps(
{
"row_budget": {"salaries": 2},
"window_seconds": 60,
"fixed_aggregate_sources": ["salaries"],
"cohorts": {"salaries": {"id_column": "id", "min_difference": 2}},
"cohort_id_filter_sources": ["salaries"],
}
)
)
upstream = FakeUpstream()
monkeypatch.setenv("TEST_LOCAL_COHORT_DB", f"sqlite:///{database}")

def start_upstream(_command: list[str], *, env: dict[str, str]) -> FakeUpstream:
assert "TEST_LOCAL_COHORT_DB" not in env
return upstream

monkeypatch.setattr("sqlguardllm.proxy.StdioUpstream", start_upstream)
sql = "SELECT COUNT(*) FROM salaries"
queries = [
{"sql": sql},
{"sql": sql + " WHERE id <= 7"},
{"sql": sql + " WHERE id <= 5"},
{"sql": sql, "extra": "unsupported"},
]
messages = [
{
"jsonrpc": "2.0",
"id": i,
"method": "tools/call",
"params": {"name": "execute_sql", "arguments": arguments},
}
for i, arguments in enumerate(queries, 1)
]
stdin = io.StringIO("".join(json.dumps(message) + "\n" for message in messages))
stdout, stderr = io.StringIO(), io.StringIO()
assert (
main(
[
"proxy",
"--policy",
str(policy),
"--map",
str(tool_map),
"--row-budgets",
str(budgets),
"--cohort-db-env",
"TEST_LOCAL_COHORT_DB",
"--",
"unused-upstream",
],
stdin,
stdout,
stderr,
)
== 0
), stderr.getvalue()
results = [json.loads(line)["result"] for line in stdout.getvalue().splitlines()]
assert [result["structuredContent"] for result in results] == [
{"rows": [[8]]},
{"code": "differencing"},
{"rows": [[5]]},
{"code": "cohort_unavailable"},
]
assert upstream.tool_calls() == []
Loading