BlueGit

timfa posprint

Files

posprint / src / referrer_verify.rs

referrer_verify.rs

referrer_verify.rs 6.7 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 allow_local_referrer() -> bool {
91 matches!(
92 std::env::var("POSPRINT_ALLOW_LOCAL_REFERRER")
93 .unwrap_or_default()
94 .to_ascii_lowercase()
95 .as_str(),
96 "1" | "true" | "yes"
97 )
98}
99
100fn is_blocked_verify_host(host: &str) -> bool {
101 let h = host.to_ascii_lowercase();
102 let is_loopback_name = h == "localhost" || h.ends_with(".localhost") || h == "0.0.0.0";
103 if let Ok(ip) = h.parse::<IpAddr>() {
104 let loopback = match ip {
105 IpAddr::V4(v4) => v4.is_loopback() || v4.is_unspecified(),
106 IpAddr::V6(v6) => v6.is_loopback() || v6.is_unspecified(),
107 };
108 if loopback {
109 return !allow_local_referrer();
110 }
111 return match ip {
112 IpAddr::V4(v4) => v4.is_private() || v4.is_link_local(),
113 IpAddr::V6(_) => false,
114 };
115 }
116 if is_loopback_name {
117 return !allow_local_referrer();
118 }
119 false
120}
121
122/// True when an HTTP status means the print request is authorized by the site.
123pub fn is_verification_success(status: u16) -> bool {
124 status == 200
125}
126
127/// GET `referrer_url` (no redirects). On HTTP 200 returns the trust hostname.
128pub fn verify_referrer(referrer_url: &str) -> Result<String, ReferrerVerifyError> {
129 let url = normalize_referrer_url(referrer_url)?;
130 let host = referrer_trust_host(&url)
131 .ok_or_else(|| ReferrerVerifyError::InvalidUrl("missing host".into()))?;
132
133 let agent = ureq::AgentBuilder::new()
134 .timeout_connect(Duration::from_secs(VERIFY_TIMEOUT_SECS))
135 .timeout_read(Duration::from_secs(VERIFY_TIMEOUT_SECS))
136 .redirects(0)
137 .build();
138
139 let response = agent.get(&url).call().map_err(|e| match e {
140 ureq::Error::Status(code, _) => ReferrerVerifyError::HttpStatus(code),
141 other => ReferrerVerifyError::Network(other.to_string()),
142 })?;
143
144 let status = response.status();
145 if !is_verification_success(status) {
146 return Err(ReferrerVerifyError::HttpStatus(status));
147 }
148 Ok(host)
149}
150
151#[cfg(test)]
152mod tests {
153 use super::*;
154 use std::sync::Mutex;
155
156 static ENV_LOCK: Mutex<()> = Mutex::new(());
157
158 #[test]
159 fn normalizes_bare_host_path_to_https() {
160 let url = normalize_referrer_url("website.com/bonnen/verify?code=84923").unwrap();
161 assert_eq!(url, "https://website.com/bonnen/verify?code=84923");
162 assert_eq!(referrer_trust_host(&url).as_deref(), Some("website.com"));
163 }
164
165 #[test]
166 fn rejects_non_http_schemes() {
167 let err = normalize_referrer_url("file:///etc/passwd").unwrap_err();
168 assert!(matches!(err, ReferrerVerifyError::UnsupportedScheme(_)));
169 }
170
171 #[test]
172 fn blocks_localhost() {
173 let _g = ENV_LOCK.lock().unwrap();
174 std::env::remove_var("POSPRINT_ALLOW_LOCAL_REFERRER");
175 let err = normalize_referrer_url("http://127.0.0.1/verify").unwrap_err();
176 assert!(matches!(err, ReferrerVerifyError::BlockedHost(_)));
177 let err = normalize_referrer_url("https://localhost/x").unwrap_err();
178 assert!(matches!(err, ReferrerVerifyError::BlockedHost(_)));
179 }
180
181 #[test]
182 fn allows_localhost_when_env_set() {
183 let _g = ENV_LOCK.lock().unwrap();
184 std::env::set_var("POSPRINT_ALLOW_LOCAL_REFERRER", "1");
185 let url = normalize_referrer_url("http://127.0.0.1:8765/verify?code=1").unwrap();
186 assert_eq!(url, "http://127.0.0.1:8765/verify?code=1");
187 std::env::remove_var("POSPRINT_ALLOW_LOCAL_REFERRER");
188 }
189
190 #[test]
191 fn only_http_200_counts_as_success() {
192 assert!(is_verification_success(200));
193 assert!(!is_verification_success(204));
194 assert!(!is_verification_success(404));
195 assert!(!is_verification_success(302));
196 }
197}