xdid_method_web/
target.rs1use std::net::{
2 IpAddr,
3 Ipv4Addr,
4 Ipv6Addr,
5};
6
7use reqwest::Url;
8use thiserror::Error;
9
10#[derive(Debug, Default, Copy, Clone, PartialEq, Eq)]
12#[non_exhaustive]
13pub enum TargetPolicy {
14 #[default]
16 PublicOnly,
17 AllowLocal,
22}
23
24#[derive(Debug, Error)]
26#[non_exhaustive]
27pub enum TargetNotAllowed {
28 #[error("only https is permitted")]
29 Scheme,
30 #[error("{0} is outside public unicast space")]
31 Address(IpAddr),
32}
33
34impl TargetPolicy {
35 #[must_use]
37 pub const fn permits_address(self, ip: IpAddr) -> bool {
38 match self {
39 Self::PublicOnly => !is_restricted(ip),
40 Self::AllowLocal => true,
41 }
42 }
43
44 pub fn permits_url(self, url: &Url) -> Result<(), TargetNotAllowed> {
57 if url.scheme() != "https" && !(self == Self::AllowLocal && url.scheme() == "http") {
58 return Err(TargetNotAllowed::Scheme);
59 }
60
61 if let Some(ip) = literal_host(url)
62 && !self.permits_address(ip)
63 {
64 return Err(TargetNotAllowed::Address(ip));
65 }
66
67 Ok(())
68 }
69
70 #[must_use]
75 pub fn scheme_for(self, domain: &str) -> &'static str {
76 let host = domain.split_once(':').map_or(domain, |(host, _)| host);
77
78 if self == Self::AllowLocal && host == "localhost" {
79 "http"
80 } else {
81 "https"
82 }
83 }
84}
85
86fn literal_host(url: &Url) -> Option<IpAddr> {
89 let host = url.host_str()?;
90
91 host.strip_prefix('[')
92 .and_then(|inner| inner.strip_suffix(']'))
93 .unwrap_or(host)
94 .parse()
95 .ok()
96}
97
98const fn is_restricted(ip: IpAddr) -> bool {
103 match ip {
104 IpAddr::V4(ip) => is_restricted_v4(ip),
105 IpAddr::V6(ip) => is_restricted_v6(ip),
106 }
107}
108
109const fn is_restricted_v4(ip: Ipv4Addr) -> bool {
110 let [a, b, c, _] = ip.octets();
111
112 ip.is_loopback()
113 || ip.is_private()
114 || ip.is_link_local()
115 || ip.is_broadcast()
116 || ip.is_documentation()
117 || ip.is_unspecified()
118 || ip.is_multicast()
119 || a == 0
120 || a >= 240
121 || (a == 100 && (b & 0xC0) == 64)
122 || (a == 192 && b == 0 && c == 0)
123 || (a == 198 && (b & 0xFE) == 18)
124}
125
126const fn is_restricted_v6(ip: Ipv6Addr) -> bool {
127 if let Some(embedded) = embedded_v4(ip) {
128 return is_restricted_v4(embedded);
129 }
130
131 let s = ip.segments();
132
133 ip.is_loopback()
134 || ip.is_unspecified()
135 || ip.is_multicast()
136 || (s[0] & 0xFE00) == 0xFC00
137 || (s[0] & 0xFFC0) == 0xFE80
138 || (s[0] == 0x0100 && s[1] == 0 && s[2] == 0 && s[3] == 0)
140 || (s[0] == 0x2001 && (s[1] & 0xFE00) == 0)
143 || (s[0] == 0x2001 && s[1] == 0x0db8)
145}
146
147const fn embedded_v4(ip: Ipv6Addr) -> Option<Ipv4Addr> {
151 if let Some(mapped) = ip.to_ipv4_mapped() {
152 return Some(mapped);
153 }
154
155 let s = ip.segments();
156
157 if s[0] == 0x2002 {
159 return Some(v4_of(s[1], s[2]));
160 }
161
162 if s[0] == 0x0064 && s[1] == 0xFF9B && s[2] == 0 && s[3] == 0 && s[4] == 0 && s[5] == 0 {
164 return Some(v4_of(s[6], s[7]));
165 }
166
167 if s[0] == 0 && s[1] == 0 && s[2] == 0 && s[3] == 0 && s[4] == 0 && s[5] == 0 {
170 return Some(v4_of(s[6], s[7]));
171 }
172
173 None
174}
175
176const fn v4_of(high: u16, low: u16) -> Ipv4Addr {
177 let [a, b] = high.to_be_bytes();
178 let [c, d] = low.to_be_bytes();
179
180 Ipv4Addr::new(a, b, c, d)
181}
182
183#[cfg(test)]
184mod tests {
185 use std::str::FromStr;
186
187 use super::*;
188
189 fn restricted(s: &str) -> bool {
190 !TargetPolicy::PublicOnly.permits_address(IpAddr::from_str(s).expect("valid address"))
191 }
192
193 fn url(s: &str) -> Url {
194 Url::parse(s).expect("valid url")
195 }
196
197 #[test]
198 fn blocks_loopback_and_metadata() {
199 assert!(restricted("127.0.0.1"));
200 assert!(restricted("127.1.2.3"));
201 assert!(restricted("0.0.0.0"));
202 assert!(restricted("169.254.169.254"));
203 assert!(restricted("::1"));
204 assert!(restricted("::"));
205 }
206
207 #[test]
208 fn blocks_private_ranges() {
209 assert!(restricted("10.0.0.1"));
210 assert!(restricted("172.16.0.1"));
211 assert!(restricted("192.168.1.1"));
212 assert!(restricted("100.64.0.1"));
213 assert!(restricted("198.18.0.1"));
214 assert!(restricted("192.0.0.1"));
215 assert!(restricted("255.255.255.255"));
216 assert!(restricted("240.0.0.1"));
217 }
218
219 #[test]
220 fn blocks_ipv6_local() {
221 assert!(restricted("fc00::1"));
222 assert!(restricted("fd00::1"));
223 assert!(restricted("fe80::1"));
224 assert!(restricted("ff02::1"));
225 }
226
227 #[test]
228 fn blocks_ipv4_mapped_loopback() {
229 assert!(restricted("::ffff:127.0.0.1"));
230 assert!(restricted("::ffff:169.254.169.254"));
231 assert!(restricted("::ffff:10.0.0.1"));
232 }
233
234 #[test]
237 fn blocks_every_ipv4_embedding() {
238 assert!(restricted("::127.0.0.1"), "IPv4-compatible");
239 assert!(restricted("::169.254.169.254"), "IPv4-compatible");
240 assert!(restricted("2002:7f00:1::"), "6to4 to 127.0.0.1");
241 assert!(restricted("2002:a9fe:a9fe::"), "6to4 to 169.254.169.254");
242 assert!(restricted("64:ff9b::127.0.0.1"), "NAT64");
243 assert!(restricted("64:ff9b::10.0.0.1"), "NAT64");
244 }
245
246 #[test]
247 fn blocks_reserved_ipv6_ranges() {
248 assert!(restricted("2001:db8::1"), "documentation");
249 assert!(restricted("2001::1"), "Teredo");
250 assert!(restricted("2001:2::1"), "benchmarking");
251 assert!(restricted("100::1"), "discard-only");
252 }
253
254 #[test]
255 fn allows_public() {
256 assert!(!restricted("1.1.1.1"));
257 assert!(!restricted("8.8.8.8"));
258 assert!(!restricted("192.0.3.1"));
259 assert!(!restricted("198.20.0.1"));
260 assert!(!restricted("2606:4700:4700::1111"));
261 assert!(!restricted("2001:4860:4860::8888"));
262 }
263
264 #[test]
267 fn allows_a_public_ipv4_embedding() {
268 assert!(!restricted("2002:808:808::"));
269 assert!(!restricted("64:ff9b::8.8.8.8"));
270 }
271
272 #[test]
273 fn allow_local_permits_every_address() {
274 for s in ["127.0.0.1", "169.254.169.254", "::1", "10.0.0.1"] {
275 let ip = IpAddr::from_str(s).expect("valid address");
276 assert!(TargetPolicy::AllowLocal.permits_address(ip), "{s}");
277 }
278 }
279
280 #[test]
281 fn public_only_refuses_plaintext() {
282 assert!(matches!(
283 TargetPolicy::PublicOnly.permits_url(&url("http://example.com/did.json")),
284 Err(TargetNotAllowed::Scheme)
285 ));
286 assert!(
287 TargetPolicy::PublicOnly
288 .permits_url(&url("https://example.com/did.json"))
289 .is_ok()
290 );
291 }
292
293 #[test]
294 fn public_only_refuses_a_restricted_literal_host() {
295 for s in [
296 "https://127.0.0.1/did.json",
297 "https://169.254.169.254/did.json",
298 "https://[::1]/did.json",
299 "https://[::ffff:10.0.0.1]/did.json",
300 ] {
301 assert!(
302 matches!(
303 TargetPolicy::PublicOnly.permits_url(&url(s)),
304 Err(TargetNotAllowed::Address(_))
305 ),
306 "{s}"
307 );
308 }
309 }
310
311 #[test]
313 fn a_hostname_is_left_to_the_address_check() {
314 assert!(
315 TargetPolicy::PublicOnly
316 .permits_url(&url("https://localhost/did.json"))
317 .is_ok()
318 );
319 }
320
321 #[test]
322 fn allow_local_permits_plaintext_and_restricted_literals() {
323 for s in [
324 "http://localhost:3000/did.json",
325 "https://127.0.0.1/did.json",
326 ] {
327 assert!(TargetPolicy::AllowLocal.permits_url(&url(s)).is_ok(), "{s}");
328 }
329 }
330
331 #[test]
332 fn only_localhost_is_plaintext_and_only_when_local_is_allowed() {
333 let cases = [
334 (TargetPolicy::AllowLocal, "localhost", "http"),
335 (TargetPolicy::AllowLocal, "localhost:3000", "http"),
336 (TargetPolicy::PublicOnly, "localhost", "https"),
337 (TargetPolicy::PublicOnly, "localhost:3000", "https"),
338 (TargetPolicy::AllowLocal, "example.com", "https"),
339 (TargetPolicy::AllowLocal, "127.0.0.1", "https"),
340 (TargetPolicy::AllowLocal, "localhost.evil.com", "https"),
341 ];
342
343 for (policy, domain, scheme) in cases {
344 assert_eq!(policy.scheme_for(domain), scheme, "{policy:?} {domain}");
345 }
346 }
347}