pub mod cookies;
pub mod cors;
pub mod crawler;
pub mod dns;
pub mod exposure;
pub mod headers;
pub mod html;
pub mod methods;
pub mod response_audit;
pub mod tls;
use std::collections::{HashMap, HashSet, VecDeque};
use std::sync::atomic::AtomicBool;
use std::sync::Arc;
use std::time::Instant;
use chrono::Utc;
use reqwest::header::CONTENT_TYPE;
use reqwest::Method;
use url::Url;
use crate::advisories;
use crate::models::{
compute_fingerprint, Category, CheckOutcome, Confidence, CoverageSummary, ExecutionStatus,
Finding, FindingInstance, ScanConfig, ScanProfile, ScanReport, Severity, SeverityCounts,
Verdict, SCHEMA_VERSION,
};
use crate::openapi;
use crate::rules;
use crate::scoring::compute_score_with_breakdown;
use crate::transport::{AuthMode, HttpTransport, SecretRedactor, TransportError};
pub fn normalize_target(raw: &str) -> anyhow::Result<Url> {
let trimmed = raw.trim();
if trimmed.is_empty() {
anyhow::bail!("empty target URL");
}
let with_scheme = if trimmed.starts_with("http://") || trimmed.starts_with("https://") {
trimmed.to_string()
} else {
format!("https://{trimmed}")
};
let url = Url::parse(&with_scheme)?;
if url.host_str().is_none() {
anyhow::bail!("target URL has no host: {raw}");
}
Ok(url)
}
pub fn parse_header_pair(raw: &str) -> anyhow::Result<(String, String)> {
let Some((name, val)) = raw.split_once(':') else {
anyhow::bail!("Header must be in 'Name: Value' format: {raw}");
};
let name = name.trim();
let val = val.trim();
if name.is_empty() {
anyhow::bail!("Empty header name in: {raw}");
}
Ok((name.to_string(), val.to_string()))
}
fn is_web_only_finding(id: &str) -> bool {
const WEB_ONLY_IDS: &[&str] = &[
"HDR-CSP-MISSING",
"HDR-CSP-WEAK",
"HDR-XFO-MISSING",
"HDR-XFO-INVALID",
"HDR-PERMISSIONS-MISSING",
"HDR-COOP-INFO",
"HTML-TARGET-BLANK",
];
WEB_ONLY_IDS.contains(&id)
}
fn merge_findings(all: Vec<Finding>) -> Vec<Finding> {
let mut order: Vec<String> = Vec::new();
let mut map: HashMap<String, (Finding, Vec<String>)> = HashMap::new();
for f in all {
if let Some((existing, evidences)) = map.get_mut(&f.id) {
if f.severity.rank() > existing.severity.rank() {
existing.severity = f.severity;
}
if let Some(ev) = f.evidence {
if !ev.is_empty() && !evidences.contains(&ev) && evidences.len() < 4 {
evidences.push(ev);
}
}
} else {
let mut evidences = Vec::new();
if let Some(ev) = &f.evidence {
if !ev.is_empty() {
evidences.push(ev.clone());
}
}
order.push(f.id.clone());
map.insert(f.id.clone(), (f, evidences));
}
}
let mut merged = Vec::with_capacity(order.len());
for id in order {
if let Some((mut f, evidences)) = map.remove(&id) {
if !evidences.is_empty() {
f.evidence = Some(evidences.join(" | "));
}
merged.push(f);
}
}
merged
}
fn filter_findings_for_profile(
findings: &mut Vec<Finding>,
instances: &mut Vec<FindingInstance>,
profile: ScanProfile,
) {
if profile != ScanProfile::Api {
return;
}
findings.retain(|f| !is_web_only_finding(&f.id));
instances.retain(|inst| !is_web_only_finding(&inst.finding_id));
}
#[allow(clippy::too_many_arguments)]
fn collect_findings(
raw_findings: &mut Vec<Finding>,
instances: &mut Vec<FindingInstance>,
seen_fps: &mut HashSet<String>,
target: &str,
location: &str,
auth_context: &str,
redactor: &SecretRedactor,
batch: Vec<Finding>,
) {
let safe_location = redactor.sanitize_text(location);
for mut f in batch {
f.summary = redactor.sanitize_text(&f.summary);
f.evidence = f.evidence.map(|e| redactor.sanitize_text(&e));
if f.severity != Severity::Pass {
let fp = compute_fingerprint(&f.id, target, &safe_location, auth_context);
if seen_fps.insert(fp.clone()) {
instances.push(FindingInstance {
fingerprint: fp,
finding_id: f.id.clone(),
category: f.category,
severity: f.severity,
confidence: f.confidence,
location: safe_location.clone(),
auth_context: auth_context.to_string(),
title: f.title.clone(),
summary: f.summary.clone(),
evidence: f.evidence.clone(),
remediation: f.remediation.clone(),
standard_ref: f.standard_ref.clone(),
});
}
}
raw_findings.push(f);
}
}
fn has_issue(batch: &[Finding]) -> bool {
batch.iter().any(|f| f.severity != Severity::Pass)
}
async fn inspect_js_bundles(
transport: &HttpTransport,
script_urls: &[Url],
custom_advisories: &[advisories::AdvisoryEntry],
auth_context: &str,
) -> (Vec<Finding>, Vec<Url>, CheckOutcome) {
let mut findings = Vec::new();
let mut discovered_routes = Vec::new();
let mut checked = 0usize;
for js_url in script_urls.iter().take(6) {
if transport.is_cancelled() {
return (
findings,
discovered_routes,
CheckOutcome {
check_id: "js-bundle-discovery".into(),
category: Category::ClientHtml,
location: transport.redactor.sanitize_url(js_url),
auth_context: auth_context.to_string(),
status: ExecutionStatus::Cancelled,
verdict: Verdict::Inconclusive,
reason: Some("Scan cancelled during JS bundle inspection".into()),
},
);
}
let resp = match transport
.send(
Method::GET,
js_url,
AuthMode::TargetOrigin,
&[],
Some(256 * 1024),
)
.await
{
Ok(r) if r.status < 400 => r,
Ok(_) => continue,
Err(TransportError::Cancelled) | Err(TransportError::BudgetExhausted(_)) => break,
Err(_) => continue,
};
checked += 1;
let Ok(js_text) = std::str::from_utf8(&resp.body) else {
continue;
};
findings.extend(response_audit::analyze_response_leaks(
&resp.headers,
js_text,
&resp.final_url,
));
for adv in advisories::match_advisories(js_text, custom_advisories) {
findings.push(Finding {
id: format!("COMP-OUTDATED-{}", adv.id_suffix),
category: Category::ClientHtml,
severity: adv.severity,
title: format!(
"Outdated client-side library detected in JS bundle: {} {}",
adv.package, adv.detected_version
),
summary: format!(
"Version {} matched inside script content ({}). {}",
adv.detected_version, adv.advisory_id, adv.summary
),
evidence: Some(transport.redactor.sanitize_url(&resp.final_url)),
remediation: format!(
"Upgrade {} to a supported version ({}).",
adv.package, adv.fixed_in
),
standard_ref: Some("OWASP ASVS V14.2.1".into()),
confidence: Confidence::Medium,
});
}
let (sourcemap_opt, routes) =
response_audit::extract_js_routes_and_sourcemap(js_text, &resp.final_url);
discovered_routes.extend(routes);
if let Some(map_url) = sourcemap_opt {
if !transport.is_cancelled() {
if let Ok(map_resp) = transport
.send(
Method::GET,
&map_url,
AuthMode::Anonymous,
&[],
Some(65_536),
)
.await
{
if map_resp.status == 200 {
let map_txt = String::from_utf8_lossy(&map_resp.body);
if map_txt.contains("\"mappings\"") || map_txt.contains("\"sources\"") {
findings.push(Finding {
id: "INFO-SOURCEMAP-EXPOSED".into(),
category: Category::InformationDisclosure,
severity: Severity::Medium,
title: "Production JavaScript SourceMap (.map) is publicly accessible".into(),
summary: "Exposed `.js.map` files allow reconstructing original TypeScript/JSX client source code, comments, and routes.".into(),
evidence: Some(transport.redactor.sanitize_url(&map_resp.final_url)),
remediation: "Do not deploy `.map` files to public web roots, or restrict access to internal error-tracking tools.".into(),
standard_ref: Some("OWASP WSTG-INFO-05".into()),
confidence: Confidence::High,
});
}
}
}
}
}
}
let outcome = CheckOutcome {
check_id: "js-bundle-discovery".into(),
category: Category::ClientHtml,
location: script_urls
.first()
.map(|u| transport.redactor.sanitize_url(u))
.unwrap_or_else(|| "none".into()),
auth_context: auth_context.to_string(),
status: ExecutionStatus::Completed,
verdict: if checked == 0 {
Verdict::NotApplicable
} else if has_issue(&findings) {
Verdict::Fail
} else {
Verdict::Pass
},
reason: Some(format!(
"inspected {checked} bundle(s), discovered {} route(s)",
discovered_routes.len()
)),
};
(findings, discovered_routes, outcome)
}
async fn check_unauth_route_parity(
transport: &HttpTransport,
authed_routes: &[(Url, usize)],
auth_context: &str,
) -> (Vec<Finding>, CheckOutcome) {
let mut findings = Vec::new();
let mut checked = 0usize;
for (route_url, authed_len) in authed_routes.iter().take(6) {
let p = route_url.path().to_ascii_lowercase();
if p == "/"
|| p.contains("login")
|| p.contains("signin")
|| p.contains("health")
|| p.contains("/assets")
|| p.contains("/static")
|| *authed_len == 0
{
continue;
}
if transport.is_cancelled() {
return (
findings,
CheckOutcome {
check_id: "unauth-route-access".into(),
category: Category::ApiSecurity,
location: transport.redactor.sanitize_url(route_url),
auth_context: auth_context.to_string(),
status: ExecutionStatus::Cancelled,
verdict: Verdict::Inconclusive,
reason: Some("Scan cancelled before parity check".into()),
},
);
}
let Ok(anon_resp) = transport
.send(
Method::GET,
route_url,
AuthMode::Anonymous,
&[],
Some(65_536),
)
.await
else {
continue;
};
checked += 1;
if anon_resp.status == 200 && !anon_resp.body.is_empty() {
let anon_len = anon_resp.body.len();
let min_expected = (*authed_len * 8) / 10;
let anon_path = anon_resp.final_url.path().to_ascii_lowercase();
if anon_len >= min_expected && !anon_path.contains("login") {
findings.push(Finding {
id: "AUTH-PUBLIC-WHEN-AUTHED".into(),
category: Category::ApiSecurity,
severity: Severity::Medium,
title: format!("Route accessible without auth headers: {}", route_url.path()),
summary: "This non-root route returned an almost identical HTTP 200 payload anonymously as it did with custom auth headers. Verify whether unauthenticated access is intentional.".into(),
evidence: Some(format!(
"{} (authed: {} B, anon: {} B)",
transport.redactor.sanitize_url(route_url),
authed_len,
anon_len
)),
remediation: "Ensure protected routes enforce server-side session/token authentication and return 401/403 anonymously.".into(),
standard_ref: Some("OWASP ASVS V4.1.1 / WSTG-ATHZ".into()),
confidence: Confidence::Low,
});
}
}
}
let outcome = CheckOutcome {
check_id: "unauth-route-access".into(),
category: Category::ApiSecurity,
location: authed_routes
.first()
.map(|(u, _)| transport.redactor.sanitize_url(u))
.unwrap_or_else(|| "none".into()),
auth_context: auth_context.to_string(),
status: ExecutionStatus::Completed,
verdict: if checked == 0 {
Verdict::NotApplicable
} else if has_issue(&findings) {
Verdict::Fail
} else {
Verdict::Pass
},
reason: Some(format!("checked {checked} route(s) without credentials")),
};
(findings, outcome)
}
pub async fn scan_target(raw_target: &str, config: &ScanConfig) -> ScanReport {
scan_target_with_cancel(raw_target, config, Arc::new(AtomicBool::new(false))).await
}
pub async fn scan_target_with_cancel(
raw_target: &str,
config: &ScanConfig,
cancel_flag: Arc<AtomicBool>,
) -> ScanReport {
let started = Instant::now();
let scanned_at = Utc::now().to_rfc3339();
let auth_context = config.auth_context.clone();
let redactor = SecretRedactor::new(&config.auth_headers);
let url = match normalize_target(raw_target) {
Ok(u) => u,
Err(e) => {
let finding = Finding {
id: "TARGET-INVALID".into(),
category: Category::Availability,
severity: Severity::Critical,
title: "Invalid target URL".into(),
summary: redactor.sanitize_text(&e.to_string()),
evidence: Some(redactor.sanitize_text(raw_target)),
remediation: "Provide a valid URL or domain, e.g. https://example.com.".into(),
standard_ref: None,
confidence: Confidence::High,
};
let fp = compute_fingerprint(&finding.id, raw_target, raw_target, &auth_context);
let instances = vec![FindingInstance {
fingerprint: fp,
finding_id: finding.id.clone(),
category: finding.category,
severity: finding.severity,
confidence: finding.confidence,
location: raw_target.to_string(),
auth_context: auth_context.clone(),
title: finding.title.clone(),
summary: finding.summary.clone(),
evidence: finding.evidence.clone(),
remediation: finding.remediation.clone(),
standard_ref: finding.standard_ref.clone(),
}];
let findings = vec![finding];
let outcomes = vec![CheckOutcome {
check_id: "target-normalization".into(),
category: Category::Availability,
location: raw_target.to_string(),
auth_context: auth_context.clone(),
status: ExecutionStatus::Error,
verdict: Verdict::Inconclusive,
reason: Some(e.to_string()),
}];
let (score, grade, score_breakdown) = compute_score_with_breakdown(&findings);
let counts = SeverityCounts::from_findings(&findings);
let coverage = CoverageSummary::from_outcomes(&outcomes, false);
return ScanReport {
schema_version: SCHEMA_VERSION.to_string(),
engine_version: env!("CARGO_PKG_VERSION").to_string(),
target: raw_target.to_string(),
final_url: raw_target.to_string(),
scanned_at,
duration_ms: started.elapsed().as_millis(),
status_code: None,
profile: config.profile,
auth_context,
run_status: ExecutionStatus::Error,
cancelled: false,
pages_scanned: 0,
crawled_urls: Vec::new(),
score,
grade,
score_breakdown,
coverage,
outcomes,
instances,
tls: None,
findings,
counts,
};
}
};
let transport = Arc::new(HttpTransport::new(
url.clone(),
config.timeout_secs,
config.concurrency,
config.max_requests,
config.max_body_bytes,
config.user_agent.clone(),
config.auth_headers.clone(),
Arc::clone(&cancel_flag),
));
let mut raw_findings = Vec::new();
let mut instances = Vec::new();
let mut seen_fps = HashSet::new();
let mut outcomes = Vec::new();
let (tls_info, tls_findings, tls_outcome) =
tls::inspect_tls(&url, config.timeout_secs, &auth_context).await;
collect_findings(
&mut raw_findings,
&mut instances,
&mut seen_fps,
raw_target,
url.as_str(),
&auth_context,
&transport.redactor,
tls_findings,
);
outcomes.push(tls_outcome);
if config.check_legacy_tls && !transport.is_cancelled() {
let (legacy_findings, legacy_outcome) =
tls::probe_legacy_tls_versions(&url, config.timeout_secs, &auth_context).await;
collect_findings(
&mut raw_findings,
&mut instances,
&mut seen_fps,
raw_target,
url.as_str(),
&auth_context,
&transport.redactor,
legacy_findings,
);
outcomes.push(legacy_outcome);
}
let (redir_finding, redir_outcome) = tls::check_http_redirect(&url, &auth_context).await;
if let Some(rf) = redir_finding {
collect_findings(
&mut raw_findings,
&mut instances,
&mut seen_fps,
raw_target,
url.as_str(),
&auth_context,
&transport.redactor,
vec![rf],
);
}
outcomes.push(redir_outcome);
if config.skip_dns {
outcomes.push(CheckOutcome {
check_id: "dns-hygiene".into(),
category: Category::DnsEmail,
location: url.host_str().unwrap_or("").to_string(),
auth_context: auth_context.clone(),
status: ExecutionStatus::Skipped,
verdict: Verdict::Inconclusive,
reason: Some("Skipped via --skip-dns".into()),
});
} else if transport.is_cancelled() {
outcomes.push(CheckOutcome {
check_id: "dns-hygiene".into(),
category: Category::DnsEmail,
location: url.host_str().unwrap_or("").to_string(),
auth_context: auth_context.clone(),
status: ExecutionStatus::Cancelled,
verdict: Verdict::Inconclusive,
reason: Some("Scan cancelled before DNS check".into()),
});
} else {
let (dns_findings, dns_outcomes) = dns::check_dns_hygiene(&url, &auth_context).await;
collect_findings(
&mut raw_findings,
&mut instances,
&mut seen_fps,
raw_target,
url.host_str().unwrap_or(url.as_str()),
&auth_context,
&transport.redactor,
dns_findings,
);
outcomes.extend(dns_outcomes);
}
let mut final_url = url.clone();
let mut status_code = None;
let mut crawled_urls = Vec::new();
let max_pages = config.max_pages.max(1);
let mut run_status = if transport.is_cancelled() {
ExecutionStatus::Cancelled
} else {
ExecutionStatus::Completed
};
if transport.is_cancelled() {
outcomes.push(CheckOutcome {
check_id: "primary-http-fetch".into(),
category: Category::Availability,
location: transport.redactor.sanitize_url(&url),
auth_context: auth_context.clone(),
status: ExecutionStatus::Cancelled,
verdict: Verdict::Inconclusive,
reason: Some("Scan cancelled before primary HTTP fetch".into()),
});
} else {
match transport
.send(Method::GET, &url, AuthMode::TargetOrigin, &[], None)
.await
{
Ok(resp) => {
final_url = resp.final_url.clone();
status_code = Some(resp.status);
crawled_urls.push(transport.redactor.sanitize_url(&final_url));
outcomes.push(CheckOutcome {
check_id: "primary-http-fetch".into(),
category: Category::Availability,
location: transport.redactor.sanitize_url(&final_url),
auth_context: auth_context.clone(),
status: ExecutionStatus::Completed,
verdict: Verdict::Pass,
reason: Some(format!("HTTP {}", resp.status)),
});
let resp_headers = resp.headers.clone();
let is_https = final_url.scheme() == "https";
let content_type = resp_headers
.get(CONTENT_TYPE)
.and_then(|v| v.to_str().ok())
.unwrap_or("")
.to_ascii_lowercase();
if url.scheme() == "http" && is_https {
collect_findings(
&mut raw_findings,
&mut instances,
&mut seen_fps,
raw_target,
final_url.as_str(),
&auth_context,
&transport.redactor,
vec![Finding {
id: "TLS-UPGRADED-HTTPS".into(),
category: Category::TransportTls,
severity: Severity::Pass,
title: "HTTP automatically upgraded to HTTPS".into(),
summary: format!("Final URL: {final_url}."),
evidence: Some(final_url.to_string()),
remediation: String::new(),
standard_ref: Some("OWASP ASVS V9.1.1".into()),
confidence: Confidence::High,
}],
);
raw_findings.retain(|f| f.id != "TLS-NO-HTTPS");
instances.retain(|i| i.finding_id != "TLS-NO-HTTPS");
}
let hdr_batch = headers::analyze_headers(&resp_headers, is_https);
outcomes.push(CheckOutcome {
check_id: "security-headers".into(),
category: Category::SecurityHeaders,
location: transport.redactor.sanitize_url(&final_url),
auth_context: auth_context.clone(),
status: ExecutionStatus::Completed,
verdict: if has_issue(&hdr_batch) {
Verdict::Fail
} else {
Verdict::Pass
},
reason: None,
});
collect_findings(
&mut raw_findings,
&mut instances,
&mut seen_fps,
raw_target,
final_url.as_str(),
&auth_context,
&transport.redactor,
hdr_batch,
);
let cookie_batch = cookies::analyze_cookies(&resp_headers, is_https);
outcomes.push(CheckOutcome {
check_id: "cookie-attributes".into(),
category: Category::Cookies,
location: transport.redactor.sanitize_url(&final_url),
auth_context: auth_context.clone(),
status: ExecutionStatus::Completed,
verdict: if has_issue(&cookie_batch) {
Verdict::Fail
} else {
Verdict::Pass
},
reason: None,
});
collect_findings(
&mut raw_findings,
&mut instances,
&mut seen_fps,
raw_target,
final_url.as_str(),
&auth_context,
&transport.redactor,
cookie_batch,
);
let ((cors_findings, cors_outcome), (methods_findings, methods_outcome)) = tokio::join!(
cors::check_cors(&transport, &final_url, &resp_headers, &auth_context),
methods::check_http_methods(&transport, &final_url, &auth_context)
);
outcomes.push(cors_outcome);
outcomes.push(methods_outcome);
collect_findings(
&mut raw_findings,
&mut instances,
&mut seen_fps,
raw_target,
final_url.as_str(),
&auth_context,
&transport.redactor,
cors_findings,
);
collect_findings(
&mut raw_findings,
&mut instances,
&mut seen_fps,
raw_target,
final_url.as_str(),
&auth_context,
&transport.redactor,
methods_findings,
);
let mut discovered_links = Vec::new();
let mut root_has_password = false;
let mut root_text: Option<String> = None;
let mut script_urls_to_inspect = Vec::new();
let mut authed_ok_routes: Vec<(Url, usize)> = Vec::new();
if let Ok(text) = std::str::from_utf8(&resp.body) {
let leak_batch =
response_audit::analyze_response_leaks(&resp_headers, text, &final_url);
outcomes.push(CheckOutcome {
check_id: "response-secrets-leaks".into(),
category: Category::SecretsAndLeaks,
location: transport.redactor.sanitize_url(&final_url),
auth_context: auth_context.clone(),
status: ExecutionStatus::Completed,
verdict: if has_issue(&leak_batch) {
Verdict::Fail
} else {
Verdict::Pass
},
reason: None,
});
collect_findings(
&mut raw_findings,
&mut instances,
&mut seen_fps,
raw_target,
final_url.as_str(),
&auth_context,
&transport.redactor,
leak_batch,
);
if config.profile == ScanProfile::Api {
outcomes.push(CheckOutcome {
check_id: "html-client-hygiene".into(),
category: Category::ClientHtml,
location: transport.redactor.sanitize_url(&final_url),
auth_context: auth_context.clone(),
status: ExecutionStatus::Completed,
verdict: Verdict::NotApplicable,
reason: Some("Not applicable to API profile".into()),
});
} else if content_type.contains("text/html") || content_type.is_empty() {
root_has_password = html::has_password_input(text);
let html_batch = html::analyze_html_with_advisories(
text,
&final_url,
&config.custom_advisories,
);
outcomes.push(CheckOutcome {
check_id: "html-client-hygiene".into(),
category: Category::ClientHtml,
location: transport.redactor.sanitize_url(&final_url),
auth_context: auth_context.clone(),
status: ExecutionStatus::Completed,
verdict: if has_issue(&html_batch) {
Verdict::Fail
} else {
Verdict::Pass
},
reason: None,
});
collect_findings(
&mut raw_findings,
&mut instances,
&mut seen_fps,
raw_target,
final_url.as_str(),
&auth_context,
&transport.redactor,
html_batch,
);
script_urls_to_inspect =
html::extract_same_origin_script_urls(text, &final_url, 6);
if max_pages > 1 {
discovered_links =
crawler::extract_same_origin_links(text, &final_url, max_pages * 3);
}
}
root_text = Some(text.to_string());
}
if !script_urls_to_inspect.is_empty() && !transport.is_cancelled() {
let (js_findings, js_routes, js_outcome) = inspect_js_bundles(
&transport,
&script_urls_to_inspect,
&config.custom_advisories,
&auth_context,
)
.await;
outcomes.push(js_outcome);
collect_findings(
&mut raw_findings,
&mut instances,
&mut seen_fps,
raw_target,
final_url.as_str(),
&auth_context,
&transport.redactor,
js_findings,
);
if max_pages > 1 && config.profile == ScanProfile::Web {
discovered_links.extend(js_routes);
}
}
if !config.custom_rules.is_empty() {
let custom_batch = rules::evaluate_page_rules(
&config.custom_rules,
&resp_headers,
root_text.as_deref(),
&final_url,
);
collect_findings(
&mut raw_findings,
&mut instances,
&mut seen_fps,
raw_target,
final_url.as_str(),
&auth_context,
&transport.redactor,
custom_batch,
);
}
let cache_sensitive = root_has_password || config.profile == ScanProfile::Api;
if let Some(cache_f) =
headers::analyze_caching(&resp_headers, cache_sensitive, final_url.as_str())
{
outcomes.push(CheckOutcome {
check_id: "cache-control".into(),
category: Category::HttpProtocol,
location: transport.redactor.sanitize_url(&final_url),
auth_context: auth_context.clone(),
status: ExecutionStatus::Completed,
verdict: Verdict::Fail,
reason: None,
});
collect_findings(
&mut raw_findings,
&mut instances,
&mut seen_fps,
raw_target,
final_url.as_str(),
&auth_context,
&transport.redactor,
vec![cache_f],
);
} else {
outcomes.push(CheckOutcome {
check_id: "cache-control".into(),
category: Category::HttpProtocol,
location: transport.redactor.sanitize_url(&final_url),
auth_context: auth_context.clone(),
status: ExecutionStatus::Completed,
verdict: Verdict::Pass,
reason: None,
});
}
if max_pages > 1 && config.profile == ScanProfile::Web && !transport.is_cancelled()
{
let sitemap_links =
crawler::fetch_sitemap_urls(&transport, &final_url, max_pages).await;
let mut visited = HashSet::new();
visited.insert(final_url.as_str().to_string());
let mut queue = VecDeque::new();
for link in discovered_links.into_iter().chain(sitemap_links) {
let s = link.as_str().to_string();
if visited.insert(s) {
queue.push_back(link);
}
}
while crawled_urls.len() < max_pages {
if transport.is_cancelled() {
run_status = ExecutionStatus::Cancelled;
break;
}
let Some(next_url) = queue.pop_front() else {
break;
};
let page_resp = match transport
.send(Method::GET, &next_url, AuthMode::TargetOrigin, &[], None)
.await
{
Ok(r) => r,
Err(TransportError::Cancelled) => {
run_status = ExecutionStatus::Cancelled;
break;
}
Err(TransportError::BudgetExhausted(max_req)) => {
outcomes.push(CheckOutcome {
check_id: "crawl-budget".into(),
category: Category::Availability,
location: transport.redactor.sanitize_url(&next_url),
auth_context: auth_context.clone(),
status: ExecutionStatus::Error,
verdict: Verdict::Inconclusive,
reason: Some(format!("Request budget exhausted ({max_req})")),
});
break;
}
Err(_) => continue,
};
let page_final = page_resp.final_url.clone();
crawled_urls.push(transport.redactor.sanitize_url(&page_final));
let p_headers = page_resp.headers;
let p_https = page_final.scheme() == "https";
let p_ct = p_headers
.get(CONTENT_TYPE)
.and_then(|v| v.to_str().ok())
.unwrap_or("")
.to_ascii_lowercase();
collect_findings(
&mut raw_findings,
&mut instances,
&mut seen_fps,
raw_target,
page_final.as_str(),
&auth_context,
&transport.redactor,
headers::analyze_headers(&p_headers, p_https),
);
collect_findings(
&mut raw_findings,
&mut instances,
&mut seen_fps,
raw_target,
page_final.as_str(),
&auth_context,
&transport.redactor,
cookies::analyze_cookies(&p_headers, p_https),
);
let mut page_has_password = false;
let mut page_html: Option<String> = None;
if page_resp.status == 200 && authed_ok_routes.len() < 12 {
authed_ok_routes.push((page_final.clone(), page_resp.body.len()));
}
if let Ok(p_text) = std::str::from_utf8(&page_resp.body) {
collect_findings(
&mut raw_findings,
&mut instances,
&mut seen_fps,
raw_target,
page_final.as_str(),
&auth_context,
&transport.redactor,
response_audit::analyze_response_leaks(
&p_headers,
p_text,
&page_final,
),
);
if p_ct.contains("text/html") || p_ct.is_empty() {
page_has_password = html::has_password_input(p_text);
collect_findings(
&mut raw_findings,
&mut instances,
&mut seen_fps,
raw_target,
page_final.as_str(),
&auth_context,
&transport.redactor,
html::analyze_html_with_advisories(
p_text,
&page_final,
&config.custom_advisories,
),
);
if crawled_urls.len() + queue.len() < max_pages * 2 {
for sub in crawler::extract_same_origin_links(
p_text,
&page_final,
max_pages,
) {
if visited.insert(sub.as_str().to_string()) {
queue.push_back(sub);
}
}
}
page_html = Some(p_text.to_string());
}
}
if !config.custom_rules.is_empty() {
collect_findings(
&mut raw_findings,
&mut instances,
&mut seen_fps,
raw_target,
page_final.as_str(),
&auth_context,
&transport.redactor,
rules::evaluate_page_rules(
&config.custom_rules,
&p_headers,
page_html.as_deref(),
&page_final,
),
);
}
if let Some(cache_f) = headers::analyze_caching(
&p_headers,
page_has_password,
page_final.as_str(),
) {
collect_findings(
&mut raw_findings,
&mut instances,
&mut seen_fps,
raw_target,
page_final.as_str(),
&auth_context,
&transport.redactor,
vec![cache_f],
);
}
}
}
if config.skip_paths {
outcomes.push(CheckOutcome {
check_id: "exposed-artifacts".into(),
category: Category::ExposedFiles,
location: transport.redactor.sanitize_url(&final_url),
auth_context: auth_context.clone(),
status: ExecutionStatus::Skipped,
verdict: Verdict::Inconclusive,
reason: Some("Skipped via --skip-paths".into()),
});
} else if transport.is_cancelled() {
run_status = ExecutionStatus::Cancelled;
outcomes.push(CheckOutcome {
check_id: "exposed-artifacts".into(),
category: Category::ExposedFiles,
location: transport.redactor.sanitize_url(&final_url),
auth_context: auth_context.clone(),
status: ExecutionStatus::Cancelled,
verdict: Verdict::Inconclusive,
reason: Some("Scan cancelled before path checks".into()),
});
} else {
let (exp_findings, exp_outcomes) =
exposure::check_exposed_paths(&transport, &final_url, &auth_context).await;
collect_findings(
&mut raw_findings,
&mut instances,
&mut seen_fps,
raw_target,
final_url.as_str(),
&auth_context,
&transport.redactor,
exp_findings,
);
outcomes.extend(exp_outcomes);
if !config.custom_rules.is_empty() && !transport.is_cancelled() {
let (path_findings, path_outcomes) = rules::evaluate_path_rules(
&config.custom_rules,
&transport,
&final_url,
&auth_context,
)
.await;
collect_findings(
&mut raw_findings,
&mut instances,
&mut seen_fps,
raw_target,
final_url.as_str(),
&auth_context,
&transport.redactor,
path_findings,
);
outcomes.extend(path_outcomes);
}
}
if let Some(spec_src) = &config.openapi_path {
if !transport.is_cancelled() {
let (api_findings, api_outcomes) = openapi::run_openapi_audit(
spec_src,
&transport,
&final_url,
&auth_context,
)
.await;
collect_findings(
&mut raw_findings,
&mut instances,
&mut seen_fps,
raw_target,
final_url.as_str(),
&auth_context,
&transport.redactor,
api_findings,
);
outcomes.extend(api_outcomes);
}
}
if config.check_unauth_access
&& !config.auth_headers.is_empty()
&& !authed_ok_routes.is_empty()
&& !transport.is_cancelled()
{
let (parity_findings, parity_outcome) =
check_unauth_route_parity(&transport, &authed_ok_routes, &auth_context)
.await;
collect_findings(
&mut raw_findings,
&mut instances,
&mut seen_fps,
raw_target,
final_url.as_str(),
&auth_context,
&transport.redactor,
parity_findings,
);
outcomes.push(parity_outcome);
}
}
Err(TransportError::Cancelled) => {
run_status = ExecutionStatus::Cancelled;
outcomes.push(CheckOutcome {
check_id: "primary-http-fetch".into(),
category: Category::Availability,
location: transport.redactor.sanitize_url(&url),
auth_context: auth_context.clone(),
status: ExecutionStatus::Cancelled,
verdict: Verdict::Inconclusive,
reason: Some("Scan cancelled".into()),
});
}
Err(e) => {
let err_msg = transport.redactor.sanitize_text(&e.to_string());
run_status = ExecutionStatus::Error;
outcomes.push(CheckOutcome {
check_id: "primary-http-fetch".into(),
category: Category::Availability,
location: transport.redactor.sanitize_url(&url),
auth_context: auth_context.clone(),
status: ExecutionStatus::Error,
verdict: Verdict::Inconclusive,
reason: Some(err_msg.clone()),
});
collect_findings(
&mut raw_findings,
&mut instances,
&mut seen_fps,
raw_target,
url.as_str(),
&auth_context,
&transport.redactor,
vec![Finding {
id: "HTTP-FETCH-ERR".into(),
category: Category::Availability,
severity: Severity::High,
title: "Failed to fetch HTTP response".into(),
summary: format!("HTTP client failed to load {}: {err_msg}", transport.redactor.sanitize_url(&url)),
evidence: Some(err_msg),
remediation: "Check DNS resolution, server availability, TLS certificate chain, and firewall rules.".into(),
standard_ref: None,
confidence: Confidence::High,
}],
);
}
}
}
let cancelled = transport.is_cancelled() || run_status == ExecutionStatus::Cancelled;
if cancelled {
run_status = ExecutionStatus::Cancelled;
}
let mut findings = merge_findings(raw_findings);
filter_findings_for_profile(&mut findings, &mut instances, config.profile);
findings.sort_by_key(|a| std::cmp::Reverse(a.severity.rank()));
instances.sort_by_key(|a| std::cmp::Reverse(a.severity.rank()));
let (score, grade, score_breakdown) = compute_score_with_breakdown(&findings);
let counts = SeverityCounts::from_findings(&findings);
let coverage = CoverageSummary::from_outcomes(&outcomes, cancelled);
ScanReport {
schema_version: SCHEMA_VERSION.to_string(),
engine_version: env!("CARGO_PKG_VERSION").to_string(),
target: raw_target.to_string(),
final_url: transport.redactor.sanitize_url(&final_url),
scanned_at,
duration_ms: started.elapsed().as_millis(),
status_code,
profile: config.profile,
auth_context,
run_status,
cancelled,
pages_scanned: crawled_urls.len(),
crawled_urls,
score,
grade,
score_breakdown,
coverage,
outcomes,
instances,
tls: tls_info,
findings,
counts,
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn normalizes_bare_domain_to_https() {
let u = normalize_target("example.com").unwrap();
assert_eq!(u.as_str(), "https://example.com/");
}
#[test]
fn preserves_explicit_http_port() {
let u = normalize_target("http://127.0.0.1:8080/app").unwrap();
assert_eq!(u.scheme(), "http");
assert_eq!(u.port(), Some(8080));
}
#[test]
fn parses_auth_header_pair() {
let (k, v) = parse_header_pair("Authorization: Bearer abc.123").unwrap();
assert_eq!(k, "Authorization");
assert_eq!(v, "Bearer abc.123");
assert!(parse_header_pair("invalid-no-colon").is_err());
}
}