website-vulnerability-scanner 0.2.0

Cross-platform defensive website security & configuration scanner with GUI and CLI reports.
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
use std::collections::{HashMap, HashSet};
use std::path::Path;

use serde::{Deserialize, Serialize};

use crate::models::{
    Category, ExecutionStatus, Finding, MultiScanReport, ScanReport, Severity, Verdict,
};

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TargetDiff {
    pub target: String,
    pub old_score: Option<u8>,
    pub new_score: u8,
    pub score_delta: i16,
    pub old_grade: Option<String>,
    pub new_grade: String,
    #[serde(default = "default_true")]
    pub compatible: bool,
    #[serde(default)]
    pub compatibility_notes: Vec<String>,
    pub new_issues: Vec<Finding>,
    #[serde(default)]
    pub worsened_issues: Vec<Finding>,
    pub resolved_issues: Vec<Finding>,
    #[serde(default)]
    pub unverified_issues: Vec<Finding>,
    pub unchanged_issues: usize,
    #[serde(default)]
    pub new_instances: usize,
    #[serde(default)]
    pub resolved_instances: usize,
}

fn default_true() -> bool {
    true
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct MultiReportDiff {
    pub baseline_generated_at: String,
    pub targets: Vec<TargetDiff>,
}

impl MultiReportDiff {
    pub fn has_new_regressions(&self) -> bool {
        self.targets.iter().any(|t| {
            t.new_issues
                .iter()
                .chain(t.worsened_issues.iter())
                .any(|f| f.severity.rank() >= Severity::Low.rank())
        })
    }

    pub fn new_issue_ids_for(&self, target_url: &str) -> HashSet<String> {
        self.targets
            .iter()
            .find(|t| t.target == target_url)
            .map(|t| t.new_issues.iter().map(|f| f.id.clone()).collect())
            .unwrap_or_default()
    }

    pub fn worsened_issue_ids_for(&self, target_url: &str) -> HashSet<String> {
        self.targets
            .iter()
            .find(|t| t.target == target_url)
            .map(|t| t.worsened_issues.iter().map(|f| f.id.clone()).collect())
            .unwrap_or_default()
    }
}

pub fn load_baseline(path: &Path) -> anyhow::Result<MultiScanReport> {
    let raw = std::fs::read_to_string(path)?;
    let parsed: MultiScanReport = serde_json::from_str(&raw)?;
    Ok(parsed)
}

fn is_issue(f: &Finding) -> bool {
    f.severity != Severity::Pass && f.severity != Severity::Info
}

fn category_verified_in_current(cur: &ScanReport, category: Category) -> bool {
    if cur.cancelled {
        return false;
    }
    if cur.outcomes.is_empty() {
        // Legacy schema v1 reports did not emit CheckOutcome lists.
        return true;
    }
    let relevant: Vec<_> = cur
        .outcomes
        .iter()
        .filter(|o| o.category == category)
        .collect();
    if relevant.is_empty() {
        return false;
    }
    let has_completed = relevant
        .iter()
        .any(|o| o.status == ExecutionStatus::Completed && o.verdict != Verdict::Inconclusive);
    let has_incomplete = relevant.iter().any(|o| {
        matches!(
            o.status,
            ExecutionStatus::Skipped | ExecutionStatus::Error | ExecutionStatus::Cancelled
        )
    });
    has_completed && !has_incomplete
}

pub fn compare_reports(baseline: &MultiScanReport, current: &MultiScanReport) -> MultiReportDiff {
    let mut base_by_target: HashMap<String, &ScanReport> = HashMap::new();
    for r in &baseline.reports {
        base_by_target.insert(r.final_url.clone(), r);
        base_by_target.insert(r.target.clone(), r);
    }

    let mut targets = Vec::with_capacity(current.reports.len());
    for (idx, cur) in current.reports.iter().enumerate() {
        let base_opt = base_by_target
            .get(&cur.final_url)
            .or_else(|| base_by_target.get(&cur.target))
            .copied()
            .or_else(|| {
                if baseline.reports.len() == 1 && current.reports.len() == 1 {
                    baseline.reports.get(idx)
                } else {
                    None
                }
            });

        if let Some(base) = base_opt {
            let mut compatible = true;
            let mut compatibility_notes = Vec::new();
            if base.profile != cur.profile {
                compatible = false;
                compatibility_notes.push(format!(
                    "Profile changed: baseline={}, current={}",
                    base.profile.label(),
                    cur.profile.label()
                ));
            }
            if base.auth_context != cur.auth_context {
                compatible = false;
                compatibility_notes.push(format!(
                    "Auth context changed: baseline='{}', current='{}'",
                    base.auth_context, cur.auth_context
                ));
            }
            if cur.cancelled {
                compatibility_notes
                    .push("Current scan was cancelled; missing issues may be unverified.".into());
            } else if cur.coverage.is_preliminary {
                compatibility_notes.push(format!(
                    "Current scan coverage is preliminary ({}%).",
                    cur.coverage.coverage_percent
                ));
            }

            let base_map: HashMap<&str, &Finding> = base
                .findings
                .iter()
                .filter(|f| is_issue(f))
                .map(|f| (f.id.as_str(), f))
                .collect();
            let cur_map: HashMap<&str, &Finding> = cur
                .findings
                .iter()
                .filter(|f| is_issue(f))
                .map(|f| (f.id.as_str(), f))
                .collect();

            let mut new_issues = Vec::new();
            let mut worsened_issues = Vec::new();
            let mut unchanged_issues = 0usize;

            for f in cur.findings.iter().filter(|f| is_issue(f)) {
                match base_map.get(f.id.as_str()) {
                    None => new_issues.push(f.clone()),
                    Some(prev) => {
                        if f.severity.rank() > prev.severity.rank() {
                            worsened_issues.push(f.clone());
                        } else {
                            unchanged_issues += 1;
                        }
                    }
                }
            }

            let mut resolved_issues = Vec::new();
            let mut unverified_issues = Vec::new();
            for f in base.findings.iter().filter(|f| is_issue(f)) {
                if !cur_map.contains_key(f.id.as_str()) {
                    if category_verified_in_current(cur, f.category) {
                        resolved_issues.push(f.clone());
                    } else {
                        unverified_issues.push(f.clone());
                    }
                }
            }

            let base_fps: HashSet<&str> = base
                .instances
                .iter()
                .map(|i| i.fingerprint.as_str())
                .collect();
            let cur_fps: HashSet<&str> = cur
                .instances
                .iter()
                .map(|i| i.fingerprint.as_str())
                .collect();
            let new_instances = cur_fps.difference(&base_fps).count();
            let resolved_instances = base_fps.difference(&cur_fps).count();

            let score_delta = i16::from(cur.score) - i16::from(base.score);

            targets.push(TargetDiff {
                target: cur.final_url.clone(),
                old_score: Some(base.score),
                new_score: cur.score,
                score_delta,
                old_grade: Some(base.grade.clone()),
                new_grade: cur.grade.clone(),
                compatible,
                compatibility_notes,
                new_issues,
                worsened_issues,
                resolved_issues,
                unverified_issues,
                unchanged_issues,
                new_instances,
                resolved_instances,
            });
        } else {
            let new_issues: Vec<Finding> = cur
                .findings
                .iter()
                .filter(|f| is_issue(f))
                .cloned()
                .collect();
            targets.push(TargetDiff {
                target: cur.final_url.clone(),
                old_score: None,
                new_score: cur.score,
                score_delta: 0,
                old_grade: None,
                new_grade: cur.grade.clone(),
                compatible: true,
                compatibility_notes: vec![
                    "No matching baseline target; treated as initial baseline.".into(),
                ],
                new_issues,
                worsened_issues: Vec::new(),
                resolved_issues: Vec::new(),
                unverified_issues: Vec::new(),
                unchanged_issues: 0,
                new_instances: cur.instances.len(),
                resolved_instances: 0,
            });
        }
    }

    MultiReportDiff {
        baseline_generated_at: baseline.generated_at.clone(),
        targets,
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::models::{
        CheckOutcome, Confidence, CoverageSummary, ScanProfile, SeverityCounts, SCHEMA_VERSION,
    };

    fn mk_report(
        score: u8,
        grade: &str,
        ids: &[(&str, Category, Severity)],
        outcomes: Vec<CheckOutcome>,
        cancelled: bool,
    ) -> ScanReport {
        let findings: Vec<Finding> = ids
            .iter()
            .map(|(id, cat, sev)| Finding {
                id: (*id).into(),
                category: *cat,
                severity: *sev,
                title: (*id).into(),
                summary: String::new(),
                evidence: None,
                remediation: String::new(),
                standard_ref: None,
                confidence: Confidence::High,
            })
            .collect();
        let counts = SeverityCounts::from_findings(&findings);
        let coverage = CoverageSummary::from_outcomes(&outcomes, cancelled);
        ScanReport {
            schema_version: SCHEMA_VERSION.into(),
            engine_version: "0.2.0".into(),
            target: "https://example.com/".into(),
            final_url: "https://example.com/".into(),
            scanned_at: "2026-11-16T00:00:00Z".into(),
            duration_ms: 10,
            status_code: Some(200),
            profile: ScanProfile::Web,
            auth_context: "anonymous".into(),
            run_status: if cancelled {
                ExecutionStatus::Cancelled
            } else {
                ExecutionStatus::Completed
            },
            cancelled,
            pages_scanned: 1,
            crawled_urls: vec![],
            score,
            grade: grade.into(),
            score_breakdown: vec![],
            coverage,
            outcomes,
            instances: vec![],
            tls: None,
            findings,
            counts,
        }
    }

    #[test]
    fn detects_new_worsened_resolved_and_unverified_issues() {
        let base = MultiScanReport {
            schema_version: SCHEMA_VERSION.into(),
            engine_version: "0.2.0".into(),
            tool: "web-vuln-scanner".into(),
            version: "0.2.0".into(),
            generated_at: "t1".into(),
            cancelled: false,
            reports: vec![mk_report(
                80,
                "B",
                &[
                    (
                        "HDR-CSP-MISSING",
                        Category::SecurityHeaders,
                        Severity::Medium,
                    ),
                    ("CORS-WILDCARD", Category::Cors, Severity::Low),
                    ("DNS-NO-DMARC", Category::DnsEmail, Severity::Low),
                ],
                vec![],
                false,
            )],
        };
        let cur = MultiScanReport {
            schema_version: SCHEMA_VERSION.into(),
            engine_version: "0.2.0".into(),
            tool: "web-vuln-scanner".into(),
            version: "0.2.0".into(),
            generated_at: "t2".into(),
            cancelled: false,
            reports: vec![mk_report(
                70,
                "B",
                &[
                    (
                        "EXP-GIT-EXPOSED",
                        Category::ExposedFiles,
                        Severity::Critical,
                    ),
                    ("CORS-WILDCARD", Category::Cors, Severity::High),
                ],
                vec![
                    CheckOutcome {
                        check_id: "security-headers".into(),
                        category: Category::SecurityHeaders,
                        location: "https://example.com/".into(),
                        auth_context: "anonymous".into(),
                        status: ExecutionStatus::Completed,
                        verdict: Verdict::Pass,
                        reason: None,
                    },
                    CheckOutcome {
                        check_id: "dns-hygiene".into(),
                        category: Category::DnsEmail,
                        location: "example.com".into(),
                        auth_context: "anonymous".into(),
                        status: ExecutionStatus::Error,
                        verdict: Verdict::Inconclusive,
                        reason: Some("DNS timeout".into()),
                    },
                ],
                false,
            )],
        };

        let diff = compare_reports(&base, &cur);
        assert!(diff.has_new_regressions());
        assert_eq!(diff.targets[0].score_delta, -10);
        assert_eq!(diff.targets[0].new_issues[0].id, "EXP-GIT-EXPOSED");
        assert_eq!(diff.targets[0].worsened_issues[0].id, "CORS-WILDCARD");
        assert_eq!(diff.targets[0].resolved_issues[0].id, "HDR-CSP-MISSING");
        assert_eq!(diff.targets[0].unverified_issues[0].id, "DNS-NO-DMARC");
    }

    #[test]
    fn flags_incompatible_auth_or_profile_baseline() {
        let base_r = mk_report(90, "A", &[], vec![], false);
        let mut cur_r = mk_report(95, "A", &[], vec![], false);
        cur_r.auth_context = "admin-token".into();
        let base = MultiScanReport {
            schema_version: SCHEMA_VERSION.into(),
            engine_version: "0.2.0".into(),
            tool: "web-vuln-scanner".into(),
            version: "0.2.0".into(),
            generated_at: "t1".into(),
            cancelled: false,
            reports: vec![base_r],
        };
        let cur = MultiScanReport {
            schema_version: SCHEMA_VERSION.into(),
            engine_version: "0.2.0".into(),
            tool: "web-vuln-scanner".into(),
            version: "0.2.0".into(),
            generated_at: "t2".into(),
            cancelled: false,
            reports: vec![cur_r],
        };
        let diff = compare_reports(&base, &cur);
        assert!(!diff.targets[0].compatible);
        assert!(!diff.targets[0].compatibility_notes.is_empty());
    }
}