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
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ A minor release. The stable API (the guard, the violation codes, the policy sche

### Added

- **Verified queries** (#287, [guide](docs/CATALOG.md), experimental): a git-managed catalog (YAML or JSON) of approved, read-only business queries with a version, stable ids, `:name` SQL templates, typed parameters (`string`, `integer`, `number`, `boolean`, `date`) and allowed roles. `sqlguardllm mcp --catalog FILE` adds `list_verified_queries` and `run_verified_query`; the server owns the SQL and the values are bound, never written into it. A verified query gets no extra privileges: it goes through the same policy, masks, row filters, row limit, read-only transaction, timeout, taint tracking, row budgets and plan checks as `query`, which does not change. The catalog is checked at startup against the policy and the guard's rewrite; audit events carry `catalog_query` and `catalog_version` and never a value or a row. `sqlguardllm catalog check FILE --policy ...` does the same check for CI. Examples with fixtures and expected business results are in `examples/catalog/`.
- **Plan checks** (#292, [guide](docs/PLAN_CHECKS.md), experimental): `sqlguardllm.plan.PlanGuard` judges the database's own plan for a query the guard allowed (it only accepts a `CheckResult`, so the rewritten SQL is what is explained, never `ANALYZE`) against `max_cost`, `max_rows` and `full_scan_tables`, with `on_exceed` `deny` or `warn`; `sqlalchemy_runner` runs the statements. Plans are read for PostgreSQL, MySQL, **SQL Server (`SHOWPLAN_XML`), DuckDB and SQLite**, with SQLite and MySQL aliases resolved through the SQL. `sqlguardllm mcp` gains `--plan-full-scan TABLE` and `--plan-on-exceed`, and a warn-mode query runs with `status: "warned"` and the reasons in `warnings`. **Changed:** `--max-cost` or `--max-plan-rows` on an engine whose plan has no such number (SQLite, DuckDB) is now an error at startup instead of being ignored with a warning; backends with no plan reader (Oracle, MariaDB) still warn and ignore.
- **`classify --sample N`, value checks and Spanish names** (#294): `sqlguardllm classify --sample N` also looks at up to N values per column (off by default, at most 1000 values and 500 columns, read-only, never printed) and checks them with an email shape, Luhn, CURP, RFC, SSN, CLABE and IBAN checks; each proposal says whether name, values or both support it. Spanish and Mexican names (`tarjeta`, `numero_cuenta`, `pasaporte`, `imss`) are recognised, and a descriptive first word (`tipo_tarjeta`, `fecha_curp`) is not a match. 130 corpus cases pin each class action in five dialects, per-role overrides in policy sets are documented and tested, and the threat model lists what classes do not cover.
- **Advice per table, and `advice` / `data_classes` in the Node.js and .NET clients** (#291, #294): `Advice.tables` gives the columns used per physical table and clause, resolved through aliases, subqueries and the policy `schema`. The protocol schema lists both optional fields, a conformance test checks that in-process, stdio and HTTP explanations agree, `Explanation` (Node.js) and `ExplainResult.Advice` / `.DataClasses` (.NET) are typed, and the Node.js generated types now include the policy fields added since 1.0 (`advice`, `data_classes`, `column_classes`, `not_sensitive`), which were missing.
Expand Down
89 changes: 89 additions & 0 deletions docs/CATALOG.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,89 @@
# Verified queries

*Español: [es/CATALOG.md](es/CATALOG.md)*

> Experimental: not covered by the 1.x stability guarantee (see [STABILITY.md](STABILITY.md)); it may change in a minor release.

A generated query can pass every policy check and still calculate the wrong metric: gross sales where the business means net sales. The guard cannot tell. A **catalog** lets a data team publish the reviewed definition once, in git, and lets an agent ask for it by name with typed values. The server owns the SQL, so the definition is maintained, tested and audited in one place.

```
agent ──run_verified_query("net_sales_by_month", {from_date, to_date})──▶ server
the server owns the SQL, values are bound, never written in
```

**Approval grants no extra privileges.** A catalog query goes through the same policy as any query: allowed tables and columns, masks, row filters bound to the trusted context, the row limit, the read-only transaction and the timeout, plus [taint tracking](MCP.md#tainted-sessions-prompt-injection-in-query-results), [row budgets](DESIGN.md#mcp-row-budgets) and [plan checks](PLAN_CHECKS.md) when you have them on.

## Set it up

```bash
# 1. The example data, on a disposable PostgreSQL database
createdb sg_catalog
psql sg_catalog -f examples/catalog/fixtures.sql

# 2. Check the catalog against the policy, for each role (also fine in CI, no database needed)
sqlguardllm catalog check examples/catalog/catalog.yaml \
--policy examples/catalog/policy.yaml --role manager --context @examples/catalog/context.json

# 3. Serve it
DATABASE_URL=postgresql+psycopg://you@localhost/sg_catalog \
sqlguardllm mcp --policy examples/catalog/policy.yaml --role manager \
--context @examples/catalog/context.json --catalog examples/catalog/catalog.yaml

# 4. Run the checks of the expected business results (they run in CI too)
SQLGUARD_PG_URL=postgresql+psycopg://you@localhost/postgres \
uv run pytest tests/engines/test_catalog_engines.py -v
```

The server then has two more tools next to `query`, which does not change: `list_verified_queries` (the ids, descriptions and typed parameters this role may run) and `run_verified_query` (an id and its values).

## The file

YAML or JSON, kept in git next to the policy. The example, [`examples/catalog/catalog.yaml`](https://github.com/jmmana/sqlguardllm/blob/main/examples/catalog/catalog.yaml):

```yaml
version: "2026-12-01" # a string or an integer; recorded in every audit event
dialect: postgres # must match the policy's dialect
queries:
- id: net_sales_by_month
description: Net sales per month: invoice total minus its discount.
roles: [analyst, manager] # optional; every role when omitted
params:
from_date: {type: date, description: First day included, required: true}
to_date: {type: date, description: First day NOT included, required: true}
sql: >
SELECT to_char(issued_at, 'YYYY-MM') AS month, SUM(total - discount) AS net_sales
FROM invoices
WHERE issued_at >= :from_date AND issued_at < :to_date
GROUP BY 1 ORDER BY 1
```

- **`id`**: lowercase letters, digits and `_`, from a letter. Stable: agents and audits refer to it.
- **`sql`**: exactly one statement, with `:name` placeholders. Nothing else binds: `?`, `$1` and `%s` are refused, and a colon inside a string or a `::` cast is never a parameter.
- **`params`**: each parameter is declared and used. Types: `string` (`max_length`, at most 200, no NUL), `integer` (64-bit), `number` (finite), `boolean`, `date` (`YYYY-MM-DD`). Options: `required` (default true), `default`, `enum`, `minimum`, `maximum`, `description`.
- **`roles`**: who may see and run it. A role outside the list gets the same answer as for an id that does not exist.

## What is checked, and when

**At startup** (the server refuses to start, `catalog check` exits non-zero): invalid definitions, duplicate ids, undeclared or unused parameters, a catalog written for another dialect than the policy, unknown role names, and any query the policy would refuse for the role (a table not allowed, a hidden column). The query is also checked as the guard rewrites it: the rewrite must keep every parameter, as many times as the template uses it.

**On every call**, before anything runs: the id and the role, then each value against its declared type. A missing, unknown or invalid parameter is `invalid_parameters` and the message names the parameter, never the value. Values are then **bound** by the driver; nothing a caller sends is ever written into the SQL.

## The result

Like `query`, plus the id and the version: `status`, `rewrites` (the row filters and masks that applied), `truncated`, `applied_limit`, `warnings`, and `query_id` and `catalog_version`. See [what a result says](MCP.md#what-a-query-result-says).

## The audit trail

Each decision is recorded with `catalog_query` (the id) and `catalog_version`. The event holds no parameter value and no row, even with raw SQL logging on: the SQL recorded is the template, with its `:name` placeholders.

## Keeping a metric honest

The point of a catalog is that its definitions are reviewed. `examples/catalog/expected.json` lists what each query must return on the fixture data (checked by hand: see the comment in `fixtures.sql`), and `tests/engines/test_catalog_engines.py` runs them. Change net sales to gross sales and the SQL is still valid and the policy still passes, but the test fails, so the change cannot ship unnoticed. The same file proves tenant isolation, masks, the row limit and the audit trail.

## Limits

- **Not a restriction.** The agent can still call `query`. A catalog makes the right definition easy to use; it does not forbid free SQL. To forbid it, narrow the policy.
- **A `LIMIT` cannot be a parameter.** The guard replaces a limit it cannot read with the policy's row limit, so the parameter would vanish; the server refuses such a catalog at startup and says so. Write a number, or let the row limit decide.
- **PostgreSQL first.** The examples and their expected results run on PostgreSQL 16 in CI. The binding is also tested on SQLite, and the SQL conversion on MySQL and T-SQL spellings, but a catalog on another engine has not been run against that engine here.
- **With OIDC authentication** the context comes from each caller's token, so the policy check that runs at startup otherwise runs on every call instead. Role names are still checked at startup.
- A query is one statement and read-only. Writes belong to [controlled writes](WRITES.md), not to a catalog.
5 changes: 4 additions & 1 deletion docs/MCP.md
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,8 @@ To enable [experimental controlled writes](WRITES.md), configure `writes` in the
| `explain_query` | [`Guard.explain()`](DESIGN.md#richer-policies) without running anything: whether the query is allowed, the tables and columns it reads, the masks, group sizes, row filters (as written in the policy, with their `{user.…}` placeholders) and limit it gets, or the violations |
| `query` | `Guard.enforce()`, then the safe SQL in a read-only transaction: columns and rows, at most `max_rows` rows, and what the guard did to the query ([below](#what-a-query-result-says)) |

With `--catalog`, two more tools: `list_verified_queries` (the approved queries this role may run, with their typed parameters) and `run_verified_query` (an id and its values; the server owns the SQL, and the result is shaped like `query`'s plus `query_id` and `catalog_version`). See [verified queries](CATALOG.md).

Every tool advertises a typed `outputSchema`. Fields that appear only sometimes (`advice`, `estimate`, the taint fields) are not in the required list, so a client can validate the response without losing them.

### What a query result says
Expand Down Expand Up @@ -87,7 +89,7 @@ The `mcp` extra brings the [MCP Python SDK](https://github.com/modelcontextproto
sqlguardllm mcp --policy FILE [--role NAME] [--db URL] [--context JSON|@file]
[--language en|es] [--timeout SECONDS]
[--max-cost N] [--max-plan-rows N]
[--plan-full-scan TABLE] [--plan-on-exceed deny|warn] [--write-db URL] [--ledger PATH]
[--plan-full-scan TABLE] [--plan-on-exceed deny|warn] [--catalog FILE] [--write-db URL] [--ledger PATH]
```

| Option | |
Expand All @@ -103,6 +105,7 @@ sqlguardllm mcp --policy FILE [--role NAME] [--db URL] [--context JSON|@file]
| `--max-cost` | Plan check: refuse queries whose planner cost is above this (PostgreSQL, MySQL and SQL Server) |
| `--max-plan-rows` | Plan check: refuse queries whose planner row estimate is above this (not SQLite) |
| `--plan-full-scan` | Plan check: refuse queries whose plan reads this table in full, whatever the cost (repeatable) |
| `--catalog` | Experimental: a [catalog of verified queries](CATALOG.md) the agent runs by id, with typed parameters, through two extra tools |
| `--plan-on-exceed` | What a broken plan rule does: `deny` the query (default) or let it run and add a warning |

### Plan checks (cost guard)
Expand Down
1 change: 1 addition & 0 deletions docs/STABILITY.md
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@ These may change, or be removed, in any minor release. Each is marked in its doc
- Controlled writes: `Policy.writes`, `WritePolicy`, `TableWrites`, `Guard.check_write`, `WriteCheckResult`, and the codes `write_not_allowed`, `write_column_not_allowed`, `missing_where`, `too_many_rows`.
- Stored procedures: `Policy.procedures` and the codes `procedure_not_allowed`, `procedure_param_invalid`.
- Tainted sessions: `untrusted_columns`, `sensitive_tables`, `on_tainted` and the code `tainted_session`.
- Verified queries (`sqlguardllm.catalog`, `sqlguardllm mcp --catalog`, the tools `list_verified_queries` and `run_verified_query`, `sqlguardllm catalog check`, the `catalog_query` and `catalog_version` audit fields, [CATALOG.md](CATALOG.md)).
- Plan checks (`sqlguardllm.plan`, `PlanGuard`, `sqlguardllm mcp --plan-full-scan` and `--plan-on-exceed`, [PLAN_CHECKS.md](PLAN_CHECKS.md)).
- Policy diff (`sqlguardllm.policy_diff`, `sqlguardllm diff`, [POLICY_DIFF.md](POLICY_DIFF.md)).
- Sensitive data classes: `Policy.data_classes`, `Policy.column_classes`, `Policy.not_sensitive`, `Explanation.data_classes`, `sqlguardllm.classes` and `sqlguardllm classify` ([CLASSES.md](CLASSES.md)).
Expand Down
Loading
Loading