//! Verify `noconfirm` print requests via a caller-controlled HTTP(S) referrer URL. use std::net::IpAddr; use std::time::Duration; use crate::config::normalize_origin; const VERIFY_TIMEOUT_SECS: u64 = 10; #[derive(Debug, Clone, PartialEq, Eq)] pub enum ReferrerVerifyError { Empty, UnsupportedScheme(String), InvalidUrl(String), BlockedHost(String), HttpStatus(u16), Network(String), } impl std::fmt::Display for ReferrerVerifyError { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { Self::Empty => write!(f, "referrer URL is empty"), Self::UnsupportedScheme(s) => { write!(f, "referrer must be http(s), got '{s}'") } Self::InvalidUrl(e) => write!(f, "invalid referrer URL: {e}"), Self::BlockedHost(h) => { write!(f, "referrer host '{h}' is not allowed for verification") } Self::HttpStatus(code) => write!( f, "referrer verification failed (HTTP {code}); expected 200" ), Self::Network(e) => write!(f, "referrer verification network error: {e}"), } } } impl std::error::Error for ReferrerVerifyError {} /// Normalize a referrer parameter into an absolute `http://` or `https://` URL. /// Bare values like `shop.example/verify?code=1` become `https://shop.example/verify?code=1`. pub fn normalize_referrer_url(raw: &str) -> Result { let s = raw.trim(); if s.is_empty() { return Err(ReferrerVerifyError::Empty); } let absolute = if let Some(rest) = s.strip_prefix("https://") { format!("https://{rest}") } else if let Some(rest) = s.strip_prefix("http://") { format!("http://{rest}") } else if let Some(idx) = s.find("://") { let scheme = &s[..idx]; return Err(ReferrerVerifyError::UnsupportedScheme(scheme.to_string())); } else { format!("https://{s}") }; let host = host_from_http_url(&absolute) .ok_or_else(|| ReferrerVerifyError::InvalidUrl("missing host".into()))?; if is_blocked_verify_host(&host) { return Err(ReferrerVerifyError::BlockedHost(host)); } Ok(absolute) } /// Hostname used for trust storage after a successful verification GET. pub fn referrer_trust_host(referrer_url: &str) -> Option { normalize_origin(referrer_url) } fn host_from_http_url(url: &str) -> Option { let rest = url .strip_prefix("https://") .or_else(|| url.strip_prefix("http://"))?; let host_port = rest.split('/').next()?.split('?').next()?.trim(); if host_port.is_empty() { return None; } let host = host_port.split(':').next()?.trim(); if host.is_empty() { None } else { Some(host.to_ascii_lowercase()) } } fn allow_local_referrer() -> bool { matches!( std::env::var("POSPRINT_ALLOW_LOCAL_REFERRER") .unwrap_or_default() .to_ascii_lowercase() .as_str(), "1" | "true" | "yes" ) } fn is_blocked_verify_host(host: &str) -> bool { let h = host.to_ascii_lowercase(); let is_loopback_name = h == "localhost" || h.ends_with(".localhost") || h == "0.0.0.0"; if let Ok(ip) = h.parse::() { let loopback = match ip { IpAddr::V4(v4) => v4.is_loopback() || v4.is_unspecified(), IpAddr::V6(v6) => v6.is_loopback() || v6.is_unspecified(), }; if loopback { return !allow_local_referrer(); } return match ip { IpAddr::V4(v4) => v4.is_private() || v4.is_link_local(), IpAddr::V6(_) => false, }; } if is_loopback_name { return !allow_local_referrer(); } false } /// True when an HTTP status means the print request is authorized by the site. pub fn is_verification_success(status: u16) -> bool { status == 200 } /// GET `referrer_url` (no redirects). On HTTP 200 returns the trust hostname. pub fn verify_referrer(referrer_url: &str) -> Result { let url = normalize_referrer_url(referrer_url)?; let host = referrer_trust_host(&url) .ok_or_else(|| ReferrerVerifyError::InvalidUrl("missing host".into()))?; let agent = ureq::AgentBuilder::new() .timeout_connect(Duration::from_secs(VERIFY_TIMEOUT_SECS)) .timeout_read(Duration::from_secs(VERIFY_TIMEOUT_SECS)) .redirects(0) .build(); let response = agent.get(&url).call().map_err(|e| match e { ureq::Error::Status(code, _) => ReferrerVerifyError::HttpStatus(code), other => ReferrerVerifyError::Network(other.to_string()), })?; let status = response.status(); if !is_verification_success(status) { return Err(ReferrerVerifyError::HttpStatus(status)); } Ok(host) } #[cfg(test)] mod tests { use super::*; use std::sync::Mutex; static ENV_LOCK: Mutex<()> = Mutex::new(()); #[test] fn normalizes_bare_host_path_to_https() { let url = normalize_referrer_url("website.com/bonnen/verify?code=84923").unwrap(); assert_eq!(url, "https://website.com/bonnen/verify?code=84923"); assert_eq!(referrer_trust_host(&url).as_deref(), Some("website.com")); } #[test] fn rejects_non_http_schemes() { let err = normalize_referrer_url("file:///etc/passwd").unwrap_err(); assert!(matches!(err, ReferrerVerifyError::UnsupportedScheme(_))); } #[test] fn blocks_localhost() { let _g = ENV_LOCK.lock().unwrap(); std::env::remove_var("POSPRINT_ALLOW_LOCAL_REFERRER"); let err = normalize_referrer_url("http://127.0.0.1/verify").unwrap_err(); assert!(matches!(err, ReferrerVerifyError::BlockedHost(_))); let err = normalize_referrer_url("https://localhost/x").unwrap_err(); assert!(matches!(err, ReferrerVerifyError::BlockedHost(_))); } #[test] fn allows_localhost_when_env_set() { let _g = ENV_LOCK.lock().unwrap(); std::env::set_var("POSPRINT_ALLOW_LOCAL_REFERRER", "1"); let url = normalize_referrer_url("http://127.0.0.1:8765/verify?code=1").unwrap(); assert_eq!(url, "http://127.0.0.1:8765/verify?code=1"); std::env::remove_var("POSPRINT_ALLOW_LOCAL_REFERRER"); } #[test] fn only_http_200_counts_as_success() { assert!(is_verification_success(200)); assert!(!is_verification_success(204)); assert!(!is_verification_success(404)); assert!(!is_verification_success(302)); } }