Skip to main content

vlorql_core/policy/
engine.rs

1//! Table-, column-, and row-level policy evaluation.
2
3use super::config::{PolicyConfig, RowFilter, TablePolicy};
4use crate::errors::{PolicyErrorKind, SchemaErrorKind, VlorQLError};
5use crate::query::{
6    ColumnReference, QueryScope, QuerySource, collect_plan_references, collect_predicate_references,
7};
8use crate::schema::{
9    Expression, InTarget, Predicate, Projection, QueryPlan, SchemaSnapshot, TableSchema,
10};
11use serde_json::json;
12use std::collections::HashSet;
13
14/// Evaluates query plans against a fixed policy configuration.
15///
16/// # Examples
17///
18/// ```
19/// use vlorql_core::policy::{PolicyConfig, PolicyEngine};
20///
21/// let engine = PolicyEngine::new(PolicyConfig::default());
22/// assert!(engine.config().table_policies.is_empty());
23/// ```
24#[derive(Debug, Clone)]
25pub struct PolicyEngine {
26    config: PolicyConfig,
27}
28
29impl PolicyEngine {
30    /// Creates an engine from an immutable policy configuration.
31    pub fn new(config: PolicyConfig) -> Self {
32        Self { config }
33    }
34
35    /// Returns the configuration used by this engine.
36    pub fn config(&self) -> &PolicyConfig {
37        &self.config
38    }
39
40    /// Validates all base-table and column references and collects every violation.
41    pub fn validate(
42        &self,
43        plan: &QueryPlan,
44        schema: &SchemaSnapshot,
45    ) -> Result<(), Vec<VlorQLError>> {
46        let mut errors = Vec::new();
47        self.validate_plan(plan, schema, &mut errors);
48
49        if errors.is_empty() {
50            Ok(())
51        } else {
52            Err(errors)
53        }
54    }
55
56    /// Combines every applicable row filter into one left-associated `AND` predicate.
57    ///
58    /// The returned predicate contains policy filters only. The caller is responsible
59    /// for combining it with the query plan's existing `WHERE` predicate.
60    pub fn apply_row_filters(&self, plan: &QueryPlan) -> Option<Predicate> {
61        let sources = QueryScope::from_plan(plan).sources;
62        let mut filters = Vec::new();
63
64        for source in &sources {
65            if let Some(filter) = self
66                .get_policy_for_table(&source.table)
67                .and_then(|policy| policy.row_filter.as_ref())
68            {
69                filters.push(filter.condition.clone());
70            }
71        }
72
73        for filter in &self.config.row_filters {
74            if row_filter_matches_sources(filter, &sources) {
75                filters.push(filter.condition.clone());
76            }
77        }
78
79        combine_with_and(filters)
80    }
81
82    /// Returns whether a table and column pass the configured policy rules.
83    pub fn is_column_allowed(&self, table: &str, column: &str) -> bool {
84        if self.is_globally_denied(table, column) {
85            return false;
86        }
87
88        let Some(policy) = self.get_policy_for_table(table) else {
89            return true;
90        };
91        if !policy.allowed || contains_name(&policy.denied_columns, column) {
92            return false;
93        }
94
95        match &policy.allowed_columns {
96            Some(allowed) => contains_name(allowed, column),
97            None => true,
98        }
99    }
100
101    /// Returns the table-specific row filter, if configured.
102    pub fn get_row_filter(&self, table: &str) -> Option<&RowFilter> {
103        self.get_policy_for_table(table)?.row_filter.as_ref()
104    }
105
106    /// Returns the policy configured for an exact schema table name.
107    pub fn get_policy_for_table(&self, table: &str) -> Option<&TablePolicy> {
108        self.config.table_policies.get(table)
109    }
110
111    fn validate_plan(
112        &self,
113        plan: &QueryPlan,
114        schema: &SchemaSnapshot,
115        errors: &mut Vec<VlorQLError>,
116    ) {
117        self.validate_plan_inner(plan, schema, errors, None);
118    }
119
120    fn validate_plan_inner(
121        &self,
122        plan: &QueryPlan,
123        schema: &SchemaSnapshot,
124        errors: &mut Vec<VlorQLError>,
125        outer_scope: Option<&QueryScope>,
126    ) {
127        // A CTE's body is an independent query scope and must be checked recursively.
128        if let Some(ctes) = &plan.ctes {
129            for cte in ctes {
130                self.validate_plan_inner(&cte.query, schema, errors, None);
131            }
132        }
133
134        let mut scope = QueryScope::from_plan(plan);
135        if let Some(outer) = outer_scope {
136            scope.extend_with_outer(outer);
137        }
138        let mut reported_tables = HashSet::new();
139        let mut reported_columns = HashSet::new();
140
141        for source in &scope.sources {
142            if scope.cte_names.contains(&source.table) {
143                continue;
144            }
145            let Some(table_schema) = schema.get_table(&source.table) else {
146                if reported_tables.insert(("schema", source.table.clone())) {
147                    errors.push(table_not_found_error(&source.table, schema));
148                }
149                continue;
150            };
151            self.validate_table_access(table_schema, errors, &mut reported_tables);
152        }
153
154        let references = collect_plan_references(plan);
155        for star in &references.stars {
156            self.validate_star(
157                star.as_deref(),
158                &scope,
159                schema,
160                errors,
161                &mut reported_tables,
162                &mut reported_columns,
163            );
164        }
165        for column in &references.columns {
166            self.validate_column_reference(
167                column,
168                &scope,
169                schema,
170                errors,
171                &mut reported_tables,
172                &mut reported_columns,
173            );
174        }
175
176        self.validate_subqueries_in_plan(plan, schema, errors, &scope);
177    }
178
179    fn validate_subqueries_in_plan(
180        &self,
181        plan: &QueryPlan,
182        schema: &SchemaSnapshot,
183        errors: &mut Vec<VlorQLError>,
184        outer_scope: &QueryScope,
185    ) {
186        for projection in &plan.select {
187            if let Projection::Expr { expression, .. } = projection {
188                self.validate_subqueries_in_expression(expression, schema, errors, outer_scope);
189            }
190        }
191        if let Some(predicate) = &plan.r#where {
192            self.validate_subqueries_in_predicate(predicate, schema, errors, outer_scope);
193        }
194        if let Some(expressions) = &plan.group_by {
195            for expression in expressions {
196                self.validate_subqueries_in_expression(expression, schema, errors, outer_scope);
197            }
198        }
199        if let Some(predicate) = &plan.having {
200            self.validate_subqueries_in_predicate(predicate, schema, errors, outer_scope);
201        }
202        if let Some(terms) = &plan.order_by {
203            for term in terms {
204                self.validate_subqueries_in_expression(&term.expr, schema, errors, outer_scope);
205            }
206        }
207        if let Some(joins) = &plan.joins {
208            for join in joins {
209                self.validate_subqueries_in_predicate(&join.on, schema, errors, outer_scope);
210            }
211        }
212    }
213
214    fn validate_subqueries_in_expression(
215        &self,
216        expression: &Expression,
217        schema: &SchemaSnapshot,
218        errors: &mut Vec<VlorQLError>,
219        outer_scope: &QueryScope,
220    ) {
221        match expression {
222            Expression::SubQuery { query } => {
223                self.validate_plan_inner(query, schema, errors, Some(outer_scope));
224            }
225            Expression::FunctionCall { args, .. } => {
226                for argument in args {
227                    self.validate_subqueries_in_expression(argument, schema, errors, outer_scope);
228                }
229            }
230            Expression::BinaryOp { left, right, .. } => {
231                self.validate_subqueries_in_expression(left, schema, errors, outer_scope);
232                self.validate_subqueries_in_expression(right, schema, errors, outer_scope);
233            }
234            _ => {}
235        }
236    }
237
238    fn validate_subqueries_in_predicate(
239        &self,
240        predicate: &Predicate,
241        schema: &SchemaSnapshot,
242        errors: &mut Vec<VlorQLError>,
243        outer_scope: &QueryScope,
244    ) {
245        match predicate {
246            Predicate::Comparison { left, right, .. } => {
247                self.validate_subqueries_in_expression(left, schema, errors, outer_scope);
248                self.validate_subqueries_in_expression(right, schema, errors, outer_scope);
249            }
250            Predicate::And { left, right } | Predicate::Or { left, right } => {
251                self.validate_subqueries_in_predicate(left, schema, errors, outer_scope);
252                self.validate_subqueries_in_predicate(right, schema, errors, outer_scope);
253            }
254            Predicate::Not { child } => {
255                self.validate_subqueries_in_predicate(child, schema, errors, outer_scope);
256            }
257            Predicate::Between { expr, low, high } => {
258                self.validate_subqueries_in_expression(expr, schema, errors, outer_scope);
259                self.validate_subqueries_in_expression(low, schema, errors, outer_scope);
260                self.validate_subqueries_in_expression(high, schema, errors, outer_scope);
261            }
262            Predicate::In { expr, target } => {
263                self.validate_subqueries_in_expression(expr, schema, errors, outer_scope);
264                if let InTarget::SubQuery(query) = target {
265                    self.validate_plan_inner(query, schema, errors, Some(outer_scope));
266                }
267            }
268            Predicate::Exists { query } => {
269                self.validate_plan_inner(query, schema, errors, Some(outer_scope));
270            }
271            Predicate::Like { expr, .. } | Predicate::IsNull { expr } => {
272                self.validate_subqueries_in_expression(expr, schema, errors, outer_scope);
273            }
274        }
275    }
276
277    fn validate_table_access(
278        &self,
279        table: &TableSchema,
280        errors: &mut Vec<VlorQLError>,
281        reported_tables: &mut HashSet<(&'static str, String)>,
282    ) {
283        let denied = self
284            .get_policy_for_table(&table.name)
285            .is_some_and(|policy| !policy.allowed);
286        if denied && reported_tables.insert(("policy", table.name.clone())) {
287            errors.push(VlorQLError::policy(
288                PolicyErrorKind::TableDenied {
289                    table: table.name.clone(),
290                },
291                json!({
292                    "table": table.name,
293                    "reason": "table_policy_denied",
294                }),
295            ));
296        }
297    }
298
299    fn validate_star(
300        &self,
301        qualifier: Option<&str>,
302        scope: &QueryScope,
303        schema: &SchemaSnapshot,
304        errors: &mut Vec<VlorQLError>,
305        reported_tables: &mut HashSet<(&'static str, String)>,
306        reported_columns: &mut HashSet<(String, String, &'static str)>,
307    ) {
308        let sources = match qualifier {
309            Some(qualifier) => match scope.resolve_source(qualifier) {
310                Some(source) => vec![source],
311                None => {
312                    if reported_tables.insert(("schema", qualifier.to_owned())) {
313                        errors.push(table_not_in_scope_or_not_found(qualifier, schema));
314                    }
315                    return;
316                }
317            },
318            None => scope.sources.iter().collect(),
319        };
320
321        for source in sources {
322            if scope.cte_names.contains(&source.table) {
323                continue;
324            }
325            let Some(table) = schema.get_table(&source.table) else {
326                continue;
327            };
328            for column in &table.columns {
329                self.validate_column_policy(table, &column.name, errors, reported_columns);
330            }
331        }
332    }
333
334    fn validate_column_reference(
335        &self,
336        reference: &ColumnReference,
337        scope: &QueryScope,
338        schema: &SchemaSnapshot,
339        errors: &mut Vec<VlorQLError>,
340        reported_tables: &mut HashSet<(&'static str, String)>,
341        reported_columns: &mut HashSet<(String, String, &'static str)>,
342    ) {
343        if let Some(qualifier) = &reference.table {
344            let Some(source) = scope.resolve_source(qualifier) else {
345                if reported_tables.insert(("schema", qualifier.clone())) {
346                    errors.push(table_not_in_scope_or_not_found(qualifier, schema));
347                }
348                return;
349            };
350            if scope.cte_names.contains(&source.table) {
351                return;
352            }
353            let Some(table) = schema.get_table(&source.table) else {
354                return;
355            };
356            self.validate_existing_column(table, &reference.column, errors, reported_columns);
357            return;
358        }
359
360        let candidates: Vec<_> = scope
361            .sources
362            .iter()
363            .filter(|source| !scope.cte_names.contains(&source.table))
364            .filter_map(|source| schema.get_table(&source.table))
365            .filter(|table| {
366                table
367                    .columns
368                    .iter()
369                    .any(|column| column.name == reference.column)
370            })
371            .collect();
372
373        if candidates.is_empty() {
374            // An unqualified CTE column cannot be resolved without deriving the CTE output
375            // schema, which belongs to schema validation rather than policy evaluation.
376            if scope
377                .sources
378                .iter()
379                .any(|source| scope.cte_names.contains(&source.table))
380            {
381                return;
382            }
383            let table = scope
384                .sources
385                .first()
386                .map_or("<unknown>", |source| source.table.as_str());
387            self.push_missing_column(table, &reference.column, schema, errors, reported_columns);
388            return;
389        }
390
391        // Conservatively enforce policy for every matching table. An ambiguous SQL
392        // reference will be rejected later by schema validation, but must not bypass policy.
393        for table in candidates {
394            self.validate_column_policy(table, &reference.column, errors, reported_columns);
395        }
396    }
397
398    fn validate_existing_column(
399        &self,
400        table: &TableSchema,
401        column: &str,
402        errors: &mut Vec<VlorQLError>,
403        reported_columns: &mut HashSet<(String, String, &'static str)>,
404    ) {
405        if table
406            .columns
407            .iter()
408            .any(|candidate| candidate.name == column)
409        {
410            self.validate_column_policy(table, column, errors, reported_columns);
411        } else {
412            self.push_missing_column(
413                &table.name,
414                column,
415                &SchemaView::from_table(table),
416                errors,
417                reported_columns,
418            );
419        }
420    }
421
422    fn push_missing_column<S: AvailableColumns>(
423        &self,
424        table: &str,
425        column: &str,
426        schema: &S,
427        errors: &mut Vec<VlorQLError>,
428        reported_columns: &mut HashSet<(String, String, &'static str)>,
429    ) {
430        if reported_columns.insert((table.to_owned(), column.to_owned(), "schema")) {
431            errors.push(VlorQLError::schema(
432                SchemaErrorKind::ColumnNotFound {
433                    table: table.to_owned(),
434                    column: column.to_owned(),
435                },
436                json!({
437                    "table": table,
438                    "column": column,
439                    "available_columns": schema.available_columns(table),
440                }),
441            ));
442        }
443    }
444
445    fn validate_column_policy(
446        &self,
447        table: &TableSchema,
448        column: &str,
449        errors: &mut Vec<VlorQLError>,
450        reported_columns: &mut HashSet<(String, String, &'static str)>,
451    ) {
452        let reason = self.column_denial_reason(&table.name, column);
453        if let Some(reason) = reason
454            && reported_columns.insert((table.name.clone(), column.to_owned(), reason))
455        {
456            errors.push(VlorQLError::policy(
457                PolicyErrorKind::ColumnDenied {
458                    table: table.name.clone(),
459                    column: column.to_owned(),
460                },
461                json!({
462                    "table": table.name,
463                    "column": column,
464                    "reason": reason,
465                }),
466            ));
467        }
468    }
469
470    fn column_denial_reason(&self, table: &str, column: &str) -> Option<&'static str> {
471        if self.is_globally_denied(table, column) {
472            return Some("global_denied_column");
473        }
474
475        let policy = self.get_policy_for_table(table)?;
476        if !policy.allowed {
477            return None;
478        }
479        if contains_name(&policy.denied_columns, column) {
480            return Some("table_denied_column");
481        }
482        if policy
483            .allowed_columns
484            .as_ref()
485            .is_some_and(|allowed| !contains_name(allowed, column))
486        {
487            return Some("column_not_in_allowlist");
488        }
489        None
490    }
491
492    fn is_globally_denied(&self, table: &str, column: &str) -> bool {
493        self.config.global_denied_columns.iter().any(|denied| {
494            denied.len() == column.len() && denied == column
495                || denied.len() > table.len() + 1
496                    && denied.starts_with(table)
497                    && denied.as_bytes().get(table.len()) == Some(&b'.')
498                    && &denied[table.len() + 1..] == column
499        })
500    }
501}
502
503fn table_not_found_error(table: &str, schema: &SchemaSnapshot) -> VlorQLError {
504    VlorQLError::schema(
505        SchemaErrorKind::TableNotFound {
506            table: table.to_owned(),
507        },
508        json!({
509            "table": table,
510            "available_tables": schema
511                .tables
512                .iter()
513                .map(|candidate| candidate.name.as_str())
514                .collect::<Vec<_>>(),
515        }),
516    )
517}
518
519fn table_not_in_scope_or_not_found(table: &str, schema: &SchemaSnapshot) -> VlorQLError {
520    let context = json!({
521        "table": table,
522        "available_tables": schema
523            .tables
524            .iter()
525            .map(|candidate| candidate.name.as_str())
526            .collect::<Vec<_>>(),
527    });
528    if schema.get_table(table).is_some() {
529        VlorQLError::schema(
530            SchemaErrorKind::TableNotInScope {
531                table: table.to_owned(),
532            },
533            context,
534        )
535    } else {
536        VlorQLError::schema(
537            SchemaErrorKind::TableNotFound {
538                table: table.to_owned(),
539            },
540            context,
541        )
542    }
543}
544
545trait AvailableColumns {
546    fn available_columns(&self, table: &str) -> Vec<&str>;
547}
548
549impl AvailableColumns for SchemaSnapshot {
550    fn available_columns(&self, table: &str) -> Vec<&str> {
551        self.get_table(table)
552            .map(|table| {
553                table
554                    .columns
555                    .iter()
556                    .map(|column| column.name.as_str())
557                    .collect()
558            })
559            .unwrap_or_default()
560    }
561}
562
563struct SchemaView<'a> {
564    table: &'a TableSchema,
565}
566
567impl<'a> SchemaView<'a> {
568    fn from_table(table: &'a TableSchema) -> Self {
569        Self { table }
570    }
571}
572
573impl AvailableColumns for SchemaView<'_> {
574    fn available_columns(&self, table: &str) -> Vec<&str> {
575        if self.table.name == table {
576            self.table
577                .columns
578                .iter()
579                .map(|column| column.name.as_str())
580                .collect()
581        } else {
582            Vec::new()
583        }
584    }
585}
586
587fn contains_name(names: &[String], candidate: &str) -> bool {
588    names.iter().any(|name| name == candidate)
589}
590
591fn combine_with_and(filters: Vec<Predicate>) -> Option<Predicate> {
592    filters.into_iter().reduce(|left, right| Predicate::And {
593        left: Box::new(left),
594        right: Box::new(right),
595    })
596}
597
598fn row_filter_matches_sources(filter: &RowFilter, sources: &[QuerySource]) -> bool {
599    let mut references = Vec::new();
600    collect_predicate_references(&filter.condition, &mut references);
601    let qualified_tables: HashSet<_> = references
602        .iter()
603        .filter_map(|reference| reference.table.as_deref())
604        .collect();
605
606    if qualified_tables.is_empty() {
607        return !sources.is_empty();
608    }
609
610    qualified_tables.iter().all(|qualifier| {
611        sources.iter().any(|source| {
612            source.table == **qualifier || source.alias.as_deref() == Some(*qualifier)
613        })
614    })
615}