diff --git a/CHANGELOG.md b/CHANGELOG.md index 9f9bd520..e5a18d97 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -16,6 +16,9 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - Fix RUSTSEC-2026-0381, RUSTSEC-2026-0382, RUSTSEC-2026-0383 by updating `rustls-webpki` to 0.103.16 and `webpki-roots`/`webpki-root-certs` to 1.0.10 (#594) - Fix RUSTSEC-2026-0386 by updating `tokio` to 1.54.1 (#600) - Fix RUSTSEC-2026-0385 by updating `ctutils` to 0.4.6 (#600) +- Ignore yanked versions when checking crates.io for a new `espup` version +- Ignore an empty `GITHUB_TOKEN` and report invalid tokens and GitHub API rate limits without retrying them +- Query the GitHub API once instead of twice when resolving the latest Xtensa Rust version ### Changed diff --git a/README.md b/README.md index 15f6c5ac..fec11f00 100644 --- a/README.md +++ b/README.md @@ -136,7 +136,7 @@ Options: > [!NOTE] > #### GitHub API -> During the installation process, several GitHub queries are made, [which are subject to certain limits](https://docs.github.com/en/rest/overview/resources-in-the-rest-api?apiVersion=2022-11-28#rate-limiting). Our number of queries should not hit the limit unless you are running `espup install` command numerous times in a short span of time. We recommend setting the [`GITHUB_TOKEN` environment variable](https://docs.github.com/en/actions/security-guides/automatic-token-authentication#about-the-github_token-secret) when using `espup` in CI, if you want to use `espup` on CI, recommend using it via the [`xtensa-toolchain` action](https://github.com/esp-rs/xtensa-toolchain/), and making sure `GITHUB_TOKEN` is not set when using it on a host machine. See https://github.com/esp-rs/xtensa-toolchain/issues/15 for more details on this. +> During the installation process, `espup` queries the GitHub API once to resolve the Xtensa Rust version. [Unauthenticated queries are limited to 60 per hour per IP address](https://docs.github.com/en/rest/using-the-rest-api/rate-limits-for-the-rest-api), a limit that is shared with every other client behind the same IP address (e.g. CI runners, VPNs, or corporate networks). If you hit it, set the `GITHUB_TOKEN` environment variable to a valid [GitHub token](https://docs.github.com/en/authentication/keeping-your-account-and-data-secure/managing-your-personal-access-tokens), which raises the limit. When set, `GITHUB_TOKEN` must be valid: an expired or revoked token makes the query fail. For CI, we recommend using the [`xtensa-toolchain` action](https://github.com/esp-rs/xtensa-toolchain/), which passes the workflow's [`GITHUB_TOKEN`](https://docs.github.com/en/actions/security-guides/automatic-token-authentication#about-the-github_token-secret) to `espup`. ``` Usage: espup install [OPTIONS] diff --git a/src/error.rs b/src/error.rs index e26ee293..baa1deaa 100644 --- a/src/error.rs +++ b/src/error.rs @@ -7,11 +7,15 @@ pub enum Error { CreateDirectory(String), #[diagnostic(code(espup::toolchain::rust::query_github))] - #[error("Failed to query GitHub API: Rate Limiting")] + #[error( + "Failed to query GitHub API: rate limit exceeded. Wait for the limit to reset or set `GITHUB_TOKEN` to a valid GitHub token" + )] GithubRateLimit, #[diagnostic(code(espup::toolchain::rust::query_github))] - #[error("Failed to query GitHub API: Invalid Github token")] + #[error( + "Failed to query GitHub API: invalid `GITHUB_TOKEN`. Unset it or set it to a valid GitHub token" + )] GithubTokenInvalid, #[diagnostic(code(espup::toolchain::rust::query_github))] diff --git a/src/lib.rs b/src/lib.rs index 54fa3a85..7c28f45f 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -37,14 +37,37 @@ pub mod logging { pub mod update { use log::warn; use std::time::Duration; - use update_informer::{Check, registry}; + use update_informer::{ + Check, Package, Registry, + http_client::{GenericHttpClient, HttpClient}, + }; + + /// crates.io registry that ignores yanked and pre-release versions. + /// + /// `update_informer::registry::Crates` reports the newest published version, + /// even when it has been yanked. + struct CratesStable; + + impl Registry for CratesStable { + const NAME: &'static str = "crates"; + + fn get_latest_version( + http_client: GenericHttpClient, + pkg: &Package, + ) -> update_informer::Result> { + let url = format!("https://crates.io/api/v1/crates/{pkg}"); + let response = http_client.get::(&url)?; + Ok(response["crate"]["max_stable_version"] + .as_str() + .map(str::to_string)) + } + } /// Check crates.io for a new version of the application pub fn check_for_update(name: &str, version: &str) { // By setting the interval to 0 seconds we invalidate the cache with each // invocation and ensure we're getting up-to-date results - let informer = - update_informer::new(registry::Crates, name, version).interval(Duration::ZERO); + let informer = update_informer::new(CratesStable, name, version).interval(Duration::ZERO); if let Some(version) = informer.check_version().ok().flatten() { warn!("A new version of {name} ('{version}') is available"); diff --git a/src/toolchain/mod.rs b/src/toolchain/mod.rs index 68063ac7..b767f073 100644 --- a/src/toolchain/mod.rs +++ b/src/toolchain/mod.rs @@ -18,8 +18,8 @@ use async_trait::async_trait; use flate2::bufread::GzDecoder; use log::{debug, info, warn}; use miette::Result; -use reqwest::{blocking::Client, header}; -use retry::{delay::Fixed, retry}; +use reqwest::{StatusCode, blocking::Client, header}; +use retry::{OperationResult, delay::Fixed, retry}; use std::{ env, fs::{File, OpenOptions, create_dir_all, remove_file}, @@ -584,51 +584,55 @@ pub fn github_query(url: &str) -> Result { ); headers.insert("X-GitHub-Api-Version", "2022-11-28".parse().unwrap()); - if let Some(token) = env::var_os("GITHUB_TOKEN") { - debug!("Auth header added"); - headers.insert( - "Authorization", - format!("Bearer {}", token.to_string_lossy()) - .parse() - .unwrap(), - ); + // An empty token would still be sent and rejected with 401. + let token = env::var("GITHUB_TOKEN") + .ok() + .filter(|token| !token.is_empty()); + if let Some(token) = &token { + info!("Using `GITHUB_TOKEN` to authenticate GitHub API requests"); + headers.insert("Authorization", format!("Bearer {token}").parse().unwrap()); } let client = build_proxy_blocking_client()?; - let json: Result = retry( - Fixed::from_millis(100).take(5), - || -> Result { - let response = client.get(url).headers(headers.clone()).send()?; - let status = response.status(); - - if !status.is_success() { - return Err(Error::HttpError(format!( + // Only retry transient failures: retrying authentication or rate limit + // errors cannot succeed and consumes more of the rate limit. + retry(Fixed::from_millis(100).take(5), || { + let response = match client.get(url).headers(headers.clone()).send() { + Ok(response) => response, + Err(err) => return OperationResult::Retry(Error::from(err)), + }; + let status = response.status(); + match status { + StatusCode::UNAUTHORIZED if token.is_some() => { + return OperationResult::Err(Error::GithubTokenInvalid); + } + StatusCode::FORBIDDEN | StatusCode::TOO_MANY_REQUESTS => { + return OperationResult::Err(Error::GithubRateLimit); + } + _ if status.is_server_error() => { + return OperationResult::Retry(Error::HttpError(format!( "GitHub API returned status code: {status}" ))); } - - let res = response.text()?; - - // Check for rate limiting response - if res.contains( - "https://docs.github.com/rest/overview/resources-in-the-rest-api#rate-limiting", - ) { - return Err(Error::GithubRateLimit); - } - - // Check for authentication errors - if res.contains("Bad credentials") { - return Err(Error::GithubTokenInvalid); + _ if !status.is_success() => { + return OperationResult::Err(Error::HttpError(format!( + "GitHub API returned status code: {status}" + ))); } + _ => {} + } - // Try to parse the JSON - serde_json::from_str(&res).map_err(|_| Error::SerializeJson) - }, - ) - .map_err(|err| err.error); - - json + let body = match response.text() { + Ok(body) => body, + Err(err) => return OperationResult::Retry(Error::from(err)), + }; + match serde_json::from_str(&body) { + Ok(json) => OperationResult::Ok(json), + Err(_) => OperationResult::Err(Error::SerializeJson), + } + }) + .map_err(|err| err.error) } /// Checks if the directory exists and deletes it if it does. diff --git a/src/toolchain/rust.rs b/src/toolchain/rust.rs index f9fa63ac..9a429e54 100644 --- a/src/toolchain/rust.rs +++ b/src/toolchain/rust.rs @@ -93,16 +93,15 @@ impl XtensaRust { let mut version = json["tag_name"].to_string(); version.retain(|c| c != 'v' && c != '"'); - // Validate the version format - handle both spawning and parsing errors - let parse_task = - tokio::task::spawn_blocking(move || Self::find_latest_version_on_github(&version)) - .await - .map_err(|_| Error::SerializeJson)?; - - let validated_version = parse_task?; + if !Regex::new(RE_EXTENDED_SEMANTIC_VERSION) + .unwrap() + .is_match(&version) + { + return Err(Error::InvalidVersion(version)); + } - debug!("Latest Xtensa Rust version: {validated_version}"); - Ok(validated_version) + debug!("Latest Xtensa Rust version: {version}"); + Ok(version) } /// Create a new instance.