sqlguard-ninja 0.1.0__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 (120) hide show
  1. sqlguard_ninja-0.1.0/.gitignore +30 -0
  2. sqlguard_ninja-0.1.0/CHANGELOG.md +41 -0
  3. sqlguard_ninja-0.1.0/LICENSE +202 -0
  4. sqlguard_ninja-0.1.0/PKG-INFO +370 -0
  5. sqlguard_ninja-0.1.0/README.md +314 -0
  6. sqlguard_ninja-0.1.0/THIRD_PARTY_NOTICES.md +56 -0
  7. sqlguard_ninja-0.1.0/benchmarks/baselines/native.json +16955 -0
  8. sqlguard_ninja-0.1.0/benchmarks/datasets/v1/cases/01_destructive.yaml +169 -0
  9. sqlguard_ninja-0.1.0/benchmarks/datasets/v1/cases/02_multi_statement_and_formatting.yaml +155 -0
  10. sqlguard_ninja-0.1.0/benchmarks/datasets/v1/cases/03_table_and_column_access.yaml +205 -0
  11. sqlguard_ninja-0.1.0/benchmarks/datasets/v1/cases/04_privacy.yaml +245 -0
  12. sqlguard_ninja-0.1.0/benchmarks/datasets/v1/cases/05_tenant_isolation.yaml +167 -0
  13. sqlguard_ninja-0.1.0/benchmarks/datasets/v1/cases/06_cte_nested_unicode.yaml +168 -0
  14. sqlguard_ninja-0.1.0/benchmarks/datasets/v1/cases/07_legitimate_lookalike_cost_dialect.yaml +243 -0
  15. sqlguard_ninja-0.1.0/benchmarks/datasets/v1/generated/grant_matrix.yaml +573 -0
  16. sqlguard_ninja-0.1.0/benchmarks/datasets/v1/generated/label_matrix.yaml +403 -0
  17. sqlguard_ninja-0.1.0/benchmarks/datasets/v1/generated/tenant_matrix.yaml +684 -0
  18. sqlguard_ninja-0.1.0/benchmarks/datasets/v1/generated/transforms.yaml +927 -0
  19. sqlguard_ninja-0.1.0/benchmarks/datasets/v1/manifest.yaml +15 -0
  20. sqlguard_ninja-0.1.0/benchmarks/policies/retail_saas.yaml +259 -0
  21. sqlguard_ninja-0.1.0/benchmarks/results/v1.0.0/agent-sql-guard.json +16663 -0
  22. sqlguard_ninja-0.1.0/benchmarks/results/v1.0.0/agent-sql-guard.md +98 -0
  23. sqlguard_ninja-0.1.0/benchmarks/results/v1.0.0/krish2105-sqlguard.json +16600 -0
  24. sqlguard_ninja-0.1.0/benchmarks/results/v1.0.0/krish2105-sqlguard.md +98 -0
  25. sqlguard_ninja-0.1.0/benchmarks/results/v1.0.0/native.json +16955 -0
  26. sqlguard_ninja-0.1.0/benchmarks/results/v1.0.0/native.md +66 -0
  27. sqlguard_ninja-0.1.0/benchmarks/results/v1.0.0/sql-guardrail.json +17210 -0
  28. sqlguard_ninja-0.1.0/benchmarks/results/v1.0.0/sql-guardrail.md +91 -0
  29. sqlguard_ninja-0.1.0/docs/architecture/ARCHITECTURE_DECISIONS.md +129 -0
  30. sqlguard_ninja-0.1.0/docs/benchmarks/RESULTS_v1.md +50 -0
  31. sqlguard_ninja-0.1.0/docs/guides/AGENT_INTEGRATION.md +94 -0
  32. sqlguard_ninja-0.1.0/docs/guides/BENCHMARK_METHODOLOGY.md +118 -0
  33. sqlguard_ninja-0.1.0/docs/guides/CI_INTEGRATION.md +71 -0
  34. sqlguard_ninja-0.1.0/docs/guides/POLICY_REFERENCE.md +127 -0
  35. sqlguard_ninja-0.1.0/docs/guides/QUERY_COST.md +71 -0
  36. sqlguard_ninja-0.1.0/docs/release/FINAL_TECHNICAL_AUDIT.md +83 -0
  37. sqlguard_ninja-0.1.0/docs/releases/v0.1.0.md +45 -0
  38. sqlguard_ninja-0.1.0/docs/research/COMPETITIVE_ANALYSIS.md +127 -0
  39. sqlguard_ninja-0.1.0/docs/security/THREAT_MODEL.md +83 -0
  40. sqlguard_ninja-0.1.0/examples/_shared.py +21 -0
  41. sqlguard_ninja-0.1.0/examples/fastapi/app.py +48 -0
  42. sqlguard_ninja-0.1.0/examples/github-actions/sql-security.yml +32 -0
  43. sqlguard_ninja-0.1.0/examples/langchain/guarded_tool_demo.py +49 -0
  44. sqlguard_ninja-0.1.0/examples/langgraph/real_llm_agent.py +45 -0
  45. sqlguard_ninja-0.1.0/examples/langgraph/sql_agent_demo.py +117 -0
  46. sqlguard_ninja-0.1.0/examples/postgresql/plan_inspection_demo.py +56 -0
  47. sqlguard_ninja-0.1.0/examples/sdk/quickstart.py +31 -0
  48. sqlguard_ninja-0.1.0/examples/sqlite/text_to_sql_demo.py +64 -0
  49. sqlguard_ninja-0.1.0/pyproject.toml +122 -0
  50. sqlguard_ninja-0.1.0/src/sqlguard_ninja/__init__.py +35 -0
  51. sqlguard_ninja-0.1.0/src/sqlguard_ninja/_version.py +1 -0
  52. sqlguard_ninja-0.1.0/src/sqlguard_ninja/benchmarking/__init__.py +1 -0
  53. sqlguard_ninja-0.1.0/src/sqlguard_ninja/benchmarking/adapters.py +303 -0
  54. sqlguard_ninja-0.1.0/src/sqlguard_ninja/benchmarking/builtin.py +39 -0
  55. sqlguard_ninja-0.1.0/src/sqlguard_ninja/benchmarking/compare.py +168 -0
  56. sqlguard_ninja-0.1.0/src/sqlguard_ninja/benchmarking/dataset.py +265 -0
  57. sqlguard_ninja-0.1.0/src/sqlguard_ninja/benchmarking/fixtures.py +274 -0
  58. sqlguard_ninja-0.1.0/src/sqlguard_ninja/benchmarking/metrics.py +114 -0
  59. sqlguard_ninja-0.1.0/src/sqlguard_ninja/benchmarking/runner.py +126 -0
  60. sqlguard_ninja-0.1.0/src/sqlguard_ninja/benchmarking/translate.py +64 -0
  61. sqlguard_ninja-0.1.0/src/sqlguard_ninja/benchmarking/workers/_protocol.py +53 -0
  62. sqlguard_ninja-0.1.0/src/sqlguard_ninja/benchmarking/workers/agent_sql_guard_worker.py +40 -0
  63. sqlguard_ninja-0.1.0/src/sqlguard_ninja/benchmarking/workers/krish_sqlguard_worker.py +25 -0
  64. sqlguard_ninja-0.1.0/src/sqlguard_ninja/benchmarking/workers/sql_guardrail_worker.py +48 -0
  65. sqlguard_ninja-0.1.0/src/sqlguard_ninja/cli/__init__.py +1 -0
  66. sqlguard_ninja-0.1.0/src/sqlguard_ninja/cli/config.py +76 -0
  67. sqlguard_ninja-0.1.0/src/sqlguard_ninja/cli/main.py +433 -0
  68. sqlguard_ninja-0.1.0/src/sqlguard_ninja/cli/templates.py +91 -0
  69. sqlguard_ninja-0.1.0/src/sqlguard_ninja/core/__init__.py +1 -0
  70. sqlguard_ninja-0.1.0/src/sqlguard_ninja/core/analysis.py +581 -0
  71. sqlguard_ninja-0.1.0/src/sqlguard_ninja/core/findings.py +133 -0
  72. sqlguard_ninja-0.1.0/src/sqlguard_ninja/core/guard.py +256 -0
  73. sqlguard_ninja-0.1.0/src/sqlguard_ninja/core/rules/__init__.py +1 -0
  74. sqlguard_ninja-0.1.0/src/sqlguard_ninja/core/rules/access.py +127 -0
  75. sqlguard_ninja-0.1.0/src/sqlguard_ninja/core/rules/base.py +40 -0
  76. sqlguard_ninja-0.1.0/src/sqlguard_ninja/core/rules/catalog.py +61 -0
  77. sqlguard_ninja-0.1.0/src/sqlguard_ninja/core/rules/functions.py +197 -0
  78. sqlguard_ninja-0.1.0/src/sqlguard_ninja/core/rules/statements.py +99 -0
  79. sqlguard_ninja-0.1.0/src/sqlguard_ninja/core/rules/structure.py +72 -0
  80. sqlguard_ninja-0.1.0/src/sqlguard_ninja/core/rules/tenant.py +196 -0
  81. sqlguard_ninja-0.1.0/src/sqlguard_ninja/integrations/__init__.py +43 -0
  82. sqlguard_ninja-0.1.0/src/sqlguard_ninja/integrations/audit.py +109 -0
  83. sqlguard_ninja-0.1.0/src/sqlguard_ninja/integrations/checkpoint.py +342 -0
  84. sqlguard_ninja-0.1.0/src/sqlguard_ninja/integrations/executors.py +64 -0
  85. sqlguard_ninja-0.1.0/src/sqlguard_ninja/integrations/fastapi.py +89 -0
  86. sqlguard_ninja-0.1.0/src/sqlguard_ninja/integrations/langchain.py +67 -0
  87. sqlguard_ninja-0.1.0/src/sqlguard_ninja/integrations/langgraph.py +87 -0
  88. sqlguard_ninja-0.1.0/src/sqlguard_ninja/policy/__init__.py +39 -0
  89. sqlguard_ninja-0.1.0/src/sqlguard_ninja/policy/model.py +370 -0
  90. sqlguard_ninja-0.1.0/src/sqlguard_ninja/privacy/__init__.py +9 -0
  91. sqlguard_ninja-0.1.0/src/sqlguard_ninja/privacy/rules.py +286 -0
  92. sqlguard_ninja-0.1.0/src/sqlguard_ninja/privacy/suggest.py +46 -0
  93. sqlguard_ninja-0.1.0/src/sqlguard_ninja/py.typed +0 -0
  94. sqlguard_ninja-0.1.0/src/sqlguard_ninja/query_cost/__init__.py +1 -0
  95. sqlguard_ninja-0.1.0/src/sqlguard_ninja/query_cost/postgres.py +226 -0
  96. sqlguard_ninja-0.1.0/src/sqlguard_ninja/query_cost/static.py +241 -0
  97. sqlguard_ninja-0.1.0/src/sqlguard_ninja/reporting/__init__.py +1 -0
  98. sqlguard_ninja-0.1.0/src/sqlguard_ninja/reporting/markdown.py +137 -0
  99. sqlguard_ninja-0.1.0/tests/__init__.py +0 -0
  100. sqlguard_ninja-0.1.0/tests/conftest.py +46 -0
  101. sqlguard_ninja-0.1.0/tests/integration/__init__.py +0 -0
  102. sqlguard_ninja-0.1.0/tests/integration/test_corpus_sqlite_validation.py +40 -0
  103. sqlguard_ninja-0.1.0/tests/integration/test_external_adapters.py +36 -0
  104. sqlguard_ninja-0.1.0/tests/integration/test_frameworks.py +209 -0
  105. sqlguard_ninja-0.1.0/tests/integration/test_postgres.py +130 -0
  106. sqlguard_ninja-0.1.0/tests/pg_support.py +74 -0
  107. sqlguard_ninja-0.1.0/tests/property/__init__.py +0 -0
  108. sqlguard_ninja-0.1.0/tests/property/test_guard_properties.py +64 -0
  109. sqlguard_ninja-0.1.0/tests/security/__init__.py +0 -0
  110. sqlguard_ninja-0.1.0/tests/security/test_agent_boundaries.py +238 -0
  111. sqlguard_ninja-0.1.0/tests/security/test_corpus_native.py +29 -0
  112. sqlguard_ninja-0.1.0/tests/unit/__init__.py +0 -0
  113. sqlguard_ninja-0.1.0/tests/unit/helpers.py +5 -0
  114. sqlguard_ninja-0.1.0/tests/unit/test_benchmark_engine.py +288 -0
  115. sqlguard_ninja-0.1.0/tests/unit/test_cli.py +188 -0
  116. sqlguard_ninja-0.1.0/tests/unit/test_dataset.py +60 -0
  117. sqlguard_ninja-0.1.0/tests/unit/test_docs.py +130 -0
  118. sqlguard_ninja-0.1.0/tests/unit/test_function_policy_mechanics.py +74 -0
  119. sqlguard_ninja-0.1.0/tests/unit/test_policy.py +125 -0
  120. sqlguard_ninja-0.1.0/tests/unit/test_rules.py +415 -0
@@ -0,0 +1,30 @@
1
+ # Python
2
+ __pycache__/
3
+ *.py[cod]
4
+ *.egg-info/
5
+ build/
6
+ dist/
7
+ .eggs/
8
+ # Environments
9
+ .venv/
10
+ .venvs/
11
+ venv/
12
+ # Tooling caches
13
+ .pytest_cache/
14
+ .mypy_cache/
15
+ .ruff_cache/
16
+ .hypothesis/
17
+ .coverage
18
+ .coverage.*
19
+ coverage.xml
20
+ htmlcov/
21
+ # Local artefacts
22
+ /results/
23
+ *.sqlite3
24
+ *.db
25
+ .pgdata/
26
+ .env
27
+ .env.*
28
+ !.env.example
29
+ audit*.jsonl
30
+ .pytest_tmp/
@@ -0,0 +1,41 @@
1
+ # Changelog
2
+
3
+ All notable changes are documented here. The project follows
4
+ [Semantic Versioning](https://semver.org/); before 1.0, minor versions may change the API.
5
+
6
+ ## [0.1.0] — 2026-10-24
7
+
8
+ First release.
9
+
10
+ ### Added
11
+ * Policy schema v1: catalog, classification labels, roles, tenant settings, function policy,
12
+ limits, cost thresholds, disclosure mode. Policies are validated on load.
13
+ * Guard and rules on sqlglot 30: read-only statements, system catalogs, functions,
14
+ table/column grants, privacy labels (deny / aggregate-only / review, JSON paths, small
15
+ cohort, minimisation), tenant isolation, structure limits, static cost score.
16
+ * `SQLCheckpoint` with block / review / audit modes, approvals bound to the SQL hash
17
+ (single use, expiry, no self-approval), retry lock-out, redacted audit events.
18
+ * LangChain tool, LangGraph nodes and router, FastAPI router, read-only executors.
19
+ * PostgreSQL `EXPLAIN (FORMAT JSON)` inspector with guard gating and a read-only,
20
+ time-limited, rolled-back transaction.
21
+ * Benchmark corpus v1.0.0 (530 cases, 1,002 evaluations), seeded generator, metrics,
22
+ adapters (native, callable, isolated external workers for three existing tools), JSON
23
+ and Markdown reports, baseline comparison with a label-change gate.
24
+ * `sqlninja` CLI and a composite GitHub Action.
25
+
26
+ ### Known limitations
27
+ * The benchmark corpus does not contain cases for two categories: **restricted functions** (e.g. calls to server file-access, sleep, dynamic-SQL or administrative functions) and **system catalogs** (PostgreSQL `pg_catalog`/`information_schema`, SQLite `sqlite_master`/`sqlite_schema`, in qualified, joined, CTE and nested positions). The corresponding rules (`function.*`, `catalog.system_object`) ship and run by default; their mechanics are unit-tested with fictitious function names, but their detection is not measured by the benchmark.
28
+ * Writes are always denied; only PostgreSQL and SQLite are tested.
29
+
30
+ ### Packaging
31
+ * The reference corpus and policy are bundled in the wheel (`builtin:v1`, `builtin:retail_saas`).
32
+ * Published to PyPI through GitHub Actions Trusted Publishing (OIDC).
33
+
34
+ ### Fixed during development (each with a regression test)
35
+ * Unknown select-list columns were allowed when qualification aliased them to themselves.
36
+ * `Guard.validate` raised on lone UTF-16 surrogates.
37
+ * Quoted mixed-case identifiers were re-lowercased, so PostgreSQL `"Orders"` matched `orders`.
38
+ * A cast of the tenant column was accepted as a tenant pin.
39
+ * LangGraph nodes did not receive the run config (it needs a `RunnableConfig` annotation).
40
+ * The shared SQLite connection could not be used from FastAPI worker threads.
41
+ * CLI output crashed on cp1252 consoles.
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
@@ -0,0 +1,370 @@
1
+ Metadata-Version: 2.5
2
+ Name: sqlguard-ninja
3
+ Version: 0.1.0
4
+ Summary: Security testing, policy enforcement, agent integration, privacy analysis and CI benchmarking for LLM-generated SQL.
5
+ Project-URL: Homepage, https://github.com/Pratik653/SQLGuard_Ninjapy
6
+ Project-URL: Documentation, https://github.com/Pratik653/SQLGuard_Ninjapy/tree/main/docs
7
+ Project-URL: Issues, https://github.com/Pratik653/SQLGuard_Ninjapy/issues
8
+ Author: SQLGuard Ninja contributors
9
+ License-Expression: Apache-2.0
10
+ License-File: LICENSE
11
+ License-File: THIRD_PARTY_NOTICES.md
12
+ Keywords: benchmark,guardrail,langchain,langgraph,llm,privacy,security,sql,sqlglot,text-to-sql
13
+ Classifier: Development Status :: 3 - Alpha
14
+ Classifier: Intended Audience :: Developers
15
+ Classifier: Operating System :: OS Independent
16
+ Classifier: Programming Language :: Python :: 3
17
+ Classifier: Programming Language :: Python :: 3.11
18
+ Classifier: Programming Language :: Python :: 3.12
19
+ Classifier: Programming Language :: Python :: 3.13
20
+ Classifier: Programming Language :: SQL
21
+ Classifier: Topic :: Database
22
+ Classifier: Topic :: Security
23
+ Classifier: Typing :: Typed
24
+ Requires-Python: >=3.11
25
+ Requires-Dist: pydantic<3.0,>=2.6
26
+ Requires-Dist: pyyaml>=6.0
27
+ Requires-Dist: sqlglot<31.0,>=30.0
28
+ Provides-Extra: all
29
+ Requires-Dist: fastapi>=0.110; extra == 'all'
30
+ Requires-Dist: langchain-core>=0.3; extra == 'all'
31
+ Requires-Dist: langgraph>=0.2; extra == 'all'
32
+ Requires-Dist: psycopg[binary]>=3.1; extra == 'all'
33
+ Provides-Extra: dev
34
+ Requires-Dist: build>=1.2; extra == 'dev'
35
+ Requires-Dist: fastapi>=0.110; extra == 'dev'
36
+ Requires-Dist: httpx>=0.27; extra == 'dev'
37
+ Requires-Dist: hypothesis>=6.100; extra == 'dev'
38
+ Requires-Dist: langchain-core>=0.3; extra == 'dev'
39
+ Requires-Dist: langgraph>=0.2; extra == 'dev'
40
+ Requires-Dist: mypy>=1.10; extra == 'dev'
41
+ Requires-Dist: psycopg[binary]>=3.1; extra == 'dev'
42
+ Requires-Dist: pytest-cov>=5.0; extra == 'dev'
43
+ Requires-Dist: pytest>=8.0; extra == 'dev'
44
+ Requires-Dist: ruff>=0.6; extra == 'dev'
45
+ Requires-Dist: types-pyyaml; extra == 'dev'
46
+ Provides-Extra: fastapi
47
+ Requires-Dist: fastapi>=0.110; extra == 'fastapi'
48
+ Provides-Extra: langchain
49
+ Requires-Dist: langchain-core>=0.3; extra == 'langchain'
50
+ Provides-Extra: langgraph
51
+ Requires-Dist: langchain-core>=0.3; extra == 'langgraph'
52
+ Requires-Dist: langgraph>=0.2; extra == 'langgraph'
53
+ Provides-Extra: postgres
54
+ Requires-Dist: psycopg[binary]>=3.1; extra == 'postgres'
55
+ Description-Content-Type: text/markdown
56
+
57
+ # SQLGuard Ninja
58
+
59
+ **Security testing, policy enforcement, agent integration, privacy analysis and CI
60
+ benchmarking for LLM-generated SQL.**
61
+
62
+ [![CI](https://github.com/Pratik653/SQLGuard_Ninjapy/actions/workflows/ci.yml/badge.svg)](https://github.com/Pratik653/SQLGuard_Ninjapy/actions/workflows/ci.yml)
63
+ [![PyPI](https://img.shields.io/pypi/v/sqlguard-ninja)](https://pypi.org/project/sqlguard-ninja/)
64
+ ![Python](https://img.shields.io/badge/python-3.11%20%7C%203.12%20%7C%203.13-blue)
65
+ ![License](https://img.shields.io/badge/license-Apache--2.0-green)
66
+
67
+ When an LLM writes SQL, the system prompt is not a security boundary. SQLGuard Ninja sits
68
+ between the model and the database. It checks every statement against a declared policy for
69
+ the *authenticated* caller: which tables and columns a role may use, which data classes may
70
+ appear only in aggregates or only after human approval, and which tenant the caller belongs
71
+ to. It records an audit trail and gives the agent an explanation it can act on.
72
+
73
+ It ships with a labelled benchmark corpus (530 cases, 1,002 dialect evaluations) and a
74
+ regression gate for CI. The same benchmark harness can evaluate other open-source guards
75
+ side by side.
76
+
77
+ > **One layer, not the only one.** Static SQL inspection cannot guarantee database security.
78
+ > Use a read-only least-privilege role, row-level security and statement timeouts as well.
79
+ > See the [threat model](docs/security/THREAT_MODEL.md).
80
+
81
+ ## What it does
82
+
83
+ | Workstream | What you get | Status |
84
+ |---|---|---|
85
+ | **Policy engine** | Read-only enforcement, table/column grants, tenant isolation, function and catalog rules, structural limits. Built on [sqlglot](https://github.com/tobymao/sqlglot). Fails closed when analysis is incomplete. | PostgreSQL + SQLite tested |
86
+ | **Privacy pack** | Explicit classification labels, `deny` / `aggregate_only` / `review` per role, JSON-path labels, small-cohort review, minimisation hints and alternatives | implemented |
87
+ | **Agent integrations** | `SQLCheckpoint` with block / review / audit modes, hash-bound single-use approvals, retry lock-out, redacted audit events. LangChain tool, LangGraph nodes, FastAPI router | implemented |
88
+ | **Benchmark engine** | Versioned corpus, metrics (recall, precision, FPR, FNR, exact match, per category/dialect, latency percentiles), adapters for native, callable and isolated external validators, JSON and Markdown reports | implemented |
89
+ | **Query cost** | Explainable static score; optional PostgreSQL `EXPLAIN (FORMAT JSON)` inspection, gated and read-only | implemented |
90
+ | **CI** | Composite GitHub Action and CLI gate: security, usability, label-change and error regressions against an approved baseline | implemented |
91
+
92
+ Not yet included: governed writes (all writes are denied in v0.1); benchmark cases for
93
+ restricted functions and system catalogs (the rules exist, but the corpus does not cover
94
+ them); dialects beyond PostgreSQL and SQLite (they parse, but are untested). Full list:
95
+ [KNOWN_LIMITATIONS.md](KNOWN_LIMITATIONS.md).
96
+
97
+ ## Architecture
98
+
99
+ ```mermaid
100
+ flowchart LR
101
+ subgraph App["Your application"]
102
+ Auth["Auth layer"] --> Ctx["RequestContext<br/>(principal, role, tenant)"]
103
+ LLM["LLM / agent"] -->|SQL text| CP
104
+ Ctx --> CP["SQLCheckpoint<br/>block / review / audit"]
105
+ end
106
+ CP --> G["Guard"]
107
+ G --> AN["Analyser<br/>sqlglot qualify + scopes"]
108
+ AN --> R1["Statement / catalog / function rules"]
109
+ AN --> R2["Table and column grants"]
110
+ AN --> R3["Privacy labels"]
111
+ AN --> R4["Tenant pins"]
112
+ AN --> R5["Limits + static cost"]
113
+ CP -->|authorized only| EX["Read-only executor"] --> DB[("Database<br/>grants, RLS, timeouts")]
114
+ CP --> AU["Audit sink<br/>hash + redacted SQL"]
115
+ CP -.review.-> AP["ApprovalQueue (human)"]
116
+ G -.ALLOW only.-> PI["PostgreSQL EXPLAIN inspector"]
117
+ subgraph Bench["Benchmark + CI"]
118
+ DS["Corpus v1"] --> RUN["Runner"] --> ADP["Adapters: native, callable,<br/>isolated external workers"]
119
+ RUN --> RES["Result JSON / Markdown"] --> CMP["Baseline compare"] --> GATE["GitHub Action gate"]
120
+ end
121
+ ```
122
+
123
+ Design decisions and their trade-offs are recorded in
124
+ [ARCHITECTURE_DECISIONS.md](docs/architecture/ARCHITECTURE_DECISIONS.md).
125
+
126
+ ## Five-minute quick start
127
+
128
+ ```bash
129
+ python -m pip install sqlguard-ninja # core: sqlglot, pydantic, PyYAML
130
+ python -m pip install "sqlguard-ninja[all]" # + LangChain, LangGraph, FastAPI, psycopg
131
+ ```
132
+
133
+ Extras: `langchain`, `langgraph`, `fastapi`, `postgres`, `all`. Python 3.11+.
134
+
135
+ Validate a query against the bundled reference policy (`builtin:retail_saas`, a synthetic
136
+ multi-tenant retail schema):
137
+
138
+ ```bash
139
+ sqlninja validate --policy builtin:retail_saas --role support_analyst --tenant 1 --sql "SELECT o.id FROM orders o WHERE o.tenant_id = 1 OR 1 = 1"
140
+ ```
141
+
142
+ ```
143
+ DENY:
144
+ [deny] tenant.missing_predicate: Every read of table 'orders' must filter on the caller's tenant. Suggestion: Add `o.tenant_id = :tenant_id` to the WHERE clause of the scope that reads this table.
145
+ ```
146
+
147
+ Exit codes: 0 allow, 1 deny, 3 review, 2 usage error.
148
+
149
+ Run the bundled benchmark corpus, then start your own project:
150
+
151
+ ```bash
152
+ sqlninja benchmark run --dataset builtin:v1 --output results/native.json
153
+ sqlninja init my-project && cd my-project
154
+ sqlninja benchmark run --config sqlninja.yaml
155
+ ```
156
+
157
+ The runnable demos live in the repository (deterministic; no API key needed):
158
+
159
+ ```bash
160
+ git clone https://github.com/Pratik653/SQLGuard_Ninjapy.git && cd SQLGuard_Ninjapy
161
+ python -m pip install -e ".[all]"
162
+ python examples/sdk/quickstart.py
163
+ python examples/sqlite/text_to_sql_demo.py
164
+ python examples/langgraph/sql_agent_demo.py
165
+ ```
166
+
167
+ ## Python SDK
168
+
169
+ ```python
170
+ from sqlguard_ninja import Guard, Policy
171
+
172
+ from sqlguard_ninja.benchmarking.builtin import resolve
173
+
174
+ guard = Guard(Policy.from_file(resolve("builtin:retail_saas", "policy")))
175
+ result = guard.validate(
176
+ "SELECT department, AVG(salary) FROM employees GROUP BY department",
177
+ role="hr_analyst",
178
+ dialect="postgres",
179
+ )
180
+ result.allowed # True
181
+ result.findings # () - structured Finding objects with rule_id, action, message, remediation
182
+
183
+ guard.validate("SELECT full_name, salary FROM employees", role="hr_analyst").explain()
184
+ # DENY:
185
+ # [deny] privacy.aggregate_only: The column 'employees.salary' may only be used inside
186
+ # statistical aggregates (COUNT, SUM, AVG, ...), not as individual values. ...
187
+ ```
188
+
189
+ ## LangGraph
190
+
191
+ ```python
192
+ from sqlguard_ninja.integrations import RequestContext, SQLCheckpoint
193
+ from sqlguard_ninja.integrations.langgraph import (
194
+ CONTEXT_KEY, make_execute_node, make_guard_node, route_after_guard)
195
+
196
+ checkpoint = SQLCheckpoint(guard, mode="block", max_denied_attempts=3)
197
+ graph.add_node("guard", make_guard_node(checkpoint))
198
+ graph.add_node("execute", make_execute_node(checkpoint, executor)) # re-validates
199
+ graph.add_conditional_edges("guard", route_after_guard(3),
200
+ {"execute": "execute", "revise": "generate", "end": END})
201
+
202
+ ctx = RequestContext(principal=user.id, role=user.role, tenant_id=user.tenant_id)
203
+ app.invoke(state, config={"configurable": {CONTEXT_KEY: ctx}}) # nodes cannot alter config
204
+ ```
205
+
206
+ More in [AGENT_INTEGRATION.md](docs/guides/AGENT_INTEGRATION.md): the LangChain tool (its
207
+ schema accepts only `query`), the FastAPI router, review-mode approvals and audit sinks.
208
+
209
+ ## Privacy policies
210
+
211
+ Sensitivity comes from labels **you** assign in the policy, never from column names, and
212
+ access is resolved per role:
213
+
214
+ ```yaml
215
+ labels:
216
+ payment_card: {sensitivity: critical, masking: use card_last4 and card_brand}
217
+ financial: {sensitivity: high}
218
+ catalog:
219
+ tables:
220
+ payments:
221
+ tenant_column: tenant_id
222
+ columns:
223
+ card_number: {labels: [payment_card], alternatives: [card_last4]}
224
+ card_last4: text
225
+ roles:
226
+ support_analyst:
227
+ tables: {payments: [id, tenant_id, card_last4, card_brand, amount, status]}
228
+ labels: {payment_card: deny, financial: deny}
229
+ hr_analyst:
230
+ tables: {employees: "*"}
231
+ labels: {hr: allow, financial: aggregate_only} # salary only inside COUNT/SUM/AVG
232
+ ```
233
+
234
+ ```text
235
+ support_analyst> SELECT p.card_number FROM payments p WHERE p.tenant_id = 1
236
+ DENY:
237
+ [deny] privacy.label_denied: The column 'payments.card_number' contains classified data (payment_card) that this role may not access. Suggestion: Use column 'payments.card_last4' instead. ...
238
+
239
+ hr_analyst> SELECT AVG(salary) FROM employees WHERE id = 7
240
+ REVIEW:
241
+ [review] privacy.small_cohort: An aggregate of restricted data is filtered or grouped by an identifying column, which can reveal individual values. ...
242
+ ```
243
+
244
+ Labels also apply to paths inside JSON columns (`profile->'health'->>'allergies'`).
245
+ `sqlninja policy suggest` proposes labels from column names for a human to review; those
246
+ suggestions are never enforced. This is a technical control, not a certification of GDPR
247
+ compliance. Full semantics: [POLICY_REFERENCE.md](docs/guides/POLICY_REFERENCE.md).
248
+
249
+ ## Query cost analysis
250
+
251
+ Every validation includes an explainable static score that uses the catalog's
252
+ `estimated_rows`:
253
+
254
+ ```text
255
+ platform_admin> SELECT o.id, i.id FROM orders o CROSS JOIN order_items i
256
+ DENY:
257
+ [deny] cost.static_score: Estimated query cost risk is 100/100: join with i has no join condition (Cartesian product); o has an estimated 10,000,000 rows and is read without a filter; ...
258
+ ```
259
+
260
+ Optionally, compare it with PostgreSQL's planner. This runs `EXPLAIN (FORMAT JSON)` only,
261
+ never `ANALYZE`, and only on SQL the guard allowed, inside a read-only, time-limited,
262
+ rolled-back transaction:
263
+
264
+ ```python
265
+ from sqlguard_ninja.query_cost.postgres import PostgresPlanInspector
266
+ report = PostgresPlanInspector(guard, lambda: psycopg.connect(READER_DSN)).inspect(
267
+ sql, role="support_analyst", context={"tenant_id": 1})
268
+ report.total_cost, report.plan_rows, report.static.score, report.findings
269
+ ```
270
+
271
+ See [QUERY_COST.md](docs/guides/QUERY_COST.md) and `examples/postgresql/plan_inspection_demo.py`.
272
+
273
+ ## Benchmark
274
+
275
+ ```bash
276
+ sqlninja benchmark run --dataset builtin:v1 --adapter native
277
+ python scripts/setup_external_adapters.py # (repository) isolated venvs for other tools
278
+ sqlninja benchmark run --dataset builtin:v1 --adapter external:sql-guardrail
279
+ sqlninja benchmark compare --baseline benchmarks/baselines/native.json --candidate results/latest.json
280
+ ```
281
+
282
+ Results for corpus v1.0.0 (Windows 11, Python 3.11, 1,002 evaluations). Details and raw files:
283
+ [RESULTS_v1.md](docs/benchmarks/RESULTS_v1.md).
284
+
285
+ | Validator | Recall | Precision | FPR | Recall / FPR within declared capability | p95 ms |
286
+ |---|---:|---:|---:|---:|---:|
287
+ | SQLGuard Ninja 0.1.0 | 100.0% | 100.0% | 0.0% | 100.0% / 0.0% | 2.15 |
288
+ | sql-guardrail 0.5.2 | 98.6% | 86.6% | 21.2% | 98.3% / 19.3% | 1.72 |
289
+ | agent-sql-guard 0.2.0 | 67.9% | 86.6% | 14.5% | 89.5% / 17.2% | 1.26 |
290
+ | krish2105/sqlguard 0.1.0 | 65.8% | 91.4% | 8.6% | 83.5% / 5.2% | 1.22 |
291
+
292
+ **Read the native row with care.** The corpus and the engine were developed together, and
293
+ every disagreement was triaged by fixing the engine or correcting a label (both are logged).
294
+ 100% shows consistency with the documented semantics, not independent detection quality. The
295
+ other tools have smaller policy models (no roles, labels, aggregate-only access or review), so
296
+ the "within capability" column is the fairer comparison. Methodology and threats to validity:
297
+ [BENCHMARK_METHODOLOGY.md](docs/guides/BENCHMARK_METHODOLOGY.md).
298
+
299
+ ## How it relates to existing tools
300
+
301
+ SQLGuard Ninja uses **sqlglot** for parsing, dialects and scope analysis, and does not
302
+ re-implement them. [sql-guardrail](https://github.com/nickusevich/sql-guardrail) is a
303
+ thorough read-only validator with a tautology catch-all, which this project does not
304
+ duplicate. [agent-sql-guard](https://github.com/sakura-sky/sql-guard) has a careful
305
+ schema-less PII denylist. What SQLGuard Ninja adds: role- and label-based policies, the agent
306
+ checkpoint contract, a shared benchmark with isolated adapters, planner inspection, and the
307
+ CI gate. Full comparison: [COMPETITIVE_ANALYSIS.md](docs/research/COMPETITIVE_ANALYSIS.md).
308
+
309
+ ## Security limitations
310
+
311
+ * Static inspection can be wrong where sqlglot and the real database parse SQL differently.
312
+ Only PostgreSQL and SQLite are tested.
313
+ * It cannot see inside views or user-defined functions, and it does not stop inference
314
+ across many permitted queries.
315
+ * Cost scores and planner estimates are indicators, not guarantees.
316
+ * v0.1 denies all writes.
317
+ * The benchmark has no restricted-function or system-catalog cases yet. The rules exist,
318
+ but those two categories are not measured.
319
+
320
+ Use database grants, row-level security and timeouts as the authoritative controls. See the
321
+ [threat model](docs/security/THREAT_MODEL.md) and [KNOWN_LIMITATIONS.md](KNOWN_LIMITATIONS.md).
322
+
323
+ ## Roadmap
324
+
325
+ Next: restricted-function and system-catalog benchmark cases, an independent held-out
326
+ corpus, lineage-aware aggregate checks, and tenant predicate push-down. Later: governed
327
+ writes, more tested dialects, and SARIF output. Details in [ROADMAP.md](ROADMAP.md).
328
+
329
+ ## Links
330
+
331
+ * Repository: https://github.com/Pratik653/SQLGuard_Ninjapy
332
+ * Releases: https://github.com/Pratik653/SQLGuard_Ninjapy/releases
333
+ * PyPI: https://pypi.org/project/sqlguard-ninja/
334
+ * Issues: https://github.com/Pratik653/SQLGuard_Ninjapy/issues
335
+ * Security policy: [SECURITY.md](SECURITY.md) · Contributing: [CONTRIBUTING.md](CONTRIBUTING.md)
336
+
337
+ ## Documentation
338
+
339
+ * [Policy reference](docs/guides/POLICY_REFERENCE.md)
340
+ * [Agent integration](docs/guides/AGENT_INTEGRATION.md)
341
+ * [Query cost](docs/guides/QUERY_COST.md)
342
+ * [CI integration](docs/guides/CI_INTEGRATION.md)
343
+ * [Benchmark methodology](docs/guides/BENCHMARK_METHODOLOGY.md)
344
+ * [Threat model](docs/security/THREAT_MODEL.md)
345
+ * [Architecture decisions](docs/architecture/ARCHITECTURE_DECISIONS.md)
346
+ * [Known limitations](KNOWN_LIMITATIONS.md) · [Roadmap](ROADMAP.md) · [Changelog](CHANGELOG.md)
347
+
348
+ ## Supported versions
349
+
350
+ * Python 3.11, 3.12, 3.13 (CI matrix on Linux and Windows).
351
+ * SQL dialects: **PostgreSQL** (tested against PostgreSQL 16) and **SQLite**. Other sqlglot
352
+ dialects parse but are experimental and untested.
353
+
354
+ ## Development
355
+
356
+ ```bash
357
+ python -m pip install -e ".[dev]"
358
+ ruff check src tests scripts examples && ruff format --check src tests scripts examples
359
+ mypy
360
+ pytest # PostgreSQL tests run if SQLNINJA_PG_DSN is set or pgserver is installed
361
+ python scripts/generate_corpus.py --check
362
+ ```
363
+
364
+ See [CONTRIBUTING.md](CONTRIBUTING.md). Report vulnerabilities privately per
365
+ [SECURITY.md](SECURITY.md).
366
+
367
+ ## Licence
368
+
369
+ Apache-2.0. No third-party code is vendored; dependencies and their licences are listed in
370
+ [THIRD_PARTY_NOTICES.md](THIRD_PARTY_NOTICES.md). All benchmark data is synthetic.