sqlguardllm 0.1.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.
Files changed (35) hide show
  1. sqlguardllm-0.1.0a1/.gitignore +17 -0
  2. sqlguardllm-0.1.0a1/CHANGELOG.md +31 -0
  3. sqlguardllm-0.1.0a1/LICENSE +202 -0
  4. sqlguardllm-0.1.0a1/PKG-INFO +84 -0
  5. sqlguardllm-0.1.0a1/README.md +212 -0
  6. sqlguardllm-0.1.0a1/docs/pypi.md +51 -0
  7. sqlguardllm-0.1.0a1/pyproject.toml +75 -0
  8. sqlguardllm-0.1.0a1/src/sqlguard/__init__.py +35 -0
  9. sqlguardllm-0.1.0a1/src/sqlguard/_compiled.py +37 -0
  10. sqlguardllm-0.1.0a1/src/sqlguard/_names.py +104 -0
  11. sqlguardllm-0.1.0a1/src/sqlguard/data/__init__.py +1 -0
  12. sqlguardllm-0.1.0a1/src/sqlguard/data/denied_functions.py +127 -0
  13. sqlguardllm-0.1.0a1/src/sqlguard/guard.py +182 -0
  14. sqlguardllm-0.1.0a1/src/sqlguard/messages.py +64 -0
  15. sqlguardllm-0.1.0a1/src/sqlguard/policy.py +118 -0
  16. sqlguardllm-0.1.0a1/src/sqlguard/py.typed +0 -0
  17. sqlguardllm-0.1.0a1/src/sqlguard/result.py +78 -0
  18. sqlguardllm-0.1.0a1/src/sqlguard/rules/__init__.py +1 -0
  19. sqlguardllm-0.1.0a1/src/sqlguard/rules/columns.py +90 -0
  20. sqlguardllm-0.1.0a1/src/sqlguard/rules/functions.py +55 -0
  21. sqlguardllm-0.1.0a1/src/sqlguard/rules/limit.py +40 -0
  22. sqlguardllm-0.1.0a1/src/sqlguard/rules/row_filters.py +162 -0
  23. sqlguardllm-0.1.0a1/src/sqlguard/rules/sources.py +67 -0
  24. sqlguardllm-0.1.0a1/src/sqlguard/rules/statement.py +97 -0
  25. sqlguardllm-0.1.0a1/tests/conftest.py +31 -0
  26. sqlguardllm-0.1.0a1/tests/corpus/allowed.yaml +58 -0
  27. sqlguardllm-0.1.0a1/tests/corpus/context.yaml +26 -0
  28. sqlguardllm-0.1.0a1/tests/corpus/functions.yaml +85 -0
  29. sqlguardllm-0.1.0a1/tests/corpus/tables_columns.yaml +68 -0
  30. sqlguardllm-0.1.0a1/tests/corpus/writes.yaml +104 -0
  31. sqlguardllm-0.1.0a1/tests/test_api.py +61 -0
  32. sqlguardllm-0.1.0a1/tests/test_corpus.py +84 -0
  33. sqlguardllm-0.1.0a1/tests/test_policy.py +76 -0
  34. sqlguardllm-0.1.0a1/tests/test_row_filters.py +131 -0
  35. sqlguardllm-0.1.0a1/tests/test_rules.py +108 -0
@@ -0,0 +1,17 @@
1
+ __pycache__/
2
+ *.py[cod]
3
+ .venv/
4
+ .pytest_cache/
5
+ .mypy_cache/
6
+ .ruff_cache/
7
+ .coverage
8
+ htmlcov/
9
+ dist/
10
+ build/
11
+ *.egg-info/
12
+ site/
13
+ .env
14
+ .env.*
15
+ .DS_Store
16
+ .idea/
17
+ .vscode/
@@ -0,0 +1,31 @@
1
+ # Changelog
2
+
3
+ All notable changes to sqlguard 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
+
5
+ ## [Unreleased]
6
+
7
+ ## [0.1.0a1] - 2026-11-25
8
+
9
+ First alpha. Install with `pip install sqlguardllm`; import with `import sqlguard`.
10
+
11
+ ### Added
12
+
13
+ - Public API: `Guard`, `Policy`, `CheckResult`, `Violation`, `GuardViolation`, `PolicyError` and `ViolationCode` with 11 stable codes. `Guard.check()`, `Guard.enforce()` and `Guard.wrap()`.
14
+ - Rule 1–3: fail-closed parsing, a single query root, and a read-only walk of the whole tree (writes, DDL, `SELECT … INTO`, `COPY`, `ATTACH`, `PRAGMA`, `EXEC`, `SET`, `CALL`, row locks), including writes hidden in CTEs.
15
+ - Rule 4: table allowlist with CTE scoping, per-dialect identifier normalization, `default_schema`, rejection of table functions, and a fail-closed check that every table reference was classified.
16
+ - Rule 5: hidden columns in every clause, through `*` and `t.*`, whole-row references, `USING`, `NATURAL JOIN` and correlated subqueries.
17
+ - Rule 6: built-in denied functions for PostgreSQL, MySQL, SQL Server, Oracle, SQLite and DuckDB (file readers, sleeps, shells, network calls, functions that run SQL from a string such as `query_to_xml`), qualified names like `SYS.DBMS_PIPE.*`, and an allowlist mode.
18
+ - Rule 7: row filters injected as derived tables in every occurrence of a table, with context values bound as escaped literals; missing or unsupported values fail closed.
19
+ - Rule 8: row limit in each dialect's syntax (`LIMIT`, `TOP`, `FETCH FIRST`); set operations are limited as a whole.
20
+ - Messages in English and Spanish.
21
+ - `Policy.from_dict()` and `Policy.from_file()` for JSON, and YAML with the `sqlguardllm[yaml]` extra.
22
+ - An adversarial corpus of 64 cases in `tests/corpus/`, and row-filter tests that execute the rewritten SQL on SQLite.
23
+
24
+ ### Known limitations
25
+
26
+ - Without table metadata, an unqualified column that shares its name with a hidden column is rejected (conservative). Exact checking with `Policy(schema=...)` is planned.
27
+ - Table functions are rejected, even harmless ones like `generate_series`.
28
+ - No command-line tool yet (planned for v0.2).
29
+
30
+ [Unreleased]: https://github.com/jmmana/sqlguard/compare/v0.1.0a1...HEAD
31
+ [0.1.0a1]: https://github.com/jmmana/sqlguard/releases/tag/v0.1.0a1
@@ -0,0 +1,202 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright 2026 Juan Castillo
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
202
+
@@ -0,0 +1,84 @@
1
+ Metadata-Version: 2.5
2
+ Name: sqlguardllm
3
+ Version: 0.1.0a1
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/sqlguard
6
+ Project-URL: Documentation, https://github.com/jmmana/sqlguard/tree/main/docs
7
+ Project-URL: Issues, https://github.com/jmmana/sqlguard/issues
8
+ Project-URL: Changelog, https://github.com/jmmana/sqlguard/blob/main/CHANGELOG.md
9
+ Project-URL: Source, https://github.com/jmmana/sqlguard
10
+ Author: Juan Castillo
11
+ License-Expression: Apache-2.0
12
+ License-File: LICENSE
13
+ Keywords: ai-safety,guardrails,llm,nl2sql,prompt-injection,row-level-security,security,sql,sqlglot,text-to-sql
14
+ Classifier: Development Status :: 3 - Alpha
15
+ Classifier: Intended Audience :: Developers
16
+ Classifier: Operating System :: OS Independent
17
+ Classifier: Programming Language :: Python :: 3
18
+ Classifier: Programming Language :: Python :: 3 :: Only
19
+ Classifier: Programming Language :: Python :: 3.10
20
+ Classifier: Programming Language :: Python :: 3.11
21
+ Classifier: Programming Language :: Python :: 3.12
22
+ Classifier: Programming Language :: Python :: 3.13
23
+ Classifier: Programming Language :: SQL
24
+ Classifier: Topic :: Database
25
+ Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
26
+ Classifier: Topic :: Security
27
+ Classifier: Typing :: Typed
28
+ Requires-Python: >=3.10
29
+ Requires-Dist: sqlglot<31,>=30.0
30
+ Provides-Extra: yaml
31
+ Requires-Dist: pyyaml>=6.0; extra == 'yaml'
32
+ Description-Content-Type: text/markdown
33
+
34
+ <p align="center">
35
+ <img alt="sqlguard" src="https://raw.githubusercontent.com/jmmana/sqlguard/main/docs/assets/logo-light.svg" width="340">
36
+ </p>
37
+
38
+ # sqlguard — the SQL firewall for LLM apps
39
+
40
+ Your model writes SQL. **sqlguard** 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
+
42
+ ```bash
43
+ pip install sqlguardllm
44
+ ```
45
+
46
+ ```python
47
+ from sqlguard import Guard, Policy
48
+
49
+ guard = Guard(
50
+ Policy(
51
+ dialect="postgres",
52
+ tables={"invoices", "branches", "customers"},
53
+ hidden_columns={"customers.email"},
54
+ row_filters={"invoices": "branch_id IN ({user.branches})"},
55
+ max_rows=1000,
56
+ )
57
+ )
58
+
59
+ result = guard.check(sql_from_llm, context={"user": {"branches": [1, 2]}})
60
+ if result.ok:
61
+ rows = db.execute(result.sql) # read-only, row-filtered, limited
62
+ else:
63
+ print(result.messages) # ["The query tries to change data or structure (DELETE)"]
64
+ ```
65
+
66
+ ## What it guarantees
67
+
68
+ - **One statement** that is a query. Nothing stacked after a `;`.
69
+ - **Read-only across the whole syntax tree**: no `INSERT`, `UPDATE`, `DELETE`, `MERGE`, `SELECT … INTO`, DDL, `COPY`, `ATTACH`, `PRAGMA`, `EXEC` or row locks, at any depth. A `DELETE` hidden in a CTE is caught.
70
+ - **Allowlisted tables and hidden columns**, CTE-aware; `SELECT *`, whole-row references and predicates on hidden columns are rejected.
71
+ - **Denied functions** per dialect: file readers, sleeps, shells, network calls and functions that run SQL from a string (`pg_read_file`, `query_to_xml`, `LOAD_FILE`, `OPENROWSET`, `DBMS_PIPE.*`, DuckDB `read_csv`…).
72
+ - **Row-level filters**: every occurrence of a table becomes a filtered derived table, with the user's values bound as escaped literals.
73
+ - **Row limit** in the dialect's own syntax (`LIMIT`, `TOP`, `FETCH FIRST`).
74
+ - **Fails closed**: what can't be understood is rejected with a reason.
75
+
76
+ Pure Python, one dependency (sqlglot), no network, no LLM. Status: **alpha** — the API may still change before 1.0; violation codes are stable.
77
+
78
+ ## Learn more
79
+
80
+ - Source, design and attack gallery: <https://github.com/jmmana/sqlguard>
81
+ - Threat model: <https://github.com/jmmana/sqlguard/blob/main/docs/THREAT_MODEL.md>
82
+ - Report a bypass privately: <https://github.com/jmmana/sqlguard/security/advisories/new>
83
+
84
+ The distribution is named `sqlguardllm` on PyPI; the import name is `sqlguard`. Licensed under Apache-2.0.
@@ -0,0 +1,212 @@
1
+ <div align="center">
2
+
3
+ [![English](https://img.shields.io/badge/English-10B981?style=for-the-badge)](README.md)
4
+ [![Leer en español](https://img.shields.io/badge/Leer_en_espa%C3%B1ol-1F2937?style=for-the-badge)](README.es.md)
5
+
6
+ <picture>
7
+ <source media="(prefers-color-scheme: dark)" srcset="docs/assets/logo-dark.svg">
8
+ <img alt="sqlguard" src="docs/assets/logo-light.svg" width="360">
9
+ </picture>
10
+
11
+ ### The SQL firewall for LLM apps.
12
+
13
+ Your model writes SQL. **sqlguard** 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
+
15
+ [![PyPI](https://img.shields.io/pypi/v/sqlguardllm?include_prereleases&label=pypi&color=10B981)](https://pypi.org/project/sqlguardllm/)
16
+ [![CI](https://github.com/jmmana/sqlguard/actions/workflows/ci.yml/badge.svg)](https://github.com/jmmana/sqlguard/actions/workflows/ci.yml)
17
+ [![License](https://img.shields.io/badge/license-Apache--2.0-3B82F6)](LICENSE)
18
+ [![Python](https://img.shields.io/badge/python-3.10%2B-3776AB?logo=python&logoColor=white)](docs/DESIGN.md)
19
+ [![Built on sqlglot](https://img.shields.io/badge/built%20on-sqlglot-10B981)](https://github.com/tobymao/sqlglot)
20
+ [![PRs welcome](https://img.shields.io/badge/PRs-welcome-22C55E)](CONTRIBUTING.md)
21
+
22
+ <img src="docs/assets/hero.svg" alt="sqlguard 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
+
24
+ </div>
25
+
26
+ > [!NOTE]
27
+ > **Status: alpha.** `0.1.0a1` is on PyPI as [`sqlguardllm`](https://pypi.org/project/sqlguardllm/) (the import name is `sqlguard`), with the rules of [docs/DESIGN.md](docs/DESIGN.md) and a 64-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/sqlguard/discussions).
28
+
29
+ ---
30
+
31
+ ## Why
32
+
33
+ LLM apps that talk to databases (text-to-SQL, data agents, MCP database tools) all share the same risk: **the model writes SQL, and someone will eventually make it write the wrong SQL.** Through a prompt injection, a malicious row in your own data, or a plain hallucination.
34
+
35
+ The usual defense is a keyword blocklist. It fails in **both** directions:
36
+
37
+ | SQL | Keyword filter (`"DELETE" in sql`) | What it actually is |
38
+ |---|---|---|
39
+ | `SELECT 'x; DROP TABLE invoices' AS note` | ❌ Blocks it | A harmless read with a string literal |
40
+ | `WITH d AS (DELETE FROM invoices RETURNING *) SELECT * FROM d` | ✅ Blocks it, by luck | A write hidden inside a CTE. Spell it with a comment or odd casing and the filter misses it |
41
+ | `SELECT * INTO backup FROM invoices` | ⚠️ Lets it through: it starts with `SELECT` | Creates a new table (SQL Server) |
42
+ | `SELECT name, email FROM customers` | ⚠️ Lets it through | Reads personal data the model should never see |
43
+
44
+ sqlguard 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
+
46
+ ## What it guarantees
47
+
48
+ | | Rule |
49
+ |---|---|
50
+ | 1️⃣ | **One statement** that is a query (`SELECT`, `UNION`, `WITH … SELECT`). Nothing stacked after a `;` |
51
+ | 2️⃣ | **Read-only across the whole tree**: no `INSERT`, `UPDATE`, `DELETE`, `MERGE`, `SELECT … INTO`, DDL, `COPY`, `ATTACH`, `PRAGMA`, `EXEC`, row locks… at any depth |
52
+ | 3️⃣ | **Allowlisted tables and hidden columns**: CTE-aware; `SELECT *` on a table with hidden columns is rejected |
53
+ | 4️⃣ | **Denied functions** per dialect: file readers, sleeps, shells, network calls (`pg_read_file`, `pg_sleep`, `LOAD_FILE`, `OPENROWSET`, `DBMS_PIPE.*`…) |
54
+ | 5️⃣ | **Row-level filters**: every occurrence of a table becomes a filtered derived table, with the user's values bound as escaped literals |
55
+ | 6️⃣ | **Row limit** applied or lowered, in the dialect's own syntax (`LIMIT`, `TOP`, `FETCH FIRST`) |
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
+
58
+ ## Quick look
59
+
60
+ ```bash
61
+ pip install sqlguardllm # Python 3.10+, one dependency: sqlglot
62
+ ```
63
+
64
+ ```python
65
+ from sqlguard import Guard, Policy
66
+
67
+ guard = Guard(Policy(
68
+ dialect="postgres",
69
+ tables={"invoices", "branches", "customers"},
70
+ hidden_columns={"customers.email", "customers.tax_id"},
71
+ row_filters={"invoices": "branch_id IN ({user.branches})"},
72
+ max_rows=1000,
73
+ ))
74
+
75
+ result = guard.check(sql_from_llm, context={"user": {"branches": [1, 2]}})
76
+
77
+ if result.ok:
78
+ rows = db.execute(result.sql) # read-only, row-filtered, limited
79
+ else:
80
+ for v in result.violations:
81
+ print(v.code, v.message) # write_operation: DELETE inside a CTE…
82
+ ```
83
+
84
+ It doesn't care which model, agent framework or ORM produced the SQL: **it only needs the SQL string.**
85
+
86
+ ## How it works
87
+
88
+ ```mermaid
89
+ flowchart LR
90
+ LLM["LLM / agent<br/>writes SQL"] --> P{"Parse with<br/>sqlglot"}
91
+ P -- "can't parse" --> X["❌ Rejected<br/>with a reason"]
92
+ P --> S{"One read-only<br/>query?"}
93
+ S -- no --> X
94
+ S --> A{"Allowed tables,<br/>columns, functions?"}
95
+ A -- no --> X
96
+ A --> R["Inject row filters<br/>as derived tables"]
97
+ R --> L["Apply row limit"]
98
+ L --> G["Generate SQL<br/>in your dialect"]
99
+ G --> DB[("Your database<br/>read-only user")]
100
+ ```
101
+
102
+ What runs is the SQL regenerated from the validated tree, never the original string.
103
+
104
+ ## Row-level security, rewritten
105
+
106
+ Each occurrence of a filtered table is replaced by a derived table that keeps its alias, so the filter holds inside joins, subqueries and CTEs. Real sqlglot output for a user who can only see branches 1 and 2:
107
+
108
+ <table>
109
+ <tr><th>The LLM wrote</th><th>What runs</th></tr>
110
+ <tr>
111
+ <td>
112
+
113
+ ```sql
114
+ SELECT b.name, SUM(i.total)
115
+ FROM invoices i
116
+ JOIN branches b ON b.id = i.branch_id
117
+ GROUP BY b.name
118
+ ```
119
+
120
+ </td>
121
+ <td>
122
+
123
+ ```sql
124
+ SELECT b.name, SUM(i.total)
125
+ FROM (
126
+ SELECT * FROM invoices
127
+ WHERE branch_id IN (1, 2)
128
+ ) AS i
129
+ JOIN branches AS b ON b.id = i.branch_id
130
+ GROUP BY b.name
131
+ LIMIT 1000
132
+ ```
133
+
134
+ </td>
135
+ </tr>
136
+ </table>
137
+
138
+ Same idea on SQL Server, where the limit becomes `TOP 500`, or Oracle, where it becomes `FETCH FIRST 100 ROWS ONLY`. More examples in [docs/DESIGN.md](docs/DESIGN.md#7-row-filters).
139
+
140
+ ## Attack gallery
141
+
142
+ What sqlglot 30.35 actually sees for each attempt, and what sqlguard does about it. Every row is a test case. The full list is in [docs/ATTACK_GALLERY.md](docs/ATTACK_GALLERY.md).
143
+
144
+ | Dialect | Attempt | sqlglot sees | sqlguard |
145
+ |---|---|---|---|
146
+ | postgres | `WITH d AS (DELETE FROM invoices RETURNING *) SELECT * FROM d` | `Select` root with a `Delete` inside | ❌ `write_operation` |
147
+ | tsql | `SELECT 1; DROP TABLE invoices` | 2 statements | ❌ `multiple_statements` |
148
+ | tsql | `SELECT * INTO backup FROM invoices` | `Select` with an `Into` node | ❌ `write_operation` |
149
+ | postgres | `SELECT * FROM invoices FOR UPDATE` | `Select` with a `Lock` | ❌ `row_lock` |
150
+ | mysql | `SELECT * FROM invoices INTO OUTFILE '/tmp/x'` | parse error | ❌ `parse_error` (fails closed) |
151
+ | sqlite | `ATTACH DATABASE '/tmp/x.db' AS x` | `Attach` | ❌ `not_a_query` |
152
+ | postgres | `SELECT pg_read_file('/etc/passwd')` | function `pg_read_file` | ❌ `denied_function` |
153
+ | oracle | `SELECT DBMS_PIPE.RECEIVE_MESSAGE('a', 10) FROM dual` | qualified function call | ❌ `denied_function` |
154
+ | postgres | `SELECT 'x; DROP TABLE invoices' AS note` | one `Select`, a string literal | ✅ allowed |
155
+ | postgres | `SELECT 1 /* ; DROP TABLE invoices */` | one `Select`, a comment | ✅ allowed |
156
+
157
+ Found a way through? That's a vulnerability: please [report it privately](SECURITY.md).
158
+
159
+ ## Where it fits
160
+
161
+ sqlguard is **one layer**, not the only one. Keep the others:
162
+
163
+ 1. **A read-only database user** with access to only the tables the app needs. Non-negotiable.
164
+ 2. **sqlguard** between the model and the database: shape, allowlists, row filters, limits.
165
+ 3. **Statement timeouts** in the database, against expensive queries.
166
+ 4. **Audit logs** of every SQL that ran and for whom.
167
+
168
+ What it does not do, and why, is in the [threat model](docs/THREAT_MODEL.md).
169
+
170
+ ## Works with your stack
171
+
172
+ sqlguard 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
+
174
+ A command-line tool is planned too, handy in CI and for trying policies:
175
+
176
+ ```bash
177
+ sqlguard check --policy policy.yaml --context '{"user": {"branches": [1, 2]}}' \
178
+ "SELECT * FROM invoices"
179
+ ```
180
+
181
+ ## Playground: try to break it
182
+
183
+ A static playground (planned for v0.3) will run sqlguard **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
+
185
+ ## Roadmap
186
+
187
+ | Milestone | Scope |
188
+ |---|---|
189
+ | [**v0.1 · Core guard**](https://github.com/jmmana/sqlguard/milestone/1) | Statement and read-only checks, allowlists, hidden columns, denied functions, row limit, adversarial corpus |
190
+ | [**v0.2 · Row-level security & CLI**](https://github.com/jmmana/sqlguard/milestone/2) | Row filters as derived tables, policy files, CLI, dialect test matrix, docs site, PyPI release |
191
+ | [**v0.3 · Ecosystem & playground**](https://github.com/jmmana/sqlguard/milestone/3) | Integration recipes, browser playground, performance budget |
192
+
193
+ Details in [docs/ROADMAP.md](docs/ROADMAP.md).
194
+
195
+ ## Contributing
196
+
197
+ Contributions are very welcome, and some of the most valuable ones need no deep knowledge of the codebase:
198
+
199
+ - **Add attack cases** to the adversarial corpus, especially for dialects you know well.
200
+ - **Extend the denied-function lists** for your database.
201
+ - **Translate violation messages.**
202
+ - **Challenge the design** in [Discussions](https://github.com/jmmana/sqlguard/discussions) before v0.1 freezes the API.
203
+
204
+ Start with [CONTRIBUTING.md](CONTRIBUTING.md) and the [good first issues](https://github.com/jmmana/sqlguard/labels/good%20first%20issue). This project follows a [Code of Conduct](CODE_OF_CONDUCT.md).
205
+
206
+ ## Security
207
+
208
+ A bypass of sqlguard is a security vulnerability. **Don't open a public issue:** report it privately as described in [SECURITY.md](SECURITY.md).
209
+
210
+ ## License
211
+
212
+ [Apache-2.0](LICENSE) © 2026 Juan Castillo. sqlguard was born inside [ChatIApp](https://github.com/jmmana/ChatIApp), an open-source chat that turns business questions into safe SQL.
@@ -0,0 +1,51 @@
1
+ <p align="center">
2
+ <img alt="sqlguard" src="https://raw.githubusercontent.com/jmmana/sqlguard/main/docs/assets/logo-light.svg" width="340">
3
+ </p>
4
+
5
+ # sqlguard — the SQL firewall for LLM apps
6
+
7
+ Your model writes SQL. **sqlguard** 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
+
9
+ ```bash
10
+ pip install sqlguardllm
11
+ ```
12
+
13
+ ```python
14
+ from sqlguard import Guard, Policy
15
+
16
+ guard = Guard(
17
+ Policy(
18
+ dialect="postgres",
19
+ tables={"invoices", "branches", "customers"},
20
+ hidden_columns={"customers.email"},
21
+ row_filters={"invoices": "branch_id IN ({user.branches})"},
22
+ max_rows=1000,
23
+ )
24
+ )
25
+
26
+ result = guard.check(sql_from_llm, context={"user": {"branches": [1, 2]}})
27
+ if result.ok:
28
+ rows = db.execute(result.sql) # read-only, row-filtered, limited
29
+ else:
30
+ print(result.messages) # ["The query tries to change data or structure (DELETE)"]
31
+ ```
32
+
33
+ ## What it guarantees
34
+
35
+ - **One statement** that is a query. Nothing stacked after a `;`.
36
+ - **Read-only across the whole syntax tree**: no `INSERT`, `UPDATE`, `DELETE`, `MERGE`, `SELECT … INTO`, DDL, `COPY`, `ATTACH`, `PRAGMA`, `EXEC` or row locks, at any depth. A `DELETE` hidden in a CTE is caught.
37
+ - **Allowlisted tables and hidden columns**, CTE-aware; `SELECT *`, whole-row references and predicates on hidden columns are rejected.
38
+ - **Denied functions** per dialect: file readers, sleeps, shells, network calls and functions that run SQL from a string (`pg_read_file`, `query_to_xml`, `LOAD_FILE`, `OPENROWSET`, `DBMS_PIPE.*`, DuckDB `read_csv`…).
39
+ - **Row-level filters**: every occurrence of a table becomes a filtered derived table, with the user's values bound as escaped literals.
40
+ - **Row limit** in the dialect's own syntax (`LIMIT`, `TOP`, `FETCH FIRST`).
41
+ - **Fails closed**: what can't be understood is rejected with a reason.
42
+
43
+ Pure Python, one dependency (sqlglot), no network, no LLM. Status: **alpha** — the API may still change before 1.0; violation codes are stable.
44
+
45
+ ## Learn more
46
+
47
+ - Source, design and attack gallery: <https://github.com/jmmana/sqlguard>
48
+ - Threat model: <https://github.com/jmmana/sqlguard/blob/main/docs/THREAT_MODEL.md>
49
+ - Report a bypass privately: <https://github.com/jmmana/sqlguard/security/advisories/new>
50
+
51
+ The distribution is named `sqlguardllm` on PyPI; the import name is `sqlguard`. Licensed under Apache-2.0.