sqlguardllm 0.1.0a1__tar.gz → 0.2.0a1__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- {sqlguardllm-0.1.0a1 → sqlguardllm-0.2.0a1}/CHANGELOG.md +26 -4
- {sqlguardllm-0.1.0a1 → sqlguardllm-0.2.0a1}/PKG-INFO +14 -14
- {sqlguardllm-0.1.0a1 → sqlguardllm-0.2.0a1}/README.md +40 -21
- {sqlguardllm-0.1.0a1 → sqlguardllm-0.2.0a1}/docs/pypi.md +8 -8
- {sqlguardllm-0.1.0a1 → sqlguardllm-0.2.0a1}/pyproject.toml +7 -7
- {sqlguardllm-0.1.0a1/src/sqlguard → sqlguardllm-0.2.0a1/src/sqlguardllm}/__init__.py +5 -5
- {sqlguardllm-0.1.0a1/src/sqlguard → sqlguardllm-0.2.0a1/src/sqlguardllm}/_compiled.py +7 -2
- {sqlguardllm-0.1.0a1/src/sqlguard → sqlguardllm-0.2.0a1/src/sqlguardllm}/_names.py +1 -1
- {sqlguardllm-0.1.0a1/src/sqlguard → sqlguardllm-0.2.0a1/src/sqlguardllm}/guard.py +34 -13
- {sqlguardllm-0.1.0a1/src/sqlguard → sqlguardllm-0.2.0a1/src/sqlguardllm}/messages.py +9 -1
- {sqlguardllm-0.1.0a1/src/sqlguard → sqlguardllm-0.2.0a1/src/sqlguardllm}/policy.py +40 -3
- {sqlguardllm-0.1.0a1/src/sqlguard → sqlguardllm-0.2.0a1/src/sqlguardllm}/result.py +6 -4
- {sqlguardllm-0.1.0a1/src/sqlguard → sqlguardllm-0.2.0a1/src/sqlguardllm}/rules/columns.py +4 -4
- sqlguardllm-0.2.0a1/src/sqlguardllm/rules/complexity.py +122 -0
- {sqlguardllm-0.1.0a1/src/sqlguard → sqlguardllm-0.2.0a1/src/sqlguardllm}/rules/functions.py +3 -3
- sqlguardllm-0.2.0a1/src/sqlguardllm/rules/required_filters.py +76 -0
- {sqlguardllm-0.1.0a1/src/sqlguard → sqlguardllm-0.2.0a1/src/sqlguardllm}/rules/row_filters.py +6 -6
- {sqlguardllm-0.1.0a1/src/sqlguard → sqlguardllm-0.2.0a1/src/sqlguardllm}/rules/sources.py +4 -4
- {sqlguardllm-0.1.0a1/src/sqlguard → sqlguardllm-0.2.0a1/src/sqlguardllm}/rules/statement.py +2 -2
- {sqlguardllm-0.1.0a1 → sqlguardllm-0.2.0a1}/tests/conftest.py +1 -1
- sqlguardllm-0.2.0a1/tests/corpus/complexity.yaml +125 -0
- sqlguardllm-0.2.0a1/tests/corpus/required_filters.yaml +76 -0
- {sqlguardllm-0.1.0a1 → sqlguardllm-0.2.0a1}/tests/test_api.py +4 -4
- {sqlguardllm-0.1.0a1 → sqlguardllm-0.2.0a1}/tests/test_corpus.py +3 -2
- {sqlguardllm-0.1.0a1 → sqlguardllm-0.2.0a1}/tests/test_policy.py +34 -1
- {sqlguardllm-0.1.0a1 → sqlguardllm-0.2.0a1}/tests/test_row_filters.py +1 -1
- {sqlguardllm-0.1.0a1 → sqlguardllm-0.2.0a1}/tests/test_rules.py +52 -1
- {sqlguardllm-0.1.0a1 → sqlguardllm-0.2.0a1}/.gitignore +0 -0
- {sqlguardllm-0.1.0a1 → sqlguardllm-0.2.0a1}/LICENSE +0 -0
- {sqlguardllm-0.1.0a1/src/sqlguard → sqlguardllm-0.2.0a1/src/sqlguardllm}/data/__init__.py +0 -0
- {sqlguardllm-0.1.0a1/src/sqlguard → sqlguardllm-0.2.0a1/src/sqlguardllm}/data/denied_functions.py +0 -0
- {sqlguardllm-0.1.0a1/src/sqlguard → sqlguardllm-0.2.0a1/src/sqlguardllm}/py.typed +0 -0
- {sqlguardllm-0.1.0a1/src/sqlguard → sqlguardllm-0.2.0a1/src/sqlguardllm}/rules/__init__.py +0 -0
- {sqlguardllm-0.1.0a1/src/sqlguard → sqlguardllm-0.2.0a1/src/sqlguardllm}/rules/limit.py +0 -0
- {sqlguardllm-0.1.0a1 → sqlguardllm-0.2.0a1}/tests/corpus/allowed.yaml +0 -0
- {sqlguardllm-0.1.0a1 → sqlguardllm-0.2.0a1}/tests/corpus/context.yaml +0 -0
- {sqlguardllm-0.1.0a1 → sqlguardllm-0.2.0a1}/tests/corpus/functions.yaml +0 -0
- {sqlguardllm-0.1.0a1 → sqlguardllm-0.2.0a1}/tests/corpus/tables_columns.yaml +0 -0
- {sqlguardllm-0.1.0a1 → sqlguardllm-0.2.0a1}/tests/corpus/writes.yaml +0 -0
|
@@ -1,12 +1,32 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
-
All notable changes to
|
|
3
|
+
All notable changes to sqlguardllm are documented here. The format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/) and the project uses [Semantic Versioning](https://semver.org/). Violation codes are stable across minor versions.
|
|
4
4
|
|
|
5
5
|
## [Unreleased]
|
|
6
6
|
|
|
7
|
+
## [0.2.0a1] - 2026-11-25
|
|
8
|
+
|
|
9
|
+
Optional limits for queries that are far more expensive than the question that produced them. All new options are off by default: existing policies behave exactly the same.
|
|
10
|
+
|
|
11
|
+
### Added
|
|
12
|
+
|
|
13
|
+
- Complexity limits, all off by default: `max_joins`, `max_subquery_depth` and `forbid_cartesian`, with the new violation code `too_complex` (#23).
|
|
14
|
+
- `required_filters`: a table can only be read with a predicate on one of the given columns, such as a date range on a fact table, with the new code `missing_required_filter` (#24).
|
|
15
|
+
- `output_dialect`: parse in the policy's dialect and generate the rewritten SQL in another one; limits render as `TOP` or `FETCH FIRST` where needed (#25).
|
|
16
|
+
- Corpus cases can set their own policy options with a `policy` key.
|
|
17
|
+
|
|
18
|
+
## [0.1.0a2] - 2026-11-25
|
|
19
|
+
|
|
20
|
+
One name everywhere: the project is now **sqlguardllm**.
|
|
21
|
+
|
|
22
|
+
### Changed
|
|
23
|
+
|
|
24
|
+
- The import package is now `sqlguardllm` (`from sqlguardllm import Guard, Policy`), matching the PyPI name. `import sqlguard` from 0.1.0a1 no longer works.
|
|
25
|
+
- The repository moved to [jmmana/sqlguardllm](https://github.com/jmmana/sqlguardllm); the old URL redirects.
|
|
26
|
+
|
|
7
27
|
## [0.1.0a1] - 2026-11-25
|
|
8
28
|
|
|
9
|
-
First alpha.
|
|
29
|
+
First alpha. Installed with `pip install sqlguardllm` and imported as `import sqlguard`.
|
|
10
30
|
|
|
11
31
|
### Added
|
|
12
32
|
|
|
@@ -27,5 +47,7 @@ First alpha. Install with `pip install sqlguardllm`; import with `import sqlguar
|
|
|
27
47
|
- Table functions are rejected, even harmless ones like `generate_series`.
|
|
28
48
|
- No command-line tool yet (planned for v0.2).
|
|
29
49
|
|
|
30
|
-
[Unreleased]: https://github.com/jmmana/
|
|
31
|
-
[0.
|
|
50
|
+
[Unreleased]: https://github.com/jmmana/sqlguardllm/compare/v0.2.0a1...HEAD
|
|
51
|
+
[0.2.0a1]: https://github.com/jmmana/sqlguardllm/compare/v0.1.0a2...v0.2.0a1
|
|
52
|
+
[0.1.0a2]: https://github.com/jmmana/sqlguardllm/compare/v0.1.0a1...v0.1.0a2
|
|
53
|
+
[0.1.0a1]: https://github.com/jmmana/sqlguardllm/releases/tag/v0.1.0a1
|
|
@@ -1,12 +1,12 @@
|
|
|
1
1
|
Metadata-Version: 2.5
|
|
2
2
|
Name: sqlguardllm
|
|
3
|
-
Version: 0.
|
|
3
|
+
Version: 0.2.0a1
|
|
4
4
|
Summary: The SQL firewall for LLM apps: validate SQL written by AI and rewrite it read-only, allowlisted, row-filtered and limited.
|
|
5
|
-
Project-URL: Homepage, https://github.com/jmmana/
|
|
6
|
-
Project-URL: Documentation, https://github.com/jmmana/
|
|
7
|
-
Project-URL: Issues, https://github.com/jmmana/
|
|
8
|
-
Project-URL: Changelog, https://github.com/jmmana/
|
|
9
|
-
Project-URL: Source, https://github.com/jmmana/
|
|
5
|
+
Project-URL: Homepage, https://github.com/jmmana/sqlguardllm
|
|
6
|
+
Project-URL: Documentation, https://github.com/jmmana/sqlguardllm/tree/main/docs
|
|
7
|
+
Project-URL: Issues, https://github.com/jmmana/sqlguardllm/issues
|
|
8
|
+
Project-URL: Changelog, https://github.com/jmmana/sqlguardllm/blob/main/CHANGELOG.md
|
|
9
|
+
Project-URL: Source, https://github.com/jmmana/sqlguardllm
|
|
10
10
|
Author: Juan Castillo
|
|
11
11
|
License-Expression: Apache-2.0
|
|
12
12
|
License-File: LICENSE
|
|
@@ -32,19 +32,19 @@ Requires-Dist: pyyaml>=6.0; extra == 'yaml'
|
|
|
32
32
|
Description-Content-Type: text/markdown
|
|
33
33
|
|
|
34
34
|
<p align="center">
|
|
35
|
-
<img alt="
|
|
35
|
+
<img alt="sqlguardllm" src="https://raw.githubusercontent.com/jmmana/sqlguardllm/main/docs/assets/logo-light.svg" width="340">
|
|
36
36
|
</p>
|
|
37
37
|
|
|
38
|
-
#
|
|
38
|
+
# sqlguardllm — the SQL firewall for LLM apps
|
|
39
39
|
|
|
40
|
-
Your model writes SQL. **
|
|
40
|
+
Your model writes SQL. **sqlguardllm** makes sure it can only read what it's allowed to read: one read-only statement, allowlisted tables and columns, row-level filters per user, and a row limit, in any dialect [sqlglot](https://github.com/tobymao/sqlglot) understands.
|
|
41
41
|
|
|
42
42
|
```bash
|
|
43
43
|
pip install sqlguardllm
|
|
44
44
|
```
|
|
45
45
|
|
|
46
46
|
```python
|
|
47
|
-
from
|
|
47
|
+
from sqlguardllm import Guard, Policy
|
|
48
48
|
|
|
49
49
|
guard = Guard(
|
|
50
50
|
Policy(
|
|
@@ -77,8 +77,8 @@ Pure Python, one dependency (sqlglot), no network, no LLM. Status: **alpha** —
|
|
|
77
77
|
|
|
78
78
|
## Learn more
|
|
79
79
|
|
|
80
|
-
- Source, design and attack gallery: <https://github.com/jmmana/
|
|
81
|
-
- Threat model: <https://github.com/jmmana/
|
|
82
|
-
- Report a bypass privately: <https://github.com/jmmana/
|
|
80
|
+
- Source, design and attack gallery: <https://github.com/jmmana/sqlguardllm>
|
|
81
|
+
- Threat model: <https://github.com/jmmana/sqlguardllm/blob/main/docs/THREAT_MODEL.md>
|
|
82
|
+
- Report a bypass privately: <https://github.com/jmmana/sqlguardllm/security/advisories/new>
|
|
83
83
|
|
|
84
|
-
|
|
84
|
+
Licensed under Apache-2.0.
|
|
@@ -5,26 +5,26 @@
|
|
|
5
5
|
|
|
6
6
|
<picture>
|
|
7
7
|
<source media="(prefers-color-scheme: dark)" srcset="docs/assets/logo-dark.svg">
|
|
8
|
-
<img alt="
|
|
8
|
+
<img alt="sqlguardllm" src="docs/assets/logo-light.svg" width="380">
|
|
9
9
|
</picture>
|
|
10
10
|
|
|
11
11
|
### The SQL firewall for LLM apps.
|
|
12
12
|
|
|
13
|
-
Your model writes SQL. **
|
|
13
|
+
Your model writes SQL. **sqlguardllm** makes sure it can only read what it's allowed to read: one read-only statement, allowlisted tables and columns, row-level filters per user, and a row limit, in any of the 32 dialects [sqlglot](https://github.com/tobymao/sqlglot) speaks.
|
|
14
14
|
|
|
15
15
|
[](https://pypi.org/project/sqlguardllm/)
|
|
16
|
-
[](https://github.com/jmmana/sqlguardllm/actions/workflows/ci.yml)
|
|
17
17
|
[](LICENSE)
|
|
18
18
|
[](docs/DESIGN.md)
|
|
19
19
|
[](https://github.com/tobymao/sqlglot)
|
|
20
20
|
[](CONTRIBUTING.md)
|
|
21
21
|
|
|
22
|
-
<img src="docs/assets/hero.svg" alt="
|
|
22
|
+
<img src="docs/assets/hero.svg" alt="sqlguardllm blocks a DELETE hidden inside a CTE and a query on a hidden column, and rewrites an allowed query with the user's row filter and a row limit" width="100%">
|
|
23
23
|
|
|
24
24
|
</div>
|
|
25
25
|
|
|
26
26
|
> [!NOTE]
|
|
27
|
-
> **Status: alpha.** `0.
|
|
27
|
+
> **Status: alpha.** `0.2.0a1` is on [PyPI](https://pypi.org/project/sqlguardllm/) (`pip install sqlguardllm`, `import sqlguardllm`), with the rules of [docs/DESIGN.md](docs/DESIGN.md), optional complexity limits and a 94-case adversarial corpus. The API may still change before 1.0; violation codes are stable. ⭐ Star the repo to follow along, and tell us what you think in [Discussions](https://github.com/jmmana/sqlguardllm/discussions).
|
|
28
28
|
|
|
29
29
|
---
|
|
30
30
|
|
|
@@ -41,7 +41,7 @@ The usual defense is a keyword blocklist. It fails in **both** directions:
|
|
|
41
41
|
| `SELECT * INTO backup FROM invoices` | ⚠️ Lets it through: it starts with `SELECT` | Creates a new table (SQL Server) |
|
|
42
42
|
| `SELECT name, email FROM customers` | ⚠️ Lets it through | Reads personal data the model should never see |
|
|
43
43
|
|
|
44
|
-
|
|
44
|
+
sqlguardllm parses the statement into a syntax tree with sqlglot and **decides on the tree, not on the text**. Then it rewrites the query so it can only see the rows the current user is allowed to see.
|
|
45
45
|
|
|
46
46
|
## What it guarantees
|
|
47
47
|
|
|
@@ -55,6 +55,18 @@ sqlguard parses the statement into a syntax tree with sqlglot and **decides on t
|
|
|
55
55
|
| 6️⃣ | **Row limit** applied or lowered, in the dialect's own syntax (`LIMIT`, `TOP`, `FETCH FIRST`) |
|
|
56
56
|
| 🔒 | **Fails closed**: if the SQL can't be parsed, or the user context is missing a value a filter needs, the answer is *no* |
|
|
57
57
|
|
|
58
|
+
### Optional limits
|
|
59
|
+
|
|
60
|
+
Off by default; turn on what you need. They stop queries that are far more expensive than the question that produced them.
|
|
61
|
+
|
|
62
|
+
| Policy option | What it does | Violation |
|
|
63
|
+
|---|---|---|
|
|
64
|
+
| `max_joins=4` | Caps joins in the whole query, CTEs and subqueries included | `too_complex` |
|
|
65
|
+
| `max_subquery_depth=2` | Caps nesting of subqueries, derived tables and CTEs | `too_complex` |
|
|
66
|
+
| `forbid_cartesian=True` | Rejects `CROSS JOIN` and comma joins with no linking equality in `WHERE` | `too_complex` |
|
|
67
|
+
| `required_filters={"invoices": ["issued_at"]}` | Every read of the table must filter on one of the columns, such as a date range on a big fact table | `missing_required_filter` |
|
|
68
|
+
| `output_dialect="tsql"` | The model writes PostgreSQL; the rewritten SQL comes out for SQL Server, Oracle or any sqlglot dialect | — |
|
|
69
|
+
|
|
58
70
|
## Quick look
|
|
59
71
|
|
|
60
72
|
```bash
|
|
@@ -62,7 +74,7 @@ pip install sqlguardllm # Python 3.10+, one dependency: sqlglot
|
|
|
62
74
|
```
|
|
63
75
|
|
|
64
76
|
```python
|
|
65
|
-
from
|
|
77
|
+
from sqlguardllm import Guard, Policy
|
|
66
78
|
|
|
67
79
|
guard = Guard(Policy(
|
|
68
80
|
dialect="postgres",
|
|
@@ -139,9 +151,9 @@ Same idea on SQL Server, where the limit becomes `TOP 500`, or Oracle, where it
|
|
|
139
151
|
|
|
140
152
|
## Attack gallery
|
|
141
153
|
|
|
142
|
-
What sqlglot 30.35 actually sees for each attempt, and what
|
|
154
|
+
What sqlglot 30.35 actually sees for each attempt, and what sqlguardllm does about it. Every row is a test case. The full list is in [docs/ATTACK_GALLERY.md](docs/ATTACK_GALLERY.md).
|
|
143
155
|
|
|
144
|
-
| Dialect | Attempt | sqlglot sees |
|
|
156
|
+
| Dialect | Attempt | sqlglot sees | sqlguardllm |
|
|
145
157
|
|---|---|---|---|
|
|
146
158
|
| postgres | `WITH d AS (DELETE FROM invoices RETURNING *) SELECT * FROM d` | `Select` root with a `Delete` inside | ❌ `write_operation` |
|
|
147
159
|
| tsql | `SELECT 1; DROP TABLE invoices` | 2 statements | ❌ `multiple_statements` |
|
|
@@ -158,10 +170,10 @@ Found a way through? That's a vulnerability: please [report it privately](SECURI
|
|
|
158
170
|
|
|
159
171
|
## Where it fits
|
|
160
172
|
|
|
161
|
-
|
|
173
|
+
sqlguardllm is **one layer**, not the only one. Keep the others:
|
|
162
174
|
|
|
163
175
|
1. **A read-only database user** with access to only the tables the app needs. Non-negotiable.
|
|
164
|
-
2. **
|
|
176
|
+
2. **sqlguardllm** between the model and the database: shape, allowlists, row filters, limits.
|
|
165
177
|
3. **Statement timeouts** in the database, against expensive queries.
|
|
166
178
|
4. **Audit logs** of every SQL that ran and for whom.
|
|
167
179
|
|
|
@@ -169,26 +181,33 @@ What it does not do, and why, is in the [threat model](docs/THREAT_MODEL.md).
|
|
|
169
181
|
|
|
170
182
|
## Works with your stack
|
|
171
183
|
|
|
172
|
-
|
|
184
|
+
sqlguardllm sits wherever your app executes the SQL the model wrote. Recipes, planned for v0.3, will cover a generic `execute()` wrapper, LangChain and LlamaIndex SQL tools, Vanna, and MCP database servers. See [docs/INTEGRATIONS.md](docs/INTEGRATIONS.md).
|
|
173
185
|
|
|
174
186
|
A command-line tool is planned too, handy in CI and for trying policies:
|
|
175
187
|
|
|
176
188
|
```bash
|
|
177
|
-
|
|
189
|
+
sqlguardllm check --policy policy.yaml --context '{"user": {"branches": [1, 2]}}' \
|
|
178
190
|
"SELECT * FROM invoices"
|
|
179
191
|
```
|
|
180
192
|
|
|
193
|
+
## Other languages
|
|
194
|
+
|
|
195
|
+
sqlguardllm is a Python library today: its engine is [sqlglot](https://github.com/tobymao/sqlglot), which only exists in Python, and three engines in three languages could disagree, which in a security library means a bypass. **Node.js and .NET are planned** as one engine with many clients: `sqlguardllm serve` (an HTTP sidecar and Docker image) plus official npm and NuGet clients, with the attack corpus as a conformance suite so every language behaves the same. Follow it in [Later · Node.js and .NET](https://github.com/jmmana/sqlguardllm/milestone/6) and the [design](docs/DESIGN.md#other-languages). Until then, any language can use the MCP server (v0.4) or the CLI (v0.2).
|
|
196
|
+
|
|
181
197
|
## Playground: try to break it
|
|
182
198
|
|
|
183
|
-
A static playground (planned for v0.3) will run
|
|
199
|
+
A static playground (planned for v0.3) will run sqlguardllm **entirely in your browser** with Pyodide and a demo SQLite database: pick a role, type the nastiest SQL you can think of, and watch it get blocked or rewritten. No server, no sign-up.
|
|
184
200
|
|
|
185
201
|
## Roadmap
|
|
186
202
|
|
|
187
203
|
| Milestone | Scope |
|
|
188
204
|
|---|---|
|
|
189
|
-
| [**v0.1 · Core guard**](https://github.com/jmmana/
|
|
190
|
-
| [**v0.2 · Row-level security & CLI**](https://github.com/jmmana/
|
|
191
|
-
| [**v0.3 ·
|
|
205
|
+
| [**v0.1 · Core guard**](https://github.com/jmmana/sqlguardllm/milestone/1) | Statement and read-only checks, allowlists, hidden columns, denied functions, row limit, adversarial corpus |
|
|
206
|
+
| [**v0.2 · Row-level security & CLI**](https://github.com/jmmana/sqlguardllm/milestone/2) | Row filters as derived tables, policy files, CLI, dialect test matrix, docs site, PyPI release |
|
|
207
|
+
| [**v0.3 · More power**](https://github.com/jmmana/sqlguardllm/milestone/4) | Complexity limits, required filters, PII masking, aggregate-only tables (k-anonymity), exact schema from the database, policies per role, `explain()`, dialect translation |
|
|
208
|
+
| [**v0.4 · MCP server**](https://github.com/jmmana/sqlguardllm/milestone/5) | A safe database tool for Claude Desktop, Cursor and any agent, with an optional cost guard |
|
|
209
|
+
| [**v0.5 · Ecosystem & playground**](https://github.com/jmmana/sqlguardllm/milestone/3) | Integration recipes, browser playground, performance budget |
|
|
210
|
+
| [**Later · Node.js and .NET**](https://github.com/jmmana/sqlguardllm/milestone/6) | One engine, many clients: server mode plus npm and NuGet clients |
|
|
192
211
|
|
|
193
212
|
Details in [docs/ROADMAP.md](docs/ROADMAP.md).
|
|
194
213
|
|
|
@@ -199,14 +218,14 @@ Contributions are very welcome, and some of the most valuable ones need no deep
|
|
|
199
218
|
- **Add attack cases** to the adversarial corpus, especially for dialects you know well.
|
|
200
219
|
- **Extend the denied-function lists** for your database.
|
|
201
220
|
- **Translate violation messages.**
|
|
202
|
-
- **Challenge the design** in [Discussions](https://github.com/jmmana/
|
|
221
|
+
- **Challenge the design** in [Discussions](https://github.com/jmmana/sqlguardllm/discussions) before v0.1 freezes the API.
|
|
203
222
|
|
|
204
|
-
Start with [CONTRIBUTING.md](CONTRIBUTING.md) and the [good first issues](https://github.com/jmmana/
|
|
223
|
+
Start with [CONTRIBUTING.md](CONTRIBUTING.md) and the [good first issues](https://github.com/jmmana/sqlguardllm/labels/good%20first%20issue). This project follows a [Code of Conduct](CODE_OF_CONDUCT.md).
|
|
205
224
|
|
|
206
225
|
## Security
|
|
207
226
|
|
|
208
|
-
A bypass of
|
|
227
|
+
A bypass of sqlguardllm is a security vulnerability. **Don't open a public issue:** report it privately as described in [SECURITY.md](SECURITY.md).
|
|
209
228
|
|
|
210
229
|
## License
|
|
211
230
|
|
|
212
|
-
[Apache-2.0](LICENSE) © 2026 Juan Castillo.
|
|
231
|
+
[Apache-2.0](LICENSE) © 2026 Juan Castillo. sqlguardllm was born inside [ChatIApp](https://github.com/jmmana/ChatIApp), an open-source chat that turns business questions into safe SQL.
|
|
@@ -1,17 +1,17 @@
|
|
|
1
1
|
<p align="center">
|
|
2
|
-
<img alt="
|
|
2
|
+
<img alt="sqlguardllm" src="https://raw.githubusercontent.com/jmmana/sqlguardllm/main/docs/assets/logo-light.svg" width="340">
|
|
3
3
|
</p>
|
|
4
4
|
|
|
5
|
-
#
|
|
5
|
+
# sqlguardllm — the SQL firewall for LLM apps
|
|
6
6
|
|
|
7
|
-
Your model writes SQL. **
|
|
7
|
+
Your model writes SQL. **sqlguardllm** makes sure it can only read what it's allowed to read: one read-only statement, allowlisted tables and columns, row-level filters per user, and a row limit, in any dialect [sqlglot](https://github.com/tobymao/sqlglot) understands.
|
|
8
8
|
|
|
9
9
|
```bash
|
|
10
10
|
pip install sqlguardllm
|
|
11
11
|
```
|
|
12
12
|
|
|
13
13
|
```python
|
|
14
|
-
from
|
|
14
|
+
from sqlguardllm import Guard, Policy
|
|
15
15
|
|
|
16
16
|
guard = Guard(
|
|
17
17
|
Policy(
|
|
@@ -44,8 +44,8 @@ Pure Python, one dependency (sqlglot), no network, no LLM. Status: **alpha** —
|
|
|
44
44
|
|
|
45
45
|
## Learn more
|
|
46
46
|
|
|
47
|
-
- Source, design and attack gallery: <https://github.com/jmmana/
|
|
48
|
-
- Threat model: <https://github.com/jmmana/
|
|
49
|
-
- Report a bypass privately: <https://github.com/jmmana/
|
|
47
|
+
- Source, design and attack gallery: <https://github.com/jmmana/sqlguardllm>
|
|
48
|
+
- Threat model: <https://github.com/jmmana/sqlguardllm/blob/main/docs/THREAT_MODEL.md>
|
|
49
|
+
- Report a bypass privately: <https://github.com/jmmana/sqlguardllm/security/advisories/new>
|
|
50
50
|
|
|
51
|
-
|
|
51
|
+
Licensed under Apache-2.0.
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
[project]
|
|
2
2
|
name = "sqlguardllm"
|
|
3
|
-
version = "0.
|
|
3
|
+
version = "0.2.0a1"
|
|
4
4
|
description = "The SQL firewall for LLM apps: validate SQL written by AI and rewrite it read-only, allowlisted, row-filtered and limited."
|
|
5
5
|
readme = "docs/pypi.md"
|
|
6
6
|
requires-python = ">=3.10"
|
|
@@ -30,11 +30,11 @@ dependencies = ["sqlglot>=30.0,<31"]
|
|
|
30
30
|
yaml = ["pyyaml>=6.0"]
|
|
31
31
|
|
|
32
32
|
[project.urls]
|
|
33
|
-
Homepage = "https://github.com/jmmana/
|
|
34
|
-
Documentation = "https://github.com/jmmana/
|
|
35
|
-
Issues = "https://github.com/jmmana/
|
|
36
|
-
Changelog = "https://github.com/jmmana/
|
|
37
|
-
Source = "https://github.com/jmmana/
|
|
33
|
+
Homepage = "https://github.com/jmmana/sqlguardllm"
|
|
34
|
+
Documentation = "https://github.com/jmmana/sqlguardllm/tree/main/docs"
|
|
35
|
+
Issues = "https://github.com/jmmana/sqlguardllm/issues"
|
|
36
|
+
Changelog = "https://github.com/jmmana/sqlguardllm/blob/main/CHANGELOG.md"
|
|
37
|
+
Source = "https://github.com/jmmana/sqlguardllm"
|
|
38
38
|
|
|
39
39
|
[dependency-groups]
|
|
40
40
|
dev = [
|
|
@@ -50,7 +50,7 @@ requires = ["hatchling>=1.26"]
|
|
|
50
50
|
build-backend = "hatchling.build"
|
|
51
51
|
|
|
52
52
|
[tool.hatch.build.targets.wheel]
|
|
53
|
-
packages = ["src/
|
|
53
|
+
packages = ["src/sqlguardllm"]
|
|
54
54
|
|
|
55
55
|
[tool.hatch.build.targets.sdist]
|
|
56
56
|
include = ["src", "tests", "docs/pypi.md", "README.md", "LICENSE", "CHANGELOG.md"]
|
|
@@ -1,9 +1,9 @@
|
|
|
1
|
-
"""
|
|
1
|
+
"""sqlguardllm: the SQL firewall for LLM apps.
|
|
2
2
|
|
|
3
3
|
Validate SQL written by an untrusted source and rewrite it so it is a single read-only query
|
|
4
4
|
over allowlisted tables and columns, filtered per user and bounded in rows::
|
|
5
5
|
|
|
6
|
-
from
|
|
6
|
+
from sqlguardllm import Guard, Policy
|
|
7
7
|
|
|
8
8
|
guard = Guard(Policy(dialect="postgres", tables={"invoices"}, max_rows=1000))
|
|
9
9
|
result = guard.check("SELECT * FROM invoices")
|
|
@@ -13,9 +13,9 @@ from __future__ import annotations
|
|
|
13
13
|
|
|
14
14
|
from importlib.metadata import PackageNotFoundError, version
|
|
15
15
|
|
|
16
|
-
from
|
|
17
|
-
from
|
|
18
|
-
from
|
|
16
|
+
from sqlguardllm.guard import Guard
|
|
17
|
+
from sqlguardllm.policy import FunctionPolicy, Policy
|
|
18
|
+
from sqlguardllm.result import CheckResult, GuardViolation, PolicyError, Violation, ViolationCode
|
|
19
19
|
|
|
20
20
|
try:
|
|
21
21
|
__version__ = version("sqlguardllm")
|
|
@@ -3,12 +3,12 @@
|
|
|
3
3
|
from __future__ import annotations
|
|
4
4
|
|
|
5
5
|
from collections.abc import Mapping
|
|
6
|
-
from dataclasses import dataclass
|
|
6
|
+
from dataclasses import dataclass, field
|
|
7
7
|
|
|
8
8
|
from sqlglot import exp
|
|
9
9
|
from sqlglot.dialects.dialect import Dialect
|
|
10
10
|
|
|
11
|
-
from
|
|
11
|
+
from sqlguardllm._names import TableName
|
|
12
12
|
|
|
13
13
|
|
|
14
14
|
@dataclass(frozen=True)
|
|
@@ -35,3 +35,8 @@ class Compiled:
|
|
|
35
35
|
allowed: frozenset[str] | None
|
|
36
36
|
max_rows: int | None
|
|
37
37
|
default_schema: str | None
|
|
38
|
+
output_dialect_name: str
|
|
39
|
+
max_joins: int | None = None
|
|
40
|
+
max_subquery_depth: int | None = None
|
|
41
|
+
forbid_cartesian: bool = False
|
|
42
|
+
required: Mapping[TableName, frozenset[str]] = field(default_factory=dict)
|
|
@@ -12,18 +12,20 @@ from sqlglot.dialects.dialect import Dialect
|
|
|
12
12
|
from sqlglot.errors import SqlglotError
|
|
13
13
|
from sqlglot.optimizer.scope import traverse_scope
|
|
14
14
|
|
|
15
|
-
from
|
|
16
|
-
from
|
|
17
|
-
from
|
|
18
|
-
from
|
|
19
|
-
from
|
|
20
|
-
from
|
|
21
|
-
from
|
|
22
|
-
from
|
|
23
|
-
from
|
|
24
|
-
from
|
|
25
|
-
from
|
|
26
|
-
from
|
|
15
|
+
from sqlguardllm._compiled import Compiled, RowFilter
|
|
16
|
+
from sqlguardllm._names import TableName, find, norm, parse_column_entry, parse_table_entry
|
|
17
|
+
from sqlguardllm.data.denied_functions import default_denylist
|
|
18
|
+
from sqlguardllm.messages import LANGUAGES, violation
|
|
19
|
+
from sqlguardllm.policy import Policy
|
|
20
|
+
from sqlguardllm.result import CheckResult, GuardViolation, PolicyError, Violation, ViolationCode
|
|
21
|
+
from sqlguardllm.rules.columns import check_columns
|
|
22
|
+
from sqlguardllm.rules.complexity import check_complexity
|
|
23
|
+
from sqlguardllm.rules.functions import check_functions
|
|
24
|
+
from sqlguardllm.rules.limit import apply_limit
|
|
25
|
+
from sqlguardllm.rules.required_filters import check_required_filters
|
|
26
|
+
from sqlguardllm.rules.row_filters import apply_filters, compile_filter
|
|
27
|
+
from sqlguardllm.rules.sources import collect_sources
|
|
28
|
+
from sqlguardllm.rules.statement import check_statements
|
|
27
29
|
|
|
28
30
|
R = TypeVar("R")
|
|
29
31
|
|
|
@@ -41,6 +43,11 @@ def _compile(policy: Policy, language: str) -> Compiled:
|
|
|
41
43
|
dialect = Dialect.get_or_raise(dialect_name)
|
|
42
44
|
except (ValueError, SqlglotError) as exc:
|
|
43
45
|
raise PolicyError(f"unknown dialect {policy.dialect!r}") from exc
|
|
46
|
+
output_name = (policy.output_dialect or dialect_name).lower()
|
|
47
|
+
try:
|
|
48
|
+
Dialect.get_or_raise(output_name)
|
|
49
|
+
except (ValueError, SqlglotError) as exc:
|
|
50
|
+
raise PolicyError(f"unknown output_dialect {policy.output_dialect!r}") from exc
|
|
44
51
|
|
|
45
52
|
tables = (
|
|
46
53
|
tuple(parse_table_entry(t, dialect, dialect_name) for t in sorted(policy.tables))
|
|
@@ -61,6 +68,13 @@ def _compile(policy: Policy, language: str) -> Compiled:
|
|
|
61
68
|
raise PolicyError(f"row filter for {key!r}, which is not in the allowed tables")
|
|
62
69
|
filters[table] = compile_filter(table, template, dialect_name)
|
|
63
70
|
|
|
71
|
+
required: dict[TableName, frozenset[str]] = {}
|
|
72
|
+
for key, columns in sorted(policy.required_filters.items()):
|
|
73
|
+
table = parse_table_entry(key, dialect, dialect_name)
|
|
74
|
+
if tables is not None and find(tables, table, default_schema) is None:
|
|
75
|
+
raise PolicyError(f"required filter for {key!r}, which is not in the allowed tables")
|
|
76
|
+
required[table] = frozenset(norm(column, dialect) for column in columns)
|
|
77
|
+
|
|
64
78
|
base = (
|
|
65
79
|
policy.denied_functions
|
|
66
80
|
if policy.denied_functions is not None
|
|
@@ -83,6 +97,11 @@ def _compile(policy: Policy, language: str) -> Compiled:
|
|
|
83
97
|
allowed=allowed,
|
|
84
98
|
max_rows=policy.max_rows,
|
|
85
99
|
default_schema=default_schema,
|
|
100
|
+
output_dialect_name=output_name,
|
|
101
|
+
max_joins=policy.max_joins,
|
|
102
|
+
max_subquery_depth=policy.max_subquery_depth,
|
|
103
|
+
forbid_cartesian=policy.forbid_cartesian,
|
|
104
|
+
required=required,
|
|
86
105
|
)
|
|
87
106
|
|
|
88
107
|
|
|
@@ -137,6 +156,8 @@ class Guard:
|
|
|
137
156
|
refs, problems = collect_sources(root, scopes, compiled)
|
|
138
157
|
problems += check_columns(scopes, compiled)
|
|
139
158
|
problems += check_functions(root, compiled)
|
|
159
|
+
problems += check_complexity(root, scopes, compiled)
|
|
160
|
+
problems += check_required_filters(refs, compiled)
|
|
140
161
|
if problems:
|
|
141
162
|
return self._rejected(problems)
|
|
142
163
|
|
|
@@ -147,7 +168,7 @@ class Guard:
|
|
|
147
168
|
root = apply_limit(root, compiled.max_rows)
|
|
148
169
|
return CheckResult(
|
|
149
170
|
ok=True,
|
|
150
|
-
sql=root.sql(dialect=compiled.
|
|
171
|
+
sql=root.sql(dialect=compiled.output_dialect_name, pretty=self._pretty),
|
|
151
172
|
tables=frozenset(str(ref.name) for ref in refs),
|
|
152
173
|
applied_filters=tuple(applied),
|
|
153
174
|
)
|
|
@@ -6,7 +6,7 @@ already appear in the query or the policy.
|
|
|
6
6
|
|
|
7
7
|
from __future__ import annotations
|
|
8
8
|
|
|
9
|
-
from
|
|
9
|
+
from sqlguardllm.result import Violation, ViolationCode
|
|
10
10
|
|
|
11
11
|
LANGUAGES = ("en", "es")
|
|
12
12
|
|
|
@@ -55,6 +55,14 @@ _TEMPLATES: dict[ViolationCode, dict[str, str]] = {
|
|
|
55
55
|
"en": "The context value {detail} can't be used safely in a row filter",
|
|
56
56
|
"es": "El valor de contexto {detail} no se puede usar con seguridad en un filtro por fila",
|
|
57
57
|
},
|
|
58
|
+
ViolationCode.TOO_COMPLEX: {
|
|
59
|
+
"en": "The query is too complex for the policy: {detail}",
|
|
60
|
+
"es": "La consulta es demasiado compleja para la política: {detail}",
|
|
61
|
+
},
|
|
62
|
+
ViolationCode.MISSING_REQUIRED_FILTER: {
|
|
63
|
+
"en": "Reading {detail} requires a filter on one of those columns",
|
|
64
|
+
"es": "Leer {detail} exige un filtro sobre una de esas columnas",
|
|
65
|
+
},
|
|
58
66
|
}
|
|
59
67
|
|
|
60
68
|
|
|
@@ -9,7 +9,7 @@ from pathlib import Path
|
|
|
9
9
|
from types import MappingProxyType
|
|
10
10
|
from typing import Any, Literal
|
|
11
11
|
|
|
12
|
-
from
|
|
12
|
+
from sqlguardllm.result import PolicyError
|
|
13
13
|
|
|
14
14
|
FunctionPolicy = Literal["denylist", "allowlist"]
|
|
15
15
|
|
|
@@ -41,6 +41,15 @@ class Policy:
|
|
|
41
41
|
extra_denied_functions: Added to the denylist.
|
|
42
42
|
function_policy: ``"denylist"`` (default) or ``"allowlist"``.
|
|
43
43
|
allowed_functions: Functions allowed in ``"allowlist"`` mode.
|
|
44
|
+
max_joins: Maximum joins in the whole query, across every scope. ``None`` = no limit.
|
|
45
|
+
max_subquery_depth: Maximum nesting of subqueries, derived tables and CTEs. ``0`` allows
|
|
46
|
+
none. ``None`` = no limit.
|
|
47
|
+
forbid_cartesian: Reject joins with no ``ON``/``USING`` whose tables aren't linked by an
|
|
48
|
+
equality in ``WHERE``, and every explicit ``CROSS JOIN``.
|
|
49
|
+
required_filters: Table → columns. Every read of the table must be filtered on at least
|
|
50
|
+
one of them in its own ``WHERE`` or ``JOIN … ON``, such as a date range on a large
|
|
51
|
+
fact table.
|
|
52
|
+
output_dialect: Generate the rewritten SQL in this dialect instead of ``dialect``.
|
|
44
53
|
"""
|
|
45
54
|
|
|
46
55
|
dialect: str
|
|
@@ -53,6 +62,11 @@ class Policy:
|
|
|
53
62
|
extra_denied_functions: Collection[str] = frozenset()
|
|
54
63
|
function_policy: FunctionPolicy = "denylist"
|
|
55
64
|
allowed_functions: Collection[str] | None = None
|
|
65
|
+
max_joins: int | None = None
|
|
66
|
+
max_subquery_depth: int | None = None
|
|
67
|
+
forbid_cartesian: bool = False
|
|
68
|
+
required_filters: Mapping[str, Collection[str]] = field(default_factory=dict)
|
|
69
|
+
output_dialect: str | None = None
|
|
56
70
|
|
|
57
71
|
def __post_init__(self) -> None:
|
|
58
72
|
if not isinstance(self.dialect, str) or not self.dialect.strip():
|
|
@@ -85,6 +99,29 @@ class Policy:
|
|
|
85
99
|
raise PolicyError('function_policy must be "denylist" or "allowlist"')
|
|
86
100
|
if self.function_policy == "allowlist" and self.allowed_functions is None:
|
|
87
101
|
raise PolicyError('function_policy="allowlist" requires allowed_functions')
|
|
102
|
+
for name in ("max_joins", "max_subquery_depth"):
|
|
103
|
+
value = getattr(self, name)
|
|
104
|
+
if value is not None and (
|
|
105
|
+
isinstance(value, bool) or not isinstance(value, int) or value < 0
|
|
106
|
+
):
|
|
107
|
+
raise PolicyError(f"{name} must be a non-negative integer or None")
|
|
108
|
+
if not isinstance(self.forbid_cartesian, bool):
|
|
109
|
+
raise PolicyError("forbid_cartesian must be true or false")
|
|
110
|
+
if not isinstance(self.required_filters, Mapping):
|
|
111
|
+
raise PolicyError("required_filters must map table names to lists of columns")
|
|
112
|
+
required: dict[str, frozenset[str]] = {}
|
|
113
|
+
for table, columns in self.required_filters.items():
|
|
114
|
+
if not isinstance(table, str) or not table.strip():
|
|
115
|
+
raise PolicyError("required_filters keys must be non-empty table names")
|
|
116
|
+
frozen = _frozen(columns, f"required_filters[{table!r}]")
|
|
117
|
+
if not frozen:
|
|
118
|
+
raise PolicyError(f"required_filters[{table!r}] needs at least one column")
|
|
119
|
+
required[table] = frozen
|
|
120
|
+
object.__setattr__(self, "required_filters", MappingProxyType(required))
|
|
121
|
+
if self.output_dialect is not None and (
|
|
122
|
+
not isinstance(self.output_dialect, str) or not self.output_dialect.strip()
|
|
123
|
+
):
|
|
124
|
+
raise PolicyError("output_dialect must be a non-empty string or None")
|
|
88
125
|
|
|
89
126
|
@classmethod
|
|
90
127
|
def from_dict(cls, data: Mapping[str, Any]) -> Policy:
|
|
@@ -101,7 +138,7 @@ class Policy:
|
|
|
101
138
|
def from_file(cls, path: str | Path) -> Policy:
|
|
102
139
|
"""Load a policy from a ``.json``, ``.yaml`` or ``.yml`` file.
|
|
103
140
|
|
|
104
|
-
YAML needs the optional extra: ``pip install "
|
|
141
|
+
YAML needs the optional extra: ``pip install "sqlguardllm[yaml]"``.
|
|
105
142
|
"""
|
|
106
143
|
file = Path(path)
|
|
107
144
|
text = file.read_text(encoding="utf-8")
|
|
@@ -109,7 +146,7 @@ class Policy:
|
|
|
109
146
|
try:
|
|
110
147
|
import yaml # noqa: PLC0415
|
|
111
148
|
except ImportError as exc: # pragma: no cover - depends on the environment
|
|
112
|
-
raise PolicyError('YAML policies need: pip install "
|
|
149
|
+
raise PolicyError('YAML policies need: pip install "sqlguardllm[yaml]"') from exc
|
|
113
150
|
data = yaml.safe_load(text)
|
|
114
151
|
else:
|
|
115
152
|
data = json.loads(text)
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
"""Results, violation codes and errors of
|
|
1
|
+
"""Results, violation codes and errors of sqlguardllm."""
|
|
2
2
|
|
|
3
3
|
from __future__ import annotations
|
|
4
4
|
|
|
@@ -20,6 +20,8 @@ class ViolationCode(str, Enum):
|
|
|
20
20
|
DENIED_FUNCTION = "denied_function"
|
|
21
21
|
MISSING_CONTEXT = "missing_context"
|
|
22
22
|
INVALID_CONTEXT = "invalid_context"
|
|
23
|
+
TOO_COMPLEX = "too_complex"
|
|
24
|
+
MISSING_REQUIRED_FILTER = "missing_required_filter"
|
|
23
25
|
|
|
24
26
|
|
|
25
27
|
@dataclass(frozen=True)
|
|
@@ -39,7 +41,7 @@ class Violation:
|
|
|
39
41
|
|
|
40
42
|
@dataclass(frozen=True)
|
|
41
43
|
class CheckResult:
|
|
42
|
-
"""Outcome of :meth:`
|
|
44
|
+
"""Outcome of :meth:`sqlguardllm.Guard.check`.
|
|
43
45
|
|
|
44
46
|
Attributes:
|
|
45
47
|
ok: True when the query may run.
|
|
@@ -67,11 +69,11 @@ class CheckResult:
|
|
|
67
69
|
|
|
68
70
|
|
|
69
71
|
class PolicyError(ValueError):
|
|
70
|
-
"""The policy itself is invalid. Raised when a :class:`~
|
|
72
|
+
"""The policy itself is invalid. Raised when a :class:`~sqlguardllm.Guard` is created."""
|
|
71
73
|
|
|
72
74
|
|
|
73
75
|
class GuardViolation(Exception):
|
|
74
|
-
"""Raised by :meth:`
|
|
76
|
+
"""Raised by :meth:`sqlguardllm.Guard.enforce` when a query is rejected."""
|
|
75
77
|
|
|
76
78
|
def __init__(self, violations: tuple[Violation, ...]) -> None:
|
|
77
79
|
self.violations = violations
|
|
@@ -5,10 +5,10 @@ from __future__ import annotations
|
|
|
5
5
|
from sqlglot import exp
|
|
6
6
|
from sqlglot.optimizer.scope import Scope
|
|
7
7
|
|
|
8
|
-
from
|
|
9
|
-
from
|
|
10
|
-
from
|
|
11
|
-
from
|
|
8
|
+
from sqlguardllm._compiled import Compiled
|
|
9
|
+
from sqlguardllm._names import TableName, find, norm, table_name
|
|
10
|
+
from sqlguardllm.messages import violation
|
|
11
|
+
from sqlguardllm.result import Violation, ViolationCode
|
|
12
12
|
|
|
13
13
|
|
|
14
14
|
def _visible_sources(scope: Scope) -> dict[str, exp.Expression | Scope]:
|