use crate::{config::AuthFrameworkSettings, errors::Result};
use chrono;
use std::sync::Arc;
use tokio::sync::RwLock;
#[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>>,
}
#[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,
}
#[derive(Debug, Clone)]
pub enum HealthStatus {
Healthy,
Warning(String),
Critical(String),
}
#[derive(Debug, Clone)]
pub struct ServerInfo {
pub version: String,
pub uptime: String,
pub status: String,
pub port: Option<u16>,
pub active_sessions: u32,
}
#[derive(Debug, Clone)]
pub struct UserStatistics {
pub total_users: u32,
pub active_sessions: u32,
pub failed_logins_today: u32,
pub new_registrations_today: u32,
}
#[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 {
HealthStatus::Healthy
}
pub async fn reload_config(&self) -> Result<()> {
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;
}
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(), status: if status.web_server_running {
"Running"
} else {
"Stopped"
}
.to_string(),
port: status.web_server_port,
active_sessions: status.active_sessions,
})
}
pub async fn get_user_statistics(&self) -> Result<UserStatistics> {
Ok(UserStatistics {
total_users: 0,
active_sessions: 0,
failed_logins_today: 0,
new_registrations_today: 0,
})
}
pub async fn get_recent_security_events(&self) -> Result<Vec<SecurityEvent>> {
Ok(vec![])
}
} #[cfg(feature = "cli")]
pub mod cli;
#[cfg(feature = "tui")]
pub mod tui;
#[cfg(feature = "web-gui")]
pub mod web;
#[derive(Debug, Clone, clap::Subcommand)]
pub enum CliCommand {
Config {
#[command(subcommand)]
action: ConfigAction,
},
Users {
#[command(subcommand)]
action: UserAction,
},
Server {
#[command(subcommand)]
action: ServerAction,
},
Security {
#[command(subcommand)]
action: SecurityAction,
},
Status {
#[arg(long)]
detailed: bool,
#[arg(long, default_value = "table")]
format: String,
},
}
#[derive(Clone, clap::Subcommand)]
pub enum ConfigAction {
Show {
section: Option<String>,
#[arg(long, default_value = "table")]
format: String,
#[arg(long)]
show_secrets: bool,
},
Set {
key: String,
value: String,
#[arg(long)]
hot_reload: bool,
},
Reset,
Validate {
file: Option<String>,
},
Get {
key: String,
#[arg(long)]
show_secrets: bool,
},
Reload {
#[arg(long)]
show_diff: bool,
},
Template {
output: Option<String>,
#[arg(long)]
complete: bool,
},
}
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 {
limit: Option<u32>,
#[arg(long)]
active: bool,
},
Create {
email: String,
password: Option<String>,
#[arg(long)]
admin: bool,
},
Delete {
user: String,
#[arg(long)]
force: bool,
},
SetRole {
email: String,
role: String,
},
Update {
user: String,
#[arg(long)]
email: Option<String>,
#[arg(long)]
active: Option<bool>,
},
}
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 {
Status,
Start {
port: Option<u16>,
#[arg(long)]
daemon: bool,
},
Stop {
#[arg(long)]
force: bool,
},
Restart {
port: Option<u16>,
},
}
#[derive(Debug, Clone, clap::Subcommand)]
pub enum SecurityAction {
AuditLog,
ThreatReport,
ForceLogout {
user_id: String,
},
Audit {
#[arg(long, default_value = "7")]
days: u32,
#[arg(long)]
detailed: bool,
},
Sessions {
#[arg(long)]
user: Option<String>,
#[arg(long)]
terminate: Option<String>,
},
ThreatIntel {
#[arg(long)]
update: bool,
#[arg(long)]
check_ip: Option<String>,
},
}
const MASKED: &str = "<redacted>";
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))
}
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));
}
}
_ => {}
}
}
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}");
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}"
);
assert!(
format!(
"{:?}",
ConfigAction::Get {
key: "k".into(),
show_secrets: false
}
)
.contains("Get"),
);
}
}