lonkero 3.7.0

Web scanner built for actual pentests. Fast, modular, 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
// Copyright (c) 2026 Bountyy Oy. All rights reserved.
// This software is proprietary and confidential.

use anyhow::{Context, Result};
use notify::{Event, RecommendedWatcher, RecursiveMode, Watcher};
use parking_lot::RwLock;
use serde::de::DeserializeOwned;
use std::path::{Path, PathBuf};
use std::sync::Arc;
use std::time::Duration;
use tokio::sync::broadcast;

use super::core::{AppConfig, Environment};
use super::profiles::{ProfileRegistry, ScanProfile};
use super::targets::TargetConfig;
use super::validation::ConfigValidator;

pub struct ConfigLoader {
    config_path: PathBuf,
    format: ConfigFormat,
    environment: Environment,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ConfigFormat {
    Yaml,
    Toml,
    Json,
}

impl ConfigLoader {
    pub fn new<P: AsRef<Path>>(config_path: P) -> Result<Self> {
        let path = config_path.as_ref().to_path_buf();

        let format = Self::detect_format(&path)?;

        let environment = std::env::var("ENVIRONMENT")
            .unwrap_or_else(|_| "development".to_string())
            .parse()
            .unwrap_or(Environment::Development);

        Ok(Self {
            config_path: path,
            format,
            environment,
        })
    }

    pub fn with_format<P: AsRef<Path>>(config_path: P, format: ConfigFormat) -> Result<Self> {
        let path = config_path.as_ref().to_path_buf();

        let environment = std::env::var("ENVIRONMENT")
            .unwrap_or_else(|_| "development".to_string())
            .parse()
            .unwrap_or(Environment::Development);

        Ok(Self {
            config_path: path,
            format,
            environment,
        })
    }

    fn detect_format(path: &Path) -> Result<ConfigFormat> {
        let extension = path
            .extension()
            .and_then(|e| e.to_str())
            .ok_or_else(|| anyhow::anyhow!("Could not determine config file format"))?;

        match extension {
            "yaml" | "yml" => Ok(ConfigFormat::Yaml),
            "toml" => Ok(ConfigFormat::Toml),
            "json" => Ok(ConfigFormat::Json),
            _ => Err(anyhow::anyhow!(
                "Unsupported config file format: {}",
                extension
            )),
        }
    }

    pub fn load_config(&self) -> Result<AppConfig> {
        let content = std::fs::read_to_string(&self.config_path)
            .with_context(|| format!("Failed to read config file: {:?}", self.config_path))?;

        let mut config: AppConfig = match self.format {
            ConfigFormat::Yaml => {
                serde_yaml::from_str(&content).context("Failed to parse YAML config")?
            }
            ConfigFormat::Toml => {
                toml::from_str(&content).context("Failed to parse TOML config")?
            }
            ConfigFormat::Json => {
                serde_json::from_str(&content).context("Failed to parse JSON config")?
            }
        };

        config.server.environment = self.environment;

        self.apply_env_overrides(&mut config)?;

        ConfigValidator::validate_app_config(&config)?;

        Ok(config)
    }

    fn apply_env_overrides(&self, config: &mut AppConfig) -> Result<()> {
        if let Ok(port) = std::env::var("SERVER_PORT") {
            config.server.port = port.parse().context("Invalid SERVER_PORT")?;
        }

        if let Ok(redis_url) = std::env::var("REDIS_URL") {
            config.redis.url = redis_url;
        }

        if let Ok(db_url) = std::env::var("DATABASE_URL") {
            config.database.url = db_url;
            config.database.enabled = true;
        }

        if let Ok(log_level) = std::env::var("LOG_LEVEL") {
            config.observability.log_level = log_level;
        }

        if let Ok(workers) = std::env::var("WORKERS") {
            config.server.workers = workers.parse().context("Invalid WORKERS")?;
        }

        if let Ok(concurrency) = std::env::var("MAX_CONCURRENCY") {
            config.scanner.max_concurrency =
                concurrency.parse().context("Invalid MAX_CONCURRENCY")?;
        }

        Ok(())
    }

    pub fn load_profile(&self, profile_path: &Path) -> Result<ScanProfile> {
        let format = Self::detect_format(profile_path)?;
        let content = std::fs::read_to_string(profile_path)
            .with_context(|| format!("Failed to read profile file: {:?}", profile_path))?;

        let profile: ScanProfile = match format {
            ConfigFormat::Yaml => serde_yaml::from_str(&content)?,
            ConfigFormat::Toml => toml::from_str(&content)?,
            ConfigFormat::Json => serde_json::from_str(&content)?,
        };

        ConfigValidator::validate_scan_profile(&profile)?;

        Ok(profile)
    }

    pub fn load_target_config(&self, target_path: &Path) -> Result<TargetConfig> {
        let format = Self::detect_format(target_path)?;
        let content = std::fs::read_to_string(target_path)
            .with_context(|| format!("Failed to read target config file: {:?}", target_path))?;

        let target_config: TargetConfig = match format {
            ConfigFormat::Yaml => serde_yaml::from_str(&content)?,
            ConfigFormat::Toml => toml::from_str(&content)?,
            ConfigFormat::Json => serde_json::from_str(&content)?,
        };

        ConfigValidator::validate_target_config(&target_config)?;

        Ok(target_config)
    }

    pub fn load_profiles_from_directory(&self, dir_path: &Path) -> Result<ProfileRegistry> {
        let mut registry = ProfileRegistry::new();

        if !dir_path.exists() {
            return Ok(registry);
        }

        for entry in std::fs::read_dir(dir_path)? {
            let entry = entry?;
            let path = entry.path();

            if path.is_file() {
                if let Ok(profile) = self.load_profile(&path) {
                    registry.register(profile);
                }
            }
        }

        Ok(registry)
    }

    pub fn save_config(&self, config: &AppConfig) -> Result<()> {
        ConfigValidator::validate_app_config(config)?;

        let content = match self.format {
            ConfigFormat::Yaml => serde_yaml::to_string(config)?,
            ConfigFormat::Toml => toml::to_string_pretty(config)?,
            ConfigFormat::Json => serde_json::to_string_pretty(config)?,
        };

        std::fs::write(&self.config_path, content)
            .with_context(|| format!("Failed to write config file: {:?}", self.config_path))?;

        Ok(())
    }

    pub fn save_profile(&self, profile: &ScanProfile, output_path: &Path) -> Result<()> {
        ConfigValidator::validate_scan_profile(profile)?;

        let format = Self::detect_format(output_path)?;

        let content = match format {
            ConfigFormat::Yaml => serde_yaml::to_string(profile)?,
            ConfigFormat::Toml => toml::to_string_pretty(profile)?,
            ConfigFormat::Json => serde_json::to_string_pretty(profile)?,
        };

        std::fs::write(output_path, content)
            .with_context(|| format!("Failed to write profile file: {:?}", output_path))?;

        Ok(())
    }
}

pub struct HotReloadManager<T: Clone + Send + Sync + DeserializeOwned + 'static> {
    config: Arc<RwLock<T>>,
    config_path: PathBuf,
    reload_tx: broadcast::Sender<T>,
    _watcher: Option<RecommendedWatcher>,
}

impl<T: Clone + Send + Sync + DeserializeOwned + 'static> HotReloadManager<T> {
    pub fn new(initial_config: T, config_path: PathBuf) -> Result<Self> {
        let config = Arc::new(RwLock::new(initial_config));
        let (reload_tx, _) = broadcast::channel(100);

        Ok(Self {
            config,
            config_path,
            reload_tx,
            _watcher: None,
        })
    }

    pub fn start_watching(mut self) -> Result<Self> {
        let config = Arc::clone(&self.config);
        let reload_tx = self.reload_tx.clone();
        let config_path = self.config_path.clone();

        let (tx, mut rx) = tokio::sync::mpsc::channel(100);

        let mut watcher = notify::recommended_watcher(move |res: Result<Event, notify::Error>| {
            if let Ok(event) = res {
                let _ = tx.blocking_send(event);
            }
        })?;

        watcher.watch(&self.config_path, RecursiveMode::NonRecursive)?;

        tokio::spawn(async move {
            let mut debounce_timer: Option<tokio::time::Instant> = None;

            while let Some(event) = rx.recv().await {
                use notify::EventKind;

                match event.kind {
                    EventKind::Modify(_) | EventKind::Create(_) => {
                        let now = tokio::time::Instant::now();

                        if let Some(last_reload) = debounce_timer {
                            if now.duration_since(last_reload) < Duration::from_millis(500) {
                                continue;
                            }
                        }

                        debounce_timer = Some(now);

                        if let Err(e) =
                            Self::reload_config_internal(&config, &config_path, &reload_tx).await
                        {
                            tracing::error!("Failed to reload config: {}", e);
                        }
                    }
                    _ => {}
                }
            }
        });

        self._watcher = Some(watcher);
        Ok(self)
    }

    async fn reload_config_internal(
        config: &Arc<RwLock<T>>,
        config_path: &Path,
        reload_tx: &broadcast::Sender<T>,
    ) -> Result<()> {
        let content = tokio::fs::read_to_string(config_path).await?;

        let new_config: T = if config_path.extension().and_then(|e| e.to_str()) == Some("yaml")
            || config_path.extension().and_then(|e| e.to_str()) == Some("yml")
        {
            serde_yaml::from_str(&content)?
        } else if config_path.extension().and_then(|e| e.to_str()) == Some("toml") {
            toml::from_str(&content)?
        } else {
            serde_json::from_str(&content)?
        };

        {
            let mut config_write = config.write();
            *config_write = new_config.clone();
        }

        let _ = reload_tx.send(new_config);

        tracing::info!("Configuration reloaded successfully");

        Ok(())
    }

    pub fn get_config(&self) -> T {
        self.config.read().clone()
    }

    pub fn subscribe(&self) -> broadcast::Receiver<T> {
        self.reload_tx.subscribe()
    }

    pub fn update_config<F>(&self, updater: F) -> Result<()>
    where
        F: FnOnce(&mut T),
    {
        let mut config = self.config.write();
        updater(&mut *config);
        let _ = self.reload_tx.send(config.clone());
        Ok(())
    }
}

trait EnvironmentParse {
    fn parse(s: &str) -> Result<Self>
    where
        Self: Sized;
}

impl EnvironmentParse for Environment {
    fn parse(s: &str) -> Result<Self> {
        match s.to_lowercase().as_str() {
            "development" | "dev" => Ok(Environment::Development),
            "staging" | "stage" => Ok(Environment::Staging),
            "production" | "prod" => Ok(Environment::Production),
            _ => Err(anyhow::anyhow!("Invalid environment: {}", s)),
        }
    }
}

pub fn load_config_with_overrides(base_path: &str, environment: Environment) -> Result<AppConfig> {
    let base_config_path = PathBuf::from(base_path);

    let mut builder = config::Config::builder().add_source(config::File::from(base_config_path));

    let env_config_path = match environment {
        Environment::Development => "config/development.yaml",
        Environment::Staging => "config/staging.yaml",
        Environment::Production => "config/production.yaml",
    };

    let env_path = PathBuf::from(env_config_path);
    if env_path.exists() {
        builder = builder.add_source(config::File::from(env_path));
    }

    builder = builder.add_source(
        config::Environment::with_prefix("APP")
            .separator("__")
            .try_parsing(true),
    );

    let settings = builder.build()?;
    let app_config: AppConfig = settings.try_deserialize()?;

    ConfigValidator::validate_app_config(&app_config)?;

    Ok(app_config)
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::io::Write;
    use tempfile::NamedTempFile;

    #[test]
    fn test_detect_format() {
        assert_eq!(
            ConfigLoader::detect_format(Path::new("config.yaml")).unwrap(),
            ConfigFormat::Yaml
        );
        assert_eq!(
            ConfigLoader::detect_format(Path::new("config.toml")).unwrap(),
            ConfigFormat::Toml
        );
        assert_eq!(
            ConfigLoader::detect_format(Path::new("config.json")).unwrap(),
            ConfigFormat::Json
        );
    }

    #[test]
    fn test_load_yaml_config() -> Result<()> {
        let yaml_content = r#"
server:
  port: 8080
  host: "0.0.0.0"
  workers: 4
redis:
  url: "redis://localhost:6379"
  pool_size: 20
database:
  enabled: false
  url: "postgresql://localhost/test"
  pool_size: 20
  batch_size: 100
scanner:
  max_concurrency: 100
  request_timeout_secs: 30
  max_retries: 2
security:
  secrets_backend: "env-vars"
  tls_verify: true
"#;

        let mut temp_file = NamedTempFile::new()?;
        temp_file.write_all(yaml_content.as_bytes())?;
        temp_file.flush()?;

        let loader = ConfigLoader::with_format(temp_file.path(), ConfigFormat::Yaml)?;
        let config = loader.load_config()?;

        assert_eq!(config.server.port, 8080);
        assert_eq!(config.redis.url, "redis://localhost:6379");

        Ok(())
    }
}