auth-framework 0.4.40

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
//! Comprehensive administration module for AuthFramework management.
//!
//! This module provides multiple administrative interfaces for monitoring,
//! configuring, and managing AuthFramework deployments. It includes both
//! interactive and programmatic interfaces suitable for different operational
//! environments.
//!
//! # Administrative Interfaces
//!
//! - **CLI (Command Line Interface)**: Scriptable command-line administration
//! - **TUI (Terminal User Interface)**: Interactive terminal dashboard
//! - **Web Interface**: Browser-based administrative console
//! - **API**: RESTful API for programmatic management
//!
//! # Core Capabilities
//!
//! - **Real-time Monitoring**: Live metrics and health status
//! - **Configuration Management**: Dynamic configuration updates
//! - **User Management**: User account and permission administration
//! - **Security Monitoring**: Threat detection and incident response
//! - **Audit Logging**: Comprehensive activity tracking
//! - **Performance Analytics**: System performance and optimization
//!
//! # Security Features
//!
//! - **Role-based Access**: Admin, operator, and read-only roles
//! - **Audit Trail**: All administrative actions are logged
//! - **Secure Sessions**: Encrypted admin sessions
//! - **MFA Enforcement**: Multi-factor authentication for admins
//! - **IP Whitelisting**: Restrict admin access by network
//!
//! # Monitoring Dashboard
//!
//! The administrative interfaces provide comprehensive monitoring:
//! - Active user sessions
//! - Authentication success/failure rates
//! - Security alerts and incidents
//! - System performance metrics
//! - Error rates and debugging information
//!
//! # Configuration Management
//!
//! - **Live Updates**: Modify configuration without restarts
//! - **Validation**: Real-time configuration validation
//! - **Backup/Restore**: Configuration versioning and rollback
//! - **Environment Management**: Dev, staging, production configs
//!
//! # Example Usage
//!
//! ```rust,no_run
//! use auth_framework::admin::AppState;
//! use auth_framework::config::AuthFrameworkSettings;
//!
//! # async fn example() -> Result<(), Box<dyn std::error::Error>> {
//! // Create shared administrative state
//! let app_state = AppState::new(AuthFrameworkSettings::default())?;
//!
//! // Start web interface (requires the `web-gui` feature)
//! auth_framework::admin::web::run_web_gui(app_state, "127.0.0.1", 8080, false, true).await?;
//! // A terminal UI is available via `admin::tui::run_tui(state, readonly)` (`tui` feature)
//! # Ok(())
//! # }
//! ```
//!
//! # Deployment Scenarios
//!
//! - **Development**: TUI for local development and testing
//! - **Production**: Web interface for remote administration
//! - **Automation**: CLI for scripted operations and CI/CD
//! - **Monitoring**: API integration with external monitoring systems
//!
//! # Integration
//!
//! Integrates with external systems:
//! - Prometheus metrics export
//! - Grafana dashboard templates
//! - SIEM system integration
//! - Log aggregation systems

use crate::{config::AuthFrameworkSettings, errors::Result};
use chrono;
use std::sync::Arc;
use tokio::sync::RwLock;

/// Shared application state
#[derive(Debug, Clone)]
pub struct AppState {
    pub config: Arc<RwLock<AuthFrameworkSettings>>,
    pub config_manager: crate::config::ConfigManager,
    pub health_status: HealthStatus,
    pub server_status: Arc<RwLock<ServerStatus>>,
}

/// Server status information
#[derive(Debug, Clone)]
pub struct ServerStatus {
    pub web_server_running: bool,
    pub web_server_port: Option<u16>,
    pub last_config_update: Option<chrono::DateTime<chrono::Utc>>,
    pub active_sessions: u32,
    pub health_status: HealthStatus,
}

/// System health status
#[derive(Debug, Clone)]
pub enum HealthStatus {
    Healthy,
    Warning(String),
    Critical(String),
}

/// Server information for TUI display
#[derive(Debug, Clone)]
pub struct ServerInfo {
    pub version: String,
    pub uptime: String,
    pub status: String,
    pub port: Option<u16>,
    pub active_sessions: u32,
}

/// User statistics for TUI display
#[derive(Debug, Clone)]
pub struct UserStatistics {
    pub total_users: u32,
    pub active_sessions: u32,
    pub failed_logins_today: u32,
    pub new_registrations_today: u32,
}

/// Security event for TUI display
#[derive(Debug, Clone)]
pub struct SecurityEvent {
    pub timestamp: chrono::DateTime<chrono::Utc>,
    pub event_type: String,
    pub description: String,
    pub ip_address: Option<String>,
    pub user_id: Option<String>,
}

impl AppState {
    pub fn new(settings: AuthFrameworkSettings) -> Result<Self> {
        let config = Arc::new(RwLock::new(settings));
        let config_manager = crate::config::ConfigManager::new()?;

        let server_status = ServerStatus {
            web_server_running: false,
            web_server_port: None,
            last_config_update: None,
            active_sessions: 0,
            health_status: HealthStatus::Healthy,
        };

        Ok(Self {
            config,
            config_manager,
            health_status: HealthStatus::Healthy,
            server_status: Arc::new(RwLock::new(server_status)),
        })
    }

    pub async fn get_health_status(&self) -> HealthStatus {
        // Simplified health check - in a real implementation this would
        // check database connections, external services, etc.
        HealthStatus::Healthy
    }

    pub async fn reload_config(&self) -> Result<()> {
        // Reload configuration logic here
        // For now, just update the timestamp
        let mut status = self.server_status.write().await;
        status.last_config_update = Some(chrono::Utc::now());
        Ok(())
    }

    pub async fn update_server_status(&self, running: bool, port: Option<u16>) {
        let mut status = self.server_status.write().await;
        status.web_server_running = running;
        status.web_server_port = port;
    }

    /// Get server information for display in TUI
    pub async fn get_server_info(&self) -> Result<ServerInfo> {
        let status = self.server_status.read().await;
        Ok(ServerInfo {
            version: env!("CARGO_PKG_VERSION").to_string(),
            uptime: "N/A".to_string(), // Would be calculated from start time
            status: if status.web_server_running {
                "Running"
            } else {
                "Stopped"
            }
            .to_string(),
            port: status.web_server_port,
            active_sessions: status.active_sessions,
        })
    }

    /// Get user statistics for display in TUI
    pub async fn get_user_statistics(&self) -> Result<UserStatistics> {
        // Mock data - in real implementation would query the database
        Ok(UserStatistics {
            total_users: 0,
            active_sessions: 0,
            failed_logins_today: 0,
            new_registrations_today: 0,
        })
    }

    /// Get recent security events for display in TUI
    pub async fn get_recent_security_events(&self) -> Result<Vec<SecurityEvent>> {
        // Mock data - in real implementation would query the audit log
        Ok(vec![])
    }
} // Command line interface types and functions
#[cfg(feature = "cli")]
pub mod cli;

#[cfg(feature = "tui")]
pub mod tui;

#[cfg(feature = "web-gui")]
pub mod web;

// CLI command types
#[derive(Debug, Clone, clap::Subcommand)]
pub enum CliCommand {
    /// Configuration management commands
    Config {
        #[command(subcommand)]
        action: ConfigAction,
    },
    /// User management commands
    Users {
        #[command(subcommand)]
        action: UserAction,
    },
    /// Server management commands
    Server {
        #[command(subcommand)]
        action: ServerAction,
    },
    /// Security management commands
    Security {
        #[command(subcommand)]
        action: SecurityAction,
    },
    /// Show system status
    Status {
        /// Show detailed information
        #[arg(long)]
        detailed: bool,
        /// Output format (json, yaml, table)
        #[arg(long, default_value = "table")]
        format: String,
    },
}

#[derive(Clone, clap::Subcommand)]
pub enum ConfigAction {
    /// Show configuration
    Show {
        /// Configuration section to show
        section: Option<String>,
        /// Output format (json, yaml, table)
        #[arg(long, default_value = "table")]
        format: String,
        /// Print secrets (keys, passwords, tokens, URL credentials) instead of `<redacted>`
        #[arg(long)]
        show_secrets: bool,
    },
    /// Set configuration value
    Set {
        /// Configuration key
        key: String,
        /// Configuration value
        value: String,
        /// Apply hot reload
        #[arg(long)]
        hot_reload: bool,
    },
    /// Reset configuration to defaults
    Reset,
    /// Validate configuration
    Validate {
        /// Configuration file to validate
        file: Option<String>,
    },
    /// Get configuration value
    Get {
        /// Configuration key
        key: String,
        /// Print a secret value instead of `<redacted>`
        #[arg(long)]
        show_secrets: bool,
    },
    /// Reload configuration
    Reload {
        /// Show configuration differences
        #[arg(long)]
        show_diff: bool,
    },
    /// Generate configuration template
    Template {
        /// Output file path
        output: Option<String>,
        /// Generate complete template with all options
        #[arg(long)]
        complete: bool,
    },
}

/// `config set <key> <value>` can carry a secret value on the command line, so `Debug` hides it.
impl std::fmt::Debug for ConfigAction {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        use crate::utils::redact::redacted;
        match self {
            Self::Show {
                section,
                format,
                show_secrets,
            } => f
                .debug_struct("Show")
                .field("section", section)
                .field("format", format)
                .field("show_secrets", show_secrets)
                .finish(),
            Self::Set {
                key,
                value,
                hot_reload,
            } => f
                .debug_struct("Set")
                .field("key", key)
                .field("value", &redacted(value))
                .field("hot_reload", hot_reload)
                .finish(),
            Self::Reset => f.write_str("Reset"),
            Self::Validate { file } => f.debug_struct("Validate").field("file", file).finish(),
            Self::Get { key, show_secrets } => f
                .debug_struct("Get")
                .field("key", key)
                .field("show_secrets", show_secrets)
                .finish(),
            Self::Reload { show_diff } => f
                .debug_struct("Reload")
                .field("show_diff", show_diff)
                .finish(),
            Self::Template { output, complete } => f
                .debug_struct("Template")
                .field("output", output)
                .field("complete", complete)
                .finish(),
        }
    }
}

#[derive(Clone, clap::Subcommand)]
pub enum UserAction {
    /// List users
    List {
        /// Maximum number of users to show
        limit: Option<u32>,
        /// Show only active users
        #[arg(long)]
        active: bool,
    },
    /// Create new user
    Create {
        /// User email address
        email: String,
        /// User password (will prompt if not provided)
        password: Option<String>,
        /// Grant admin privileges
        #[arg(long)]
        admin: bool,
    },
    /// Delete user
    Delete {
        /// User to delete (email or ID)
        user: String,
        /// Force deletion without confirmation
        #[arg(long)]
        force: bool,
    },
    /// Set user role
    SetRole {
        /// User email
        email: String,
        /// Role to assign
        role: String,
    },
    /// Update user properties
    Update {
        /// User to update (email or ID)
        user: String,
        /// New email address
        #[arg(long)]
        email: Option<String>,
        /// Set active status
        #[arg(long)]
        active: Option<bool>,
    },
}

/// `user create <email> <password>` can carry the password on the command line, so `Debug` hides it.
impl std::fmt::Debug for UserAction {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        use crate::utils::redact::redacted;
        match self {
            Self::List { limit, active } => f
                .debug_struct("List")
                .field("limit", limit)
                .field("active", active)
                .finish(),
            Self::Create {
                email,
                password,
                admin,
            } => f
                .debug_struct("Create")
                .field("email", email)
                .field("password", &redacted(password))
                .field("admin", admin)
                .finish(),
            Self::Delete { user, force } => f
                .debug_struct("Delete")
                .field("user", user)
                .field("force", force)
                .finish(),
            Self::SetRole { email, role } => f
                .debug_struct("SetRole")
                .field("email", email)
                .field("role", role)
                .finish(),
            Self::Update {
                user,
                email,
                active,
            } => f
                .debug_struct("Update")
                .field("user", user)
                .field("email", email)
                .field("active", active)
                .finish(),
        }
    }
}

#[derive(Debug, Clone, clap::Subcommand)]
pub enum ServerAction {
    /// Show server status
    Status,
    /// Start the server
    Start {
        /// Port to bind to
        port: Option<u16>,
        /// Run as daemon
        #[arg(long)]
        daemon: bool,
    },
    /// Stop the server
    Stop {
        /// Force stop without graceful shutdown
        #[arg(long)]
        force: bool,
    },
    /// Restart the server
    Restart {
        /// Port to bind to
        port: Option<u16>,
    },
}

#[derive(Debug, Clone, clap::Subcommand)]
pub enum SecurityAction {
    /// Show audit log
    AuditLog,
    /// Generate threat report
    ThreatReport,
    /// Force user logout
    ForceLogout {
        /// User ID to logout
        user_id: String,
    },
    /// Run security audit
    Audit {
        /// Number of days to audit
        #[arg(long, default_value = "7")]
        days: u32,
        /// Show detailed information
        #[arg(long)]
        detailed: bool,
    },
    /// Manage user sessions
    Sessions {
        /// Filter by specific user
        #[arg(long)]
        user: Option<String>,
        /// Terminate specific session
        #[arg(long)]
        terminate: Option<String>,
    },
    /// Threat intelligence operations
    ThreatIntel {
        /// Update threat intelligence database
        #[arg(long)]
        update: bool,
        /// Check specific IP address
        #[arg(long)]
        check_ip: Option<String>,
    },
}

/// What a masked value is replaced with.
const MASKED: &str = "<redacted>";

/// Whether a configuration key names a secret (over-matching only hides more).
fn is_secret_key(key: &str) -> bool {
    let key = key.to_ascii_lowercase();
    [
        "secret",
        "password",
        "passwd",
        "token",
        "key",
        "credential",
        "passphrase",
        "salt",
        "pepper",
    ]
    .iter()
    .any(|marker| key.contains(marker))
}

/// A URL with the user info (`user:password@`) and the values of secret-named query parameters
/// masked; text that is not a URL is returned as it is.
fn mask_url(text: &str) -> String {
    let Some((scheme, rest)) = text.split_once("://") else {
        return text.to_string();
    };
    let end = rest.find(['/', '?', '#']).unwrap_or(rest.len());
    let (authority, tail) = rest.split_at(end);
    let authority = match authority.rsplit_once('@') {
        Some((_, host)) => format!("{MASKED}@{host}"),
        None => authority.to_string(),
    };
    let tail = match tail.split_once('?') {
        Some((path, query)) => {
            let query: Vec<String> = query
                .split('&')
                .map(|pair| match pair.split_once('=') {
                    Some((name, _)) if is_secret_key(name) => format!("{name}={MASKED}"),
                    _ => pair.to_string(),
                })
                .collect();
            format!("{path}?{}", query.join("&"))
        }
        None => tail.to_string(),
    };
    format!("{scheme}://{authority}{tail}")
}

fn mask_value(value: &mut serde_json::Value, under_secret_key: bool) {
    match value {
        serde_json::Value::String(text) => {
            *text = if under_secret_key {
                MASKED.to_string()
            } else {
                mask_url(text)
            };
        }
        serde_json::Value::Array(items) => {
            for item in items {
                mask_value(item, under_secret_key);
            }
        }
        serde_json::Value::Object(map) => {
            for (key, item) in map.iter_mut() {
                mask_value(item, under_secret_key || is_secret_key(key));
            }
        }
        _ => {}
    }
}

/// The configuration as `config show` and `config get` print it: every string under a secret-named
/// key, and the credentials in any URL, are replaced with `<redacted>`. Numbers and booleans are
/// kept, so `token_lifetime` and `enable_token_rotation` still show. `--show-secrets` skips this.
pub(crate) fn masked_config<T: serde::Serialize>(
    config: &T,
) -> crate::errors::Result<serde_json::Value> {
    let mut value = serde_json::to_value(config).map_err(|e| {
        crate::errors::AuthError::internal(format!("Failed to serialize config: {e}"))
    })?;
    mask_value(&mut value, false);
    Ok(value)
}

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

    #[derive(clap::Parser)]
    struct ConfigCli {
        #[command(subcommand)]
        action: ConfigAction,
    }

    #[test]
    fn masked_config_hides_secrets_and_keeps_everything_else() {
        let masked = masked_config(&serde_json::json!({
            "jwt_secret": "SECRET-MARKER",
            "storage": { "Redis": { "url": "redis://:SECRET-MARKER@cache:6379/0", "key_prefix": "auth:" } },
            "api_keys": ["SECRET-MARKER", "SECRET-MARKER"],
            "database_url": "postgres://app:SECRET-MARKER@db:5432/auth?sslmode=require&password=SECRET-MARKER",
            "token_lifetime": 3600,
            "enable_token_rotation": true,
            "issuer": "https://issuer.example",
            "refresh_token": null
        }))
        .unwrap();
        let shown = masked.to_string();
        assert!(!shown.contains("SECRET-MARKER"), "{shown}");
        // Controls: what is not secret is still there, and a masked value says so.
        assert_eq!(masked["token_lifetime"], 3600);
        assert_eq!(masked["enable_token_rotation"], true);
        assert_eq!(masked["issuer"], "https://issuer.example");
        assert_eq!(masked["jwt_secret"], "<redacted>");
        assert_eq!(
            masked["database_url"],
            "postgres://<redacted>@db:5432/auth?sslmode=require&password=<redacted>"
        );
        assert!(masked["refresh_token"].is_null());
    }

    #[test]
    fn show_secrets_is_off_unless_asked_for_on_show_and_get() {
        use clap::Parser;
        for args in [["x", "show"], ["x", "get"]] {
            let args: Vec<&str> = if args[1] == "get" {
                vec!["x", "get", "jwt_secret"]
            } else {
                args.to_vec()
            };
            match ConfigCli::try_parse_from(&args).unwrap().action {
                ConfigAction::Show { show_secrets, .. }
                | ConfigAction::Get { show_secrets, .. } => {
                    assert!(!show_secrets, "{args:?}");
                }
                other => panic!("unexpected {other:?}"),
            }
            let mut asked = args.clone();
            asked.push("--show-secrets");
            match ConfigCli::try_parse_from(&asked).unwrap().action {
                ConfigAction::Show { show_secrets, .. }
                | ConfigAction::Get { show_secrets, .. } => {
                    assert!(show_secrets, "{asked:?}");
                }
                other => panic!("unexpected {other:?}"),
            }
        }
    }

    #[test]
    fn command_line_values_are_not_printed_by_debug() {
        const SECRET: &str = "SECRET-MARKER-7f3a9c";
        let shown = format!(
            "{:?}",
            ConfigAction::Set {
                key: "key-visible".into(),
                value: SECRET.into(),
                hot_reload: false
            }
        );
        assert!(
            !shown.contains(SECRET) && shown.contains("key-visible"),
            "{shown}"
        );
        let shown = format!(
            "{:?}",
            UserAction::Create {
                email: "mail-visible".into(),
                password: Some(SECRET.into()),
                admin: false
            }
        );
        assert!(
            !shown.contains(SECRET) && shown.contains("mail-visible"),
            "{shown}"
        );
        // Control: a variant with no secret still prints its payload.
        assert!(
            format!(
                "{:?}",
                ConfigAction::Get {
                    key: "k".into(),
                    show_secrets: false
                }
            )
            .contains("Get"),
        );
    }
}