Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
42 changes: 42 additions & 0 deletions .github/workflows/policy-diff-example.yml
Original file line number Diff line number Diff line change
@@ -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
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
2 changes: 1 addition & 1 deletion clients/dotnet/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,7 @@ It works with `dotnet run`, `dotnet publish -r <rid>`, 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
Expand Down
21 changes: 20 additions & 1 deletion clients/dotnet/src/SqlGuardLlm/SqlGuardLlm.cs
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,26 @@ public sealed record CheckResult

/// <summary>Result of /v1/explain. <see cref="Raw"/> holds the whole JSON object.</summary>
public sealed record ExplainResult(
bool Ok, string? Sql, IReadOnlyList<string> Tables, IReadOnlyList<Violation> Violations, JsonElement Raw);
bool Ok, string? Sql, IReadOnlyList<string> Tables, IReadOnlyList<Violation> Violations, JsonElement Raw)
{
/// <summary>Experimental. Findings and the 1-100 score; <c>null</c> unless the policy has an <c>advice</c> section.</summary>
public QueryAdvice? Advice => Wire.ParseAdvice(Raw);

/// <summary>Experimental. Class to the <c>table.column</c> entries the query reads; empty unless the policy has data classes.</summary>
public IReadOnlyDictionary<string, IReadOnlyList<string>> DataClasses => Wire.ParseDataClasses(Raw);
}

/// <summary>Experimental. One thing that makes a query wasteful: a stable code, what it points at, and its penalty.</summary>
public sealed record AdviceFinding(string Code, string Detail, int Penalty);

/// <summary>
/// Experimental. Query advice from an explanation. <see cref="Columns"/> is clause to column names as written;
/// <see cref="Tables"/> is table to clause to column names, resolved to the physical table.
/// </summary>
public sealed record QueryAdvice(
int Score, bool Warn, IReadOnlyList<AdviceFinding> Findings,
IReadOnlyDictionary<string, IReadOnlyList<string>> Columns,
IReadOnlyDictionary<string, IReadOnlyDictionary<string, IReadOnlyList<string>>> Tables);

/// <summary>Result of /v1/health.</summary>
public sealed record HealthResult(
Expand Down
43 changes: 43 additions & 0 deletions clients/dotnet/src/SqlGuardLlm/Wire.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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<string> Strings(JsonElement array)
{
var list = new List<string>();
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<string, IReadOnlyList<string>> StringMap(JsonElement obj)
{
var map = new Dictionary<string, IReadOnlyList<string>>();
if (obj.ValueKind == JsonValueKind.Object)
foreach (var p in obj.EnumerateObject()) map[p.Name] = Strings(p.Value);
return map;
}

public static IReadOnlyDictionary<string, IReadOnlyList<string>> ParseDataClasses(JsonElement raw)
=> raw.ValueKind == JsonValueKind.Object && raw.TryGetProperty("data_classes", out var d)
? StringMap(d) : new Dictionary<string, IReadOnlyList<string>>();

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<AdviceFinding>();
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<string, IReadOnlyDictionary<string, IReadOnlyList<string>>>();
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<string, IReadOnlyList<string>>(),
tables);
}

/// <summary>Writes a context value without reflection. Unsupported types fail loudly instead of being dropped.</summary>
public static void WriteValue(Utf8JsonWriter w, object? value, int depth)
{
Expand Down
18 changes: 18 additions & 0 deletions clients/dotnet/tests/SqlGuardLlm.Tests/ClientTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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"}""")));
Expand Down
2 changes: 1 addition & 1 deletion clients/node/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
33 changes: 33 additions & 0 deletions clients/node/src/generated.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<string, string>;
/** 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<string, {
action: "hide" | "mask";
strategy?: "null" | "redact" | "hash" | "partial";
}>);
/** Experimental. table.column -> a class defined in data_classes. */
column_classes?: (null | Record<string, string>);
/** Experimental. table.column -> why a column that looks sensitive is not. Only the linter reads it. */
not_sensitive?: (null | Record<string, string>);
};

/** Values for the {context.path} placeholders of the row filters. */
Expand Down Expand Up @@ -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<string, string[]>;
tables: Record<string, Record<string, string[]>>;
};
/** Present only when the policy has data classes. Experimental. */
data_classes?: Record<string, string[]>;
};

export type WireErrorBody = {
Expand Down
5 changes: 5 additions & 0 deletions clients/node/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<Response>;

Expand All @@ -19,6 +20,10 @@ export interface Explanation extends Record<string, unknown> {
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;
Expand Down
10 changes: 10 additions & 0 deletions clients/node/test/client.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ beforeAll(async () => {
if (sql === "slow") return void setTimeout(() => j(200, {}), 500);
if (sql === "garbage") return j(200, "<html>");
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: [] });
Expand Down Expand Up @@ -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);
Expand Down
3 changes: 1 addition & 2 deletions docs/ADVICE.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand All @@ -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.
1 change: 0 additions & 1 deletion docs/CLASSES.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Loading
Loading