footing 0.4.3

Feature-gated foundations for Rust backend services
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
//! Network primitives shared by service configuration and transports.
//!
//! ```rust
//! # #[cfg(feature = "net")]
//! # {
//! use footing::net::{ClientIp, IpNetworkSet};
//!
//! let proxies = IpNetworkSet::from_cidrs(["10.0.0.0/8", " 10.0.0.0/8 "]).unwrap();
//! assert_eq!(proxies.normalized_cidrs(), ["10.0.0.0/8"]);
//!
//! let client_ip = ClientIp::new("\"[2001:db8::1]:443\"").unwrap();
//! assert_eq!(client_ip.as_str(), "2001:db8::1");
//! # }
//! ```

use std::{fmt, net::IpAddr};

use ipnet::IpNet;
use serde::{Deserialize, Deserializer, Serialize, Serializer};
use thiserror::Error;

use crate::result::{ClassifyError, ErrorKind};

/// Maximum supported client IP length.
pub const MAX_CLIENT_IP_LENGTH: usize = 128;

#[derive(Debug, Clone, PartialEq, Eq, Hash)]
/// Represents client IP.
pub struct ClientIp {
    address: IpAddr,
    display: String,
}

impl ClientIp {
    /// Parses and normalizes a client IP address, rejecting invalid input.
    pub fn new(value: impl AsRef<str>) -> Result<Self, ClientIpError> {
        parse_client_ip_value(value.as_ref()).ok_or(ClientIpError::Invalid)
    }

    #[must_use]
    /// Creates an address, converting IPv4-mapped IPv6 to its IPv4 form.
    pub fn from_ip_addr(address: IpAddr) -> Self {
        let address = address.to_canonical();
        Self {
            address,
            display: address.to_string(),
        }
    }

    #[must_use]
    /// Parses the value.
    pub fn parse(value: &str) -> Option<Self> {
        Self::new(value).ok()
    }

    #[must_use]
    /// Returns this value as IP addr.
    pub fn as_ip_addr(&self) -> IpAddr {
        self.address
    }

    #[must_use]
    /// Returns this value as str.
    pub fn as_str(&self) -> &str {
        &self.display
    }
}

impl TryFrom<&str> for ClientIp {
    type Error = ClientIpError;

    fn try_from(value: &str) -> Result<Self, Self::Error> {
        Self::new(value)
    }
}

impl TryFrom<String> for ClientIp {
    type Error = ClientIpError;

    fn try_from(value: String) -> Result<Self, Self::Error> {
        Self::new(value)
    }
}

impl From<IpAddr> for ClientIp {
    fn from(value: IpAddr) -> Self {
        Self::from_ip_addr(value)
    }
}

impl From<ClientIp> for String {
    fn from(value: ClientIp) -> Self {
        value.display
    }
}

impl fmt::Display for ClientIp {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter.write_str(self.as_str())
    }
}

impl Serialize for ClientIp {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        serializer.serialize_str(self.as_str())
    }
}

impl<'de> Deserialize<'de> for ClientIp {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        let value = String::deserialize(deserializer)?;
        Self::new(value).map_err(serde::de::Error::custom)
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Error)]
#[non_exhaustive]
/// Errors that can occur while handling client IP.
pub enum ClientIpError {
    #[error("client IP is invalid")]
    /// Indicates invalid.
    Invalid,
}

impl ClassifyError for ClientIpError {
    fn error_kind(&self) -> ErrorKind {
        ErrorKind::Validation
    }

    fn error_code(&self) -> crate::result::ErrorCode {
        crate::result::ErrorCode::internal(match self {
            Self::Invalid => "client_ip_invalid",
        })
    }
}

#[derive(Debug, Clone, Default, PartialEq, Eq)]
#[non_exhaustive]
/// Represents IP network set.
pub struct IpNetworkSet {
    networks: Vec<IpNet>,
}

impl IpNetworkSet {
    #[must_use]
    /// Canonicalizes network addresses, then sorts and deduplicates CIDRs.
    /// Networks sort by address family (IPv4 first), address, then prefix length.
    /// IPv4-mapped IPv6 networks within `::ffff:0:0/96` become IPv4 networks.
    /// Broader IPv6 networks remain IPv6-only; IPv4 trust must be explicit.
    pub fn new(networks: impl IntoIterator<Item = IpNet>) -> Self {
        let mut networks: Vec<_> = networks
            .into_iter()
            .map(|network| {
                let network = network.trunc();
                if let IpNet::V6(network) = network
                    && network.prefix_len() >= 96
                    && let Some(address) = network.addr().to_ipv4_mapped()
                {
                    IpNet::new_assert(IpAddr::V4(address), network.prefix_len() - 96)
                } else {
                    network
                }
            })
            .collect();
        networks.sort_unstable();
        networks.dedup();
        Self { networks }
    }

    /// Creates a value from CIDRs.
    pub fn from_cidrs(
        cidrs: impl IntoIterator<Item = impl AsRef<str>>,
    ) -> Result<Self, IpNetworkSetParseError> {
        let mut networks = Vec::new();
        for cidr in cidrs {
            let value = cidr.as_ref().trim();
            if value.is_empty() {
                return Err(IpNetworkSetParseError::EmptyCidr);
            }
            let network =
                value
                    .parse::<IpNet>()
                    .map_err(|_| IpNetworkSetParseError::InvalidCidr {
                        value: value.to_owned(),
                    })?;
            networks.push(network);
        }
        Ok(Self::new(networks))
    }

    #[must_use]
    /// Returns the networks.
    pub fn networks(&self) -> &[IpNet] {
        &self.networks
    }

    #[must_use]
    /// Consumes this value and returns networks.
    pub fn into_networks(self) -> Vec<IpNet> {
        self.networks
    }

    #[must_use]
    /// Returns the normalized CIDRs.
    pub fn normalized_cidrs(&self) -> Vec<String> {
        self.networks.iter().map(ToString::to_string).collect()
    }

    #[must_use]
    /// Tests membership after converting IPv4-mapped IPv6 addresses to IPv4.
    pub fn contains(&self, ip: IpAddr) -> bool {
        let ip = ip.to_canonical();
        self.networks.iter().any(|network| network.contains(&ip))
    }

    #[must_use]
    /// Returns whether the collection is empty.
    pub fn is_empty(&self) -> bool {
        self.networks.is_empty()
    }
}

#[derive(Debug, Clone, PartialEq, Eq, Error)]
#[non_exhaustive]
/// Errors that can occur while handling IP network set parse.
pub enum IpNetworkSetParseError {
    #[error("CIDR value must not be empty")]
    /// The CIDR is empty.
    EmptyCidr,
    #[error("CIDR value is invalid: {value}")]
    /// The CIDR is invalid.
    InvalidCidr {
        #[doc = "The offending value."]
        value: String,
    },
}

impl ClassifyError for IpNetworkSetParseError {
    fn error_kind(&self) -> ErrorKind {
        ErrorKind::Validation
    }

    fn error_code(&self) -> crate::result::ErrorCode {
        crate::result::ErrorCode::internal(match self {
            Self::EmptyCidr => "cidr_empty",
            Self::InvalidCidr { .. } => "cidr_invalid",
        })
    }
}

impl IpNetworkSetParseError {
    #[must_use]
    /// Returns the value.
    pub const fn value(&self) -> Option<&str> {
        match self {
            Self::EmptyCidr => None,
            Self::InvalidCidr { value } => Some(value.as_str()),
        }
    }

    #[must_use]
    /// Returns whether this value is empty CIDR.
    pub const fn is_empty_cidr(&self) -> bool {
        matches!(self, Self::EmptyCidr)
    }
}

fn parse_client_ip_value(value: &str) -> Option<ClientIp> {
    let value = value.trim();
    let value = match value.strip_prefix('"') {
        Some(quoted) => quoted.strip_suffix('"')?,
        None => value,
    };
    let value = client_ip_host(value)?;
    value.parse::<IpAddr>().ok().map(ClientIp::from_ip_addr)
}

fn client_ip_host(value: &str) -> Option<&str> {
    if value.is_empty() || value.len() > MAX_CLIENT_IP_LENGTH {
        return None;
    }

    if let Some(rest) = value.strip_prefix('[') {
        let (host, suffix) = rest.split_once(']')?;
        if host.parse::<std::net::Ipv6Addr>().is_err() {
            return None;
        }
        if suffix.is_empty() {
            return Some(host);
        }
        let port = suffix.strip_prefix(':')?;
        return valid_client_ip_port(port).then_some(host);
    }

    match value.rsplit_once(':') {
        Some((host, port)) if !host.contains(':') && valid_client_ip_port(port) => Some(host),
        _ => Some(value),
    }
}

fn valid_client_ip_port(port: &str) -> bool {
    !port.is_empty()
        && port.bytes().all(|byte| byte.is_ascii_digit())
        && port.parse::<u16>().is_ok()
}

#[cfg(test)]
mod tests {
    use std::net::IpAddr;

    use super::{ClientIp, ClientIpError, IpNetworkSet, IpNetworkSetParseError};
    use crate::result::{ClassifyError, ErrorKind};

    #[test]
    fn client_ip_normalizes_plain_and_forwarded_values() {
        let ipv4 = ClientIp::new("198.51.100.10:443").expect("client IP should parse");
        assert_eq!(ipv4.as_str(), "198.51.100.10");
        assert_eq!(
            ipv4.as_ip_addr(),
            "198.51.100.10".parse::<IpAddr>().unwrap()
        );

        let ipv6 = ClientIp::new(r#""[2001:db8::1]:443""#).expect("client IP should parse");
        assert_eq!(ipv6.as_str(), "2001:db8::1");
        assert_eq!(ipv6.as_ip_addr(), "2001:db8::1".parse::<IpAddr>().unwrap());
    }

    #[test]
    fn mapped_ipv4_addresses_share_one_identity_and_network_membership() {
        let ipv4 = ClientIp::new("10.1.2.3").unwrap();
        let mapped = ClientIp::new("[::ffff:10.1.2.3]:443").unwrap();
        assert_eq!(mapped, ipv4);
        assert_eq!(serde_json::to_string(&mapped).unwrap(), "\"10.1.2.3\"");
        assert_eq!(ClientIp::new("::1").unwrap().as_str(), "::1");

        let set = IpNetworkSet::from_cidrs(["10.0.0.0/8", "::ffff:10.1.2.3/104"]).unwrap();
        assert_eq!(set.normalized_cidrs(), ["10.0.0.0/8"]);
        for address in ["10.1.2.3", "::ffff:10.1.2.3"] {
            assert!(set.contains(address.parse().unwrap()));
        }
        assert!(!set.contains("::ffff:11.1.2.3".parse().unwrap()));
        assert!(!set.contains("::1".parse().unwrap()));

        let mapped_all = IpNetworkSet::from_cidrs(["::ffff:0:0/96"]).unwrap();
        assert_eq!(mapped_all.normalized_cidrs(), ["0.0.0.0/0"]);
        assert!(mapped_all.contains("192.0.2.1".parse().unwrap()));
        let ipv6_all = IpNetworkSet::from_cidrs(["::/0"]).unwrap();
        assert!(ipv6_all.contains("::1".parse().unwrap()));
        assert!(!ipv6_all.contains("::ffff:192.0.2.1".parse().unwrap()));
    }

    #[test]
    fn client_ip_rejects_invalid_values() {
        for value in [
            "\"198.51.100.10",
            "198.51.100.10\"",
            "\"\"198.51.100.10\"\"",
        ] {
            assert_eq!(ClientIp::new(value), Err(ClientIpError::Invalid));
        }
        assert!(matches!(
            ClientIp::new("not-an-ip"),
            Err(ClientIpError::Invalid)
        ));
        assert!(matches!(ClientIp::new(""), Err(ClientIpError::Invalid)));
        assert!(matches!(
            ClientIp::new("198.51.100.10:"),
            Err(ClientIpError::Invalid)
        ));
        assert!(matches!(
            ClientIp::new("[2001:db8::1]extra"),
            Err(ClientIpError::Invalid)
        ));
        assert!(matches!(
            ClientIp::new("[2001:db8::1]:https"),
            Err(ClientIpError::Invalid)
        ));
    }

    #[test]
    fn client_ip_checks_socket_syntax_at_the_security_boundary() {
        for value in [
            "198.51.100.10:65536",
            "[2001:db8::1]:65536",
            "198.51.100.10:999999",
            "[2001:db8::1]:999999",
            "198.51.100.10:+443",
            "[2001:db8::1]:+443",
            "[198.51.100.10]",
            "[198.51.100.10]:443",
        ] {
            assert_eq!(ClientIp::new(value), Err(ClientIpError::Invalid));
        }
        for port in ["0", "443", "00443", "000443", "000000", "65535"] {
            assert_eq!(
                ClientIp::new(format!("198.51.100.10:{port}"))
                    .unwrap()
                    .as_str(),
                "198.51.100.10"
            );
            assert_eq!(
                ClientIp::new(format!("[2001:db8::1]:{port}"))
                    .unwrap()
                    .as_str(),
                "2001:db8::1"
            );
        }
    }

    #[test]
    fn network_errors_are_classified() {
        let client_ip = ClientIp::new("not-an-ip").unwrap_err();
        assert_eq!(client_ip.error_kind(), ErrorKind::Validation);
        assert_eq!(client_ip.error_code(), "client_ip_invalid");

        let cidr = IpNetworkSet::from_cidrs(["not-a-cidr"]).unwrap_err();
        assert_eq!(cidr.error_kind(), ErrorKind::Validation);
        assert_eq!(cidr.error_code(), "cidr_invalid");
    }

    #[test]
    fn network_set_canonicalizes_host_bits_before_deduplicating() {
        let set = IpNetworkSet::from_cidrs([
            "10.1.2.3/8",
            "10.255.255.255/8",
            "10.0.0.0/8",
            "2001:db8::1234/32",
            "2001:db8::/32",
        ])
        .unwrap();
        assert_eq!(set.normalized_cidrs(), ["10.0.0.0/8", "2001:db8::/32"]);
        let direct = IpNetworkSet::new([
            "10.4.5.6/8".parse().unwrap(),
            "2001:db8::abcd/32".parse().unwrap(),
        ]);
        assert_eq!(set, direct);
        assert!(set.contains("10.255.255.255".parse().unwrap()));
        assert!(!set.contains("11.0.0.0".parse().unwrap()));
        assert!(set.contains("2001:db8:ffff::1".parse().unwrap()));
        assert!(!set.contains("2001:db9::1".parse().unwrap()));
    }

    #[test]
    fn network_set_normalizes_sorts_and_deduplicates_cidrs() {
        let set = IpNetworkSet::from_cidrs([
            " 10.0.0.0/8 ",
            "2001:db8::/32",
            "10.0.0.0/8",
            "192.168.0.0/16",
            "2.0.0.0/8",
            "10.0.0.0/16",
        ])
        .expect("CIDRs should parse");

        assert_eq!(
            set.normalized_cidrs(),
            [
                "2.0.0.0/8",
                "10.0.0.0/8",
                "10.0.0.0/16",
                "192.168.0.0/16",
                "2001:db8::/32"
            ]
        );
        assert!(set.contains("10.1.2.3".parse::<IpAddr>().unwrap()));
        assert!(!set.contains("172.16.0.1".parse::<IpAddr>().unwrap()));
    }

    #[test]
    fn network_set_rejects_empty_and_invalid_cidrs() {
        assert!(matches!(
            IpNetworkSet::from_cidrs([" "]),
            Err(IpNetworkSetParseError::EmptyCidr)
        ));

        assert!(matches!(
            IpNetworkSet::from_cidrs(["not-a-cidr"]),
            Err(IpNetworkSetParseError::InvalidCidr { value }) if value == "not-a-cidr"
        ));
    }
}