mise-util 2026.11.14

Environment, directory, and filesystem helpers shared by mise's crates
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
use super::*;

#[tokio::test(flavor = "multi_thread")]
async fn test_github_oauth_401_refreshes_and_retries_once() {
    let (port, count, requests) = spawn_recording_server(vec![
        unauthorized_response(),
        github_oauth_token_response(),
        json_empty_array_response(),
    ])
    .await;
    let server_url = format!("http://127.0.0.1:{port}");
    let dir = tempfile::tempdir().unwrap();
    let cache_path = dir.path().join("github-oauth-tokens.toml");
    let _guard = set_test_github_oauth(&server_url, cache_path.clone());
    seed_github_oauth_cache(&cache_path);

    let mut headers = HeaderMap::new();
    headers.insert(AUTHORIZATION, HeaderValue::from_static("Bearer ghu-stale"));
    let client = Client::new(Duration::from_secs(3), ClientKind::Http).unwrap();
    let text = client
        .get_text_request(format!("{server_url}/api/v3/repos/owner/repo/releases"))
        .headers(&headers)
        .send()
        .await
        .unwrap_or_else(|err| {
            let requests = requests.lock().unwrap();
            panic!(
                "request failed: {err:#}\nrequests:\n{}",
                requests.join("\n---\n")
            );
        });

    assert_eq!(text, "[]");
    assert_eq!(count.load(std::sync::atomic::Ordering::SeqCst), 3);
    let requests = requests.lock().unwrap();
    let first_request = requests[0].to_ascii_lowercase();
    let refresh_request = requests[1].to_ascii_lowercase();
    let retry_request = requests[2].to_ascii_lowercase();
    assert!(first_request.contains("get /api/v3/repos/owner/repo/releases"));
    assert!(first_request.contains("authorization: bearer ghu-stale"));
    assert!(refresh_request.contains("post /login/oauth/access_token"));
    assert!(retry_request.contains("get /api/v3/repos/owner/repo/releases"));
    assert!(retry_request.contains("authorization: bearer ghu-refreshed"));
    let cache = std::fs::read_to_string(cache_path).unwrap();
    assert!(cache.contains("ghu-refreshed"));
}

#[tokio::test(flavor = "multi_thread")]
async fn test_github_oauth_401_reports_refreshed_token_source() {
    let (port, count, _requests) = spawn_recording_server(vec![
        unauthorized_response(),
        github_oauth_token_response(),
        unauthorized_response(),
    ])
    .await;
    let server_url = format!("http://127.0.0.1:{port}");
    let dir = tempfile::tempdir().unwrap();
    let cache_path = dir.path().join("github-oauth-tokens.toml");
    let _guard = set_test_github_oauth(&server_url, cache_path.clone());
    seed_github_oauth_cache(&cache_path);

    let mut headers = HeaderMap::new();
    headers.insert(AUTHORIZATION, HeaderValue::from_static("Bearer ghu-stale"));
    let client = Client::new(Duration::from_secs(3), ClientKind::Http).unwrap();
    let err = client
        .get_text_request(format!("{server_url}/api/v3/repos/owner/repo/releases"))
        .headers(&headers)
        .send()
        .await
        .unwrap_err();
    let msg = format!("{err:?}");

    assert_eq!(count.load(std::sync::atomic::Ordering::SeqCst), 3);
    assert!(
        msg.contains("github auth: yes (token from GitHub OAuth)"),
        "{msg}"
    );
    assert!(
        msg.contains("token from GitHub OAuth was rejected by GitHub"),
        "{msg}"
    );
}

/// Drive a real request through the client so the whole chain is covered:
/// the 403 handler calling `is_github_rate_limited`, the marker reaching
/// `is_transient`, and the retry loop acting on it. Asserting on the
/// request count is the point — passing the flag to
/// `github_forbidden_report` by hand would still pass if the call site
/// stopped supplying it. `/api/v3/` makes the loopback host a GitHub API
/// URL, the same trick the OAuth tests use.
async fn send_github_403(response: &'static str, retries: i64) -> (Report, usize) {
    let attempts = retries as usize + 1;
    let (port, count) = spawn_canned_server(vec![response; 8]).await;
    let _guard = set_test_http_retries(retries);
    let client = Client::new(Duration::from_secs(3), ClientKind::Http).unwrap();
    let err = client
        .get_text_request(format!(
            "http://127.0.0.1:{port}/api/v3/repos/aubepkg/aube/contents/x.json"
        ))
        .send()
        .await
        .expect_err("403 should be an error");
    let seen = count.load(std::sync::atomic::Ordering::SeqCst);
    assert!(
        seen <= attempts,
        "server saw {seen} requests, more than the {attempts} allowed"
    );
    (err, seen)
}

/// An exhausted primary limit must be retried. GitHub reports it as 403,
/// which `is_transient`'s status check treats as deterministic, so without
/// the marker a rate limit fails on the first attempt.
#[tokio::test(flavor = "current_thread")]
async fn test_github_rate_limited_403_is_retried() {
    let (err, seen) = send_github_403(github_rate_limited_response(), 3).await;

    assert_eq!(seen, 4, "exhausted limit should be retried: {err:?}");
    assert!(is_transient(&err), "{err:?}");
    // The marker must not change what the user reads. The auth line is not
    // asserted on here: `github_forbidden_report` covers it.
    let msg = format!("{err:?}");
    assert!(
        msg.contains("github rate limit: 0/5000 (core), resets at 1789456621"),
        "{msg}"
    );
    assert!(
        msg.contains("API rate limit exceeded for installation"),
        "{msg}"
    );
}

/// The secondary-limit branch: quota remains, but `retry-after` says to
/// back off. Covered separately so neither detector can regress alone.
#[tokio::test(flavor = "current_thread")]
async fn test_github_secondary_rate_limited_403_is_retried() {
    let (err, seen) = send_github_403(github_secondary_rate_limited_response(), 2).await;

    assert_eq!(seen, 3, "secondary limit should be retried: {err:?}");
    assert!(is_transient(&err), "{err:?}");
    assert!(
        format!("{err:?}").contains("secondary rate limit"),
        "{err:?}"
    );
}

/// A 403 with quota left and no `retry-after` is a refusal, not a rate
/// limit. It must stay deterministic so mise does not spend the whole
/// backoff on something that cannot succeed.
#[tokio::test(flavor = "current_thread")]
async fn test_github_forbidden_with_quota_left_is_not_retried() {
    let (err, seen) = send_github_403(github_forbidden_response(), 3).await;

    assert_eq!(seen, 1, "a refusal should not be retried: {err:?}");
    assert!(!is_transient(&err), "{err:?}");
}

#[tokio::test(flavor = "current_thread")]
async fn test_github_forbidden_report_includes_body_and_auth_state() {
    let (port, _count) = spawn_canned_server(vec![github_forbidden_response()]).await;
    let url = format!("http://127.0.0.1:{port}/repos/microsoft/edit/releases");
    let resp = reqwest::Client::new().get(url).send().await.unwrap();
    let rate_limit = github_rate_limit_summary(&resp);
    let status_error = resp
        .error_for_status_ref()
        .expect_err("403 response should be an error");
    let body = resp.text().await.unwrap();
    let err = github_forbidden_report(status_error, true, rate_limit, false, &body);
    let msg = format!("{err:?}");

    assert!(msg.contains("github auth: yes"));
    assert!(msg.contains("github rate limit: 42/5000 (core), resets at 1781337353"));
    assert!(msg.contains(r#"{"message":"secondary rate limit","docs":"url"}"#));
}

#[tokio::test(flavor = "current_thread")]
async fn test_github_unauthorized_report_names_token_source() {
    // env var known → the message names it and includes the token-guide hint.
    let (port, _count) = spawn_canned_server(vec![unauthorized_response()]).await;
    let url = format!("http://127.0.0.1:{port}/repos/owner/repo/releases");
    let resp = reqwest::Client::new().get(url).send().await.unwrap();
    let status_error = resp
        .error_for_status_ref()
        .expect_err("401 response should be an error");
    let body = resp.text().await.unwrap();
    let err = github_unauthorized_report(
        status_error,
        true,
        Some(&crate::github::TokenSource::EnvVar("GITHUB_TOKEN")),
        &body,
    );
    let msg = format!("{err:?}");

    assert!(
        msg.contains("github auth: yes (token from GITHUB_TOKEN)"),
        "{msg}"
    );
    assert!(msg.contains("Bad credentials"), "{msg}");
    assert!(
        msg.contains("token in `GITHUB_TOKEN` was rejected by GitHub (401 Unauthorized)"),
        "{msg}"
    );
    assert!(msg.contains("github-tokens.html"), "{msg}");
}

#[tokio::test(flavor = "current_thread")]
async fn test_github_unauthorized_report_names_non_env_token_sources() {
    let sources = [
        (crate::github::TokenSource::TokensFile, "github_tokens.toml"),
        (crate::github::TokenSource::GhCli, "gh CLI (hosts.yml)"),
        (
            crate::github::TokenSource::CredentialCommand,
            "credential_command",
        ),
        (crate::github::TokenSource::GithubOauth, "GitHub OAuth"),
        (
            crate::github::TokenSource::GitCredential,
            "git credential fill",
        ),
    ];
    let (port, _count) = spawn_canned_server(vec![unauthorized_response(); sources.len()]).await;
    let url = format!("http://127.0.0.1:{port}/repos/owner/repo/releases");

    for (source, label) in sources {
        let resp = reqwest::Client::new().get(&url).send().await.unwrap();
        let status_error = resp.error_for_status_ref().unwrap_err();
        let body = resp.text().await.unwrap();
        let msg = format!(
            "{:?}",
            github_unauthorized_report(status_error, true, Some(&source), &body)
        );

        assert!(
            msg.contains(&format!("github auth: yes (token from {label})")),
            "{msg}"
        );
        assert!(
            msg.contains(&format!("token from {label} was rejected by GitHub")),
            "{msg}"
        );
    }
}

#[tokio::test(flavor = "current_thread")]
async fn test_github_unauthorized_report_without_known_source() {
    // Token used but source unknown → generic auth "yes" and generic hint;
    // no token → auth "no" and no hint.
    let (port, _count) =
        spawn_canned_server(vec![unauthorized_response(), unauthorized_response()]).await;
    let url = format!("http://127.0.0.1:{port}/repos/owner/repo/releases");

    let resp = reqwest::Client::new().get(&url).send().await.unwrap();
    let status_error = resp.error_for_status_ref().unwrap_err();
    let body = resp.text().await.unwrap();
    let used_msg = format!(
        "{:?}",
        github_unauthorized_report(status_error, true, None, &body)
    );
    assert!(used_msg.contains("github auth: yes"), "{used_msg}");
    assert!(!used_msg.contains("token from"), "{used_msg}");
    assert!(used_msg.contains("configured GitHub token"), "{used_msg}");

    let resp = reqwest::Client::new().get(&url).send().await.unwrap();
    let status_error = resp.error_for_status_ref().unwrap_err();
    let body = resp.text().await.unwrap();
    let anon_msg = format!(
        "{:?}",
        github_unauthorized_report(status_error, false, None, &body)
    );
    assert!(anon_msg.contains("github auth: no"), "{anon_msg}");
    assert!(!anon_msg.contains("hint:"), "{anon_msg}");
}

#[tokio::test(flavor = "current_thread")]
async fn test_github_unauthorized_report_ignores_source_when_no_auth_sent() {
    // A GitHub token env var may be present in the process even when this
    // request sent no Authorization header; it must not be reported as used.
    let (port, _count) = spawn_canned_server(vec![unauthorized_response()]).await;
    let url = format!("http://127.0.0.1:{port}/repos/owner/repo/releases");
    let resp = reqwest::Client::new().get(url).send().await.unwrap();
    let status_error = resp.error_for_status_ref().unwrap_err();
    let body = resp.text().await.unwrap();
    let msg = format!(
        "{:?}",
        github_unauthorized_report(
            status_error,
            false,
            Some(&crate::github::TokenSource::EnvVar("GITHUB_TOKEN")),
            &body
        )
    );

    assert!(msg.contains("github auth: no"), "{msg}");
    assert!(!msg.contains("token from"), "{msg}");
    assert!(!msg.contains("hint:"), "{msg}");
}

#[tokio::test(flavor = "current_thread")]
async fn test_read_bounded_error_body_caps_large_body() {
    // An oversized error body must be truncated during reading, not buffered
    // whole, so a hostile endpoint can't exhaust memory.
    let big_body = "x".repeat(MAX_ERROR_BODY_BYTES + 4096);
    let raw = format!(
        "HTTP/1.1 401 Unauthorized\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}",
        big_body.len(),
        big_body
    );
    let leaked: &'static str = Box::leak(raw.into_boxed_str());
    let (port, _count) = spawn_canned_server(vec![leaked]).await;
    let url = format!("http://127.0.0.1:{port}/repos/owner/repo/releases");
    let resp = reqwest::Client::new().get(url).send().await.unwrap();

    let body = read_bounded_error_body(resp, Duration::from_secs(30)).await;
    assert_eq!(body.len(), MAX_ERROR_BODY_BYTES);
}

#[tokio::test(flavor = "current_thread")]
async fn test_read_bounded_error_body_honors_deadline() {
    // A response body that trickles forever (staying under the byte cap and
    // the idle read_timeout) must still be abandoned at the deadline instead
    // of blocking indefinitely.
    use tokio::io::{AsyncReadExt, AsyncWriteExt};
    let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
    let port = listener.local_addr().unwrap().port();
    tokio::spawn(async move {
        if let Ok((mut sock, _)) = listener.accept().await {
            // Read the request first: a response sent before the client has
            // written its request is an `UnexpectedMessage` to hyper.
            let mut buf = [0u8; 1024];
            let _ = sock.read(&mut buf).await;
            // No Content-Length + `close` → body is read until EOF, which the
            // server never sends; it just trickles one byte at a time.
            let _ = sock
                .write_all(b"HTTP/1.1 401 Unauthorized\r\nConnection: close\r\n\r\n")
                .await;
            loop {
                if sock.write_all(b"x").await.is_err() {
                    break;
                }
                tokio::time::sleep(Duration::from_millis(20)).await;
            }
        }
    });
    let url = format!("http://127.0.0.1:{port}/repos/owner/repo/releases");
    let resp = reqwest::Client::new().get(url).send().await.unwrap();

    let start = tokio::time::Instant::now();
    let body = read_bounded_error_body(resp, Duration::from_millis(150)).await;
    assert!(
        start.elapsed() < Duration::from_secs(5),
        "read must stop at the deadline"
    );
    assert!(
        body.is_empty(),
        "timed-out read yields no body, got {body:?}"
    );
}

#[test]
fn test_netrc_should_apply_treats_netrc_as_fallback() {
    // No existing auth → netrc fills in (normal fallback).
    assert!(netrc_should_apply(false, false));
    // Explicit auth (e.g. forge token) on a same-host request →
    // netrc must NOT clobber it. This is the regression guard for
    // private GitHub release-asset downloads where a netrc github
    // entry was overriding the resolved Bearer token.
    assert!(!netrc_should_apply(false, true));
    // Host changed via URL replacement → existing auth was built for the
    // original host, so netrc (scoped to the new host) wins.
    assert!(netrc_should_apply(true, true));
    assert!(netrc_should_apply(true, false));
}

fn basic_netrc_headers() -> HeaderMap {
    let mut h = HeaderMap::new();
    h.insert(AUTHORIZATION, HeaderValue::from_static("Basic bmV0cmM="));
    h
}

fn auth_value(headers: &HeaderMap) -> Vec<String> {
    headers
        .get_all(AUTHORIZATION)
        .iter()
        .map(|v| v.to_str().unwrap().to_string())
        .collect()
}

#[test]
fn test_apply_netrc_keeps_forge_token_on_un_redirected_url() {
    // Regression: a netrc entry for api.github.com must NOT override the
    // Bearer forge token when the URL was not rewritten. Previously this
    // clobbered the token and broke private release-asset downloads.
    let url: Url = "https://api.github.com/repos/o/r/releases/assets/1"
        .parse()
        .unwrap();
    let mut headers = HeaderMap::new();
    headers.insert(
        AUTHORIZATION,
        HeaderValue::from_static("Bearer forge-token"),
    );

    let out = apply_netrc_credentials(headers, &url, &url, basic_netrc_headers());
    // Exactly one Authorization header, still the forge token.
    assert_eq!(auth_value(&out), vec!["Bearer forge-token".to_string()]);
}

#[test]
fn test_apply_netrc_fills_in_when_no_existing_auth() {
    let url: Url = "https://example.com/file".parse().unwrap();
    let out = apply_netrc_credentials(HeaderMap::new(), &url, &url, basic_netrc_headers());
    assert_eq!(auth_value(&out), vec!["Basic bmV0cmM=".to_string()]);
}

#[test]
fn test_apply_netrc_overrides_existing_auth_when_url_redirected() {
    // #7164 use case: a URL replacement redirected the request to a
    // private mirror. The pre-existing auth header was built for the
    // original host, so netrc (scoped to the new host) must win — and
    // replace, not duplicate, the Authorization header.
    let original: Url = "https://public.example.com/file".parse().unwrap();
    let redirected: Url = "https://mirror.internal/file".parse().unwrap();
    let mut headers = HeaderMap::new();
    headers.insert(AUTHORIZATION, HeaderValue::from_static("Bearer stale"));

    let out = apply_netrc_credentials(headers, &original, &redirected, basic_netrc_headers());
    assert_eq!(auth_value(&out), vec!["Basic bmV0cmM=".to_string()]);
}

#[test]
fn test_cross_host_replacement_clears_credentials_without_netrc() {
    let original: Url = "https://user:password@public.example.com/file"
        .parse()
        .unwrap();
    let mut redirected: Url = "https://user:password@mirror.internal/file"
        .parse()
        .unwrap();
    let mut headers = HeaderMap::new();
    headers.insert(AUTHORIZATION, HeaderValue::from_static("Bearer stale"));
    headers.insert("x-api-key", HeaderValue::from_static("secret"));
    headers.insert("x-request-id", HeaderValue::from_static("keep-me"));

    clear_cross_host_credentials(&mut headers, &original, &mut redirected);

    assert!(!headers.contains_key(AUTHORIZATION));
    assert!(!headers.contains_key("x-api-key"));
    assert_eq!(headers["x-request-id"], "keep-me");
    assert!(redirected.username().is_empty());
    assert!(redirected.password().is_none());
}

#[test]
fn test_apply_netrc_keeps_forge_token_on_same_host_path_rewrite() {
    // A URL replacement that only rewrites the path/query on the SAME host
    // must not let netrc override the forge token: the token is still valid
    // for that host, and netrc is host-scoped anyway.
    let original: Url = "https://github.com/o/r/releases/download/v1/f.tar.gz"
        .parse()
        .unwrap();
    let rewritten: Url = "https://github.com/o/r/releases/download/v1/f-linux.tar.gz"
        .parse()
        .unwrap();
    let mut headers = HeaderMap::new();
    headers.insert(
        AUTHORIZATION,
        HeaderValue::from_static("Bearer forge-token"),
    );

    let out = apply_netrc_credentials(headers, &original, &rewritten, basic_netrc_headers());
    assert_eq!(auth_value(&out), vec!["Bearer forge-token".to_string()]);
}

#[test]
fn test_rejects_credentials_on_https_to_http_replacement() {
    let original: Url = "https://public.example.com/file".parse().unwrap();
    let rewritten: Url = "http://mirror.internal/file".parse().unwrap();
    let mut headers = HeaderMap::new();
    headers.insert(AUTHORIZATION, HeaderValue::from_static("Bearer secret"));

    let err = ensure_secure_replacement_credentials(&original, &rewritten, &headers).unwrap_err();
    assert!(err.to_string().contains("refusing to send credentials"));
    let mut cookie_headers = HeaderMap::new();
    cookie_headers.insert(COOKIE, HeaderValue::from_static("session=secret"));
    assert!(ensure_secure_replacement_credentials(&original, &rewritten, &cookie_headers).is_err());
    let mut api_key_headers = HeaderMap::new();
    api_key_headers.insert("x-api-key", HeaderValue::from_static("secret"));
    assert!(
        ensure_secure_replacement_credentials(&original, &rewritten, &api_key_headers).is_err()
    );
    let rewritten_with_credentials: Url =
        "http://user:password@mirror.internal/file".parse().unwrap();
    assert!(
        ensure_secure_replacement_credentials(
            &original,
            &rewritten_with_credentials,
            &HeaderMap::new(),
        )
        .is_err()
    );
    assert!(
        ensure_secure_replacement_credentials(&original, &rewritten, &HeaderMap::new()).is_ok()
    );
    assert!(
        ensure_secure_replacement_credentials(
            &"http://public.example.com/file".parse().unwrap(),
            &rewritten,
            &headers,
        )
        .is_ok()
    );
}

#[test]
fn unscoped_credential_detection_ignores_headers_reqwest_already_strips() {
    let mut headers = HeaderMap::new();
    headers.insert(AUTHORIZATION, HeaderValue::from_static("Bearer secret"));
    headers.insert(COOKIE, HeaderValue::from_static("session=secret"));
    headers.insert("x-request-id", HeaderValue::from_static("keep-me"));
    assert!(!has_unscoped_credential(&headers));

    headers.insert("x-api-key", HeaderValue::from_static("secret"));
    assert!(has_unscoped_credential(&headers));

    ForwardRules::default().retain_for(
        &mut headers,
        &Url::parse("https://origin.test/").unwrap(),
        &Url::parse("https://elsewhere.test/").unwrap(),
    );
    assert!(!headers.contains_key(AUTHORIZATION));
    assert!(!headers.contains_key("x-api-key"));
    assert_eq!(headers["x-request-id"], "keep-me");
}

#[test]
fn user_headers_replace_host_auth_headers_instead_of_appending() {
    // `TextRequest::send` starts from the host's automatic token and extends it with
    // the caller's headers; the caller's `Authorization` must be the only one sent.
    let mut headers = HeaderMap::new();
    headers.insert(AUTHORIZATION, HeaderValue::from_static("Bearer automatic"));
    let mut user = HeaderMap::new();
    user.insert(AUTHORIZATION, HeaderValue::from_static("Bearer configured"));
    headers.extend(user);
    let values = headers.get_all(AUTHORIZATION).iter().collect::<Vec<_>>();
    assert_eq!(values, ["Bearer configured"]);
}

#[test]
fn header_digest_depends_on_values_without_exposing_them() {
    let mut a = HeaderMap::new();
    a.insert(AUTHORIZATION, HeaderValue::from_static("Bearer one"));
    let mut b = HeaderMap::new();
    b.insert(AUTHORIZATION, HeaderValue::from_static("Bearer two"));
    assert_ne!(header_digest(&a), header_digest(&b));
    assert_eq!(header_digest(&a), header_digest(&a.clone()));
    assert!(!header_digest(&a).contains("one"));
}

#[test]
fn forward_hosts_accept_exact_hosts_and_subdomain_wildcards_only() {
    for ok in ["cdn.example.com", "*.example.com", "localhost"] {
        assert!(is_valid_forward_host(ok), "{ok}");
    }
    for bad in [
        "",
        "*",
        "*.",
        "*.*.com",
        "a*.com",
        "example.com:443",
        "https://x.com",
        ".x.com",
        "x.com.",
    ] {
        assert!(!is_valid_forward_host(bad), "{bad}");
    }
    let patterns = vec![
        "cdn.example.com".to_string(),
        "*.assets.example.com".to_string(),
    ];
    assert!(host_matches_any(&patterns, "cdn.example.com"));
    assert!(host_matches_any(&patterns, "CDN.example.com"));
    let mixed = vec!["*.Assets.EXAMPLE.com".to_string()];
    assert!(host_matches_any(&mixed, "a.assets.example.com"));
    assert!(host_matches_any(&mixed, "A.ASSETS.example.com"));
    assert!(host_matches_any(&patterns, "a.assets.example.com"));
    assert!(host_matches_any(&patterns, "a.b.assets.example.com"));
    // A wildcard is for subdomains: neither the bare suffix nor a lookalike matches.
    assert!(!host_matches_any(&patterns, "assets.example.com"));
    assert!(!host_matches_any(&patterns, "evilassets.example.com"));
    assert!(!host_matches_any(&patterns, "cdn.example.com.evil.test"));
}

#[test]
fn forward_rules_keep_only_listed_headers_on_listed_https_hosts() {
    let key = HeaderName::from_static("x-api-key");
    let mut headers = HeaderMap::new();
    headers.insert(&key, HeaderValue::from_static("secret"));
    headers.insert("x-other-token", HeaderValue::from_static("secret"));
    headers.insert("x-request-id", HeaderValue::from_static("keep-me"));
    let (rule_name, rule_value) =
        forward_rule_header(&key, &["cdn.example.com".to_string()]).unwrap();
    headers.insert(rule_name, rule_value);

    let (mut real, rules) = split_forward_rules(&headers);

    // A retry sends the request again, so the rules must survive a round trip.
    let mut resent = real.clone();
    rules.attach_to(&mut resent);
    let (resent_real, resent_rules) = split_forward_rules(&resent);
    assert_eq!(resent_real, real);
    assert_eq!(resent_rules.0, rules.0);
    assert!(
        real.keys()
            .all(|name| !name.as_str().starts_with(FORWARD_RULE_PREFIX))
    );
    assert!(rules.applies_to(&real));

    // An unlisted host loses every credential, the listed header included.
    let from = Url::parse("https://origin.test/x").unwrap();
    let mut elsewhere = real.clone();
    rules.retain_for(
        &mut elsewhere,
        &from,
        &Url::parse("https://other.example.com/x").unwrap(),
    );
    assert!(!elsewhere.contains_key(&key) && !elsewhere.contains_key("x-other-token"));
    assert_eq!(elsewhere["x-request-id"], "keep-me");

    // A listed host over plain HTTP is refused after an HTTPS hop, but a chain that was
    // plain HTTP from the start may stay that way.
    let mut plain = real.clone();
    let plain_next = Url::parse("http://cdn.example.com/x").unwrap();
    rules.retain_for(&mut plain, &from, &plain_next);
    assert!(!plain.contains_key(&key));
    let mut http_chain = real.clone();
    rules.retain_for(
        &mut http_chain,
        &Url::parse("http://origin.test/x").unwrap(),
        &plain_next,
    );
    assert_eq!(http_chain["x-api-key"], "secret");

    // Only the listed header reaches a listed HTTPS host.
    rules.retain_for(
        &mut real,
        &from,
        &Url::parse("https://cdn.example.com/x").unwrap(),
    );
    assert_eq!(real["x-api-key"], "secret");
    assert!(!real.contains_key("x-other-token"));
}

#[test]
fn with_host_auth_layers_configured_headers_over_automatic_ones() {
    let url = Url::parse("https://example.com/file").unwrap();
    let mut user = HeaderMap::new();
    user.insert(AUTHORIZATION, HeaderValue::from_static("Bearer configured"));
    user.insert("x-extra", HeaderValue::from_static("1"));
    let merged = with_host_auth(&url, &user).unwrap();
    assert_eq!(merged.get_all(AUTHORIZATION).iter().count(), 1);
    assert_eq!(merged[AUTHORIZATION], "Bearer configured");
    assert_eq!(merged["x-extra"], "1");
}

#[test]
fn a_raw_content_404_with_a_token_is_retried_without_it() {
    let raw = Url::parse("https://raw.githubusercontent.com/o/r/abc/SKILL.md").unwrap();
    let mut with_token = HeaderMap::new();
    with_token.insert(AUTHORIZATION, HeaderValue::from_static("Bearer ghp_stale"));

    assert_eq!(
        raw_content_token_to_drop(&raw, StatusCode::NOT_FOUND, &with_token),
        Some("ghp_stale")
    );
    // Only a 404, only with a token, and only on raw.githubusercontent.com:
    // the API's 401 has its own report, and other hosts' 404s are real.
    assert_eq!(
        raw_content_token_to_drop(&raw, StatusCode::OK, &with_token),
        None
    );
    assert_eq!(
        raw_content_token_to_drop(&raw, StatusCode::NOT_FOUND, &HeaderMap::new()),
        None
    );
    let api = Url::parse("https://api.github.com/repos/o/r/contents/SKILL.md").unwrap();
    assert_eq!(
        raw_content_token_to_drop(&api, StatusCode::NOT_FOUND, &with_token),
        None
    );
    let other = Url::parse("https://example.com/o/r/abc/SKILL.md").unwrap();
    assert_eq!(
        raw_content_token_to_drop(&other, StatusCode::NOT_FOUND, &with_token),
        None
    );

    let msg = rejected_raw_token_warning(Some(&crate::github::TokenSource::EnvVar("GITHUB_TOKEN")));
    assert!(
        msg.contains("did not accept the token in `GITHUB_TOKEN`"),
        "{msg}"
    );
    assert!(msg.contains("mise token github"), "{msg}");
    assert!(
        rejected_raw_token_warning(None).contains("configured GitHub token"),
        "{}",
        rejected_raw_token_warning(None)
    );
}

const NOT_FOUND_RESPONSE: &str =
    "HTTP/1.1 404 Not Found\r\nContent-Length: 0\r\nConnection: close\r\n\r\n";
const SKILL_RESPONSE: &str = "HTTP/1.1 200 OK\r\nContent-Type: text/plain\r\nContent-Length: 6\r\nConnection: close\r\n\r\nskill\n";

/// A client that sends raw.githubusercontent.com to the local test server.
/// The server speaks plain HTTP, which is why the retry matches the host
/// whatever the scheme.
fn raw_content_client(port: u16) -> Client {
    let timeout = Duration::from_secs(3);
    // Downloads ask for `identity` and go through the undecoded client, which
    // must resolve the host to the test server as well.
    let resolved = |decode: bool| {
        Client::_new_with(decode)
            .no_proxy()
            .resolve(
                "raw.githubusercontent.com",
                std::net::SocketAddr::from(([127, 0, 0, 1], port)),
            )
            .read_timeout(timeout)
            .connect_timeout(timeout)
            .build()
            .unwrap()
    };
    Client {
        reqwest: Ok(resolved(true)),
        manual_redirects: Default::default(),
        undecoded: std::sync::OnceLock::from(Ok(resolved(false))),
        undecoded_manual_redirects: Default::default(),
        timeout,
        read_timeout: Some(timeout),
        downgrade: Downgrade::Refuse,
        kind: ClientKind::Http,
    }
}

async fn get_raw_content_with_token(
    responses: Vec<&'static str>,
) -> (
    Result<String>,
    usize,
    std::sync::Arc<std::sync::Mutex<Vec<String>>>,
) {
    let (port, count, requests) = spawn_recording_server(responses).await;
    let mut headers = HeaderMap::new();
    headers.insert(AUTHORIZATION, HeaderValue::from_static("Bearer ghp-stale"));
    let result = raw_content_client(port)
        .get_text_request(format!(
            "http://raw.githubusercontent.com:{port}/o/r/abc/SKILL.md"
        ))
        .headers(&headers)
        .send()
        .await;
    (
        result,
        count.load(std::sync::atomic::Ordering::SeqCst),
        requests,
    )
}

#[tokio::test(flavor = "multi_thread")]
async fn a_raw_content_404_is_fetched_again_without_the_token() {
    let (result, count, requests) =
        get_raw_content_with_token(vec![NOT_FOUND_RESPONSE, SKILL_RESPONSE, SKILL_RESPONSE]).await;

    assert_eq!(result.unwrap(), "skill\n");
    assert_eq!(count, 2);
    let requests = requests.lock().unwrap();
    assert!(
        requests[0]
            .to_ascii_lowercase()
            .contains("authorization: bearer ghp-stale"),
        "{}",
        requests[0]
    );
    assert!(
        !requests[1].to_ascii_lowercase().contains("authorization:"),
        "{}",
        requests[1]
    );
}

#[tokio::test(flavor = "multi_thread")]
async fn a_raw_content_404_without_the_token_is_still_a_404() {
    let (result, count, requests) = get_raw_content_with_token(vec![NOT_FOUND_RESPONSE; 6]).await;

    let err = result.unwrap_err();
    assert!(format!("{err:#}").contains("404"), "{err:#}");
    // One request with the token and one without; neither the outer retry
    // loop nor the retry itself sends the token, or anything, again.
    assert_eq!(count, 2);
    let requests = requests.lock().unwrap();
    assert!(
        !requests[1].to_ascii_lowercase().contains("authorization:"),
        "{}",
        requests[1]
    );
}

#[tokio::test(flavor = "multi_thread")]
async fn a_download_retry_after_a_raw_content_404_leaves_the_token_out() {
    let _guard = set_test_http_retries(1);
    let (port, count, requests) = spawn_recording_server(vec![
        NOT_FOUND_RESPONSE,
        truncated_download_response(),
        resumed_download_response(),
    ])
    .await;
    let dir = tempfile::tempdir().unwrap();
    let destination = dir.path().join("artifact");
    let mut headers = HeaderMap::new();
    headers.insert(AUTHORIZATION, HeaderValue::from_static("Bearer ghp-stale"));

    raw_content_client(port)
        .download_file_with_headers(
            format!("http://raw.githubusercontent.com:{port}/o/r/abc/artifact"),
            &destination,
            &headers,
            None,
        )
        .await
        .unwrap();

    assert_eq!(std::fs::read(&destination).unwrap(), b"helloworld");
    assert_eq!(count.load(std::sync::atomic::Ordering::SeqCst), 3);
    let requests = requests.lock().unwrap();
    assert!(
        requests[0]
            .to_ascii_lowercase()
            .contains("authorization: bearer ghp-stale"),
        "{}",
        requests[0]
    );
    // The truncated body fails the first attempt; the resumed one keeps its
    // range headers but not the token GitHub already turned down.
    let resumed = requests[2].to_ascii_lowercase();
    assert!(!requests[1].to_ascii_lowercase().contains("authorization:"));
    assert!(!resumed.contains("authorization:"), "{resumed}");
    assert!(resumed.contains("range: bytes=5-"), "{resumed}");
    assert!(resumed.contains("if-range: \"artifact-v1\""), "{resumed}");
}