solidb 1.0.1

A lightweight, high-performance structured database server written in Rust.
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
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
//! Role-Based Access Control (RBAC) authorization service for SoliDB.
//!
//! This module provides permission checking and role management functionality.

use crate::error::{DbError, DbResult};
use serde::{Deserialize, Serialize};
use std::collections::HashSet;

/// Permission action types
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum PermissionAction {
    /// Full access: create/delete databases, manage users, cluster ops
    Admin,
    /// Insert, update, delete documents; create indexes
    Write,
    /// Get, list, query (SELECT only)
    Read,
}

impl PermissionAction {
    /// Check if this action implies another action
    /// Admin > Write > Read
    pub fn implies(&self, other: &PermissionAction) -> bool {
        match self {
            PermissionAction::Admin => true, // Admin implies all
            PermissionAction::Write => {
                matches!(other, PermissionAction::Write | PermissionAction::Read)
            }
            PermissionAction::Read => matches!(other, PermissionAction::Read),
        }
    }
}

/// Permission scope types
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum PermissionScope {
    /// Permission applies to all databases
    Global,
    /// Permission applies to a specific database
    Database,
}

/// A single permission granting access to perform an action on a scope
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct Permission {
    /// The action this permission grants
    pub action: PermissionAction,
    /// The scope of this permission
    pub scope: PermissionScope,
    /// Database name (None for global scope)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub database: Option<String>,
}

impl Permission {
    /// Create a global admin permission
    pub fn global_admin() -> Self {
        Self {
            action: PermissionAction::Admin,
            scope: PermissionScope::Global,
            database: None,
        }
    }

    /// Create a global write permission
    pub fn global_write() -> Self {
        Self {
            action: PermissionAction::Write,
            scope: PermissionScope::Global,
            database: None,
        }
    }

    /// Create a global read permission
    pub fn global_read() -> Self {
        Self {
            action: PermissionAction::Read,
            scope: PermissionScope::Global,
            database: None,
        }
    }

    /// Create a database-scoped permission
    pub fn database_permission(action: PermissionAction, database: &str) -> Self {
        Self {
            action,
            scope: PermissionScope::Database,
            database: Some(database.to_string()),
        }
    }
}

/// Role definition stored in _system._roles
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Role {
    /// Role name (also used as _key)
    #[serde(rename = "_key")]
    pub name: String,
    /// Human-readable description
    #[serde(skip_serializing_if = "Option::is_none")]
    pub description: Option<String>,
    /// Permissions granted by this role
    pub permissions: Vec<Permission>,
    /// Whether this is a built-in role (cannot be deleted)
    #[serde(default)]
    pub is_builtin: bool,
    /// Creation timestamp (RFC3339)
    pub created_at: String,
    /// Last update timestamp (RFC3339)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub updated_at: Option<String>,
}

impl Role {
    /// Create the built-in admin role
    pub fn builtin_admin() -> Self {
        Self {
            name: "admin".to_string(),
            description: Some("Full system access".to_string()),
            permissions: vec![Permission::global_admin()],
            is_builtin: true,
            created_at: chrono::Utc::now().to_rfc3339(),
            updated_at: None,
        }
    }

    /// Create the built-in editor role
    pub fn builtin_editor() -> Self {
        Self {
            name: "editor".to_string(),
            description: Some("Read and write access to all databases".to_string()),
            permissions: vec![Permission::global_write(), Permission::global_read()],
            is_builtin: true,
            created_at: chrono::Utc::now().to_rfc3339(),
            updated_at: None,
        }
    }

    /// Create the built-in viewer role
    pub fn builtin_viewer() -> Self {
        Self {
            name: "viewer".to_string(),
            description: Some("Read-only access to all databases".to_string()),
            permissions: vec![Permission::global_read()],
            is_builtin: true,
            created_at: chrono::Utc::now().to_rfc3339(),
            updated_at: None,
        }
    }

    /// Get all built-in roles
    pub fn builtin_roles() -> Vec<Self> {
        vec![
            Self::builtin_admin(),
            Self::builtin_editor(),
            Self::builtin_viewer(),
        ]
    }
}

/// User-to-role assignment stored in _system._user_roles
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct UserRole {
    /// Assignment ID (UUID, also used as _key)
    #[serde(rename = "_key")]
    pub id: String,
    /// Username (references _admins._key)
    pub username: String,
    /// Role name (references _roles._key)
    pub role: String,
    /// Database scope (None for global assignment)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub database: Option<String>,
    /// Assignment timestamp (RFC3339)
    pub assigned_at: String,
    /// Who assigned this role
    pub assigned_by: String,
}

impl UserRole {
    /// Create a new global role assignment
    pub fn new_global(username: &str, role: &str, assigned_by: &str) -> Self {
        Self {
            id: uuid::Uuid::new_v4().to_string(),
            username: username.to_string(),
            role: role.to_string(),
            database: None,
            assigned_at: chrono::Utc::now().to_rfc3339(),
            assigned_by: assigned_by.to_string(),
        }
    }

    /// Create a new database-scoped role assignment
    pub fn new_database_scoped(
        username: &str,
        role: &str,
        database: &str,
        assigned_by: &str,
    ) -> Self {
        Self {
            id: uuid::Uuid::new_v4().to_string(),
            username: username.to_string(),
            role: role.to_string(),
            database: Some(database.to_string()),
            assigned_at: chrono::Utc::now().to_rfc3339(),
            assigned_by: assigned_by.to_string(),
        }
    }
}

/// System collection names for RBAC
pub const ROLES_COLLECTION: &str = "_roles";
pub const USER_ROLES_COLLECTION: &str = "_user_roles";

/// Authorization service for checking permissions
pub struct AuthorizationService;

impl AuthorizationService {
    /// Check if any permission in the set satisfies the requirement
    fn has_permission(permissions: &HashSet<Permission>, required: &Permission) -> bool {
        for perm in permissions {
            // Exact match
            if perm == required {
                return true;
            }

            // Check if action implies required action
            if !perm.action.implies(&required.action) {
                continue;
            }

            // Global scope covers all databases
            if perm.scope == PermissionScope::Global {
                return true;
            }

            // Database scope must match
            if perm.scope == PermissionScope::Database
                && required.scope == PermissionScope::Database
                && perm.database == required.database
            {
                return true;
            }
        }

        false
    }

    /// Resolve permissions from roles
    pub fn resolve_permissions(roles: &[Role]) -> HashSet<Permission> {
        let mut permissions = HashSet::new();
        for role in roles {
            for perm in &role.permissions {
                permissions.insert(perm.clone());
            }
        }
        permissions
    }

    /// Get effective permissions for a user from Claims and AppState
    ///
    /// This method:
    /// 1. Checks the permission cache first
    /// 2. If not cached, loads roles from DB and resolves permissions
    /// 3. Caches the result for future calls
    pub async fn get_effective_permissions(
        claims: &crate::server::auth::Claims,
        state: &crate::server::handlers::AppState,
    ) -> DbResult<HashSet<Permission>> {
        use crate::server::permission_cache::CachedPermissions;

        // Check cache first
        if let Some(cached) = state.permission_cache.get(&claims.sub) {
            return Ok(cached.permissions);
        }

        // Get role names from claims
        let role_names = claims.roles.clone().unwrap_or_default();
        if role_names.is_empty() {
            return Ok(HashSet::new());
        }

        // Load roles from cache (pre-seeded with the builtin roles) or DB.
        // A missing `_system`/`_roles` collection is not an error: the cache
        // still resolves builtin roles, and unknown role names simply grant
        // nothing.
        let mut roles = Vec::new();
        let roles_coll = state
            .storage
            .get_database("_system")
            .ok()
            .and_then(|db| db.get_collection(ROLES_COLLECTION).ok());

        for role_name in &role_names {
            // Try cache first
            if let Some(role) = state.permission_cache.get_role(role_name) {
                roles.push(role);
            } else if let Some(ref coll) = roles_coll {
                // Load from DB
                if let Ok(doc) = coll.get(role_name) {
                    if let Ok(role) = serde_json::from_value::<Role>(doc.data) {
                        state.permission_cache.set_role(role.clone());
                        roles.push(role);
                    }
                }
            }
        }

        // Resolve permissions
        let permissions = Self::resolve_permissions(&roles);

        // Cache the result
        let cached = CachedPermissions::new(
            permissions.clone(),
            role_names,
            claims.scoped_databases.clone(),
        );
        state.permission_cache.set(claims.sub.clone(), cached);

        Ok(permissions)
    }

    /// Resolve role names to permissions straight from storage, for callers
    /// without an `AppState` (e.g. the binary driver protocol). Unknown role
    /// names fall back to the built-in definitions so a fresh node where
    /// `init_rbac` hasn't persisted them yet still resolves admin/editor/viewer.
    pub fn load_permissions_from_storage(
        storage: &crate::storage::StorageEngine,
        role_names: &[String],
    ) -> HashSet<Permission> {
        let mut roles = Vec::new();
        let roles_coll = storage
            .get_database("_system")
            .ok()
            .and_then(|db| db.get_collection(ROLES_COLLECTION).ok());

        for role_name in role_names {
            let stored = roles_coll
                .as_ref()
                .and_then(|coll| coll.get(role_name).ok())
                .and_then(|doc| serde_json::from_value::<Role>(doc.data).ok());
            if let Some(role) = stored {
                roles.push(role);
            } else if let Some(builtin) = Role::builtin_roles()
                .into_iter()
                .find(|r| &r.name == role_name)
            {
                roles.push(builtin);
            }
        }

        Self::resolve_permissions(&roles)
    }

    /// Check if a user (from Claims) has permission for an action
    ///
    /// This is the main entry point for permission checking in handlers.
    /// It loads permissions from the user's roles and checks against the required action.
    pub async fn check_permission(
        claims: &crate::server::auth::Claims,
        state: &crate::server::handlers::AppState,
        required_action: PermissionAction,
        database: Option<&str>,
    ) -> DbResult<()> {
        let permissions = Self::get_effective_permissions(claims, state).await?;
        let scoped_databases = claims.scoped_databases.as_deref();
        Self::check_permission_raw(&permissions, required_action, database, scoped_databases)
    }

    /// Check if the given permissions satisfy the required action on a resource (raw version)
    ///
    /// # Arguments
    /// * `permissions` - Set of permissions the user has
    /// * `required_action` - The action being performed
    /// * `database` - Optional database name for scoped checks
    /// * `scoped_databases` - Optional list of databases the user is restricted to (for API keys)
    ///
    /// # Returns
    /// * `Ok(())` if permission is granted
    /// * `Err(DbError::Forbidden)` if permission is denied
    pub fn check_permission_raw(
        permissions: &HashSet<Permission>,
        required_action: PermissionAction,
        database: Option<&str>,
        scoped_databases: Option<&[String]>,
    ) -> DbResult<()> {
        // Check database scope restriction (for API keys). A scoped key is
        // confined to its databases: global operations (database == None,
        // e.g. create/delete database, role and API-key management) are
        // denied outright — otherwise a db-scoped admin key could escalate
        // by minting unscoped keys or deleting other databases.
        if let Some(scoped_dbs) = scoped_databases {
            match database {
                Some(db) if scoped_dbs.iter().any(|d| d == db) => {}
                Some(db) => {
                    return Err(DbError::Forbidden(format!(
                        "Access denied: API key not authorized for database '{}'",
                        db
                    )));
                }
                None => {
                    return Err(DbError::Forbidden(
                        "Access denied: database-scoped API key cannot perform global operations"
                            .to_string(),
                    ));
                }
            }
        }

        // Check if user has global admin permission (implies all)
        if permissions.contains(&Permission::global_admin()) {
            return Ok(());
        }

        // Build the required permission
        let required = Permission {
            action: required_action.clone(),
            scope: if database.is_some() {
                PermissionScope::Database
            } else {
                PermissionScope::Global
            },
            database: database.map(String::from),
        };

        // Check if any permission satisfies the requirement
        if Self::has_permission(permissions, &required) {
            Ok(())
        } else {
            Err(DbError::Forbidden(format!(
                "Access denied: insufficient permissions for {:?} on {}",
                required_action,
                database.unwrap_or("global")
            )))
        }
    }
}

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

    #[test]
    fn test_permission_action_implies() {
        assert!(PermissionAction::Admin.implies(&PermissionAction::Admin));
        assert!(PermissionAction::Admin.implies(&PermissionAction::Write));
        assert!(PermissionAction::Admin.implies(&PermissionAction::Read));

        assert!(!PermissionAction::Write.implies(&PermissionAction::Admin));
        assert!(PermissionAction::Write.implies(&PermissionAction::Write));
        assert!(PermissionAction::Write.implies(&PermissionAction::Read));

        assert!(!PermissionAction::Read.implies(&PermissionAction::Admin));
        assert!(!PermissionAction::Read.implies(&PermissionAction::Write));
        assert!(PermissionAction::Read.implies(&PermissionAction::Read));
    }

    #[test]
    fn test_global_admin_implies_all() {
        let mut permissions = HashSet::new();
        permissions.insert(Permission::global_admin());

        // Admin should have access to everything
        assert!(AuthorizationService::check_permission_raw(
            &permissions,
            PermissionAction::Admin,
            None,
            None
        )
        .is_ok());
        assert!(AuthorizationService::check_permission_raw(
            &permissions,
            PermissionAction::Write,
            None,
            None
        )
        .is_ok());
        assert!(AuthorizationService::check_permission_raw(
            &permissions,
            PermissionAction::Read,
            None,
            None
        )
        .is_ok());
        assert!(AuthorizationService::check_permission_raw(
            &permissions,
            PermissionAction::Write,
            Some("mydb"),
            None
        )
        .is_ok());
    }

    #[test]
    fn test_global_write_implies_read() {
        let mut permissions = HashSet::new();
        permissions.insert(Permission::global_write());
        permissions.insert(Permission::global_read());

        // Write+Read should allow read and write but not admin
        assert!(AuthorizationService::check_permission_raw(
            &permissions,
            PermissionAction::Read,
            None,
            None
        )
        .is_ok());
        assert!(AuthorizationService::check_permission_raw(
            &permissions,
            PermissionAction::Write,
            None,
            None
        )
        .is_ok());
        assert!(AuthorizationService::check_permission_raw(
            &permissions,
            PermissionAction::Admin,
            None,
            None
        )
        .is_err());
    }

    #[test]
    fn test_database_scope_restriction() {
        let mut permissions = HashSet::new();
        permissions.insert(Permission::database_permission(
            PermissionAction::Write,
            "allowed_db",
        ));

        // Should work for allowed_db
        assert!(AuthorizationService::check_permission_raw(
            &permissions,
            PermissionAction::Write,
            Some("allowed_db"),
            None
        )
        .is_ok());
        assert!(AuthorizationService::check_permission_raw(
            &permissions,
            PermissionAction::Read,
            Some("allowed_db"),
            None
        )
        .is_ok());

        // Should fail for other databases
        assert!(AuthorizationService::check_permission_raw(
            &permissions,
            PermissionAction::Write,
            Some("other_db"),
            None
        )
        .is_err());
    }

    #[test]
    fn test_api_key_scoped_databases() {
        let mut permissions = HashSet::new();
        permissions.insert(Permission::global_write());
        permissions.insert(Permission::global_read());

        let scoped_dbs = vec!["db1".to_string(), "db2".to_string()];

        // Should work for scoped databases
        assert!(AuthorizationService::check_permission_raw(
            &permissions,
            PermissionAction::Write,
            Some("db1"),
            Some(&scoped_dbs)
        )
        .is_ok());
        assert!(AuthorizationService::check_permission_raw(
            &permissions,
            PermissionAction::Write,
            Some("db2"),
            Some(&scoped_dbs)
        )
        .is_ok());

        // Should fail for non-scoped databases
        assert!(AuthorizationService::check_permission_raw(
            &permissions,
            PermissionAction::Write,
            Some("db3"),
            Some(&scoped_dbs)
        )
        .is_err());
    }

    #[test]
    fn test_scoped_key_denied_global_operations() {
        // Even a scoped key carrying global admin must not perform global
        // operations (create/delete database, role management, key minting).
        let mut permissions = HashSet::new();
        permissions.insert(Permission::global_admin());

        let scoped_dbs = vec!["db1".to_string()];

        assert!(AuthorizationService::check_permission_raw(
            &permissions,
            PermissionAction::Admin,
            None,
            Some(&scoped_dbs)
        )
        .is_err());
        assert!(AuthorizationService::check_permission_raw(
            &permissions,
            PermissionAction::Read,
            None,
            Some(&scoped_dbs)
        )
        .is_err());

        // Inside its scope the key still works, including admin actions.
        assert!(AuthorizationService::check_permission_raw(
            &permissions,
            PermissionAction::Admin,
            Some("db1"),
            Some(&scoped_dbs)
        )
        .is_ok());

        // Unscoped principals are unaffected by the global-op rule.
        assert!(AuthorizationService::check_permission_raw(
            &permissions,
            PermissionAction::Admin,
            None,
            None
        )
        .is_ok());
    }

    #[test]
    fn test_builtin_roles() {
        let roles = Role::builtin_roles();
        assert_eq!(roles.len(), 3);

        let admin = &roles[0];
        assert_eq!(admin.name, "admin");
        assert!(admin.is_builtin);
        assert!(admin.permissions.contains(&Permission::global_admin()));

        let editor = &roles[1];
        assert_eq!(editor.name, "editor");
        assert!(editor.permissions.contains(&Permission::global_write()));
        assert!(editor.permissions.contains(&Permission::global_read()));

        let viewer = &roles[2];
        assert_eq!(viewer.name, "viewer");
        assert!(viewer.permissions.contains(&Permission::global_read()));
    }

    #[test]
    fn test_resolve_permissions() {
        let roles = vec![Role::builtin_editor(), Role::builtin_viewer()];
        let permissions = AuthorizationService::resolve_permissions(&roles);

        assert!(permissions.contains(&Permission::global_write()));
        assert!(permissions.contains(&Permission::global_read()));
        assert!(!permissions.contains(&Permission::global_admin()));
    }
}