BlueGit

timfa posprint

Files

posprint / src / referrer_verify.rs

referrer_verify.rs

referrer_verify.rs 6.1 KiB Download Raw
1//! Verify `noconfirm` print requests via a caller-controlled HTTP(S) referrer URL.
2
3use std::net::IpAddr;
4use std::time::Duration;
5
6use crate::config::normalize_origin;
7
8const VERIFY_TIMEOUT_SECS: u64 = 10;
9
10#[derive(Debug, Clone, PartialEq, Eq)]
11pub enum ReferrerVerifyError {
12 Empty,
13 UnsupportedScheme(String),
14 InvalidUrl(String),
15 BlockedHost(String),
16 HttpStatus(u16),
17 Network(String),
18}
19
20impl 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
40impl 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`.
44pub 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.
70pub fn referrer_trust_host(referrer_url: &str) -> Option<String> {
71 normalize_origin(referrer_url)
72}
73
74fn 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
90fn is_blocked_verify_host(host: &str) -> bool {
91 let h = host.to_ascii_lowercase();
92 // Loopback is allowed (local verify servers / dev). Block other private LAN hosts.
93 if h == "localhost" || h.ends_with(".localhost") {
94 return false;
95 }
96 if let Ok(ip) = h.parse::<IpAddr>() {
97 return match ip {
98 IpAddr::V4(v4) => {
99 !v4.is_loopback()
100 && (v4.is_private() || v4.is_link_local() || v4.is_unspecified())
101 }
102 IpAddr::V6(v6) => !v6.is_loopback() && v6.is_unspecified(),
103 };
104 }
105 false
106}
107
108/// True when an HTTP status means the print request is authorized by the site.
109pub fn is_verification_success(status: u16) -> bool {
110 status == 200
111}
112
113/// GET `referrer_url` (no redirects). On HTTP 200 returns the trust hostname.
114pub fn verify_referrer(referrer_url: &str) -> Result<String, ReferrerVerifyError> {
115 let url = normalize_referrer_url(referrer_url)?;
116 let host = referrer_trust_host(&url)
117 .ok_or_else(|| ReferrerVerifyError::InvalidUrl("missing host".into()))?;
118
119 let agent = ureq::AgentBuilder::new()
120 .timeout_connect(Duration::from_secs(VERIFY_TIMEOUT_SECS))
121 .timeout_read(Duration::from_secs(VERIFY_TIMEOUT_SECS))
122 .redirects(0)
123 .build();
124
125 let response = agent.get(&url).call().map_err(|e| match e {
126 ureq::Error::Status(code, _) => ReferrerVerifyError::HttpStatus(code),
127 other => ReferrerVerifyError::Network(other.to_string()),
128 })?;
129
130 let status = response.status();
131 if !is_verification_success(status) {
132 return Err(ReferrerVerifyError::HttpStatus(status));
133 }
134 Ok(host)
135}
136
137#[cfg(test)]
138mod tests {
139 use super::*;
140
141 #[test]
142 fn normalizes_bare_host_path_to_https() {
143 let url = normalize_referrer_url("website.com/bonnen/verify?code=84923").unwrap();
144 assert_eq!(url, "https://website.com/bonnen/verify?code=84923");
145 assert_eq!(referrer_trust_host(&url).as_deref(), Some("website.com"));
146 }
147
148 #[test]
149 fn rejects_non_http_schemes() {
150 let err = normalize_referrer_url("file:///etc/passwd").unwrap_err();
151 assert!(matches!(err, ReferrerVerifyError::UnsupportedScheme(_)));
152 }
153
154 #[test]
155 fn allows_loopback_hosts() {
156 let url = normalize_referrer_url("http://127.0.0.1:8765/verify?code=1").unwrap();
157 assert_eq!(url, "http://127.0.0.1:8765/verify?code=1");
158 assert!(normalize_referrer_url("http://localhost/verify").is_ok());
159 }
160
161 #[test]
162 fn blocks_private_lan_hosts() {
163 let err = normalize_referrer_url("http://192.168.1.10/verify").unwrap_err();
164 assert!(matches!(err, ReferrerVerifyError::BlockedHost(_)));
165 let err = normalize_referrer_url("http://10.0.0.5/x").unwrap_err();
166 assert!(matches!(err, ReferrerVerifyError::BlockedHost(_)));
167 }
168
169 #[test]
170 fn only_http_200_counts_as_success() {
171 assert!(is_verification_success(200));
172 assert!(!is_verification_success(204));
173 assert!(!is_verification_success(404));
174 assert!(!is_verification_success(302));
175 }
176}