auth-framework 0.6.0-rc166

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
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
//! 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**: Configuration inspection and disk-backed reloads
//! - **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
//!
//! - **Configuration Inspection**: Review current effective settings
//! - **Disk-Backed Reloads**: Reload configuration from the configured sources
//! - **Validation**: Real-time configuration validation
//! - **Backup/Restore**: Configuration versioning and rollback
//! - **Environment Management**: Dev, staging, production configs
//!
//! # Example Usage
//!
//! ```rust,ignore
//! use auth_framework::admin::{AdminInterface, AppState};
//!
//! // Create administrative interface
//! let app_state = AppState::new(config_manager).await?;
//! let admin = AdminInterface::new(app_state);
//!
//! // Start web interface
//! admin.start_web_interface("127.0.0.1:8080").await?;
//!
//! // Start TUI interface
//! admin.start_tui_interface().await?;
//! ```
//!
//! # 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;

/// Server-side admin GUI session metadata.
///
/// Tracks an authenticated admin session with CSRF protection.
/// Sessions expire after `expires_at` is passed.
///
/// # Example
/// ```rust,ignore
/// let session = AdminSessionRecord {
///     username: "admin".into(),
///     created_at: chrono::Utc::now(),
///     expires_at: chrono::Utc::now() + chrono::Duration::hours(1),
///     last_activity: chrono::Utc::now(),
///     csrf_token: "random-token".into(),
/// };
/// ```
#[derive(Clone)]
pub struct AdminSessionRecord {
    pub username: String,
    pub created_at: chrono::DateTime<chrono::Utc>,
    pub expires_at: chrono::DateTime<chrono::Utc>,
    pub last_activity: chrono::DateTime<chrono::Utc>,
    /// Per-session CSRF token (Synchronizer Token Pattern).
    pub csrf_token: String,
}

impl std::fmt::Debug for AdminSessionRecord {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let mut d = f.debug_struct("AdminSessionRecord");
        d.field("username", &self.username);
        d.field("created_at", &self.created_at);
        d.field("expires_at", &self.expires_at);
        d.field("last_activity", &self.last_activity);
        d.field(
            "csrf_token",
            &crate::utils::redact::redacted(&self.csrf_token),
        );
        d.finish()
    }
}

/// In-memory login throttling state for the admin GUI.
///
/// Tracks failed login attempts to mitigate brute force attacks
/// on the administrative interface.
#[derive(Debug, Clone)]
pub struct AdminLoginAttemptRecord {
    pub failed_attempts: u32,
    pub first_failed_at: chrono::DateTime<chrono::Utc>,
    pub last_failed_at: chrono::DateTime<chrono::Utc>,
    pub locked_until: Option<chrono::DateTime<chrono::Utc>>,
}

/// Shared application state.
///
/// # Example
/// ```rust,ignore
/// let state = AppState::new(settings)?;
/// ```
#[derive(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>>,
    /// Active admin GUI sessions keyed by random session token.
    ///
    /// Using a `Mutex`-guarded map so the same `AppState` clone shared across
    /// all Axum handlers can atomically validate, renew, and revoke sessions
    /// without requiring an async lock at the middleware site.
    pub admin_sessions:
        Arc<std::sync::Mutex<std::collections::HashMap<String, AdminSessionRecord>>>,
    /// Failed admin GUI login attempts keyed by username.
    pub admin_login_attempts:
        Arc<std::sync::Mutex<std::collections::HashMap<String, AdminLoginAttemptRecord>>>,
    /// Optional reference to the running AuthFramework instance.
    /// When present, web/API handlers can query live storage data (users, events, etc.).
    pub auth_framework: Option<Arc<crate::AuthFramework>>,
}

impl std::fmt::Debug for AppState {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("AppState")
            .field("health_status", &self.health_status)
            .field("auth_framework_present", &self.auth_framework.is_some())
            .finish_non_exhaustive()
    }
}

/// Current running state of the server
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ServerRunState {
    /// Server is actively running and accepting connections
    Running,
    /// Server is stopped
    Stopped,
    /// Server is paused
    Paused,
}

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

pub(crate) fn format_uptime_since(
    started_at: chrono::DateTime<chrono::Utc>,
    now: chrono::DateTime<chrono::Utc>,
) -> String {
    let elapsed = now.signed_duration_since(started_at);
    if elapsed < chrono::Duration::zero() {
        return "0m".to_string();
    }

    let seconds = elapsed.num_seconds() as u64;
    let days = seconds / 86_400;
    let hours = (seconds % 86_400) / 3_600;
    let minutes = (seconds % 3_600) / 60;

    if days > 0 {
        format!("{days}d {hours}h {minutes}m")
    } else if hours > 0 {
        format!("{hours}h {minutes}m")
    } else {
        format!("{minutes}m")
    }
}
/// 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_state: ServerRunState::Stopped,
            web_server_port: None,
            last_config_update: None,
            active_sessions: 0,
            health_status: HealthStatus::Healthy,
            started_at: chrono::Utc::now(),
        };

        Ok(Self {
            config,
            config_manager,
            health_status: HealthStatus::Healthy,
            server_status: Arc::new(RwLock::new(server_status)),
            admin_sessions: Arc::new(std::sync::Mutex::new(std::collections::HashMap::new())),
            admin_login_attempts: Arc::new(std::sync::Mutex::new(std::collections::HashMap::new())),
            auth_framework: None,
        })
    }

    /// Attach a running [`crate::AuthFramework`] instance so that admin GUI
    /// handlers can query live storage data (users, audit events, etc.).
    ///
    /// # Example
    /// ```rust,ignore
    /// let state = state.with_auth_framework(fw.clone());
    /// ```
    pub fn with_auth_framework(mut self, af: Arc<crate::AuthFramework>) -> Self {
        self.auth_framework = Some(af);
        self
    }

    pub async fn get_health_status(&self) -> HealthStatus {
        // Check storage connectivity if auth_framework is available
        if let Some(ref af) = self.auth_framework {
            let storage = af.storage();
            // Attempt a lightweight storage operation to verify connectivity
            match storage.get_kv("health_check_ping").await {
                Ok(_) => {
                    let status = self.server_status.read().await;
                    match status.web_server_state {
                        ServerRunState::Running => HealthStatus::Healthy,
                        _ => HealthStatus::Warning("Web server not running".to_string()),
                    }
                }
                Err(e) => HealthStatus::Critical(format!("Storage unavailable: {}", e)),
            }
        } else {
            HealthStatus::Warning("AuthFramework not attached".to_string())
        }
    }

    pub async fn reload_config(&self) -> Result<()> {
        // Re-read configuration from sources
        let new_settings = self.config_manager.get_auth_settings()?;
        {
            let mut config = self.config.write().await;
            *config = new_settings;
        }
        let mut status = self.server_status.write().await;
        status.last_config_update = Some(chrono::Utc::now());
        Ok(())
    }

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

    /// Get server information for display in TUI.
    ///
    /// # Example
    /// ```rust,ignore
    /// let info = state.get_server_info().await?;
    /// println!("version: {}", info.version);
    /// ```
    pub async fn get_server_info(&self) -> Result<ServerInfo> {
        let status = self.server_status.read().await;
        let uptime = format_uptime_since(status.started_at, chrono::Utc::now());
        Ok(ServerInfo {
            version: env!("CARGO_PKG_VERSION").to_string(),
            uptime,
            status: match status.web_server_state {
                ServerRunState::Running => "Running",
                ServerRunState::Stopped => "Stopped",
                ServerRunState::Paused => "Paused",
            }
            .to_string(),
            port: status.web_server_port,
            active_sessions: status.active_sessions,
        })
    }

    /// Get user statistics for display in TUI.
    ///
    /// # Example
    /// ```rust,ignore
    /// let stats = state.get_user_statistics().await?;
    /// println!("total users: {}", stats.total_users);
    /// ```
    pub async fn get_user_statistics(&self) -> Result<UserStatistics> {
        if let Some(ref af) = self.auth_framework {
            let storage = af.storage();

            // Count total users from the users:index list.
            let total_users = match storage.get_kv("users:index").await {
                Ok(Some(bytes)) => serde_json::from_slice::<Vec<String>>(&bytes)
                    .map(|v| v.len() as u32)
                    .unwrap_or(0),
                _ => 0,
            };

            let status = self.server_status.read().await;
            let (failed_logins, new_regs) = match af.get_security_audit_stats().await {
                Ok(stats) => (
                    stats.failed_logins_24h as u32,
                    stats.password_resets_24h as u32,
                ),
                Err(_) => (0, 0),
            };
            Ok(UserStatistics {
                total_users,
                active_sessions: status.active_sessions,
                failed_logins_today: failed_logins,
                new_registrations_today: new_regs,
            })
        } else {
            let status = self.server_status.read().await;
            Ok(UserStatistics {
                total_users: 0,
                active_sessions: status.active_sessions,
                failed_logins_today: 0,
                new_registrations_today: 0,
            })
        }
    }

    /// Get recent security events for display in TUI.
    ///
    /// # Example
    /// ```rust,ignore
    /// let events = state.get_recent_security_events().await?;
    /// ```
    pub async fn get_recent_security_events(&self) -> Result<Vec<SecurityEvent>> {
        if let Some(ref af) = self.auth_framework {
            let logs = af
                .get_permission_audit_logs(None, None, None, Some(20))
                .await?;
            let events = logs
                .into_iter()
                .map(|log_line| {
                    // Log format: "[timestamp] EventType user=uid outcome=Outcome - description"
                    let (ts, rest) = log_line
                        .strip_prefix('[')
                        .and_then(|s| s.split_once("] "))
                        .unwrap_or(("", &log_line));
                    let event_type = rest.split_whitespace().next().unwrap_or("Unknown");
                    let user_id = rest
                        .split("user=")
                        .nth(1)
                        .and_then(|s| s.split_whitespace().next())
                        .map(|s| s.to_string());
                    let timestamp = chrono::DateTime::parse_from_rfc3339(ts)
                        .map(|dt| dt.with_timezone(&chrono::Utc))
                        .unwrap_or_else(|_| chrono::Utc::now());
                    SecurityEvent {
                        timestamp,
                        event_type: event_type.to_string(),
                        description: rest.to_string(),
                        ip_address: None,
                        user_id,
                    }
                })
                .collect();
            Ok(events)
        } else {
            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,
    },
    /// Maintenance operations for backup, restore, reset, and migration generation
    Maintenance {
        #[command(subcommand)]
        action: MaintenanceAction,
    },
    /// Show system status
    Status {
        /// Show detailed information
        #[arg(long)]
        detailed: bool,
        /// Output format (json, yaml, table)
        #[arg(long, default_value = "table")]
        format: String,
    },
}

#[derive(Debug, Clone, clap::Subcommand)]
pub enum MaintenanceAction {
    /// Export a logical maintenance snapshot to disk
    Backup {
        /// Output snapshot path
        output_path: String,
        /// Preview the operation without writing the snapshot
        #[arg(long)]
        dry_run: bool,
    },
    /// Restore a logical maintenance snapshot from disk
    Restore {
        /// Input snapshot path
        backup_path: String,
        /// Confirm destructive overwrite
        #[arg(long)]
        confirm: bool,
        /// Preview the restore without mutating storage
        #[arg(long)]
        dry_run: bool,
    },
    /// Reset logical auth data in the configured backend
    Reset {
        /// Confirm destructive deletion
        #[arg(long)]
        confirm: bool,
        /// Preview the reset without deleting data
        #[arg(long)]
        dry_run: bool,
    },
    /// Create a backend-specific migration template
    CreateMigration {
        /// Human-readable migration name
        name: 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>,
    },
    /// Encrypt any plaintext KV-layer values at rest (for data written
    /// before encryption was enabled). Safe to re-run: already-encrypted
    /// values are left untouched. A value that fails to decrypt is
    /// skipped (identified in the output by a safe identifier, never
    /// its raw key) rather than aborting the rest of the run, but the
    /// command as a whole then exits with a non-zero status so a
    /// failure is never silently missed.
    ///
    /// Each migrated value keeps its remaining TTL on storage backends
    /// that report TTLs (all built-in ones). On a backend that cannot,
    /// a real run is refused unless `--accept-ttl-loss` is given, because
    /// it would make every expiring entry (OAuth codes, MFA/SMS codes,
    /// rate-limit windows, expiring API keys) permanent; scope `--prefix`
    /// to a durable-secret namespace then. An empty prefix touches
    /// everything and requires `--confirm`.
    ///
    /// A value in the original (pre-redesign) format-version-0 shape has
    /// no AAD, so decrypting it cannot verify that its plaintext actually
    /// belongs to the record it's filed under -- upgrading one is never
    /// a silent side effect of running this command; pass
    /// `--accept-legacy-v0` to actually upgrade any found, after
    /// understanding that risk.
    EncryptKv {
        /// Only operate on keys starting with this prefix (default: all keys).
        #[arg(long, default_value = "")]
        prefix: String,
        /// Preview what would change without writing anything.
        #[arg(long)]
        dry_run: bool,
        /// Required when --prefix is empty and this is NOT a dry run.
        /// Not needed for --dry-run, which makes no changes.
        #[arg(long)]
        confirm: bool,
        /// Proceed on a storage backend that cannot report KV TTLs even
        /// though that makes every migrated expiring entry permanent.
        #[arg(long)]
        accept_ttl_loss: bool,
        /// Required to actually rewrite a legacy (format-version-0 or -1)
        /// envelope to the current format. Without it, such envelopes are detected
        /// and reported but left untouched. See the WARNING above about
        /// what this upgrade can and cannot verify.
        #[arg(long)]
        accept_legacy_v0: bool,
    },
}

/// 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 test_server_status_default_fields() {
        let status = ServerStatus {
            web_server_state: ServerRunState::Stopped,
            web_server_port: None,
            last_config_update: None,
            active_sessions: 0,
            health_status: HealthStatus::Healthy,
            started_at: chrono::Utc::now(),
        };
        assert_eq!(status.web_server_state, ServerRunState::Stopped);
        assert_eq!(status.active_sessions, 0);
        assert!(status.web_server_port.is_none());
    }

    #[test]
    fn test_health_status_variants() {
        let h = HealthStatus::Healthy;
        assert!(matches!(h, HealthStatus::Healthy));

        let w = HealthStatus::Warning("low memory".to_string());
        assert!(matches!(w, HealthStatus::Warning(_)));

        let c = HealthStatus::Critical("storage down".to_string());
        assert!(matches!(c, HealthStatus::Critical(_)));
    }

    #[test]
    fn test_server_info_creation() {
        let info = ServerInfo {
            version: "0.5.0".to_string(),
            uptime: "1h 30m".to_string(),
            status: "running".to_string(),
            port: Some(8080),
            active_sessions: 5,
        };
        assert_eq!(info.version, "0.5.0");
        assert_eq!(info.active_sessions, 5);
        assert_eq!(info.port, Some(8080));
    }

    #[test]
    fn test_user_statistics_creation() {
        let stats = UserStatistics {
            total_users: 100,
            active_sessions: 20,
            failed_logins_today: 3,
            new_registrations_today: 5,
        };
        assert_eq!(stats.total_users, 100);
        assert_eq!(stats.failed_logins_today, 3);
    }

    #[test]
    fn test_security_event_creation() {
        let event = SecurityEvent {
            timestamp: chrono::Utc::now(),
            event_type: "LoginFailure".to_string(),
            description: "Failed login attempt".to_string(),
            ip_address: Some("192.168.1.1".to_string()),
            user_id: Some("user123".to_string()),
        };
        assert_eq!(event.event_type, "LoginFailure");
        assert!(event.ip_address.is_some());
        assert!(event.user_id.is_some());
    }

    #[test]
    fn test_format_uptime_since() {
        let started_at = chrono::DateTime::parse_from_rfc3339("2026-03-21T10:00:00Z")
            .unwrap()
            .with_timezone(&chrono::Utc);
        let now = chrono::DateTime::parse_from_rfc3339("2026-03-21T12:45:00Z")
            .unwrap()
            .with_timezone(&chrono::Utc);

        assert_eq!(format_uptime_since(started_at, now), "2h 45m");
    }

    #[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"),
        );
    }
}