sqlguardllm 0.1.0a1__py3-none-any.whl
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.
- sqlguard/__init__.py +35 -0
- sqlguard/_compiled.py +37 -0
- sqlguard/_names.py +104 -0
- sqlguard/data/__init__.py +1 -0
- sqlguard/data/denied_functions.py +127 -0
- sqlguard/guard.py +182 -0
- sqlguard/messages.py +64 -0
- sqlguard/policy.py +118 -0
- sqlguard/py.typed +0 -0
- sqlguard/result.py +78 -0
- sqlguard/rules/__init__.py +1 -0
- sqlguard/rules/columns.py +90 -0
- sqlguard/rules/functions.py +55 -0
- sqlguard/rules/limit.py +40 -0
- sqlguard/rules/row_filters.py +162 -0
- sqlguard/rules/sources.py +67 -0
- sqlguard/rules/statement.py +97 -0
- sqlguardllm-0.1.0a1.dist-info/METADATA +84 -0
- sqlguardllm-0.1.0a1.dist-info/RECORD +21 -0
- sqlguardllm-0.1.0a1.dist-info/WHEEL +4 -0
- sqlguardllm-0.1.0a1.dist-info/licenses/LICENSE +202 -0
sqlguard/result.py
ADDED
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
"""Results, violation codes and errors of sqlguard."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from dataclasses import dataclass, field
|
|
6
|
+
from enum import Enum
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
class ViolationCode(str, Enum):
|
|
10
|
+
"""Stable reasons why a query is rejected. Codes never change within a major version."""
|
|
11
|
+
|
|
12
|
+
PARSE_ERROR = "parse_error"
|
|
13
|
+
EMPTY_STATEMENT = "empty_statement"
|
|
14
|
+
MULTIPLE_STATEMENTS = "multiple_statements"
|
|
15
|
+
NOT_A_QUERY = "not_a_query"
|
|
16
|
+
WRITE_OPERATION = "write_operation"
|
|
17
|
+
ROW_LOCK = "row_lock"
|
|
18
|
+
TABLE_NOT_ALLOWED = "table_not_allowed"
|
|
19
|
+
HIDDEN_COLUMN = "hidden_column"
|
|
20
|
+
DENIED_FUNCTION = "denied_function"
|
|
21
|
+
MISSING_CONTEXT = "missing_context"
|
|
22
|
+
INVALID_CONTEXT = "invalid_context"
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
@dataclass(frozen=True)
|
|
26
|
+
class Violation:
|
|
27
|
+
"""One reason a query was rejected.
|
|
28
|
+
|
|
29
|
+
Attributes:
|
|
30
|
+
code: Stable machine-readable reason.
|
|
31
|
+
message: Human-readable explanation, safe to show to a model or a user.
|
|
32
|
+
detail: The offending SQL fragment or name, when there is one.
|
|
33
|
+
"""
|
|
34
|
+
|
|
35
|
+
code: ViolationCode
|
|
36
|
+
message: str
|
|
37
|
+
detail: str = ""
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
@dataclass(frozen=True)
|
|
41
|
+
class CheckResult:
|
|
42
|
+
"""Outcome of :meth:`sqlguard.Guard.check`.
|
|
43
|
+
|
|
44
|
+
Attributes:
|
|
45
|
+
ok: True when the query may run.
|
|
46
|
+
sql: The rewritten SQL to execute (only when ``ok``).
|
|
47
|
+
tables: Physical tables the query reads, as normalized dotted names.
|
|
48
|
+
applied_filters: Row filters injected, one entry per filtered table occurrence.
|
|
49
|
+
violations: Every reason the query was rejected (empty when ``ok``).
|
|
50
|
+
"""
|
|
51
|
+
|
|
52
|
+
ok: bool
|
|
53
|
+
sql: str | None = None
|
|
54
|
+
tables: frozenset[str] = frozenset()
|
|
55
|
+
applied_filters: tuple[str, ...] = ()
|
|
56
|
+
violations: tuple[Violation, ...] = field(default_factory=tuple)
|
|
57
|
+
|
|
58
|
+
@property
|
|
59
|
+
def codes(self) -> frozenset[ViolationCode]:
|
|
60
|
+
"""The set of violation codes, handy for assertions and branching."""
|
|
61
|
+
return frozenset(v.code for v in self.violations)
|
|
62
|
+
|
|
63
|
+
@property
|
|
64
|
+
def messages(self) -> list[str]:
|
|
65
|
+
"""Human-readable messages of every violation."""
|
|
66
|
+
return [v.message for v in self.violations]
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
class PolicyError(ValueError):
|
|
70
|
+
"""The policy itself is invalid. Raised when a :class:`~sqlguard.Guard` is created."""
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
class GuardViolation(Exception):
|
|
74
|
+
"""Raised by :meth:`sqlguard.Guard.enforce` when a query is rejected."""
|
|
75
|
+
|
|
76
|
+
def __init__(self, violations: tuple[Violation, ...]) -> None:
|
|
77
|
+
self.violations = violations
|
|
78
|
+
super().__init__("; ".join(v.message for v in violations))
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"""The rules of the pipeline described in docs/DESIGN.md."""
|
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
"""Rule 5: hidden columns can't be referenced anywhere, nor reached through ``*``."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from sqlglot import exp
|
|
6
|
+
from sqlglot.optimizer.scope import Scope
|
|
7
|
+
|
|
8
|
+
from sqlguard._compiled import Compiled
|
|
9
|
+
from sqlguard._names import TableName, find, norm, table_name
|
|
10
|
+
from sqlguard.messages import violation
|
|
11
|
+
from sqlguard.result import Violation, ViolationCode
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def _visible_sources(scope: Scope) -> dict[str, exp.Expression | Scope]:
|
|
15
|
+
"""Sources of a scope plus those of enclosing scopes (correlated references)."""
|
|
16
|
+
chain: list[Scope] = []
|
|
17
|
+
current: Scope | None = scope
|
|
18
|
+
while current is not None:
|
|
19
|
+
chain.append(current)
|
|
20
|
+
current = current.parent
|
|
21
|
+
merged: dict[str, exp.Expression | Scope] = {}
|
|
22
|
+
for item in reversed(chain):
|
|
23
|
+
merged.update(item.sources)
|
|
24
|
+
return merged
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def _hidden_sources(
|
|
28
|
+
sources: dict[str, exp.Expression | Scope], compiled: Compiled
|
|
29
|
+
) -> dict[str, tuple[TableName, frozenset[str]]]:
|
|
30
|
+
found: dict[str, tuple[TableName, frozenset[str]]] = {}
|
|
31
|
+
for alias, source in sources.items():
|
|
32
|
+
if isinstance(source, exp.Table) and isinstance(source.this, exp.Identifier):
|
|
33
|
+
entry = find(
|
|
34
|
+
compiled.hidden.keys(),
|
|
35
|
+
table_name(source, compiled.dialect),
|
|
36
|
+
compiled.default_schema,
|
|
37
|
+
)
|
|
38
|
+
if entry is not None:
|
|
39
|
+
found[norm(alias, compiled.dialect)] = (entry, compiled.hidden[entry])
|
|
40
|
+
return found
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def check_columns(scopes: list[Scope], compiled: Compiled) -> list[Violation]:
|
|
44
|
+
"""Reject references to hidden columns, conservatively when a column is unqualified."""
|
|
45
|
+
if not compiled.hidden:
|
|
46
|
+
return []
|
|
47
|
+
lang = compiled.language
|
|
48
|
+
details: list[str] = []
|
|
49
|
+
|
|
50
|
+
for scope in scopes:
|
|
51
|
+
visible = _hidden_sources(_visible_sources(scope), compiled)
|
|
52
|
+
if not visible:
|
|
53
|
+
continue
|
|
54
|
+
local = _hidden_sources(dict(scope.sources), compiled)
|
|
55
|
+
all_hidden = frozenset().union(*(cols for _, cols in visible.values()))
|
|
56
|
+
expression = scope.expression
|
|
57
|
+
|
|
58
|
+
if isinstance(expression, exp.Select):
|
|
59
|
+
for projection in expression.expressions:
|
|
60
|
+
if isinstance(projection, exp.Star) and local:
|
|
61
|
+
details.append(f"* over {', '.join(str(t) for t, _ in local.values())}")
|
|
62
|
+
elif isinstance(projection, exp.Column) and isinstance(projection.this, exp.Star):
|
|
63
|
+
qualifier = (
|
|
64
|
+
norm(projection.args["table"], compiled.dialect) if projection.table else ""
|
|
65
|
+
)
|
|
66
|
+
if qualifier in visible:
|
|
67
|
+
details.append(f"{projection.table}.*")
|
|
68
|
+
for join in expression.args.get("joins") or []:
|
|
69
|
+
for ident in join.args.get("using") or []:
|
|
70
|
+
if norm(ident, compiled.dialect) in all_hidden:
|
|
71
|
+
details.append(f"USING ({ident.name})")
|
|
72
|
+
if str(join.args.get("method") or "").upper() == "NATURAL":
|
|
73
|
+
details.append("NATURAL JOIN over a table with hidden columns")
|
|
74
|
+
|
|
75
|
+
for column in scope.columns:
|
|
76
|
+
if not isinstance(column.this, exp.Identifier):
|
|
77
|
+
continue
|
|
78
|
+
name = norm(column.this, compiled.dialect)
|
|
79
|
+
if column.table:
|
|
80
|
+
qualifier = norm(column.args["table"], compiled.dialect)
|
|
81
|
+
if qualifier in visible and name in visible[qualifier][1]:
|
|
82
|
+
details.append(f"{visible[qualifier][0]}.{name}")
|
|
83
|
+
elif name in all_hidden:
|
|
84
|
+
owners = [str(t) for t, cols in visible.values() if name in cols]
|
|
85
|
+
details.append(f"{owners[0]}.{name}" if owners else name)
|
|
86
|
+
elif name in visible:
|
|
87
|
+
details.append(f"{name} (whole-row reference to {visible[name][0]})")
|
|
88
|
+
|
|
89
|
+
unique = list(dict.fromkeys(details))
|
|
90
|
+
return [violation(ViolationCode.HIDDEN_COLUMN, detail, lang) for detail in unique]
|
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
"""Rule 6: denied functions (default) or only allowlisted functions."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from sqlglot import exp
|
|
6
|
+
|
|
7
|
+
from sqlguard._compiled import Compiled
|
|
8
|
+
from sqlguard.messages import violation
|
|
9
|
+
from sqlguard.result import Violation, ViolationCode
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
def function_names(node: exp.Func, dialect_name: str) -> set[str]:
|
|
13
|
+
"""Every lowercase name a call may be known by, including qualified forms.
|
|
14
|
+
|
|
15
|
+
``SYS.DBMS_PIPE.RECEIVE_MESSAGE(...)`` yields ``receive_message``,
|
|
16
|
+
``dbms_pipe.receive_message`` and ``sys.dbms_pipe.receive_message``.
|
|
17
|
+
"""
|
|
18
|
+
base = node.name if isinstance(node, exp.Anonymous) else type(node).sql_name()
|
|
19
|
+
base = base.lower()
|
|
20
|
+
names = {base}
|
|
21
|
+
parent = node.parent
|
|
22
|
+
if isinstance(parent, exp.Dot) and parent.expression is node:
|
|
23
|
+
parts = (
|
|
24
|
+
parent.this.sql(dialect=dialect_name)
|
|
25
|
+
.lower()
|
|
26
|
+
.replace('"', "")
|
|
27
|
+
.replace("`", "")
|
|
28
|
+
.split(".")
|
|
29
|
+
)
|
|
30
|
+
for i in range(len(parts)):
|
|
31
|
+
names.add(".".join([*parts[i:], base]))
|
|
32
|
+
return names
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def _is_denied(name: str, denied: frozenset[str]) -> bool:
|
|
36
|
+
if name in denied:
|
|
37
|
+
return True
|
|
38
|
+
return any(entry.endswith(".*") and name.startswith(entry[:-1]) for entry in denied)
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def check_functions(root: exp.Expression, compiled: Compiled) -> list[Violation]:
|
|
42
|
+
"""Reject denied functions, or any function outside the allowlist in allowlist mode."""
|
|
43
|
+
details: list[str] = []
|
|
44
|
+
for node in root.find_all(exp.Func):
|
|
45
|
+
names = function_names(node, compiled.dialect_name)
|
|
46
|
+
display = max(names, key=len)
|
|
47
|
+
if compiled.allowed is not None:
|
|
48
|
+
if not names & compiled.allowed:
|
|
49
|
+
details.append(display)
|
|
50
|
+
elif any(_is_denied(name, compiled.denied) for name in names):
|
|
51
|
+
details.append(display)
|
|
52
|
+
return [
|
|
53
|
+
violation(ViolationCode.DENIED_FUNCTION, detail, compiled.language)
|
|
54
|
+
for detail in dict.fromkeys(details)
|
|
55
|
+
]
|
sqlguard/rules/limit.py
ADDED
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
"""Rule 8: bound the rows the outermost query returns."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from sqlglot import exp
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
def _literal_int(node: exp.Expression | None) -> int | None:
|
|
9
|
+
if isinstance(node, exp.Literal) and node.is_int:
|
|
10
|
+
return int(node.name)
|
|
11
|
+
return None
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def apply_limit(root: exp.Expression, max_rows: int | None) -> exp.Expression:
|
|
15
|
+
"""Add, lower or replace the outermost limit. Set operations are wrapped first."""
|
|
16
|
+
if max_rows is None:
|
|
17
|
+
return root
|
|
18
|
+
if not isinstance(root, exp.Select):
|
|
19
|
+
# UNION / INTERSECT / EXCEPT: limit the combined result, portable across dialects.
|
|
20
|
+
wrapped = exp.select("*").from_(
|
|
21
|
+
exp.Subquery(this=root, alias=exp.TableAlias(this=exp.to_identifier("sqlguard_rows")))
|
|
22
|
+
)
|
|
23
|
+
return wrapped.limit(max_rows, copy=False)
|
|
24
|
+
|
|
25
|
+
current = root.args.get("limit")
|
|
26
|
+
if current is None:
|
|
27
|
+
return root.limit(max_rows, copy=False)
|
|
28
|
+
if isinstance(current, exp.Limit):
|
|
29
|
+
value = _literal_int(current.expression)
|
|
30
|
+
if value is None or value > max_rows:
|
|
31
|
+
current.set("expression", exp.Literal.number(max_rows))
|
|
32
|
+
return root
|
|
33
|
+
if isinstance(current, exp.Fetch) and not current.args.get("percent"):
|
|
34
|
+
value = _literal_int(current.args.get("count"))
|
|
35
|
+
if value is None or value > max_rows:
|
|
36
|
+
current.set("count", exp.Literal.number(max_rows))
|
|
37
|
+
return root
|
|
38
|
+
# Anything else (percent limits, unknown forms): replace with a plain limit.
|
|
39
|
+
root.set("limit", None)
|
|
40
|
+
return root.limit(max_rows, copy=False)
|
|
@@ -0,0 +1,162 @@
|
|
|
1
|
+
"""Rule 7: row filters injected as derived tables, with context values bound as literals."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import datetime
|
|
6
|
+
import math
|
|
7
|
+
import re
|
|
8
|
+
from collections.abc import Mapping
|
|
9
|
+
from decimal import Decimal
|
|
10
|
+
from typing import Any, cast
|
|
11
|
+
|
|
12
|
+
import sqlglot
|
|
13
|
+
from sqlglot import exp
|
|
14
|
+
from sqlglot.errors import SqlglotError
|
|
15
|
+
|
|
16
|
+
from sqlguard._compiled import Compiled, RowFilter
|
|
17
|
+
from sqlguard._names import TableName, find
|
|
18
|
+
from sqlguard.messages import violation
|
|
19
|
+
from sqlguard.result import PolicyError, Violation, ViolationCode
|
|
20
|
+
from sqlguard.rules.sources import PhysicalRef
|
|
21
|
+
from sqlguard.rules.statement import WRITE_NODES
|
|
22
|
+
|
|
23
|
+
_PLACEHOLDER = re.compile(r"\{([A-Za-z_]\w*(?:\.[A-Za-z_]\w*)*)\}")
|
|
24
|
+
_SCALARS = (bool, int, float, Decimal, str, datetime.date, datetime.datetime)
|
|
25
|
+
_MISSING = object()
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def compile_filter(table: TableName, template: str, dialect_name: str) -> RowFilter:
|
|
29
|
+
"""Parse a filter template once, replacing each placeholder with a sentinel column."""
|
|
30
|
+
placeholders: dict[str, str] = {}
|
|
31
|
+
|
|
32
|
+
def to_sentinel(match: re.Match[str]) -> str:
|
|
33
|
+
sentinel = f"__sqlguard_ph_{len(placeholders)}__"
|
|
34
|
+
placeholders[sentinel] = match.group(1)
|
|
35
|
+
return sentinel
|
|
36
|
+
|
|
37
|
+
text = _PLACEHOLDER.sub(to_sentinel, template)
|
|
38
|
+
try:
|
|
39
|
+
condition = cast(exp.Expression, sqlglot.condition(text, dialect=dialect_name))
|
|
40
|
+
except SqlglotError as exc:
|
|
41
|
+
raise PolicyError(f"row filter for {table} is not valid SQL: {template!r}") from exc
|
|
42
|
+
if condition.find(exp.Select, exp.Subquery):
|
|
43
|
+
raise PolicyError(f"row filter for {table} can't contain subqueries: {template!r}")
|
|
44
|
+
if condition.find(*WRITE_NODES):
|
|
45
|
+
raise PolicyError(f"row filter for {table} can't contain statements: {template!r}")
|
|
46
|
+
|
|
47
|
+
for sentinel, path in placeholders.items():
|
|
48
|
+
columns = [c for c in condition.find_all(exp.Column) if c.name == sentinel]
|
|
49
|
+
identifiers = [i for i in condition.find_all(exp.Identifier) if i.name == sentinel]
|
|
50
|
+
if not columns or any(c.table for c in columns) or len(identifiers) != len(columns):
|
|
51
|
+
raise PolicyError(
|
|
52
|
+
f"placeholder {{{path}}} in the row filter for {table} must be used as a value, "
|
|
53
|
+
"not inside quotes, as a name or as a function"
|
|
54
|
+
)
|
|
55
|
+
return RowFilter(table=table, template=template, condition=condition, placeholders=placeholders)
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
class _ContextError(Exception):
|
|
59
|
+
def __init__(self, code: ViolationCode, detail: str) -> None:
|
|
60
|
+
self.code = code
|
|
61
|
+
self.detail = detail
|
|
62
|
+
super().__init__(detail)
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def _resolve(context: Any, path: str) -> Any:
|
|
66
|
+
current = context
|
|
67
|
+
for part in path.split("."):
|
|
68
|
+
if isinstance(current, Mapping):
|
|
69
|
+
current = current.get(part, _MISSING)
|
|
70
|
+
else:
|
|
71
|
+
current = getattr(current, part, _MISSING)
|
|
72
|
+
if current is _MISSING:
|
|
73
|
+
return _MISSING
|
|
74
|
+
return current
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
def _literal(value: Any, path: str) -> exp.Expression:
|
|
78
|
+
if value is None:
|
|
79
|
+
return exp.null()
|
|
80
|
+
if not isinstance(value, _SCALARS):
|
|
81
|
+
raise _ContextError(ViolationCode.INVALID_CONTEXT, f"{{{path}}} ({type(value).__name__})")
|
|
82
|
+
if isinstance(value, float) and not math.isfinite(value):
|
|
83
|
+
raise _ContextError(ViolationCode.INVALID_CONTEXT, f"{{{path}}} (non-finite number)")
|
|
84
|
+
return cast(exp.Expression, exp.convert(value))
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
def bind(row_filter: RowFilter, context: Any) -> exp.Expression:
|
|
88
|
+
"""The filter condition with every placeholder replaced by safe literals."""
|
|
89
|
+
condition = row_filter.condition.copy()
|
|
90
|
+
for column in list(condition.find_all(exp.Column)):
|
|
91
|
+
path = row_filter.placeholders.get(column.name)
|
|
92
|
+
if path is None:
|
|
93
|
+
continue
|
|
94
|
+
value = _resolve(context, path)
|
|
95
|
+
if value is _MISSING:
|
|
96
|
+
raise _ContextError(ViolationCode.MISSING_CONTEXT, f"{{{path}}}")
|
|
97
|
+
if isinstance(value, (list, tuple, set, frozenset)):
|
|
98
|
+
items = sorted(value, key=repr) if isinstance(value, (set, frozenset)) else list(value)
|
|
99
|
+
literals = [_literal(item, path) for item in items] or [exp.null()]
|
|
100
|
+
parent = column.parent
|
|
101
|
+
if not (isinstance(parent, exp.In) and column.arg_key == "expressions"):
|
|
102
|
+
raise _ContextError(
|
|
103
|
+
ViolationCode.INVALID_CONTEXT,
|
|
104
|
+
f"{{{path}}} (a list can only be used inside IN (...))",
|
|
105
|
+
)
|
|
106
|
+
current = list(parent.expressions)
|
|
107
|
+
index = next(i for i, node in enumerate(current) if node is column)
|
|
108
|
+
parent.set("expressions", [*current[:index], *literals, *current[index + 1 :]])
|
|
109
|
+
else:
|
|
110
|
+
column.replace(_literal(value, path))
|
|
111
|
+
return condition
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
def apply_filters(
|
|
115
|
+
refs: list[PhysicalRef], compiled: Compiled, context: Any
|
|
116
|
+
) -> tuple[list[str], list[Violation]]:
|
|
117
|
+
"""Replace each filtered table occurrence with a filtered derived table."""
|
|
118
|
+
if not compiled.filters:
|
|
119
|
+
return [], []
|
|
120
|
+
lang = compiled.language
|
|
121
|
+
bound: dict[TableName, exp.Expression] = {}
|
|
122
|
+
problems: list[Violation] = []
|
|
123
|
+
targets: list[tuple[PhysicalRef, TableName]] = []
|
|
124
|
+
|
|
125
|
+
for ref in refs:
|
|
126
|
+
entry = find(compiled.filters.keys(), ref.name, compiled.default_schema)
|
|
127
|
+
if entry is None:
|
|
128
|
+
continue
|
|
129
|
+
if entry not in bound:
|
|
130
|
+
try:
|
|
131
|
+
bound[entry] = bind(compiled.filters[entry], context)
|
|
132
|
+
except _ContextError as problem:
|
|
133
|
+
problems.append(violation(problem.code, problem.detail, lang))
|
|
134
|
+
continue
|
|
135
|
+
if ref.table.args.get("laterals") or ref.table.args.get("joins"):
|
|
136
|
+
problems.append(
|
|
137
|
+
violation(ViolationCode.TABLE_NOT_ALLOWED, f"{ref.name} (unsupported syntax)", lang)
|
|
138
|
+
)
|
|
139
|
+
continue
|
|
140
|
+
targets.append((ref, entry))
|
|
141
|
+
|
|
142
|
+
if problems:
|
|
143
|
+
return [], list({(v.code, v.detail): v for v in problems}.values())
|
|
144
|
+
|
|
145
|
+
applied: list[str] = []
|
|
146
|
+
for ref, entry in targets:
|
|
147
|
+
table = ref.table
|
|
148
|
+
condition = bound[entry].copy()
|
|
149
|
+
inner = table.copy()
|
|
150
|
+
for key in ("alias", "pivots", "sample"):
|
|
151
|
+
inner.set(key, None)
|
|
152
|
+
alias = table.args.get("alias")
|
|
153
|
+
new_alias = alias.copy() if alias is not None else exp.TableAlias(this=table.this.copy())
|
|
154
|
+
derived = exp.Subquery(
|
|
155
|
+
this=exp.select("*").from_(inner).where(condition),
|
|
156
|
+
alias=new_alias,
|
|
157
|
+
)
|
|
158
|
+
if table.args.get("pivots"):
|
|
159
|
+
derived.set("pivots", [p.copy() for p in table.args["pivots"]])
|
|
160
|
+
table.replace(derived)
|
|
161
|
+
applied.append(f"{ref.name}: {condition.sql(dialect=compiled.dialect_name)}")
|
|
162
|
+
return applied, []
|
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
"""Rule 4: every physical table must be allowlisted; table functions are rejected."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from dataclasses import dataclass
|
|
6
|
+
|
|
7
|
+
from sqlglot import exp
|
|
8
|
+
from sqlglot.optimizer.scope import Scope
|
|
9
|
+
|
|
10
|
+
from sqlguard._compiled import Compiled
|
|
11
|
+
from sqlguard._names import TableName, find, table_name
|
|
12
|
+
from sqlguard.messages import violation
|
|
13
|
+
from sqlguard.result import Violation, ViolationCode
|
|
14
|
+
|
|
15
|
+
_DUAL_DIALECTS = frozenset({"oracle", "mysql"})
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
@dataclass(frozen=True)
|
|
19
|
+
class PhysicalRef:
|
|
20
|
+
"""A reference to an allowlisted physical table, in the scope where it appears."""
|
|
21
|
+
|
|
22
|
+
table: exp.Table
|
|
23
|
+
name: TableName
|
|
24
|
+
scope: Scope
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def collect_sources(
|
|
28
|
+
root: exp.Expression, scopes: list[Scope], compiled: Compiled
|
|
29
|
+
) -> tuple[list[PhysicalRef], list[Violation]]:
|
|
30
|
+
"""Classify every table reference: CTE, derived table, allowed table, or violation."""
|
|
31
|
+
lang = compiled.language
|
|
32
|
+
refs: list[PhysicalRef] = []
|
|
33
|
+
violations: list[Violation] = []
|
|
34
|
+
handled: set[int] = set()
|
|
35
|
+
|
|
36
|
+
for scope in scopes:
|
|
37
|
+
for table in scope.tables:
|
|
38
|
+
handled.add(id(table))
|
|
39
|
+
source = scope.sources.get(table.alias_or_name)
|
|
40
|
+
if isinstance(source, Scope):
|
|
41
|
+
continue # a CTE or derived table: its own scope is checked separately
|
|
42
|
+
if not isinstance(table.this, exp.Identifier):
|
|
43
|
+
fragment = table.this.sql(dialect=compiled.dialect_name)[:80]
|
|
44
|
+
violations.append(violation(ViolationCode.TABLE_NOT_ALLOWED, fragment, lang))
|
|
45
|
+
continue
|
|
46
|
+
name = table_name(table, compiled.dialect)
|
|
47
|
+
if (
|
|
48
|
+
name.name.lower() == "dual"
|
|
49
|
+
and name.db is None
|
|
50
|
+
and compiled.dialect_name in _DUAL_DIALECTS
|
|
51
|
+
):
|
|
52
|
+
continue
|
|
53
|
+
if (
|
|
54
|
+
compiled.tables is not None
|
|
55
|
+
and find(compiled.tables, name, compiled.default_schema) is None
|
|
56
|
+
):
|
|
57
|
+
violations.append(violation(ViolationCode.TABLE_NOT_ALLOWED, str(name), lang))
|
|
58
|
+
continue
|
|
59
|
+
refs.append(PhysicalRef(table=table, name=name, scope=scope))
|
|
60
|
+
|
|
61
|
+
# Fail closed: any table node the scope analysis didn't classify is rejected.
|
|
62
|
+
for table in root.find_all(exp.Table):
|
|
63
|
+
if id(table) not in handled:
|
|
64
|
+
fragment = table.sql(dialect=compiled.dialect_name)[:80]
|
|
65
|
+
violations.append(violation(ViolationCode.TABLE_NOT_ALLOWED, fragment, lang))
|
|
66
|
+
|
|
67
|
+
return refs, violations
|
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
"""Rules 2 and 3: one statement, a query root, and no write anywhere in the tree."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from sqlglot import exp
|
|
6
|
+
|
|
7
|
+
from sqlguard.messages import violation
|
|
8
|
+
from sqlguard.result import Violation, ViolationCode
|
|
9
|
+
|
|
10
|
+
_WRITE_NODE_NAMES = (
|
|
11
|
+
"Insert",
|
|
12
|
+
"Update",
|
|
13
|
+
"Delete",
|
|
14
|
+
"Merge",
|
|
15
|
+
"Into",
|
|
16
|
+
"Create",
|
|
17
|
+
"Drop",
|
|
18
|
+
"Alter",
|
|
19
|
+
"AlterTable",
|
|
20
|
+
"TruncateTable",
|
|
21
|
+
"Copy",
|
|
22
|
+
"Grant",
|
|
23
|
+
"Revoke",
|
|
24
|
+
"Command",
|
|
25
|
+
"Execute",
|
|
26
|
+
"Attach",
|
|
27
|
+
"Detach",
|
|
28
|
+
"Pragma",
|
|
29
|
+
"Set",
|
|
30
|
+
"Use",
|
|
31
|
+
"Transaction",
|
|
32
|
+
"Commit",
|
|
33
|
+
"Rollback",
|
|
34
|
+
"Kill",
|
|
35
|
+
"LoadData",
|
|
36
|
+
"Refresh",
|
|
37
|
+
"Cache",
|
|
38
|
+
"Uncache",
|
|
39
|
+
"Analyze",
|
|
40
|
+
)
|
|
41
|
+
|
|
42
|
+
WRITE_NODES: tuple[type[exp.Expression], ...] = tuple(
|
|
43
|
+
node
|
|
44
|
+
for node in (getattr(exp, name, None) for name in _WRITE_NODE_NAMES)
|
|
45
|
+
if isinstance(node, type) and issubclass(node, exp.Expression)
|
|
46
|
+
)
|
|
47
|
+
|
|
48
|
+
QUERY_ROOTS: tuple[type[exp.Expression], ...] = (exp.Select, exp.Union, exp.Intersect, exp.Except)
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def _unwrap(node: exp.Expression) -> exp.Expression:
|
|
52
|
+
while isinstance(node, (exp.Subquery, exp.Paren)) and isinstance(node.this, exp.Expression):
|
|
53
|
+
node = node.this
|
|
54
|
+
return node
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def describe(node: exp.Expression) -> str:
|
|
58
|
+
"""A short, readable name for a statement or node (``DELETE``, ``SELECT ... INTO``)."""
|
|
59
|
+
if isinstance(node, exp.Command):
|
|
60
|
+
return str(node.this).upper()
|
|
61
|
+
if isinstance(node, exp.Into):
|
|
62
|
+
return "SELECT ... INTO"
|
|
63
|
+
name = type(node).__name__
|
|
64
|
+
return {"TruncateTable": "TRUNCATE", "LoadData": "LOAD DATA"}.get(name, name.upper())
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def check_statements(
|
|
68
|
+
statements: list[exp.Expression], language: str
|
|
69
|
+
) -> tuple[exp.Expression | None, list[Violation]]:
|
|
70
|
+
"""Validate the statements; return the query root when there is exactly one valid query."""
|
|
71
|
+
violations: list[Violation] = []
|
|
72
|
+
if not statements:
|
|
73
|
+
return None, [violation(ViolationCode.EMPTY_STATEMENT, "", language)]
|
|
74
|
+
if len(statements) > 1:
|
|
75
|
+
violations.append(
|
|
76
|
+
violation(ViolationCode.MULTIPLE_STATEMENTS, f"{len(statements)} statements", language)
|
|
77
|
+
)
|
|
78
|
+
|
|
79
|
+
for statement in statements:
|
|
80
|
+
root = _unwrap(statement)
|
|
81
|
+
if not isinstance(root, QUERY_ROOTS):
|
|
82
|
+
violations.append(violation(ViolationCode.NOT_A_QUERY, describe(root), language))
|
|
83
|
+
for node in statement.walk():
|
|
84
|
+
if node is root:
|
|
85
|
+
continue
|
|
86
|
+
if isinstance(node, exp.Lock):
|
|
87
|
+
violations.append(
|
|
88
|
+
violation(ViolationCode.ROW_LOCK, node.sql()[:60] or "FOR UPDATE", language)
|
|
89
|
+
)
|
|
90
|
+
elif isinstance(node, WRITE_NODES):
|
|
91
|
+
violations.append(
|
|
92
|
+
violation(ViolationCode.WRITE_OPERATION, describe(node), language)
|
|
93
|
+
)
|
|
94
|
+
|
|
95
|
+
if violations:
|
|
96
|
+
return None, violations
|
|
97
|
+
return _unwrap(statements[0]), []
|
|
@@ -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.
|