use std::collections::HashMap;
use std::fs;
use std::path::{Path, PathBuf};
use chrono::Utc;
use serde::{Deserialize, Serialize};
use crate::models::{MultiScanReport, ScanConfig, ScanProfile};
use crate::rules::CustomRule;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
#[serde(rename_all = "snake_case")]
pub enum DecisionStatus {
#[default]
Open,
InProgress,
Fixed,
AcceptedRisk,
FalsePositive,
}
impl DecisionStatus {
pub fn label(self) -> &'static str {
match self {
DecisionStatus::Open => "Open",
DecisionStatus::InProgress => "In Progress",
DecisionStatus::Fixed => "Fixed",
DecisionStatus::AcceptedRisk => "Accepted Risk",
DecisionStatus::FalsePositive => "False Positive",
}
}
pub const ALL: &'static [DecisionStatus] = &[
DecisionStatus::Open,
DecisionStatus::InProgress,
DecisionStatus::Fixed,
DecisionStatus::AcceptedRisk,
DecisionStatus::FalsePositive,
];
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct FindingDecision {
pub fingerprint: String,
pub finding_id: String,
pub status: DecisionStatus,
#[serde(default)]
pub owner: Option<String>,
#[serde(default)]
pub due_date: Option<String>,
#[serde(default)]
pub expires_at: Option<String>,
#[serde(default)]
pub note: Option<String>,
pub updated_at: String,
}
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct DecisionStore {
pub decisions: HashMap<String, FindingDecision>,
}
impl DecisionStore {
pub fn load(base_dir: &Path, project: &str) -> anyhow::Result<Self> {
let path = project_dir(base_dir, project).join("decisions.json");
if !path.exists() {
return Ok(Self::default());
}
let raw = fs::read_to_string(&path)?;
Ok(serde_json::from_str(&raw)?)
}
pub fn save(&self, base_dir: &Path, project: &str) -> anyhow::Result<()> {
let dir = project_dir(base_dir, project);
fs::create_dir_all(&dir)?;
let path = dir.join("decisions.json");
fs::write(path, serde_json::to_string_pretty(self)?)?;
Ok(())
}
pub fn upsert(&mut self, decision: FindingDecision) {
self.decisions
.insert(decision.fingerprint.clone(), decision);
}
pub fn get(&self, fingerprint: &str) -> Option<&FindingDecision> {
self.decisions.get(fingerprint)
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ProjectConfig {
pub name: String,
#[serde(default)]
pub targets: Vec<String>,
#[serde(default)]
pub profile: ScanProfile,
#[serde(default = "default_max_pages")]
pub max_pages: usize,
#[serde(default = "default_max_requests")]
pub max_requests: usize,
#[serde(default = "default_timeout_secs")]
pub timeout_secs: u64,
#[serde(default = "default_concurrency")]
pub concurrency: usize,
#[serde(default)]
pub skip_paths: bool,
#[serde(default)]
pub skip_dns: bool,
#[serde(default)]
pub rules_file: Option<String>,
#[serde(default)]
pub openapi_path: Option<String>,
#[serde(default)]
pub advisories_path: Option<String>,
#[serde(default = "default_auth_context")]
pub auth_context: String,
#[serde(default)]
pub fail_on: Option<String>,
#[serde(default)]
pub baseline_run_id: Option<String>,
}
fn default_max_pages() -> usize {
10
}
fn default_max_requests() -> usize {
120
}
fn default_timeout_secs() -> u64 {
10
}
fn default_concurrency() -> usize {
6
}
fn default_auth_context() -> String {
"anonymous".to_string()
}
impl Default for ProjectConfig {
fn default() -> Self {
Self {
name: "default".into(),
targets: Vec::new(),
profile: ScanProfile::Web,
max_pages: 10,
max_requests: 120,
timeout_secs: 10,
concurrency: 6,
skip_paths: false,
skip_dns: false,
rules_file: None,
openapi_path: None,
advisories_path: None,
auth_context: "anonymous".into(),
fail_on: None,
baseline_run_id: None,
}
}
}
impl ProjectConfig {
pub fn load_from(path: &Path) -> anyhow::Result<Self> {
let raw = fs::read_to_string(path)?;
Ok(serde_json::from_str(&raw)?)
}
pub fn save_to(&self, path: &Path) -> anyhow::Result<()> {
if let Some(parent) = path.parent() {
if !parent.as_os_str().is_empty() {
fs::create_dir_all(parent)?;
}
}
fs::write(path, serde_json::to_string_pretty(self)?)?;
Ok(())
}
pub fn to_scan_config(
&self,
custom_rules: Vec<CustomRule>,
auth_headers: Vec<(String, String)>,
) -> ScanConfig {
ScanConfig {
timeout_secs: self.timeout_secs.max(1),
concurrency: self.concurrency.max(1),
max_pages: self.max_pages.max(1),
max_requests: self.max_requests.max(1),
profile: self.profile,
skip_paths: self.skip_paths,
skip_dns: self.skip_dns,
auth_context: self.auth_context.clone(),
openapi_path: self.openapi_path.clone(),
custom_rules,
auth_headers,
..ScanConfig::default()
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ScanRunRecord {
pub run_id: String,
pub project: String,
pub generated_at: String,
pub targets: Vec<String>,
pub min_score: u8,
pub avg_score: u8,
pub is_preliminary: bool,
pub cancelled: bool,
pub report_file: String,
}
pub fn default_data_dir() -> PathBuf {
if let Ok(xdg) = std::env::var("XDG_CONFIG_HOME") {
if !xdg.trim().is_empty() {
return PathBuf::from(xdg).join("web-vuln-scanner");
}
}
if let Ok(appdata) = std::env::var("APPDATA") {
if !appdata.trim().is_empty() {
return PathBuf::from(appdata).join("web-vuln-scanner");
}
}
if let Ok(home) = std::env::var("HOME") {
if !home.trim().is_empty() {
return PathBuf::from(home).join(".config").join("web-vuln-scanner");
}
}
if let Ok(profile) = std::env::var("USERPROFILE") {
if !profile.trim().is_empty() {
return PathBuf::from(profile)
.join(".config")
.join("web-vuln-scanner");
}
}
std::env::current_dir()
.unwrap_or_else(|_| PathBuf::from("."))
.join(".web-vuln-scanner")
}
pub fn sanitize_project_name(raw: &str) -> String {
let cleaned: String = raw
.trim()
.chars()
.map(|c| {
if c.is_ascii_alphanumeric() || c == '-' || c == '_' {
c.to_ascii_lowercase()
} else {
'-'
}
})
.collect();
let trimmed = cleaned.trim_matches('-');
if trimmed.is_empty() {
"default".to_string()
} else {
trimmed.to_string()
}
}
pub fn project_dir(base_dir: &Path, project: &str) -> PathBuf {
base_dir
.join("projects")
.join(sanitize_project_name(project))
}
pub fn save_run(
base_dir: &Path,
project: &str,
report: &MultiScanReport,
) -> anyhow::Result<ScanRunRecord> {
let proj_slug = sanitize_project_name(project);
let runs_dir = project_dir(base_dir, &proj_slug).join("runs");
fs::create_dir_all(&runs_dir)?;
let run_id = format!("run-{}", Utc::now().format("%Y%m%dT%H%M%S%.3fZ"));
let report_file = format!("{run_id}.json");
let report_path = runs_dir.join(&report_file);
fs::write(&report_path, serde_json::to_string_pretty(report)?)?;
let targets: Vec<String> = report.reports.iter().map(|r| r.final_url.clone()).collect();
let min_score = report.reports.iter().map(|r| r.score).min().unwrap_or(0);
let avg_score = if report.reports.is_empty() {
0
} else {
let sum: u32 = report.reports.iter().map(|r| u32::from(r.score)).sum();
(sum / report.reports.len() as u32) as u8
};
let is_preliminary =
report.cancelled || report.reports.iter().any(|r| r.coverage.is_preliminary);
let record = ScanRunRecord {
run_id,
project: proj_slug.clone(),
generated_at: report.generated_at.clone(),
targets,
min_score,
avg_score,
is_preliminary,
cancelled: report.cancelled,
report_file,
};
let mut history = list_runs(base_dir, &proj_slug).unwrap_or_default();
history.insert(0, record.clone());
history.truncate(50);
let history_path = project_dir(base_dir, &proj_slug).join("history.json");
fs::write(history_path, serde_json::to_string_pretty(&history)?)?;
Ok(record)
}
pub fn list_runs(base_dir: &Path, project: &str) -> anyhow::Result<Vec<ScanRunRecord>> {
let history_path = project_dir(base_dir, project).join("history.json");
if !history_path.exists() {
return Ok(Vec::new());
}
let raw = fs::read_to_string(&history_path)?;
Ok(serde_json::from_str(&raw)?)
}
pub fn load_run_report(
base_dir: &Path,
project: &str,
record: &ScanRunRecord,
) -> anyhow::Result<MultiScanReport> {
let path = project_dir(base_dir, project)
.join("runs")
.join(&record.report_file);
let raw = fs::read_to_string(&path)?;
Ok(serde_json::from_str(&raw)?)
}
#[cfg(test)]
mod tests {
use super::*;
use crate::models::{
CoverageSummary, ExecutionStatus, ScanReport, SeverityCounts, SCHEMA_VERSION,
};
#[test]
fn persists_project_decisions_and_run_history() {
let root = std::env::temp_dir().join(format!(
"wvs-storage-test-{}",
Utc::now().timestamp_nanos_opt().unwrap_or(1)
));
let cfg_path = root.join("scanner-project.json");
let proj = ProjectConfig {
name: "my-api".into(),
targets: vec!["http://127.0.0.1:8787".into()],
profile: ScanProfile::Api,
..ProjectConfig::default()
};
proj.save_to(&cfg_path).unwrap();
let loaded_proj = ProjectConfig::load_from(&cfg_path).unwrap();
assert_eq!(loaded_proj.name, "my-api");
assert_eq!(loaded_proj.profile, ScanProfile::Api);
let mut store = DecisionStore::default();
store.upsert(FindingDecision {
fingerprint: "fp-123".into(),
finding_id: "HDR-CSP-MISSING".into(),
status: DecisionStatus::AcceptedRisk,
owner: Some("platform-team".into()),
due_date: Some("2026-12-01".into()),
expires_at: None,
note: Some("API only returns JSON".into()),
updated_at: "2026-11-16T00:00:00Z".into(),
});
store.save(&root, "my-api").unwrap();
let loaded_store = DecisionStore::load(&root, "my-api").unwrap();
assert_eq!(
loaded_store.get("fp-123").unwrap().status,
DecisionStatus::AcceptedRisk
);
let report = MultiScanReport {
schema_version: SCHEMA_VERSION.into(),
engine_version: "0.2.0".into(),
tool: "web-vuln-scanner".into(),
version: "0.2.0".into(),
generated_at: "2026-11-16T10:00:00Z".into(),
cancelled: false,
reports: vec![ScanReport {
schema_version: SCHEMA_VERSION.into(),
engine_version: "0.2.0".into(),
target: "http://127.0.0.1:8787".into(),
final_url: "http://127.0.0.1:8787/".into(),
scanned_at: "2026-11-16T10:00:00Z".into(),
duration_ms: 12,
status_code: Some(200),
profile: ScanProfile::Api,
auth_context: "anonymous".into(),
run_status: ExecutionStatus::Completed,
cancelled: false,
pages_scanned: 1,
crawled_urls: vec!["http://127.0.0.1:8787/".into()],
score: 85,
grade: "B".into(),
score_breakdown: vec![],
coverage: CoverageSummary::default(),
outcomes: vec![],
instances: vec![],
tls: None,
findings: vec![],
counts: SeverityCounts::default(),
}],
};
let rec = save_run(&root, "my-api", &report).unwrap();
let runs = list_runs(&root, "my-api").unwrap();
assert_eq!(runs.len(), 1);
assert_eq!(runs[0].run_id, rec.run_id);
let reloaded = load_run_report(&root, "my-api", &runs[0]).unwrap();
assert_eq!(reloaded.reports[0].score, 85);
let _ = fs::remove_dir_all(&root);
}
}