fortress-cli 1.0.1

Command-line interface for Fortress secure database
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
use color_eyre::eyre::Result;
use console::style;
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::path::PathBuf;
use tokio::fs;
use tracing::info;
use crate::ConfigAction;

#[derive(Debug, Clone, Serialize, Deserialize)]
/// Complete configuration settings for Fortress
pub struct ConfigSettings {
    /// Server configuration
    pub server: ServerConfig,
    /// Database configuration
    pub database: DatabaseConfig,
    /// Security configuration
    pub security: SecurityConfig,
    /// Logging configuration
    pub logging: LoggingConfig,
    /// Custom configuration values
    #[serde(flatten)]
    pub custom: HashMap<String, serde_json::Value>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
/// Server configuration settings
pub struct ServerConfig {
    /// Server host address
    pub host: String,
    /// Server port number
    pub port: u16,
    /// Number of worker threads
    pub workers: usize,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
/// Database configuration settings
pub struct DatabaseConfig {
    /// Path to the database file or directory
    pub path: String,
    /// Maximum number of concurrent connections
    pub max_connections: usize,
    /// Connection timeout in seconds
    pub connection_timeout: u64,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
/// Security configuration settings
pub struct SecurityConfig {
    /// Encryption algorithm to use (e.g., "aegis256", "aes256")
    pub encryption_algorithm: String,
    /// Key rotation interval in seconds
    pub key_rotation_interval: u64,
    /// Whether audit logging is enabled
    pub audit_enabled: bool,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
/// Logging configuration settings
pub struct LoggingConfig {
    /// Log level (e.g., "info", "debug", "warn")
    pub level: String,
    /// Optional path to log file
    pub file_path: Option<String>,
    /// Maximum log file size in bytes
    pub max_file_size: u64,
}

impl Default for ConfigSettings {
    fn default() -> Self {
        Self {
            server: ServerConfig {
                host: "127.0.0.1".to_string(),
                port: 8080,
                workers: num_cpus::get(),
            },
            database: DatabaseConfig {
                path: "./fortress".to_string(),
                max_connections: 100,
                connection_timeout: 30,
            },
            security: SecurityConfig {
                encryption_algorithm: "aegis256".to_string(),
                key_rotation_interval: 86400 * 7, // 7 days
                audit_enabled: true,
            },
            logging: LoggingConfig {
                level: "info".to_string(),
                file_path: None,
                max_file_size: 10 * 1024 * 1024, // 10MB
            },
            custom: HashMap::new(),
        }
    }
}

/// Handle configuration actions
/// 
/// # Arguments
/// * `action` - The configuration action to perform
///
/// # Returns
/// * `Result<()>` - Ok if successful, Err otherwise
pub async fn handle_config_action(action: ConfigAction) -> Result<()> {
    match action {
        ConfigAction::Show => {
            handle_config_show().await
        }
        ConfigAction::Set { key, value } => {
            handle_config_set(key, value).await
        }
        ConfigAction::Reset => {
            handle_config_reset().await
        }
        ConfigAction::Validate => {
            handle_config_validate().await
        }
    }
}

async fn handle_config_show() -> Result<()> {
    println!("{}", style("Current Configuration").bold().cyan());
    println!();
    
    let config_path = get_config_path()?;
    
    if !config_path.exists() {
        println!("{} No configuration file found. Using defaults.", style("").yellow());
        println!();
        print_default_config();
        return Ok(());
    }
    
    let config_content = fs::read_to_string(&config_path).await
        .map_err(|e| color_eyre::eyre::eyre!("Failed to read config file: {}", e))?;
    
    let config: ConfigSettings = toml::from_str(&config_content)
        .map_err(|e| color_eyre::eyre::eyre!("Failed to parse config file: {}", e))?;
    
    print_config(&config);
    println!("Configuration file: {}", style(config_path.display()).bold());
    
    Ok(())
}

async fn handle_config_set(key: String, value: String) -> Result<()> {
    println!("{}", style("Configuration Management").bold().cyan());
    println!();
    println!("{} = {}", style(key.clone()).bold(), style(value.clone()).bold());
    
    let config_path = get_config_path()?;
    let mut config = load_or_create_config(&config_path).await?;
    
    // Parse and set the configuration value
    set_config_value(&mut config, &key, &value)?;
    
    // Save the updated configuration
    save_config(&config_path, &config).await?;
    
    println!("✓ Configuration updated successfully");
    info!("Configuration updated: {} = {}", key, value);
    
    Ok(())
}

async fn handle_config_reset() -> Result<()> {
    println!("{}", style("Configuration Reset").bold().cyan());
    println!();
    
    let config_path = get_config_path()?;
    
    if !config_path.exists() {
        println!("{} No configuration file exists. Nothing to reset.", style("").blue());
        return Ok(());
    }
    
    // Create backup before reset
    let backup_path = config_path.with_extension("toml.bak");
    fs::copy(&config_path, &backup_path).await
        .map_err(|e| color_eyre::eyre::eyre!("Failed to create backup: {}", e))?;
    
    println!("Configuration backed up to: {}", style(backup_path.display()).bold());
    
    // Reset to defaults
    let default_config = ConfigSettings::default();
    save_config(&config_path, &default_config).await?;
    
    println!("✓ Configuration reset to defaults successfully");
    info!("Configuration reset to defaults");
    
    Ok(())
}

async fn handle_config_validate() -> Result<()> {
    println!("{}", style("Configuration Validation").bold().cyan());
    println!();
    
    let config_path = get_config_path()?;
    
    if !config_path.exists() {
        println!("{} No configuration file found. Using defaults.", style("").yellow());
        let default_config = ConfigSettings::default();
        validate_config(&default_config)?;
        return Ok(());
    }
    
    let config_content = fs::read_to_string(&config_path).await
        .map_err(|e| color_eyre::eyre::eyre!("Failed to read config file: {}", e))?;
    
    let config: ConfigSettings = toml::from_str(&config_content)
        .map_err(|e| color_eyre::eyre::eyre!("Failed to parse config file: {}", e))?;
    
    validate_config(&config)?;
    
    println!("✓ Configuration is valid");
    println!("Configuration file: {}", style(config_path.display()).bold());
    
    Ok(())
}

/// Get the path to the Fortress configuration file
/// 
/// # Returns
/// * `Result<PathBuf>` - Path to the fortress.toml configuration file
pub fn get_config_path() -> Result<PathBuf> {
    let home_dir = dirs::home_dir().ok_or_else(|| color_eyre::eyre::eyre!("Could not find home directory"))?;
    let fortress_dir = home_dir.join(".fortress");
    Ok(fortress_dir.join("config").join("fortress.toml"))
}

/// Load existing configuration or create default configuration
/// 
/// # Arguments
/// * `config_path` - Path to the configuration file
///
/// # Returns
/// * `Result<ConfigSettings>` - Loaded or created configuration
pub async fn load_or_create_config(config_path: &PathBuf) -> Result<ConfigSettings> {
    if config_path.exists() {
        let config_content = fs::read_to_string(config_path).await
            .map_err(|e| color_eyre::eyre::eyre!("Failed to read config file: {}", e))?;
        
        toml::from_str(&config_content)
            .map_err(|e| color_eyre::eyre::eyre!("Failed to parse config file: {}", e))
    } else {
        // Create parent directories if they don't exist
        if let Some(parent) = config_path.parent() {
            fs::create_dir_all(parent).await
                .map_err(|e| color_eyre::eyre::eyre!("Failed to create config directory: {}", e))?;
        }
        
        Ok(ConfigSettings::default())
    }
}

async fn save_config(config_path: &PathBuf, config: &ConfigSettings) -> Result<()> {
    let config_content = toml::to_string_pretty(config)
        .map_err(|e| color_eyre::eyre::eyre!("Failed to serialize config: {}", e))?;
    
    fs::write(config_path, config_content).await
        .map_err(|e| color_eyre::eyre::eyre!("Failed to write config file: {}", e))?;
    
    Ok(())
}

fn set_config_value(config: &mut ConfigSettings, key: &str, value: &str) -> Result<()> {
    let parts: Vec<&str> = key.split('.').collect();
    
    match parts.as_slice() {
        ["server", "host"] => {
            config.server.host = value.to_string();
        }
        ["server", "port"] => {
            config.server.port = value.parse()
                .map_err(|_| color_eyre::eyre::eyre!("Invalid port number: {}", value))?;
        }
        ["server", "workers"] => {
            config.server.workers = value.parse()
                .map_err(|_| color_eyre::eyre::eyre!("Invalid worker count: {}", value))?;
        }
        ["database", "path"] => {
            config.database.path = value.to_string();
        }
        ["database", "max_connections"] => {
            config.database.max_connections = value.parse()
                .map_err(|_| color_eyre::eyre::eyre!("Invalid max connections: {}", value))?;
        }
        ["database", "connection_timeout"] => {
            config.database.connection_timeout = value.parse()
                .map_err(|_| color_eyre::eyre::eyre!("Invalid connection timeout: {}", value))?;
        }
        ["security", "encryption_algorithm"] => {
            config.security.encryption_algorithm = value.to_string();
        }
        ["security", "key_rotation_interval"] => {
            config.security.key_rotation_interval = value.parse()
                .map_err(|_| color_eyre::eyre::eyre!("Invalid key rotation interval: {}", value))?;
        }
        ["security", "audit_enabled"] => {
            config.security.audit_enabled = value.parse()
                .map_err(|_| color_eyre::eyre::eyre!("Invalid audit enabled value: {}", value))?;
        }
        ["logging", "level"] => {
            config.logging.level = value.to_string();
        }
        ["logging", "file_path"] => {
            config.logging.file_path = if value.is_empty() { None } else { Some(value.to_string()) };
        }
        ["logging", "max_file_size"] => {
            config.logging.max_file_size = value.parse()
                .map_err(|_| color_eyre::eyre::eyre!("Invalid max file size: {}", value))?;
        }
        _ => {
            // Handle custom configuration values
            let json_value = parse_value_to_json(value)?;
            config.custom.insert(key.to_string(), json_value);
        }
    }
    
    Ok(())
}

fn parse_value_to_json(value: &str) -> Result<serde_json::Value> {
    // Try to parse as JSON first
    if let Ok(json_val) = serde_json::from_str(value) {
        return Ok(json_val);
    }
    
    // Try to parse as boolean
    if let Ok(bool_val) = value.parse::<bool>() {
        return Ok(serde_json::Value::Bool(bool_val));
    }
    
    // Try to parse as number
    if let Ok(int_val) = value.parse::<i64>() {
        return Ok(serde_json::Value::Number(serde_json::Number::from(int_val)));
    }
    
    if let Ok(float_val) = value.parse::<f64>() {
        return Ok(serde_json::Value::Number(serde_json::Number::from_f64(float_val)
            .ok_or_else(|| color_eyre::eyre::eyre!("Invalid float value: {}", value))?));
    }
    
    // Default to string
    Ok(serde_json::Value::String(value.to_string()))
}

fn validate_config(config: &ConfigSettings) -> Result<()> {
    let mut errors = Vec::new();
    
    // Validate server configuration
    if config.server.host.is_empty() {
        errors.push("Server host cannot be empty");
    }
    
    if config.server.port == 0 {
        errors.push("Server port must be between 1 and 65535");
    }
    
    if config.server.workers == 0 || config.server.workers > 1024 {
        errors.push("Worker count must be between 1 and 1024");
    }
    
    // Validate database configuration
    if config.database.path.is_empty() {
        errors.push("Database path cannot be empty");
    }
    
    if config.database.max_connections == 0 || config.database.max_connections > 10000 {
        errors.push("Max connections must be between 1 and 10000");
    }
    
    if config.database.connection_timeout == 0 || config.database.connection_timeout > 3600 {
        errors.push("Connection timeout must be between 1 and 3600 seconds");
    }
    
    // Validate security configuration
    if !["aegis256", "aes256gcm", "chacha20poly1305"].contains(&config.security.encryption_algorithm.as_str()) {
        errors.push("Encryption algorithm must be one of: aegis256, aes256gcm, chacha20poly1305");
    }
    
    if config.security.key_rotation_interval < 3600 {
        errors.push("Key rotation interval must be at least 1 hour");
    }
    
    // Validate logging configuration
    if !["trace", "debug", "info", "warn", "error"].contains(&config.logging.level.as_str()) {
        errors.push("Logging level must be one of: trace, debug, info, warn, error");
    }
    
    if config.logging.max_file_size < 1024 * 1024 {
        errors.push("Max file size must be at least 1MB");
    }
    
    if !errors.is_empty() {
        println!("{} Configuration validation failed:", style("").red());
        for error in errors {
            println!("  - {}", style(error).red());
        }
        return Err(color_eyre::eyre::eyre!("Configuration validation failed"));
    }
    
    Ok(())
}

fn print_config(config: &ConfigSettings) {
    println!("Server Configuration:");
    println!("  Host: {}", style(&config.server.host).bold());
    println!("  Port: {}", style(config.server.port).bold());
    println!("  Workers: {}", style(config.server.workers).bold());
    println!();
    
    println!("Database Configuration:");
    println!("  Path: {}", style(&config.database.path).bold());
    println!("  Max Connections: {}", style(config.database.max_connections).bold());
    println!("  Connection Timeout: {}s", style(config.database.connection_timeout).bold());
    println!();
    
    println!("Security Configuration:");
    println!("  Encryption Algorithm: {}", style(&config.security.encryption_algorithm).bold());
    println!("  Key Rotation Interval: {}h", style(config.security.key_rotation_interval / 3600).bold());
    println!("  Audit Enabled: {}", style(config.security.audit_enabled).bold());
    println!();
    
    println!("Logging Configuration:");
    println!("  Level: {}", style(&config.logging.level).bold());
    if let Some(ref file_path) = config.logging.file_path {
        println!("  File Path: {}", style(file_path).bold());
    } else {
        println!("  File Path: {}", style("stdout").dim());
    }
    println!("  Max File Size: {}MB", style(config.logging.max_file_size / 1024 / 1024).bold());
    println!();
    
    if !config.custom.is_empty() {
        println!("Custom Configuration:");
        for (key, value) in &config.custom {
            println!("  {}: {}", style(key).bold(), value);
        }
        println!();
    }
}

fn print_default_config() {
    let default_config = ConfigSettings::default();
    print_config(&default_config);
}