1use std::net::{IpAddr, Ipv4Addr, Ipv6Addr};
7
8#[must_use]
16pub fn is_public(address: IpAddr) -> bool {
17 match address {
18 IpAddr::V4(address) => public_v4(address),
19 IpAddr::V6(address) => public_v6(address),
20 }
21}
22
23fn public_v4(address: Ipv4Addr) -> bool {
24 let [a, b, c, _] = address.octets();
25 let reserved = a == 0
26 || a == 10
27 || a == 127
28 || (a == 100 && (64..128).contains(&b))
30 || (a == 169 && b == 254)
32 || (a == 172 && (16..32).contains(&b))
33 || (a == 192 && b == 168)
34 || (a == 192 && b == 0 && (c == 0 || c == 2))
36 || (a == 198 && b == 51 && c == 100)
37 || (a == 203 && b == 0 && c == 113)
38 || (a == 198 && (b == 18 || b == 19))
40 || a >= 224
42 || address == Ipv4Addr::new(168, 63, 129, 16);
46 !reserved
47}
48
49fn public_v6(address: Ipv6Addr) -> bool {
50 if let Some(v4) = address.to_ipv4_mapped() {
51 return public_v4(v4);
52 }
53 let [s0, s1, s2, s3, s4, s5, s6, s7] = address.segments();
54 if s0 == 0x0064 && s1 == 0xff9b && s2 == 0 && s3 == 0 && s4 == 0 && s5 == 0 {
57 let [a, b] = s6.to_be_bytes();
58 let [c, d] = s7.to_be_bytes();
59 return public_v4(Ipv4Addr::new(a, b, c, d));
60 }
61 let reserved =
62 (s0 == 0 && s1 == 0 && s2 == 0 && s3 == 0 && s4 == 0 && s5 == 0)
64 || (s0 == 0x0064 && s1 == 0xff9b)
70 || s0 == 0x2002
71 || (s0 == 0x2001 && (s1 & 0xfe00) == 0)
72 || (s0 == 0x0100 && s1 == 0 && s2 == 0 && s3 == 0)
74 || (s0 == 0x2001 && s1 == 0x0db8)
76 || (s0 & 0xfe00) == 0xfc00
78 || (s0 & 0xffc0) == 0xfe80
79 || (s0 & 0xffc0) == 0xfec0
80 || (s0 & 0xff00) == 0xff00;
81 !reserved && (s0 & 0xe000) == 0x2000
83}
84
85#[must_use]
94pub fn written_out(url: &url::Url) -> Option<IpAddr> {
95 match url.host() {
96 Some(url::Host::Ipv4(address)) => Some(IpAddr::V4(address)),
97 Some(url::Host::Ipv6(address)) => Some(IpAddr::V6(address)),
98 Some(url::Host::Domain(text)) => text.parse::<IpAddr>().ok(),
99 None => match url.origin() {
100 url::Origin::Tuple(_, url::Host::Ipv4(address), _) => Some(IpAddr::V4(address)),
101 url::Origin::Tuple(_, url::Host::Ipv6(address), _) => Some(IpAddr::V6(address)),
102 url::Origin::Tuple(_, url::Host::Domain(text), _) => text.parse::<IpAddr>().ok(),
103 url::Origin::Opaque(_) => None,
104 },
105 }
106}
107
108#[must_use]
112pub fn is_non_public_literal(url: &url::Url) -> bool {
113 written_out(url).is_some_and(|address| !is_public(address))
114}
115
116#[cfg(not(target_family = "wasm"))]
118fn literal(name: &str) -> Option<IpAddr> {
119 name.strip_prefix('[')
120 .and_then(|inner| inner.strip_suffix(']'))
121 .unwrap_or(name)
122 .parse()
123 .ok()
124}
125
126#[cfg(not(target_family = "wasm"))]
129pub type Lookup = std::sync::Arc<
130 dyn Fn(String) -> std::pin::Pin<Box<dyn Future<Output = std::io::Result<Vec<IpAddr>>> + Send>>
131 + Send
132 + Sync,
133>;
134
135#[cfg(not(target_family = "wasm"))]
138#[derive(Debug)]
139pub struct NotPublic {
140 pub name: String,
142}
143
144#[cfg(not(target_family = "wasm"))]
145impl std::fmt::Display for NotPublic {
146 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
147 write!(
148 f,
149 "{} answers with an address of this machine or its network",
150 self.name
151 )
152 }
153}
154
155#[cfg(not(target_family = "wasm"))]
156impl std::error::Error for NotPublic {}
157
158#[cfg(not(target_family = "wasm"))]
171pub async fn public_addresses(lookup: &Lookup, name: &str) -> std::io::Result<Vec<IpAddr>> {
172 let addresses = match literal(name) {
173 Some(address) => vec![address],
174 None => lookup(name.to_owned()).await?,
175 };
176 if addresses.is_empty() {
177 return Err(std::io::Error::new(
178 std::io::ErrorKind::NotFound,
179 format!("{name} does not resolve"),
180 ));
181 }
182 if addresses.iter().any(|address| !is_public(*address)) {
183 return Err(std::io::Error::other(NotPublic {
184 name: name.to_owned(),
185 }));
186 }
187 Ok(addresses)
188}
189
190#[cfg(not(target_family = "wasm"))]
193#[must_use]
194pub fn public_only(lookup: Lookup) -> Lookup {
195 std::sync::Arc::new(move |name: String| {
196 let lookup = std::sync::Arc::clone(&lookup);
197 Box::pin(async move { public_addresses(&lookup, &name).await })
198 })
199}
200
201#[must_use]
206pub fn webhook_refusal(url: &str) -> Option<&'static str> {
207 const OWN_ADDRESS: &str = "a webhook posts to the public internet, and this URL names an \
209 address of the device's own machine or network";
210 const PUBLIC_OR_HERE: &str = "a webhook posts to an https URL on the public internet, or \
212 over plain http to this computer";
213 const LOCALHOST: &str = "localhost";
214 let Ok(url) = url::Url::parse(url) else {
215 return Some(PUBLIC_OR_HERE);
216 };
217 let written = written_out(&url);
218 match url.scheme() {
219 "https" if written.is_some_and(|address| !is_public(address)) => Some(OWN_ADDRESS),
220 "https" => None,
221 "http" => match written {
222 Some(address) if address.is_loopback() => None,
223 None if url.domain() == Some(LOCALHOST) => None,
224 _ => Some(PUBLIC_OR_HERE),
225 },
226 _ => Some(PUBLIC_OR_HERE),
227 }
228}
229
230#[cfg(not(target_family = "wasm"))]
233#[must_use]
234pub fn system_lookup() -> Lookup {
235 std::sync::Arc::new(|name: String| {
236 Box::pin(async move {
237 if let Some(address) = literal(&name) {
240 return Ok(vec![address]);
241 }
242 tokio::task::spawn_blocking(move || {
243 std::net::ToSocketAddrs::to_socket_addrs(&(name.as_str(), 0))
244 .map(|found| found.map(|address| address.ip()).collect::<Vec<IpAddr>>())
245 })
246 .await
247 .map_err(std::io::Error::other)?
248 })
249 })
250}
251
252#[cfg(not(target_family = "wasm"))]
265pub fn asked_as_written(lookup: &Lookup, address: IpAddr) -> std::io::Result<()> {
266 let mut asking = lookup(address.to_string());
267 let mut context = std::task::Context::from_waker(std::task::Waker::noop());
268 match asking.as_mut().poll(&mut context) {
269 std::task::Poll::Ready(Ok(answered)) if answered.contains(&address) => Ok(()),
270 std::task::Poll::Ready(Err(refused)) => Err(refused),
271 std::task::Poll::Ready(Ok(_)) | std::task::Poll::Pending => Err(std::io::Error::other(
272 format!("{address} is not an address its lookup answers"),
273 )),
274 }
275}
276
277#[cfg(not(target_family = "wasm"))]
280#[must_use]
281pub fn not_public(error: &std::io::Error) -> bool {
282 matches!(error.get_ref(), Some(inner) if inner.is::<NotPublic>())
283}
284
285#[cfg(test)]
286mod tests {
287 use super::*;
288
289 #[test]
295 fn an_address_a_url_writes_out_is_asked_of_a_lookup_without_waiting() {
296 let own = IpAddr::from([10, 0, 0, 8]);
297 let public = IpAddr::from([93, 184, 216, 34]);
298 assert!(asked_as_written(&system_lookup(), own).is_ok());
299 let judged = public_only(system_lookup());
300 assert!(asked_as_written(&judged, public).is_ok());
301 let refused = asked_as_written(&judged, own).expect_err("an own address");
302 assert!(not_public(&refused), "the judge's refusal: {refused}");
303 let loopback = asked_as_written(&judged, IpAddr::from(Ipv6Addr::LOCALHOST));
304 assert!(loopback.is_err_and(|refused| not_public(&refused)));
305 let waits: Lookup = std::sync::Arc::new(|_: String| {
306 Box::pin(std::future::pending::<std::io::Result<Vec<IpAddr>>>())
307 });
308 assert!(asked_as_written(&waits, public).is_err());
309 let elsewhere: Lookup =
310 std::sync::Arc::new(move |_: String| Box::pin(async move { Ok(vec![own]) }));
311 assert!(asked_as_written(&elsewhere, public).is_err());
312 }
313
314 #[test]
318 fn every_form_of_an_own_address_is_not_public() {
319 let own = [
320 "0.0.0.0",
322 "0.1.2.3",
323 "10.0.0.7",
324 "127.0.0.1",
325 "100.64.0.1",
326 "100.100.100.200",
327 "169.254.169.254",
328 "169.254.170.2",
329 "172.16.0.1",
330 "172.31.255.255",
331 "192.168.1.1",
332 "192.0.0.1",
333 "192.0.2.1",
334 "198.18.0.1",
335 "198.51.100.1",
336 "203.0.113.1",
337 "224.0.0.1",
338 "240.0.0.1",
339 "255.255.255.255",
340 "168.63.129.16",
342 "::",
343 "::1",
344 "fe80::1",
345 "febf::1",
346 "fe80::a9fe:a9fe",
347 "fc00::1",
348 "fd00:ec2::254",
349 "fdff:ffff::1",
350 "fec0::1",
351 "ff02::1",
352 "::ffff:127.0.0.1",
355 "::ffff:169.254.169.254",
356 "::ffff:10.0.0.7",
357 "::127.0.0.1",
358 "::10.0.0.7",
359 "64:ff9b::7f00:1",
360 "64:ff9b::a9fe:a9fe",
361 "64:ff9b:1::7f00:1",
362 "64:ff9b:1::101:101",
363 "2002:7f00:1::",
364 "2002:a00:7::1",
365 "2002:101:101::",
366 "2001:0:4136:e378:8000:63bf:3fff:fdd2",
367 "2001::1",
368 "2001:1::1",
369 "100::1",
372 "2001:db8::1",
373 "4000::1",
374 ];
375 let let_through: Vec<&str> = own
376 .into_iter()
377 .filter(|address| is_public(address.parse().unwrap()))
378 .collect();
379 assert!(
380 let_through.is_empty(),
381 "addresses of this machine or its network judged public: {let_through:#?}"
382 );
383 for public in [
384 "1.1.1.1",
385 "93.184.216.34",
386 "172.32.0.1",
387 "100.128.0.1",
388 "168.63.129.17",
389 "2606:4700:4700::1111",
390 "2a00:1450:4001:81b::200e",
391 "2001:4860:4860::8888",
392 "::ffff:1.1.1.1",
393 "64:ff9b::5db8:d822",
394 ] {
395 assert!(is_public(public.parse().unwrap()), "{public} is public");
396 }
397 }
398
399 #[cfg(not(target_family = "wasm"))]
403 #[tokio::test]
404 async fn a_name_is_connected_to_only_where_every_address_it_answers_with_is_public() {
405 use std::sync::Arc;
406 use std::sync::atomic::{AtomicUsize, Ordering};
407
408 let asked = Arc::new(AtomicUsize::new(0));
409 let counted = Arc::clone(&asked);
410 let lookup: Lookup = Arc::new(
411 move |name: String| -> std::pin::Pin<
412 Box<dyn Future<Output = std::io::Result<Vec<IpAddr>>> + Send>,
413 > {
414 counted.fetch_add(1, Ordering::SeqCst);
415 Box::pin(async move {
416 let answer = |addresses: &[&str]| -> Vec<IpAddr> {
417 addresses
418 .iter()
419 .map(|address| address.parse().unwrap())
420 .collect()
421 };
422 match name.as_str() {
423 "public.example" => Ok(answer(&["93.184.216.34", "2606:2800:220:1::1"])),
424 "both.example" => Ok(answer(&["93.184.216.34", "10.0.0.7"])),
425 "own.example" => Ok(answer(&["::ffff:127.0.0.1"])),
426 "nothing.example" => Ok(Vec::new()),
427 _ => Err(std::io::Error::other("the resolver is down")),
428 }
429 })
430 },
431 );
432
433 let public = public_addresses(&lookup, "public.example").await.unwrap();
434 assert_eq!(public.len(), 2, "every address of the one answer");
435 assert_eq!(asked.load(Ordering::SeqCst), 1, "one look-up");
436 for name in ["both.example", "own.example"] {
437 let refused = public_addresses(&lookup, name).await.unwrap_err();
438 assert!(not_public(&refused), "{name}: {refused}");
439 }
440 let nothing = public_addresses(&lookup, "nothing.example")
441 .await
442 .unwrap_err();
443 assert_eq!(nothing.kind(), std::io::ErrorKind::NotFound);
444 assert!(!not_public(¬hing));
445 let failed = public_addresses(&lookup, "down.example").await.unwrap_err();
446 assert!(!not_public(&failed), "a look-up that failed is no refusal");
447
448 let only = public_only(Arc::clone(&lookup));
450 assert_eq!(only("public.example".to_owned()).await.unwrap(), public);
451 let refused = only("both.example".to_owned()).await.unwrap_err();
452 assert!(not_public(&refused), "{refused}");
453 assert_eq!(asked.load(Ordering::SeqCst), 7, "one look-up a call");
454
455 let written = public_addresses(&lookup, "93.184.216.34").await.unwrap();
457 assert_eq!(written, ["93.184.216.34".parse::<IpAddr>().unwrap()]);
458 for own in ["10.0.0.5", "[::1]", "::ffff:127.0.0.1"] {
459 let refused = public_addresses(&lookup, own).await.unwrap_err();
460 assert!(not_public(&refused), "{own}: {refused}");
461 }
462 assert_eq!(
463 asked.load(Ordering::SeqCst),
464 7,
465 "an address written out is never looked up"
466 );
467 }
468
469 #[test]
472 fn an_address_a_url_writes_out_is_found_and_a_name_is_not() {
473 for (url, address) in [
474 ("https://10.0.0.7/x", "10.0.0.7"),
475 ("https://[::1]:8443/x", "::1"),
476 ("http://[::ffff:127.0.0.1]/", "::ffff:127.0.0.1"),
477 ("https://0x7f.1/", "127.0.0.1"),
478 ("https://2130706433/", "127.0.0.1"),
479 ] {
480 assert_eq!(
481 written_out(&url::Url::parse(url).unwrap()),
482 Some(address.parse().unwrap()),
483 "{url}"
484 );
485 }
486 for url in ["https://example.com/", "mailto:ops@example.com"] {
487 assert_eq!(written_out(&url::Url::parse(url).unwrap()), None, "{url}");
488 }
489 }
490
491 #[cfg(not(target_family = "wasm"))]
494 #[tokio::test]
495 async fn the_systems_resolver_answers_and_this_machines_own_name_is_refused() {
496 let system = system_lookup();
497 let found = system("localhost".to_owned()).await.unwrap();
498 assert!(!found.is_empty() && found.iter().all(IpAddr::is_loopback));
499 let refused = public_addresses(&system, "localhost").await.unwrap_err();
500 assert!(not_public(&refused), "{refused}");
501 }
502
503 mod superseded_readings {
506 use std::net::IpAddr;
507
508 pub(super) fn proxy_match(url: &url::Url) -> Option<IpAddr> {
510 match url.host() {
511 None | Some(url::Host::Domain(_)) => None,
512 Some(url::Host::Ipv4(address)) => Some(IpAddr::V4(address)),
513 Some(url::Host::Ipv6(address)) => Some(IpAddr::V6(address)),
514 }
515 }
516
517 pub(super) fn previous_written_out(url: &url::Url) -> Option<IpAddr> {
519 let url::Origin::Tuple(_, named, _) = url.origin() else {
520 return None;
521 };
522 let name = named.to_string();
523 name.strip_prefix('[')
524 .and_then(|inner| inner.strip_suffix(']'))
525 .unwrap_or(&name)
526 .parse()
527 .ok()
528 }
529
530 pub(super) fn web_call_slicing(url: &url::Url) -> Option<IpAddr> {
533 if url.domain().is_some() {
534 return None;
535 }
536 let origin = url.origin().ascii_serialization();
537 let at = origin.split_once("://").map_or("", |(_, at)| at);
538 let literal = at.strip_prefix('[').map_or_else(
539 || at.rsplit_once(':').map_or(at, |(address, _)| address),
540 |inside| inside.split(']').next().unwrap_or_default(),
541 );
542 literal.parse::<IpAddr>().ok()
543 }
544
545 pub(super) fn connections_address_trim(url: &url::Url) -> Option<IpAddr> {
548 url.host_str().and_then(|literal| {
549 literal
550 .trim_start_matches('[')
551 .trim_end_matches(']')
552 .parse::<IpAddr>()
553 .ok()
554 })
555 }
556
557 pub(super) fn calendars_slicing(url: &url::Url) -> Option<IpAddr> {
560 if url.domain().is_some() {
561 return None;
562 }
563 let origin = url.origin().ascii_serialization();
564 let at = origin.split_once("://").map_or("", |(_, at)| at);
565 let address = at.strip_prefix('[').map_or_else(
566 || at.rsplit_once(':').map_or(at, |(address, _)| address),
567 |inside| inside.split(']').next().unwrap_or_default(),
568 );
569 address.parse::<IpAddr>().ok()
570 }
571
572 pub(super) fn model_gateway_trim(url: &url::Url) -> Option<IpAddr> {
575 if url.domain().is_some() {
576 return None;
577 }
578 url.host_str()
579 .map(|host| host.trim_start_matches('[').trim_end_matches(']'))
580 .and_then(|host| host.parse::<IpAddr>().ok())
581 }
582 }
583
584 const COMPARISON_TABLE: &[(&str, Option<&str>)] = &[
585 ("http://127.0.0.1/", Some("127.0.0.1")),
587 ("https://127.255.255.254/", Some("127.255.255.254")),
588 ("https://0.0.0.0/", Some("0.0.0.0")),
589 ("https://10.0.0.1/", Some("10.0.0.1")),
590 ("https://100.64.0.1/", Some("100.64.0.1")),
591 (
592 "https://169.254.169.254/latest/meta-data/",
593 Some("169.254.169.254"),
594 ),
595 ("https://168.63.129.16/", Some("168.63.129.16")),
596 ("https://172.16.0.1/", Some("172.16.0.1")),
597 ("https://192.168.1.1/", Some("192.168.1.1")),
598 ("https://1.1.1.1/", Some("1.1.1.1")),
599 ("http://[::1]/", Some("::1")),
601 ("https://[0:0:0:0:0:0:0:1]/", Some("::1")),
602 ("https://[fe80::1]/", Some("fe80::1")),
603 ("https://[fc00::1]/", Some("fc00::1")),
604 ("https://[fd12:3456::1]/", Some("fd12:3456::1")),
605 (
606 "https://[2606:4700:4700::1111]/",
607 Some("2606:4700:4700::1111"),
608 ),
609 ("http://[::ffff:127.0.0.1]/", Some("::ffff:127.0.0.1")),
610 ("https://[::ffff:7f00:1]/", Some("::ffff:127.0.0.1")),
611 ("https://[::ffff:10.0.0.7]/", Some("::ffff:10.0.0.7")),
612 ("https://[::ffff:1.1.1.1]/", Some("::ffff:1.1.1.1")),
613 ("https://[::127.0.0.1]/", Some("::127.0.0.1")),
614 ("http://2130706433/", Some("127.0.0.1")),
616 ("http://0x7f000001/", Some("127.0.0.1")),
617 ("http://0x7f.1/", Some("127.0.0.1")),
618 ("http://0177.0.0.1/", Some("127.0.0.1")),
619 ("http://127.1/", Some("127.0.0.1")),
620 ("http://10.0.1/", Some("10.0.0.1")),
621 ("http://0/", Some("0.0.0.0")),
622 ("http://%31%32%37.0.0.1/", Some("127.0.0.1")),
623 (
624 "http://\u{ff11}\u{ff12}\u{ff17}.\u{ff10}.\u{ff10}.\u{ff11}/",
625 Some("127.0.0.1"),
626 ),
627 ("http://127.0.0.1./", Some("127.0.0.1")),
629 ("https://10.0.0.1.:8443/", Some("10.0.0.1")),
630 ("https://1.1.1.1./", Some("1.1.1.1")),
631 ("http://user:pass@127.0.0.1/", Some("127.0.0.1")),
632 ("https://user:pass@[::1]:8443/", Some("::1")),
633 ("http://1.1.1.1@127.0.0.1/", Some("127.0.0.1")),
634 ("http://127.0.0.1@1.1.1.1/", Some("1.1.1.1")),
635 ("http://127.0.0.1:8080/", Some("127.0.0.1")),
636 ("https://[::1]:443/", Some("::1")),
637 ("blob:http://127.0.0.1/x", Some("127.0.0.1")),
639 ("blob:http://[::1]/x", Some("::1")),
640 ("blob:https://1.1.1.1/x", Some("1.1.1.1")),
641 ("redis://127.0.0.1/", Some("127.0.0.1")),
642 ("redis://1.1.1.1/", Some("1.1.1.1")),
643 ("file://127.0.0.1/etc/passwd", Some("127.0.0.1")),
644 ("file://[::1]/etc/passwd", Some("::1")),
645 ("gopher://[::1]/", Some("::1")),
646 ("https://example.com/", None),
648 ("https://example.com./", None),
649 ("https://127.0.0.1.example.com/", None),
650 ("https://127-0-0-1.nip.io/", None),
651 ("https://0x7f.example/", None),
652 ("file:///etc/passwd", None),
653 ];
654
655 #[test]
658 fn written_out_covers_every_superseded_literal_address_reading() {
659 type Reading = (&'static str, fn(&url::Url) -> Option<IpAddr>);
660 let old_readings: [Reading; 6] = [
661 ("proxy_match", superseded_readings::proxy_match),
662 (
663 "previous_written_out",
664 superseded_readings::previous_written_out,
665 ),
666 ("web_call_slicing", superseded_readings::web_call_slicing),
667 (
668 "connections_address_trim",
669 superseded_readings::connections_address_trim,
670 ),
671 ("calendars_slicing", superseded_readings::calendars_slicing),
672 (
673 "model_gateway_trim",
674 superseded_readings::model_gateway_trim,
675 ),
676 ];
677
678 let mut disagreed = Vec::new();
679 for &(raw, expected) in COMPARISON_TABLE {
680 let url = url::Url::parse(raw).unwrap();
681 let expected: Option<IpAddr> = expected.map(|text| text.parse().unwrap());
682 let unified = written_out(&url);
683 assert_eq!(unified, expected, "{raw}");
684 assert_eq!(
685 is_non_public_literal(&url),
686 unified.is_some_and(|address| !is_public(address)),
687 "{raw}"
688 );
689 let old_answers: Vec<(&str, Option<IpAddr>)> = old_readings
690 .iter()
691 .map(|(name, read)| (*name, read(&url)))
692 .collect();
693 for (name, answer) in &old_answers {
694 if let Some(address) = *answer {
695 assert_eq!(
696 unified,
697 Some(address),
698 "{raw}: {name} reported {address}, unified reported {unified:?}"
699 );
700 }
701 }
702 if old_answers.iter().any(|(_, a)| *a != old_answers[0].1) {
703 disagreed.push(raw);
704 }
705 }
706 assert_eq!(
707 disagreed,
708 vec![
709 "blob:http://127.0.0.1/x",
710 "blob:http://[::1]/x",
711 "blob:https://1.1.1.1/x",
712 "redis://127.0.0.1/",
713 "redis://1.1.1.1/",
714 "file://127.0.0.1/etc/passwd",
715 "file://[::1]/etc/passwd",
716 "gopher://[::1]/",
717 ]
718 );
719 }
720}