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
//! `auth = "auto"`: decide once, before any client exists.
//!
//! reqwest treats a 407 as terminal, so a proxy's authentication scheme cannot be
//! discovered *reactively* — by the time the challenge arrives, the request has already
//! failed. It therefore has to be discovered proactively, and exactly once.
//!
//! ## Why this is async and separate, and why `build_client` is not
//!
//! `build_client` is called from several async tasks during daemon start-up
//! (`daemon/mod.rs`, `worker.rs`) and from every CLI command. Probing inside it would mean a
//! network round trip and a keychain read **per client**, on runtime threads, several times
//! per process. So `build_client` stays synchronous and pure — no network, no keychain — and
//! this runs once, before the first client is built, concretising `auth: Auto` into a real
//! scheme and parking the resolved password on the config that every later `build_client`
//! reads.
//!
//! ## The prime invariant
//!
//! **A network state never fails start-up.** Every probe outcome below, including every
//! failure, produces a config a client can be built from. A proxy that is down, a TLS error,
//! a truncated response, a timeout — each becomes [`ProbeOutcome::Undetermined`] plus a
//! warning that `doctor` renders, and the request fails later with its own `OL-122x` at the
//! moment it is actually attempted. The alternative — refusing to start because a proxy was
//! briefly unreachable — turns a transient network condition into an outage.
//!
//! ## What is probed, and what is not
//!
//! | Configuration | Probe |
//! | ------------- | ----- |
//! | `auth = "basic" \| "negotiate" \| "none"` | none — explicit wins |
//! | `mode = "direct"`, or no proxy URL | none — there is nothing to authenticate to |
//! | `socks5://` / `socks5h://` proxy | **none** — SOCKS has no HTTP challenge, and writing HTTP text at a SOCKS listener is a protocol error, not a probe |
//! | `http://` / `https://` proxy, `auth = "auto"` | one credential-less `CONNECT`, bounded |

use std::time::Duration;

use tokio::io::{AsyncReadExt, AsyncWriteExt};
use tokio::net::TcpStream;

use super::config::{EgressConfig, ProxyAuth, ProxyMode};
use super::credentials::{self, ProxyCredentialFile};

/// Connect deadline for the probe. Short on purpose: this runs before the daemon serves
/// anything, and a slow answer is the same as no answer for the decision being made.
const PROBE_CONNECT_TIMEOUT: Duration = Duration::from_secs(3);
/// Deadline for the proxy's response head.
const PROBE_READ_TIMEOUT: Duration = Duration::from_secs(3);
/// Ceiling on that head.
const PROBE_MAX_HEAD: usize = 8 * 1024;

/// What the one probe found.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ProbeOutcome {
    /// Not run: explicit `auth`, no proxy, or a SOCKS route.
    Skipped,
    /// `200` — the proxy tunnels without credentials.
    Open,
    /// `407`, with the schemes it offered (lowercased).
    Challenged(Vec<String>),
    /// The probe could not reach a conclusion. **Never a start-up failure.**
    Undetermined,
}

/// The concretized authentication decision, plus how it was reached.
#[derive(Debug, Clone)]
pub struct ResolvedAuth {
    /// The scheme to present. Never `Auto` — that is what this resolves.
    pub scheme: ProxyAuth,
    /// What the probe found.
    pub probe: ProbeOutcome,
    /// Whether a password was found for this authority, and where. Provenance only.
    pub password_source: Option<credentials::PasswordSource>,
    /// A degradation worth surfacing in `doctor`. Present exactly when something did not go
    /// to plan and the client was built anyway.
    pub warning: Option<String>,
}

/// Resolve `auth = "auto"` and the proxy password, once, before any client is built.
///
/// `api_url` is the configured platform URL: the probe uses its **actual** host and
/// effective port rather than a hard-coded `:443`, because a development deployment on a
/// custom port or plain HTTP is legal and probing the wrong destination would answer a
/// question nobody asked.
///
/// `credentials` is the encrypted file tier; `None` skips it (env and keychain still run).
///
/// Takes and returns [`EgressConfig`] so no `build_client` call site has to change.
pub async fn resolve_auth(
    mut cfg: EgressConfig,
    api_url: Option<&str>,
    credentials_file: Option<&ProxyCredentialFile>,
) -> EgressConfig {
    // Nothing to authenticate to.
    if cfg.mode == ProxyMode::Direct || cfg.url.is_none() {
        cfg.resolved = Some(ResolvedAuth {
            scheme: if cfg.auth == ProxyAuth::Auto {
                ProxyAuth::None
            } else {
                cfg.auth
            },
            probe: ProbeOutcome::Skipped,
            password_source: None,
            warning: None,
        });
        if cfg.auth == ProxyAuth::Auto {
            cfg.auth = ProxyAuth::None;
        }
        return cfg;
    }

    let url = cfg.url.clone().unwrap_or_default();
    let scheme = url
        .split_once("://")
        .map(|(s, _)| s.to_ascii_lowercase())
        .unwrap_or_default();

    // The credential ladder runs whatever the scheme: a SOCKS route authenticates with the
    // same username and password, through its own exchange rather than an HTTP header.
    let (password, password_source) = match cfg.proxy_authority() {
        Some(authority) => {
            match credentials::resolve_password(
                &authority,
                cfg.env_password.as_deref(),
                credentials_file,
            )
            .await
            {
                Some((secret, source)) => {
                    use secrecy::ExposeSecret;
                    (Some(secret.expose_secret().to_string()), Some(source))
                }
                None => (None, None),
            }
        }
        None => (None, None),
    };
    cfg.resolved_password = password;
    let have_credentials = cfg.proxy_password().is_some() && cfg.username.is_some();

    // Explicit beats discovered, always.
    if cfg.auth != ProxyAuth::Auto {
        cfg.resolved = Some(ResolvedAuth {
            scheme: cfg.auth,
            probe: ProbeOutcome::Skipped,
            password_source,
            warning: None,
        });
        return cfg;
    }

    // SOCKS never sees an HTTP probe: its listener speaks a binary protocol, and a CONNECT
    // line at it is a protocol error rather than an unanswered question.
    if scheme.starts_with("socks") {
        let chosen = if have_credentials {
            ProxyAuth::Basic
        } else {
            ProxyAuth::None
        };
        cfg.auth = chosen;
        cfg.resolved = Some(ResolvedAuth {
            scheme: chosen,
            probe: ProbeOutcome::Skipped,
            password_source,
            warning: None,
        });
        return cfg;
    }

    let outcome = probe(&url, &scheme, api_url).await;
    let (chosen, warning) = decide(&outcome, have_credentials, &cfg).await;
    cfg.auth = chosen;
    cfg.resolved = Some(ResolvedAuth {
        scheme: chosen,
        probe: outcome,
        password_source,
        warning,
    });
    cfg
}

/// Turn a probe outcome into the scheme to present, and a warning when one is owed.
async fn decide(
    outcome: &ProbeOutcome,
    have_credentials: bool,
    cfg: &EgressConfig,
) -> (ProxyAuth, Option<String>) {
    match outcome {
        ProbeOutcome::Open => (ProxyAuth::None, None),

        ProbeOutcome::Challenged(schemes) => {
            let offers_negotiate = schemes.iter().any(|s| s == "negotiate");
            let offers_basic = schemes.iter().any(|s| s == "basic");

            if offers_negotiate {
                match negotiate_viability(cfg).await {
                    Ok(()) => return (ProxyAuth::Negotiate, None),
                    // A ticket that will not mint is not an error here: it is a reason to
                    // use the other scheme the proxy offered. Returning OL-1229 at start-up
                    // would fail a host that has perfectly good Basic credentials.
                    Err(why) if offers_basic && have_credentials => {
                        return (
                            ProxyAuth::Basic,
                            Some(format!(
                                "the proxy offers Negotiate but this host cannot use it \
                                 ({why}); falling back to Basic"
                            )),
                        )
                    }
                    Err(why) => {
                        return (
                            ProxyAuth::None,
                            Some(format!(
                                "the proxy offers Negotiate and this host cannot use it \
                                 ({why}); no usable scheme remains"
                            )),
                        )
                    }
                }
            }

            if offers_basic {
                return if have_credentials {
                    (ProxyAuth::Basic, None)
                } else {
                    (
                        ProxyAuth::Basic,
                        Some(
                            "the proxy asks for Basic and no credential is stored for this \
                             authority; run 'openlatch proxy set'"
                                .to_string(),
                        ),
                    )
                };
            }

            // Only schemes this product refuses or does not implement. Recorded rather than
            // guessed at: requests then fail with OL-1223 naming what was offered.
            (
                ProxyAuth::None,
                Some(format!(
                    "the proxy offers only {} — none of which this client speaks (NTLM is \
                     deliberately not supported)",
                    schemes.join(", ")
                )),
            )
        }

        // The prime invariant: a network state produces a buildable client and a warning,
        // never a start-up failure.
        ProbeOutcome::Undetermined => (
            if have_credentials {
                ProxyAuth::Basic
            } else {
                ProxyAuth::None
            },
            Some(
                "could not determine the proxy's authentication scheme; continuing with \
                 whatever credentials are configured"
                    .to_string(),
            ),
        ),

        ProbeOutcome::Skipped => (ProxyAuth::None, None),
    }
}

/// Can this build and this host actually speak Negotiate to this proxy?
///
/// Viability is the whole first leg, not just "the feature is compiled in": the library has
/// to load and a token has to mint for this SPN. That is the difference between choosing
/// Negotiate and choosing a scheme that will fail on every request.
#[cfg(feature = "proxy-negotiate")]
async fn negotiate_viability(cfg: &EgressConfig) -> Result<(), String> {
    use super::negotiate::{platform_provider, StepResult};

    let spn = cfg
        .spn
        .clone()
        .or_else(|| {
            cfg.proxy_authority().map(|a| {
                format!(
                    "HTTP/{}",
                    a.rsplit_once(':').map_or(a.clone(), |(h, _)| h.to_string())
                )
            })
        })
        .unwrap_or_else(|| "HTTP/localhost".to_string());

    // The mint is blocking work on both platforms (SSPI calls into LSA, GSSAPI reads the
    // credential cache off disk), so it goes to a blocking thread rather than stalling the
    // runtime during start-up.
    tokio::task::spawn_blocking(move || {
        let factory = platform_provider().map_err(|e| e.to_string())?;
        let mut context = factory.new_provider(&spn).map_err(|e| e.to_string())?;
        match context.step(None) {
            StepResult::Continue(token) | StepResult::Done(Some(token)) if !token.is_empty() => {
                Ok(())
            }
            StepResult::Done(_) => Err("the security context produced no token".to_string()),
            StepResult::Failed(e) => Err(e.to_string()),
            StepResult::Continue(_) => {
                Err("the security context produced an empty token".to_string())
            }
        }
    })
    .await
    .unwrap_or_else(|e| Err(format!("the credential probe panicked: {e}")))
}

/// Without the feature there is no provider to be viable.
#[cfg(not(feature = "proxy-negotiate"))]
async fn negotiate_viability(_cfg: &EgressConfig) -> Result<(), String> {
    Err("this build does not include the proxy-negotiate feature".to_string())
}

/// One credential-less `CONNECT`, bounded in time and size.
async fn probe(url: &str, scheme: &str, api_url: Option<&str>) -> ProbeOutcome {
    let Some((host, port)) = proxy_host_port(url, scheme) else {
        return ProbeOutcome::Undetermined;
    };
    // The destination the product actually talks to, not a hard-coded :443. A deployment on
    // a custom port -- or on plain http, which config/mod.rs permits -- would otherwise be
    // probed against a destination it never uses.
    let target = api_url
        .and_then(target_authority)
        .unwrap_or_else(|| "app.openlatch.ai:443".to_string());

    // TLS to an https:// proxy needs the connector's TLS setup, which lives behind the
    // negotiate feature. A build without it cannot probe such a proxy without sending the
    // CONNECT in the clear, which is exactly what must not happen -- so it reports
    // Undetermined and the client is built from the configured credentials.
    if scheme == "https" && !cfg!(feature = "proxy-negotiate") {
        return ProbeOutcome::Undetermined;
    }

    let Ok(Ok(mut stream)) = tokio::time::timeout(
        PROBE_CONNECT_TIMEOUT,
        TcpStream::connect((host.as_str(), port)),
    )
    .await
    else {
        return ProbeOutcome::Undetermined;
    };

    #[cfg(feature = "proxy-negotiate")]
    if scheme == "https" {
        return probe_over_tls(stream, &host, &target).await;
    }

    match probe_exchange(&mut stream, &target).await {
        Some(outcome) => outcome,
        None => ProbeOutcome::Undetermined,
    }
}

#[cfg(feature = "proxy-negotiate")]
async fn probe_over_tls(stream: TcpStream, host: &str, target: &str) -> ProbeOutcome {
    let Ok(setup) = super::negotiate::TlsSetup::new(&EgressConfig::direct()) else {
        return ProbeOutcome::Undetermined;
    };
    let Ok(mut tls) = setup.connect_proxy(host, stream).await else {
        return ProbeOutcome::Undetermined;
    };
    probe_exchange(&mut tls, target)
        .await
        .unwrap_or(ProbeOutcome::Undetermined)
}

/// Write the credential-less CONNECT and classify the answer.
async fn probe_exchange<S>(stream: &mut S, target: &str) -> Option<ProbeOutcome>
where
    S: AsyncReadExt + AsyncWriteExt + Unpin,
{
    let request =
        format!("CONNECT {target} HTTP/1.1\r\nHost: {target}\r\nProxy-Connection: close\r\n\r\n");
    stream.write_all(request.as_bytes()).await.ok()?;
    stream.flush().await.ok()?;

    let head = tokio::time::timeout(PROBE_READ_TIMEOUT, read_head(stream))
        .await
        .ok()??;

    let mut headers = [httparse::EMPTY_HEADER; 32];
    let mut response = httparse::Response::new(&mut headers);
    response.parse(&head).ok()?;
    let status = response.code?;

    Some(match status {
        200 => ProbeOutcome::Open,
        407 => ProbeOutcome::Challenged(offered_schemes(&head)),
        // Any other status means the proxy is there but did not answer the question. That
        // is a state, not a scheme.
        _ => ProbeOutcome::Undetermined,
    })
}

async fn read_head<S>(stream: &mut S) -> Option<Vec<u8>>
where
    S: AsyncReadExt + Unpin,
{
    let mut head = Vec::with_capacity(256);
    let mut byte = [0u8; 1];
    loop {
        match stream.read(&mut byte).await {
            Ok(0) | Err(_) => return None,
            Ok(_) => {}
        }
        head.push(byte[0]);
        if head.ends_with(b"\r\n\r\n") || head.ends_with(b"\n\n") {
            return Some(head);
        }
        if head.len() >= PROBE_MAX_HEAD {
            return None;
        }
    }
}

/// The schemes a `407` offered, lowercased, in header order.
fn offered_schemes(head: &[u8]) -> Vec<String> {
    String::from_utf8_lossy(head)
        .lines()
        .skip(1)
        .filter_map(|line| {
            let (k, v) = line.split_once(':')?;
            if !k.trim().eq_ignore_ascii_case("proxy-authenticate") {
                return None;
            }
            v.split_whitespace().next().map(|s| s.to_ascii_lowercase())
        })
        .collect()
}

/// `(host, port)` for the proxy, with the scheme's default port filled in.
fn proxy_host_port(url: &str, scheme: &str) -> Option<(String, u16)> {
    let authority = credentials::authority_key(url)?;
    let (host, port) = authority.rsplit_once(':')?;
    let port = port.parse().ok().or(match scheme {
        "https" => Some(443),
        "http" => Some(80),
        _ => None,
    })?;
    Some((host.to_string(), port))
}

/// `host:port` for the configured platform URL — the probe's CONNECT target.
fn target_authority(api_url: &str) -> Option<String> {
    credentials::authority_key(api_url)
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::core::egress::config::{EnvSource, ProxyToml};
    use std::collections::HashMap;

    struct MapEnv(HashMap<String, String>);
    impl EnvSource for MapEnv {
        fn var(&self, key: &str) -> Option<String> {
            self.0.get(key).cloned()
        }
    }
    fn empty_env() -> MapEnv {
        MapEnv(HashMap::new())
    }

    fn cfg(toml: ProxyToml) -> EgressConfig {
        EgressConfig::resolve(Some(&toml), &empty_env(), 7443, 7444).expect("resolve")
    }

    #[tokio::test]
    async fn a_direct_configuration_is_resolved_without_a_probe() {
        let resolved = resolve_auth(EgressConfig::direct(), None, None).await;
        let auth = resolved.resolved.expect("a resolution is always recorded");
        assert_eq!(auth.probe, ProbeOutcome::Skipped);
        assert_eq!(auth.scheme, ProxyAuth::None);
        assert!(auth.warning.is_none());
    }

    #[tokio::test]
    async fn an_explicit_scheme_skips_the_probe_entirely() {
        // Explicit beats discovered. A probe here would be a network round trip whose
        // answer could not change anything.
        for (spelling, expected) in [
            ("basic", ProxyAuth::Basic),
            ("negotiate", ProxyAuth::Negotiate),
            ("none", ProxyAuth::None),
        ] {
            let resolved = resolve_auth(
                cfg(ProxyToml {
                    // Port 1 on loopback: if a probe ran, it would take a measurable amount
                    // of time to fail. It does not run.
                    url: Some("http://127.0.0.1:1".into()),
                    auth: Some(spelling.into()),
                    ..Default::default()
                }),
                None,
                None,
            )
            .await;
            let auth = resolved.resolved.expect("resolution");
            assert_eq!(auth.probe, ProbeOutcome::Skipped, "{spelling}");
            assert_eq!(auth.scheme, expected, "{spelling}");
        }
    }

    /// Writing an HTTP CONNECT line at a SOCKS listener is a protocol error, not a probe.
    #[tokio::test]
    async fn a_socks_route_is_never_probed() {
        let resolved = resolve_auth(
            cfg(ProxyToml {
                url: Some("socks5://127.0.0.1:1".into()),
                ..Default::default()
            }),
            None,
            None,
        )
        .await;
        let auth = resolved.resolved.expect("resolution");
        assert_eq!(auth.probe, ProbeOutcome::Skipped);
        assert_ne!(auth.scheme, ProxyAuth::Negotiate);
    }

    /// The prime invariant. A proxy that is not there must still produce a buildable client.
    #[tokio::test]
    async fn a_dead_proxy_yields_a_warning_and_a_buildable_client() {
        let listener = tokio::net::TcpListener::bind(("127.0.0.1", 0))
            .await
            .expect("bind");
        let port = listener.local_addr().expect("addr").port();
        drop(listener);

        let resolved = resolve_auth(
            cfg(ProxyToml {
                url: Some(format!("http://127.0.0.1:{port}")),
                ..Default::default()
            }),
            Some("https://app.openlatch.ai"),
            None,
        )
        .await;
        let auth = resolved.resolved.clone().expect("resolution");
        assert_eq!(auth.probe, ProbeOutcome::Undetermined);
        assert!(auth.warning.is_some(), "a degradation must be reported");
        assert_ne!(resolved.auth, ProxyAuth::Auto, "auto must be concretized");
        // The point of the invariant: a client still builds.
        super::super::build_client(super::super::Consumer::Auth, &resolved)
            .expect("a probe failure must never stop a client from being built");
    }

    #[test]
    fn the_probe_target_is_the_configured_api_url_not_a_hard_coded_443() {
        assert_eq!(
            target_authority("https://app.openlatch.ai").as_deref(),
            Some("app.openlatch.ai:443")
        );
        // A development deployment on plain http and a custom port is legal.
        assert_eq!(
            target_authority("http://localhost:8080").as_deref(),
            Some("localhost:8080")
        );
        assert_eq!(
            target_authority("https://platform.internal:8443").as_deref(),
            Some("platform.internal:8443")
        );
    }

    #[test]
    fn the_offered_schemes_are_read_from_every_challenge_header() {
        let head = b"HTTP/1.1 407 Proxy Authentication Required\r\n\
                     Proxy-Authenticate: Negotiate\r\n\
                     Proxy-Authenticate: NTLM\r\n\
                     Proxy-Authenticate: Basic realm=\"corp\"\r\n\r\n";
        assert_eq!(offered_schemes(head), vec!["negotiate", "ntlm", "basic"]);
    }

    #[tokio::test]
    async fn an_open_proxy_resolves_to_no_credentials() {
        let (scheme, warning) = decide(&ProbeOutcome::Open, true, &EgressConfig::direct()).await;
        assert_eq!(scheme, ProxyAuth::None);
        assert!(warning.is_none());
    }

    #[tokio::test]
    async fn basic_is_chosen_when_offered_and_a_credential_exists() {
        let offered = ProbeOutcome::Challenged(vec!["basic".into()]);
        let (scheme, warning) = decide(&offered, true, &EgressConfig::direct()).await;
        assert_eq!(scheme, ProxyAuth::Basic);
        assert!(warning.is_none());

        // Offered but nothing stored: still Basic, and the operator is told what to do.
        let (scheme, warning) = decide(&offered, false, &EgressConfig::direct()).await;
        assert_eq!(scheme, ProxyAuth::Basic);
        assert!(warning.is_some_and(|w| w.contains("proxy set")));
    }

    /// A ticket that will not mint is a reason to use the *other* scheme the proxy offered,
    /// not a reason to fail. `EgressConfig::direct()` has no SPN and no ticket on any CI
    /// runner, which is exactly the unviable case.
    #[tokio::test]
    async fn an_unviable_negotiate_falls_through_to_basic_rather_than_failing() {
        let offered = ProbeOutcome::Challenged(vec!["negotiate".into(), "basic".into()]);
        let (scheme, warning) = decide(&offered, true, &EgressConfig::direct()).await;
        // On a host that CAN mint (a domain-joined Windows box), Negotiate is correct and
        // there is no warning. On one that cannot, Basic with a warning is correct. Both
        // outcomes are asserted; what must never happen is a hard failure.
        assert!(
            matches!(scheme, ProxyAuth::Negotiate | ProxyAuth::Basic),
            "expected a usable scheme, got {scheme:?}"
        );
        if scheme == ProxyAuth::Basic {
            assert!(warning.is_some_and(|w| w.contains("falling back to Basic")));
        }
    }

    /// NTLM-only: nothing usable, recorded rather than guessed at.
    #[tokio::test]
    async fn an_ntlm_only_challenge_resolves_to_no_scheme_and_names_why() {
        let offered = ProbeOutcome::Challenged(vec!["ntlm".into()]);
        let (scheme, warning) = decide(&offered, true, &EgressConfig::direct()).await;
        assert_eq!(scheme, ProxyAuth::None);
        let warning = warning.expect("a refusal must be explained");
        assert!(warning.contains("ntlm"), "{warning}");
        assert!(
            warning.contains("NTLM is deliberately not supported"),
            "{warning}"
        );
    }

    #[tokio::test]
    async fn an_undetermined_probe_uses_whatever_credentials_exist() {
        let (with, _) = decide(&ProbeOutcome::Undetermined, true, &EgressConfig::direct()).await;
        assert_eq!(with, ProxyAuth::Basic);
        let (without, warning) =
            decide(&ProbeOutcome::Undetermined, false, &EgressConfig::direct()).await;
        assert_eq!(without, ProxyAuth::None);
        assert!(warning.is_some());
    }
}