From be4703273339f3db7033ca5426beb031f0bb9f32 Mon Sep 17 00:00:00 2001 From: Juan Castillo Date: Mon, 30 Nov 2026 12:12:14 -0500 Subject: [PATCH 1/2] Add allowlisted stored procedures with typed, context-bound parameters (#173) procedures in Policy and the schemas, procedure_not_allowed and procedure_param_invalid (EN/ES), rules/procedures.py for tsql EXEC and postgres CALL (named parameters only, literals type-checked, context-bound parameters injected, dynamic SQL, sp_executesql and linked servers rejected), corpus cases, tests, docs. Co-Authored-By: Claude Sonnet 5.5 --- conformance/cases.json | 231 +++++++++++++++-- docs/PROCEDURES.md | 40 +++ mkdocs.yml | 1 + schema/policy-set.schema.json | 105 ++++++++ schema/policy-tests.schema.json | 4 +- schema/policy.schema.json | 35 +++ src/sqlguardllm/_compiled.py | 17 ++ src/sqlguardllm/guard.py | 57 +++++ src/sqlguardllm/messages.py | 8 + src/sqlguardllm/policy.py | 46 ++++ src/sqlguardllm/result.py | 2 + src/sqlguardllm/rules/procedures.py | 372 ++++++++++++++++++++++++++++ src/sqlguardllm/schema.py | 28 +++ tests/corpus/procedures.yaml | 48 ++++ tests/test_procedures.py | 124 ++++++++++ 15 files changed, 1094 insertions(+), 24 deletions(-) create mode 100644 docs/PROCEDURES.md create mode 100644 src/sqlguardllm/rules/procedures.py create mode 100644 tests/corpus/procedures.yaml create mode 100644 tests/test_procedures.py diff --git a/conformance/cases.json b/conformance/cases.json index 10cfb55..62c70a2 100644 --- a/conformance/cases.json +++ b/conformance/cases.json @@ -195,6 +195,191 @@ ] } }, + { + "cases": [ + { + "codes": [ + "procedure_param_invalid" + ], + "contains": [], + "context": { + "user": { + "tenant_id": 7 + } + }, + "expect": "reject", + "expected": { + "codes": [ + "procedure_param_invalid" + ], + "ok": false, + "sql": null + }, + "id": "proc-bound-param-override", + "not_contains": [], + "sql": "EXEC dbo.P @a = 1, @tenant_id = 9" + } + ], + "name": "g03-tsql", + "policy": { + "default_schema": "dbo", + "dialect": "tsql", + "hidden_columns": [ + "customers.email", + "customers.tax_id" + ], + "max_rows": 1000, + "procedures": { + "dbo.P": { + "params": { + "@a": "int", + "@tenant_id": { + "bind": "{user.tenant_id}" + } + } + } + }, + "row_filters": { + "invoices": "branch_id IN ({user.branches})" + }, + "tables": [ + "branches", + "customers", + "invoice_lines", + "invoices", + "products" + ] + } + }, + { + "cases": [ + { + "codes": [ + "procedure_not_allowed" + ], + "contains": [], + "context": { + "user": { + "branches": [ + 1, + 2 + ] + } + }, + "expect": "reject", + "expected": { + "codes": [ + "procedure_not_allowed" + ], + "ok": false, + "sql": null + }, + "id": "proc-dynamic-sql", + "not_contains": [], + "sql": "EXEC(@sql)" + }, + { + "codes": [ + "procedure_not_allowed" + ], + "contains": [], + "context": { + "user": { + "branches": [ + 1, + 2 + ] + } + }, + "expect": "reject", + "expected": { + "codes": [ + "procedure_not_allowed" + ], + "ok": false, + "sql": null + }, + "id": "proc-sp-executesql", + "not_contains": [], + "sql": "EXEC sp_executesql @stmt" + }, + { + "codes": [ + "procedure_not_allowed" + ], + "contains": [], + "context": { + "user": { + "branches": [ + 1, + 2 + ] + } + }, + "expect": "reject", + "expected": { + "codes": [ + "procedure_not_allowed" + ], + "ok": false, + "sql": null + }, + "id": "proc-linked-server", + "not_contains": [], + "sql": "EXEC ('select 1') AT linked" + }, + { + "codes": [], + "contains": [ + "P" + ], + "context": { + "user": { + "branches": [ + 1, + 2 + ] + } + }, + "expect": "allow", + "expected": { + "codes": [], + "ok": true, + "sql": "EXEC dbo.P @a = 1" + }, + "id": "proc-allowed-named", + "not_contains": [], + "sql": "EXEC dbo.P @a = 1" + } + ], + "name": "g04-tsql", + "policy": { + "default_schema": "dbo", + "dialect": "tsql", + "hidden_columns": [ + "customers.email", + "customers.tax_id" + ], + "max_rows": 1000, + "procedures": { + "dbo.P": { + "params": { + "@a": "int" + } + } + }, + "row_filters": { + "invoices": "branch_id IN ({user.branches})" + }, + "tables": [ + "branches", + "customers", + "invoice_lines", + "invoices", + "products" + ] + } + }, { "cases": [ { @@ -219,7 +404,7 @@ "sql": "SELECT b.name, SUM(i.total) FROM invoices i JOIN branches b ON b.id = i.branch_id WHERE i.issued_at >= '20261101' GROUP BY b.name" } ], - "name": "g03-tsql", + "name": "g05-tsql", "policy": { "default_schema": "dbo", "dialect": "tsql", @@ -604,7 +789,7 @@ "sql": "WAITFOR DELAY '00:00:10'" } ], - "name": "g04-tsql", + "name": "g06-tsql", "policy": { "default_schema": "dbo", "dialect": "tsql", @@ -679,7 +864,7 @@ "sql": "SELECT load_data(1)" } ], - "name": "g05-bigquery", + "name": "g07-bigquery", "policy": { "dialect": "bigquery", "hidden_columns": [ @@ -1325,7 +1510,7 @@ "sql": "SELECT * FROM urlcluster('x')" } ], - "name": "g06-clickhouse", + "name": "g08-clickhouse", "policy": { "dialect": "clickhouse", "hidden_columns": [ @@ -1449,7 +1634,7 @@ "sql": "SELECT MAX(COLUMNS('.*')) FROM customers" } ], - "name": "g07-duckdb", + "name": "g09-duckdb", "policy": { "dialect": "duckdb", "hidden_columns": [ @@ -1497,7 +1682,7 @@ "sql": "SELECT b.name FROM branches b JOIN products p" } ], - "name": "g08-mysql", + "name": "g10-mysql", "policy": { "dialect": "mysql", "forbid_cartesian": true, @@ -1567,7 +1752,7 @@ "sql": "SELECT ROW_NUMBER() OVER (ORDER BY 1), SUPPLIER AS X FROM products" } ], - "name": "g09-mysql", + "name": "g11-mysql", "policy": { "dialect": "mysql", "hidden_columns": [ @@ -1663,7 +1848,7 @@ "sql": "SELECT PHONE FROM customers" } ], - "name": "g10-mysql", + "name": "g12-mysql", "policy": { "dialect": "mysql", "hidden_columns": [ @@ -1735,7 +1920,7 @@ "sql": "SELECT name FROM products WHERE id IN (SELECT product_id FROM invoice_lines)" } ], - "name": "g11-mysql", + "name": "g13-mysql", "policy": { "dialect": "mysql", "hidden_columns": [ @@ -1780,7 +1965,7 @@ "sql": "SELECT SUM(total) FROM invoices WHERE branch_id = 3" } ], - "name": "g12-mysql", + "name": "g14-mysql", "policy": { "dialect": "mysql", "hidden_columns": [ @@ -1984,7 +2169,7 @@ "sql": "SELECT * FROM invoices INTO OUTFILE '/tmp/x.csv'" } ], - "name": "g13-mysql", + "name": "g15-mysql", "policy": { "dialect": "mysql", "hidden_columns": [ @@ -2053,7 +2238,7 @@ "sql": "SELECT l.quantity FROM invoices i, invoice_lines l, products p WHERE l.invoice_id = i.id" } ], - "name": "g14-oracle", + "name": "g16-oracle", "policy": { "dialect": "oracle", "forbid_cartesian": true, @@ -2175,7 +2360,7 @@ "sql": "SELECT SYS.DBMS_PIPE.RECEIVE_MESSAGE('a', 10) FROM dual" } ], - "name": "g15-oracle", + "name": "g17-oracle", "policy": { "dialect": "oracle", "hidden_columns": [ @@ -2315,7 +2500,7 @@ "sql": "SELECT b.name FROM invoices i JOIN branches b ON b.id = i.branch_id JOIN invoice_lines l USING (id)" } ], - "name": "g16-postgres", + "name": "g18-postgres", "policy": { "dialect": "postgres", "forbid_cartesian": true, @@ -2389,7 +2574,7 @@ "sql": "WITH t AS (SELECT i.id FROM invoices i JOIN branches b ON b.id = i.branch_id) SELECT p.name FROM products p JOIN invoice_lines l ON l.product_id = p.id WHERE l.invoice_id IN (SELECT id FROM t)" } ], - "name": "g17-postgres", + "name": "g19-postgres", "policy": { "dialect": "postgres", "hidden_columns": [ @@ -2434,7 +2619,7 @@ "sql": "SELECT b.name, SUM(l.quantity) FROM invoices i JOIN branches b ON b.id = i.branch_id JOIN invoice_lines l ON l.invoice_id = i.id GROUP BY b.name" } ], - "name": "g18-postgres", + "name": "g20-postgres", "policy": { "dialect": "postgres", "hidden_columns": [ @@ -2529,7 +2714,7 @@ "sql": "SELECT name FROM branches UNION ALL SELECT name FROM products" } ], - "name": "g19-postgres", + "name": "g21-postgres", "policy": { "dialect": "postgres", "hidden_columns": [ @@ -2578,7 +2763,7 @@ "sql": "SELECT SUM(total) FROM invoices" } ], - "name": "g20-postgres", + "name": "g22-postgres", "policy": { "dialect": "postgres", "hidden_columns": [ @@ -2794,7 +2979,7 @@ "sql": "SELECT SUM(total) FROM invoices WHERE issued_at >= '2026-11-01' UNION ALL SELECT SUM(total) FROM invoices" } ], - "name": "g21-postgres", + "name": "g23-postgres", "policy": { "dialect": "postgres", "hidden_columns": [ @@ -4194,7 +4379,7 @@ "sql": "SELECT id FROM invoices;" } ], - "name": "g22-postgres", + "name": "g24-postgres", "policy": { "dialect": "postgres", "hidden_columns": [ @@ -4542,7 +4727,7 @@ "sql": "SELECT name FROM customers QUALIFY ROW_NUMBER() OVER (ORDER BY id) = 1 AND MAX(email) OVER () > 'm'" } ], - "name": "g23-snowflake", + "name": "g25-snowflake", "policy": { "dialect": "snowflake", "hidden_columns": [ @@ -4640,7 +4825,7 @@ "sql": "PRAGMA writable_schema = 1" } ], - "name": "g24-sqlite", + "name": "g26-sqlite", "policy": { "dialect": "sqlite", "hidden_columns": [ @@ -4738,7 +4923,7 @@ "sql": "SELECT system.slow_query('x')" } ], - "name": "g25-trino", + "name": "g27-trino", "policy": { "dialect": "trino", "hidden_columns": [ diff --git a/docs/PROCEDURES.md b/docs/PROCEDURES.md new file mode 100644 index 0000000..c05a903 --- /dev/null +++ b/docs/PROCEDURES.md @@ -0,0 +1,40 @@ +# Stored procedures + +Teams on SQL Server, Oracle and PostgreSQL keep business logic in stored procedures. By default +sqlguardllm rejects every `EXEC` and `CALL`. Add `procedures` to the policy to allow specific +calls: + +```yaml +procedures: + dbo.SalesByRegion: + params: + "@region": nvarchar(50) + "@year": int + "@tenant_id": {bind: "{user.tenant_id}"} # set from context, never by the model +``` + +## What is accepted + +- `EXEC dbo.SalesByRegion @region = N'North', @year = 2026` on SQL Server: named parameters + only, literal values type-checked. +- `CALL public.refresh_totals(a => 1, b => 'a')` on PostgreSQL: named arguments only, literal values type-checked. +- Context-bound parameters are injected by the guard as typed literals. + +## What is rejected + +| Case | Code | +|------|------| +| Procedure not listed | `procedure_not_allowed` | +| Dynamic SQL (`EXEC(@sql)`, `sp_executesql`) | `procedure_not_allowed` | +| Linked servers (`EXEC (...) AT ...`) | `procedure_not_allowed` | +| Positional, unknown, repeated or non-literal parameters | `procedure_param_invalid` | +| Wrong literal type | `procedure_param_invalid` | +| The model passes a context-bound parameter | `procedure_param_invalid` | + +## Security + +A listed procedure is trusted code: it runs with its owner's permissions and may write. Row +filters, masks and table allowlists do not apply inside it. Context-bound parameters are how +calls are scoped to a tenant or user. List only procedures you would let the caller run. + +Anything the parser does not recognise is rejected (fail closed). diff --git a/mkdocs.yml b/mkdocs.yml index 949a780..d1a078c 100644 --- a/mkdocs.yml +++ b/mkdocs.yml @@ -34,6 +34,7 @@ nav: - Español: es/quickstart.md - Rules: DESIGN.md - Policy reference: policy-reference.md + - Stored procedures: PROCEDURES.md - API reference: api.md - Threat model: THREAT_MODEL.md - Attack gallery: ATTACK_GALLERY.md diff --git a/schema/policy-set.schema.json b/schema/policy-set.schema.json index 23c6223..fd5f9d0 100644 --- a/schema/policy-set.schema.json +++ b/schema/policy-set.schema.json @@ -280,6 +280,41 @@ } }, "description": "Enables Guard.check_write: single-table INSERT, UPDATE and DELETE. null keeps every write rejected." + }, + "procedures": { + "type": "object", + "minProperties": 1, + "description": "Stored procedures a call may target. Each key is a procedure name; params maps a parameter name to a SQL type (int, float, bool, date, varchar(n)...) or {bind: \"{user.x}\"} to inject a value from the context. Without it every EXEC and CALL is rejected.", + "additionalProperties": { + "type": "object", + "additionalProperties": false, + "properties": { + "params": { + "type": "object", + "additionalProperties": { + "oneOf": [ + { + "type": "string", + "minLength": 1 + }, + { + "type": "object", + "additionalProperties": false, + "required": [ + "bind" + ], + "properties": { + "bind": { + "type": "string", + "minLength": 1 + } + } + } + ] + } + } + } + } } } }, @@ -423,6 +458,41 @@ "minLength": 1 }, "description": "Added to the inherited sensitive_tables." + }, + "procedures": { + "type": "object", + "minProperties": 1, + "description": "Added to the inherited procedures.", + "additionalProperties": { + "type": "object", + "additionalProperties": false, + "properties": { + "params": { + "type": "object", + "additionalProperties": { + "oneOf": [ + { + "type": "string", + "minLength": 1 + }, + { + "type": "object", + "additionalProperties": false, + "required": [ + "bind" + ], + "properties": { + "bind": { + "type": "string", + "minLength": 1 + } + } + } + ] + } + } + } + } } }, "description": "Joined to inherited lists, merged into inherited mappings." @@ -673,6 +743,41 @@ } }, "description": "Enables Guard.check_write: single-table INSERT, UPDATE and DELETE. null keeps every write rejected." + }, + "procedures": { + "type": "object", + "minProperties": 1, + "description": "Stored procedures a call may target. Each key is a procedure name; params maps a parameter name to a SQL type (int, float, bool, date, varchar(n)...) or {bind: \"{user.x}\"} to inject a value from the context. Without it every EXEC and CALL is rejected.", + "additionalProperties": { + "type": "object", + "additionalProperties": false, + "properties": { + "params": { + "type": "object", + "additionalProperties": { + "oneOf": [ + { + "type": "string", + "minLength": 1 + }, + { + "type": "object", + "additionalProperties": false, + "required": [ + "bind" + ], + "properties": { + "bind": { + "type": "string", + "minLength": 1 + } + } + } + ] + } + } + } + } } } } diff --git a/schema/policy-tests.schema.json b/schema/policy-tests.schema.json index 1659229..2ecb386 100644 --- a/schema/policy-tests.schema.json +++ b/schema/policy-tests.schema.json @@ -63,7 +63,9 @@ "write_not_allowed", "write_column_not_allowed", "missing_where", - "too_many_rows" + "too_many_rows", + "procedure_not_allowed", + "procedure_param_invalid" ] }, "sql_contains": { diff --git a/schema/policy.schema.json b/schema/policy.schema.json index 530442a..cd5ab78 100644 --- a/schema/policy.schema.json +++ b/schema/policy.schema.json @@ -255,6 +255,41 @@ } }, "description": "Enables Guard.check_write: single-table INSERT, UPDATE and DELETE. null keeps every write rejected." + }, + "procedures": { + "type": "object", + "minProperties": 1, + "description": "Stored procedures a call may target. Each key is a procedure name; params maps a parameter name to a SQL type (int, float, bool, date, varchar(n)...) or {bind: \"{user.x}\"} to inject a value from the context. Without it every EXEC and CALL is rejected.", + "additionalProperties": { + "type": "object", + "additionalProperties": false, + "properties": { + "params": { + "type": "object", + "additionalProperties": { + "oneOf": [ + { + "type": "string", + "minLength": 1 + }, + { + "type": "object", + "additionalProperties": false, + "required": [ + "bind" + ], + "properties": { + "bind": { + "type": "string", + "minLength": 1 + } + } + } + ] + } + } + } + } } } } diff --git a/src/sqlguardllm/_compiled.py b/src/sqlguardllm/_compiled.py index cf67350..727e807 100644 --- a/src/sqlguardllm/_compiled.py +++ b/src/sqlguardllm/_compiled.py @@ -4,6 +4,7 @@ from collections.abc import Mapping from dataclasses import dataclass, field +from typing import Any from sqlglot import exp from sqlglot.dialects.dialect import Dialect @@ -38,6 +39,21 @@ class CompiledWrites: approval: str +@dataclass(frozen=True) +class ProcedureParam: + """One parameter of a listed procedure: a literal type, or a context-bound filter.""" + + name: str # lowercase, without the leading "@" + type_name: str | None # lowercase declared type, None when bound + bound: RowFilter | None # the context placeholder, None when the model supplies the value + + +@dataclass(frozen=True) +class CompiledProcedure: + name: str # lowercase dotted name, as written in the policy + params: Mapping[str, ProcedureParam] + + @dataclass(frozen=True) class Compiled: """Everything the rules need, normalized for the dialect.""" @@ -63,3 +79,4 @@ class Compiled: untrusted: Mapping[TableName, frozenset[str]] = field(default_factory=dict) sensitive: tuple[TableName, ...] = () writes: CompiledWrites | None = None + procedures: Mapping[str, Any] | None = None # name -> rules.procedures.ProcRules diff --git a/src/sqlguardllm/guard.py b/src/sqlguardllm/guard.py index fdbbc26..5d50c2a 100644 --- a/src/sqlguardllm/guard.py +++ b/src/sqlguardllm/guard.py @@ -39,6 +39,11 @@ from sqlguardllm.rules.functions import check_functions from sqlguardllm.rules.limit import apply_limit, current_limit from sqlguardllm.rules.masking import HASH_TEMPLATES, MaskPlan, apply_masks, plan_masks +from sqlguardllm.rules.procedures import ( + check_procedure_statement, + compile_procedures, + is_procedure_statement, +) from sqlguardllm.rules.required_filters import check_required_filters from sqlguardllm.rules.row_filters import apply_filters, compile_filter from sqlguardllm.rules.sources import PhysicalRef, collect_sources @@ -173,6 +178,12 @@ def _compile(policy: Policy, language: str) -> Compiled: approval=write_policy.approval, ) + compiled_procedures = ( + compile_procedures(policy.procedures, dialect_name) + if policy.procedures is not None + else None + ) + base = ( policy.denied_functions if policy.denied_functions is not None @@ -206,6 +217,7 @@ def _compile(policy: Policy, language: str) -> Compiled: untrusted={table: frozenset(columns) for table, columns in untrusted.items()}, sensitive=sensitive, writes=compiled_writes, + procedures=compiled_procedures, ) @@ -266,6 +278,7 @@ def check(self, sql: str, context: Mapping[str, Any] | None = None) -> CheckResu audit = self._audit started = time.perf_counter() if audit is not None else 0.0 state = self._analyze(sql) + self._call_procedure(state, context) self._rewrite(state, context) result = self._result(state) if audit is None: @@ -356,6 +369,7 @@ def explain(self, sql: str, context: Mapping[str, Any] | None = None) -> Explana context: Values for row-filter placeholders, as in :meth:`check`. """ state = self._analyze(sql) + self._call_procedure(state, context) # Read the columns before the rewrite replaces filtered tables with derived tables. reads = read_columns(state.scopes, state.refs, self._compiled) masked, groups = protections(reads, state.refs, self._compiled) @@ -416,6 +430,19 @@ def _analyze(self, sql: str) -> _State: cast(exp.Expression, statement) for statement in parsed if statement is not None ] + if ( + compiled.procedures is not None + and len(statements) == 1 + and ( + isinstance(statements[0], (exp.Execute, exp.ExecuteSql)) + or ( + isinstance(statements[0], exp.Command) + and str(statements[0].this).upper() == "CALL" + ) + ) + ): + return _State([], root=statements[0]) + root, violations = check_statements(statements, lang) if root is None: return _State(violations) @@ -438,6 +465,36 @@ def _analyze(self, sql: str) -> _State: problems, root=root, scopes=scopes, refs=refs, masks=masks, aggregates=aggregates ) + def _call_procedure(self, state: _State, context: Mapping[str, Any] | None) -> None: + """Validate a procedure call (``EXEC``/``CALL``) held in ``state.root`` and finish it.""" + root = state.root + compiled = self._compiled + if ( + state.violations + or root is None + or compiled.procedures is None + or not is_procedure_statement(root) + ): + return + handled = check_procedure_statement( + root, + compiled.procedures, + compiled.default_schema, + context if context is not None else {}, + compiled.language, + compiled.dialect_name, + ) + if handled is None: + return + sql, problems = handled + state.root = None + if problems or sql is None: + state.violations = problems or [ + violation(ViolationCode.PROCEDURE_NOT_ALLOWED, "", compiled.language) + ] + return + state.sql = sql + def _rewrite(self, state: _State, context: Mapping[str, Any] | None) -> None: """Steps 7-9, only for a query without violations: masks, row filters, limit, generate.""" if state.violations or state.root is None: diff --git a/src/sqlguardllm/messages.py b/src/sqlguardllm/messages.py index bd9de5a..e52730d 100644 --- a/src/sqlguardllm/messages.py +++ b/src/sqlguardllm/messages.py @@ -93,6 +93,14 @@ "en": "The write would change {detail} rows, more than the policy allows", "es": "La escritura cambiaría {detail} filas, más de las que permite la política", }, + ViolationCode.PROCEDURE_NOT_ALLOWED: { + "en": "This procedure call is not allowed: {detail}", + "es": "Esta llamada a procedimiento no está permitida: {detail}", + }, + ViolationCode.PROCEDURE_PARAM_INVALID: { + "en": "Invalid procedure parameter: {detail}", + "es": "Parámetro de procedimiento inválido: {detail}", + }, ViolationCode.AUDIT_FAILURE: { "en": "The decision could not be written to the audit log, so the query was rejected", "es": "No se pudo registrar la decisión en el log de auditoría, así que se rechazó", diff --git a/src/sqlguardllm/policy.py b/src/sqlguardllm/policy.py index 40c65c4..221f143 100644 --- a/src/sqlguardllm/policy.py +++ b/src/sqlguardllm/policy.py @@ -144,6 +144,11 @@ class Policy: Only the linter reads it: checking SQL ignores it. writes: A :class:`WritePolicy` (or its mapping) that enables ``Guard.check_write``. ``None`` (default) keeps every write rejected. ``Guard.check`` never allows writes. + procedures: Stored procedures a call may target, ``name`` → ``{"params": {...}}`` where + each parameter is a type string (``"nvarchar(50)"``, ``"int"``) or + ``{"bind": "{user.tenant_id}"}`` (set from the context, never by the model). A + listed procedure is trusted code: row filters don't apply inside it. ``None`` + (default) rejects every ``EXEC``/``CALL``. """ dialect: str @@ -169,6 +174,7 @@ class Policy: sensitive_tables: Collection[str] = frozenset() on_tainted: TaintAction = "deny" writes: WritePolicy | Mapping[str, Any] | None = None + procedures: Mapping[str, Mapping[str, Any]] | None = None def __post_init__(self) -> None: if not isinstance(self.dialect, str) or not self.dialect.strip(): @@ -267,8 +273,48 @@ def __post_init__(self) -> None: object.__setattr__(self, "writes", WritePolicy(**dict(self.writes))) if self.writes is not None and not isinstance(self.writes, WritePolicy): raise PolicyError("writes must be a WritePolicy, a mapping or None") + self._check_procedures() self._check_lint_suppress() + def _check_procedures(self) -> None: + if self.procedures is None: + return + if not isinstance(self.procedures, Mapping) or not self.procedures: + raise PolicyError("procedures must map procedure names to their definition") + frozen: dict[str, Mapping[str, Any]] = {} + for name, spec in self.procedures.items(): + if not isinstance(name, str) or not name.strip(): + raise PolicyError("procedures keys must be non-empty procedure names") + if not isinstance(spec, Mapping): + raise PolicyError(f"procedures[{name!r}] must be a mapping with params") + unknown = sorted(set(spec) - {"params"}) + if unknown: + raise PolicyError(f"unknown keys in procedures[{name!r}]: {unknown}") + params = spec.get("params", {}) + if not isinstance(params, Mapping): + raise PolicyError(f"procedures[{name!r}].params must be a mapping") + clean: dict[str, Any] = {} + for pname, ptype in params.items(): + if not isinstance(pname, str) or not pname.strip(): + raise PolicyError(f"procedures[{name!r}] has an empty parameter name") + if isinstance(ptype, str): + if not ptype.strip(): + raise PolicyError(f"procedures[{name!r}].params[{pname!r}] needs a type") + clean[pname] = ptype + elif isinstance(ptype, Mapping): + if set(ptype) != {"bind"} or not isinstance(ptype["bind"], str): + raise PolicyError( + f"procedures[{name!r}].params[{pname!r}] must be a type string " + 'or {"bind": "{context.path}"}' + ) + clean[pname] = {"bind": ptype["bind"]} + else: + raise PolicyError( + f"procedures[{name!r}].params[{pname!r}] must be a type string or a bind" + ) + frozen[name] = MappingProxyType({"params": MappingProxyType(clean)}) + object.__setattr__(self, "procedures", MappingProxyType(frozen)) + def _check_lint_suppress(self) -> None: from sqlguardllm.lint import LINT_CODES # noqa: PLC0415 - lint imports this module diff --git a/src/sqlguardllm/result.py b/src/sqlguardllm/result.py index 146698e..54b3c6f 100644 --- a/src/sqlguardllm/result.py +++ b/src/sqlguardllm/result.py @@ -29,6 +29,8 @@ class ViolationCode(str, Enum): WRITE_COLUMN_NOT_ALLOWED = "write_column_not_allowed" MISSING_WHERE = "missing_where" TOO_MANY_ROWS = "too_many_rows" + PROCEDURE_NOT_ALLOWED = "procedure_not_allowed" + PROCEDURE_PARAM_INVALID = "procedure_param_invalid" @dataclass(frozen=True) diff --git a/src/sqlguardllm/rules/procedures.py b/src/sqlguardllm/rules/procedures.py new file mode 100644 index 0000000..eb89b7c --- /dev/null +++ b/src/sqlguardllm/rules/procedures.py @@ -0,0 +1,372 @@ +"""Stored procedures: an allowlist of calls with typed, named parameters.""" + +from __future__ import annotations + +import datetime +import re +from collections.abc import Mapping +from dataclasses import dataclass +from decimal import Decimal, InvalidOperation +from typing import Any + +from sqlglot import exp + +from sqlguardllm.messages import violation +from sqlguardllm.result import Violation, ViolationCode +from sqlguardllm.rules import row_filters +from sqlguardllm.rules.row_filters import ContextError + +_IDENT = r"[A-Za-z_][A-Za-z0-9_$#]*" +_QUALIFIED = re.compile(rf"^\s*({_IDENT}(?:\s*\.\s*{_IDENT}){{0,2}})\s*\(") +_NAMED_ARG = re.compile(rf"^\s*(@?{_IDENT})\s*=>?\s*") +_NUMBER = re.compile(r"^-?\d+(?:\.\d+)?") +_BIND = re.compile(r"\{([A-Za-z_]\w*(?:\.[A-Za-z_]\w*)*)\}") +_TYPE_ALIASES = { + "int": "int", + "integer": "int", + "bigint": "int", + "smallint": "int", + "tinyint": "int", + "number": "int", + "float": "float", + "real": "float", + "double": "float", + "decimal": "float", + "numeric": "float", + "bit": "bool", + "bool": "bool", + "boolean": "bool", + "date": "date", + "datetime": "date", + "datetime2": "date", + "timestamp": "date", +} +_TEXT_TYPES = ("varchar", "nvarchar", "char", "nchar", "text", "varchar2", "nvarchar2", "string") + + +@dataclass(frozen=True) +class ProcParam: + """One parameter: a literal type, or a template bound from the context.""" + + name: str + kind: str # "int", "float", "bool", "date", "text" or "bind" + bind_template: str | None = None + + +@dataclass(frozen=True) +class ProcRules: + params: Mapping[str, ProcParam] + + +def _kind_of(type_name: str) -> str | None: + base = re.sub(r"\(.*\)", "", type_name).strip().lower() + if base in _TEXT_TYPES: + return "text" + return _TYPE_ALIASES.get(base) + + +def _norm_param(name: str) -> str: + return name.lstrip("@").lower() + + +def _norm_proc(name: str, default_schema: str | None) -> str: + parts = [part.strip().strip('"[]`').lower() for part in name.split(".")] + return ".".join(parts) + + +def compile_procedures( + raw: Mapping[str, Mapping[str, Any]], default_schema: str | None +) -> dict[str, ProcRules]: + """Normalize the policy's ``procedures`` mapping. Raises ``ValueError`` when invalid.""" + out: dict[str, ProcRules] = {} + for proc_name, spec in raw.items(): + params: dict[str, ProcParam] = {} + declared = spec.get("params", {}) if isinstance(spec, Mapping) else {} + for pname, pspec in declared.items(): + key = _norm_param(pname) + if isinstance(pspec, Mapping): + template = pspec.get("bind") + if not isinstance(template, str) or not _BIND.search(template): + raise ValueError(f"procedures[{proc_name!r}].{pname}: bind needs a placeholder") + params[key] = ProcParam(key, "bind", template) + elif isinstance(pspec, str): + kind = _kind_of(pspec) + if kind is None: + raise ValueError(f"procedures[{proc_name!r}].{pname}: unknown type {pspec!r}") + params[key] = ProcParam(key, kind) + else: + raise ValueError(f"procedures[{proc_name!r}].{pname}: invalid parameter spec") + out[_norm_proc(proc_name, default_schema)] = ProcRules(params) + return out + + +def _bad(detail: str, language: str) -> list[Violation]: + return [violation(ViolationCode.PROCEDURE_PARAM_INVALID, detail, language)] + + +def _lookup( + name: str, procedures: Mapping[str, ProcRules], default_schema: str | None +) -> ProcRules | None: + key = _norm_proc(name, default_schema) + if key in procedures: + return procedures[key] + if "." not in key and default_schema: + return procedures.get(f"{default_schema.lower()}.{key}") + if "." in key: + short = key.split(".")[-1] + if default_schema and key == f"{default_schema.lower()}.{short}": + return procedures.get(short) + return None + + +def _literal_node(value: str, kind: str) -> exp.Expression | None: + """A typed literal node for ``value`` given as SQL text, or ``None`` if it doesn't fit.""" + if kind in ("int", "float"): + if not _NUMBER.fullmatch(value): + return None + if kind == "int" and "." in value: + return None + return exp.Literal.number(value) + return None + + +def _check_value(node: exp.Expression, param: ProcParam) -> exp.Expression | None: + """Validate a parsed literal against the declared type; return the normalized node.""" + kind = param.kind + if isinstance(node, exp.Neg) and isinstance(node.this, exp.Literal): + inner = node.this + if inner.is_string or kind not in ("int", "float"): + return None + if kind == "int" and not re.fullmatch(r"\d+", inner.name): + return None + return exp.Literal.number(f"-{inner.name}") + if isinstance(node, exp.Literal): + if node.is_string: + if kind == "text": + return exp.Literal.string(node.name) + if kind == "date": + try: + datetime.date.fromisoformat(node.name[:10]) + except ValueError: + return None + return exp.Literal.string(node.name) + return None + if kind == "int": + return node.copy() if re.fullmatch(r"\d+", node.name) else None + if kind == "float": + try: + Decimal(node.name) + except InvalidOperation: + return None + return node.copy() + if kind == "bool" and node.name in ("0", "1"): + return node.copy() + return None + if isinstance(node, exp.National): + # keep the N prefix: dropping it would turn a Unicode value into the database's code page + return node.copy() if kind == "text" else None + if isinstance(node, exp.Boolean): + return node.copy() if kind == "bool" else None + return None + + +def _bound_literal(param: ProcParam, context: Any) -> exp.Expression: + """Inject a context-bound parameter as a typed literal (reuses the row-filter binder).""" + assert param.bind_template is not None + match = _BIND.fullmatch(param.bind_template.strip()) + if match is None: + raise ContextError(ViolationCode.INVALID_CONTEXT, param.bind_template) + path = match.group(1) + value = row_filters._resolve(context, path) + if value is row_filters._MISSING: + raise ContextError(ViolationCode.MISSING_CONTEXT, f"{{{path}}}") + return row_filters._literal(value, path) + + +def _finish( # noqa: PLR0917 + proc_name: str, + given: dict[str, exp.Expression], + rules: ProcRules, + context: Any, + language: str, + dialect_name: str, + style: str, +) -> tuple[str | None, list[Violation]]: + problems: list[Violation] = [] + final: dict[str, exp.Expression] = {} + for key, node in given.items(): + param = rules.params.get(key) + if param is None: + problems += _bad(f"{key}: not a parameter of {proc_name}", language) + continue + if param.kind == "bind": + problems += _bad(f"{key}: set by the context, not by the query", language) + continue + checked = _check_value(node, param) + if checked is None: + problems += _bad(f"{key}: value does not match {param.kind}", language) + continue + final[key] = checked + for key, param in rules.params.items(): + if param.kind == "bind": + try: + final[key] = _bound_literal(param, context) + except ContextError as problem: + problems.append(violation(problem.code, problem.detail, language)) + elif key not in final and not problems: + problems += _bad(f"{key}: required parameter missing", language) + if problems: + return None, problems + ordered = [(key, final[key]) for key in rules.params] + if style == "exec": + args = ", ".join(f"@{k} = {v.sql(dialect=dialect_name)}" for k, v in ordered) + return f"EXEC {proc_name}" + (f" {args}" if args else ""), [] + args = ", ".join(f"{k} => {v.sql(dialect=dialect_name)}" for k, v in ordered) + return f"CALL {proc_name}({args})", [] + + +def check_execute( # noqa: PLR0917 + node: exp.Execute, + procedures: Mapping[str, ProcRules], + default_schema: str | None, + context: Any, + language: str, + dialect_name: str, +) -> tuple[str | None, list[Violation]]: + """Validate a T-SQL ``EXEC`` against the procedure allowlist.""" + target = node.this + if not isinstance(target, exp.Table) or isinstance(target.this, exp.Parameter): + return None, [violation(ViolationCode.PROCEDURE_NOT_ALLOWED, "dynamic SQL", language)] + if not isinstance(target.this, exp.Identifier) or target.args.get("catalog"): + return None, [violation(ViolationCode.PROCEDURE_NOT_ALLOWED, target.sql(), language)] + proc_name = ".".join( + part.name for part in (target.args.get("db"), target.this) if part is not None + ) + if proc_name.lower() in ("sp_executesql", "sp_execute", "xp_cmdshell"): + return None, [violation(ViolationCode.PROCEDURE_NOT_ALLOWED, proc_name, language)] + rules = _lookup(proc_name, procedures, default_schema) + if rules is None: + return None, [violation(ViolationCode.PROCEDURE_NOT_ALLOWED, proc_name, language)] + given: dict[str, exp.Expression] = {} + for arg in node.expressions: + if not ( + isinstance(arg, exp.EQ) + and isinstance(arg.this, exp.Parameter) + and isinstance(arg.this.this, exp.Var) + ): + return None, _bad("named parameters only (@name = value)", language) + key = _norm_param(arg.this.this.name) + if key in given: + return None, _bad(f"{key}: given twice", language) + given[key] = arg.expression + return _finish(proc_name, given, rules, context, language, dialect_name, "exec") + + +def _split_args(text: str) -> list[str] | None: + """Split a CALL argument list on top-level commas; ``None`` when it is malformed.""" + args: list[str] = [] + current: list[str] = [] + quote = False + i = 0 + while i < len(text): + char = text[i] + if quote: + current.append(char) + if char == "'": + if i + 1 < len(text) and text[i + 1] == "'": + current.append("'") + i += 1 + else: + quote = False + elif char == "'": + quote = True + current.append(char) + elif char in "();": + return None + elif char == ",": + args.append("".join(current).strip()) + current = [] + else: + current.append(char) + i += 1 + if quote: + return None + last = "".join(current).strip() + if last or args: + args.append(last) + return args + + +def check_call( # noqa: PLR0917 + node: exp.Command, + procedures: Mapping[str, ProcRules], + default_schema: str | None, + context: Any, + language: str, + dialect_name: str, +) -> tuple[str | None, list[Violation]]: + """Validate a PostgreSQL-style ``CALL schema.proc(name => value, ...)``.""" + body = node.expression + text = body.name if isinstance(body, exp.Expression) else str(body or "") + match = _QUALIFIED.match(text) + stripped = text.rstrip() + if match is None or not stripped.endswith(")"): + return None, [violation(ViolationCode.PROCEDURE_NOT_ALLOWED, text[:60], language)] + proc_name = re.sub(r"\s+", "", match.group(1)) + rules = _lookup(proc_name, procedures, default_schema) + if rules is None: + return None, [violation(ViolationCode.PROCEDURE_NOT_ALLOWED, proc_name, language)] + args = _split_args(stripped[match.end() : -1]) + if args is None: + return None, _bad("malformed argument list", language) + given: dict[str, exp.Expression] = {} + for arg in args: + named = _NAMED_ARG.match(arg) + if named is None: + return None, _bad("named parameters only (name => value)", language) + key = _norm_param(named.group(1)) + raw = arg[named.end() :].strip() + if not raw or key in given: + return None, _bad(f"{key}: missing or repeated value", language) + value = _parse_value(raw, dialect_name) + if value is None: + return None, _bad(f"{key}: only literal values are allowed", language) + given[key] = value + return _finish(proc_name, given, rules, context, language, dialect_name, "call") + + +def _parse_value(raw: str, dialect_name: str) -> exp.Expression | None: + """Parse one literal argument; anything that is not a plain literal is ``None``.""" + if raw.startswith("'") and raw.endswith("'") and len(raw) >= 2: + inner = raw[1:-1] + if "'" in inner.replace("''", ""): + return None + return exp.Literal.string(inner.replace("''", "'")) + if _NUMBER.fullmatch(raw): + return exp.Literal.number(raw) + if raw.lower() in ("true", "false"): + return exp.Boolean(this=raw.lower() == "true") + return None + + +def is_procedure_statement(node: exp.Expression) -> bool: + """True for the statement shapes this module decides: ``EXEC`` and ``CALL``.""" + if isinstance(node, (exp.Execute, exp.ExecuteSql)): + return True + return isinstance(node, exp.Command) and str(node.this).upper() == "CALL" + + +def check_procedure_statement( # noqa: PLR0917 + node: exp.Expression, + procedures: Mapping[str, ProcRules], + default_schema: str | None, + context: Any, + language: str, + dialect_name: str, +) -> tuple[str | None, list[Violation]]: + """Dispatch a procedure statement; anything not understood is rejected (fail closed).""" + if isinstance(node, exp.Execute): + return check_execute(node, procedures, default_schema, context, language, dialect_name) + if isinstance(node, exp.Command): + return check_call(node, procedures, default_schema, context, language, dialect_name) + return None, [violation(ViolationCode.PROCEDURE_NOT_ALLOWED, "dynamic SQL", language)] diff --git a/src/sqlguardllm/schema.py b/src/sqlguardllm/schema.py index 815f35b..49dcfa2 100644 --- a/src/sqlguardllm/schema.py +++ b/src/sqlguardllm/schema.py @@ -139,6 +139,34 @@ "description": "Enables Guard.check_write: single-table INSERT, UPDATE and DELETE. " "null keeps every write rejected.", }, + "procedures": { + "type": "object", + "minProperties": 1, + "description": "Stored procedures a call may target. Each key is a procedure name; params " + "maps a parameter name to a SQL type (int, float, bool, date, varchar(n)...) or " + '{bind: "{user.x}"} to inject a value from the context. Without it every EXEC and CALL ' + "is rejected.", + "additionalProperties": { + "type": "object", + "additionalProperties": False, + "properties": { + "params": { + "type": "object", + "additionalProperties": { + "oneOf": [ + {"type": "string", "minLength": 1}, + { + "type": "object", + "additionalProperties": False, + "required": ["bind"], + "properties": {"bind": {"type": "string", "minLength": 1}}, + }, + ] + }, + } + }, + }, + }, "lint_suppress": { "type": "object", "propertyNames": {"enum": [code.value for code in LintCode]}, diff --git a/tests/corpus/procedures.yaml b/tests/corpus/procedures.yaml new file mode 100644 index 0000000..806b4a5 --- /dev/null +++ b/tests/corpus/procedures.yaml @@ -0,0 +1,48 @@ +- id: proc-dynamic-sql + dialect: tsql + sql: "EXEC(@sql)" + expect: reject + codes: [procedure_not_allowed] + policy: + procedures: + dbo.P: + params: {"@a": int} +- id: proc-sp-executesql + dialect: tsql + sql: "EXEC sp_executesql @stmt" + expect: reject + codes: [procedure_not_allowed] + policy: + procedures: + dbo.P: + params: {"@a": int} +- id: proc-linked-server + dialect: tsql + sql: "EXEC ('select 1') AT linked" + expect: reject + codes: [procedure_not_allowed] + policy: + procedures: + dbo.P: + params: {"@a": int} +- id: proc-bound-param-override + dialect: tsql + sql: "EXEC dbo.P @a = 1, @tenant_id = 9" + expect: reject + codes: [procedure_param_invalid] + context: {user: {tenant_id: 7}} + policy: + procedures: + dbo.P: + params: + "@a": int + "@tenant_id": {bind: "{user.tenant_id}"} +- id: proc-allowed-named + dialect: tsql + sql: "EXEC dbo.P @a = 1" + expect: allow + contains: ["P"] + policy: + procedures: + dbo.P: + params: {"@a": int} diff --git a/tests/test_procedures.py b/tests/test_procedures.py new file mode 100644 index 0000000..e5a7b8a --- /dev/null +++ b/tests/test_procedures.py @@ -0,0 +1,124 @@ +"""The procedure rules, at the parsing level (the Guard wiring has its own tests).""" + +from __future__ import annotations + +import sqlglot +from sqlglot import exp + +from sqlguardllm import Guard, Policy +from sqlguardllm.result import ViolationCode +from sqlguardllm.rules.procedures import ( + check_procedure_statement, + compile_procedures, + is_procedure_statement, +) + +RAW = { + "dbo.SalesByRegion": { + "params": {"@region": "nvarchar(50)", "@year": "int"}, + }, + "public.refresh_totals": {"params": {"n": "int", "label": "text"}}, +} +CONTEXT: dict[str, object] = {} + + +def _run(sql: str, dialect: str) -> tuple[str | None, set[ViolationCode]]: + node = sqlglot.parse_one(sql, read=dialect) + assert is_procedure_statement(node) + procedures = compile_procedures(RAW, None) + text, problems = check_procedure_statement(node, procedures, None, CONTEXT, "en", dialect) + return text, {p.code for p in problems} + + +def test_exec_valid() -> None: + text, codes = _run("EXEC dbo.SalesByRegion @region = N'North', @year = 2026", "tsql") + assert not codes + assert text is not None and "dbo.SalesByRegion" in text and "2026" in text + + +def test_exec_unlisted() -> None: + _, codes = _run("EXEC dbo.Other @a = 1", "tsql") + assert codes == {ViolationCode.PROCEDURE_NOT_ALLOWED} + + +def test_exec_positional_rejected() -> None: + _, codes = _run("EXEC dbo.SalesByRegion N'North', 2026", "tsql") + assert codes == {ViolationCode.PROCEDURE_PARAM_INVALID} + + +def test_exec_wrong_type() -> None: + _, codes = _run("EXEC dbo.SalesByRegion @region = N'North', @year = 'x'", "tsql") + assert codes == {ViolationCode.PROCEDURE_PARAM_INVALID} + + +def test_exec_dynamic_sql() -> None: + _, codes = _run("EXEC(@sql)", "tsql") + assert codes == {ViolationCode.PROCEDURE_NOT_ALLOWED} + + +def test_exec_sp_executesql() -> None: + _, codes = _run("EXEC sp_executesql @stmt", "tsql") + assert codes == {ViolationCode.PROCEDURE_NOT_ALLOWED} + + +def test_exec_linked_server() -> None: + _, codes = _run("EXEC ('select 1') AT linked", "tsql") + assert codes == {ViolationCode.PROCEDURE_NOT_ALLOWED} + + +def test_call_valid() -> None: + text, codes = _run("CALL public.refresh_totals(n => 1, label => 'a')", "postgres") + assert not codes + assert text is not None and text.startswith("CALL public.refresh_totals(") + + +def test_call_unlisted() -> None: + _, codes = _run("CALL public.drop_all(n => 1)", "postgres") + assert codes == {ViolationCode.PROCEDURE_NOT_ALLOWED} + + +def test_call_positional_rejected() -> None: + _, codes = _run("CALL public.refresh_totals(1, 'a')", "postgres") + assert codes == {ViolationCode.PROCEDURE_PARAM_INVALID} + + +def test_bound_parameter_cannot_be_set_by_model() -> None: + procedures = compile_procedures( + {"dbo.P": {"params": {"@a": "int", "@tenant_id": {"bind": "{user.tenant_id}"}}}}, None + ) + node = sqlglot.parse_one("EXEC dbo.P @a = 1, @tenant_id = 9", read="tsql") + assert isinstance(node, exp.Execute) + _, problems = check_procedure_statement( + node, procedures, None, {"user": {"tenant_id": 5}}, "en", "tsql" + ) + assert {p.code for p in problems} == {ViolationCode.PROCEDURE_PARAM_INVALID} + + +def test_bound_parameter_injected() -> None: + procedures = compile_procedures( + {"dbo.P": {"params": {"@a": "int", "@tenant_id": {"bind": "{user.tenant_id}"}}}}, None + ) + node = sqlglot.parse_one("EXEC dbo.P @a = 1", read="tsql") + text, problems = check_procedure_statement( + node, procedures, None, {"user": {"tenant_id": 5}}, "en", "tsql" + ) + assert not problems + assert text is not None and "@tenant_id = 5" in text + + +def test_a_plain_query_still_works_when_procedures_are_configured() -> None: + guard = Guard(Policy(dialect="tsql", procedures={"dbo.P": {"params": {"@a": "int"}}})) + assert guard.check("SELECT 1").ok + + +def test_the_unicode_prefix_of_a_text_value_is_kept() -> None: + guard = Guard(Policy(dialect="tsql", procedures={"dbo.P": {"params": {"@a": "nvarchar(20)"}}})) + result = guard.check("EXEC dbo.P @a = N'Bogotá'") + assert result.ok + assert result.sql is not None and "N'Bogotá'" in result.sql + + +def test_postgres_call_needs_named_arguments() -> None: + guard = Guard(Policy(dialect="postgres", procedures={"public.p": {"params": {"a": "int"}}})) + assert guard.check("CALL public.p(a => 1)").ok + assert guard.check("CALL public.p(1)").codes == {ViolationCode.PROCEDURE_PARAM_INVALID} From b6a01db2cfffa234c9b8e61a2d45c4dce854520b Mon Sep 17 00:00:00 2001 From: Juan Castillo Date: Mon, 30 Nov 2026 12:16:43 -0500 Subject: [PATCH 2/2] fix(procedures): close the security review findings (#173) Canonical names, no catalog or 4-part names, extra EXEC clauses rejected, consistent integer forms on EXEC and CALL, non-scalar bound values rejected, regression tests. Co-Authored-By: Claude Sonnet 5.5 --- src/sqlguardllm/guard.py | 21 ++-- src/sqlguardllm/rules/procedures.py | 99 +++++++++++++------ tests/test_procedures.py | 144 +++++++++++++++++++++++++++- 3 files changed, 220 insertions(+), 44 deletions(-) diff --git a/src/sqlguardllm/guard.py b/src/sqlguardllm/guard.py index 5d50c2a..e7170e8 100644 --- a/src/sqlguardllm/guard.py +++ b/src/sqlguardllm/guard.py @@ -178,11 +178,14 @@ def _compile(policy: Policy, language: str) -> Compiled: approval=write_policy.approval, ) - compiled_procedures = ( - compile_procedures(policy.procedures, dialect_name) - if policy.procedures is not None - else None - ) + try: + compiled_procedures = ( + compile_procedures(policy.procedures, default_schema) + if policy.procedures is not None + else None + ) + except ValueError as exc: + raise PolicyError(str(exc)) from exc base = ( policy.denied_functions @@ -433,13 +436,7 @@ def _analyze(self, sql: str) -> _State: if ( compiled.procedures is not None and len(statements) == 1 - and ( - isinstance(statements[0], (exp.Execute, exp.ExecuteSql)) - or ( - isinstance(statements[0], exp.Command) - and str(statements[0].this).upper() == "CALL" - ) - ) + and is_procedure_statement(statements[0]) ): return _State([], root=statements[0]) diff --git a/src/sqlguardllm/rules/procedures.py b/src/sqlguardllm/rules/procedures.py index eb89b7c..1612df1 100644 --- a/src/sqlguardllm/rules/procedures.py +++ b/src/sqlguardllm/rules/procedures.py @@ -16,6 +16,9 @@ from sqlguardllm.rules import row_filters from sqlguardllm.rules.row_filters import ContextError +_MAX_BOUND_TEXT = 4096 +_DATE_RE = re.compile(r"\d{4}-\d{2}-\d{2}") +_DATETIME_RE = re.compile(r"\d{4}-\d{2}-\d{2}[ T]\d{2}:\d{2}(:\d{2}(\.\d{1,7})?)?") _IDENT = r"[A-Za-z_][A-Za-z0-9_$#]*" _QUALIFIED = re.compile(rf"^\s*({_IDENT}(?:\s*\.\s*{_IDENT}){{0,2}})\s*\(") _NAMED_ARG = re.compile(rf"^\s*(@?{_IDENT})\s*=>?\s*") @@ -56,6 +59,7 @@ class ProcParam: @dataclass(frozen=True) class ProcRules: params: Mapping[str, ProcParam] + name: str = "" def _kind_of(type_name: str) -> str | None: @@ -69,9 +73,9 @@ def _norm_param(name: str) -> str: return name.lstrip("@").lower() -def _norm_proc(name: str, default_schema: str | None) -> str: - parts = [part.strip().strip('"[]`').lower() for part in name.split(".")] - return ".".join(parts) +def _norm_proc(name: str) -> str: + """Case-folded policy key; the canonical spelling is kept in ``ProcRules.name``.""" + return ".".join(part.strip().lower() for part in name.split(".")) def compile_procedures( @@ -84,6 +88,8 @@ def compile_procedures( declared = spec.get("params", {}) if isinstance(spec, Mapping) else {} for pname, pspec in declared.items(): key = _norm_param(pname) + if key in params: + raise ValueError(f"procedures[{proc_name!r}].{pname}: duplicate parameter") if isinstance(pspec, Mapping): template = pspec.get("bind") if not isinstance(template, str) or not _BIND.search(template): @@ -96,7 +102,10 @@ def compile_procedures( params[key] = ProcParam(key, kind) else: raise ValueError(f"procedures[{proc_name!r}].{pname}: invalid parameter spec") - out[_norm_proc(proc_name, default_schema)] = ProcRules(params) + key = _norm_proc(proc_name) + if key in out: + raise ValueError(f"procedures[{proc_name!r}]: duplicate procedure") + out[key] = ProcRules(params, proc_name.strip()) return out @@ -107,26 +116,11 @@ def _bad(detail: str, language: str) -> list[Violation]: def _lookup( name: str, procedures: Mapping[str, ProcRules], default_schema: str | None ) -> ProcRules | None: - key = _norm_proc(name, default_schema) + key = _norm_proc(name) if key in procedures: return procedures[key] if "." not in key and default_schema: return procedures.get(f"{default_schema.lower()}.{key}") - if "." in key: - short = key.split(".")[-1] - if default_schema and key == f"{default_schema.lower()}.{short}": - return procedures.get(short) - return None - - -def _literal_node(value: str, kind: str) -> exp.Expression | None: - """A typed literal node for ``value`` given as SQL text, or ``None`` if it doesn't fit.""" - if kind in ("int", "float"): - if not _NUMBER.fullmatch(value): - return None - if kind == "int" and "." in value: - return None - return exp.Literal.number(value) return None @@ -139,21 +133,34 @@ def _check_value(node: exp.Expression, param: ProcParam) -> exp.Expression | Non return None if kind == "int" and not re.fullmatch(r"\d+", inner.name): return None + if kind == "float" and not _NUMBER.fullmatch(inner.name): + return None return exp.Literal.number(f"-{inner.name}") if isinstance(node, exp.Literal): if node.is_string: if kind == "text": - return exp.Literal.string(node.name) - if kind == "date": - try: - datetime.date.fromisoformat(node.name[:10]) - except ValueError: + if len(node.name) > _MAX_BOUND_TEXT: return None return exp.Literal.string(node.name) + if kind == "date": + if _DATE_RE.fullmatch(node.name): + try: + parsed = datetime.date.fromisoformat(node.name) + except ValueError: + return None + return exp.Literal.string(parsed.isoformat()) + if _DATETIME_RE.fullmatch(node.name): + try: + datetime.date.fromisoformat(node.name[:10]) + except ValueError: + return None + return exp.Literal.string(node.name) return None if kind == "int": return node.copy() if re.fullmatch(r"\d+", node.name) else None if kind == "float": + if not _NUMBER.fullmatch(node.name): + return None try: Decimal(node.name) except InvalidOperation: @@ -180,6 +187,10 @@ def _bound_literal(param: ProcParam, context: Any) -> exp.Expression: value = row_filters._resolve(context, path) if value is row_filters._MISSING: raise ContextError(ViolationCode.MISSING_CONTEXT, f"{{{path}}}") + if value is None or not isinstance(value, (bool, int, float, str)): + raise ContextError(ViolationCode.INVALID_CONTEXT, f"{{{path}}} (not a scalar)") + if isinstance(value, str) and len(value) > _MAX_BOUND_TEXT: + raise ContextError(ViolationCode.INVALID_CONTEXT, f"{{{path}}} (too long)") return row_filters._literal(value, path) @@ -194,6 +205,7 @@ def _finish( # noqa: PLR0917 ) -> tuple[str | None, list[Violation]]: problems: list[Violation] = [] final: dict[str, exp.Expression] = {} + proc_name = rules.name or proc_name for key, node in given.items(): param = rules.params.get(key) if param is None: @@ -212,8 +224,11 @@ def _finish( # noqa: PLR0917 try: final[key] = _bound_literal(param, context) except ContextError as problem: - problems.append(violation(problem.code, problem.detail, language)) - elif key not in final and not problems: + if problem.code == ViolationCode.INVALID_CONTEXT: + problems += _bad(f"{key}: {problem.detail}", language) + else: + problems.append(violation(problem.code, problem.detail, language)) + elif key not in final and not any(p.detail.startswith(f"{key}:") for p in problems): problems += _bad(f"{key}: required parameter missing", language) if problems: return None, problems @@ -234,19 +249,39 @@ def check_execute( # noqa: PLR0917 dialect_name: str, ) -> tuple[str | None, list[Violation]]: """Validate a T-SQL ``EXEC`` against the procedure allowlist.""" + extra = [ + key for key, value in node.args.items() if key not in ("this", "expressions") and value + ] + if extra: + return None, [ + violation( + ViolationCode.PROCEDURE_NOT_ALLOWED, + f"unsupported EXEC clause: {extra[0]}", + language, + ) + ] target = node.this if not isinstance(target, exp.Table) or isinstance(target.this, exp.Parameter): return None, [violation(ViolationCode.PROCEDURE_NOT_ALLOWED, "dynamic SQL", language)] if not isinstance(target.this, exp.Identifier) or target.args.get("catalog"): return None, [violation(ViolationCode.PROCEDURE_NOT_ALLOWED, target.sql(), language)] - proc_name = ".".join( - part.name for part in (target.args.get("db"), target.this) if part is not None - ) + parts = [part for part in (target.args.get("db"), target.this) if part is not None] + if not all(isinstance(part, exp.Identifier) for part in parts): + return None, [violation(ViolationCode.PROCEDURE_NOT_ALLOWED, target.sql(), language)] + proc_name = ".".join(part.name for part in parts) if proc_name.lower() in ("sp_executesql", "sp_execute", "xp_cmdshell"): return None, [violation(ViolationCode.PROCEDURE_NOT_ALLOWED, proc_name, language)] rules = _lookup(proc_name, procedures, default_schema) if rules is None: return None, [violation(ViolationCode.PROCEDURE_NOT_ALLOWED, proc_name, language)] + canon = rules.name.split(".") + flags = [bool(part.args.get("quoted")) for part in parts] + spelled = [part.name for part in parts] + # a quoted part must match the policy spelling exactly; unquoted ones case-insensitively + for index, (text, quoted) in enumerate(zip(reversed(spelled), reversed(flags), strict=False)): + expected = canon[-1 - index] if index < len(canon) else None + if expected is not None and quoted and text != expected: + return None, [violation(ViolationCode.PROCEDURE_NOT_ALLOWED, proc_name, language)] given: dict[str, exp.Expression] = {} for arg in node.expressions: if not ( @@ -308,10 +343,12 @@ def check_call( # noqa: PLR0917 """Validate a PostgreSQL-style ``CALL schema.proc(name => value, ...)``.""" body = node.expression text = body.name if isinstance(body, exp.Expression) else str(body or "") + if any(token in text for token in ("\\", "$", "--", "/*")): + return None, [violation(ViolationCode.PROCEDURE_NOT_ALLOWED, "ambiguous syntax", language)] match = _QUALIFIED.match(text) stripped = text.rstrip() if match is None or not stripped.endswith(")"): - return None, [violation(ViolationCode.PROCEDURE_NOT_ALLOWED, text[:60], language)] + return None, [violation(ViolationCode.PROCEDURE_NOT_ALLOWED, "malformed CALL", language)] proc_name = re.sub(r"\s+", "", match.group(1)) rules = _lookup(proc_name, procedures, default_schema) if rules is None: diff --git a/tests/test_procedures.py b/tests/test_procedures.py index e5a7b8a..a98b28b 100644 --- a/tests/test_procedures.py +++ b/tests/test_procedures.py @@ -6,7 +6,7 @@ from sqlglot import exp from sqlguardllm import Guard, Policy -from sqlguardllm.result import ViolationCode +from sqlguardllm.result import PolicyError, ViolationCode from sqlguardllm.rules.procedures import ( check_procedure_statement, compile_procedures, @@ -118,6 +118,148 @@ def test_the_unicode_prefix_of_a_text_value_is_kept() -> None: assert result.sql is not None and "N'Bogotá'" in result.sql +def _guard_tsql() -> Guard: + return Guard( + Policy( + dialect="tsql", + procedures={ + "dbo.P": {"params": {"@a": "int", "@d": "date"}}, + "dbo.B": {"params": {"@t": {"bind": "{user.t}"}}}, + }, + ) + ) + + +def _guard_pg() -> Guard: + return Guard( + Policy( + dialect="postgres", + procedures={"public.p": {"params": {"a": "int", "s": "text"}}}, + ) + ) + + +_NOT_OR_PARAM = {ViolationCode.PROCEDURE_NOT_ALLOWED, ViolationCode.PROCEDURE_PARAM_INVALID} + + +def test_quoted_forms_emit_the_canonical_name() -> None: + guard = _guard_tsql() + for sql in ("EXEC [dbo].[P] @a = 1, @d = '2026-01-01'", "EXEC DBO.p @a = 1, @d = '2026-01-01'"): + result = guard.check(sql) + assert result.ok, sql + assert result.sql is not None and result.sql.startswith("EXEC dbo.P ") + + +def test_quoted_case_mismatch_rejected() -> None: + result = _guard_tsql().check('EXEC "dbo"."p" @a = 1, @d = \'2026-01-01\'') + assert result.codes == {ViolationCode.PROCEDURE_NOT_ALLOWED} + + +def test_catalog_and_linked_server_names_rejected() -> None: + guard = _guard_tsql() + for sql in ("EXEC srv.db.dbo.P @a = 1", "EXEC db.dbo.P @a = 1", "EXEC master..sp_x @a = 1"): + result = guard.check(sql) + assert not result.ok, sql + assert result.codes <= _NOT_OR_PARAM, sql + + +def test_unqualified_name_does_not_match_without_default_schema() -> None: + result = _guard_tsql().check("EXEC P @a = 1, @d = '2026-01-01'") + assert result.codes == {ViolationCode.PROCEDURE_NOT_ALLOWED} + + +def test_exec_extra_clauses_rejected() -> None: + guard = _guard_tsql() + for sql in ( + "EXEC dbo.P;1 @a = 1, @d = '2026-01-01'", + "EXEC dbo.P @a = 1, @d = '2026-01-01' WITH RECOMPILE", + "EXEC dbo.P @a = 1, @d = '2026-01-01' WITH RESULT SETS ((x int))", + "EXEC AS USER = 'u'", + "EXEC dbo.P @a = 1 OUTPUT", + "EXEC @rc = dbo.P @a = 1, @d = '2026-01-01'", + ): + result = guard.check(sql) + assert not result.ok, sql + assert result.codes <= _NOT_OR_PARAM | {ViolationCode.PARSE_ERROR}, sql + + +def test_stacked_statements_rejected() -> None: + stacked = _guard_tsql().check("EXEC dbo.P @a = 1, @d = '2026-01-01'; DROP TABLE x") + assert not stacked.ok and ViolationCode.MULTIPLE_STATEMENTS in stacked.codes + result = _guard_pg().check("CALL public.p(a => 1, s => 'x'); CALL public.p(a => 2, s => 'y')") + assert not result.ok and ViolationCode.MULTIPLE_STATEMENTS in result.codes + + +def test_negative_int_consistent_on_exec_and_call() -> None: + assert _guard_tsql().check("EXEC dbo.P @a = -5, @d = '2026-01-01'").ok + result = _guard_pg().check("CALL public.p(a => -5, s => 'x')") + assert result.ok + assert result.sql is not None and "-5" in result.sql + + +def test_call_backslash_rejected() -> None: + result = _guard_pg().check(r"CALL public.p(a => 1, s => 'a\')") + assert not result.ok + assert result.codes <= _NOT_OR_PARAM + + +def test_call_ambiguous_literals_rejected() -> None: + guard = _guard_pg() + for sql in ( + "CALL public.p(a => 1, s => E'x')", + "CALL public.p(a => 1, s => $$x$$)", + "CALL public.p(a => 1, s => 'x') -- c", + "CALL public.p(/* c */ a => 1, s => 'x')", + "CALL public.p(a => 1, s => 'x'); ", + ): + result = guard.check(sql) + assert not result.ok or "--" not in (result.sql or ""), sql + assert result.codes <= _NOT_OR_PARAM | {ViolationCode.PARSE_ERROR}, sql + + +def test_call_quotes_and_parens_inside_strings() -> None: + guard = _guard_pg() + assert guard.check("CALL public.p(a => 1, s => 'it''s')").ok + result = guard.check("CALL public.p(a => 1, s => 'x) , a => 2 (')") + assert result.ok or result.codes <= _NOT_OR_PARAM + + +def test_bound_value_must_be_scalar() -> None: + guard = _guard_tsql() + for value in ([1, 2], (1,), None, {"x": 1}): + result = guard.check("EXEC dbo.B", {"user": {"t": value}}) + assert result.codes == {ViolationCode.PROCEDURE_PARAM_INVALID}, value + + +def test_bound_missing_path() -> None: + result = _guard_tsql().check("EXEC dbo.B", {"user": {}}) + assert result.codes == {ViolationCode.MISSING_CONTEXT} + + +def test_bound_string_with_quote_is_escaped() -> None: + result = _guard_tsql().check("EXEC dbo.B", {"user": {"t": "a'b"}}) + assert result.ok + assert result.sql is not None and "'a''b'" in result.sql + + +def test_bound_param_set_by_model_case_variant() -> None: + result = _guard_tsql().check("EXEC dbo.B @T = 9", {"user": {"t": 1}}) + assert result.codes == {ViolationCode.PROCEDURE_PARAM_INVALID} + + +def test_date_must_be_a_full_date() -> None: + result = _guard_tsql().check("EXEC dbo.P @a = 1, @d = '2026-01-01; DROP TABLE x'") + assert result.codes == {ViolationCode.PROCEDURE_PARAM_INVALID} + + +def test_duplicate_policy_procedures_rejected() -> None: + try: + Guard(Policy(dialect="tsql", procedures={"dbo.P": {}, "DBO.p": {}})) + except PolicyError: + return + raise AssertionError("expected PolicyError") + + def test_postgres_call_needs_named_arguments() -> None: guard = Guard(Policy(dialect="postgres", procedures={"public.p": {"params": {"a": "int"}}})) assert guard.check("CALL public.p(a => 1)").ok