| 1 | //! Verify `noconfirm` print requests via a caller-controlled HTTP(S) referrer URL.
|
| 2 |
|
| 3 | use std::net::IpAddr;
|
| 4 | use std::time::Duration;
|
| 5 |
|
| 6 | use crate::config::normalize_origin;
|
| 7 |
|
| 8 | const VERIFY_TIMEOUT_SECS: u64 = 10;
|
| 9 |
|
| 10 | #[derive(Debug, Clone, PartialEq, Eq)]
|
| 11 | pub enum ReferrerVerifyError {
|
| 12 | Empty,
|
| 13 | UnsupportedScheme(String),
|
| 14 | InvalidUrl(String),
|
| 15 | BlockedHost(String),
|
| 16 | HttpStatus(u16),
|
| 17 | Network(String),
|
| 18 | }
|
| 19 |
|
| 20 | impl std::fmt::Display for ReferrerVerifyError {
|
| 21 | fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
| 22 | match self {
|
| 23 | Self::Empty => write!(f, "referrer URL is empty"),
|
| 24 | Self::UnsupportedScheme(s) => {
|
| 25 | write!(f, "referrer must be http(s), got '{s}'")
|
| 26 | }
|
| 27 | Self::InvalidUrl(e) => write!(f, "invalid referrer URL: {e}"),
|
| 28 | Self::BlockedHost(h) => {
|
| 29 | write!(f, "referrer host '{h}' is not allowed for verification")
|
| 30 | }
|
| 31 | Self::HttpStatus(code) => write!(
|
| 32 | f,
|
| 33 | "referrer verification failed (HTTP {code}); expected 200"
|
| 34 | ),
|
| 35 | Self::Network(e) => write!(f, "referrer verification network error: {e}"),
|
| 36 | }
|
| 37 | }
|
| 38 | }
|
| 39 |
|
| 40 | impl std::error::Error for ReferrerVerifyError {}
|
| 41 |
|
| 42 | /// Normalize a referrer parameter into an absolute `http://` or `https://` URL.
|
| 43 | /// Bare values like `shop.example/verify?code=1` become `https://shop.example/verify?code=1`.
|
| 44 | pub fn normalize_referrer_url(raw: &str) -> Result<String, ReferrerVerifyError> {
|
| 45 | let s = raw.trim();
|
| 46 | if s.is_empty() {
|
| 47 | return Err(ReferrerVerifyError::Empty);
|
| 48 | }
|
| 49 |
|
| 50 | let absolute = if let Some(rest) = s.strip_prefix("https://") {
|
| 51 | format!("https://{rest}")
|
| 52 | } else if let Some(rest) = s.strip_prefix("http://") {
|
| 53 | format!("http://{rest}")
|
| 54 | } else if let Some(idx) = s.find("://") {
|
| 55 | let scheme = &s[..idx];
|
| 56 | return Err(ReferrerVerifyError::UnsupportedScheme(scheme.to_string()));
|
| 57 | } else {
|
| 58 | format!("https://{s}")
|
| 59 | };
|
| 60 |
|
| 61 | let host = host_from_http_url(&absolute)
|
| 62 | .ok_or_else(|| ReferrerVerifyError::InvalidUrl("missing host".into()))?;
|
| 63 | if is_blocked_verify_host(&host) {
|
| 64 | return Err(ReferrerVerifyError::BlockedHost(host));
|
| 65 | }
|
| 66 | Ok(absolute)
|
| 67 | }
|
| 68 |
|
| 69 | /// Hostname used for trust storage after a successful verification GET.
|
| 70 | pub fn referrer_trust_host(referrer_url: &str) -> Option<String> {
|
| 71 | normalize_origin(referrer_url)
|
| 72 | }
|
| 73 |
|
| 74 | fn host_from_http_url(url: &str) -> Option<String> {
|
| 75 | let rest = url
|
| 76 | .strip_prefix("https://")
|
| 77 | .or_else(|| url.strip_prefix("http://"))?;
|
| 78 | let host_port = rest.split('/').next()?.split('?').next()?.trim();
|
| 79 | if host_port.is_empty() {
|
| 80 | return None;
|
| 81 | }
|
| 82 | let host = host_port.split(':').next()?.trim();
|
| 83 | if host.is_empty() {
|
| 84 | None
|
| 85 | } else {
|
| 86 | Some(host.to_ascii_lowercase())
|
| 87 | }
|
| 88 | }
|
| 89 |
|
| 90 | fn is_blocked_verify_host(host: &str) -> bool {
|
| 91 | let h = host.to_ascii_lowercase();
|
| 92 | if h == "localhost" || h.ends_with(".localhost") || h == "0.0.0.0" {
|
| 93 | return true;
|
| 94 | }
|
| 95 | if let Ok(ip) = h.parse::<IpAddr>() {
|
| 96 | return match ip {
|
| 97 | IpAddr::V4(v4) => {
|
| 98 | v4.is_loopback()
|
| 99 | || v4.is_private()
|
| 100 | || v4.is_link_local()
|
| 101 | || v4.is_unspecified()
|
| 102 | || v4.octets()[0] == 169 && v4.octets()[1] == 254
|
| 103 | }
|
| 104 | IpAddr::V6(v6) => v6.is_loopback() || v6.is_unspecified(),
|
| 105 | };
|
| 106 | }
|
| 107 | false
|
| 108 | }
|
| 109 |
|
| 110 | /// True when an HTTP status means the print request is authorized by the site.
|
| 111 | pub fn is_verification_success(status: u16) -> bool {
|
| 112 | status == 200
|
| 113 | }
|
| 114 |
|
| 115 | /// GET `referrer_url` (no redirects). On HTTP 200 returns the trust hostname.
|
| 116 | pub fn verify_referrer(referrer_url: &str) -> Result<String, ReferrerVerifyError> {
|
| 117 | let url = normalize_referrer_url(referrer_url)?;
|
| 118 | let host = referrer_trust_host(&url)
|
| 119 | .ok_or_else(|| ReferrerVerifyError::InvalidUrl("missing host".into()))?;
|
| 120 |
|
| 121 | let agent = ureq::AgentBuilder::new()
|
| 122 | .timeout_connect(Duration::from_secs(VERIFY_TIMEOUT_SECS))
|
| 123 | .timeout_read(Duration::from_secs(VERIFY_TIMEOUT_SECS))
|
| 124 | .redirects(0)
|
| 125 | .build();
|
| 126 |
|
| 127 | let response = agent.get(&url).call().map_err(|e| match e {
|
| 128 | ureq::Error::Status(code, _) => ReferrerVerifyError::HttpStatus(code),
|
| 129 | other => ReferrerVerifyError::Network(other.to_string()),
|
| 130 | })?;
|
| 131 |
|
| 132 | let status = response.status();
|
| 133 | if !is_verification_success(status) {
|
| 134 | return Err(ReferrerVerifyError::HttpStatus(status));
|
| 135 | }
|
| 136 | Ok(host)
|
| 137 | }
|
| 138 |
|
| 139 | #[cfg(test)]
|
| 140 | mod tests {
|
| 141 | use super::*;
|
| 142 |
|
| 143 | #[test]
|
| 144 | fn normalizes_bare_host_path_to_https() {
|
| 145 | let url = normalize_referrer_url("website.com/bonnen/verify?code=84923").unwrap();
|
| 146 | assert_eq!(url, "https://website.com/bonnen/verify?code=84923");
|
| 147 | assert_eq!(referrer_trust_host(&url).as_deref(), Some("website.com"));
|
| 148 | }
|
| 149 |
|
| 150 | #[test]
|
| 151 | fn rejects_non_http_schemes() {
|
| 152 | let err = normalize_referrer_url("file:///etc/passwd").unwrap_err();
|
| 153 | assert!(matches!(err, ReferrerVerifyError::UnsupportedScheme(_)));
|
| 154 | }
|
| 155 |
|
| 156 | #[test]
|
| 157 | fn blocks_localhost() {
|
| 158 | let err = normalize_referrer_url("http://127.0.0.1/verify").unwrap_err();
|
| 159 | assert!(matches!(err, ReferrerVerifyError::BlockedHost(_)));
|
| 160 | let err = normalize_referrer_url("https://localhost/x").unwrap_err();
|
| 161 | assert!(matches!(err, ReferrerVerifyError::BlockedHost(_)));
|
| 162 | }
|
| 163 |
|
| 164 | #[test]
|
| 165 | fn only_http_200_counts_as_success() {
|
| 166 | assert!(is_verification_success(200));
|
| 167 | assert!(!is_verification_success(204));
|
| 168 | assert!(!is_verification_success(404));
|
| 169 | assert!(!is_verification_success(302));
|
| 170 | }
|
| 171 | }
|