//! Turn an HTTP exchange into a verdict using the site's detector.
use super::http::Exchange;
use super::result::{Confidence, Status};
use super::waf;
use crate::db::{Detector, Site};
use crate::util;
#[derive(Clone, Debug, PartialEq)]
pub struct Verdict {
pub status: Status,
pub confidence: Confidence,
pub reason: String,
}
impl Verdict {
pub fn new(status: Status, confidence: Confidence, reason: impl Into<String>) -> Self {
Verdict {
status,
confidence,
reason: reason.into(),
}
}
fn found(confidence: Confidence, reason: impl Into<String>) -> Self {
Verdict::new(Status::Found, confidence, reason)
}
fn missing(confidence: Confidence, reason: impl Into<String>) -> Self {
Verdict::new(Status::NotFound, confidence, reason)
}
}
/// Where a redirect chain ended up, classified.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Landing {
/// No redirect happened.
Direct,
/// The final URL still names the account (canonical profile URL).
SameAccount,
/// Root, login, signup, 404 or similar: the site bounced us away.
Junk,
/// Somewhere else on the site.
Elsewhere,
}
const JUNK_PATHS: &[&str] = &[
"login",
"signin",
"sign-in",
"sign_in",
"signup",
"sign-up",
"sign_up",
"register",
"404",
"not-found",
"notfound",
"not_found",
"error",
"home",
"index",
"/auth",
"session",
"welcome",
"explore",
"search",
"landing",
"accounts/",
"account/",
"unavailable",
"suspended",
"removed",
];
fn landing(ex: &Exchange, account: &str) -> Landing {
if ex.hops.is_empty() {
return Landing::Direct;
}
let Ok(u) = url::Url::parse(&ex.final_url) else {
return Landing::Elsewhere;
};
let path = u.path().trim_end_matches('/').to_ascii_lowercase();
let decoded = percent_encoding::percent_decode_str(&path)
.decode_utf8_lossy()
.to_string();
let acct = account.to_ascii_lowercase();
if !acct.is_empty() && decoded.contains(&acct) {
return Landing::SameAccount;
}
if path.is_empty() || JUNK_PATHS.iter().any(|j| path.contains(j)) {
return Landing::Junk;
}
Landing::Elsewhere
}
fn short_path(ex: &Exchange) -> String {
url::Url::parse(&ex.final_url)
.map(|u| util::truncate(u.path(), 50))
.unwrap_or_default()
}
/// Shared 2xx / redirect logic for status-based detectors.
fn status_verdict(ex: &Exchange, account: &str, status: u16) -> Verdict {
match landing(ex, account) {
Landing::Direct => Verdict::found(Confidence::High, format!("HTTP {status}")),
Landing::SameAccount => Verdict::found(
Confidence::High,
format!("HTTP {status} after redirect to the canonical profile URL"),
),
Landing::Junk => Verdict::missing(
Confidence::High,
format!("redirected to {}", short_path(ex)),
),
Landing::Elsewhere => Verdict::found(
Confidence::Medium,
format!("HTTP {status} after redirect to {}", short_path(ex)),
),
}
}
pub fn evaluate(site: &Site, ex: &Exchange, account: &str) -> Verdict {
let body = ex.body.as_str();
let status = ex.final_status;
let first = ex.first_status;
let status_is = |code: u16| status == code || first == code;
for (marker, reason) in &site.errors {
if !marker.is_empty() && body.contains(marker.as_str()) {
return Verdict::new(
Status::Blocked,
Confidence::High,
format!("site error marker: {reason}"),
);
}
}
if let Some(block) = waf::strong_block(status, &ex.headers, body) {
return Verdict::new(Status::Blocked, Confidence::High, block);
}
let undecided = |reason: String| -> Verdict {
if !(status == 403 && site.ignore_403) {
if let Some(block) = waf::weak_block(status, body) {
return Verdict::new(Status::Blocked, Confidence::Medium, block);
}
}
if status >= 500 {
return Verdict::new(
Status::Error,
Confidence::Medium,
format!("HTTP {status} server error"),
);
}
Verdict::new(Status::Unknown, Confidence::Low, reason)
};
match &site.detector {
Detector::CodeAndString {
e_code,
e_string,
m_code,
m_string,
} => {
let exists =
status_is(*e_code) && (e_string.is_empty() || body.contains(e_string.as_str()));
let missing =
status_is(*m_code) && (m_string.is_empty() || body.contains(m_string.as_str()));
match (exists, missing) {
(true, false) => Verdict::found(
Confidence::High,
format!("HTTP {status} with presence marker"),
),
(true, true) => Verdict::found(
Confidence::Medium,
"presence and absence markers both matched",
),
(false, true) => Verdict::missing(
Confidence::High,
format!("HTTP {status} with absence marker"),
),
(false, false) => undecided(format!(
"no marker matched (HTTP {status}, expected {e_code} or {m_code})"
)),
}
}
Detector::Message { absence, presence } => {
if let Some(a) = absence
.iter()
.find(|s| !s.is_empty() && body.contains(s.as_str()))
{
return Verdict::missing(
Confidence::High,
format!("absence marker {:?}", util::truncate(a, 40)),
);
}
if !presence.is_empty() {
if presence.iter().all(|s| body.contains(s.as_str())) {
return Verdict::found(Confidence::High, "presence markers matched");
}
return undecided(format!("presence markers missing (HTTP {status})"));
}
match status {
200..=299 => Verdict::found(
Confidence::High,
format!("HTTP {status} without absence marker"),
),
404 | 410 => Verdict::missing(Confidence::Medium, format!("HTTP {status}")),
_ => undecided(format!("HTTP {status} without absence marker")),
}
}
Detector::StatusCode { error_codes } => {
if error_codes.contains(&status) {
return Verdict::missing(
Confidence::High,
format!("HTTP {status} is a configured absence code"),
);
}
match status {
200..=299 => status_verdict(ex, account, status),
404 | 410 => Verdict::missing(Confidence::High, format!("HTTP {status}")),
300..=399 => {
Verdict::missing(Confidence::Medium, format!("redirect loop (HTTP {status})"))
}
403 if site.ignore_403 => {
Verdict::missing(Confidence::Medium, "HTTP 403 (ignored per site rules)")
}
_ => undecided(format!("HTTP {status}")),
}
}
Detector::ResponseUrl { error_url } => {
if let Some(eu) = error_url.as_deref().filter(|e| !e.is_empty()) {
let eu = eu.trim_end_matches('/');
if ex
.hops
.iter()
.any(|h| h.trim_end_matches('/').starts_with(eu))
|| ex.location.as_deref().is_some_and(|l| l.starts_with(eu))
{
return Verdict::missing(
Confidence::High,
"redirected to the site's error URL",
);
}
}
match status {
200..=299 => status_verdict(ex, account, status),
404 | 410 => Verdict::missing(Confidence::High, format!("HTTP {status}")),
300..=399 => {
Verdict::missing(Confidence::Medium, format!("redirect loop (HTTP {status})"))
}
_ => undecided(format!("HTTP {status}")),
}
}
}
}
#[cfg(test)]
mod tests {
use super::*;
fn ex(first: u16, fin: u16, body: &str) -> Exchange {
Exchange {
first_status: first,
final_status: fin,
body: body.to_string(),
..Default::default()
}
}
fn site(det: Detector) -> Site {
let mut s = Site {
name: "t".into(),
url: "https://t/{account}".into(),
detector: det,
..Default::default()
};
s.finalize();
s
}
#[test]
fn code_and_string() {
let s = site(Detector::CodeAndString {
e_code: 200,
e_string: "profile".into(),
m_code: 302,
m_string: String::new(),
});
assert_eq!(
evaluate(&s, &ex(200, 200, "<h1>profile</h1>"), "acct").status,
Status::Found
);
// Missing users redirect (first hop 302) to a page without the marker.
assert_eq!(
evaluate(&s, &ex(302, 200, "<h1>home</h1>"), "acct").status,
Status::NotFound
);
// Existing users redirect then land on the profile: presence wins (medium confidence).
let v = evaluate(&s, &ex(302, 200, "<h1>profile</h1>"), "acct");
assert_eq!(v.status, Status::Found);
assert_eq!(v.confidence, Confidence::Medium);
assert_eq!(
evaluate(&s, &ex(200, 200, "nothing"), "acct").status,
Status::Unknown
);
assert_eq!(
evaluate(&s, &ex(503, 503, "<title>Just a moment...</title>"), "acct").status,
Status::Blocked
);
assert_eq!(
evaluate(&s, &ex(500, 500, "boom"), "acct").status,
Status::Error
);
assert_eq!(
evaluate(&s, &ex(403, 403, "x"), "acct").status,
Status::Blocked
);
}
#[test]
fn message_detector() {
let s = site(Detector::Message {
absence: vec!["not found".into()],
presence: vec![],
});
assert_eq!(
evaluate(&s, &ex(200, 200, "user not found"), "acct").status,
Status::NotFound
);
assert_eq!(
evaluate(&s, &ex(200, 200, "hello"), "acct").status,
Status::Found
);
assert_eq!(
evaluate(&s, &ex(404, 404, "hello"), "acct").status,
Status::NotFound
);
let s = site(Detector::Message {
absence: vec!["gone".into()],
presence: vec!["a".into(), "b".into()],
});
assert_eq!(
evaluate(&s, &ex(200, 200, "a and b"), "acct").status,
Status::Found
);
assert_eq!(
evaluate(&s, &ex(200, 200, "only a"), "acct").status,
Status::Unknown
);
let s = Site {
errors: vec![("Login required".into(), "login wall".into())],
..site(Detector::Message {
absence: vec![],
presence: vec![],
})
};
assert_eq!(
evaluate(&s, &ex(200, 200, "Login required"), "acct").status,
Status::Blocked
);
}
#[test]
fn status_and_redirect_detectors() {
let s = site(Detector::StatusCode {
error_codes: vec![410],
});
assert_eq!(
evaluate(&s, &ex(200, 200, ""), "acct").status,
Status::Found
);
assert_eq!(
evaluate(&s, &ex(404, 404, ""), "acct").status,
Status::NotFound
);
assert_eq!(
evaluate(&s, &ex(410, 410, ""), "acct").status,
Status::NotFound
);
assert_eq!(
evaluate(&s, &ex(302, 302, ""), "acct").status,
Status::NotFound
);
assert_eq!(
evaluate(&s, &ex(429, 429, ""), "acct").status,
Status::Blocked
);
let mut e = ex(301, 200, "");
e.hops = vec!["https://t/".into()];
e.final_url = "https://t/".into();
assert_eq!(evaluate(&s, &e, "acct").status, Status::NotFound);
e.final_url = "https://t/login?next=x".into();
assert_eq!(evaluate(&s, &e, "acct").status, Status::NotFound);
e.final_url = "https://t/user/show/123-acct".into();
let v = evaluate(&s, &e, "acct");
assert_eq!((v.status, v.confidence), (Status::Found, Confidence::High));
e.final_url = "https://t/somewhere/else".into();
let v = evaluate(&s, &e, "acct");
assert_eq!(
(v.status, v.confidence),
(Status::Found, Confidence::Medium)
);
let s = site(Detector::ResponseUrl {
error_url: Some("https://t/".into()),
});
let mut e = ex(302, 200, "");
e.hops = vec!["https://t/?err".into()];
e.final_url = "https://t/?err".into();
e.location = Some("https://t/?err".into());
let v = evaluate(&s, &e, "acct");
assert_eq!(v.status, Status::NotFound);
assert_eq!(v.confidence, Confidence::High);
assert_eq!(
evaluate(&s, &ex(200, 200, ""), "acct").status,
Status::Found
);
}
}