qail-core 1.2.0

AST-native query builder - type-safe expressions, zero SQL strings
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
//! Row-Level Security (RLS) Context for Multi-Tenant SaaS
//!
//! Provides a shared tenant context that all Qail drivers can use
//! for data isolation. Each driver implements isolation differently:
//!
//! - **qail-pg**: `set_config('app.current_tenant_id', ...)` session variables
//! - **qail-qdrant**: metadata filter `{ tenant_id: "..." }` on vector search
//!
//! # Example
//!
//! ```
//! use qail_core::rls::{RlsContext, SuperAdminToken};
//!
//! // Tenant context — scopes data to a single tenant
//! let ctx = RlsContext::tenant("550e8400-e29b-41d4-a716-446655440000");
//! assert_eq!(ctx.tenant_id, "550e8400-e29b-41d4-a716-446655440000");
//!
//! // Super admin — bypasses tenant isolation (requires named constructor)
//! let token = SuperAdminToken::for_system_process("example");
//! let admin = RlsContext::super_admin(token);
//! assert!(admin.bypasses_rls());
//!
//! // Global context — scopes to platform rows (tenant_id IS NULL)
//! let global = RlsContext::global();
//! assert!(global.is_global());
//! ```

/// Tenant context for multi-tenant data isolation.
///
/// Each driver uses this context to scope operations to a specific tenant:
/// - **PostgreSQL**: Sets `app.current_tenant_id` session variable
/// - **Qdrant**: Filters vector searches by tenant metadata
pub mod tenant;

/// An opaque token that authorizes RLS bypass.
///
/// Create via one of the named constructors:
/// - [`SuperAdminToken::for_system_process`] — cron, startup, cross-tenant internals
/// - [`SuperAdminToken::for_webhook`] — inbound callbacks
/// - [`SuperAdminToken::for_auth`] — login, register, token refresh
///
/// External code cannot fabricate this token — it has a private field
/// and no public field constructor.
///
/// # Usage
/// ```ignore
/// let token = SuperAdminToken::for_system_process("cron::cleanup");
/// let ctx = RlsContext::super_admin(token);
/// assert!(ctx.bypasses_rls());
/// ```
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SuperAdminToken {
    _private: (),
}

impl SuperAdminToken {
    /// Issue a token for a system/background process.
    ///
    /// Use for cron jobs, startup introspection, and internal cross-tenant
    /// maintenance paths. For shared/public reference data, prefer
    /// [`RlsContext::global()`] instead of bypass.
    ///
    /// The `_reason` parameter documents intent at the call site
    /// (e.g. `"cron::check_expired_holds"`). Drivers like `qail-pg`
    /// may log it via tracing.
    pub fn for_system_process(_reason: &str) -> Self {
        Self { _private: () }
    }

    /// Issue a token for an inbound webhook or gateway trigger.
    ///
    /// Use for Meta WhatsApp callbacks, Xendit payment callbacks,
    /// and gateway event triggers that are authenticated via shared
    /// secret (`X-Trigger-Secret`) rather than JWT.
    pub fn for_webhook(_source: &str) -> Self {
        Self { _private: () }
    }

    /// Issue a token for an authentication operation.
    ///
    /// Use for login, register, token refresh, and admin-claims
    /// resolution — operations that necessarily run before (or
    /// outside) a tenant scope is known.
    pub fn for_auth(_operation: &str) -> Self {
        Self { _private: () }
    }
}

/// RLS context carrying tenant identity for data isolation.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct RlsContext {
    /// The unified tenant ID — the primary identity for data isolation.
    /// Empty string means no tenant scope.
    pub tenant_id: String,

    /// Legacy: The agent (reseller) this context is scoped to.
    /// Empty string means no agent scope.
    pub agent_id: String,

    /// When true, the current user is a platform super admin
    /// and should bypass tenant isolation.
    ///
    /// This field is private — external code must use `bypasses_rls()`.
    /// Only `super_admin(token)` can set this to true, and that requires
    /// a `SuperAdminToken` which emits an audit log on creation.
    is_super_admin: bool,

    /// When true, the context is explicitly scoped to global/platform rows
    /// (`tenant_id IS NULL`) rather than tenant-specific rows.
    is_global: bool,

    /// The authenticated user's UUID for user-scoped DB policies.
    /// Empty string means no user scope. Set via `RlsContext::user()`.
    user_id: String,
}

impl RlsContext {
    /// Create a context scoped to a specific tenant (the unified identity).
    pub fn tenant(tenant_id: &str) -> Self {
        Self {
            tenant_id: tenant_id.to_string(),
            agent_id: String::new(),
            is_super_admin: false,
            is_global: false,
            user_id: String::new(),
        }
    }

    /// Create a context scoped to a specific agent (reseller).
    pub fn agent(agent_id: &str) -> Self {
        Self {
            tenant_id: String::new(),
            agent_id: agent_id.to_string(),
            is_super_admin: false,
            is_global: false,
            user_id: String::new(),
        }
    }

    /// Create a context scoped to both tenant and agent.
    pub fn tenant_and_agent(tenant_id: &str, agent_id: &str) -> Self {
        Self {
            tenant_id: tenant_id.to_string(),
            agent_id: agent_id.to_string(),
            is_super_admin: false,
            is_global: false,
            user_id: String::new(),
        }
    }

    /// Create a global context scoped to platform rows (`tenant_id IS NULL`).
    ///
    /// This is not a bypass: it applies explicit global scoping in AST injection
    /// and exposes `app.is_global=true` for policy usage at the database layer.
    pub fn global() -> Self {
        Self {
            tenant_id: String::new(),
            agent_id: String::new(),
            is_super_admin: false,
            is_global: true,
            user_id: String::new(),
        }
    }

    /// Create a super admin context that bypasses tenant isolation.
    ///
    /// Requires a `SuperAdminToken` — which can only be created via
    /// named constructors (`for_system_process`, `for_webhook`, `for_auth`).
    ///
    /// Uses nil UUID for all IDs to avoid `''::uuid` cast errors
    /// in PostgreSQL RLS policies (PostgreSQL doesn't short-circuit OR).
    pub fn super_admin(_token: SuperAdminToken) -> Self {
        let nil = "00000000-0000-0000-0000-000000000000".to_string();
        Self {
            tenant_id: nil,
            agent_id: String::new(),
            is_super_admin: true,
            is_global: false,
            user_id: String::new(),
        }
    }

    /// Create an empty context (no tenant, no super admin).
    ///
    /// Used for system-level operations that must not operate within
    /// any tenant scope (startup introspection, migrations, health checks).
    pub fn empty() -> Self {
        Self {
            tenant_id: String::new(),
            agent_id: String::new(),
            is_super_admin: false,
            is_global: false,
            user_id: String::new(),
        }
    }

    /// Create a user-scoped context for authenticated end-user operations.
    ///
    /// Sets `app.current_user_id` so that DB policies can enforce
    /// row-level isolation by user (e.g. `user_id = get_current_user_id()`).
    /// Does NOT bypass tenant isolation or grant super-admin.
    pub fn user(user_id: &str) -> Self {
        Self {
            tenant_id: String::new(),
            agent_id: String::new(),
            is_super_admin: false,
            is_global: false,
            user_id: user_id.to_string(),
        }
    }

    /// Attach an authenticated user ID to an existing tenant/global context.
    ///
    /// User scope is orthogonal to tenant/agent scope: PostgreSQL policies can
    /// use both `app.current_tenant_id` and `app.current_user_id`.
    pub fn with_user(mut self, user_id: &str) -> Self {
        self.user_id = user_id.to_string();
        self
    }

    /// Returns true if this context has a tenant scope.
    pub fn has_tenant(&self) -> bool {
        !self.tenant_id.is_empty()
    }

    /// Returns true if this context has an agent scope.
    pub fn has_agent(&self) -> bool {
        !self.agent_id.is_empty()
    }

    /// Returns true if this context has a user scope.
    pub fn has_user(&self) -> bool {
        !self.user_id.is_empty()
    }

    /// Returns the user ID for this context (empty if none).
    pub fn user_id(&self) -> &str {
        &self.user_id
    }

    /// Returns true if this context bypasses tenant isolation.
    pub fn bypasses_rls(&self) -> bool {
        self.is_super_admin
    }

    /// Returns true if this context is explicitly scoped to global rows.
    pub fn is_global(&self) -> bool {
        self.is_global
    }
}

impl std::fmt::Display for RlsContext {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        if self.is_super_admin {
            write!(f, "RlsContext(super_admin)")
        } else if self.is_global {
            write!(f, "RlsContext(global)")
        } else if !self.tenant_id.is_empty() {
            write!(f, "RlsContext(tenant={})", self.tenant_id)
        } else {
            write!(f, "RlsContext(none)")
        }
    }
}

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

    #[test]
    fn test_tenant_context() {
        let ctx = RlsContext::tenant("t-123");
        assert_eq!(ctx.tenant_id, "t-123");
        assert!(ctx.agent_id.is_empty());
        assert!(!ctx.bypasses_rls());
        assert!(ctx.has_tenant());
    }

    #[test]
    fn test_agent_context_sets_tenant() {
        let ctx = RlsContext::agent("ag-456");
        assert!(ctx.tenant_id.is_empty());
        assert_eq!(ctx.agent_id, "ag-456");
        assert!(ctx.has_agent());
    }

    #[test]
    fn test_super_admin_via_named_constructors() {
        let token = SuperAdminToken::for_system_process("test");
        let ctx = RlsContext::super_admin(token);
        assert!(ctx.bypasses_rls());

        let token = SuperAdminToken::for_webhook("test");
        let ctx = RlsContext::super_admin(token);
        assert!(ctx.bypasses_rls());

        let token = SuperAdminToken::for_auth("test");
        let ctx = RlsContext::super_admin(token);
        assert!(ctx.bypasses_rls());
    }

    #[test]
    fn test_tenant_and_agent() {
        let ctx = RlsContext::tenant_and_agent("tenant-1", "ag-2");
        assert_eq!(ctx.tenant_id, "tenant-1");
        assert!(ctx.has_agent());
        assert!(!ctx.bypasses_rls());
    }

    #[test]
    fn test_display() {
        let token = SuperAdminToken::for_system_process("test_display");
        assert_eq!(
            RlsContext::super_admin(token).to_string(),
            "RlsContext(super_admin)"
        );
        assert_eq!(RlsContext::tenant("x").to_string(), "RlsContext(tenant=x)");
    }

    #[test]
    fn test_equality() {
        let a = RlsContext::tenant("t-1");
        let b = RlsContext::tenant("t-1");
        let c = RlsContext::tenant("t-2");
        assert_eq!(a, b);
        assert_ne!(a, c);
    }

    #[test]
    fn test_empty_context() {
        let ctx = RlsContext::empty();
        assert!(!ctx.has_tenant());
        assert!(!ctx.has_agent());
        assert!(!ctx.bypasses_rls());
        assert!(!ctx.is_global());
    }

    #[test]
    fn test_global_context() {
        let ctx = RlsContext::global();
        assert!(!ctx.has_tenant());
        assert!(!ctx.has_agent());
        assert!(!ctx.bypasses_rls());
        assert!(ctx.is_global());
        assert_eq!(ctx.to_string(), "RlsContext(global)");
    }

    #[test]
    fn test_for_system_process() {
        let token = SuperAdminToken::for_system_process("cron::check_expired_holds");
        let ctx = RlsContext::super_admin(token);
        assert!(ctx.bypasses_rls());
    }

    #[test]
    fn test_for_webhook() {
        let token = SuperAdminToken::for_webhook("xendit_callback");
        let ctx = RlsContext::super_admin(token);
        assert!(ctx.bypasses_rls());
    }

    #[test]
    fn test_for_auth() {
        let token = SuperAdminToken::for_auth("login");
        let ctx = RlsContext::super_admin(token);
        assert!(ctx.bypasses_rls());
    }

    #[test]
    fn test_all_constructors_produce_equal_tokens() {
        let a = SuperAdminToken::for_system_process("a");
        let b = SuperAdminToken::for_webhook("b");
        let c = SuperAdminToken::for_auth("c");
        // All tokens are structurally identical
        assert_eq!(a, b);
        assert_eq!(b, c);
    }

    #[test]
    fn test_user_context() {
        let ctx = RlsContext::user("550e8400-e29b-41d4-a716-446655440000");
        assert!(!ctx.has_tenant());
        assert!(!ctx.has_agent());
        assert!(!ctx.bypasses_rls());
        assert!(!ctx.is_global());
        assert!(ctx.has_user());
        assert_eq!(ctx.user_id(), "550e8400-e29b-41d4-a716-446655440000");
    }

    #[test]
    fn test_with_user_preserves_tenant_scope() {
        let ctx = RlsContext::tenant("tenant-1").with_user("user-1");

        assert_eq!(ctx.tenant_id, "tenant-1");
        assert_eq!(ctx.user_id(), "user-1");
        assert!(ctx.has_tenant());
        assert!(ctx.has_user());
        assert!(!ctx.bypasses_rls());
    }

    #[test]
    fn test_user_context_display() {
        let ctx = RlsContext::user("u-123");
        assert_eq!(ctx.to_string(), "RlsContext(none)");
        // user context doesn't have tenant, so Display falls through to "none"
        // (user_id is an orthogonal axis, not a tenant scope)
    }

    #[test]
    fn test_other_constructors_have_no_user() {
        assert!(!RlsContext::tenant("t-1").has_user());
        assert!(!RlsContext::global().has_user());
        assert!(!RlsContext::empty().has_user());
        let token = SuperAdminToken::for_auth("test");
        assert!(!RlsContext::super_admin(token).has_user());
    }
}