From 2cf1c73650c5a97138e673efb6ee57e2be3d4905 Mon Sep 17 00:00:00 2001 From: jmmana <33883620+jmmana@users.noreply.github.com> Date: Thu, 3 Dec 2026 10:55:58 -0500 Subject: [PATCH 1/2] Run the policy-diff example in CI and write its report to the job summary (#293) Co-Authored-By: Claude Sonnet 5.5 --- .github/workflows/policy-diff-example.yml | 42 +++++++++++++++++++++++ docs/POLICY_DIFF.md | 2 +- docs/es/POLICY_DIFF.md | 2 +- 3 files changed, 44 insertions(+), 2 deletions(-) create mode 100644 .github/workflows/policy-diff-example.yml diff --git a/.github/workflows/policy-diff-example.yml b/.github/workflows/policy-diff-example.yml new file mode 100644 index 0000000..54450cf --- /dev/null +++ b/.github/workflows/policy-diff-example.yml @@ -0,0 +1,42 @@ +name: Policy diff example +# Runs the fixtures of examples/policy-diff/ through `sqlguardllm diff` the way the example +# workflow there does, and writes the Markdown report to the job summary. +on: + push: + branches: [main] + pull_request: + paths: + - "examples/policy-diff/**" + - "src/sqlguardllm/policy_diff.py" + - "src/sqlguardllm/cli.py" + - ".github/workflows/policy-diff-example.yml" +permissions: + contents: read +jobs: + diff: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4 + - uses: astral-sh/setup-uv@d4b2f3b6ecc6e67c4457f6d3e41ec42d3d0fcb86 # v5 + - run: uv sync --extra yaml + - name: A loosened policy trips the gates and the report reaches the job summary + run: | + set +e + uv run sqlguardllm diff \ + --base examples/policy-diff/base.yaml \ + --candidate examples/policy-diff/candidate.yaml \ + examples/policy-diff/cases.yaml \ + --redact --format md --fail-on filter-removed,mask-removed > diff.md + code=$? + set -e + cat diff.md + cat diff.md >> "$GITHUB_STEP_SUMMARY" + test "$code" = 1 + grep -q "Gates tripped: filter-removed, mask-removed" diff.md + grep -q '^```diff' diff.md + - name: An unchanged policy trips nothing + run: | + uv run sqlguardllm diff \ + --base examples/policy-diff/base.yaml \ + --candidate examples/policy-diff/base.yaml \ + examples/policy-diff/cases.yaml --fail-on any-change diff --git a/docs/POLICY_DIFF.md b/docs/POLICY_DIFF.md index fb85e28..ed1c554 100644 --- a/docs/POLICY_DIFF.md +++ b/docs/POLICY_DIFF.md @@ -63,7 +63,7 @@ The same file as [`sqlguardllm test`](DESIGN.md) (`cases:` with `name`, `sql`, ` Use it on **authored fixtures** that are safe to show in a pull request. The output holds the SQL of your cases and the context you gave them (`IN (1, 2)`). `--redact` replaces every literal with `?`, including the numbers in a `LIMIT`, which stay in their own `limit` field. For private traffic use [shadow mode](SHADOW.md), which keeps no SQL. -A ready workflow is in [`examples/policy-diff/`](https://github.com/jmmana/sqlguardllm/tree/main/examples/policy-diff), with a pair of fixture policies that trip the gates (a test runs them). +A ready workflow is in [`examples/policy-diff/`](https://github.com/jmmana/sqlguardllm/tree/main/examples/policy-diff), with a pair of fixture policies that trip the gates. This repository runs them in CI (the `Policy diff example` workflow writes the Markdown report to the job summary, and a test checks the gates). ## Limits diff --git a/docs/es/POLICY_DIFF.md b/docs/es/POLICY_DIFF.md index 2aef208..d1cd0e9 100644 --- a/docs/es/POLICY_DIFF.md +++ b/docs/es/POLICY_DIFF.md @@ -63,7 +63,7 @@ El mismo archivo que [`sqlguardllm test`](../DESIGN.md) (`cases:` con `name`, `s Úsalo con **casos escritos por ti** que sea seguro mostrar en un pull request. La salida contiene el SQL de tus casos y el contexto que les diste (`IN (1, 2)`). `--redact` reemplaza cada literal por `?`, incluidos los números de un `LIMIT`, que quedan en su propio campo `limit`. Para tráfico privado usa el [modo sombra](SHADOW.md), que no guarda SQL. -Hay un workflow listo en [`examples/policy-diff/`](https://github.com/jmmana/sqlguardllm/tree/main/examples/policy-diff), con un par de políticas de prueba que activan las compuertas (un test las ejecuta). +Hay un workflow listo en [`examples/policy-diff/`](https://github.com/jmmana/sqlguardllm/tree/main/examples/policy-diff), con un par de políticas de prueba que activan las compuertas. Este repositorio las ejecuta en el CI (el workflow `Policy diff example` escribe el reporte en Markdown en el resumen del job, y un test comprueba las compuertas). ## Límites From 35f360de84107853f13e589e8d0f335c2dd83c4d Mon Sep 17 00:00:00 2001 From: jmmana <33883620+jmmana@users.noreply.github.com> Date: Thu, 3 Dec 2026 11:02:05 -0500 Subject: [PATCH 2/2] Advice per table, and advice/data_classes in the Node.js and .NET clients (#291, #294) Co-Authored-By: Claude Sonnet 5.5 --- CHANGELOG.md | 1 + clients/dotnet/README.md | 2 +- clients/dotnet/src/SqlGuardLlm/SqlGuardLlm.cs | 21 +++- clients/dotnet/src/SqlGuardLlm/Wire.cs | 43 +++++++ .../tests/SqlGuardLlm.Tests/ClientTests.cs | 18 +++ clients/node/README.md | 2 +- clients/node/src/generated.ts | 33 +++++ clients/node/src/index.ts | 5 + clients/node/test/client.test.ts | 10 ++ docs/ADVICE.md | 3 +- docs/CLASSES.md | 1 - docs/PROTOCOL.md | 2 +- docs/es/ADVICE.md | 3 +- docs/es/CLASSES.md | 1 - schema/protocol/protocol.schema.json | 39 +++++- src/sqlguardllm/advice.py | 102 ++++++++++++++- src/sqlguardllm/guard.py | 2 +- tests/conformance/test_explain_extras.py | 116 ++++++++++++++++++ tests/test_advice.py | 71 +++++++++++ 19 files changed, 461 insertions(+), 14 deletions(-) create mode 100644 tests/conformance/test_explain_extras.py diff --git a/CHANGELOG.md b/CHANGELOG.md index f9160de..462bd0f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,6 +9,7 @@ Sections used: Added, Changed, Deprecated (an API that still works but will be r ### Added +- **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. - **`sqlguardllm diff`** (#293, [guide](docs/POLICY_DIFF.md), experimental): runs authored cases under a base and a candidate policy (or policy set) and reports the decision, codes, rewritten-SQL diff, row filters, masks, limit and advice score, plus the changes between the policies themselves. `--fail-on` gates (`newly-allowed`, `newly-denied`, `filter-removed`, `mask-removed`, `hidden-removed`, `limit-raised`, `any-change`) make the exit code 1 for CI; output as text, JSON (versioned schema) or Markdown for a PR summary; `--redact` replaces literals. An example workflow and fixtures are in `examples/policy-diff/`. - **Sensitive data classes** (#294, [guide](docs/CLASSES.md), experimental): `Policy.data_classes`, `column_classes` and `not_sensitive` say once what a kind of data is (`hide` or `mask`) and which columns are of it. They compile into `hidden_columns` and `masked_columns`, so enforcement is unchanged and an explicit entry wins. `Guard.explain()` and `explain_query` report the classes a query reads, `lint` skips columns marked `not_sensitive`, and `sqlguardllm classify --db URL` proposes the mapping from column names only (never a row). - **MCP results that say what the guard did** (#295): `query` now returns `status` (`allowed`, `rewritten`, `warned`), an exact `truncated` (the server runs the query with one more row allowed to tell a cut result from a full one), `applied_limit`, `rewrites` (tables with row filters and masked columns, never their values) and `warnings`, plus `advice` when the policy has it. `list_tables`, `describe_table`, `explain_query` and `query` advertise a typed `outputSchema`, and `sqlguardllm proxy` advertises mapped SQL tools as read-only. `limit_reached` stays and is deprecated. diff --git a/clients/dotnet/README.md b/clients/dotnet/README.md index 944ca58..985bc7a 100644 --- a/clients/dotnet/README.md +++ b/clients/dotnet/README.md @@ -75,7 +75,7 @@ It works with `dotnet run`, `dotnet publish -r `, self-contained and single | --- | --- | | `CheckAsync(sql, context?, ct)` | `CheckResult { Ok, Sql, Tables, AppliedFilters, Violations }` | | `EnforceAsync(sql, context?, ct)` | the safe SQL, or throws `GuardViolationException` (has `Violations`) | -| `ExplainAsync(sql, context?, ct)` | `ExplainResult { Ok, Sql, Tables, Violations, Raw }` (`Raw` is the full `JsonElement`) | +| `ExplainAsync(sql, context?, ct)` | `ExplainResult { Ok, Sql, Tables, Violations, Raw }` (`Raw` is the full `JsonElement`), plus the experimental `Advice` (`QueryAdvice?`) and `DataClasses`, present when the policy has those sections | | `HealthAsync(ct)` | `HealthResult { Status, Version }` | ## Fails closed diff --git a/clients/dotnet/src/SqlGuardLlm/SqlGuardLlm.cs b/clients/dotnet/src/SqlGuardLlm/SqlGuardLlm.cs index 9602666..a5a0a06 100644 --- a/clients/dotnet/src/SqlGuardLlm/SqlGuardLlm.cs +++ b/clients/dotnet/src/SqlGuardLlm/SqlGuardLlm.cs @@ -27,7 +27,26 @@ public sealed record CheckResult /// Result of /v1/explain. holds the whole JSON object. public sealed record ExplainResult( - bool Ok, string? Sql, IReadOnlyList Tables, IReadOnlyList Violations, JsonElement Raw); + bool Ok, string? Sql, IReadOnlyList Tables, IReadOnlyList Violations, JsonElement Raw) +{ + /// Experimental. Findings and the 1-100 score; null unless the policy has an advice section. + public QueryAdvice? Advice => Wire.ParseAdvice(Raw); + + /// Experimental. Class to the table.column entries the query reads; empty unless the policy has data classes. + public IReadOnlyDictionary> DataClasses => Wire.ParseDataClasses(Raw); +} + +/// Experimental. One thing that makes a query wasteful: a stable code, what it points at, and its penalty. +public sealed record AdviceFinding(string Code, string Detail, int Penalty); + +/// +/// Experimental. Query advice from an explanation. is clause to column names as written; +/// is table to clause to column names, resolved to the physical table. +/// +public sealed record QueryAdvice( + int Score, bool Warn, IReadOnlyList Findings, + IReadOnlyDictionary> Columns, + IReadOnlyDictionary>> Tables); /// Result of /v1/health. public sealed record HealthResult( diff --git a/clients/dotnet/src/SqlGuardLlm/Wire.cs b/clients/dotnet/src/SqlGuardLlm/Wire.cs index 3498eb5..6744ce5 100644 --- a/clients/dotnet/src/SqlGuardLlm/Wire.cs +++ b/clients/dotnet/src/SqlGuardLlm/Wire.cs @@ -78,6 +78,49 @@ public static ExplainResult ParseExplain(JsonElement raw) catch (JsonException e) { throw new SqlGuardException("bad_response", "Unexpected explain response.", null, e); } } + private static IReadOnlyList Strings(JsonElement array) + { + var list = new List(); + if (array.ValueKind == JsonValueKind.Array) + foreach (var item in array.EnumerateArray()) + if (item.ValueKind == JsonValueKind.String) list.Add(item.GetString()!); + return list; + } + + private static IReadOnlyDictionary> StringMap(JsonElement obj) + { + var map = new Dictionary>(); + if (obj.ValueKind == JsonValueKind.Object) + foreach (var p in obj.EnumerateObject()) map[p.Name] = Strings(p.Value); + return map; + } + + public static IReadOnlyDictionary> ParseDataClasses(JsonElement raw) + => raw.ValueKind == JsonValueKind.Object && raw.TryGetProperty("data_classes", out var d) + ? StringMap(d) : new Dictionary>(); + + public static QueryAdvice? ParseAdvice(JsonElement raw) + { + if (raw.ValueKind != JsonValueKind.Object || !raw.TryGetProperty("advice", out var a) || a.ValueKind != JsonValueKind.Object) + return null; + var findings = new List(); + if (a.TryGetProperty("findings", out var fs) && fs.ValueKind == JsonValueKind.Array) + foreach (var f in fs.EnumerateArray()) + findings.Add(new AdviceFinding( + f.TryGetProperty("code", out var c) ? c.GetString() ?? "" : "", + f.TryGetProperty("detail", out var d) ? d.GetString() ?? "" : "", + f.TryGetProperty("penalty", out var p) && p.TryGetInt32(out var n) ? n : 0)); + var tables = new Dictionary>>(); + if (a.TryGetProperty("tables", out var ts) && ts.ValueKind == JsonValueKind.Object) + foreach (var t in ts.EnumerateObject()) tables[t.Name] = StringMap(t.Value); + return new QueryAdvice( + a.TryGetProperty("score", out var s) && s.TryGetInt32(out var score) ? score : 0, + a.TryGetProperty("warn", out var w) && w.ValueKind == JsonValueKind.True, + findings, + a.TryGetProperty("columns", out var cols) ? StringMap(cols) : new Dictionary>(), + tables); + } + /// Writes a context value without reflection. Unsupported types fail loudly instead of being dropped. public static void WriteValue(Utf8JsonWriter w, object? value, int depth) { diff --git a/clients/dotnet/tests/SqlGuardLlm.Tests/ClientTests.cs b/clients/dotnet/tests/SqlGuardLlm.Tests/ClientTests.cs index 6a0b81b..615b541 100644 --- a/clients/dotnet/tests/SqlGuardLlm.Tests/ClientTests.cs +++ b/clients/dotnet/tests/SqlGuardLlm.Tests/ClientTests.cs @@ -61,6 +61,24 @@ [Fact] public async Task Explain_exposes_known_fields_and_raw() Assert.True(r.Ok); Assert.Equal(["a"], r.Tables); Assert.Equal(1, r.Raw.GetProperty("extra").GetProperty("x").GetInt32()); Assert.Equal("/v1/explain", h.Last!.RequestUri!.AbsolutePath); } + [Fact] public async Task Explain_exposes_advice_and_data_classes_when_present() + { + const string body = """{"ok":true,"sql":"S","tables":["t"],"violations":[],"advice":{"score":50,"warn":true,"findings":[{"code":"select-star","detail":"*","penalty":15}],"columns":{"projected":["id"]},"tables":{"t":{"projected":["id"],"filtered":["total"]}}},"data_classes":{"email":["t.email"]}}"""; + var (c, _) = Make((_, _) => Task.FromResult(J(HttpStatusCode.OK, body))); + var r = await c.ExplainAsync("S"); + Assert.NotNull(r.Advice); + Assert.Equal(50, r.Advice!.Score); Assert.True(r.Advice.Warn); + Assert.Equal(new AdviceFinding("select-star", "*", 15), r.Advice.Findings[0]); + Assert.Equal(["id"], r.Advice.Columns["projected"]); + Assert.Equal(["total"], r.Advice.Tables["t"]["filtered"]); + Assert.Equal(["t.email"], r.DataClasses["email"]); + } + [Fact] public async Task Explain_without_the_policy_sections_has_no_advice_and_no_classes() + { + var (c, _) = Make((_, _) => Task.FromResult(J(HttpStatusCode.OK, """{"ok":true,"sql":"S","tables":[],"violations":[]}"""))); + var r = await c.ExplainAsync("S"); + Assert.Null(r.Advice); Assert.Empty(r.DataClasses); + } [Fact] public async Task Health() { var (c, h) = Make((_, _) => Task.FromResult(J(HttpStatusCode.OK, """{"status":"ok","version":"0.5.0"}"""))); diff --git a/clients/node/README.md b/clients/node/README.md index 25a9a84..da2bce7 100644 --- a/clients/node/README.md +++ b/clients/node/README.md @@ -20,7 +20,7 @@ const safeSql = await guard.enforce(modelSql, { tenant_id: session.tenantId }); // or: const r = await guard.check(modelSql, ctx); // r.ok, r.sql, r.tables, r.appliedFilters, r.violations ``` -`enforce` returns the rewritten safe SQL or throws `GuardViolation` (with `.violations`). `explain(sql, ctx)` and `health()` are also available. Options: `baseUrl`, `token?`, `timeoutMs?` (default 5000), `fetch?`. +`enforce` returns the rewritten safe SQL or throws `GuardViolation` (with `.violations`). `explain(sql, ctx)` and `health()` are also available; an explanation carries typed, experimental `advice` and `data_classes` when the policy has those sections. Options: `baseUrl`, `token?`, `timeoutMs?` (default 5000), `fetch?`. ### pg diff --git a/clients/node/src/generated.ts b/clients/node/src/generated.ts index 397c2de..697e74e 100644 --- a/clients/node/src/generated.ts +++ b/clients/node/src/generated.ts @@ -68,6 +68,25 @@ export type Policy = { }>; /** Experimental. Only read by sqlguardllm mcp --auth oidc: context path (user.tenant_id) to claim of the verified access token. The key role names the claim that selects the role of a policy set. A missing claim leaves the value out (missing_context). */ context_from_claims?: Record; + /** Experimental. Opt-in query advice: findings and a 1-100 score for allowed but wasteful queries. It never changes the decision unless min_score is set. */ + advice?: (null | { + enabled?: boolean; + /** Tables where no-filter does not apply. */ + small_tables?: string[]; + /** Finding code to penalty, overriding the default. */ + weights?: { [K in "select-star" | "no-filter" | "no-row-bound" | "leading-wildcard" | "function-on-filtered-column" | "or-chain" | "unlinked-join" | "deep-nesting" | "order-without-limit"]?: number }; + warn_below?: (number | null); + min_score?: (number | null); + }); + /** Experimental. Kinds of sensitive data and what happens to them. They compile into hidden_columns and masked_columns; an explicit entry there wins. */ + data_classes?: (null | Record); + /** Experimental. table.column -> a class defined in data_classes. */ + column_classes?: (null | Record); + /** Experimental. table.column -> why a column that looks sensitive is not. Only the linter reads it. */ + not_sensitive?: (null | Record); }; /** Values for the {context.path} placeholders of the row filters. */ @@ -105,6 +124,20 @@ export type WireExplainResult = { limit: (number | null); violations: WireViolation[]; text: string; + /** Present only when the policy has an advice section. Experimental. */ + advice?: { + score: number; + warn: boolean; + findings: { + code: string; + detail: string; + penalty: number; + }[]; + columns: Record; + tables: Record>; + }; + /** Present only when the policy has data classes. Experimental. */ + data_classes?: Record; }; export type WireErrorBody = { diff --git a/clients/node/src/index.ts b/clients/node/src/index.ts index 52d718d..7afaa46 100644 --- a/clients/node/src/index.ts +++ b/clients/node/src/index.ts @@ -3,6 +3,7 @@ export type { EngineEnv, PlatformInfo, ResolveEngineOptions } from "./engine"; import { LocalEngine, type LocalOptions } from "./local"; export type { LocalOptions } from "./local"; export type * from "./generated"; +import type { WireExplainResult } from "./generated"; export type Fetch =(input: string, init?: RequestInit) => Promise; @@ -19,6 +20,10 @@ export interface Explanation extends Record { sql?: string | null; tables?: string[]; violations?: Violation[]; + /** Experimental. Findings and the 1-100 score; present only when the policy has an `advice` section. */ + advice?: WireExplainResult["advice"]; + /** Experimental. Class to the `table.column` entries it reads; present only when the policy has data classes. */ + data_classes?: WireExplainResult["data_classes"]; } export interface SqlGuardOptions { baseUrl: string; diff --git a/clients/node/test/client.test.ts b/clients/node/test/client.test.ts index c80eb6a..cd65a37 100644 --- a/clients/node/test/client.test.ts +++ b/clients/node/test/client.test.ts @@ -16,6 +16,7 @@ beforeAll(async () => { if (sql === "slow") return void setTimeout(() => j(200, {}), 500); if (sql === "garbage") return j(200, ""); if (sql === "liar") return j(200, { ok: true, sql: null, tables: [], applied_filters: [], violations: [] }); + if (req.url === "/v1/explain" && sql === "advised") return j(200, { ok: true, sql, tables: ["t"], violations: [], advice: { score: 50, warn: true, findings: [{ code: "select-star", detail: "*", penalty: 15 }], columns: { projected: ["id"] }, tables: { t: { projected: ["id"] } } }, data_classes: { email: ["t.email"] } }); if (req.url === "/v1/explain") return j(200, { ok: true, sql, tables: ["t"], violations: [], steps: [1] }); if (sql.startsWith("DROP")) return j(200, { ok: false, sql: null, tables: [], applied_filters: [], violations: [{ code: "NOT_SELECT", message: "only select", detail: "d" }] }); j(200, { ok: true, sql: `${sql} LIMIT 10`, tables: ["t"], applied_filters: ["tenant"], violations: [] }); @@ -44,6 +45,15 @@ describe("SqlGuard", () => { }); it("enforce returns safe sql", async () => expect(await g().enforce("SELECT 1")).toBe("SELECT 1 LIMIT 10")); it("explain", async () => expect((await g().explain("SELECT 1")).steps).toEqual([1])); + it("explain exposes typed advice and data classes when the policy has them", async () => { + const e = await g().explain("advised"); + const score: number | undefined = e.advice?.score; + const first: string | undefined = e.advice?.findings[0]?.code; + const read: string[] | undefined = e.data_classes?.email; + expect([score, first, read]).toEqual([50, "select-star", ["t.email"]]); + expect(e.advice?.tables.t?.projected).toEqual(["id"]); + expect((await g().explain("SELECT 1")).advice).toBeUndefined(); + }); it("401 -> SqlGuardError with code, no token leak", async () => { const e = await new SqlGuard({ baseUrl: url, token: "bad" }).check("SELECT 1").catch((x) => x); expect(e).toBeInstanceOf(SqlGuardError); expect(e.code).toBe("unauthorized"); expect(e.status).toBe(401); diff --git a/docs/ADVICE.md b/docs/ADVICE.md index f12dd70..b6d6712 100644 --- a/docs/ADVICE.md +++ b/docs/ADVICE.md @@ -44,7 +44,7 @@ The score is `max(1, 100 − the sum of the penalties)`. A finding that repeats | `deep-nesting` | More than 2 levels of subqueries, derived tables and CTEs | 8 | | `order-without-limit` | `ORDER BY` in the outermost query with no row bound | 5 | -It also lists the columns by clause, **as written in the query** (`o.total` or `total`): `projected`, `filtered`, `joined`, `grouped`, `ordered` and `in_functions`. Names are not resolved through aliases to their tables. +It also lists the columns by clause, in two views: `columns` **as written in the query** (`o.total` or `total`), and `tables`, resolved to the physical table the way `Guard.explain()` does (aliases, correlated subqueries, and unqualified columns through the policy's `schema`): `{"orders": {"projected": ["id"], "filtered": ["total"]}}`. The clauses are `projected`, `filtered`, `joined`, `grouped`, `ordered` and `in_functions`. A column that can't be tied to one table is left out of `tables`, and a column of a derived table or CTE is counted at the table it comes from. ## Rejecting low scores @@ -55,4 +55,3 @@ With `min_score: 80`, `check()` rejects a query whose score is lower, with the e - It scores the model's SQL **before** the rewrite. The row filters, masks and limit the guard adds are not credited, and no context value ever appears in the advice. - It knows nothing about table sizes, indexes or plans. For those see the cost guard in [MCP.md](MCP.md). - It is a heuristic over the syntax tree. A query can score 100 and still be slow, and `no-filter` fires on a deliberate full-table report. -- The Node.js and .NET clients do not expose `advice` yet. diff --git a/docs/CLASSES.md b/docs/CLASSES.md index 017c624..dfadcde 100644 --- a/docs/CLASSES.md +++ b/docs/CLASSES.md @@ -53,4 +53,3 @@ The classes it proposes: `email`, `phone`, `national_id` (`curp`, `rfc`, `nss`, - **Names only.** A sensitive column with an innocent name (`contact`, `notes`) is not found, and a harmless one can be flagged (`network_docs.rfc_number` above). Review the proposal. Checking values (for example email, card Luhn, CURP and CLABE formats on a bounded sample) is not built yet. - **Whole columns.** Sensitive values inside a JSON or free-text column are not seen. - **Inference through aggregates.** A class hides or masks a column; it does not stop someone from learning a value from `COUNT` or `SUM` over it. See the [threat model](THREAT_MODEL.md). -- The Node.js and .NET clients do not expose `data_classes` in explanations yet. diff --git a/docs/PROTOCOL.md b/docs/PROTOCOL.md index 85c54b9..c1d06da 100644 --- a/docs/PROTOCOL.md +++ b/docs/PROTOCOL.md @@ -8,7 +8,7 @@ - Messages are JSON objects on one line (no embedded raw newlines). Responses are ASCII-only JSON. - SQL and context are never logged or echoed in errors. -The single JSON Schema is [`schema/protocol/protocol.schema.json`](https://github.com/jmmana/sqlguardllm/blob/main/schema/protocol/protocol.schema.json). `CheckResult` and `ExplainResult` are the bodies of HTTP `POST /v1/check` and `/v1/explain` and the `result` of the `check` and `explain` responses. The server tests, the protocol tests and the clients all validate against it. +The single JSON Schema is [`schema/protocol/protocol.schema.json`](https://github.com/jmmana/sqlguardllm/blob/main/schema/protocol/protocol.schema.json). `ExplainResult` also carries two optional, experimental fields: `advice` (when the policy has an [`advice`](ADVICE.md) section) and `data_classes` (when it has [data classes](CLASSES.md)); both are absent otherwise, and the Node.js and .NET clients type them. `CheckResult` and `ExplainResult` are the bodies of HTTP `POST /v1/check` and `/v1/explain` and the `result` of the `check` and `explain` responses. The server tests, the protocol tests and the clients all validate against it. ## Requests diff --git a/docs/es/ADVICE.md b/docs/es/ADVICE.md index 03cfa87..7b1847b 100644 --- a/docs/es/ADVICE.md +++ b/docs/es/ADVICE.md @@ -44,7 +44,7 @@ La puntuación es `max(1, 100 − la suma de las penalizaciones)`. Un hallazgo r | `deep-nesting` | Más de 2 niveles de subconsultas, tablas derivadas y CTE | 8 | | `order-without-limit` | `ORDER BY` en la consulta más externa sin límite de filas | 5 | -También lista las columnas por cláusula, **tal como están escritas en la consulta** (`o.total` o `total`): `projected`, `filtered`, `joined`, `grouped`, `ordered` e `in_functions`. Los nombres no se resuelven a sus tablas a través de alias. +También lista las columnas por cláusula, en dos vistas: `columns` **tal como están escritas en la consulta** (`o.total` o `total`), y `tables`, resueltas a la tabla física como lo hace `Guard.explain()` (alias, subconsultas correlacionadas y columnas sin calificar mediante el `schema` de la política): `{"orders": {"projected": ["id"], "filtered": ["total"]}}`. Las cláusulas son `projected`, `filtered`, `joined`, `grouped`, `ordered` e `in_functions`. Una columna que no se puede asignar a una sola tabla no aparece en `tables`, y una columna de una tabla derivada o CTE se cuenta en la tabla de la que viene. ## Rechazar puntuaciones bajas @@ -55,4 +55,3 @@ Con `min_score: 80`, `check()` rechaza una consulta con puntuación menor, con e - Puntúa el SQL del modelo **antes** de la reescritura. Los filtros por fila, las máscaras y el límite que agrega el guard no suman, y ningún valor de contexto aparece en los consejos. - No sabe nada de tamaños de tabla, índices ni planes. Para eso está el cost guard de [MCP.md](../MCP.md). - Es una heurística sobre el árbol sintáctico. Una consulta puede sacar 100 y ser lenta, y `no-filter` se activa en un reporte deliberado de toda la tabla. -- Los clientes de Node.js y .NET todavía no exponen `advice`. diff --git a/docs/es/CLASSES.md b/docs/es/CLASSES.md index 6b72361..afecfd8 100644 --- a/docs/es/CLASSES.md +++ b/docs/es/CLASSES.md @@ -53,4 +53,3 @@ Las clases que propone: `email`, `phone`, `national_id` (`curp`, `rfc`, `nss`, ` - **Solo nombres.** Una columna sensible con nombre inocente (`contact`, `notes`) no se encuentra, y una inofensiva puede marcarse (`network_docs.rfc_number` arriba). Revisa la propuesta. Comprobar valores (por ejemplo formatos de correo, Luhn de tarjetas, CURP y CLABE sobre una muestra acotada) todavía no está construido. - **Columnas completas.** No se ven los valores sensibles dentro de una columna JSON o de texto libre. - **Inferencia con agregados.** Una clase oculta o enmascara una columna; no impide que alguien deduzca un valor con `COUNT` o `SUM` sobre ella. Véase el [modelo de amenazas](../THREAT_MODEL.md). -- Los clientes de Node.js y .NET todavía no exponen `data_classes` en las explicaciones. diff --git a/schema/protocol/protocol.schema.json b/schema/protocol/protocol.schema.json index 89bc786..fa179ab 100644 --- a/schema/protocol/protocol.schema.json +++ b/schema/protocol/protocol.schema.json @@ -57,7 +57,44 @@ "row_filters": {"type": "object", "additionalProperties": {"type": "string"}}, "limit": {"type": ["integer", "null"]}, "violations": {"type": "array", "items": {"$ref": "#/$defs/Violation"}}, - "text": {"type": "string"} + "text": {"type": "string"}, + "advice": { + "type": "object", + "description": "Present only when the policy has an advice section. Experimental.", + "required": ["score", "warn", "findings", "columns", "tables"], + "properties": { + "score": {"type": "integer", "minimum": 1, "maximum": 100}, + "warn": {"type": "boolean"}, + "findings": { + "type": "array", + "items": { + "type": "object", + "required": ["code", "detail", "penalty"], + "properties": { + "code": {"type": "string"}, + "detail": {"type": "string"}, + "penalty": {"type": "integer", "minimum": 0} + } + } + }, + "columns": { + "type": "object", + "additionalProperties": {"type": "array", "items": {"type": "string"}} + }, + "tables": { + "type": "object", + "additionalProperties": { + "type": "object", + "additionalProperties": {"type": "array", "items": {"type": "string"}} + } + } + } + }, + "data_classes": { + "type": "object", + "description": "Present only when the policy has data classes. Experimental.", + "additionalProperties": {"type": "array", "items": {"type": "string"}} + } } }, "ErrorBody": { diff --git a/src/sqlguardllm/advice.py b/src/sqlguardllm/advice.py index f458077..3715279 100644 --- a/src/sqlguardllm/advice.py +++ b/src/sqlguardllm/advice.py @@ -11,7 +11,7 @@ from __future__ import annotations -from collections.abc import Collection, Mapping +from collections.abc import Collection, Mapping, Sequence from dataclasses import dataclass, field from types import MappingProxyType from typing import Any @@ -121,6 +121,10 @@ class Advice: columns: Clause → column names as written in the query (``"o.total"`` or ``"total"``): ``projected``, ``filtered`` (``WHERE``/``HAVING``), ``joined``, ``grouped``, ``ordered`` and ``in_functions`` (wrapped in a function or cast). + tables: Table → clause → column names, with aliases and subqueries resolved to the + physical table (``{"orders": {"projected": ("id",), "filtered": ("total",)}}``), + using the same resolution as ``Guard.explain()``. A column that can't be tied to one + table is left out; a column of a derived table or CTE is counted where it is read. warn: True when ``score`` is below the policy's ``warn_below``. """ @@ -128,6 +132,7 @@ class Advice: findings: tuple[Finding, ...] = () columns: Mapping[str, tuple[str, ...]] = field(default_factory=dict) warn: bool = False + tables: Mapping[str, Mapping[str, tuple[str, ...]]] = field(default_factory=dict) def to_dict(self) -> dict[str, Any]: return { @@ -137,6 +142,10 @@ def to_dict(self) -> dict[str, Any]: {"code": f.code, "detail": f.detail, "penalty": f.penalty} for f in self.findings ], "columns": {clause: list(names) for clause, names in self.columns.items()}, + "tables": { + table: {clause: list(names) for clause, names in clauses.items()} + for table, clauses in self.tables.items() + }, } @@ -272,7 +281,95 @@ def _column_use(root: exp.Expr) -> dict[str, tuple[str, ...]]: return {clause: tuple(sorted(names)) for clause, names in use.items() if names} -def analyze(root: exp.Expression, scopes: list[Scope], compiled: Compiled) -> Advice | None: +_CLAUSE_OF = { + "expressions": "projected", + "where": "filtered", + "having": "filtered", + "qualify": "filtered", + "joins": "joined", + "group": "grouped", + "order": "ordered", +} + + +def _tables_use( + scopes: list[Scope], refs: Sequence[Any], compiled: Compiled +) -> dict[str, dict[str, tuple[str, ...]]]: + """Per physical table, which columns are used in which clause (the resolution of explain).""" + from sqlguardllm._names import norm # noqa: PLC0415 - explain imports this module + from sqlguardllm.explain import ( # noqa: PLC0415 + _clause, + _nearest_sources, + _schema_owner, + ) + from sqlguardllm.rules.columns import _visible_sources, scope_columns # noqa: PLC0415 + + dialect = compiled.dialect + physical = {id(ref.table): str(ref.name) for ref in refs} + use: dict[str, dict[str, set[str]]] = {} + + def put(source: object, clause: str, name: str, wrapped: bool = False) -> None: + table = physical.get(id(source)) if isinstance(source, exp.Table) else None + if table is None: + return + slots = use.setdefault(table, {}) + slots.setdefault(clause, set()).add(name) + if wrapped: + slots.setdefault("in_functions", set()).add(name) + + for scope in scopes: + select = scope.expression + if not isinstance(select, exp.Select): + continue + visible = {norm(a, dialect): s for a, s in _visible_sources(scope).items()} + for projection in select.expressions: + if isinstance(projection, exp.Star): + for _, source in scope.selected_sources.values(): + put(source, "projected", "*") + elif ( + isinstance(projection, exp.Column) + and isinstance(projection.this, exp.Star) + and projection.table + ): + put(visible.get(norm(projection.args["table"], dialect)), "projected", "*") + aliases = {norm(i.alias, dialect) for i in select.expressions if isinstance(i, exp.Alias)} + for column in scope_columns(scope): + if not isinstance(column.this, exp.Identifier): + continue + if column.find_ancestor(exp.Select) is not select: + continue + name = norm(column.this, dialect) + clause = _CLAUSE_OF.get(_clause(column, select) or "") + if clause is None: + continue + wrapped = any(_is_function(a) for a in _ancestors_until(column, select)) + if column.table: + put(visible.get(norm(column.args["table"], dialect)), clause, name, wrapped) + continue + if name in aliases and clause != "projected": + continue # an output alias in GROUP BY, HAVING or ORDER BY + sources = _nearest_sources(scope) + owner = sources[0] if len(sources) == 1 else _schema_owner(name, sources, compiled) + if owner is not None: + put(owner, clause, name, wrapped) + return { + table: {clause: tuple(sorted(names)) for clause, names in sorted(clauses.items())} + for table, clauses in sorted(use.items()) + } + + +def _ancestors_until(node: exp.Expr, stop: exp.Expr) -> list[exp.Expr]: + found: list[exp.Expr] = [] + current = node.parent + while current is not None and current is not stop: + found.append(current) + current = current.parent + return found + + +def analyze( + root: exp.Expression, scopes: list[Scope], compiled: Compiled, refs: Sequence[Any] = () +) -> Advice | None: """Findings and the score for a parsed query, or ``None`` when advice is off or there is nothing to analyze (a procedure call, a statement that did not parse).""" config = compiled.advice @@ -311,5 +408,6 @@ def analyze(root: exp.Expression, scopes: list[Scope], compiled: Compiled) -> Ad score=score, findings=tuple(findings), columns=MappingProxyType(_column_use(root)), + tables=MappingProxyType(_tables_use(scopes, refs, compiled)), warn=config.warn_below is not None and score < config.warn_below, ) diff --git a/src/sqlguardllm/guard.py b/src/sqlguardllm/guard.py index 6b61246..1340b17 100644 --- a/src/sqlguardllm/guard.py +++ b/src/sqlguardllm/guard.py @@ -475,7 +475,7 @@ def _analyze(self, sql: str) -> _State: problems += mask_problems aggregates, aggregate_problems = check_aggregate_only(refs, compiled) problems += aggregate_problems - advice = analyze(root, scopes, compiled) + advice = analyze(root, scopes, compiled, refs) if ( advice is not None and compiled.advice.min_score is not None diff --git a/tests/conformance/test_explain_extras.py b/tests/conformance/test_explain_extras.py new file mode 100644 index 0000000..4367281 --- /dev/null +++ b/tests/conformance/test_explain_extras.py @@ -0,0 +1,116 @@ +"""`advice` and `data_classes` in an explanation are the same in process, over stdio and HTTP.""" + +from __future__ import annotations + +import json +import subprocess +import sys +import threading +import urllib.request +from pathlib import Path +from typing import Any + +import pytest + +from sqlguardllm import Guard, Policy +from sqlguardllm.server import make_server + +SCHEMA = json.loads( + (Path(__file__).parents[2] / "schema" / "protocol" / "protocol.schema.json").read_text("utf-8") +) +POLICY: dict[str, Any] = { + "dialect": "postgres", + "tables": ["orders", "customers"], + "schema": {"orders": ["id", "total", "customer_id"], "customers": ["id", "name", "email"]}, + "data_classes": {"email": {"action": "mask", "strategy": "partial"}}, + "column_classes": {"customers.email": "email"}, + "advice": {"warn_below": 90}, +} +SQL = ( + "SELECT o.id, c.email FROM orders o JOIN customers c ON c.id = o.customer_id " + "WHERE UPPER(c.name) = 'A'" +) + + +def in_process() -> dict[str, Any]: + return Guard(Policy.from_dict(POLICY)).explain(SQL).to_dict() + + +def over_stdio() -> dict[str, Any]: + proc = subprocess.Popen( + [sys.executable, "-m", "sqlguardllm", "engine", "--stdio"], + stdin=subprocess.PIPE, + stdout=subprocess.PIPE, + stderr=subprocess.DEVNULL, + text=True, + encoding="utf-8", + ) + assert proc.stdin is not None and proc.stdout is not None + + def call(message: dict[str, Any]) -> dict[str, Any]: + proc.stdin.write(json.dumps(message) + "\n") # type: ignore[union-attr] + proc.stdin.flush() # type: ignore[union-attr] + return json.loads(proc.stdout.readline()) # type: ignore[union-attr,no-any-return] + + handle = call({"id": 0, "type": "load_policy", "policy": POLICY})["handle"] + reply = call({"id": 1, "type": "explain", "handle": handle, "sql": SQL, "context": None}) + proc.stdin.close() + assert proc.wait(timeout=30) == 0 + proc.stdout.close() + return reply["result"] # type: ignore[no-any-return] + + +def over_http() -> dict[str, Any]: + server = make_server(Guard(Policy.from_dict(POLICY)), port=0) + thread = threading.Thread(target=server.serve_forever, daemon=True) + thread.start() + try: + url = f"http://127.0.0.1:{server.server_address[1]}/v1/explain" + body = json.dumps({"sql": SQL, "context": None}).encode() + request = urllib.request.Request(url, body, {"Content-Type": "application/json"}) + with urllib.request.urlopen(request) as response: + return json.load(response) # type: ignore[no-any-return] + finally: + server.shutdown() + server.server_close() + + +@pytest.fixture(scope="module") +def answers() -> dict[str, dict[str, Any]]: + return {"process": in_process(), "stdio": over_stdio(), "http": over_http()} + + +def test_the_three_transports_agree(answers: dict[str, dict[str, Any]]) -> None: + for name in ("process", "stdio"): + assert answers[name] == answers["http"], name + + +def test_the_extras_are_there_and_make_sense(answers: dict[str, dict[str, Any]]) -> None: + got = answers["http"] + assert got["data_classes"] == {"email": ["customers.email"]} + advice = got["advice"] + assert advice["score"] < 100 and advice["warn"] is True + assert "function-on-filtered-column" in {f["code"] for f in advice["findings"]} + assert advice["tables"]["customers"]["filtered"] == ["name"] + assert advice["tables"]["orders"]["joined"] == ["customer_id"] + + +def test_the_extras_follow_the_published_schema(answers: dict[str, dict[str, Any]]) -> None: + schema = SCHEMA["$defs"]["ExplainResult"] + got = answers["http"] + assert set(schema["required"]) <= set(got) + assert {"advice", "data_classes"} <= set(schema["properties"]) + assert set(schema["properties"]["advice"]["required"]) <= set(got["advice"]) + try: + import jsonschema # noqa: PLC0415 - stronger check when it is installed + except ImportError: + return + jsonschema.validate(got, {**schema, "$defs": SCHEMA["$defs"]}) + + +def test_without_the_policy_sections_the_fields_are_absent() -> None: + plain = { + k: v for k, v in POLICY.items() if k not in ("data_classes", "column_classes", "advice") + } + got = Guard(Policy.from_dict(plain)).explain(SQL).to_dict() + assert "advice" not in got and "data_classes" not in got diff --git a/tests/test_advice.py b/tests/test_advice.py index 172777e..4066035 100644 --- a/tests/test_advice.py +++ b/tests/test_advice.py @@ -257,3 +257,74 @@ def test_policy_files_accept_advice(tmp_path: Any) -> None: policy = Policy.from_file(path) assert policy.advice == {"warn_below": 60} assert Guard(policy).explain("SELECT * FROM ventas").advice is not None + + +# --- per-table breakdown (#291) ---------------------------------------------------------- + +TABLE_SCHEMA = { + "orders": ["id", "total", "customer_id", "created_at"], + "customers": ["id", "name", "email"], +} + + +def per_table(sql: str, **advice: Any) -> dict[str, Any]: + policy = Policy( + dialect="postgres", tables=list(TABLE_SCHEMA), schema=TABLE_SCHEMA, advice=advice + ) + result = Guard(policy).explain(sql).advice + assert result is not None + return {t: dict(c) for t, c in result.tables.items()} + + +def test_aliases_and_unqualified_columns_resolve_to_their_tables() -> None: + sql = ( + "SELECT o.id, UPPER(c.name), total FROM orders o JOIN customers c ON c.id = o.customer_id " + "WHERE o.created_at >= '2026-01-01' AND LOWER(c.email) = 'a' " + "GROUP BY o.id, c.name, total ORDER BY o.id LIMIT 5" + ) + tables = per_table(sql) + assert tables["orders"] == { + "filtered": ("created_at",), + "grouped": ("id", "total"), + "joined": ("customer_id",), + "ordered": ("id",), + "projected": ("id", "total"), + } + assert tables["customers"] == { + "filtered": ("email",), + "grouped": ("name",), + "in_functions": ("email", "name"), + "joined": ("id",), + "projected": ("name",), + } + + +def test_subquery_columns_belong_to_the_physical_table() -> None: + tables = per_table( + "SELECT id FROM (SELECT id, total FROM orders WHERE total > 5) t WHERE id > 1" + ) + assert tables == {"orders": {"filtered": ("total",), "projected": ("id", "total")}} + + +def test_stars_and_correlated_subqueries() -> None: + tables = per_table( + "SELECT * FROM orders o WHERE EXISTS " + "(SELECT 1 FROM customers c WHERE c.id = o.customer_id) LIMIT 3" + ) + assert tables["orders"] == {"filtered": ("customer_id",), "projected": ("*",)} + assert tables["customers"] == {"filtered": ("id",)} + + +def test_an_unqualified_column_with_no_single_owner_is_left_out() -> None: + policy = Policy( + dialect="postgres", + tables=list(TABLE_SCHEMA), + advice={}, # no schema: an unqualified `id` over two tables belongs to neither + ) + result = Guard(policy).explain("SELECT id FROM orders o JOIN customers c ON c.id = o.id").advice + assert result is not None and "projected" not in result.tables.get("orders", {}) + + +def test_the_breakdown_is_in_the_serialized_advice() -> None: + data = guard().explain("SELECT id FROM orders WHERE total > 1 LIMIT 5").to_dict()["advice"] + assert data["tables"] == {"orders": {"filtered": ["total"], "projected": ["id"]}}