qail-core 3.0.1

QAIL AST Kernel - typed query AST, schema validation, RLS context, and native access policy
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
//! RLS Policy Definition (AST-native)
//!
//! Defines PostgreSQL Row-Level Security policies using typed AST
//! expressions — not raw SQL strings. QAIL speaks AST.
//!
//! # Example
//! ```
//! use qail_core::migrate::policy::{RlsPolicy, PolicyTarget};
//! use qail_core::ast::{Expr, BinaryOp, Value};
//!
//! // tenant_id = current_setting('app.current_tenant_id')::uuid
//! let tenant_check = Expr::Binary {
//!     left: Box::new(Expr::Named("tenant_id".into())),
//!     op: BinaryOp::Eq,
//!     right: Box::new(Expr::Cast {
//!         expr: Box::new(Expr::FunctionCall {
//!             name: "current_setting".into(),
//!             args: vec![Expr::Literal(Value::String("app.current_tenant_id".into()))],
//!             alias: None,
//!         }),
//!         target_type: "uuid".into(),
//!         alias: None,
//!     }),
//!     alias: None,
//! };
//!
//! let policy = RlsPolicy::create("orders_operator_isolation", "orders")
//!     .for_all()
//!     .using(tenant_check.clone())
//!     .with_check(tenant_check);
//! ```

use crate::ast::Expr;

/// What the policy applies to (SELECT, INSERT, UPDATE, DELETE, or ALL).
#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub enum PolicyTarget {
    /// Applies to all operations.
    All,
    /// Applies to SELECT queries.
    Select,
    /// Applies to INSERT operations.
    Insert,
    /// Applies to UPDATE operations.
    Update,
    /// Applies to DELETE operations.
    Delete,
}

impl std::fmt::Display for PolicyTarget {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            PolicyTarget::All => write!(f, "ALL"),
            PolicyTarget::Select => write!(f, "SELECT"),
            PolicyTarget::Insert => write!(f, "INSERT"),
            PolicyTarget::Update => write!(f, "UPDATE"),
            PolicyTarget::Delete => write!(f, "DELETE"),
        }
    }
}

/// Whether this is permissive (default) or restrictive.
#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub enum PolicyPermissiveness {
    /// Rows matching ANY permissive policy are visible (OR).
    Permissive,
    /// Rows must also match ALL restrictive policies (AND).
    Restrictive,
}

impl std::fmt::Display for PolicyPermissiveness {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            PolicyPermissiveness::Permissive => write!(f, "PERMISSIVE"),
            PolicyPermissiveness::Restrictive => write!(f, "RESTRICTIVE"),
        }
    }
}

/// AST-native RLS policy definition.
///
/// All expressions use typed `Expr` nodes — no raw SQL strings.
/// The transpiler converts these to `CREATE POLICY ... USING (...) WITH CHECK (...)`.
#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)]
pub struct RlsPolicy {
    /// Policy name (e.g., "orders_operator_isolation")
    pub name: String,
    /// Table this policy applies to
    pub table: String,
    /// Target command(s): ALL, SELECT, INSERT, UPDATE, DELETE
    pub target: PolicyTarget,
    /// Permissive (default) or Restrictive
    pub permissiveness: PolicyPermissiveness,
    /// USING expression — controls which existing rows are visible.
    /// Applied to SELECT, UPDATE (read), DELETE.
    pub using: Option<Expr>,
    /// WITH CHECK expression — controls which new rows can be written.
    /// Applied to INSERT, UPDATE (write).
    pub with_check: Option<Expr>,
    /// Role this policy applies to (default: PUBLIC)
    pub role: Option<String>,
    /// Further roles after `role` (`TO a, b, c`). Requires `role`; PostgreSQL
    /// ignores every other role when PUBLIC is listed, so PUBLIC never appears here.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub additional_roles: Vec<String>,
}

impl RlsPolicy {
    /// Create a new policy builder.
    ///
    /// ```
    /// use qail_core::migrate::policy::RlsPolicy;
    /// let policy = RlsPolicy::create("tenant_isolation", "orders");
    /// ```
    pub fn create(name: impl Into<String>, table: impl Into<String>) -> Self {
        Self {
            name: name.into(),
            table: table.into(),
            target: PolicyTarget::All,
            permissiveness: PolicyPermissiveness::Permissive,
            using: None,
            with_check: None,
            role: None,
            additional_roles: Vec::new(),
        }
    }

    /// Set policy target to ALL (SELECT + INSERT + UPDATE + DELETE).
    pub fn for_all(mut self) -> Self {
        self.target = PolicyTarget::All;
        self
    }

    /// Set policy target to SELECT only.
    pub fn for_select(mut self) -> Self {
        self.target = PolicyTarget::Select;
        self
    }

    /// Set policy target to INSERT only.
    pub fn for_insert(mut self) -> Self {
        self.target = PolicyTarget::Insert;
        self
    }

    /// Set policy target to UPDATE only.
    pub fn for_update(mut self) -> Self {
        self.target = PolicyTarget::Update;
        self
    }

    /// Set policy target to DELETE only.
    pub fn for_delete(mut self) -> Self {
        self.target = PolicyTarget::Delete;
        self
    }

    /// Make this policy restrictive (AND with other policies).
    pub fn restrictive(mut self) -> Self {
        self.permissiveness = PolicyPermissiveness::Restrictive;
        self
    }

    /// Set the USING expression (visibility filter for existing rows).
    /// This is an AST expression, not a raw SQL string.
    pub fn using(mut self, expr: Expr) -> Self {
        self.using = Some(expr);
        self
    }

    /// Set the WITH CHECK expression (write filter for new rows).
    /// This is an AST expression, not a raw SQL string.
    pub fn with_check(mut self, expr: Expr) -> Self {
        self.with_check = Some(expr);
        self
    }

    /// Restrict policy to a specific role.
    pub fn to_role(mut self, role: impl Into<String>) -> Self {
        self.role = Some(role.into());
        self
    }

    /// Restrict policy to several roles (`TO a, b`). An empty list means PUBLIC.
    pub fn to_roles<I, S>(mut self, roles: I) -> Self
    where
        I: IntoIterator<Item = S>,
        S: Into<String>,
    {
        let mut roles = roles.into_iter().map(Into::into);
        self.role = roles.next();
        self.additional_roles = roles.collect();
        self
    }

    /// Every role in `TO` order; empty means PUBLIC.
    pub fn roles(&self) -> Vec<&str> {
        self.role
            .iter()
            .chain(self.additional_roles.iter())
            .map(String::as_str)
            .collect()
    }

    /// Reject role lists PostgreSQL would silently reinterpret.
    pub fn validate_roles(&self) -> Result<(), String> {
        if self.role.is_none() && !self.additional_roles.is_empty() {
            return Err(format!(
                "policy '{}' lists additional roles without a first role",
                self.name
            ));
        }
        let roles = self.roles();
        let mut seen = std::collections::HashSet::new();
        for role in &roles {
            if role.trim().is_empty() {
                return Err(format!("policy '{}' has an empty role name", self.name));
            }
            if !seen.insert(*role) {
                return Err(format!(
                    "policy '{}' lists role '{}' more than once",
                    self.name, role
                ));
            }
            // PostgreSQL warns and drops every other role when PUBLIC is listed.
            if roles.len() > 1 && role.eq_ignore_ascii_case("public") {
                return Err(format!(
                    "policy '{}' combines PUBLIC with other roles; PostgreSQL would ignore the others",
                    self.name
                ));
            }
        }
        Ok(())
    }
}

/// Helper: build the standard tenant isolation expression.
///
/// Generates: `column = current_setting('app.session_var')::cast_type`
///
/// This is the most common RLS pattern and deserves a first-class helper.
///
/// # Example
/// ```
/// use qail_core::migrate::policy::tenant_check;
///
/// let expr = tenant_check("tenant_id", "app.current_tenant_id", "uuid");
/// // Equivalent to: tenant_id = current_setting('app.current_tenant_id')::uuid
/// ```
pub fn tenant_check(
    column: impl Into<String>,
    session_var: impl Into<String>,
    cast_type: impl Into<String>,
) -> Expr {
    use crate::ast::{BinaryOp, Value};

    Expr::Binary {
        left: Box::new(Expr::Named(column.into())),
        op: BinaryOp::Eq,
        right: Box::new(Expr::Cast {
            expr: Box::new(Expr::FunctionCall {
                name: "current_setting".into(),
                args: vec![Expr::Literal(Value::String(session_var.into()))],
                alias: None,
            }),
            target_type: cast_type.into(),
            alias: None,
        }),
        alias: None,
    }
}

/// Helper: build a boolean session variable check.
///
/// Generates: `current_setting('app.session_var')::boolean = true`
///
/// Used for super admin bypass policies.
///
/// # Example
/// ```
/// use qail_core::migrate::policy::session_bool_check;
///
/// let expr = session_bool_check("app.is_super_admin");
/// // Equivalent to: current_setting('app.is_super_admin')::boolean = true
/// ```
pub fn session_bool_check(session_var: impl Into<String>) -> Expr {
    use crate::ast::{BinaryOp, Value};

    Expr::Binary {
        left: Box::new(Expr::Cast {
            expr: Box::new(Expr::FunctionCall {
                name: "current_setting".into(),
                args: vec![Expr::Literal(Value::String(session_var.into()))],
                alias: None,
            }),
            target_type: "boolean".into(),
            alias: None,
        }),
        op: BinaryOp::Eq,
        right: Box::new(Expr::Literal(Value::Bool(true))),
        alias: None,
    }
}

/// Helper: combine two expressions with OR.
///
/// Useful for: `tenant_check OR super_admin_bypass`
pub fn or(left: Expr, right: Expr) -> Expr {
    use crate::ast::BinaryOp;

    Expr::Binary {
        left: Box::new(left),
        op: BinaryOp::Or,
        right: Box::new(right),
        alias: None,
    }
}

/// Helper: combine two expressions with AND.
pub fn and(left: Expr, right: Expr) -> Expr {
    use crate::ast::BinaryOp;

    Expr::Binary {
        left: Box::new(left),
        op: BinaryOp::And,
        right: Box::new(right),
        alias: None,
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::ast::BinaryOp;

    #[test]
    fn test_policy_builder() {
        let policy = RlsPolicy::create("orders_isolation", "orders")
            .for_all()
            .using(tenant_check("tenant_id", "app.current_tenant_id", "uuid"))
            .with_check(tenant_check("tenant_id", "app.current_tenant_id", "uuid"));

        assert_eq!(policy.name, "orders_isolation");
        assert_eq!(policy.table, "orders");
        assert_eq!(policy.target, PolicyTarget::All);
        assert!(policy.using.is_some());
        assert!(policy.with_check.is_some());
    }

    #[test]
    fn test_policy_restrictive() {
        let policy = RlsPolicy::create("admin_only", "secrets")
            .for_select()
            .restrictive()
            .to_role("app_user");

        assert_eq!(policy.target, PolicyTarget::Select);
        assert_eq!(policy.permissiveness, PolicyPermissiveness::Restrictive);
        assert_eq!(policy.role.as_deref(), Some("app_user"));
    }

    #[test]
    fn test_tenant_check_helper() {
        let expr = tenant_check("tenant_id", "app.current_tenant_id", "uuid");

        let Expr::Binary {
            left, op, right, ..
        } = &expr
        else {
            panic!("Expected Binary, got {expr:?}");
        };
        assert_eq!(*op, BinaryOp::Eq);

        let Expr::Named(n) = left.as_ref() else {
            panic!("Expected Named, got {left:?}");
        };
        assert_eq!(n, "tenant_id");

        let Expr::Cast {
            expr: cast_expr,
            target_type,
            ..
        } = right.as_ref()
        else {
            panic!("Expected Cast, got {right:?}");
        };
        assert_eq!(target_type, "uuid");

        let Expr::FunctionCall { name, args, .. } = cast_expr.as_ref() else {
            panic!("Expected FunctionCall, got {cast_expr:?}");
        };
        assert_eq!(name, "current_setting");
        assert_eq!(args.len(), 1);
    }

    #[test]
    fn test_super_admin_bypass() {
        let expr = or(
            tenant_check("tenant_id", "app.current_tenant_id", "uuid"),
            session_bool_check("app.is_super_admin"),
        );

        assert!(
            matches!(
                &expr,
                Expr::Binary {
                    op: BinaryOp::Or,
                    ..
                }
            ),
            "Expected Binary OR, got {expr:?}"
        );
    }

    #[test]
    fn test_and_combinator() {
        let expr = and(
            tenant_check("tenant_id", "app.current_tenant_id", "uuid"),
            tenant_check("user_id", "app.current_user_id", "uuid"),
        );

        assert!(
            matches!(
                &expr,
                Expr::Binary {
                    op: BinaryOp::And,
                    ..
                }
            ),
            "Expected Binary AND, got {expr:?}"
        );
    }

    #[test]
    fn test_policy_target_display() {
        assert_eq!(PolicyTarget::All.to_string(), "ALL");
        assert_eq!(PolicyTarget::Select.to_string(), "SELECT");
        assert_eq!(PolicyTarget::Insert.to_string(), "INSERT");
        assert_eq!(PolicyTarget::Update.to_string(), "UPDATE");
        assert_eq!(PolicyTarget::Delete.to_string(), "DELETE");
    }
}