chio-data-guards 0.1.0

Data layer guards for the Chio runtime kernel (SQL, vector DB, warehouse cost).
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
//! The `SqlQueryGuard` implementation.
//!
//! The guard listens for `ToolAction::DatabaseQuery { database, query }` via
//! [`chio_guards::extract_action`] and enforces four knobs defined by
//! [`SqlGuardConfig`]: operation allowlist, table allowlist, per-table
//! column allowlist, and regex predicate denylist.  Failures route through
//! [`SqlGuardDenyReason`](crate::error::SqlGuardDenyReason) so downstream
//! callers can match on structured reasons.
//!
//! Fail-closed semantics:
//!
//! - parse errors deny (even when `allow_all` is set);
//! - empty configurations deny unless `allow_all` is set;
//! - any check that fails short-circuits to `Verdict::Deny`;
//! - the guard passes non-`DatabaseQuery` actions through with
//!   `Verdict::Allow` (guards are additive).

use regex::{Regex, RegexBuilder};
use tracing::warn;

use chio_guards::{extract_action, ToolAction};
use chio_kernel::{GuardContext, KernelError, Verdict};

use crate::config::{SqlGuardConfig, SqlOperation};
use crate::error::SqlGuardDenyReason;
use crate::sql_parser::{self, SqlAnalysis};

/// Built-in SQL query guard (roadmap phase 7.1).
pub struct SqlQueryGuard {
    config: SqlGuardConfig,
    denylist_regex: Vec<(String, Regex)>,
}

const MAX_DENYLISTED_PREDICATES: usize = 64;
const MAX_DENYLISTED_PREDICATE_LEN: usize = 512;
const MAX_DENYLISTED_PREDICATE_COMPLEXITY: usize = 96;
const DENYLISTED_PREDICATE_REGEX_SIZE_LIMIT: usize = 1 << 20;
const DENYLISTED_PREDICATE_DFA_SIZE_LIMIT: usize = 1 << 20;

impl SqlQueryGuard {
    /// Construct a new guard with the given configuration.
    ///
    /// Invalid or over-broad `denylisted_predicates` produce a guard that
    /// denies every SQL query. Use [`Self::try_new`] when policy loading should
    /// reject invalid configurations directly.
    pub fn new(config: SqlGuardConfig) -> Self {
        match Self::try_new(config) {
            Ok(guard) => guard,
            Err(error) => {
                warn!(
                    target: "chio.data-guards.sql",
                    error = %error,
                    "invalid sql-query-guard config; constructing fail-closed deny-all guard"
                );
                Self {
                    config: SqlGuardConfig::default(),
                    denylist_regex: Vec::new(),
                }
            }
        }
    }

    /// Construct a new guard or reject invalid user-supplied regex patterns.
    pub fn try_new(config: SqlGuardConfig) -> Result<Self, String> {
        if config.allow_all {
            warn!(
                target: "chio.data-guards.sql",
                "sql-query-guard constructed with allow_all=true; fail-closed default disabled"
            );
        }

        if config.denylisted_predicates.len() > MAX_DENYLISTED_PREDICATES {
            return Err(format!(
                "sql_query.denylisted_predicates allows at most {MAX_DENYLISTED_PREDICATES} patterns"
            ));
        }
        let mut denylist_regex = Vec::with_capacity(config.denylisted_predicates.len());
        for pattern in &config.denylisted_predicates {
            let trimmed = pattern.trim();
            if trimmed.is_empty() {
                return Err("sql_query.denylisted_predicates cannot contain empty patterns".into());
            }
            if trimmed.len() > MAX_DENYLISTED_PREDICATE_LEN {
                return Err(format!(
                    "sql_query.denylisted_predicates entries must be at most {MAX_DENYLISTED_PREDICATE_LEN} characters"
                ));
            }
            let complexity = predicate_pattern_complexity(trimmed);
            if complexity > MAX_DENYLISTED_PREDICATE_COMPLEXITY {
                return Err(format!(
                    "sql_query.denylisted_predicates entries must have complexity at most {MAX_DENYLISTED_PREDICATE_COMPLEXITY}"
                ));
            }
            let re = RegexBuilder::new(trimmed)
                .case_insensitive(true)
                .size_limit(DENYLISTED_PREDICATE_REGEX_SIZE_LIMIT)
                .dfa_size_limit(DENYLISTED_PREDICATE_DFA_SIZE_LIMIT)
                .build()
                .map_err(|error| {
                    format!("invalid sql_query.denylisted_predicates entry `{trimmed}`: {error}")
                })?;
            denylist_regex.push((trimmed.to_string(), re));
        }

        Ok(Self {
            config,
            denylist_regex,
        })
    }

    /// Read-only access to the configuration (useful for tests and
    /// observability).
    pub fn config(&self) -> &SqlGuardConfig {
        &self.config
    }

    /// Evaluate a raw SQL query string against the configured policy.
    ///
    /// Returns `Ok(())` to allow, `Err(SqlGuardDenyReason)` to deny.  This
    /// is the primary testing and integration entry point; the
    /// [`chio_kernel::Guard`] impl is a thin wrapper that maps this result
    /// to [`Verdict`].
    pub fn analyze(&self, query: &str) -> Result<SqlAnalysis, SqlGuardDenyReason> {
        // Fail-closed on parse error, even when allow_all is set.
        let analysis = sql_parser::parse(query, self.config.dialect)
            .map_err(|e| SqlGuardDenyReason::ParseError { error: e })?;

        if self.config.allow_all {
            return Ok(analysis);
        }

        if self.config.is_empty() {
            return Err(SqlGuardDenyReason::NoConfig);
        }

        self.enforce_operation(&analysis)?;
        self.enforce_tables(&analysis)?;
        self.enforce_columns(&analysis)?;
        self.enforce_predicate_denylist(&analysis)?;
        self.enforce_where_for_mutations(&analysis)?;

        Ok(analysis)
    }

    fn enforce_operation(&self, analysis: &SqlAnalysis) -> Result<(), SqlGuardDenyReason> {
        if self.config.operation_allowlist.is_empty() {
            // If no operation allowlist was set but other lists are, we
            // conservatively require an explicit allowlist: fail-closed.
            return Err(SqlGuardDenyReason::OperationNotAllowed {
                operation: analysis.operation.as_str().to_string(),
            });
        }
        if !self
            .config
            .operation_allowlist
            .contains(&analysis.operation)
        {
            return Err(SqlGuardDenyReason::OperationNotAllowed {
                operation: analysis.operation.as_str().to_string(),
            });
        }
        Ok(())
    }

    fn enforce_tables(&self, analysis: &SqlAnalysis) -> Result<(), SqlGuardDenyReason> {
        if self.config.table_allowlist.is_empty() {
            return Err(SqlGuardDenyReason::TableNotAllowed {
                table: analysis
                    .tables
                    .first()
                    .cloned()
                    .unwrap_or_else(|| "<none>".to_string()),
            });
        }
        for table in &analysis.tables {
            if !self.config.table_allowed(table) {
                return Err(SqlGuardDenyReason::TableNotAllowed {
                    table: table.clone(),
                });
            }
        }
        Ok(())
    }

    fn enforce_columns(&self, analysis: &SqlAnalysis) -> Result<(), SqlGuardDenyReason> {
        if analysis.operation != SqlOperation::Select {
            return Ok(());
        }
        let Some(_) = self.config.column_allowlist.as_ref() else {
            return Ok(());
        };

        for (table, column) in &analysis.projected_columns {
            // Wildcard projection: deny whenever the table has an
            // explicit column allowlist.  We cannot prove the expansion
            // is inside the allowed set.
            if column == "*" {
                if self.config.table_has_column_allowlist(table) {
                    return Err(SqlGuardDenyReason::SelectStarDenied {
                        table: table.clone(),
                    });
                }
                continue;
            }

            // Computed/opaque projections (`"?"` from the parser, e.g.
            // `SELECT lower(ssn) FROM users`) or JOINs where the source
            // table cannot be resolved (parser emits `table == "?"` too).
            // A per-table allowlist check is not enough: the computed
            // expression could read any column from any joined table,
            // and for JOINs `table == "?"` never matches a real
            // allowlist entry, letting sensitive columns leak through
            // expressions like `lower(users.ssn)`.
            //
            // We reach this branch only after the early return at the
            // top of `enforce_columns` proved that SOME column allowlist
            // is configured, so fail closed uniformly on any `"?"`
            // projection: the guard cannot prove the expression stays
            // inside the allowed set without evaluating it.
            if column == "?" {
                return Err(SqlGuardDenyReason::ColumnNotAllowed {
                    table: table.clone(),
                    column: "?".to_string(),
                });
            }

            // Apply the column allowlist for this table if configured.
            match self.config.column_allowed(table, column) {
                Some(true) => {}
                Some(false) => {
                    return Err(SqlGuardDenyReason::ColumnNotAllowed {
                        table: table.clone(),
                        column: column.clone(),
                    })
                }
                None => {
                    // Table has no column allowlist entry: allow.
                }
            }
        }
        Ok(())
    }

    fn enforce_predicate_denylist(&self, analysis: &SqlAnalysis) -> Result<(), SqlGuardDenyReason> {
        if self.denylist_regex.is_empty() {
            return Ok(());
        }
        if analysis.where_canonical.is_empty() {
            return Ok(());
        }
        for (pattern, re) in &self.denylist_regex {
            if re.is_match(&analysis.where_canonical) {
                return Err(SqlGuardDenyReason::PredicateDenylisted {
                    pattern: pattern.clone(),
                });
            }
        }
        Ok(())
    }

    fn enforce_where_for_mutations(
        &self,
        analysis: &SqlAnalysis,
    ) -> Result<(), SqlGuardDenyReason> {
        if !self.config.require_where_for_mutations {
            return Ok(());
        }
        let needs_where = matches!(
            analysis.operation,
            SqlOperation::Update | SqlOperation::Delete
        );
        if needs_where && !analysis.has_where {
            return Err(SqlGuardDenyReason::MissingWhereClause {
                operation: analysis.operation.as_str().to_string(),
            });
        }
        Ok(())
    }
}

fn predicate_pattern_complexity(pattern: &str) -> usize {
    let mut score = 0usize;
    let mut escaped = false;
    for ch in pattern.chars() {
        if escaped {
            escaped = false;
            continue;
        }
        match ch {
            '\\' => escaped = true,
            '|' | '*' | '+' | '?' => score = score.saturating_add(4),
            '{' | '[' | '(' => score = score.saturating_add(2),
            _ => {}
        }
    }
    score
}

impl chio_kernel::Guard for SqlQueryGuard {
    fn name(&self) -> &str {
        "sql-query"
    }

    fn evaluate(&self, ctx: &GuardContext) -> Result<Verdict, KernelError> {
        let action = extract_action(&ctx.request.tool_name, &ctx.request.arguments);
        let (database, query) = match &action {
            ToolAction::DatabaseQuery { database, query } => (database.as_str(), query.as_str()),
            _ => return Ok(Verdict::Allow),
        };

        match self.analyze(query) {
            Ok(_) => Ok(Verdict::Allow),
            Err(reason) => {
                warn!(
                    target: "chio.data-guards.sql",
                    database = %database,
                    code = reason.code(),
                    reason = %reason,
                    "sql-query-guard denied query"
                );
                Ok(Verdict::Deny)
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::collections::HashMap;

    use crate::config::{SqlDialect, SqlGuardConfig, SqlOperation};

    fn cfg_select_orders() -> SqlGuardConfig {
        SqlGuardConfig {
            dialect: SqlDialect::Generic,
            operation_allowlist: vec![SqlOperation::Select],
            table_allowlist: vec!["orders".to_string()],
            ..Default::default()
        }
    }

    #[test]
    fn allow_select_from_allowed_table() {
        let g = SqlQueryGuard::new(cfg_select_orders());
        g.analyze("SELECT id FROM orders").expect("allowed");
    }

    #[test]
    fn deny_select_from_unlisted_table() {
        let g = SqlQueryGuard::new(cfg_select_orders());
        let err = g.analyze("SELECT * FROM users").expect_err("denied");
        assert!(matches!(err, SqlGuardDenyReason::TableNotAllowed { .. }));
    }

    #[test]
    fn deny_drop_when_ddl_not_allowed() {
        let g = SqlQueryGuard::new(cfg_select_orders());
        let err = g.analyze("DROP TABLE orders").expect_err("denied");
        assert!(matches!(
            err,
            SqlGuardDenyReason::OperationNotAllowed { .. }
        ));
    }

    #[test]
    fn deny_update_when_only_select_allowed() {
        let g = SqlQueryGuard::new(cfg_select_orders());
        let err = g
            .analyze("UPDATE orders SET foo=1 WHERE id=1")
            .expect_err("denied");
        assert!(matches!(
            err,
            SqlGuardDenyReason::OperationNotAllowed { .. }
        ));
    }

    #[test]
    fn deny_malformed_sql() {
        let g = SqlQueryGuard::new(cfg_select_orders());
        let err = g.analyze("SELEKT oops").expect_err("denied");
        assert!(matches!(err, SqlGuardDenyReason::ParseError { .. }));
    }

    #[test]
    fn empty_config_denies() {
        let g = SqlQueryGuard::new(SqlGuardConfig::default());
        let err = g.analyze("SELECT 1").expect_err("denied");
        assert!(matches!(err, SqlGuardDenyReason::NoConfig));
    }

    #[test]
    fn allow_all_still_denies_parse_errors() {
        let g = SqlQueryGuard::new(SqlGuardConfig {
            allow_all: true,
            ..Default::default()
        });
        let err = g.analyze("NOT SQL AT ALL ;;;;").expect_err("denied");
        assert!(matches!(err, SqlGuardDenyReason::ParseError { .. }));
    }

    #[test]
    fn allow_all_permits_well_formed_query() {
        let g = SqlQueryGuard::new(SqlGuardConfig {
            allow_all: true,
            ..Default::default()
        });
        g.analyze("SELECT id FROM whatever").expect("allowed");
    }

    #[test]
    fn column_allowlist_denies_unlisted_column() {
        let mut map = HashMap::new();
        map.insert(
            "orders".to_string(),
            vec!["id".to_string(), "total".to_string()],
        );
        let cfg = SqlGuardConfig {
            operation_allowlist: vec![SqlOperation::Select],
            table_allowlist: vec!["orders".into()],
            column_allowlist: Some(map),
            ..Default::default()
        };
        let g = SqlQueryGuard::new(cfg);
        g.analyze("SELECT id, total FROM orders").expect("allowed");
        let err = g
            .analyze("SELECT id, email FROM orders")
            .expect_err("denied");
        assert!(matches!(err, SqlGuardDenyReason::ColumnNotAllowed { .. }));
    }

    #[test]
    fn select_star_denied_when_column_allowlist_active() {
        let mut map = HashMap::new();
        map.insert("orders".to_string(), vec!["id".to_string()]);
        let cfg = SqlGuardConfig {
            operation_allowlist: vec![SqlOperation::Select],
            table_allowlist: vec!["orders".into()],
            column_allowlist: Some(map),
            ..Default::default()
        };
        let g = SqlQueryGuard::new(cfg);
        let err = g.analyze("SELECT * FROM orders").expect_err("denied");
        assert!(matches!(err, SqlGuardDenyReason::SelectStarDenied { .. }));
    }

    #[test]
    fn predicate_denylist_blocks_or_1_equals_1() {
        let cfg = SqlGuardConfig {
            operation_allowlist: vec![SqlOperation::Select],
            table_allowlist: vec!["orders".into()],
            denylisted_predicates: vec![r"\bor\s+1\s*=\s*1\b".to_string()],
            ..Default::default()
        };
        let g = SqlQueryGuard::new(cfg);
        let err = g
            .analyze("SELECT id FROM orders WHERE id = 1 OR 1=1")
            .expect_err("denied");
        assert!(matches!(
            err,
            SqlGuardDenyReason::PredicateDenylisted { .. }
        ));
    }

    #[test]
    fn mutation_without_where_is_denied() {
        let cfg = SqlGuardConfig {
            operation_allowlist: vec![SqlOperation::Delete],
            table_allowlist: vec!["orders".into()],
            ..Default::default()
        };
        let g = SqlQueryGuard::new(cfg);
        let err = g.analyze("DELETE FROM orders").expect_err("denied");
        assert!(matches!(err, SqlGuardDenyReason::MissingWhereClause { .. }));
    }

    #[test]
    fn mutation_where_optional_when_disabled() {
        let cfg = SqlGuardConfig {
            operation_allowlist: vec![SqlOperation::Delete],
            table_allowlist: vec!["orders".into()],
            require_where_for_mutations: false,
            ..Default::default()
        };
        let g = SqlQueryGuard::new(cfg);
        g.analyze("DELETE FROM orders").expect("allowed");
    }
}