Skip to main content

tilo_net/
address.rs

1//! One judge of whether an address is on the public internet, for every
2//! caller that keeps a request off this machine and its network: the fetch
3//! proxy ([`crate::proxy`]) and the guard of a page's fetch both ask it, and
4//! neither keeps a list of its own.
5
6use std::net::{IpAddr, Ipv4Addr, Ipv6Addr};
7
8/// Whether `address` is on the public internet: not loopback, private
9/// (RFC 1918, unique-local), link-local, shared (carrier-grade NAT),
10/// multicast, unspecified, documentation or otherwise reserved, and not the
11/// address a cloud answers its own machines on. An IPv6 address that carries
12/// an IPv4 one is judged by it where it is mapped or translated under the
13/// well-known prefix; the blocks that carry or stand for one in another way
14/// are not public at all.
15#[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        // Shared address space (carrier-grade NAT), 100.64.0.0/10.
29        || (a == 100 && (64..128).contains(&b))
30        // Link-local, 169.254.0.0/16, a cloud's metadata among it.
31        || (a == 169 && b == 254)
32        || (a == 172 && (16..32).contains(&b))
33        || (a == 192 && b == 168)
34        // IETF protocol assignments, 192.0.0.0/24, and documentation.
35        || (a == 192 && b == 0 && (c == 0 || c == 2))
36        || (a == 198 && b == 51 && c == 100)
37        || (a == 203 && b == 0 && c == 113)
38        // Benchmarking, 198.18.0.0/15.
39        || (a == 198 && (b == 18 || b == 19))
40        // Multicast, reserved and broadcast, 224.0.0.0/3.
41        || a >= 224
42        // The one address Azure answers its own machines on (their metadata
43        // and their agent's own service): public by its range, reached only
44        // from inside a machine there.
45        || 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    // NAT64 under the well-known prefix (64:ff9b::/96) reaches the IPv4
55    // address it ends in.
56    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        // ::, ::1 and the deprecated IPv4-compatible addresses, ::/96.
63        (s0 == 0 && s1 == 0 && s2 == 0 && s3 == 0 && s4 == 0 && s5 == 0)
64        // Blocks that carry or stand for an IPv4 address in a way this does
65        // not judge, none of them a place of the public web: the rest of
66        // 64:ff9b::/32 with the local-use translation prefix
67        // (64:ff9b:1::/48), 6to4 (2002::/16) and the protocol assignments
68        // with Teredo among them (2001::/23).
69        || (s0 == 0x0064 && s1 == 0xff9b)
70        || s0 == 0x2002
71        || (s0 == 0x2001 && (s1 & 0xfe00) == 0)
72        // Discard-only, 100::/64.
73        || (s0 == 0x0100 && s1 == 0 && s2 == 0 && s3 == 0)
74        // Documentation, 2001:db8::/32.
75        || (s0 == 0x2001 && s1 == 0x0db8)
76        // Unique-local, link-local, site-local and multicast.
77        || (s0 & 0xfe00) == 0xfc00
78        || (s0 & 0xffc0) == 0xfe80
79        || (s0 & 0xffc0) == 0xfec0
80        || (s0 & 0xff00) == 0xff00;
81    // Only global unicast (2000::/3) is routed on the internet.
82    !reserved && (s0 & 0xe000) == 0x2000
83}
84
85/// The address `url` writes out where a name would stand, if it writes one:
86/// `https://10.0.0.7/` and `https://[::1]/` do, `https://example.com/` does
87/// not. Reads the parsed host (`Host::Ipv4`, `Host::Ipv6`, or a non-special
88/// scheme's opaque `Host::Domain` whose text parses as an `IpAddr`), and for a
89/// URL without a host (such as `blob:http://127.0.0.1/…`) reads the origin
90/// tuple's host. Such an address is never looked up, so whoever keeps a
91/// request to the public internet judges it ([`is_public`]) before anything is
92/// sent; a name is judged where it is looked up.
93#[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/// Whether `url` writes out a literal address ([`written_out`]) that is not on
109/// the public internet ([`is_public`]). A domain name or a URL that names no
110/// address is never one.
111#[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/// `name` as the address it writes out, in brackets or not.
117#[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/// Resolves a name to its addresses: the shape of a client's lookup
127/// ([`crate::Lookup`]) and of the fetch proxy's, so one value serves them all.
128#[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/// Why a name is not connected to: an address it answered with is not on the
136/// public internet.
137#[cfg(not(target_family = "wasm"))]
138#[derive(Debug)]
139pub struct NotPublic {
140    /// The name that was looked up.
141    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/// The addresses to connect to for `name`: one look-up, every address it
159/// answered with judged ([`is_public`]), and all of them handed back or none.
160/// A caller connects to exactly these and looks nothing up again, so no
161/// second look-up, which might answer otherwise, lies between the judging and
162/// the connection. A name that answers with a public and an own address is
163/// refused whole, since a connection might take either. A name that is itself
164/// an address is judged as that address and is never looked up.
165///
166/// # Errors
167/// The look-up's own failure; `NotFound` for a name that answers with
168/// nothing; and for a name that is refused an error that holds
169/// [`NotPublic`], which [`not_public`] tells apart.
170#[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/// `lookup`, answering a name only as [`public_addresses`] does: the lookup
191/// of a connection that reaches the public internet and nothing else.
192#[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/// Why no webhook delivery is posted to `url`, where none is: over `https` to an address on the
202/// public internet, or over plain `http` to this machine's own loopback, for the person's own
203/// programs there. A name is judged where the connection looks it up (see `public_only`); this
204/// refuses only what the URL itself writes out.
205#[must_use]
206pub fn webhook_refusal(url: &str) -> Option<&'static str> {
207    /// What either says of an address of its own written into a URL.
208    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    /// What a URL that is no such address says.
211    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/// The system's resolver, as a [`Lookup`]. A name that is itself an address
231/// is answered with that address at once: the resolver is not asked for it.
232#[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            // An address is its own answer: nothing is asked for it and
238            // nothing is waited for.
239            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/// Whether `lookup` would have `address` dialled, for an address that a URL
253/// writes out ([`written_out`]): no connection looks such an address up, so
254/// whoever gave its client a lookup asks it here, with the address as the
255/// name, before anything is sent. The lookup is asked once and not waited
256/// for: a name that is itself an address needs no look-up, and every lookup
257/// of this module answers it at once. So a caller on a thread that awaits
258/// nothing can ask.
259///
260/// # Errors
261/// The lookup's own refusal, of which [`not_public`] tells the judge's; and
262/// for a lookup that answers another address, or would wait, a refusal that
263/// says so.
264#[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/// Whether `error` is the refusal of [`public_addresses`], not a look-up
278/// that failed.
279#[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    /// An address is its own answer, at once: the system's resolver is not
290    /// waited for, and the judge over it refuses an own address and passes a
291    /// public one. So the address a URL writes out is asked about from a
292    /// thread that awaits nothing. A lookup that would wait for it, or that
293    /// answers another address, has it dialled by nobody.
294    #[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    /// Every form of an address of this machine or its network is not
315    /// public, in IPv6 as in IPv4, and the public web is: the one table the
316    /// fetch proxy and a page's fetch are both judged by.
317    #[test]
318    fn every_form_of_an_own_address_is_not_public() {
319        let own = [
320            // Unspecified, loopback, private, shared, link-local, reserved.
321            "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            // The one address Azure answers its own machines on.
341            "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            // An IPv4 address inside an IPv6 one: mapped, compatible,
353            // translated under both prefixes, 6to4 and Teredo.
354            "::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            // Where no page is: discard-only, documentation, and what lies
370            // outside global unicast.
371            "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    /// A name is connected to only where every address it answered with is
400    /// public: one look-up, all of its addresses handed back or none, and a
401    /// refusal told apart from a look-up that failed.
402    #[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(&nothing));
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        // The lookup a connection is given answers the same.
449        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        // A name that is itself an address is judged as that address.
456        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    /// An address written into a URL is found in the forms a URL takes, and
470    /// a name is not one.
471    #[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    /// The system's resolver answers for this machine's own name, and that
492    /// name is refused: nothing leaves the machine for it.
493    #[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    /// Verbatim test-only copies of every literal-address reading that existed
504    /// before `written_out` unified them.
505    mod superseded_readings {
506        use std::net::IpAddr;
507
508        /// `crates/platform/tilo-net/src/proxy/host.rs` (`check_target`).
509        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        /// Previous `crates/platform/tilo-net/src/address.rs` (`written_out`).
518        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        /// `crates/core/tilo-workspace-service/src/workspaces/hosted_use/web_call.rs`
531        /// (`literal_inside`, returning the parsed address before `!is_public`).
532        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        /// `crates/core/tilo-workspace-service/src/connections/address.rs`
546        /// (`literal_inside`, returning the parsed address before `!is_public`).
547        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        /// `crates/core/tilo-workspace-service/src/workspaces/person_settings/calendars/connect.rs`
558        /// (`literal`).
559        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        /// `crates/integrations/model-gateway/src/host_backend.rs` (`public_endpoint`,
573        /// literal branch after its `url.domain().is_some()` guard).
574        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        // Plain IPv4: loopback, unspecified, private, CGNAT, link-local, Azure, public.
586        ("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        // Bracketed IPv6 and IPv4-mapped / IPv4-compatible IPv6.
600        ("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        // Unusual IPv4 spellings as `url` normalises them.
615        ("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        // Trailing dot, credentials, and ports.
628        ("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        // Schemes where the superseded readings disagreed.
638        ("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        // Real domains and domains that only look like an address.
647        ("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    /// `written_out` reports an address whenever any of the six superseded
656    /// readings reports one, and reports the exact same address.
657    #[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}