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/__init__.py
ADDED
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
"""sqlguard: the SQL firewall for LLM apps.
|
|
2
|
+
|
|
3
|
+
Validate SQL written by an untrusted source and rewrite it so it is a single read-only query
|
|
4
|
+
over allowlisted tables and columns, filtered per user and bounded in rows::
|
|
5
|
+
|
|
6
|
+
from sqlguard import Guard, Policy
|
|
7
|
+
|
|
8
|
+
guard = Guard(Policy(dialect="postgres", tables={"invoices"}, max_rows=1000))
|
|
9
|
+
result = guard.check("SELECT * FROM invoices")
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
from __future__ import annotations
|
|
13
|
+
|
|
14
|
+
from importlib.metadata import PackageNotFoundError, version
|
|
15
|
+
|
|
16
|
+
from sqlguard.guard import Guard
|
|
17
|
+
from sqlguard.policy import FunctionPolicy, Policy
|
|
18
|
+
from sqlguard.result import CheckResult, GuardViolation, PolicyError, Violation, ViolationCode
|
|
19
|
+
|
|
20
|
+
try:
|
|
21
|
+
__version__ = version("sqlguardllm")
|
|
22
|
+
except PackageNotFoundError: # pragma: no cover - running from a source tree without install
|
|
23
|
+
__version__ = "0.0.0"
|
|
24
|
+
|
|
25
|
+
__all__ = [
|
|
26
|
+
"CheckResult",
|
|
27
|
+
"FunctionPolicy",
|
|
28
|
+
"Guard",
|
|
29
|
+
"GuardViolation",
|
|
30
|
+
"Policy",
|
|
31
|
+
"PolicyError",
|
|
32
|
+
"Violation",
|
|
33
|
+
"ViolationCode",
|
|
34
|
+
"__version__",
|
|
35
|
+
]
|
sqlguard/_compiled.py
ADDED
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
"""The policy compiled once per Guard, ready for the rules."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from collections.abc import Mapping
|
|
6
|
+
from dataclasses import dataclass
|
|
7
|
+
|
|
8
|
+
from sqlglot import exp
|
|
9
|
+
from sqlglot.dialects.dialect import Dialect
|
|
10
|
+
|
|
11
|
+
from sqlguard._names import TableName
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
@dataclass(frozen=True)
|
|
15
|
+
class RowFilter:
|
|
16
|
+
"""A row filter parsed with sentinel columns in place of its placeholders."""
|
|
17
|
+
|
|
18
|
+
table: TableName
|
|
19
|
+
template: str
|
|
20
|
+
condition: exp.Expression
|
|
21
|
+
placeholders: Mapping[str, str] # sentinel column name -> context path
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
@dataclass(frozen=True)
|
|
25
|
+
class Compiled:
|
|
26
|
+
"""Everything the rules need, normalized for the dialect."""
|
|
27
|
+
|
|
28
|
+
dialect: Dialect
|
|
29
|
+
dialect_name: str
|
|
30
|
+
language: str
|
|
31
|
+
tables: tuple[TableName, ...] | None
|
|
32
|
+
hidden: Mapping[TableName, frozenset[str]]
|
|
33
|
+
filters: Mapping[TableName, RowFilter]
|
|
34
|
+
denied: frozenset[str]
|
|
35
|
+
allowed: frozenset[str] | None
|
|
36
|
+
max_rows: int | None
|
|
37
|
+
default_schema: str | None
|
sqlguard/_names.py
ADDED
|
@@ -0,0 +1,104 @@
|
|
|
1
|
+
"""Table and column names, normalized with each dialect's identifier rules."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from collections.abc import Iterable
|
|
6
|
+
from dataclasses import dataclass
|
|
7
|
+
|
|
8
|
+
from sqlglot import exp
|
|
9
|
+
from sqlglot.dialects.dialect import Dialect
|
|
10
|
+
from sqlglot.errors import SqlglotError
|
|
11
|
+
|
|
12
|
+
from sqlguard.result import PolicyError
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
@dataclass(frozen=True)
|
|
16
|
+
class TableName:
|
|
17
|
+
"""A normalized, possibly qualified table name."""
|
|
18
|
+
|
|
19
|
+
name: str
|
|
20
|
+
db: str | None = None
|
|
21
|
+
catalog: str | None = None
|
|
22
|
+
|
|
23
|
+
def __str__(self) -> str:
|
|
24
|
+
return ".".join(part for part in (self.catalog, self.db, self.name) if part)
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def norm(identifier: exp.Expression | str, dialect: Dialect) -> str:
|
|
28
|
+
"""Normalize an identifier: unquoted ones follow the dialect's case rules."""
|
|
29
|
+
node = (
|
|
30
|
+
identifier if isinstance(identifier, exp.Identifier) else exp.to_identifier(str(identifier))
|
|
31
|
+
)
|
|
32
|
+
normalized = dialect.normalize_identifier(node.copy())
|
|
33
|
+
return normalized.name
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def _part(table: exp.Table, key: str, dialect: Dialect) -> str | None:
|
|
37
|
+
value = table.args.get(key)
|
|
38
|
+
if value is None:
|
|
39
|
+
return None
|
|
40
|
+
if isinstance(value, exp.Identifier):
|
|
41
|
+
return norm(value, dialect)
|
|
42
|
+
return value.name or None
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def table_name(table: exp.Table, dialect: Dialect) -> TableName:
|
|
46
|
+
"""The normalized name of a table reference (its ``this`` must be an identifier)."""
|
|
47
|
+
return TableName(
|
|
48
|
+
name=norm(table.this, dialect),
|
|
49
|
+
db=_part(table, "db", dialect),
|
|
50
|
+
catalog=_part(table, "catalog", dialect),
|
|
51
|
+
)
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def parse_table_entry(entry: str, dialect: Dialect, dialect_name: str) -> TableName:
|
|
55
|
+
"""Parse a policy table entry such as ``"invoices"`` or ``"sales.customers"``."""
|
|
56
|
+
try:
|
|
57
|
+
table = exp.to_table(entry, dialect=dialect_name)
|
|
58
|
+
except SqlglotError as exc:
|
|
59
|
+
raise PolicyError(f"invalid table name in policy: {entry!r}") from exc
|
|
60
|
+
if not isinstance(table.this, exp.Identifier):
|
|
61
|
+
raise PolicyError(f"invalid table name in policy: {entry!r}")
|
|
62
|
+
return table_name(table, dialect)
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def parse_column_entry(entry: str, dialect: Dialect, dialect_name: str) -> tuple[TableName, str]:
|
|
66
|
+
"""Parse a hidden column entry such as ``"customers.email"``."""
|
|
67
|
+
try:
|
|
68
|
+
column = exp.to_column(entry, dialect=dialect_name)
|
|
69
|
+
except SqlglotError as exc:
|
|
70
|
+
raise PolicyError(f"invalid hidden column in policy: {entry!r}") from exc
|
|
71
|
+
if not isinstance(column, exp.Column) or not column.table:
|
|
72
|
+
raise PolicyError(f"hidden columns must be written as table.column, got {entry!r}")
|
|
73
|
+
table = TableName(
|
|
74
|
+
name=norm(column.args["table"], dialect),
|
|
75
|
+
db=norm(column.args["db"], dialect) if column.args.get("db") else None,
|
|
76
|
+
catalog=norm(column.args["catalog"], dialect) if column.args.get("catalog") else None,
|
|
77
|
+
)
|
|
78
|
+
return table, norm(column.this, dialect)
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
def matches(entry: TableName, ref: TableName, default_schema: str | None) -> bool:
|
|
82
|
+
"""Whether a reference in a query is the table named by a policy entry.
|
|
83
|
+
|
|
84
|
+
Unqualified entries only match unqualified references (or references to the default
|
|
85
|
+
schema), so allowing ``invoices`` never allows ``other_schema.invoices``.
|
|
86
|
+
"""
|
|
87
|
+
if entry.name != ref.name:
|
|
88
|
+
return False
|
|
89
|
+
if (entry.catalog is not None or ref.catalog is not None) and entry.catalog != ref.catalog:
|
|
90
|
+
return False
|
|
91
|
+
ref_db = ref.db if ref.db is not None else default_schema
|
|
92
|
+
if entry.db is None:
|
|
93
|
+
return ref.db is None or (default_schema is not None and ref.db == default_schema)
|
|
94
|
+
return entry.db == ref_db
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
def find(
|
|
98
|
+
entries: Iterable[TableName], ref: TableName, default_schema: str | None
|
|
99
|
+
) -> TableName | None:
|
|
100
|
+
"""The first policy entry that names ``ref``."""
|
|
101
|
+
for entry in entries:
|
|
102
|
+
if matches(entry, ref, default_schema):
|
|
103
|
+
return entry
|
|
104
|
+
return None
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"""Built-in data used by the rules."""
|
|
@@ -0,0 +1,127 @@
|
|
|
1
|
+
"""Functions denied by default.
|
|
2
|
+
|
|
3
|
+
Entries are lowercase. ``package.*`` denies every function of a package. Functions that read
|
|
4
|
+
files, call the network, sleep, run commands, execute SQL passed as a string, or change server
|
|
5
|
+
state are denied. Contributions welcome: add the function with a corpus case that rejects it.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
# Denied in every dialect: these names are dangerous wherever they exist.
|
|
11
|
+
COMMON: frozenset[str] = frozenset(
|
|
12
|
+
{
|
|
13
|
+
"pg_sleep",
|
|
14
|
+
"sleep",
|
|
15
|
+
"benchmark",
|
|
16
|
+
"load_file",
|
|
17
|
+
"pg_read_file",
|
|
18
|
+
"pg_read_binary_file",
|
|
19
|
+
"pg_ls_dir",
|
|
20
|
+
"xp_cmdshell",
|
|
21
|
+
"openrowset",
|
|
22
|
+
"opendatasource",
|
|
23
|
+
"openquery",
|
|
24
|
+
"dblink",
|
|
25
|
+
"dblink_exec",
|
|
26
|
+
"load_extension",
|
|
27
|
+
"readfile",
|
|
28
|
+
"writefile",
|
|
29
|
+
"lo_import",
|
|
30
|
+
"lo_export",
|
|
31
|
+
"utl_http.*",
|
|
32
|
+
"utl_file.*",
|
|
33
|
+
"dbms_pipe.*",
|
|
34
|
+
}
|
|
35
|
+
)
|
|
36
|
+
|
|
37
|
+
BY_DIALECT: dict[str, frozenset[str]] = {
|
|
38
|
+
"postgres": frozenset(
|
|
39
|
+
{
|
|
40
|
+
"pg_stat_file",
|
|
41
|
+
"pg_ls_logdir",
|
|
42
|
+
"pg_ls_waldir",
|
|
43
|
+
"lo_get",
|
|
44
|
+
"lo_unlink",
|
|
45
|
+
"pg_terminate_backend",
|
|
46
|
+
"pg_cancel_backend",
|
|
47
|
+
"pg_reload_conf",
|
|
48
|
+
"pg_rotate_logfile",
|
|
49
|
+
"pg_logical_emit_message",
|
|
50
|
+
"set_config",
|
|
51
|
+
"nextval",
|
|
52
|
+
"setval",
|
|
53
|
+
"pg_advisory_lock",
|
|
54
|
+
"pg_advisory_xact_lock",
|
|
55
|
+
"pg_try_advisory_lock",
|
|
56
|
+
"dblink_connect",
|
|
57
|
+
"dblink_open",
|
|
58
|
+
# These run SQL passed as a string, which would bypass the table allowlist.
|
|
59
|
+
"query_to_xml",
|
|
60
|
+
"query_to_xmlschema",
|
|
61
|
+
"query_to_xml_and_xmlschema",
|
|
62
|
+
"cursor_to_xml",
|
|
63
|
+
"table_to_xml",
|
|
64
|
+
"table_to_xmlschema",
|
|
65
|
+
"table_to_xml_and_xmlschema",
|
|
66
|
+
"schema_to_xml",
|
|
67
|
+
"database_to_xml",
|
|
68
|
+
}
|
|
69
|
+
),
|
|
70
|
+
"mysql": frozenset(
|
|
71
|
+
{
|
|
72
|
+
"get_lock",
|
|
73
|
+
"release_lock",
|
|
74
|
+
"is_free_lock",
|
|
75
|
+
"master_pos_wait",
|
|
76
|
+
"source_pos_wait",
|
|
77
|
+
"sys_exec",
|
|
78
|
+
"sys_eval",
|
|
79
|
+
}
|
|
80
|
+
),
|
|
81
|
+
"tsql": frozenset(
|
|
82
|
+
{"xp_dirtree", "xp_fileexist", "xp_regread", "xp_subdirs", "sp_executesql", "openxml"}
|
|
83
|
+
),
|
|
84
|
+
"oracle": frozenset(
|
|
85
|
+
{
|
|
86
|
+
"dbms_lock.sleep",
|
|
87
|
+
"dbms_session.sleep",
|
|
88
|
+
"dbms_xmlgen.*",
|
|
89
|
+
"dbms_sql.*",
|
|
90
|
+
"dbms_scheduler.*",
|
|
91
|
+
"dbms_java.*",
|
|
92
|
+
"utl_inaddr.*",
|
|
93
|
+
"utl_tcp.*",
|
|
94
|
+
"utl_smtp.*",
|
|
95
|
+
"httpuritype",
|
|
96
|
+
}
|
|
97
|
+
),
|
|
98
|
+
"sqlite": frozenset({"edit", "fts3_tokenizer"}),
|
|
99
|
+
"duckdb": frozenset(
|
|
100
|
+
{
|
|
101
|
+
"read_csv",
|
|
102
|
+
"read_csv_auto",
|
|
103
|
+
"read_parquet",
|
|
104
|
+
"parquet_scan",
|
|
105
|
+
"read_json",
|
|
106
|
+
"read_json_auto",
|
|
107
|
+
"read_ndjson",
|
|
108
|
+
"read_text",
|
|
109
|
+
"read_blob",
|
|
110
|
+
"glob",
|
|
111
|
+
"sniff_csv",
|
|
112
|
+
"query",
|
|
113
|
+
"query_table",
|
|
114
|
+
"getenv",
|
|
115
|
+
"sqlite_scan",
|
|
116
|
+
"postgres_scan",
|
|
117
|
+
"mysql_scan",
|
|
118
|
+
"iceberg_scan",
|
|
119
|
+
"delta_scan",
|
|
120
|
+
}
|
|
121
|
+
),
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
def default_denylist(dialect: str) -> frozenset[str]:
|
|
126
|
+
"""The built-in denylist for a dialect."""
|
|
127
|
+
return COMMON | BY_DIALECT.get(dialect, frozenset())
|
sqlguard/guard.py
ADDED
|
@@ -0,0 +1,182 @@
|
|
|
1
|
+
"""The Guard: compile a policy once, then check and rewrite SQL."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import functools
|
|
6
|
+
from collections.abc import Callable, Mapping
|
|
7
|
+
from typing import Any, TypeVar, cast
|
|
8
|
+
|
|
9
|
+
import sqlglot
|
|
10
|
+
from sqlglot import exp
|
|
11
|
+
from sqlglot.dialects.dialect import Dialect
|
|
12
|
+
from sqlglot.errors import SqlglotError
|
|
13
|
+
from sqlglot.optimizer.scope import traverse_scope
|
|
14
|
+
|
|
15
|
+
from sqlguard._compiled import Compiled, RowFilter
|
|
16
|
+
from sqlguard._names import TableName, find, norm, parse_column_entry, parse_table_entry
|
|
17
|
+
from sqlguard.data.denied_functions import default_denylist
|
|
18
|
+
from sqlguard.messages import LANGUAGES, violation
|
|
19
|
+
from sqlguard.policy import Policy
|
|
20
|
+
from sqlguard.result import CheckResult, GuardViolation, PolicyError, Violation, ViolationCode
|
|
21
|
+
from sqlguard.rules.columns import check_columns
|
|
22
|
+
from sqlguard.rules.functions import check_functions
|
|
23
|
+
from sqlguard.rules.limit import apply_limit
|
|
24
|
+
from sqlguard.rules.row_filters import apply_filters, compile_filter
|
|
25
|
+
from sqlguard.rules.sources import collect_sources
|
|
26
|
+
from sqlguard.rules.statement import check_statements
|
|
27
|
+
|
|
28
|
+
R = TypeVar("R")
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def _first_line(exc: Exception) -> str:
|
|
32
|
+
text = str(exc).strip().splitlines()
|
|
33
|
+
return (text[0] if text else type(exc).__name__)[:200]
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def _compile(policy: Policy, language: str) -> Compiled:
|
|
37
|
+
if language not in LANGUAGES:
|
|
38
|
+
raise PolicyError(f"language must be one of {', '.join(LANGUAGES)}")
|
|
39
|
+
dialect_name = policy.dialect.lower()
|
|
40
|
+
try:
|
|
41
|
+
dialect = Dialect.get_or_raise(dialect_name)
|
|
42
|
+
except (ValueError, SqlglotError) as exc:
|
|
43
|
+
raise PolicyError(f"unknown dialect {policy.dialect!r}") from exc
|
|
44
|
+
|
|
45
|
+
tables = (
|
|
46
|
+
tuple(parse_table_entry(t, dialect, dialect_name) for t in sorted(policy.tables))
|
|
47
|
+
if policy.tables is not None
|
|
48
|
+
else None
|
|
49
|
+
)
|
|
50
|
+
default_schema = norm(policy.default_schema, dialect) if policy.default_schema else None
|
|
51
|
+
|
|
52
|
+
hidden: dict[TableName, set[str]] = {}
|
|
53
|
+
for entry in sorted(policy.hidden_columns):
|
|
54
|
+
table, column = parse_column_entry(entry, dialect, dialect_name)
|
|
55
|
+
hidden.setdefault(table, set()).add(column)
|
|
56
|
+
|
|
57
|
+
filters: dict[TableName, RowFilter] = {}
|
|
58
|
+
for key, template in sorted(policy.row_filters.items()):
|
|
59
|
+
table = parse_table_entry(key, dialect, dialect_name)
|
|
60
|
+
if tables is not None and find(tables, table, default_schema) is None:
|
|
61
|
+
raise PolicyError(f"row filter for {key!r}, which is not in the allowed tables")
|
|
62
|
+
filters[table] = compile_filter(table, template, dialect_name)
|
|
63
|
+
|
|
64
|
+
base = (
|
|
65
|
+
policy.denied_functions
|
|
66
|
+
if policy.denied_functions is not None
|
|
67
|
+
else default_denylist(dialect_name)
|
|
68
|
+
)
|
|
69
|
+
denied = frozenset(name.lower() for name in (*base, *policy.extra_denied_functions))
|
|
70
|
+
allowed = (
|
|
71
|
+
frozenset(name.lower() for name in policy.allowed_functions)
|
|
72
|
+
if policy.function_policy == "allowlist" and policy.allowed_functions is not None
|
|
73
|
+
else None
|
|
74
|
+
)
|
|
75
|
+
return Compiled(
|
|
76
|
+
dialect=dialect,
|
|
77
|
+
dialect_name=dialect_name,
|
|
78
|
+
language=language,
|
|
79
|
+
tables=tables,
|
|
80
|
+
hidden={table: frozenset(columns) for table, columns in hidden.items()},
|
|
81
|
+
filters=filters,
|
|
82
|
+
denied=denied,
|
|
83
|
+
allowed=allowed,
|
|
84
|
+
max_rows=policy.max_rows,
|
|
85
|
+
default_schema=default_schema,
|
|
86
|
+
)
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
class Guard:
|
|
90
|
+
"""Validates and rewrites SQL written by an untrusted source, following a :class:`Policy`.
|
|
91
|
+
|
|
92
|
+
Args:
|
|
93
|
+
policy: What queries may read.
|
|
94
|
+
language: Language of violation messages, ``"en"`` (default) or ``"es"``.
|
|
95
|
+
pretty: Pretty-print the rewritten SQL.
|
|
96
|
+
|
|
97
|
+
Raises:
|
|
98
|
+
PolicyError: If the policy is invalid (checked once, here).
|
|
99
|
+
"""
|
|
100
|
+
|
|
101
|
+
def __init__(self, policy: Policy, *, language: str = "en", pretty: bool = False) -> None:
|
|
102
|
+
self.policy = policy
|
|
103
|
+
self._compiled = _compile(policy, language)
|
|
104
|
+
self._pretty = pretty
|
|
105
|
+
|
|
106
|
+
def check(self, sql: str, context: Mapping[str, Any] | None = None) -> CheckResult:
|
|
107
|
+
"""Validate ``sql`` and, when it is allowed, return the rewritten SQL to execute.
|
|
108
|
+
|
|
109
|
+
Args:
|
|
110
|
+
sql: The SQL written by the model, agent or user.
|
|
111
|
+
context: Values for row-filter placeholders, from the authenticated user, never
|
|
112
|
+
from the model's output. ``{"user": {"branches": [1, 2]}}`` fills
|
|
113
|
+
``{user.branches}``.
|
|
114
|
+
"""
|
|
115
|
+
if not isinstance(sql, str):
|
|
116
|
+
raise TypeError("sql must be a string")
|
|
117
|
+
compiled = self._compiled
|
|
118
|
+
lang = compiled.language
|
|
119
|
+
|
|
120
|
+
try:
|
|
121
|
+
parsed = sqlglot.parse(sql, read=compiled.dialect_name)
|
|
122
|
+
except SqlglotError as exc:
|
|
123
|
+
return self._rejected([violation(ViolationCode.PARSE_ERROR, _first_line(exc), lang)])
|
|
124
|
+
statements = [
|
|
125
|
+
cast(exp.Expression, statement) for statement in parsed if statement is not None
|
|
126
|
+
]
|
|
127
|
+
|
|
128
|
+
root, violations = check_statements(statements, lang)
|
|
129
|
+
if root is None:
|
|
130
|
+
return self._rejected(violations)
|
|
131
|
+
|
|
132
|
+
try:
|
|
133
|
+
scopes = traverse_scope(root)
|
|
134
|
+
except SqlglotError as exc:
|
|
135
|
+
return self._rejected([violation(ViolationCode.PARSE_ERROR, _first_line(exc), lang)])
|
|
136
|
+
|
|
137
|
+
refs, problems = collect_sources(root, scopes, compiled)
|
|
138
|
+
problems += check_columns(scopes, compiled)
|
|
139
|
+
problems += check_functions(root, compiled)
|
|
140
|
+
if problems:
|
|
141
|
+
return self._rejected(problems)
|
|
142
|
+
|
|
143
|
+
applied, problems = apply_filters(refs, compiled, context if context is not None else {})
|
|
144
|
+
if problems:
|
|
145
|
+
return self._rejected(problems)
|
|
146
|
+
|
|
147
|
+
root = apply_limit(root, compiled.max_rows)
|
|
148
|
+
return CheckResult(
|
|
149
|
+
ok=True,
|
|
150
|
+
sql=root.sql(dialect=compiled.dialect_name, pretty=self._pretty),
|
|
151
|
+
tables=frozenset(str(ref.name) for ref in refs),
|
|
152
|
+
applied_filters=tuple(applied),
|
|
153
|
+
)
|
|
154
|
+
|
|
155
|
+
def enforce(self, sql: str, context: Mapping[str, Any] | None = None) -> str:
|
|
156
|
+
"""Like :meth:`check`, but return the safe SQL or raise :class:`GuardViolation`."""
|
|
157
|
+
result = self.check(sql, context)
|
|
158
|
+
if not result.ok or result.sql is None:
|
|
159
|
+
raise GuardViolation(result.violations)
|
|
160
|
+
return result.sql
|
|
161
|
+
|
|
162
|
+
def wrap(
|
|
163
|
+
self,
|
|
164
|
+
execute: Callable[..., R],
|
|
165
|
+
context_fn: Callable[[], Mapping[str, Any] | None] | None = None,
|
|
166
|
+
) -> Callable[..., R]:
|
|
167
|
+
"""Wrap a function whose first argument is SQL so it only ever receives safe SQL.
|
|
168
|
+
|
|
169
|
+
``context_fn`` is called on every call to get the current user's context.
|
|
170
|
+
"""
|
|
171
|
+
|
|
172
|
+
@functools.wraps(execute)
|
|
173
|
+
def guarded(sql: str, *args: Any, **kwargs: Any) -> R:
|
|
174
|
+
context = context_fn() if context_fn is not None else None
|
|
175
|
+
return execute(self.enforce(sql, context), *args, **kwargs)
|
|
176
|
+
|
|
177
|
+
return guarded
|
|
178
|
+
|
|
179
|
+
@staticmethod
|
|
180
|
+
def _rejected(violations: list[Violation]) -> CheckResult:
|
|
181
|
+
unique = tuple({(v.code, v.detail): v for v in violations}.values())
|
|
182
|
+
return CheckResult(ok=False, violations=unique)
|
sqlguard/messages.py
ADDED
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
"""Human-readable violation messages in English and Spanish.
|
|
2
|
+
|
|
3
|
+
Messages never include values from the caller's context: only SQL fragments and names that
|
|
4
|
+
already appear in the query or the policy.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
from sqlguard.result import Violation, ViolationCode
|
|
10
|
+
|
|
11
|
+
LANGUAGES = ("en", "es")
|
|
12
|
+
|
|
13
|
+
_TEMPLATES: dict[ViolationCode, dict[str, str]] = {
|
|
14
|
+
ViolationCode.PARSE_ERROR: {
|
|
15
|
+
"en": "The SQL could not be understood, so it was rejected: {detail}",
|
|
16
|
+
"es": "No se pudo entender el SQL, así que se rechazó: {detail}",
|
|
17
|
+
},
|
|
18
|
+
ViolationCode.EMPTY_STATEMENT: {
|
|
19
|
+
"en": "There is no SQL statement to run",
|
|
20
|
+
"es": "No hay ninguna sentencia SQL para ejecutar",
|
|
21
|
+
},
|
|
22
|
+
ViolationCode.MULTIPLE_STATEMENTS: {
|
|
23
|
+
"en": "Only one statement is allowed, found {detail}",
|
|
24
|
+
"es": "Solo se permite una sentencia y hay {detail}",
|
|
25
|
+
},
|
|
26
|
+
ViolationCode.NOT_A_QUERY: {
|
|
27
|
+
"en": "Only SELECT queries are allowed, not {detail}",
|
|
28
|
+
"es": "Solo se permiten consultas SELECT, no {detail}",
|
|
29
|
+
},
|
|
30
|
+
ViolationCode.WRITE_OPERATION: {
|
|
31
|
+
"en": "The query tries to change data or structure ({detail})",
|
|
32
|
+
"es": "La consulta intenta modificar datos o estructura ({detail})",
|
|
33
|
+
},
|
|
34
|
+
ViolationCode.ROW_LOCK: {
|
|
35
|
+
"en": "Locking rows is not allowed ({detail})",
|
|
36
|
+
"es": "No se permite bloquear filas ({detail})",
|
|
37
|
+
},
|
|
38
|
+
ViolationCode.TABLE_NOT_ALLOWED: {
|
|
39
|
+
"en": "{detail} is not an allowed table",
|
|
40
|
+
"es": "{detail} no es una tabla permitida",
|
|
41
|
+
},
|
|
42
|
+
ViolationCode.HIDDEN_COLUMN: {
|
|
43
|
+
"en": "{detail} is a hidden column",
|
|
44
|
+
"es": "{detail} es una columna oculta",
|
|
45
|
+
},
|
|
46
|
+
ViolationCode.DENIED_FUNCTION: {
|
|
47
|
+
"en": "The function {detail} is not allowed",
|
|
48
|
+
"es": "La función {detail} no está permitida",
|
|
49
|
+
},
|
|
50
|
+
ViolationCode.MISSING_CONTEXT: {
|
|
51
|
+
"en": "A row filter needs {detail}, which was not provided, so nothing ran",
|
|
52
|
+
"es": "Un filtro por fila necesita {detail}, que no se recibió, así que no se ejecutó nada",
|
|
53
|
+
},
|
|
54
|
+
ViolationCode.INVALID_CONTEXT: {
|
|
55
|
+
"en": "The context value {detail} can't be used safely in a row filter",
|
|
56
|
+
"es": "El valor de contexto {detail} no se puede usar con seguridad en un filtro por fila",
|
|
57
|
+
},
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def violation(code: ViolationCode, detail: str = "", language: str = "en") -> Violation:
|
|
62
|
+
"""Build a :class:`Violation` with its message in ``language``."""
|
|
63
|
+
template = _TEMPLATES[code].get(language, _TEMPLATES[code]["en"])
|
|
64
|
+
return Violation(code=code, message=template.format(detail=detail), detail=detail)
|
sqlguard/policy.py
ADDED
|
@@ -0,0 +1,118 @@
|
|
|
1
|
+
"""The policy: what a query may read, for whom, and how much."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import json
|
|
6
|
+
from collections.abc import Collection, Mapping
|
|
7
|
+
from dataclasses import dataclass, field, fields
|
|
8
|
+
from pathlib import Path
|
|
9
|
+
from types import MappingProxyType
|
|
10
|
+
from typing import Any, Literal
|
|
11
|
+
|
|
12
|
+
from sqlguard.result import PolicyError
|
|
13
|
+
|
|
14
|
+
FunctionPolicy = Literal["denylist", "allowlist"]
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def _frozen(value: Collection[str] | None, name: str) -> frozenset[str] | None:
|
|
18
|
+
if value is None:
|
|
19
|
+
return None
|
|
20
|
+
if isinstance(value, str):
|
|
21
|
+
raise PolicyError(f"{name} must be a collection of strings, not a single string")
|
|
22
|
+
items = frozenset(value)
|
|
23
|
+
if not all(isinstance(item, str) and item.strip() for item in items):
|
|
24
|
+
raise PolicyError(f"{name} must contain non-empty strings")
|
|
25
|
+
return items
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
@dataclass(frozen=True)
|
|
29
|
+
class Policy:
|
|
30
|
+
"""What SQL written by an untrusted source may do.
|
|
31
|
+
|
|
32
|
+
Args:
|
|
33
|
+
dialect: Any dialect name sqlglot understands (``"postgres"``, ``"tsql"``, ``"oracle"``…).
|
|
34
|
+
tables: Allowlisted tables, optionally qualified (``"sales.customers"``). ``None`` disables
|
|
35
|
+
the table allowlist, which is not recommended.
|
|
36
|
+
hidden_columns: Columns that may never be referenced, as ``"table.column"``.
|
|
37
|
+
row_filters: Table → boolean SQL expression with ``{context.path}`` placeholders.
|
|
38
|
+
max_rows: Maximum rows a query may return. ``None`` disables the limit.
|
|
39
|
+
default_schema: Schema assumed for unqualified table references.
|
|
40
|
+
denied_functions: Replaces the built-in denylist for the dialect when given.
|
|
41
|
+
extra_denied_functions: Added to the denylist.
|
|
42
|
+
function_policy: ``"denylist"`` (default) or ``"allowlist"``.
|
|
43
|
+
allowed_functions: Functions allowed in ``"allowlist"`` mode.
|
|
44
|
+
"""
|
|
45
|
+
|
|
46
|
+
dialect: str
|
|
47
|
+
tables: Collection[str] | None = None
|
|
48
|
+
hidden_columns: Collection[str] = frozenset()
|
|
49
|
+
row_filters: Mapping[str, str] = field(default_factory=dict)
|
|
50
|
+
max_rows: int | None = 1000
|
|
51
|
+
default_schema: str | None = None
|
|
52
|
+
denied_functions: Collection[str] | None = None
|
|
53
|
+
extra_denied_functions: Collection[str] = frozenset()
|
|
54
|
+
function_policy: FunctionPolicy = "denylist"
|
|
55
|
+
allowed_functions: Collection[str] | None = None
|
|
56
|
+
|
|
57
|
+
def __post_init__(self) -> None:
|
|
58
|
+
if not isinstance(self.dialect, str) or not self.dialect.strip():
|
|
59
|
+
raise PolicyError("dialect must be a non-empty string")
|
|
60
|
+
object.__setattr__(self, "tables", _frozen(self.tables, "tables"))
|
|
61
|
+
object.__setattr__(self, "hidden_columns", _frozen(self.hidden_columns, "hidden_columns"))
|
|
62
|
+
object.__setattr__(
|
|
63
|
+
self, "denied_functions", _frozen(self.denied_functions, "denied_functions")
|
|
64
|
+
)
|
|
65
|
+
object.__setattr__(
|
|
66
|
+
self,
|
|
67
|
+
"extra_denied_functions",
|
|
68
|
+
_frozen(self.extra_denied_functions, "extra_denied_functions"),
|
|
69
|
+
)
|
|
70
|
+
object.__setattr__(
|
|
71
|
+
self, "allowed_functions", _frozen(self.allowed_functions, "allowed_functions")
|
|
72
|
+
)
|
|
73
|
+
if not isinstance(self.row_filters, Mapping) or not all(
|
|
74
|
+
isinstance(k, str) and isinstance(v, str) for k, v in self.row_filters.items()
|
|
75
|
+
):
|
|
76
|
+
raise PolicyError("row_filters must map table names to SQL condition strings")
|
|
77
|
+
object.__setattr__(self, "row_filters", MappingProxyType(dict(self.row_filters)))
|
|
78
|
+
if self.max_rows is not None and (
|
|
79
|
+
isinstance(self.max_rows, bool)
|
|
80
|
+
or not isinstance(self.max_rows, int)
|
|
81
|
+
or self.max_rows <= 0
|
|
82
|
+
):
|
|
83
|
+
raise PolicyError("max_rows must be a positive integer or None")
|
|
84
|
+
if self.function_policy not in ("denylist", "allowlist"):
|
|
85
|
+
raise PolicyError('function_policy must be "denylist" or "allowlist"')
|
|
86
|
+
if self.function_policy == "allowlist" and self.allowed_functions is None:
|
|
87
|
+
raise PolicyError('function_policy="allowlist" requires allowed_functions')
|
|
88
|
+
|
|
89
|
+
@classmethod
|
|
90
|
+
def from_dict(cls, data: Mapping[str, Any]) -> Policy:
|
|
91
|
+
"""Build a policy from a mapping, rejecting unknown keys."""
|
|
92
|
+
known = {f.name for f in fields(cls)}
|
|
93
|
+
unknown = sorted(set(data) - known)
|
|
94
|
+
if unknown:
|
|
95
|
+
raise PolicyError(f"unknown policy keys: {', '.join(unknown)}")
|
|
96
|
+
if "dialect" not in data:
|
|
97
|
+
raise PolicyError("the policy needs a dialect")
|
|
98
|
+
return cls(**dict(data))
|
|
99
|
+
|
|
100
|
+
@classmethod
|
|
101
|
+
def from_file(cls, path: str | Path) -> Policy:
|
|
102
|
+
"""Load a policy from a ``.json``, ``.yaml`` or ``.yml`` file.
|
|
103
|
+
|
|
104
|
+
YAML needs the optional extra: ``pip install "sqlguard[yaml]"``.
|
|
105
|
+
"""
|
|
106
|
+
file = Path(path)
|
|
107
|
+
text = file.read_text(encoding="utf-8")
|
|
108
|
+
if file.suffix.lower() in (".yaml", ".yml"):
|
|
109
|
+
try:
|
|
110
|
+
import yaml # noqa: PLC0415
|
|
111
|
+
except ImportError as exc: # pragma: no cover - depends on the environment
|
|
112
|
+
raise PolicyError('YAML policies need: pip install "sqlguard[yaml]"') from exc
|
|
113
|
+
data = yaml.safe_load(text)
|
|
114
|
+
else:
|
|
115
|
+
data = json.loads(text)
|
|
116
|
+
if not isinstance(data, Mapping):
|
|
117
|
+
raise PolicyError(f"{file} must contain a mapping at the top level")
|
|
118
|
+
return cls.from_dict(data)
|
sqlguard/py.typed
ADDED
|
File without changes
|