auth-framework 0.5.0-rc18

A comprehensive, production-ready authentication and authorization framework for Rust applications
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
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
//! Storage adapters for role-system integration
//!
//! This module provides storage adapters that integrate role-system with
//! AuthFramework's existing storage infrastructure. It defines its own
//! serializable types (`StoredRole`, `StoredPermission`) for persistence,
//! with conversions to/from the `role_system` crate's types.

use async_trait::async_trait;
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::sync::Arc;
use tokio::sync::RwLock;
use tracing::{debug, info};

// ── Storage-layer error types ────────────────────────────────────────────────

/// Error type for storage operations
#[derive(Debug, thiserror::Error)]
pub enum StorageError {
    #[error("Database error: {0}")]
    Database(String),
    #[error("Serialization error: {0}")]
    Serialization(String),
    #[error("Not found: {0}")]
    NotFound(String),
}

/// Result alias for storage operations
pub type StorageResult<T> = Result<T, StorageError>;

// ── Serializable storage types (decoupled from role_system's private fields) ─

/// A serializable role representation for persistence
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct StoredRole {
    pub id: String,
    pub name: String,
    pub description: Option<String>,
    pub permissions: Vec<StoredPermission>,
}

/// A serializable permission representation for persistence
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct StoredPermission {
    pub action: String,
    pub resource: String,
    pub instance: Option<String>,
}

/// A role-to-user assignment record
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RoleAssignment {
    pub user_id: String,
    pub role_id: String,
    pub assigned_by: Option<String>,
    pub expires_at: Option<chrono::DateTime<chrono::Utc>>,
}

/// An audit log entry for authorization events
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AuditEntry {
    pub user_id: Option<String>,
    pub action: String,
    pub resource: Option<String>,
    pub result: String,
    pub context: HashMap<String, String>,
}

// ── Conversions between storage types and role_system types ──────────────────

impl StoredRole {
    /// Convert to a `role_system::Role` (for use with the role-system engine)
    pub fn to_role_system(&self) -> role_system::Role {
        let mut role = role_system::Role::with_id(&self.id, &self.name);
        if let Some(ref desc) = self.description {
            role = role.with_description(desc);
        }
        for perm in &self.permissions {
            role = role.add_permission(perm.to_role_system());
        }
        role
    }

    /// Create from a `role_system::Role`
    pub fn from_role_system(role: &role_system::Role) -> Self {
        Self {
            id: role.id().to_string(),
            name: role.name().to_string(),
            description: role.description().map(|s| s.to_string()),
            permissions: role
                .permissions()
                .permissions()
                .iter()
                .map(StoredPermission::from_role_system)
                .collect(),
        }
    }
}

impl StoredPermission {
    /// Convert to a `role_system::Permission`
    pub fn to_role_system(&self) -> role_system::Permission {
        if let Some(ref instance) = self.instance {
            role_system::Permission::with_instance(&self.action, &self.resource, instance)
        } else {
            role_system::Permission::new(&self.action, &self.resource)
        }
    }

    /// Create from a `role_system::Permission`
    pub fn from_role_system(perm: &role_system::Permission) -> Self {
        Self {
            action: perm.action().to_string(),
            resource: perm.resource_type().to_string(),
            instance: perm.instance().map(|s| s.to_string()),
        }
    }
}

// ── Async storage trait ─────────────────────────────────────────────────────

/// Async storage trait for persisting RBAC data (roles, permissions, assignments, audit)
#[async_trait]
pub trait RoleStorage: Send + Sync {
    async fn create_role(&self, role: &StoredRole) -> StorageResult<()>;
    async fn update_role(&self, role: &StoredRole) -> StorageResult<()>;
    async fn delete_role(&self, role_id: &str) -> StorageResult<()>;
    async fn get_role(&self, role_id: &str) -> StorageResult<Option<StoredRole>>;
    async fn list_roles(&self) -> StorageResult<Vec<StoredRole>>;

    async fn store_permission(&self, id: &str, permission: &StoredPermission) -> StorageResult<()>;
    async fn get_permission(&self, permission_id: &str) -> StorageResult<Option<StoredPermission>>;

    async fn assign_role(&self, assignment: &RoleAssignment) -> StorageResult<()>;
    async fn revoke_role(&self, user_id: &str, role_id: &str) -> StorageResult<()>;
    async fn get_user_roles(&self, user_id: &str) -> StorageResult<Vec<String>>;
    async fn get_role_permissions(&self, role_id: &str) -> StorageResult<Vec<String>>;

    async fn log_audit_entry(&self, entry: &AuditEntry) -> StorageResult<()>;
}

// ── Database abstractions ───────────────────────────────────────────────────

/// Database-backed storage adapter for role-system
pub struct DatabaseStorage {
    connection: Arc<dyn DatabaseConnection>,
    role_cache: Arc<RwLock<HashMap<String, StoredRole>>>,
    permission_cache: Arc<RwLock<HashMap<String, StoredPermission>>>,
    cache_ttl: u64,
}

/// Database connection trait (abstraction over actual database)
#[async_trait]
pub trait DatabaseConnection: Send + Sync {
    async fn execute_query(
        &self,
        query: &str,
        params: &[&dyn DatabaseValue],
    ) -> Result<QueryResult, DatabaseError>;
    async fn fetch_one(
        &self,
        query: &str,
        params: &[&dyn DatabaseValue],
    ) -> Result<Row, DatabaseError>;
    async fn fetch_all(
        &self,
        query: &str,
        params: &[&dyn DatabaseValue],
    ) -> Result<Vec<Row>, DatabaseError>;
}

/// Database value trait for query parameters
pub trait DatabaseValue: Send + Sync {
    fn as_str(&self) -> Option<&str>;
    fn as_i64(&self) -> Option<i64>;
    fn as_bool(&self) -> Option<bool>;
}

impl DatabaseValue for String {
    fn as_str(&self) -> Option<&str> {
        Some(self.as_ref())
    }
    fn as_i64(&self) -> Option<i64> {
        None
    }
    fn as_bool(&self) -> Option<bool> {
        None
    }
}

impl DatabaseValue for &str {
    fn as_str(&self) -> Option<&str> {
        Some(self)
    }
    fn as_i64(&self) -> Option<i64> {
        None
    }
    fn as_bool(&self) -> Option<bool> {
        None
    }
}

impl DatabaseValue for Option<&str> {
    fn as_str(&self) -> Option<&str> {
        *self
    }
    fn as_i64(&self) -> Option<i64> {
        None
    }
    fn as_bool(&self) -> Option<bool> {
        None
    }
}

impl DatabaseValue for i64 {
    fn as_str(&self) -> Option<&str> {
        None
    }
    fn as_i64(&self) -> Option<i64> {
        Some(*self)
    }
    fn as_bool(&self) -> Option<bool> {
        None
    }
}

impl DatabaseValue for bool {
    fn as_str(&self) -> Option<&str> {
        None
    }
    fn as_i64(&self) -> Option<i64> {
        None
    }
    fn as_bool(&self) -> Option<bool> {
        Some(*self)
    }
}

/// Database query result
#[derive(Debug)]
pub struct QueryResult {
    pub rows_affected: u64,
}

/// Database row
#[derive(Debug)]
pub struct Row {
    pub columns: HashMap<String, DatabaseColumnValue>,
}

/// Database column value
#[derive(Debug, Clone)]
pub enum DatabaseColumnValue {
    String(String),
    Integer(i64),
    Boolean(bool),
    Null,
}

/// Database error
#[derive(Debug, thiserror::Error)]
pub enum DatabaseError {
    #[error("Connection error: {0}")]
    Connection(String),
    #[error("Query error: {0}")]
    Query(String),
    #[error("Serialization error: {0}")]
    Serialization(String),
}

impl DatabaseStorage {
    /// Create new database storage adapter
    pub fn new(connection: Arc<dyn DatabaseConnection>) -> Self {
        Self {
            connection,
            role_cache: Arc::new(RwLock::new(HashMap::new())),
            permission_cache: Arc::new(RwLock::new(HashMap::new())),
            cache_ttl: 300, // 5 minutes
        }
    }

    /// Set cache TTL
    pub fn with_cache_ttl(mut self, ttl_seconds: u64) -> Self {
        self.cache_ttl = ttl_seconds;
        self
    }

    /// Initialize database schema
    pub async fn initialize_schema(&self) -> Result<(), DatabaseError> {
        self.connection
            .execute_query(
                r#"CREATE TABLE IF NOT EXISTS roles (
                    id VARCHAR(255) PRIMARY KEY,
                    name VARCHAR(255) NOT NULL UNIQUE,
                    description TEXT,
                    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
                    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
                )"#,
                &[],
            )
            .await?;

        self.connection
            .execute_query(
                r#"CREATE TABLE IF NOT EXISTS permissions (
                    id VARCHAR(255) PRIMARY KEY,
                    action VARCHAR(255) NOT NULL,
                    resource VARCHAR(255) NOT NULL,
                    instance VARCHAR(255),
                    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
                    UNIQUE(action, resource)
                )"#,
                &[],
            )
            .await?;

        self.connection
            .execute_query(
                r#"CREATE TABLE IF NOT EXISTS role_permissions (
                    role_id VARCHAR(255),
                    permission_id VARCHAR(255),
                    granted_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
                    PRIMARY KEY (role_id, permission_id),
                    FOREIGN KEY (role_id) REFERENCES roles(id) ON DELETE CASCADE,
                    FOREIGN KEY (permission_id) REFERENCES permissions(id) ON DELETE CASCADE
                )"#,
                &[],
            )
            .await?;

        self.connection
            .execute_query(
                r#"CREATE TABLE IF NOT EXISTS user_roles (
                    user_id VARCHAR(255),
                    role_id VARCHAR(255),
                    assigned_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
                    assigned_by VARCHAR(255),
                    expires_at TIMESTAMP NULL,
                    PRIMARY KEY (user_id, role_id),
                    FOREIGN KEY (role_id) REFERENCES roles(id) ON DELETE CASCADE
                )"#,
                &[],
            )
            .await?;

        self.connection
            .execute_query(
                r#"CREATE TABLE IF NOT EXISTS audit_log (
                    id BIGINT PRIMARY KEY AUTO_INCREMENT,
                    user_id VARCHAR(255),
                    action VARCHAR(255) NOT NULL,
                    resource VARCHAR(255),
                    result VARCHAR(50) NOT NULL,
                    context TEXT,
                    timestamp TIMESTAMP DEFAULT CURRENT_TIMESTAMP
                )"#,
                &[],
            )
            .await?;

        info!("Database schema initialized successfully");
        Ok(())
    }

    /// Clear caches
    async fn clear_caches(&self) {
        self.role_cache.write().await.clear();
        self.permission_cache.write().await.clear();
        debug!("Cleared authorization caches");
    }

    fn row_to_stored_role(&self, row: &Row) -> StorageResult<StoredRole> {
        let id = self.get_string_column(row, "id")?;
        let name = self.get_string_column(row, "name")?;
        let description = self.get_optional_string_column(row, "description");
        Ok(StoredRole {
            id,
            name,
            description,
            permissions: Vec::new(), // loaded via role_permissions join
        })
    }

    fn row_to_stored_permission(&self, row: &Row) -> StorageResult<StoredPermission> {
        let action = self.get_string_column(row, "action")?;
        let resource = self.get_string_column(row, "resource")?;
        let instance = self.get_optional_string_column(row, "instance");
        Ok(StoredPermission {
            action,
            resource,
            instance,
        })
    }

    fn get_string_column(&self, row: &Row, column: &str) -> StorageResult<String> {
        match row.columns.get(column) {
            Some(DatabaseColumnValue::String(value)) => Ok(value.clone()),
            Some(DatabaseColumnValue::Null) => {
                Err(StorageError::Database(format!("Column {column} is null")))
            }
            Some(_) => Err(StorageError::Database(format!(
                "Column {column} is not a string"
            ))),
            None => Err(StorageError::Database(format!("Column {column} not found"))),
        }
    }

    fn get_optional_string_column(&self, row: &Row, column: &str) -> Option<String> {
        match row.columns.get(column) {
            Some(DatabaseColumnValue::String(value)) => Some(value.clone()),
            _ => None,
        }
    }
}

#[async_trait]
impl RoleStorage for DatabaseStorage {
    async fn create_role(&self, role: &StoredRole) -> StorageResult<()> {
        self.connection
            .execute_query(
                "INSERT INTO roles (id, name, description) VALUES (?, ?, ?)",
                &[
                    &role.id as &dyn DatabaseValue,
                    &role.name as &dyn DatabaseValue,
                    &role.description.as_deref().unwrap_or("") as &dyn DatabaseValue,
                ],
            )
            .await
            .map_err(|e| StorageError::Database(e.to_string()))?;
        self.clear_caches().await;
        info!("Created role: {}", role.name);
        Ok(())
    }

    async fn update_role(&self, role: &StoredRole) -> StorageResult<()> {
        self.connection
            .execute_query(
                "UPDATE roles SET name = ?, description = ?, updated_at = CURRENT_TIMESTAMP WHERE id = ?",
                &[
                    &role.name as &dyn DatabaseValue,
                    &role.description.as_deref().unwrap_or("") as &dyn DatabaseValue,
                    &role.id as &dyn DatabaseValue,
                ],
            )
            .await
            .map_err(|e| StorageError::Database(e.to_string()))?;
        self.role_cache
            .write()
            .await
            .insert(role.id.clone(), role.clone());
        info!("Updated role: {}", role.name);
        Ok(())
    }

    async fn delete_role(&self, role_id: &str) -> StorageResult<()> {
        self.connection
            .execute_query(
                "DELETE FROM roles WHERE id = ?",
                &[&role_id as &dyn DatabaseValue],
            )
            .await
            .map_err(|e| StorageError::Database(e.to_string()))?;
        self.role_cache.write().await.remove(role_id);
        info!("Deleted role: {}", role_id);
        Ok(())
    }

    async fn get_role(&self, role_id: &str) -> StorageResult<Option<StoredRole>> {
        {
            let cache = self.role_cache.read().await;
            if let Some(role) = cache.get(role_id) {
                return Ok(Some(role.clone()));
            }
        }
        let row = match self
            .connection
            .fetch_one(
                "SELECT id, name, description FROM roles WHERE id = ?",
                &[&role_id as &dyn DatabaseValue],
            )
            .await
        {
            Ok(row) => row,
            Err(DatabaseError::Query(_)) => return Ok(None),
            Err(e) => return Err(StorageError::Database(e.to_string())),
        };
        let role = self.row_to_stored_role(&row)?;
        self.role_cache
            .write()
            .await
            .insert(role_id.to_string(), role.clone());
        Ok(Some(role))
    }

    async fn list_roles(&self) -> StorageResult<Vec<StoredRole>> {
        let rows = self
            .connection
            .fetch_all("SELECT id, name, description FROM roles ORDER BY name", &[])
            .await
            .map_err(|e| StorageError::Database(e.to_string()))?;
        rows.iter().map(|r| self.row_to_stored_role(r)).collect()
    }

    async fn store_permission(&self, id: &str, permission: &StoredPermission) -> StorageResult<()> {
        self.connection
            .execute_query(
                "INSERT INTO permissions (id, action, resource, instance) VALUES (?, ?, ?, ?)",
                &[
                    &id as &dyn DatabaseValue,
                    &permission.action as &dyn DatabaseValue,
                    &permission.resource as &dyn DatabaseValue,
                    &permission.instance.as_deref() as &dyn DatabaseValue,
                ],
            )
            .await
            .map_err(|e| StorageError::Database(e.to_string()))?;
        self.permission_cache
            .write()
            .await
            .insert(id.to_string(), permission.clone());
        info!(
            "Created permission: {}:{}",
            permission.action, permission.resource
        );
        Ok(())
    }

    async fn get_permission(&self, permission_id: &str) -> StorageResult<Option<StoredPermission>> {
        {
            let cache = self.permission_cache.read().await;
            if let Some(p) = cache.get(permission_id) {
                return Ok(Some(p.clone()));
            }
        }
        let row = match self
            .connection
            .fetch_one(
                "SELECT action, resource, instance FROM permissions WHERE id = ?",
                &[&permission_id as &dyn DatabaseValue],
            )
            .await
        {
            Ok(row) => row,
            Err(DatabaseError::Query(_)) => return Ok(None),
            Err(e) => return Err(StorageError::Database(e.to_string())),
        };
        let perm = self.row_to_stored_permission(&row)?;
        self.permission_cache
            .write()
            .await
            .insert(permission_id.to_string(), perm.clone());
        Ok(Some(perm))
    }

    async fn assign_role(&self, assignment: &RoleAssignment) -> StorageResult<()> {
        self.connection
            .execute_query(
                "INSERT OR REPLACE INTO user_roles (user_id, role_id, assigned_by) VALUES (?, ?, ?)",
                &[
                    &assignment.user_id as &dyn DatabaseValue,
                    &assignment.role_id as &dyn DatabaseValue,
                    &assignment.assigned_by.as_deref() as &dyn DatabaseValue,
                ],
            )
            .await
            .map_err(|e| StorageError::Database(e.to_string()))?;
        info!(
            "Assigned role {} to user {}",
            assignment.role_id, assignment.user_id
        );
        Ok(())
    }

    async fn revoke_role(&self, user_id: &str, role_id: &str) -> StorageResult<()> {
        self.connection
            .execute_query(
                "DELETE FROM user_roles WHERE user_id = ? AND role_id = ?",
                &[
                    &user_id as &dyn DatabaseValue,
                    &role_id as &dyn DatabaseValue,
                ],
            )
            .await
            .map_err(|e| StorageError::Database(e.to_string()))?;
        info!("Revoked role {} from user {}", role_id, user_id);
        Ok(())
    }

    async fn get_user_roles(&self, user_id: &str) -> StorageResult<Vec<String>> {
        let rows = self
            .connection
            .fetch_all(
                "SELECT role_id FROM user_roles WHERE user_id = ? AND (expires_at IS NULL OR expires_at > CURRENT_TIMESTAMP)",
                &[&user_id as &dyn DatabaseValue],
            )
            .await
            .map_err(|e| StorageError::Database(e.to_string()))?;
        Ok(rows
            .iter()
            .filter_map(|r| match r.columns.get("role_id") {
                Some(DatabaseColumnValue::String(s)) => Some(s.clone()),
                _ => None,
            })
            .collect())
    }

    async fn get_role_permissions(&self, role_id: &str) -> StorageResult<Vec<String>> {
        let rows = self
            .connection
            .fetch_all(
                "SELECT permission_id FROM role_permissions WHERE role_id = ?",
                &[&role_id as &dyn DatabaseValue],
            )
            .await
            .map_err(|e| StorageError::Database(e.to_string()))?;
        Ok(rows
            .iter()
            .filter_map(|r| match r.columns.get("permission_id") {
                Some(DatabaseColumnValue::String(s)) => Some(s.clone()),
                _ => None,
            })
            .collect())
    }

    async fn log_audit_entry(&self, entry: &AuditEntry) -> StorageResult<()> {
        let context_json = serde_json::to_string(&entry.context)
            .map_err(|e| StorageError::Serialization(e.to_string()))?;
        self.connection
            .execute_query(
                "INSERT INTO audit_log (user_id, action, resource, result, context) VALUES (?, ?, ?, ?, ?)",
                &[
                    &entry.user_id.as_deref() as &dyn DatabaseValue,
                    &entry.action as &dyn DatabaseValue,
                    &entry.resource.as_deref() as &dyn DatabaseValue,
                    &entry.result as &dyn DatabaseValue,
                    &context_json as &dyn DatabaseValue,
                ],
            )
            .await
            .map_err(|e| StorageError::Database(e.to_string()))?;
        debug!(
            "Logged audit entry for user {:?}: {}",
            entry.user_id, entry.action
        );
        Ok(())
    }
}

// ── In-memory storage (for testing and development) ─────────────────────────

/// In-memory storage adapter for testing and development
pub struct MemoryRbacStorage {
    roles: Arc<RwLock<HashMap<String, StoredRole>>>,
    permissions: Arc<RwLock<HashMap<String, StoredPermission>>>,
    user_roles: Arc<RwLock<HashMap<String, Vec<String>>>>,
    role_permissions: Arc<RwLock<HashMap<String, Vec<String>>>>,
    audit_log: Arc<RwLock<Vec<AuditEntry>>>,
}

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

impl MemoryRbacStorage {
    pub fn new() -> Self {
        Self {
            roles: Arc::new(RwLock::new(HashMap::new())),
            permissions: Arc::new(RwLock::new(HashMap::new())),
            user_roles: Arc::new(RwLock::new(HashMap::new())),
            role_permissions: Arc::new(RwLock::new(HashMap::new())),
            audit_log: Arc::new(RwLock::new(Vec::new())),
        }
    }

    /// Clear all data (useful for testing)
    pub async fn clear(&self) {
        self.roles.write().await.clear();
        self.permissions.write().await.clear();
        self.user_roles.write().await.clear();
        self.role_permissions.write().await.clear();
        self.audit_log.write().await.clear();
    }
}

#[async_trait]
impl RoleStorage for MemoryRbacStorage {
    async fn create_role(&self, role: &StoredRole) -> StorageResult<()> {
        self.roles
            .write()
            .await
            .insert(role.id.clone(), role.clone());
        info!("Created role in memory: {}", role.name);
        Ok(())
    }

    async fn update_role(&self, role: &StoredRole) -> StorageResult<()> {
        self.roles
            .write()
            .await
            .insert(role.id.clone(), role.clone());
        info!("Updated role in memory: {}", role.name);
        Ok(())
    }

    async fn delete_role(&self, role_id: &str) -> StorageResult<()> {
        self.roles.write().await.remove(role_id);
        info!("Deleted role from memory: {}", role_id);
        Ok(())
    }

    async fn get_role(&self, role_id: &str) -> StorageResult<Option<StoredRole>> {
        Ok(self.roles.read().await.get(role_id).cloned())
    }

    async fn list_roles(&self) -> StorageResult<Vec<StoredRole>> {
        Ok(self.roles.read().await.values().cloned().collect())
    }

    async fn store_permission(&self, id: &str, permission: &StoredPermission) -> StorageResult<()> {
        self.permissions
            .write()
            .await
            .insert(id.to_string(), permission.clone());
        info!(
            "Created permission in memory: {}:{}",
            permission.action, permission.resource
        );
        Ok(())
    }

    async fn get_permission(&self, permission_id: &str) -> StorageResult<Option<StoredPermission>> {
        Ok(self.permissions.read().await.get(permission_id).cloned())
    }

    async fn assign_role(&self, assignment: &RoleAssignment) -> StorageResult<()> {
        self.user_roles
            .write()
            .await
            .entry(assignment.user_id.clone())
            .or_default()
            .push(assignment.role_id.clone());
        info!(
            "Assigned role in memory: {} to {}",
            assignment.role_id, assignment.user_id
        );
        Ok(())
    }

    async fn revoke_role(&self, user_id: &str, role_id: &str) -> StorageResult<()> {
        if let Some(roles) = self.user_roles.write().await.get_mut(user_id) {
            roles.retain(|r| r != role_id);
        }
        info!("Revoked role from memory: {} from {}", role_id, user_id);
        Ok(())
    }

    async fn get_user_roles(&self, user_id: &str) -> StorageResult<Vec<String>> {
        Ok(self
            .user_roles
            .read()
            .await
            .get(user_id)
            .cloned()
            .unwrap_or_default())
    }

    async fn get_role_permissions(&self, role_id: &str) -> StorageResult<Vec<String>> {
        Ok(self
            .role_permissions
            .read()
            .await
            .get(role_id)
            .cloned()
            .unwrap_or_default())
    }

    async fn log_audit_entry(&self, entry: &AuditEntry) -> StorageResult<()> {
        self.audit_log.write().await.push(entry.clone());
        debug!(
            "Logged audit entry in memory for user {:?}: {}",
            entry.user_id, entry.action
        );
        Ok(())
    }
}

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

    #[tokio::test]
    async fn test_memory_storage_basic_operations() {
        let storage = MemoryRbacStorage::new();

        let role = StoredRole {
            id: "test_role".to_string(),
            name: "Test Role".to_string(),
            description: Some("A test role".to_string()),
            permissions: Vec::new(),
        };

        storage.create_role(&role).await.unwrap();

        let retrieved = storage.get_role("test_role").await.unwrap();
        assert!(retrieved.is_some());
        assert_eq!(retrieved.unwrap().name, "Test Role");

        let roles = storage.list_roles().await.unwrap();
        assert_eq!(roles.len(), 1);

        storage.delete_role("test_role").await.unwrap();
        let retrieved = storage.get_role("test_role").await.unwrap();
        assert!(retrieved.is_none());
    }

    #[tokio::test]
    async fn test_memory_storage_permissions() {
        let storage = MemoryRbacStorage::new();

        let permission = StoredPermission {
            action: "read".to_string(),
            resource: "users".to_string(),
            instance: None,
        };

        storage
            .store_permission("test_perm", &permission)
            .await
            .unwrap();

        let retrieved = storage.get_permission("test_perm").await.unwrap();
        assert!(retrieved.is_some());
        assert_eq!(retrieved.unwrap().action, "read");
    }

    #[tokio::test]
    async fn test_memory_storage_role_assignment() {
        let storage = MemoryRbacStorage::new();

        let assignment = RoleAssignment {
            user_id: "user1".to_string(),
            role_id: "admin".to_string(),
            assigned_by: Some("system".to_string()),
            expires_at: None,
        };

        storage.assign_role(&assignment).await.unwrap();
        let user_roles = storage.get_user_roles("user1").await.unwrap();
        assert_eq!(user_roles, vec!["admin"]);

        storage.revoke_role("user1", "admin").await.unwrap();
        let user_roles = storage.get_user_roles("user1").await.unwrap();
        assert!(user_roles.is_empty());
    }

    #[tokio::test]
    async fn test_stored_role_conversion_roundtrip() {
        let stored = StoredRole {
            id: "role1".to_string(),
            name: "Admin".to_string(),
            description: Some("Administrator role".to_string()),
            permissions: vec![StoredPermission {
                action: "read".to_string(),
                resource: "users".to_string(),
                instance: None,
            }],
        };

        let rs_role = stored.to_role_system();
        assert_eq!(rs_role.id(), "role1");
        assert_eq!(rs_role.name(), "Admin");
        assert_eq!(rs_role.description(), Some("Administrator role"));

        let back = StoredRole::from_role_system(&rs_role);
        assert_eq!(back.id, "role1");
        assert_eq!(back.name, "Admin");
        assert_eq!(back.permissions.len(), 1);
        assert_eq!(back.permissions[0].action, "read");
    }

    #[tokio::test]
    async fn test_audit_logging() {
        let storage = MemoryRbacStorage::new();

        let entry = AuditEntry {
            user_id: Some("user1".to_string()),
            action: "login".to_string(),
            resource: Some("auth".to_string()),
            result: "success".to_string(),
            context: HashMap::from([("ip".to_string(), "127.0.0.1".to_string())]),
        };

        storage.log_audit_entry(&entry).await.unwrap();
        let log = storage.audit_log.read().await;
        assert_eq!(log.len(), 1);
        assert_eq!(log[0].action, "login");
    }
}