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
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
//! Windows discovery rungs.
//!
//! Two ladders, one per [`Context`], both frozen by the PRD's resolver table:
//!
//! | Context | Rungs, in order |
//! | --- | --- |
//! | user session | per-user WinINet static → per-user `AutoConfigURL` PAC → machine WinHTTP → gated WPAD |
//! | daemon service | `HKLM` Internet Settings (only when `ProxySettingsPerUser = 0`) → machine WinHTTP → gated WPAD |
//!
//! The rung logic is pure over [`WinSource`], so it compiles and is unit-tested on every
//! host; only the backend behind that seam is `#[cfg(windows)]`. That split is what lets a
//! Linux developer change the ladder's *order* and see the test fail.
//!
//! Three decisions worth reading before changing anything here:
//!
//! - **WPAD is delegated, never implemented.** WPAD is a documented attack vector, and a
//!   security client that re-enabled a protocol the enterprise baseline disabled would be
//!   doing the opposite of its job. The rung asks WinHTTP to auto-detect, and only after
//!   both gates — `DisableWpad` and the `WinHttpAutoProxySvc` start type — say it may.
//! - **The machine store is read through `WinHttpGetDefaultProxyConfiguration`**, which is
//!   the sanctioned reader of what `netsh winhttp set proxy` writes. The
//!   `Connections\WinHttpSettings` blob it lands in is an undocumented binary layout, and
//!   parsing it ourselves would be a bug waiting for a Windows release.
//! - **`https=` in a WinINet proxy list selects a destination scheme, not the proxy's own.**
//!   `https=proxy.corp:8080` means "use proxy.corp:8080 *for* https traffic", and that
//!   proxy is reached over plain HTTP unless it says otherwise.

use reqwest::Url;

use crate::core::egress::config::ProxySource;
use crate::core::error::{OlError, ERR_PAC_UNAVAILABLE};

use super::{parse_discovered, rung, Context, Ladder, PacAnswer, PacBinding, Route, RungResult};

/// `HKLM` path of the machine-wide Internet Settings.
const INET_SETTINGS: &str = r"SOFTWARE\Microsoft\Windows\CurrentVersion\Internet Settings";
/// `HKLM` path of the policy-pushed Internet Settings, which WinHTTP checks as well.
const INET_SETTINGS_POLICY: &str =
    r"SOFTWARE\Policies\Microsoft\Windows\CurrentVersion\Internet Settings";
/// Where the WPAD kill switch lives.
const WINHTTP_POLICY: &str = r"SOFTWARE\Microsoft\Windows\CurrentVersion\Internet Settings\WinHttp";
/// The service that performs WPAD auto-detection on behalf of WinHTTP.
const AUTOPROXY_SERVICE: &str = "WinHttpAutoProxySvc";

/// The per-user WinINet settings, as `WinHttpGetIEProxyConfigForCurrentUser` reports them.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct IeProxyConfig {
    /// `fAutoDetect` — the "Automatically detect settings" checkbox.
    pub auto_detect: bool,
    /// `lpszAutoConfigUrl` — an explicit PAC script.
    pub auto_config_url: Option<String>,
    /// `lpszProxy` — the WinINet proxy list. See the module note on `https=`.
    pub proxy: Option<String>,
    /// `lpszProxyBypass` — the bypass list. Read for completeness; the product's own
    /// `no_proxy` grammar is the one that decides bypasses, so this is not merged.
    pub proxy_bypass: Option<String>,
}

/// How WinHTTP should locate the PAC script.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum AutoProxyMode {
    /// An explicit `AutoConfigURL`.
    ConfigUrl(String),
    /// WPAD: DHCP option 252, then the `wpad` DNS A record.
    AutoDetect,
}

/// What the host says about a Windows service, as far as the WPAD gate cares.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ServiceState {
    /// `Start = 4`: an administrator or a security baseline turned it off.
    Disabled,
    /// Registered and not disabled.
    ///
    /// Its *running* state is deliberately not a gate. `WinHttpAutoProxySvc` is
    /// demand-start, so "stopped" is its normal resting state and WinHTTP starts it when
    /// asked — gating on that would switch WPAD off on every healthy host.
    Enabled,
    /// No such service on this host.
    Absent,
}

/// Everything the Windows ladder needs from the OS, behind one seam.
///
/// Tests inject fixtures on every platform; the real implementation is
/// [`native`], which exists only on Windows.
pub trait WinSource {
    /// `WinHttpGetIEProxyConfigForCurrentUser`.
    fn ie_config(&self) -> Option<IeProxyConfig>;
    /// `WinHttpGetDefaultProxyConfiguration` — the machine WinHTTP proxy list.
    fn default_proxy(&self) -> Option<String>;
    /// A `REG_DWORD` under `HKLM`.
    fn hklm_dword(&self, path: &str, name: &str) -> Option<u32>;
    /// A `REG_SZ` under `HKLM`.
    fn hklm_string(&self, path: &str, name: &str) -> Option<String>;
    /// See [`ServiceState`].
    fn service_state(&self, name: &str) -> ServiceState;
    /// `WinHttpGetProxyForUrl` for one destination.
    fn get_proxy_for_url(
        &self,
        target: &Url,
        mode: &AutoProxyMode,
    ) -> Result<Option<PacAnswer>, OlError>;
}

// ---------------------------------------------------------------------------
// The ladder — pure over the seam
// ---------------------------------------------------------------------------

/// Walk the Windows ladder for `ctx`.
pub fn walk(ladder: &mut Ladder, ctx: Context, src: &dyn WinSource, target: &Url) {
    match ctx {
        Context::UserSession => {
            // One read, four rungs: the IE config answers the static rung, supplies the
            // PAC rung's URL, and holds the auto-detect hint the WPAD rung needs.
            let ie = src.ie_config();
            if ladder.offer(rung::WININET_USER, user_static(ie.as_ref())) {
                return;
            }
            if ladder.offer(rung::IE_PAC, ie_pac(src, ie.as_ref(), target)) {
                return;
            }
            if ladder.offer(rung::WINHTTP_MACHINE, machine_winhttp(src)) {
                return;
            }
            let hinted = ie.as_ref().is_some_and(|c| c.auto_detect);
            ladder.offer(rung::WPAD, wpad(src, target, hinted));
        }
        Context::DaemonService => {
            if ladder.offer(rung::HKLM_INETSETTINGS, hklm_internet_settings(src, target)) {
                return;
            }
            if ladder.offer(rung::WINHTTP_MACHINE, machine_winhttp(src)) {
                return;
            }
            // A service has no per-user checkbox to consult, so the registry gates are the
            // whole of the decision.
            ladder.offer(rung::WPAD, wpad(src, target, true));
        }
    }
}

fn user_static(ie: Option<&IeProxyConfig>) -> RungResult {
    let list = ie.and_then(|c| c.proxy.as_deref()).unwrap_or_default();
    from_proxy_list(ProxySource::Windows, list, "per-user WinINet")
}

fn machine_winhttp(src: &dyn WinSource) -> RungResult {
    let list = src.default_proxy().unwrap_or_default();
    from_proxy_list(ProxySource::Windows, &list, "machine WinHTTP")
}

fn from_proxy_list(source: ProxySource, list: &str, what: &str) -> RungResult {
    let Some(entry) = parse_proxy_list(list) else {
        return RungResult::empty(source);
    };
    match parse_discovered(&entry) {
        Some(url) => RungResult::static_route(source, url),
        None => RungResult::skipped(
            source,
            crate::core::error::ERR_PROXY_CONFIG_INVALID,
            format!("{what} names a proxy this client cannot use: {entry}"),
        ),
    }
}

fn ie_pac(src: &dyn WinSource, ie: Option<&IeProxyConfig>, target: &Url) -> RungResult {
    let Some(raw) = ie.and_then(|c| c.auto_config_url.as_deref()) else {
        return RungResult::empty(ProxySource::Pac);
    };
    let Some(pac_url) = Url::parse(raw).ok() else {
        return RungResult::skipped(
            ProxySource::Pac,
            crate::core::error::ERR_PROXY_CONFIG_INVALID,
            format!("AutoConfigURL is not a URL: {raw}"),
        );
    };
    pac_rung(
        src,
        target,
        ProxySource::Pac,
        AutoProxyMode::ConfigUrl(pac_url.to_string()),
        Some(pac_url),
    )
}

/// The WPAD rung and its two gates.
///
/// `auto_detect_hinted` is the per-user "Automatically detect settings" checkbox. It is a
/// preference, so an unchecked box leaves an empty rung rather than a gated one; the two
/// *gates* below are security decisions the host made, and each leaves a skip in the trace
/// naming exactly which one fired and where it lives.
fn wpad(src: &dyn WinSource, target: &Url, auto_detect_hinted: bool) -> RungResult {
    if !auto_detect_hinted {
        return RungResult::empty_with(
            ProxySource::Wpad,
            "per-user auto-detect (fAutoDetect) is off",
        );
    }
    if src.hklm_dword(WINHTTP_POLICY, "DisableWpad") == Some(1) {
        return RungResult::skipped(
            ProxySource::Wpad,
            ERR_PAC_UNAVAILABLE,
            format!(r"WPAD is disabled by policy: HKLM\{WINHTTP_POLICY}\DisableWpad = 1"),
        );
    }
    match src.service_state(AUTOPROXY_SERVICE) {
        ServiceState::Disabled => {
            return RungResult::skipped(
                ProxySource::Wpad,
                ERR_PAC_UNAVAILABLE,
                format!("{AUTOPROXY_SERVICE} is disabled (Start = 4)"),
            )
        }
        ServiceState::Absent => {
            return RungResult::skipped(
                ProxySource::Wpad,
                ERR_PAC_UNAVAILABLE,
                format!("{AUTOPROXY_SERVICE} is not registered on this host"),
            )
        }
        ServiceState::Enabled => {}
    }
    pac_rung(
        src,
        target,
        ProxySource::Wpad,
        AutoProxyMode::AutoDetect,
        None,
    )
}

/// Evaluate a PAC for the probe target and turn the answer into a candidate.
///
/// The route persisted on a win is the PAC *source*; `probe_via` is the answer for this one
/// destination and exists only so the candidate can be validated. They are different values
/// on purpose — see [`Route`].
fn pac_rung(
    src: &dyn WinSource,
    target: &Url,
    source: ProxySource,
    mode: AutoProxyMode,
    pac_url: Option<Url>,
) -> RungResult {
    match src.get_proxy_for_url(target, &mode) {
        // The lookup ran and the network named no proxy. `none`, exactly like every other
        // rung that finds nothing — not an error code on an otherwise healthy host.
        Ok(None) => RungResult::empty_with(
            source,
            match mode {
                AutoProxyMode::AutoDetect => "no WPAD server answered on this network",
                _ => "auto-detection named no proxy",
            },
        ),
        Ok(Some(answer)) => {
            let probe_via = answer.first_route();
            if probe_via.is_none() && answer.names_a_proxy() {
                return RungResult::skipped(
                    source,
                    crate::core::error::ERR_PROXY_CONFIG_INVALID,
                    format!("the PAC named no usable proxy: {:?}", answer.proxies),
                );
            }
            RungResult::Candidate {
                source,
                route: Route::PacSource { pac_url },
                probe_via,
            }
        }
        Err(e) => RungResult::skipped(source, e.code, e.message),
    }
}

/// The service-context rung: machine Internet Settings, and only when they apply.
///
/// `ProxySettingsPerUser` is checked in both the policy hive and the plain one, which is
/// what WinHTTP itself does. Either saying `0` makes the machine values authoritative; a
/// service must never read a per-user hive, because from `SYSTEM` "the user" is whichever
/// profile happens to be loaded.
fn hklm_internet_settings(src: &dyn WinSource, target: &Url) -> RungResult {
    let machine_wide = [INET_SETTINGS_POLICY, INET_SETTINGS]
        .iter()
        .any(|p| src.hklm_dword(p, "ProxySettingsPerUser") == Some(0));
    if !machine_wide {
        return RungResult::empty_with(
            ProxySource::Windows,
            "machine Internet Settings do not apply: ProxySettingsPerUser is not 0",
        );
    }
    if let Some(raw) = src.hklm_string(INET_SETTINGS, "AutoConfigURL") {
        if let Ok(pac_url) = Url::parse(&raw) {
            return pac_rung(
                src,
                target,
                ProxySource::Pac,
                AutoProxyMode::ConfigUrl(pac_url.to_string()),
                Some(pac_url),
            );
        }
    }
    if src.hklm_dword(INET_SETTINGS, "ProxyEnable") != Some(1) {
        return RungResult::empty(ProxySource::Windows);
    }
    let list = src
        .hklm_string(INET_SETTINGS, "ProxyServer")
        .unwrap_or_default();
    from_proxy_list(ProxySource::Windows, &list, "HKLM Internet Settings")
}

/// The per-destination PAC answer, for the factory's custom-proxy closure.
pub fn eval_pac(
    src: &dyn WinSource,
    target: &Url,
    binding: &PacBinding,
) -> Result<Option<Url>, OlError> {
    let mode = match &binding.pac_url {
        Some(u) => AutoProxyMode::ConfigUrl(u.to_string()),
        None => AutoProxyMode::AutoDetect,
    };
    Ok(src
        .get_proxy_for_url(target, &mode)?
        .and_then(|answer| answer.first_route()))
}

/// `ERROR_WINHTTP_LOGIN_FAILURE` — the PAC server asked the caller to authenticate.
///
/// Named here rather than imported from `windows-sys` so [`with_autologon_retry`] below
/// stays compilable, and testable, on every host.
pub const WINHTTP_LOGIN_FAILURE: u32 = 12015;

/// `ERROR_WINHTTP_AUTODETECTION_FAILED` — WPAD asked the network and nothing answered.
///
/// The ordinary result on the many networks that run no WPAD server, and therefore not a
/// failure: the question "is there a proxy here?" was answered, correctly, with "no".
/// Mapping it to `OL-1225` made every such host print an error code on a healthy run.
pub const WINHTTP_AUTODETECTION_FAILED: u32 = 12180;

/// The .NET `WinInetProxyHelper` dance: try with `fAutoLogonIfChallenged = FALSE`, and
/// retry once with `TRUE` only when the PAC server actually challenged us.
///
/// `TRUE` on the first call would be simpler and is wrong: it bypasses the WinHTTP
/// service's PAC cache every time, so a process that always passes it re-downloads the
/// script on every request it makes.
pub fn with_autologon_retry<F>(mut attempt: F) -> Result<Option<PacAnswer>, OlError>
where
    F: FnMut(bool) -> Result<PacAnswer, u32>,
{
    let raw = match attempt(false) {
        Ok(answer) => return Ok(Some(answer)),
        Err(WINHTTP_LOGIN_FAILURE) => attempt(true),
        Err(code) => Err(code),
    };
    match raw {
        Ok(answer) => Ok(Some(answer)),
        Err(WINHTTP_AUTODETECTION_FAILED) => Ok(None),
        Err(code) => Err(pac_error(code)),
    }
}

/// The `OL-1225` a failed `WinHttpGetProxyForUrl` produces.
fn pac_error(code: u32) -> OlError {
    OlError::new(
        ERR_PAC_UNAVAILABLE,
        format!("WinHttpGetProxyForUrl failed with Windows error {code}"),
    )
    .with_suggestion(
        "The PAC script could not be fetched or evaluated. Set an explicit proxy with \
         `openlatch proxy set <url>` if this host has no working PAC.",
    )
}

/// Pick one proxy out of a WinINet / WinHTTP proxy list.
///
/// The grammar is `host:port`, or `scheme=host:port` entries separated by semicolons or
/// whitespace. `scheme` names the *destination* protocol the entry serves, so the order of
/// preference is `https=` (what all our egress is), then `http=`, then a bare entry that
/// serves everything. `ftp=`, `gopher=` and `socks=` are ignored: the first two are
/// irrelevant, and WinINet's `socks=` does not say whether it means SOCKS4 or SOCKS5, which
/// is not a guess worth making inside an egress path.
pub(crate) fn parse_proxy_list(list: &str) -> Option<String> {
    let mut https: Option<&str> = None;
    let mut http: Option<&str> = None;
    let mut bare: Option<&str> = None;
    for token in list.split([';', ' ', '\t', '\r', '\n']) {
        let token = token.trim();
        if token.is_empty() {
            continue;
        }
        match token.split_once('=') {
            Some(("https", v)) if https.is_none() => https = Some(v),
            Some(("http", v)) if http.is_none() => http = Some(v),
            Some(_) => continue,
            None if bare.is_none() => bare = Some(token),
            None => continue,
        }
    }
    https
        .or(http)
        .or(bare)
        .map(|v| v.trim().to_string())
        .filter(|v| !v.is_empty())
}

// ---------------------------------------------------------------------------
// The Win32 backend
// ---------------------------------------------------------------------------

/// The process-wide Windows backend.
///
/// One instance per process, holding one WinHTTP session: the PAC script cache lives in
/// that session, so a second session would re-download the script on every evaluation.
#[cfg(windows)]
pub(super) fn native() -> &'static Win32Source {
    static SOURCE: std::sync::OnceLock<Win32Source> = std::sync::OnceLock::new();
    SOURCE.get_or_init(Win32Source::default)
}

/// The real Windows implementation of [`WinSource`].
#[cfg(windows)]
#[derive(Default)]
pub struct Win32Source {
    /// When a PAC or WPAD evaluation last timed out. A dead WPAD responder makes every
    /// evaluation cost the full deadline, and the ladder would otherwise pay it twice in a
    /// row — once for the PAC rung, once for WPAD.
    negative_until: std::sync::Mutex<Option<std::time::Instant>>,
}

#[cfg(windows)]
mod win32 {
    //! The FFI. Every failure collapses to `None` or an `OlError` and never panics: the
    //! answer to "the OS would not tell us" is the next rung, not a crash on a developer's
    //! laptop.

    use std::ffi::{OsStr, OsString};
    use std::os::windows::ffi::{OsStrExt, OsStringExt};

    /// A registry string longer than this is not a proxy setting.
    pub(super) const MAX_VALUE_BYTES: u32 = 64 * 1024;

    /// NUL-terminated UTF-16, the only string form the Win32 W-APIs accept.
    pub(super) fn wide(s: &str) -> Vec<u16> {
        OsStr::new(s)
            .encode_wide()
            .chain(std::iter::once(0))
            .collect()
    }

    /// Read a NUL-terminated UTF-16 string the OS allocated.
    ///
    /// # Safety
    ///
    /// `p` must be null or point at a NUL-terminated UTF-16 buffer that stays alive for
    /// the duration of the call.
    pub(super) unsafe fn from_wide_ptr(p: *const u16) -> Option<String> {
        if p.is_null() {
            return None;
        }
        let mut len = 0usize;
        // SAFETY: the caller guarantees a NUL terminator, which bounds this walk.
        while unsafe { *p.add(len) } != 0 {
            len += 1;
            // A proxy list this long is a corrupt value, not a setting. Refusing to walk
            // further keeps a bad pointer from turning into an unbounded read.
            if len > 64 * 1024 {
                return None;
            }
        }
        // SAFETY: `len` is the number of u16s before the NUL, verified above.
        let slice = unsafe { std::slice::from_raw_parts(p, len) };
        Some(OsString::from_wide(slice).to_string_lossy().into_owned())
    }

    /// Owns a `PWSTR` the OS allocated with `GlobalAlloc`, and frees it on drop.
    ///
    /// `WinHttpGetIEProxyConfigForCurrentUser` and `WinHttpGetProxyForUrl` both hand back
    /// strings the caller owns; every early return in this module would otherwise be a
    /// leak.
    pub(super) struct GlobalStr(pub *mut u16);

    impl GlobalStr {
        pub(super) fn take(&self) -> Option<String> {
            // SAFETY: the pointer came from a WinHTTP out-parameter, which is either null
            // or a NUL-terminated UTF-16 buffer this struct owns.
            unsafe { from_wide_ptr(self.0) }
        }
    }

    impl Drop for GlobalStr {
        fn drop(&mut self) {
            if !self.0.is_null() {
                // SAFETY: the pointer was allocated by WinHTTP with `GlobalAlloc`, which
                // is what `GlobalFree` releases, and it is freed exactly once.
                unsafe {
                    windows_sys::Win32::Foundation::GlobalFree(self.0.cast());
                }
            }
        }
    }
}

#[cfg(windows)]
impl Win32Source {
    /// How long one `WinHttpGetProxyForUrl` may take before the ladder moves on.
    const PAC_DEADLINE: std::time::Duration = std::time::Duration::from_secs(5);
    /// How long a timeout suppresses further evaluations.
    const NEGATIVE_TTL: std::time::Duration = std::time::Duration::from_secs(10);

    fn in_negative_cache(&self) -> bool {
        self.negative_until
            .lock()
            .ok()
            .and_then(|g| *g)
            .is_some_and(|at| at.elapsed() < Self::NEGATIVE_TTL)
    }

    fn record_timeout(&self) {
        if let Ok(mut g) = self.negative_until.lock() {
            *g = Some(std::time::Instant::now());
        }
    }
}

/// The one WinHTTP session for this process, as a raw handle.
///
/// Deliberately never closed. A PAC evaluation that blew its deadline is *abandoned*, not
/// cancelled — WinHTTP's synchronous `WinHttpGetProxyForUrl` has no timeout parameter and
/// no cancellation — so the abandoned thread may still be inside the call. Closing the
/// handle under it would be a use-after-free; letting the process own one handle for its
/// lifetime costs nothing and the OS reclaims it at exit.
#[cfg(windows)]
fn winhttp_session() -> Option<usize> {
    use windows_sys::Win32::Networking::WinHttp::{WinHttpOpen, WINHTTP_ACCESS_TYPE_NO_PROXY};

    struct Handle(usize);
    // SAFETY: WinHTTP handles are usable from any thread; the value is an opaque pointer
    // that is only ever passed back to WinHTTP.
    unsafe impl Send for Handle {}
    unsafe impl Sync for Handle {}

    static SESSION: std::sync::OnceLock<Option<Handle>> = std::sync::OnceLock::new();
    SESSION
        .get_or_init(|| {
            let agent = win32::wide("openlatch-egress");
            // NO_PROXY access: this session exists to *ask about* proxies, never to send
            // traffic through one. Synchronous (flags = 0) because `WinHttpGetProxyForUrl`
            // is a synchronous API and the watchdog below owns the deadline.
            // SAFETY: `agent` outlives the call; the three proxy arguments are the
            // documented "none" form for NO_PROXY access.
            let h = unsafe {
                WinHttpOpen(
                    agent.as_ptr(),
                    WINHTTP_ACCESS_TYPE_NO_PROXY,
                    std::ptr::null(),
                    std::ptr::null(),
                    0,
                )
            };
            if h.is_null() {
                None
            } else {
                Some(Handle(h as usize))
            }
        })
        .as_ref()
        .map(|h| h.0)
}

#[cfg(windows)]
impl WinSource for Win32Source {
    fn ie_config(&self) -> Option<IeProxyConfig> {
        use windows_sys::Win32::Networking::WinHttp::{
            WinHttpGetIEProxyConfigForCurrentUser, WINHTTP_CURRENT_USER_IE_PROXY_CONFIG,
        };

        let mut raw = WINHTTP_CURRENT_USER_IE_PROXY_CONFIG::default();
        // SAFETY: `raw` is a live, zeroed struct of exactly the shape the API writes.
        let ok = unsafe { WinHttpGetIEProxyConfigForCurrentUser(&mut raw) };
        if ok == 0 {
            // The documented answer in a service context, where there is no user to have
            // settings. The next rung is the right place to be.
            return None;
        }
        // Each string is wrapped before anything else can return early: the API hands over
        // ownership of all three whether we read them or not.
        let auto_config_url = win32::GlobalStr(raw.lpszAutoConfigUrl);
        let proxy = win32::GlobalStr(raw.lpszProxy);
        let proxy_bypass = win32::GlobalStr(raw.lpszProxyBypass);
        Some(IeProxyConfig {
            auto_detect: raw.fAutoDetect != 0,
            auto_config_url: auto_config_url.take().filter(|s| !s.is_empty()),
            proxy: proxy.take().filter(|s| !s.is_empty()),
            proxy_bypass: proxy_bypass.take().filter(|s| !s.is_empty()),
        })
    }

    fn default_proxy(&self) -> Option<String> {
        use windows_sys::Win32::Networking::WinHttp::{
            WinHttpGetDefaultProxyConfiguration, WINHTTP_ACCESS_TYPE_NAMED_PROXY,
            WINHTTP_PROXY_INFO,
        };

        let mut info = WINHTTP_PROXY_INFO::default();
        // SAFETY: `info` is a live, zeroed struct of the shape the API writes.
        let ok = unsafe { WinHttpGetDefaultProxyConfiguration(&mut info) };
        if ok == 0 {
            return None;
        }
        let proxy = win32::GlobalStr(info.lpszProxy);
        let _bypass = win32::GlobalStr(info.lpszProxyBypass);
        if info.dwAccessType != WINHTTP_ACCESS_TYPE_NAMED_PROXY {
            return None;
        }
        proxy.take().filter(|s| !s.is_empty())
    }

    fn hklm_dword(&self, path: &str, name: &str) -> Option<u32> {
        use windows_sys::Win32::Foundation::ERROR_SUCCESS;
        use windows_sys::Win32::System::Registry::{
            RegGetValueW, HKEY_LOCAL_MACHINE, RRF_RT_REG_DWORD,
        };

        let subkey = win32::wide(path);
        let value = win32::wide(name);
        let mut out: u32 = 0;
        let mut size: u32 = std::mem::size_of::<u32>() as u32;
        // SAFETY: both name pointers are NUL-terminated UTF-16 buffers alive for the call,
        // and `out`/`size` are live out-parameters sized for a DWORD.
        let rc = unsafe {
            RegGetValueW(
                HKEY_LOCAL_MACHINE,
                subkey.as_ptr(),
                value.as_ptr(),
                RRF_RT_REG_DWORD,
                std::ptr::null_mut(),
                std::ptr::addr_of_mut!(out).cast(),
                &mut size,
            )
        };
        (rc == ERROR_SUCCESS).then_some(out)
    }

    fn hklm_string(&self, path: &str, name: &str) -> Option<String> {
        use windows_sys::Win32::Foundation::ERROR_SUCCESS;
        use windows_sys::Win32::System::Registry::{
            RegGetValueW, HKEY_LOCAL_MACHINE, RRF_RT_REG_SZ,
        };

        let subkey = win32::wide(path);
        let value = win32::wide(name);
        let mut bytes: u32 = 0;
        // SAFETY: a null data pointer with a live size out-parameter is the documented
        // "tell me how big it is" form.
        let rc = unsafe {
            RegGetValueW(
                HKEY_LOCAL_MACHINE,
                subkey.as_ptr(),
                value.as_ptr(),
                RRF_RT_REG_SZ,
                std::ptr::null_mut(),
                std::ptr::null_mut(),
                &mut bytes,
            )
        };
        if rc != ERROR_SUCCESS || bytes == 0 || bytes > win32::MAX_VALUE_BYTES {
            return None;
        }
        let mut buf = vec![0u16; bytes as usize / 2 + 1];
        let mut written = bytes;
        // SAFETY: `buf` is at least `written` bytes of writable UTF-16 storage and
        // `written` is a live u32 out-parameter, which is the contract for the second call.
        let rc = unsafe {
            RegGetValueW(
                HKEY_LOCAL_MACHINE,
                subkey.as_ptr(),
                value.as_ptr(),
                RRF_RT_REG_SZ,
                std::ptr::null_mut(),
                buf.as_mut_ptr().cast(),
                &mut written,
            )
        };
        if rc != ERROR_SUCCESS {
            return None;
        }
        // `written` counts the terminating NUL, which is not part of the value.
        let len = (written as usize / 2).saturating_sub(1).min(buf.len());
        let s = String::from_utf16_lossy(&buf[..len]);
        (!s.is_empty()).then_some(s)
    }

    fn service_state(&self, name: &str) -> ServiceState {
        // The registry start type is the authoritative answer and needs no privilege
        // beyond read access to the Services key.
        match self.hklm_dword(
            &format!(r"SYSTEM\CurrentControlSet\Services\{name}"),
            "Start",
        ) {
            Some(4) => return ServiceState::Disabled,
            Some(_) => return ServiceState::Enabled,
            None => {}
        }
        // The registry told us nothing — the key is missing, or unreadable. Ask the SCM
        // which of the two it is, so an unreadable key does not silently read as "absent"
        // and switch WPAD off on a host that has it.
        service_state_via_scm(name)
    }

    fn get_proxy_for_url(
        &self,
        target: &Url,
        mode: &AutoProxyMode,
    ) -> Result<Option<PacAnswer>, OlError> {
        if self.in_negative_cache() {
            return Err(OlError::new(
                ERR_PAC_UNAVAILABLE,
                "a PAC evaluation timed out moments ago; not retrying yet",
            )
            .with_suggestion(
                "Set an explicit proxy with `openlatch proxy set <url>` if this host has \
                 no working PAC responder.",
            ));
        }
        let Some(session) = winhttp_session() else {
            return Err(OlError::new(
                ERR_PAC_UNAVAILABLE,
                "WinHttpOpen failed; this host has no usable WinHTTP session",
            ));
        };
        let url = target.to_string();
        let mode = mode.clone();
        let (tx, rx) = std::sync::mpsc::channel();
        // `WinHttpGetProxyForUrl` is documented-blocking with no timeout parameter, and a
        // dead WPAD responder blocks it for as long as DNS and DHCP take to give up. The
        // watchdog bounds the ladder, not the call: on a timeout the thread is abandoned
        // and finishes into a receiver nobody reads. One abandoned thread per PAC attempt
        // is bounded — the negative cache below stops the second one.
        std::thread::spawn(move || {
            let _ = tx.send(get_proxy_for_url_blocking(session, &url, &mode));
        });
        match rx.recv_timeout(Self::PAC_DEADLINE) {
            Ok(result) => result,
            Err(_) => {
                self.record_timeout();
                Err(OlError::new(
                    ERR_PAC_UNAVAILABLE,
                    format!(
                        "the PAC evaluation did not finish within {} s",
                        Self::PAC_DEADLINE.as_secs()
                    ),
                )
                .with_suggestion(
                    "A WPAD responder that never answers looks exactly like this. Set an \
                     explicit proxy with `openlatch proxy set <url>`.",
                ))
            }
        }
    }
}

/// `OpenSCManagerW` + `OpenServiceW`, purely to tell "absent" from "unreadable".
#[cfg(windows)]
fn service_state_via_scm(name: &str) -> ServiceState {
    use windows_sys::Win32::Foundation::{GetLastError, ERROR_SERVICE_DOES_NOT_EXIST};
    use windows_sys::Win32::System::Services::{
        CloseServiceHandle, OpenSCManagerW, OpenServiceW, QueryServiceStatusEx, SC_MANAGER_CONNECT,
        SC_STATUS_PROCESS_INFO, SERVICE_QUERY_STATUS, SERVICE_STATUS_PROCESS,
    };

    // SAFETY: null machine and database names select the local machine's active database,
    // which is the documented default form.
    let scm = unsafe { OpenSCManagerW(std::ptr::null(), std::ptr::null(), SC_MANAGER_CONNECT) };
    if scm.is_null() {
        // No opinion. Treating "we could not ask" as "enabled" keeps the WPAD gate from
        // failing shut on a host that never disabled anything; the evaluation below still
        // has its own deadline.
        return ServiceState::Enabled;
    }
    let wide_name = win32::wide(name);
    // SAFETY: `scm` is a live handle and `wide_name` is NUL-terminated for the call.
    let svc = unsafe { OpenServiceW(scm, wide_name.as_ptr(), SERVICE_QUERY_STATUS) };
    if svc.is_null() {
        // SAFETY: reads the calling thread's last-error, set by the failed call above.
        let missing = unsafe { GetLastError() } == ERROR_SERVICE_DOES_NOT_EXIST;
        // SAFETY: `scm` is a live SCM handle, closed exactly once.
        unsafe { CloseServiceHandle(scm) };
        return if missing {
            ServiceState::Absent
        } else {
            ServiceState::Enabled
        };
    }
    let mut status = SERVICE_STATUS_PROCESS::default();
    let mut needed: u32 = 0;
    // SAFETY: the buffer is a live `SERVICE_STATUS_PROCESS` and its size is passed
    // exactly, which is what `SC_STATUS_PROCESS_INFO` requires.
    let ok = unsafe {
        QueryServiceStatusEx(
            svc,
            SC_STATUS_PROCESS_INFO,
            std::ptr::addr_of_mut!(status).cast(),
            std::mem::size_of::<SERVICE_STATUS_PROCESS>() as u32,
            &mut needed,
        )
    };
    // SAFETY: both handles are live and each is closed exactly once.
    unsafe {
        CloseServiceHandle(svc);
        CloseServiceHandle(scm);
    }
    // The service exists. Its running state is not a gate — see `ServiceState::Enabled`.
    let _ = ok;
    ServiceState::Enabled
}

/// The blocking half of the PAC evaluation, run on the watchdog thread.
///
/// The `fAutoLogonIfChallenged: FALSE` first attempt is deliberate and copied from .NET's
/// `WinInetProxyHelper`: `TRUE` bypasses the service-side PAC cache on every call, so a
/// process that always passes it re-downloads the script forever. The retry on
/// `ERROR_WINHTTP_LOGIN_FAILURE` (12015) covers the PAC servers that do demand auth.
#[cfg(windows)]
fn get_proxy_for_url_blocking(
    session: usize,
    url: &str,
    mode: &AutoProxyMode,
) -> Result<Option<PacAnswer>, OlError> {
    use windows_sys::Win32::Foundation::GetLastError;
    use windows_sys::Win32::Networking::WinHttp::{
        WinHttpGetProxyForUrl, WINHTTP_ACCESS_TYPE_NAMED_PROXY, WINHTTP_AUTOPROXY_AUTO_DETECT,
        WINHTTP_AUTOPROXY_CONFIG_URL, WINHTTP_AUTOPROXY_OPTIONS, WINHTTP_AUTO_DETECT_TYPE_DHCP,
        WINHTTP_AUTO_DETECT_TYPE_DNS_A, WINHTTP_PROXY_INFO,
    };

    let url_w = win32::wide(url);
    let config_url_w = match mode {
        AutoProxyMode::ConfigUrl(u) => Some(win32::wide(u)),
        AutoProxyMode::AutoDetect => None,
    };

    let attempt = |auto_logon: bool| -> Result<PacAnswer, u32> {
        let mut opts = WINHTTP_AUTOPROXY_OPTIONS::default();
        match &config_url_w {
            Some(w) => {
                opts.dwFlags = WINHTTP_AUTOPROXY_CONFIG_URL;
                opts.lpszAutoConfigUrl = w.as_ptr();
            }
            None => {
                opts.dwFlags = WINHTTP_AUTOPROXY_AUTO_DETECT;
                opts.dwAutoDetectFlags =
                    WINHTTP_AUTO_DETECT_TYPE_DHCP | WINHTTP_AUTO_DETECT_TYPE_DNS_A;
            }
        }
        opts.fAutoLogonIfChallenged = i32::from(auto_logon);
        let mut info = WINHTTP_PROXY_INFO::default();
        // SAFETY: `session` is the process session handle, `url_w` and any config URL are
        // NUL-terminated and outlive the call, and `opts`/`info` are live structs of the
        // documented shapes.
        let ok = unsafe {
            WinHttpGetProxyForUrl(
                session as *mut std::ffi::c_void,
                url_w.as_ptr(),
                &mut opts,
                &mut info,
            )
        };
        if ok == 0 {
            // SAFETY: reads the calling thread's last-error, set by the failed call above.
            return Err(unsafe { GetLastError() });
        }
        let proxy = win32::GlobalStr(info.lpszProxy);
        let _bypass = win32::GlobalStr(info.lpszProxyBypass);
        if info.dwAccessType != WINHTTP_ACCESS_TYPE_NAMED_PROXY {
            // The PAC answered `DIRECT` for this destination. An empty list is that
            // answer, not an absence.
            return Ok(PacAnswer::default());
        }
        Ok(PacAnswer {
            proxies: proxy
                .take()
                .unwrap_or_default()
                .split([';', ' '])
                .map(str::trim)
                .filter(|s| !s.is_empty())
                .map(str::to_string)
                .collect(),
        })
    };

    with_autologon_retry(attempt)
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::core::egress::discovery::tests::ScriptedProbe;
    use crate::core::egress::discovery::CandidateOutcome;
    use std::cell::RefCell;
    use std::collections::HashMap;

    /// A fixture host: whatever the test says the OS reports, and a count of the PAC calls
    /// so a test can prove a gate cost zero of them.
    #[derive(Default)]
    struct FakeWin {
        ie: Option<IeProxyConfig>,
        default_proxy: Option<String>,
        dwords: HashMap<(String, String), u32>,
        strings: HashMap<(String, String), String>,
        service: Option<ServiceState>,
        pac: Option<PacAnswer>,
        pac_error: Option<&'static str>,
        /// Every `fAutoLogonIfChallenged` value the fixture was asked with, in order.
        calls: RefCell<Vec<AutoProxyMode>>,
    }

    impl FakeWin {
        fn dword(mut self, path: &str, name: &str, v: u32) -> Self {
            self.dwords.insert((path.to_string(), name.to_string()), v);
            self
        }
        fn string(mut self, path: &str, name: &str, v: &str) -> Self {
            self.strings
                .insert((path.to_string(), name.to_string()), v.to_string());
            self
        }
        fn pac_calls(&self) -> usize {
            self.calls.borrow().len()
        }
    }

    impl WinSource for FakeWin {
        fn ie_config(&self) -> Option<IeProxyConfig> {
            self.ie.clone()
        }
        fn default_proxy(&self) -> Option<String> {
            self.default_proxy.clone()
        }
        fn hklm_dword(&self, path: &str, name: &str) -> Option<u32> {
            self.dwords
                .get(&(path.to_string(), name.to_string()))
                .copied()
        }
        fn hklm_string(&self, path: &str, name: &str) -> Option<String> {
            self.strings
                .get(&(path.to_string(), name.to_string()))
                .cloned()
        }
        fn service_state(&self, _name: &str) -> ServiceState {
            self.service.unwrap_or(ServiceState::Enabled)
        }
        fn get_proxy_for_url(
            &self,
            _target: &Url,
            mode: &AutoProxyMode,
        ) -> Result<Option<PacAnswer>, OlError> {
            self.calls.borrow_mut().push(mode.clone());
            if let Some(code) = self.pac_error {
                return Err(OlError::new(code, "fixture PAC failure"));
            }
            Ok(Some(self.pac.clone().unwrap_or_default()))
        }
    }

    fn target() -> Url {
        Url::parse("https://app.openlatch.ai/api/v1/health").expect("target")
    }

    fn walk_with(
        src: &FakeWin,
        ctx: Context,
        probe: &ScriptedProbe,
    ) -> Vec<super::super::CandidateAttempt> {
        let mut ladder = Ladder::new(probe);
        walk(&mut ladder, ctx, src, &target());
        ladder.finish().1
    }

    #[test]
    fn the_user_context_walks_the_frozen_rung_order() {
        // Every rung fails, so the whole ladder is walked and its order is observable.
        let src = FakeWin {
            ie: Some(IeProxyConfig {
                auto_detect: true,
                auto_config_url: Some("http://wpad.corp/proxy.pac".into()),
                proxy: Some("https=user.corp:8080".into()),
                proxy_bypass: None,
            }),
            default_proxy: Some("machine.corp:8080".into()),
            pac: Some(PacAnswer {
                proxies: vec!["PROXY pac.corp:3128".into()],
            }),
            ..Default::default()
        };
        let probe = ScriptedProbe::always_fails();
        let trace = walk_with(&src, Context::UserSession, &probe);
        let order: Vec<_> = trace.iter().map(|a| a.rung).collect();
        assert_eq!(
            order,
            vec![
                rung::WININET_USER,
                rung::IE_PAC,
                rung::WINHTTP_MACHINE,
                rung::WPAD
            ]
        );
    }

    #[test]
    fn a_winning_rung_stops_the_walk_before_the_expensive_ones() {
        let src = FakeWin {
            ie: Some(IeProxyConfig {
                auto_detect: true,
                auto_config_url: Some("http://wpad.corp/proxy.pac".into()),
                proxy: Some("user.corp:8080".into()),
                ..Default::default()
            }),
            ..Default::default()
        };
        let probe = ScriptedProbe::new(vec![Ok(5)]);
        let trace = walk_with(&src, Context::UserSession, &probe);
        assert_eq!(trace.len(), 1);
        assert_eq!(trace[0].rung, rung::WININET_USER);
        assert_eq!(
            src.pac_calls(),
            0,
            "a won ladder must not evaluate a PAC at all"
        );
    }

    #[test]
    fn disable_wpad_skips_the_rung_and_costs_no_network() {
        // The gate the CISO's baseline sets. Re-enabling a protocol the enterprise turned
        // off would be the single worst thing this module could do.
        let src = FakeWin {
            ie: Some(IeProxyConfig {
                auto_detect: true,
                ..Default::default()
            }),
            ..Default::default()
        }
        .dword(WINHTTP_POLICY, "DisableWpad", 1);
        let probe = ScriptedProbe::always_fails();
        let trace = walk_with(&src, Context::UserSession, &probe);
        let wpad = trace
            .iter()
            .find(|a| a.rung == rung::WPAD)
            .expect("wpad row");
        assert_eq!(wpad.probe, CandidateOutcome::Skipped(ERR_PAC_UNAVAILABLE));
        assert!(wpad
            .detail
            .as_deref()
            .is_some_and(|d| d.contains("DisableWpad")));
        assert_eq!(
            src.pac_calls(),
            0,
            "a gated WPAD must not touch the network"
        );
    }

    #[test]
    fn a_disabled_autoproxy_service_skips_wpad() {
        let src = FakeWin {
            ie: Some(IeProxyConfig {
                auto_detect: true,
                ..Default::default()
            }),
            service: Some(ServiceState::Disabled),
            ..Default::default()
        };
        let probe = ScriptedProbe::always_fails();
        let trace = walk_with(&src, Context::UserSession, &probe);
        let wpad = trace
            .iter()
            .find(|a| a.rung == rung::WPAD)
            .expect("wpad row");
        assert_eq!(wpad.probe, CandidateOutcome::Skipped(ERR_PAC_UNAVAILABLE));
        assert!(wpad
            .detail
            .as_deref()
            .is_some_and(|d| d.contains(AUTOPROXY_SERVICE)));
        assert_eq!(src.pac_calls(), 0);
    }

    #[test]
    fn auto_detect_off_leaves_an_empty_rung_not_a_gated_one() {
        // An unchecked box is a preference, not a security decision, and reporting it as a
        // blocked gate would send an operator hunting for a policy that does not exist.
        let src = FakeWin {
            ie: Some(IeProxyConfig::default()),
            ..Default::default()
        };
        let probe = ScriptedProbe::always_fails();
        let trace = walk_with(&src, Context::UserSession, &probe);
        let wpad = trace
            .iter()
            .find(|a| a.rung == rung::WPAD)
            .expect("wpad row");
        assert_eq!(wpad.probe, CandidateOutcome::NotConfigured);
        assert_eq!(src.pac_calls(), 0);
    }

    #[test]
    fn a_pac_win_persists_the_script_and_probes_the_answer() {
        let src = FakeWin {
            ie: Some(IeProxyConfig {
                auto_config_url: Some("http://wpad.corp/proxy.pac".into()),
                ..Default::default()
            }),
            pac: Some(PacAnswer {
                proxies: vec!["PROXY pac.corp:3128".into()],
            }),
            ..Default::default()
        };
        let probe = ScriptedProbe::new(vec![Ok(11)]);
        let mut ladder = Ladder::new(&probe);
        walk(&mut ladder, Context::UserSession, &src, &target());
        let (won, trace) = ladder.finish();
        let won = won.expect("the PAC rung wins");
        assert_eq!(won.source, ProxySource::Pac);
        match won.route {
            Route::PacSource { pac_url } => assert_eq!(
                pac_url.map(|u| u.to_string()).as_deref(),
                Some("http://wpad.corp/proxy.pac")
            ),
            Route::Static(_) => panic!("a PAC win must never materialise a static route"),
        }
        // The probe dialled the answer, but the trace names the script.
        assert_eq!(
            probe.seen.borrow().as_slice(),
            &[Some("http://pac.corp:3128".to_string())]
        );
        let pac_row = trace
            .iter()
            .find(|a| a.rung == rung::IE_PAC)
            .expect("pac row");
        assert_eq!(pac_row.url_masked, "pac:http://wpad.corp/proxy.pac");
    }

    #[test]
    fn a_pac_answering_direct_is_a_real_answer() {
        // `FindProxyForURL` returning DIRECT for one destination is legal and common; the
        // probe validates it by going direct.
        let src = FakeWin {
            ie: Some(IeProxyConfig {
                auto_config_url: Some("http://wpad.corp/proxy.pac".into()),
                ..Default::default()
            }),
            pac: Some(PacAnswer::default()),
            ..Default::default()
        };
        let probe = ScriptedProbe::new(vec![Ok(2)]);
        let mut ladder = Ladder::new(&probe);
        walk(&mut ladder, Context::UserSession, &src, &target());
        let (won, _) = ladder.finish();
        assert!(won.is_some());
        assert_eq!(probe.seen.borrow().as_slice(), &[None]);
    }

    #[test]
    fn the_service_context_reads_hklm_only_when_it_applies() {
        let src = FakeWin::default()
            .dword(INET_SETTINGS, "ProxySettingsPerUser", 1)
            .dword(INET_SETTINGS, "ProxyEnable", 1)
            .string(INET_SETTINGS, "ProxyServer", "machine.corp:8080");
        let probe = ScriptedProbe::always_fails();
        let trace = walk_with(&src, Context::DaemonService, &probe);
        let row = trace
            .iter()
            .find(|a| a.rung == rung::HKLM_INETSETTINGS)
            .expect("hklm row");
        assert_eq!(row.probe, CandidateOutcome::NotConfigured);
        assert!(row
            .detail
            .as_deref()
            .is_some_and(|d| d.contains("ProxySettingsPerUser")));
    }

    #[test]
    fn the_policy_hive_alone_can_make_hklm_authoritative() {
        // WinHTTP checks both hives; checking only one is how a policy-managed fleet ends
        // up with a daemon that reads nothing.
        let src = FakeWin::default()
            .dword(INET_SETTINGS_POLICY, "ProxySettingsPerUser", 0)
            .dword(INET_SETTINGS, "ProxyEnable", 1)
            .string(INET_SETTINGS, "ProxyServer", "https=machine.corp:8080");
        let probe = ScriptedProbe::new(vec![Ok(4)]);
        let mut ladder = Ladder::new(&probe);
        walk(&mut ladder, Context::DaemonService, &src, &target());
        let (won, _) = ladder.finish();
        let won = won.expect("HKLM wins");
        assert_eq!(won.source, ProxySource::Windows);
        assert_eq!(
            won.route,
            Route::Static(Url::parse("http://machine.corp:8080").expect("url"))
        );
    }

    #[test]
    fn the_service_context_walks_its_own_rung_order() {
        let src = FakeWin::default();
        let probe = ScriptedProbe::always_fails();
        let trace = walk_with(&src, Context::DaemonService, &probe);
        let order: Vec<_> = trace.iter().map(|a| a.rung).collect();
        assert_eq!(
            order,
            vec![rung::HKLM_INETSETTINGS, rung::WINHTTP_MACHINE, rung::WPAD]
        );
    }

    #[test]
    fn the_proxy_list_grammar_prefers_https_then_http_then_bare() {
        assert_eq!(
            parse_proxy_list("http=a.corp:80;https=b.corp:443;ftp=c.corp:21").as_deref(),
            Some("b.corp:443")
        );
        assert_eq!(
            parse_proxy_list("http=a.corp:80 ftp=c.corp:21").as_deref(),
            Some("a.corp:80")
        );
        assert_eq!(
            parse_proxy_list("plain.corp:8080").as_deref(),
            Some("plain.corp:8080")
        );
        assert_eq!(parse_proxy_list("").as_deref(), None);
        assert_eq!(parse_proxy_list("   ;  ").as_deref(), None);
        // `socks=` is skipped rather than guessed at: WinINet does not say 4 or 5.
        assert_eq!(parse_proxy_list("socks=s.corp:1080").as_deref(), None);
    }

    #[test]
    fn an_https_entry_names_a_destination_scheme_not_the_proxys_own() {
        // `https=proxy.corp:8080` is reached over plain HTTP. Reading it the other way
        // would send a TLS ClientHello at a proxy that speaks none.
        let src = FakeWin {
            ie: Some(IeProxyConfig {
                proxy: Some("https=proxy.corp:8080".into()),
                ..Default::default()
            }),
            ..Default::default()
        };
        let probe = ScriptedProbe::new(vec![Ok(1)]);
        let mut ladder = Ladder::new(&probe);
        walk(&mut ladder, Context::UserSession, &src, &target());
        let (won, _) = ladder.finish();
        assert_eq!(
            won.expect("static win").route,
            Route::Static(Url::parse("http://proxy.corp:8080").expect("url"))
        );
    }

    #[test]
    fn a_failing_pac_leaves_a_skip_with_its_code() {
        let src = FakeWin {
            ie: Some(IeProxyConfig {
                auto_config_url: Some("http://wpad.corp/proxy.pac".into()),
                ..Default::default()
            }),
            pac_error: Some(ERR_PAC_UNAVAILABLE),
            ..Default::default()
        };
        let probe = ScriptedProbe::always_fails();
        let trace = walk_with(&src, Context::UserSession, &probe);
        let row = trace
            .iter()
            .find(|a| a.rung == rung::IE_PAC)
            .expect("pac row");
        assert_eq!(row.probe, CandidateOutcome::Skipped(ERR_PAC_UNAVAILABLE));
        assert!(!row.was_probed());
    }

    #[test]
    fn the_autologon_retry_is_false_first_and_only_once() {
        // FALSE first keeps the WinHTTP service's PAC cache warm; TRUE first would
        // re-download the script on every request this process makes.
        let seen = RefCell::new(Vec::new());
        let answer = PacAnswer {
            proxies: vec!["pac.corp:3128".into()],
        };

        let ok = with_autologon_retry(|auto| {
            seen.borrow_mut().push(auto);
            Ok(answer.clone())
        });
        assert_eq!(ok.expect("first attempt succeeds"), Some(answer.clone()));
        assert_eq!(seen.borrow().as_slice(), &[false]);

        // A login challenge, and only a login challenge, earns the second attempt.
        seen.borrow_mut().clear();
        let retried = with_autologon_retry(|auto| {
            seen.borrow_mut().push(auto);
            if auto {
                Ok(answer.clone())
            } else {
                Err(WINHTTP_LOGIN_FAILURE)
            }
        });
        assert_eq!(retried.expect("the retry succeeds"), Some(answer));
        assert_eq!(seen.borrow().as_slice(), &[false, true]);

        seen.borrow_mut().clear();
        let failed = with_autologon_retry(|auto| {
            seen.borrow_mut().push(auto);
            Err(12002)
        });
        assert_eq!(
            failed.expect_err("a timeout is not a login challenge").code,
            ERR_PAC_UNAVAILABLE
        );
        assert_eq!(
            seen.borrow().as_slice(),
            &[false],
            "only 12015 earns a second attempt"
        );
    }

    /// The real API answers on this host. No candidate is asserted — a developer laptop or
    /// a CI runner usually has no proxy at all — only that the calls return instead of
    /// hanging, faulting, or leaking a handle the next call trips over.
    #[cfg(windows)]
    #[test]
    fn the_real_backend_answers_without_faulting() {
        let src = native();
        for _ in 0..3 {
            let _ = src.ie_config();
            let _ = src.default_proxy();
        }
        // The gates must be readable by an unprivileged process, or they fail open on
        // every non-admin host.
        let _ = src.hklm_dword(WINHTTP_POLICY, "DisableWpad");
        assert_ne!(
            src.service_state(AUTOPROXY_SERVICE),
            ServiceState::Absent,
            "WinHttpAutoProxySvc is registered on every supported Windows"
        );
        assert_eq!(
            src.service_state("openlatch-no-such-service-exists"),
            ServiceState::Absent
        );
    }
}