liter-llm 2.0.0

Universal LLM API client — 165 providers, streaming, tool calling. Rust-powered, type-safe, compiled.
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
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
//! Outbound HTTP request policy guard.
//!
//! Allows callers (the proxy server in particular) to constrain which upstream
//! URLs can be reached.  The library default is [`OutboundPolicy::Off`] —
//! preserves backward-compatibility for FFI consumers and embedded applications
//! where the application owner registers their own providers and is trusted.
//! The proxy switches the policy to [`OutboundPolicy::DenyPrivate`] at startup
//! so multi-tenant deployments cannot SSRF into cloud metadata services or
//! private networks. Native HTTP clients enforce the policy before each
//! request, on redirects, and again after connection-time DNS resolution.

#[cfg(all(any(feature = "native-http", feature = "wasm-http"), not(target_arch = "wasm32")))]
use std::error::Error as _;
use std::net::IpAddr;
use std::sync::{OnceLock, RwLock};

use url::Url;

use crate::error::LiterLlmError;

/// Controls which upstream URLs the library is allowed to connect to.
///
/// Set once at application startup via [`set_outbound_policy`].  Checked at
/// provider registration time, immediately before each effective request, on
/// native redirect hops, and at every native TCP connection attempt (defense
/// in depth against DNS rebinding).
#[derive(Debug, Clone, Default)]
#[cfg_attr(alef, alef(skip))]
pub enum OutboundPolicy {
    /// No restrictions — library default.  Use only when the application is
    /// the sole registrar of provider URLs and trusts itself.
    #[default]
    Off,

    /// Reject URLs whose host resolves to any private / loopback / link-local
    /// / multicast / CGNAT address. Recommended for native multi-tenant proxies.
    /// WASM can reject literal addresses but browser-owned DNS and redirects
    /// cannot be inspected by this policy.
    DenyPrivate,

    /// Only allow URLs whose origin (scheme + host + port) matches one of the
    /// provided entries.
    Allowlist(Vec<Url>),
}

static GLOBAL_POLICY: OnceLock<RwLock<OutboundPolicy>> = OnceLock::new();

fn policy_lock() -> &'static RwLock<OutboundPolicy> {
    GLOBAL_POLICY.get_or_init(|| RwLock::new(OutboundPolicy::default()))
}

/// Set the global outbound policy.
///
/// Subsequent calls to [`validate_outbound_url`] and the per-connection DNS
/// resolver use this policy.  Intended to be called once at application
/// startup before any provider is registered.
#[cfg_attr(alef, alef(skip))]
#[tracing::instrument(level = "info")]
pub fn set_outbound_policy(policy: OutboundPolicy) {
    // ~keep A poisoned lock must not permanently disable outbound-policy enforcement:
    // recover the guard and keep going rather than propagate the panic.
    let mut guard = policy_lock().write().unwrap_or_else(|poisoned| {
        tracing::warn!("outbound policy lock poisoned; recovering");
        poisoned.into_inner()
    });
    *guard = policy;
}

/// Read a snapshot of the current outbound policy.
#[cfg_attr(alef, alef(skip))]
pub fn current_policy() -> OutboundPolicy {
    // ~keep See `set_outbound_policy`: recover rather than panic on a poisoned lock.
    policy_lock()
        .read()
        .unwrap_or_else(|poisoned| {
            tracing::warn!("outbound policy lock poisoned; recovering");
            poisoned.into_inner()
        })
        .clone()
}

/// Validate `raw_url` against the current outbound policy.
///
/// Under [`OutboundPolicy::DenyPrivate`] the host is resolved via DNS; if
/// *any* returned address is forbidden the call returns
/// [`LiterLlmError::OutboundForbidden`].  This defeats DNS rebinding at
/// registration time.
///
/// Under [`OutboundPolicy::Off`] the function is a no-op and always returns
/// `Ok(())`.
#[cfg_attr(alef, alef(skip))]
pub async fn validate_outbound_url(raw_url: &str) -> Result<(), LiterLlmError> {
    let policy = current_policy();
    if matches!(policy, OutboundPolicy::Off) {
        return Ok(());
    }

    let url = Url::parse(raw_url).map_err(|e| LiterLlmError::OutboundForbidden {
        url: raw_url.to_string(),
        reason: format!("invalid URL: {e}"),
    })?;

    match url.scheme() {
        "http" | "https" => {}
        other => {
            return Err(LiterLlmError::OutboundForbidden {
                url: raw_url.to_string(),
                reason: format!("scheme '{other}' is not allowed; only http/https"),
            });
        }
    }

    validate_literal_host(&url, raw_url)?;

    match policy {
        OutboundPolicy::Off => Ok(()),
        OutboundPolicy::DenyPrivate => check_deny_private(&url, raw_url).await,
        OutboundPolicy::Allowlist(allowed) => check_allowlist(&url, raw_url, &allowed),
    }
}

#[cfg(target_arch = "wasm32")]
async fn check_deny_private(_url: &Url, _raw: &str) -> Result<(), LiterLlmError> {
    // ~keep Literal private hosts are rejected before this function. WASM has no Rust DNS or
    // ~keep redirect hook, so hostname resolution and redirect enforcement remain browser-owned.
    Ok(())
}

/// Synchronous URL validation — parse + scheme check + literal-IP private range
/// check only.  Does not perform DNS resolution.
///
/// Used from synchronous registration paths.  Catches the obvious
/// `http://169.254.169.254/` literal-IP case without requiring an async
/// context.  DNS-based checks still happen at connect time via
/// [`GuardedResolver`].
#[cfg_attr(alef, alef(skip))]
pub fn validate_outbound_url_sync(raw_url: &str) -> Result<(), LiterLlmError> {
    let policy = current_policy();
    if matches!(policy, OutboundPolicy::Off) {
        return Ok(());
    }

    let url = Url::parse(raw_url).map_err(|e| LiterLlmError::OutboundForbidden {
        url: raw_url.to_string(),
        reason: format!("invalid URL: {e}"),
    })?;

    match url.scheme() {
        "http" | "https" => {}
        other => {
            return Err(LiterLlmError::OutboundForbidden {
                url: raw_url.to_string(),
                reason: format!("scheme '{other}' is not allowed; only http/https"),
            });
        }
    }

    validate_literal_host(&url, raw_url)?;

    if let OutboundPolicy::Allowlist(allowed) = policy {
        return check_allowlist(&url, raw_url, &allowed);
    }

    Ok(())
}

fn validate_literal_host(url: &Url, raw_url: &str) -> Result<(), LiterLlmError> {
    match url.host() {
        Some(url::Host::Ipv4(v4)) if is_forbidden(IpAddr::V4(v4)) => {
            return Err(LiterLlmError::OutboundForbidden {
                url: raw_url.to_owned(),
                reason: format!("host is a forbidden address {v4}"),
            });
        }
        Some(url::Host::Ipv6(v6)) if is_forbidden(IpAddr::V6(v6)) => {
            return Err(LiterLlmError::OutboundForbidden {
                url: raw_url.to_owned(),
                reason: format!("host is a forbidden address {v6}"),
            });
        }
        _ => {}
    }
    Ok(())
}

#[cfg(all(feature = "native-http", not(target_arch = "wasm32")))]
fn outbound_redirect_policy(allow_cross_origin: bool) -> reqwest::redirect::Policy {
    let default_policy = reqwest::redirect::Policy::default();
    reqwest::redirect::Policy::custom(move |attempt| {
        match validate_redirect(attempt.previous().last(), attempt.url(), allow_cross_origin) {
            Ok(()) => default_policy.redirect(attempt),
            Err(error) => attempt.error(error),
        }
    })
}

#[cfg(all(feature = "native-http", not(target_arch = "wasm32")))]
fn validate_redirect(previous: Option<&Url>, next: &Url, allow_cross_origin: bool) -> Result<(), LiterLlmError> {
    if let Some(previous) = previous
        && previous.scheme() == "https"
        && next.scheme() == "http"
    {
        return Err(LiterLlmError::OutboundForbidden {
            url: next.as_str().to_owned(),
            reason: "HTTPS-to-HTTP redirects are forbidden".into(),
        });
    }

    if matches!(current_policy(), OutboundPolicy::Off) {
        return Ok(());
    }

    if let Some(previous) = previous
        && !allow_cross_origin
        && !same_origin(previous, next)
    {
        return Err(LiterLlmError::OutboundForbidden {
            url: next.as_str().to_owned(),
            reason: "cross-origin redirects are forbidden while an outbound policy is active".into(),
        });
    }

    validate_outbound_url_sync(next.as_str())
}

fn same_origin(left: &Url, right: &Url) -> bool {
    left.scheme() == right.scheme()
        && left.host_str() == right.host_str()
        && left.port_or_known_default() == right.port_or_known_default()
}

#[cfg(not(target_arch = "wasm32"))]
async fn check_deny_private(url: &Url, raw: &str) -> Result<(), LiterLlmError> {
    let host = url.host_str().ok_or_else(|| LiterLlmError::OutboundForbidden {
        url: raw.to_string(),
        reason: "URL has no host".into(),
    })?;

    let port = url.port_or_known_default().unwrap_or(0);

    let addrs =
        tokio::net::lookup_host(format!("{host}:{port}"))
            .await
            .map_err(|e| LiterLlmError::OutboundForbidden {
                url: raw.to_string(),
                reason: format!("DNS resolution failed: {e}"),
            })?;

    for sa in addrs {
        if is_forbidden(sa.ip()) {
            return Err(LiterLlmError::OutboundForbidden {
                url: raw.to_string(),
                reason: format!("host resolves to forbidden address {}", sa.ip()),
            });
        }
    }
    Ok(())
}

fn check_allowlist(url: &Url, raw: &str, allowed: &[Url]) -> Result<(), LiterLlmError> {
    let origin_match = allowed.iter().any(|allowed_url| same_origin(allowed_url, url));
    if origin_match {
        Ok(())
    } else {
        Err(LiterLlmError::OutboundForbidden {
            url: raw.to_string(),
            reason: "URL not in outbound allowlist".into(),
        })
    }
}

/// Returns `true` if `ip` is in a range that must not be reached from a
/// multi-tenant proxy.
///
/// Covers loopback, unspecified, private (RFC 1918), link-local, multicast,
/// broadcast, CGNAT (100.64/10), IPv4-mapped IPv6, ULA (fc00::/7), and IPv6
/// link-local (fe80::/10).
#[cfg_attr(alef, alef(skip))]
pub fn is_forbidden(ip: IpAddr) -> bool {
    match ip {
        IpAddr::V4(v4) => {
            v4.is_loopback()
                || v4.is_unspecified()
                || v4.is_private()
                || v4.is_link_local()
                || v4.is_multicast()
                || v4.is_broadcast()
                || is_cgnat(v4)
        }
        IpAddr::V6(v6) => {
            v6.is_loopback()
                || v6.is_unspecified()
                || v6.is_multicast()
                || is_unique_local_v6(v6)
                || is_link_local_v6(v6)
                || v6
                    .to_ipv4_mapped()
                    .map(|m| is_forbidden(IpAddr::V4(m)))
                    .unwrap_or(false)
        }
    }
}

fn is_cgnat(ip: std::net::Ipv4Addr) -> bool {
    let [a, b, _, _] = ip.octets();
    a == 100 && (64..=127).contains(&b)
}

fn is_unique_local_v6(ip: std::net::Ipv6Addr) -> bool {
    (ip.segments()[0] & 0xfe00) == 0xfc00
}

fn is_link_local_v6(ip: std::net::Ipv6Addr) -> bool {
    (ip.segments()[0] & 0xffc0) == 0xfe80
}

/// A `reqwest` DNS resolver that filters resolved addresses through the
/// current [`OutboundPolicy`].
///
/// Install via `reqwest::Client::builder().dns_resolver(Arc::new(GuardedResolver))`.
/// Only active when the policy is not [`OutboundPolicy::Off`].  When the
/// policy is `Off` the resolver skips filtering entirely, falling back to
/// standard system behaviour.
#[cfg_attr(alef, alef(skip))]
pub struct GuardedResolver;

#[cfg(all(feature = "native-http", not(target_arch = "wasm32")))]
mod resolver_impl {
    use std::collections::HashMap;
    use std::net::SocketAddr;
    use std::sync::Arc;
    use std::sync::Mutex;
    use std::time::{Duration, Instant};

    use reqwest::dns::{Addrs, Name, Resolve, Resolving};

    use super::{GuardedResolver, LiterLlmError, OutboundPolicy, current_policy, is_forbidden};

    #[derive(Clone)]
    struct DnsCacheEntry {
        expires_at: Instant,
        addrs: Vec<SocketAddr>,
    }

    struct CachedGuardedResolver {
        cache_ttl: Option<Duration>,
        cache: Arc<Mutex<HashMap<String, DnsCacheEntry>>>,
    }

    impl CachedGuardedResolver {
        fn new(cache_ttl: Option<Duration>) -> Self {
            Self {
                cache_ttl,
                cache: Arc::new(Mutex::new(HashMap::new())),
            }
        }
    }

    fn cached_addrs(
        cache: &Mutex<HashMap<String, DnsCacheEntry>>,
        cache_ttl: Option<Duration>,
        host: &str,
    ) -> Option<Vec<SocketAddr>> {
        cache_ttl?;

        let now = Instant::now();
        let mut guard = cache.lock().unwrap_or_else(|poisoned| poisoned.into_inner());
        let entry = guard.get(host)?;
        if entry.expires_at > now {
            return Some(entry.addrs.clone());
        }
        guard.remove(host);
        None
    }

    fn store_addrs(
        cache: &Mutex<HashMap<String, DnsCacheEntry>>,
        cache_ttl: Option<Duration>,
        host: String,
        addrs: Vec<SocketAddr>,
    ) {
        let Some(ttl) = cache_ttl else {
            return;
        };
        if ttl.is_zero() {
            return;
        }

        let expires_at = Instant::now().checked_add(ttl).unwrap_or_else(Instant::now);
        let mut guard = cache.lock().unwrap_or_else(|poisoned| poisoned.into_inner());
        guard.insert(host, DnsCacheEntry { expires_at, addrs });
    }

    async fn resolve_system(host: &str) -> Result<Vec<SocketAddr>, Box<dyn std::error::Error + Send + Sync>> {
        let addrs = tokio::net::lookup_host((host, 0))
            .await
            .map_err(|e| {
                let err: Box<dyn std::error::Error + Send + Sync> = Box::new(e);
                err
            })?
            .collect();
        Ok(addrs)
    }

    pub(super) fn validate_addrs(
        policy: OutboundPolicy,
        host: &str,
        addrs: &[SocketAddr],
    ) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
        if matches!(policy, OutboundPolicy::Off) {
            return Ok(());
        }

        for sa in addrs {
            if is_forbidden(sa.ip()) {
                let err: Box<dyn std::error::Error + Send + Sync> = Box::new(LiterLlmError::OutboundForbidden {
                    url: format!("dns://{host}"),
                    reason: format!("DNS resolution produced forbidden address {}", sa.ip()),
                });
                return Err(err);
            }
        }

        Ok(())
    }

    impl Resolve for GuardedResolver {
        fn resolve(&self, name: Name) -> Resolving {
            Box::pin(async move {
                let policy = current_policy();
                let host = name.as_str().to_string();

                let addrs = resolve_system(&host).await?;
                validate_addrs(policy, &host, &addrs)?;

                let iter: Addrs = Box::new(addrs.into_iter());
                Ok(iter)
            })
        }
    }

    impl Resolve for CachedGuardedResolver {
        fn resolve(&self, name: Name) -> Resolving {
            let policy = current_policy();
            let host = name.as_str().to_string();
            let cache_ttl = self.cache_ttl;
            let cache = Arc::clone(&self.cache);

            Box::pin(async move {
                if let Some(addrs) = cached_addrs(&cache, cache_ttl, &host) {
                    validate_addrs(policy, &host, &addrs)?;
                    let iter: Addrs = Box::new(addrs.into_iter());
                    return Ok(iter);
                }

                let addrs = resolve_system(&host).await?;
                validate_addrs(policy, &host, &addrs)?;
                store_addrs(&cache, cache_ttl, host, addrs.clone());

                let iter: Addrs = Box::new(addrs.into_iter());
                Ok(iter)
            })
        }
    }

    /// Build an [`Arc`]-wrapped [`GuardedResolver`] ready for use with
    /// `reqwest::Client::builder().dns_resolver(...)`.
    #[cfg_attr(alef, alef(skip))]
    pub fn guarded_resolver() -> Arc<GuardedResolver> {
        Arc::new(GuardedResolver)
    }

    /// Build a resolver that applies the active outbound policy and optionally
    /// caches successful DNS lookups for the configured TTL.
    #[cfg_attr(alef, alef(skip))]
    pub fn cached_guarded_resolver(cache_ttl: Option<Duration>) -> Arc<dyn Resolve> {
        Arc::new(CachedGuardedResolver::new(cache_ttl))
    }
}

#[cfg(all(feature = "native-http", not(target_arch = "wasm32")))]
pub use resolver_impl::{cached_guarded_resolver, guarded_resolver};

#[cfg(all(feature = "native-http", not(target_arch = "wasm32")))]
/// Apply authenticated outbound-request protections to a native HTTP client.
///
/// The returned builder validates every resolved address and redirect target.
/// Cross-origin redirects are rejected so credentials in custom headers cannot
/// be forwarded to a different origin. Active policies also disable proxies;
/// otherwise the proxy could resolve the target outside the guarded resolver.
#[cfg_attr(alef, alef(skip))]
pub fn configure_outbound_client_builder(
    mut builder: reqwest::ClientBuilder,
    dns_cache_ttl: Option<std::time::Duration>,
) -> reqwest::ClientBuilder {
    builder = builder.redirect(outbound_redirect_policy(false));
    if !matches!(current_policy(), OutboundPolicy::Off) {
        builder = builder.no_proxy();
        builder = builder.dns_resolver(cached_guarded_resolver(dns_cache_ttl));
    } else if dns_cache_ttl.is_some() {
        builder = builder.dns_resolver(cached_guarded_resolver(dns_cache_ttl));
    }
    builder
}

#[cfg(all(feature = "native-http", not(target_arch = "wasm32")))]
pub(crate) fn configure_credential_free_outbound_client_builder(
    mut builder: reqwest::ClientBuilder,
) -> reqwest::ClientBuilder {
    builder = builder.redirect(outbound_redirect_policy(true));
    if !matches!(current_policy(), OutboundPolicy::Off) {
        builder = builder.no_proxy();
        builder = builder.dns_resolver(cached_guarded_resolver(None));
    }
    builder
}

#[cfg(all(feature = "native-http", not(target_arch = "wasm32")))]
pub(crate) fn authenticated_outbound_client() -> Result<reqwest::Client, LiterLlmError> {
    crate::ensure_crypto_provider();
    configure_outbound_client_builder(reqwest::Client::builder(), None)
        .build()
        .map_err(LiterLlmError::from)
}

#[cfg(all(any(feature = "native-http", feature = "wasm-http"), not(target_arch = "wasm32")))]
pub(crate) fn outbound_forbidden_from_reqwest(error: &reqwest::Error) -> Option<LiterLlmError> {
    let mut source = error.source();
    while let Some(current) = source {
        if let Some(LiterLlmError::OutboundForbidden { url, reason }) = current.downcast_ref::<LiterLlmError>() {
            return Some(LiterLlmError::OutboundForbidden {
                url: url.clone(),
                reason: reason.clone(),
            });
        }
        source = current.source();
    }
    None
}

#[cfg(all(feature = "wasm-http", target_arch = "wasm32"))]
pub(crate) fn outbound_forbidden_from_reqwest(_error: &reqwest::Error) -> Option<LiterLlmError> {
    // ~keep Browser fetch owns DNS and redirect handling, so reqwest cannot carry a native
    // ~keep guarded-resolver or redirect-policy error on WASM.
    None
}

#[cfg(test)]
mod tests {
    #[cfg(all(feature = "native-http", not(target_arch = "wasm32")))]
    use std::io::{Read, Write};
    #[cfg(all(feature = "native-http", not(target_arch = "wasm32")))]
    use std::net::{SocketAddr, TcpListener};
    #[cfg(all(feature = "native-http", not(target_arch = "wasm32")))]
    use std::sync::Arc;
    #[cfg(all(feature = "native-http", not(target_arch = "wasm32")))]
    use std::sync::atomic::{AtomicBool, Ordering};
    #[cfg(all(feature = "native-http", not(target_arch = "wasm32")))]
    use std::time::{Duration, Instant};

    use serial_test::serial;

    use super::*;

    #[cfg(all(feature = "native-http", not(target_arch = "wasm32")))]
    struct OneShotServer {
        address: SocketAddr,
        hit: Arc<AtomicBool>,
        handle: Option<std::thread::JoinHandle<()>>,
    }

    #[cfg(all(feature = "native-http", not(target_arch = "wasm32")))]
    impl OneShotServer {
        fn start(response: String) -> Self {
            let listener = TcpListener::bind("127.0.0.1:0").expect("bind redirect test server");
            listener.set_nonblocking(true).expect("set redirect server nonblocking");
            let address = listener.local_addr().expect("redirect server address");
            let hit = Arc::new(AtomicBool::new(false));
            let hit_writer = Arc::clone(&hit);
            let handle = std::thread::spawn(move || {
                let deadline = Instant::now() + Duration::from_secs(2);
                loop {
                    match listener.accept() {
                        Ok((mut stream, _)) => {
                            hit_writer.store(true, Ordering::SeqCst);
                            stream.set_nonblocking(false).expect("set redirect stream blocking");
                            let mut request = [0_u8; 4096];
                            let _ = stream.read(&mut request).expect("read redirect request");
                            stream.write_all(response.as_bytes()).expect("write redirect response");
                            break;
                        }
                        Err(error) if error.kind() == std::io::ErrorKind::WouldBlock => {
                            if Instant::now() >= deadline {
                                break;
                            }
                            std::thread::sleep(Duration::from_millis(5));
                        }
                        Err(error) => panic!("accept redirect request: {error}"),
                    }
                }
            });
            Self {
                address,
                hit,
                handle: Some(handle),
            }
        }

        fn finish(mut self) -> bool {
            self.handle
                .take()
                .expect("redirect server handle")
                .join()
                .expect("redirect server thread");
            self.hit.load(Ordering::SeqCst)
        }
    }

    /// Helper for sync tests — `#[serial(outbound_policy)]` on the test fn
    /// guarantees no other policy-mutating test is running concurrently.
    fn with_policy<F: FnOnce()>(policy: OutboundPolicy, f: F) {
        set_outbound_policy(policy);
        f();
        set_outbound_policy(OutboundPolicy::Off);
    }

    #[test]
    fn is_forbidden_recognizes_private_ranges() {
        let cases: &[(&str, bool)] = &[
            ("10.0.0.1", true),
            ("172.16.0.1", true),
            ("192.168.1.1", true),
            ("127.0.0.1", true),
            ("169.254.0.1", true),
            ("100.100.0.1", true),
            ("0.0.0.0", true),
            ("255.255.255.255", true),
            ("224.0.0.1", true),
            ("8.8.8.8", false),
            ("1.1.1.1", false),
        ];
        for (addr, expected) in cases {
            let ip: IpAddr = addr.parse().expect("valid IP");
            assert_eq!(is_forbidden(ip), *expected, "is_forbidden({addr}) should be {expected}");
        }
    }

    #[test]
    fn is_forbidden_ipv6_loopback() {
        let ip: IpAddr = "::1".parse().expect("::1 is a valid IPv6 address");
        assert!(is_forbidden(ip));
    }

    #[test]
    fn is_forbidden_ipv6_ula() {
        let ip: IpAddr = "fc00::1".parse().expect("fc00::1 is a valid IPv6 address");
        assert!(is_forbidden(ip));
    }

    #[test]
    fn is_forbidden_ipv6_link_local() {
        let ip: IpAddr = "fe80::1".parse().expect("fe80::1 is a valid IPv6 address");
        assert!(is_forbidden(ip));
    }

    #[test]
    fn is_forbidden_ipv6_public() {
        let ip: IpAddr = "2001:4860:4860::8888"
            .parse()
            .expect("Google DNS is a valid IPv6 address");
        assert!(!is_forbidden(ip));
    }

    #[test]
    #[serial(outbound_policy)]
    fn validate_sync_off_passes_everything() {
        with_policy(OutboundPolicy::Off, || {
            assert!(validate_outbound_url_sync("http://127.0.0.1/").is_ok());
            assert!(validate_outbound_url_sync("http://169.254.169.254/").is_ok());
        });
    }

    #[test]
    #[serial(outbound_policy)]
    fn validate_sync_deny_private_rejects_loopback() {
        with_policy(OutboundPolicy::DenyPrivate, || {
            let result = validate_outbound_url_sync("http://127.0.0.1/");
            assert!(result.is_err(), "loopback should be rejected");
            let err = result.unwrap_err().to_string();
            assert!(
                err.contains("forbidden"),
                "error message should mention 'forbidden': {err}"
            );
        });
    }

    #[test]
    #[serial(outbound_policy)]
    fn validate_sync_deny_private_rejects_metadata_ip() {
        with_policy(OutboundPolicy::DenyPrivate, || {
            let result = validate_outbound_url_sync("http://169.254.169.254/");
            assert!(result.is_err(), "metadata IP should be rejected");
        });
    }

    #[test]
    #[serial(outbound_policy)]
    fn validate_sync_deny_private_rejects_ula() {
        with_policy(OutboundPolicy::DenyPrivate, || {
            let result = validate_outbound_url_sync("http://[fc00::1]/");
            assert!(result.is_err(), "ULA address should be rejected");
        });
    }

    #[test]
    #[serial(outbound_policy)]
    fn validate_sync_deny_private_rejects_link_local_v6() {
        with_policy(OutboundPolicy::DenyPrivate, || {
            let result = validate_outbound_url_sync("http://[fe80::1]/");
            assert!(result.is_err(), "IPv6 link-local should be rejected");
        });
    }

    #[test]
    #[serial(outbound_policy)]
    fn validate_sync_deny_private_rejects_unknown_scheme() {
        with_policy(OutboundPolicy::DenyPrivate, || {
            let result = validate_outbound_url_sync("ftp://example.com/");
            assert!(result.is_err(), "ftp:// scheme should be rejected");
            let err = result.unwrap_err().to_string();
            assert!(err.contains("scheme"), "error should mention 'scheme': {err}");
        });
    }

    #[test]
    #[serial(outbound_policy)]
    fn validate_sync_allowlist_accepts_exact_origin() {
        let allowed = vec![Url::parse("https://api.openai.com").expect("openai URL should be valid")];
        with_policy(OutboundPolicy::Allowlist(allowed), || {
            let result = validate_outbound_url_sync("https://api.openai.com/v1/chat/completions");
            assert!(result.is_ok(), "same-origin with different path should pass");
        });
    }

    #[test]
    #[serial(outbound_policy)]
    fn validate_sync_allowlist_rejects_other_host() {
        let allowed = vec![Url::parse("https://api.openai.com").expect("openai URL should be valid")];
        with_policy(OutboundPolicy::Allowlist(allowed), || {
            let result = validate_outbound_url_sync("https://api.anthropic.com/");
            assert!(result.is_err(), "different host should be rejected");
        });
    }

    #[test]
    #[serial(outbound_policy)]
    fn validate_sync_allowlist_requires_exact_scheme_host_and_effective_port() {
        let allowed = vec![Url::parse("https://api.example.com").expect("allowlist URL")];
        with_policy(OutboundPolicy::Allowlist(allowed), || {
            assert!(validate_outbound_url_sync("https://api.example.com:443/v1").is_ok());
            for rejected in [
                "http://api.example.com/v1",
                "https://other.example.com/v1",
                "https://api.example.com:8443/v1",
            ] {
                assert!(
                    validate_outbound_url_sync(rejected).is_err(),
                    "allowlist must reject a different origin: {rejected}"
                );
            }
        });
    }

    #[test]
    #[serial(outbound_policy)]
    #[cfg(all(feature = "native-http", not(target_arch = "wasm32")))]
    fn redirect_validation_rejects_cross_origin_under_deny_private() {
        with_policy(OutboundPolicy::DenyPrivate, || {
            let previous = Url::parse("https://api.example.com/v1/chat").expect("previous URL");
            let next = Url::parse("https://cdn.example.net/v1/chat").expect("next URL");
            let result = validate_redirect(Some(&previous), &next, false);
            assert!(
                matches!(result, Err(LiterLlmError::OutboundForbidden { .. })),
                "active policies must reject cross-origin redirects that could leak custom auth headers"
            );
        });
    }

    #[test]
    #[serial(outbound_policy)]
    #[cfg(all(feature = "native-http", not(target_arch = "wasm32")))]
    fn redirect_validation_allows_same_origin_under_deny_private() {
        with_policy(OutboundPolicy::DenyPrivate, || {
            let previous = Url::parse("https://api.example.com/v1/chat").expect("previous URL");
            let next = Url::parse("https://api.example.com/v2/chat").expect("next URL");
            assert!(validate_redirect(Some(&previous), &next, false).is_ok());
        });
    }

    #[test]
    #[serial(outbound_policy)]
    #[cfg(all(feature = "native-http", not(target_arch = "wasm32")))]
    fn credential_free_redirect_still_rejects_private_target() {
        with_policy(OutboundPolicy::DenyPrivate, || {
            let previous = Url::parse("https://github.com/example/catalog.json").expect("previous URL");
            let next = Url::parse("http://169.254.169.254/catalog.json").expect("next URL");
            let result = validate_redirect(Some(&previous), &next, true);
            assert!(
                matches!(result, Err(LiterLlmError::OutboundForbidden { .. })),
                "credential-free redirects must still validate the target policy"
            );
        });
    }

    #[test]
    #[serial(outbound_policy)]
    #[cfg(all(feature = "native-http", not(target_arch = "wasm32")))]
    fn credential_free_redirect_rejects_https_to_http_downgrade_when_policy_is_off() {
        with_policy(OutboundPolicy::Off, || {
            let previous = Url::parse("https://github.com/example/catalog.json").expect("previous URL");
            let next = Url::parse("http://release-assets.example.com/catalog.json").expect("next URL");
            let result = validate_redirect(Some(&previous), &next, true);
            assert!(
                matches!(result, Err(LiterLlmError::OutboundForbidden { .. })),
                "catalog redirects must never downgrade transport security"
            );
        });
    }

    #[test]
    #[cfg(all(feature = "native-http", not(target_arch = "wasm32")))]
    fn guarded_resolver_rejects_private_connection_address() {
        let addresses = [SocketAddr::from(([127, 0, 0, 1], 443))];
        let result = resolver_impl::validate_addrs(OutboundPolicy::DenyPrivate, "api.example.com", &addresses);
        assert!(
            result.is_err(),
            "connection-time DNS results must reject private addresses"
        );
    }

    #[tokio::test]
    #[serial(outbound_policy)]
    #[cfg(all(feature = "native-http", not(target_arch = "wasm32")))]
    async fn configured_builder_rejects_private_hostname_resolution() {
        let target = OneShotServer::start(
            "HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: 2\r\n\r\n{}".to_string(),
        );
        let target_url = format!("http://localhost:{}/", target.address.port());
        set_outbound_policy(OutboundPolicy::DenyPrivate);
        let client = configure_outbound_client_builder(reqwest::Client::builder(), None)
            .build()
            .expect("guarded client");

        let result = client.get(&target_url).send().await;
        set_outbound_policy(OutboundPolicy::Off);

        let error = LiterLlmError::from(result.expect_err("guarded builder must reject localhost DNS"));
        assert!(
            matches!(error, LiterLlmError::OutboundForbidden { .. }),
            "resolver policy failures must preserve OutboundForbidden: {error:?}"
        );
        assert!(!target.finish(), "a DNS-blocked target must not receive a request");
    }

    #[tokio::test]
    #[serial(outbound_policy)]
    #[cfg(all(feature = "native-http", not(target_arch = "wasm32")))]
    async fn credential_free_client_allows_policy_checked_cross_origin_redirect() {
        let target = OneShotServer::start(
            "HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: 2\r\n\r\n{}".to_string(),
        );
        let target_url = format!("http://catalog-assets.test:{}/catalog.json", target.address.port());
        let source = OneShotServer::start(format!(
            "HTTP/1.1 302 Found\r\nLocation: {target_url}\r\nContent-Length: 0\r\n\r\n"
        ));
        let source_url = format!("http://catalog-origin.test:{}/catalog.json", source.address.port());
        set_outbound_policy(OutboundPolicy::Allowlist(vec![
            Url::parse(&source_url).expect("source allowlist URL"),
            Url::parse(&target_url).expect("target allowlist URL"),
        ]));
        let client = reqwest::Client::builder()
            .resolve("catalog-origin.test", source.address)
            .resolve("catalog-assets.test", target.address)
            .redirect(outbound_redirect_policy(true))
            .build()
            .expect("credential-free redirect client");

        let result = crate::http::request::get_json_raw(&client, &source_url, None, &[], 0).await;
        set_outbound_policy(OutboundPolicy::Off);

        assert_eq!(result.expect("allowlisted catalog redirect"), serde_json::json!({}));
        assert!(source.finish(), "catalog origin must receive the initial request");
        assert!(
            target.finish(),
            "catalog asset origin must receive the redirected request"
        );
    }

    #[tokio::test]
    #[serial(outbound_policy)]
    #[cfg(all(feature = "native-http", not(target_arch = "wasm32")))]
    async fn redirect_policy_failure_is_outbound_forbidden_and_not_retried() {
        let target = OneShotServer::start(
            "HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: 2\r\n\r\n{}".to_string(),
        );
        let target_url = format!("http://blocked.test:{}/done", target.address.port());
        let source = OneShotServer::start(format!(
            "HTTP/1.1 307 Temporary Redirect\r\nLocation: {target_url}\r\nContent-Length: 0\r\n\r\n"
        ));
        let source_url = format!("http://allowed.test:{}/start", source.address.port());
        set_outbound_policy(OutboundPolicy::Allowlist(vec![
            Url::parse(&source_url).expect("source allowlist URL"),
        ]));
        let client = reqwest::Client::builder()
            .resolve("allowed.test", source.address)
            .resolve("blocked.test", target.address)
            .redirect(outbound_redirect_policy(false))
            .build()
            .expect("redirect test client");
        let mut attempts = 0_u32;

        let result = crate::http::request::with_retry(&source_url, 3, || {
            attempts += 1;
            client
                .post(&source_url)
                .header("authorization", "Bearer secret-token")
                .header("x-api-key", "secret-api-key")
                .body("secret request body")
                .send()
        })
        .await;
        set_outbound_policy(OutboundPolicy::Off);

        assert!(
            matches!(result, Err(LiterLlmError::OutboundForbidden { .. })),
            "redirect policy errors must preserve their classification: {result:?}"
        );
        assert_eq!(attempts, 1, "policy failures are deterministic and must not be retried");
        assert!(
            source.finish(),
            "allowed source must receive exactly the initial request"
        );
        assert!(!target.finish(), "blocked redirect target must not receive a request");
    }

    #[tokio::test]
    #[serial(outbound_policy)]
    #[cfg(all(feature = "native-http", not(target_arch = "wasm32")))]
    async fn redirect_policy_rejects_allowed_to_unallowed_public_origin() {
        let target = OneShotServer::start(
            "HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: 2\r\n\r\n{}".to_string(),
        );
        let target_url = format!("http://unallowed.test:{}/done", target.address.port());
        let source = OneShotServer::start(format!(
            "HTTP/1.1 302 Found\r\nLocation: {target_url}\r\nContent-Length: 0\r\n\r\n"
        ));
        let source_url = format!("http://allowed.test:{}/start", source.address.port());
        set_outbound_policy(OutboundPolicy::Allowlist(vec![
            Url::parse(&source_url).expect("source allowlist URL"),
        ]));
        let client = reqwest::Client::builder()
            .resolve("allowed.test", source.address)
            .resolve("unallowed.test", target.address)
            .redirect(outbound_redirect_policy(false))
            .build()
            .expect("redirect test client");

        let result = crate::http::request::get_json_raw(&client, &source_url, None, &[], 0).await;
        set_outbound_policy(OutboundPolicy::Off);

        assert!(result.is_err(), "redirect outside the allowlist must fail");
        assert!(source.finish(), "allowed source must receive the initial request");
        assert!(!target.finish(), "unallowed redirect target must not receive a request");
    }

    #[tokio::test]
    #[serial(outbound_policy)]
    #[cfg(all(feature = "native-http", not(target_arch = "wasm32")))]
    async fn redirect_policy_rejects_allowed_to_private_origin() {
        let target = OneShotServer::start(
            "HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: 2\r\n\r\n{}".to_string(),
        );
        let target_url = format!("http://127.0.0.1:{}/done", target.address.port());
        let source = OneShotServer::start(format!(
            "HTTP/1.1 302 Found\r\nLocation: {target_url}\r\nContent-Length: 0\r\n\r\n"
        ));
        let source_url = format!("http://allowed.test:{}/start", source.address.port());
        set_outbound_policy(OutboundPolicy::Allowlist(vec![
            Url::parse(&source_url).expect("source allowlist URL"),
        ]));
        let client = reqwest::Client::builder()
            .resolve("allowed.test", source.address)
            .redirect(outbound_redirect_policy(false))
            .build()
            .expect("redirect test client");

        let result = crate::http::request::get_json_raw(&client, &source_url, None, &[], 0).await;
        set_outbound_policy(OutboundPolicy::Off);

        assert!(result.is_err(), "redirect into private address space must fail");
        assert!(source.finish(), "allowed source must receive the initial request");
        assert!(!target.finish(), "private redirect target must not receive a request");
    }

    #[tokio::test]
    #[serial(outbound_policy)]
    async fn validate_async_off_passes_everything() {
        set_outbound_policy(OutboundPolicy::Off);
        assert!(validate_outbound_url("http://127.0.0.1/").await.is_ok());
        assert!(validate_outbound_url("http://169.254.169.254/").await.is_ok());
    }

    #[tokio::test]
    #[serial(outbound_policy)]
    async fn validate_async_deny_private_rejects_loopback() {
        set_outbound_policy(OutboundPolicy::DenyPrivate);
        let result = validate_outbound_url("http://127.0.0.1/").await;
        set_outbound_policy(OutboundPolicy::Off);
        assert!(result.is_err(), "loopback should be rejected by DenyPrivate");
    }

    #[tokio::test]
    #[serial(outbound_policy)]
    async fn validate_async_deny_private_rejects_metadata_ip() {
        set_outbound_policy(OutboundPolicy::DenyPrivate);
        let result = validate_outbound_url("http://169.254.169.254/").await;
        set_outbound_policy(OutboundPolicy::Off);
        assert!(result.is_err(), "AWS metadata IP should be rejected");
    }

    #[tokio::test]
    #[serial(outbound_policy)]
    async fn validate_async_deny_private_rejects_ula() {
        set_outbound_policy(OutboundPolicy::DenyPrivate);
        let result = validate_outbound_url("http://[fc00::1]/").await;
        set_outbound_policy(OutboundPolicy::Off);
        assert!(result.is_err(), "ULA address should be rejected");
    }

    #[tokio::test]
    #[serial(outbound_policy)]
    async fn validate_async_deny_private_rejects_link_local_v6() {
        set_outbound_policy(OutboundPolicy::DenyPrivate);
        let result = validate_outbound_url("http://[fe80::1]/").await;
        set_outbound_policy(OutboundPolicy::Off);
        assert!(result.is_err(), "IPv6 link-local should be rejected");
    }

    #[tokio::test]
    #[serial(outbound_policy)]
    async fn validate_async_deny_private_rejects_unknown_scheme() {
        set_outbound_policy(OutboundPolicy::DenyPrivate);
        let result = validate_outbound_url("ftp://example.com/").await;
        set_outbound_policy(OutboundPolicy::Off);
        assert!(result.is_err(), "ftp:// scheme should be rejected");
    }

    #[tokio::test]
    #[serial(outbound_policy)]
    async fn validate_async_allowlist_accepts_exact_origin() {
        let allowed = vec![Url::parse("https://api.openai.com").expect("openai URL should be valid")];
        set_outbound_policy(OutboundPolicy::Allowlist(allowed));
        let result = validate_outbound_url("https://api.openai.com/v1/chat/completions").await;
        set_outbound_policy(OutboundPolicy::Off);
        assert!(result.is_ok(), "same-origin with different path should pass");
    }

    #[tokio::test]
    #[serial(outbound_policy)]
    async fn validate_async_allowlist_rejects_other_host() {
        let allowed = vec![Url::parse("https://api.openai.com").expect("openai URL should be valid")];
        set_outbound_policy(OutboundPolicy::Allowlist(allowed));
        let result = validate_outbound_url("https://api.anthropic.com/").await;
        set_outbound_policy(OutboundPolicy::Off);
        assert!(result.is_err(), "different host should be rejected");
    }
}