use thiserror::Error;
use crate::net_policy::{BlockedHost, BlockingPolicy};
use crate::package::InvalidPackageName;
use crate::redact::{RedactedName, RedactedUrl};
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum RateLimitEvidence {
Confirmed,
Inferred,
}
fn http_status_message(status: u16, url: &RedactedUrl) -> String {
let reason = reqwest::StatusCode::from_u16(status)
.ok()
.and_then(|s| s.canonical_reason());
reason.map_or_else(
|| format!("HTTP {status} for {url}"),
|reason| format!("HTTP {status} {reason} for {url}"),
)
}
fn registry_error_message(package: &RedactedUrl, source: &SanitizedRegistryError) -> String {
format!("registry request failed for {package}: {source}")
}
fn response_too_large_message(url: &RedactedUrl, limit: usize) -> String {
format!("response body for {url} exceeds {limit} byte limit")
}
fn offline_message(url: &RedactedUrl) -> String {
format!("offline: request to {url} was blocked by network.offline")
}
pub struct SanitizedRegistryError(Inner);
enum Inner {
Transport(reqwest::Error),
Resolution(ResolutionFailure),
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
pub enum ResolutionFailure {
#[error("DNS preflight resolved no addresses")]
NoAddresses,
#[error("DNS preflight lookup failed")]
LookupFailed,
}
impl SanitizedRegistryError {
#[must_use]
pub const fn resolution_failure(&self) -> Option<ResolutionFailure> {
match &self.0 {
Inner::Resolution(failure) => Some(*failure),
Inner::Transport(_) => None,
}
}
#[must_use]
pub fn origin(&self) -> ErrorOrigin {
match &self.0 {
Inner::Resolution(_) => ErrorOrigin::Unattributed,
Inner::Transport(error) if error.is_builder() => ErrorOrigin::Unattributed,
Inner::Transport(_) => ErrorOrigin::Endpoint,
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ErrorOrigin {
Endpoint,
Unattributed,
}
impl ErrorOrigin {
pub(crate) const fn merge(self, other: Self) -> Self {
match (self, other) {
(Self::Unattributed, Self::Unattributed) => Self::Unattributed,
(Self::Endpoint, _) | (_, Self::Endpoint) => Self::Endpoint,
}
}
}
impl From<reqwest::Error> for SanitizedRegistryError {
fn from(error: reqwest::Error) -> Self {
Self(Inner::Transport(error.without_url()))
}
}
impl From<ResolutionFailure> for SanitizedRegistryError {
fn from(failure: ResolutionFailure) -> Self {
Self(Inner::Resolution(failure))
}
}
impl std::fmt::Display for SanitizedRegistryError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match &self.0 {
Inner::Transport(error) => std::fmt::Display::fmt(error, f),
Inner::Resolution(failure) => std::fmt::Display::fmt(failure, f),
}
}
}
impl std::fmt::Debug for SanitizedRegistryError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "SanitizedRegistryError({self})")
}
}
impl std::error::Error for SanitizedRegistryError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
None
}
}
#[non_exhaustive]
#[derive(Error)]
pub enum DepsError {
#[error("failed to parse {file_type}: {source}")]
#[non_exhaustive]
ParseError {
file_type: String,
#[source]
source: Box<dyn std::error::Error + Send + Sync>,
},
#[error("{}", registry_error_message(package, source))]
RegistryError {
package: RedactedUrl,
#[source]
source: SanitizedRegistryError,
},
#[error("cache error: {0}")]
CacheError(String),
#[error("{message}")]
#[non_exhaustive]
RateLimited {
message: String,
verified: RateLimitEvidence,
source_status: Option<u16>,
},
#[error("{package} not found on {registry}")]
#[non_exhaustive]
PackageNotFound {
package: RedactedName,
registry: &'static str,
origin: ErrorOrigin,
},
#[error("{}", http_status_message(*status, url))]
HttpStatus {
url: RedactedUrl,
status: u16,
},
#[error("failed to parse {registry} response for {package}: {source}")]
ApiResponse {
package: RedactedName,
registry: &'static str,
#[source]
source: serde_json::Error,
},
#[error("{}", response_too_large_message(url, *limit))]
ResponseTooLarge {
url: RedactedUrl,
limit: usize,
},
#[error("invalid version requirement: {0}")]
InvalidVersionReq(String),
#[error("invalid package name: {0}")]
InvalidPackageName(#[from] InvalidPackageName),
#[error("I/O error: {0}")]
Io(#[from] std::io::Error),
#[error("JSON error: {0}")]
Json(#[from] serde_json::Error),
#[error("unsupported ecosystem: {0}")]
UnsupportedEcosystem(String),
#[error("ambiguous ecosystem detection for file: {0}")]
AmbiguousEcosystem(String),
#[error("invalid URI: {0}")]
InvalidUri(String),
#[error("{}", offline_message(url))]
Offline {
url: RedactedUrl,
},
#[error(
"index chain resolution halted by a transport error on one hop — not falling back \
to a less-trusted index"
)]
ChainResolutionHalted,
#[error("{package} on {registry}: {reason}")]
PaginatedListIncomplete {
package: RedactedName,
registry: &'static str,
reason: PaginationStop,
},
#[error("registry host of {url} resolves to a {} address, blocked by network policy", block.class())]
#[non_exhaustive]
HostBlockedByPolicy {
url: RedactedUrl,
block: BlockedHost,
},
#[error("refusing to send a credential to {url} outside its trusted prefix")]
#[non_exhaustive]
CredentialOutsideTrustedPrefix {
url: RedactedUrl,
},
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum PaginationStop {
PageCap,
InvalidNextLink,
TimeBudget,
NoConsistentSnapshot,
}
impl std::fmt::Display for PaginationStop {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(match self {
Self::PageCap => "registry release list exceeds the page limit",
Self::InvalidNextLink => "registry returned an unusable next-page link",
Self::TimeBudget => "registry release list took too long to fetch",
Self::NoConsistentSnapshot => "no consistent registry release list is available",
})
}
}
impl std::fmt::Debug for DepsError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::ParseError { file_type, source } => f
.debug_struct("ParseError")
.field("file_type", file_type)
.field("source", source)
.finish(),
Self::RegistryError { package, source } => f
.debug_struct("RegistryError")
.field("package", package)
.field("source", source)
.finish(),
Self::CacheError(message) => f.debug_tuple("CacheError").field(message).finish(),
Self::RateLimited {
message,
verified,
source_status,
} => f
.debug_struct("RateLimited")
.field("message", message)
.field("verified", verified)
.field("source_status", source_status)
.finish(),
Self::PackageNotFound {
package,
registry,
origin,
} => f
.debug_struct("PackageNotFound")
.field("package", package)
.field("registry", registry)
.field("origin", origin)
.finish(),
Self::HttpStatus { url, status } => f
.debug_struct("HttpStatus")
.field("url", url)
.field("status", status)
.finish(),
Self::ApiResponse {
package,
registry,
source,
} => f
.debug_struct("ApiResponse")
.field("package", package)
.field("registry", registry)
.field("source", source)
.finish(),
Self::ResponseTooLarge { url, limit } => f
.debug_struct("ResponseTooLarge")
.field("url", url)
.field("limit", limit)
.finish(),
Self::InvalidVersionReq(req) => f.debug_tuple("InvalidVersionReq").field(req).finish(),
Self::InvalidPackageName(err) => {
f.debug_tuple("InvalidPackageName").field(err).finish()
}
Self::Io(source) => f.debug_tuple("Io").field(source).finish(),
Self::Json(source) => f.debug_tuple("Json").field(source).finish(),
Self::UnsupportedEcosystem(ecosystem) => f
.debug_tuple("UnsupportedEcosystem")
.field(ecosystem)
.finish(),
Self::AmbiguousEcosystem(path) => {
f.debug_tuple("AmbiguousEcosystem").field(path).finish()
}
Self::InvalidUri(uri) => f.debug_tuple("InvalidUri").field(uri).finish(),
Self::Offline { url } => f.debug_struct("Offline").field("url", url).finish(),
Self::ChainResolutionHalted => f.write_str("ChainResolutionHalted"),
Self::PaginatedListIncomplete {
package,
registry,
reason,
} => f
.debug_struct("PaginatedListIncomplete")
.field("package", package)
.field("registry", registry)
.field("reason", reason)
.finish(),
Self::HostBlockedByPolicy { url, block } => f
.debug_struct("HostBlockedByPolicy")
.field("url", url)
.field("block", block)
.finish(),
Self::CredentialOutsideTrustedPrefix { url } => f
.debug_struct("CredentialOutsideTrustedPrefix")
.field("url", url)
.finish(),
}
}
}
impl DepsError {
#[must_use]
pub fn rate_limited(message: impl Into<String>, verified: RateLimitEvidence) -> Self {
Self::RateLimited {
message: message.into(),
verified,
source_status: None,
}
}
#[must_use]
pub fn parse_error(file_type: impl Into<String>, source: &dyn std::fmt::Display) -> Self {
Self::ParseError {
file_type: file_type.into(),
source: crate::redact::parse_error_source(source),
}
}
#[must_use]
pub fn not_found_locally(package: &str, registry: &'static str) -> Self {
Self::PackageNotFound {
package: package.into(),
registry,
origin: ErrorOrigin::Unattributed,
}
}
pub(crate) fn not_found_at_endpoint(package: &str, registry: &'static str) -> Self {
Self::PackageNotFound {
package: package.into(),
registry,
origin: ErrorOrigin::Endpoint,
}
}
#[must_use]
pub const fn is_not_found(&self) -> bool {
matches!(
self,
Self::PackageNotFound { .. } | Self::HttpStatus { status: 404, .. }
)
}
#[must_use]
pub fn fetch_failure(&self) -> FetchFailure {
match self {
Self::RateLimited { message, .. } => FetchFailure::Actionable(message.clone()),
Self::ChainResolutionHalted => FetchFailure::Actionable(
"index unreachable — resolution halted, not falling back to a less-trusted \
index"
.to_string(),
),
Self::PaginatedListIncomplete { reason, .. } => {
FetchFailure::Actionable(format!("{reason}; not showing a partial list"))
}
Self::HostBlockedByPolicy { block, .. } => {
let class = block.class();
FetchFailure::Actionable(match block.policy() {
BlockingPolicy::Floor => format!(
"registry host resolves to a {class} address, which is never a registry \
under any policy"
),
BlockingPolicy::WorkspaceRegistries(_) => format!(
"registry host resolves to a {class} address, blocked by \
registries.workspace_registries policy{}",
block.hint_suffix()
),
})
}
Self::CredentialOutsideTrustedPrefix { .. } => FetchFailure::Actionable(
"credential withheld: the registry URL is outside the credential's trusted prefix"
.to_string(),
),
Self::Offline { .. }
| Self::ParseError { .. }
| Self::RegistryError { .. }
| Self::CacheError(_)
| Self::PackageNotFound { .. }
| Self::HttpStatus { .. }
| Self::ApiResponse { .. }
| Self::ResponseTooLarge { .. }
| Self::InvalidVersionReq(_)
| Self::InvalidPackageName(_)
| Self::Io(_)
| Self::Json(_)
| Self::UnsupportedEcosystem(_)
| Self::AmbiguousEcosystem(_)
| Self::InvalidUri(_) => FetchFailure::Transient,
}
}
#[must_use]
pub const fn is_offline(&self) -> bool {
matches!(self, Self::Offline { .. })
}
#[must_use]
pub fn into_chain_halt(self) -> Self {
match self {
Self::HostBlockedByPolicy { .. } => self,
Self::ParseError { .. }
| Self::RegistryError { .. }
| Self::CacheError(_)
| Self::RateLimited { .. }
| Self::PackageNotFound { .. }
| Self::HttpStatus { .. }
| Self::ApiResponse { .. }
| Self::ResponseTooLarge { .. }
| Self::InvalidVersionReq(_)
| Self::InvalidPackageName(_)
| Self::Io(_)
| Self::Json(_)
| Self::UnsupportedEcosystem(_)
| Self::AmbiguousEcosystem(_)
| Self::InvalidUri(_)
| Self::CredentialOutsideTrustedPrefix { .. }
| Self::Offline { .. }
| Self::ChainResolutionHalted
| Self::PaginatedListIncomplete { .. } => Self::ChainResolutionHalted,
}
}
#[must_use]
pub(crate) const fn safe_tracing_summary(&self) -> (Option<u16>, &'static str) {
match self {
Self::HttpStatus { status, .. } => (Some(*status), "http-status"),
Self::RegistryError { .. } => (None, "transport"),
Self::CacheError(_) => (None, "cache"),
Self::Offline { .. } => (None, "offline"),
Self::ResponseTooLarge { .. } => (None, "response-too-large"),
Self::RateLimited {
verified: RateLimitEvidence::Confirmed,
..
} => (None, "rate-limited"),
Self::RateLimited {
verified: RateLimitEvidence::Inferred,
..
} => (None, "rate-limited-unverified"),
Self::ApiResponse { .. } => (None, "api-response"),
Self::PackageNotFound { .. } => (None, "not-found"),
Self::ParseError { .. } => (None, "parse-error"),
Self::InvalidVersionReq(_) => (None, "invalid-version-req"),
Self::InvalidPackageName(_) => (None, "invalid-package-name"),
Self::Io(_) => (None, "io"),
Self::Json(_) => (None, "json"),
Self::UnsupportedEcosystem(_) => (None, "unsupported-ecosystem"),
Self::AmbiguousEcosystem(_) => (None, "ambiguous-ecosystem"),
Self::InvalidUri(_) => (None, "invalid-uri"),
Self::ChainResolutionHalted => (None, "chain-resolution-halted"),
Self::PaginatedListIncomplete { .. } => (None, "paginated-list-incomplete"),
Self::HostBlockedByPolicy { .. } => (None, "host-blocked-by-policy"),
Self::CredentialOutsideTrustedPrefix { .. } => (None, "credential-scope"),
}
}
#[must_use]
pub fn origin(&self) -> ErrorOrigin {
match self {
Self::PackageNotFound { origin, .. } => *origin,
Self::HttpStatus { .. }
| Self::ApiResponse { .. }
| Self::ResponseTooLarge { .. }
| Self::ChainResolutionHalted
| Self::RateLimited {
source_status: Some(_),
..
}
| Self::PaginatedListIncomplete {
reason:
PaginationStop::PageCap
| PaginationStop::InvalidNextLink
| PaginationStop::TimeBudget,
..
} => ErrorOrigin::Endpoint,
Self::RegistryError { source, .. } => source.origin(),
Self::RateLimited {
source_status: None,
..
}
| Self::PaginatedListIncomplete {
reason: PaginationStop::NoConsistentSnapshot,
..
}
| Self::ParseError { .. }
| Self::CacheError(_)
| Self::InvalidVersionReq(_)
| Self::InvalidPackageName(_)
| Self::Io(_)
| Self::Json(_)
| Self::UnsupportedEcosystem(_)
| Self::AmbiguousEcosystem(_)
| Self::InvalidUri(_)
| Self::Offline { .. }
| Self::HostBlockedByPolicy { .. }
| Self::CredentialOutsideTrustedPrefix { .. } => ErrorOrigin::Unattributed,
}
}
}
#[non_exhaustive]
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum FetchFailure {
Actionable(String),
Transient,
NotAttempted,
}
pub type Result<T> = std::result::Result<T, DepsError>;
#[cfg(test)]
mod tests {
use super::*;
use crate::net_policy::{HostClass, WorkspaceRegistryAccess};
use std::assert_matches;
use std::error::Error as StdError;
#[test]
fn test_error_display() {
let error = DepsError::CacheError("test error".into());
assert_eq!(error.to_string(), "cache error: test error");
}
#[tokio::test]
async fn test_sanitized_registry_error_strips_url_on_real_transport_error() {
let port = {
let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
listener.local_addr().unwrap().port()
};
let url = format!("http://127.0.0.1:{port}/pkg?token=super-secret-value");
let reqwest_err = reqwest::Client::new().get(&url).send().await.unwrap_err();
assert!(
reqwest_err.url().is_some(),
"test setup invariant: the underlying reqwest::Error must carry a URL"
);
let sanitized: SanitizedRegistryError = reqwest_err.into();
assert!(
!sanitized.to_string().contains("super-secret-value"),
"sanitized: {sanitized}"
);
assert!(
!format!("{sanitized:?}").contains("super-secret-value"),
"sanitized debug: {sanitized:?}"
);
}
#[tokio::test]
async fn test_sanitized_registry_error_source_is_always_none() {
let port = {
let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
listener.local_addr().unwrap().port()
};
let url = format!("http://127.0.0.1:{port}/pkg?token=super-secret-value");
let reqwest_err = reqwest::Client::new().get(&url).send().await.unwrap_err();
let sanitized: SanitizedRegistryError = reqwest_err.into();
let Inner::Transport(raw) = &sanitized.0 else {
panic!("a reqwest error converts to the transport case");
};
assert!(
raw.source().is_some(),
"test setup invariant: a connection-refused error must have a populated source chain"
);
assert!(
StdError::source(&sanitized).is_none(),
"SanitizedRegistryError::source() must always be None"
);
}
#[test]
fn test_safe_tracing_summary_covers_every_reachable_variant() {
assert_eq!(
DepsError::HttpStatus {
url: "https://example.com/pkg?token=secret".into(),
status: 503,
}
.safe_tracing_summary(),
(Some(503), "http-status")
);
assert_eq!(
DepsError::RegistryError {
package: "https://example.com/pkg?token=secret".into(),
source: reqwest::Client::new()
.get("not a url")
.build()
.unwrap_err()
.into(),
}
.safe_tracing_summary(),
(None, "transport")
);
assert_eq!(
DepsError::CacheError("poisoned lock".into()).safe_tracing_summary(),
(None, "cache")
);
assert_eq!(
DepsError::Offline {
url: "https://example.com/pkg?token=secret".into(),
}
.safe_tracing_summary(),
(None, "offline")
);
assert_eq!(
DepsError::ResponseTooLarge {
url: "https://example.com/pkg?token=secret".into(),
limit: 1024,
}
.safe_tracing_summary(),
(None, "response-too-large")
);
assert_eq!(
DepsError::RateLimited {
message: "set GITHUB_TOKEN".into(),
verified: RateLimitEvidence::Confirmed,
source_status: Some(403),
}
.safe_tracing_summary(),
(None, "rate-limited")
);
assert_eq!(
DepsError::RateLimited {
message: "set GITHUB_TOKEN".into(),
verified: RateLimitEvidence::Inferred,
source_status: None,
}
.safe_tracing_summary(),
(None, "rate-limited-unverified")
);
assert_eq!(
DepsError::ApiResponse {
package: "flask".into(),
registry: "PyPI",
source: serde_json::from_str::<serde_json::Value>("{invalid}").unwrap_err(),
}
.safe_tracing_summary(),
(None, "api-response")
);
assert_eq!(
DepsError::not_found_locally("flask", "PyPI").safe_tracing_summary(),
(None, "not-found")
);
assert_eq!(
DepsError::ParseError {
file_type: "Cargo.toml".into(),
source: Box::new(std::io::Error::new(std::io::ErrorKind::InvalidData, "bad")),
}
.safe_tracing_summary(),
(None, "parse-error")
);
assert_eq!(
DepsError::InvalidVersionReq("bad range".into()).safe_tracing_summary(),
(None, "invalid-version-req")
);
assert_eq!(
DepsError::Io(std::io::Error::new(
std::io::ErrorKind::NotFound,
"not found"
))
.safe_tracing_summary(),
(None, "io")
);
assert_eq!(
DepsError::Json(serde_json::from_str::<serde_json::Value>("{bad}").unwrap_err())
.safe_tracing_summary(),
(None, "json")
);
assert_eq!(
DepsError::UnsupportedEcosystem("unknown".into()).safe_tracing_summary(),
(None, "unsupported-ecosystem")
);
assert_eq!(
DepsError::AmbiguousEcosystem("file.txt".into()).safe_tracing_summary(),
(None, "ambiguous-ecosystem")
);
assert_eq!(
DepsError::InvalidUri("not a uri".into()).safe_tracing_summary(),
(None, "invalid-uri")
);
assert_eq!(
DepsError::ChainResolutionHalted.safe_tracing_summary(),
(None, "chain-resolution-halted")
);
}
#[test]
fn test_safe_tracing_summary_output_never_contains_the_url() {
let error = DepsError::HttpStatus {
url: "https://npm.internal/pkg?token=super-secret-value".into(),
status: 503,
};
let (status, cause) = error.safe_tracing_summary();
assert_eq!(status, Some(503));
assert!(!cause.contains("super-secret-value"));
assert!(!cause.contains("npm.internal"));
}
#[test]
fn test_response_too_large() {
let error = DepsError::ResponseTooLarge {
url: "https://example.com/data".into(),
limit: 32 * 1024 * 1024,
};
assert_eq!(
error.to_string(),
"response body for https://example.com/data exceeds 33554432 byte limit"
);
}
#[test]
fn test_http_status_display_redacts_query_string() {
let error = DepsError::HttpStatus {
url: "https://npm.internal/pkg?_authToken=super-secret-value".into(),
status: 503,
};
let message = error.to_string();
assert!(
!message.contains("super-secret-value"),
"message: {message}"
);
assert_eq!(
message,
"HTTP 503 Service Unavailable for https://npm.internal/pkg"
);
}
#[test]
fn test_registry_error_display_redacts_query_string() {
let error = DepsError::RegistryError {
package: "https://npm.internal/pkg?_authToken=super-secret-value".into(),
source: reqwest::Client::new()
.get("not a url")
.build()
.unwrap_err()
.into(),
};
let message = error.to_string();
assert!(
!message.contains("super-secret-value"),
"message: {message}"
);
assert!(message.starts_with("registry request failed for https://npm.internal/pkg:"));
}
#[test]
fn test_registry_error_display_does_not_mangle_scoped_package_name() {
let error = DepsError::RegistryError {
package: "@types/node".into(),
source: reqwest::Client::new()
.get("not a url")
.build()
.unwrap_err()
.into(),
};
let message = error.to_string();
assert!(
message.starts_with("registry request failed for @types/node:"),
"message: {message}"
);
}
#[test]
fn test_offline_display_redacts_query_string() {
let error = DepsError::Offline {
url: "https://npm.internal/pkg?_authToken=super-secret-value".into(),
};
let message = error.to_string();
assert!(
!message.contains("super-secret-value"),
"message: {message}"
);
}
#[test]
fn test_response_too_large_display_redacts_query_string() {
let error = DepsError::ResponseTooLarge {
url: "https://npm.internal/pkg?_authToken=super-secret-value".into(),
limit: 1024,
};
let message = error.to_string();
assert!(
!message.contains("super-secret-value"),
"message: {message}"
);
}
#[test]
fn test_debug_redacts_query_string_for_every_url_bearing_variant() {
let credential_bearing = [
DepsError::HttpStatus {
url: "https://npm.internal/pkg?_authToken=super-secret-value".into(),
status: 503,
},
DepsError::Offline {
url: "https://npm.internal/pkg?_authToken=super-secret-value".into(),
},
DepsError::ResponseTooLarge {
url: "https://npm.internal/pkg?_authToken=super-secret-value".into(),
limit: 1024,
},
DepsError::RegistryError {
package: "https://npm.internal/pkg?_authToken=super-secret-value".into(),
source: reqwest::Client::new()
.get("not a url")
.build()
.unwrap_err()
.into(),
},
];
for error in credential_bearing {
let debug = format!("{error:?}");
assert!(
!debug.contains("super-secret-value"),
"Debug leaked the credential for {error}: {debug}"
);
}
}
#[test]
fn test_http_status_url_field_is_redacted_even_via_direct_destructure() {
let error = DepsError::HttpStatus {
url: RedactedUrl::new("https://npm.internal/pkg?_authToken=super-secret-value"),
status: 401,
};
let DepsError::HttpStatus { url, .. } = error else {
unreachable!()
};
assert_eq!(url.to_string(), "https://npm.internal/pkg");
assert!(!url.to_string().contains("super-secret-value"));
}
#[test]
fn test_debug_still_shows_non_url_fields() {
let error = DepsError::not_found_locally("left-pad", "npm");
let debug = format!("{error:?}");
assert!(debug.contains("left-pad"), "debug: {debug}");
assert!(debug.contains("npm"), "debug: {debug}");
}
#[test]
fn test_invalid_version_req() {
let error = DepsError::InvalidVersionReq("invalid".into());
assert_eq!(error.to_string(), "invalid version requirement: invalid");
}
#[test]
fn test_parse_error() {
let io_err = std::io::Error::new(std::io::ErrorKind::InvalidData, "bad data");
let error = DepsError::ParseError {
file_type: "Cargo.toml".into(),
source: Box::new(io_err),
};
assert!(error.to_string().contains("failed to parse Cargo.toml"));
}
#[test]
fn test_io_error_conversion() {
let io_err = std::io::Error::new(std::io::ErrorKind::NotFound, "file not found");
let error: DepsError = io_err.into();
assert!(error.to_string().contains("I/O error"));
}
#[test]
fn test_unsupported_ecosystem() {
let error = DepsError::UnsupportedEcosystem("unknown".into());
assert_eq!(error.to_string(), "unsupported ecosystem: unknown");
}
#[test]
fn test_ambiguous_ecosystem() {
let error = DepsError::AmbiguousEcosystem("file.txt".into());
assert_eq!(
error.to_string(),
"ambiguous ecosystem detection for file: file.txt"
);
}
#[test]
fn test_invalid_uri() {
let error = DepsError::InvalidUri("http://example.com".into());
assert_eq!(error.to_string(), "invalid URI: http://example.com");
}
#[test]
fn test_offline_error_display_and_predicate() {
let error = DepsError::Offline {
url: "https://crates.io/api/v1/crates/serde".into(),
};
assert!(error.to_string().contains("offline"));
assert!(error.is_offline());
assert!(!error.is_not_found());
let other = DepsError::CacheError("boom".into());
assert!(!other.is_offline());
}
#[test]
fn test_package_not_found() {
let error = DepsError::not_found_locally("flask", "PyPI");
assert_eq!(error.to_string(), "flask not found on PyPI");
}
#[test]
fn test_package_not_found_display_redacts_credential_shaped_name() {
let error = DepsError::not_found_locally(
"com.example:deploy:AUDITSENTINEL0000@git.internal.corp",
"Maven Central",
);
assert!(
!error.to_string().contains("AUDITSENTINEL0000"),
"Display leaked a credential-shaped package name: {error}"
);
assert!(
!format!("{error:?}").contains("AUDITSENTINEL0000"),
"Debug leaked a credential-shaped package name: {error:?}"
);
assert!(error.to_string().contains("git.internal.corp"));
}
#[test]
fn test_api_response_display_redacts_credential_shaped_name() {
let json_err = serde_json::from_str::<serde_json::Value>("{invalid}").unwrap_err();
let error = DepsError::ApiResponse {
package: "com.example:deploy:AUDITSENTINEL0000@git.internal.corp".into(),
registry: "Maven Central",
source: json_err,
};
assert!(
!error.to_string().contains("AUDITSENTINEL0000"),
"Display leaked a credential-shaped package name: {error}"
);
assert!(
!format!("{error:?}").contains("AUDITSENTINEL0000"),
"Debug leaked a credential-shaped package name: {error:?}"
);
}
#[test]
fn test_http_status_with_known_reason() {
let error = DepsError::HttpStatus {
url: "https://example.com/data".into(),
status: 404,
};
assert_eq!(
error.to_string(),
"HTTP 404 Not Found for https://example.com/data"
);
}
#[test]
fn test_http_status_with_unknown_code() {
let error = DepsError::HttpStatus {
url: "https://example.com/data".into(),
status: 599,
};
assert_eq!(error.to_string(), "HTTP 599 for https://example.com/data");
}
#[test]
fn test_api_response_error() {
let json_err = serde_json::from_str::<serde_json::Value>("{invalid}").unwrap_err();
let error = DepsError::ApiResponse {
package: "flask".into(),
registry: "PyPI",
source: json_err,
};
assert!(
error
.to_string()
.starts_with("failed to parse PyPI response for flask:")
);
}
#[test]
fn paginated_list_incomplete_is_actionable_with_fixed_message() {
let incomplete = |reason| DepsError::PaginatedListIncomplete {
package: "acme.networking".into(),
registry: "Swift package registry",
reason,
};
assert_eq!(
incomplete(PaginationStop::PageCap).fetch_failure(),
FetchFailure::Actionable(
"registry release list exceeds the page limit; not showing a partial list".into()
)
);
let err = incomplete(PaginationStop::InvalidNextLink);
assert_eq!(
err.fetch_failure(),
FetchFailure::Actionable(
"registry returned an unusable next-page link; not showing a partial list".into()
)
);
assert_eq!(
err.safe_tracing_summary(),
(None, "paginated-list-incomplete")
);
}
#[test]
fn host_blocked_by_policy_message_distinguishes_never_a_registry_from_gated() {
let blocked = |class| DepsError::HostBlockedByPolicy {
url: "https://10.0.0.5.nip.io/api?token=secret".into(),
block: BlockedHost::new(class, WorkspaceRegistryAccess::PublicOnly),
};
assert_eq!(
blocked(HostClass::PrivateV4).fetch_failure(),
FetchFailure::Actionable(format!(
"registry host resolves to a private (RFC1918) address, blocked by \
registries.workspace_registries policy{}",
BlockedHost::new(HostClass::PrivateV4, WorkspaceRegistryAccess::PublicOnly)
.hint_suffix()
))
);
let at_off = DepsError::HostBlockedByPolicy {
url: "https://corp.example/".into(),
block: BlockedHost::new(HostClass::PrivateV4, WorkspaceRegistryAccess::Off),
};
assert!(
!format!("{:?}", at_off.fetch_failure()).contains("DEPS_LSP_PRIVATE_REGISTRY_HOSTS"),
"the allowlist cannot help at level Off"
);
assert_eq!(
blocked(HostClass::Loopback).fetch_failure(),
FetchFailure::Actionable(
"registry host resolves to a loopback address, which is never a registry \
under any policy"
.into()
)
);
let err = blocked(HostClass::Cgnat);
assert_eq!(err.safe_tracing_summary(), (None, "host-blocked-by-policy"));
assert!(!err.is_not_found());
assert!(!err.to_string().contains("secret"), "{err}");
assert!(!format!("{err:?}").contains("secret"), "{err:?}");
}
#[test]
fn credential_outside_trusted_prefix_is_actionable_halts_chain_and_redacts_url() {
let err = DepsError::CredentialOutsideTrustedPrefix {
url: "https://elsewhere.test/api?token=secret".into(),
};
assert_eq!(
err.to_string(),
format!(
"refusing to send a credential to {} outside its trusted prefix",
RedactedUrl::new("https://elsewhere.test/api?token=secret")
)
);
let FetchFailure::Actionable(hint) = err.fetch_failure() else {
panic!("a credential outside its trusted prefix is a configuration fault");
};
assert!(
!hint.contains("elsewhere.test") && !hint.contains("secret"),
"{hint}"
);
assert_eq!(err.safe_tracing_summary(), (None, "credential-scope"));
assert!(!err.is_not_found());
assert!(!format!("{err} {err:?}").contains("secret"));
assert_matches!(err.into_chain_halt(), DepsError::ChainResolutionHalted);
}
#[test]
fn into_chain_halt_keeps_policy_block_and_halts_everything_else() {
let blocked = DepsError::HostBlockedByPolicy {
url: "https://corp.example/".into(),
block: BlockedHost::new(HostClass::PrivateV4, WorkspaceRegistryAccess::PublicOnly),
};
assert_matches!(
blocked.into_chain_halt(),
DepsError::HostBlockedByPolicy { .. }
);
assert_matches!(
DepsError::CacheError("x".into()).into_chain_halt(),
DepsError::ChainResolutionHalted
);
}
#[test]
fn test_fetch_failure_classifies_every_non_rate_limited_variant_as_transient() {
let reqwest_err = reqwest::Client::new()
.get("not a valid url")
.build()
.unwrap_err();
let json_err = serde_json::from_str::<serde_json::Value>("{invalid}").unwrap_err();
let io_err = std::io::Error::new(std::io::ErrorKind::NotFound, "not found");
let non_rate_limited = [
DepsError::ParseError {
file_type: "Cargo.toml".into(),
source: Box::new(std::io::Error::new(std::io::ErrorKind::InvalidData, "bad")),
},
DepsError::RegistryError {
package: "flask".into(),
source: reqwest_err.into(),
},
DepsError::CacheError("connection reset".into()),
DepsError::not_found_locally("flask", "PyPI"),
DepsError::HttpStatus {
url: "https://example.com".into(),
status: 500,
},
DepsError::ApiResponse {
package: "flask".into(),
registry: "PyPI",
source: json_err,
},
DepsError::ResponseTooLarge {
url: "https://example.com".into(),
limit: 1024,
},
DepsError::InvalidVersionReq("bad range".into()),
DepsError::Io(io_err),
DepsError::Json(serde_json::from_str::<serde_json::Value>("{bad}").unwrap_err()),
DepsError::UnsupportedEcosystem("unknown".into()),
DepsError::AmbiguousEcosystem("file.txt".into()),
DepsError::InvalidUri("not a uri".into()),
DepsError::Offline {
url: "https://example.com".into(),
},
];
for error in non_rate_limited {
assert_eq!(
error.fetch_failure(),
FetchFailure::Transient,
"expected Transient for {error:?}"
);
}
for verified in [RateLimitEvidence::Confirmed, RateLimitEvidence::Inferred] {
let rate_limited = DepsError::RateLimited {
message: "set GITHUB_TOKEN to increase the rate limit".into(),
verified,
source_status: None,
};
assert_eq!(
rate_limited.fetch_failure(),
FetchFailure::Actionable("set GITHUB_TOKEN to increase the rate limit".into()),
"verified={verified:?}"
);
}
assert_eq!(
DepsError::ChainResolutionHalted.fetch_failure(),
FetchFailure::Actionable(
"index unreachable — resolution halted, not falling back to a less-trusted \
index"
.to_string()
)
);
}
#[test]
fn origin_table() {
let endpoint = [
DepsError::HttpStatus {
url: "https://r.example/x".into(),
status: 500,
},
DepsError::ResponseTooLarge {
url: "https://r.example/x".into(),
limit: 1,
},
DepsError::ChainResolutionHalted,
DepsError::PaginatedListIncomplete {
package: "p".into(),
registry: "gitlab",
reason: PaginationStop::PageCap,
},
DepsError::RateLimited {
message: "m".into(),
verified: RateLimitEvidence::Confirmed,
source_status: Some(429),
},
crate::not_found_or(
DepsError::HttpStatus {
url: "https://r.example/x".into(),
status: 404,
},
"p",
"npm",
&[],
),
];
for error in endpoint {
assert_eq!(error.origin(), ErrorOrigin::Endpoint, "{error:?}");
}
let unattributed = [
DepsError::CacheError("x".into()),
DepsError::not_found_locally("p", "npm"),
DepsError::PaginatedListIncomplete {
package: "p".into(),
registry: "gitlab",
reason: PaginationStop::NoConsistentSnapshot,
},
DepsError::rate_limited("m", RateLimitEvidence::Confirmed),
DepsError::Offline {
url: "https://r.example/x".into(),
},
];
for error in unattributed {
assert_eq!(error.origin(), ErrorOrigin::Unattributed, "{error:?}");
}
}
#[test]
fn origin_of_every_remaining_variant() {
let api = serde_json::from_str::<serde_json::Value>("{bad}").unwrap_err();
let endpoint = [
DepsError::ApiResponse {
package: "p".into(),
registry: "npm",
source: api,
},
DepsError::PaginatedListIncomplete {
package: "p".into(),
registry: "gitlab",
reason: PaginationStop::InvalidNextLink,
},
DepsError::PaginatedListIncomplete {
package: "p".into(),
registry: "gitlab",
reason: PaginationStop::TimeBudget,
},
];
for error in endpoint {
assert_eq!(error.origin(), ErrorOrigin::Endpoint, "{error:?}");
}
let unattributed = [
DepsError::parse_error("Cargo.toml", &"bad"),
DepsError::Io(std::io::Error::other("io")),
DepsError::Json(serde_json::from_str::<serde_json::Value>("{bad}").unwrap_err()),
DepsError::InvalidVersionReq("bad".into()),
DepsError::InvalidPackageName(InvalidPackageName::new("bad")),
DepsError::UnsupportedEcosystem("x".into()),
DepsError::AmbiguousEcosystem("x".into()),
DepsError::InvalidUri("x".into()),
DepsError::HostBlockedByPolicy {
url: "https://r.example/".into(),
block: BlockedHost::new(HostClass::PrivateV4, WorkspaceRegistryAccess::PublicOnly),
},
DepsError::CredentialOutsideTrustedPrefix {
url: "https://r.example/".into(),
},
];
for error in unattributed {
assert_eq!(error.origin(), ErrorOrigin::Unattributed, "{error:?}");
}
}
#[tokio::test]
async fn a_transport_error_that_is_not_a_builder_error_is_endpoint() {
let port = {
let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
listener.local_addr().unwrap().port()
};
let url = format!("http://127.0.0.1:{port}/pkg");
let refused = reqwest::Client::new().get(&url).send().await.unwrap_err();
let error = DepsError::RegistryError {
package: url.as_str().into(),
source: refused.into(),
};
assert_eq!(error.origin(), ErrorOrigin::Endpoint);
}
#[test]
fn registry_error_origin_follows_the_sanitized_cause() {
let builder = reqwest::Client::new().get("not a url").build().unwrap_err();
assert_eq!(
SanitizedRegistryError::from(builder).origin(),
ErrorOrigin::Unattributed
);
assert_eq!(
SanitizedRegistryError::from(ResolutionFailure::LookupFailed).origin(),
ErrorOrigin::Unattributed
);
}
}