c2pa 0.91.10

Rust SDK for C2PA (Coalition for Content Provenance and Authenticity) implementors
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
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
// Copyright 2025 Adobe. All rights reserved.
// This file is licensed to you under the Apache License,
// Version 2.0 (http://www.apache.org/licenses/LICENSE-2.0)
// or the MIT license (http://opensource.org/licenses/MIT),
// at your option.

// Unless required by applicable law or agreed to in writing,
// this software is distributed on an "AS IS" BASIS, WITHOUT
// WARRANTIES OR REPRESENTATIONS OF ANY KIND, either express or
// implied. See the LICENSE-MIT and LICENSE-APACHE files for the
// specific language governing permissions and limitations under
// each license.

//! HTTP request restriction layer.
//!
//! This module provides a [`RestrictedResolver`] that wraps an existing [`SyncHttpResolver`]
//! or [`AsyncHttpResolver`] to enforce host filtering.
//!
//! The SDK can also manage an allowed list for you via the [`Core::allowed_network_hosts`] setting.
//!
//! # Why restrict network requests?
//! In some environments, you may not want the SDK to talk to arbitrary hosts. Restricting
//! network requests help to:
//! - Reduce SSRF-style risks (e.g. requests to internal services).
//! - Constrain requests to a small, trusted set of domains.
//!
//! [`SyncGenericResolver`]: crate::http::SyncGenericResolver
//! [`AsyncGenericResolver`]: crate::http::AsyncGenericResolver
//!
//! # OCSP and other dynamic endpoints
//! Some protocols used by the SDK (like OCSP or CRLs) discover endpoints from certificate
//! metadata at runtime. In a restricted environment, there is no way for the resolver to
//! know that these endpoints are "special" unless you anticipate them in advance and add
//! their hosts to the allow-list.
//!
//! # Disabling networking completely
//! This restriction layer is a runtime control. To turn networking off entirely at compile
//! time, do not enable any of the HTTP features (`http_*`), see ["Features"].
//!
//! ["Features"]: crate#features
//! [`Core::allowed_network_hosts`]: crate::settings::Core::allowed_network_hosts

use std::{
    io::Read,
    net::{IpAddr, Ipv4Addr, Ipv6Addr},
};

use async_trait::async_trait;
use http::{Request, Response, Uri};
use serde::{Deserialize, Deserializer, Serialize, Serializer};

use crate::{
    http::{sanitize_for_log, AsyncHttpResolver, HttpResolverError, SyncHttpResolver},
    Result,
};

/// HTTP resolver wrapper that enforces an allowed list of hosts.
///
/// If the allowed list is empty, no filtering is applied and all requests are allowed.
///
/// When a URI is not permitted, the resolver returns [`HttpResolverError::UriDisallowed`].
#[derive(Debug)]
pub struct RestrictedResolver<T> {
    inner: T,
    allowed_hosts: Option<Vec<HostPattern>>,
}

impl<T> RestrictedResolver<T> {
    /// Creates a new `RestrictedResolver` with an empty allowed list.
    pub fn new(inner: T) -> Self {
        Self {
            inner,
            allowed_hosts: None,
        }
    }

    /// Creates a new `RestrictedResolver` with the specified allowed list.
    #[allow(dead_code)] // Public API, not used internally
    pub fn with_allowed_hosts(inner: T, allowed_hosts: Vec<HostPattern>) -> Self {
        Self {
            inner,
            allowed_hosts: Some(allowed_hosts),
        }
    }

    /// Replaces the current allowed list with the given allowed list if specified.
    pub fn set_allowed_hosts(&mut self, allowed_hosts: Option<Vec<HostPattern>>) {
        self.allowed_hosts = allowed_hosts;
    }

    /// Returns a reference to the allowed list.
    #[allow(dead_code)] // Public API, not used internally
    pub fn allowed_hosts(&self) -> Option<&[HostPattern]> {
        self.allowed_hosts.as_deref()
    }

    /// Returns true if the given URI is allowed by this resolver's policy.
    fn is_uri_allowed(&self, uri: &Uri) -> bool {
        self.allowed_hosts
            .as_ref()
            .map(|hosts| is_uri_allowed(hosts, uri))
            .unwrap_or(true) // None means allow all
    }
}

impl<T: SyncHttpResolver> SyncHttpResolver for RestrictedResolver<T> {
    fn http_resolve(
        &self,
        request: Request<Vec<u8>>,
    ) -> Result<Response<Box<dyn Read>>, HttpResolverError> {
        if !self.is_uri_allowed(request.uri()) {
            return Err(HttpResolverError::UriDisallowed {
                uri: sanitize_for_log(&request.uri().to_string()),
            });
        }
        self.inner.http_resolve(request)
    }
}

#[cfg_attr(not(target_arch = "wasm32"), async_trait)]
#[cfg_attr(target_arch = "wasm32", async_trait(?Send))]
impl<T: AsyncHttpResolver + Sync> AsyncHttpResolver for RestrictedResolver<T> {
    async fn http_resolve_async(
        &self,
        request: Request<Vec<u8>>,
    ) -> Result<Response<Box<dyn Read>>, HttpResolverError> {
        if !self.is_uri_allowed(request.uri()) {
            return Err(HttpResolverError::UriDisallowed {
                uri: sanitize_for_log(&request.uri().to_string()),
            });
        }
        self.inner.http_resolve_async(request).await
    }
}

/// A host/scheme pattern used to restrict network requests.
///
/// Each pattern may include:
/// - A scheme (e.g. `https://` or `http://`)
/// - A hostname or IP address (e.g. `contentauthenticity.org` or `192.0.2.1`)
///     - The hostname may contain a single leading wildcard (e.g. `*.contentauthenticity.org`)
/// - An optional port (e.g. `contentauthenticity.org:443` or `192.0.2.1:8080`)
///
/// Matching is case-insensitive. A wildcard pattern such as `*.contentauthenticity.org` matches
/// `sub.contentauthenticity.org`, but does not match `contentauthenticity.org` or `fakecontentauthenticity.org`.
/// If a scheme is present in the pattern, only URIs using the same scheme are considered a match. If the scheme
/// is omitted, any scheme is allowed as long as the host matches.
///
/// # Examples
///
/// Pattern: `*.contentauthenticity.org`
/// - Does match:
///   - `https://sub.contentauthenticity.org`
///   - `http://api.contentauthenticity.org`
/// - Does **not** match:
///   - `https://contentauthenticity.org` (no subdomain)
///   - `https://sub.fakecontentauthenticity.org` (different host)
///
/// Pattern: `http://192.0.2.1:8080`
/// - Does match:
///   - `http://192.0.2.1:8080`
/// - Does **not** match:
///   - `https://192.0.2.1:8080` (scheme mismatch)
///   - `http://192.0.2.1` (port omitted)
///   - `http://192.0.2.2:8080` (different IP address)
#[cfg_attr(
    feature = "json_schema",
    derive(schemars::JsonSchema),
    schemars(with = "String")
)]
#[derive(Debug, Clone, PartialEq)]
pub struct HostPattern {
    pattern: String,
    scheme: Option<String>,
    host: Option<String>,
    port: Option<String>,
}

impl HostPattern {
    /// Creates a new `HostPattern` with the given pattern.
    pub fn new(pattern: &str) -> Self {
        let pattern = pattern.to_ascii_lowercase();
        let (scheme, rest): (Option<String>, &str) =
            if let Some(host) = pattern.strip_prefix("https://") {
                (Some("https".to_owned()), host)
            } else if let Some(host) = pattern.strip_prefix("http://") {
                (Some("http".to_owned()), host)
            } else {
                (None, &pattern)
            };

        let (host, port) = if let Some((host, port)) = rest.rsplit_once(':') {
            (host, Some(port.to_owned()))
        } else {
            (rest, None)
        };

        Self {
            host: if host.is_empty() {
                None
            } else {
                Some(host.to_owned())
            },
            pattern,
            scheme,
            port,
        }
    }

    /// Returns true if the given URI matches the `HostPattern`.
    pub fn matches(&self, uri: &Uri) -> bool {
        if let Some(allowed_host_pattern) = &self.host {
            if let Some(host) = uri.host() {
                // If there's a wildcard, do an suffix match, otherwise do an exact match.
                let is_host_allowed = if let Some(suffix) = allowed_host_pattern.strip_prefix("*.")
                {
                    let host = host.to_ascii_lowercase();

                    if host.len() <= suffix.len() || !host.ends_with(&suffix) {
                        false
                    } else {
                        // Make sure there is a component in place of the wildcard.
                        host.as_bytes()[host.len() - suffix.len() - 1] == b'.'
                    }
                } else {
                    allowed_host_pattern.eq_ignore_ascii_case(host)
                };

                let is_port_allowed =
                    self.port.as_deref() == uri.port().as_ref().map(|port| port.as_str());

                if is_host_allowed && is_port_allowed {
                    if let Some(allowed_scheme) = &self.scheme {
                        if let Some(scheme) = uri.scheme() {
                            return scheme.as_str() == allowed_scheme;
                        }
                    } else {
                        return true;
                    }
                }
            }
        } else if let Some(allowed_scheme) = &self.scheme {
            if let Some(scheme) = uri.scheme() {
                return scheme.as_str() == allowed_scheme;
            }
        }

        false
    }
}

impl From<&str> for HostPattern {
    fn from(pattern: &str) -> Self {
        Self::new(pattern)
    }
}

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

impl<'de> Deserialize<'de> for HostPattern {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        Ok(HostPattern::new(&String::deserialize(deserializer)?))
    }
}

/// Returns true if the given URI matches at least one of the [`HostPattern`]s.
pub(crate) fn is_uri_allowed(patterns: &[HostPattern], uri: &Uri) -> bool {
    for pattern in patterns {
        if pattern.matches(uri) {
            return true;
        }
    }

    false
}

/// Maximum number of HTTP redirects [`RedirectResolver`] will follow before giving up.
const MAX_REDIRECTS: usize = 10;

/// Resolver wrapper that follows HTTP redirects at the SDK layer, validating each hop.
///
/// The underlying client is configured not to follow redirects on its own (`max_redirects(0)` /
/// `redirect::Policy::none()`), so each 3xx surfaces here as a bare response. This wrapper then:
///
/// - if `allow_redirects` is `false`, returns [`HttpResolverError::RedirectDisallowed`] rather than
///   following;
/// - otherwise resolves the `Location` (relative locations are resolved against the current URL)
///   and, if the target is a non-globally-routable/internal address ([`host_is_non_global`]),
///   returns [`HttpResolverError::RedirectTargetDisallowed`] (SSRF protection, CAI-12574);
/// - otherwise re-issues the request to the target through the wrapped resolver, preserving the
///   method and body, up to [`MAX_REDIRECTS`] hops.
///
/// This wrapper sits *outside* [`RestrictedResolver`], so each re-issued hop passes back through the
/// allow-list (when one is configured) as well as the internal-address check above.
#[derive(Debug)]
pub(crate) struct RedirectResolver<T> {
    inner: T,
    allow_redirects: bool,
}

impl<T> RedirectResolver<T> {
    /// Wraps `inner`. If `allow_redirects` is false, no redirect is followed.
    pub(crate) fn new(inner: T, allow_redirects: bool) -> Self {
        Self {
            inner,
            allow_redirects,
        }
    }

    /// Inspects a response and decides what to do next.
    ///
    /// Returns `Ok(None)` if the response is not a redirect (the caller returns it as-is), or
    /// `Ok(Some(target))` with the validated redirect target to re-issue. Errors if redirects are
    /// disabled or the target is disallowed.
    fn redirect_target<B>(
        &self,
        from_uri: &Uri,
        response: &Response<B>,
    ) -> Result<Option<Uri>, HttpResolverError> {
        let Some(location) = redirect_location(response) else {
            return Ok(None);
        };

        if !self.allow_redirects {
            return Err(HttpResolverError::RedirectDisallowed {
                uri: sanitize_for_log(&from_uri.to_string()),
                location: sanitize_for_log(&location),
            });
        }

        let target = resolve_redirect_target(from_uri, &location)?;
        if host_is_non_global(&target) {
            return Err(HttpResolverError::RedirectTargetDisallowed {
                uri: sanitize_for_log(&from_uri.to_string()),
                location: sanitize_for_log(&target.to_string()),
            });
        }

        Ok(Some(target))
    }
}

impl<T: SyncHttpResolver> SyncHttpResolver for RedirectResolver<T> {
    fn http_resolve(
        &self,
        mut request: Request<Vec<u8>>,
    ) -> Result<Response<Box<dyn Read>>, HttpResolverError> {
        for _ in 0..=MAX_REDIRECTS {
            let from_uri = request.uri().clone();
            let method = request.method().clone();
            let headers = request.headers().clone();
            let body = request.body().clone();

            let response = self.inner.http_resolve(request)?;

            match self.redirect_target(&from_uri, &response)? {
                None => return Ok(response),
                Some(target) => {
                    request = build_redirected_request(method, headers, body, target)?;
                }
            }
        }

        Err(HttpResolverError::TooManyRedirects {
            uri: sanitize_for_log(&request.uri().to_string()),
        })
    }
}

#[cfg_attr(not(target_arch = "wasm32"), async_trait)]
#[cfg_attr(target_arch = "wasm32", async_trait(?Send))]
impl<T: AsyncHttpResolver + Sync> AsyncHttpResolver for RedirectResolver<T> {
    async fn http_resolve_async(
        &self,
        mut request: Request<Vec<u8>>,
    ) -> Result<Response<Box<dyn Read>>, HttpResolverError> {
        for _ in 0..=MAX_REDIRECTS {
            let from_uri = request.uri().clone();
            let method = request.method().clone();
            let headers = request.headers().clone();
            let body = request.body().clone();

            let response = self.inner.http_resolve_async(request).await?;

            match self.redirect_target(&from_uri, &response)? {
                None => return Ok(response),
                Some(target) => {
                    request = build_redirected_request(method, headers, body, target)?;
                }
            }
        }

        Err(HttpResolverError::TooManyRedirects {
            uri: sanitize_for_log(&request.uri().to_string()),
        })
    }
}

/// Returns the redirect target from a response's `Location` header if it is an HTTP redirect (a 3xx
/// status carrying a `Location`), otherwise `None`. A 3xx without a `Location` (e.g.
/// `304 Not Modified`) is not treated as a redirect.
fn redirect_location<B>(response: &Response<B>) -> Option<String> {
    if !response.status().is_redirection() {
        return None;
    }

    response
        .headers()
        .get(http::header::LOCATION)
        .and_then(|v| v.to_str().ok())
        .map(|s| s.to_owned())
}

/// Resolves a redirect `Location` (absolute or relative) against the request's current URI.
fn resolve_redirect_target(base: &Uri, location: &str) -> Result<Uri, HttpResolverError> {
    let base_url =
        url::Url::parse(&base.to_string()).map_err(|e| HttpResolverError::Other(Box::new(e)))?;

    let target = base_url
        .join(location)
        .map_err(|e| HttpResolverError::Other(Box::new(e)))?;

    target
        .as_str()
        .parse::<Uri>()
        .map_err(|e| HttpResolverError::Http(http::Error::from(e)))
}

/// Builds the follow-up request for a redirect, preserving the original method and body.
///
/// `Host` is dropped so the client recomputes it for the new authority. Credential-bearing headers
/// (`Authorization`, `Cookie`, `Proxy-Authorization`) are also dropped: a redirect can cross origins,
/// and forwarding credentials to the redirect target would leak them to a different host.
fn build_redirected_request(
    method: http::Method,
    headers: http::HeaderMap,
    body: Vec<u8>,
    target: Uri,
) -> Result<Request<Vec<u8>>, HttpResolverError> {
    let mut builder = Request::builder().method(method).uri(target);

    for (name, value) in headers.iter() {
        let drop = name == http::header::HOST
            || name == http::header::AUTHORIZATION
            || name == http::header::COOKIE
            || name == http::header::PROXY_AUTHORIZATION;
        if !drop {
            builder = builder.header(name, value);
        }
    }

    builder.body(body).map_err(HttpResolverError::Http)
}

/// Returns true if `uri`'s host is not globally routable (loopback, private, link-local /
/// cloud-metadata, unique-local, CGNAT, etc.) and must therefore not be used as a redirect target.
///
/// This is a URI-string check: it normalizes the host and rejects obfuscated/malformed numeric
/// forms. Filtering on the *resolved* IP address (to defeat DNS names that point at internal
/// addresses, i.e. DNS rebinding) is tracked separately in
/// <https://github.com/contentauth/c2pa-rs/issues/2430>.
pub(crate) fn host_is_non_global(uri: &Uri) -> bool {
    let Some(host) = uri.host() else {
        // A request with no host is malformed; reject it under the strict policy.
        return true;
    };

    let host = normalize_host(host);

    if let Ok(ip) = host.parse::<IpAddr>() {
        return ip_is_non_global(ip);
    }

    // Reject numeric hosts that did not parse as a standard IP address. These are obfuscated or
    // malformed IPv4 forms (e.g. `2130706433`, `127.1`, `0x7f.0.0.1`) that an OS resolver may still
    // route to an internal address, so we fail closed. Comprehensive resolved-IP filtering is
    // tracked in <https://github.com/contentauth/c2pa-rs/issues/2430>.
    if looks_like_obfuscated_ip(&host) {
        return true;
    }

    // Otherwise treat it as a DNS name. Block the loopback host name; DNS names that resolve to
    // internal addresses are handled by resolved-IP filtering (see above).
    host == "localhost" || host.ends_with(".localhost")
}

/// Normalizes a URI host for comparison: strips IPv6 brackets and a fully-qualified trailing dot,
/// and lower-cases the result.
fn normalize_host(host: &str) -> String {
    let host = host
        .strip_prefix('[')
        .and_then(|h| h.strip_suffix(']'))
        .unwrap_or(host);

    let host = host.strip_suffix('.').unwrap_or(host);

    host.to_ascii_lowercase()
}

/// Returns true if `host` looks like a numeric IPv4 address in a non-standard/obfuscated form:
/// all digits and dots (decimal / octal-looking forms such as `2130706433`, `127.1`, `0177.0.0.1`),
/// or any dot-separated component in `0x`/`0X` hex form. The hex form may appear in *any* position,
/// not just the first (e.g. `127.0x1` or `0x7f.0x0.0x0.0x1`). Standard addresses are handled by
/// `IpAddr::parse` before this is called; this only catches forms that parse failed on.
fn looks_like_obfuscated_ip(host: &str) -> bool {
    if host.is_empty() {
        return false;
    }

    // Purely decimal / dotted-decimal (and octal-looking) numeric forms.
    if host.bytes().all(|b| b.is_ascii_digit() || b == b'.') {
        return true;
    }

    // A hex-form octet in any position.
    host.split('.')
        .any(|label| label.starts_with("0x") || label.starts_with("0X"))
}

/// Returns true if `ip` is not a globally routable unicast address and should therefore be blocked
/// by the default network policy.
fn ip_is_non_global(ip: IpAddr) -> bool {
    match ip {
        IpAddr::V4(v4) => ipv4_is_non_global(v4),
        IpAddr::V6(v6) => ipv6_is_non_global(v6),
    }
}

fn ipv4_is_non_global(ip: Ipv4Addr) -> bool {
    let [a, b, ..] = ip.octets();

    ip.is_unspecified()          // 0.0.0.0
        || a == 0                // 0.0.0.0/8 "this network"
        || ip.is_loopback()      // 127.0.0.0/8
        || ip.is_private()       // 10/8, 172.16/12, 192.168/16
        || ip.is_link_local()    // 169.254.0.0/16 (includes 169.254.169.254)
        || ip.is_broadcast()     // 255.255.255.255
        || ip.is_documentation() // 192.0.2/24, 198.51.100/24, 203.0.113/24
        || ip.is_multicast()     // 224.0.0.0/4
        || (a == 100 && (b & 0xc0) == 64) // 100.64.0.0/10 CGNAT / shared address space
}

fn ipv6_is_non_global(ip: Ipv6Addr) -> bool {
    // Unwrap IPv4-mapped addresses (e.g. ::ffff:169.254.169.254) and apply the IPv4 rules.
    if let Some(v4) = ip.to_ipv4_mapped() {
        return ipv4_is_non_global(v4);
    }

    let segments = ip.segments();

    ip.is_unspecified()                     // ::
        || ip.is_loopback()                 // ::1
        || ip.is_multicast()                // ff00::/8
        || (segments[0] & 0xfe00) == 0xfc00 // fc00::/7 unique local
        || (segments[0] & 0xffc0) == 0xfe80 // fe80::/10 link local
}

#[cfg(test)]
mod test {
    #![allow(clippy::panic, clippy::unwrap_used)]

    use super::*;

    struct NoopHttpResolver;

    impl SyncHttpResolver for NoopHttpResolver {
        fn http_resolve(
            &self,
            _request: Request<Vec<u8>>,
        ) -> Result<Response<Box<dyn Read>>, HttpResolverError> {
            Ok(Response::new(Box::new(std::io::empty()) as Box<dyn Read>))
        }
    }

    fn assert_allowed_uri(resolver: &impl SyncHttpResolver, uri: &'static str) {
        let result = resolver.http_resolve(
            Request::get(Uri::from_static(uri))
                .body(Vec::new())
                .unwrap(),
        );
        assert!(matches!(result, Ok(..)));
    }

    fn assert_disallowed_uri(resolver: &impl SyncHttpResolver, uri: &'static str) {
        let result = resolver.http_resolve(
            Request::get(Uri::from_static(uri))
                .body(Vec::new())
                .unwrap(),
        );
        assert!(matches!(
            result,
            Err(HttpResolverError::UriDisallowed { .. })
        ));
    }

    #[test]
    fn allowed_http_request() {
        let allowed_list = vec![
            "*.prefix.contentauthenticity.org".into(),
            "test.contentauthenticity.org".into(),
            "fakecontentauthenticity.org".into(),
            "https://*.contentauthenticity.org".into(),
            "https://test.contentauthenticity.org".into(),
        ];
        let restricted_resolver =
            RestrictedResolver::with_allowed_hosts(NoopHttpResolver, allowed_list);

        assert_allowed_uri(&restricted_resolver, "fakecontentauthenticity.org");
        assert_allowed_uri(&restricted_resolver, "test.prefix.contentauthenticity.org");
        assert_allowed_uri(&restricted_resolver, "https://test.contentauthenticity.org");
        assert_allowed_uri(
            &restricted_resolver,
            "https://test2.contentauthenticity.org",
        );

        assert_disallowed_uri(&restricted_resolver, "test.test.contentauthenticity.org");
        assert_disallowed_uri(
            &restricted_resolver,
            "https://test.prefix.fakecontentauthenticity.org",
        );
        assert_disallowed_uri(
            &restricted_resolver,
            "https://test.fakecontentauthenticity.org",
        );
        assert_disallowed_uri(&restricted_resolver, "https://contentauthenticity.org");
    }

    #[test]
    fn allowed_none_http_request() {
        let allowed_list = vec![];
        let restricted_resolver =
            RestrictedResolver::with_allowed_hosts(NoopHttpResolver, allowed_list);

        assert_disallowed_uri(
            &restricted_resolver,
            "test.test.fakecontentauthenticity.org",
        );
        assert_disallowed_uri(
            &restricted_resolver,
            "https://test.prefix.fakecontentauthenticity.org",
        );
        assert_disallowed_uri(
            &restricted_resolver,
            "https://test.fakecontentauthenticity.org",
        );
        assert_disallowed_uri(&restricted_resolver, "https://contentauthenticity.org");
    }

    #[test]
    fn wildcard_pattern() {
        let pattern = HostPattern::new("*.contentauthenticity.org");

        let uri = Uri::from_static("test.contentauthenticity.org");
        assert!(pattern.matches(&uri));

        let uri = Uri::from_static("contentauthenticity.org");
        assert!(!pattern.matches(&uri));

        let uri = Uri::from_static("fakecontentauthenticity.org");
        assert!(!pattern.matches(&uri));
    }

    #[test]
    fn wildcard_pattern_with_scheme() {
        let pattern = HostPattern::new("https://*.contentauthenticity.org");

        let uri = Uri::from_static("test.contentauthenticity.org");
        assert!(!pattern.matches(&uri));

        let uri = Uri::from_static("contentauthenticity.org");
        assert!(!pattern.matches(&uri));

        let uri = Uri::from_static("fakecontentauthenticity.org");
        assert!(!pattern.matches(&uri));

        let uri = Uri::from_static("https://test.contentauthenticity.org");
        assert!(pattern.matches(&uri));

        let uri = Uri::from_static("https://contentauthenticity.org");
        assert!(!pattern.matches(&uri));

        let uri = Uri::from_static("https://fakecontentauthenticity.org");
        assert!(!pattern.matches(&uri));

        let uri = Uri::from_static("http://test.contentauthenticity.org");
        assert!(!pattern.matches(&uri));
    }

    #[test]
    fn case_insensitive_pattern() {
        let pattern = HostPattern::new("*.contentAuthenticity.org");

        let uri = Uri::from_static("tEst.conTentauthenticity.orG");
        assert!(pattern.matches(&uri));
    }

    #[test]
    fn exact_pattern() {
        let pattern = HostPattern::new("contentauthenticity.org");

        let uri = Uri::from_static("contentauthenticity.org");
        assert!(pattern.matches(&uri));

        let uri = Uri::from_static("https://contentauthenticity.org");
        assert!(pattern.matches(&uri));

        let uri = Uri::from_static("http://contentauthenticity.org");
        assert!(pattern.matches(&uri));
    }

    #[test]
    fn exact_pattern_with_schema() {
        let pattern = HostPattern::new("https://contentauthenticity.org");

        let uri = Uri::from_static("https://contentauthenticity.org");
        assert!(pattern.matches(&uri));

        let uri = Uri::from_static("http://contentauthenticity.org");
        assert!(!pattern.matches(&uri));

        let uri = Uri::from_static("contentauthenticity.org");
        assert!(!pattern.matches(&uri));
    }

    #[test]
    fn exact_pattern_ip_address() {
        let pattern = HostPattern::new("192.0.2.1");

        let uri = Uri::from_static("192.0.2.1");
        assert!(pattern.matches(&uri));

        let uri = Uri::from_static("192.0.2.1.1");
        assert!(!pattern.matches(&uri));
    }

    #[test]
    fn exact_pattern_ip_address_with_port() {
        let pattern = HostPattern::new("192.0.2.1:443");

        let uri = Uri::from_static("192.0.2.1:443");
        assert!(pattern.matches(&uri));

        let uri = Uri::from_static("192.0.2.1");
        assert!(!pattern.matches(&uri));
    }

    #[test]
    fn exact_pattern_hostname_with_port() {
        let pattern = HostPattern::new("contentauthenticity.org:8080");

        let uri = Uri::from_static("contentauthenticity.org:8080");
        assert!(pattern.matches(&uri));

        let uri = Uri::from_static("contentauthenticity.org");
        assert!(!pattern.matches(&uri));
    }

    #[test]
    fn scheme_only_pattern() {
        let pattern = HostPattern::new("https://");

        let uri = Uri::from_static("https://contentauthenticity.org");
        assert!(pattern.matches(&uri));

        let uri = Uri::from_static("http://contentauthenticity.org");
        assert!(!pattern.matches(&uri));

        let uri = Uri::from_static("contentauthenticity.org");
        assert!(!pattern.matches(&uri));
    }

    #[test]
    fn invalid_pattern() {
        let pattern = HostPattern::new("https:// ");

        let uri = Uri::from_static("https://contentauthenticity.org");
        assert!(!pattern.matches(&uri));
    }

    #[test]
    fn test_restricted_generic_resolver() {
        use crate::http::{HttpResolverError, SyncGenericResolver, SyncHttpResolver};

        let inner = SyncGenericResolver::new();
        let mut resolver = RestrictedResolver::new(inner);

        // Set allowed hosts to only allow localhost
        resolver.set_allowed_hosts(Some(vec!["127.0.0.1".into()]));

        // Request to localhost should work (though it will fail to connect in this test)
        let request = http::Request::get("http://127.0.0.1/test")
            .body(vec![])
            .unwrap();
        let result = resolver.http_resolve(request);
        // We expect a connection error, not a UriDisallowed error
        assert!(!matches!(
            result,
            Err(HttpResolverError::UriDisallowed { .. })
        ));

        // Request to external host should be blocked
        let request = http::Request::get("http://example.com/test")
            .body(vec![])
            .unwrap();
        let result = resolver.http_resolve(request);
        assert!(matches!(
            result,
            Err(HttpResolverError::UriDisallowed { .. })
        ));
    }

    #[cfg(not(target_arch = "wasm32"))]
    #[tokio::test]
    async fn test_restricted_async_generic_resolver() {
        use crate::http::{AsyncGenericResolver, AsyncHttpResolver, HttpResolverError};

        let inner = AsyncGenericResolver::new();
        let mut resolver = RestrictedResolver::new(inner);

        // Set allowed hosts to only allow localhost
        resolver.set_allowed_hosts(Some(vec!["127.0.0.1".into()]));

        // Request to localhost should work (though it will fail to connect in this test)
        let request = http::Request::get("http://127.0.0.1/test")
            .body(vec![])
            .unwrap();
        let result = resolver.http_resolve_async(request).await;
        // We expect a connection error, not a UriDisallowed error
        assert!(!matches!(
            result,
            Err(HttpResolverError::UriDisallowed { .. })
        ));

        // Request to external host should be blocked
        let request = http::Request::get("http://example.com/test")
            .body(vec![])
            .unwrap();
        let result = resolver.http_resolve_async(request).await;
        assert!(matches!(
            result,
            Err(HttpResolverError::UriDisallowed { .. })
        ));
    }

    #[test]
    fn non_global_hosts_are_rejected_as_redirect_targets() {
        for uri in [
            "http://169.254.169.254/latest/meta-data/", // link-local / cloud metadata
            "http://127.0.0.1/",                        // IPv4 loopback
            "http://127.1.2.3/",                        // IPv4 loopback (whole /8)
            "http://10.0.0.1/",                         // RFC1918
            "http://172.16.5.4/",                       // RFC1918
            "http://192.168.1.1/",                      // RFC1918
            "http://100.64.0.1/",                       // CGNAT / shared
            "http://0.0.0.0/",                          // unspecified
            "http://[::1]/",                            // IPv6 loopback
            "http://[fe80::1]/",                        // IPv6 link-local
            "http://[fc00::1]/",                        // IPv6 unique-local
            "http://[::ffff:169.254.169.254]/",         // IPv4-mapped link-local
            "http://localhost/",                        // loopback host name
            "http://api.localhost/",                    // loopback host name suffix
            "http://LOCALHOST/",                        // case-insensitive host name
            "http://127.0.0.1./",                       // trailing-dot FQDN form of loopback
            "http://2130706433/",                       // obfuscated decimal 127.0.0.1
            "http://0x7f000001/",                       // obfuscated hex 127.0.0.1
            "http://127.0x1/",                          // hex octet in a non-leading position
            "http://0x7f.0x0.0x0.0x1/",                 // dotted all-hex form of 127.0.0.1
            "http://127.1/",                            // short-form IPv4 loopback
        ] {
            assert!(
                host_is_non_global(&Uri::from_static(uri)),
                "expected {uri} to be denied"
            );
        }
    }

    #[test]
    fn global_hosts_are_allowed_as_redirect_targets() {
        for uri in [
            "http://93.184.216.34/",            // public IPv4 literal
            "https://contentauthenticity.org/", // public host name
            "https://sub.example.com/path",
            "http://[2606:2800:220:1:248:1893:25c8:1946]/", // public IPv6 literal
            "http://cafe.example.com/", // hex-looking label is a normal host name
        ] {
            assert!(
                !host_is_non_global(&Uri::from_static(uri)),
                "expected {uri} to be allowed"
            );
        }
    }

    // A scripted resolver used to exercise the `RedirectResolver` loop without real networking. It
    // returns a canned response based on the request path.
    struct ScriptedChain;

    impl ScriptedChain {
        fn response(uri: &str) -> Response<Box<dyn Read>> {
            let empty = || Box::new(std::io::empty()) as Box<dyn Read>;
            let redirect_to = |location: &str| {
                Response::builder()
                    .status(302)
                    .header(http::header::LOCATION, location)
                    .body(empty())
                    .unwrap()
            };

            if uri.contains("/final") {
                Response::builder().status(200).body(empty()).unwrap()
            } else if uri.contains("/to-public") {
                redirect_to("http://example.com/final")
            } else if uri.contains("/to-internal") {
                redirect_to("http://169.254.169.254/latest/meta-data/")
            } else if uri.contains("/loop") {
                redirect_to("http://example.com/loop")
            } else {
                Response::builder().status(404).body(empty()).unwrap()
            }
        }
    }

    impl SyncHttpResolver for ScriptedChain {
        fn http_resolve(
            &self,
            request: Request<Vec<u8>>,
        ) -> Result<Response<Box<dyn Read>>, HttpResolverError> {
            Ok(Self::response(&request.uri().to_string()))
        }
    }

    fn scripted_get(
        resolver: &impl SyncHttpResolver,
        uri: &'static str,
    ) -> Result<Response<Box<dyn Read>>, HttpResolverError> {
        resolver.http_resolve(
            Request::get(Uri::from_static(uri))
                .body(Vec::new())
                .unwrap(),
        )
    }

    #[test]
    fn redirect_resolver_follows_redirect_to_public_host() {
        let resolver = RedirectResolver::new(ScriptedChain, true);
        let response = scripted_get(&resolver, "http://example.com/to-public").unwrap();
        assert_eq!(response.status(), 200);
    }

    #[test]
    fn redirect_resolver_blocks_redirect_to_internal_host() {
        let resolver = RedirectResolver::new(ScriptedChain, true);
        let result = scripted_get(&resolver, "http://example.com/to-internal");
        assert!(matches!(
            result,
            Err(HttpResolverError::RedirectTargetDisallowed { .. })
        ));
    }

    #[test]
    fn redirect_resolver_refuses_redirect_when_disabled() {
        let resolver = RedirectResolver::new(ScriptedChain, false);
        let result = scripted_get(&resolver, "http://example.com/to-public");
        assert!(matches!(
            result,
            Err(HttpResolverError::RedirectDisallowed { .. })
        ));
    }

    #[test]
    fn redirect_resolver_caps_redirect_chain() {
        let resolver = RedirectResolver::new(ScriptedChain, true);
        let result = scripted_get(&resolver, "http://example.com/loop");
        assert!(matches!(
            result,
            Err(HttpResolverError::TooManyRedirects { .. })
        ));
    }

    #[test]
    fn resolve_redirect_target_handles_relative_locations() {
        let base = Uri::from_static("https://example.com/a/b");
        let target = resolve_redirect_target(&base, "/c/d").unwrap();
        assert_eq!(target.to_string(), "https://example.com/c/d");

        let target = resolve_redirect_target(&base, "https://other.example.org/x").unwrap();
        assert_eq!(target.to_string(), "https://other.example.org/x");
    }

    #[test]
    fn sanitize_for_log_escapes_control_chars_and_truncates() {
        // CR/LF are escaped so a crafted URL can't inject lines into logs.
        let out = sanitize_for_log("http://x/\r\nSet-Cookie: evil");
        assert!(!out.contains('\n') && !out.contains('\r'));
        assert!(out.contains("\\r") && out.contains("\\n"));

        // Overlong values are truncated with an ellipsis marker.
        let out = sanitize_for_log(&"a".repeat(1000));
        assert!(out.ends_with('…'));
        assert!(out.chars().count() <= 257);
    }

    #[test]
    fn build_redirected_request_drops_credential_headers() {
        use http::header;

        let mut headers = http::HeaderMap::new();
        headers.insert(header::AUTHORIZATION, "Bearer secret".parse().unwrap());
        headers.insert(header::COOKIE, "sid=secret".parse().unwrap());
        headers.insert(header::HOST, "old.example.com".parse().unwrap());
        headers.insert(header::ACCEPT, "application/json".parse().unwrap());

        let req = build_redirected_request(
            http::Method::GET,
            headers,
            Vec::new(),
            Uri::from_static("https://new.example.com/x"),
        )
        .unwrap();

        // Credential-bearing and host headers are not forwarded across the redirect.
        assert!(req.headers().get(header::AUTHORIZATION).is_none());
        assert!(req.headers().get(header::COOKIE).is_none());
        assert!(req.headers().get(header::HOST).is_none());
        // Non-sensitive headers are preserved.
        assert_eq!(
            req.headers().get(header::ACCEPT).unwrap(),
            "application/json"
        );
    }
}