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
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
use crate::redactions::strip_url_credentials_in_arg;
use crate::tokens;
use crate::yaml::{self, Value};
use eyre::Result;
use heck::ToKebabCase;
use mise_settings::Settings;
use reqwest::IntoUrl;
use reqwest::header::HeaderMap;
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::fmt;
use std::path::PathBuf;
use std::sync::LazyLock as Lazy;
use tokio::sync::{RwLock, RwLockReadGuard};
use xx::regex;

use crate::cache::{CacheManager, CacheManagerBuilder};
use crate::{dirs, env};

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct GitlabRelease {
    pub tag_name: String,
    pub description: Option<String>,
    /// When GitLab stored the release. A release list an older mise cached
    /// has none.
    #[serde(default)]
    pub created_at: Option<String>,
    pub released_at: Option<String>,
    pub assets: GitlabAssets,
}

impl GitlabRelease {
    /// The time this release became public. GitLab's `released_at` is a date
    /// the publisher may set to anything, older than the release itself for
    /// a "historical release"; `created_at` is when GitLab stored it. The
    /// later of the two is used, so a backdated release is still as new as
    /// it is and an upcoming one (a future `released_at`) stays hidden until
    /// its date.
    pub fn published_at(&self) -> Option<&str> {
        let timestamp = |s: &str| s.parse::<jiff::Timestamp>().ok();
        match (self.created_at.as_deref(), self.released_at.as_deref()) {
            (Some(created), Some(released)) if timestamp(created) > timestamp(released) => {
                Some(created)
            }
            (created, released) => released.or(created),
        }
    }
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct GitlabTag {
    pub name: String,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct GitlabAssets {
    // pub count: i64,
    pub sources: Vec<GitlabAssetSource>,
    pub links: Vec<GitlabAssetLink>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct GitlabAssetSource {
    pub format: String,
    pub url: String,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct GitlabAssetLink {
    pub id: i64,
    pub name: String,
    pub url: String,
    pub direct_asset_url: String,
    pub link_type: String,
}

type CacheGroup<T> = HashMap<String, CacheManager<T>>;

static RELEASES_CACHE: Lazy<RwLock<CacheGroup<Vec<GitlabRelease>>>> = Lazy::new(Default::default);

static RELEASE_CACHE: Lazy<RwLock<CacheGroup<GitlabRelease>>> = Lazy::new(Default::default);

static TAGS_CACHE: Lazy<RwLock<CacheGroup<Vec<String>>>> = Lazy::new(Default::default);

static PROJECT_CACHE: Lazy<RwLock<CacheGroup<ProjectIdentity>>> = Lazy::new(Default::default);

/// What GitLab says a project path stands for now: the project's immutable
/// IDs and its current path. A moved project's old path answers with the new
/// path and the same `id`.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ProjectIdentity {
    /// The project's numeric ID, which no rename or transfer changes.
    pub id: String,
    /// `group/subgroup/project` as the project is called now.
    pub path_with_namespace: String,
    /// The numeric ID of the project's namespace.
    pub namespace_id: Option<String>,
}

#[derive(Debug, Deserialize)]
struct GitlabProjectIds {
    id: u64,
    path_with_namespace: String,
    namespace: Option<GitlabNamespace>,
}

#[derive(Debug, Deserialize)]
struct GitlabNamespace {
    id: u64,
}

/// The identity gitlab.com gives a project path now, following a move's
/// redirect. Cached like a release listing.
pub async fn project_identity(path: &str) -> Result<ProjectIdentity> {
    let key = format!(
        "{}-project-{}",
        path.to_kebab_case(),
        crate::hash::hash_to_str(&path)
    );
    PROJECT_CACHE
        .write()
        .await
        .entry(key.clone())
        .or_insert_with(|| {
            CacheManagerBuilder::new(cache_dir().join(format!("{key}.msgpack.z")))
                .with_fresh_duration(crate::network::fetch_remote_versions_cache(&Settings::get()))
                .build()
        });
    let caches = PROJECT_CACHE.read().await;
    let cache = caches.get(&key).unwrap();
    Ok(cache
        .get_or_try_init_async(async || {
            let url = format!("{API_URL}/projects/{}", urlencoding::encode(path));
            let headers = get_headers(&url, API_URL)?;
            let project: GitlabProjectIds = crate::http::HTTP_FETCH
                .json_with_headers(url, &headers)
                .await?;
            Ok(ProjectIdentity {
                id: project.id.to_string(),
                path_with_namespace: project.path_with_namespace,
                namespace_id: project.namespace.map(|n| n.id.to_string()),
            })
        })
        .await?
        .clone())
}

pub static API_URL: &str = "https://gitlab.com/api/v4";

/// Key of a persisted release, release-list or tag-list entry. Kebab-casing
/// alone is lossy (`group/a-b` and `group-a/b` come out the same), so the exact
/// parts are hashed in too, or one project's cached data would answer for
/// another's.
fn cache_key(parts: &[&str]) -> String {
    format!(
        "{}-{}",
        parts.join("-").to_kebab_case(),
        crate::hash::hash_to_str(&parts)
    )
}

pub static API_PATH: &str = "/api/v4";

async fn get_tags_cache(key: &str) -> RwLockReadGuard<'_, CacheGroup<Vec<String>>> {
    TAGS_CACHE
        .write()
        .await
        .entry(key.to_string())
        .or_insert_with(|| {
            CacheManagerBuilder::new(cache_dir().join(format!("{key}-tags.msgpack.z")))
                .with_fresh_duration(crate::network::fetch_remote_versions_cache(&Settings::get()))
                .build()
        });
    TAGS_CACHE.read().await
}

async fn get_releases_cache(key: &str) -> RwLockReadGuard<'_, CacheGroup<Vec<GitlabRelease>>> {
    RELEASES_CACHE
        .write()
        .await
        .entry(key.to_string())
        .or_insert_with(|| {
            CacheManagerBuilder::new(cache_dir().join(format!("{key}-releases.msgpack.z")))
                .with_fresh_duration(crate::network::fetch_remote_versions_cache(&Settings::get()))
                .build()
        });
    RELEASES_CACHE.read().await
}

async fn get_release_cache(key: &str) -> RwLockReadGuard<'_, CacheGroup<GitlabRelease>> {
    RELEASE_CACHE
        .write()
        .await
        .entry(key.to_string())
        .or_insert_with(|| {
            CacheManagerBuilder::new(cache_dir().join(format!("{key}.msgpack.z")))
                .with_fresh_duration(crate::network::fetch_remote_versions_cache(&Settings::get()))
                .build()
        });
    RELEASE_CACHE.read().await
}

#[allow(dead_code)]
pub async fn list_releases(repo: &str) -> Result<Vec<GitlabRelease>> {
    let key = cache_key(&[repo]);
    let cache = get_releases_cache(&key).await;
    let cache = cache.get(&key).unwrap();
    Ok(cache
        .get_or_try_init_async(async || {
            list_releases_(API_URL, repo, *env::MISE_LIST_ALL_VERSIONS).await
        })
        .await?
        .to_vec())
}

pub async fn list_releases_from_url(api_url: &str, repo: &str) -> Result<Vec<GitlabRelease>> {
    let key_api_url = strip_url_credentials_in_arg(api_url);
    let key = cache_key(&[&key_api_url, repo]);
    let cache = get_releases_cache(&key).await;
    let cache = cache.get(&key).unwrap();
    Ok(cache
        .get_or_try_init_async(async || {
            list_releases_(api_url, repo, *env::MISE_LIST_ALL_VERSIONS).await
        })
        .await?
        .to_vec())
}

/// `list_all` is `MISE_LIST_ALL_VERSIONS`, taken as an argument rather than read here so
/// tests can exercise the pagination loop: the env var is a process-wide `Lazy` that other
/// modules' tests have already forced by the time this one runs.
async fn list_releases_(api_url: &str, repo: &str, list_all: bool) -> Result<Vec<GitlabRelease>> {
    let mut url = format!(
        "{}/projects/{}/releases?per_page=100",
        api_url,
        urlencoding::encode(repo)
    );

    let headers = get_headers(&url, api_url)?;
    let (mut releases, mut headers) = crate::http::HTTP_FETCH
        .json_headers_with_headers::<Vec<GitlabRelease>, _>(&url, &headers)
        .await?;

    if list_all {
        while let Some(next) = next_page(&headers) {
            url = crate::http::resolve_pagination_url(&url, &next)?;
            // Re-derive auth for every page. `headers` holds the *response* headers of the
            // previous page at this point (that is how `next_page` reads `Link`), and
            // `json_headers_with_headers` bypasses the automatic host auth, so reusing it
            // would send page 2 onward unauthenticated. Same defect github had (#6318).
            headers = get_headers(&url, api_url)?;
            let (more, h) = crate::http::HTTP_FETCH
                .json_headers_with_headers::<Vec<GitlabRelease>, _>(&url, &headers)
                .await?;
            releases.extend(more);
            headers = h;
        }
    }

    Ok(releases)
}

#[allow(dead_code)]
pub async fn list_tags(repo: &str) -> Result<Vec<String>> {
    let key = cache_key(&[repo]);
    let cache = get_tags_cache(&key).await;
    let cache = cache.get(&key).unwrap();
    Ok(cache
        .get_or_try_init_async(async || {
            list_tags_(API_URL, repo, *env::MISE_LIST_ALL_VERSIONS).await
        })
        .await?
        .to_vec())
}

pub async fn list_tags_from_url(api_url: &str, repo: &str) -> Result<Vec<String>> {
    let key_api_url = strip_url_credentials_in_arg(api_url);
    let key = cache_key(&[&key_api_url, repo]);
    let cache = get_tags_cache(&key).await;
    let cache = cache.get(&key).unwrap();
    Ok(cache
        .get_or_try_init_async(async || {
            list_tags_(api_url, repo, *env::MISE_LIST_ALL_VERSIONS).await
        })
        .await?
        .to_vec())
}

/// See [`list_releases_`] for why `list_all` is a parameter.
async fn list_tags_(api_url: &str, repo: &str, list_all: bool) -> Result<Vec<String>> {
    let mut url = format!(
        "{}/projects/{}/repository/tags?per_page=100",
        api_url,
        urlencoding::encode(repo)
    );
    let headers = get_headers(&url, api_url)?;
    let (mut tags, mut headers) = crate::http::HTTP_FETCH
        .json_headers_with_headers::<Vec<GitlabTag>, _>(&url, &headers)
        .await?;

    if list_all {
        while let Some(next) = next_page(&headers) {
            url = crate::http::resolve_pagination_url(&url, &next)?;
            // Re-derive auth for every page — see the comment in `list_releases_`.
            headers = get_headers(&url, api_url)?;
            let (more, h) = crate::http::HTTP_FETCH
                .json_headers_with_headers::<Vec<GitlabTag>, _>(&url, &headers)
                .await?;
            tags.extend(more);
            headers = h;
        }
    }

    Ok(tags.into_iter().map(|t| t.name).collect())
}

#[allow(dead_code)]
pub async fn get_release(repo: &str, tag: &str) -> Result<GitlabRelease> {
    let key = cache_key(&[repo, tag]);
    let cache = get_release_cache(&key).await;
    let cache = cache.get(&key).unwrap();
    Ok(cache
        .get_or_try_init_async(async || get_release_(API_URL, repo, tag).await)
        .await?
        .clone())
}

pub async fn get_release_for_url(api_url: &str, repo: &str, tag: &str) -> Result<GitlabRelease> {
    let key_api_url = strip_url_credentials_in_arg(api_url);
    let key = cache_key(&[&key_api_url, repo, tag]);
    let cache = get_release_cache(&key).await;
    let cache = cache.get(&key).unwrap();
    Ok(cache
        .get_or_try_init_async(async || get_release_(api_url, repo, tag).await)
        .await?
        .clone())
}

async fn get_release_(api_url: &str, repo: &str, tag: &str) -> Result<GitlabRelease> {
    let url = format!(
        "{}/projects/{}/releases/{}",
        api_url,
        urlencoding::encode(repo),
        urlencoding::encode(tag)
    );
    let headers = get_headers(&url, api_url)?;
    crate::http::HTTP_FETCH
        .json_with_headers(url, &headers)
        .await
}

fn next_page(headers: &HeaderMap) -> Option<String> {
    let link = headers
        .get("link")
        .map(|l| l.to_str().unwrap_or_default().to_string())
        .unwrap_or_default();
    regex!(r#"<([^>]+)>; rel="next""#)
        .captures(&link)
        .map(|c| c.get(1).unwrap().as_str().to_string())
}

fn cache_dir() -> PathBuf {
    dirs::CACHE.join("gitlab")
}

pub fn get_headers<U: IntoUrl>(url: U, api_url: &str) -> Result<HeaderMap> {
    let mut headers = HeaderMap::new();
    // An invalid URL just means no auth headers; the real error surfaces when the
    // request is made. Avoid panicking here. See #3547.
    let Ok(url) = url.into_url() else {
        return Ok(headers);
    };
    let Ok(api_url) = reqwest::Url::parse(api_url) else {
        return Ok(headers);
    };
    if url.origin() != api_url.origin() {
        return Ok(headers);
    }
    let lookup_host = url.host_str().unwrap_or("gitlab.com");

    if let Some((token, _source)) = resolve_token(lookup_host) {
        headers.insert(
            reqwest::header::AUTHORIZATION,
            tokens::bearer_header("GitLab", &token)?,
        );
    }

    Ok(headers)
}

/// The source from which a GitLab token was resolved.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum TokenSource {
    EnvVar(&'static str),
    TokensFile,
    GlabCli,
    CredentialCommand,
    GitCredential,
}

impl fmt::Display for TokenSource {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            TokenSource::EnvVar(name) => write!(f, "{name}"),
            TokenSource::TokensFile => write!(f, "gitlab_tokens.toml"),
            TokenSource::GlabCli => write!(f, "glab CLI (config.yml)"),
            TokenSource::CredentialCommand => write!(f, "credential_command"),
            TokenSource::GitCredential => write!(f, "git credential fill"),
        }
    }
}

#[doc(hidden)]
pub mod test_support {
    //! Test-only hook that lets tests seed a token without mutating the environment.
    //! Compiled into every build, but [`super::resolve_token`] only consults it while
    //! [`crate::testing::in_tests`] is true, which never holds in a release binary.
    //! Deliberately checked *before* the env-var branch so a developer's
    //! ambient `GITLAB_TOKEN` / `MISE_GITLAB_ENTERPRISE_TOKEN` cannot change the outcome.
    //! Mirrors the equivalent in [`crate::github`].

    use std::collections::HashMap;
    use std::sync::RwLock;

    /// Overrides the `gitlab_tokens.toml` source in [`super::resolve_token`], keyed by host.
    pub static TOKENS_FILE_OVERRIDE: RwLock<Option<HashMap<String, String>>> = RwLock::new(None);

    pub fn lookup_tokens_file_override(host: &str) -> Option<String> {
        let guard = TOKENS_FILE_OVERRIDE.read().ok()?;
        guard.as_ref()?.get(host).cloned()
    }
}

/// Resolve the GitLab token for the given hostname.
///
/// Priority:
/// 1. `MISE_GITLAB_ENTERPRISE_TOKEN` env var (non-gitlab.com only)
/// 2. `MISE_GITLAB_TOKEN` / `GITLAB_TOKEN` env vars
/// 3. `credential_command` (if set)
/// 4. `gitlab_tokens.toml` (per-host)
/// 5. glab CLI token (from `config.yml`)
/// 6. `git credential fill` (if enabled)
pub fn resolve_token(host: &str) -> Option<(String, TokenSource)> {
    // A host that project config named in safe mode; see `untrusted_hosts`.
    if crate::untrusted_hosts::forge_token_denied(host) {
        return None;
    }
    if crate::testing::in_tests()
        && let Some(token) = test_support::lookup_tokens_file_override(host)
    {
        return Some((token, TokenSource::TokensFile));
    }

    let settings = Settings::get();
    let is_gitlab_com = host == "gitlab.com";

    // 1. Enterprise token (non-gitlab.com only)
    if !is_gitlab_com && let Some(token) = env::scoped_var("MISE_GITLAB_ENTERPRISE_TOKEN") {
        return Some((token, TokenSource::EnvVar("MISE_GITLAB_ENTERPRISE_TOKEN")));
    }

    // 2. Standard env vars
    for var_name in &["MISE_GITLAB_TOKEN", "GITLAB_TOKEN"] {
        if let Some(token) = env::scoped_var(var_name) {
            return Some((token, TokenSource::EnvVar(var_name)));
        }
    }

    // 3. credential_command
    let credential_command = &settings.gitlab.credential_command;
    if !credential_command.is_empty()
        && let Some(token) =
            tokens::get_credential_command_token("gitlab", credential_command, host)
    {
        return Some((token, TokenSource::CredentialCommand));
    }

    // 4. gitlab_tokens.toml
    if let Some(token) = MISE_GITLAB_TOKENS.get(host) {
        return Some((token.clone(), TokenSource::TokensFile));
    }

    // 5. glab CLI config.yml
    if settings.gitlab.glab_cli_tokens
        && let Some(token) = GLAB_HOSTS.get(host)
    {
        return Some((token.clone(), TokenSource::GlabCli));
    }

    // 6. git credential fill
    if settings.gitlab.use_git_credentials
        && let Some(token) = tokens::get_git_credential_token("gitlab", host)
    {
        return Some((token, TokenSource::GitCredential));
    }

    None
}

// ── gitlab_tokens.toml ─────────────────────────────────────────────

static MISE_GITLAB_TOKENS: Lazy<HashMap<String, String>> = Lazy::new(|| {
    tokens::read_tokens_toml("gitlab_tokens.toml", "gitlab_tokens.toml").unwrap_or_default()
});

// ── glab CLI config.yml ────────────────────────────────────────────

static GLAB_HOSTS: Lazy<HashMap<String, String>> =
    Lazy::new(|| read_glab_hosts().unwrap_or_default());

/// Resolve the path to glab's config.yml, following glab's own `ConfigDir()`:
/// 1. `$GLAB_CONFIG_DIR/config.yml`
/// 2. `$HOME/.config/glab-cli/config.yml` — glab's *legacy* location, which it still prefers when
///    the file is there. glab's `legacyConfigDir()` is `os.UserHomeDir()` + `.config/glab-cli` on
///    every platform, so it is deliberately derived from `HOME` and **not** from
///    `XDG_CONFIG_HOME`: those differ as soon as the user sets that variable.
/// 3. `xdg.ConfigHome/glab-cli/config.yml`, which on Windows is under `%LOCALAPPDATA%`: glab uses
///    the `adrg/xdg` package, and that maps `XDG_CONFIG_HOME` to `%LOCALAPPDATA%` there, not to
///    `%APPDATA%` the way `gh` does
fn glab_config_path() -> Option<PathBuf> {
    // Empty means unset, as in glab's `if glabDir != ""`; `var_os` rather than `var` so a
    // non-UTF-8 directory is honoured instead of silently skipped.
    if let Some(dir) = std::env::var_os("GLAB_CONFIG_DIR").filter(|dir| !dir.is_empty()) {
        return Some(PathBuf::from(dir).join("config.yml"));
    }

    let xdg_path = env::XDG_CONFIG_HOME.join("glab-cli/config.yml");
    let candidates: Vec<PathBuf> = [
        dirs::HOME.join(".config/glab-cli/config.yml"),
        xdg_path.clone(),
    ]
    .into_iter()
    .chain(glab_native_config_paths())
    .collect();
    // Nothing found: name the location glab itself would settle on, which is the last candidate
    // (its platform-native XDG config dir).
    let fallback = candidates.last().cloned().unwrap_or(xdg_path);
    Some(tokens::first_existing_file(candidates, fallback))
}

/// Platform-native locations glab may have written to, probed after the legacy/XDG one.
#[cfg(target_os = "macos")]
fn glab_native_config_paths() -> Vec<PathBuf> {
    vec![dirs::HOME.join("Library/Application Support/glab-cli/config.yml")]
}

#[cfg(windows)]
fn glab_native_config_paths() -> Vec<PathBuf> {
    vec![env::LOCAL_APPDATA.join("glab-cli/config.yml")]
}

#[cfg(all(not(target_os = "macos"), not(windows)))]
fn glab_native_config_paths() -> Vec<PathBuf> {
    Vec::new()
}

fn read_glab_hosts() -> Option<HashMap<String, String>> {
    let path = glab_config_path()?;
    let contents = match std::fs::read_to_string(&path) {
        Ok(c) => c,
        Err(e) => {
            trace!("glab config.yml not readable at {}: {e}", path.display());
            return None;
        }
    };
    let hosts = glab_usable_tokens(&contents);
    if hosts.is_none() {
        debug!("failed to parse glab config.yml at {}", path.display());
    }
    hosts
}

/// Parse glab's config into host tokens, warning about and dropping expired OAuth2 tokens.
fn glab_usable_tokens(contents: &str) -> Option<HashMap<String, String>> {
    let expired = warn_glab_expired_tokens(contents);
    let mut tokens = tokens::yaml_hosts_to_tokens(contents)?;
    // An expired OAuth2 token only earns a 401, so fall through to an
    // unauthenticated request rather than send it.
    // Only drop the host when the selected token is the expired one; a valid
    // token for the same host from another config section must survive.
    for (host, expired_token) in expired {
        if tokens.get(&host) == Some(&expired_token) {
            tokens.remove(&host);
        }
    }
    Some(tokens)
}

/// Warn if any glab OAuth2 tokens are expired.
///
/// glab stores `oauth2_expiry_date` alongside `oauth2_refresh_token`. Current glab
/// versions write RFC3339; older versions used RFC822. We only check RFC3339 since
/// that is the correct format going forward--old tokens will simply not trigger the
/// warning. mise cannot refresh OAuth2 tokens itself, so we warn the user to run a
/// glab command (e.g. `glab api user`) which will trigger a silent token refresh.
/// Returns the `(host, token)` pairs that expired so the caller can stop using them.
fn warn_glab_expired_tokens(contents: &str) -> Vec<(String, String)> {
    find_expired_glab_tokens(contents)
        .into_iter()
        .map(|(host, expiry_str, token)| {
            warn!(
                "glab OAuth2 token for {host} expired at {expiry_str}, ignoring it. Run a glab command (e.g. `glab api user`) to refresh it."
            );
            (host, token)
        })
        .collect()
}

/// Returns `(host, expiry_str, token)` for every glab host whose OAuth2 token is expired.
fn find_expired_glab_tokens(contents: &str) -> Vec<(String, String, String)> {
    let Ok(doc) = yaml::from_str::<Value>(contents) else {
        return vec![];
    };
    let Some(hosts) = doc.get("hosts").and_then(Value::as_mapping) else {
        return vec![];
    };

    let mut expired = vec![];
    let now = chrono::Utc::now();
    for (k, entry) in hosts {
        let Some(host) = k.as_str() else { continue };
        if entry.get("oauth2_refresh_token").is_none() {
            continue;
        }
        let Some(entry_map) = entry.as_mapping() else {
            continue;
        };
        let Some(token) = tokens::token_from_entry(entry_map) else {
            continue;
        };
        let Some(expiry_str) = entry.get("oauth2_expiry_date").and_then(Value::as_str) else {
            continue;
        };
        let Ok(expiry_date) = chrono::DateTime::parse_from_rfc3339(expiry_str) else {
            continue;
        };
        if expiry_date < now {
            expired.push((host.to_string(), expiry_str.to_string(), token));
        }
    }
    expired
}

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

    #[test]
    fn cache_key_separates_names_kebab_case_collapses() {
        let key = cache_key(&[API_URL, "group/graphql-engine", "v2.40.0"]);
        assert_ne!(
            key,
            cache_key(&[API_URL, "group-graphql/engine", "v2.40.0"])
        );
        assert_ne!(key, cache_key(&[API_URL, "group/graphqlEngine", "v2.40.0"]));
        // the repo/tag boundary moved
        assert_ne!(
            cache_key(&[API_URL, "group/tool", "v1-0"]),
            cache_key(&[API_URL, "group/tool-v1", "0"])
        );
        assert_ne!(
            cache_key(&[API_URL, "group/a-b"]),
            cache_key(&[API_URL, "group-a/b"])
        );
        assert_eq!(
            key,
            cache_key(&[API_URL, "group/graphql-engine", "v2.40.0"])
        );
    }

    #[test]
    fn test_parse_gitlab_tokens() {
        let toml = r#"
[tokens."gitlab.com"]
token = "glpat_abc123"

[tokens."gitlab.mycompany.com"]
token = "glpat_def456"
"#;
        let result = tokens::parse_tokens_toml(toml).unwrap();
        assert_eq!(result.get("gitlab.com").unwrap(), "glpat_abc123");
        assert_eq!(result.get("gitlab.mycompany.com").unwrap(), "glpat_def456");
    }

    #[test]
    fn test_parse_gitlab_tokens_empty() {
        assert!(tokens::parse_tokens_toml("").is_none());
    }

    #[test]
    fn test_parse_gitlab_tokens_empty_tokens() {
        let toml = "[tokens]\n";
        let result = tokens::parse_tokens_toml(toml).unwrap();
        assert!(result.is_empty());
    }

    #[test]
    fn test_parse_gitlab_tokens_missing_token_field() {
        let toml = r#"
[tokens."gitlab.com"]
something_else = "value"
"#;
        let result = tokens::parse_tokens_toml(toml).unwrap();
        assert!(result.is_empty());
    }

    #[test]
    fn test_find_expired_glab_tokens_expired() {
        let yaml = r#"
hosts:
  gitlab.com:
    oauth_token: gloas-abc123
    oauth2_refresh_token: refresh_token
    oauth2_expiry_date: "2023-03-13T15:47:00Z"
"#;
        let expired = find_expired_glab_tokens(yaml);
        assert_eq!(expired.len(), 1);
        assert_eq!(expired[0].0, "gitlab.com");
        assert_eq!(expired[0].1, "2023-03-13T15:47:00Z");
        assert_eq!(expired[0].2, "gloas-abc123");
    }

    #[test]
    fn test_glab_usable_tokens_keeps_valid_login_over_expired_host_token() {
        let yaml = r#"
hosts:
  gitlab.com:
    oauth_token: gloas-expired
    oauth2_refresh_token: refresh
    oauth2_expiry_date: "2023-03-13T15:47:00Z"
logins:
  - name: gitlab.com
    token: glpat-valid
"#;
        let tokens = glab_usable_tokens(yaml).unwrap();
        assert_eq!(tokens.get("gitlab.com").unwrap(), "glpat-valid");
    }

    #[test]
    fn test_find_expired_glab_tokens_not_expired() {
        let yaml = r#"
hosts:
  gitlab.com:
    oauth_token: gloas-abc123
    oauth2_refresh_token: refresh_token
    oauth2_expiry_date: "2050-01-01T00:00:00Z"
"#;
        let expired = find_expired_glab_tokens(yaml);
        assert!(expired.is_empty());
    }

    #[test]
    fn test_find_expired_glab_tokens_no_expiry_field() {
        // PATs have no expiry date--should not be flagged
        let yaml = r#"
hosts:
  gitlab.com:
    token: glpat-abc123
"#;
        let expired = find_expired_glab_tokens(yaml);
        assert!(expired.is_empty());
    }

    #[test]
    fn test_find_expired_glab_tokens_multiple_hosts() {
        let yaml = r#"
hosts:
  gitlab.com:
    oauth_token: gloas-abc123
    oauth2_refresh_token: refresh1
    oauth2_expiry_date: "2023-03-13T15:47:00Z"
  gitlab.mycompany.com:
    oauth_token: gloas-def456
    oauth2_refresh_token: refresh2
    oauth2_expiry_date: "2050-01-01T00:00:00Z"
"#;
        let expired = find_expired_glab_tokens(yaml);
        assert_eq!(expired.len(), 1);
        assert_eq!(expired[0].0, "gitlab.com");
    }

    #[test]
    fn test_find_expired_glab_tokens_old_format_skipped() {
        // Old RFC822 format is not parsed--no false positives
        let yaml = r#"
hosts:
  gitlab.com:
    oauth_token: gloas-abc123
    oauth2_expiry_date: "13 Mar 23 15:47 GMT"
"#;
        let expired = find_expired_glab_tokens(yaml);
        assert!(expired.is_empty());
    }

    #[test]
    fn test_find_expired_glab_tokens_invalid_date() {
        let yaml = r#"
hosts:
  gitlab.com:
    oauth_token: gloas-abc123
    oauth2_expiry_date: "not-a-date"
"#;
        let expired = find_expired_glab_tokens(yaml);
        assert!(expired.is_empty());
    }

    #[test]
    fn test_find_expired_glab_tokens_no_refresh_token_skipped() {
        // No oauth2_refresh_token means reauthentication is needed, not a refresh—don't warn.
        let yaml = r#"
hosts:
  gitlab.com:
    oauth_token: gloas-abc123
    oauth2_expiry_date: "2023-03-13T15:47:00Z"
"#;
        let expired = find_expired_glab_tokens(yaml);
        assert!(expired.is_empty());
    }

    #[test]
    fn test_find_expired_glab_tokens_empty() {
        assert!(find_expired_glab_tokens("").is_empty());
        assert!(find_expired_glab_tokens("hosts: {}").is_empty());
    }

    const TEST_TOKEN: &str = "glpat_paginate_test";

    /// Seeds a token for `host` for the lifetime of the guard.
    struct TokensFileOverrideGuard;

    impl TokensFileOverrideGuard {
        fn set(host: &str) -> Self {
            let mut tokens = HashMap::new();
            tokens.insert(host.to_string(), TEST_TOKEN.to_string());
            *test_support::TOKENS_FILE_OVERRIDE.write().unwrap() = Some(tokens);
            Self
        }
    }

    impl Drop for TokensFileOverrideGuard {
        fn drop(&mut self) {
            *test_support::TOKENS_FILE_OVERRIDE.write().unwrap() = None;
        }
    }

    fn host_of(url: &str) -> String {
        url::Url::parse(url)
            .unwrap()
            .host_str()
            .unwrap()
            .to_string()
    }

    fn tag_json(name: &str) -> serde_json::Value {
        serde_json::json!({ "name": name })
    }

    fn release_json(tag: &str) -> serde_json::Value {
        serde_json::json!({
            "tag_name": tag,
            "description": null,
            "released_at": null,
            "assets": { "sources": [], "links": [] },
        })
    }

    #[test]
    fn published_at_is_the_later_of_created_at_and_released_at() {
        let published_at = |created_at: Option<&str>, released_at: Option<&str>| {
            let mut json = release_json("v1.0.0");
            json["created_at"] = created_at.into();
            json["released_at"] = released_at.into();
            let release: GitlabRelease = serde_json::from_value(json).unwrap();
            release.published_at().map(str::to_string)
        };
        let created = "2026-01-02T00:00:00.000Z";

        // A historical release: the publisher backdated `released_at`.
        assert_eq!(
            published_at(Some(created), Some("2020-01-01T00:00:00.000Z")).as_deref(),
            Some(created)
        );
        // An upcoming release.
        assert_eq!(
            published_at(Some(created), Some("2026-02-01T00:00:00.000Z")).as_deref(),
            Some("2026-02-01T00:00:00.000Z")
        );
        // Instants are compared, not strings: this is 2026-01-01T23:30Z.
        assert_eq!(
            published_at(Some(created), Some("2026-01-02T01:30:00.000+02:00")).as_deref(),
            Some(created)
        );
        assert_eq!(
            published_at(Some(created), Some("garbage")).as_deref(),
            Some(created)
        );
        assert_eq!(published_at(Some(created), None).as_deref(), Some(created));
        assert_eq!(published_at(None, Some(created)).as_deref(), Some(created));
        assert_eq!(published_at(None, None), None);
    }

    #[test]
    fn a_release_cached_without_created_at_still_reads() {
        let release: GitlabRelease = serde_json::from_value(release_json("v1.0.0")).unwrap();
        assert_eq!(release.created_at, None);
        assert_eq!(release.published_at(), None);
    }

    #[test]
    fn test_get_headers_only_authenticates_api_origin() {
        let api_url = "https://gitlab.example.com/api/v4";
        let _token = TokensFileOverrideGuard::set("gitlab.example.com");

        let headers = get_headers(
            "https://gitlab.example.com/releases/download/tool.tar.gz",
            api_url,
        )
        .unwrap();
        assert_eq!(
            headers.get(reqwest::header::AUTHORIZATION).unwrap(),
            format!("Bearer {TEST_TOKEN}").as_str()
        );

        let headers = get_headers("https://downloads.example.com/tool.tar.gz", api_url).unwrap();
        assert!(!headers.contains_key(reqwest::header::AUTHORIZATION));

        let headers = get_headers("http://gitlab.example.com/api/v4/page2", api_url).unwrap();
        assert!(!headers.contains_key(reqwest::header::AUTHORIZATION));
    }

    // Regression: every paginated request must carry the Authorization header. Before the
    // fix, page 2 was sent page 1's *response* headers, so it went out unauthenticated and
    // hit the anonymous rate limit on private/rate-limited projects. github had the same
    // defect until #6318; gitlab never got that fix.
    #[tokio::test]
    async fn test_list_releases_sends_auth_on_every_page() {
        let mut server = mockito::Server::new_async().await;
        let base = server.url();
        let _token = TokensFileOverrideGuard::set(&host_of(&base));
        let auth = format!("Bearer {TEST_TOKEN}");

        // Regex rather than an exact path: the project is percent-encoded into the path
        // (`owner%2Frepo`) and how that is normalized before matching is not this test's
        // subject -- the Authorization header on page 2 is.
        let page1 = server
            .mock(
                "GET",
                mockito::Matcher::Regex(r"^/projects/.+/releases$".to_string()),
            )
            .match_query(mockito::Matcher::UrlEncoded(
                "per_page".into(),
                "100".into(),
            ))
            .match_header("authorization", auth.as_str())
            .with_status(200)
            .with_header("content-type", "application/json")
            .with_header("link", format!("<{base}/page2>; rel=\"next\"").as_str())
            .with_body(serde_json::json!([release_json("v2.0.0")]).to_string())
            .expect(1)
            .create_async()
            .await;
        let page2 = server
            .mock("GET", "/page2")
            .match_header("authorization", auth.as_str())
            .with_status(200)
            .with_header("content-type", "application/json")
            .with_body(serde_json::json!([release_json("v1.0.0")]).to_string())
            .expect(1)
            .create_async()
            .await;

        let releases = list_releases_(&base, "owner/repo", true).await.unwrap();
        page1.assert_async().await;
        page2.assert_async().await;
        assert_eq!(
            releases
                .iter()
                .map(|r| r.tag_name.as_str())
                .collect::<Vec<_>>(),
            ["v2.0.0", "v1.0.0"]
        );
    }

    // Monorepo-style tags contain a slash (`admin-cli/v1.2.3`); GitLab only resolves them when
    // the tag is percent-encoded in the path.
    #[tokio::test]
    async fn test_get_release_encodes_slash_in_tag() {
        let mut server = mockito::Server::new_async().await;
        let base = server.url();
        let _token = TokensFileOverrideGuard::set(&host_of(&base));

        let mock = server
            .mock(
                "GET",
                mockito::Matcher::Regex(
                    r"^/projects/.+/releases/admin-cli%2Fv1\.2\.3$".to_string(),
                ),
            )
            .with_status(200)
            .with_header("content-type", "application/json")
            .with_body(release_json("admin-cli/v1.2.3").to_string())
            .expect(1)
            .create_async()
            .await;

        let release = get_release_(&base, "owner/repo", "admin-cli/v1.2.3")
            .await
            .unwrap();
        mock.assert_async().await;
        assert_eq!(release.tag_name, "admin-cli/v1.2.3");
    }

    // Same regression for the tags loop -- see `test_list_releases_sends_auth_on_every_page`.
    #[tokio::test]
    async fn test_list_tags_sends_auth_on_every_page() {
        let mut server = mockito::Server::new_async().await;
        let base = server.url();
        let _token = TokensFileOverrideGuard::set(&host_of(&base));
        let auth = format!("Bearer {TEST_TOKEN}");

        let page1 = server
            .mock(
                "GET",
                mockito::Matcher::Regex(r"^/projects/.+/repository/tags$".to_string()),
            )
            .match_query(mockito::Matcher::UrlEncoded(
                "per_page".into(),
                "100".into(),
            ))
            .match_header("authorization", auth.as_str())
            .with_status(200)
            .with_header("content-type", "application/json")
            .with_header("link", format!("<{base}/page2>; rel=\"next\"").as_str())
            .with_body(serde_json::json!([tag_json("v2.0.0")]).to_string())
            .expect(1)
            .create_async()
            .await;
        let page2 = server
            .mock("GET", "/page2")
            .match_header("authorization", auth.as_str())
            .with_status(200)
            .with_header("content-type", "application/json")
            .with_body(serde_json::json!([tag_json("v1.0.0")]).to_string())
            .expect(1)
            .create_async()
            .await;

        let tags = list_tags_(&base, "owner/repo", true).await.unwrap();
        page1.assert_async().await;
        page2.assert_async().await;
        assert_eq!(tags, ["v2.0.0", "v1.0.0"]);
    }
}