use std::collections::HashSet;
use reqwest::header::HeaderMap;
use url::Url;
use crate::models::{Category, Confidence, Finding, Severity};
fn mask_secret(raw: &str) -> String {
let trimmed = raw.trim();
let chars: Vec<char> = trimmed.chars().collect();
if chars.len() <= 8 {
return "[REDACTED_SECRET]".to_string();
}
let head: String = chars.iter().take(4).collect();
let tail: String = chars[chars.len() - 2..].iter().collect();
format!("{head}****{tail} (len={})", chars.len())
}
fn decode_base64url(input: &str) -> Option<Vec<u8>> {
let mut buf = Vec::with_capacity((input.len() * 3) / 4 + 3);
let mut acc: u32 = 0;
let mut bits: u8 = 0;
for b in input.bytes() {
let val = match b {
b'A'..=b'Z' => b - b'A',
b'a'..=b'z' => b - b'a' + 26,
b'0'..=b'9' => b - b'0' + 52,
b'-' | b'+' => 62,
b'_' | b'/' => 63,
b'=' => break,
_ => return None,
};
acc = (acc << 6) | u32::from(val);
bits += 6;
if bits >= 8 {
bits -= 8;
buf.push(((acc >> bits) & 0xff) as u8);
}
}
Some(buf)
}
fn find_prefixed_token<'a>(
text: &'a str,
prefix: &str,
min_tail_len: usize,
is_valid_char: fn(char) -> bool,
) -> Option<&'a str> {
let mut start = 0;
while let Some(rel) = text[start..].find(prefix) {
let idx = start + rel;
let tail = &text[idx + prefix.len()..];
let tail_len = tail
.char_indices()
.take_while(|(_, c)| is_valid_char(*c))
.last()
.map(|(i, c)| i + c.len_utf8())
.unwrap_or(0);
if tail_len >= min_tail_len {
let candidate = &text[idx..idx + prefix.len() + tail_len];
if !candidate.to_ascii_uppercase().contains("EXAMPLE")
&& !candidate.to_ascii_uppercase().contains("DUMMY")
&& !candidate.to_ascii_uppercase().contains("PLACEHOLDER")
{
return Some(candidate);
}
}
start = idx + prefix.len();
}
None
}
fn audit_secrets(body: &str, url: &Url) -> Vec<Finding> {
let mut findings = Vec::new();
let is_alnum = |c: char| c.is_ascii_alphanumeric();
let is_upper_alnum = |c: char| c.is_ascii_uppercase() || c.is_ascii_digit();
let is_token_char = |c: char| c.is_ascii_alphanumeric() || c == '_' || c == '-';
if let Some(tok) = find_prefixed_token(body, "AKIA", 16, is_upper_alnum) {
if tok.len() == 20 {
findings.push(Finding {
id: "LEAK-SECRET-AWS".into(),
category: Category::SecretsAndLeaks,
severity: Severity::Critical,
title: "Potential AWS Access Key ID exposed in response".into(),
summary: "An AWS Access Key ID pattern (`AKIA...`) was detected in HTTP response content.".into(),
evidence: Some(format!("{} at {}", mask_secret(tok), url)),
remediation: "Revoke the exposed IAM key immediately and remove secrets from responses/client bundles.".into(),
standard_ref: Some("OWASP ASVS V14.3 / WSTG-INFO".into()),
confidence: Confidence::High,
});
}
}
for gh_prefix in ["ghp_", "gho_", "ghu_", "ghs_", "github_pat_"] {
if let Some(tok) = find_prefixed_token(body, gh_prefix, 20, is_token_char) {
findings.push(Finding {
id: "LEAK-SECRET-GITHUB".into(),
category: Category::SecretsAndLeaks,
severity: Severity::Critical,
title: "Potential GitHub access token exposed in response".into(),
summary: format!("A GitHub token (`{gh_prefix}...`) was found in response content."),
evidence: Some(format!("{} at {}", mask_secret(tok), url)),
remediation: "Revoke the token in GitHub settings and inject credentials strictly on the server side.".into(),
standard_ref: Some("OWASP ASVS V2.10 / V14.3".into()),
confidence: Confidence::High,
});
break;
}
}
for stripe_prefix in ["sk_live_", "rk_live_"] {
if let Some(tok) = find_prefixed_token(body, stripe_prefix, 16, is_alnum) {
findings.push(Finding {
id: "LEAK-SECRET-STRIPE".into(),
category: Category::SecretsAndLeaks,
severity: Severity::Critical,
title: "Stripe live secret key exposed in response".into(),
summary: "A live Stripe secret/restricted key was detected in HTTP response content.".into(),
evidence: Some(format!("{} at {}", mask_secret(tok), url)),
remediation: "Roll the Stripe API key immediately and keep secret keys strictly on backend servers.".into(),
standard_ref: Some("OWASP ASVS V14.3".into()),
confidence: Confidence::High,
});
break;
}
}
for slack_prefix in ["xoxb-", "xoxp-", "xoxa-", "xoxr-"] {
if let Some(tok) = find_prefixed_token(body, slack_prefix, 16, is_token_char) {
findings.push(Finding {
id: "LEAK-SECRET-SLACK".into(),
category: Category::SecretsAndLeaks,
severity: Severity::Critical,
title: "Slack API token exposed in response".into(),
summary: "A Slack token pattern was found in HTTP response content.".into(),
evidence: Some(format!("{} at {}", mask_secret(tok), url)),
remediation: "Revoke the Slack app token and rotate workspace credentials.".into(),
standard_ref: Some("OWASP ASVS V14.3".into()),
confidence: Confidence::High,
});
break;
}
}
if let Some(tok) = find_prefixed_token(body, "AIza", 32, is_token_char) {
findings.push(Finding {
id: "LEAK-SECRET-GOOGLE-API".into(),
category: Category::SecretsAndLeaks,
severity: Severity::Medium,
title: "Google API key detected in response".into(),
summary: "A Google API key (`AIza...`) is embedded in response output. Verify referrer/API restrictions if intended to be public.".into(),
evidence: Some(format!("{} at {}", mask_secret(tok), url)),
remediation: "Restrict the key by HTTP referrer/IP and enabled APIs in Google Cloud Console, or move calls server-side.".into(),
standard_ref: Some("OWASP ASVS V14.3".into()),
confidence: Confidence::Medium,
});
}
for pem in [
"-----BEGIN RSA PRIVATE KEY-----",
"-----BEGIN EC PRIVATE KEY-----",
"-----BEGIN PRIVATE KEY-----",
"-----BEGIN OPENSSH PRIVATE KEY-----",
] {
if body.contains(pem) {
findings.push(Finding {
id: "LEAK-PRIVATE-KEY".into(),
category: Category::SecretsAndLeaks,
severity: Severity::Critical,
title: "Cryptographic private key material exposed in response".into(),
summary: format!("Detected PEM private key header `{pem}` in HTTP response."),
evidence: Some(format!("{pem} at {url}")),
remediation: "Revoke and replace the compromised key pair immediately and block access to key files.".into(),
standard_ref: Some("OWASP ASVS V6.4 / V14.3".into()),
confidence: Confidence::High,
});
break;
}
}
for scheme in [
"postgres://",
"postgresql://",
"mysql://",
"mongodb://",
"mongodb+srv://",
"redis://",
] {
if let Some(pos) = body.find(scheme) {
let tail = &body[pos..body.len().min(pos + 120)];
if let Some(at_pos) = tail.find('@') {
let auth_part = &tail[scheme.len()..at_pos];
if auth_part.contains(':') && !auth_part.contains(' ') {
findings.push(Finding {
id: "LEAK-DB-CONNECTION".into(),
category: Category::SecretsAndLeaks,
severity: Severity::Critical,
title: "Database connection string with credentials exposed".into(),
summary: format!("Detected a `{scheme}user:***@...` connection URI in response content."),
evidence: Some(format!("{scheme}[CREDENTIALS_REDACTED]@... at {url}")),
remediation: "Remove database credentials from HTTP responses/configs and rotate the database password.".into(),
standard_ref: Some("OWASP ASVS V2.10 / V14.3".into()),
confidence: Confidence::High,
});
break;
}
}
}
}
findings
}
fn audit_jwts(text: &str, url: &Url) -> Vec<Finding> {
let mut findings = Vec::new();
let mut search_from = 0usize;
let mut checked = 0usize;
while let Some(rel) = text[search_from..].find("eyJ") {
if checked >= 8 {
break;
}
let idx = search_from + rel;
search_from = idx + 3;
let token: String = text[idx..]
.chars()
.take_while(|c| c.is_ascii_alphanumeric() || *c == '_' || *c == '-' || *c == '.')
.collect();
let parts: Vec<&str> = token.split('.').collect();
if parts.len() != 3 || parts[0].len() < 8 || parts[1].len() < 8 {
continue;
}
let Some(hdr_bytes) = decode_base64url(parts[0]) else {
continue;
};
let Ok(hdr_json) = serde_json::from_slice::<serde_json::Value>(&hdr_bytes) else {
continue;
};
let Some(pay_bytes) = decode_base64url(parts[1]) else {
continue;
};
let Ok(pay_json) = serde_json::from_slice::<serde_json::Value>(&pay_bytes) else {
continue;
};
checked += 1;
if hdr_json
.get("alg")
.and_then(|v| v.as_str())
.map(|a| a.eq_ignore_ascii_case("none"))
.unwrap_or(false)
{
findings.push(Finding {
id: "AUTH-JWT-ALG-NONE".into(),
category: Category::ApiSecurity,
severity: Severity::Critical,
title: "JWT using insecure `alg: none` observed in response".into(),
summary: "A JSON Web Token with signature algorithm `none` was issued or returned.".into(),
evidence: Some(format!("alg=none in token at {url}")),
remediation: "Enforce strong asymmetric (RS256/EdDSA) or HMAC (HS256) JWT verification and explicitly reject `alg=none`.".into(),
standard_ref: Some("OWASP ASVS V3.5.3 / WSTG-SESS".into()),
confidence: Confidence::High,
});
}
if pay_json.get("exp").is_none() {
findings.push(Finding {
id: "AUTH-JWT-NO-EXP".into(),
category: Category::ApiSecurity,
severity: Severity::Medium,
title: "JWT missing expiration (`exp`) claim".into(),
summary: "A JSON Web Token returned by the application has no `exp` claim, leaving leaked tokens valid indefinitely.".into(),
evidence: Some(format!("JWT without `exp` at {url}")),
remediation: "Set a short `exp` lifetime on all issued JWTs and rotate refresh tokens properly.".into(),
standard_ref: Some("OWASP ASVS V3.5.1".into()),
confidence: Confidence::High,
});
}
}
findings
}
fn audit_stacktraces_and_internal_ips(headers: &HeaderMap, body: &str, url: &Url) -> Vec<Finding> {
let mut findings = Vec::new();
let markers = [
"NullPointerException",
"System.NullReferenceException",
"You have an error in your SQL syntax",
"PG::SyntaxError",
"SQLite3::SQLException",
"Traceback (most recent call last):",
"panicked at '",
"at Object.<anonymous>",
];
for m in markers {
if body.contains(m) {
findings.push(Finding {
id: "INFO-API-STACKTRACE".into(),
category: Category::SecretsAndLeaks,
severity: Severity::High,
title: "Application stack trace or SQL error exposed in response".into(),
summary: "Detailed runtime stack traces expose file paths, dependencies, and query structure.".into(),
evidence: Some(format!("Marker `{m}` at {url}")),
remediation: "Disable verbose error responses in production and log stack traces server-side only.".into(),
standard_ref: Some("OWASP ASVS V7.4.1 / WSTG-ERRH-01".into()),
confidence: Confidence::High,
});
break;
}
}
for (name, val) in headers {
let lower_name = name.as_str().to_ascii_lowercase();
if matches!(
lower_name.as_str(),
"x-backend-server" | "x-upstream" | "x-internal-ip" | "x-server-ip" | "x-host"
) {
if let Ok(v) = val.to_str() {
findings.push(Finding {
id: "INFO-INTERNAL-HEADER".into(),
category: Category::InformationDisclosure,
severity: Severity::Low,
title: format!("Internal routing header exposed: {name}"),
summary: "Server exposes internal infrastructure hostnames or backend node identifiers.".into(),
evidence: Some(format!("{name}: {v}")),
remediation: "Strip internal proxy/upstream headers before returning responses to clients.".into(),
standard_ref: Some("OWASP WSTG-INFO-02".into()),
confidence: Confidence::High,
});
}
}
}
findings
}
pub fn analyze_response_leaks(headers: &HeaderMap, body: &str, url: &Url) -> Vec<Finding> {
let mut findings = Vec::new();
findings.extend(audit_secrets(body, url));
findings.extend(audit_jwts(body, url));
for hv in headers.get_all(reqwest::header::SET_COOKIE) {
if let Ok(s) = hv.to_str() {
findings.extend(audit_jwts(s, url));
}
}
findings.extend(audit_stacktraces_and_internal_ips(headers, body, url));
findings
}
pub fn extract_js_routes_and_sourcemap(js_body: &str, js_url: &Url) -> (Option<Url>, Vec<Url>) {
let mut sourcemap = None;
for line in js_body.lines().rev().take(15) {
let trimmed = line.trim();
for prefix in ["//# sourceMappingURL=", "//@ sourceMappingURL="] {
if let Some(raw_map) = trimmed.strip_prefix(prefix) {
let candidate = raw_map.trim();
if !candidate.starts_with("data:") {
if let Ok(resolved) = js_url.join(candidate) {
if resolved.host_str() == js_url.host_str() {
sourcemap = Some(resolved);
}
}
}
break;
}
}
if sourcemap.is_some() {
break;
}
}
let mut discovered = Vec::new();
let mut seen = HashSet::new();
let api_prefixes = [
"/api/", "/v1/", "/v2/", "/graphql", "/admin", "/account", "/profile",
];
for quote in ['"', '\'', '`'] {
let mut rest = js_body;
while let Some(pos) = rest.find(quote) {
let after = &rest[pos + 1..];
let Some(end) = after.find(quote) else {
break;
};
let literal = &after[..end];
rest = &after[end + 1..];
if literal.len() < 3
|| literal.len() > 80
|| literal.contains("${")
|| literal.contains(' ')
|| literal.contains('*')
{
continue;
}
if api_prefixes.iter().any(|p| literal.starts_with(p)) {
if let Ok(resolved) = js_url.join(literal) {
if resolved.host_str() == js_url.host_str()
&& seen.insert(resolved.as_str().to_string())
{
discovered.push(resolved);
if discovered.len() >= 15 {
return (sourcemap, discovered);
}
}
}
}
}
}
(sourcemap, discovered)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn detects_and_masks_leaked_secrets_and_db_uri() {
let url = Url::parse("https://app.example.test/config.js").unwrap();
let body = r#"
const aws = "AKIA1234567890ABCDEF";
const db = "postgres://admin:SuperSecretPass99@db.internal:5432/prod";
const key = "-----BEGIN PRIVATE KEY-----\nABC";
"#;
let findings = analyze_response_leaks(&HeaderMap::new(), body, &url);
let ids: Vec<&str> = findings.iter().map(|f| f.id.as_str()).collect();
assert!(ids.contains(&"LEAK-SECRET-AWS"));
assert!(ids.contains(&"LEAK-DB-CONNECTION"));
assert!(ids.contains(&"LEAK-PRIVATE-KEY"));
let joined: String = findings
.iter()
.filter_map(|f| f.evidence.clone())
.collect::<Vec<_>>()
.join(" ");
assert!(!joined.contains("AKIA1234567890ABCDEF"));
assert!(!joined.contains("SuperSecretPass99"));
}
#[test]
fn detects_jwt_issues_and_js_sourcemap_and_routes() {
let url = Url::parse("https://app.example.test/static/main.js").unwrap();
let jwt = "eyJhbGciOiJub25lIiwidHlwIjoiSldUIn0.eyJzdWIiOiIxMjMifQ.sig";
let js = format!(
"const ep = \"/api/v1/users\"; const t = \"{jwt}\";\n//# sourceMappingURL=main.js.map\n"
);
let findings = analyze_response_leaks(&HeaderMap::new(), &js, &url);
assert!(findings.iter().any(|f| f.id == "AUTH-JWT-ALG-NONE"));
assert!(findings.iter().any(|f| f.id == "AUTH-JWT-NO-EXP"));
let (map, routes) = extract_js_routes_and_sourcemap(&js, &url);
assert_eq!(
map.unwrap().as_str(),
"https://app.example.test/static/main.js.map"
);
assert_eq!(routes[0].as_str(), "https://app.example.test/api/v1/users");
}
}