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
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
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
// SPDX-License-Identifier: BUSL-1.1

//! Permission evaluation: `check`, `check_function`, `is_owner`.
//!
//! Multi-layer order: superuser → owner → built-in role → explicit
//! user grant → role grants (with custom-role inheritance).

use crate::control::security::audit::{AuditEmitContext, AuditEmitter, AuditEvent};
use crate::control::security::identity::{self, AuthenticatedIdentity, Permission};
use crate::control::security::role::RoleStore;

use crate::types::{DatabaseId, TenantId};

use super::store::PermissionStore;
use super::types::{Grant, collection_target, function_target, owner_key, tenant_target};

impl PermissionStore {
    /// Does any grant on `target` confer `permission` to this identity —
    /// either through an explicit `user:<name>` grant or through any role
    /// in the identity's inheritance chain?
    ///
    /// Acquires the grants read lock for the duration of the lookup.
    fn target_grants_permission(
        &self,
        target: &str,
        permission: Permission,
        identity: &AuthenticatedIdentity,
        role_store: &RoleStore,
    ) -> bool {
        let grants = match self.grants.read() {
            Ok(g) => g,
            Err(p) => {
                tracing::error!("permission grants lock poisoned — recovering data");
                p.into_inner()
            }
        };

        let user_grantee = format!("user:{}", identity.username);
        if grants.contains(&Grant {
            target: target.to_string(),
            grantee: user_grantee,
            permission,
        }) {
            return true;
        }

        for role in &identity.roles {
            let chain = match role_store.resolve_inheritance(role) {
                Ok(c) => c,
                Err(e) => {
                    tracing::error!(error = %e, "failed to resolve role inheritance — denying");
                    continue;
                }
            };
            for ancestor in &chain {
                if grants.contains(&Grant {
                    target: target.to_string(),
                    grantee: ancestor.to_string(),
                    permission,
                }) {
                    return true;
                }
            }
        }
        false
    }

    /// Check if an identity has a specific permission on a collection.
    ///
    /// Checks in order:
    /// 1. Superuser → always allowed
    /// 2. Ownership → owner has all permissions on their objects
    /// 3. Built-in role grants (from identity.rs role_grants_permission)
    /// 4. Explicit collection-level grants (on user or any of user's roles)
    /// 5. Custom role inheritance chain (via `RoleStore`)
    ///
    /// When access is denied (returns `false`) the decision is emitted to
    /// `emitter` as `AuditEvent::PermissionDenied`.  Pass
    /// `&NoopAuditEmitter` from callers that are not the terminal denial
    /// point (e.g. multi-layer fallback chains that try broader scopes
    /// after this call).
    pub fn check(
        &self,
        identity: &AuthenticatedIdentity,
        permission: Permission,
        database_id: DatabaseId,
        collection: &str,
        role_store: &RoleStore,
        emitter: &dyn AuditEmitter,
    ) -> bool {
        if identity.is_superuser {
            return true;
        }

        if self.is_owner(
            "collection",
            database_id,
            identity.tenant_id,
            collection,
            &identity.username,
        ) {
            return true;
        }

        let target = collection_target(identity.tenant_id, collection);

        for role in &identity.roles {
            if identity::role_grants_permission(role, permission) {
                return true;
            }
        }

        // Explicit grant on the collection itself.
        if self.target_grants_permission(&target, permission, identity, role_store) {
            return true;
        }

        // Tenant-wide grant — `GRANT <perm> ON TENANT <name>` confers the
        // permission on every collection in the tenant.
        let tenant_tgt = tenant_target(identity.tenant_id);
        if self.target_grants_permission(&tenant_tgt, permission, identity, role_store) {
            return true;
        }

        emitter.emit(
            AuditEvent::PermissionDenied,
            &identity.username,
            &format!(
                "permission {:?} denied on '{}' for user '{}'",
                permission, collection, identity.username
            ),
            AuditEmitContext::new(
                Some(identity.tenant_id),
                &identity.user_id.to_string(),
                &identity.username,
            ),
        );
        false
    }

    /// Check if an identity has EXECUTE permission on a function.
    ///
    /// Same multi-layer check as [`Self::check`] but uses
    /// `function:tenant:name` targets. Function owners implicitly
    /// have EXECUTE.  Emits `AuditEvent::PermissionDenied` via
    /// `emitter` when access is denied.
    pub fn check_function(
        &self,
        identity: &AuthenticatedIdentity,
        database_id: DatabaseId,
        function_name: &str,
        role_store: &RoleStore,
        emitter: &dyn AuditEmitter,
    ) -> bool {
        if identity.is_superuser {
            return true;
        }

        if self.is_owner(
            "function",
            database_id,
            identity.tenant_id,
            function_name,
            &identity.username,
        ) {
            return true;
        }

        let target = function_target(identity.tenant_id, function_name);

        for role in &identity.roles {
            if identity::role_grants_permission(role, Permission::Execute) {
                return true;
            }
        }

        if self.target_grants_permission(&target, Permission::Execute, identity, role_store) {
            return true;
        }

        emitter.emit(
            AuditEvent::PermissionDenied,
            &identity.username,
            &format!(
                "EXECUTE permission denied on function '{}' for user '{}'",
                function_name, identity.username
            ),
            AuditEmitContext::new(
                Some(identity.tenant_id),
                &identity.user_id.to_string(),
                &identity.username,
            ),
        );
        false
    }

    /// Check if an identity holds `permission` scoped to an entire tenant
    /// (`GRANT <perm> ON TENANT <name>`).
    ///
    /// Used for tenant-wide operations such as `BACKUP TENANT` /
    /// `RESTORE TENANT`. Checks superuser → built-in role grants → explicit
    /// tenant-scoped grants (on the user or any of the user's roles). Emits
    /// `AuditEvent::PermissionDenied` via `emitter` when access is denied.
    pub fn check_tenant(
        &self,
        identity: &AuthenticatedIdentity,
        permission: Permission,
        tenant_id: TenantId,
        role_store: &RoleStore,
        emitter: &dyn AuditEmitter,
    ) -> bool {
        if identity.is_superuser {
            return true;
        }

        for role in &identity.roles {
            if identity::role_grants_permission(role, permission) {
                return true;
            }
        }

        let target = tenant_target(tenant_id);
        if self.target_grants_permission(&target, permission, identity, role_store) {
            return true;
        }

        emitter.emit(
            AuditEvent::PermissionDenied,
            &identity.username,
            &format!(
                "permission {:?} denied on tenant {} for user '{}'",
                permission,
                tenant_id.as_u64(),
                identity.username
            ),
            AuditEmitContext::new(
                Some(identity.tenant_id),
                &identity.user_id.to_string(),
                &identity.username,
            ),
        );
        false
    }

    /// Lookup helper: is `username` recorded as the owner of the object?
    ///
    /// The owners map is keyed by [`owner_key`] —
    /// `{object_type}:{database_id}:{tenant_id}:{object_name}` — which is a
    /// different shape from the `{object_type}:{tenant_id}:{object_name}`
    /// target strings used for *grants*. The two must not be interchanged:
    /// passing a grant target here silently never matches, which reads as
    /// "nobody owns anything" rather than as an error.
    pub(super) fn is_owner(
        &self,
        object_type: &str,
        database_id: DatabaseId,
        tenant_id: TenantId,
        object_name: &str,
        username: &str,
    ) -> bool {
        let key = owner_key(
            object_type,
            database_id.as_u64(),
            tenant_id.as_u64(),
            object_name,
        );
        let owners = match self.owners.read() {
            Ok(o) => o,
            Err(p) => {
                tracing::error!("owner store lock poisoned — recovering data");
                p.into_inner()
            }
        };
        owners.get(&key).is_some_and(|o| o == username)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::control::security::audit::NoopAuditEmitter;
    use crate::control::security::identity::{AuthMethod, Role};
    use crate::types::TenantId;

    const NOOP: &NoopAuditEmitter = &NoopAuditEmitter;

    fn identity(username: &str, roles: Vec<Role>, superuser: bool) -> AuthenticatedIdentity {
        use crate::control::security::identity::DatabaseSet;
        AuthenticatedIdentity {
            user_id: 1,
            username: username.into(),
            tenant_id: TenantId::new(1),
            auth_method: AuthMethod::Trust,
            roles,
            is_superuser: superuser,
            default_database: None,
            accessible_databases: if superuser {
                DatabaseSet::All
            } else {
                DatabaseSet::Some(smallvec::smallvec![nodedb_types::id::DatabaseId::DEFAULT])
            },
        }
    }

    #[test]
    fn superuser_always_allowed() {
        let store = PermissionStore::new();
        let roles = RoleStore::new();
        let id = identity("admin", vec![], true);
        assert!(store.check(
            &id,
            Permission::Write,
            DatabaseId::DEFAULT,
            "secret",
            &roles,
            NOOP
        ));
    }

    #[test]
    fn owner_has_all_permissions() {
        let store = PermissionStore::new();
        let roles = RoleStore::new();
        store
            .set_owner("collection", TenantId::new(1), "users", "alice", None)
            .unwrap();

        let id = identity("alice", vec![], false);
        assert!(store.check(
            &id,
            Permission::Read,
            DatabaseId::DEFAULT,
            "users",
            &roles,
            NOOP
        ));
        assert!(store.check(
            &id,
            Permission::Write,
            DatabaseId::DEFAULT,
            "users",
            &roles,
            NOOP
        ));
        assert!(store.check(
            &id,
            Permission::Drop,
            DatabaseId::DEFAULT,
            "users",
            &roles,
            NOOP
        ));
    }

    /// Owner rows are keyed by database. A check against the database the
    /// row was written to must recognise the owner, and a check against any
    /// other database must not — a same-named collection elsewhere belongs
    /// to whoever owns it there, not to this user.
    #[test]
    fn ownership_is_scoped_to_its_database() {
        let store = PermissionStore::new();
        let roles = RoleStore::new();
        let db = DatabaseId::new(7);
        store
            .set_owner_in_database(
                "collection",
                db.as_u64(),
                TenantId::new(1),
                "users",
                "alice",
                None,
            )
            .unwrap();

        let id = identity("alice", vec![], false);
        assert!(
            store.check(&id, Permission::Read, db, "users", &roles, NOOP),
            "owner must hold implicit permissions in their own database"
        );
        assert!(
            !store.check(
                &id,
                Permission::Read,
                DatabaseId::DEFAULT,
                "users",
                &roles,
                NOOP
            ),
            "ownership must not leak into a same-named collection in another database"
        );
    }

    #[test]
    fn non_owner_denied_without_grant() {
        let store = PermissionStore::new();
        let roles = RoleStore::new();
        store
            .set_owner("collection", TenantId::new(1), "users", "alice", None)
            .unwrap();

        let id = identity("bob", vec![], false);
        assert!(!store.check(
            &id,
            Permission::Write,
            DatabaseId::DEFAULT,
            "users",
            &roles,
            NOOP
        ));
    }

    #[test]
    fn explicit_user_grant() {
        let store = PermissionStore::new();
        let roles = RoleStore::new();
        let target = collection_target(TenantId::new(1), "orders");
        store
            .grant(&target, "user:bob", Permission::Read, "admin", None)
            .unwrap();

        let id = identity("bob", vec![], false);
        assert!(store.check(
            &id,
            Permission::Read,
            DatabaseId::DEFAULT,
            "orders",
            &roles,
            NOOP
        ));
        assert!(!store.check(
            &id,
            Permission::Write,
            DatabaseId::DEFAULT,
            "orders",
            &roles,
            NOOP
        ));
    }

    #[test]
    fn grant_on_role() {
        let store = PermissionStore::new();
        let roles = RoleStore::new();
        let target = collection_target(TenantId::new(1), "reports");
        store
            .grant(&target, "readonly", Permission::Read, "admin", None)
            .unwrap();

        let id = identity("viewer", vec![Role::Custom("readonly".into())], false);
        assert!(store.check(
            &id,
            Permission::Read,
            DatabaseId::DEFAULT,
            "reports",
            &roles,
            NOOP
        ));
    }

    #[test]
    fn inherited_role_grant() {
        let role_store = RoleStore::new();
        role_store
            .create_role("analyst", TenantId::new(1), Some("readonly"), None)
            .unwrap();

        let perm_store = PermissionStore::new();
        let target = collection_target(TenantId::new(1), "data");
        perm_store
            .grant(&target, "readonly", Permission::Read, "admin", None)
            .unwrap();

        let id = identity("alice", vec![Role::Custom("analyst".into())], false);
        assert!(perm_store.check(
            &id,
            Permission::Read,
            DatabaseId::DEFAULT,
            "data",
            &role_store,
            NOOP
        ));
    }

    #[test]
    fn revoke_removes_grant() {
        let store = PermissionStore::new();
        let target = collection_target(TenantId::new(1), "users");
        store
            .grant(&target, "user:bob", Permission::Read, "admin", None)
            .unwrap();
        assert!(
            store
                .revoke(&target, "user:bob", Permission::Read, None)
                .unwrap()
        );

        let roles = RoleStore::new();
        let id = identity("bob", vec![], false);
        assert!(!store.check(
            &id,
            Permission::Read,
            DatabaseId::DEFAULT,
            "users",
            &roles,
            NOOP
        ));
    }

    #[test]
    fn builtin_role_still_works() {
        let store = PermissionStore::new();
        let roles = RoleStore::new();
        let id = identity("writer", vec![Role::ReadWrite], false);
        assert!(store.check(
            &id,
            Permission::Read,
            DatabaseId::DEFAULT,
            "anything",
            &roles,
            NOOP
        ));
        assert!(store.check(
            &id,
            Permission::Write,
            DatabaseId::DEFAULT,
            "anything",
            &roles,
            NOOP
        ));
        assert!(!store.check(
            &id,
            Permission::Drop,
            DatabaseId::DEFAULT,
            "anything",
            &roles,
            NOOP
        ));
    }

    #[test]
    fn denied_check_emits_permission_denied() {
        use crate::control::security::audit::emitter::test_helpers::CapturingEmitter;

        let store = PermissionStore::new();
        let roles = RoleStore::new();
        let emitter = CapturingEmitter::new();
        let id = identity("eve", vec![], false);

        let allowed = store.check(
            &id,
            Permission::Write,
            DatabaseId::DEFAULT,
            "secrets",
            &roles,
            &emitter,
        );
        assert!(!allowed);

        let recorded = emitter.recorded();
        assert_eq!(recorded.len(), 1);
        assert_eq!(recorded[0].0, AuditEvent::PermissionDenied);
    }

    #[test]
    fn allowed_check_does_not_emit() {
        use crate::control::security::audit::emitter::test_helpers::CapturingEmitter;

        let store = PermissionStore::new();
        let roles = RoleStore::new();
        let emitter = CapturingEmitter::new();
        let id = identity("admin", vec![], true);

        let allowed = store.check(
            &id,
            Permission::Write,
            DatabaseId::DEFAULT,
            "anything",
            &roles,
            &emitter,
        );
        assert!(allowed);
        assert!(emitter.recorded().is_empty());
    }

    #[test]
    fn tenant_wide_grant_covers_every_collection() {
        let store = PermissionStore::new();
        let roles = RoleStore::new();
        // `GRANT READ ON TENANT <name>` lands on the tenant target.
        let target = tenant_target(TenantId::new(1));
        store
            .grant(&target, "user:bob", Permission::Read, "admin", None)
            .unwrap();

        let id = identity("bob", vec![], false);
        // A tenant-wide grant confers the permission on any collection in
        // the tenant, with no per-collection grant.
        assert!(store.check(
            &id,
            Permission::Read,
            DatabaseId::DEFAULT,
            "orders",
            &roles,
            NOOP
        ));
        assert!(store.check(
            &id,
            Permission::Read,
            DatabaseId::DEFAULT,
            "invoices",
            &roles,
            NOOP
        ));
        // It does not widen to permissions that were not granted.
        assert!(!store.check(
            &id,
            Permission::Write,
            DatabaseId::DEFAULT,
            "orders",
            &roles,
            NOOP
        ));
    }

    #[test]
    fn check_tenant_honors_explicit_grant() {
        let store = PermissionStore::new();
        let roles = RoleStore::new();
        let target = tenant_target(TenantId::new(1));
        store
            .grant(&target, "user:ops", Permission::Backup, "admin", None)
            .unwrap();

        let granted = identity("ops", vec![], false);
        assert!(store.check_tenant(&granted, Permission::Backup, TenantId::new(1), &roles, NOOP));

        // A different user without the grant is denied.
        let other = identity("eve", vec![], false);
        assert!(!store.check_tenant(&other, Permission::Backup, TenantId::new(1), &roles, NOOP));
    }

    #[test]
    fn check_tenant_superuser_always_allowed() {
        let store = PermissionStore::new();
        let roles = RoleStore::new();
        let id = identity("admin", vec![], true);
        assert!(store.check_tenant(&id, Permission::Backup, TenantId::new(9), &roles, NOOP));
    }
}