diff --git a/CHANGELOG.md b/CHANGELOG.md index b2ed106..1ab28ff 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -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. diff --git a/docs/CATALOG.md b/docs/CATALOG.md new file mode 100644 index 0000000..0068324 --- /dev/null +++ b/docs/CATALOG.md @@ -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. diff --git a/docs/MCP.md b/docs/MCP.md index 53ccb05..a58fd56 100644 --- a/docs/MCP.md +++ b/docs/MCP.md @@ -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 @@ -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 | | @@ -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) diff --git a/docs/STABILITY.md b/docs/STABILITY.md index 0df1720..6556f31 100644 --- a/docs/STABILITY.md +++ b/docs/STABILITY.md @@ -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)). diff --git a/docs/es/CATALOG.md b/docs/es/CATALOG.md new file mode 100644 index 0000000..61cd7a2 --- /dev/null +++ b/docs/es/CATALOG.md @@ -0,0 +1,89 @@ +# Consultas verificadas + +*English: [CATALOG.md](../CATALOG.md)* + +> Experimental: no está cubierto por la garantía de estabilidad de 1.x (véase [STABILITY.md](STABILITY.md)); puede cambiar en una versión menor. + +Una consulta generada puede pasar todas las reglas de la política y aun así calcular mal una métrica: ventas brutas donde el negocio quiere decir ventas netas. El guard no puede notarlo. Un **catálogo** permite al equipo de datos publicar una vez, en git, la definición revisada, y que un agente la pida por nombre con valores tipados. El servidor es dueño del SQL, así que la definición se mantiene, se prueba y se audita en un solo lugar. + +``` +agente ──run_verified_query("net_sales_by_month", {from_date, to_date})──▶ servidor + el servidor es dueño del SQL; los valores se enlazan, nunca se escriben en él +``` + +**La aprobación no da privilegios extra.** Una consulta del catálogo pasa por la misma política que cualquier otra: tablas y columnas permitidas, máscaras, filtros por fila enlazados al contexto confiable, el límite de filas, la transacción de solo lectura y el tiempo límite, además del [rastreo de contaminación](../MCP.md#tainted-sessions-prompt-injection-in-query-results), los [presupuestos de filas](../DESIGN.md#mcp-row-budgets) y las [comprobaciones de plan](PLAN_CHECKS.md) cuando los tengas activados. + +## Puesta en marcha + +```bash +# 1. Los datos de ejemplo, en una base PostgreSQL desechable +createdb sg_catalog +psql sg_catalog -f examples/catalog/fixtures.sql + +# 2. Comprobar el catálogo contra la política, por rol (sirve también en CI, sin base de datos) +sqlguardllm catalog check examples/catalog/catalog.yaml \ + --policy examples/catalog/policy.yaml --role manager --context @examples/catalog/context.json + +# 3. Servirlo +DATABASE_URL=postgresql+psycopg://tu_usuario@localhost/sg_catalog \ +sqlguardllm mcp --policy examples/catalog/policy.yaml --role manager \ + --context @examples/catalog/context.json --catalog examples/catalog/catalog.yaml + +# 4. Ejecutar las comprobaciones de los resultados de negocio esperados (también corren en CI) +SQLGUARD_PG_URL=postgresql+psycopg://tu_usuario@localhost/postgres \ +uv run pytest tests/engines/test_catalog_engines.py -v +``` + +El servidor tiene entonces dos herramientas más junto a `query`, que no cambia: `list_verified_queries` (los ids, descripciones y parámetros tipados que este rol puede ejecutar) y `run_verified_query` (un id y sus valores). + +## El archivo + +YAML o JSON, guardado en git junto a la política. El ejemplo, [`examples/catalog/catalog.yaml`](https://github.com/jmmana/sqlguardllm/blob/main/examples/catalog/catalog.yaml): + +```yaml +version: "2026-12-01" # texto o entero; queda en cada evento de auditoría +dialect: postgres # debe coincidir con el dialecto de la política +queries: + - id: net_sales_by_month + description: Ventas netas por mes: total de la factura menos su descuento. + roles: [analyst, manager] # opcional; todos los roles si se omite + params: + from_date: {type: date, description: Primer día incluido, required: true} + to_date: {type: date, description: Primer día NO incluido, 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`**: minúsculas, dígitos y `_`, empezando por letra. Estable: los agentes y las auditorías se refieren a él. +- **`sql`**: exactamente una sentencia, con marcadores `:nombre`. Nada más enlaza: `?`, `$1` y `%s` se rechazan, y un dos puntos dentro de un texto o un `::` de conversión nunca es un parámetro. +- **`params`**: cada parámetro se declara y se usa. Tipos: `string` (`max_length`, máximo 200, sin NUL), `integer` (64 bits), `number` (finito), `boolean`, `date` (`AAAA-MM-DD`). Opciones: `required` (por defecto verdadero), `default`, `enum`, `minimum`, `maximum`, `description`. +- **`roles`**: quién puede verla y ejecutarla. Un rol fuera de la lista recibe la misma respuesta que para un id que no existe. + +## Qué se comprueba y cuándo + +**Al arrancar** (el servidor se niega a iniciar, `catalog check` sale con error): definiciones inválidas, ids duplicados, parámetros sin declarar o sin usar, un catálogo escrito para otro dialecto que el de la política, nombres de rol desconocidos y cualquier consulta que la política rechazaría para el rol (una tabla no permitida, una columna oculta). La consulta también se comprueba tal como la reescribe el guard: la reescritura debe conservar cada parámetro, tantas veces como lo usa la plantilla. + +**En cada llamada**, antes de ejecutar nada: el id y el rol, y luego cada valor contra su tipo declarado. Un parámetro ausente, desconocido o inválido es `invalid_parameters` y el mensaje nombra el parámetro, nunca el valor. Después los valores se **enlazan** por el driver; nada de lo que envía quien llama se escribe jamás en el SQL. + +## El resultado + +Como `query`, más el id y la versión: `status`, `rewrites` (los filtros por fila y máscaras aplicados), `truncated`, `applied_limit`, `warnings`, y `query_id` y `catalog_version`. Véase [qué dice un resultado](MCP_RESULT.md). + +## El rastro de auditoría + +Cada decisión se registra con `catalog_query` (el id) y `catalog_version`. El evento no contiene ningún valor de parámetro ni ninguna fila, ni siquiera con el registro de SQL en crudo activado: el SQL registrado es la plantilla, con sus marcadores `:nombre`. + +## Mantener honesta una métrica + +El sentido de un catálogo es que sus definiciones estén revisadas. `examples/catalog/expected.json` lista lo que cada consulta debe devolver con los datos de prueba (verificado a mano: véase el comentario en `fixtures.sql`), y `tests/engines/test_catalog_engines.py` las ejecuta. Si cambias ventas netas por ventas brutas, el SQL sigue siendo válido y la política sigue pasando, pero la prueba falla, así que el cambio no puede salir sin que nadie lo note. El mismo archivo demuestra el aislamiento entre inquilinos, las máscaras, el límite de filas y el rastro de auditoría. + +## Límites + +- **No es una restricción.** El agente todavía puede llamar a `query`. Un catálogo hace fácil usar la definición correcta; no prohíbe el SQL libre. Para prohibirlo, estrecha la política. +- **Un `LIMIT` no puede ser un parámetro.** El guard reemplaza un límite que no puede leer por el límite de filas de la política, así que el parámetro desaparecería; el servidor rechaza ese catálogo al arrancar y lo explica. Escribe un número, o deja que decida el límite de filas. +- **Primero PostgreSQL.** Los ejemplos y sus resultados esperados corren en PostgreSQL 16 en CI. El enlace de parámetros también se prueba en SQLite, y la conversión del SQL en las grafías de MySQL y T-SQL, pero un catálogo en otro motor no se ha ejecutado aquí contra ese motor. +- **Con autenticación OIDC** el contexto viene del token de cada persona, así que la comprobación de política que se hace al arrancar se hace en cada llamada. Los nombres de rol sí se comprueban al arrancar. +- Una consulta es una sola sentencia y de solo lectura. Las escrituras son de las [escrituras controladas](../WRITES.md), no de un catálogo. diff --git a/docs/es/STABILITY.md b/docs/es/STABILITY.md index b30e3dc..60cbffe 100644 --- a/docs/es/STABILITY.md +++ b/docs/es/STABILITY.md @@ -36,6 +36,7 @@ Esto puede cambiar, o eliminarse, en cualquier versión menor. Cada elemento lle - Escrituras controladas: `Policy.writes`, `WritePolicy`, `TableWrites`, `Guard.check_write`, `WriteCheckResult` y los códigos `write_not_allowed`, `write_column_not_allowed`, `missing_where`, `too_many_rows`. - Procedimientos almacenados: `Policy.procedures` y los códigos `procedure_not_allowed`, `procedure_param_invalid`. - Sesiones contaminadas: `untrusted_columns`, `sensitive_tables`, `on_tainted` y el código `tainted_session`. +- Consultas verificadas (`sqlguardllm.catalog`, `sqlguardllm mcp --catalog`, las herramientas `list_verified_queries` y `run_verified_query`, `sqlguardllm catalog check`, los campos de auditoría `catalog_query` y `catalog_version`, [CATALOG.md](CATALOG.md)). - Comprobaciones de plan (`sqlguardllm.plan`, `PlanGuard`, `sqlguardllm mcp --plan-full-scan` y `--plan-on-exceed`, [PLAN_CHECKS.md](PLAN_CHECKS.md)). - Comparar políticas (`sqlguardllm.policy_diff`, `sqlguardllm diff`, [POLICY_DIFF.md](POLICY_DIFF.md)). - Clases de datos sensibles: `Policy.data_classes`, `Policy.column_classes`, `Policy.not_sensitive`, `Explanation.data_classes`, `sqlguardllm.classes` y `sqlguardllm classify` ([CLASSES.md](CLASSES.md)). diff --git a/examples/catalog/catalog.yaml b/examples/catalog/catalog.yaml new file mode 100644 index 0000000..89577ed --- /dev/null +++ b/examples/catalog/catalog.yaml @@ -0,0 +1,37 @@ +# Verified queries: reviewed definitions of business metrics, kept in git next to the policy. +# Run `sqlguardllm catalog check examples/catalog/catalog.yaml --policy examples/catalog/policy.yaml +# --role manager --context @examples/catalog/context.json` to check them against the policy. +version: "2026-12-01" +dialect: postgres +queries: + - id: net_sales_by_month + description: > + Net sales per month: invoice total minus its discount, over invoices issued from from_date + (included) to to_date (excluded). Gross sales (total alone) is a different number. + 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: top_customers_by_net_sales + description: The five customers with the highest net sales (total minus discount) since from_date. + roles: [analyst, manager] + params: + from_date: {type: date, description: First day included, required: true} + sql: > + SELECT c.name AS customer, SUM(i.total - i.discount) AS net_sales + FROM invoices i JOIN customers c ON c.id = i.customer_id + WHERE i.issued_at >= :from_date + GROUP BY c.name ORDER BY net_sales DESC, c.name LIMIT 5 + + - id: customer_directory + description: Customer names and e-mail addresses whose name matches a pattern such as 'A%'. + roles: [manager] + params: + pattern: {type: string, description: LIKE pattern for the name, max_length: 40, required: true} + sql: > + SELECT name, email FROM customers WHERE name LIKE :pattern ORDER BY name diff --git a/examples/catalog/context.json b/examples/catalog/context.json new file mode 100644 index 0000000..ed69aa6 --- /dev/null +++ b/examples/catalog/context.json @@ -0,0 +1 @@ +{"user": {"tenant": "t1"}} diff --git a/examples/catalog/expected.json b/examples/catalog/expected.json new file mode 100644 index 0000000..a7e889d --- /dev/null +++ b/examples/catalog/expected.json @@ -0,0 +1,33 @@ +{ + "_comment": "Expected results of examples/catalog/catalog.yaml on examples/catalog/fixtures.sql, for tenant t1. Checked by hand: see the comment in fixtures.sql. A CI run fails when a metric definition changes without this file changing.", + "cases": [ + { + "id": "net_sales_by_month", + "role": "analyst", + "parameters": {"from_date": "2026-01-01", "to_date": "2026-04-01"}, + "columns": ["month", "net_sales"], + "rows": [["2026-01", 290], ["2026-02", 185], ["2026-03", 270]] + }, + { + "id": "net_sales_by_month", + "role": "manager", + "parameters": {"from_date": "2026-02-01", "to_date": "2026-03-01"}, + "columns": ["month", "net_sales"], + "rows": [["2026-02", 185]] + }, + { + "id": "top_customers_by_net_sales", + "role": "analyst", + "parameters": {"from_date": "2026-01-01"}, + "columns": ["customer", "net_sales"], + "rows": [["Ana", 560], ["Luis", 185]] + }, + { + "id": "customer_directory", + "role": "manager", + "parameters": {"pattern": "A%"}, + "columns": ["name", "email"], + "rows": [["Ana", "an***"]] + } + ] +} diff --git a/examples/catalog/fixtures.sql b/examples/catalog/fixtures.sql new file mode 100644 index 0000000..4277664 --- /dev/null +++ b/examples/catalog/fixtures.sql @@ -0,0 +1,22 @@ +-- Fixture data for examples/catalog/. Small enough to check by hand. +-- t1 net sales: Jan (100-10)+(200-0)=290, Feb (150-15)+(50-0)=185, Mar 300-30=270. +-- Gross sales would be Jan 300, Feb 200, Mar 300: a changed metric shows up at once. +-- Tenant t2 has an invoice of 999 that tenant t1 must never see. +DROP TABLE IF EXISTS invoices; +DROP TABLE IF EXISTS customers; +CREATE TABLE customers (id INT PRIMARY KEY, tenant_id TEXT NOT NULL, name TEXT NOT NULL, email TEXT); +CREATE TABLE invoices ( + id INT PRIMARY KEY, tenant_id TEXT NOT NULL, customer_id INT NOT NULL, status TEXT NOT NULL, + issued_at DATE NOT NULL, total NUMERIC(10, 2) NOT NULL, discount NUMERIC(10, 2) NOT NULL +); +INSERT INTO customers VALUES + (1, 't1', 'Ana', 'ana@acme.test'), + (2, 't1', 'Luis', 'luis@acme.test'), + (3, 't2', 'Eva', 'eva@other.test'); +INSERT INTO invoices VALUES + (1, 't1', 1, 'paid', '2026-01-10', 100, 10), + (2, 't1', 1, 'paid', '2026-01-20', 200, 0), + (3, 't1', 2, 'paid', '2026-02-05', 150, 15), + (4, 't1', 2, 'open', '2026-02-25', 50, 0), + (5, 't1', 1, 'open', '2026-03-02', 300, 30), + (6, 't2', 3, 'paid', '2026-01-15', 999, 99); diff --git a/examples/catalog/policy.yaml b/examples/catalog/policy.yaml new file mode 100644 index 0000000..569bfa1 --- /dev/null +++ b/examples/catalog/policy.yaml @@ -0,0 +1,21 @@ +# yaml-language-server: $schema=https://raw.githubusercontent.com/jmmana/sqlguardllm/main/schema/policy-set.schema.json +# The policy the verified queries run under. A catalog query gets no extra privileges: every one +# still goes through these tables, masks and row filters, and the row limit. +base: + dialect: postgres + tables: [invoices, customers] + schema: + invoices: [id, tenant_id, customer_id, status, issued_at, total, discount] + customers: [id, tenant_id, name, email] + row_filters: + # {user.tenant} comes from the authenticated user in the application, never from the model. + invoices: "tenant_id = {user.tenant}" + customers: "tenant_id = {user.tenant}" + max_rows: 50 +roles: + analyst: + add: + hidden_columns: [customers.email] + manager: + masked_columns: + customers.email: partial diff --git a/mkdocs.yml b/mkdocs.yml index e3b1b6e..227e28b 100644 --- a/mkdocs.yml +++ b/mkdocs.yml @@ -55,6 +55,9 @@ nav: - Query advice (experimental): - English: ADVICE.md - Español: es/ADVICE.md + - Verified queries (experimental): + - English: CATALOG.md + - Español: es/CATALOG.md - Plan checks (experimental): - English: PLAN_CHECKS.md - Español: es/PLAN_CHECKS.md diff --git a/src/sqlguardllm/audit.py b/src/sqlguardllm/audit.py index 15bb798..16c0a55 100644 --- a/src/sqlguardllm/audit.py +++ b/src/sqlguardllm/audit.py @@ -50,6 +50,25 @@ ) +# Set by a verified-query call around its checks (experimental); never read from user input. +_CATALOG: contextvars.ContextVar[tuple[str, str] | None] = contextvars.ContextVar( + "sqlguardllm_audit_catalog", default=None +) + + +@contextlib.contextmanager +def audit_catalog(query_id: str, version: str) -> Iterator[None]: + """Mark the events recorded inside the block with a verified query's id and catalog version. + + Only the id and the version: never a parameter value (internal). + """ + token = _CATALOG.set((query_id, version)) + try: + yield + finally: + _CATALOG.reset(token) + + @contextlib.contextmanager def audit_subject(subject: str | None) -> Iterator[None]: """Mark the events recorded inside the block with the verified ``subject`` (internal).""" @@ -80,6 +99,8 @@ class AuditEvent: sql: The SQL as ``include_sql`` allows: ``None``, redacted or raw. subject: The verified token subject when the decision was made for an authenticated caller (``sqlguardllm mcp --auth oidc``), else ``None``. Experimental. + catalog_query: Id of the verified query that was asked for, else ``None``. Experimental. + catalog_version: Version of the catalog that query came from, else ``None``. Experimental. """ timestamp: str @@ -95,6 +116,8 @@ class AuditEvent: context_keys: tuple[str, ...] sql: str | None = None subject: str | None = None + catalog_query: str | None = None + catalog_version: str | None = None def to_dict(self) -> dict[str, Any]: """The JSON shape of the event. ``sql`` is present only when it is logged.""" @@ -115,6 +138,9 @@ def to_dict(self) -> dict[str, Any]: data["sql"] = self.sql if self.subject is not None: data["subject"] = self.subject + if self.catalog_query is not None: + data["catalog_query"] = self.catalog_query + data["catalog_version"] = self.catalog_version return data @@ -321,6 +347,8 @@ def record( context_keys=context_key_names(context), sql=shown, subject=_SUBJECT.get(), + catalog_query=(_CATALOG.get() or (None, None))[0], + catalog_version=(_CATALOG.get() or (None, None))[1], ) self._sink(event) except Exception as exc: diff --git a/src/sqlguardllm/catalog.py b/src/sqlguardllm/catalog.py new file mode 100644 index 0000000..22e2e63 --- /dev/null +++ b/src/sqlguardllm/catalog.py @@ -0,0 +1,435 @@ +"""Verified queries: approved, read-only business queries that an MCP agent can run by name. + +Experimental: not covered by the 1.x stability guarantee (see docs/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. A catalog lets a data team publish the reviewed +definition once. The agent asks for ``net_sales_by_month`` with typed values; the server owns the +SQL. Approval grants **no** extra privileges: a catalog query still goes through the policy (tables, +columns, masks, row filters, the row limit), the read-only transaction and the timeout. + +The file (YAML or JSON), kept in git next to the policy:: + + version: "2026-12-01" + dialect: postgres + queries: + - id: net_sales_by_month + description: Net sales (total minus discount) per month. + roles: [analyst, manager] # optional: every role when omitted + sql: > + SELECT date_trunc('month', issued_at) AS month, SUM(total - discount) AS net_sales + FROM invoices WHERE issued_at >= :from_date AND issued_at < :to_date GROUP BY 1 + params: + from_date: {type: date, required: true} + to_date: {type: date, required: true} + +Values are only ever *bound* to the ``:name`` placeholders, never written into the SQL. +""" + +from __future__ import annotations + +import datetime +import math +import re +import secrets +from collections.abc import Mapping, Sequence +from dataclasses import dataclass, field +from pathlib import Path +from typing import Any + +import sqlglot +from sqlglot import exp +from sqlglot.errors import SqlglotError + +from sqlguardllm.guard import Guard +from sqlguardllm.policy import read_mapping +from sqlguardllm.result import PolicyError + +__all__ = ["Catalog", "CatalogError", "Param", "VerifiedQuery", "check_against_policy"] + +TYPES = ("string", "integer", "number", "boolean", "date") +MAX_STRING = 200 # longest string value, unless the parameter says less +_ID = re.compile(r"^[a-z][a-z0-9_]{0,63}$") +_NAME = re.compile(r"^[a-z][a-z0-9_]{0,63}$") +_KEYS = {"id", "description", "sql", "params", "roles"} +_PARAM_KEYS = { + "type", + "description", + "required", + "default", + "enum", + "minimum", + "maximum", + "max_length", +} +_INT64 = 2**63 + + +class CatalogError(PolicyError): + """The catalog is invalid, or a call does not fit it. The message never holds a value.""" + + +@dataclass(frozen=True) +class Param: + """One typed parameter of a verified query.""" + + name: str + type: str + description: str = "" + required: bool = True + default: Any = None + enum: tuple[Any, ...] = () + minimum: float | None = None + maximum: float | None = None + max_length: int = MAX_STRING + + def schema(self) -> dict[str, Any]: + """The parameter as JSON Schema, for the discovery tool.""" + kind = {"date": "string", "number": "number"}.get(self.type, self.type) + data: dict[str, Any] = {"type": kind} + if self.type == "date": + data["format"] = "date" + if self.description: + data["description"] = self.description + if self.enum: + data["enum"] = list(self.enum) + if self.minimum is not None: + data["minimum"] = self.minimum + if self.maximum is not None: + data["maximum"] = self.maximum + if self.type == "string": + data["maxLength"] = self.max_length + if self.default is not None: + data["default"] = self.default + return data + + def convert(self, value: Any) -> Any: + """The value as the Python type that gets bound, or ``CatalogError`` (no value shown).""" + label = f"parameter {self.name}" + if self.type == "boolean": + if not isinstance(value, bool): + raise CatalogError(f"{label} must be true or false") + return value + if self.type == "integer": + if isinstance(value, bool) or not isinstance(value, int) or abs(value) >= _INT64: + raise CatalogError(f"{label} must be an integer") + return self._range(value, label) + if self.type == "number": + if isinstance(value, bool) or not isinstance(value, int | float): + raise CatalogError(f"{label} must be a number") + if not math.isfinite(value): + raise CatalogError(f"{label} must be a finite number") + return self._range(value, label) + if not isinstance(value, str): + raise CatalogError(f"{label} must be a string") + if self.type == "date": + try: + if len(value) != 10: + raise ValueError + converted: Any = datetime.date.fromisoformat(value) + except ValueError: + raise CatalogError(f"{label} must be a date written YYYY-MM-DD") from None + return self._enum(converted, value, label) + if len(value) > self.max_length: + raise CatalogError(f"{label} is longer than {self.max_length} characters") + if "\x00" in value: + raise CatalogError(f"{label} must not contain NUL characters") + return self._enum(value, value, label) + + def _range(self, value: Any, label: str) -> Any: + if self.minimum is not None and value < self.minimum: + raise CatalogError(f"{label} must be at least {self.minimum:g}") + if self.maximum is not None and value > self.maximum: + raise CatalogError(f"{label} must be at most {self.maximum:g}") + return self._enum(value, value, label) + + def _enum(self, converted: Any, original: Any, label: str) -> Any: + if self.enum and original not in self.enum: + raise CatalogError(f"{label} must be one of the values the catalog lists") + return converted + + +@dataclass(frozen=True) +class VerifiedQuery: + """One reviewed query: a stable id, its SQL template and its typed parameters.""" + + id: str + description: str + sql: str + params: tuple[Param, ...] = () + roles: tuple[str, ...] = () + placeholders: frozenset[str] = field(default_factory=frozenset) + counts: Mapping[str, int] = field(default_factory=dict) + + def allows(self, role: str | None) -> bool: + """Whether ``role`` may see and run it (every role when the query lists none).""" + return not self.roles or (role is not None and role in self.roles) + + def describe(self) -> dict[str, Any]: + """What discovery tells an agent: the id, the description and the parameters.""" + required = [p.name for p in self.params if p.required and p.default is None] + return { + "id": self.id, + "description": self.description, + "parameters": { + "type": "object", + "properties": {p.name: p.schema() for p in self.params}, + "required": required, + "additionalProperties": False, + }, + } + + def bind(self, given: Mapping[str, Any] | None) -> dict[str, Any]: + """Check ``given`` against the declared parameters and return the values to bind. + + Raises ``CatalogError`` for an unknown, missing or invalid parameter. The message names + parameters, never their values. + """ + values = dict(given or {}) + known = {p.name for p in self.params} + unknown = sorted(str(k) for k in values if k not in known) + if unknown: + raise CatalogError(f"unknown parameter(s): {', '.join(unknown)}") + bound: dict[str, Any] = {} + missing: list[str] = [] + for param in self.params: + if param.name in values: + bound[param.name] = param.convert(values[param.name]) + elif param.default is not None: + bound[param.name] = param.convert(param.default) + elif param.required: + missing.append(param.name) + else: + bound[param.name] = None + if missing: + raise CatalogError(f"missing parameter(s): {', '.join(missing)}") + return bound + + +def placeholder_counts(sql: str, dialect: str) -> dict[str, int]: + """How many times each ``:name`` placeholder of ``sql`` is used. Anything else that binds is + refused.""" + try: + statements = [s for s in sqlglot.parse(sql, read=dialect) if s is not None] + except SqlglotError: + raise CatalogError("the SQL could not be parsed") from None + if len(statements) != 1: + raise CatalogError("a verified query is exactly one statement") + counts: dict[str, int] = {} + for node in statements[0].find_all(exp.Placeholder, exp.Parameter): + name = _placeholder_name(node) if isinstance(node, exp.Placeholder) else None + if name is None: + raise CatalogError("write parameters as :name (lowercase letters, digits, _)") + counts[name] = counts.get(name, 0) + 1 + return counts + + +def placeholders_of(sql: str, dialect: str) -> frozenset[str]: + """The names of the ``:name`` placeholders of ``sql``.""" + return frozenset(placeholder_counts(sql, dialect)) + + +def _placeholder_name(node: exp.Expr) -> str | None: + """The name of a named placeholder, in any dialect's spelling (PostgreSQL's ``%(name)s`` + carries it in an identifier), or ``None`` for ``?``, ``$1`` and the like.""" + name = node.this + if isinstance(name, exp.Identifier): + name = name.name + return name if isinstance(name, str) and _NAME.match(name) else None + + +def to_bound(sql: str, dialect: str) -> tuple[str, dict[str, int]]: + """``sql`` ready for SQLAlchemy's ``text()``, and how many times each placeholder is used. + + The SQL is read back after the guard rewrote it, where each dialect spells a placeholder its + own way (``%(n)s``, ``@n``, ``$n``). Every placeholder is replaced on the tree by a unique + marker, the SQL is written again, **every remaining colon is escaped** (``::`` casts, + ``'12:30'``, a tenant value such as ``'a:b'`` that a row filter wrote in) and only then are + the markers turned into ``:name``. Nothing but a real placeholder can bind a value. + """ + try: + tree = sqlglot.parse_one(sql, read=dialect) + except SqlglotError: + raise CatalogError("the SQL could not be read back") from None + token = secrets.token_hex(8) + names: dict[str, int] = {} + count = 0 + for node in list(tree.find_all(exp.Placeholder, exp.Parameter)): + name = _placeholder_name(node) if isinstance(node, exp.Placeholder) else None + if name is None: + raise CatalogError("only :name parameters can be bound") + names[name] = names.get(name, 0) + 1 + count += 1 + node.replace(exp.Var(this=f"__sgbind{token}_{name}__")) + text = tree.sql(dialect=dialect).replace(":", "\\:") + text, replaced = re.subn(rf"__sgbind{token}_([a-z][a-z0-9_]*)__", r":\1", text) + if replaced != count: + raise CatalogError("a parameter did not survive the rewrite") + return text, names + + +def _param(name: str, raw: Any) -> Param: + if not _NAME.match(name): + raise CatalogError(f"invalid parameter name: {name!r}") + if not isinstance(raw, Mapping) or set(raw) - _PARAM_KEYS: + raise CatalogError(f"parameter {name} takes only: {', '.join(sorted(_PARAM_KEYS))}") + kind = raw.get("type") + if kind not in TYPES: + raise CatalogError(f"parameter {name}: type must be one of {', '.join(TYPES)}") + required = raw.get("required", True) + if not isinstance(required, bool): + raise CatalogError(f"parameter {name}: required must be true or false") + description = raw.get("description", "") + if not isinstance(description, str): + raise CatalogError(f"parameter {name}: description must be a string") + limits: dict[str, float | None] = {} + for key in ("minimum", "maximum"): + value = raw.get(key) + if value is not None and ( + isinstance(value, bool) + or not isinstance(value, int | float) + or kind not in ("integer", "number") + ): + raise CatalogError(f"parameter {name}: {key} needs a number on an integer or number") + limits[key] = value + if ( + limits["minimum"] is not None + and limits["maximum"] is not None + and limits["minimum"] > limits["maximum"] + ): + raise CatalogError(f"parameter {name}: minimum is above maximum") + max_length = raw.get("max_length", MAX_STRING) + if isinstance(max_length, bool) or not isinstance(max_length, int) or not max_length >= 1: + raise CatalogError(f"parameter {name}: max_length must be a positive integer") + enum = raw.get("enum", ()) + if not isinstance(enum, Sequence) or isinstance(enum, str): + raise CatalogError(f"parameter {name}: enum must be a list") + param = Param( + name=name, + type=kind, + description=description, + required=required, + default=raw.get("default"), + enum=tuple(enum), + minimum=limits["minimum"], + maximum=limits["maximum"], + max_length=min(max_length, MAX_STRING), + ) + for sample in (*param.enum, *([param.default] if param.default is not None else [])): + param.convert(sample) # a default or enum value that its own type refuses is a mistake + return param + + +def _query(raw: Any, index: int, dialect: str) -> VerifiedQuery: + where = f"query {index}" + if not isinstance(raw, Mapping) or set(raw) - _KEYS: + raise CatalogError(f"{where}: takes only {', '.join(sorted(_KEYS))}") + query_id = raw.get("id") + if not isinstance(query_id, str) or not _ID.match(query_id): + raise CatalogError(f"{where}: id must be lowercase letters, digits and _, from a letter") + where = f"query {query_id}" + sql, description = raw.get("sql"), raw.get("description") + if not isinstance(sql, str) or not sql.strip(): + raise CatalogError(f"{where}: sql must be a non-empty string") + if not isinstance(description, str) or not description.strip(): + raise CatalogError(f"{where}: description must be a non-empty string") + roles = raw.get("roles", ()) + if ( + isinstance(roles, str) + or not isinstance(roles, Sequence) + or not all(isinstance(r, str) and r for r in roles) + ): + raise CatalogError(f"{where}: roles must be a list of role names") + declared = raw.get("params", {}) + if not isinstance(declared, Mapping): + raise CatalogError(f"{where}: params must map names to definitions") + try: + params = tuple(_param(str(name), spec) for name, spec in declared.items()) + counts = placeholder_counts(sql, dialect) + found = frozenset(counts) + except CatalogError as exc: + raise CatalogError(f"{where}: {exc}") from None + names = {p.name for p in params} + if found - names: + raise CatalogError(f"{where}: undeclared parameter(s): {', '.join(sorted(found - names))}") + if names - found: + raise CatalogError(f"{where}: unused parameter(s): {', '.join(sorted(names - found))}") + return VerifiedQuery( + query_id, description.strip(), sql.strip(), params, tuple(roles), found, counts + ) + + +def check_against_policy( + catalog: Catalog, + guard: Guard, + context: Mapping[str, Any] | None = None, + role: str | None = None, +) -> tuple[VerifiedQuery, ...]: + """Check that every query ``role`` can see passes ``guard`` and keeps all its placeholders. + + Returns those queries. Raises ``CatalogError`` for the first one the policy refuses, or whose + rewrite (row filters, masks, the limit) would lose a parameter. + """ + policy = guard.policy + target = (policy.output_dialect or policy.dialect).lower() + if catalog.dialect.lower() not in (policy.dialect.lower(), target): + raise CatalogError( + f"the catalog is written for {catalog.dialect} but the policy uses {policy.dialect}" + ) + visible = catalog.visible_to(role) + for entry in visible: + result = guard.explain(entry.sql, context) # not check(): a startup check is no decision + if not result.ok or result.sql is None: + codes = ", ".join(sorted(c.value for c in result.codes)) + raise CatalogError(f"query {entry.id} is refused by the policy ({codes})") + if to_bound(result.sql, target)[1] != entry.counts: + raise CatalogError( + f"query {entry.id}: the policy rewrite loses a parameter (a LIMIT given as a " + "parameter is replaced by the policy's row limit: write a number instead)" + ) + return visible + + +@dataclass(frozen=True) +class Catalog: + """A versioned set of verified queries.""" + + version: str + dialect: str + queries: tuple[VerifiedQuery, ...] + + def get(self, query_id: str) -> VerifiedQuery | None: + return next((q for q in self.queries if q.id == query_id), None) + + def visible_to(self, role: str | None) -> tuple[VerifiedQuery, ...]: + """The queries ``role`` may see, in file order.""" + return tuple(q for q in self.queries if q.allows(role)) + + @classmethod + def from_dict(cls, data: Mapping[str, Any]) -> Catalog: + if set(data) - {"version", "dialect", "queries"}: + raise CatalogError("a catalog has only version, dialect and queries") + version = data.get("version") + if isinstance(version, bool) or not isinstance(version, str | int) or version == "": + raise CatalogError("version must be a non-empty string or an integer") + dialect = data.get("dialect", "postgres") + if not isinstance(dialect, str): + raise CatalogError("dialect must be a string") + raw = data.get("queries") + if not isinstance(raw, Sequence) or isinstance(raw, str) or not raw: + raise CatalogError("queries must be a non-empty list") + queries = tuple(_query(item, i, dialect) for i, item in enumerate(raw, 1)) + ids = [q.id for q in queries] + duplicated = sorted({i for i in ids if ids.count(i) > 1}) + if duplicated: + raise CatalogError(f"duplicate query id(s): {', '.join(duplicated)}") + return cls(str(version), dialect, queries) + + @classmethod + def from_file(cls, path: str | Path) -> Catalog: + """Load a ``.json``, ``.yaml`` or ``.yml`` catalog.""" + try: + return cls.from_dict(read_mapping(path)) + except OSError as exc: + raise CatalogError(f"cannot read the catalog: {type(exc).__name__}") from None diff --git a/src/sqlguardllm/cli.py b/src/sqlguardllm/cli.py index 654d48f..a010bd3 100644 --- a/src/sqlguardllm/cli.py +++ b/src/sqlguardllm/cli.py @@ -41,7 +41,7 @@ from sqlguardllm.guard import Guard from sqlguardllm.lint import DEFAULT_MAX_ROWS_THRESHOLD, format_report, lint_file from sqlguardllm.messages import LANGUAGES -from sqlguardllm.policy import Policy +from sqlguardllm.policy import Policy, read_mapping from sqlguardllm.policy_set import PolicySet from sqlguardllm.result import CheckResult, PolicyError, violation_to_dict from sqlguardllm.schema import policy_schema, policy_set_schema, policy_tests_schema @@ -194,6 +194,14 @@ def _parser() -> argparse.ArgumentParser: default=None, help="refuse queries whose EXPLAIN row estimate exceeds this (not SQLite)", ) + mcp.add_argument( + "--catalog", + type=Path, + default=None, + metavar="FILE", + help="experimental: a catalog of verified queries (.yaml or .json) the agent may run " + "by id, with typed parameters, through run_verified_query", + ) mcp.add_argument( "--plan-full-scan", action="append", @@ -386,6 +394,25 @@ def _parser() -> argparse.ArgumentParser: red_report.add_argument("--compare-with", type=Path, help="a second saved report") red_report.add_argument("--format", choices=("md",), default="md", help="output format") + catalog = commands.add_parser( + "catalog", + help="experimental: check a catalog of verified queries against a policy", + description="Validates the catalog file (ids, typed parameters, placeholders) and, with " + "--policy, that every query visible to --role passes the guard with its parameters " + "intact. Exit code 0 when it fits, 1 when the policy refuses a query, 2 when the catalog " + "or the policy cannot be read.", + ) + catalog_commands = catalog.add_subparsers(dest="catalog_command", required=True) + catalog_check = catalog_commands.add_parser("check", help="validate a catalog") + catalog_check.add_argument("file", type=Path, help="the catalog (.yaml or .json)") + catalog_check.add_argument("--policy", type=Path, default=None, help="policy or policy set") + catalog_check.add_argument( + "--role", default=None, help="role of a policy set (or of the server)" + ) + catalog_check.add_argument( + "--context", default=None, help="trusted context JSON, or @file.json, for row filters" + ) + classify = commands.add_parser( "classify", help="experimental: propose data classes for the columns of a database, by their names", @@ -635,6 +662,49 @@ def _redteam(args: argparse.Namespace, command: list[str], stdout: TextIO) -> in return exit_status(report) +def _catalog(args: argparse.Namespace, stdout: TextIO) -> int: + from sqlguardllm.catalog import ( # noqa: PLC0415 - only this command + Catalog, + CatalogError, + check_against_policy, + ) + + try: + catalog = Catalog.from_file(args.file) + except (CatalogError, PolicyError, ValueError) as exc: + raise _UsageError(f"invalid catalog {args.file}: {exc}") from exc + print( + f"catalog {catalog.version}: {len(catalog.queries)} queries, " + f"{', '.join(q.id for q in catalog.queries)}", + file=stdout, + ) + if args.policy is None: + return EXIT_OK + context = _read_context(args.context) + guard_role = args.role + try: + data = read_mapping(args.policy) + if "base" in data or "roles" in data: + if guard_role is None: + raise _UsageError("a policy set needs --role") + guard = PolicySet.from_dict(data).guard(guard_role) + else: + guard = Guard(Policy.from_dict(data), role=guard_role) + except (OSError, PolicyError, ValueError) as exc: + raise _UsageError(f"invalid policy {args.policy}: {exc}") from exc + try: + visible = check_against_policy(catalog, guard, context, guard_role) + except CatalogError as exc: + print(f"refused: {exc}", file=stdout) + return EXIT_REJECTED + print( + f"ok: {len(visible)} queries pass the policy" + + (f" for role {guard_role}" if guard_role else ""), + file=stdout, + ) + return EXIT_OK + + def _classify(args: argparse.Namespace, stdout: TextIO) -> int: from sqlguardllm.classes import ( # noqa: PLC0415 - only this command MAX_SAMPLE, @@ -847,6 +917,7 @@ def _run_mcp( max_plan_rows=args.max_plan_rows, plan_full_scan=args.plan_full_scan, plan_on_exceed=args.plan_on_exceed, + catalog=args.catalog, audit=audit if audit is not None else _audit_log(args), role=args.role, demo=args.demo, @@ -1050,6 +1121,8 @@ def main( return EXIT_OK if args.command == "test": return _test(args, stdout) + if args.command == "catalog": + return _catalog(args, stdout) if args.command == "classify": return _classify(args, stdout) if args.command == "lint": diff --git a/src/sqlguardllm/mcp_server.py b/src/sqlguardllm/mcp_server.py index 89814bf..911a20f 100644 --- a/src/sqlguardllm/mcp_server.py +++ b/src/sqlguardllm/mcp_server.py @@ -43,7 +43,7 @@ from mcp.server.mcpserver.exceptions import ToolError from mcp.types import ToolAnnotations from pydantic import BaseModel, ConfigDict, Field, with_config -from sqlalchemy import create_engine, inspect +from sqlalchemy import create_engine, inspect, text from sqlalchemy.engine import Connection, Engine, Inspector from sqlalchemy.engine.interfaces import ReflectedColumn, ReflectedForeignKeyConstraint from sqlalchemy.exc import ( @@ -60,8 +60,14 @@ from sqlguardllm._compiled import Compiled from sqlguardllm._cost import ENGINES, CostEstimate, explain_statements, parse_plan from sqlguardllm._names import TableName, find, norm, parse_table_entry -from sqlguardllm.audit import AuditEvent, AuditLog, audit_subject +from sqlguardllm.audit import AuditEvent, AuditLog, audit_catalog, audit_subject from sqlguardllm.auth import AuthError, OIDCVerifier, claims_to_context +from sqlguardllm.catalog import ( + Catalog, + CatalogError, + check_against_policy, + to_bound, +) from sqlguardllm.demo import DEMO_NOTICE from sqlguardllm.explain import Explanation from sqlguardllm.guard import Guard @@ -120,6 +126,10 @@ "inténtalo de nuevo" ), }, + "unknown_verified": { + "en": "There is no verified query with that id for your role", + "es": "No hay ninguna consulta verificada con ese id para tu rol", + }, "full_scan": { "en": ( "The query would read {tables} in full. Add a filter (WHERE) on an indexed column " @@ -218,6 +228,19 @@ class DescribeTableOutput(TypedDict): select_star_allowed: bool +@with_config(ConfigDict(extra="allow")) +class VerifiedQueriesOutput(TypedDict): + catalog_version: str + queries: list[dict[str, Any]] + + +_QueryIdArg = Annotated[ + str, Field(description="Id of a verified query, as list_verified_queries shows it") +] +_ParamsArg = Annotated[ + dict[str, Any] | None, Field(description="Values for the parameters that query declares") +] + _READ_ONLY = ToolAnnotations( read_only_hint=True, destructive_hint=False, idempotent_hint=True, open_world_hint=False ) @@ -257,6 +280,12 @@ class _Approval(BaseModel): every row: narrow the query or aggregate.""" +_VERIFIED_INSTRUCTIONS = """ +Verified queries are approved definitions of business metrics. When one fits the question, call +list_verified_queries and then run_verified_query with its id and typed values instead of writing +SQL: the definition is reviewed and the SQL is owned by the server.""" + + def _approval_mode(writes: Any) -> str: """The approval setting of a writes policy ("required" unless it says "none").""" if isinstance(writes, Mapping): @@ -358,13 +387,15 @@ def _begin_read_only(conn: Connection, timeout: float) -> Callable[[], None]: _COST_BACKENDS = tuple(ENGINES) -def _explain_estimate(conn: Connection, sql: str) -> CostEstimate: +def _explain_estimate( + conn: Connection, sql: str, binds: Mapping[str, Any] | None = None +) -> CostEstimate: """Ask the engine for its plan in JSON and read the estimate. Never executes ``sql``.""" backend = conn.dialect.name statements = explain_statements(backend, sql) if statements is None: raise ValueError(f"cost estimates are not supported for {backend}") - return parse_plan(backend, sqlalchemy_runner(conn)(statements)) + return parse_plan(backend, sqlalchemy_runner(conn, bind=binds)(statements)) def _fmt(value: float) -> str: @@ -424,6 +455,7 @@ def __init__( self.extra_untrusted: frozenset[str] = frozenset() self.result_policy: ResultPolicy | None = None self.row_budgets: RowBudgets | None = None + self.catalog: Catalog | None = None # verified queries, opt-in (experimental) self.max_cost = max_cost self.max_plan_rows = max_plan_rows self.plan_full_scan = plan_full_scan @@ -821,7 +853,14 @@ def cost_guard(self) -> bool: self.max_cost is not None or self.max_plan_rows is not None or bool(self.plan_full_scan) ) - def _check_cost(self, conn: Connection, sql: str) -> list[str]: + def _check_cost( + self, + conn: Connection, + sql: str, + binds: Mapping[str, Any] | None = None, + *, + explained: str | None = None, + ) -> list[str]: """Judge the plan of a query the guard allowed. Fails closed when a rule is set. A broken rule, or a plan that can't be read, refuses the query (``on_exceed: deny``) or is @@ -831,7 +870,10 @@ def _check_cost(self, conn: Connection, sql: str) -> list[str]: return [] warn = self.plan_on_exceed == "warn" try: - estimate = (self.estimator or _explain_estimate)(conn, sql) + if self.estimator is not None: + estimate = self.estimator(conn, sql) + else: + estimate = _explain_estimate(conn, explained or sql, binds) except Exception as exc: # EXPLAIN failed or its output can't be read: don't run blind if isinstance(exc, DBAPIError) and exc.connection_invalidated: raise @@ -913,6 +955,21 @@ def _estimate_report(self, sql: str) -> dict[str, Any] | None: def query(self, sql: _SqlArg, ctx: Context = None) -> QueryOutput: # type: ignore[assignment] """Run a read-only query and return its rows.""" + return self._run_query(sql, ctx) + + def _run_query( + self, + sql: str, + ctx: Context | None = None, + *, + binds: Mapping[str, Any] | None = None, + uses: Mapping[str, int] | None = None, + ) -> QueryOutput: + """The checks, the read-only run and the delivery of one query. + + ``binds`` are the values of a verified query's ``:name`` placeholders. They are bound by + the driver and never written into the SQL; ``sql`` is then the reviewed template. + """ # The taint check comes first, so a query it refuses is recorded once, as a refusal, and # never as an allowed query. reading: frozenset[str] = frozenset() @@ -932,6 +989,17 @@ def query(self, sql: _SqlArg, ctx: Context = None) -> QueryOutput: # type: igno probe = self._probe.check(sql, self._context) if probe.ok and probe.sql is not None: run_sql = probe.sql # same query, one more row allowed: tells "cut" from "full" + bound_sql = "" + if binds is not None: + try: + bound_sql, kept = to_bound(run_sql, self.compiled.output_dialect_name) + except CatalogError as exc: + raise ToolError(f"invalid_parameters: {exc}") from None + if kept != dict(uses or dict.fromkeys(binds, 1)): + raise ToolError( + "the policy rewrote this verified query and lost a parameter (a LIMIT given as " + "a parameter is replaced by the row limit)" + ) @functools.cache def budget_session() -> str | None: @@ -994,14 +1062,21 @@ def budget_session() -> str | None: plan_warnings: list[str] = [] started = time.monotonic() try: - # no_parameters: percent signs in LIKE patterns reach the driver untouched. - conn = conn.execution_options(no_parameters=True) + if binds is None: + # no_parameters: percent signs in LIKE patterns reach the driver untouched. + conn = conn.execution_options(no_parameters=True) transaction = conn.begin() try: restore = _begin_read_only(conn, self.timeout) try: - plan_warnings = self._check_cost(conn, run_sql) - result = conn.exec_driver_sql(run_sql) + plan_warnings = self._check_cost( + conn, run_sql, binds, explained=bound_sql or None + ) + result = ( + conn.exec_driver_sql(run_sql) + if binds is None + else conn.execute(text(bound_sql), dict(binds)) + ) columns = list(map(str, result.keys())) # not iter(result): rows rows = result.fetchmany(self.max_rows + 1) result.close() @@ -1047,6 +1122,45 @@ def budget_session() -> str | None: sql, explanation, columns, serialized_rows, truncated, plan_warnings=plan_warnings ) + # Verified queries (experimental) ---------------------------------------------------------- + + def _verified(self) -> tuple[Catalog, str | None]: + if self.catalog is None: + raise ToolError("verified queries are not enabled on this server") + return self.catalog, getattr(self.guard, "_role", None) + + def list_verified_queries(self) -> VerifiedQueriesOutput: + """List the approved queries you may run by id, with the parameters each takes.""" + catalog, role = self._verified() + return cast( + VerifiedQueriesOutput, + { + "catalog_version": catalog.version, + "queries": [entry.describe() for entry in catalog.visible_to(role)], + }, + ) + + def run_verified_query( + self, + query_id: _QueryIdArg, + parameters: _ParamsArg = None, + ctx: Context = None, # type: ignore[assignment] + ) -> QueryOutput: + """Run an approved query by id with typed values. The server owns the SQL.""" + catalog, role = self._verified() + entry = catalog.get(query_id) + if entry is None or not entry.allows(role): # one answer for "missing" and "not yours" + raise ToolError(self._text("unknown_verified")) + try: + bound = entry.bind(parameters) + except CatalogError as exc: + raise ToolError(f"invalid_parameters: {exc}") from None + with audit_catalog(entry.id, catalog.version): + result = self._run_query(entry.sql, ctx, binds=bound, uses=entry.counts) + return cast( + QueryOutput, {**result, "query_id": entry.id, "catalog_version": catalog.version} + ) + def _row_budget_exceeded(self) -> ToolError: message = ( "Se agotó el presupuesto de filas de la sesión o no se pudo verificar." @@ -1449,6 +1563,31 @@ def _create_engine(url: str) -> Engine: ) from None +def _validate_catalog( + catalog: Catalog, + guard: Guard, + context: Mapping[str, Any] | None, + *, + role: str | None, + policy_set: PolicySet | None, + authenticated: bool, +) -> None: + """Refuse a catalog the policy would not run, at startup instead of at the first call. + + Every query visible to the server's role must pass the guard and come out with all its + placeholders. With authentication the context comes from each caller's token, which is not + known here, so the check happens on every call instead; the role names are still checked. + """ + if policy_set is not None: + known = set(policy_set.roles) + for entry in catalog.queries: + unknown = sorted(set(entry.roles) - known) + if unknown: + raise CatalogError(f"query {entry.id}: unknown role(s): {', '.join(unknown)}") + if not authenticated: + check_against_policy(catalog, guard, context, role) + + def create_server( policy: Policy, database: str | Engine, @@ -1461,6 +1600,7 @@ def create_server( max_plan_rows: float | None = None, plan_full_scan: Collection[str] = (), plan_on_exceed: str = "deny", + catalog: Catalog | str | Path | None = None, estimator: Estimator | None = None, audit: AuditLog | Callable[[AuditEvent], None] | None = None, role: str | None = None, @@ -1618,8 +1758,20 @@ def create_server( tools.row_budgets = row_budgets tools.result_policy = result_policy if isinstance(result_policy, ResultPolicy) else None binder: _CallerBinder | None = None + verified: Catalog | None = None try: _validate_taint_settings(tools) + if catalog is not None: + verified = catalog if isinstance(catalog, Catalog) else Catalog.from_file(catalog) + _validate_catalog( + verified, + guard, + context, + role=role, + policy_set=policy_set, + authenticated=auth is not None, + ) + tools.catalog = verified if auth is not None: views: dict[str | None, _Tools] = {} names: list[str | None] = list(policy_set.roles) if policy_set is not None else [None] @@ -1649,6 +1801,7 @@ def create_server( view._sessions = tools._sessions view._taint_lock = tools._taint_lock view.row_budgets = row_budgets + view.catalog = verified view.result_policy = role_results.get(role_name or "", tools.result_policy) views[role_name] = view base = policy_set.base if policy_set is not None else policy @@ -1718,6 +1871,7 @@ async def lifespan(_: MCPServer[Any]) -> AsyncIterator[None]: version=__version__, instructions=_INSTRUCTIONS.format(dialect=policy.dialect, max_rows=tools.max_rows) + (_WRITE_INSTRUCTIONS if write_tools is not None else "") + + (_VERIFIED_INSTRUCTIONS if verified is not None else "") + (f"\n{DEMO_NOTICE}" if demo else ""), lifespan=lifespan, **( @@ -1791,6 +1945,30 @@ def scoped(method: Any) -> Any: ), annotations=_READ_ONLY, ) + if verified is not None: + server.add_tool( + scoped(tools.list_verified_queries), + name="list_verified_queries", + title="List verified queries", + description=( + "List the approved business queries you may run by id, with the typed " + "parameters each takes. Prefer one of them over writing SQL when it fits the " + "question: the definition is reviewed." + note + ), + annotations=_READ_ONLY, + ) + server.add_tool( + scoped(tools.run_verified_query), + name="run_verified_query", + title="Run a verified query", + description=( + "Run an approved query by id with typed values for its parameters. The server " + "owns the SQL: values are bound, never written into it. The same policy, row " + "filters, masks, row limit and timeout apply as for query, and the result says " + "what the guard did, as query's does." + note + ), + annotations=_READ_ONLY, + ) if write_tools is not None: server.add_tool( write_tools.propose_write, diff --git a/src/sqlguardllm/plan.py b/src/sqlguardllm/plan.py index f0bfda8..5d98888 100644 --- a/src/sqlguardllm/plan.py +++ b/src/sqlguardllm/plan.py @@ -233,23 +233,36 @@ def _action(self) -> str: return "warn" if self.on_exceed == "warn" else "deny" -def sqlalchemy_runner(connection: Any) -> Callable[[Sequence[str]], str]: +def sqlalchemy_runner( + connection: Any, bind: Mapping[str, Any] | None = None +) -> Callable[[Sequence[str]], str]: """A ``run_explain`` for a SQLAlchemy connection (anything with ``exec_driver_sql`` and a ``dialect.name``). It runs the statements in order and returns the plan text. Nothing is - committed; roll the transaction back as you do for the query itself.""" + committed; roll the transaction back as you do for the query itself. + + ``bind`` gives the values of ``:name`` placeholders in the SQL (a verified query); the + statements then run through ``text()``, with only the values each one uses.""" + + def execute(statement: str) -> Any: + if bind is None: + return connection.exec_driver_sql(statement) + from sqlalchemy import text # noqa: PLC0415 - only needed with bound values + + used = {name: value for name, value in bind.items() if f":{name}" in statement} + return connection.execute(text(statement), used) def run(statements: Sequence[str]) -> str: backend = connection.dialect.name if backend == "mssql": # SHOWPLAN is a session setting: ON, the query returns the plan, OFF - connection.exec_driver_sql(statements[0]) + execute(statements[0]) try: - row = connection.exec_driver_sql(statements[1]).fetchone() + row = execute(statements[1]).fetchone() finally: - connection.exec_driver_sql(statements[2]) + execute(statements[2]) if row is None: raise ValueError("SQL Server returned no plan") return _text(row[0]) - result = connection.exec_driver_sql(statements[0]) + result = execute(statements[0]) if backend == "sqlite": # rows of (id, parent, notused, detail) return "\n".join(str(row[3]) for row in result) row = result.fetchone() diff --git a/tests/engines/test_catalog_engines.py b/tests/engines/test_catalog_engines.py new file mode 100644 index 0000000..3f8bb73 --- /dev/null +++ b/tests/engines/test_catalog_engines.py @@ -0,0 +1,179 @@ +"""Verified queries on a real PostgreSQL (#287): the examples, their expected business results, +tenant isolation, masks, the row limit, the audit trail, and a changed metric being caught.""" + +from __future__ import annotations + +import dataclasses +import json +import os +from collections.abc import Iterator +from pathlib import Path +from typing import Any +from uuid import uuid4 + +import anyio +import pytest +from mcp import Client + +from sqlguardllm import PolicySet +from sqlguardllm.catalog import Catalog +from sqlguardllm.mcp_server import create_server + +sa = pytest.importorskip("sqlalchemy") +EXAMPLES = Path(__file__).parents[2] / "examples" / "catalog" +EXPECTED = json.loads((EXAMPLES / "expected.json").read_text(encoding="utf-8"))["cases"] +POLICIES = PolicySet.from_file(EXAMPLES / "policy.yaml") +CONTEXT = json.loads((EXAMPLES / "context.json").read_text(encoding="utf-8")) + + +@pytest.fixture +def url() -> Iterator[str]: + base = os.environ.get("SQLGUARD_PG_URL") + if not base: + if os.environ.get("SQLGUARD_REQUIRE_ENGINES") == "1": + pytest.fail("PostgreSQL: SQLGUARD_PG_URL not set") + pytest.skip("PostgreSQL: SQLGUARD_PG_URL not set") + name = f"sg_catalog_{uuid4().hex[:12]}" + admin = sa.create_engine(base, isolation_level="AUTOCOMMIT") + with admin.connect() as conn: + conn.exec_driver_sql(f"CREATE DATABASE {name}") + target = sa.make_url(base).set(database=name) + engine = sa.create_engine(target) + with engine.begin() as conn: + conn.exec_driver_sql((EXAMPLES / "fixtures.sql").read_text("utf-8")) + engine.dispose() + try: + yield target.render_as_string(hide_password=False) + finally: + with admin.connect() as conn: + conn.exec_driver_sql(f"DROP DATABASE IF EXISTS {name} WITH (FORCE)") + admin.dispose() + + +def server(url: str, role: str, catalog: Any = None, **options: Any) -> Any: + return create_server( + POLICIES.for_role(role), + url, + context=options.pop("context", CONTEXT), + role=role, + catalog=catalog if catalog is not None else EXAMPLES / "catalog.yaml", + **options, + ) + + +def call(srv: Any, tool: str, **args: Any) -> Any: + async def go() -> Any: + async with Client(srv) as client: + return await client.call_tool(tool, args) + + return anyio.run(go) + + +def run(srv: Any, query_id: str, parameters: dict[str, Any]) -> Any: + return call(srv, "run_verified_query", query_id=query_id, parameters=parameters) + + +@pytest.mark.parametrize("case", EXPECTED, ids=[f"{c['id']}-{c['role']}" for c in EXPECTED]) +def test_the_examples_return_their_expected_business_results( + url: str, case: dict[str, Any] +) -> None: + result = run(server(url, case["role"]), case["id"], case["parameters"]) + assert not result.is_error, result.content + data = result.structured_content + assert data["columns"] == case["columns"] and data["rows"] == case["rows"] + assert data["query_id"] == case["id"] and data["catalog_version"] == "2026-12-01" + + +def test_a_changed_metric_definition_is_caught_by_the_expected_results(url: str) -> None: + """Gross sales instead of net sales: valid SQL, passes the policy, and the wrong number.""" + definition = json.loads(json.dumps(_as_dict(Catalog.from_file(EXAMPLES / "catalog.yaml")))) + sales = next(q for q in definition["queries"] if q["id"] == "net_sales_by_month") + sales["sql"] = sales["sql"].replace("SUM(total - discount)", "SUM(total)") + changed = Catalog.from_dict(definition) + case = next(c for c in EXPECTED if c["id"] == "net_sales_by_month" and c["role"] == "analyst") + got = run(server(url, "analyst", catalog=changed), case["id"], case["parameters"]) + assert not got.is_error # the policy cannot tell: that is why the expected results exist + assert got.structured_content["rows"] != case["rows"] + assert got.structured_content["rows"] == [["2026-01", 300], ["2026-02", 200], ["2026-03", 300]] + + +def _as_dict(catalog: Catalog) -> dict[str, Any]: + return { + "version": catalog.version, + "dialect": catalog.dialect, + "queries": [ + { + "id": q.id, + "description": q.description, + "sql": q.sql, + "roles": list(q.roles), + "params": { + p.name: {"type": p.type, "required": p.required, "description": p.description} + for p in q.params + }, + } + for q in catalog.queries + ], + } + + +def test_a_role_that_may_not_see_a_query_cannot_discover_or_invoke_it(url: str) -> None: + analyst = server(url, "analyst") + listed = call(analyst, "list_verified_queries").structured_content + assert [q["id"] for q in listed["queries"]] == [ + "net_sales_by_month", + "top_customers_by_net_sales", + ] + hidden = run(analyst, "customer_directory", {"pattern": "%"}) + missing = run(analyst, "no_such_query", {}) + assert hidden.is_error and missing.is_error + assert str(hidden.content) == str(missing.content) + + +def test_tenants_receive_only_their_own_rows(url: str) -> None: + first = run(server(url, "analyst"), "net_sales_by_month", EXPECTED[0]["parameters"]) + other = server(url, "analyst", context={"user": {"tenant": "t2"}}) + second = run(other, "net_sales_by_month", EXPECTED[0]["parameters"]) + assert first.structured_content["rows"] == EXPECTED[0]["rows"] + assert second.structured_content["rows"] == [["2026-01", 900]] # Eva's 999 - 99, nobody else's + + +def test_masks_and_the_row_limit_apply_to_verified_queries(url: str) -> None: + manager = server(url, "manager") + directory = run(manager, "customer_directory", {"pattern": "%"}).structured_content + assert directory["rows"] == [["Ana", "an***"], ["Luis", "lu***"]] + assert "acme.test" not in json.dumps(directory) + capped = create_server( + dataclasses.replace(POLICIES.for_role("manager"), max_rows=1), + url, + context=CONTEXT, + role="manager", + catalog=EXAMPLES / "catalog.yaml", + ) + cut = run(capped, "customer_directory", {"pattern": "%"}).structured_content + assert cut["row_count"] == 1 and cut["truncated"] is True + + +def test_audit_events_hold_the_id_and_version_and_no_value_or_row(url: str) -> None: + events: list[Any] = [] + srv = server(url, "manager", audit=events.append) + run(srv, "customer_directory", {"pattern": "A%"}) + run(srv, "net_sales_by_month", EXPECTED[0]["parameters"]) + assert [(e.catalog_query, e.catalog_version) for e in events] == [ + ("customer_directory", "2026-12-01"), + ("net_sales_by_month", "2026-12-01"), + ] + dump = json.dumps([e.to_dict() for e in events]) + assert "A%" not in dump and "Ana" not in dump and "2026-01-01" not in dump + assert all(e.allowed for e in events) + + +def test_invalid_parameters_never_reach_the_database(url: str) -> None: + srv = server(url, "analyst") + for params in ( + {}, + {"from_date": "tomorrow", "to_date": "2026-04-01"}, + {"from_date": "2026-01-01", "to_date": "2026-04-01", "x": 1}, + ): + result = run(srv, "net_sales_by_month", params) + assert result.is_error and "invalid_parameters" in str(result.content) diff --git a/tests/test_catalog.py b/tests/test_catalog.py new file mode 100644 index 0000000..c01c75a --- /dev/null +++ b/tests/test_catalog.py @@ -0,0 +1,609 @@ +"""Verified queries (#287): the catalog format, typed parameters and the MCP tools on SQLite.""" + +from __future__ import annotations + +import io +import json +import re +import sqlite3 +from pathlib import Path +from typing import Any + +import anyio +import pytest +import yaml +from mcp import Client +from mcp.types import CallToolResult + +from sqlguardllm import AuditLog, PolicySet +from sqlguardllm import Policy as GuardPolicy +from sqlguardllm.catalog import ( + Catalog, + CatalogError, + check_against_policy, + placeholder_counts, + placeholders_of, + to_bound, +) +from sqlguardllm.cli import main +from sqlguardllm.mcp_server import create_server + +EXAMPLES = Path(__file__).parents[1] / "examples" / "catalog" +SECRET = "secret-value-7f3a" + + +def catalog( + *queries: dict[str, Any], dialect: str = "sqlite", version: Any = "v1" +) -> dict[str, Any]: + return {"version": version, "dialect": dialect, "queries": list(queries)} + + +def query(**changes: Any) -> dict[str, Any]: + base: dict[str, Any] = { + "id": "sales", + "description": "Net sales.", + "sql": "SELECT SUM(total - discount) AS net FROM invoices WHERE issued_at >= :since", + "params": {"since": {"type": "date"}}, + } + base.update(changes) + return {k: v for k, v in base.items() if v is not None} + + +# --- the format --------------------------------------------------------------------------- + + +def test_the_example_catalog_loads_and_describes_itself() -> None: + loaded = Catalog.from_file(EXAMPLES / "catalog.yaml") + assert loaded.version == "2026-12-01" and loaded.dialect == "postgres" + assert [q.id for q in loaded.queries] == [ + "net_sales_by_month", + "top_customers_by_net_sales", + "customer_directory", + ] + sales = loaded.queries[0].describe() + assert sales["parameters"]["required"] == ["from_date", "to_date"] + assert sales["parameters"]["properties"]["from_date"]["format"] == "date" + assert sales["parameters"]["additionalProperties"] is False + + +def test_roles_decide_what_is_visible() -> None: + loaded = Catalog.from_file(EXAMPLES / "catalog.yaml") + assert [q.id for q in loaded.visible_to("analyst")] == [ + "net_sales_by_month", + "top_customers_by_net_sales", + ] + assert len(loaded.visible_to("manager")) == 3 + assert [q.id for q in loaded.visible_to(None)] == ["net_sales_by_month"] + + +@pytest.mark.parametrize( + ("data", "message"), + [ + ({"queries": [query()]}, "version"), + ({"version": True, "queries": [query()]}, "version"), + ({"version": "v", "queries": []}, "non-empty list"), + ({"version": "v", "queries": [query()], "extra": 1}, "only version"), + (catalog(query(id="Bad-ID")), "id must be"), + (catalog(query(id=None)), "id must be"), + (catalog(query(), query()), "duplicate query id"), + (catalog(query(sql="")), "sql must be"), + (catalog(query(description=" ")), "description must be"), + (catalog(query(roles="analyst")), "roles must be"), + (catalog(query(extra=1)), "takes only"), + (catalog(query(sql="SELECT 1; SELECT 2", params={})), "exactly one statement"), + (catalog(query(sql="SELECT a FROM t WHERE x = ?", params={})), "write parameters as"), + ( + catalog(query(sql="SELECT a FROM t WHERE x = $1", params={}), dialect="postgres"), + "write parameters as", + ), + (catalog(query(sql="SELECT a FROM t WHERE x = :Upper", params={})), "write parameters as"), + (catalog(query(params={})), "undeclared parameter"), + ( + catalog(query(params={"since": {"type": "date"}, "unused": {"type": "string"}})), + "unused", + ), + (catalog(query(params={"since": {"type": "blob"}})), "type must be one of"), + (catalog(query(params={"since": {"type": "date", "bogus": 1}})), "takes only"), + (catalog(query(params={"Since": {"type": "date"}})), "invalid parameter name"), + (catalog(query(params={"since": {"type": "date", "enum": ["nope"]}})), "must be a date"), + ( + catalog( + query( + sql="SELECT 1 FROM t WHERE n > :n", + params={"n": {"type": "integer", "minimum": 5, "maximum": 1}}, + ) + ), + "minimum is above maximum", + ), + ( + catalog( + query( + sql="SELECT 1 FROM t WHERE n > :n", + params={"n": {"type": "string", "minimum": 1}}, + ) + ), + "needs a number", + ), + ( + catalog( + query( + sql="SELECT 1 FROM t WHERE n > :n", + params={"n": {"type": "integer", "default": "text"}}, + ) + ), + "must be an integer", + ), + ], +) +def test_invalid_catalogs_are_refused_at_load(data: dict[str, Any], message: str) -> None: + with pytest.raises(CatalogError, match=message): + Catalog.from_dict(data) + + +def test_a_missing_or_broken_file_is_a_catalog_error(tmp_path: Path) -> None: + with pytest.raises(CatalogError, match="cannot read"): + Catalog.from_file(tmp_path / "nope.yaml") + bad = tmp_path / "bad.yaml" + bad.write_text("version: [unterminated") + with pytest.raises(Exception): # noqa: B017 - the YAML error, whatever its class + Catalog.from_file(bad) + + +# --- typed parameters --------------------------------------------------------------------- + + +def bound(params: dict[str, Any], given: dict[str, Any] | None, sql: str | None = None) -> Any: + names = " AND ".join(f"x = :{name}" for name in params) + entry = Catalog.from_dict( + catalog(query(sql=sql or f"SELECT a FROM t WHERE {names}", params=params)) + ).queries[0] + return entry.bind(given) + + +def test_values_are_converted_to_the_type_that_is_bound() -> None: + got = bound( + { + "d": {"type": "date"}, + "i": {"type": "integer"}, + "n": {"type": "number"}, + "b": {"type": "boolean"}, + "s": {"type": "string"}, + }, + {"d": "2026-01-31", "i": 5, "n": 2.5, "b": False, "s": "hi"}, + ) + import datetime # noqa: PLC0415 + + assert got == {"d": datetime.date(2026, 1, 31), "i": 5, "n": 2.5, "b": False, "s": "hi"} + + +@pytest.mark.parametrize( + ("param", "value", "message"), + [ + ({"type": "integer"}, True, "must be an integer"), + ({"type": "integer"}, 1.5, "must be an integer"), + ({"type": "integer"}, "5", "must be an integer"), + ({"type": "integer"}, 2**70, "must be an integer"), + ({"type": "integer", "minimum": 1}, 0, "at least 1"), + ({"type": "integer", "maximum": 10}, 11, "at most 10"), + ({"type": "number"}, True, "must be a number"), + ({"type": "number"}, float("nan"), "finite"), + ({"type": "number"}, float("inf"), "finite"), + ({"type": "boolean"}, 1, "true or false"), + ({"type": "boolean"}, "true", "true or false"), + ({"type": "string"}, 5, "must be a string"), + ({"type": "string", "max_length": 3}, "abcd", "longer than 3"), + ({"type": "string"}, "a\x00b", "NUL"), + ({"type": "string", "enum": ["a", "b"]}, "c", "one of the values"), + ({"type": "date"}, "2026-13-01", "YYYY-MM-DD"), + ({"type": "date"}, "2026-1-5", "YYYY-MM-DD"), + ({"type": "date"}, "2026-01-01T00:00:00", "YYYY-MM-DD"), + ({"type": "date"}, 20260101, "must be a string"), + ], +) +def test_bad_values_are_refused(param: dict[str, Any], value: Any, message: str) -> None: + with pytest.raises(CatalogError, match=message): + bound({"p": param}, {"p": value}) + + +def test_unknown_missing_default_and_optional() -> None: + params = { + "needed": {"type": "string"}, + "fallback": {"type": "integer", "default": 7}, + "maybe": {"type": "string", "required": False}, + } + sql = "SELECT a FROM t WHERE x = :needed AND y = :fallback AND z = :maybe" + assert bound(params, {"needed": "a"}, sql) == {"needed": "a", "fallback": 7, "maybe": None} + with pytest.raises(CatalogError, match=r"missing parameter\(s\): needed"): + bound(params, {}, sql) + with pytest.raises(CatalogError, match=r"unknown parameter\(s\): extra"): + bound(params, {"needed": "a", "extra": 1}, sql) + + +def test_error_messages_never_hold_the_value() -> None: + for param, value in ( + ({"type": "integer"}, SECRET), + ({"type": "date"}, SECRET), + ({"type": "string", "enum": ["a"]}, SECRET), + ({"type": "boolean"}, SECRET), + ): + with pytest.raises(CatalogError) as caught: + bound({"p": param}, {"p": value}) + assert SECRET not in str(caught.value) + with pytest.raises(CatalogError) as unknown: + bound({"p": {"type": "string"}}, {"p": "a", SECRET: 1}) + assert SECRET in str(unknown.value) # the NAME of an unknown parameter is shown, a value never + + +# --- binding ------------------------------------------------------------------------------ + + +@pytest.mark.parametrize("dialect", ["postgres", "mysql", "tsql", "sqlite"]) +def test_only_real_placeholders_bind_and_every_other_colon_is_escaped(dialect: str) -> None: + guard_sql = { + "postgres": "SELECT '12:30'::time AS t, a FROM t WHERE x = %(since)s AND s = 'a:b :c'", + "mysql": "SELECT '12:30' AS t, a FROM t WHERE x = :since AND s = 'a:b :c'", + "tsql": "SELECT '12:30' AS t, a FROM t WHERE x = :since AND s = 'a:b :c'", + "sqlite": "SELECT '12:30' AS t, a FROM t WHERE x = :since AND s = 'a:b :c'", + }[dialect] + text, names = to_bound(guard_sql, dialect) + assert names == {"since": 1} + assert len(re.findall(r"(? None: + text, names = to_bound("SELECT a FROM t WHERE tenant = 'x:since' AND d >= :since", "sqlite") + assert names == {"since": 1} and "'x\\:since'" in text + assert len(re.findall(r"(? None: + with pytest.raises(CatalogError, match="only :name"): + to_bound("SELECT a FROM t WHERE x = ?", "sqlite") + assert placeholders_of("SELECT :a, :b, :a", "sqlite") == {"a", "b"} + assert placeholder_counts("SELECT :a, :b, :a", "sqlite") == {"a": 2, "b": 1} + + +# --- the MCP tools, on SQLite ------------------------------------------------------------- + +SCHEMA = """ +CREATE TABLE customers (id INTEGER PRIMARY KEY, tenant_id TEXT, name TEXT, email TEXT); +CREATE TABLE invoices (id INTEGER PRIMARY KEY, tenant_id TEXT, customer_id INT, issued_at TEXT, + total NUMERIC, discount NUMERIC); +INSERT INTO customers VALUES (1, 't1', 'Ana', 'ana@acme.test'), (2, 't1', 'Luis', 'luis@x.test'), + (3, 't2', 'Eva', 'eva@y.test'); +INSERT INTO invoices VALUES (1, 't1', 1, '2026-01-10', 100, 10), (2, 't1', 1, '2026-01-20', 200, 0), + (3, 't1', 2, '2026-02-05', 150, 15), (4, 't1', 2, '2026-02-25', 50, 0), + (5, 't1', 1, '2026-03-02', 300, 30), (6, 't2', 3, '2026-01-15', 999, 99); +""" +CATALOG = { + "version": "7", + "dialect": "sqlite", + "queries": [ + { + "id": "net_sales", + "description": "Net sales by month.", + "params": {"since": {"type": "date", "required": True}}, + "sql": "SELECT substr(issued_at, 1, 7) AS month, SUM(total - discount) AS net " + "FROM invoices WHERE issued_at >= :since GROUP BY 1 ORDER BY 1", + }, + { + "id": "people", + "description": "Customers by name pattern.", + "roles": ["manager"], + "params": {"pattern": {"type": "string", "max_length": 20}}, + "sql": "SELECT name, email FROM customers WHERE name LIKE :pattern ORDER BY name", + }, + { + "id": "all_invoices", + "description": "Every invoice id.", + "params": {"floor": {"type": "integer", "default": 0}}, + "sql": "SELECT id FROM invoices WHERE id > :floor ORDER BY id", + }, + ], +} + + +def policy(**changes: Any) -> GuardPolicy: + values: dict[str, Any] = { + "dialect": "sqlite", + "tables": {"invoices", "customers"}, + "row_filters": { + "invoices": "tenant_id = {user.tenant}", + "customers": "tenant_id = {user.tenant}", + }, + "masked_columns": {"customers.email": "partial"}, + "max_rows": 100, + } + values.update(changes) + return GuardPolicy(**values) + + +@pytest.fixture +def url(tmp_path: Path) -> str: + path = tmp_path / "c.db" + with sqlite3.connect(path) as conn: + conn.executescript(SCHEMA) + conn.close() + return f"sqlite:///{path}" + + +def server(url: str, **options: Any) -> Any: + options.setdefault("context", {"user": {"tenant": "t1"}}) + options.setdefault("catalog", CATALOG) + return create_server( + options.pop("policy", policy()), url, **{**options, "catalog": _cat(options)} + ) + + +def _cat(options: dict[str, Any]) -> Catalog: + given = options.get("catalog", CATALOG) + return given if isinstance(given, Catalog) else Catalog.from_dict(given) + + +def call(srv: Any, tool: str, **args: Any) -> CallToolResult: + async def go() -> CallToolResult: + async with Client(srv) as client: + return await client.call_tool(tool, args) + + return anyio.run(go) + + +def run(srv: Any, query_id: str, parameters: dict[str, Any] | None = None) -> CallToolResult: + return call(srv, "run_verified_query", query_id=query_id, parameters=parameters) + + +def ok(result: CallToolResult) -> dict[str, Any]: + assert not result.is_error, result.content + assert result.structured_content is not None + return dict(result.structured_content) + + +def message(result: CallToolResult) -> str: + assert result.is_error + return "".join(getattr(block, "text", "") for block in result.content) + + +def test_the_tools_exist_only_when_there_is_a_catalog(url: str) -> None: + async def names(srv: Any) -> set[str]: + async with Client(srv) as client: + return {t.name for t in (await client.list_tools()).tools} + + with_catalog = anyio.run(names, server(url)) + assert {"list_verified_queries", "run_verified_query", "query"} <= with_catalog + without = anyio.run(names, create_server(policy(), url, context={"user": {"tenant": "t1"}})) + assert "list_verified_queries" not in without and "run_verified_query" not in without + assert message(call(create_server(policy(), url), "query", sql="DELETE FROM invoices")) + + +def test_query_keeps_its_contract_when_a_catalog_is_on(url: str) -> None: + out = ok(call(server(url), "query", sql="SELECT id FROM invoices ORDER BY id LIMIT 2")) + assert out["rows"] == [[1], [2]] and out["truncated"] is False + assert "query_id" not in out + + +def test_discovery_lists_what_the_role_may_run(url: str) -> None: + listed = ok(call(server(url), "list_verified_queries")) + assert listed["catalog_version"] == "7" + assert [q["id"] for q in listed["queries"]] == ["net_sales", "all_invoices"] + assert listed["queries"][0]["parameters"]["required"] == ["since"] + manager = ok(call(server(url, role="manager"), "list_verified_queries")) + assert [q["id"] for q in manager["queries"]] == ["net_sales", "people", "all_invoices"] + + +def test_a_verified_query_runs_with_its_values_bound(url: str) -> None: + out = ok(run(server(url), "net_sales", {"since": "2026-01-01"})) + assert out["rows"] == [["2026-01", 290], ["2026-02", 185], ["2026-03", 270]] + assert out["query_id"] == "net_sales" and out["catalog_version"] == "7" + assert out["rewrites"]["row_filters"] == ["invoices"] # t2's 999 never appears + + +def test_the_tenant_comes_from_the_trusted_context_only(url: str) -> None: + other = server(url, context={"user": {"tenant": "t2"}}) + assert ok(run(other, "net_sales", {"since": "2026-01-01"}))["rows"] == [["2026-01", 900]] + colon = server(url, context={"user": {"tenant": "t:1"}}) + assert ok(run(colon, "net_sales", {"since": "2026-01-01"}))["rows"] == [] # no tenant "t:1" + + +def test_masks_and_the_row_limit_still_apply(url: str) -> None: + manager = server(url, role="manager", policy=policy(max_rows=1)) + out = ok(run(manager, "people", {"pattern": "%"})) + assert out["rows"] == [["Ana", "an***"]] + assert out["truncated"] is True and out["rewrites"]["masked_columns"] == { + "customers.email": "partial" + } + assert "ana@acme.test" not in json.dumps(out) + + +def test_an_unauthorized_role_cannot_discover_or_invoke(url: str) -> None: + analyst = server(url) # no role + missing = message(run(analyst, "no_such_query")) + hidden = message(run(analyst, "people", {"pattern": "%"})) + assert missing == hidden and "no verified query" in missing # no hint that it exists + assert "people" not in json.dumps(ok(call(analyst, "list_verified_queries"))) + + +def test_invalid_parameters_are_refused_before_anything_runs(url: str) -> None: + srv = server(url) + for given, expected in ( + (None, "missing parameter"), + ({}, "missing parameter"), + ({"since": "yesterday"}, "YYYY-MM-DD"), + ({"since": "2026-01-01", "extra": 1}, "unknown parameter"), + ({"since": 20260101}, "must be a string"), + ): + text = message(run(srv, "net_sales", given)) + assert text.startswith("Error executing tool run_verified_query: invalid_parameters:") + assert expected in text + + +def test_a_value_is_data_never_sql(url: str) -> None: + hostile = "x'; DROP TABLE t;--" # 19 characters: within max_length 20 + srv = server(url, role="manager") + out = ok(run(srv, "people", {"pattern": hostile})) + assert out["rows"] == [] + assert ok(run(srv, "net_sales", {"since": "2026-01-01"}))["rows"] # the table is still there + with sqlite3.connect(url.removeprefix("sqlite:///")) as conn: + assert conn.execute("SELECT COUNT(*) FROM invoices").fetchone() == (6,) + + +def test_a_default_is_used_when_the_caller_gives_none(url: str) -> None: + out = ok(run(server(url), "all_invoices")) + assert [r[0] for r in out["rows"]] == [1, 2, 3, 4, 5] + assert [r[0] for r in ok(run(server(url), "all_invoices", {"floor": 3}))["rows"]] == [4, 5] + + +def test_audit_events_carry_the_id_and_version_and_never_a_value_or_a_row(url: str) -> None: + events: list[Any] = [] + srv = server(url, audit=events.append, role="manager") + ok(run(srv, "people", {"pattern": SECRET})) + ok(run(srv, "net_sales", {"since": "2026-01-01"})) + assert [(e.catalog_query, e.catalog_version) for e in events] == [ + ("people", "7"), + ("net_sales", "7"), + ] + dump = json.dumps([e.to_dict() for e in events]) + assert SECRET not in dump and "Ana" not in dump and "ana@acme.test" not in dump + assert "2026-01-01" not in dump # a value is not in the event, even with raw SQL on + with_sql = AuditLog(events.append, include_sql="raw") + events.clear() + raw = server(url, audit=with_sql, role="manager") + ok(run(raw, "people", {"pattern": SECRET})) + assert SECRET not in json.dumps([e.to_dict() for e in events]) and ":pattern" in str( + events[0].sql + ) + plain: list[Any] = [] + ok(call(server(url, audit=plain.append), "query", sql="SELECT id FROM invoices LIMIT 1")) + assert plain[0].catalog_query is None and "catalog_query" not in plain[0].to_dict() + + +# --- startup validation ------------------------------------------------------------------- + + +def test_a_catalog_the_policy_refuses_stops_the_server_at_startup(url: str) -> None: + bad = { + **CATALOG, + "queries": [query(id="spy", sql="SELECT secret FROM vault WHERE x = :since")], + } + with pytest.raises( + CatalogError, match=r"query spy is refused by the policy \(table_not_allowed" + ): + server(url, catalog=bad) + nothing_left = { + **CATALOG, + "queries": [query(id="spy", sql="SELECT 1 FROM invoices WHERE issued_at >= :since")], + } + server(url, catalog=nothing_left) # a harmless one is fine + + +def test_a_limit_given_as_a_parameter_is_explained_at_startup(url: str) -> None: + limited = { + **CATALOG, + "queries": [ + query( + id="top", + sql="SELECT id FROM invoices LIMIT :n", + params={"n": {"type": "integer"}}, + ) + ], + } + with pytest.raises(CatalogError, match="write a number instead"): + server(url, catalog=limited) + + +def test_the_dialect_and_the_roles_are_checked(url: str) -> None: + with pytest.raises(CatalogError, match="written for postgres but the policy uses sqlite"): + server(url, catalog={**CATALOG, "dialect": "postgres"}) + roles = PolicySet.from_dict( + {"base": {"dialect": "sqlite", "tables": ["invoices"]}, "roles": {"a": {}}} + ) + typo = {**CATALOG, "queries": [query(roles=["admn"])]} + from sqlguardllm.mcp_server import _validate_catalog # noqa: PLC0415 + + with pytest.raises(CatalogError, match=r"unknown role\(s\): admn"): + _validate_catalog( + Catalog.from_dict(typo), + roles.guard("a"), + None, + role="a", + policy_set=roles, + authenticated=True, + ) + + +def test_check_against_policy_returns_what_the_role_can_run() -> None: + guard = PolicySet.from_file(EXAMPLES / "policy.yaml").guard("analyst") + loaded = Catalog.from_file(EXAMPLES / "catalog.yaml") + ctx = json.loads((EXAMPLES / "context.json").read_text()) + assert [q.id for q in check_against_policy(loaded, guard, ctx, "analyst")] == [ + "net_sales_by_month", + "top_customers_by_net_sales", + ] + + +# --- the command -------------------------------------------------------------------------- + + +def cli(*args: str) -> tuple[int, str, str]: + out, err = io.StringIO(), io.StringIO() + return main(list(args), stdout=out, stderr=err), out.getvalue(), err.getvalue() + + +def test_the_command_checks_the_example_for_both_roles() -> None: + base = [ + "catalog", + "check", + str(EXAMPLES / "catalog.yaml"), + "--policy", + str(EXAMPLES / "policy.yaml"), + "--context", + f"@{EXAMPLES / 'context.json'}", + ] + for role, count in (("analyst", 2), ("manager", 3)): + code, out, err = cli(*base, "--role", role) + assert code == 0, err + assert f"ok: {count} queries pass the policy for role {role}" in out + code, _out, err = cli(*base) + assert code == 2 and "needs --role" in err + + +def test_the_command_exit_codes(tmp_path: Path) -> None: + code, out, _err = cli("catalog", "check", str(EXAMPLES / "catalog.yaml")) + assert code == 0 and "3 queries" in out # no policy: the file alone is checked + broken = tmp_path / "broken.yaml" + broken.write_text(yaml.safe_dump(catalog(query(), query()))) + code, _out, err = cli("catalog", "check", str(broken)) + assert code == 2 and "duplicate query id" in err and "Traceback" not in err + refused = tmp_path / "refused.yaml" + refused.write_text( + yaml.safe_dump( + catalog(query(sql="SELECT x FROM vault WHERE d >= :since"), dialect="sqlite") + ) + ) + narrow = tmp_path / "policy.yaml" + narrow.write_text("dialect: sqlite\ntables: [invoices]\n") + code, out, _err = cli("catalog", "check", str(refused), "--policy", str(narrow)) + assert code == 1 and "refused: query sales is refused by the policy" in out + + +def test_a_parameter_used_twice_cannot_lose_a_use_to_the_rewrite(url: str) -> None: + """`WHERE id > :n LIMIT :n`: the guard replaces the LIMIT, so only one :n is left. That is a + different query from the one that was reviewed, and it is refused at startup.""" + twice = { + **CATALOG, + "queries": [ + query( + id="top", + sql="SELECT id FROM invoices WHERE id > :n LIMIT :n", + params={"n": {"type": "integer"}}, + ) + ], + } + with pytest.raises(CatalogError, match="write a number instead"): + server(url, catalog=twice) + + +def test_startup_validation_records_no_audit_events(url: str) -> None: + events: list[Any] = [] + server(url, audit=events.append, role="manager") + assert events == []