Skip to main content

weida_core/
host.rs

1//! The host a remote peer counts as.
2//!
3//! A listener that bounds what one peer may hold has to decide what "one peer"
4//! is, and the socket address is the wrong answer: an IPv6 host is routed a
5//! whole `/64` and picks the rest of the address itself, and a dual-stack
6//! listener sees an IPv4 client under two spellings. Every transport crate that
7//! keeps such a ceiling asks this module, so that they bound the same threat the
8//! same way and the rule has one place to be wrong in.
9
10use std::net::{IpAddr, Ipv6Addr};
11
12/// How a per-host ceiling counts the peer at one address.
13///
14/// Built by [`host_key`].
15#[derive(Clone, Copy, Debug, PartialEq, Eq)]
16pub struct HostKey {
17    /// What the ceiling counts the peer under: its IPv4 address, or its IPv6
18    /// address with the low 64 bits cleared.
19    ///
20    /// Count under this and not under the whole `HostKey`: [`HostKey::loopback`]
21    /// is a fact about the address and not part of the host, and two addresses
22    /// of one `/64` can disagree on it.
23    pub key: IpAddr,
24    /// Whether the peer is this machine's own processes, in any form.
25    ///
26    /// A ceiling that exists to stop a stranger from holding the table has
27    /// nothing to say about loopback, which a test or a sidecar legitimately
28    /// opens by the thousand; whether to count it anyway is the caller's
29    /// decision, and this is what it needs to make it.
30    pub loopback: bool,
31}
32
33/// The key a per-host ceiling counts the peer at `ip` under, and whether that
34/// peer is local. A listener takes `ip` from the accepted connection's
35/// [`SocketAddr::ip`](std::net::SocketAddr::ip).
36///
37/// An IPv4 peer is counted by its address and an IPv6 peer by its `/64`. An
38/// IPv6 host is routed a whole `/64`, so a count per address would be a count
39/// per suffix the host chooses: one host could hold every slot of a table while
40/// staying under the ceiling of each address it connects from. An IPv4-mapped
41/// IPv6 address — what an IPv4 client looks like to a dual-stack listener,
42/// `tcp://[::]:port` — is counted as the IPv4 address it carries, so one host
43/// is one key however it reaches the listener.
44///
45/// Loopback is judged on the canonical address and **before** the `/64` is
46/// taken. `::ffff:127.0.0.1` is loopback like `127.0.0.1`, and `::2` is not,
47/// though it shares `::1`'s `/64` and therefore its key.
48pub fn host_key(ip: IpAddr) -> HostKey {
49    let ip = ip.to_canonical();
50    let key = match ip {
51        IpAddr::V4(_) => ip,
52        IpAddr::V6(v6) => {
53            let [a, b, c, d, ..] = v6.segments();
54            IpAddr::V6(Ipv6Addr::new(a, b, c, d, 0, 0, 0, 0))
55        }
56    };
57    HostKey {
58        key,
59        loopback: ip.is_loopback(),
60    }
61}
62
63#[cfg(test)]
64mod tests {
65    use super::*;
66
67    fn of(text: &str) -> HostKey {
68        host_key(text.parse().expect("an address"))
69    }
70
71    fn address(text: &str) -> IpAddr {
72        text.parse().expect("an address")
73    }
74
75    /// Claim: an IPv4 peer is counted by its own address, and two addresses are
76    /// two hosts.
77    #[test]
78    fn an_ipv4_peer_is_its_own_key() {
79        assert_eq!(of("192.0.2.1").key, address("192.0.2.1"));
80        assert_ne!(of("192.0.2.1").key, of("192.0.2.2").key);
81    }
82
83    /// Claim: an IPv6 host is its `/64`: every address of one is one key, and
84    /// the key is the prefix with the host part cleared.
85    #[test]
86    fn an_ipv6_peer_is_its_slash_64() {
87        let host = of("2001:db8:0:1::1").key;
88        assert_eq!(host, address("2001:db8:0:1::"));
89        assert_eq!(host, of("2001:db8:0:1:ffff:ffff:ffff:ffff").key);
90        assert_eq!(host, of("2001:db8:0:1:dead:beef:0:7").key);
91        assert_ne!(
92            host,
93            of("2001:db8:0:2::1").key,
94            "the next /64 is another host"
95        );
96        assert_ne!(
97            host,
98            of("2001:db8:1:1::1").key,
99            "a difference in the prefix is another host"
100        );
101    }
102
103    /// Claim: an IPv4 client of a dual-stack listener is the IPv4 host it
104    /// carries, so the mapped and the plain form are one key.
105    #[test]
106    fn an_ipv4_mapped_address_is_the_ipv4_host_it_carries() {
107        assert_eq!(of("::ffff:192.0.2.1").key, of("192.0.2.1").key);
108        assert_eq!(of("::ffff:192.0.2.1").key, address("192.0.2.1"));
109        assert_ne!(of("::ffff:192.0.2.1").key, of("::ffff:192.0.2.2").key);
110    }
111
112    /// Claim: loopback is recognised in every form, judged on the canonical
113    /// address and before the `/64` is taken — so `::2`, which shares `::1`'s
114    /// key, is not loopback, and the flag and not the key is what tells them
115    /// apart.
116    #[test]
117    fn loopback_is_judged_on_the_address_and_not_on_the_key() {
118        for local in ["127.0.0.1", "127.255.255.254", "::1", "::ffff:127.0.0.1"] {
119            assert!(of(local).loopback, "{local} is loopback");
120        }
121        for remote in ["192.0.2.1", "2001:db8::1", "::", "::2", "::ffff:192.0.2.1"] {
122            assert!(!of(remote).loopback, "{remote} is not loopback");
123        }
124        assert_eq!(of("::1").key, of("::2").key);
125        assert_ne!(of("::1").loopback, of("::2").loopback);
126    }
127}