Skip to main content

tea_coding_tools/web_fetch/
address_policy.rs

1use std::fmt;
2use std::net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr};
3
4use thiserror::Error;
5
6/// Address-policy failure detected before creating an HTTP connection.
7#[derive(Debug, Clone, Copy, PartialEq, Eq, Error)]
8pub enum FetchAddressPolicyError {
9    /// DNS returned no usable A or AAAA records.
10    #[error("web fetch DNS response is empty")]
11    Empty,
12    /// At least one DNS answer belongs to a forbidden address range.
13    #[error("web fetch DNS response contains a forbidden address")]
14    Forbidden,
15}
16
17/// Immutable IP-address policy applied to every DNS answer and peer address.
18#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
19pub struct FetchAddressPolicy {
20    allow_loopback: bool,
21}
22
23impl FetchAddressPolicy {
24    /// Creates the production public-network policy.
25    #[must_use]
26    pub const fn public_network() -> Self {
27        Self {
28            allow_loopback: false,
29        }
30    }
31
32    /// Creates a policy for deterministic loopback fixture servers.
33    ///
34    /// All non-loopback private, link-local, reserved, and multicast ranges
35    /// remain forbidden.
36    #[must_use]
37    pub const fn loopback_tests() -> Self {
38        Self {
39            allow_loopback: true,
40        }
41    }
42
43    /// Validates every resolved A/AAAA answer and returns a deterministic set.
44    ///
45    /// # Errors
46    ///
47    /// Rejects empty answers and the entire answer set when any address is
48    /// forbidden. This prevents a safe first record from hiding a private or
49    /// metadata address later in the DNS response.
50    pub fn validate<I>(
51        &self,
52        addresses: I,
53    ) -> Result<ValidatedFetchAddresses, FetchAddressPolicyError>
54    where
55        I: IntoIterator<Item = IpAddr>,
56    {
57        let mut addresses = addresses.into_iter().collect::<Vec<_>>();
58        addresses.sort();
59        addresses.dedup();
60        if addresses.is_empty() {
61            return Err(FetchAddressPolicyError::Empty);
62        }
63        if addresses
64            .iter()
65            .copied()
66            .any(|address| !self.allows(address))
67        {
68            return Err(FetchAddressPolicyError::Forbidden);
69        }
70        Ok(ValidatedFetchAddresses { addresses })
71    }
72
73    /// Returns whether one resolved or connected address satisfies the policy.
74    #[must_use]
75    pub fn allows(&self, address: IpAddr) -> bool {
76        match address {
77            IpAddr::V4(address) => self.allows_v4(address),
78            IpAddr::V6(address) => self.allows_v6(address),
79        }
80    }
81
82    fn allows_v4(self, address: Ipv4Addr) -> bool {
83        if address.is_loopback() {
84            return self.allow_loopback;
85        }
86        let value = u32::from(address);
87        !IPV4_FORBIDDEN
88            .iter()
89            .copied()
90            .any(|(network, prefix)| in_v4_network(value, u32::from(network), prefix))
91    }
92
93    fn allows_v6(self, address: Ipv6Addr) -> bool {
94        if address.is_loopback() {
95            return self.allow_loopback;
96        }
97        if let Some(mapped) = address.to_ipv4_mapped() {
98            return self.allows_v4(mapped);
99        }
100        let value = u128::from(address);
101        !IPV6_FORBIDDEN
102            .iter()
103            .copied()
104            .any(|(network, prefix)| in_v6_network(value, u128::from(network), prefix))
105    }
106}
107
108impl Default for FetchAddressPolicy {
109    fn default() -> Self {
110        Self::public_network()
111    }
112}
113
114/// Deterministic, deduplicated set of fully validated DNS answers.
115#[derive(Clone, PartialEq, Eq)]
116pub struct ValidatedFetchAddresses {
117    addresses: Vec<IpAddr>,
118}
119
120impl ValidatedFetchAddresses {
121    /// Returns validated addresses in deterministic order.
122    #[must_use]
123    pub fn addresses(&self) -> &[IpAddr] {
124        &self.addresses
125    }
126
127    /// Returns socket addresses for one validated destination port.
128    #[must_use]
129    pub fn socket_addresses(&self, port: u16) -> Vec<SocketAddr> {
130        self.addresses
131            .iter()
132            .copied()
133            .map(|address| SocketAddr::new(address, port))
134            .collect()
135    }
136
137    /// Verifies a connected peer against both policy and the pinned answer set.
138    #[must_use]
139    pub fn contains_peer(&self, peer: SocketAddr, expected_port: u16) -> bool {
140        peer.port() == expected_port && self.addresses.binary_search(&peer.ip()).is_ok()
141    }
142}
143
144impl fmt::Debug for ValidatedFetchAddresses {
145    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
146        formatter
147            .debug_struct("ValidatedFetchAddresses")
148            .field("address_count", &self.addresses.len())
149            .finish()
150    }
151}
152
153const IPV4_FORBIDDEN: &[(Ipv4Addr, u32)] = &[
154    (Ipv4Addr::UNSPECIFIED, 8),
155    (Ipv4Addr::new(10, 0, 0, 0), 8),
156    (Ipv4Addr::new(100, 64, 0, 0), 10),
157    (Ipv4Addr::new(169, 254, 0, 0), 16),
158    (Ipv4Addr::new(172, 16, 0, 0), 12),
159    (Ipv4Addr::new(192, 0, 0, 0), 24),
160    (Ipv4Addr::new(192, 0, 2, 0), 24),
161    (Ipv4Addr::new(192, 31, 196, 0), 24),
162    (Ipv4Addr::new(192, 52, 193, 0), 24),
163    (Ipv4Addr::new(192, 88, 99, 0), 24),
164    (Ipv4Addr::new(192, 168, 0, 0), 16),
165    (Ipv4Addr::new(192, 175, 48, 0), 24),
166    (Ipv4Addr::new(198, 18, 0, 0), 15),
167    (Ipv4Addr::new(198, 51, 100, 0), 24),
168    (Ipv4Addr::new(203, 0, 113, 0), 24),
169    (Ipv4Addr::new(224, 0, 0, 0), 4),
170    (Ipv4Addr::new(240, 0, 0, 0), 4),
171];
172
173const IPV6_FORBIDDEN: &[(Ipv6Addr, u32)] = &[
174    (Ipv6Addr::UNSPECIFIED, 96),
175    (Ipv6Addr::new(0x64, 0xff9b, 0, 0, 0, 0, 0, 0), 96),
176    (Ipv6Addr::new(0x64, 0xff9b, 1, 0, 0, 0, 0, 0), 48),
177    (Ipv6Addr::new(0x100, 0, 0, 0, 0, 0, 0, 0), 64),
178    (Ipv6Addr::new(0x2001, 0, 0, 0, 0, 0, 0, 0), 32),
179    (Ipv6Addr::new(0x2001, 2, 0, 0, 0, 0, 0, 0), 48),
180    (Ipv6Addr::new(0x2001, 0x10, 0, 0, 0, 0, 0, 0), 28),
181    (Ipv6Addr::new(0x2001, 0x20, 0, 0, 0, 0, 0, 0), 28),
182    (Ipv6Addr::new(0x2001, 0x0db8, 0, 0, 0, 0, 0, 0), 32),
183    (Ipv6Addr::new(0x2002, 0, 0, 0, 0, 0, 0, 0), 16),
184    (Ipv6Addr::new(0x3fff, 0, 0, 0, 0, 0, 0, 0), 20),
185    (Ipv6Addr::new(0xfc00, 0, 0, 0, 0, 0, 0, 0), 7),
186    (Ipv6Addr::new(0xfe80, 0, 0, 0, 0, 0, 0, 0), 10),
187    (Ipv6Addr::new(0xfec0, 0, 0, 0, 0, 0, 0, 0), 10),
188    (Ipv6Addr::new(0xff00, 0, 0, 0, 0, 0, 0, 0), 8),
189];
190
191fn in_v4_network(value: u32, network: u32, prefix: u32) -> bool {
192    let mask = u32::MAX.checked_shl(32 - prefix).unwrap_or(0);
193    value & mask == network & mask
194}
195
196fn in_v6_network(value: u128, network: u128, prefix: u32) -> bool {
197    let mask = u128::MAX.checked_shl(128 - prefix).unwrap_or(0);
198    value & mask == network & mask
199}