Skip to main content

deps_core/
error.rs

1use thiserror::Error;
2
3use crate::net_policy::{BlockedHost, BlockingPolicy};
4use crate::package::InvalidPackageName;
5use crate::redact::{RedactedName, RedactedUrl};
6
7/// Whether a [`DepsError::RateLimited`] classification is backed by explicit server evidence
8/// or merely inferred from a status code and request context alone (#1295).
9#[derive(Debug, Clone, Copy, PartialEq, Eq)]
10pub enum RateLimitEvidence {
11    /// Backed by explicit server evidence, e.g. a confirmed `X-RateLimit-Remaining: 0`
12    /// response header (checked in `crate::cache`).
13    Confirmed,
14    /// Inferred from a status code and request context alone — could be an
15    /// abuse-detection false positive, a secondary rate limit, or an access-restricted repo.
16    Inferred,
17}
18
19/// Reconstructs the "{status} {reason}" text `reqwest::StatusCode`'s `Display`
20/// produces, since `HttpStatus` stores a bare `u16` for structural matching
21/// and loses the canonical reason phrase otherwise.
22///
23/// `url` is already a [`RedactedUrl`] (#789: `HttpStatus::url`'s field type itself makes the
24/// raw value unreachable, so there is nothing left to redact here) — this is the only place
25/// `HttpStatus`'s `Display` text is built.
26fn http_status_message(status: u16, url: &RedactedUrl) -> String {
27    let reason = reqwest::StatusCode::from_u16(status)
28        .ok()
29        .and_then(|s| s.canonical_reason());
30    reason.map_or_else(
31        || format!("HTTP {status} for {url}"),
32        |reason| format!("HTTP {status} {reason} for {url}"),
33    )
34}
35
36/// Builds [`DepsError::RegistryError`]'s `Display` text from its already-[`RedactedUrl`]
37/// `package` field (#767, #789).
38///
39/// [`DepsError::RegistryError`]'s `package` field is documented as a package name, but
40/// several `deps-core::cache` call sites populate it with a URL instead, so it is stored as
41/// [`RedactedUrl`] rather than a plain `String` — a no-op for an actual package name
42/// (including an npm-scoped one like `@types/node`, which an earlier revision of this
43/// function mangled into `***@types/node` before
44/// [`crate::redact::redact_userinfo`]'s empty-userinfo false positive was fixed at the
45/// root — #767 M1/code-review follow-up). `source`'s own `Display` can no longer re-embed the
46/// raw URL either: [`SanitizedRegistryError`]'s only constructor strips it unconditionally.
47fn registry_error_message(package: &RedactedUrl, source: &SanitizedRegistryError) -> String {
48    format!("registry request failed for {package}: {source}")
49}
50
51/// Builds [`DepsError::ResponseTooLarge`]'s `Display` text from its already-[`RedactedUrl`]
52/// `url` field (#767, #789).
53fn response_too_large_message(url: &RedactedUrl, limit: usize) -> String {
54    format!("response body for {url} exceeds {limit} byte limit")
55}
56
57/// Builds [`DepsError::Offline`]'s `Display` text from its already-[`RedactedUrl`] `url`
58/// field (#767, #789).
59fn offline_message(url: &RedactedUrl) -> String {
60    format!("offline: request to {url} was blocked by network.offline")
61}
62
63/// Wraps a `reqwest::Error` with its embedded request URL stripped, for storage in
64/// [`DepsError::RegistryError`]'s `source` field.
65///
66/// `reqwest::Error`'s own `Display` appends `" for url (...)"` when the underlying error
67/// carries a URL — `reqwest::Error::without_url()` strips this, but relying on every
68/// `RegistryError`-construction site to remember to call it is exactly the discipline gap
69/// this type closes (issue #789, see [`RedactedUrl`]'s own docs for the same problem on the
70/// URL-string side). The only constructor (`From<reqwest::Error>`) applies `.without_url()`
71/// unconditionally, so a raw URL can never reach `DepsError`'s `Display`/`Debug` through
72/// `{source}` forwarding, even when a future call site forgets.
73///
74/// **`self.0`'s own `source` chain is never exposed**, through either `Debug` or
75/// [`std::error::Error::source`] — this is deliberate, not an oversight. `.without_url()`
76/// only clears the *outer* error's own `url` field; `reqwest`'s `source` field is
77/// independent of it, and that source is not always a URL-free `hyper`/`io` error: reqwest
78/// 0.13.4's redirect policy (`src/redirect.rs`, the `https_only` check in
79/// `TowerPolicy::redirect`) rejects an `http://` redirect target by building
80/// `crate::error::redirect(crate::error::url_bad_scheme(next_url.clone()), next_url)` — the
81/// *inner* `url_bad_scheme(...)` error is itself a full `reqwest::Error` with `next_url`
82/// populated via `.with_url(...)`, nested as the *outer* error's `source`. That inner `url`
83/// is a field `.without_url()` on the outer error never touches, and `reqwest::Error`'s own
84/// derived-style `Debug` impl recursively prints `source`'s `Debug` (including that inner
85/// `url`) — so both a manual `.source()` walk and `{:?}` on the raw `reqwest::Error` can leak
86/// it. Since `reqwest` exposes no `source_mut()`-style API to reach in and strip that nested
87/// URL, this type treats itself as a leaf node instead: its [`std::error::Error::source`]
88/// impl always returns `None`, and `Debug` is hand-written to forward to the (already-safe)
89/// `Display` text rather than to `self.0`'s own `Debug`.
90///
91/// **Precision note on what is actually verified today**: this project's own client
92/// configuration never calls `reqwest::ClientBuilder::https_only` (`grep -rn '\.https_only('
93/// crates/` finds no hits), so the nested-URL shape above cannot currently occur through this
94/// crate's own request paths — the regression test below instead exercises a genuinely
95/// populated source chain via a real connection-refused (io-level) failure, which is what
96/// this project's client config can actually produce, and confirms it is discarded. The
97/// `https_only`/redirect mechanism itself is read directly from `reqwest` 0.13.4's pinned
98/// source (`redirect.rs`), not reproduced live here (doing so would need a TLS test harness
99/// this project does not otherwise have). `source()` returning `None` unconditionally — not
100/// only when a URL-bearing nested error is possible — is what makes this correct regardless:
101/// if a future change enables `https_only` on a shared client, this type's contract does not
102/// need re-auditing.
103///
104/// # Examples
105///
106/// ```
107/// use deps_core::error::SanitizedRegistryError;
108///
109/// // A builder-only `reqwest::Error` never carries a URL in the first place, so this
110/// // demonstrates the wrapper's `Display`/`Debug` forwarding without needing a real request.
111/// let raw = reqwest::Client::new().get("not a url").build().unwrap_err();
112/// let sanitized: SanitizedRegistryError = raw.into();
113/// assert!(!sanitized.to_string().is_empty());
114/// ```
115pub struct SanitizedRegistryError(Inner);
116
117enum Inner {
118    Transport(reqwest::Error),
119    Resolution(ResolutionFailure),
120}
121
122/// Why the DNS preflight that guards a proxied request could not resolve the target host.
123///
124/// Carried by [`SanitizedRegistryError`] so a preflight failure is classified like the
125/// transport failure the send path would have produced, instead of an untyped cache error.
126///
127/// # Examples
128///
129/// ```
130/// use deps_core::error::{ResolutionFailure, SanitizedRegistryError};
131///
132/// let error = SanitizedRegistryError::from(ResolutionFailure::NoAddresses);
133/// assert_eq!(error.resolution_failure(), Some(ResolutionFailure::NoAddresses));
134/// ```
135#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
136pub enum ResolutionFailure {
137    /// The resolver answered with zero addresses for the host.
138    #[error("DNS preflight resolved no addresses")]
139    NoAddresses,
140    /// The host name was unusable or the resolver failed outright.
141    #[error("DNS preflight lookup failed")]
142    LookupFailed,
143}
144
145impl SanitizedRegistryError {
146    /// A real [`ErrorOrigin::Endpoint`] transport failure (connection refused on a closed
147    /// loopback port), for tests of code that classifies errors by origin.
148    #[cfg(any(test, feature = "test-util"))]
149    #[must_use]
150    #[allow(
151        clippy::expect_used,
152        reason = "test-only constructor: a setup failure must abort the test"
153    )]
154    pub async fn endpoint_failure_for_test() -> Self {
155        let port = {
156            let listener = std::net::TcpListener::bind("127.0.0.1:0").expect("bind loopback");
157            listener.local_addr().expect("local addr").port()
158        };
159        reqwest::Client::new()
160            .get(format!("http://127.0.0.1:{port}/"))
161            .send()
162            .await
163            .expect_err("nothing listens on the closed port")
164            .into()
165    }
166
167    /// The preflight resolution failure this error wraps, or `None` for a transport error.
168    #[must_use]
169    pub const fn resolution_failure(&self) -> Option<ResolutionFailure> {
170        match &self.0 {
171            Inner::Resolution(failure) => Some(*failure),
172            Inner::Transport(_) => None,
173        }
174    }
175
176    /// Whether this failure says anything about the registry endpoint.
177    ///
178    /// A DNS-preflight failure and a request that could not even be built are local, so they
179    /// are [`ErrorOrigin::Unattributed`]; any other transport error (connect, timeout, TLS,
180    /// body) is [`ErrorOrigin::Endpoint`].
181    #[must_use]
182    pub fn origin(&self) -> ErrorOrigin {
183        match &self.0 {
184            Inner::Resolution(_) => ErrorOrigin::Unattributed,
185            Inner::Transport(error) if error.is_builder() => ErrorOrigin::Unattributed,
186            Inner::Transport(_) => ErrorOrigin::Endpoint,
187        }
188    }
189}
190
191/// Where a [`DepsError`] was produced, which decides whether it counts as evidence about the
192/// registry endpoint it was fetched from.
193///
194/// # Examples
195///
196/// ```
197/// use deps_core::DepsError;
198/// use deps_core::error::ErrorOrigin;
199///
200/// let status = DepsError::HttpStatus { url: "https://registry.example/x".into(), status: 503 };
201/// assert_eq!(status.origin(), ErrorOrigin::Endpoint);
202/// assert_eq!(DepsError::RecentlyFailed.origin(), ErrorOrigin::Unattributed);
203/// ```
204#[derive(Debug, Clone, Copy, PartialEq, Eq)]
205pub enum ErrorOrigin {
206    /// The endpoint produced or caused the error: a response was received, or the transport to
207    /// it failed.
208    Endpoint,
209    /// The error was raised locally (policy, parsing, cache, configuration) or cannot be tied
210    /// to the endpoint. It neither vouches for the endpoint nor accuses it.
211    Unattributed,
212}
213
214impl ErrorOrigin {
215    /// Combines two origins observed for one logical lookup: any endpoint involvement wins.
216    pub(crate) const fn merge(self, other: Self) -> Self {
217        match (self, other) {
218            (Self::Unattributed, Self::Unattributed) => Self::Unattributed,
219            (Self::Endpoint, _) | (_, Self::Endpoint) => Self::Endpoint,
220        }
221    }
222}
223
224impl From<reqwest::Error> for SanitizedRegistryError {
225    fn from(error: reqwest::Error) -> Self {
226        Self(Inner::Transport(error.without_url()))
227    }
228}
229
230impl From<ResolutionFailure> for SanitizedRegistryError {
231    fn from(failure: ResolutionFailure) -> Self {
232        Self(Inner::Resolution(failure))
233    }
234}
235
236impl std::fmt::Display for SanitizedRegistryError {
237    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
238        match &self.0 {
239            Inner::Transport(error) => std::fmt::Display::fmt(error, f),
240            Inner::Resolution(failure) => std::fmt::Display::fmt(failure, f),
241        }
242    }
243}
244
245impl std::fmt::Debug for SanitizedRegistryError {
246    /// Hand-written, not derived: forwards to `Display` (safe — `reqwest::Error`'s own
247    /// `Display` never recurses into its `source`'s text) instead of `self.0`'s own `Debug`,
248    /// which does recurse into `source` and would reopen the nested-URL leak this type's own
249    /// docs describe.
250    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
251        write!(f, "SanitizedRegistryError({self})")
252    }
253}
254
255impl std::error::Error for SanitizedRegistryError {
256    /// Always `None` — see this type's own docs for why the wrapped error's source chain is
257    /// never safe to expose, even via this trait's usual chain-walking contract.
258    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
259        None
260    }
261}
262
263/// Why a manifest or lockfile failed to parse, carried on [`DepsError::ParseError`].
264///
265/// Lets the language server tell the user the cause (for instance an over-nested TOML file)
266/// without matching on error text.
267///
268/// # Examples
269///
270/// ```
271/// use deps_core::ParseFailureKind;
272///
273/// assert_ne!(ParseFailureKind::Malformed, ParseFailureKind::NestingTooDeep);
274/// ```
275#[derive(Debug, Clone, Copy, PartialEq, Eq)]
276pub enum ParseFailureKind {
277    /// The content is not valid for its format.
278    Malformed,
279    /// The content nests deeper than the parser guard allows.
280    NestingTooDeep,
281}
282
283/// Core error types for deps-lsp.
284///
285/// Extended from Phase 1 to support multiple ecosystems (Cargo, npm, PyPI).
286/// All errors provide structured error handling with source error tracking.
287///
288/// # Examples
289///
290/// ```
291/// use deps_core::error::{DepsError, Result};
292///
293/// fn parse_file(content: &str, file_type: &str) -> Result<()> {
294///     // Parsing errors are automatically wrapped
295///     if content.is_empty() {
296///         return Err(DepsError::parse_error(
297///             file_type,
298///             &std::io::Error::new(std::io::ErrorKind::InvalidData, "empty content"),
299///         ));
300///     }
301///     Ok(())
302/// }
303/// ```
304#[non_exhaustive]
305#[derive(Error)]
306pub enum DepsError {
307    /// A manifest or lockfile failed to parse.
308    ///
309    /// `#[non_exhaustive]` on the variant itself (#1250, mirrors [`Self::RateLimited`]'s
310    /// precedent): the only way to construct this from outside `deps-core` is
311    /// [`Self::parse_error`], which always routes `source` through
312    /// [`crate::redact::parse_error_source`] — closing the recurring gap (#1240, #1243,
313    /// #1249) where a new call site hand-built this variant with an unredacted source.
314    ///
315    /// An external crate cannot build this variant as a struct literal — this fails to
316    /// compile with E0639 (`#[non_exhaustive]` variant constructed outside its defining
317    /// crate), not for some unrelated reason:
318    ///
319    /// ```compile_fail
320    /// use deps_core::DepsError;
321    ///
322    /// let _ = DepsError::ParseError {
323    ///     file_type: "Cargo.toml".into(),
324    ///     source: Box::new(std::io::Error::other("bad")),
325    /// };
326    /// ```
327    #[error("failed to parse {file_type}: {source}")]
328    #[non_exhaustive]
329    ParseError {
330        /// Ecosystem/file kind being parsed (e.g. `"Cargo.toml"`), for the error message.
331        file_type: String,
332        /// Why the parse failed, so a client-facing diagnostic can branch without matching text.
333        kind: ParseFailureKind,
334        /// The underlying parser error.
335        #[source]
336        source: Box<dyn std::error::Error + Send + Sync>,
337    },
338
339    /// A registry HTTP request failed at the transport layer.
340    #[error("{}", registry_error_message(package, source))]
341    RegistryError {
342        /// Name of the package the request was for — or, at several `deps-core::cache` call
343        /// sites, the request URL instead (see [`RedactedUrl`]'s own docs). Redaction is safe
344        /// to apply unconditionally: a genuine URL is redacted for real, and a genuine package
345        /// name is left alone unless it happens to contain a `:` or a non-leading `@` (a
346        /// leading `@`, e.g. an npm-scoped name like `@types/node`, is left untouched), in
347        /// which case it is redacted the same way a credential-bearing value would be (e.g. a
348        /// Maven/Gradle `group:artifact` coordinate becomes `group:***`) — a cosmetic false
349        /// positive, never a correctness issue, since no current call site populates this
350        /// field with a coordinate (only `cache/` does, always with a URL).
351        package: RedactedUrl,
352        /// The underlying `reqwest` error, with its embedded request URL stripped.
353        #[source]
354        source: SanitizedRegistryError,
355    },
356
357    /// A request URL was not `https`, refused at the egress chokepoint before any send. A
358    /// configuration fault that no retry resolves, so it is [`FetchFailure::Actionable`] with a
359    /// fixed, URL-free message.
360    ///
361    /// Only a configured or operator-declared URL can reach that check: URLs a registry supplies
362    /// (service-index resources, pagination links) are vetted by their ecosystem first, so this
363    /// never blames the user for a registry's own bad data.
364    ///
365    /// `#[non_exhaustive]` on the variant itself: only `deps-core`'s cache builds it.
366    #[error("URL must use HTTPS: {url}")]
367    #[non_exhaustive]
368    InsecureScheme {
369        /// The request URL, stored redacted.
370        url: RedactedUrl,
371    },
372
373    /// A bounded lookup gave up on its own budget before the registry finished answering.
374    #[error("{0}")]
375    BudgetExceeded(LookupBudget),
376
377    /// A repeated lookup was skipped because an identical one failed moments ago, sparing the
378    /// registry a duplicate live attempt.
379    #[error("an identical lookup failed recently; skipping the duplicate live attempt")]
380    RecentlyFailed,
381
382    /// A registry request was rejected for exceeding a rate limit. Unlike other variants,
383    /// `message` is a pre-vetted, IP-free, actionable hint safe to surface verbatim in a
384    /// per-dependency diagnostic (see [`Self::fetch_failure`]) — never build one from a raw
385    /// registry error body, which can embed the caller's public IP (`github.rs:332-346`).
386    ///
387    /// `#[non_exhaustive]` on the variant itself (#1295 critic M1, added alongside `verified`):
388    /// a future field addition to this variant specifically should not need to be a breaking
389    /// change again — unlike the enum-level `#[non_exhaustive]` above, which only blocks an
390    /// exhaustive top-level `match` on [`DepsError`], not an exhaustive struct-literal pattern
391    /// on this one variant's own fields.
392    #[error("{message}")]
393    #[non_exhaustive]
394    RateLimited {
395        /// Pre-vetted, IP-free message safe to surface verbatim in a diagnostic.
396        message: String,
397        /// Whether this classification is backed by explicit server evidence (e.g. a
398        /// confirmed `X-RateLimit-Remaining: 0` response header, checked in
399        /// `crate::cache`) rather than merely inferred from a status code and request
400        /// context alone (#1295). An unauthenticated GitHub 403 with no such evidence —
401        /// which could be an abuse-detection false positive, a secondary rate limit, or an
402        /// access-restricted repo — still gets classified as `RateLimited` for its actionable
403        /// hint, but with `verified: RateLimitEvidence::Inferred`, so a caller like
404        /// `test_util::unwrap_or_skip_github_rate_limit` can tell a confirmed exhaustion apart
405        /// from an assumed one instead of silently treating both as the same expected case.
406        verified: RateLimitEvidence,
407        /// The HTTP status this classification was built from, when known (#1295 critic N1).
408        /// `Some(403)`/`Some(429)` for a `crate::cache`-classified confirmed rate limit —
409        /// `None` for a canned, inference-only construction (e.g.
410        /// `crate::github::github_rate_limit_error`) that never saw a live response. Exists
411        /// so a caller like the authenticated pinned-tier cache-eviction guard (FR-015/
412        /// NFR-004, `crate::cache`) can restrict itself to a genuine 401/403
413        /// credential-rejection signal without also matching a 429 (mere throttling, not a
414        /// credential-revocation signal) that happens to also classify as `RateLimited`.
415        source_status: Option<u16>,
416    },
417
418    /// A package name was not found on the given registry.
419    ///
420    /// `#[non_exhaustive]` on the variant itself (#1854): from outside `deps-core` the
421    /// constructors are [`Self::not_found_locally`] (never vouches for the endpoint) and
422    /// [`crate::not_found_or`] (which yields [`ErrorOrigin::Endpoint`] from a received HTTP
423    /// status). Misuse-resistant, not sealed: an `HttpStatus` literal is still constructible, so
424    /// feeding `not_found_or` a status that was not received would mislabel the origin.
425    #[error("{package} not found on {registry}")]
426    #[non_exhaustive]
427    PackageNotFound {
428        /// Name of the package that was looked up — stored redacted (#1209): the raw value
429        /// is unreachable from this field's type.
430        package: RedactedName,
431        /// Name of the registry that reported the package as missing.
432        registry: &'static str,
433        /// Whether a registry response produced this error or it was decided locally.
434        origin: ErrorOrigin,
435    },
436
437    /// A registry HTTP request returned a non-success status code.
438    #[error("{}", http_status_message(*status, url))]
439    HttpStatus {
440        /// URL that was requested — stored redacted (#789): the raw value is unreachable
441        /// from this field's type.
442        url: RedactedUrl,
443        /// HTTP status code returned.
444        status: u16,
445    },
446
447    /// A registry's response body failed to deserialize as JSON.
448    #[error("failed to parse {registry} response for {package}: {source}")]
449    ApiResponse {
450        /// Name of the package whose response failed to parse — stored redacted (#1209): the
451        /// raw value is unreachable from this field's type.
452        package: RedactedName,
453        /// Name of the registry the response came from.
454        registry: &'static str,
455        /// The underlying JSON deserialization error.
456        #[source]
457        source: serde_json::Error,
458    },
459
460    /// A response body exceeded the configured size cap and was rejected before full download.
461    #[error("{}", response_too_large_message(url, *limit))]
462    ResponseTooLarge {
463        /// URL the oversized response came from — stored redacted (#789): the raw value is
464        /// unreachable from this field's type.
465        url: RedactedUrl,
466        /// The size cap, in bytes, that was exceeded.
467        limit: usize,
468    },
469
470    /// A malformed version-requirement string, for any ecosystem.
471    ///
472    /// Previously also carried `deps-go`'s malformed-module-path rejections (#399 deferred
473    /// that split); those now use [`Self::InvalidPackageName`] instead (#1514) — a module path
474    /// is a package identifier, not a version requirement, and consumers that only expect
475    /// version-requirement text (e.g. `GoFormatter::validate_package_name`) previously needed
476    /// a documented `unreachable!()` arm to rule the version-requirement shape back out.
477    #[error("invalid version requirement: {0}")]
478    InvalidVersionReq(String),
479
480    /// A registry request's target package/module name failed a structural validation gate
481    /// (e.g. empty, oversized, or containing a `.`/`..` path segment) — distinct from
482    /// [`Self::InvalidVersionReq`], which is for a malformed version-requirement string, not a
483    /// malformed name. `deps-go`'s `validate_module_path` is the first caller (#1514).
484    ///
485    /// # Examples
486    ///
487    /// ```
488    /// use deps_core::{DepsError, InvalidPackageName};
489    ///
490    /// let err: DepsError = InvalidPackageName::new("module path is empty").into();
491    /// assert!(matches!(err, DepsError::InvalidPackageName(_)));
492    /// ```
493    #[error("invalid package name: {0}")]
494    InvalidPackageName(#[from] InvalidPackageName),
495
496    /// A filesystem I/O operation failed.
497    #[error("I/O error: {0}")]
498    Io(#[from] std::io::Error),
499
500    /// A JSON parsing operation failed outside of a registry response context.
501    #[error("JSON error: {0}")]
502    Json(#[from] serde_json::Error),
503
504    /// The manifest file's ecosystem could not be determined from any registered router.
505    #[error("unsupported ecosystem: {0}")]
506    UnsupportedEcosystem(String),
507
508    /// More than one ecosystem's routing rules matched the same manifest path.
509    #[error("ambiguous ecosystem detection for file: {0}")]
510    AmbiguousEcosystem(String),
511
512    /// A URI supplied by the client or a manifest could not be parsed.
513    #[error("invalid URI: {0}")]
514    InvalidUri(String),
515
516    /// Returned by `deps_core::cache::HttpCache`'s 4 send sites (issue #483) when
517    /// `network.offline` is set, instead of attempting the request. `url` is the request
518    /// that was blocked, for diagnostic/logging purposes.
519    #[error("{}", offline_message(url))]
520    Offline {
521        /// The request URL that was blocked — stored redacted (#789): the raw value is
522        /// unreachable from this field's type.
523        url: RedactedUrl,
524    },
525
526    /// A multi-hop alternate/private-index chain's resolution was halted because a hop
527    /// returned a genuine transport error (5xx, timeout, connection failure) rather than a
528    /// clean "not found" — the chain deliberately does not fall through to a further, less
529    /// trusted hop in this case (`deps_pypi`'s FR-005(c)/NFR-003(3), #513). Carries no
530    /// arbitrary error text — mirrors [`Self::RateLimited`]'s pre-vetted-message precedent
531    /// (see [`Self::fetch_failure`]'s security-load-bearing invariant) — so its
532    /// classification there can safely be [`FetchFailure::Actionable`] with a fixed, safe
533    /// message, surfacing this case in hover/diagnostics instead of only a `tracing::warn!`.
534    #[error(
535        "index chain resolution halted by a transport error on one hop — not falling back \
536         to a less-trusted index"
537    )]
538    ChainResolutionHalted,
539
540    /// A registry's paginated release list (`Link: rel="next"`) could not be followed to its
541    /// end, so what was fetched is discarded rather than reported as the full list.
542    /// Carries no response text, so [`Self::fetch_failure`] can classify it as
543    /// [`FetchFailure::Actionable`] with a fixed message.
544    #[error("{package} on {registry}: {reason}")]
545    PaginatedListIncomplete {
546        /// Package whose release list was paginated — stored redacted (#1209).
547        package: RedactedName,
548        /// Name of the registry that paginated the list.
549        registry: &'static str,
550        /// Why following the pages stopped.
551        reason: PaginationStop,
552    },
553
554    /// The registry host resolved, at connect time, to an address class the active policy
555    /// refuses to connect to (DNS rebinding or a name that points at an internal address).
556    /// Built only by `crate::cache`; carries no address, so [`Self::fetch_failure`] can classify
557    /// it as [`FetchFailure::Actionable`] with a fixed message.
558    #[error("registry host of {url} resolves to a {} address, blocked by network policy", block.class())]
559    #[non_exhaustive]
560    HostBlockedByPolicy {
561        /// The request URL, stored redacted.
562        url: RedactedUrl,
563        /// The blocked resolved address: its class and the rule that refused it.
564        block: BlockedHost,
565    },
566
567    /// A credentialed request targeted a URL outside the credential's trusted prefix, so the
568    /// credential was withheld (it would otherwise travel to a host the caller never trusted
569    /// with it). Built only by `crate::cache`; a configuration fault, so it is
570    /// [`FetchFailure::Actionable`] (with a fixed, URL-free message) and halts a multi-hop chain.
571    #[error("refusing to send a credential to {url} outside its trusted prefix")]
572    #[non_exhaustive]
573    CredentialOutsideTrustedPrefix {
574        /// The request URL, stored redacted.
575        url: RedactedUrl,
576    },
577}
578
579/// Which budget a bounded lookup exceeded ([`DepsError::BudgetExceeded`]).
580///
581/// # Examples
582///
583/// ```
584/// use deps_core::error::LookupBudget;
585///
586/// assert_eq!(
587///     LookupBudget::Time.to_string(),
588///     "registry did not answer within the time budget"
589/// );
590/// ```
591#[derive(Debug, Clone, Copy, PartialEq, Eq)]
592pub enum LookupBudget {
593    /// The registry did not answer within the lookup's time budget.
594    Time,
595    /// The response exceeded the bounded scan the parser allows itself.
596    Scan,
597}
598
599impl std::fmt::Display for LookupBudget {
600    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
601        f.write_str(match self {
602            Self::Time => "registry did not answer within the time budget",
603            Self::Scan => "registry response exceeded the version scan budget",
604        })
605    }
606}
607
608/// Why following a registry's paginated release list stopped before its last page.
609///
610/// # Examples
611///
612/// ```
613/// use deps_core::error::PaginationStop;
614///
615/// assert_eq!(
616///     PaginationStop::PageCap.to_string(),
617///     "registry release list exceeds the page limit"
618/// );
619/// ```
620#[derive(Debug, Clone, Copy, PartialEq, Eq)]
621pub enum PaginationStop {
622    /// The page limit was reached while a `rel="next"` link was still present.
623    PageCap,
624    /// A `rel="next"` link was missing, ambiguous, cyclic, or pointed outside the registry.
625    InvalidNextLink,
626    /// Fetching all pages did not finish within the overall time budget.
627    TimeBudget,
628    /// No complete, consistent release list is available: the registry cannot be asked and no
629    /// earlier full list exists to serve in its place.
630    NoConsistentSnapshot,
631}
632
633impl std::fmt::Display for PaginationStop {
634    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
635        f.write_str(match self {
636            Self::PageCap => "registry release list exceeds the page limit",
637            Self::InvalidNextLink => "registry returned an unusable next-page link",
638            Self::TimeBudget => "registry release list took too long to fetch",
639            Self::NoConsistentSnapshot => "no consistent registry release list is available",
640        })
641    }
642}
643
644/// Hand-written, not derived: originally because a derived `Debug` would have printed
645/// `HttpStatus.url`, `Offline.url`, `ResponseTooLarge.url`, and `RegistryError.package` raw
646/// and unredacted (#767 code-review follow-up) — any `tracing::warn!(?err, ...)`/`{err:?}`
647/// call site, a common and arguably more idiomatic alternative to `%err`, would have bypassed
648/// the hand-written `Display` text entirely and reintroduced the raw URL/query string. Since
649/// #789, those four fields are typed [`RedactedUrl`] directly, so a derived `Debug` would
650/// actually be safe too (each field's own `Debug` already forwards to redacted text) — this
651/// impl is kept hand-written anyway as defense-in-depth against a future field-type
652/// regression, not because it is still load-bearing on its own. Every field is still shown
653/// (this is not a summary).
654impl std::fmt::Debug for DepsError {
655    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
656        match self {
657            Self::ParseError {
658                file_type,
659                kind,
660                source,
661            } => f
662                .debug_struct("ParseError")
663                .field("file_type", file_type)
664                .field("kind", kind)
665                .field("source", source)
666                .finish(),
667            Self::RegistryError { package, source } => f
668                .debug_struct("RegistryError")
669                .field("package", package)
670                .field("source", source)
671                .finish(),
672            Self::InsecureScheme { url } => {
673                f.debug_struct("InsecureScheme").field("url", url).finish()
674            }
675            Self::BudgetExceeded(budget) => f.debug_tuple("BudgetExceeded").field(budget).finish(),
676            Self::RecentlyFailed => f.write_str("RecentlyFailed"),
677            Self::RateLimited {
678                message,
679                verified,
680                source_status,
681            } => f
682                .debug_struct("RateLimited")
683                .field("message", message)
684                .field("verified", verified)
685                .field("source_status", source_status)
686                .finish(),
687            Self::PackageNotFound {
688                package,
689                registry,
690                origin,
691            } => f
692                .debug_struct("PackageNotFound")
693                .field("package", package)
694                .field("registry", registry)
695                .field("origin", origin)
696                .finish(),
697            Self::HttpStatus { url, status } => f
698                .debug_struct("HttpStatus")
699                .field("url", url)
700                .field("status", status)
701                .finish(),
702            Self::ApiResponse {
703                package,
704                registry,
705                source,
706            } => f
707                .debug_struct("ApiResponse")
708                .field("package", package)
709                .field("registry", registry)
710                .field("source", source)
711                .finish(),
712            Self::ResponseTooLarge { url, limit } => f
713                .debug_struct("ResponseTooLarge")
714                .field("url", url)
715                .field("limit", limit)
716                .finish(),
717            Self::InvalidVersionReq(req) => f.debug_tuple("InvalidVersionReq").field(req).finish(),
718            Self::InvalidPackageName(err) => {
719                f.debug_tuple("InvalidPackageName").field(err).finish()
720            }
721            Self::Io(source) => f.debug_tuple("Io").field(source).finish(),
722            Self::Json(source) => f.debug_tuple("Json").field(source).finish(),
723            Self::UnsupportedEcosystem(ecosystem) => f
724                .debug_tuple("UnsupportedEcosystem")
725                .field(ecosystem)
726                .finish(),
727            Self::AmbiguousEcosystem(path) => {
728                f.debug_tuple("AmbiguousEcosystem").field(path).finish()
729            }
730            Self::InvalidUri(uri) => f.debug_tuple("InvalidUri").field(uri).finish(),
731            Self::Offline { url } => f.debug_struct("Offline").field("url", url).finish(),
732            Self::ChainResolutionHalted => f.write_str("ChainResolutionHalted"),
733            Self::PaginatedListIncomplete {
734                package,
735                registry,
736                reason,
737            } => f
738                .debug_struct("PaginatedListIncomplete")
739                .field("package", package)
740                .field("registry", registry)
741                .field("reason", reason)
742                .finish(),
743            Self::HostBlockedByPolicy { url, block } => f
744                .debug_struct("HostBlockedByPolicy")
745                .field("url", url)
746                .field("block", block)
747                .finish(),
748            Self::CredentialOutsideTrustedPrefix { url } => f
749                .debug_struct("CredentialOutsideTrustedPrefix")
750                .field("url", url)
751                .finish(),
752        }
753    }
754}
755
756impl DepsError {
757    /// Constructs a [`Self::RateLimited`] error.
758    ///
759    /// The only way to build this `#[non_exhaustive]` variant from outside this crate (#1295
760    /// critic M1: `#[non_exhaustive]` on the variant blocks a downstream crate's struct
761    /// literal, not just an exhaustive match) — an ecosystem crate with its own rate-limit
762    /// classification distinct from `crate::github`'s (e.g. `deps-gitlab-ci`) uses this
763    /// instead. `message` must be a pre-vetted, IP-free, actionable hint (see the variant's own
764    /// doc); `verified` should be [`RateLimitEvidence::Confirmed`] only when the caller has
765    /// confirmed genuine exhaustion from explicit server evidence, not merely inferred it.
766    ///
767    /// # Examples
768    ///
769    /// ```
770    /// use deps_core::{DepsError, RateLimitEvidence};
771    ///
772    /// let err = DepsError::rate_limited("set MY_TOKEN to increase the limit", RateLimitEvidence::Inferred);
773    /// assert!(matches!(err, DepsError::RateLimited { verified: RateLimitEvidence::Inferred, .. }));
774    /// ```
775    #[must_use]
776    pub fn rate_limited(message: impl Into<String>, verified: RateLimitEvidence) -> Self {
777        Self::RateLimited {
778            message: message.into(),
779            verified,
780            // No live response is available at this generic construction site — only
781            // `crate::cache`'s own confirmed-evidence classification knows a real status
782            // (#1295 critic N1).
783            source_status: None,
784        }
785    }
786
787    /// Constructs a [`Self::ParseError`], routing `source` through
788    /// [`crate::redact::parse_error_source`] so a credential-shaped parser error can never
789    /// reach `Debug`/`Display` unredacted (#1250).
790    ///
791    /// The only way to build this `#[non_exhaustive]` variant from outside this crate —
792    /// mirrors [`Self::rate_limited`]'s precedent exactly.
793    ///
794    /// # Examples
795    ///
796    /// ```
797    /// use deps_core::DepsError;
798    ///
799    /// let err = DepsError::parse_error("Cargo.toml", &"duplicate key: `serde`");
800    /// assert!(matches!(err, DepsError::ParseError { .. }));
801    /// ```
802    #[must_use]
803    pub fn parse_error(file_type: impl Into<String>, source: &dyn std::fmt::Display) -> Self {
804        Self::parse_error_of_kind(file_type, ParseFailureKind::Malformed, source)
805    }
806
807    /// Like [`Self::parse_error`], recording why parsing failed as a [`ParseFailureKind`].
808    ///
809    /// # Examples
810    ///
811    /// ```
812    /// use deps_core::{DepsError, ParseFailureKind};
813    ///
814    /// let err = DepsError::parse_error_of_kind(
815    ///     "Cargo.toml",
816    ///     ParseFailureKind::NestingTooDeep,
817    ///     &"nesting depth 65 exceeds maximum of 64",
818    /// );
819    /// assert_eq!(err.parse_failure_kind(), Some(ParseFailureKind::NestingTooDeep));
820    /// ```
821    #[must_use]
822    pub fn parse_error_of_kind(
823        file_type: impl Into<String>,
824        kind: ParseFailureKind,
825        source: &dyn std::fmt::Display,
826    ) -> Self {
827        Self::ParseError {
828            file_type: file_type.into(),
829            kind,
830            source: crate::redact::parse_error_source(source),
831        }
832    }
833
834    /// The [`ParseFailureKind`] when this is a [`Self::ParseError`], `None` for any other error.
835    #[must_use]
836    pub const fn parse_failure_kind(&self) -> Option<ParseFailureKind> {
837        match self {
838            Self::ParseError { kind, .. } => Some(*kind),
839            _ => None,
840        }
841    }
842
843    /// Constructs a [`Self::PackageNotFound`] decided locally (a rejected name, a missing
844    /// route, an unregistered alternate), which is [`ErrorOrigin::Unattributed`]: it neither
845    /// vouches for the registry endpoint nor accuses it (#1854).
846    ///
847    /// A not-found that a registry actually answered is built only by
848    /// [`crate::not_found_or`], so a remote 404 is the one way to get
849    /// [`ErrorOrigin::Endpoint`].
850    ///
851    /// # Examples
852    ///
853    /// ```
854    /// use deps_core::DepsError;
855    /// use deps_core::error::ErrorOrigin;
856    ///
857    /// let error = DepsError::not_found_locally("left-pad", "npm");
858    /// assert!(error.is_not_found());
859    /// assert_eq!(error.origin(), ErrorOrigin::Unattributed);
860    /// ```
861    #[must_use]
862    pub fn not_found_locally(package: &str, registry: &'static str) -> Self {
863        Self::PackageNotFound {
864            package: package.into(),
865            registry,
866            origin: ErrorOrigin::Unattributed,
867        }
868    }
869
870    /// Constructs a [`Self::PackageNotFound`] from a registry's own not-found response.
871    /// Crate-private so [`ErrorOrigin::Endpoint`] stays reachable only through a response.
872    pub(crate) fn not_found_at_endpoint(package: &str, registry: &'static str) -> Self {
873        Self::PackageNotFound {
874            package: package.into(),
875            registry,
876            origin: ErrorOrigin::Endpoint,
877        }
878    }
879
880    /// Returns `true` when this error means the registry was successfully asked and
881    /// answered "this package doesn't exist", as opposed to the registry not having
882    /// been answerable at all (network failure, timeout, malformed response, 5xx).
883    ///
884    /// Distinguishing the two matters for diagnostics (#267): a genuine not-found is
885    /// evidence the package name is wrong, while any other error is evidence only that
886    /// this particular request failed — reporting the latter as "Unknown package" would
887    /// mislabel a transient registry outage as a nonexistent dependency. Covers
888    /// [`DepsError::PackageNotFound`] (the ecosystems that map a 404 to it explicitly:
889    /// npm, PyPI, Go, Swift) and a bare [`DepsError::HttpStatus`] with `status == 404`
890    /// (the ecosystems that propagate the raw HTTP status instead: Cargo, Maven, Gradle,
891    /// Bundler, Dart, Composer, NuGet).
892    ///
893    /// # Examples
894    ///
895    /// ```
896    /// use deps_core::DepsError;
897    ///
898    /// let not_found = DepsError::not_found_locally("left-pad", "npm");
899    /// assert!(not_found.is_not_found());
900    ///
901    /// let http_404 = DepsError::HttpStatus {
902    ///     url: "https://crates.io/api/v1/crates/left-pad".into(),
903    ///     status: 404,
904    /// };
905    /// assert!(http_404.is_not_found());
906    ///
907    /// let outage = DepsError::HttpStatus {
908    ///     url: "https://crates.io/api/v1/crates/serde".into(),
909    ///     status: 503,
910    /// };
911    /// assert!(!outage.is_not_found());
912    ///
913    /// let skipped = DepsError::RecentlyFailed;
914    /// assert!(!skipped.is_not_found());
915    /// ```
916    #[must_use]
917    pub const fn is_not_found(&self) -> bool {
918        matches!(
919            self,
920            Self::PackageNotFound { .. } | Self::HttpStatus { status: 404, .. }
921        )
922    }
923
924    /// Classifies this error for the per-dependency "registry lookup failed" diagnostic
925    /// (#478), distinguishing a failure with a safe, actionable hint to show the user from
926    /// one whose raw text must never reach a diagnostic.
927    ///
928    /// **Security-load-bearing invariant**: [`FetchFailure::Actionable`] is produced only from
929    /// a fixed, pre-vetted, IP-free message — never by calling `.to_string()`/`Display` on an
930    /// arbitrary `DepsError` to build one, since a raw `HttpStatus` or `RegistryError` body can
931    /// embed the caller's public IP (`github.rs:332-346`, exercised by the `github` crate's
932    /// `test_parse_tags_page_github_rate_limit_returns_error`).
933    ///
934    /// **Exhaustive by design, no wildcard arm** (#1244 — the same bug class already fixed
935    /// twice for `CompletionContext` (#793, #819) and designed against for `EcosystemId`
936    /// (#118)): every current and future [`DepsError`] variant must be listed explicitly, so a
937    /// new variant that should carry [`FetchFailure::Actionable`] guidance cannot silently fall
938    /// through to [`FetchFailure::Transient`] just by being added after this match was written.
939    /// `#[non_exhaustive]` on this enum does not block an exhaustive match here, since this
940    /// method is defined in the same crate that declares the enum.
941    ///
942    /// # Examples
943    ///
944    /// ```
945    /// use deps_core::error::{DepsError, FetchFailure};
946    /// use deps_core::RateLimitEvidence;
947    ///
948    /// let rate_limited = DepsError::rate_limited("set GITHUB_TOKEN", RateLimitEvidence::Confirmed);
949    /// assert_eq!(
950    ///     rate_limited.fetch_failure(),
951    ///     FetchFailure::Actionable("set GITHUB_TOKEN".into())
952    /// );
953    ///
954    /// let other = DepsError::RecentlyFailed;
955    /// assert_eq!(other.fetch_failure(), FetchFailure::Transient);
956    /// ```
957    #[must_use]
958    pub fn fetch_failure(&self) -> FetchFailure {
959        match self {
960            // `verified` does not change the classification: even an unverified rate-limit
961            // guess still carries a safe, actionable hint worth showing (#1295).
962            Self::RateLimited { message, .. } => FetchFailure::Actionable(message.clone()),
963            // Fixed, pre-vetted message — see `Self::ChainResolutionHalted`'s own doc for why
964            // this is safe to build as `Actionable` the same way `RateLimited` is.
965            Self::ChainResolutionHalted => FetchFailure::Actionable(
966                "index unreachable — resolution halted, not falling back to a less-trusted \
967                 index"
968                    .to_string(),
969            ),
970            Self::PaginatedListIncomplete { reason, .. } => {
971                FetchFailure::Actionable(format!("{reason}; not showing a partial list"))
972            }
973            Self::HostBlockedByPolicy { block, .. } => {
974                let class = block.class();
975                FetchFailure::Actionable(match block.policy() {
976                    BlockingPolicy::Floor => format!(
977                        "registry host resolves to a {class} address, which is never a registry \
978                         under any policy"
979                    ),
980                    BlockingPolicy::WorkspaceRegistries(_) => format!(
981                        "registry host resolves to a {class} address, blocked by \
982                         registries.workspace_registries policy{}",
983                        block.hint_suffix()
984                    ),
985                })
986            }
987            Self::InsecureScheme { .. } => {
988                FetchFailure::Actionable("registry URL must use https".to_string())
989            }
990            // A configuration fault that no retry resolves, so it must not read as a transient
991            // lookup failure (and must not let a last-good fallback paper over it). The
992            // message is fixed: the request URL is never interpolated (#1841).
993            Self::CredentialOutsideTrustedPrefix { .. } => FetchFailure::Actionable(
994                "credential withheld: the registry URL is outside the credential's trusted prefix"
995                    .to_string(),
996            ),
997            // Deliberately `Transient`, not `Actionable` (#1295 critic S5, reverted from an
998            // earlier `Actionable` attempt): `lsp_helpers::diagnostics` already suppresses
999            // every per-dependency fetch-failure message while `versions.offline` is set,
1000            // rendering a single file-level notice instead
1001            // (`test_generate_diagnostics_from_cache_offline_suppresses_per_dependency_warning`)
1002            // — an `Actionable` message here would be unreachable in the normal case and would
1003            // reintroduce exactly the per-dependency duplication that test forbids if it ever
1004            // did render (a config-flip race between fetch and render). #1244 only asks for
1005            // exhaustiveness, not a behavior change here.
1006            Self::Offline { .. }
1007            | Self::ParseError { .. }
1008            | Self::RegistryError { .. }
1009            | Self::BudgetExceeded(_)
1010            | Self::RecentlyFailed
1011            | Self::PackageNotFound { .. }
1012            | Self::HttpStatus { .. }
1013            | Self::ApiResponse { .. }
1014            | Self::ResponseTooLarge { .. }
1015            | Self::InvalidVersionReq(_)
1016            | Self::InvalidPackageName(_)
1017            | Self::Io(_)
1018            | Self::Json(_)
1019            | Self::UnsupportedEcosystem(_)
1020            | Self::AmbiguousEcosystem(_)
1021            | Self::InvalidUri(_) => FetchFailure::Transient,
1022        }
1023    }
1024
1025    /// Returns `true` when this error means a request was blocked by `network.offline`
1026    /// (issue #483), as opposed to any other network or registry failure.
1027    ///
1028    /// Used by `deps_maven::registry` to skip poisoning its negative-search-failure
1029    /// cache with an offline block, so toggling `network.offline` back to `false` takes
1030    /// effect immediately instead of being masked by `RECENT_FAILURE_TTL`.
1031    ///
1032    /// # Examples
1033    ///
1034    /// ```
1035    /// use deps_core::DepsError;
1036    ///
1037    /// let offline = DepsError::Offline { url: "https://crates.io/".into() };
1038    /// assert!(offline.is_offline());
1039    ///
1040    /// let other = DepsError::RecentlyFailed;
1041    /// assert!(!other.is_offline());
1042    /// ```
1043    #[must_use]
1044    pub const fn is_offline(&self) -> bool {
1045        matches!(self, Self::Offline { .. })
1046    }
1047
1048    /// Collapses a failed hop of a multi-hop index chain into the error that halts the chain.
1049    ///
1050    /// A [`Self::HostBlockedByPolicy`] is kept as is, so its actionable message survives; every
1051    /// other error becomes [`Self::ChainResolutionHalted`]. Only for non-not-found errors:
1052    /// callers must handle [`Self::is_not_found`] before halting.
1053    ///
1054    /// # Examples
1055    ///
1056    /// ```
1057    /// use deps_core::DepsError;
1058    ///
1059    /// let halted = DepsError::RecentlyFailed.into_chain_halt();
1060    /// assert!(matches!(halted, DepsError::ChainResolutionHalted));
1061    /// ```
1062    #[must_use]
1063    pub fn into_chain_halt(self) -> Self {
1064        match self {
1065            Self::HostBlockedByPolicy { .. } => self,
1066            Self::ParseError { .. }
1067            | Self::RegistryError { .. }
1068            | Self::InsecureScheme { .. }
1069            | Self::BudgetExceeded(_)
1070            | Self::RecentlyFailed
1071            | Self::RateLimited { .. }
1072            | Self::PackageNotFound { .. }
1073            | Self::HttpStatus { .. }
1074            | Self::ApiResponse { .. }
1075            | Self::ResponseTooLarge { .. }
1076            | Self::InvalidVersionReq(_)
1077            | Self::InvalidPackageName(_)
1078            | Self::Io(_)
1079            | Self::Json(_)
1080            | Self::UnsupportedEcosystem(_)
1081            | Self::AmbiguousEcosystem(_)
1082            | Self::InvalidUri(_)
1083            | Self::CredentialOutsideTrustedPrefix { .. }
1084            | Self::Offline { .. }
1085            | Self::ChainResolutionHalted
1086            | Self::PaginatedListIncomplete { .. } => Self::ChainResolutionHalted,
1087        }
1088    }
1089
1090    /// A URL-free summary of this error, safe to attach to a `tracing` field or log line at
1091    /// an outbound-request chokepoint. [`Self::HttpStatus`], [`Self::Offline`],
1092    /// [`Self::ResponseTooLarge`], and [`Self::RegistryError`]'s own `Display` now redact
1093    /// their URL via [`RedactedUrl`] (#767, #789), but this summary deliberately still never
1094    /// derives from `self`'s `Display`/`Debug`: a future variant added here should not be
1095    /// able to reintroduce a leak just by being included in a `{self}` interpolation.
1096    /// [`Self::RegistryError`]'s wrapped [`SanitizedRegistryError`] can no longer re-embed
1097    /// the raw URL through its own `Display` either way, since its only constructor strips
1098    /// it unconditionally.
1099    ///
1100    /// Returns the HTTP status code when this is [`Self::HttpStatus`], plus a coarse,
1101    /// URL-free cause discriminant for every variant — so a routine transport
1102    /// failure/timeout still carries some triage signal instead of collapsing to `status =
1103    /// None` with nothing else.
1104    ///
1105    /// **Exhaustive by design, no wildcard arm** (#1244 — see [`Self::fetch_failure`]'s doc for
1106    /// why): kept in lockstep with that method so the two classifiers cannot silently drift
1107    /// apart on which variants they know about.
1108    #[must_use]
1109    pub(crate) const fn safe_tracing_summary(&self) -> (Option<u16>, &'static str) {
1110        match self {
1111            Self::HttpStatus { status, .. } => (Some(*status), "http-status"),
1112            Self::RegistryError { .. } => (None, "transport"),
1113            Self::InsecureScheme { .. } => (None, "insecure-scheme"),
1114            Self::BudgetExceeded(_) => (None, "budget-exceeded"),
1115            Self::RecentlyFailed => (None, "recently-failed"),
1116            Self::Offline { .. } => (None, "offline"),
1117            Self::ResponseTooLarge { .. } => (None, "response-too-large"),
1118            // Split by `verified` (#1295 critic S2): a human triaging logs can tell a
1119            // confirmed rate limit apart from an unverified guess at this label alone,
1120            // without needing to also inspect the message text.
1121            Self::RateLimited {
1122                verified: RateLimitEvidence::Confirmed,
1123                ..
1124            } => (None, "rate-limited"),
1125            Self::RateLimited {
1126                verified: RateLimitEvidence::Inferred,
1127                ..
1128            } => (None, "rate-limited-unverified"),
1129            Self::ApiResponse { .. } => (None, "api-response"),
1130            Self::PackageNotFound { .. } => (None, "not-found"),
1131            Self::ParseError { .. } => (None, "parse-error"),
1132            Self::InvalidVersionReq(_) => (None, "invalid-version-req"),
1133            Self::InvalidPackageName(_) => (None, "invalid-package-name"),
1134            Self::Io(_) => (None, "io"),
1135            Self::Json(_) => (None, "json"),
1136            Self::UnsupportedEcosystem(_) => (None, "unsupported-ecosystem"),
1137            Self::AmbiguousEcosystem(_) => (None, "ambiguous-ecosystem"),
1138            Self::InvalidUri(_) => (None, "invalid-uri"),
1139            Self::ChainResolutionHalted => (None, "chain-resolution-halted"),
1140            Self::PaginatedListIncomplete { .. } => (None, "paginated-list-incomplete"),
1141            Self::HostBlockedByPolicy { .. } => (None, "host-blocked-by-policy"),
1142            Self::CredentialOutsideTrustedPrefix { .. } => (None, "credential-scope"),
1143        }
1144    }
1145
1146    /// Whether this error is evidence about the registry endpoint that was fetched from.
1147    ///
1148    /// [`Self::RateLimited`] uses `source_status` as a proxy for provenance: a confirmed 429
1149    /// rebuilt without a status (GitLab) reads as [`ErrorOrigin::Unattributed`], which only
1150    /// shifts the verdict toward inconclusive. [`Self::PackageNotFound`] carries its own origin:
1151    /// [`ErrorOrigin::Endpoint`] only when built from a registry response.
1152    ///
1153    /// **Exhaustive by design, no wildcard arm** (#1244 — see [`Self::fetch_failure`]).
1154    ///
1155    /// # Examples
1156    ///
1157    /// ```
1158    /// use deps_core::DepsError;
1159    /// use deps_core::error::ErrorOrigin;
1160    ///
1161    /// let halted = DepsError::ChainResolutionHalted;
1162    /// assert_eq!(halted.origin(), ErrorOrigin::Endpoint);
1163    /// ```
1164    #[must_use]
1165    pub fn origin(&self) -> ErrorOrigin {
1166        match self {
1167            Self::PackageNotFound { origin, .. } => *origin,
1168            Self::HttpStatus { .. }
1169            | Self::ApiResponse { .. }
1170            | Self::ResponseTooLarge { .. }
1171            | Self::ChainResolutionHalted
1172            | Self::RateLimited {
1173                source_status: Some(_),
1174                ..
1175            }
1176            | Self::PaginatedListIncomplete {
1177                reason:
1178                    PaginationStop::PageCap
1179                    | PaginationStop::InvalidNextLink
1180                    | PaginationStop::TimeBudget,
1181                ..
1182            } => ErrorOrigin::Endpoint,
1183            Self::RegistryError { source, .. } => source.origin(),
1184            Self::RateLimited {
1185                source_status: None,
1186                ..
1187            }
1188            | Self::PaginatedListIncomplete {
1189                reason: PaginationStop::NoConsistentSnapshot,
1190                ..
1191            }
1192            | Self::ParseError { .. }
1193            | Self::InsecureScheme { .. }
1194            | Self::BudgetExceeded(_)
1195            | Self::RecentlyFailed
1196            | Self::InvalidVersionReq(_)
1197            | Self::InvalidPackageName(_)
1198            | Self::Io(_)
1199            | Self::Json(_)
1200            | Self::UnsupportedEcosystem(_)
1201            | Self::AmbiguousEcosystem(_)
1202            | Self::InvalidUri(_)
1203            | Self::Offline { .. }
1204            | Self::HostBlockedByPolicy { .. }
1205            | Self::CredentialOutsideTrustedPrefix { .. } => ErrorOrigin::Unattributed,
1206        }
1207    }
1208}
1209
1210/// Outcome of a registry fetch attempt for one dependency, as recorded in
1211/// `DocumentState::signals.outcomes` (`deps-lsp`) and rendered by
1212/// [`crate::lsp_helpers::generate_diagnostics_from_cache`] (#478).
1213///
1214/// Replaces a bare `HashSet<PackageName>` membership check so the per-dependency diagnostic
1215/// can distinguish a failure with a safe, user-actionable hint from an opaque one, without
1216/// ever threading raw, potentially IP-bearing error text into the diagnostic (see
1217/// [`DepsError::fetch_failure`]).
1218#[non_exhaustive]
1219#[derive(Clone, Debug, PartialEq, Eq)]
1220pub enum FetchFailure {
1221    /// The fetch failed with a pre-vetted, safe-to-display hint — produced from
1222    /// [`DepsError::RateLimited`], [`DepsError::ChainResolutionHalted`],
1223    /// [`DepsError::PaginatedListIncomplete`], [`DepsError::HostBlockedByPolicy`] or
1224    /// [`DepsError::CredentialOutsideTrustedPrefix`] (see
1225    /// [`DepsError::fetch_failure`] for the exhaustive, deliberately-chosen list of which
1226    /// variants produce this versus [`Self::Transient`]).
1227    Actionable(String),
1228    /// The fetch failed for a reason with no safe user-facing detail to show — the
1229    /// diagnostic falls back to a generic "lookup failed" message.
1230    Transient,
1231    /// The dependency was never actually queried (e.g. a name/source collision detected
1232    /// before the fetch, see `deps-lsp`'s `dedup_dependencies_by_source`) — renders the
1233    /// same generic "lookup failed" message as [`Self::Transient`], since the absence of
1234    /// an attempt is not evidence the package doesn't exist.
1235    NotAttempted,
1236}
1237
1238impl FetchFailure {
1239    /// Whether a registry request was actually sent and failed.
1240    ///
1241    /// `false` only for [`Self::NotAttempted`] placeholders (forced-refetch resets, collided
1242    /// names), which say nothing about the registry and must not surface for dependencies
1243    /// that already have a lock-file version.
1244    ///
1245    /// # Examples
1246    ///
1247    /// ```
1248    /// use deps_core::error::FetchFailure;
1249    ///
1250    /// assert!(FetchFailure::Transient.was_attempted());
1251    /// assert!(!FetchFailure::NotAttempted.was_attempted());
1252    /// ```
1253    #[must_use]
1254    pub const fn was_attempted(&self) -> bool {
1255        match self {
1256            Self::Actionable(_) | Self::Transient => true,
1257            Self::NotAttempted => false,
1258        }
1259    }
1260}
1261
1262/// Convenience type alias for `Result<T, DepsError>`.
1263///
1264/// This is the standard `Result` type used throughout the deps-lsp codebase.
1265/// It simplifies function signatures by defaulting the error type to `DepsError`.
1266///
1267/// # Examples
1268///
1269/// ```
1270/// use deps_core::error::Result;
1271///
1272/// fn get_version(name: &str) -> Result<String> {
1273///     if name.is_empty() {
1274///         return Err(deps_core::error::DepsError::parse_error("name", &"empty name"));
1275///     }
1276///     Ok("1.0.0".into())
1277/// }
1278/// ```
1279pub type Result<T> = std::result::Result<T, DepsError>;
1280
1281#[cfg(test)]
1282mod tests {
1283    use super::*;
1284    use crate::net_policy::{HostClass, WorkspaceRegistryAccess};
1285    use std::assert_matches;
1286    use std::error::Error as StdError;
1287
1288    #[test]
1289    fn test_error_display() {
1290        let error = DepsError::Io(std::io::Error::other("test error"));
1291        assert_eq!(error.to_string(), "I/O error: test error");
1292    }
1293
1294    /// #789: `SanitizedRegistryError`'s own `Display` must never re-embed the request URL,
1295    /// even when the wrapped `reqwest::Error` genuinely carries one — a builder-only error
1296    /// like `Client::get("not a url").build().unwrap_err()` never populates `.url()`, so this
1297    /// needs a real transport-level failure (connection refused on a closed loopback port) to
1298    /// actually exercise the strip, mirroring `deps_core::cache`'s own
1299    /// `test_registry_error_source_redacts_url_on_real_transport_error`.
1300    #[tokio::test]
1301    async fn test_sanitized_registry_error_strips_url_on_real_transport_error() {
1302        let port = {
1303            let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
1304            listener.local_addr().unwrap().port()
1305        };
1306        let url = format!("http://127.0.0.1:{port}/pkg?token=super-secret-value");
1307
1308        let reqwest_err = reqwest::Client::new().get(&url).send().await.unwrap_err();
1309        assert!(
1310            reqwest_err.url().is_some(),
1311            "test setup invariant: the underlying reqwest::Error must carry a URL"
1312        );
1313
1314        let sanitized: SanitizedRegistryError = reqwest_err.into();
1315        assert!(
1316            !sanitized.to_string().contains("super-secret-value"),
1317            "sanitized: {sanitized}"
1318        );
1319        assert!(
1320            !format!("{sanitized:?}").contains("super-secret-value"),
1321            "sanitized debug: {sanitized:?}"
1322        );
1323    }
1324
1325    /// #789 S2: `SanitizedRegistryError` must treat itself as a leaf node for source-chaining
1326    /// purposes — `reqwest`'s redirect policy can nest a *second* `reqwest::Error` (with its
1327    /// own populated `url` field) as the outer error's `source` (see the type's own docs for
1328    /// the exact `https_only`/redirect code path), which `.without_url()` on the outer error
1329    /// alone does not touch. This proves the wrapper discards a real, populated source chain
1330    /// (not merely that one never existed): the wrapped transport error genuinely has
1331    /// `.source().is_some()` for a real connection-refused failure, yet
1332    /// `SanitizedRegistryError`'s own `source()` is unconditionally `None`.
1333    #[tokio::test]
1334    async fn test_sanitized_registry_error_source_is_always_none() {
1335        let port = {
1336            let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
1337            listener.local_addr().unwrap().port()
1338        };
1339        let url = format!("http://127.0.0.1:{port}/pkg?token=super-secret-value");
1340
1341        let reqwest_err = reqwest::Client::new().get(&url).send().await.unwrap_err();
1342        let sanitized: SanitizedRegistryError = reqwest_err.into();
1343        let Inner::Transport(raw) = &sanitized.0 else {
1344            panic!("a reqwest error converts to the transport case");
1345        };
1346        assert!(
1347            raw.source().is_some(),
1348            "test setup invariant: a connection-refused error must have a populated source chain"
1349        );
1350        assert!(
1351            StdError::source(&sanitized).is_none(),
1352            "SanitizedRegistryError::source() must always be None"
1353        );
1354    }
1355
1356    /// #756 code-review finding: `safe_tracing_summary` must never derive its output from
1357    /// `self`'s own `Display`/`Debug` (both embed the raw, unredacted request URL for several
1358    /// variants) — pinning the exact `(status, cause)` pairs for every variant a `HttpCache`/
1359    /// `OsvClient` call site can actually produce, so a routine transport failure still
1360    /// carries triage signal (`cause`) instead of collapsing to `(None, "other")`.
1361    ///
1362    /// #1295 critic M2: genuinely exhaustive now, matching the method's own no-wildcard-arm
1363    /// match — every `DepsError` variant gets its own assertion, not a handful of spot checks,
1364    /// so a typo'd or missing label can't ship silently.
1365    #[test]
1366    fn test_safe_tracing_summary_covers_every_reachable_variant() {
1367        assert_eq!(
1368            DepsError::HttpStatus {
1369                url: "https://example.com/pkg?token=secret".into(),
1370                status: 503,
1371            }
1372            .safe_tracing_summary(),
1373            (Some(503), "http-status")
1374        );
1375        assert_eq!(
1376            DepsError::RegistryError {
1377                package: "https://example.com/pkg?token=secret".into(),
1378                source: reqwest::Client::new()
1379                    .get("not a url")
1380                    .build()
1381                    .unwrap_err()
1382                    .into(),
1383            }
1384            .safe_tracing_summary(),
1385            (None, "transport")
1386        );
1387        assert_eq!(
1388            DepsError::Offline {
1389                url: "https://example.com/pkg?token=secret".into(),
1390            }
1391            .safe_tracing_summary(),
1392            (None, "offline")
1393        );
1394        assert_eq!(
1395            DepsError::ResponseTooLarge {
1396                url: "https://example.com/pkg?token=secret".into(),
1397                limit: 1024,
1398            }
1399            .safe_tracing_summary(),
1400            (None, "response-too-large")
1401        );
1402        assert_eq!(
1403            DepsError::RateLimited {
1404                message: "set GITHUB_TOKEN".into(),
1405                verified: RateLimitEvidence::Confirmed,
1406                source_status: Some(403),
1407            }
1408            .safe_tracing_summary(),
1409            (None, "rate-limited")
1410        );
1411        assert_eq!(
1412            DepsError::RateLimited {
1413                message: "set GITHUB_TOKEN".into(),
1414                verified: RateLimitEvidence::Inferred,
1415                source_status: None,
1416            }
1417            .safe_tracing_summary(),
1418            (None, "rate-limited-unverified")
1419        );
1420        assert_eq!(
1421            DepsError::ApiResponse {
1422                package: "flask".into(),
1423                registry: "PyPI",
1424                source: serde_json::from_str::<serde_json::Value>("{invalid}").unwrap_err(),
1425            }
1426            .safe_tracing_summary(),
1427            (None, "api-response")
1428        );
1429        assert_eq!(
1430            DepsError::not_found_locally("flask", "PyPI").safe_tracing_summary(),
1431            (None, "not-found")
1432        );
1433        assert_eq!(
1434            DepsError::ParseError {
1435                file_type: "Cargo.toml".into(),
1436                kind: ParseFailureKind::Malformed,
1437                source: Box::new(std::io::Error::new(std::io::ErrorKind::InvalidData, "bad")),
1438            }
1439            .safe_tracing_summary(),
1440            (None, "parse-error")
1441        );
1442        assert_eq!(
1443            DepsError::InvalidVersionReq("bad range".into()).safe_tracing_summary(),
1444            (None, "invalid-version-req")
1445        );
1446        assert_eq!(
1447            DepsError::Io(std::io::Error::new(
1448                std::io::ErrorKind::NotFound,
1449                "not found"
1450            ))
1451            .safe_tracing_summary(),
1452            (None, "io")
1453        );
1454        assert_eq!(
1455            DepsError::Json(serde_json::from_str::<serde_json::Value>("{bad}").unwrap_err())
1456                .safe_tracing_summary(),
1457            (None, "json")
1458        );
1459        assert_eq!(
1460            DepsError::UnsupportedEcosystem("unknown".into()).safe_tracing_summary(),
1461            (None, "unsupported-ecosystem")
1462        );
1463        assert_eq!(
1464            DepsError::AmbiguousEcosystem("file.txt".into()).safe_tracing_summary(),
1465            (None, "ambiguous-ecosystem")
1466        );
1467        assert_eq!(
1468            DepsError::InvalidUri("not a uri".into()).safe_tracing_summary(),
1469            (None, "invalid-uri")
1470        );
1471        assert_eq!(
1472            DepsError::ChainResolutionHalted.safe_tracing_summary(),
1473            (None, "chain-resolution-halted")
1474        );
1475    }
1476
1477    /// A `(status, cause)` pair must never itself carry the URL — the whole point of this
1478    /// method — even when the source error's own `Display` would have.
1479    #[test]
1480    fn test_safe_tracing_summary_output_never_contains_the_url() {
1481        let error = DepsError::HttpStatus {
1482            url: "https://npm.internal/pkg?token=super-secret-value".into(),
1483            status: 503,
1484        };
1485        let (status, cause) = error.safe_tracing_summary();
1486        assert_eq!(status, Some(503));
1487        assert!(!cause.contains("super-secret-value"));
1488        assert!(!cause.contains("npm.internal"));
1489    }
1490
1491    #[test]
1492    fn test_response_too_large() {
1493        let error = DepsError::ResponseTooLarge {
1494            url: "https://example.com/data".into(),
1495            limit: 32 * 1024 * 1024,
1496        };
1497        assert_eq!(
1498            error.to_string(),
1499            "response body for https://example.com/data exceeds 33554432 byte limit"
1500        );
1501    }
1502
1503    /// #767: `HttpStatus`'s `Display` is surfaced verbatim through `window/showMessage`
1504    /// (`deps-lsp`'s fetch-failure toast), so a query-string credential (e.g. an `.npmrc`
1505    /// `?_authToken=...` value after `${VAR}` expansion) must never reach it.
1506    #[test]
1507    fn test_http_status_display_redacts_query_string() {
1508        let error = DepsError::HttpStatus {
1509            url: "https://npm.internal/pkg?_authToken=super-secret-value".into(),
1510            status: 503,
1511        };
1512        let message = error.to_string();
1513        assert!(
1514            !message.contains("super-secret-value"),
1515            "message: {message}"
1516        );
1517        assert_eq!(
1518            message,
1519            "HTTP 503 Service Unavailable for https://npm.internal/pkg"
1520        );
1521    }
1522
1523    /// #767 companion for [`DepsError::RegistryError`], whose `package` field is frequently
1524    /// populated with a raw URL rather than a package name (`deps-core::cache`'s
1525    /// `read_body_capped`/`get_cached_with_headers_via`/`post_json`/`get_cached_bytes`).
1526    #[test]
1527    fn test_registry_error_display_redacts_query_string() {
1528        let error = DepsError::RegistryError {
1529            package: "https://npm.internal/pkg?_authToken=super-secret-value".into(),
1530            source: reqwest::Client::new()
1531                .get("not a url")
1532                .build()
1533                .unwrap_err()
1534                .into(),
1535        };
1536        let message = error.to_string();
1537        assert!(
1538            !message.contains("super-secret-value"),
1539            "message: {message}"
1540        );
1541        assert!(message.starts_with("registry request failed for https://npm.internal/pkg:"));
1542    }
1543
1544    /// #767 M1: `RegistryError::package` is documented as a package name, and an npm-scoped
1545    /// name (leading `@`, no scheme) must never be mangled by the URL redaction meant for
1546    /// call sites that populate this field with a URL instead — reproduced false positive:
1547    /// `url_for_tracing`'s unparseable-URL fallback previously misread `@types/node` as
1548    /// `user@host`-shaped userinfo and rendered `***@types/node`.
1549    #[test]
1550    fn test_registry_error_display_does_not_mangle_scoped_package_name() {
1551        let error = DepsError::RegistryError {
1552            package: "@types/node".into(),
1553            source: reqwest::Client::new()
1554                .get("not a url")
1555                .build()
1556                .unwrap_err()
1557                .into(),
1558        };
1559        let message = error.to_string();
1560        assert!(
1561            message.starts_with("registry request failed for @types/node:"),
1562            "message: {message}"
1563        );
1564    }
1565
1566    /// #767: `Offline`'s `Display` also embeds the blocked request URL — same redaction
1567    /// applies.
1568    #[test]
1569    fn test_offline_display_redacts_query_string() {
1570        let error = DepsError::Offline {
1571            url: "https://npm.internal/pkg?_authToken=super-secret-value".into(),
1572        };
1573        let message = error.to_string();
1574        assert!(
1575            !message.contains("super-secret-value"),
1576            "message: {message}"
1577        );
1578    }
1579
1580    /// #767: `ResponseTooLarge`'s `Display` also embeds the source URL — same redaction
1581    /// applies.
1582    #[test]
1583    fn test_response_too_large_display_redacts_query_string() {
1584        let error = DepsError::ResponseTooLarge {
1585            url: "https://npm.internal/pkg?_authToken=super-secret-value".into(),
1586            limit: 1024,
1587        };
1588        let message = error.to_string();
1589        assert!(
1590            !message.contains("super-secret-value"),
1591            "message: {message}"
1592        );
1593    }
1594
1595    /// Code-review follow-up on #767: `DepsError` derives `Debug` no longer — a derived
1596    /// impl would print `HttpStatus.url`/`Offline.url`/`ResponseTooLarge.url`/
1597    /// `RegistryError.package` raw, so any `tracing::warn!(?err, ...)`/`{err:?}` call site
1598    /// (a common, arguably more idiomatic alternative to `%err`) would bypass every
1599    /// hand-written `Display` redaction above and reintroduce the leak. Covers all four
1600    /// URL-shaped variants via `{:?}`.
1601    #[test]
1602    fn test_debug_redacts_query_string_for_every_url_bearing_variant() {
1603        let credential_bearing = [
1604            DepsError::HttpStatus {
1605                url: "https://npm.internal/pkg?_authToken=super-secret-value".into(),
1606                status: 503,
1607            },
1608            DepsError::Offline {
1609                url: "https://npm.internal/pkg?_authToken=super-secret-value".into(),
1610            },
1611            DepsError::ResponseTooLarge {
1612                url: "https://npm.internal/pkg?_authToken=super-secret-value".into(),
1613                limit: 1024,
1614            },
1615            DepsError::RegistryError {
1616                package: "https://npm.internal/pkg?_authToken=super-secret-value".into(),
1617                source: reqwest::Client::new()
1618                    .get("not a url")
1619                    .build()
1620                    .unwrap_err()
1621                    .into(),
1622            },
1623        ];
1624        for error in credential_bearing {
1625            let debug = format!("{error:?}");
1626            assert!(
1627                !debug.contains("super-secret-value"),
1628                "Debug leaked the credential for {error}: {debug}"
1629            );
1630        }
1631    }
1632
1633    /// #789 S1 regression: destructuring `HttpStatus.url` directly (bypassing `Display`/
1634    /// `Debug` entirely) must still yield only redacted text — the field's type itself
1635    /// (`RedactedUrl`, not `String`) is what makes this true, not any redaction step at the
1636    /// access site. There is no way to get the raw string back out even via direct field
1637    /// access, because nothing raw was ever stored in the field to begin with.
1638    #[test]
1639    fn test_http_status_url_field_is_redacted_even_via_direct_destructure() {
1640        let error = DepsError::HttpStatus {
1641            url: RedactedUrl::new("https://npm.internal/pkg?_authToken=super-secret-value"),
1642            status: 401,
1643        };
1644        let DepsError::HttpStatus { url, .. } = error else {
1645            unreachable!()
1646        };
1647        assert_eq!(url.to_string(), "https://npm.internal/pkg");
1648        assert!(!url.to_string().contains("super-secret-value"));
1649    }
1650
1651    /// `Debug` must still show every field for the ordinary, non-URL-bearing variants —
1652    /// this is a redaction fix, not a summary, so field values unrelated to a URL must
1653    /// come through unchanged.
1654    #[test]
1655    fn test_debug_still_shows_non_url_fields() {
1656        let error = DepsError::not_found_locally("left-pad", "npm");
1657        let debug = format!("{error:?}");
1658        assert!(debug.contains("left-pad"), "debug: {debug}");
1659        assert!(debug.contains("npm"), "debug: {debug}");
1660    }
1661
1662    #[test]
1663    fn test_invalid_version_req() {
1664        let error = DepsError::InvalidVersionReq("invalid".into());
1665        assert_eq!(error.to_string(), "invalid version requirement: invalid");
1666    }
1667
1668    #[test]
1669    fn test_parse_error() {
1670        let io_err = std::io::Error::new(std::io::ErrorKind::InvalidData, "bad data");
1671        let error = DepsError::ParseError {
1672            file_type: "Cargo.toml".into(),
1673            kind: ParseFailureKind::Malformed,
1674            source: Box::new(io_err),
1675        };
1676        assert!(error.to_string().contains("failed to parse Cargo.toml"));
1677    }
1678
1679    #[test]
1680    fn test_io_error_conversion() {
1681        let io_err = std::io::Error::new(std::io::ErrorKind::NotFound, "file not found");
1682        let error: DepsError = io_err.into();
1683        assert!(error.to_string().contains("I/O error"));
1684    }
1685
1686    #[test]
1687    fn test_unsupported_ecosystem() {
1688        let error = DepsError::UnsupportedEcosystem("unknown".into());
1689        assert_eq!(error.to_string(), "unsupported ecosystem: unknown");
1690    }
1691
1692    #[test]
1693    fn test_ambiguous_ecosystem() {
1694        let error = DepsError::AmbiguousEcosystem("file.txt".into());
1695        assert_eq!(
1696            error.to_string(),
1697            "ambiguous ecosystem detection for file: file.txt"
1698        );
1699    }
1700
1701    #[test]
1702    fn test_invalid_uri() {
1703        let error = DepsError::InvalidUri("http://example.com".into());
1704        assert_eq!(error.to_string(), "invalid URI: http://example.com");
1705    }
1706
1707    #[test]
1708    fn test_offline_error_display_and_predicate() {
1709        let error = DepsError::Offline {
1710            url: "https://crates.io/api/v1/crates/serde".into(),
1711        };
1712        assert!(error.to_string().contains("offline"));
1713        assert!(error.is_offline());
1714        assert!(!error.is_not_found());
1715
1716        let other = DepsError::Io(std::io::Error::other("boom"));
1717        assert!(!other.is_offline());
1718    }
1719
1720    #[test]
1721    fn test_package_not_found() {
1722        let error = DepsError::not_found_locally("flask", "PyPI");
1723        assert_eq!(error.to_string(), "flask not found on PyPI");
1724    }
1725
1726    /// #1209: `PackageNotFound.package` is redacted at construction (via [`RedactedName`]),
1727    /// so a credential embedded in a manifest's name-shaped field (e.g. Maven property
1728    /// interpolation producing `group:artifact:secret@host`) must never reach this variant's
1729    /// `Display`/`Debug` — the sink a server log or an LSP client toast (`window/showMessage`)
1730    /// reads verbatim.
1731    #[test]
1732    fn test_package_not_found_display_redacts_credential_shaped_name() {
1733        let error = DepsError::not_found_locally(
1734            "com.example:deploy:AUDITSENTINEL0000@git.internal.corp",
1735            "Maven Central",
1736        );
1737        assert!(
1738            !error.to_string().contains("AUDITSENTINEL0000"),
1739            "Display leaked a credential-shaped package name: {error}"
1740        );
1741        assert!(
1742            !format!("{error:?}").contains("AUDITSENTINEL0000"),
1743            "Debug leaked a credential-shaped package name: {error:?}"
1744        );
1745        assert!(error.to_string().contains("git.internal.corp"));
1746    }
1747
1748    /// Same sink, `ApiResponse` variant (#1209).
1749    #[test]
1750    fn test_api_response_display_redacts_credential_shaped_name() {
1751        let json_err = serde_json::from_str::<serde_json::Value>("{invalid}").unwrap_err();
1752        let error = DepsError::ApiResponse {
1753            package: "com.example:deploy:AUDITSENTINEL0000@git.internal.corp".into(),
1754            registry: "Maven Central",
1755            source: json_err,
1756        };
1757        assert!(
1758            !error.to_string().contains("AUDITSENTINEL0000"),
1759            "Display leaked a credential-shaped package name: {error}"
1760        );
1761        assert!(
1762            !format!("{error:?}").contains("AUDITSENTINEL0000"),
1763            "Debug leaked a credential-shaped package name: {error:?}"
1764        );
1765    }
1766
1767    #[test]
1768    fn test_http_status_with_known_reason() {
1769        let error = DepsError::HttpStatus {
1770            url: "https://example.com/data".into(),
1771            status: 404,
1772        };
1773        assert_eq!(
1774            error.to_string(),
1775            "HTTP 404 Not Found for https://example.com/data"
1776        );
1777    }
1778
1779    #[test]
1780    fn test_http_status_with_unknown_code() {
1781        let error = DepsError::HttpStatus {
1782            url: "https://example.com/data".into(),
1783            status: 599,
1784        };
1785        assert_eq!(error.to_string(), "HTTP 599 for https://example.com/data");
1786    }
1787
1788    #[test]
1789    fn test_api_response_error() {
1790        let json_err = serde_json::from_str::<serde_json::Value>("{invalid}").unwrap_err();
1791        let error = DepsError::ApiResponse {
1792            package: "flask".into(),
1793            registry: "PyPI",
1794            source: json_err,
1795        };
1796        assert!(
1797            error
1798                .to_string()
1799                .starts_with("failed to parse PyPI response for flask:")
1800        );
1801    }
1802
1803    #[test]
1804    fn paginated_list_incomplete_is_actionable_with_fixed_message() {
1805        let incomplete = |reason| DepsError::PaginatedListIncomplete {
1806            package: "acme.networking".into(),
1807            registry: "Swift package registry",
1808            reason,
1809        };
1810        assert_eq!(
1811            incomplete(PaginationStop::PageCap).fetch_failure(),
1812            FetchFailure::Actionable(
1813                "registry release list exceeds the page limit; not showing a partial list".into()
1814            )
1815        );
1816        let err = incomplete(PaginationStop::InvalidNextLink);
1817        assert_eq!(
1818            err.fetch_failure(),
1819            FetchFailure::Actionable(
1820                "registry returned an unusable next-page link; not showing a partial list".into()
1821            )
1822        );
1823        assert_eq!(
1824            err.safe_tracing_summary(),
1825            (None, "paginated-list-incomplete")
1826        );
1827    }
1828
1829    #[test]
1830    fn typed_variants_that_replaced_cache_error_classify_per_variant() {
1831        let insecure = DepsError::InsecureScheme {
1832            url: "http://example.com/pkg?token=secret".into(),
1833        };
1834        assert_eq!(
1835            insecure.fetch_failure(),
1836            FetchFailure::Actionable("registry URL must use https".into())
1837        );
1838        assert_eq!(insecure.origin(), ErrorOrigin::Unattributed);
1839        assert_eq!(insecure.safe_tracing_summary(), (None, "insecure-scheme"));
1840        assert_matches!(insecure.into_chain_halt(), DepsError::ChainResolutionHalted);
1841
1842        let transient = [
1843            (
1844                DepsError::BudgetExceeded(LookupBudget::Time),
1845                "budget-exceeded",
1846            ),
1847            (
1848                DepsError::BudgetExceeded(LookupBudget::Scan),
1849                "budget-exceeded",
1850            ),
1851            (DepsError::RecentlyFailed, "recently-failed"),
1852        ];
1853        for (error, label) in transient {
1854            assert_eq!(error.fetch_failure(), FetchFailure::Transient, "{error:?}");
1855            assert_eq!(error.origin(), ErrorOrigin::Unattributed, "{error:?}");
1856            assert_eq!(error.safe_tracing_summary(), (None, label), "{error:?}");
1857        }
1858    }
1859
1860    #[test]
1861    fn host_blocked_by_policy_message_distinguishes_never_a_registry_from_gated() {
1862        let blocked = |class| DepsError::HostBlockedByPolicy {
1863            url: "https://10.0.0.5.nip.io/api?token=secret".into(),
1864            block: BlockedHost::new(class, WorkspaceRegistryAccess::PublicOnly),
1865        };
1866        assert_eq!(
1867            blocked(HostClass::PrivateV4).fetch_failure(),
1868            FetchFailure::Actionable(format!(
1869                "registry host resolves to a private (RFC1918) address, blocked by \
1870                     registries.workspace_registries policy{}",
1871                BlockedHost::new(HostClass::PrivateV4, WorkspaceRegistryAccess::PublicOnly)
1872                    .hint_suffix()
1873            ))
1874        );
1875        let at_off = DepsError::HostBlockedByPolicy {
1876            url: "https://corp.example/".into(),
1877            block: BlockedHost::new(HostClass::PrivateV4, WorkspaceRegistryAccess::Off),
1878        };
1879        assert!(
1880            !format!("{:?}", at_off.fetch_failure()).contains("DEPS_LSP_PRIVATE_REGISTRY_HOSTS"),
1881            "the allowlist cannot help at level Off"
1882        );
1883        assert_eq!(
1884            blocked(HostClass::Loopback).fetch_failure(),
1885            FetchFailure::Actionable(
1886                "registry host resolves to a loopback address, which is never a registry \
1887                 under any policy"
1888                    .into()
1889            )
1890        );
1891        let err = blocked(HostClass::Cgnat);
1892        assert_eq!(err.safe_tracing_summary(), (None, "host-blocked-by-policy"));
1893        assert!(!err.is_not_found());
1894        assert!(!err.to_string().contains("secret"), "{err}");
1895        assert!(!format!("{err:?}").contains("secret"), "{err:?}");
1896    }
1897
1898    #[test]
1899    fn credential_outside_trusted_prefix_is_actionable_halts_chain_and_redacts_url() {
1900        let err = DepsError::CredentialOutsideTrustedPrefix {
1901            url: "https://elsewhere.test/api?token=secret".into(),
1902        };
1903        assert_eq!(
1904            err.to_string(),
1905            format!(
1906                "refusing to send a credential to {} outside its trusted prefix",
1907                RedactedUrl::new("https://elsewhere.test/api?token=secret")
1908            )
1909        );
1910        let FetchFailure::Actionable(hint) = err.fetch_failure() else {
1911            panic!("a credential outside its trusted prefix is a configuration fault");
1912        };
1913        assert!(
1914            !hint.contains("elsewhere.test") && !hint.contains("secret"),
1915            "{hint}"
1916        );
1917        assert_eq!(err.safe_tracing_summary(), (None, "credential-scope"));
1918        assert!(!err.is_not_found());
1919        assert!(!format!("{err} {err:?}").contains("secret"));
1920        assert_matches!(err.into_chain_halt(), DepsError::ChainResolutionHalted);
1921    }
1922
1923    #[test]
1924    fn into_chain_halt_keeps_policy_block_and_halts_everything_else() {
1925        let blocked = DepsError::HostBlockedByPolicy {
1926            url: "https://corp.example/".into(),
1927            block: BlockedHost::new(HostClass::PrivateV4, WorkspaceRegistryAccess::PublicOnly),
1928        };
1929        assert_matches!(
1930            blocked.into_chain_halt(),
1931            DepsError::HostBlockedByPolicy { .. }
1932        );
1933        assert_matches!(
1934            DepsError::Io(std::io::Error::other("x")).into_chain_halt(),
1935            DepsError::ChainResolutionHalted
1936        );
1937    }
1938
1939    /// Exhaustive companion to the doc-test on [`DepsError::fetch_failure`]: every variant
1940    /// other than [`DepsError::RateLimited`], [`DepsError::ChainResolutionHalted`] and
1941    /// [`DepsError::PaginatedListIncomplete`] must classify as [`FetchFailure::Transient`] — including [`DepsError::Offline`] (#1295
1942    /// critic S5: deliberately *not* `Actionable`, see `fetch_failure`'s own comment on that
1943    /// arm). This is the invariant the doc comment calls security-load-bearing (a future
1944    /// variant wired to `Actionable` by mistake could leak raw, potentially IP-bearing error
1945    /// text into a diagnostic), so it must be a real test enumerating every variant, not just a
1946    /// handful of spot checks. The exempted variants carry no arbitrary payload, only a
1947    /// fixed, pre-vetted message, so each is safe to be an `Actionable`-producing variant (see
1948    /// their own docs, and #513's M2 fix for `ChainResolutionHalted`). A
1949    /// dedicated test above pins `PaginatedListIncomplete`'s fixed messages.
1950    #[test]
1951    fn test_fetch_failure_classifies_every_non_rate_limited_variant_as_transient() {
1952        // A `reqwest::Error` built from an invalid URL — `RequestBuilder::build`
1953        // is synchronous and fails on URL parsing alone, so this needs no network
1954        // access or async runtime.
1955        let reqwest_err = reqwest::Client::new()
1956            .get("not a valid url")
1957            .build()
1958            .unwrap_err();
1959        let json_err = serde_json::from_str::<serde_json::Value>("{invalid}").unwrap_err();
1960        let io_err = std::io::Error::new(std::io::ErrorKind::NotFound, "not found");
1961
1962        let non_rate_limited = [
1963            DepsError::ParseError {
1964                file_type: "Cargo.toml".into(),
1965                kind: ParseFailureKind::Malformed,
1966                source: Box::new(std::io::Error::new(std::io::ErrorKind::InvalidData, "bad")),
1967            },
1968            DepsError::RegistryError {
1969                package: "flask".into(),
1970                source: reqwest_err.into(),
1971            },
1972            DepsError::Io(std::io::Error::other("connection reset")),
1973            DepsError::not_found_locally("flask", "PyPI"),
1974            DepsError::HttpStatus {
1975                url: "https://example.com".into(),
1976                status: 500,
1977            },
1978            DepsError::ApiResponse {
1979                package: "flask".into(),
1980                registry: "PyPI",
1981                source: json_err,
1982            },
1983            DepsError::ResponseTooLarge {
1984                url: "https://example.com".into(),
1985                limit: 1024,
1986            },
1987            DepsError::InvalidVersionReq("bad range".into()),
1988            DepsError::Io(io_err),
1989            DepsError::Json(serde_json::from_str::<serde_json::Value>("{bad}").unwrap_err()),
1990            DepsError::UnsupportedEcosystem("unknown".into()),
1991            DepsError::AmbiguousEcosystem("file.txt".into()),
1992            DepsError::InvalidUri("not a uri".into()),
1993            DepsError::Offline {
1994                url: "https://example.com".into(),
1995            },
1996        ];
1997
1998        for error in non_rate_limited {
1999            assert_eq!(
2000                error.fetch_failure(),
2001                FetchFailure::Transient,
2002                "expected Transient for {error:?}"
2003            );
2004        }
2005
2006        for verified in [RateLimitEvidence::Confirmed, RateLimitEvidence::Inferred] {
2007            let rate_limited = DepsError::RateLimited {
2008                message: "set GITHUB_TOKEN to increase the rate limit".into(),
2009                verified,
2010                source_status: None,
2011            };
2012            assert_eq!(
2013                rate_limited.fetch_failure(),
2014                FetchFailure::Actionable("set GITHUB_TOKEN to increase the rate limit".into()),
2015                "verified={verified:?}"
2016            );
2017        }
2018
2019        assert_eq!(
2020            DepsError::ChainResolutionHalted.fetch_failure(),
2021            FetchFailure::Actionable(
2022                "index unreachable — resolution halted, not falling back to a less-trusted \
2023                 index"
2024                    .to_string()
2025            )
2026        );
2027    }
2028
2029    #[test]
2030    fn origin_table() {
2031        let endpoint = [
2032            DepsError::HttpStatus {
2033                url: "https://r.example/x".into(),
2034                status: 500,
2035            },
2036            DepsError::ResponseTooLarge {
2037                url: "https://r.example/x".into(),
2038                limit: 1,
2039            },
2040            DepsError::ChainResolutionHalted,
2041            DepsError::PaginatedListIncomplete {
2042                package: "p".into(),
2043                registry: "gitlab",
2044                reason: PaginationStop::PageCap,
2045            },
2046            DepsError::RateLimited {
2047                message: "m".into(),
2048                verified: RateLimitEvidence::Confirmed,
2049                source_status: Some(429),
2050            },
2051            crate::not_found_or(
2052                DepsError::HttpStatus {
2053                    url: "https://r.example/x".into(),
2054                    status: 404,
2055                },
2056                "p",
2057                "npm",
2058                &[],
2059            ),
2060        ];
2061        for error in endpoint {
2062            assert_eq!(error.origin(), ErrorOrigin::Endpoint, "{error:?}");
2063        }
2064
2065        let unattributed = [
2066            DepsError::Io(std::io::Error::other("x")),
2067            DepsError::not_found_locally("p", "npm"),
2068            DepsError::PaginatedListIncomplete {
2069                package: "p".into(),
2070                registry: "gitlab",
2071                reason: PaginationStop::NoConsistentSnapshot,
2072            },
2073            DepsError::rate_limited("m", RateLimitEvidence::Confirmed),
2074            DepsError::Offline {
2075                url: "https://r.example/x".into(),
2076            },
2077        ];
2078        for error in unattributed {
2079            assert_eq!(error.origin(), ErrorOrigin::Unattributed, "{error:?}");
2080        }
2081    }
2082
2083    /// Every `DepsError` variant has a declared origin, so a new variant's class is a decision
2084    /// made here and not a default.
2085    #[test]
2086    fn origin_of_every_remaining_variant() {
2087        let api = serde_json::from_str::<serde_json::Value>("{bad}").unwrap_err();
2088        let endpoint = [
2089            DepsError::ApiResponse {
2090                package: "p".into(),
2091                registry: "npm",
2092                source: api,
2093            },
2094            DepsError::PaginatedListIncomplete {
2095                package: "p".into(),
2096                registry: "gitlab",
2097                reason: PaginationStop::InvalidNextLink,
2098            },
2099            DepsError::PaginatedListIncomplete {
2100                package: "p".into(),
2101                registry: "gitlab",
2102                reason: PaginationStop::TimeBudget,
2103            },
2104        ];
2105        for error in endpoint {
2106            assert_eq!(error.origin(), ErrorOrigin::Endpoint, "{error:?}");
2107        }
2108
2109        let unattributed = [
2110            DepsError::parse_error("Cargo.toml", &"bad"),
2111            DepsError::Io(std::io::Error::other("io")),
2112            DepsError::Json(serde_json::from_str::<serde_json::Value>("{bad}").unwrap_err()),
2113            DepsError::InvalidVersionReq("bad".into()),
2114            DepsError::InvalidPackageName(InvalidPackageName::new("bad")),
2115            DepsError::UnsupportedEcosystem("x".into()),
2116            DepsError::AmbiguousEcosystem("x".into()),
2117            DepsError::InvalidUri("x".into()),
2118            DepsError::HostBlockedByPolicy {
2119                url: "https://r.example/".into(),
2120                block: BlockedHost::new(HostClass::PrivateV4, WorkspaceRegistryAccess::PublicOnly),
2121            },
2122            DepsError::CredentialOutsideTrustedPrefix {
2123                url: "https://r.example/".into(),
2124            },
2125        ];
2126        for error in unattributed {
2127            assert_eq!(error.origin(), ErrorOrigin::Unattributed, "{error:?}");
2128        }
2129    }
2130
2131    #[tokio::test]
2132    async fn a_transport_error_that_is_not_a_builder_error_is_endpoint() {
2133        let port = {
2134            let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
2135            listener.local_addr().unwrap().port()
2136        };
2137        let url = format!("http://127.0.0.1:{port}/pkg");
2138        let refused = reqwest::Client::new().get(&url).send().await.unwrap_err();
2139        let error = DepsError::RegistryError {
2140            package: url.as_str().into(),
2141            source: refused.into(),
2142        };
2143
2144        assert_eq!(error.origin(), ErrorOrigin::Endpoint);
2145    }
2146
2147    #[test]
2148    fn registry_error_origin_follows_the_sanitized_cause() {
2149        let builder = reqwest::Client::new().get("not a url").build().unwrap_err();
2150        assert_eq!(
2151            SanitizedRegistryError::from(builder).origin(),
2152            ErrorOrigin::Unattributed
2153        );
2154        assert_eq!(
2155            SanitizedRegistryError::from(ResolutionFailure::LookupFailed).origin(),
2156            ErrorOrigin::Unattributed
2157        );
2158    }
2159}