allsource-core 0.19.1

High-performance event store core built in Rust
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
use crate::error::{AllSourceError, Result};
/// Configuration management for AllSource v1.0
///
/// Features:
/// - Environment-based configuration
/// - TOML file support
/// - Runtime configuration validation
/// - Hot-reloading support (via file watcher)
/// - Secure credential handling
use serde::{Deserialize, Serialize};
use std::{
    fs,
    path::{Component, Path, PathBuf},
};

/// Reject obviously-unsafe config paths before opening them.
fn validate_config_path(path: &Path) -> Result<()> {
    let os = path.as_os_str();
    if os.is_empty() {
        return Err(AllSourceError::ValidationError(
            "config path must not be empty".to_string(),
        ));
    }
    let bytes = os.as_encoded_bytes();
    if bytes.contains(&0) {
        return Err(AllSourceError::ValidationError(
            "config path contains a null byte".to_string(),
        ));
    }
    if path.components().any(|c| matches!(c, Component::ParentDir)) {
        return Err(AllSourceError::ValidationError(
            "config path must not contain '..' components".to_string(),
        ));
    }
    Ok(())
}

/// Main application configuration
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct Config {
    pub server: ServerConfig,
    pub storage: StorageConfig,
    pub auth: AuthConfig,
    pub rate_limit: RateLimitConfigFile,
    pub backup: BackupConfigFile,
    pub metrics: MetricsConfig,
    pub logging: LoggingConfig,
}

/// Server configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ServerConfig {
    pub host: String,
    pub port: u16,
    pub workers: Option<usize>,
    pub max_connections: usize,
    pub request_timeout_secs: u64,
    pub cors_enabled: bool,
    pub cors_origins: Vec<String>,
}

impl Default for ServerConfig {
    fn default() -> Self {
        Self {
            host: "0.0.0.0".to_string(),
            port: 3900,
            workers: None, // Use number of CPUs
            max_connections: 10_000,
            request_timeout_secs: 30,
            cors_enabled: true,
            cors_origins: vec!["*".to_string()],
        }
    }
}

impl ServerConfig {
    /// Create ServerConfig from environment variables.
    /// Reads ALLSOURCE_HOST (or HOST), ALLSOURCE_PORT (or PORT), falling back to defaults.
    pub fn from_env() -> Self {
        let mut config = Self::default();

        if let Ok(host) = std::env::var("ALLSOURCE_HOST").or_else(|_| std::env::var("HOST")) {
            config.host = host;
        }

        if let Ok(port) = std::env::var("ALLSOURCE_PORT").or_else(|_| std::env::var("PORT"))
            && let Ok(p) = port.parse::<u16>()
        {
            config.port = p;
        }

        config
    }
}

/// Storage configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct StorageConfig {
    pub data_dir: PathBuf,
    pub wal_dir: PathBuf,
    pub batch_size: usize,
    pub compression: CompressionType,
    pub retention_days: Option<u32>,
    pub max_storage_gb: Option<u32>,
}

impl Default for StorageConfig {
    fn default() -> Self {
        Self {
            data_dir: PathBuf::from("./data"),
            wal_dir: PathBuf::from("./wal"),
            batch_size: 1000,
            compression: CompressionType::Lz4,
            retention_days: None,
            max_storage_gb: None,
        }
    }
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "lowercase")]
pub enum CompressionType {
    None,
    Lz4,
    Gzip,
    Snappy,
}

/// Authentication configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AuthConfig {
    pub jwt_secret: String,
    pub jwt_expiry_hours: i64,
    pub api_key_expiry_days: Option<i64>,
    pub password_min_length: usize,
    pub require_email_verification: bool,
    pub session_timeout_minutes: u64,
}

impl Default for AuthConfig {
    fn default() -> Self {
        Self {
            jwt_secret: "CHANGE_ME_IN_PRODUCTION".to_string(),
            jwt_expiry_hours: 24,
            api_key_expiry_days: Some(90),
            password_min_length: 8,
            require_email_verification: false,
            session_timeout_minutes: 60,
        }
    }
}

/// Rate limiting configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RateLimitConfigFile {
    pub enabled: bool,
    pub default_tier: RateLimitTier,
    pub requests_per_minute: Option<u32>,
    pub burst_size: Option<u32>,
}

impl Default for RateLimitConfigFile {
    fn default() -> Self {
        Self {
            enabled: true,
            default_tier: RateLimitTier::Professional,
            requests_per_minute: None,
            burst_size: None,
        }
    }
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "lowercase")]
pub enum RateLimitTier {
    Free,
    Professional,
    Unlimited,
    Custom,
}

/// Backup configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct BackupConfigFile {
    pub enabled: bool,
    pub backup_dir: PathBuf,
    pub schedule_cron: Option<String>,
    pub retention_count: usize,
    pub compression_level: u8,
    pub verify_after_backup: bool,
}

impl Default for BackupConfigFile {
    fn default() -> Self {
        Self {
            enabled: false,
            backup_dir: PathBuf::from("./backups"),
            schedule_cron: None, // e.g., "0 2 * * *" for 2am daily
            retention_count: 7,
            compression_level: 6,
            verify_after_backup: true,
        }
    }
}

/// Metrics configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct MetricsConfig {
    pub enabled: bool,
    pub endpoint: String,
    pub push_interval_secs: Option<u64>,
    pub push_gateway_url: Option<String>,
}

impl Default for MetricsConfig {
    fn default() -> Self {
        Self {
            enabled: true,
            endpoint: "/metrics".to_string(),
            push_interval_secs: None,
            push_gateway_url: None,
        }
    }
}

/// Logging configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct LoggingConfig {
    pub level: LogLevel,
    pub format: LogFormat,
    pub output: LogOutput,
    pub file_path: Option<PathBuf>,
    pub rotate_size_mb: Option<u64>,
}

impl Default for LoggingConfig {
    fn default() -> Self {
        Self {
            level: LogLevel::Info,
            format: LogFormat::Pretty,
            output: LogOutput::Stdout,
            file_path: None,
            rotate_size_mb: Some(100),
        }
    }
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "lowercase")]
pub enum LogLevel {
    Trace,
    Debug,
    Info,
    Warn,
    Error,
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "lowercase")]
pub enum LogFormat {
    Json,
    Pretty,
    Compact,
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "lowercase")]
pub enum LogOutput {
    Stdout,
    Stderr,
    File,
    Both,
}

impl Config {
    /// Load configuration from file.
    ///
    /// The path is supplied by the operator (CLI flag or env var), not by an
    /// HTTP client. We still reject obviously malformed paths (embedded null
    /// bytes, parent-directory traversal components) so that a mis-configured
    /// deployment fails fast instead of silently reading an unintended file.
    pub fn from_file<P: AsRef<Path>>(path: P) -> Result<Self> {
        let path_ref = path.as_ref();
        validate_config_path(path_ref)?;
        let content = fs::read_to_string(path_ref).map_err(|e| {
            AllSourceError::StorageError(format!("Failed to read config file: {e}"))
        })?;

        toml::from_str(&content)
            .map_err(|e| AllSourceError::ValidationError(format!("Invalid config format: {e}")))
    }

    /// Load configuration from environment variables
    /// Variables are prefixed with ALLSOURCE_
    /// Also supports standard PORT env var for serverless platforms (Cloud Run, Fly.io, etc.)
    pub fn from_env() -> Result<Self> {
        let mut config = Config::default();

        // Server - check ALLSOURCE_HOST first, then HOST (serverless fallback)
        if let Ok(host) = std::env::var("ALLSOURCE_HOST").or_else(|_| std::env::var("HOST")) {
            config.server.host = host;
        }

        // Port priority: ALLSOURCE_PORT > PORT (serverless standard)
        let port_str = std::env::var("ALLSOURCE_PORT").or_else(|_| std::env::var("PORT"));
        if let Ok(port) = port_str {
            config.server.port = port
                .parse()
                .map_err(|_| AllSourceError::ValidationError("Invalid port number".to_string()))?;
        }

        // Storage
        if let Ok(data_dir) = std::env::var("ALLSOURCE_DATA_DIR") {
            config.storage.data_dir = PathBuf::from(data_dir);
        }

        // Auth
        if let Ok(jwt_secret) = std::env::var("ALLSOURCE_JWT_SECRET") {
            config.auth.jwt_secret = jwt_secret;
        }

        Ok(config)
    }

    /// Load configuration with fallback priority:
    /// 1. Config file (if provided)
    /// 2. Environment variables
    /// 3. Defaults
    pub fn load(config_path: Option<PathBuf>) -> Result<Self> {
        let mut config = if let Some(path) = config_path {
            if path.exists() {
                tracing::info!("Loading config from: {}", path.display());
                Self::from_file(path)?
            } else {
                tracing::warn!("Config file not found: {}, using defaults", path.display());
                Config::default()
            }
        } else {
            Config::default()
        };

        // Override with environment variables
        if let Ok(env_config) = Self::from_env() {
            config.merge_env(env_config);
        }

        config.validate()?;

        Ok(config)
    }

    /// Merge environment variable overrides
    fn merge_env(&mut self, env_config: Config) {
        // Merge server config
        if env_config.server.host != ServerConfig::default().host {
            self.server.host = env_config.server.host;
        }
        if env_config.server.port != ServerConfig::default().port {
            self.server.port = env_config.server.port;
        }

        // Merge storage config
        if env_config.storage.data_dir != StorageConfig::default().data_dir {
            self.storage.data_dir = env_config.storage.data_dir;
        }

        // Merge auth config
        if env_config.auth.jwt_secret != AuthConfig::default().jwt_secret {
            self.auth.jwt_secret = env_config.auth.jwt_secret;
        }
    }

    /// Validate configuration
    pub fn validate(&self) -> Result<()> {
        // Validate port
        if self.server.port == 0 {
            return Err(AllSourceError::ValidationError(
                "Server port cannot be 0".to_string(),
            ));
        }

        // Validate JWT secret in production
        if self.auth.jwt_secret == "CHANGE_ME_IN_PRODUCTION" {
            tracing::warn!("⚠️  Using default JWT secret - INSECURE for production!");
        }

        // Validate storage paths
        if self.storage.data_dir.as_os_str().is_empty() {
            return Err(AllSourceError::ValidationError(
                "Data directory path cannot be empty".to_string(),
            ));
        }

        Ok(())
    }

    /// Save configuration to TOML file
    pub fn save<P: AsRef<Path>>(&self, path: P) -> Result<()> {
        let toml = toml::to_string_pretty(self).map_err(|e| {
            AllSourceError::ValidationError(format!("Failed to serialize config: {e}"))
        })?;

        fs::write(path.as_ref(), toml).map_err(|e| {
            AllSourceError::StorageError(format!("Failed to write config file: {e}"))
        })?;

        Ok(())
    }

    /// Generate example configuration file
    pub fn example() -> String {
        toml::to_string_pretty(&Config::default())
            .unwrap_or_else(|_| String::from("# Failed to generate example config"))
    }
}

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

    #[test]
    fn test_default_config() {
        let config = Config::default();
        assert_eq!(config.server.port, 3900);
        assert!(config.rate_limit.enabled);
    }

    #[test]
    fn test_config_validation() {
        let config = Config::default();
        assert!(config.validate().is_ok());
    }

    #[test]
    fn test_invalid_port() {
        let mut config = Config::default();
        config.server.port = 0;
        assert!(config.validate().is_err());
    }

    #[test]
    fn test_validate_config_path_accepts_normal_paths() {
        assert!(validate_config_path(Path::new("config.toml")).is_ok());
        assert!(validate_config_path(Path::new("/etc/allsource/config.toml")).is_ok());
        assert!(validate_config_path(Path::new("./config/allsource.toml")).is_ok());
    }

    #[test]
    fn test_validate_config_path_rejects_traversal_and_nulls() {
        assert!(validate_config_path(Path::new("")).is_err());
        assert!(validate_config_path(Path::new("../secret.toml")).is_err());
        assert!(validate_config_path(Path::new("config/../../secret.toml")).is_err());
    }

    #[test]
    fn test_config_serialization() {
        let config = Config::default();
        let toml = toml::to_string(&config).unwrap();
        let deserialized: Config = toml::from_str(&toml).unwrap();
        assert_eq!(config.server.port, deserialized.server.port);
    }
}