nodedb 0.4.0

Local-first, real-time, edge-to-cloud hybrid database for multi-modal workloads
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
// SPDX-License-Identifier: BUSL-1.1

//! Scope grant management: GRANT/REVOKE SCOPE TO/FROM ORG/USER/TEAM.
//!
//! Effective scopes for a user = user scopes UNION team scopes UNION org scopes.

use std::collections::{HashMap, HashSet};
use std::sync::RwLock;

use tracing::info;

use crate::control::security::catalog::{StoredScopeGrant, SystemCatalog};
use crate::control::security::time::now_secs;

/// In-memory scope grant record with time-bound support.
#[derive(Debug, Clone)]
pub struct ScopeGrant {
    pub scope_name: String,
    pub grantee_type: String,
    pub grantee_id: String,
    pub granted_by: String,
    pub granted_at: u64,
    /// Unix timestamp when this grant expires. 0 = no expiry (permanent).
    pub expires_at: u64,
    /// Grace period in seconds after expiry before hard cutoff.
    pub grace_period_secs: u64,
    /// Action on expiry: "revoke_all", "grant:<scope_name>", or "" (just expire).
    pub on_expire_action: String,
}

/// Status of a time-bound scope grant.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ScopeStatus {
    /// Grant is active (not expired, or no expiry set).
    Active,
    /// Grant is in grace period (expired but within grace window).
    Grace,
    /// Grant is fully expired (past grace period).
    Expired,
    /// Grant does not exist for this grantee.
    None,
}

impl std::fmt::Display for ScopeStatus {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Active => write!(f, "active"),
            Self::Grace => write!(f, "grace"),
            Self::Expired => write!(f, "expired"),
            Self::None => write!(f, "none"),
        }
    }
}

impl ScopeGrant {
    /// Check the time-bound status of this grant.
    pub fn status(&self) -> ScopeStatus {
        if self.expires_at == 0 {
            return ScopeStatus::Active; // No expiry = permanent.
        }
        let now = now_secs();
        if now < self.expires_at {
            ScopeStatus::Active
        } else if now < self.expires_at + self.grace_period_secs {
            ScopeStatus::Grace
        } else {
            ScopeStatus::Expired
        }
    }

    /// Check if this grant is still effective (active or in grace period).
    pub fn is_effective(&self) -> bool {
        matches!(self.status(), ScopeStatus::Active | ScopeStatus::Grace)
    }

    fn from_stored(s: &StoredScopeGrant) -> Self {
        Self {
            scope_name: s.scope_name.clone(),
            grantee_type: s.grantee_type.clone(),
            grantee_id: s.grantee_id.clone(),
            granted_by: s.granted_by.clone(),
            granted_at: s.granted_at,
            expires_at: s.expires_at,
            grace_period_secs: s.grace_period_secs,
            on_expire_action: s.on_expire_action.clone(),
        }
    }

    fn to_stored(&self) -> StoredScopeGrant {
        StoredScopeGrant {
            scope_name: self.scope_name.clone(),
            grantee_type: self.grantee_type.clone(),
            grantee_id: self.grantee_id.clone(),
            granted_by: self.granted_by.clone(),
            granted_at: self.granted_at,
            expires_at: self.expires_at,
            grace_period_secs: self.grace_period_secs,
            on_expire_action: self.on_expire_action.clone(),
        }
    }
}

/// Thread-safe scope grant store.
pub struct ScopeGrantStore {
    /// Key: `"{scope}:{type}:{id}"` → grant.
    grants: RwLock<HashMap<String, ScopeGrant>>,
    catalog: Option<SystemCatalog>,
}

/// Parameters for [`ScopeGrantStore::grant`].
pub struct ScopeGrantParams<'a> {
    pub scope_name: &'a str,
    pub grantee_type: &'a str,
    pub grantee_id: &'a str,
    pub granted_by: &'a str,
    /// 0 means permanent (no expiry).
    pub expires_at: u64,
    /// Seconds after expiry before hard cutoff.
    pub grace_period_secs: u64,
    /// "revoke_all", "grant:<scope>", or "" (just expire).
    pub on_expire_action: &'a str,
}

impl ScopeGrantStore {
    pub fn new() -> Self {
        Self {
            grants: RwLock::new(HashMap::new()),
            catalog: None,
        }
    }

    pub fn open(catalog: SystemCatalog) -> crate::Result<Self> {
        let stored = catalog.load_all_scope_grants()?;
        let mut grants = HashMap::with_capacity(stored.len());
        for s in &stored {
            let key = grant_key(&s.scope_name, &s.grantee_type, &s.grantee_id);
            grants.insert(key, ScopeGrant::from_stored(s));
        }
        if !grants.is_empty() {
            info!(count = grants.len(), "scope grants loaded from catalog");
        }
        Ok(Self {
            grants: RwLock::new(grants),
            catalog: Some(catalog),
        })
    }

    /// Grant a scope to a user, role, org, or team.
    pub fn grant(&self, params: ScopeGrantParams<'_>) -> crate::Result<()> {
        let ScopeGrantParams {
            scope_name,
            grantee_type,
            grantee_id,
            granted_by,
            expires_at,
            grace_period_secs,
            on_expire_action,
        } = params;

        let record = ScopeGrant {
            scope_name: scope_name.into(),
            grantee_type: grantee_type.into(),
            grantee_id: grantee_id.into(),
            granted_by: granted_by.into(),
            granted_at: now_secs(),
            expires_at,
            grace_period_secs,
            on_expire_action: on_expire_action.into(),
        };

        if let Some(ref catalog) = self.catalog {
            catalog.put_scope_grant(&record.to_stored())?;
        }

        let key = grant_key(scope_name, grantee_type, grantee_id);
        let mut grants = self.grants.write().unwrap_or_else(|p| p.into_inner());
        grants.insert(key, record);
        info!(scope = %scope_name, grantee_type, grantee_id, "scope granted");
        Ok(())
    }

    /// Revoke a scope grant.
    pub fn revoke(
        &self,
        scope_name: &str,
        grantee_type: &str,
        grantee_id: &str,
    ) -> crate::Result<bool> {
        if let Some(ref catalog) = self.catalog {
            catalog.delete_scope_grant(scope_name, grantee_type, grantee_id)?;
        }
        let key = grant_key(scope_name, grantee_type, grantee_id);
        let mut grants = self.grants.write().unwrap_or_else(|p| p.into_inner());
        Ok(grants.remove(&key).is_some())
    }

    /// Get all effective scope names granted to a specific grantee.
    /// Filters out expired grants.
    pub fn scopes_for(&self, grantee_type: &str, grantee_id: &str) -> Vec<String> {
        let grants = self.grants.read().unwrap_or_else(|p| p.into_inner());
        grants
            .values()
            .filter(|g| {
                g.grantee_type == grantee_type && g.grantee_id == grantee_id && g.is_effective()
            })
            .map(|g| g.scope_name.clone())
            .collect()
    }

    /// Get the status of a specific scope grant.
    pub fn scope_status(
        &self,
        scope_name: &str,
        grantee_type: &str,
        grantee_id: &str,
    ) -> ScopeStatus {
        let key = grant_key(scope_name, grantee_type, grantee_id);
        let grants = self.grants.read().unwrap_or_else(|p| p.into_inner());
        grants
            .get(&key)
            .map(|g| g.status())
            .unwrap_or(ScopeStatus::None)
    }

    /// Get the expiry timestamp of a scope grant. Returns 0 if permanent or not found.
    pub fn scope_expires_at(&self, scope_name: &str, grantee_type: &str, grantee_id: &str) -> u64 {
        let key = grant_key(scope_name, grantee_type, grantee_id);
        let grants = self.grants.read().unwrap_or_else(|p| p.into_inner());
        grants.get(&key).map(|g| g.expires_at).unwrap_or(0)
    }

    /// Renew a scope grant by extending its expiry.
    pub fn renew(
        &self,
        scope_name: &str,
        grantee_type: &str,
        grantee_id: &str,
        extend_secs: u64,
    ) -> crate::Result<bool> {
        let key = grant_key(scope_name, grantee_type, grantee_id);
        let mut grants = self.grants.write().unwrap_or_else(|p| p.into_inner());
        if let Some(g) = grants.get_mut(&key) {
            if g.expires_at == 0 {
                return Ok(true); // Already permanent.
            }
            let now = now_secs();
            // Extend from current expiry or from now (whichever is later).
            let base = g.expires_at.max(now);
            g.expires_at = base + extend_secs;
            if let Some(ref catalog) = self.catalog {
                let _ = catalog.put_scope_grant(&g.to_stored());
            }
            info!(scope = %scope_name, grantee_type, grantee_id, new_expires = g.expires_at, "scope renewed");
            Ok(true)
        } else {
            Ok(false)
        }
    }

    /// List grants expiring within the given window (seconds from now).
    pub fn expiring_within(&self, window_secs: u64) -> Vec<ScopeGrant> {
        let now = now_secs();
        let deadline = now + window_secs;
        let grants = self.grants.read().unwrap_or_else(|p| p.into_inner());
        grants
            .values()
            .filter(|g| g.expires_at > 0 && g.expires_at <= deadline && g.is_effective())
            .cloned()
            .collect()
    }

    /// Resolve effective scopes for a user.
    ///
    /// Collects: user's direct scopes + org scopes for each org membership.
    /// Filters out expired grants.
    pub fn effective_scopes(&self, user_id: &str, org_ids: &[String]) -> HashSet<String> {
        let grants = self.grants.read().unwrap_or_else(|p| p.into_inner());
        let mut effective = HashSet::new();

        for g in grants.values() {
            if !g.is_effective() {
                continue; // Skip expired grants.
            }
            // Direct user grant.
            if g.grantee_type == "user" && g.grantee_id == user_id {
                effective.insert(g.scope_name.clone());
            }
            // Org grant (user inherits via membership).
            if g.grantee_type == "org" && org_ids.contains(&g.grantee_id) {
                effective.insert(g.scope_name.clone());
            }
        }

        effective
    }

    /// Check if a user (directly or via orgs) has a specific scope.
    pub fn has_scope(&self, user_id: &str, org_ids: &[String], scope_name: &str) -> bool {
        self.effective_scopes(user_id, org_ids).contains(scope_name)
    }

    /// List all grants, optionally filtered by scope name.
    pub fn list(&self, scope_filter: Option<&str>) -> Vec<ScopeGrant> {
        let grants = self.grants.read().unwrap_or_else(|p| p.into_inner());
        grants
            .values()
            .filter(|g| scope_filter.is_none_or(|s| g.scope_name == s))
            .cloned()
            .collect()
    }

    pub fn count(&self) -> usize {
        self.grants.read().unwrap_or_else(|p| p.into_inner()).len()
    }
}

impl Default for ScopeGrantStore {
    fn default() -> Self {
        Self::new()
    }
}

fn grant_key(scope: &str, grantee_type: &str, grantee_id: &str) -> String {
    format!("{scope}:{grantee_type}:{grantee_id}")
}

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

    #[test]
    fn grant_and_check() {
        let store = ScopeGrantStore::new();
        store
            .grant(ScopeGrantParams {
                scope_name: "profile:read",
                grantee_type: "user",
                grantee_id: "u1",
                granted_by: "admin",
                expires_at: 0,
                grace_period_secs: 0,
                on_expire_action: "",
            })
            .unwrap();

        assert!(store.has_scope("u1", &[], "profile:read"));
        assert!(!store.has_scope("u1", &[], "orders:write"));
        assert!(!store.has_scope("u2", &[], "profile:read"));
    }

    #[test]
    fn org_scope_inheritance() {
        let store = ScopeGrantStore::new();
        store
            .grant(ScopeGrantParams {
                scope_name: "pro:all",
                grantee_type: "org",
                grantee_id: "acme",
                granted_by: "admin",
                expires_at: 0,
                grace_period_secs: 0,
                on_expire_action: "",
            })
            .unwrap();

        // User u1 is member of acme → inherits pro:all.
        assert!(store.has_scope("u1", &["acme".into()], "pro:all"));
        // User u2 is NOT member → doesn't inherit.
        assert!(!store.has_scope("u2", &[], "pro:all"));
    }

    #[test]
    fn effective_scopes_union() {
        let store = ScopeGrantStore::new();
        store
            .grant(ScopeGrantParams {
                scope_name: "scope_a",
                grantee_type: "user",
                grantee_id: "u1",
                granted_by: "admin",
                expires_at: 0,
                grace_period_secs: 0,
                on_expire_action: "",
            })
            .unwrap();
        store
            .grant(ScopeGrantParams {
                scope_name: "scope_b",
                grantee_type: "org",
                grantee_id: "acme",
                granted_by: "admin",
                expires_at: 0,
                grace_period_secs: 0,
                on_expire_action: "",
            })
            .unwrap();
        store
            .grant(ScopeGrantParams {
                scope_name: "scope_c",
                grantee_type: "org",
                grantee_id: "beta",
                granted_by: "admin",
                expires_at: 0,
                grace_period_secs: 0,
                on_expire_action: "",
            })
            .unwrap();

        let effective = store.effective_scopes("u1", &["acme".into()]);
        assert!(effective.contains("scope_a")); // Direct user grant.
        assert!(effective.contains("scope_b")); // Via acme org.
        assert!(!effective.contains("scope_c")); // Not member of beta.
    }

    #[test]
    fn revoke_removes_grant() {
        let store = ScopeGrantStore::new();
        store
            .grant(ScopeGrantParams {
                scope_name: "s1",
                grantee_type: "user",
                grantee_id: "u1",
                granted_by: "admin",
                expires_at: 0,
                grace_period_secs: 0,
                on_expire_action: "",
            })
            .unwrap();
        assert!(store.has_scope("u1", &[], "s1"));

        store.revoke("s1", "user", "u1").unwrap();
        assert!(!store.has_scope("u1", &[], "s1"));
    }
}