auth-framework 0.5.0-rc19

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
//! Migration utilities for transitioning to role-system v1.0
//!
//! This module provides comprehensive migration tools to help users
//! transition from legacy authorization systems to the unified
//! role-system v1.0 approach with minimal disruption.

use serde::{Deserialize, Serialize};
use std::collections::{HashMap, HashSet};
use std::path::PathBuf;
use thiserror::Error;
use tokio::fs;

pub mod analyzers;
pub mod converters;
pub mod executors;
pub mod planners;
pub mod validators;

/// Migration-related errors
#[derive(Error, Debug)]
pub enum MigrationError {
    #[error("Legacy system analysis failed: {0}")]
    AnalysisError(String),

    #[error("Migration plan generation failed: {0}")]
    PlanningError(String),

    #[error("Migration execution failed: {0}")]
    ExecutionError(String),

    #[error("Migration validation failed: {0}")]
    ValidationError(String),

    #[error("Rollback operation failed: {0}")]
    RollbackError(String),

    #[error("I/O error: {0}")]
    IoError(#[from] std::io::Error),

    #[error("Serialization error: {0}")]
    SerializationError(#[from] serde_json::Error),
}

/// Type of legacy authorization system
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub enum LegacySystemType {
    /// Simple permission lists
    PermissionBased,
    /// Basic role-based access control
    BasicRbac,
    /// Attribute-based access control
    Abac,
    /// Custom authorization implementation
    Custom(String),
    /// Multiple mixed systems
    Hybrid(Vec<LegacySystemType>),
}

/// Legacy role definition
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct LegacyRole {
    pub id: String,
    pub name: String,
    pub description: Option<String>,
    pub permissions: Vec<String>,
    pub parent_roles: Vec<String>,
    pub metadata: HashMap<String, String>,
}

/// Legacy user assignment
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct LegacyUserAssignment {
    pub user_id: String,
    pub role_id: Option<String>,
    pub permissions: Vec<String>,
    pub attributes: HashMap<String, String>,
    pub expiration: Option<chrono::DateTime<chrono::Utc>>,
}

/// Legacy permission definition
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct LegacyPermission {
    pub id: String,
    pub action: String,
    pub resource: String,
    pub conditions: HashMap<String, String>,
    pub metadata: HashMap<String, String>,
}

/// Analysis result of legacy authorization system
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct LegacySystemAnalysis {
    /// Type of legacy system detected
    pub system_type: LegacySystemType,

    /// Total number of roles found
    pub role_count: usize,

    /// Total number of permissions found
    pub permission_count: usize,

    /// Total number of user assignments
    pub user_assignment_count: usize,

    /// Discovered roles
    pub roles: Vec<LegacyRole>,

    /// Discovered permissions
    pub permissions: Vec<LegacyPermission>,

    /// User assignments
    pub user_assignments: Vec<LegacyUserAssignment>,

    /// Role hierarchy complexity (depth levels)
    pub hierarchy_depth: usize,

    /// Duplicate roles/permissions detected
    pub duplicates_found: bool,

    /// Orphaned permissions (not assigned to any role)
    pub orphaned_permissions: Vec<String>,

    /// Circular dependencies in role hierarchy
    pub circular_dependencies: Vec<Vec<String>>,

    /// Custom attributes that need special handling
    pub custom_attributes: HashSet<String>,

    /// Estimated migration complexity (1-10 scale)
    pub complexity_score: u8,

    /// Recommended migration strategy
    pub recommended_strategy: MigrationStrategy,
}

/// Migration strategy options
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub enum MigrationStrategy {
    /// Direct mapping with minimal changes
    DirectMapping,
    /// Gradual migration with coexistence period
    GradualMigration,
    /// Complete rebuild with role consolidation
    Rebuild,
    /// Custom strategy for complex scenarios
    Custom(String),
}

/// Migration plan for transitioning to role-system v1.0
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct MigrationPlan {
    /// Unique plan identifier
    pub id: String,

    /// Source system analysis
    pub source_analysis: LegacySystemAnalysis,

    /// Selected migration strategy
    pub strategy: MigrationStrategy,

    /// Planned migration phases
    pub phases: Vec<MigrationPhase>,

    /// Role mapping from legacy to new system
    pub role_mappings: HashMap<String, String>,

    /// Permission mapping from legacy to new system
    pub permission_mappings: HashMap<String, String>,

    /// User assignment migrations
    pub user_migrations: Vec<UserMigration>,

    /// Pre-migration validation steps
    pub pre_validation_steps: Vec<ValidationStep>,

    /// Post-migration validation steps
    pub post_validation_steps: Vec<ValidationStep>,

    /// Rollback plan
    pub rollback_plan: RollbackPlan,

    /// Estimated migration time
    pub estimated_duration: chrono::Duration,

    /// Risk assessment
    pub risk_level: RiskLevel,

    /// Required downtime (if any)
    pub downtime_required: Option<chrono::Duration>,
}

/// Individual migration phase
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct MigrationPhase {
    pub id: String,
    pub name: String,
    pub description: String,
    pub order: u32,
    pub operations: Vec<MigrationOperation>,
    pub dependencies: Vec<String>,
    pub estimated_duration: chrono::Duration,
    pub rollback_operations: Vec<MigrationOperation>,
}

/// Migration operation types
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum MigrationOperation {
    CreateRole {
        role_id: String,
        name: String,
        description: Option<String>,
        permissions: Vec<String>,
        parent_role: Option<String>,
    },
    AssignUserRole {
        user_id: String,
        role_id: String,
        expiration: Option<chrono::DateTime<chrono::Utc>>,
    },
    CreatePermission {
        permission_id: String,
        action: String,
        resource: String,
        conditions: HashMap<String, String>,
    },
    MigrateCustomAttribute {
        attribute_name: String,
        conversion_logic: String,
    },
    ValidateIntegrity {
        validation_type: String,
        parameters: HashMap<String, String>,
    },
    Backup {
        backup_location: PathBuf,
        backup_type: BackupType,
    },
}

/// User migration details
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct UserMigration {
    pub user_id: String,
    pub legacy_roles: Vec<String>,
    pub legacy_permissions: Vec<String>,
    pub new_roles: Vec<String>,
    pub migration_notes: Option<String>,
}

/// Validation step definition
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ValidationStep {
    pub id: String,
    pub name: String,
    pub description: String,
    pub validation_type: ValidationType,
    pub parameters: HashMap<String, String>,
    pub required: bool,
}

/// Types of validation
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Hash)]
pub enum ValidationType {
    /// Check role hierarchy integrity
    HierarchyIntegrity,
    /// Validate permission consistency
    PermissionConsistency,
    /// Check user assignment validity
    UserAssignmentValidity,
    /// Verify no privilege escalation
    PrivilegeEscalationCheck,
    /// Custom validation script
    Custom(String),
}

/// Rollback plan for migration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RollbackPlan {
    pub phases: Vec<RollbackPhase>,
    pub backup_locations: Vec<PathBuf>,
    pub recovery_time_objective: chrono::Duration,
    pub manual_steps: Vec<String>,
}

/// Rollback phase
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RollbackPhase {
    pub id: String,
    pub name: String,
    pub operations: Vec<MigrationOperation>,
    pub order: u32,
}

/// Risk assessment levels
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)]
pub enum RiskLevel {
    Low,
    Medium,
    High,
    Critical,
}

/// Backup types
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum BackupType {
    /// Full system backup
    Full,
    /// Incremental backup
    Incremental,
    /// Configuration only
    ConfigOnly,
    /// Data only
    DataOnly,
}

/// Migration execution result
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct MigrationResult {
    pub plan_id: String,
    pub status: MigrationStatus,
    pub started_at: chrono::DateTime<chrono::Utc>,
    pub completed_at: Option<chrono::DateTime<chrono::Utc>>,
    pub phases_completed: Vec<String>,
    pub current_phase: Option<String>,
    pub errors: Vec<String>,
    pub warnings: Vec<String>,
    pub metrics: MigrationMetrics,
}

/// Migration execution status
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub enum MigrationStatus {
    Planned,
    InProgress,
    Completed,
    Failed,
    RolledBack,
    Paused,
}

/// Migration execution metrics
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct MigrationMetrics {
    pub roles_migrated: usize,
    pub permissions_migrated: usize,
    pub users_migrated: usize,
    pub errors_encountered: usize,
    pub warnings_generated: usize,
    pub validation_failures: usize,
    pub rollback_count: usize,
}

/// Main migration manager
pub struct MigrationManager {
    /// Configuration for migration operations
    config: MigrationConfig,
}

/// Migration manager configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct MigrationConfig {
    /// Working directory for migration files
    pub working_directory: PathBuf,

    /// Backup directory
    pub backup_directory: PathBuf,

    /// Maximum concurrent operations
    pub max_concurrent_operations: usize,

    /// Operation timeout
    pub operation_timeout: chrono::Duration,

    /// Enable dry-run mode
    pub dry_run: bool,

    /// Verbose logging
    pub verbose: bool,
}

impl Default for MigrationConfig {
    fn default() -> Self {
        Self {
            working_directory: PathBuf::from("./migration"),
            backup_directory: PathBuf::from("./migration/backups"),
            max_concurrent_operations: 4,
            operation_timeout: chrono::Duration::minutes(30),
            dry_run: false,
            verbose: false,
        }
    }
}

impl MigrationConfig {
    /// Dry-run mode: analyse the migration plan without applying changes.
    ///
    /// Verbose logging is enabled automatically.
    pub fn dry_run() -> Self {
        Self {
            dry_run: true,
            verbose: true,
            ..Default::default()
        }
    }

    /// Conservative mode: sequential execution with long timeouts.
    ///
    /// Best for production environments where safety is paramount.
    pub fn conservative() -> Self {
        Self {
            max_concurrent_operations: 1,
            operation_timeout: chrono::Duration::minutes(120),
            verbose: true,
            ..Default::default()
        }
    }

    /// Aggressive mode: maximum parallelism for large-scale migrations.
    pub fn aggressive() -> Self {
        Self {
            max_concurrent_operations: 16,
            operation_timeout: chrono::Duration::minutes(60),
            ..Default::default()
        }
    }

    /// Create a builder starting from the default configuration.
    pub fn builder() -> MigrationConfigBuilder {
        MigrationConfigBuilder {
            config: MigrationConfig::default(),
        }
    }
}

/// Fluent builder for [`MigrationConfig`].
///
/// # Example
///
/// ```rust,no_run
/// use auth_framework::migration::MigrationConfig;
///
/// let config = MigrationConfig::builder()
///     .working_directory("./my_migration")
///     .dry_run(true)
///     .max_concurrent(8)
///     .build();
/// ```
#[derive(Debug, Clone)]
pub struct MigrationConfigBuilder {
    config: MigrationConfig,
}

impl MigrationConfigBuilder {
    /// Set the working directory.
    pub fn working_directory(mut self, dir: impl Into<PathBuf>) -> Self {
        self.config.working_directory = dir.into();
        self
    }

    /// Set the backup directory.
    pub fn backup_directory(mut self, dir: impl Into<PathBuf>) -> Self {
        self.config.backup_directory = dir.into();
        self
    }

    /// Set maximum concurrent operations.
    pub fn max_concurrent(mut self, count: usize) -> Self {
        self.config.max_concurrent_operations = count;
        self
    }

    /// Set operation timeout.
    pub fn timeout(mut self, timeout: chrono::Duration) -> Self {
        self.config.operation_timeout = timeout;
        self
    }

    /// Enable or disable dry-run mode.
    pub fn dry_run(mut self, enabled: bool) -> Self {
        self.config.dry_run = enabled;
        self
    }

    /// Enable or disable verbose logging.
    pub fn verbose(mut self, enabled: bool) -> Self {
        self.config.verbose = enabled;
        self
    }

    /// Consume the builder and produce the config.
    pub fn build(self) -> MigrationConfig {
        self.config
    }
}

impl MigrationManager {
    /// Create new migration manager
    pub fn new(config: MigrationConfig) -> Result<Self, MigrationError> {
        // Ensure directories exist
        std::fs::create_dir_all(&config.working_directory)?;
        std::fs::create_dir_all(&config.backup_directory)?;

        Ok(Self { config })
    }

    /// Analyze legacy authorization system
    pub async fn analyze_legacy_system<P: AsRef<std::path::Path>>(
        &self,
        config_path: P,
    ) -> Result<LegacySystemAnalysis, MigrationError> {
        analyzers::analyze_legacy_system(config_path, &self.config).await
    }

    /// Generate migration plan
    pub async fn generate_migration_plan(
        &self,
        analysis: &LegacySystemAnalysis,
        strategy: Option<MigrationStrategy>,
    ) -> Result<MigrationPlan, MigrationError> {
        planners::generate_migration_plan(analysis, strategy, &self.config).await
    }

    /// Validate migration plan
    pub async fn validate_migration_plan(
        &self,
        plan: &MigrationPlan,
    ) -> Result<Vec<String>, MigrationError> {
        validators::validate_migration_plan(plan, &self.config).await
    }

    /// Execute migration plan
    pub async fn execute_migration(
        &self,
        plan: &MigrationPlan,
    ) -> Result<MigrationResult, MigrationError> {
        executors::execute_migration_plan(plan, &self.config).await
    }

    /// Get migration status
    pub async fn get_migration_status(
        &self,
        plan_id: &str,
    ) -> Result<Option<MigrationResult>, MigrationError> {
        let status_file = self
            .config
            .working_directory
            .join(format!("{}_status.json", plan_id));

        if !status_file.exists() {
            return Ok(None);
        }

        let content = fs::read_to_string(status_file).await?;
        let result: MigrationResult = serde_json::from_str(&content)?;
        Ok(Some(result))
    }

    /// Rollback migration
    pub async fn rollback_migration(
        &self,
        plan: &MigrationPlan,
    ) -> Result<MigrationResult, MigrationError> {
        executors::rollback_migration(plan, &self.config).await
    }

    /// List available migration plans
    pub async fn list_migration_plans(&self) -> Result<Vec<String>, MigrationError> {
        let mut plans = Vec::new();
        let mut entries = fs::read_dir(&self.config.working_directory).await?;

        while let Some(entry) = entries.next_entry().await? {
            let path = entry.path();
            if path.extension().is_some_and(|ext| ext == "json")
                && let Some(file_name) = path.file_stem()
                && let Some(name) = file_name.to_str()
                && name.ends_with("_plan")
            {
                plans.push(name.trim_end_matches("_plan").to_string());
            }
        }

        Ok(plans)
    }

    /// Save migration plan to disk
    pub async fn save_migration_plan(
        &self,
        plan: &MigrationPlan,
    ) -> Result<PathBuf, MigrationError> {
        let plan_file = self
            .config
            .working_directory
            .join(format!("{}_plan.json", plan.id));
        let content = serde_json::to_string_pretty(plan)?;
        fs::write(&plan_file, content).await?;
        Ok(plan_file)
    }

    /// Load migration plan from disk
    pub async fn load_migration_plan(
        &self,
        plan_id: &str,
    ) -> Result<MigrationPlan, MigrationError> {
        let plan_file = self
            .config
            .working_directory
            .join(format!("{}_plan.json", plan_id));
        let content = fs::read_to_string(plan_file).await?;
        let plan: MigrationPlan = serde_json::from_str(&content)?;
        Ok(plan)
    }

    /// Generate migration report
    pub async fn generate_migration_report(
        &self,
        result: &MigrationResult,
    ) -> Result<String, MigrationError> {
        let mut report = String::new();

        report.push_str("# Migration Report\n\n");
        report.push_str(&format!("**Plan ID**: {}\n", result.plan_id));
        report.push_str(&format!("**Status**: {:?}\n", result.status));
        report.push_str(&format!("**Started**: {}\n", result.started_at));

        if let Some(completed) = result.completed_at {
            report.push_str(&format!("**Completed**: {}\n", completed));
            let duration = completed - result.started_at;
            report.push_str(&format!(
                "**Duration**: {} minutes\n",
                duration.num_minutes()
            ));
        }

        report.push_str("\n## Metrics\n\n");
        report.push_str(&format!(
            "- Roles migrated: {}\n",
            result.metrics.roles_migrated
        ));
        report.push_str(&format!(
            "- Permissions migrated: {}\n",
            result.metrics.permissions_migrated
        ));
        report.push_str(&format!(
            "- Users migrated: {}\n",
            result.metrics.users_migrated
        ));
        report.push_str(&format!(
            "- Errors: {}\n",
            result.metrics.errors_encountered
        ));
        report.push_str(&format!(
            "- Warnings: {}\n",
            result.metrics.warnings_generated
        ));

        if !result.errors.is_empty() {
            report.push_str("\n## Errors\n\n");
            for error in &result.errors {
                report.push_str(&format!("- {}\n", error));
            }
        }

        if !result.warnings.is_empty() {
            report.push_str("\n## Warnings\n\n");
            for warning in &result.warnings {
                report.push_str(&format!("- {}\n", warning));
            }
        }

        Ok(report)
    }
}

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

    #[tokio::test]
    async fn test_migration_manager_creation() {
        let config = MigrationConfig::default();
        let manager = MigrationManager::new(config);
        assert!(manager.is_ok());
    }

    #[test]
    fn test_legacy_system_type_serialization() {
        let system_type = LegacySystemType::BasicRbac;
        let serialized = serde_json::to_string(&system_type).unwrap();
        let deserialized: LegacySystemType = serde_json::from_str(&serialized).unwrap();
        assert_eq!(system_type, deserialized);
    }

    #[test]
    fn test_migration_strategy_serialization() {
        let strategy = MigrationStrategy::GradualMigration;
        let serialized = serde_json::to_string(&strategy).unwrap();
        let deserialized: MigrationStrategy = serde_json::from_str(&serialized).unwrap();
        assert_eq!(strategy, deserialized);
    }

    #[test]
    fn test_risk_level_ordering() {
        assert!(RiskLevel::Low < RiskLevel::Medium);
        assert!(RiskLevel::Medium < RiskLevel::High);
        assert!(RiskLevel::High < RiskLevel::Critical);
    }

    #[test]
    fn test_migration_config_dry_run_preset() {
        let config = MigrationConfig::dry_run();
        assert!(config.dry_run);
        assert!(config.verbose);
    }

    #[test]
    fn test_migration_config_conservative_preset() {
        let config = MigrationConfig::conservative();
        assert_eq!(config.max_concurrent_operations, 1);
        assert!(config.verbose);
        assert!(!config.dry_run);
    }

    #[test]
    fn test_migration_config_aggressive_preset() {
        let config = MigrationConfig::aggressive();
        assert_eq!(config.max_concurrent_operations, 16);
    }

    #[test]
    fn test_migration_config_builder() {
        let config = MigrationConfig::builder()
            .working_directory("/tmp/migration")
            .dry_run(true)
            .max_concurrent(8)
            .verbose(true)
            .build();
        assert_eq!(config.working_directory, PathBuf::from("/tmp/migration"));
        assert!(config.dry_run);
        assert_eq!(config.max_concurrent_operations, 8);
        assert!(config.verbose);
    }

    #[tokio::test]
    async fn test_migration_manager_with_dry_run_preset() {
        let config = MigrationConfig::dry_run();
        let manager = MigrationManager::new(config);
        assert!(manager.is_ok());
    }
}