openlatch-client 0.3.3

OpenLatch runtime enforcement node — the capture-and-enforce adapter that evaluates every covered action against a coding agent's Autonomy Zone before it runs
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
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
//! The resolved egress configuration: what proxy to use, how to authenticate to it,
//! what to trust, and what to bypass.
//!
//! Every value here comes from the PRD's frozen `[proxy]` contract. The enums mirror the
//! wire strings exactly, so `serde` round-trips a `config.toml` block without a translation
//! layer.
//!
//! **Precedence is per key, not per block** (D-6). A `OPENLATCH_PROXY` in the environment
//! overrides a `mode = "direct"` in the file, and each key resolves independently down the
//! tiers. This module implements tiers 2 through 4:
//!
//! | Tier | Source | Owner |
//! |------|--------|-------|
//! | 1 | CLI flags | I-2 |
//! | 2 | `OPENLATCH_*` environment | here |
//! | 3 | `[proxy]` in `config.toml` | here |
//! | 4 | standard `https_proxy` / `HTTP_PROXY` / … | here |
//! | 5 | OS discovery | I-2 |
//! | 6 | direct | here (unless `allow_direct = false`) |
//!
//! A *parse* error fails startup; a *network* state never does (D-9). Everything in this
//! file is the former: if the input is malformed, that is a bug in the input, and the
//! daemon says so loudly at boot rather than silently going direct.

use std::path::PathBuf;

use crate::core::error::{OlError, ERR_PROXY_CONFIG_INVALID};

use super::no_proxy::NoProxyMatcher;

/// How the proxy route is chosen. Mirrors `proxy.mode` in the frozen contract.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, serde::Deserialize, serde::Serialize)]
#[serde(rename_all = "lowercase")]
pub enum ProxyMode {
    /// Walk the resolver ladder: settings, then environment, then OS discovery.
    #[default]
    Auto,
    /// Use exactly what is configured; never discover, and never let self-heal
    /// overwrite it (D-7, D-18).
    Manual,
    /// Never use a proxy.
    Direct,
}

/// Which authentication scheme to present to the proxy. Mirrors `proxy.auth`.
///
/// NTLM is deliberately absent: Microsoft deprecated it in 2024, and `Negotiate` verifies
/// that Kerberos — not NTLM — was actually selected before it will use the tunnel.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, serde::Deserialize, serde::Serialize)]
#[serde(rename_all = "lowercase")]
pub enum ProxyAuth {
    /// Respond to whatever scheme the proxy offers.
    #[default]
    Auto,
    /// Send no credentials.
    None,
    /// Preemptive HTTP Basic.
    Basic,
    /// Kerberos/SPNEGO. Requires the `proxy-negotiate` cargo feature.
    Negotiate,
}

/// Where the active route came from. Mirrors `proxy.source`.
///
/// This is provenance, not preference: it rides the *winning candidate* rather than being
/// resolved per key, and every protection gate keys on `Manual` specifically.
#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Deserialize, serde::Serialize)]
#[serde(rename_all = "lowercase")]
pub enum ProxySource {
    /// A human set it, via `proxy set` or the `init` prompt. Never overwritten by
    /// discovery or self-heal.
    Manual,
    /// Read from the ambient environment.
    Env,
    /// Windows WinINET/WinHTTP settings.
    Windows,
    /// macOS system network settings.
    Macos,
    /// GNOME `gsettings`.
    Gnome,
    /// An explicit PAC URL. The *source* is persisted, never the result it returned.
    Pac,
    /// PAC discovered by WPAD, through the OS only.
    Wpad,
}

impl ProxySource {
    /// The wire string for diagnostics, telemetry and the status endpoint.
    ///
    /// Mirrors the `serde` rename above; kept as a plain accessor so a caller
    /// that only wants the word does not have to round-trip through JSON.
    pub fn as_str(self) -> &'static str {
        match self {
            Self::Manual => "manual",
            Self::Env => "env",
            Self::Windows => "windows",
            Self::Macos => "macos",
            Self::Gnome => "gnome",
            Self::Pac => "pac",
            Self::Wpad => "wpad",
        }
    }
}

/// A resolution detail worth reporting but not worth failing over.
///
/// These are data, not diagnostics: `doctor` renders them (I-3), and carrying them on the
/// config keeps this module free of any opinion about presentation.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum EgressWarning {
    /// `https_proxy` and `HTTPS_PROXY` (or another pair) disagree. Lowercase wins, and the
    /// operator is told, because the pair disagreeing at all is usually an accident.
    ///
    /// Unix only: Windows environment lookups are case-insensitive, so the pair cannot
    /// disagree there.
    EnvCaseMismatch {
        /// The lowercase variable name, which is the one that won.
        lower: String,
        /// The uppercase variable name, which was ignored.
        upper: String,
    },
    /// A `no_proxy` entry could not be parsed. It is reported rather than dropped, because
    /// an entry the operator believes is bypassing traffic and that silently is not is the
    /// worst of the available outcomes.
    UnsupportedNoProxyEntry(String),
}

impl std::fmt::Display for EgressWarning {
    /// The operator-facing sentence. Lives here, beside the variants, so
    /// `doctor` and `/admin/egress/status` cannot render the same warning two
    /// different ways.
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::EnvCaseMismatch { lower, upper } => {
                write!(f, "{lower} and {upper} disagree; {lower} wins")
            }
            Self::UnsupportedNoProxyEntry(entry) => write!(
                f,
                "no_proxy entry \"{entry}\" could not be parsed and bypasses nothing"
            ),
        }
    }
}

/// The `[proxy]` block as it appears in `config.toml`, all fields optional.
///
/// Deliberately ungated and free of any `egress` type: `core::config` compiles in builds
/// where `core::egress` does not exist, so the mirror struct has to survive on its own.
#[derive(Debug, Default, Clone, serde::Deserialize)]
pub struct ProxyToml {
    /// See [`ProxyMode`].
    pub mode: Option<String>,
    /// Proxy URL. Never carries userinfo — see [`EgressConfig::resolve`].
    pub url: Option<String>,
    /// Username; the password lives in the credential store.
    pub username: Option<String>,
    /// See [`ProxyAuth`].
    pub auth: Option<String>,
    /// Additive bypass list, Go grammar.
    pub no_proxy: Option<String>,
    /// Explicit PAC URL. Refused on Linux (D-20).
    pub pac_url: Option<String>,
    /// PEM bundle merged on top of the OS roots.
    pub ca_bundle: Option<String>,
    /// `false` means the ladder never ends at DIRECT (D-21).
    pub allow_direct: Option<bool>,
    /// See [`ProxySource`].
    pub source: Option<String>,
    /// Kerberos SPN override.
    pub spn: Option<String>,
    /// Force HTTP/1.1 for HTTP/2-hostile inspection proxies.
    pub http1_only: Option<bool>,
}

/// The keys `[proxy]` accepts, for the unknown-key checker in `core::config`.
pub const PROXY_TOML_KEYS: &[&str] = &[
    "mode",
    "url",
    "username",
    "auth",
    "no_proxy",
    "pac_url",
    "ca_bundle",
    "allow_direct",
    "source",
    "spn",
    "http1_only",
];

/// Reads environment variables. A trait so tests can supply an environment without mutating
/// the process — `std::env::set_var` races every other thread in the binary.
pub trait EnvSource {
    /// Return the value of `key`, if set and non-empty.
    fn var(&self, key: &str) -> Option<String>;
}

/// The real process environment.
pub struct ProcessEnv;

impl EnvSource for ProcessEnv {
    fn var(&self, key: &str) -> Option<String> {
        std::env::var(key).ok().filter(|v| !v.is_empty())
    }
}

/// The fully resolved egress configuration a client is built from.
///
/// `Debug` is hand-written rather than derived, and that is load-bearing: this struct holds
/// proxy passwords, and a derived `Debug` would print them into any `tracing` field, any
/// `anyhow` context, and any test failure message that formats a config. The masking
/// invariant is only real if it holds on the *default* rendering.
#[derive(Clone)]
pub struct EgressConfig {
    /// See [`ProxyMode`].
    pub mode: ProxyMode,
    /// The active proxy URL, with userinfo stripped. Empty for PAC-sourced routes, which
    /// are re-evaluated per destination rather than materialized.
    pub url: Option<String>,
    /// Username for Basic, if one was configured.
    pub username: Option<String>,
    /// A password that arrived via `OPENLATCH_PROXY` userinfo. Held in memory only and
    /// never written to `config.toml` (D-19).
    pub env_password: Option<String>,
    /// The password the credential ladder resolved for this proxy authority — env, then
    /// keychain, then `proxy-credentials.enc`.
    ///
    /// Filled by `egress::resolve_auth` before any client is built, never at parse time: a
    /// keychain read is blocking I/O and can raise a macOS authorization dialog, and neither
    /// belongs in a config parser. `None` means the ladder found nothing, which is a
    /// perfectly ordinary state and never an error here.
    pub resolved_password: Option<String>,
    /// See [`ProxyAuth`].
    pub auth: ProxyAuth,
    /// Merged bypass matcher: the non-removable loopback entries, then the operator's.
    pub no_proxy: NoProxyMatcher,
    /// Parsed but inert in I-1 — the resolver that evaluates it is I-2's.
    pub pac_url: Option<String>,
    /// A PEM bundle merged on top of the OS trust store.
    pub ca_bundle: Option<PathBuf>,
    /// `false` refuses to fall through to a direct connection.
    pub allow_direct: bool,
    /// See [`ProxySource`].
    pub source: Option<ProxySource>,
    /// Kerberos SPN override.
    pub spn: Option<String>,
    /// Force HTTP/1.1.
    pub http1_only: bool,
    /// Resolution details worth surfacing; see [`EgressWarning`].
    pub warnings: Vec<EgressWarning>,
    /// What `egress::resolve_auth` concluded, once, before any client was built.
    ///
    /// `None` means it has not run — a unit test, a library consumer, or a code path that
    /// builds a client before start-up finishes. `build_client` works either way; what it
    /// loses is the resolved password and the concretized `auth`.
    pub resolved: Option<super::resolve::ResolvedAuth>,
}

/// Every field except the two passwords, which render as a fixed placeholder.
///
/// The placeholder is deliberately not the value's length or a hash — either one is a fact
/// about the secret, and a Debug line is the least controlled surface in the product.
impl std::fmt::Debug for EgressConfig {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        /// Renders as `Some(<redacted>)` / `None` without ever touching the value.
        struct Redacted<'a>(&'a Option<String>);
        impl std::fmt::Debug for Redacted<'_> {
            fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
                match self.0 {
                    Some(_) => f.write_str("Some(<redacted>)"),
                    None => f.write_str("None"),
                }
            }
        }

        f.debug_struct("EgressConfig")
            .field("mode", &self.mode)
            .field("url", &self.masked_url())
            .field("username", &self.username)
            .field("env_password", &Redacted(&self.env_password))
            .field("resolved_password", &Redacted(&self.resolved_password))
            .field("auth", &self.auth)
            .field("no_proxy", &self.no_proxy)
            .field("pac_url", &self.pac_url)
            .field("ca_bundle", &self.ca_bundle)
            .field("allow_direct", &self.allow_direct)
            .field("source", &self.source)
            .field("spn", &self.spn)
            .field("http1_only", &self.http1_only)
            .field("warnings", &self.warnings)
            .field("resolved", &self.resolved)
            .finish()
    }
}

impl Default for EgressConfig {
    fn default() -> Self {
        Self::direct()
    }
}

impl EgressConfig {
    /// A configuration that never uses a proxy and reads nothing.
    ///
    /// This is what hermetic tests and the boundary's default client are built from: no
    /// file, no environment, no surprises.
    pub fn direct() -> Self {
        Self {
            mode: ProxyMode::Direct,
            url: None,
            username: None,
            env_password: None,
            resolved_password: None,
            auth: ProxyAuth::None,
            no_proxy: NoProxyMatcher::new("").0,
            pac_url: None,
            ca_bundle: None,
            allow_direct: true,
            source: None,
            spn: None,
            http1_only: false,
            warnings: Vec::new(),
            resolved: None,
        }
    }

    /// True when a proxy route is actually configured.
    pub fn has_proxy(&self) -> bool {
        self.mode != ProxyMode::Direct && self.url.is_some()
    }

    /// The password to present to the proxy, resolved tier beating env tier.
    ///
    /// One accessor rather than two fields consulted at each call site: the credential
    /// ladder already put env first, so a resolved value either *is* the env value or beat
    /// it. The env field remains as the pre-resolution fallback, which is what a client
    /// built before `resolve_auth` ran — a unit test, a library consumer — sees.
    pub fn proxy_password(&self) -> Option<&str> {
        self.resolved_password
            .as_deref()
            .or(self.env_password.as_deref())
    }

    /// The proxy URL as it may be rendered: userinfo masked, never the raw string.
    ///
    /// `url` is stored already stripped, so this is belt-and-braces — and it is the helper
    /// every log line and diagnostic reaches for, so the one day a URL arrives with
    /// userinfo attached, nothing has to change.
    pub fn masked_url(&self) -> Option<String> {
        self.url.as_deref().map(super::credentials::mask_userinfo)
    }

    /// The credential key for the configured proxy authority, if there is one.
    pub fn proxy_authority(&self) -> Option<String> {
        self.url
            .as_deref()
            .and_then(super::credentials::authority_key)
    }

    /// This configuration, re-pointed at a discovered candidate.
    ///
    /// Everything the operator set stays: the bypass list, the trust bundle, the auth
    /// scheme, `allow_direct`, `http1_only`. Only the route and its provenance move —
    /// which is exactly the scope a self-heal pass is allowed to change (D-18).
    ///
    /// `mode` is forced to [`ProxyMode::Auto`] because a candidate *is* the result of
    /// discovery; a `Direct` base would otherwise keep every built client unproxied while
    /// the snapshot claimed a route. A `Manual` base never reaches here — self-heal
    /// declines on `source == manual` before a candidate is ever asked for (D-7).
    pub fn with_candidate(&self, candidate: &super::ProxyCandidate) -> Self {
        Self {
            mode: ProxyMode::Auto,
            url: Some(candidate.url.clone()),
            source: Some(candidate.source),
            ..self.clone()
        }
    }

    /// Resolve tiers 2 through 4 into one configuration.
    ///
    /// `daemon_port` and `boundary_port` are passed in rather than re-derived: they are
    /// final only after the whole `Config` has merged, and a guard that re-derives them
    /// would be guarding a different number than the one the listeners actually bind.
    pub fn resolve(
        toml: Option<&ProxyToml>,
        env: &dyn EnvSource,
        daemon_port: u16,
        boundary_port: u16,
    ) -> Result<Self, OlError> {
        let mut warnings = Vec::new();

        // Tier 2 beats tier 3 beats tier 4, per key.
        let mode = pick(
            env.var("OPENLATCH_PROXY_MODE"),
            toml.and_then(|t| t.mode.clone()),
        );
        let mode = match mode.as_deref() {
            None => ProxyMode::Auto,
            Some("auto") => ProxyMode::Auto,
            Some("manual") => ProxyMode::Manual,
            Some("direct") => ProxyMode::Direct,
            Some(other) => return Err(invalid("mode", other, "auto, manual or direct")),
        };

        let auth = pick(
            env.var("OPENLATCH_PROXY_AUTH"),
            toml.and_then(|t| t.auth.clone()),
        );
        let auth = match auth.as_deref() {
            None => ProxyAuth::Auto,
            Some("auto") => ProxyAuth::Auto,
            Some("none") => ProxyAuth::None,
            Some("basic") => ProxyAuth::Basic,
            Some("negotiate") => ProxyAuth::Negotiate,
            Some(other) => {
                return Err(invalid(
                    "auth",
                    other,
                    "auto, none, basic or negotiate (NTLM is not supported)",
                ))
            }
        };

        let source = match toml.and_then(|t| t.source.clone()).as_deref() {
            None => None,
            Some("manual") => Some(ProxySource::Manual),
            Some("env") => Some(ProxySource::Env),
            Some("windows") => Some(ProxySource::Windows),
            Some("macos") => Some(ProxySource::Macos),
            Some("gnome") => Some(ProxySource::Gnome),
            Some("pac") => Some(ProxySource::Pac),
            Some("wpad") => Some(ProxySource::Wpad),
            Some(other) => {
                return Err(invalid(
                    "source",
                    other,
                    "manual, env, windows, macos, gnome, pac or wpad",
                ))
            }
        };

        let allow_direct = toml.and_then(|t| t.allow_direct).unwrap_or(true);

        // The contract contradiction: asking never to go direct while configuring nothing
        // but direct. Rejecting it at parse time is kinder than a daemon that starts and
        // then refuses every request.
        if mode == ProxyMode::Direct && !allow_direct {
            return Err(OlError::new(
                ERR_PROXY_CONFIG_INVALID,
                "[proxy] mode = \"direct\" contradicts allow_direct = false",
            )
            .with_suggestion(
                "Set a proxy url and mode = \"manual\", or set allow_direct = true.",
            ));
        }

        // Tier 2 URL. Userinfo is accepted HERE and only here: the environment is a
        // private, per-process channel, unlike argv (world-readable) and config.toml
        // (persisted). The password is lifted into memory and the URL cleaned.
        let (env_url, env_password) = match env.var("OPENLATCH_PROXY") {
            Some(raw) => {
                let (clean, user, pass) = split_userinfo(&raw)?;
                (Some((clean, user)), pass)
            }
            None => (None, None),
        };

        // Tier 3 URL. Userinfo here is a hand-edited file, and is refused: a password in
        // config.toml is a password on disk in plaintext.
        let toml_url = match toml.and_then(|t| t.url.clone()).filter(|u| !u.is_empty()) {
            Some(raw) => {
                if has_userinfo(&raw) {
                    return Err(OlError::new(
                        ERR_PROXY_CONFIG_INVALID,
                        "[proxy] url must not contain a username or password",
                    )
                    .with_suggestion(
                        "Credentials belong in OPENLATCH_PROXY or the init prompt, which \
                         store them in the OS credential store. config.toml is plaintext \
                         on disk.",
                    ));
                }
                Some(raw)
            }
            None => None,
        };

        // Tier 4: the ambient variables, lowercase first. Claude Code, curl and Go all
        // read lowercase first; reqwest and hyper-util provide no precedence at all.
        let (ambient_url, ambient_warning) = ambient_proxy(env);
        if let Some(w) = ambient_warning {
            warnings.push(w);
        }

        let (url, username) = match (env_url, toml_url, ambient_url) {
            (Some((u, user)), _, _) => (
                Some(u),
                user.or_else(|| toml.and_then(|t| t.username.clone())),
            ),
            (None, Some(u), _) => (Some(u), toml.and_then(|t| t.username.clone())),
            (None, None, Some(u)) => (Some(u), None),
            (None, None, None) => (None, toml.and_then(|t| t.username.clone())),
        };

        let url = match url.filter(|u| !u.is_empty()) {
            Some(raw) => Some(validate_url(&raw, daemon_port, boundary_port)?),
            None => None,
        };

        let no_proxy_raw = pick(
            env.var("OPENLATCH_NO_PROXY"),
            toml.and_then(|t| t.no_proxy.clone()),
        )
        .or_else(|| ambient_no_proxy(env))
        .unwrap_or_default();

        let (no_proxy, unsupported) = NoProxyMatcher::new(&no_proxy_raw);
        warnings.extend(
            unsupported
                .into_iter()
                .map(EgressWarning::UnsupportedNoProxyEntry),
        );

        // A bypass list under allow_direct = false would silently defeat the policy: the
        // point of the flag is that traffic never leaves unproxied, and `no_proxy` is
        // exactly a list of traffic that leaves unproxied.
        if !allow_direct && no_proxy.has_non_loopback_entry() {
            return Err(OlError::new(
                ERR_PROXY_CONFIG_INVALID,
                "[proxy] no_proxy has a non-loopback entry while allow_direct = false",
            )
            .with_suggestion(
                "allow_direct = false means no traffic may bypass the proxy. Remove the \
                 no_proxy entries, or set allow_direct = true. Loopback always bypasses \
                 and needs no entry.",
            ));
        }

        let ca_bundle = match pick(
            env.var("OPENLATCH_CA_BUNDLE"),
            toml.and_then(|t| t.ca_bundle.clone()),
        )
        .filter(|p| !p.is_empty())
        {
            Some(p) => Some(validate_ca_bundle(&p)?),
            None => None,
        };

        Ok(Self {
            mode,
            url,
            username,
            env_password,
            // Filled later by `resolve_auth`: the parser does no I/O.
            resolved_password: None,
            auth,
            no_proxy,
            pac_url: pick(
                env.var("OPENLATCH_PROXY_PAC_URL"),
                toml.and_then(|t| t.pac_url.clone()),
            )
            .filter(|p| !p.is_empty()),
            ca_bundle,
            allow_direct,
            source,
            spn: pick(
                env.var("OPENLATCH_PROXY_SPN"),
                toml.and_then(|t| t.spn.clone()),
            )
            .filter(|s| !s.is_empty()),
            http1_only: toml.and_then(|t| t.http1_only).unwrap_or(false),
            warnings,
            // Filled by `resolve_auth`, which runs once per process before any client is
            // built. The parser does no network and no keychain I/O.
            resolved: None,
        })
    }
}

/// Tier 2 wins over tier 3 for a single key.
fn pick(tier2: Option<String>, tier3: Option<String>) -> Option<String> {
    tier2.filter(|v| !v.is_empty()).or(tier3)
}

fn invalid(key: &str, got: &str, expected: &str) -> OlError {
    OlError::new(
        ERR_PROXY_CONFIG_INVALID,
        format!("[proxy] {key} = \"{got}\" is not a valid value"),
    )
    .with_suggestion(format!("Expected one of: {expected}."))
}

fn has_userinfo(url: &str) -> bool {
    match url.split_once("://") {
        Some((_, rest)) => rest.split('/').next().is_some_and(|a| a.contains('@')),
        None => false,
    }
}

/// Split `scheme://user:pass@host:port` into the clean URL, the user, and the password.
fn split_userinfo(url: &str) -> Result<(String, Option<String>, Option<String>), OlError> {
    let Some((scheme, rest)) = url.split_once("://") else {
        return Err(invalid_url(url, "no scheme"));
    };
    let (authority, path) = match rest.split_once('/') {
        Some((a, p)) => (a, Some(p)),
        None => (rest, None),
    };
    let Some((userinfo, host)) = authority.rsplit_once('@') else {
        return Ok((url.to_string(), None, None));
    };
    let (user, pass) = match userinfo.split_once(':') {
        Some((u, p)) => (u.to_string(), Some(percent_decode(p))),
        None => (userinfo.to_string(), None),
    };
    let clean = match path {
        Some(p) => format!("{scheme}://{host}/{p}"),
        None => format!("{scheme}://{host}"),
    };
    Ok((clean, Some(percent_decode(&user)), pass))
}

/// Minimal percent-decoding for userinfo, which is where `@` and `:` in a password have to
/// be escaped to survive the URL at all.
fn percent_decode(s: &str) -> String {
    let bytes = s.as_bytes();
    let mut out = Vec::with_capacity(bytes.len());
    let mut i = 0;
    while i < bytes.len() {
        if bytes[i] == b'%' && i + 2 < bytes.len() {
            let hi = (bytes[i + 1] as char).to_digit(16);
            let lo = (bytes[i + 2] as char).to_digit(16);
            if let (Some(hi), Some(lo)) = (hi, lo) {
                out.push((hi * 16 + lo) as u8);
                i += 3;
                continue;
            }
        }
        out.push(bytes[i]);
        i += 1;
    }
    String::from_utf8_lossy(&out).into_owned()
}

/// A malformed proxy URL, rendered with any userinfo masked.
///
/// The masking is not decorative. `split_userinfo` reports "no scheme" against the *raw*
/// value it was handed, and the raw value of `OPENLATCH_PROXY` is exactly where a password
/// legitimately lives -- so an unmasked message here would print the proxy password into
/// the daemon log the first time someone typed the variable without a scheme.
fn invalid_url(url: &str, why: &str) -> OlError {
    let url = super::credentials::mask_userinfo(url);
    OlError::new(
        ERR_PROXY_CONFIG_INVALID,
        format!("proxy url \"{url}\" is not usable: {why}"),
    )
    .with_suggestion(
        "Use http://host:port, https://host:port, socks5://host:port or \
         socks5h://host:port.",
    )
}

/// Check the scheme, the shape, and that we are not being told to proxy through ourselves.
fn validate_url(raw: &str, daemon_port: u16, boundary_port: u16) -> Result<String, OlError> {
    let Some((scheme, rest)) = raw.split_once("://") else {
        return Err(invalid_url(raw, "no scheme"));
    };
    if !matches!(scheme, "http" | "https" | "socks5" | "socks5h") {
        return Err(invalid_url(
            raw,
            &format!("unsupported scheme \"{scheme}\""),
        ));
    }
    let authority = rest.split('/').next().unwrap_or(rest);
    if authority.is_empty() {
        return Err(invalid_url(raw, "no host"));
    }

    // Our own listeners are the one loopback pair that must never be a proxy: forwarding
    // to ourselves is an infinite loop dressed as a configuration. Any OTHER loopback port
    // stays legal, because the test fixtures are loopback proxies.
    let (host, port) = split_host_port(authority);
    let is_loopback = matches!(host, "127.0.0.1" | "localhost" | "::1" | "[::1]");
    if is_loopback && port.is_some_and(|p| p == daemon_port || p == boundary_port) {
        return Err(OlError::new(
            ERR_PROXY_CONFIG_INVALID,
            format!(
                "proxy url \"{}\" points at this client's own listener",
                super::credentials::mask_userinfo(raw)
            ),
        )
        .with_suggestion(
            "The daemon and boundary ports cannot also be the proxy — that would forward \
             traffic to ourselves. Point [proxy] url at the corporate proxy instead.",
        ));
    }
    Ok(raw.to_string())
}

fn split_host_port(authority: &str) -> (&str, Option<u16>) {
    if let Some(rest) = authority.strip_prefix('[') {
        // IPv6 literal: [::1]:8080
        if let Some((host, tail)) = rest.split_once(']') {
            let port = tail.strip_prefix(':').and_then(|p| p.parse().ok());
            return (host, port);
        }
    }
    match authority.rsplit_once(':') {
        Some((h, p)) => (h, p.parse().ok()),
        None => (authority, None),
    }
}

/// The bundle has to exist and parse now, not at the first request: a missing or malformed
/// PEM is a bug in the input, and D-9 says those fail startup.
fn validate_ca_bundle(path: &str) -> Result<PathBuf, OlError> {
    let p = PathBuf::from(path);
    let bytes = std::fs::read(&p).map_err(|e| {
        OlError::new(
            ERR_PROXY_CONFIG_INVALID,
            format!("[proxy] ca_bundle \"{path}\" cannot be read: {e}"),
        )
        .with_suggestion("Point ca_bundle at a readable PEM file, or remove the key.")
    })?;
    let text = String::from_utf8_lossy(&bytes);
    if !text.contains("-----BEGIN CERTIFICATE-----") {
        return Err(OlError::new(
            ERR_PROXY_CONFIG_INVALID,
            format!("[proxy] ca_bundle \"{path}\" contains no PEM certificate"),
        )
        .with_suggestion(
            "The file must be PEM, not DER. Convert with: \
             openssl x509 -inform der -in cert.der -out cert.pem",
        ));
    }
    Ok(p)
}

/// Read the ambient proxy variables, lowercase first.
///
/// Returns the winning value and, on Unix, a warning when the pair disagrees. Windows
/// environment lookups are case-insensitive, so the pair cannot disagree there and the
/// check would report a difference that does not exist.
fn ambient_proxy(env: &dyn EnvSource) -> (Option<String>, Option<EgressWarning>) {
    for (lower, upper) in [
        ("https_proxy", "HTTPS_PROXY"),
        ("http_proxy", "HTTP_PROXY"),
        ("all_proxy", "ALL_PROXY"),
    ] {
        let lo = env.var(lower);
        let up = env.var(upper);
        match (lo, up) {
            (Some(l), Some(u)) => {
                let warning = if cfg!(unix) && l != u {
                    Some(EgressWarning::EnvCaseMismatch {
                        lower: lower.to_string(),
                        upper: upper.to_string(),
                    })
                } else {
                    None
                };
                return (Some(l), warning);
            }
            (Some(l), None) => return (Some(l), None),
            (None, Some(u)) => return (Some(u), None),
            (None, None) => continue,
        }
    }
    (None, None)
}

fn ambient_no_proxy(env: &dyn EnvSource) -> Option<String> {
    env.var("no_proxy").or_else(|| env.var("NO_PROXY"))
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::collections::HashMap;

    #[derive(Default)]
    struct MapEnv(HashMap<String, String>);

    impl MapEnv {
        fn with(pairs: &[(&str, &str)]) -> Self {
            Self(
                pairs
                    .iter()
                    .map(|(k, v)| ((*k).to_string(), (*v).to_string()))
                    .collect(),
            )
        }
    }

    impl EnvSource for MapEnv {
        fn var(&self, key: &str) -> Option<String> {
            self.0.get(key).cloned().filter(|v| !v.is_empty())
        }
    }

    fn resolve(toml: Option<&ProxyToml>, env: &dyn EnvSource) -> Result<EgressConfig, OlError> {
        EgressConfig::resolve(toml, env, 7443, 7444)
    }

    #[test]
    fn nothing_configured_is_direct_with_no_proxy() {
        let cfg = resolve(None, &MapEnv::default()).expect("resolve");
        assert!(cfg.url.is_none());
        assert!(cfg.allow_direct);
        assert_eq!(cfg.mode, ProxyMode::Auto);
    }

    #[test]
    fn openlatch_env_beats_config_per_key() {
        // Tier 2 supplies only the url; mode must still come from tier 3.
        let toml = ProxyToml {
            mode: Some("manual".into()),
            url: Some("http://from-config:3128".into()),
            ..Default::default()
        };
        let env = MapEnv::with(&[("OPENLATCH_PROXY", "http://from-env:8080")]);
        let cfg = resolve(Some(&toml), &env).expect("resolve");
        assert_eq!(cfg.url.as_deref(), Some("http://from-env:8080"));
        assert_eq!(cfg.mode, ProxyMode::Manual);
    }

    #[test]
    fn config_beats_ambient_env() {
        let toml = ProxyToml {
            url: Some("http://from-config:3128".into()),
            ..Default::default()
        };
        let env = MapEnv::with(&[("https_proxy", "http://ambient:8080")]);
        let cfg = resolve(Some(&toml), &env).expect("resolve");
        assert_eq!(cfg.url.as_deref(), Some("http://from-config:3128"));
    }

    #[test]
    fn ambient_lowercase_wins_over_uppercase() {
        let env = MapEnv::with(&[
            ("https_proxy", "http://lower:8080"),
            ("HTTPS_PROXY", "http://upper:8080"),
        ]);
        let cfg = resolve(None, &env).expect("resolve");
        assert_eq!(cfg.url.as_deref(), Some("http://lower:8080"));
        if cfg!(unix) {
            assert!(cfg.warnings.iter().any(|w| matches!(
                w,
                EgressWarning::EnvCaseMismatch { lower, .. } if lower == "https_proxy"
            )));
        }
    }

    #[test]
    fn agreeing_case_pair_produces_no_warning() {
        let env = MapEnv::with(&[
            ("https_proxy", "http://same:8080"),
            ("HTTPS_PROXY", "http://same:8080"),
        ]);
        let cfg = resolve(None, &env).expect("resolve");
        assert!(cfg.warnings.is_empty());
    }

    #[test]
    fn env_userinfo_is_lifted_out_of_the_url() {
        let env = MapEnv::with(&[("OPENLATCH_PROXY", "http://alice:s3cr3t@proxy:8080")]);
        let cfg = resolve(None, &env).expect("resolve");
        assert_eq!(cfg.url.as_deref(), Some("http://proxy:8080"));
        assert_eq!(cfg.username.as_deref(), Some("alice"));
        assert_eq!(cfg.env_password.as_deref(), Some("s3cr3t"));
    }

    #[test]
    fn env_userinfo_is_percent_decoded() {
        let env = MapEnv::with(&[("OPENLATCH_PROXY", "http://dom%5Calice:p%40ss@proxy:8080")]);
        let cfg = resolve(None, &env).expect("resolve");
        assert_eq!(cfg.username.as_deref(), Some("dom\\alice"));
        assert_eq!(cfg.env_password.as_deref(), Some("p@ss"));
    }

    #[test]
    fn config_userinfo_is_rejected() {
        let toml = ProxyToml {
            url: Some("http://alice:s3cr3t@proxy:8080".into()),
            ..Default::default()
        };
        let err = resolve(Some(&toml), &MapEnv::default()).expect_err("must reject");
        assert_eq!(err.code, ERR_PROXY_CONFIG_INVALID);
        assert!(err
            .suggestion
            .unwrap_or_default()
            .contains("OPENLATCH_PROXY"));
    }

    #[test]
    fn unsupported_scheme_is_rejected() {
        let toml = ProxyToml {
            url: Some("ftp://proxy:21".into()),
            ..Default::default()
        };
        let err = resolve(Some(&toml), &MapEnv::default()).expect_err("must reject");
        assert_eq!(err.code, ERR_PROXY_CONFIG_INVALID);
    }

    #[test]
    fn direct_mode_with_allow_direct_false_is_a_contradiction() {
        let toml = ProxyToml {
            mode: Some("direct".into()),
            allow_direct: Some(false),
            ..Default::default()
        };
        let err = resolve(Some(&toml), &MapEnv::default()).expect_err("must reject");
        assert_eq!(err.code, ERR_PROXY_CONFIG_INVALID);
    }

    #[test]
    fn our_own_listener_cannot_be_the_proxy() {
        for port in [7443u16, 7444] {
            let toml = ProxyToml {
                url: Some(format!("http://127.0.0.1:{port}")),
                ..Default::default()
            };
            let err = resolve(Some(&toml), &MapEnv::default()).expect_err("must reject");
            assert_eq!(err.code, ERR_PROXY_CONFIG_INVALID);
        }
    }

    #[test]
    fn another_loopback_port_is_a_legal_proxy() {
        // The test fixtures are loopback proxies; only our own two ports are forbidden.
        let toml = ProxyToml {
            url: Some("http://127.0.0.1:9999".into()),
            ..Default::default()
        };
        let cfg = resolve(Some(&toml), &MapEnv::default()).expect("resolve");
        assert_eq!(cfg.url.as_deref(), Some("http://127.0.0.1:9999"));
    }

    #[test]
    fn no_proxy_with_allow_direct_false_is_rejected() {
        let toml = ProxyToml {
            url: Some("http://proxy:8080".into()),
            no_proxy: Some("internal.example".into()),
            allow_direct: Some(false),
            ..Default::default()
        };
        let err = resolve(Some(&toml), &MapEnv::default()).expect_err("must reject");
        assert_eq!(err.code, ERR_PROXY_CONFIG_INVALID);
    }

    #[test]
    fn loopback_only_no_proxy_survives_allow_direct_false() {
        // The hard bypass is not a user entry and must not trip the D-21 rule.
        let toml = ProxyToml {
            url: Some("http://proxy:8080".into()),
            allow_direct: Some(false),
            ..Default::default()
        };
        let cfg = resolve(Some(&toml), &MapEnv::default()).expect("resolve");
        assert!(!cfg.allow_direct);
        assert!(cfg.no_proxy.matches("127.0.0.1", 1234));
    }

    #[test]
    fn missing_ca_bundle_fails_at_parse() {
        let toml = ProxyToml {
            ca_bundle: Some("/definitely/not/here.pem".into()),
            ..Default::default()
        };
        let err = resolve(Some(&toml), &MapEnv::default()).expect_err("must reject");
        assert_eq!(err.code, ERR_PROXY_CONFIG_INVALID);
    }

    #[test]
    fn malformed_ca_bundle_fails_at_parse() {
        let dir = tempfile::tempdir().expect("tempdir");
        let path = dir.path().join("bad.pem");
        std::fs::write(&path, b"this is not a certificate").expect("write");
        let toml = ProxyToml {
            ca_bundle: Some(path.to_string_lossy().into_owned()),
            ..Default::default()
        };
        let err = resolve(Some(&toml), &MapEnv::default()).expect_err("must reject");
        assert_eq!(err.code, ERR_PROXY_CONFIG_INVALID);
        assert!(err.message.contains("no PEM certificate"));
    }

    #[test]
    fn bad_enum_values_name_the_key_and_the_alternatives() {
        for (toml, key) in [
            (
                ProxyToml {
                    mode: Some("sometimes".into()),
                    ..Default::default()
                },
                "mode",
            ),
            (
                ProxyToml {
                    auth: Some("ntlm".into()),
                    ..Default::default()
                },
                "auth",
            ),
            (
                ProxyToml {
                    source: Some("telepathy".into()),
                    ..Default::default()
                },
                "source",
            ),
        ] {
            let err = resolve(Some(&toml), &MapEnv::default()).expect_err("must reject");
            assert_eq!(err.code, ERR_PROXY_CONFIG_INVALID);
            assert!(err.message.contains(key), "message must name {key}");
        }
    }

    #[test]
    fn ntlm_is_refused_by_name() {
        let toml = ProxyToml {
            auth: Some("ntlm".into()),
            ..Default::default()
        };
        let err = resolve(Some(&toml), &MapEnv::default()).expect_err("must reject");
        assert!(err.suggestion.unwrap_or_default().contains("NTLM"));
    }

    /// The masking invariant on the least controlled surface there is. A derived `Debug`
    /// would have printed both passwords into every `tracing` field and every test failure
    /// message that formats a config.
    #[test]
    fn debug_output_never_renders_a_password() {
        let env = MapEnv::with(&[("OPENLATCH_PROXY", "http://alice:hunter2@proxy.corp:8080")]);
        let mut cfg = resolve(None, &env).expect("resolve");
        cfg.resolved_password = Some("from-the-keychain".to_string());

        let rendered = format!("{cfg:?}");
        assert!(
            !rendered.contains("hunter2"),
            "env_password leaked into Debug: {rendered}"
        );
        assert!(
            !rendered.contains("from-the-keychain"),
            "resolved_password leaked into Debug: {rendered}"
        );
        // The username is not a secret and must survive -- "failing as which account?" is
        // the first thing an operator needs.
        assert!(
            rendered.contains("alice"),
            "expected the username: {rendered}"
        );
        assert!(rendered.contains("proxy.corp:8080"));
    }

    /// A malformed `OPENLATCH_PROXY` is reported with the password masked. Without the
    /// mask, typing the variable without a scheme prints the proxy password into the log.
    #[test]
    fn a_malformed_env_url_is_reported_without_its_password() {
        let env = MapEnv::with(&[("OPENLATCH_PROXY", "alice:hunter2@proxy.corp:8080")]);
        let err = resolve(None, &env).expect_err("no scheme must be refused");
        assert_eq!(err.code, ERR_PROXY_CONFIG_INVALID);
        let rendered = format!("{err:?} {} {:?}", err.message, err.suggestion);
        assert!(
            !rendered.contains("hunter2"),
            "the password leaked into the parse error: {rendered}"
        );
    }

    #[test]
    fn the_resolved_password_beats_the_env_one() {
        let env = MapEnv::with(&[("OPENLATCH_PROXY", "http://alice:from-env@proxy.corp:8080")]);
        let mut cfg = resolve(None, &env).expect("resolve");
        assert_eq!(cfg.proxy_password(), Some("from-env"));
        cfg.resolved_password = Some("from-the-ladder".to_string());
        assert_eq!(cfg.proxy_password(), Some("from-the-ladder"));
    }

    #[test]
    fn the_proxy_authority_is_the_credential_key() {
        let toml = ProxyToml {
            url: Some("http://Proxy.Corp:8080".into()),
            ..Default::default()
        };
        let cfg = resolve(Some(&toml), &MapEnv::default()).expect("resolve");
        assert_eq!(cfg.proxy_authority().as_deref(), Some("proxy.corp:8080"));
        assert_eq!(cfg.masked_url().as_deref(), Some("http://Proxy.Corp:8080"));
    }
}