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
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
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
use reqwest::header::CONTENT_TYPE;
use reqwest::Method;
use tokio::task::JoinSet;
use url::Url;

use crate::models::{
    Category, CheckOutcome, Confidence, ExecutionStatus, Finding, Severity, Verdict,
};
use crate::transport::{AuthMode, HttpTransport, TransportError};

#[derive(Clone, Copy)]
enum ProbeKind {
    SecurityTxt,
    RobotsTxt,
    GitHead,
    GitConfig,
    SvnEntries,
    SvnWcDb,
    HgRequires,
    DotEnv,
    DsStore,
    PhpInfo,
    ServerStatus,
    DockerCompose,
    PackageJson,
    ComposerJson,
    OpenApiJson,
    SwaggerUi,
    DirListing,
}

struct ProbeSpec {
    path: &'static str,
    kind: ProbeKind,
}

const PROBES: &[ProbeSpec] = &[
    ProbeSpec {
        path: "/.well-known/security.txt",
        kind: ProbeKind::SecurityTxt,
    },
    ProbeSpec {
        path: "/robots.txt",
        kind: ProbeKind::RobotsTxt,
    },
    ProbeSpec {
        path: "/.git/HEAD",
        kind: ProbeKind::GitHead,
    },
    ProbeSpec {
        path: "/.git/config",
        kind: ProbeKind::GitConfig,
    },
    ProbeSpec {
        path: "/.svn/entries",
        kind: ProbeKind::SvnEntries,
    },
    ProbeSpec {
        path: "/.svn/wc.db",
        kind: ProbeKind::SvnWcDb,
    },
    ProbeSpec {
        path: "/.hg/requires",
        kind: ProbeKind::HgRequires,
    },
    ProbeSpec {
        path: "/.env",
        kind: ProbeKind::DotEnv,
    },
    ProbeSpec {
        path: "/.env.production",
        kind: ProbeKind::DotEnv,
    },
    ProbeSpec {
        path: "/.env.local",
        kind: ProbeKind::DotEnv,
    },
    ProbeSpec {
        path: "/.DS_Store",
        kind: ProbeKind::DsStore,
    },
    ProbeSpec {
        path: "/phpinfo.php",
        kind: ProbeKind::PhpInfo,
    },
    ProbeSpec {
        path: "/server-status",
        kind: ProbeKind::ServerStatus,
    },
    ProbeSpec {
        path: "/docker-compose.yml",
        kind: ProbeKind::DockerCompose,
    },
    ProbeSpec {
        path: "/compose.yml",
        kind: ProbeKind::DockerCompose,
    },
    ProbeSpec {
        path: "/package.json",
        kind: ProbeKind::PackageJson,
    },
    ProbeSpec {
        path: "/composer.json",
        kind: ProbeKind::ComposerJson,
    },
    ProbeSpec {
        path: "/openapi.json",
        kind: ProbeKind::OpenApiJson,
    },
    ProbeSpec {
        path: "/swagger.json",
        kind: ProbeKind::OpenApiJson,
    },
    ProbeSpec {
        path: "/swagger-ui.html",
        kind: ProbeKind::SwaggerUi,
    },
    ProbeSpec {
        path: "/assets/",
        kind: ProbeKind::DirListing,
    },
    ProbeSpec {
        path: "/uploads/",
        kind: ProbeKind::DirListing,
    },
    ProbeSpec {
        path: "/static/",
        kind: ProbeKind::DirListing,
    },
    ProbeSpec {
        path: "/files/",
        kind: ProbeKind::DirListing,
    },
];

pub async fn check_exposed_paths(
    transport: &std::sync::Arc<HttpTransport>,
    base_url: &Url,
    auth_context: &str,
) -> (Vec<Finding>, Vec<CheckOutcome>) {
    let mut findings = Vec::new();
    let mut outcomes = Vec::new();
    let mut set = JoinSet::new();

    for spec in PROBES {
        let Ok(target_url) = transport.resolve_in_scope(base_url, spec.path) else {
            continue;
        };
        let tr = std::sync::Arc::clone(transport);
        let kind = spec.kind;
        let path = spec.path;
        let auth_ctx = auth_context.to_string();

        set.spawn(async move {
            let loc = tr.redactor.sanitize_url(&target_url);
            let resp = match tr
                .send(Method::GET, &target_url, AuthMode::Anonymous, &[], Some(65_536))
                .await
            {
                Ok(r) => r,
                Err(TransportError::Cancelled) => {
                    return (
                        None,
                        CheckOutcome {
                            check_id: format!("exposed-probe:{}", path),
                            category: Category::ExposedFiles,
                            location: loc,
                            auth_context: auth_ctx,
                            status: ExecutionStatus::Cancelled,
                            verdict: Verdict::Inconclusive,
                            reason: Some("cancelled".into()),
                        },
                    );
                }
                Err(e) => {
                    return (
                        None,
                        CheckOutcome {
                            check_id: format!("exposed-probe:{}", path),
                            category: Category::ExposedFiles,
                            location: loc,
                            auth_context: auth_ctx,
                            status: ExecutionStatus::Error,
                            verdict: Verdict::Inconclusive,
                            reason: Some(e.to_string()),
                        },
                    );
                }
            };

            if !(200..300).contains(&resp.status) {
                if matches!(kind, ProbeKind::SecurityTxt) {
                    let f = Finding {
                        id: "EXP-NO-SECURITY-TXT".into(),
                        category: Category::ExposedFiles,
                        severity: Severity::Info,
                        title: "/.well-known/security.txt not found".into(),
                        summary: "security.txt (RFC 9116) provides a standard contact channel for security reports.".into(),
                        evidence: None,
                        remediation: "Optionally publish /.well-known/security.txt with a Contact: mailto:security@yourdomain entry.".into(),
                        standard_ref: Some("RFC 9116".into()),
                        confidence: Confidence::High,
                    };
                    return (
                        Some(f),
                        CheckOutcome {
                            check_id: format!("exposed-probe:{}", path),
                            category: Category::ExposedFiles,
                            location: loc,
                            auth_context: auth_ctx,
                            status: ExecutionStatus::Completed,
                            verdict: Verdict::Pass,
                            reason: Some(format!("HTTP {}", resp.status)),
                        },
                    );
                }
                return (
                    None,
                    CheckOutcome {
                        check_id: format!("exposed-probe:{}", path),
                        category: Category::ExposedFiles,
                        location: loc,
                        auth_context: auth_ctx,
                        status: ExecutionStatus::Completed,
                        verdict: Verdict::Pass,
                        reason: Some(format!("HTTP {}", resp.status)),
                    },
                );
            }

            let content_type = resp
                .headers
                .get(CONTENT_TYPE)
                .and_then(|v| v.to_str().ok())
                .unwrap_or("")
                .to_ascii_lowercase();

            let finding = evaluate_probe(kind, path, &target_url, &content_type, &resp.body);
            let is_fail = finding
                .as_ref()
                .map(|f| f.severity != Severity::Pass && f.severity != Severity::Info)
                .unwrap_or(false);

            (
                finding,
                CheckOutcome {
                    check_id: format!("exposed-probe:{}", path),
                    category: Category::ExposedFiles,
                    location: loc,
                    auth_context: auth_ctx,
                    status: ExecutionStatus::Completed,
                    verdict: if is_fail { Verdict::Fail } else { Verdict::Pass },
                    reason: None,
                },
            )
        });
    }

    while let Some(res) = set.join_next().await {
        if let Ok((maybe_finding, outcome)) = res {
            if let Some(f) = maybe_finding {
                findings.push(f);
            }
            outcomes.push(outcome);
        }
    }

    (findings, outcomes)
}

fn evaluate_probe(
    kind: ProbeKind,
    path: &str,
    url: &Url,
    content_type: &str,
    bytes: &[u8],
) -> Option<Finding> {
    let text = std::str::from_utf8(bytes).unwrap_or("");
    let trimmed_start = text.trim_start();
    let is_html = content_type.contains("text/html")
        || trimmed_start.starts_with("<!DOCTYPE")
        || trimmed_start.starts_with("<!doctype")
        || trimmed_start.starts_with("<html");

    match kind {
        ProbeKind::SecurityTxt => {
            if !is_html
                && text
                    .lines()
                    .any(|l| l.trim_start().to_ascii_lowercase().starts_with("contact:"))
            {
                Some(Finding {
                    id: "EXP-SECURITY-TXT-OK".into(),
                    category: Category::ExposedFiles,
                    severity: Severity::Pass,
                    title: "Valid /.well-known/security.txt found".into(),
                    summary: "Security contact policy is published per RFC 9116.".into(),
                    evidence: Some(url.to_string()),
                    remediation: String::new(),
                    standard_ref: Some("RFC 9116".into()),
                    confidence: Confidence::High,
                })
            } else {
                None
            }
        }
        ProbeKind::RobotsTxt => {
            let lower = text.to_ascii_lowercase();
            if !is_html && (lower.contains("user-agent:") || lower.contains("disallow:")) {
                let sensitive_disallow: Vec<String> = text
                    .lines()
                    .filter_map(|l| {
                        let lt = l.trim();
                        if lt.to_ascii_lowercase().starts_with("disallow:") {
                            let val = lt[9..].trim().to_string();
                            let lv = val.to_ascii_lowercase();
                            if [
                                "/admin",
                                "/backup",
                                "/config",
                                "/db",
                                "/internal",
                                "/.git",
                                "/private",
                            ]
                            .iter()
                            .any(|kw| lv.contains(kw))
                            {
                                return Some(val);
                            }
                        }
                        None
                    })
                    .take(5)
                    .collect();

                if !sensitive_disallow.is_empty() {
                    Some(Finding {
                        id: "EXP-ROBOTS-SENSITIVE-HINTS".into(),
                        category: Category::ExposedFiles,
                        severity: Severity::Info,
                        title: "/robots.txt Disallow rules mention potentially sensitive paths".into(),
                        summary: "Disallow entries are public hints for crawlers and do not enforce access control.".into(),
                        evidence: Some(format!("{url} -> {}", sensitive_disallow.join(", "))),
                        remediation: "Ensure listed routes are protected by server-side authentication and authorization.".into(),
                        standard_ref: Some("OWASP WSTG-INFO-03".into()),
                        confidence: Confidence::High,
                    })
                } else {
                    Some(Finding {
                        id: "EXP-ROBOTS-TXT".into(),
                        category: Category::ExposedFiles,
                        severity: Severity::Info,
                        title: "/robots.txt is present".into(),
                        summary: "No obvious sensitive path hints found in Disallow rules.".into(),
                        evidence: Some(url.to_string()),
                        remediation: String::new(),
                        standard_ref: Some("OWASP WSTG-INFO-03".into()),
                        confidence: Confidence::High,
                    })
                }
            } else {
                None
            }
        }
        ProbeKind::GitHead => {
            let trimmed = text.trim();
            let looks_like_git = !is_html
                && (trimmed.starts_with("ref: refs/")
                    || (trimmed.len() == 40 && trimmed.chars().all(|c| c.is_ascii_hexdigit())));
            if looks_like_git {
                Some(Finding {
                    id: "EXP-GIT-EXPOSED".into(),
                    category: Category::ExposedFiles,
                    severity: Severity::Critical,
                    title: "Publicly exposed .git repository (/.git/HEAD)".into(),
                    summary: "An exposed .git directory allows anyone to reconstruct source code and commit history.".into(),
                    evidence: Some(format!("{url} -> {trimmed}")),
                    remediation: "Block access to dotfiles in your web server (e.g., `location ~ /\\. { deny all; }` in Nginx).".into(),
                    standard_ref: Some("OWASP ASVS V14.3 / WSTG-CONF-04".into()),
                    confidence: Confidence::High,
                })
            } else {
                None
            }
        }
        ProbeKind::GitConfig => {
            if !is_html
                && text.contains("[core]")
                && (text.contains("repositoryformatversion") || text.contains("[remote"))
            {
                Some(Finding {
                    id: "EXP-GIT-CONFIG".into(),
                    category: Category::ExposedFiles,
                    severity: Severity::Critical,
                    title: "Publicly exposed /.git/config".into(),
                    summary:
                        ".git/config may disclose repository remotes and embedded credentials."
                            .into(),
                    evidence: Some(url.to_string()),
                    remediation: "Deny access to /.git/ in web server configuration.".into(),
                    standard_ref: Some("OWASP ASVS V14.3 / WSTG-CONF-04".into()),
                    confidence: Confidence::High,
                })
            } else {
                None
            }
        }
        ProbeKind::SvnEntries => {
            if !is_html
                && (text.contains("svn://")
                    || text.starts_with("10\n")
                    || text.starts_with("12\n")
                    || text.contains("dir\n"))
            {
                Some(Finding {
                    id: "EXP-SVN-EXPOSED".into(),
                    category: Category::ExposedFiles,
                    severity: Severity::Critical,
                    title: "Exposed Subversion metadata (/.svn/entries)".into(),
                    summary:
                        "An exposed .svn directory can leak repository layout and source files."
                            .into(),
                    evidence: Some(url.to_string()),
                    remediation: "Block /.svn/ in web server rules.".into(),
                    standard_ref: Some("OWASP WSTG-CONF-04".into()),
                    confidence: Confidence::High,
                })
            } else {
                None
            }
        }
        ProbeKind::SvnWcDb => {
            if bytes.starts_with(b"SQLite format 3\0") {
                Some(Finding {
                    id: "EXP-SVN-WC-DB".into(),
                    category: Category::ExposedFiles,
                    severity: Severity::Critical,
                    title: "Exposed Subversion database (/.svn/wc.db)".into(),
                    summary: "wc.db contains the working copy file index of the repository.".into(),
                    evidence: Some(url.to_string()),
                    remediation: "Block access to dotfiles on the web server.".into(),
                    standard_ref: Some("OWASP WSTG-CONF-04".into()),
                    confidence: Confidence::High,
                })
            } else {
                None
            }
        }
        ProbeKind::HgRequires => {
            if !is_html && text.contains("revlogv1") {
                Some(Finding {
                    id: "EXP-HG-EXPOSED".into(),
                    category: Category::ExposedFiles,
                    severity: Severity::Critical,
                    title: "Exposed Mercurial repository (/.hg/requires)".into(),
                    summary: "An exposed .hg directory may allow source code disclosure.".into(),
                    evidence: Some(url.to_string()),
                    remediation: "Block /.hg/ in web server configuration.".into(),
                    standard_ref: Some("OWASP WSTG-CONF-04".into()),
                    confidence: Confidence::High,
                })
            } else {
                None
            }
        }
        ProbeKind::DotEnv => {
            if !is_html && looks_like_env_file(text) {
                Some(Finding {
                    id: format!("EXP-ENV-{}", path.trim_start_matches('/').replace('.', "_").to_ascii_uppercase()),
                    category: Category::ExposedFiles,
                    severity: Severity::Critical,
                    title: format!("Publicly exposed configuration file {path}"),
                    summary: ".env files commonly store database credentials, API keys, and application secrets.".into(),
                    evidence: Some(url.to_string()),
                    remediation: "Block access immediately, move the file outside webroot, and rotate any exposed secrets.".into(),
                    standard_ref: Some("OWASP ASVS V14.3 / WSTG-CONF-05".into()),
                    confidence: Confidence::High,
                })
            } else {
                None
            }
        }
        ProbeKind::DsStore => {
            if bytes.len() >= 8 && &bytes[..8] == b"\x00\x00\x00\x01Bud1" {
                Some(Finding {
                    id: "EXP-DS-STORE".into(),
                    category: Category::ExposedFiles,
                    severity: Severity::Low,
                    title: "Publicly exposed /.DS_Store metadata file".into(),
                    summary: "macOS .DS_Store files can leak directory and file names.".into(),
                    evidence: Some(url.to_string()),
                    remediation:
                        "Exclude .DS_Store from deployments and block dotfiles on the web server."
                            .into(),
                    standard_ref: Some("OWASP WSTG-CONF-05".into()),
                    confidence: Confidence::High,
                })
            } else {
                None
            }
        }
        ProbeKind::PhpInfo => {
            if text.contains("PHP Version") && text.contains("phpinfo()") {
                Some(Finding {
                    id: "EXP-PHPINFO".into(),
                    category: Category::ExposedFiles,
                    severity: Severity::High,
                    title: "Debug page phpinfo.php is exposed".into(),
                    summary: "phpinfo() reveals environment variables, PHP modules, and server filesystem paths.".into(),
                    evidence: Some(url.to_string()),
                    remediation: "Remove phpinfo.php from production servers.".into(),
                    standard_ref: Some("OWASP ASVS V14.3 / WSTG-INFO-08".into()),
                    confidence: Confidence::High,
                })
            } else {
                None
            }
        }
        ProbeKind::ServerStatus => {
            if text.contains("Apache Server Status") {
                Some(Finding {
                    id: "EXP-SERVER-STATUS".into(),
                    category: Category::ExposedFiles,
                    severity: Severity::Medium,
                    title: format!("Server status page {path} is publicly accessible"),
                    summary: "The server-status page exposes active requests, client IPs, and internal URLs.".into(),
                    evidence: Some(url.to_string()),
                    remediation: "Restrict /server-status to localhost or internal management IPs.".into(),
                    standard_ref: Some("OWASP WSTG-CONF-05".into()),
                    confidence: Confidence::High,
                })
            } else {
                None
            }
        }
        ProbeKind::DockerCompose => {
            if !is_html
                && text.contains("services:")
                && (text.contains("image:") || text.contains("build:") || text.contains("ports:"))
            {
                Some(Finding {
                    id: "EXP-DOCKER-COMPOSE".into(),
                    category: Category::ExposedFiles,
                    severity: Severity::High,
                    title: format!("Publicly exposed {path} infrastructure file"),
                    summary: "Docker Compose manifests reveal service topology, internal ports, and often environment variables.".into(),
                    evidence: Some(url.to_string()),
                    remediation: "Move compose manifests outside the public webroot.".into(),
                    standard_ref: Some("OWASP ASVS V14.3 / WSTG-CONF-05".into()),
                    confidence: Confidence::High,
                })
            } else {
                None
            }
        }
        ProbeKind::PackageJson => {
            if !is_html {
                if let Ok(val) = serde_json::from_str::<serde_json::Value>(text) {
                    if val.get("name").is_some()
                        && (val.get("dependencies").is_some()
                            || val.get("devDependencies").is_some()
                            || val.get("scripts").is_some())
                    {
                        return Some(Finding {
                            id: "EXP-PACKAGE-JSON".into(),
                            category: Category::ExposedFiles,
                            severity: Severity::Low,
                            title: "Publicly exposed /package.json".into(),
                            summary:
                                "Discloses exact Node.js / frontend dependency names and versions."
                                    .into(),
                            evidence: Some(url.to_string()),
                            remediation: "Exclude package.json from the public static webroot."
                                .into(),
                            standard_ref: Some("OWASP WSTG-CONF-05".into()),
                            confidence: Confidence::High,
                        });
                    }
                }
            }
            None
        }
        ProbeKind::ComposerJson => {
            if !is_html {
                if let Ok(val) = serde_json::from_str::<serde_json::Value>(text) {
                    if val.get("require").is_some() || val.get("require-dev").is_some() {
                        return Some(Finding {
                            id: "EXP-COMPOSER-JSON".into(),
                            category: Category::ExposedFiles,
                            severity: Severity::Low,
                            title: "Publicly exposed /composer.json".into(),
                            summary:
                                "Discloses PHP runtime constraints and backend library versions."
                                    .into(),
                            evidence: Some(url.to_string()),
                            remediation:
                                "Serve from `public/` and block direct access to composer.json."
                                    .into(),
                            standard_ref: Some("OWASP WSTG-CONF-05".into()),
                            confidence: Confidence::High,
                        });
                    }
                }
            }
            None
        }
        ProbeKind::OpenApiJson => {
            if !is_html {
                if let Ok(val) = serde_json::from_str::<serde_json::Value>(text) {
                    if val.get("openapi").is_some() || val.get("swagger").is_some() {
                        return Some(Finding {
                            id: "EXP-OPENAPI-PUBLIC".into(),
                            category: Category::ExposedFiles,
                            severity: Severity::Info,
                            title: format!("OpenAPI/Swagger specification is publicly accessible ({path})"),
                            summary: "Normal for public APIs; for private/internal APIs, restrict specification access.".into(),
                            evidence: Some(url.to_string()),
                            remediation: "Restrict Swagger/OpenAPI endpoints in production unless intentionally public.".into(),
                            standard_ref: Some("OWASP WSTG-INFO".into()),
                            confidence: Confidence::High,
                        });
                    }
                }
            }
            None
        }
        ProbeKind::SwaggerUi => {
            if text.contains("SwaggerUIBundle") || text.contains("swagger-ui") {
                Some(Finding {
                    id: "EXP-SWAGGER-UI".into(),
                    category: Category::ExposedFiles,
                    severity: Severity::Info,
                    title: "Swagger UI is publicly accessible".into(),
                    summary: "Verify interactive API documentation is intentionally public.".into(),
                    evidence: Some(url.to_string()),
                    remediation: "Disable or protect Swagger UI in production if not intended for public use.".into(),
                    standard_ref: Some("OWASP WSTG-INFO".into()),
                    confidence: Confidence::Medium,
                })
            } else {
                None
            }
        }
        ProbeKind::DirListing => {
            if text.contains("<title>Index of /") || text.contains("<h1>Index of /") {
                Some(Finding {
                    id: format!("EXP-DIR-LISTING-{}", path.trim_matches('/').to_ascii_uppercase()),
                    category: Category::ExposedFiles,
                    severity: Severity::Medium,
                    title: format!("Directory listing enabled at {path}"),
                    summary: "Directory indexing exposes file inventories and potentially forgotten assets.".into(),
                    evidence: Some(url.to_string()),
                    remediation: "Disable directory indexing (`autoindex off;` in Nginx or `Options -Indexes` in Apache).".into(),
                    standard_ref: Some("OWASP ASVS V14.3 / WSTG-CONF-04".into()),
                    confidence: Confidence::High,
                })
            } else {
                None
            }
        }
    }
}

fn looks_like_env_file(text: &str) -> bool {
    let mut kv_lines = 0usize;
    for line in text.lines().take(40) {
        let trimmed = line.trim();
        if trimmed.is_empty() || trimmed.starts_with('#') {
            continue;
        }
        if let Some((k, _)) = trimmed.split_once('=') {
            let key = k.trim();
            if !key.is_empty()
                && key.len() <= 64
                && key
                    .chars()
                    .all(|c| c.is_ascii_uppercase() || c.is_ascii_digit() || c == '_')
            {
                kv_lines += 1;
            }
        }
    }
    kv_lines >= 2
}

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

    #[test]
    fn env_signature_rejects_html_and_accepts_dotenv() {
        assert!(looks_like_env_file(
            "APP_ENV=production\nDB_HOST=127.0.0.1\n"
        ));
        assert!(!looks_like_env_file(
            "<html><body>hello=world</body></html>"
        ));
    }

    #[test]
    fn git_head_rejects_spa_html_fallback() {
        let url = Url::parse("https://example.test/.git/HEAD").unwrap();
        let spa_html = b"<!DOCTYPE html><html><body>ref: refs/heads/main</body></html>";
        assert!(evaluate_probe(
            ProbeKind::GitHead,
            "/.git/HEAD",
            &url,
            "text/html",
            spa_html
        )
        .is_none());

        let real_git = b"ref: refs/heads/main\n";
        let f = evaluate_probe(
            ProbeKind::GitHead,
            "/.git/HEAD",
            &url,
            "text/plain",
            real_git,
        );
        assert!(f.is_some());
        assert_eq!(f.unwrap().severity, Severity::Critical);
    }

    #[test]
    fn detects_directory_listing_and_package_json() {
        let dir_url = Url::parse("https://example.test/uploads/").unwrap();
        let dir_body = b"<html><head><title>Index of /uploads/</title></head><body></body></html>";
        let df = evaluate_probe(
            ProbeKind::DirListing,
            "/uploads/",
            &dir_url,
            "text/html",
            dir_body,
        );
        assert!(df.is_some());
        assert_eq!(df.unwrap().severity, Severity::Medium);

        let pkg_url = Url::parse("https://example.test/package.json").unwrap();
        let pkg_body = br#"{"name":"my-app","dependencies":{"react":"18.2.0"}}"#;
        let pf = evaluate_probe(
            ProbeKind::PackageJson,
            "/package.json",
            &pkg_url,
            "application/json",
            pkg_body,
        );
        assert!(pf.is_some());
        assert_eq!(pf.unwrap().id, "EXP-PACKAGE-JSON");
    }
}