sqlguardllm 0.1.0a2__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.
Files changed (39) hide show
  1. {sqlguardllm-0.1.0a2 → sqlguardllm-0.2.0a1}/CHANGELOG.md +13 -1
  2. {sqlguardllm-0.1.0a2 → sqlguardllm-0.2.0a1}/PKG-INFO +1 -1
  3. {sqlguardllm-0.1.0a2 → sqlguardllm-0.2.0a1}/README.md +21 -2
  4. {sqlguardllm-0.1.0a2 → sqlguardllm-0.2.0a1}/pyproject.toml +1 -1
  5. {sqlguardllm-0.1.0a2 → sqlguardllm-0.2.0a1}/src/sqlguardllm/_compiled.py +6 -1
  6. {sqlguardllm-0.1.0a2 → sqlguardllm-0.2.0a1}/src/sqlguardllm/guard.py +22 -1
  7. {sqlguardllm-0.1.0a2 → sqlguardllm-0.2.0a1}/src/sqlguardllm/messages.py +8 -0
  8. {sqlguardllm-0.1.0a2 → sqlguardllm-0.2.0a1}/src/sqlguardllm/policy.py +37 -0
  9. {sqlguardllm-0.1.0a2 → sqlguardllm-0.2.0a1}/src/sqlguardllm/result.py +2 -0
  10. sqlguardllm-0.2.0a1/src/sqlguardllm/rules/complexity.py +122 -0
  11. sqlguardllm-0.2.0a1/src/sqlguardllm/rules/required_filters.py +76 -0
  12. sqlguardllm-0.2.0a1/tests/corpus/complexity.yaml +125 -0
  13. sqlguardllm-0.2.0a1/tests/corpus/required_filters.yaml +76 -0
  14. {sqlguardllm-0.1.0a2 → sqlguardllm-0.2.0a1}/tests/test_corpus.py +2 -1
  15. {sqlguardllm-0.1.0a2 → sqlguardllm-0.2.0a1}/tests/test_policy.py +33 -0
  16. {sqlguardllm-0.1.0a2 → sqlguardllm-0.2.0a1}/tests/test_rules.py +51 -0
  17. {sqlguardllm-0.1.0a2 → sqlguardllm-0.2.0a1}/.gitignore +0 -0
  18. {sqlguardllm-0.1.0a2 → sqlguardllm-0.2.0a1}/LICENSE +0 -0
  19. {sqlguardllm-0.1.0a2 → sqlguardllm-0.2.0a1}/docs/pypi.md +0 -0
  20. {sqlguardllm-0.1.0a2 → sqlguardllm-0.2.0a1}/src/sqlguardllm/__init__.py +0 -0
  21. {sqlguardllm-0.1.0a2 → sqlguardllm-0.2.0a1}/src/sqlguardllm/_names.py +0 -0
  22. {sqlguardllm-0.1.0a2 → sqlguardllm-0.2.0a1}/src/sqlguardllm/data/__init__.py +0 -0
  23. {sqlguardllm-0.1.0a2 → sqlguardllm-0.2.0a1}/src/sqlguardllm/data/denied_functions.py +0 -0
  24. {sqlguardllm-0.1.0a2 → sqlguardllm-0.2.0a1}/src/sqlguardllm/py.typed +0 -0
  25. {sqlguardllm-0.1.0a2 → sqlguardllm-0.2.0a1}/src/sqlguardllm/rules/__init__.py +0 -0
  26. {sqlguardllm-0.1.0a2 → sqlguardllm-0.2.0a1}/src/sqlguardllm/rules/columns.py +0 -0
  27. {sqlguardllm-0.1.0a2 → sqlguardllm-0.2.0a1}/src/sqlguardllm/rules/functions.py +0 -0
  28. {sqlguardllm-0.1.0a2 → sqlguardllm-0.2.0a1}/src/sqlguardllm/rules/limit.py +0 -0
  29. {sqlguardllm-0.1.0a2 → sqlguardllm-0.2.0a1}/src/sqlguardllm/rules/row_filters.py +0 -0
  30. {sqlguardllm-0.1.0a2 → sqlguardllm-0.2.0a1}/src/sqlguardllm/rules/sources.py +0 -0
  31. {sqlguardllm-0.1.0a2 → sqlguardllm-0.2.0a1}/src/sqlguardllm/rules/statement.py +0 -0
  32. {sqlguardllm-0.1.0a2 → sqlguardllm-0.2.0a1}/tests/conftest.py +0 -0
  33. {sqlguardllm-0.1.0a2 → sqlguardllm-0.2.0a1}/tests/corpus/allowed.yaml +0 -0
  34. {sqlguardllm-0.1.0a2 → sqlguardllm-0.2.0a1}/tests/corpus/context.yaml +0 -0
  35. {sqlguardllm-0.1.0a2 → sqlguardllm-0.2.0a1}/tests/corpus/functions.yaml +0 -0
  36. {sqlguardllm-0.1.0a2 → sqlguardllm-0.2.0a1}/tests/corpus/tables_columns.yaml +0 -0
  37. {sqlguardllm-0.1.0a2 → sqlguardllm-0.2.0a1}/tests/corpus/writes.yaml +0 -0
  38. {sqlguardllm-0.1.0a2 → sqlguardllm-0.2.0a1}/tests/test_api.py +0 -0
  39. {sqlguardllm-0.1.0a2 → sqlguardllm-0.2.0a1}/tests/test_row_filters.py +0 -0
@@ -4,6 +4,17 @@ All notable changes to sqlguardllm are documented here. The format follows [Keep
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
+
7
18
  ## [0.1.0a2] - 2026-11-25
8
19
 
9
20
  One name everywhere: the project is now **sqlguardllm**.
@@ -36,6 +47,7 @@ First alpha. Installed with `pip install sqlguardllm` and imported as `import sq
36
47
  - Table functions are rejected, even harmless ones like `generate_series`.
37
48
  - No command-line tool yet (planned for v0.2).
38
49
 
39
- [Unreleased]: https://github.com/jmmana/sqlguardllm/compare/v0.1.0a2...HEAD
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
40
52
  [0.1.0a2]: https://github.com/jmmana/sqlguardllm/compare/v0.1.0a1...v0.1.0a2
41
53
  [0.1.0a1]: https://github.com/jmmana/sqlguardllm/releases/tag/v0.1.0a1
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: sqlguardllm
3
- Version: 0.1.0a2
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
5
  Project-URL: Homepage, https://github.com/jmmana/sqlguardllm
6
6
  Project-URL: Documentation, https://github.com/jmmana/sqlguardllm/tree/main/docs
@@ -24,7 +24,7 @@ Your model writes SQL. **sqlguardllm** makes sure it can only read what it's all
24
24
  </div>
25
25
 
26
26
  > [!NOTE]
27
- > **Status: alpha.** `0.1.0a2` is on [PyPI](https://pypi.org/project/sqlguardllm/) (`pip install sqlguardllm`, `import sqlguardllm`), 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/sqlguardllm/discussions).
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
 
@@ -55,6 +55,18 @@ sqlguardllm parses the statement into a syntax tree with sqlglot and **decides o
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
@@ -178,6 +190,10 @@ 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
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.
@@ -188,7 +204,10 @@ A static playground (planned for v0.3) will run sqlguardllm **entirely in your b
188
204
  |---|---|
189
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 |
190
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 |
191
- | [**v0.3 · Ecosystem & playground**](https://github.com/jmmana/sqlguardllm/milestone/3) | Integration recipes, browser playground, performance budget |
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
 
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "sqlguardllm"
3
- version = "0.1.0a2"
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"
@@ -3,7 +3,7 @@
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
@@ -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)
@@ -19,8 +19,10 @@ from sqlguardllm.messages import LANGUAGES, violation
19
19
  from sqlguardllm.policy import Policy
20
20
  from sqlguardllm.result import CheckResult, GuardViolation, PolicyError, Violation, ViolationCode
21
21
  from sqlguardllm.rules.columns import check_columns
22
+ from sqlguardllm.rules.complexity import check_complexity
22
23
  from sqlguardllm.rules.functions import check_functions
23
24
  from sqlguardllm.rules.limit import apply_limit
25
+ from sqlguardllm.rules.required_filters import check_required_filters
24
26
  from sqlguardllm.rules.row_filters import apply_filters, compile_filter
25
27
  from sqlguardllm.rules.sources import collect_sources
26
28
  from sqlguardllm.rules.statement import check_statements
@@ -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.dialect_name, pretty=self._pretty),
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
  )
@@ -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
 
@@ -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:
@@ -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)
@@ -0,0 +1,122 @@
1
+ """Complexity limits: joins, nesting depth and cartesian products.
2
+
3
+ See docs/DESIGN.md#complexity-limits.
4
+
5
+ All three are opt-in. They catch queries that are far more expensive or convoluted than the
6
+ question that produced them, which is usually a model going wrong rather than an attack.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ from sqlglot import exp
12
+ from sqlglot.optimizer.scope import Scope, ScopeType
13
+
14
+ from sqlguardllm._compiled import Compiled
15
+ from sqlguardllm._names import norm
16
+ from sqlguardllm.messages import violation
17
+ from sqlguardllm.result import Violation, ViolationCode
18
+
19
+ _NESTING = frozenset({ScopeType.SUBQUERY, ScopeType.DERIVED_TABLE, ScopeType.CTE})
20
+
21
+
22
+ def _depth(scope: Scope) -> int:
23
+ """How many subqueries, derived tables and CTEs enclose this scope (itself included)."""
24
+ depth = 0
25
+ current: Scope | None = scope
26
+ while current is not None:
27
+ if current.scope_type in _NESTING:
28
+ depth += 1
29
+ current = current.parent
30
+ return depth
31
+
32
+
33
+ class _Components:
34
+ """Union-find over the sources of one SELECT."""
35
+
36
+ def __init__(self, names: list[str]) -> None:
37
+ self._parent = {name: name for name in names}
38
+
39
+ def find(self, name: str) -> str:
40
+ while self._parent[name] != name:
41
+ self._parent[name] = self._parent[self._parent[name]]
42
+ name = self._parent[name]
43
+ return name
44
+
45
+ def union(self, a: str, b: str) -> None:
46
+ if a in self._parent and b in self._parent:
47
+ self._parent[self.find(a)] = self.find(b)
48
+
49
+
50
+ def _source_name(node: exp.Expression, compiled: Compiled) -> str:
51
+ return norm(node.alias_or_name, compiled.dialect)
52
+
53
+
54
+ def _unlinked_sources(select: exp.Select, compiled: Compiled) -> list[str]:
55
+ """Sources of ``select`` that form a cartesian product with the rest."""
56
+ from_ = select.args.get("from_") or select.args.get("from")
57
+ joins: list[exp.Join] = select.args.get("joins") or []
58
+ if not isinstance(from_, exp.From) or not joins:
59
+ return []
60
+
61
+ first = _source_name(from_.this, compiled)
62
+ names = [first, *(_source_name(join.this, compiled) for join in joins)]
63
+ components = _Components(names)
64
+ crossed: list[str] = []
65
+ for join, name in zip(joins, names[1:], strict=True):
66
+ kind = (join.args.get("kind") or "").upper()
67
+ if kind == "CROSS":
68
+ crossed.append(name)
69
+ elif join.args.get("on") or join.args.get("using") or join.args.get("method"):
70
+ components.union(name, first)
71
+
72
+ where = select.args.get("where")
73
+ if isinstance(where, exp.Where):
74
+ condition = where.this
75
+ conjuncts = condition.flatten() if isinstance(condition, exp.And) else [condition]
76
+ for conjunct in conjuncts:
77
+ if not isinstance(conjunct, exp.EQ):
78
+ continue
79
+ left, right = conjunct.this, conjunct.expression
80
+ if (
81
+ isinstance(left, exp.Column)
82
+ and isinstance(right, exp.Column)
83
+ and left.table
84
+ and right.table
85
+ ):
86
+ components.union(
87
+ norm(left.args["table"], compiled.dialect),
88
+ norm(right.args["table"], compiled.dialect),
89
+ )
90
+
91
+ root = components.find(first)
92
+ unlinked = [n for n in names[1:] if n not in crossed and components.find(n) != root]
93
+ return crossed + unlinked
94
+
95
+
96
+ def check_complexity(
97
+ root: exp.Expression, scopes: list[Scope], compiled: Compiled
98
+ ) -> list[Violation]:
99
+ """Apply ``max_joins``, ``max_subquery_depth`` and ``forbid_cartesian``."""
100
+ lang = compiled.language
101
+ violations: list[Violation] = []
102
+
103
+ if compiled.max_joins is not None:
104
+ joins = sum(1 for _ in root.find_all(exp.Join))
105
+ if joins > compiled.max_joins:
106
+ detail = f"max_joins={compiled.max_joins} (found {joins})"
107
+ violations.append(violation(ViolationCode.TOO_COMPLEX, detail, lang))
108
+
109
+ if compiled.max_subquery_depth is not None:
110
+ depth = max((_depth(scope) for scope in scopes), default=0)
111
+ if depth > compiled.max_subquery_depth:
112
+ detail = f"max_subquery_depth={compiled.max_subquery_depth} (found {depth})"
113
+ violations.append(violation(ViolationCode.TOO_COMPLEX, detail, lang))
114
+
115
+ if compiled.forbid_cartesian:
116
+ for scope in scopes:
117
+ if isinstance(scope.expression, exp.Select):
118
+ for name in _unlinked_sources(scope.expression, compiled):
119
+ detail = f"forbid_cartesian ({name})"
120
+ violations.append(violation(ViolationCode.TOO_COMPLEX, detail, lang))
121
+
122
+ return violations
@@ -0,0 +1,76 @@
1
+ """Required filters: some tables can only be read with a predicate on given columns.
2
+
3
+ The typical use is a date range on a large fact table, so a model can't scan all of it. Every
4
+ occurrence of the table (in the main query, subqueries and CTEs) needs, in its own ``WHERE`` or
5
+ in the ``JOIN … ON``/``USING`` that brings it in, a predicate that references one of the columns.
6
+ The check runs on the query as written, before row filters are injected.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ from sqlglot import exp
12
+
13
+ from sqlguardllm._compiled import Compiled
14
+ from sqlguardllm._names import find, norm
15
+ from sqlguardllm.messages import violation
16
+ from sqlguardllm.result import Violation, ViolationCode
17
+ from sqlguardllm.rules.sources import PhysicalRef
18
+
19
+
20
+ def _predicates(ref: PhysicalRef) -> tuple[exp.Select | None, list[exp.Expression]]:
21
+ """The SELECT that reads ``ref`` and the predicates that can filter it there."""
22
+ select = ref.table.find_ancestor(exp.Select)
23
+ if select is None:
24
+ return None, []
25
+ predicates: list[exp.Expression] = []
26
+ where = select.args.get("where")
27
+ if isinstance(where, exp.Where):
28
+ predicates.append(where.this)
29
+ join = ref.table.parent
30
+ if isinstance(join, exp.Join):
31
+ if isinstance(join.args.get("on"), exp.Expression):
32
+ predicates.append(join.args["on"])
33
+ predicates.extend(join.args.get("using") or [])
34
+ return select, predicates
35
+
36
+
37
+ def _is_filtered(ref: PhysicalRef, columns: frozenset[str], compiled: Compiled) -> bool:
38
+ select, predicates = _predicates(ref)
39
+ if select is None:
40
+ return False
41
+ alias = norm(ref.table.alias_or_name, compiled.dialect)
42
+ for predicate in predicates:
43
+ nodes: list[exp.Expression] = [predicate] if isinstance(predicate, exp.Identifier) else []
44
+ nodes += list(predicate.find_all(exp.Column))
45
+ for node in nodes:
46
+ if isinstance(node, exp.Column):
47
+ # Columns of a nested subquery belong to that subquery, not to this read.
48
+ if node.find_ancestor(exp.Select) is not select:
49
+ continue
50
+ qualifier = node.args.get("table")
51
+ if qualifier is not None and norm(qualifier, compiled.dialect) != alias:
52
+ continue
53
+ name = norm(node.this, compiled.dialect)
54
+ else:
55
+ name = norm(node, compiled.dialect)
56
+ if name in columns:
57
+ return True
58
+ return False
59
+
60
+
61
+ def check_required_filters(refs: list[PhysicalRef], compiled: Compiled) -> list[Violation]:
62
+ """Reject every read of a table in ``required_filters`` that lacks its filter."""
63
+ if not compiled.required:
64
+ return []
65
+ violations: list[Violation] = []
66
+ for ref in refs:
67
+ entry = find(compiled.required, ref.name, compiled.default_schema)
68
+ if entry is None:
69
+ continue
70
+ columns = compiled.required[entry]
71
+ if not _is_filtered(ref, columns, compiled):
72
+ detail = f"{ref.name} [{', '.join(sorted(columns))}]"
73
+ violations.append(
74
+ violation(ViolationCode.MISSING_REQUIRED_FILTER, detail, compiled.language)
75
+ )
76
+ return violations
@@ -0,0 +1,125 @@
1
+ # Complexity limits (docs/DESIGN.md#complexity-limits). Each case sets the limits it needs.
2
+ - id: joins-within-limit
3
+ dialect: postgres
4
+ policy: {max_joins: 2}
5
+ sql: >-
6
+ SELECT b.name, SUM(l.quantity) FROM invoices i
7
+ JOIN branches b ON b.id = i.branch_id
8
+ JOIN invoice_lines l ON l.invoice_id = i.id GROUP BY b.name
9
+ expect: allow
10
+ - id: joins-over-limit
11
+ dialect: postgres
12
+ policy: {max_joins: 1}
13
+ sql: >-
14
+ SELECT b.name, SUM(l.quantity) FROM invoices i
15
+ JOIN branches b ON b.id = i.branch_id
16
+ JOIN invoice_lines l ON l.invoice_id = i.id GROUP BY b.name
17
+ expect: reject
18
+ codes: [too_complex]
19
+ - id: joins-counted-across-scopes
20
+ dialect: postgres
21
+ policy: {max_joins: 1}
22
+ sql: >-
23
+ WITH t AS (SELECT i.id FROM invoices i JOIN branches b ON b.id = i.branch_id)
24
+ SELECT p.name FROM products p JOIN invoice_lines l ON l.product_id = p.id
25
+ WHERE l.invoice_id IN (SELECT id FROM t)
26
+ expect: reject
27
+ codes: [too_complex]
28
+ note: One join in the CTE plus one in the main query is two.
29
+ - id: joins-zero-allows-single-table
30
+ dialect: tsql
31
+ policy: {max_joins: 0}
32
+ sql: SELECT SUM(total) FROM invoices
33
+ expect: allow
34
+ - id: depth-zero-rejects-subquery
35
+ dialect: postgres
36
+ policy: {max_subquery_depth: 0}
37
+ sql: SELECT name FROM branches WHERE id IN (SELECT branch_id FROM invoices)
38
+ expect: reject
39
+ codes: [too_complex]
40
+ - id: depth-counts-ctes
41
+ dialect: postgres
42
+ policy: {max_subquery_depth: 0}
43
+ sql: WITH t AS (SELECT id FROM branches) SELECT id FROM t
44
+ expect: reject
45
+ codes: [too_complex]
46
+ - id: depth-nested-over-limit
47
+ dialect: mysql
48
+ policy: {max_subquery_depth: 1}
49
+ sql: >-
50
+ SELECT name FROM products WHERE id IN (SELECT product_id FROM invoice_lines
51
+ WHERE invoice_id IN (SELECT id FROM invoices))
52
+ expect: reject
53
+ codes: [too_complex]
54
+ - id: depth-within-limit
55
+ dialect: mysql
56
+ policy: {max_subquery_depth: 1}
57
+ sql: SELECT name FROM products WHERE id IN (SELECT product_id FROM invoice_lines)
58
+ expect: allow
59
+ - id: depth-union-is-not-nesting
60
+ dialect: postgres
61
+ policy: {max_subquery_depth: 0}
62
+ sql: SELECT name FROM branches UNION ALL SELECT name FROM products
63
+ expect: allow
64
+ - id: cartesian-comma-join
65
+ dialect: postgres
66
+ policy: {forbid_cartesian: true}
67
+ sql: SELECT * FROM invoices, branches
68
+ expect: reject
69
+ codes: [too_complex]
70
+ - id: cartesian-comma-join-linked-in-where
71
+ dialect: postgres
72
+ policy: {forbid_cartesian: true}
73
+ sql: SELECT i.total, b.name FROM invoices i, branches b WHERE i.branch_id = b.id
74
+ expect: allow
75
+ note: The classic comma join with its link in WHERE keeps working.
76
+ - id: cartesian-chain-linked-in-where
77
+ dialect: oracle
78
+ policy: {forbid_cartesian: true}
79
+ sql: >-
80
+ SELECT l.quantity FROM invoices i, invoice_lines l, products p
81
+ WHERE l.invoice_id = i.id AND l.product_id = p.id
82
+ expect: allow
83
+ - id: cartesian-one-table-left-out
84
+ dialect: oracle
85
+ policy: {forbid_cartesian: true}
86
+ sql: >-
87
+ SELECT l.quantity FROM invoices i, invoice_lines l, products p
88
+ WHERE l.invoice_id = i.id
89
+ expect: reject
90
+ codes: [too_complex]
91
+ - id: cartesian-link-under-or-does-not-count
92
+ dialect: postgres
93
+ policy: {forbid_cartesian: true}
94
+ sql: SELECT * FROM invoices i, branches b WHERE i.branch_id = b.id OR i.total > 0
95
+ expect: reject
96
+ codes: [too_complex]
97
+ - id: cartesian-explicit-cross-join
98
+ dialect: tsql
99
+ policy: {forbid_cartesian: true}
100
+ sql: SELECT b.name, p.name FROM branches b CROSS JOIN products p
101
+ expect: reject
102
+ codes: [too_complex]
103
+ - id: cartesian-join-without-on
104
+ dialect: mysql
105
+ policy: {forbid_cartesian: true}
106
+ sql: SELECT b.name FROM branches b JOIN products p
107
+ expect: reject
108
+ codes: [too_complex]
109
+ - id: cartesian-in-subquery
110
+ dialect: postgres
111
+ policy: {forbid_cartesian: true}
112
+ sql: SELECT name FROM branches WHERE id IN (SELECT b.id FROM branches b, products p)
113
+ expect: reject
114
+ codes: [too_complex]
115
+ - id: cartesian-on-and-using-are-fine
116
+ dialect: postgres
117
+ policy: {forbid_cartesian: true}
118
+ sql: >-
119
+ SELECT b.name FROM invoices i JOIN branches b ON b.id = i.branch_id
120
+ JOIN invoice_lines l USING (id)
121
+ expect: allow
122
+ - id: cartesian-off-by-default
123
+ dialect: postgres
124
+ sql: SELECT b.name, p.name FROM branches b CROSS JOIN products p
125
+ expect: allow
@@ -0,0 +1,76 @@
1
+ # Required filters: invoices can only be read with a predicate on issued_at.
2
+ - id: required-missing
3
+ dialect: postgres
4
+ policy: {required_filters: {invoices: [issued_at]}}
5
+ sql: SELECT SUM(total) FROM invoices
6
+ expect: reject
7
+ codes: [missing_required_filter]
8
+ - id: required-in-where
9
+ dialect: postgres
10
+ policy: {required_filters: {invoices: [issued_at]}}
11
+ sql: SELECT SUM(total) FROM invoices WHERE issued_at >= '2026-11-01'
12
+ expect: allow
13
+ - id: required-qualified-with-alias
14
+ dialect: tsql
15
+ policy: {required_filters: {invoices: [issued_at]}}
16
+ sql: >-
17
+ SELECT b.name, SUM(i.total) FROM invoices i JOIN branches b ON b.id = i.branch_id
18
+ WHERE i.issued_at >= '20261101' GROUP BY b.name
19
+ expect: allow
20
+ - id: required-in-join-on
21
+ dialect: postgres
22
+ policy: {required_filters: {invoices: [issued_at]}}
23
+ sql: >-
24
+ SELECT b.name, SUM(i.total) FROM branches b
25
+ JOIN invoices i ON i.branch_id = b.id AND i.issued_at >= '2026-11-01' GROUP BY b.name
26
+ expect: allow
27
+ - id: required-column-of-another-table-does-not-count
28
+ dialect: postgres
29
+ policy: {required_filters: {invoices: [issued_at]}}
30
+ sql: >-
31
+ SELECT SUM(i.total) FROM invoices i JOIN branches b ON b.id = i.branch_id
32
+ WHERE b.issued_at >= '2026-11-01'
33
+ expect: reject
34
+ codes: [missing_required_filter]
35
+ - id: required-inside-cte-missing
36
+ dialect: postgres
37
+ policy: {required_filters: {invoices: [issued_at]}}
38
+ sql: WITH recent AS (SELECT * FROM invoices) SELECT SUM(total) FROM recent
39
+ expect: reject
40
+ codes: [missing_required_filter]
41
+ - id: required-inside-cte-present
42
+ dialect: postgres
43
+ policy: {required_filters: {invoices: [issued_at]}}
44
+ sql: >-
45
+ WITH recent AS (SELECT * FROM invoices WHERE issued_at >= '2026-11-01')
46
+ SELECT SUM(total) FROM recent
47
+ expect: allow
48
+ - id: required-filter-in-nested-subquery-does-not-count
49
+ dialect: postgres
50
+ policy: {required_filters: {invoices: [issued_at]}}
51
+ sql: >-
52
+ SELECT SUM(total) FROM invoices
53
+ WHERE id IN (SELECT invoice_id FROM invoice_lines WHERE issued_at >= '2026-11-01')
54
+ expect: reject
55
+ codes: [missing_required_filter]
56
+ note: The predicate inside the subquery filters invoice_lines, not this read of invoices.
57
+ - id: required-every-occurrence
58
+ dialect: postgres
59
+ policy: {required_filters: {invoices: [issued_at]}}
60
+ sql: >-
61
+ SELECT SUM(total) FROM invoices WHERE issued_at >= '2026-11-01'
62
+ UNION ALL SELECT SUM(total) FROM invoices
63
+ expect: reject
64
+ codes: [missing_required_filter]
65
+ - id: required-any-of-the-columns
66
+ dialect: mysql
67
+ policy: {required_filters: {invoices: [issued_at, branch_id]}}
68
+ sql: SELECT SUM(total) FROM invoices WHERE branch_id = 3
69
+ expect: allow
70
+ - id: required-row-filter-does-not-satisfy-it
71
+ dialect: postgres
72
+ policy: {required_filters: {invoices: [branch_id]}}
73
+ sql: SELECT SUM(total) FROM invoices
74
+ expect: reject
75
+ codes: [missing_required_filter]
76
+ note: The row filter on branch_id is injected after this check, so it never counts.
@@ -23,6 +23,7 @@ KEYS = {
23
23
  "context",
24
24
  "note",
25
25
  "pending",
26
+ "policy",
26
27
  }
27
28
  DIALECTS = {
28
29
  "postgres",
@@ -69,7 +70,7 @@ def test_corpus_is_well_formed() -> None:
69
70
  def test_case(case: dict[str, Any]) -> None:
70
71
  if case.get("pending"):
71
72
  pytest.skip(f"pending: {case['pending']}")
72
- guard = Guard(standard_policy(case["dialect"]))
73
+ guard = Guard(standard_policy(case["dialect"], **case.get("policy", {})))
73
74
  result = guard.check(case["sql"], case.get("context", CONTEXT))
74
75
  if case["expect"] == "reject":
75
76
  assert not result.ok, f"accepted: {result.sql}"
@@ -20,6 +20,14 @@ EXAMPLE = Path(__file__).parents[1] / "examples" / "policy.yaml"
20
20
  ({"dialect": "postgres", "tables": "invoices"}, "collection"),
21
21
  ({"dialect": "postgres", "function_policy": "allowlist"}, "allowed_functions"),
22
22
  ({"dialect": "postgres", "function_policy": "maybe"}, "function_policy"),
23
+ ({"dialect": "postgres", "max_joins": -1}, "max_joins"),
24
+ ({"dialect": "postgres", "max_joins": True}, "max_joins"),
25
+ ({"dialect": "postgres", "max_subquery_depth": 1.5}, "max_subquery_depth"),
26
+ ({"dialect": "postgres", "forbid_cartesian": "yes"}, "forbid_cartesian"),
27
+ ({"dialect": "postgres", "required_filters": ["invoices"]}, "required_filters"),
28
+ ({"dialect": "postgres", "required_filters": {"invoices": []}}, "at least one column"),
29
+ ({"dialect": "postgres", "required_filters": {"invoices": "issued_at"}}, "collection"),
30
+ ({"dialect": "postgres", "output_dialect": ""}, "output_dialect"),
23
31
  ],
24
32
  )
25
33
  def test_invalid_policy_values(kwargs: dict[str, object], message: str) -> None:
@@ -74,3 +82,28 @@ def test_from_file_json(tmp_path: Path) -> None:
74
82
  file.write_text(json.dumps({"dialect": "sqlite", "tables": ["t"], "max_rows": 5}))
75
83
  result = Guard(Policy.from_file(file)).check("SELECT a FROM t")
76
84
  assert result.ok and result.sql == "SELECT a FROM t LIMIT 5"
85
+
86
+
87
+ def test_unknown_output_dialect() -> None:
88
+ with pytest.raises(PolicyError, match="unknown output_dialect"):
89
+ Guard(Policy(dialect="postgres", output_dialect="not-a-dialect"))
90
+
91
+
92
+ def test_required_filter_for_table_outside_allowlist() -> None:
93
+ with pytest.raises(PolicyError, match="not in the allowed tables"):
94
+ Guard(standard_policy(required_filters={"secrets": ["created_at"]}))
95
+
96
+
97
+ def test_new_options_from_dict() -> None:
98
+ policy = Policy.from_dict(
99
+ {
100
+ "dialect": "postgres",
101
+ "max_joins": 3,
102
+ "max_subquery_depth": 2,
103
+ "forbid_cartesian": True,
104
+ "required_filters": {"invoices": ["issued_at"]},
105
+ "output_dialect": "tsql",
106
+ }
107
+ )
108
+ assert policy.required_filters["invoices"] == frozenset({"issued_at"})
109
+ assert Guard(policy).check("SELECT 1 AS x").sql == "SELECT TOP 1000 1 AS x"
@@ -106,3 +106,54 @@ def test_no_limit_when_disabled() -> None:
106
106
  def test_pretty_output() -> None:
107
107
  result = Guard(Policy(dialect="postgres", tables={"t"}), pretty=True).check("SELECT id FROM t")
108
108
  assert result.sql is not None and "\n" in result.sql
109
+
110
+
111
+ @pytest.mark.parametrize(
112
+ ("dialect", "output", "sql", "expected"),
113
+ [
114
+ (
115
+ "postgres",
116
+ "tsql",
117
+ "SELECT id, total FROM invoices ORDER BY total DESC",
118
+ # sqlglot keeps PostgreSQL's NULLS FIRST for DESC with a CASE in SQL Server.
119
+ "SELECT TOP 1000 id, total FROM (SELECT * FROM invoices WHERE branch_id IN (1, 2))"
120
+ " AS invoices ORDER BY CASE WHEN total IS NULL THEN 1 ELSE 0 END DESC, total DESC",
121
+ ),
122
+ (
123
+ "postgres",
124
+ "oracle",
125
+ "SELECT id FROM invoices WHERE issued_at >= CURRENT_DATE - INTERVAL '7 days'",
126
+ "FETCH FIRST 1000 ROWS ONLY",
127
+ ),
128
+ (
129
+ "mysql",
130
+ "postgres",
131
+ "SELECT `id`, IFNULL(total, 0) AS total FROM invoices",
132
+ 'SELECT "id", COALESCE(total, 0) AS total FROM (SELECT * FROM invoices WHERE branch_id'
133
+ " IN (1, 2)) AS invoices LIMIT 1000",
134
+ ),
135
+ ],
136
+ )
137
+ def test_output_dialect(dialect: str, output: str, sql: str, expected: str) -> None:
138
+ result = Guard(standard_policy(dialect, output_dialect=output)).check(sql, CONTEXT)
139
+ assert result.ok, result.messages
140
+ assert result.sql is not None
141
+ assert expected in result.sql
142
+
143
+
144
+ def test_output_dialect_keeps_parsing_in_the_input_dialect() -> None:
145
+ # T-SQL syntax is not valid input when the policy reads PostgreSQL.
146
+ guard = Guard(standard_policy("postgres", output_dialect="tsql"))
147
+ result = guard.check("SELECT TOP 5 id FROM invoices", CONTEXT)
148
+ assert result.codes == {ViolationCode.PARSE_ERROR}
149
+
150
+
151
+ def test_new_codes_have_spanish_messages() -> None:
152
+ guard = Guard(
153
+ standard_policy(max_joins=0, required_filters={"invoices": ["issued_at"]}), language="es"
154
+ )
155
+ result = guard.check(
156
+ "SELECT b.name FROM invoices i JOIN branches b ON b.id = i.branch_id", CONTEXT
157
+ )
158
+ assert result.codes == {ViolationCode.TOO_COMPLEX, ViolationCode.MISSING_REQUIRED_FILTER}
159
+ assert all("consulta" in m or "Leer" in m for m in result.messages)
File without changes
File without changes