#[cfg(feature = "archive-zip")]
use zip::result::ZipError;
pub type Result<T> = std::result::Result<T, Error>;
#[cfg(feature = "signatures")]
use zipsign_api::ZipsignError;
#[derive(Debug)]
#[non_exhaustive]
pub enum Error {
#[non_exhaustive]
Internal {
message: String,
source: Option<Box<dyn std::error::Error + Send + Sync>>,
},
#[non_exhaustive]
VerificationRejected {
reason: Option<String>,
},
#[non_exhaustive]
ArchiveVerificationRejected {
reason: Option<String>,
},
#[non_exhaustive]
ChecksumSourceInvalid {
asset: String,
reason: String,
},
#[non_exhaustive]
ChecksumMismatch {
expected: String,
computed: String,
},
Aborted,
#[non_exhaustive]
NotFound {
url: String,
},
#[non_exhaustive]
Unauthorized {
status: u16,
url: String,
},
#[non_exhaustive]
RateLimited {
status: u16,
url: String,
reset_at: Option<std::time::SystemTime>,
retry_after: Option<std::time::Duration>,
},
#[non_exhaustive]
HttpStatus {
status: u16,
url: String,
},
#[non_exhaustive]
NoReleaseFound {
target: Option<String>,
},
#[non_exhaustive]
MissingAssetField {
field: String,
},
#[non_exhaustive]
InvalidResponse {
source: Box<dyn std::error::Error + Send + Sync>,
},
#[non_exhaustive]
MissingField {
field: &'static str,
},
#[non_exhaustive]
InstallPathNotWritable {
path: std::path::PathBuf,
},
#[non_exhaustive]
NoAppBundle {
exe: std::path::PathBuf,
},
#[non_exhaustive]
ConflictingConfig {
field: &'static str,
conflict: &'static str,
},
#[non_exhaustive]
AppTranslocated {
exe: std::path::PathBuf,
},
NoCurrentVersion,
#[non_exhaustive]
InvalidHeader {
source: Box<dyn std::error::Error + Send + Sync>,
},
#[non_exhaustive]
InvalidAuthToken {
source: Box<dyn std::error::Error + Send + Sync>,
},
#[non_exhaustive]
InvalidCertificate {
source: Box<dyn std::error::Error + Send + Sync>,
},
#[non_exhaustive]
InvalidProxy {
source: Box<dyn std::error::Error + Send + Sync>,
},
#[cfg(feature = "progress-bar")]
#[non_exhaustive]
InvalidProgressStyle {
source: Box<dyn std::error::Error + Send + Sync>,
},
Io(std::io::Error),
#[cfg(feature = "archive-zip")]
Zip(Box<dyn std::error::Error + Send + Sync>),
Json(Box<dyn std::error::Error + Send + Sync>),
Transport(Box<dyn std::error::Error + Send + Sync>),
SemVer(Box<dyn std::error::Error + Send + Sync>),
ArchiveNotEnabled(String),
CompressionNotEnabled(String),
#[cfg(feature = "signatures")]
NoSignatures(crate::ArchiveKind),
#[cfg(feature = "signatures")]
Signature(Box<dyn std::error::Error + Send + Sync>),
#[non_exhaustive]
InvalidAssetName {
name: String,
},
#[cfg(feature = "signatures")]
SignatureNonUTF8,
#[cfg(feature = "s3-auth")]
S3Auth(Box<dyn std::error::Error + Send + Sync>),
#[cfg(feature = "s3")]
#[non_exhaustive]
InvalidAssetKeyPattern {
source: Box<dyn std::error::Error + Send + Sync>,
},
}
impl Error {
pub fn http_status(&self) -> Option<u16> {
match self {
Error::NotFound { .. } => Some(404),
Error::Unauthorized { status, .. } => Some(*status),
Error::RateLimited { status, .. } => Some(*status),
Error::HttpStatus { status, .. } => Some(*status),
_ => None,
}
}
pub fn url(&self) -> Option<&str> {
match self {
Error::NotFound { url } => Some(url.as_str()),
Error::Unauthorized { url, .. } => Some(url.as_str()),
Error::RateLimited { url, .. } => Some(url.as_str()),
Error::HttpStatus { url, .. } => Some(url.as_str()),
_ => None,
}
}
pub fn rate_limit_delay(&self) -> Option<std::time::Duration> {
match self {
Error::RateLimited {
reset_at,
retry_after,
..
} => retry_after.or_else(|| {
reset_at.and_then(|at| at.duration_since(std::time::SystemTime::now()).ok())
}),
_ => None,
}
}
pub fn no_release_found() -> Error {
Error::NoReleaseFound { target: None }
}
pub fn no_release_found_for_target(target: impl Into<String>) -> Error {
Error::NoReleaseFound {
target: Some(target.into()),
}
}
pub fn missing_asset_field(field: impl Into<String>) -> Error {
Error::MissingAssetField {
field: field.into(),
}
}
pub fn checksum_mismatch(expected: impl Into<String>, computed: impl Into<String>) -> Error {
Error::ChecksumMismatch {
expected: expected.into(),
computed: computed.into(),
}
}
pub fn invalid_response(source: impl Into<Box<dyn std::error::Error + Send + Sync>>) -> Error {
Error::InvalidResponse {
source: source.into(),
}
}
pub fn http_status_error(status: u16, url: impl Into<String>) -> Error {
status_to_error(status, &url.into())
}
pub fn http_status_error_with_headers(
status: u16,
url: impl Into<String>,
headers: &crate::http_client::HeaderMap,
) -> Error {
status_to_error_with_headers(status, &url.into(), headers)
}
pub fn transport(source: impl Into<Box<dyn std::error::Error + Send + Sync>>) -> Error {
Error::Transport(source.into())
}
pub fn verification_rejected(reason: impl Into<String>) -> Error {
Error::VerificationRejected {
reason: Some(reason.into()),
}
}
pub fn archive_verification_rejected(reason: impl Into<String>) -> Error {
Error::ArchiveVerificationRejected {
reason: Some(reason.into()),
}
}
}
impl std::fmt::Display for Error {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
use Error::*;
match self {
Internal { message, .. } => write!(f, "InternalError: {}", message),
VerificationRejected { reason } => match reason {
Some(reason) => write!(
f,
"VerificationRejectedError: post-update verification rejected the new binary: {}",
reason
),
None => write!(
f,
"VerificationRejectedError: post-update verification rejected the new binary"
),
},
ArchiveVerificationRejected { reason } => match reason {
Some(reason) => write!(
f,
"ArchiveVerificationRejectedError: verification rejected the downloaded archive: {}",
reason
),
None => write!(
f,
"ArchiveVerificationRejectedError: verification rejected the downloaded archive"
),
},
ChecksumSourceInvalid { asset, reason } => write!(
f,
"ChecksumSourceInvalidError: could not resolve a checksum for `{}`: {}",
asset, reason
),
ChecksumMismatch { expected, computed } => write!(
f,
"ChecksumMismatchError: checksum mismatch (expected {}, computed {})",
expected, computed
),
Aborted => write!(f, "AbortedError: the update was not confirmed"),
NotFound { url } => write!(f, "NotFoundError: no resource found at {} (HTTP 404)", url),
Unauthorized { status, url } => write!(
f,
"UnauthorizedError: request to {} was not authorized (HTTP {})",
url, status
),
RateLimited {
status,
url,
retry_after,
..
} => {
write!(
f,
"RateLimitedError: request to {} was rate limited (HTTP {})",
url, status
)?;
match retry_after {
Some(wait) => write!(f, "; retry in {}s", wait.as_secs())?,
None => {
if let Some(wait) = self.rate_limit_delay() {
write!(f, "; quota resets in {}s", wait.as_secs())?;
}
}
}
write!(
f,
"; set an auth token to raise the limit, or check less often"
)
}
HttpStatus { status, url } => write!(
f,
"HttpStatusError: request to {} failed with status {}",
url, status
),
NoReleaseFound { target } => match target {
Some(target) => write!(
f,
"ReleaseError: no release found with an asset for target `{}`",
target
),
None => write!(f, "ReleaseError: no release was found"),
},
MissingAssetField { field } => {
write!(f, "ReleaseError: release/asset payload missing `{}`", field)
}
InvalidResponse { source } => write!(f, "ReleaseError: invalid response: {}", source),
MissingField { field } => write!(f, "ConfigError: `{}` required", field),
InstallPathNotWritable { path } => write!(
f,
"InstallPathNotWritableError: cannot write to install path {}: run with elevated \
privileges or configure a user-writable install path",
path.display()
),
NoAppBundle { exe } => write!(
f,
"ConfigError: no `.app` ancestor of {}; set bundle_install_path explicitly",
exe.display()
),
ConflictingConfig { field, conflict } => write!(
f,
"ConfigError: `{}` conflicts with `{}`; set one or the other",
field, conflict
),
AppTranslocated { exe } => write!(
f,
"AppTranslocatedError: {} is running from a translocated (quarantined) copy on a \
read-only mount, so its bundle cannot be replaced: move the app (e.g. to \
/Applications) and relaunch it before updating",
exe.display()
),
NoCurrentVersion => write!(
f,
"ReleaseError: this Releases has no current_version to compare against; use \
`Update::is_update_available` for a configured updater"
),
InvalidHeader { source } => write!(f, "ConfigError: invalid HTTP header: {}", source),
InvalidAuthToken { source } => {
write!(f, "ConfigError: failed to parse auth token: {}", source)
}
InvalidCertificate { source } => {
write!(f, "ConfigError: invalid root certificate: {}", source)
}
InvalidProxy { source } => {
write!(f, "ConfigError: invalid proxy: {}", source)
}
#[cfg(feature = "progress-bar")]
InvalidProgressStyle { source } => {
write!(f, "ConfigError: invalid progress bar template: {}", source)
}
Io(e) => write!(f, "IoError: {}", e),
Json(e) => write!(f, "JsonError: {}", e),
Transport(e) => write!(f, "TransportError: {}", e),
SemVer(e) => write!(f, "SemVerError: {}", e),
#[cfg(feature = "archive-zip")]
Zip(e) => write!(f, "ZipError: {}", e),
ArchiveNotEnabled(s) => write!(
f,
"ArchiveNotEnabledError: archive extension '{}' not supported; enable the 'archive-{}' feature",
s, s
),
CompressionNotEnabled(s) => write!(
f,
"CompressionNotEnabledError: '{}' compression not supported, please enable the 'compression-tar-gz' feature (a `.tar.gz` also needs 'archive-tar')",
s
),
#[cfg(feature = "signatures")]
NoSignatures(kind) => write!(
f,
"SignatureError: signature verification is only implemented for `.tar.gz` and \
`.zip` assets, not {} files",
kind
),
#[cfg(feature = "signatures")]
Signature(e) => write!(f, "SignatureError: {}", e),
InvalidAssetName { name } => {
write!(f, "InvalidAssetNameError: unsafe asset name: {:?}", name)
}
#[cfg(feature = "signatures")]
SignatureNonUTF8 => {
write!(
f,
"SignatureError: cannot verify signature of a file with a non-UTF-8 name"
)
}
#[cfg(feature = "s3-auth")]
S3Auth(e) => write!(f, "S3AuthError: {}", e),
#[cfg(feature = "s3")]
InvalidAssetKeyPattern { source } => {
write!(f, "ConfigError: invalid asset_key_pattern: {}", source)
}
}
}
}
impl std::error::Error for Error {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
Some(match *self {
Error::Internal {
source: Some(ref e),
..
} => &**e,
Error::InvalidResponse { ref source } => &**source,
Error::InvalidHeader { ref source } => &**source,
Error::InvalidAuthToken { ref source } => &**source,
Error::InvalidCertificate { ref source } => &**source,
Error::InvalidProxy { ref source } => &**source,
#[cfg(feature = "progress-bar")]
Error::InvalidProgressStyle { ref source } => &**source,
Error::Io(ref e) => e,
Error::Json(ref e) => &**e,
Error::Transport(ref e) => &**e,
Error::SemVer(ref e) => &**e,
#[cfg(feature = "archive-zip")]
Error::Zip(ref e) => &**e,
#[cfg(feature = "signatures")]
Error::Signature(ref e) => &**e,
#[cfg(feature = "s3-auth")]
Error::S3Auth(ref e) => &**e,
#[cfg(feature = "s3")]
Error::InvalidAssetKeyPattern { ref source } => &**source,
_ => return None,
})
}
}
#[derive(Debug)]
pub(crate) struct MessageError(pub(crate) String);
impl std::fmt::Display for MessageError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(&self.0)
}
}
impl std::error::Error for MessageError {}
impl From<std::io::Error> for Error {
fn from(e: std::io::Error) -> Error {
Error::Io(e)
}
}
impl From<serde_json::Error> for Error {
fn from(e: serde_json::Error) -> Error {
Error::Json(Box::new(e))
}
}
#[cfg(feature = "reqwest")]
impl From<reqwest::Error> for Error {
fn from(e: reqwest::Error) -> Error {
Error::Transport(Box::new(e))
}
}
#[cfg(feature = "ureq")]
impl From<ureq::Error> for Error {
fn from(e: ureq::Error) -> Error {
Error::Transport(Box::new(e))
}
}
impl From<semver::Error> for Error {
fn from(e: semver::Error) -> Error {
Error::SemVer(Box::new(e))
}
}
#[cfg(feature = "archive-zip")]
impl From<ZipError> for Error {
fn from(e: ZipError) -> Error {
Error::Zip(Box::new(e))
}
}
#[cfg(feature = "signatures")]
impl From<ZipsignError> for Error {
fn from(e: ZipsignError) -> Error {
Error::Signature(Box::new(e))
}
}
#[cfg(feature = "s3-auth")]
impl From<std::time::SystemTimeError> for Error {
fn from(e: std::time::SystemTimeError) -> Self {
Error::S3Auth(Box::new(e))
}
}
#[cfg(feature = "s3-auth")]
impl From<hmac::digest::InvalidLength> for Error {
fn from(e: hmac::digest::InvalidLength) -> Self {
Error::S3Auth(Box::new(e))
}
}
#[cfg(feature = "s3-auth")]
impl From<url::ParseError> for Error {
fn from(e: url::ParseError) -> Self {
Error::S3Auth(Box::new(e))
}
}
#[cfg(feature = "s3-auth")]
impl From<time::error::ComponentRange> for Error {
fn from(e: time::error::ComponentRange) -> Self {
Error::S3Auth(Box::new(e))
}
}
pub(crate) fn status_to_error(status: u16, url: &str) -> Error {
let url = redact_url(url);
match status {
404 => Error::NotFound { url },
401 | 403 => Error::Unauthorized { status, url },
429 => Error::RateLimited {
status,
url,
reset_at: None,
retry_after: None,
},
_ => Error::HttpStatus { status, url },
}
}
#[derive(Debug, Default, Clone, Copy)]
pub(crate) struct RateLimitSignals<'a> {
pub(crate) remaining: Option<&'a str>,
pub(crate) reset: Option<&'a str>,
pub(crate) retry_after: Option<&'a str>,
}
const MAX_RATE_LIMIT_WAIT: std::time::Duration = std::time::Duration::from_secs(24 * 60 * 60);
pub(crate) fn classify_status(status: u16, url: &str, signals: RateLimitSignals<'_>) -> Error {
let quota_spent = signals
.remaining
.and_then(|v| v.trim().parse::<u64>().ok())
.is_some_and(|remaining| remaining == 0);
let retry_after = signals.retry_after.and_then(parse_retry_after);
let rate_limited = match status {
429 => true,
403 => quota_spent || retry_after.is_some(),
_ => false,
};
if rate_limited {
return Error::RateLimited {
status,
url: redact_url(url),
reset_at: signals.reset.and_then(parse_reset_epoch),
retry_after,
};
}
status_to_error(status, url)
}
fn parse_reset_epoch(value: &str) -> Option<std::time::SystemTime> {
let secs: u64 = value.trim().parse().ok()?;
let at = std::time::UNIX_EPOCH.checked_add(std::time::Duration::from_secs(secs))?;
match at.duration_since(std::time::SystemTime::now()) {
Ok(wait) if wait > MAX_RATE_LIMIT_WAIT => None,
_ => Some(at),
}
}
fn parse_retry_after(value: &str) -> Option<std::time::Duration> {
let delay = std::time::Duration::from_secs(value.trim().parse().ok()?);
(!delay.is_zero() && delay <= MAX_RATE_LIMIT_WAIT).then_some(delay)
}
pub(crate) fn status_to_error_with_headers(
status: u16,
url: &str,
headers: &http::HeaderMap,
) -> Error {
let get = |name: &str| headers.get(name).and_then(|v| v.to_str().ok());
classify_status(
status,
url,
RateLimitSignals {
remaining: get("x-ratelimit-remaining").or_else(|| get("ratelimit-remaining")),
reset: get("x-ratelimit-reset").or_else(|| get("ratelimit-reset")),
retry_after: get("retry-after"),
},
)
}
fn proxy_url_password_span(url: &str) -> Option<std::ops::Range<usize>> {
let authority_start = url.find("://").map(|i| i + 3).unwrap_or(0);
let authority_end = url[authority_start..]
.find('/')
.map(|i| authority_start + i)
.unwrap_or(url.len());
let authority = &url[authority_start..authority_end];
let at = authority.rfind('@')?;
let colon = authority[..at].find(':')?;
Some(authority_start + colon + 1..authority_start + at)
}
fn proxy_url_password(url: &str) -> Option<&str> {
proxy_url_password_span(url).map(|span| &url[span])
}
pub(crate) fn redact_proxy_url(url: &str) -> String {
let mut out = url.to_string();
if let Some(span) = proxy_url_password_span(url) {
out.replace_range(span, "REDACTED");
}
out
}
pub(crate) fn proxy_error_message(url: &str, err: impl std::fmt::Display) -> String {
let redacted = redact_proxy_url(url);
let mut inner = err.to_string();
if let Some(password) = proxy_url_password(url)
&& !password.is_empty()
{
inner = inner.replace(password, "REDACTED");
}
format!("invalid proxy URL `{redacted}`: {inner}")
}
pub(crate) fn redact_url(url: &str) -> String {
let mut out = url.to_string();
for key in ["X-Amz-Signature", "X-Amz-Credential"] {
let needle = format!("{key}=");
if let Some(start) = out.find(&needle) {
let val_start = start + needle.len();
let val_end = out[val_start..]
.find('&')
.map(|i| val_start + i)
.unwrap_or(out.len());
out.replace_range(val_start..val_end, "REDACTED");
}
}
out
}
#[cfg(test)]
mod tests {
use super::{Error, MessageError};
use std::error::Error as _;
#[test]
fn redact_url_blanks_amz_signature_and_credential() {
let url = "https://bucket.s3.amazonaws.com/app.tar.gz?X-Amz-Credential=AKIAEXAMPLE%2F20260101\
&X-Amz-Expires=300&X-Amz-Signature=deadbeefcafe&X-Amz-SignedHeaders=host";
let red = super::redact_url(url);
assert!(
!red.contains("deadbeefcafe"),
"the signature value must be redacted: {red}"
);
assert!(
!red.contains("AKIAEXAMPLE"),
"the credential value must be redacted: {red}"
);
assert!(
red.contains("X-Amz-Expires=300"),
"non-sensitive params must be preserved: {red}"
);
}
#[test]
fn redact_proxy_url_redacts_only_the_password() {
assert_eq!(
super::redact_proxy_url("http://corpuser:hunter2@proxy.corp:8080"),
"http://corpuser:REDACTED@proxy.corp:8080"
);
assert_eq!(
super::redact_proxy_url("corpuser:hunter2@proxy.corp:8080"),
"corpuser:REDACTED@proxy.corp:8080"
);
assert_eq!(
super::redact_proxy_url("http://corpuser:p@ss:word@proxy.corp:8080"),
"http://corpuser:REDACTED@proxy.corp:8080"
);
}
#[test]
fn redact_proxy_url_leaves_credential_free_urls_unchanged() {
for url in [
"http://proxy.corp:8080",
"http://corpuser@proxy.corp:8080",
"http://proxy.corp:8080/pac@file:1",
] {
assert_eq!(super::redact_proxy_url(url), url, "unchanged: {url}");
}
}
#[test]
fn proxy_error_message_scrubs_the_password_from_the_wrapped_error() {
let url = "http://corpuser:hunter2@proxy.corp:8080";
let msg = super::proxy_error_message(url, format!("failed to parse {url}"));
assert!(
!msg.contains("hunter2"),
"the password must not survive anywhere in the message, got: {msg}"
);
assert!(
msg.contains("http://corpuser:REDACTED@proxy.corp:8080"),
"the redacted URL must still identify the proxy, got: {msg}"
);
}
#[test]
fn redact_url_leaves_plain_url_unchanged() {
let url = "https://api.github.com/repos/o/r/releases/assets/1";
assert_eq!(super::redact_url(url), url);
}
#[test]
fn status_to_error_stores_redacted_url() {
let err = super::status_to_error(
403,
"https://bucket.s3.amazonaws.com/x?X-Amz-Signature=secretsig",
);
assert!(
!err.url().unwrap().contains("secretsig"),
"status_to_error must store a redacted url"
);
}
fn json_error() -> serde_json::Error {
serde_json::from_str::<serde_json::Value>("{").unwrap_err()
}
fn semver_error() -> semver::Error {
"not a version".parse::<semver::Version>().unwrap_err()
}
#[test]
fn json_error_is_opaque_with_source() {
let err: Error = json_error().into();
assert!(
matches!(err, Error::Json(_)),
"From<serde_json::Error> -> Error::Json"
);
assert!(
err.source().is_some(),
"Error::Json must expose its underlying error via source()"
);
}
#[test]
fn json_error_display_includes_prefix_and_inner_message() {
let inner = json_error();
let inner_shown = inner.to_string();
let err: Error = inner.into();
let shown = err.to_string();
assert!(
shown.starts_with("JsonError: "),
"Error::Json Display must keep the `JsonError: ` prefix, got: {}",
shown
);
assert!(
shown.contains(&inner_shown),
"Error::Json Display must embed the inner error message `{}`, got: {}",
inner_shown,
shown
);
}
#[test]
fn semver_error_is_opaque_with_source() {
let err: Error = semver_error().into();
assert!(
matches!(err, Error::SemVer(_)),
"From<semver::Error> -> Error::SemVer"
);
assert!(
err.source().is_some(),
"Error::SemVer must expose its underlying error via source()"
);
}
#[test]
fn semver_error_display_includes_prefix_and_inner_message() {
let inner = semver_error();
let inner_shown = inner.to_string();
let err: Error = inner.into();
let shown = err.to_string();
assert!(
shown.starts_with("SemVerError: "),
"Error::SemVer Display must keep the `SemVerError: ` prefix, got: {}",
shown
);
assert!(
shown.contains(&inner_shown),
"Error::SemVer Display must embed the inner error message `{}`, got: {}",
inner_shown,
shown
);
}
#[cfg(feature = "archive-zip")]
#[test]
fn zip_error_is_opaque_with_source() {
let zip_err = zip::result::ZipError::FileNotFound;
let err: Error = zip_err.into();
assert!(matches!(err, Error::Zip(_)), "From<ZipError> -> Error::Zip");
assert!(
err.source().is_some(),
"Error::Zip must expose its underlying error via source()"
);
}
#[cfg(feature = "archive-zip")]
#[test]
fn zip_error_display_includes_prefix_and_inner_message() {
let err: Error = zip::result::ZipError::FileNotFound.into();
let shown = err.to_string();
assert!(
shown.starts_with("ZipError: "),
"Error::Zip Display must keep the `ZipError: ` prefix, got: {}",
shown
);
let inner = zip::result::ZipError::FileNotFound.to_string();
assert!(
shown.contains(&inner),
"Error::Zip Display must embed the inner error message `{}`, got: {}",
inner,
shown
);
}
#[cfg(feature = "signatures")]
#[test]
fn signature_error_is_opaque_with_source() {
let inner = zipsign_api::ZipsignError::from(std::io::Error::other("boom"));
let err: Error = inner.into();
assert!(
matches!(err, Error::Signature(_)),
"From<ZipsignError> -> Error::Signature"
);
assert!(
err.source().is_some(),
"Error::Signature must expose its underlying error via source()"
);
}
#[cfg(feature = "signatures")]
#[test]
fn signature_error_display_includes_prefix_and_inner_message() {
let inner = zipsign_api::ZipsignError::from(std::io::Error::other("boom"));
let inner_shown = inner.to_string();
let err: Error = inner.into();
let shown = err.to_string();
assert!(
shown.starts_with("SignatureError: "),
"Error::Signature Display must keep the `SignatureError: ` prefix, got: {}",
shown
);
assert!(
shown.contains(&inner_shown),
"Error::Signature Display must embed the inner error message `{}`, got: {}",
inner_shown,
shown
);
}
#[cfg(feature = "signatures")]
#[test]
fn signature_non_utf8_variant_is_renamed_and_displays() {
let err = Error::SignatureNonUTF8;
assert_eq!(
err.to_string(),
"SignatureError: cannot verify signature of a file with a non-UTF-8 name"
);
}
#[cfg(feature = "reqwest")]
#[test]
fn reqwest_error_maps_to_transport_variant() {
let e = reqwest::blocking::get("not-a-url").unwrap_err();
let err: Error = e.into();
assert!(
matches!(err, Error::Transport(_)),
"From<reqwest::Error> must produce Error::Transport, got {:?}",
err
);
assert!(
err.source().is_some(),
"Error::Transport must expose its underlying error via source()"
);
let shown = err.to_string();
assert!(
shown.starts_with("TransportError: "),
"Error::Transport Display must have 'TransportError: ' prefix, got: {}",
shown
);
}
#[cfg(feature = "ureq")]
#[test]
fn ureq_error_maps_to_transport_variant() {
let e = ureq::Error::BadUri("not-a-url".to_string());
let err: Error = e.into();
assert!(
matches!(err, Error::Transport(_)),
"From<ureq::Error> must produce Error::Transport, got {:?}",
err
);
assert!(
err.source().is_some(),
"Error::Transport must expose its underlying error via source()"
);
let shown = err.to_string();
assert!(
shown.starts_with("TransportError: "),
"Error::Transport Display must have 'TransportError: ' prefix, got: {}",
shown
);
}
#[test]
fn not_found_display_matches_spec() {
let err = Error::NotFound {
url: "https://example.com/releases".to_string(),
};
assert_eq!(
err.to_string(),
"NotFoundError: no resource found at https://example.com/releases (HTTP 404)"
);
}
#[test]
fn unauthorized_display_matches_spec_401() {
let err = Error::Unauthorized {
status: 401,
url: "https://example.com/api".to_string(),
};
assert_eq!(
err.to_string(),
"UnauthorizedError: request to https://example.com/api was not authorized (HTTP 401)"
);
}
#[test]
fn unauthorized_display_matches_spec_403() {
let err = Error::Unauthorized {
status: 403,
url: "https://example.com/private".to_string(),
};
assert_eq!(
err.to_string(),
"UnauthorizedError: request to https://example.com/private was not authorized (HTTP 403)"
);
}
#[test]
fn http_status_display_matches_spec() {
let err = Error::HttpStatus {
status: 503,
url: "https://example.com/releases".to_string(),
};
assert_eq!(
err.to_string(),
"HttpStatusError: request to https://example.com/releases failed with status 503"
);
}
fn signals<'a>(
remaining: Option<&'a str>,
reset: Option<&'a str>,
retry_after: Option<&'a str>,
) -> super::RateLimitSignals<'a> {
super::RateLimitSignals {
remaining,
reset,
retry_after,
}
}
#[test]
fn classify_status_maps_a_spent_quota_403_to_rate_limited() {
let err = super::classify_status(
403,
"https://api.github.com/repos/o/r/releases/latest",
signals(Some("0"), Some("1780000000"), Some("60")),
);
let Error::RateLimited {
status,
url,
reset_at,
retry_after,
} = err
else {
panic!("a 403 with remaining=0 must classify as RateLimited, got {err:?}");
};
assert_eq!(status, 403);
assert_eq!(url, "https://api.github.com/repos/o/r/releases/latest");
assert_eq!(
reset_at,
Some(std::time::UNIX_EPOCH + std::time::Duration::from_secs(1_780_000_000)),
"x-ratelimit-reset must parse as a unix timestamp"
);
assert_eq!(retry_after, Some(std::time::Duration::from_secs(60)));
}
#[test]
fn classify_status_keeps_a_plain_403_unauthorized() {
let err = super::classify_status(403, "https://example.com/r", signals(None, None, None));
assert!(
matches!(err, Error::Unauthorized { status: 403, .. }),
"a 403 with no rate-limit headers must stay Unauthorized, got {err:?}"
);
}
#[test]
fn classify_status_keeps_403_unauthorized_when_quota_remains() {
let err = super::classify_status(
403,
"https://example.com/r",
signals(Some("57"), Some("1780000000"), None),
);
assert!(
matches!(err, Error::Unauthorized { status: 403, .. }),
"a nonzero remaining quota must not classify as RateLimited, got {err:?}"
);
}
#[test]
fn classify_status_maps_a_spent_quota_429_to_rate_limited() {
let err = super::classify_status(
429,
"https://gitlab.com/api/v4/x",
signals(Some("0"), None, None),
);
assert!(
matches!(err, Error::RateLimited { status: 429, .. }),
"a 429 with remaining=0 must classify as RateLimited, got {err:?}"
);
}
#[test]
fn classify_status_maps_a_bare_429_to_rate_limited() {
let err = super::classify_status(429, "https://example.com/r", signals(None, None, None));
assert!(
matches!(
err,
Error::RateLimited {
status: 429,
reset_at: None,
retry_after: None,
..
}
),
"a 429 must classify as RateLimited even with no quota headers, got {err:?}"
);
}
#[test]
fn classify_status_maps_a_429_with_only_retry_after_to_rate_limited() {
let err = super::classify_status(
429,
"https://example.com/r",
signals(None, None, Some("30")),
);
assert!(
matches!(
err,
Error::RateLimited {
status: 429,
retry_after: Some(d),
..
} if d == std::time::Duration::from_secs(30)
),
"a 429 with Retry-After must classify as RateLimited carrying the delay, got {err:?}"
);
}
#[test]
fn classify_status_maps_a_403_with_retry_after_to_rate_limited() {
let err = super::classify_status(
403,
"https://api.github.com/repos/o/r/releases",
signals(Some("4999"), None, Some("60")),
);
assert!(
matches!(
err,
Error::RateLimited {
status: 403,
retry_after: Some(d),
..
} if d == std::time::Duration::from_secs(60)
),
"a 403 with Retry-After must classify as RateLimited, got {err:?}"
);
}
#[test]
fn classify_status_maps_a_403_with_spent_quota_and_no_retry_after_to_rate_limited() {
let err = super::classify_status(
403,
"https://api.github.com/repos/o/r/releases",
signals(Some("0"), None, None),
);
assert!(
matches!(err, Error::RateLimited { status: 403, .. }),
"a 403 with remaining=0 must classify as RateLimited, got {err:?}"
);
}
#[test]
fn classify_status_ignores_quota_headers_on_a_404() {
let err = super::classify_status(
404,
"https://example.com/r",
signals(Some("0"), Some("1780000000"), Some("60")),
);
assert!(
matches!(err, Error::NotFound { .. }),
"a 404 must stay NotFound regardless of quota headers, got {err:?}"
);
}
#[test]
fn classify_status_ignores_quota_headers_on_other_statuses() {
let err =
super::classify_status(404, "https://example.com/r", signals(Some("0"), None, None));
assert!(
matches!(err, Error::NotFound { .. }),
"a 404 must stay NotFound regardless of quota headers, got {err:?}"
);
}
#[test]
fn classify_status_tolerates_unparseable_reset_and_retry_after() {
let err = super::classify_status(
403,
"https://example.com/r",
signals(
Some("0"),
Some("not-a-number"),
Some("Wed, 21 Oct 2026 07:28:00 GMT"),
),
);
let Error::RateLimited {
reset_at,
retry_after,
..
} = err
else {
panic!("expected RateLimited, got {err:?}");
};
assert_eq!(
reset_at, None,
"a non-numeric reset must not yield an instant"
);
assert_eq!(
retry_after, None,
"the HTTP-date form of Retry-After is not parsed"
);
}
#[test]
fn status_to_error_with_headers_reads_both_header_spellings() {
let mut github = http::HeaderMap::new();
github.insert("x-ratelimit-remaining", "0".parse().unwrap());
github.insert("x-ratelimit-reset", "1780000000".parse().unwrap());
assert!(
matches!(
super::status_to_error_with_headers(403, "https://api.github.com/x", &github),
Error::RateLimited {
status: 403,
reset_at: Some(_),
..
}
),
"the x-ratelimit-* spelling must classify as RateLimited"
);
let mut gitlab = http::HeaderMap::new();
gitlab.insert("RateLimit-Remaining", "0".parse().unwrap());
assert!(
matches!(
super::status_to_error_with_headers(429, "https://gitlab.com/x", &gitlab),
Error::RateLimited { status: 429, .. }
),
"the un-prefixed gitlab spelling must classify as RateLimited"
);
assert!(
matches!(
super::status_to_error_with_headers(
403,
"https://example.com/x",
&http::HeaderMap::new()
),
Error::Unauthorized { status: 403, .. }
),
"a header-less 403 must stay Unauthorized"
);
}
#[test]
fn classify_status_redacts_the_rate_limited_url() {
let err = super::classify_status(
429,
"https://bucket.s3.amazonaws.com/x?X-Amz-Signature=secretsig",
signals(Some("0"), None, None),
);
assert!(
!err.url().unwrap().contains("secretsig"),
"the RateLimited url must be redacted"
);
}
#[test]
fn http_status_and_url_helpers_cover_rate_limited() {
let err = Error::RateLimited {
status: 429,
url: "https://example.com/r".to_string(),
reset_at: None,
retry_after: None,
};
assert_eq!(err.http_status(), Some(429));
assert_eq!(err.url(), Some("https://example.com/r"));
assert!(
err.source().is_none(),
"RateLimited carries no chained source"
);
}
#[test]
fn rate_limited_display_names_the_limit_and_the_remedy() {
let err = Error::RateLimited {
status: 403,
url: "https://api.github.com/repos/o/r/releases/latest".to_string(),
reset_at: None,
retry_after: Some(std::time::Duration::from_secs(90)),
};
let msg = err.to_string();
assert!(
msg.starts_with("RateLimitedError:"),
"the Display string must identify the variant, got: {msg}"
);
assert!(
msg.contains("rate limited"),
"the message must name rate limiting, not authorization, got: {msg}"
);
assert!(
!msg.contains("not authorized"),
"the message must not read as an auth failure, got: {msg}"
);
assert!(
msg.contains("retry in 90s"),
"the message must surface the wait, got: {msg}"
);
assert!(
msg.contains("auth token"),
"the message must name the token remedy, got: {msg}"
);
}
#[test]
fn rate_limited_display_does_not_call_a_retry_after_wait_a_quota_reset() {
let msg = Error::RateLimited {
status: 403,
url: "https://api.github.com/x".to_string(),
reset_at: None,
retry_after: Some(std::time::Duration::from_secs(30)),
}
.to_string();
assert!(
!msg.contains("quota resets"),
"a Retry-After-sourced wait must not be worded as a quota reset, got: {msg}"
);
}
#[test]
fn rate_limited_display_still_calls_a_reset_at_wait_a_quota_reset() {
let msg = Error::RateLimited {
status: 403,
url: "https://api.github.com/x".to_string(),
reset_at: Some(std::time::SystemTime::now() + std::time::Duration::from_secs(600)),
retry_after: None,
}
.to_string();
assert!(
msg.contains("quota resets in"),
"a reset_at-derived wait must still read as a quota reset, got: {msg}"
);
assert!(
!msg.contains("retry in"),
"a reset_at-derived wait must not use the Retry-After wording, got: {msg}"
);
}
#[test]
fn rate_limited_display_prefers_retry_after_wording_when_both_fields_are_present() {
let msg = Error::RateLimited {
status: 403,
url: "https://api.github.com/x".to_string(),
reset_at: Some(std::time::SystemTime::now() + std::time::Duration::from_secs(3600)),
retry_after: Some(std::time::Duration::from_secs(30)),
}
.to_string();
assert!(
msg.contains("retry in 30s"),
"with both fields present the Retry-After value must be rendered, got: {msg}"
);
assert!(
!msg.contains("quota resets"),
"with both fields present the message must not also/instead read as a quota reset, \
got: {msg}"
);
assert!(
!msg.contains("3600s"),
"the reset_at-derived duration must never leak into the message, got: {msg}"
);
}
#[test]
fn rate_limited_display_omits_the_wait_when_unknown_or_elapsed() {
let no_info = Error::RateLimited {
status: 403,
url: "https://example.com/r".to_string(),
reset_at: None,
retry_after: None,
}
.to_string();
assert!(
!no_info.contains("resets in"),
"with no reset info the wait clause must be omitted, got: {no_info}"
);
assert!(
no_info.ends_with("check less often"),
"the message must still end with the remedy, got: {no_info}"
);
let elapsed = Error::RateLimited {
status: 403,
url: "https://example.com/r".to_string(),
reset_at: Some(std::time::UNIX_EPOCH),
retry_after: None,
}
.to_string();
assert!(
!elapsed.contains("resets in"),
"an elapsed reset window must not render a countdown, got: {elapsed}"
);
}
#[test]
fn rate_limited_display_separates_its_clauses_consistently() {
let msg = Error::RateLimited {
status: 403,
url: "https://api.github.com/x".to_string(),
reset_at: None,
retry_after: Some(std::time::Duration::from_secs(90)),
}
.to_string();
assert_eq!(
msg,
"RateLimitedError: request to https://api.github.com/x was rate limited (HTTP 403); \
retry in 90s; set an auth token to raise the limit, or check less often",
"the RateLimited Display shape changed"
);
}
fn reset_header(secs_from_now: u64) -> String {
let now = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.expect("the system clock is after the unix epoch")
.as_secs();
(now + secs_from_now).to_string()
}
#[test]
fn parse_reset_epoch_keeps_a_normal_and_a_past_window() {
let soon = reset_header(600);
assert_eq!(
super::parse_reset_epoch(&soon),
Some(
std::time::UNIX_EPOCH
+ std::time::Duration::from_secs(soon.parse::<u64>().unwrap())
),
"a window 10 minutes out must be kept as-is"
);
assert_eq!(
super::parse_reset_epoch("1"),
Some(std::time::UNIX_EPOCH + std::time::Duration::from_secs(1)),
"a reset instant in the past must not be rejected by the future-facing clamp"
);
}
#[test]
fn parse_reset_epoch_keeps_a_window_exactly_at_the_ceiling() {
assert!(
super::parse_reset_epoch(&reset_header(24 * 60 * 60)).is_some(),
"a reset exactly 24h out must be honored"
);
}
#[test]
fn parse_reset_epoch_rejects_a_window_past_the_ceiling() {
assert_eq!(
super::parse_reset_epoch(&reset_header(24 * 60 * 60 + 2)),
None,
"a reset more than 24h out must be discarded"
);
assert_eq!(
super::parse_reset_epoch(&reset_header(30 * 24 * 60 * 60)),
None,
"a reset a month out must be discarded"
);
}
#[test]
fn parse_reset_epoch_rejects_the_u64_max_timestamp() {
assert_eq!(
super::parse_reset_epoch(&u64::MAX.to_string()),
None,
"a u64::MAX reset timestamp must not yield an instant"
);
}
#[test]
fn parse_reset_epoch_rejects_malformed_values() {
for bad in ["", " ", "not-a-number", "-1", "1.5", "0x10"] {
assert_eq!(
super::parse_reset_epoch(bad),
None,
"malformed reset value {bad:?} must yield None, not a panic or a bogus instant"
);
}
}
#[test]
fn parse_retry_after_keeps_a_normal_delay() {
assert_eq!(
super::parse_retry_after("60"),
Some(std::time::Duration::from_secs(60)),
"a 60s Retry-After must be kept"
);
}
#[test]
fn parse_retry_after_keeps_the_smallest_nonzero_delay() {
assert_eq!(
super::parse_retry_after("1"),
Some(std::time::Duration::from_secs(1)),
"a 1s Retry-After is the boundary directly above the zero floor and must be kept"
);
}
#[test]
fn parse_retry_after_trims_surrounding_whitespace() {
assert_eq!(
super::parse_retry_after(" 60 \t"),
Some(std::time::Duration::from_secs(60)),
"surrounding whitespace around a valid delay must be trimmed, not treated as unparseable"
);
}
#[test]
fn parse_retry_after_rejects_malformed_values() {
for bad in ["", " ", "not-a-number", "-1", "1.5", "0x10"] {
assert_eq!(
super::parse_retry_after(bad),
None,
"malformed Retry-After value {bad:?} must yield None, not a panic or a bogus delay"
);
}
}
#[test]
fn parse_retry_after_treats_a_zero_delay_as_no_signal() {
assert_eq!(
super::parse_retry_after("0"),
None,
"a zero-second Retry-After must not be carried through as Some(0)"
);
}
#[test]
fn parse_retry_after_clamps_at_twenty_four_hours() {
assert_eq!(
super::parse_retry_after("86400"),
Some(std::time::Duration::from_secs(86_400)),
"a Retry-After exactly at the 24h ceiling must be honored"
);
assert_eq!(
super::parse_retry_after("86401"),
None,
"a Retry-After one second past the ceiling must be discarded"
);
}
#[test]
fn parse_retry_after_rejects_the_u64_max_delay() {
assert_eq!(
super::parse_retry_after(&u64::MAX.to_string()),
None,
"a u64::MAX Retry-After must not yield a delay"
);
}
#[test]
fn classify_status_ignores_an_over_ceiling_retry_after_on_a_403() {
let err = super::classify_status(
403,
"https://example.com/r",
signals(Some("4999"), None, Some(&u64::MAX.to_string())),
);
assert!(
matches!(err, Error::Unauthorized { status: 403, .. }),
"an unusable Retry-After must not promote a 403 to RateLimited, got {err:?}"
);
}
#[test]
fn classify_status_keeps_a_403_with_zero_retry_after_unauthorized() {
let err =
super::classify_status(403, "https://example.com/r", signals(None, None, Some("0")));
assert!(
matches!(err, Error::Unauthorized { status: 403, .. }),
"a 403 with Retry-After: 0 and no spent-quota signal must stay Unauthorized, got {err:?}"
);
}
#[test]
fn classify_status_still_rate_limits_a_spent_quota_403_with_zero_retry_after() {
let err = super::classify_status(
403,
"https://example.com/r",
signals(Some("0"), None, Some("0")),
);
assert!(
matches!(
err,
Error::RateLimited {
status: 403,
retry_after: None,
..
}
),
"a spent quota must still classify as RateLimited even with Retry-After: 0, got {err:?}"
);
}
#[test]
fn classify_status_keeps_a_403_unauthorized_when_only_reset_at_is_present() {
let err = super::classify_status(
403,
"https://example.com/r",
signals(None, Some(&reset_header(600)), None),
);
assert!(
matches!(err, Error::Unauthorized { status: 403, .. }),
"a 403 with only a reset_at header (no spent quota, no Retry-After) must stay \
Unauthorized, got {err:?}"
);
}
#[test]
fn classify_status_keeps_a_429_with_zero_retry_after_rate_limited() {
let err =
super::classify_status(429, "https://example.com/r", signals(None, None, Some("0")));
assert!(
matches!(
err,
Error::RateLimited {
status: 429,
retry_after: None,
..
}
),
"a 429 must stay RateLimited regardless of Retry-After, got {err:?}"
);
}
#[test]
fn rate_limit_delay_prefers_retry_after_over_reset_at() {
let err = Error::RateLimited {
status: 403,
url: "https://example.com/r".to_string(),
reset_at: Some(std::time::SystemTime::now() + std::time::Duration::from_secs(3600)),
retry_after: Some(std::time::Duration::from_secs(30)),
};
assert_eq!(
err.rate_limit_delay(),
Some(std::time::Duration::from_secs(30)),
"Retry-After must take precedence over the reset instant"
);
}
#[test]
fn rate_limit_delay_uses_retry_after_alone() {
let err = Error::RateLimited {
status: 429,
url: "https://example.com/r".to_string(),
reset_at: None,
retry_after: Some(std::time::Duration::from_secs(45)),
};
assert_eq!(
err.rate_limit_delay(),
Some(std::time::Duration::from_secs(45))
);
}
#[test]
fn rate_limit_delay_derives_a_wait_from_a_future_reset_at() {
let err = Error::RateLimited {
status: 403,
url: "https://api.github.com/x".to_string(),
reset_at: Some(std::time::SystemTime::now() + std::time::Duration::from_secs(600)),
retry_after: None,
};
let delay = err
.rate_limit_delay()
.expect("a future reset instant must yield a wait");
assert!(
delay <= std::time::Duration::from_secs(600)
&& delay > std::time::Duration::from_secs(590),
"the wait must be measured from now, got {delay:?}"
);
}
#[test]
fn rate_limit_delay_is_none_for_an_elapsed_reset_at() {
let err = Error::RateLimited {
status: 403,
url: "https://example.com/r".to_string(),
reset_at: Some(std::time::UNIX_EPOCH),
retry_after: None,
};
assert_eq!(
err.rate_limit_delay(),
None,
"an elapsed reset window must yield no wait, not a panic or a bogus duration"
);
}
#[test]
fn rate_limit_delay_is_none_when_nothing_is_known() {
let err = Error::RateLimited {
status: 429,
url: "https://example.com/r".to_string(),
reset_at: None,
retry_after: None,
};
assert_eq!(err.rate_limit_delay(), None);
}
#[test]
fn rate_limit_delay_is_none_for_a_non_rate_limited_variant() {
assert_eq!(
Error::Unauthorized {
status: 403,
url: "https://example.com/r".to_string(),
}
.rate_limit_delay(),
None,
"Unauthorized carries no rate-limit wait"
);
assert_eq!(
Error::NotFound {
url: "https://example.com/r".to_string(),
}
.rate_limit_delay(),
None,
"NotFound carries no rate-limit wait"
);
}
#[test]
fn http_status_helper_not_found() {
let err = Error::NotFound {
url: "u".to_string(),
};
assert_eq!(err.http_status(), Some(404));
}
#[test]
fn http_status_helper_unauthorized() {
assert_eq!(
Error::Unauthorized {
status: 401,
url: "u".to_string()
}
.http_status(),
Some(401)
);
assert_eq!(
Error::Unauthorized {
status: 403,
url: "u".to_string()
}
.http_status(),
Some(403)
);
}
#[test]
fn http_status_helper_http_status_variant() {
assert_eq!(
Error::HttpStatus {
status: 503,
url: "u".to_string()
}
.http_status(),
Some(503)
);
assert_eq!(
Error::HttpStatus {
status: 500,
url: "u".to_string()
}
.http_status(),
Some(500)
);
}
#[test]
fn http_status_helper_returns_none_for_non_http_variants() {
assert_eq!(
Error::Internal {
message: "x".into(),
source: None
}
.http_status(),
None
);
assert_eq!(Error::NoReleaseFound { target: None }.http_status(), None);
assert_eq!(Error::MissingField { field: "x" }.http_status(), None);
assert_eq!(Error::Io(std::io::Error::other("x")).http_status(), None);
assert_eq!(Error::Json(Box::new(json_error())).http_status(), None);
assert_eq!(
Error::Transport(Box::new(std::io::Error::other("x"))).http_status(),
None
);
}
#[test]
fn status_to_error_maps_404_to_not_found() {
let e = super::status_to_error(404, "https://example.com/r");
assert!(
matches!(e, Error::NotFound { ref url } if url == "https://example.com/r"),
"status 404 must map to Error::NotFound, got {:?}",
e
);
}
#[test]
fn status_to_error_maps_401_to_unauthorized() {
let e = super::status_to_error(401, "https://example.com/r");
assert!(
matches!(e, Error::Unauthorized { status: 401, ref url } if url == "https://example.com/r"),
"status 401 must map to Error::Unauthorized, got {:?}",
e
);
}
#[test]
fn status_to_error_maps_403_to_unauthorized() {
let e = super::status_to_error(403, "https://example.com/r");
assert!(
matches!(e, Error::Unauthorized { status: 403, ref url } if url == "https://example.com/r"),
"status 403 must map to Error::Unauthorized, got {:?}",
e
);
}
#[test]
fn status_to_error_maps_429_to_rate_limited_without_a_wait() {
let e = super::status_to_error(429, "https://example.com/r");
assert!(
matches!(
e,
Error::RateLimited {
status: 429,
ref url,
reset_at: None,
retry_after: None,
} if url == "https://example.com/r"
),
"status 429 must map to Error::RateLimited with no wait fields, got {:?}",
e
);
assert_eq!(
e.rate_limit_delay(),
None,
"a header-blind 429 knows no wait, so rate_limit_delay must be None"
);
assert_eq!(e.http_status(), Some(429));
}
#[test]
fn status_to_error_keeps_401_and_403_unauthorized() {
assert!(matches!(
super::status_to_error(401, "https://example.com/r"),
Error::Unauthorized { status: 401, .. }
));
assert!(matches!(
super::status_to_error(403, "https://example.com/r"),
Error::Unauthorized { status: 403, .. }
));
}
#[test]
fn status_to_error_maps_500_to_http_status() {
let e = super::status_to_error(500, "https://example.com/r");
assert!(
matches!(e, Error::HttpStatus { status: 500, ref url } if url == "https://example.com/r"),
"status 500 must map to Error::HttpStatus, got {:?}",
e
);
}
#[test]
fn status_to_error_maps_503_to_http_status() {
let e = super::status_to_error(503, "https://example.com/r");
assert!(
matches!(e, Error::HttpStatus { status: 503, .. }),
"status 503 must map to Error::HttpStatus, got {:?}",
e
);
}
#[test]
fn status_to_error_maps_3xx_to_http_status() {
let e = super::status_to_error(301, "https://example.com/r");
assert!(
matches!(e, Error::HttpStatus { status: 301, ref url } if url == "https://example.com/r"),
"status 301 must map to Error::HttpStatus(301), got {:?}",
e
);
let e = super::status_to_error(304, "https://example.com/r");
assert!(
matches!(e, Error::HttpStatus { status: 304, .. }),
"status 304 must map to Error::HttpStatus(304), got {:?}",
e
);
}
#[test]
fn checksum_mismatch_display_exact_string() {
let err = Error::ChecksumMismatch {
expected: "aabbcc".to_string(),
computed: "112233".to_string(),
};
assert_eq!(
err.to_string(),
"ChecksumMismatchError: checksum mismatch (expected aabbcc, computed 112233)"
);
}
#[test]
fn checksum_mismatch_http_status_is_none() {
let err = Error::ChecksumMismatch {
expected: "aa".to_string(),
computed: "bb".to_string(),
};
assert_eq!(err.http_status(), None);
}
#[test]
fn checksum_mismatch_url_is_none() {
let err = Error::ChecksumMismatch {
expected: "aa".to_string(),
computed: "bb".to_string(),
};
assert_eq!(err.url(), None);
}
#[test]
fn aborted_display_exact_string() {
assert_eq!(
Error::Aborted.to_string(),
"AbortedError: the update was not confirmed"
);
}
#[test]
fn aborted_http_status_is_none() {
assert_eq!(Error::Aborted.http_status(), None);
}
#[test]
fn aborted_url_is_none() {
assert_eq!(Error::Aborted.url(), None);
}
#[test]
fn url_helper_not_found() {
let err = Error::NotFound {
url: "https://example.com/releases".to_string(),
};
assert_eq!(err.url(), Some("https://example.com/releases"));
}
#[test]
fn url_helper_unauthorized() {
let err = Error::Unauthorized {
status: 401,
url: "https://example.com/api".to_string(),
};
assert_eq!(err.url(), Some("https://example.com/api"));
}
#[test]
fn url_helper_http_status() {
let err = Error::HttpStatus {
status: 503,
url: "https://example.com/releases".to_string(),
};
assert_eq!(err.url(), Some("https://example.com/releases"));
}
#[test]
fn url_helper_returns_none_for_non_http_variants() {
assert_eq!(
Error::Internal {
message: "x".into(),
source: None
}
.url(),
None
);
assert_eq!(Error::NoReleaseFound { target: None }.url(), None);
assert_eq!(Error::MissingField { field: "x" }.url(), None);
assert_eq!(Error::Aborted.url(), None);
assert_eq!(
Error::ChecksumMismatch {
expected: "a".into(),
computed: "b".into()
}
.url(),
None
);
assert_eq!(Error::Io(std::io::Error::other("x")).url(), None);
}
#[test]
fn archive_not_enabled_display_has_correct_prefix() {
let err = Error::ArchiveNotEnabled("zip".to_string());
let shown = err.to_string();
assert!(
shown.starts_with("ArchiveNotEnabledError: "),
"ArchiveNotEnabled Display must start with 'ArchiveNotEnabledError: ', got: {}",
shown
);
assert!(
shown.contains("zip") && shown.contains("archive-zip"),
"ArchiveNotEnabled Display must contain the extension and the feature name, got: {}",
shown
);
assert!(
!shown.ends_with('!') && !shown.ends_with('.'),
"ArchiveNotEnabled Display must not end with punctuation, got: {}",
shown
);
}
#[cfg(feature = "signatures")]
#[test]
fn signature_non_utf8_display_has_signature_error_prefix() {
let err = Error::SignatureNonUTF8;
let shown = err.to_string();
assert!(
shown.starts_with("SignatureError: "),
"SignatureNonUTF8 Display must start with 'SignatureError: ', got: {}",
shown
);
}
#[test]
fn missing_field_display_and_no_source() {
let err = Error::MissingField {
field: "current_version",
};
assert_eq!(err.to_string(), "ConfigError: `current_version` required");
assert!(
err.source().is_none(),
"MissingField carries no source, got {:?}",
err.source()
);
assert_eq!(err.http_status(), None);
assert_eq!(err.url(), None);
}
#[test]
fn install_path_not_writable_display_and_no_source() {
let err = Error::InstallPathNotWritable {
path: std::path::PathBuf::from("/usr/local/bin/app"),
};
let shown = err.to_string();
assert!(
shown.starts_with("InstallPathNotWritableError: "),
"InstallPathNotWritable Display must keep the greppable prefix, got: {shown}"
);
assert!(
shown.contains("/usr/local/bin/app"),
"InstallPathNotWritable Display must name the path, got: {shown}"
);
assert!(
shown.contains("elevated privileges") && shown.contains("user-writable install path"),
"InstallPathNotWritable Display must suggest elevated privileges or a user-writable \
install path, got: {shown}"
);
assert!(
err.source().is_none(),
"InstallPathNotWritable carries no source, got {:?}",
err.source()
);
assert_eq!(err.http_status(), None);
assert_eq!(err.url(), None);
}
#[test]
fn install_path_not_writable_is_non_exhaustive_struct_variant() {
let err = Error::InstallPathNotWritable {
path: std::path::PathBuf::from("/opt/app"),
};
let Error::InstallPathNotWritable { path, .. } = err else {
panic!("expected InstallPathNotWritable");
};
assert_eq!(path, std::path::PathBuf::from("/opt/app"));
}
#[test]
fn no_current_version_display_and_no_source() {
let err = Error::NoCurrentVersion;
let shown = err.to_string();
assert_eq!(
shown,
"ReleaseError: this Releases has no current_version to compare against; use \
`Update::is_update_available` for a configured updater"
);
assert!(
!matches!(err, Error::MissingField { .. }),
"NoCurrentVersion must be distinct from MissingField"
);
assert!(err.source().is_none(), "NoCurrentVersion carries no source");
assert_eq!(err.http_status(), None);
assert_eq!(err.url(), None);
}
#[test]
fn no_release_found_display_variants() {
assert_eq!(
Error::NoReleaseFound { target: None }.to_string(),
"ReleaseError: no release was found"
);
assert_eq!(
Error::NoReleaseFound {
target: Some("x86_64-unknown-linux-gnu".into())
}
.to_string(),
"ReleaseError: no release found with an asset for target `x86_64-unknown-linux-gnu`"
);
assert!(Error::NoReleaseFound { target: None }.source().is_none());
}
#[test]
fn missing_asset_field_display() {
let err = Error::missing_asset_field("tag_name");
assert_eq!(
err.to_string(),
"ReleaseError: release/asset payload missing `tag_name`"
);
assert!(err.source().is_none());
}
#[test]
fn verification_rejected_display_variants() {
assert_eq!(
Error::VerificationRejected { reason: None }.to_string(),
"VerificationRejectedError: post-update verification rejected the new binary"
);
assert_eq!(
Error::VerificationRejected {
reason: Some("bad signature".into())
}
.to_string(),
"VerificationRejectedError: post-update verification rejected the new binary: bad signature"
);
assert_eq!(
Error::VerificationRejected { reason: None }.http_status(),
None
);
assert!(
Error::VerificationRejected { reason: None }
.source()
.is_none()
);
}
#[test]
fn archive_verification_rejected_display_variants() {
assert_eq!(
Error::ArchiveVerificationRejected { reason: None }.to_string(),
"ArchiveVerificationRejectedError: verification rejected the downloaded archive"
);
assert_eq!(
Error::ArchiveVerificationRejected {
reason: Some("no attestation found".into())
}
.to_string(),
"ArchiveVerificationRejectedError: verification rejected the downloaded archive: no attestation found"
);
assert_eq!(
Error::ArchiveVerificationRejected { reason: None }.http_status(),
None
);
assert!(
Error::ArchiveVerificationRejected { reason: None }
.source()
.is_none()
);
}
#[test]
fn checksum_source_invalid_display_names_asset_and_reason() {
let err = Error::ChecksumSourceInvalid {
asset: "app-1.0.0.tar.gz".into(),
reason: "release 1.0.0 has no asset named `SHA256SUMS`".into(),
};
assert_eq!(
err.to_string(),
"ChecksumSourceInvalidError: could not resolve a checksum for `app-1.0.0.tar.gz`: \
release 1.0.0 has no asset named `SHA256SUMS`"
);
assert_eq!(err.http_status(), None);
assert!(err.source().is_none());
}
#[test]
fn archive_verification_rejected_constructor_sets_reason() {
match Error::archive_verification_rejected("nope") {
Error::ArchiveVerificationRejected { reason } => {
assert_eq!(reason.as_deref(), Some("nope"));
}
other => panic!("expected ArchiveVerificationRejected, got {other:?}"),
}
}
#[test]
fn invalid_response_chains_source() {
let inner = json_error();
let inner_shown = inner.to_string();
let err = Error::InvalidResponse {
source: Box::new(inner),
};
let chained = err
.source()
.expect("InvalidResponse must expose its source()");
assert!(
chained.to_string().contains(&inner_shown),
"source() must surface the inner error, got: {}",
chained
);
assert!(
err.to_string()
.starts_with("ReleaseError: invalid response: ")
);
}
#[test]
fn invalid_header_chains_source() {
let err = Error::InvalidHeader {
source: Box::new(MessageError("bad header".into())),
};
assert_eq!(
err.source().map(|s| s.to_string()).as_deref(),
Some("bad header")
);
assert!(
err.to_string()
.starts_with("ConfigError: invalid HTTP header: ")
);
}
#[test]
fn invalid_auth_token_chains_source() {
let inner = "bad\nvalue".parse::<crate::http_client::header::HeaderValue>();
let inner = inner.expect_err("control char must fail header parse");
let inner_shown = inner.to_string();
let err = Error::InvalidAuthToken {
source: Box::new(inner),
};
let chained = err
.source()
.expect("InvalidAuthToken must expose its source()");
assert!(chained.to_string().contains(&inner_shown));
assert!(
err.to_string()
.starts_with("ConfigError: failed to parse auth token: ")
);
}
#[test]
fn internal_source_chaining() {
let with = Error::Internal {
message: "boom".into(),
source: Some(Box::new(MessageError("inner".into()))),
};
assert_eq!(with.to_string(), "InternalError: boom");
assert_eq!(
with.source().map(|s| s.to_string()).as_deref(),
Some("inner")
);
let without = Error::Internal {
message: "boom".into(),
source: None,
};
assert!(
without.source().is_none(),
"Internal without a source must return None"
);
}
#[test]
fn io_error_exposes_error_kind() {
let err = Error::Io(std::io::Error::new(
std::io::ErrorKind::PermissionDenied,
"nope",
));
match err {
Error::Io(ref io_err) => {
assert_eq!(io_err.kind(), std::io::ErrorKind::PermissionDenied);
}
other => panic!("expected Error::Io, got {:?}", other),
}
}
#[test]
fn non_exhaustive_match_with_wildcard_compiles() {
fn classify(err: &Error) -> &'static str {
match err {
Error::MissingField { .. } => "missing-field",
Error::NoReleaseFound { .. } => "no-release",
Error::VerificationRejected { .. } => "verify-rejected",
Error::Internal { .. } => "internal",
_ => "other",
}
}
assert_eq!(
classify(&Error::MissingField { field: "x" }),
"missing-field"
);
assert_eq!(
classify(&Error::NoReleaseFound { target: None }),
"no-release"
);
assert_eq!(classify(&Error::Aborted), "other");
}
#[test]
fn non_exhaustive_struct_variants_destructure_with_rest() {
let internal = Error::Internal {
message: "boom".into(),
source: None,
};
if let Error::Internal { message, .. } = &internal {
assert_eq!(message, "boom");
} else {
panic!("expected Internal");
}
let nrf = Error::NoReleaseFound {
target: Some("t".into()),
};
if let Error::NoReleaseFound { target, .. } = &nrf {
assert_eq!(target.as_deref(), Some("t"));
} else {
panic!("expected NoReleaseFound");
}
let unauth = Error::Unauthorized {
status: 401,
url: "u".into(),
};
if let Error::Unauthorized { status, .. } = &unauth {
assert_eq!(*status, 401);
} else {
panic!("expected Unauthorized");
}
let hs = Error::HttpStatus {
status: 503,
url: "u".into(),
};
if let Error::HttpStatus { status, .. } = &hs {
assert_eq!(*status, 503);
} else {
panic!("expected HttpStatus");
}
let ian = Error::InvalidAssetName {
name: "../etc/passwd".into(),
};
if let Error::InvalidAssetName { name, .. } = &ian {
assert_eq!(name, "../etc/passwd");
} else {
panic!("expected InvalidAssetName");
}
}
#[test]
fn unauthorized_http_status_invalid_asset_name_are_non_exhaustive_struct_variants() {
let unauth = Error::Unauthorized {
status: 403,
url: "https://api.example.com/releases".into(),
};
let Error::Unauthorized { status, .. } = unauth else {
panic!("expected Unauthorized");
};
assert_eq!(status, 403);
let hs = Error::HttpStatus {
status: 502,
url: "https://api.example.com/releases".into(),
};
let Error::HttpStatus { status, .. } = hs else {
panic!("expected HttpStatus");
};
assert_eq!(status, 502);
let ian = Error::InvalidAssetName {
name: "../../shadow".into(),
};
let Error::InvalidAssetName { name, .. } = ian else {
panic!("expected InvalidAssetName");
};
assert_eq!(name, "../../shadow");
}
#[test]
fn unauthorized_source_is_none() {
assert!(
Error::Unauthorized {
status: 401,
url: "https://example.com/api".to_string(),
}
.source()
.is_none(),
"Unauthorized must not expose a chained source()"
);
assert!(
Error::Unauthorized {
status: 403,
url: "https://example.com/api".to_string(),
}
.source()
.is_none(),
"Unauthorized (403) must not expose a chained source()"
);
}
#[test]
fn http_status_variant_source_is_none() {
assert!(
Error::HttpStatus {
status: 503,
url: "https://example.com/releases".to_string(),
}
.source()
.is_none(),
"HttpStatus must not expose a chained source()"
);
}
#[test]
fn invalid_asset_name_display_exact_string() {
let err = Error::InvalidAssetName {
name: "../etc/passwd".to_string(),
};
assert_eq!(
err.to_string(),
r#"InvalidAssetNameError: unsafe asset name: "../etc/passwd""#,
"InvalidAssetName Display must match the spec string exactly"
);
}
#[test]
fn invalid_asset_name_source_is_none() {
assert!(
Error::InvalidAssetName {
name: "../evil".to_string(),
}
.source()
.is_none(),
"InvalidAssetName must not expose a chained source()"
);
}
#[test]
fn all_new_variants_display_without_panicking() {
let cases: Vec<(Error, &str)> = vec![
(
Error::Internal {
message: "m".into(),
source: None,
},
"InternalError:",
),
(
Error::VerificationRejected { reason: None },
"VerificationRejectedError:",
),
(
Error::ArchiveVerificationRejected { reason: None },
"ArchiveVerificationRejectedError:",
),
(
Error::ChecksumSourceInvalid {
asset: "a.tar.gz".into(),
reason: "no entry".into(),
},
"ChecksumSourceInvalidError:",
),
(Error::NoReleaseFound { target: None }, "ReleaseError:"),
(Error::missing_asset_field("f"), "ReleaseError:"),
(
Error::InvalidResponse {
source: Box::new(MessageError("x".into())),
},
"ReleaseError:",
),
(Error::MissingField { field: "f" }, "ConfigError:"),
(
Error::InvalidHeader {
source: Box::new(MessageError("x".into())),
},
"ConfigError:",
),
(
Error::InvalidAuthToken {
source: Box::new(MessageError("x".into())),
},
"ConfigError:",
),
];
for (err, prefix) in cases {
let shown = err.to_string();
assert!(
shown.starts_with(prefix),
"{:?} Display must start with `{}`, got: {}",
err,
prefix,
shown
);
assert!(!shown.is_empty(), "Display must not be empty");
}
}
}