use crate::cache::{CacheManager, CacheManagerBuilder};
use crate::redactions::strip_url_credentials_in_arg;
use crate::tokens;
use crate::{dirs, env};
use eyre::{Result, WrapErr, bail};
use heck::ToKebabCase;
use mise_settings::Settings;
use reqwest::IntoUrl;
use reqwest::header::{HeaderMap, HeaderValue};
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::fmt;
use std::path::{Path, PathBuf};
use std::sync::{LazyLock as Lazy, Mutex};
use tokio::sync::RwLock;
use tokio::sync::RwLockReadGuard;
use xx::regex;
pub mod oauth;
pub mod sigstore;
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct GithubRelease {
pub tag_name: String,
pub draft: bool,
pub prerelease: bool,
pub created_at: String,
#[serde(default)]
pub published_at: Option<String>,
pub assets: Vec<GithubAsset>,
}
impl GithubRelease {
pub fn released_at(&self) -> &str {
self.published_at.as_deref().unwrap_or(&self.created_at)
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ReleaseVersion {
pub tag_name: String,
pub released_at: Option<String>,
pub prerelease: bool,
pub has_assets: bool,
}
impl From<GithubRelease> for ReleaseVersion {
fn from(release: GithubRelease) -> Self {
Self {
released_at: Some(release.released_at().to_string()),
has_assets: !release.assets.is_empty(),
tag_name: release.tag_name,
prerelease: release.prerelease,
}
}
}
impl From<crate::versions_host::GithubListedRelease> for ReleaseVersion {
fn from(release: crate::versions_host::GithubListedRelease) -> Self {
Self {
released_at: release.date.filter(|date| !date.is_empty()),
has_assets: release.asset_count > 0,
tag_name: release.tag,
prerelease: release.prerelease,
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct GithubTag {
pub name: String,
pub commit: Option<GithubTagCommit>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct GithubTagCommit {
pub sha: String,
pub url: String,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct GithubCommit {
pub commit: GithubCommitInfo,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct GithubCommitInfo {
pub committer: GithubCommitPerson,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct GithubCommitPerson {
pub date: String,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct GithubTagWithDate {
pub name: String,
pub date: Option<String>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct GithubAsset {
pub name: String,
pub browser_download_url: String,
pub url: String,
#[serde(default)]
pub digest: Option<String>,
#[serde(default)]
pub updated_at: Option<String>,
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
pub from_versions_host: bool,
}
type CacheGroup<T> = HashMap<String, CacheManager<T>>;
static RELEASES_CACHE: Lazy<RwLock<CacheGroup<Vec<GithubRelease>>>> = Lazy::new(Default::default);
static RELEASE_CACHE: Lazy<RwLock<CacheGroup<GithubRelease>>> = Lazy::new(Default::default);
static TAGS_CACHE: Lazy<RwLock<CacheGroup<Vec<String>>>> = Lazy::new(Default::default);
static DATED_TAGS_CACHE: Lazy<RwLock<CacheGroup<Vec<GithubTagWithDate>>>> =
Lazy::new(Default::default);
static RELEASE_VERSIONS_CACHE: Lazy<RwLock<CacheGroup<Vec<ReleaseVersion>>>> =
Lazy::new(Default::default);
static REPOSITORY_CACHE: Lazy<RwLock<CacheGroup<RepositoryIdentity>>> = Lazy::new(Default::default);
pub static API_URL: &str = "https://api.github.com";
pub static API_PATH: &str = "/api/v3";
const MAX_RELEASE_FALLBACK_PAGES: usize = 3;
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_dated_tags_cache(
key: &str,
) -> RwLockReadGuard<'_, CacheGroup<Vec<GithubTagWithDate>>> {
DATED_TAGS_CACHE
.write()
.await
.entry(key.to_string())
.or_insert_with(|| {
CacheManagerBuilder::new(cache_dir().join(format!("{key}-dated-tags.msgpack.z")))
.with_fresh_duration(crate::network::fetch_remote_versions_cache(&Settings::get()))
.build()
});
DATED_TAGS_CACHE.read().await
}
async fn get_releases_cache(key: &str) -> RwLockReadGuard<'_, CacheGroup<Vec<GithubRelease>>> {
RELEASES_CACHE
.write()
.await
.entry(key.to_string())
.or_insert_with(|| {
CacheManagerBuilder::new(cache_dir().join(format!("{key}-all-releases.msgpack.z")))
.with_fresh_duration(crate::network::fetch_remote_versions_cache(&Settings::get()))
.build()
});
RELEASES_CACHE.read().await
}
async fn get_release_cache<'a>(key: &str) -> RwLockReadGuard<'a, CacheGroup<GithubRelease>> {
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
}
pub async fn list_releases(repo: &str) -> Result<Vec<GithubRelease>> {
Ok(list_releases_including_prereleases(repo)
.await?
.into_iter()
.filter(|r| !r.prerelease)
.collect())
}
pub async fn list_releases_from_url(api_url: &str, repo: &str) -> Result<Vec<GithubRelease>> {
Ok(
list_releases_including_prereleases_from_url(api_url, repo, false)
.await?
.into_iter()
.filter(|r| !r.prerelease)
.collect(),
)
}
pub async fn list_releases_including_prereleases(repo: &str) -> Result<Vec<GithubRelease>> {
let key = format!(
"{}-{}",
repo.to_kebab_case(),
crate::hash::hash_to_str(&(repo, RELEASE_LIST_CACHE_VERSION, mirror_source(repo)))
);
let cache = get_releases_cache(&key).await;
let cache = cache.get(&key).unwrap();
Ok(remember_mirrored_assets(
cached_or_stale(cache, async || list_releases_(API_URL, repo, false).await).await?,
))
}
fn remember_mirrored_assets<R: std::borrow::Borrow<GithubRelease>, T: AsRef<[R]>>(
releases: T,
) -> T {
for release in releases.as_ref() {
for asset in &release.borrow().assets {
if asset.from_versions_host {
crate::versions_host::remember_mirrored_asset_api_url(&asset.url);
}
}
}
releases
}
pub async fn list_releases_including_prereleases_from_url(
api_url: &str,
repo: &str,
require_assets: bool,
) -> Result<Vec<GithubRelease>> {
let key = releases_cache_key(api_url, repo, require_assets);
let cache = get_releases_cache(&key).await;
let cache = cache.get(&key).unwrap();
Ok(remember_mirrored_assets(
cached_or_stale(cache, async || {
list_releases_(api_url, repo, require_assets).await
})
.await?,
))
}
fn releases_cache_key(api_url: &str, repo: &str, require_assets: bool) -> String {
format!(
"{}-{}",
format!("{}-{repo}", strip_url_credentials_in_arg(api_url)).to_kebab_case(),
crate::hash::hash_to_str(&(
api_url,
repo,
require_assets,
RELEASE_LIST_CACHE_VERSION,
mirror_source(repo)
))
)
}
const RELEASE_LIST_CACHE_VERSION: &str = "2";
fn mirror_source(repo: &str) -> bool {
Settings::get().use_versions_host
&& !crate::versions_host::github_is_url_replaced(Some(repo))
&& !crate::versions_host::github_repo_excluded(repo)
}
fn has_stopping_stable_release(releases: &[GithubRelease], require_assets: bool) -> bool {
releases
.iter()
.any(|r| !r.prerelease && !r.draft && (!require_assets || !r.assets.is_empty()))
}
async fn list_releases_(
api_url: &str,
repo: &str,
require_assets: bool,
) -> Result<Vec<GithubRelease>> {
if mirrors_github_metadata(api_url, repo) {
let mirrored = list_releases_from_versions_host(repo, require_assets).await;
let listed = mirror_or_github(
&format!("GitHub releases of {repo}"),
mirrored,
async || {
list_releases_from_api(api_url, repo, require_assets)
.await
.map(Some)
},
)
.await?;
match listed {
Some(releases) => return Ok(releases),
None => ensure_private_repo_lookup(repo, &format!("GitHub repository {repo}"))?,
}
}
list_releases_from_api(api_url, repo, require_assets).await
}
async fn list_releases_from_api(
api_url: &str,
repo: &str,
require_assets: bool,
) -> Result<Vec<GithubRelease>> {
let (mut url, mut releases, mut headers) = fetch_first_release_page(api_url, repo).await?;
let mut pages_fetched = 1;
while let Some(next) = next_page(&headers) {
if !*env::MISE_LIST_ALL_VERSIONS
&& (has_stopping_stable_release(&releases, require_assets)
|| pages_fetched >= MAX_RELEASE_FALLBACK_PAGES)
{
break;
}
url = crate::http::resolve_pagination_url(&url, &next)?;
headers = get_headers(&url, api_url)?;
let (more, h) = crate::http::HTTP_FETCH
.json_headers_with_headers::<Vec<GithubRelease>, _>(&url, &headers)
.await?;
releases.extend(more);
headers = h;
pages_fetched += 1;
}
releases.retain(|r| !r.draft);
Ok(releases)
}
const RELEASE_PAGE_SIZES: [u32; 3] = [100, 30, 10];
async fn fetch_first_release_page(
api_url: &str,
repo: &str,
) -> Result<(String, Vec<GithubRelease>, HeaderMap)> {
let last = RELEASE_PAGE_SIZES.len() - 1;
for (i, per_page) in RELEASE_PAGE_SIZES.into_iter().enumerate() {
let url = format!("{api_url}/repos/{repo}/releases?per_page={per_page}");
let headers = get_headers(&url, api_url)?;
match crate::http::HTTP_FETCH
.json_headers_with_headers::<Vec<GithubRelease>, _>(&url, &headers)
.await
{
Ok((releases, headers)) => return Ok((url, releases, headers)),
Err(err) if i < last && is_server_error(&err) => {
debug!(
"GitHub failed to list {per_page} releases of {repo} at once, asking for fewer: {err:#}"
);
}
Err(err) => return Err(err),
}
}
unreachable!("the smallest page size returns its result")
}
fn is_server_error(err: &eyre::Report) -> bool {
err.chain().any(|cause| {
cause
.downcast_ref::<reqwest::Error>()
.and_then(reqwest::Error::status)
.is_some_and(|status| status.is_server_error())
})
}
async fn list_releases_from_versions_host(
repo: &str,
require_assets: bool,
) -> Result<Option<Vec<GithubRelease>>> {
let releases =
paginate_mirrored_releases(require_assets, *env::MISE_LIST_ALL_VERSIONS, |page| {
crate::versions_host::github_releases(repo, page)
})
.await?;
if releases.is_some() {
trace!("got GitHub releases for {repo} from mise-versions");
}
Ok(releases)
}
async fn paginate_mirrored_releases<F, Fut>(
require_assets: bool,
list_all: bool,
mut fetch_page: F,
) -> Result<Option<Vec<GithubRelease>>>
where
F: FnMut(u32) -> Fut,
Fut: std::future::Future<Output = Result<Option<crate::versions_host::GithubReleasesPage>>>,
{
let mut releases = Vec::new();
let mut page = 1;
let mut pages_fetched = 0;
loop {
let Some(list) = fetch_page(page).await? else {
if page == 1 {
return Ok(None);
}
bail!("mise-versions has no page {page} of a GitHub release list it listed before");
};
releases.extend(list.releases);
pages_fetched += 1;
if !list_all
&& (has_stopping_stable_release(&releases, require_assets)
|| pages_fetched >= MAX_RELEASE_FALLBACK_PAGES)
{
break;
}
let Some(next) = list.next_page else {
if list.truncated {
debug!(
"mise-versions serves the newest {pages_fetched} pages of this release list; older releases are not listed"
);
}
break;
};
if pages_fetched >= crate::versions_host::GITHUB_RELEASES_MAX_PAGES {
debug!("stopping after the {pages_fetched} release pages mise-versions serves");
break;
}
page = next;
}
Ok(Some(releases))
}
fn mirrors_github_tags(api_url: &str, repo: &str) -> bool {
mirrors_github_metadata(api_url, repo)
&& !crate::versions_host::github_api_url_is_replaced(&format!(
"{}/repos/{repo}/tags?per_page=100",
api_url.trim_end_matches('/')
))
}
fn tags_mirror_source(api_url: &str, repo: &str) -> bool {
is_public_github_api_base(api_url)
&& mirror_source(repo)
&& !crate::versions_host::github_api_url_is_replaced(&format!(
"{}/repos/{repo}/tags?per_page=100",
api_url.trim_end_matches('/')
))
}
fn tags_cache_key(api_url: &str, repo: &str) -> String {
format!(
"{}-{}",
format!("{}-{repo}", strip_url_credentials_in_arg(api_url)).to_kebab_case(),
crate::hash::hash_to_str(&(api_url, repo, tags_mirror_source(api_url, repo)))
)
}
async fn whole_list(
repo: &str,
list: crate::versions_host::GithubList<'_>,
) -> Option<crate::versions_host::GithubVersionsList> {
match crate::versions_host::github_versions_list(repo, list).await {
Ok(Some(found)) if found.truncated => {
debug!("mise-versions' {list:?} list for {repo} is truncated; paging instead");
None
}
Ok(Some(found)) if found.releases.is_empty() && found.tags.is_empty() => {
debug!("mise-versions' {list:?} list for {repo} is empty; paging instead");
None
}
Ok(Some(found)) => Some(found),
Ok(None) => None,
Err(err) => {
debug!("mise-versions' whole {list:?} list for {repo} failed, paging instead: {err:#}");
None
}
}
}
fn all_releases_dated(list: &crate::versions_host::GithubVersionsList) -> bool {
list.releases
.iter()
.all(|r| r.date.as_deref().is_some_and(|d| !d.is_empty()))
}
pub async fn list_release_versions(
api_url: &str,
repo: &str,
require_assets: bool,
) -> Result<Vec<ReleaseVersion>> {
let key = format!(
"{}-versions-{}",
format!("{}-{repo}", strip_url_credentials_in_arg(api_url)).to_kebab_case(),
crate::hash::hash_to_str(&(
api_url,
repo,
require_assets,
RELEASE_LIST_CACHE_VERSION,
is_public_github_api_base(api_url) && mirror_source(repo)
))
);
RELEASE_VERSIONS_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 = RELEASE_VERSIONS_CACHE.read().await;
let cache = caches.get(&key).unwrap();
cached_or_stale(cache, async || {
if mirrors_github_metadata(api_url, repo)
&& let Some(list) = whole_list(repo, crate::versions_host::GithubList::Releases)
.await
.filter(all_releases_dated)
{
return Ok(list.releases.into_iter().map(Into::into).collect());
}
Ok(
list_releases_including_prereleases_from_url(api_url, repo, require_assets)
.await?
.into_iter()
.map(Into::into)
.collect(),
)
})
.await
}
async fn list_releases_page_budget(repo: &str) -> Result<Vec<GithubRelease>> {
if mirrors_github_metadata(API_URL, repo) {
let mirrored = paginate_mirrored_releases(false, true, |page| {
crate::versions_host::github_releases(repo, page)
})
.await;
let listed = mirror_or_github(
&format!("GitHub releases of {repo}"),
mirrored,
async || list_release_pages_from_api(repo).await.map(Some),
)
.await?;
match listed {
Some(releases) => return Ok(releases),
None => ensure_private_repo_lookup(repo, &format!("GitHub repository {repo}"))?,
}
}
list_release_pages_from_api(repo).await
}
async fn list_release_pages_from_api(repo: &str) -> Result<Vec<GithubRelease>> {
let (mut url, mut releases, mut headers) = fetch_first_release_page(API_URL, repo).await?;
let mut pages_fetched = 1;
while let Some(next) = next_page(&headers) {
if pages_fetched >= crate::versions_host::GITHUB_RELEASES_MAX_PAGES {
break;
}
url = crate::http::resolve_pagination_url(&url, &next)?;
let request_headers = get_headers(&url, API_URL)?;
let (more, h) = crate::http::HTTP_FETCH
.json_headers_with_headers::<Vec<GithubRelease>, _>(&url, &request_headers)
.await?;
releases.extend(more);
headers = h;
pages_fetched += 1;
}
Ok(releases)
}
pub async fn list_release_versions_with_asset(
repo: &str,
asset: &str,
) -> Result<Vec<ReleaseVersion>> {
release_versions_with_asset(repo, asset, false).await
}
pub async fn refresh_release_versions_with_asset(
repo: &str,
asset: &str,
) -> Result<Vec<ReleaseVersion>> {
release_versions_with_asset(repo, asset, true).await
}
async fn release_versions_with_asset(
repo: &str,
asset: &str,
refresh: bool,
) -> Result<Vec<ReleaseVersion>> {
let key = format!(
"{}-versions-with-asset-paged-{}",
repo.to_kebab_case(),
crate::hash::hash_to_str(&(repo, asset, RELEASE_LIST_CACHE_VERSION, mirror_source(repo)))
);
RELEASE_VERSIONS_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()
});
if refresh {
let fetched = fetch_release_versions_with_asset(repo, asset).await;
let mut caches = RELEASE_VERSIONS_CACHE.write().await;
let cache = caches.get_mut(&key).unwrap();
return match fetched {
Ok(versions) => cache.refresh_async(|| async { Ok(versions) }).await,
Err(err) => stale_on_temporary_failure(cache, err),
};
}
let caches = RELEASE_VERSIONS_CACHE.read().await;
let cache = caches.get(&key).unwrap();
cached_or_stale(cache, async || {
fetch_release_versions_with_asset(repo, asset).await
})
.await
}
async fn fetch_release_versions_with_asset(repo: &str, asset: &str) -> Result<Vec<ReleaseVersion>> {
if mirrors_github_metadata(API_URL, repo)
&& let Some(list) = whole_list(
repo,
crate::versions_host::GithubList::ReleasesWithAsset(asset),
)
.await
.filter(all_releases_dated)
{
return Ok(list.releases.into_iter().map(Into::into).collect());
}
let releases = list_releases_page_budget(repo).await?;
Ok(releases
.into_iter()
.filter(|r| !r.draft && r.assets.iter().any(|a| a.name == asset))
.map(Into::into)
.collect())
}
pub async fn newest_listed_stable_release(repo: &str) -> Option<ReleaseVersion> {
let list = whole_list(repo, crate::versions_host::GithubList::Releases).await?;
let newest = newest_stable_if_fresh(list, chrono::Utc::now(), LISTED_LATEST_MAX_AGE);
if newest.is_none() {
debug!("mise-versions' release list for {repo} is too old or has no stable release");
}
newest
}
const LISTED_LATEST_MAX_AGE: std::time::Duration = std::time::Duration::from_secs(7 * 60 * 60);
fn newest_stable_if_fresh(
list: crate::versions_host::GithubVersionsList,
now: chrono::DateTime<chrono::Utc>,
max_age: std::time::Duration,
) -> Option<ReleaseVersion> {
let fetched_at = chrono::DateTime::parse_from_rfc3339(list.fetched_at.as_deref()?).ok()?;
let age = now.signed_duration_since(fetched_at);
if age.to_std().is_ok_and(|age| age > max_age) {
return None;
}
list.releases
.into_iter()
.find(|r| !r.prerelease)
.map(Into::into)
}
async fn list_mirrored_tags(
repo: &str,
list_all: bool,
dates: bool,
) -> Result<Option<Vec<crate::versions_host::GithubMirroredTag>>> {
paginate_mirrored_tags(list_all, |page| {
crate::versions_host::github_tags(repo, page, dates)
})
.await
}
async fn paginate_mirrored_tags<F, Fut>(
list_all: bool,
mut fetch_page: F,
) -> Result<Option<Vec<crate::versions_host::GithubMirroredTag>>>
where
F: FnMut(u32) -> Fut,
Fut: std::future::Future<Output = Result<Option<crate::versions_host::GithubTagsPage>>>,
{
let mut tags = Vec::new();
let mut page = 1;
for pages_fetched in 1.. {
let Some(list) = fetch_page(page).await? else {
if page == 1 {
return Ok(None);
}
bail!("mise-versions has no page {page} of a GitHub tag list it listed before");
};
tags.extend(list.tags);
let Some(next) = list.next_page.filter(|_| list_all) else {
if list_all && list.truncated {
debug!(
"mise-versions serves the first {pages_fetched} pages of tags; the rest are not listed"
);
}
break;
};
if pages_fetched >= crate::versions_host::GITHUB_RELEASES_MAX_PAGES {
break;
}
page = next;
}
Ok(Some(tags))
}
async fn cached_or_stale<T, F, Fut>(cache: &CacheManager<T>, fetch: F) -> Result<T>
where
T: Clone + serde::Serialize + serde::de::DeserializeOwned,
F: FnOnce() -> Fut,
Fut: std::future::Future<Output = Result<T>>,
{
match cache.get_or_try_init_async(|| Box::pin(fetch())).await {
Ok(val) => Ok(val.clone()),
Err(err) => stale_on_temporary_failure(cache, err),
}
}
fn stale_on_temporary_failure<T>(cache: &CacheManager<T>, err: eyre::Report) -> Result<T>
where
T: Clone + serde::Serialize + serde::de::DeserializeOwned,
{
if !crate::versions_host::is_temporarily_unavailable(&err) {
return Err(err);
}
match cache.get_cached() {
Ok(stale) => {
warn!("{err:#}\nusing the copy mise cached earlier");
Ok(stale)
}
Err(_) => Err(err),
}
}
fn mirrors_github_metadata(api_url: &str, repo: &str) -> bool {
is_public_github_api_base(api_url) && crate::versions_host::enabled_for_github_repo(repo)
}
pub(crate) enum MirrorAnswer<T> {
Answered(T),
Unavailable(eyre::Report),
}
impl<T> MirrorAnswer<T> {
pub(crate) fn from_result(result: Result<T>) -> Result<Self> {
match result {
Ok(answer) => Ok(Self::Answered(answer)),
Err(err) if crate::versions_host::retries_on_github(&err) => Ok(Self::Unavailable(err)),
Err(err) => Err(err),
}
}
}
pub(crate) async fn mirror_or_github<T, F, Fut>(
what: &str,
mirrored: Result<T>,
github: F,
) -> Result<T>
where
F: FnOnce() -> Fut,
Fut: std::future::Future<Output = Result<T>>,
{
match MirrorAnswer::from_result(mirrored) {
Ok(MirrorAnswer::Answered(answer)) => Ok(answer),
Ok(MirrorAnswer::Unavailable(mirror_err)) => {
debug!(
"mise-versions failed to answer for {what}, asking api.github.com: {mirror_err:#}"
);
Box::pin(github()).await.map_err(|github_err| {
crate::versions_host::GithubRetryFailed::new(what, &mirror_err, github_err).into()
})
}
Err(err) => Err(err.wrap_err(versions_host_failure(what))),
}
}
async fn after_mirror_404(repo: &str, what: &str) -> Result<()> {
match crate::versions_host::github_releases(repo, 1).await {
Ok(None) => ensure_private_repo_lookup(repo, what),
Ok(Some(_)) | Err(_) => bail!("{what} not found (404 from mise-versions.jdx.dev)"),
}
}
fn ensure_private_repo_lookup(repo: &str, what: &str) -> Result<()> {
if has_github_api_credentials() {
debug!("mise-versions does not know {repo}; asking GitHub, which may hold it privately");
return Ok(());
}
bail!(
"{what} not found (404 from mise-versions.jdx.dev, which mise asks before \
api.github.com). If the repository is private, set GITHUB_TOKEN; to ask GitHub \
directly, set use_versions_host = false."
)
}
pub(crate) fn has_github_api_credentials() -> bool {
resolve_token("api.github.com").is_some()
|| url::Url::parse(API_URL).is_ok_and(|url| {
crate::http::netrc_headers(&url).contains_key(reqwest::header::AUTHORIZATION)
})
}
pub(crate) fn versions_host_failure(what: &str) -> String {
format!(
"failed to read {what} from mise-versions.jdx.dev. Try again later, or set \
use_versions_host = false to ask api.github.com directly."
)
}
pub async fn attested_by_repository(owner: &str, repo: &str, attested: &[String]) -> bool {
let requested = format!("{owner}/{repo}");
if attested.iter().any(|a| a.eq_ignore_ascii_case(&requested)) {
return true;
}
let Ok(canonical) = canonical_repo(&requested).await else {
return false;
};
let mut others: Vec<String> = attested.iter().map(|a| a.to_ascii_lowercase()).collect();
others.sort();
others.dedup();
for other in others.iter().take(5) {
if canonical_repo(other)
.await
.is_ok_and(|c| c.eq_ignore_ascii_case(&canonical))
{
return true;
}
}
false
}
pub async fn list_tags(repo: &str) -> Result<Vec<String>> {
let key = tags_cache_key(API_URL, repo);
let cache = get_tags_cache(&key).await;
let cache = cache.get(&key).unwrap();
cached_or_stale(cache, async || {
list_tags_(API_URL, repo, *env::MISE_LIST_ALL_VERSIONS).await
})
.await
}
pub async fn list_tags_from_url(api_url: &str, repo: &str) -> Result<Vec<String>> {
let key = tags_cache_key(api_url, repo);
let cache = get_tags_cache(&key).await;
let cache = cache.get(&key).unwrap();
cached_or_stale(cache, async || {
list_tags_(api_url, repo, *env::MISE_LIST_ALL_VERSIONS).await
})
.await
}
async fn list_tags_(api_url: &str, repo: &str, list_all: bool) -> Result<Vec<String>> {
if mirrors_github_tags(api_url, repo) {
if let Some(list) = whole_list(repo, crate::versions_host::GithubList::Tags).await {
return Ok(list.tags.into_iter().map(|t| t.tag).collect());
}
let mirrored = list_mirrored_tags(repo, list_all, false)
.await
.map(|tags| tags.map(|tags| tags.into_iter().map(|t| t.name).collect()));
let listed = mirror_or_github(&format!("tags of {repo}"), mirrored, async || {
list_tags_from_api(api_url, repo, list_all).await.map(Some)
})
.await?;
match listed {
Some(tags) => return Ok(tags),
None => ensure_private_repo_lookup(repo, &format!("GitHub repository {repo}"))?,
}
}
list_tags_from_api(api_url, repo, list_all).await
}
async fn list_tags_from_api(api_url: &str, repo: &str, list_all: bool) -> Result<Vec<String>> {
let mut url = format!("{api_url}/repos/{repo}/tags?per_page=100");
let headers = get_headers(&url, api_url)?;
let (mut tags, mut headers) = crate::http::HTTP_FETCH
.json_headers_with_headers::<Vec<GithubTag>, _>(&url, &headers)
.await?;
if list_all {
while let Some(next) = next_page(&headers) {
url = crate::http::resolve_pagination_url(&url, &next)?;
headers = get_headers(&url, api_url)?;
let (more, h) = crate::http::HTTP_FETCH
.json_headers_with_headers::<Vec<GithubTag>, _>(&url, &headers)
.await?;
tags.extend(more);
headers = h;
}
}
Ok(tags.into_iter().map(|t| t.name).collect())
}
pub async fn list_tags_with_known_dates(repo: &str) -> Result<Vec<GithubTagWithDate>> {
let key = tags_cache_key(API_URL, repo);
let cache = get_dated_tags_cache(&key).await;
let cache = cache.get(&key).unwrap();
cached_or_stale(cache, async || {
list_tags_with_known_dates_(API_URL, repo, *env::MISE_LIST_ALL_VERSIONS).await
})
.await
}
async fn list_tags_with_known_dates_(
api_url: &str,
repo: &str,
list_all: bool,
) -> Result<Vec<GithubTagWithDate>> {
if mirrors_github_tags(api_url, repo) {
if let Some(list) = whole_list(repo, crate::versions_host::GithubList::Tags).await {
return Ok(list
.tags
.into_iter()
.map(|t| GithubTagWithDate {
name: t.tag,
date: t.date.filter(|d| !d.is_empty()),
})
.collect());
}
let mirrored = list_mirrored_tags(repo, list_all, true).await.map(|tags| {
tags.map(|tags| {
tags.into_iter()
.map(|t| GithubTagWithDate {
name: t.name,
date: t.date.filter(|d| !d.is_empty()),
})
.collect()
})
});
let listed = mirror_or_github(&format!("tags of {repo}"), mirrored, async || {
list_tags_from_api(api_url, repo, list_all)
.await
.map(|tags| Some(undated_tags(tags)))
})
.await?;
match listed {
Some(tags) => return Ok(tags),
None => ensure_private_repo_lookup(repo, &format!("GitHub repository {repo}"))?,
}
}
list_tags_from_api(api_url, repo, list_all)
.await
.map(undated_tags)
}
fn undated_tags(tags: Vec<String>) -> Vec<GithubTagWithDate> {
tags.into_iter()
.map(|name| GithubTagWithDate { name, date: None })
.collect()
}
fn tag_commit_url(api_url: &str, repo: &str, tag: &str) -> String {
let tag = tag
.split('/')
.map(|segment| urlencoding::encode(segment).into_owned())
.collect::<Vec<_>>()
.join("/");
format!("{api_url}/repos/{repo}/commits/{tag}")
}
pub async fn tag_commit_date(repo: &str, tag: &str) -> Result<Option<String>> {
let url = tag_commit_url(API_URL, repo, tag);
let headers = get_headers(&url, API_URL)?;
let commit = crate::http::HTTP_FETCH
.json_with_headers::<GithubCommit, _>(&url, &headers)
.await?;
Ok(Some(commit.commit.committer.date))
}
pub async fn list_tags_with_dates(repo: &str) -> Result<Vec<GithubTagWithDate>> {
list_tags_with_dates_(API_URL, repo).await
}
async fn list_tags_with_dates_(api_url: &str, repo: &str) -> Result<Vec<GithubTagWithDate>> {
if mirrors_github_tags(api_url, repo) {
if let Some(list) = whole_list(repo, crate::versions_host::GithubList::Tags)
.await
.filter(|list| {
list.tags
.iter()
.all(|t| t.date.as_deref().is_some_and(|d| !d.is_empty()))
})
{
return Ok(list
.tags
.into_iter()
.map(|t| GithubTagWithDate {
name: t.tag,
date: t.date,
})
.collect());
}
let mirrored = list_mirrored_tags(repo, true, true).await.map(|tags| {
tags.map(|tags| {
tags.into_iter()
.map(|t| GithubTagWithDate {
name: t.name,
date: t.date,
})
.collect()
})
});
let listed = mirror_or_github(&format!("tags of {repo}"), mirrored, async || {
list_tags_with_dates_from_api(api_url, repo).await.map(Some)
})
.await?;
match listed {
Some(tags) => return Ok(tags),
None => ensure_private_repo_lookup(repo, &format!("GitHub repository {repo}"))?,
}
}
list_tags_with_dates_from_api(api_url, repo).await
}
async fn list_tags_with_dates_from_api(
api_url: &str,
repo: &str,
) -> Result<Vec<GithubTagWithDate>> {
let mut url = format!("{api_url}/repos/{repo}/tags?per_page=100");
let headers = get_headers(&url, api_url)?;
let (mut tags, mut response_headers) = crate::http::HTTP_FETCH
.json_headers_with_headers::<Vec<GithubTag>, _>(&url, &headers)
.await?;
while let Some(next) = next_page(&response_headers) {
url = crate::http::resolve_pagination_url(&url, &next)?;
response_headers = get_headers(&url, api_url)?;
let (more, h) = crate::http::HTTP_FETCH
.json_headers_with_headers::<Vec<GithubTag>, _>(&url, &response_headers)
.await?;
tags.extend(more);
response_headers = h;
}
let tags = tags
.into_iter()
.map(|tag| (tag, api_url.to_string()))
.collect();
let results = crate::parallel::parallel(tags, |(tag, api_url)| async move {
let date = if let Some(commit) = tag.commit {
let headers = get_headers(&commit.url, &api_url)?;
match crate::http::HTTP_FETCH
.json_with_headers::<GithubCommit, _>(&commit.url, &headers)
.await
{
Ok(commit_info) => Some(commit_info.commit.committer.date),
Err(e) => {
warn!("Failed to fetch commit date for tag {}: {}", tag.name, e);
None
}
}
} else {
None
};
Ok((tag.name, date))
})
.await?;
Ok(results
.into_iter()
.map(|(name, date)| GithubTagWithDate { name, date })
.collect())
}
pub async fn get_release(repo: &str, tag: &str) -> Result<GithubRelease> {
get_release_with_versions_host(repo, tag, true).await
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct RepositoryIdentity {
pub id: String,
pub full_name: String,
pub owner_id: Option<String>,
}
#[derive(Debug, Deserialize)]
struct GithubRepositoryIds {
id: u64,
full_name: String,
owner: Option<GithubRepositoryOwner>,
}
#[derive(Debug, Deserialize)]
struct GithubRepositoryOwner {
id: u64,
}
pub async fn repository_identity(repo: &str) -> Result<RepositoryIdentity> {
let key = format!(
"{}-repository-{}",
repo.to_kebab_case(),
crate::hash::hash_to_str(&repo)
);
REPOSITORY_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 = REPOSITORY_CACHE.read().await;
let cache = caches.get(&key).unwrap();
Ok(cache
.get_or_try_init_async(async || {
let repository = fetch_repository(repo).await?;
Ok(RepositoryIdentity {
id: repository.id.to_string(),
full_name: repository.full_name,
owner_id: repository.owner.map(|o| o.id.to_string()),
})
})
.await?
.clone())
}
pub async fn canonical_repo(repo: &str) -> Result<String> {
let url = format!("{API_URL}/repos/{repo}");
let original = url::Url::parse(&url)?;
let mut replaced = original.clone();
crate::http::apply_url_replacements(&mut replaced);
eyre::ensure!(
replaced == original,
"url_replacements reroutes {API_URL}; only GitHub can confirm a repository rename or transfer"
);
Ok(fetch_repository(repo).await?.full_name)
}
async fn fetch_repository(repo: &str) -> Result<GithubRepositoryIds> {
let url = format!("{API_URL}/repos/{repo}");
let headers = get_headers(&url, API_URL)?;
crate::http::HTTP_FETCH
.json_with_headers(url, &headers)
.await
}
pub struct RepoDir {
pub entries: Vec<crate::versions_host::GithubContentsEntry>,
pub private: bool,
}
pub async fn list_repo_dir(repo: &str, commit: &str, path: &str) -> Result<RepoDir> {
let url = format!(
"{API_URL}/repos/{repo}/contents/{}?ref={commit}",
url_path(path)
);
if mirrors_github_metadata(API_URL, repo)
&& !crate::versions_host::github_api_url_is_replaced(&url)
{
let what = format!("{path} in {repo} at {commit}");
let mirrored = crate::versions_host::github_contents(repo, commit, path)
.await
.map(|entries| {
entries.map(|entries| RepoDir {
entries,
private: false,
})
});
let listed = mirror_or_github(&what, mirrored, async || {
repo_dir_from_api(&url, repo, path).await.map(Some)
})
.await?;
match listed {
Some(dir) => return Ok(dir),
None => after_mirror_404(repo, &what).await?,
}
}
repo_dir_from_api(&url, repo, path).await
}
async fn repo_dir_from_api(url: &str, repo: &str, path: &str) -> Result<RepoDir> {
let mut headers = get_headers(url, API_URL)?;
headers.insert(
reqwest::header::ACCEPT,
HeaderValue::from_static("application/vnd.github+json"),
);
let listing: serde_json::Value = crate::http::HTTP_FETCH
.json_with_headers(url, &headers)
.await?;
let Some(entries) = listing.as_array() else {
bail!("{path} is not a directory of {repo}");
};
Ok(RepoDir {
entries: entries
.iter()
.map(|entry| serde_json::from_value(entry.clone()))
.collect::<std::result::Result<_, _>>()
.wrap_err_with(|| format!("unexpected listing of {path} in {repo}"))?,
private: true,
})
}
fn url_path(path: &str) -> String {
path.split('/')
.map(|segment| urlencoding::encode(segment).into_owned())
.collect::<Vec<_>>()
.join("/")
}
pub async fn get_release_with_versions_host(
repo: &str,
tag: &str,
use_versions_host: bool,
) -> Result<GithubRelease> {
let key = release_cache_key(API_URL, repo, tag, use_versions_host);
let cache = get_release_cache(&key).await;
let cache = cache.get(&key).unwrap();
let release = cache
.get_or_try_init_async_if(
async || {
Box::pin(get_release_with_options(
API_URL,
repo,
tag,
use_versions_host,
))
.await
},
should_cache_release,
)
.await
.or_else(|err| stale_on_temporary_failure(cache, err))?;
remember_mirrored_assets([&release]);
Ok(release)
}
pub async fn get_release_for_url_with_versions_host(
api_url: &str,
repo: &str,
tag: &str,
use_versions_host: bool,
) -> Result<GithubRelease> {
let key = release_cache_key(api_url, repo, tag, use_versions_host);
let cache = get_release_cache(&key).await;
let cache = cache.get(&key).unwrap();
let release = cache
.get_or_try_init_async_if(
async || {
Box::pin(get_release_with_options(
api_url,
repo,
tag,
use_versions_host,
))
.await
},
should_cache_release,
)
.await
.or_else(|err| stale_on_temporary_failure(cache, err))?;
remember_mirrored_assets([&release]);
Ok(release)
}
fn release_cache_key(api_url: &str, repo: &str, tag: &str, use_versions_host: bool) -> String {
let source = if use_versions_host
&& mirror_source(repo)
&& !crate::versions_host::github_release_is_url_replaced(repo, tag)
{
"hosted-2"
} else {
"direct"
};
let api_url = strip_url_credentials_in_arg(api_url);
let api_url = api_url.as_ref();
format!(
"{}-{}-{source}",
format!("{api_url}-{repo}-{tag}").to_kebab_case(),
crate::hash::hash_to_str(&(api_url, repo, tag))
)
}
#[doc(hidden)]
pub fn release_cache_key_for_test(repo: &str, tag: &str) -> String {
release_cache_key(API_URL, repo, tag, true)
}
fn should_cache_release(release: &GithubRelease) -> bool {
!release.assets.is_empty()
}
#[cfg_attr(windows, allow(dead_code))]
pub async fn get_release_with_build_revision_status(
repo: &str,
version: &str,
use_versions_host: bool,
) -> Result<(GithubRelease, bool)> {
let releases = list_releases(repo).await?;
pick_release_with_build_revision_status(releases, repo, version, use_versions_host).await
}
#[cfg_attr(windows, allow(dead_code))]
pub async fn get_release_including_prereleases_with_build_revision_status(
repo: &str,
version: &str,
use_versions_host: bool,
) -> Result<(GithubRelease, bool)> {
let releases = list_releases_including_prereleases(repo).await?;
pick_release_with_build_revision_status(releases, repo, version, use_versions_host).await
}
#[cfg_attr(windows, allow(dead_code))]
async fn pick_release_with_build_revision_status(
releases: Vec<GithubRelease>,
repo: &str,
version: &str,
use_versions_host: bool,
) -> Result<(GithubRelease, bool)> {
match pick_best_numeric_build_revision(releases.clone(), version) {
Some(release) => Ok((release, true)),
None => match pick_best_build_revision(releases, version) {
Some(release) => Ok((release, false)),
None => Ok((
get_release_with_versions_host(repo, version, use_versions_host).await?,
false,
)),
},
}
}
#[cfg_attr(windows, allow(dead_code))]
fn pick_best_numeric_build_revision(
releases: Vec<GithubRelease>,
version: &str,
) -> Option<GithubRelease> {
let prefix = format!("{version}-");
releases
.into_iter()
.filter_map(|r| {
let revision = r
.tag_name
.strip_prefix(&prefix)
.and_then(|suffix| suffix.parse::<u32>().ok())?;
Some((revision, r))
})
.max_by_key(|(revision, _)| *revision)
.map(|(_, release)| release)
}
#[cfg_attr(windows, allow(dead_code))]
fn pick_best_build_revision(releases: Vec<GithubRelease>, version: &str) -> Option<GithubRelease> {
let prefix = format!("{version}-");
releases
.into_iter()
.filter(|r| {
r.tag_name == version
|| r.tag_name
.strip_prefix(&prefix)
.is_some_and(|suffix| suffix.parse::<u32>().is_ok())
})
.max_by_key(|r| {
r.tag_name
.strip_prefix(&prefix)
.and_then(|s| s.parse::<u32>().ok())
.unwrap_or(0)
})
}
async fn get_release_with_options(
api_url: &str,
repo: &str,
tag: &str,
use_versions_host: bool,
) -> Result<GithubRelease> {
if use_versions_host
&& mirrors_github_metadata(api_url, repo)
&& !crate::versions_host::github_release_is_url_replaced(repo, tag)
{
let what = format!("GitHub release {repo}@{tag}");
let mirrored = crate::versions_host::github_release(repo, tag).await;
if let Ok(Some(_)) = &mirrored {
trace!("got {what} from mise-versions");
}
let release = mirror_or_github(&what, mirrored, async || {
get_release_from_api(api_url, repo, tag).await.map(Some)
})
.await?;
match release {
Some(release) => return Ok(release),
None => after_mirror_404(repo, &what).await?,
}
}
get_release_from_api(api_url, repo, tag).await
}
async fn get_release_from_api(api_url: &str, repo: &str, tag: &str) -> Result<GithubRelease> {
let url = if tag == "latest" {
format!("{api_url}/repos/{repo}/releases/latest")
} else {
format!(
"{api_url}/repos/{repo}/releases/tags/{}",
urlencoding::encode(tag)
)
};
let headers = get_headers(&url, api_url)?;
crate::http::HTTP_FETCH
.json_with_headers(url, &headers)
.await
}
fn is_public_github_api_base(api_url: &str) -> bool {
api_url.trim_end_matches('/') == API_URL
}
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("github")
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum TokenSource {
EnvVar(&'static str),
TokensFile,
GhCli,
CredentialCommand,
GithubOauth,
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, "github_tokens.toml"),
TokenSource::GhCli => write!(f, "gh CLI (hosts.yml)"),
TokenSource::CredentialCommand => write!(f, "credential_command"),
TokenSource::GithubOauth => write!(f, "GitHub OAuth"),
TokenSource::GitCredential => write!(f, "git credential fill"),
}
}
}
fn canonical_token_host(host: &str) -> &str {
match host {
"api.github.com" => "github.com",
"raw.githubusercontent.com" => "github.com",
h if is_ghe_com_api_host(h) => h.strip_prefix("api.").unwrap_or(h),
other => other,
}
}
pub fn is_github_raw_content_url(url: &url::Url) -> bool {
url.scheme() == "https" && url.host_str() == Some("raw.githubusercontent.com")
}
fn is_github_release_asset_host(host: &str) -> bool {
matches!(
host,
"objects.githubusercontent.com"
| "objects-origin.githubusercontent.com"
| "release-assets.githubusercontent.com"
)
}
fn is_ghe_com_api_host(host: &str) -> bool {
host.starts_with("api.") && host.ends_with(".ghe.com")
}
fn is_ghes_api_path(path: &str) -> bool {
path == API_PATH
|| path
.strip_prefix(API_PATH)
.is_some_and(|rest| rest.starts_with('/'))
}
fn token_lookup_hosts(host: &str) -> Vec<&str> {
let canonical = canonical_token_host(host);
if canonical == host {
vec![host]
} else {
vec![canonical, host]
}
}
pub fn is_github_api_url(url: &url::Url) -> bool {
let Some(host) = url.host_str() else {
return false;
};
host == "api.github.com"
|| is_ghe_com_api_host(host)
|| (host != "github.com"
&& !host.ends_with(".githubusercontent.com")
&& !host.ends_with(".ghe.com")
&& is_ghes_api_path(url.path()))
}
fn may_send_token(url: &url::Url, api_url: &str) -> bool {
may_send_token_with(url, api_url, &Settings::get().github.enterprise_hosts)
}
fn is_loopback(url: &url::Url) -> bool {
match url.host() {
Some(url::Host::Domain(domain)) => domain.eq_ignore_ascii_case("localhost"),
Some(url::Host::Ipv4(ip)) => ip.is_loopback(),
Some(url::Host::Ipv6(ip)) => ip.is_loopback(),
None => false,
}
}
fn may_send_token_with(url: &url::Url, api_url: &str, enterprise_hosts: &[String]) -> bool {
match url.host_str() {
Some(host) if host == "api.github.com" || is_ghe_com_api_host(host) => {
url.scheme() == "https"
}
Some(host) => {
(url.scheme() == "https" || is_loopback(url))
&& is_github_api_url(url)
&& (url::Url::parse(api_url).is_ok_and(|api_url| url.origin() == api_url.origin())
|| enterprise_hosts.iter().any(|listed| {
listed
.trim()
.trim_end_matches('.')
.eq_ignore_ascii_case(host)
}))
}
None => false,
}
}
const PROBE_RETRIES: i64 = 1;
pub async fn pick_reachable_asset_url(browser_url: &str, api_url: &str) -> String {
if browser_url == api_url {
return browser_url.to_string();
}
match crate::http::HTTP
.head_without_netrc(browser_url, PROBE_RETRIES)
.await
{
Ok(resp) => {
let is_html = resp
.headers()
.get("content-type")
.and_then(|v| v.to_str().ok())
.is_some_and(|ct| ct.to_ascii_lowercase().contains("text/html"));
if is_html {
debug!(
"browser URL returned HTML (likely an auth page), \
using the API asset endpoint"
);
checked_api_asset_url(browser_url, api_url).await
} else {
browser_url.to_string()
}
}
Err(e) => {
debug!("HEAD on browser URL failed ({e}), using the API asset endpoint");
checked_api_asset_url(browser_url, api_url).await
}
}
}
fn confirmed_asset_path(browser_url: &str, api_url: &str) -> PathBuf {
cache_dir()
.join("confirmed-assets")
.join(crate::hash::hash_to_str(&(api_url, browser_url)))
}
fn remember_confirmed_asset(path: &Path, browser_url: &str, api_url: &str) -> Result<()> {
if let Some(parent) = path.parent() {
crate::file::create_dir_all(parent)?;
}
crate::file::write(path, format!("{api_url}\n{browser_url}\n"))?;
Ok(())
}
pub async fn checked_api_asset_url(browser_url: &str, api_url: &str) -> String {
if !crate::versions_host::is_mirrored_asset_api_url(api_url) {
return api_url.to_string();
}
let confirmed = confirmed_asset_path(browser_url, api_url);
if confirmed.is_file() {
return api_url.to_string();
}
let asset = async {
let mut headers = get_headers(api_url, API_URL)?;
headers.insert(
"accept",
HeaderValue::from_static("application/vnd.github+json"),
);
crate::http::HTTP_FETCH
.json_with_headers::<GithubAsset, _>(api_url, &headers)
.await
};
match asset.await {
Ok(asset) if same_release_download(browser_url, &asset.browser_download_url) => {
if let Err(err) = remember_confirmed_asset(&confirmed, browser_url, api_url) {
debug!("could not record the confirmed GitHub release asset {api_url}: {err:#}");
}
api_url.to_string()
}
Ok(asset) => {
warn!(
"GitHub release asset {api_url} is {}, not {browser_url}; not using it",
asset.browser_download_url
);
browser_url.to_string()
}
Err(err) => {
warn!("could not confirm GitHub release asset {api_url} is {browser_url}: {err:#}");
browser_url.to_string()
}
}
}
fn same_release_download(a: &str, b: &str) -> bool {
fn tag_and_file(url: &str) -> Option<String> {
let url = url::Url::parse(url).ok()?;
let (_, rest) = url.path().split_once("/releases/download/")?;
urlencoding::decode(rest).ok().map(|rest| rest.into_owned())
}
tag_and_file(a).is_some_and(|a| tag_and_file(b).is_some_and(|b| a == b))
}
pub fn release_asset_from_url(url: &str) -> Option<(String, String, String)> {
let url = url::Url::parse(url).ok()?;
if url.host_str()? != "github.com" {
return None;
}
let segments = url.path_segments()?.collect::<Vec<_>>();
let [owner, repo, "releases", "download", tail @ ..] = segments.as_slice() else {
return None;
};
let (asset, tag) = tail.split_last()?;
if tag.is_empty() || asset.is_empty() {
return None;
}
let tag = tag
.iter()
.map(|segment| urlencoding::decode(segment).map(|s| s.into_owned()))
.collect::<Result<Vec<_>, _>>()
.ok()?
.join("/");
let asset = urlencoding::decode(asset).ok()?.into_owned();
Some((format!("{owner}/{repo}"), tag, asset))
}
pub async fn checksum_mismatch_note(
download_url: &str,
file: &Path,
from_lockfile: bool,
) -> Option<String> {
let (repo, tag, asset_name) = release_asset_from_url(download_url)?;
let (release, source) = digests_for_checksum_note(&repo, &tag).await?;
let actual = match crate::hash::file_hash_sha256(file, None) {
Ok(actual) => actual,
Err(err) => {
debug!(
"failed to hash {} after checksum mismatch: {err:#}",
file.display()
);
return None;
}
};
replaced_asset_note(&repo, &release, &asset_name, &actual, from_lockfile, source)
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum DigestSource {
VersionsHost,
GitHub,
}
async fn digests_for_checksum_note(repo: &str, tag: &str) -> Option<(GithubRelease, DigestSource)> {
if crate::versions_host::enabled_for_github_repo(repo)
&& !crate::versions_host::github_release_is_url_replaced(repo, tag)
{
match MirrorAnswer::from_result(crate::versions_host::github_release(repo, tag).await) {
Ok(MirrorAnswer::Answered(Some(release))) => {
return Some((release, DigestSource::VersionsHost));
}
Ok(MirrorAnswer::Answered(None)) => return None,
Ok(MirrorAnswer::Unavailable(err)) => debug!(
"mise-versions could not describe {repo}@{tag} for a checksum hint, asking GitHub: {err:#}"
),
Err(err) => {
debug!(
"mise-versions could not describe {repo}@{tag} for a checksum hint: {err:#}"
);
return None;
}
}
}
match get_release_from_api(API_URL, repo, tag).await {
Ok(release) => Some((release, DigestSource::GitHub)),
Err(err) => {
debug!("failed to check GitHub release {repo}@{tag} after checksum mismatch: {err:#}");
None
}
}
}
pub async fn with_checksum_mismatch_note(
err: eyre::Report,
download_url: &str,
file: &Path,
from_lockfile: bool,
) -> eyre::Report {
if !err
.chain()
.any(|cause| cause.is::<crate::hash::ChecksumMismatch>())
{
return err;
}
match checksum_mismatch_note(download_url, file, from_lockfile).await {
Some(note) => eyre::eyre!("{err:#}\nhint: {note}"),
None => err,
}
}
fn replaced_asset_note(
repo: &str,
release: &GithubRelease,
asset_name: &str,
actual_sha256: &str,
from_lockfile: bool,
source: DigestSource,
) -> Option<String> {
let asset = release
.assets
.iter()
.find(|asset| asset.name == asset_name)?;
let digest = asset.digest.as_deref()?;
if !digest
.strip_prefix("sha256:")
.is_some_and(|hash| hash.eq_ignore_ascii_case(actual_sha256))
{
return None;
}
let tag = &release.tag_name;
let timing = match (&asset.updated_at, &release.published_at) {
(Some(updated_at), Some(published_at)) => {
format!(" (asset updated {updated_at}, release published {published_at})")
}
(Some(updated_at), None) => format!(" (asset updated {updated_at})"),
_ => String::new(),
};
let remedy = if from_lockfile {
"If you trust the new upload, update the checksum in mise.lock."
} else {
"The expected checksum came from cached release metadata, which refreshes within \
about an hour; `mise cache clear` drops mise's local copy."
};
let whose = match source {
DigestSource::GitHub => "GitHub's current digest",
DigestSource::VersionsHost => "The digest mise-versions has from GitHub",
};
Some(format!(
"{whose} for {asset_name} in {repo} {tag} matches this download{timing}, \
so the expected checksum is out of date: the maintainer likely re-uploaded the asset. \
{remedy}"
))
}
pub async fn release_asset_api_url(browser_url: &str, use_versions_host: bool) -> Option<String> {
let (repo, tag, asset_name) = release_asset_from_url(browser_url)?;
let release = match get_release_with_versions_host(&repo, &tag, use_versions_host).await {
Ok(release) => release,
Err(err) => {
debug!("failed to resolve GitHub release asset {repo}@{tag}/{asset_name}: {err:#}");
return None;
}
};
match release.assets.iter().find(|asset| asset.name == asset_name) {
Some(asset) => Some(asset.url.clone()),
None => {
debug!("GitHub release {repo}@{tag} did not include asset {asset_name}");
None
}
}
}
const GITHUB_TOKEN_ENV_VARS: &[&str] = &["MISE_GITHUB_TOKEN", "GITHUB_API_TOKEN", "GITHUB_TOKEN"];
static TOKEN_SOURCES: Lazy<Mutex<HashMap<String, (String, TokenSource)>>> =
Lazy::new(Default::default);
pub fn remember_token_source(host: &str, token: &str, source: TokenSource) {
TOKEN_SOURCES
.lock()
.unwrap()
.insert(host.to_string(), (token.to_string(), source));
}
pub fn token_source_for_token(host: &str, token: &str) -> Option<TokenSource> {
TOKEN_SOURCES
.lock()
.unwrap()
.get(host)
.filter(|(recorded, _)| recorded == token)
.map(|(_, source)| source.clone())
}
pub fn resolve_token(host: &str) -> Option<(String, TokenSource)> {
resolve_token_inner(host, true)
}
pub fn resolve_token_for_git(host: &str) -> Option<(String, TokenSource)> {
resolve_token_inner(host, false)
}
fn resolve_token_inner(host: &str, use_git_credentials: bool) -> Option<(String, TokenSource)> {
let settings = Settings::get();
if is_github_release_asset_host(host) {
return None;
}
if crate::untrusted_hosts::forge_token_denied(host) {
return None;
}
if crate::testing::in_tests()
&& let Some(token) = test_support::lookup_tokens_file_override(&token_lookup_hosts(host))
{
return Some((token, TokenSource::TokensFile));
}
let is_ghcom = canonical_token_host(host) == "github.com";
let lookup_hosts = token_lookup_hosts(host);
if !is_ghcom && let Some(token) = env::scoped_var("MISE_GITHUB_ENTERPRISE_TOKEN") {
return Some((token, TokenSource::EnvVar("MISE_GITHUB_ENTERPRISE_TOKEN")));
}
for var_name in GITHUB_TOKEN_ENV_VARS {
if let Some(token) = env::scoped_var(var_name) {
return Some((token, TokenSource::EnvVar(var_name)));
}
}
let credential_command = &settings.github.credential_command;
if use_git_credentials
&& !credential_command.is_empty()
&& let Some(canonical) = lookup_hosts.first()
&& let Some(token) =
tokens::get_credential_command_token("github", credential_command, canonical)
{
return Some((token, TokenSource::CredentialCommand));
}
if let Some(token) = oauth::resolve_token(canonical_token_host(host)) {
return Some((token, TokenSource::GithubOauth));
}
for lookup_host in &lookup_hosts {
if let Some(token) = MISE_GITHUB_TOKENS.get(*lookup_host) {
return Some((token.clone(), TokenSource::TokensFile));
}
}
if settings.github.gh_cli_tokens {
for lookup_host in &lookup_hosts {
if let Some(token) = GH_HOSTS.get(*lookup_host) {
return Some((token.clone(), TokenSource::GhCli));
}
}
}
if use_git_credentials && settings.github.use_git_credentials {
for lookup_host in &lookup_hosts {
if let Some(token) = tokens::get_git_credential_token("github", lookup_host) {
return Some((token, TokenSource::GitCredential));
}
}
}
None
}
pub fn resolve_token_for_api_url(api_url: &str) -> Option<String> {
let parsed = url::Url::parse(api_url).ok();
let host = parsed
.as_ref()
.and_then(|u| u.host_str())
.unwrap_or("api.github.com");
resolve_token(host).map(|(t, _)| t)
}
pub fn get_headers<U: IntoUrl>(url: U, api_url: &str) -> Result<HeaderMap> {
let mut headers = HeaderMap::new();
let url = url
.into_url()
.wrap_err("invalid request URL for GitHub auth headers")?;
if may_send_token(&url, api_url) {
let host = url.host_str().unwrap_or("github.com");
if let Some((token, source)) = resolve_token(host) {
remember_token_source(host, &token, source);
headers.insert(
reqwest::header::AUTHORIZATION,
tokens::bearer_header("GitHub", &token)?,
);
headers.insert(
"x-github-api-version",
HeaderValue::from_static("2022-11-28"),
);
} else {
TOKEN_SOURCES.lock().unwrap().remove(host);
}
}
if !is_github_api_url(&url)
&& is_github_raw_content_url(&url)
&& let Some((token, source)) = resolve_token("raw.githubusercontent.com")
{
remember_token_source("raw.githubusercontent.com", &token, source);
headers.insert(
reqwest::header::AUTHORIZATION,
tokens::bearer_header("GitHub", &token)?,
);
}
if is_github_api_url(&url) && url.path().contains("/releases/assets/") {
headers.insert(
"accept",
HeaderValue::from_static("application/octet-stream"),
);
} else if is_github_api_url(&url) && url.path().contains("/contents/") {
headers.insert(
"accept",
HeaderValue::from_static("application/vnd.github.raw"),
);
}
Ok(headers)
}
static MISE_GITHUB_TOKENS: Lazy<HashMap<String, String>> =
Lazy::new(|| read_mise_github_tokens().unwrap_or_default());
#[cfg(test)]
fn parse_github_tokens(contents: &str) -> Option<HashMap<String, String>> {
tokens::parse_tokens_toml(contents)
}
fn read_mise_github_tokens() -> Option<HashMap<String, String>> {
tokens::read_tokens_toml("github_tokens.toml", "github_tokens.toml")
}
static GH_HOSTS: Lazy<HashMap<String, String>> = Lazy::new(|| read_gh_hosts().unwrap_or_default());
fn gh_hosts_path() -> Option<PathBuf> {
if let Some(dir) = std::env::var_os("GH_CONFIG_DIR").filter(|dir| !dir.is_empty()) {
return Some(PathBuf::from(dir).join("hosts.yml"));
}
let xdg_path = env::var_path("XDG_CONFIG_HOME").map(|dir| dir.join("gh/hosts.yml"));
let fallback = xdg_path.clone().unwrap_or_else(gh_default_hosts_path);
let candidates = xdg_path
.into_iter()
.chain(gh_native_hosts_paths())
.collect();
Some(tokens::first_existing_file(candidates, fallback))
}
#[cfg(windows)]
fn gh_appdata_hosts_path() -> Option<PathBuf> {
std::env::var_os("APPDATA")
.filter(|v| !v.is_empty())
.map(|v| PathBuf::from(v).join("GitHub CLI/hosts.yml"))
}
#[cfg(windows)]
fn gh_default_hosts_path() -> PathBuf {
gh_appdata_hosts_path().unwrap_or_else(|| dirs::HOME.join(".config/gh/hosts.yml"))
}
#[cfg(not(windows))]
fn gh_default_hosts_path() -> PathBuf {
dirs::HOME.join(".config/gh/hosts.yml")
}
#[cfg(target_os = "macos")]
fn gh_native_hosts_paths() -> Vec<PathBuf> {
vec![dirs::HOME.join("Library/Application Support/gh/hosts.yml")]
}
#[cfg(windows)]
fn gh_native_hosts_paths() -> Vec<PathBuf> {
gh_appdata_hosts_path().into_iter().collect()
}
#[cfg(all(not(target_os = "macos"), not(windows)))]
fn gh_native_hosts_paths() -> Vec<PathBuf> {
Vec::new()
}
fn read_gh_host_entries() -> Option<HashMap<String, GhHostEntry>> {
let hosts_path = gh_hosts_path()?;
let contents = match std::fs::read_to_string(&hosts_path) {
Ok(c) => c,
Err(e) => {
trace!("gh hosts.yml not readable at {}: {e}", hosts_path.display());
return None;
}
};
match crate::yaml::from_str(&contents) {
Ok(h) => Some(h),
Err(e) => {
debug!(
"failed to parse gh hosts.yml at {}: {e}",
hosts_path.display()
);
None
}
}
}
fn read_gh_hosts() -> Option<HashMap<String, String>> {
Some(
read_gh_host_entries()?
.into_iter()
.filter_map(|(host, entry)| {
entry
.oauth_token
.filter(|token| !token.trim().is_empty())
.map(|token| (host, token))
})
.collect(),
)
}
pub fn gh_token_in_keyring(host: &str) -> bool {
if !Settings::get().github.gh_cli_tokens
|| is_github_release_asset_host(host)
|| crate::untrusted_hosts::forge_token_denied(host)
{
return false;
}
let Some(hosts) = read_gh_host_entries() else {
return false;
};
token_lookup_hosts(host)
.into_iter()
.filter_map(|lookup_host| hosts.get(lookup_host))
.any(GhHostEntry::has_user_without_token)
}
#[derive(Deserialize)]
struct GhHostEntry {
oauth_token: Option<String>,
user: Option<crate::yaml::Value>,
}
impl GhHostEntry {
fn has_user_without_token(&self) -> bool {
let has_user = self
.user
.as_ref()
.and_then(crate::yaml::Value::as_str)
.is_some_and(|user| !user.trim().is_empty());
let has_token = self
.oauth_token
.as_deref()
.is_some_and(|token| !token.trim().is_empty());
has_user && !has_token
}
}
#[doc(hidden)]
pub static TEST_ENV_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());
#[doc(hidden)]
pub mod test_support {
use std::collections::HashMap;
use std::sync::RwLock;
pub static TOKENS_FILE_OVERRIDE: RwLock<Option<HashMap<String, String>>> = RwLock::new(None);
pub fn lookup_tokens_file_override(lookup_hosts: &[&str]) -> Option<String> {
let guard = TOKENS_FILE_OVERRIDE.read().ok()?;
let map = guard.as_ref()?;
for host in lookup_hosts {
if let Some(token) = map.get(*host) {
return Some(token.clone());
}
}
None
}
}
#[cfg(test)]
mod tests;