praxis-proxy-core 0.7.0

Configuration, error types, and server factory for Praxis
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
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
// SPDX-License-Identifier: Apache-2.0
// Copyright (c) 2024 Praxis Contributors

//! Network utilities: CIDR range matching and IP address normalization.

use std::net::IpAddr;

// -----------------------------------------------------------------------------
// IP Normalization
// -----------------------------------------------------------------------------

/// Convert IPv4-mapped IPv6 addresses (`::ffff:A.B.C.D`) to plain IPv4.
///
/// Native IPv4 and non-mapped IPv6 addresses pass through unchanged.
///
/// ```
/// use std::net::IpAddr;
///
/// use praxis_core::connectivity::normalize_mapped_ipv4;
///
/// let mapped: IpAddr = "::ffff:10.0.0.1".parse().unwrap();
/// assert_eq!(
///     normalize_mapped_ipv4(mapped),
///     IpAddr::V4("10.0.0.1".parse().unwrap()),
/// );
///
/// let native_v4: IpAddr = "10.0.0.1".parse().unwrap();
/// assert_eq!(normalize_mapped_ipv4(native_v4), native_v4);
///
/// let native_v6: IpAddr = "2001:db8::1".parse().unwrap();
/// assert_eq!(normalize_mapped_ipv4(native_v6), native_v6);
/// ```
pub fn normalize_mapped_ipv4(ip: IpAddr) -> IpAddr {
    match ip {
        IpAddr::V6(v6) => v6.to_ipv4_mapped().map_or(IpAddr::V6(v6), IpAddr::V4),
        v4 @ IpAddr::V4(_) => v4,
    }
}

// -----------------------------------------------------------------------------
// Private/Reserved IP Detection
// -----------------------------------------------------------------------------

/// Returns `true` if the IP address is in a private or reserved range.
///
/// Detects addresses that should not be reachable as public upstream
/// targets, protecting against DNS rebinding and SSRF attacks where
/// a DNS name resolves to an internal IP at runtime.
///
/// Covered ranges:
/// - IPv4 loopback (`127.0.0.0/8`)
/// - IPv4 private / RFC 1918 (`10.0.0.0/8`, `172.16.0.0/12`, `192.168.0.0/16`)
/// - IPv4 link-local (`169.254.0.0/16`)
/// - IPv4 current network (`0.0.0.0/8`)
/// - IPv4 CGNAT / shared address space (`100.64.0.0/10`)
/// - IPv6 loopback (`::1`)
/// - IPv6 unspecified (`::`)
/// - IPv6 link-local (`fe80::/10`)
/// - IPv6 unique local (`fc00::/7`)
/// - IPv4-mapped IPv6 variants of all above
///
/// ```
/// use std::net::IpAddr;
///
/// use praxis_core::connectivity::is_private_ip;
///
/// assert!(is_private_ip(&"127.0.0.1".parse().unwrap()));
/// assert!(is_private_ip(&"10.0.0.1".parse().unwrap()));
/// assert!(is_private_ip(&"172.16.5.1".parse().unwrap()));
/// assert!(is_private_ip(&"192.168.1.1".parse().unwrap()));
/// assert!(is_private_ip(&"169.254.1.1".parse().unwrap()));
/// assert!(is_private_ip(&"0.0.0.0".parse().unwrap()));
/// assert!(is_private_ip(&"100.64.0.1".parse().unwrap()));
/// assert!(is_private_ip(&"::1".parse().unwrap()));
/// assert!(is_private_ip(&"::".parse().unwrap()));
/// assert!(is_private_ip(&"fe80::1".parse().unwrap()));
/// assert!(is_private_ip(&"fc00::1".parse().unwrap()));
/// assert!(is_private_ip(&"::ffff:10.0.0.1".parse().unwrap()));
///
/// assert!(!is_private_ip(&"8.8.8.8".parse().unwrap()));
/// assert!(!is_private_ip(&"2001:db8::1".parse().unwrap()));
/// ```
pub fn is_private_ip(ip: &IpAddr) -> bool {
    let normalized = normalize_mapped_ipv4(*ip);
    match normalized {
        IpAddr::V4(v4) => {
            v4.is_loopback() || v4.is_private() || v4.is_link_local() || v4.octets()[0] == 0 || is_cgnat(v4)
        },
        IpAddr::V6(v6) => {
            let seg0 = v6.segments()[0];
            // `::` is included for the same reason config-time validation
            // flags it (`is_ssrf_sensitive`): connect(2) to the unspecified
            // address is routed to loopback, so it reaches exactly the
            // services the loopback check exists to block.
            v6.is_loopback() || v6.is_unspecified() || (seg0 & 0xFFC0) == 0xFE80 || (seg0 & 0xFE00) == 0xFC00
        },
    }
}

/// Returns `true` if the IPv4 address is in the CGNAT/shared address
/// space (`100.64.0.0/10`, [RFC 6598]).
///
/// [RFC 6598]: https://datatracker.ietf.org/doc/html/rfc6598
fn is_cgnat(v4: std::net::Ipv4Addr) -> bool {
    u32::from(v4) & 0xFFC0_0000 == 0x6440_0000 // 100.64.0.0/10
}

// -----------------------------------------------------------------------------
// CIDR Range
// -----------------------------------------------------------------------------

/// A parsed CIDR range (e.g. "10.0.0.0/8").
///
/// ```
/// use praxis_core::connectivity::CidrRange;
///
/// let range = CidrRange::parse("10.0.0.0/8").unwrap();
/// assert!(range.contains(&"10.1.2.3".parse().unwrap()));
/// assert!(!range.contains(&"192.168.1.1".parse().unwrap()));
/// ```
#[derive(Clone, Debug)]
pub struct CidrRange {
    /// Network base address.
    addr: IpAddr,

    /// Prefix length (e.g. 24 for a /24).
    prefix_len: u8,
}

impl CidrRange {
    /// Parse a CIDR string like `"10.0.0.0/8"` or `"fd00::/16"`.
    ///
    /// # Errors
    ///
    /// Returns an error string if the input is not a valid CIDR notation.
    ///
    /// ```
    /// use praxis_core::connectivity::CidrRange;
    ///
    /// let range = CidrRange::parse("192.168.0.0/16").unwrap();
    /// assert!(CidrRange::parse("10.0.0.0/33").is_err());
    /// ```
    pub fn parse(cidr: &str) -> Result<Self, String> {
        let (addr_str, len_str) = cidr
            .split_once('/')
            .ok_or_else(|| format!("invalid CIDR: {cidr} (missing /)"))?;

        let addr: IpAddr = addr_str
            .parse()
            .map_err(|err| format!("invalid IP in CIDR {cidr}: {err}"))?;

        let prefix_len: u8 = len_str
            .parse()
            .map_err(|err| format!("invalid prefix length in {cidr}: {err}"))?;

        let max = match addr {
            IpAddr::V4(_) => 32,
            IpAddr::V6(_) => 128,
        };
        if prefix_len > max {
            return Err(format!("prefix length {prefix_len} exceeds maximum {max} for {cidr}"));
        }

        Ok(Self { addr, prefix_len })
    }

    /// Returns `true` if `ip` falls within this CIDR range.
    ///
    /// IPv4-mapped IPv6 addresses (e.g. `::ffff:10.0.0.1`) are
    /// transparently matched against IPv4 CIDR ranges, and vice versa.
    ///
    /// A `/0` range (`0.0.0.0/0` or `::/0`) matches **any** address of
    /// either family. Without this, `0.0.0.0/0` would match no native
    /// IPv6 address — so a `deny: ["0.0.0.0/0"]` ACL would silently
    /// admit every IPv6 peer on a dual-stack listener (fail-open).
    ///
    /// ```
    /// use praxis_core::connectivity::CidrRange;
    ///
    /// let range = CidrRange::parse("10.0.0.0/8").unwrap();
    /// assert!(range.contains(&"10.255.0.1".parse().unwrap()));
    /// assert!(!range.contains(&"11.0.0.1".parse().unwrap()));
    ///
    /// // IPv4-mapped IPv6 matches IPv4 CIDR
    /// assert!(range.contains(&"::ffff:10.1.2.3".parse().unwrap()));
    /// assert!(!range.contains(&"::ffff:192.168.1.1".parse().unwrap()));
    ///
    /// // A /0 wildcard matches every address, both families
    /// let all_v4 = CidrRange::parse("0.0.0.0/0").unwrap();
    /// assert!(all_v4.contains(&"2001:db8::1".parse().unwrap()));
    /// let all_v6 = CidrRange::parse("::/0").unwrap();
    /// assert!(all_v6.contains(&"203.0.113.7".parse().unwrap()));
    /// ```
    pub fn contains(&self, ip: &IpAddr) -> bool {
        if self.prefix_len == 0 {
            return true;
        }
        match (&self.addr, ip) {
            (IpAddr::V4(net), IpAddr::V4(candidate)) => v4_contains(*net, *candidate, self.prefix_len),
            (IpAddr::V6(net), IpAddr::V6(candidate)) => v6_contains(*net, *candidate, self.prefix_len),
            (IpAddr::V4(net), IpAddr::V6(candidate)) => v4_contains_mapped_v6(*net, *candidate, self.prefix_len),
            (IpAddr::V6(net), IpAddr::V4(candidate)) => v6_contains_v4(*net, *candidate, self.prefix_len),
        }
    }
}

// -----------------------------------------------------------------------------
// Utilities
// -----------------------------------------------------------------------------

/// Check whether two IPv4 addresses share the same prefix.
fn v4_contains(net: std::net::Ipv4Addr, candidate: std::net::Ipv4Addr, prefix_len: u8) -> bool {
    let mask = v4_mask(prefix_len);
    u32::from(net) & mask == u32::from(candidate) & mask
}

/// Check whether two IPv6 addresses share the same prefix.
fn v6_contains(net: std::net::Ipv6Addr, candidate: std::net::Ipv6Addr, prefix_len: u8) -> bool {
    let mask = v6_mask(prefix_len);
    u128::from(net) & mask == u128::from(candidate) & mask
}

/// Check if an IPv4-mapped IPv6 address falls within an IPv4 CIDR.
fn v4_contains_mapped_v6(net: std::net::Ipv4Addr, candidate: std::net::Ipv6Addr, prefix_len: u8) -> bool {
    candidate
        .to_ipv4_mapped()
        .is_some_and(|mapped| v4_contains(net, mapped, prefix_len))
}

/// Check if a plain IPv4 address falls within an IPv4-mapped IPv6 CIDR.
fn v6_contains_v4(net: std::net::Ipv6Addr, candidate: std::net::Ipv4Addr, prefix_len: u8) -> bool {
    net.to_ipv4_mapped()
        .filter(|_| prefix_len >= 96)
        .is_some_and(|mapped| v4_contains(mapped, candidate, prefix_len.saturating_sub(96)))
}

/// Compute a 32-bit mask for the given IPv4 prefix length.
fn v4_mask(prefix_len: u8) -> u32 {
    if prefix_len == 0 {
        0
    } else {
        u32::MAX << 32_u8.saturating_sub(prefix_len)
    }
}

/// Compute a 128-bit mask for the given IPv6 prefix length.
fn v6_mask(prefix_len: u8) -> u128 {
    if prefix_len == 0 {
        0
    } else {
        u128::MAX << 128_u8.saturating_sub(prefix_len)
    }
}

// -----------------------------------------------------------------------------
// Tests
// -----------------------------------------------------------------------------

#[cfg(test)]
#[expect(clippy::allow_attributes, reason = "blanket test suppressions")]
#[allow(
    clippy::unwrap_used,
    clippy::expect_used,
    clippy::indexing_slicing,
    clippy::needless_raw_strings,
    clippy::needless_raw_string_hashes,
    clippy::min_ident_chars,
    reason = "tests use unwrap/expect/indexing/raw strings for brevity"
)]
mod tests {
    use super::*;

    #[test]
    fn parse_v4() {
        let r = CidrRange::parse("10.0.0.0/8").unwrap();
        assert_eq!(r.prefix_len, 8, "IPv4 /8 prefix should parse as 8");
    }

    #[test]
    fn parse_v6() {
        let r = CidrRange::parse("fd00::/8").unwrap();
        assert_eq!(r.prefix_len, 8, "IPv6 /8 prefix should parse as 8");
    }

    #[test]
    fn parse_invalid_missing_slash() {
        assert!(CidrRange::parse("10.0.0.0").is_err(), "CIDR without slash should fail");
    }

    #[test]
    fn parse_invalid_prefix_too_large() {
        assert!(CidrRange::parse("10.0.0.0/33").is_err(), "/33 exceeds IPv4 max of 32");
    }

    #[test]
    fn contains_v4_match() {
        let r = CidrRange::parse("10.0.0.0/8").unwrap();
        assert!(
            r.contains(&"10.1.2.3".parse().unwrap()),
            "10.1.2.3 is within 10.0.0.0/8"
        );
    }

    #[test]
    fn contains_v4_no_match() {
        let r = CidrRange::parse("10.0.0.0/8").unwrap();
        assert!(
            !r.contains(&"192.168.1.1".parse().unwrap()),
            "192.168.1.1 is outside 10.0.0.0/8"
        );
    }

    #[test]
    fn contains_v4_exact() {
        let r = CidrRange::parse("192.168.1.100/32").unwrap();
        assert!(
            r.contains(&"192.168.1.100".parse().unwrap()),
            "/32 should match exact IP"
        );
    }

    #[test]
    fn v4_zero_prefix_matches_all() {
        let r = CidrRange::parse("0.0.0.0/0").unwrap();
        assert!(r.contains(&"8.8.8.8".parse().unwrap()), "/0 should match any IPv4");
    }

    #[test]
    fn v4_v6_mismatch() {
        let r = CidrRange::parse("10.0.0.0/8").unwrap();
        assert!(
            !r.contains(&"fd00::1".parse().unwrap()),
            "IPv4 range should not match non-mapped IPv6"
        );
    }

    #[test]
    fn ipv4_mapped_ipv6_matches_v4_range() {
        let r = CidrRange::parse("10.0.0.0/8").unwrap();
        assert!(
            r.contains(&"::ffff:10.1.2.3".parse().unwrap()),
            "::ffff:10.1.2.3 should match 10.0.0.0/8"
        );
    }

    #[test]
    fn ipv4_mapped_ipv6_outside_v4_range() {
        let r = CidrRange::parse("10.0.0.0/8").unwrap();
        assert!(
            !r.contains(&"::ffff:192.168.1.1".parse().unwrap()),
            "::ffff:192.168.1.1 should not match 10.0.0.0/8"
        );
    }

    #[test]
    fn ipv4_mapped_ipv6_exact_match() {
        let r = CidrRange::parse("192.168.1.100/32").unwrap();
        assert!(
            r.contains(&"::ffff:192.168.1.100".parse().unwrap()),
            "::ffff:192.168.1.100 should match 192.168.1.100/32"
        );
    }

    #[test]
    fn ipv4_mapped_ipv6_zero_prefix() {
        let r = CidrRange::parse("0.0.0.0/0").unwrap();
        assert!(
            r.contains(&"::ffff:8.8.8.8".parse().unwrap()),
            "::ffff:8.8.8.8 should match 0.0.0.0/0"
        );
    }

    #[test]
    fn plain_v4_matches_mapped_v6_range() {
        let r = CidrRange::parse("::ffff:10.0.0.0/104").unwrap();
        assert!(
            r.contains(&"10.1.2.3".parse().unwrap()),
            "10.1.2.3 should match ::ffff:10.0.0.0/104 (equivalent to 10.0.0.0/8)"
        );
    }

    #[test]
    fn plain_v4_outside_mapped_v6_range() {
        let r = CidrRange::parse("::ffff:10.0.0.0/104").unwrap();
        assert!(
            !r.contains(&"192.168.1.1".parse().unwrap()),
            "192.168.1.1 should not match ::ffff:10.0.0.0/104"
        );
    }

    #[test]
    fn v6_range_below_96_does_not_match_v4() {
        let r = CidrRange::parse("::ffff:0.0.0.0/64").unwrap();
        assert!(
            !r.contains(&"10.0.0.1".parse().unwrap()),
            "IPv6 /64 range should not match plain IPv4 (prefix < 96)"
        );
    }

    #[test]
    fn v6_range_at_96_matches_all_v4() {
        let r = CidrRange::parse("::ffff:0.0.0.0/96").unwrap();
        assert!(
            r.contains(&"10.0.0.1".parse().unwrap()),
            "/96 mapped range covers all IPv4 addresses"
        );
        assert!(
            r.contains(&"192.168.1.1".parse().unwrap()),
            "/96 mapped range covers all IPv4 addresses"
        );
    }

    #[test]
    fn contains_v6_match() {
        let r = CidrRange::parse("fd00::/16").unwrap();
        assert!(r.contains(&"fd00::1".parse().unwrap()), "fd00::1 is within fd00::/16");
    }

    #[test]
    fn contains_v6_no_match() {
        let r = CidrRange::parse("fd00::/16").unwrap();
        assert!(!r.contains(&"fe80::1".parse().unwrap()), "fe80::1 is outside fd00::/16");
    }

    #[test]
    fn is_private_ip_loopback_v4() {
        assert!(is_private_ip(&"127.0.0.1".parse().unwrap()), "127.0.0.1 is loopback");
        assert!(
            is_private_ip(&"127.255.255.255".parse().unwrap()),
            "127.255.255.255 is loopback"
        );
    }

    #[test]
    fn is_private_ip_rfc1918_10() {
        assert!(is_private_ip(&"10.0.0.1".parse().unwrap()), "10.0.0.1 is RFC 1918");
        assert!(
            is_private_ip(&"10.255.255.255".parse().unwrap()),
            "10.255.255.255 is RFC 1918"
        );
    }

    #[test]
    fn is_private_ip_rfc1918_172() {
        assert!(is_private_ip(&"172.16.0.1".parse().unwrap()), "172.16.0.1 is RFC 1918");
        assert!(
            is_private_ip(&"172.31.255.255".parse().unwrap()),
            "172.31.255.255 is RFC 1918"
        );
        assert!(
            !is_private_ip(&"172.32.0.1".parse().unwrap()),
            "172.32.0.1 is outside 172.16/12"
        );
    }

    #[test]
    fn is_private_ip_rfc1918_192() {
        assert!(
            is_private_ip(&"192.168.0.1".parse().unwrap()),
            "192.168.0.1 is RFC 1918"
        );
        assert!(
            is_private_ip(&"192.168.255.255".parse().unwrap()),
            "192.168.255.255 is RFC 1918"
        );
    }

    #[test]
    fn is_private_ip_link_local_v4() {
        assert!(
            is_private_ip(&"169.254.1.1".parse().unwrap()),
            "169.254.1.1 is link-local"
        );
        assert!(
            is_private_ip(&"169.254.169.254".parse().unwrap()),
            "169.254.169.254 is link-local"
        );
    }

    #[test]
    fn is_private_ip_current_network() {
        assert!(is_private_ip(&"0.0.0.0".parse().unwrap()), "0.0.0.0 is current network");
        assert!(
            is_private_ip(&"0.255.255.255".parse().unwrap()),
            "0.255.255.255 is current network"
        );
    }

    #[test]
    fn is_private_ip_cgnat() {
        assert!(is_private_ip(&"100.64.0.1".parse().unwrap()), "100.64.0.1 is CGNAT");
        assert!(
            is_private_ip(&"100.127.255.255".parse().unwrap()),
            "100.127.255.255 is CGNAT"
        );
        assert!(
            !is_private_ip(&"100.128.0.1".parse().unwrap()),
            "100.128.0.1 is outside CGNAT"
        );
    }

    #[test]
    fn is_private_ip_loopback_v6() {
        assert!(is_private_ip(&"::1".parse().unwrap()), "::1 is IPv6 loopback");
    }

    #[test]
    fn is_private_ip_unspecified_v6() {
        assert!(
            is_private_ip(&"::".parse().unwrap()),
            ":: (unspecified) must match the config-time is_ssrf_sensitive verdict: connecting to it lands on loopback"
        );
    }

    #[test]
    fn is_private_ip_link_local_v6() {
        assert!(is_private_ip(&"fe80::1".parse().unwrap()), "fe80::1 is IPv6 link-local");
    }

    #[test]
    fn is_private_ip_unique_local_v6() {
        assert!(
            is_private_ip(&"fc00::1".parse().unwrap()),
            "fc00::1 is IPv6 unique local"
        );
        assert!(
            is_private_ip(&"fd00::1".parse().unwrap()),
            "fd00::1 is IPv6 unique local"
        );
    }

    #[test]
    fn is_private_ip_mapped_v4() {
        assert!(
            is_private_ip(&"::ffff:10.0.0.1".parse().unwrap()),
            "mapped 10.0.0.1 is private"
        );
        assert!(
            is_private_ip(&"::ffff:127.0.0.1".parse().unwrap()),
            "mapped 127.0.0.1 is private"
        );
        assert!(
            !is_private_ip(&"::ffff:8.8.8.8".parse().unwrap()),
            "mapped 8.8.8.8 is public"
        );
    }

    #[test]
    fn is_private_ip_public_addresses() {
        assert!(!is_private_ip(&"8.8.8.8".parse().unwrap()), "8.8.8.8 is public");
        assert!(!is_private_ip(&"1.1.1.1".parse().unwrap()), "1.1.1.1 is public");
        assert!(!is_private_ip(&"2001:db8::1".parse().unwrap()), "2001:db8::1 is public");
        assert!(!is_private_ip(&"203.0.113.1".parse().unwrap()), "203.0.113.1 is public");
    }
}