1use std::collections::HashMap;
2use std::fs;
3use std::path::{Path, PathBuf};
4
5use chrono::Utc;
6use serde::{Deserialize, Serialize};
7
8use crate::models::{MultiScanReport, ScanConfig, ScanProfile};
9use crate::rules::CustomRule;
10
11#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
12#[serde(rename_all = "snake_case")]
13pub enum DecisionStatus {
14 #[default]
15 Open,
16 InProgress,
17 Fixed,
18 AcceptedRisk,
19 FalsePositive,
20}
21
22impl DecisionStatus {
23 pub fn label(self) -> &'static str {
24 match self {
25 DecisionStatus::Open => "Open",
26 DecisionStatus::InProgress => "In Progress",
27 DecisionStatus::Fixed => "Fixed",
28 DecisionStatus::AcceptedRisk => "Accepted Risk",
29 DecisionStatus::FalsePositive => "False Positive",
30 }
31 }
32
33 pub const ALL: &'static [DecisionStatus] = &[
34 DecisionStatus::Open,
35 DecisionStatus::InProgress,
36 DecisionStatus::Fixed,
37 DecisionStatus::AcceptedRisk,
38 DecisionStatus::FalsePositive,
39 ];
40}
41
42#[derive(Debug, Clone, Serialize, Deserialize)]
43pub struct FindingDecision {
44 pub fingerprint: String,
45 pub finding_id: String,
46 pub status: DecisionStatus,
47 #[serde(default)]
48 pub owner: Option<String>,
49 #[serde(default)]
50 pub due_date: Option<String>,
51 #[serde(default)]
52 pub expires_at: Option<String>,
53 #[serde(default)]
54 pub note: Option<String>,
55 pub updated_at: String,
56}
57
58#[derive(Debug, Clone, Default, Serialize, Deserialize)]
59pub struct DecisionStore {
60 pub decisions: HashMap<String, FindingDecision>,
61}
62
63impl DecisionStore {
64 pub fn load(base_dir: &Path, project: &str) -> anyhow::Result<Self> {
65 let path = project_dir(base_dir, project).join("decisions.json");
66 if !path.exists() {
67 return Ok(Self::default());
68 }
69 let raw = fs::read_to_string(&path)?;
70 Ok(serde_json::from_str(&raw)?)
71 }
72
73 pub fn save(&self, base_dir: &Path, project: &str) -> anyhow::Result<()> {
74 let dir = project_dir(base_dir, project);
75 fs::create_dir_all(&dir)?;
76 let path = dir.join("decisions.json");
77 fs::write(path, serde_json::to_string_pretty(self)?)?;
78 Ok(())
79 }
80
81 pub fn upsert(&mut self, decision: FindingDecision) {
82 self.decisions
83 .insert(decision.fingerprint.clone(), decision);
84 }
85
86 pub fn get(&self, fingerprint: &str) -> Option<&FindingDecision> {
87 self.decisions.get(fingerprint)
88 }
89}
90
91#[derive(Debug, Clone, Serialize, Deserialize)]
92pub struct ProjectConfig {
93 pub name: String,
94 #[serde(default)]
95 pub targets: Vec<String>,
96 #[serde(default)]
97 pub profile: ScanProfile,
98 #[serde(default = "default_max_pages")]
99 pub max_pages: usize,
100 #[serde(default = "default_max_requests")]
101 pub max_requests: usize,
102 #[serde(default = "default_timeout_secs")]
103 pub timeout_secs: u64,
104 #[serde(default = "default_concurrency")]
105 pub concurrency: usize,
106 #[serde(default)]
107 pub skip_paths: bool,
108 #[serde(default)]
109 pub skip_dns: bool,
110 #[serde(default)]
111 pub rules_file: Option<String>,
112 #[serde(default)]
113 pub openapi_path: Option<String>,
114 #[serde(default)]
115 pub advisories_path: Option<String>,
116 #[serde(default = "default_auth_context")]
117 pub auth_context: String,
118 #[serde(default)]
119 pub fail_on: Option<String>,
120 #[serde(default)]
121 pub baseline_run_id: Option<String>,
122}
123
124fn default_max_pages() -> usize {
125 10
126}
127
128fn default_max_requests() -> usize {
129 120
130}
131
132fn default_timeout_secs() -> u64 {
133 10
134}
135
136fn default_concurrency() -> usize {
137 6
138}
139
140fn default_auth_context() -> String {
141 "anonymous".to_string()
142}
143
144impl Default for ProjectConfig {
145 fn default() -> Self {
146 Self {
147 name: "default".into(),
148 targets: Vec::new(),
149 profile: ScanProfile::Web,
150 max_pages: 10,
151 max_requests: 120,
152 timeout_secs: 10,
153 concurrency: 6,
154 skip_paths: false,
155 skip_dns: false,
156 rules_file: None,
157 openapi_path: None,
158 advisories_path: None,
159 auth_context: "anonymous".into(),
160 fail_on: None,
161 baseline_run_id: None,
162 }
163 }
164}
165
166impl ProjectConfig {
167 pub fn load_from(path: &Path) -> anyhow::Result<Self> {
168 let raw = fs::read_to_string(path)?;
169 Ok(serde_json::from_str(&raw)?)
170 }
171
172 pub fn save_to(&self, path: &Path) -> anyhow::Result<()> {
173 if let Some(parent) = path.parent() {
174 if !parent.as_os_str().is_empty() {
175 fs::create_dir_all(parent)?;
176 }
177 }
178 fs::write(path, serde_json::to_string_pretty(self)?)?;
179 Ok(())
180 }
181
182 pub fn to_scan_config(
183 &self,
184 custom_rules: Vec<CustomRule>,
185 auth_headers: Vec<(String, String)>,
186 ) -> ScanConfig {
187 ScanConfig {
188 timeout_secs: self.timeout_secs.max(1),
189 concurrency: self.concurrency.max(1),
190 max_pages: self.max_pages.max(1),
191 max_requests: self.max_requests.max(1),
192 profile: self.profile,
193 skip_paths: self.skip_paths,
194 skip_dns: self.skip_dns,
195 auth_context: self.auth_context.clone(),
196 openapi_path: self.openapi_path.clone(),
197 custom_rules,
198 auth_headers,
199 ..ScanConfig::default()
200 }
201 }
202}
203
204#[derive(Debug, Clone, Serialize, Deserialize)]
205pub struct ScanRunRecord {
206 pub run_id: String,
207 pub project: String,
208 pub generated_at: String,
209 pub targets: Vec<String>,
210 pub min_score: u8,
211 pub avg_score: u8,
212 pub is_preliminary: bool,
213 pub cancelled: bool,
214 pub report_file: String,
215}
216
217pub fn default_data_dir() -> PathBuf {
218 if let Ok(xdg) = std::env::var("XDG_CONFIG_HOME") {
219 if !xdg.trim().is_empty() {
220 return PathBuf::from(xdg).join("web-vuln-scanner");
221 }
222 }
223 if let Ok(appdata) = std::env::var("APPDATA") {
224 if !appdata.trim().is_empty() {
225 return PathBuf::from(appdata).join("web-vuln-scanner");
226 }
227 }
228 if let Ok(home) = std::env::var("HOME") {
229 if !home.trim().is_empty() {
230 return PathBuf::from(home).join(".config").join("web-vuln-scanner");
231 }
232 }
233 if let Ok(profile) = std::env::var("USERPROFILE") {
234 if !profile.trim().is_empty() {
235 return PathBuf::from(profile)
236 .join(".config")
237 .join("web-vuln-scanner");
238 }
239 }
240 std::env::current_dir()
241 .unwrap_or_else(|_| PathBuf::from("."))
242 .join(".web-vuln-scanner")
243}
244
245pub fn sanitize_project_name(raw: &str) -> String {
246 let cleaned: String = raw
247 .trim()
248 .chars()
249 .map(|c| {
250 if c.is_ascii_alphanumeric() || c == '-' || c == '_' {
251 c.to_ascii_lowercase()
252 } else {
253 '-'
254 }
255 })
256 .collect();
257 let trimmed = cleaned.trim_matches('-');
258 if trimmed.is_empty() {
259 "default".to_string()
260 } else {
261 trimmed.to_string()
262 }
263}
264
265pub fn project_dir(base_dir: &Path, project: &str) -> PathBuf {
266 base_dir
267 .join("projects")
268 .join(sanitize_project_name(project))
269}
270
271pub fn save_run(
272 base_dir: &Path,
273 project: &str,
274 report: &MultiScanReport,
275) -> anyhow::Result<ScanRunRecord> {
276 let proj_slug = sanitize_project_name(project);
277 let runs_dir = project_dir(base_dir, &proj_slug).join("runs");
278 fs::create_dir_all(&runs_dir)?;
279
280 let run_id = format!("run-{}", Utc::now().format("%Y%m%dT%H%M%S%.3fZ"));
281 let report_file = format!("{run_id}.json");
282 let report_path = runs_dir.join(&report_file);
283 fs::write(&report_path, serde_json::to_string_pretty(report)?)?;
284
285 let targets: Vec<String> = report.reports.iter().map(|r| r.final_url.clone()).collect();
286 let min_score = report.reports.iter().map(|r| r.score).min().unwrap_or(0);
287 let avg_score = if report.reports.is_empty() {
288 0
289 } else {
290 let sum: u32 = report.reports.iter().map(|r| u32::from(r.score)).sum();
291 (sum / report.reports.len() as u32) as u8
292 };
293 let is_preliminary =
294 report.cancelled || report.reports.iter().any(|r| r.coverage.is_preliminary);
295
296 let record = ScanRunRecord {
297 run_id,
298 project: proj_slug.clone(),
299 generated_at: report.generated_at.clone(),
300 targets,
301 min_score,
302 avg_score,
303 is_preliminary,
304 cancelled: report.cancelled,
305 report_file,
306 };
307
308 let mut history = list_runs(base_dir, &proj_slug).unwrap_or_default();
309 history.insert(0, record.clone());
310 history.truncate(50);
311
312 let history_path = project_dir(base_dir, &proj_slug).join("history.json");
313 fs::write(history_path, serde_json::to_string_pretty(&history)?)?;
314
315 Ok(record)
316}
317
318pub fn list_runs(base_dir: &Path, project: &str) -> anyhow::Result<Vec<ScanRunRecord>> {
319 let history_path = project_dir(base_dir, project).join("history.json");
320 if !history_path.exists() {
321 return Ok(Vec::new());
322 }
323 let raw = fs::read_to_string(&history_path)?;
324 Ok(serde_json::from_str(&raw)?)
325}
326
327pub fn load_run_report(
328 base_dir: &Path,
329 project: &str,
330 record: &ScanRunRecord,
331) -> anyhow::Result<MultiScanReport> {
332 let path = project_dir(base_dir, project)
333 .join("runs")
334 .join(&record.report_file);
335 let raw = fs::read_to_string(&path)?;
336 Ok(serde_json::from_str(&raw)?)
337}
338
339#[cfg(test)]
340mod tests {
341 use super::*;
342 use crate::models::{
343 CoverageSummary, ExecutionStatus, ScanReport, SeverityCounts, SCHEMA_VERSION,
344 };
345
346 #[test]
347 fn persists_project_decisions_and_run_history() {
348 let root = std::env::temp_dir().join(format!(
349 "wvs-storage-test-{}",
350 Utc::now().timestamp_nanos_opt().unwrap_or(1)
351 ));
352 let cfg_path = root.join("scanner-project.json");
353
354 let proj = ProjectConfig {
355 name: "my-api".into(),
356 targets: vec!["http://127.0.0.1:8787".into()],
357 profile: ScanProfile::Api,
358 ..ProjectConfig::default()
359 };
360 proj.save_to(&cfg_path).unwrap();
361 let loaded_proj = ProjectConfig::load_from(&cfg_path).unwrap();
362 assert_eq!(loaded_proj.name, "my-api");
363 assert_eq!(loaded_proj.profile, ScanProfile::Api);
364
365 let mut store = DecisionStore::default();
366 store.upsert(FindingDecision {
367 fingerprint: "fp-123".into(),
368 finding_id: "HDR-CSP-MISSING".into(),
369 status: DecisionStatus::AcceptedRisk,
370 owner: Some("platform-team".into()),
371 due_date: Some("2026-12-01".into()),
372 expires_at: None,
373 note: Some("API only returns JSON".into()),
374 updated_at: "2026-11-16T00:00:00Z".into(),
375 });
376 store.save(&root, "my-api").unwrap();
377 let loaded_store = DecisionStore::load(&root, "my-api").unwrap();
378 assert_eq!(
379 loaded_store.get("fp-123").unwrap().status,
380 DecisionStatus::AcceptedRisk
381 );
382
383 let report = MultiScanReport {
384 schema_version: SCHEMA_VERSION.into(),
385 engine_version: "0.2.0".into(),
386 tool: "web-vuln-scanner".into(),
387 version: "0.2.0".into(),
388 generated_at: "2026-11-16T10:00:00Z".into(),
389 cancelled: false,
390 reports: vec![ScanReport {
391 schema_version: SCHEMA_VERSION.into(),
392 engine_version: "0.2.0".into(),
393 target: "http://127.0.0.1:8787".into(),
394 final_url: "http://127.0.0.1:8787/".into(),
395 scanned_at: "2026-11-16T10:00:00Z".into(),
396 duration_ms: 12,
397 status_code: Some(200),
398 profile: ScanProfile::Api,
399 auth_context: "anonymous".into(),
400 run_status: ExecutionStatus::Completed,
401 cancelled: false,
402 pages_scanned: 1,
403 crawled_urls: vec!["http://127.0.0.1:8787/".into()],
404 score: 85,
405 grade: "B".into(),
406 score_breakdown: vec![],
407 coverage: CoverageSummary::default(),
408 outcomes: vec![],
409 instances: vec![],
410 tls: None,
411 findings: vec![],
412 counts: SeverityCounts::default(),
413 }],
414 };
415
416 let rec = save_run(&root, "my-api", &report).unwrap();
417 let runs = list_runs(&root, "my-api").unwrap();
418 assert_eq!(runs.len(), 1);
419 assert_eq!(runs[0].run_id, rec.run_id);
420 let reloaded = load_run_report(&root, "my-api", &runs[0]).unwrap();
421 assert_eq!(reloaded.reports[0].score, 85);
422
423 let _ = fs::remove_dir_all(&root);
424 }
425}