Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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]
Expand Down
8 changes: 6 additions & 2 deletions src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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))]
Expand Down
29 changes: 26 additions & 3 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<T: HttpClient>(
http_client: GenericHttpClient<T>,
pkg: &Package,
) -> update_informer::Result<Option<String>> {
let url = format!("https://crates.io/api/v1/crates/{pkg}");
let response = http_client.get::<serde_json::Value>(&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");
Expand Down
80 changes: 42 additions & 38 deletions src/toolchain/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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},
Expand Down Expand Up @@ -584,51 +584,55 @@ pub fn github_query(url: &str) -> Result<serde_json::Value, Error> {
);

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<serde_json::Value, Error> = retry(
Fixed::from_millis(100).take(5),
|| -> Result<serde_json::Value, Error> {
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.
Expand Down
17 changes: 8 additions & 9 deletions src/toolchain/rust.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
Loading