Skip to main content

deps_core/cache/
fetch.rs

1//! Cached, pinned, workspace, and transport-only fetch paths of `HttpCache`.
2
3use super::CacheTier;
4use super::HttpCache;
5use super::MAX_CACHE_BYTES;
6use super::MAX_CACHE_ENTRIES;
7use super::auth::KeyAuth;
8use super::auth::RateLimitRevocation;
9use super::auth::RequestAuth;
10use super::auth::RequestHeader;
11use super::auth::WireHeader;
12use super::auth::accept_headers;
13use super::auth::apply_request_headers;
14use super::auth::wire_accept_headers;
15use super::auth::wire_headers;
16use super::body::BodyLimit;
17use super::body::read_body_capped;
18use super::errors::http_status_error;
19use super::errors::send_error;
20use super::guard::{SchemeRule, ensure_https, ensure_scheme};
21use super::response::CachedResponse;
22use super::response::CredentialPartition;
23use super::response::ResponseValidators;
24use super::response::RevalidationFailure;
25use super::transport::Transport;
26use crate::endpoint_contact::{BodyNote, RequestNote, note_request};
27use crate::error::{DepsError, Result};
28use crate::net_policy::TrustedPrefix;
29use crate::rate_limit::QuotaMeter;
30use crate::redact::RedactedUrl;
31use bytes::Bytes;
32use reqwest::{RequestBuilder, Response, StatusCode, header};
33use serde::Serialize;
34use std::sync::Arc;
35use std::sync::atomic::Ordering;
36
37/// Sends `request`, recording the arrival of the response headers on `note` for the interactive
38/// fetch gate's breaker evidence (see [`crate::endpoint_contact`]). The returned [`BodyNote`]
39/// must follow the body: [`read_body_capped`], or [`BodyNote::finished`] when none is read.
40async fn send_noted(
41    request: RequestBuilder,
42    url: &str,
43    note: RequestNote,
44) -> Result<(Response, BodyNote)> {
45    let response = request.send().await.map_err(|e| send_error(url, e))?;
46    Ok((response, note.headers()))
47}
48
49/// What a cached read does with the live responses it receives: how a confirmed rate limit
50/// counts against the credential, which meter their quota headers feed, and how large a body
51/// may be.
52#[derive(Debug, Clone, Copy)]
53pub(super) struct LivePolicy<'a> {
54    pub(super) rate_limit: RateLimitRevocation,
55    pub(super) quota: Option<&'a Arc<QuotaMeter>>,
56    pub(super) limit: BodyLimit,
57}
58
59impl Default for LivePolicy<'_> {
60    fn default() -> Self {
61        Self {
62            rate_limit: RateLimitRevocation::default(),
63            quota: None,
64            limit: BodyLimit::DEFAULT,
65        }
66    }
67}
68
69impl<'a> LivePolicy<'a> {
70    pub(super) fn of(auth: &RequestAuth<'a>, limit: BodyLimit) -> Self {
71        Self {
72            rate_limit: auth.rate_limit(),
73            quota: auth.quota(),
74            limit,
75        }
76    }
77}
78
79/// Feeds `quota` from `response`, which was just received over the network.
80///
81/// The only place a [`QuotaMeter`] is written: a cache entry or a replayed header never reaches
82/// it. A 5xx carries no trustworthy quota and is skipped.
83fn observe_live_quota(quota: Option<&Arc<QuotaMeter>>, response: &Response) {
84    if let Some(meter) = quota
85        && !response.status().is_server_error()
86    {
87        meter.observe_headers(response.headers());
88    }
89}
90
91impl HttpCache {
92    /// Tells the policy a request is about to leave over a guarded transport, so the startup
93    /// proxy notice is shown only to setups that actually connect directly.
94    fn note_guarded(&self, transport: &Transport) {
95        match transport.tier() {
96            CacheTier::Baseline => {}
97            CacheTier::WorkspaceDeclared(_) | CacheTier::Pinned { .. } => {
98                self.policy.note_guarded_request();
99            }
100        }
101    }
102
103    /// The prefix marking a workspace-tier cache key, chosen as a control character that can
104    /// never appear at the start of a URL string this module writes: production code paths
105    /// only ever write keys derived from this function, which are either the bare URL (starting
106    /// `https://`, or — test cfgs only — `http://` on loopback) or this prefix followed by a
107    /// policy digit. No in-process caller other than [`Self::insert_for_bench`] (a
108    /// `#[doc(hidden)]` test/bench helper that accepts a caller-chosen key) can write an
109    /// arbitrary key, so a `Baseline`-tier and `WorkspaceDeclared`-tier entry can never collide
110    /// in production use.
111    pub(super) const WS_KEY_PREFIX: char = '\u{1}';
112
113    /// The prefix marking a [`CacheTier::Pinned`]-tier cache key (issue #561/#562) — distinct
114    /// from [`Self::WS_KEY_PREFIX`] so the two namespaces can never collide, chosen as another
115    /// control character no URL string this module writes can start with.
116    pub(super) const PINNED_KEY_PREFIX: char = '\u{2}';
117
118    /// The prefix marking a [`CacheTier::Baseline`] key partitioned by a caller-supplied
119    /// `auth_id`, followed by that id as 16 fixed-width hex digits and then the URL. Distinct
120    /// from [`Self::WS_KEY_PREFIX`] and [`Self::PINNED_KEY_PREFIX`], so it can collide with
121    /// neither them nor a bare-URL key.
122    pub(super) const BASELINE_AUTH_KEY_PREFIX: char = '\u{3}';
123
124    /// Retrieves data from URL with intelligent caching.
125    ///
126    /// On first request, fetches data from the network and caches it.
127    /// On subsequent requests, performs a conditional GET request using
128    /// cached ETag or Last-Modified headers. If the server responds with
129    /// 304 Not Modified, returns the cached data. Otherwise, fetches and
130    /// caches the new data.
131    ///
132    /// If the conditional request fails due to network errors, falls back
133    /// to the cached data (stale-while-revalidate pattern).
134    ///
135    /// # Returns
136    ///
137    /// Returns `Bytes` containing the response body. Multiple calls for the
138    /// same URL return cheap clones (reference counting) without copying data.
139    ///
140    /// # Errors
141    ///
142    /// Returns `DepsError::RegistryError` if the initial fetch fails and no
143    /// cached data exists, `DepsError::HttpStatus` if the server returns a
144    /// non-2xx status on that initial fetch, or `DepsError::ResponseTooLarge`
145    /// if the response body exceeds the configured size cap.
146    ///
147    /// # Examples
148    ///
149    /// ```no_run
150    /// # use deps_core::cache::HttpCache;
151    /// # async fn example() -> deps_core::error::Result<()> {
152    /// let cache = HttpCache::new();
153    /// let data = cache.get_cached("https://example.com/api/data").await?;
154    /// println!("Fetched {} bytes", data.len());
155    /// # Ok(())
156    /// # }
157    /// ```
158    pub async fn get_cached(&self, url: &str) -> Result<Bytes> {
159        self.get_cached_with_headers(url, &[]).await
160    }
161
162    /// Returns the cached body for `url` without making any network request.
163    ///
164    /// Unlike `get_cached`'s own stale-while-revalidate fallback (the `Err` arm of
165    /// `conditional_request_with_headers`'s match in `get_cached_via`), this
166    /// is reachable even when a caller wraps `get_cached` in a short outer timeout: a
167    /// hung conditional request that never resolves within that timeout gets its whole
168    /// future cancelled, so `get_cached`'s internal fallback logic never runs and the
169    /// caller sees a timeout instead of stale data. A caller in that position can call
170    /// this instead — a synchronous map lookup, no I/O — to serve the last known-good
171    /// body itself. Returns `None` if `url` has never been successfully cached.
172    ///
173    /// The returned body carries no age bound: this bypasses `get_cached`'s own
174    /// freshness/revalidation logic entirely, so a caller that surfaces this body to
175    /// the user (e.g. inserting it into a manifest edit) should treat it as
176    /// arbitrarily stale, not just-expired.
177    ///
178    /// Reads the baseline (unprefixed) cache-key namespace only (see `Self::cache_key`, private) — a
179    /// body fetched via [`Self::get_cached_workspace`] is never visible through this method.
180    #[must_use]
181    pub fn peek_cached(&self, url: &str) -> Option<Bytes> {
182        self.entries.get(url).map(|r| r.body.clone())
183    }
184
185    /// Fetches a URL with additional request headers, using the cache.
186    ///
187    /// Works the same as `get_cached` but injects extra content-negotiation headers into every
188    /// request. A credential never travels here: see [`Self::get_cached_trusted_origin`].
189    ///
190    /// # Errors
191    ///
192    /// Returns `DepsError::RegistryError` if the initial fetch fails and no
193    /// cached data exists, `DepsError::HttpStatus` if the server returns a
194    /// non-2xx status on that initial fetch, or `DepsError::ResponseTooLarge`
195    /// if the response body exceeds the configured size cap.
196    pub async fn get_cached_with_headers(
197        &self,
198        url: &str,
199        extra_headers: &[RequestHeader],
200    ) -> Result<Bytes> {
201        let headers = wire_headers(extra_headers, &RequestAuth::ANONYMOUS);
202        self.get_cached_via(
203            url,
204            &headers,
205            &self.baseline,
206            KeyAuth::ANONYMOUS,
207            RevalidationFailure::ServeStale,
208            LivePolicy::default(),
209        )
210        .await
211        .map(|response| response.body)
212    }
213
214    /// Like [`Self::get_cached`], but confines every redirect hop to `trusted_origin` via
215    /// [`TrustedPrefix::permits`] (origin equality plus a path-segment-boundary prefix check,
216    /// e.g. against `https://api.nuget.org/v3/registration5-gz/`), and optionally sends a
217    /// credential.
218    ///
219    /// This is the only cached API besides [`Self::get_cached_pinned`] that accepts a credential:
220    /// the transport stops following before a cross-origin hop would ever be sent, so a header
221    /// carrying a token cannot be forwarded to an attacker-controlled host by a hostile
222    /// redirect. `auth` splits the cache by credential state — a credentialed body is stored
223    /// under its own partition and never served to an anonymous request, even after the token
224    /// is removed. `accept` is an optional content-negotiating `Accept` value.
225    ///
226    /// The block only surfaces as an error on a cold cache: like [`Self::get_cached`]'s own
227    /// stale-while-revalidate fallback, a warm entry for `url` still returns the last
228    /// known-good body instead of propagating a blocked-redirect `HttpStatus` from a
229    /// revalidation attempt. A 401/403 on a credentialed revalidation evicts the entry instead.
230    ///
231    /// # Errors
232    ///
233    /// Same as [`Self::get_cached`].
234    ///
235    /// # Examples
236    ///
237    /// ```no_run
238    /// use deps_core::cache::{CredentialHeader, HttpCache, RequestAuth};
239    /// use deps_core::net_policy::TrustedPrefix;
240    /// use deps_core::secret::{Redacted, bearer_auth_header};
241    ///
242    /// # async fn example() -> deps_core::error::Result<()> {
243    /// let cache = HttpCache::new();
244    /// let prefix = TrustedPrefix::parse("https://index.mycorp.dev/").unwrap();
245    /// let token = bearer_auth_header(&Redacted::new("secret-token".to_string()));
246    /// let data = cache
247    ///     .get_cached_trusted_origin(
248    ///         "https://index.mycorp.dev/se/rd/serde",
249    ///         &prefix,
250    ///         RequestAuth::credential(CredentialHeader::Authorization(&token), &prefix),
251    ///         None,
252    ///     )
253    ///     .await?;
254    /// println!("Fetched {} bytes", data.len());
255    /// # Ok(())
256    /// # }
257    /// ```
258    pub async fn get_cached_trusted_origin(
259        &self,
260        url: &str,
261        trusted_origin: &TrustedPrefix,
262        auth: RequestAuth<'_>,
263        accept: Option<&'static str>,
264    ) -> Result<Bytes> {
265        self.get_cached_trusted_origin_response(
266            url,
267            trusted_origin,
268            auth,
269            accept,
270            RevalidationFailure::ServeStale,
271        )
272        .await
273        .map(|response| response.body)
274    }
275
276    /// Like [`Self::get_cached_trusted_origin`], but returns the whole [`CachedResponse`] (body
277    /// plus `ETag`, `Last-Modified` and `Link`) instead of the body alone. For a caller that
278    /// must inspect response headers, e.g. to detect a paginated list.
279    ///
280    /// `on_revalidation_failure` decides whether a failed revalidation of a stored entry
281    /// serves that entry or fails the call.
282    ///
283    /// # Errors
284    ///
285    /// Same as [`Self::get_cached_trusted_origin`], plus the revalidation error under
286    /// [`RevalidationFailure::Fail`].
287    pub async fn get_cached_trusted_origin_response(
288        &self,
289        url: &str,
290        trusted_origin: &TrustedPrefix,
291        auth: RequestAuth<'_>,
292        accept: Option<&'static str>,
293        on_revalidation_failure: RevalidationFailure,
294    ) -> Result<CachedResponse> {
295        self.get_cached_trusted_origin_limited(
296            url,
297            trusted_origin,
298            auth,
299            accept,
300            on_revalidation_failure,
301            BodyLimit::DEFAULT,
302        )
303        .await
304    }
305
306    /// Like [`Self::get_cached_trusted_origin_response`], but caps the response body at `limit`
307    /// instead of [`BodyLimit::DEFAULT`], for an endpoint whose legitimate answer is small and
308    /// whose overflow must read as an error (a probe), not as a large cached body.
309    ///
310    /// A body over `limit` fails with [`DepsError::ResponseTooLarge`] and stores nothing.
311    ///
312    /// # Errors
313    ///
314    /// Same as [`Self::get_cached_trusted_origin_response`], plus
315    /// [`DepsError::ResponseTooLarge`] past `limit`.
316    pub async fn get_cached_trusted_origin_limited(
317        &self,
318        url: &str,
319        trusted_origin: &TrustedPrefix,
320        auth: RequestAuth<'_>,
321        accept: Option<&'static str>,
322        on_revalidation_failure: RevalidationFailure,
323        limit: BodyLimit,
324    ) -> Result<CachedResponse> {
325        auth.ensure_within(url, trusted_origin)?;
326        let transport = self.transport_for_origin(trusted_origin);
327        let headers = wire_headers(&accept_headers(accept), &auth);
328        self.get_cached_via(
329            url,
330            &headers,
331            &transport,
332            auth.key_auth(),
333            on_revalidation_failure,
334            LivePolicy::of(&auth, limit),
335        )
336        .await
337    }
338
339    /// Reads the stored entry of a credentialed [`Self::get_cached_trusted_origin`] request
340    /// without sending anything, for a caller that must answer from the cache while it cannot
341    /// obtain the credential (the offline Keychain case).
342    ///
343    /// Never touches the network and never consults the offline switch, so it cannot send an
344    /// unauthenticated request for a credentialed resource whatever the switch says.
345    ///
346    /// # Errors
347    ///
348    /// Returns [`DepsError::Offline`] when nothing is stored under `partition`.
349    pub fn peek_credentialed_trusted_origin(
350        &self,
351        url: &str,
352        partition: CredentialPartition,
353    ) -> Result<CachedResponse> {
354        let key = self.cache_key(url, CacheTier::Baseline, KeyAuth::Credential(partition));
355        self.entries
356            .get(key.as_ref())
357            .map(|entry| entry.clone())
358            .ok_or_else(|| DepsError::Offline {
359                url: RedactedUrl::new(url),
360            })
361    }
362
363    /// Like [`Self::get_cached_trusted_origin`], but for an origin-pinned,
364    /// connect-address-guarded `CacheTier::Pinned` transport (issue #561/#562) instead of the
365    /// baseline-guarded one — the only sanctioned way to send a credential to a
366    /// workspace-declared host. `auth` partitions the cache exactly as it does there.
367    ///
368    /// # Errors
369    ///
370    /// Same as [`Self::get_cached`].
371    pub async fn get_cached_pinned(
372        &self,
373        url: &str,
374        trusted_origin: &TrustedPrefix,
375        auth: RequestAuth<'_>,
376        accept: Option<&'static str>,
377    ) -> Result<Bytes> {
378        self.get_cached_pinned_response(
379            url,
380            trusted_origin,
381            auth,
382            accept,
383            RevalidationFailure::ServeStale,
384        )
385        .await
386        .map(|response| response.body)
387    }
388
389    /// Like [`Self::get_cached_pinned`], but returns the whole [`CachedResponse`] (body plus
390    /// `ETag`, `Last-Modified` and `Link`) instead of the body alone.
391    ///
392    /// `on_revalidation_failure` decides whether a failed revalidation of a stored entry
393    /// serves that entry or fails the call.
394    ///
395    /// # Errors
396    ///
397    /// Same as [`Self::get_cached`], plus the revalidation error under
398    /// [`RevalidationFailure::Fail`].
399    pub async fn get_cached_pinned_response(
400        &self,
401        url: &str,
402        trusted_origin: &TrustedPrefix,
403        auth: RequestAuth<'_>,
404        accept: Option<&'static str>,
405        on_revalidation_failure: RevalidationFailure,
406    ) -> Result<CachedResponse> {
407        self.get_cached_pinned_limited(
408            url,
409            trusted_origin,
410            auth,
411            accept,
412            on_revalidation_failure,
413            BodyLimit::DEFAULT,
414        )
415        .await
416    }
417
418    /// Like [`Self::get_cached_pinned_response`], but caps the response body at `limit`, the
419    /// pinned-tier counterpart of [`Self::get_cached_trusted_origin_limited`].
420    ///
421    /// # Errors
422    ///
423    /// Same as [`Self::get_cached_pinned_response`], plus [`DepsError::ResponseTooLarge`] past
424    /// `limit`.
425    pub async fn get_cached_pinned_limited(
426        &self,
427        url: &str,
428        trusted_origin: &TrustedPrefix,
429        auth: RequestAuth<'_>,
430        accept: Option<&'static str>,
431        on_revalidation_failure: RevalidationFailure,
432        limit: BodyLimit,
433    ) -> Result<CachedResponse> {
434        auth.ensure_within(url, trusted_origin)?;
435        let transport = self.transport_for_pinned(trusted_origin);
436        let headers = wire_headers(&accept_headers(accept), &auth);
437        self.get_cached_via(
438            url,
439            &headers,
440            &transport,
441            auth.key_auth(),
442            on_revalidation_failure,
443            LivePolicy::of(&auth, limit),
444        )
445        .await
446    }
447
448    /// Like [`Self::get_cached`], but for Cargo's workspace-declared-registry requests: routes
449    /// through the workspace transport field, whose guard enforces the live
450    /// [`crate::net_policy::WorkspaceRegistryAccess`] policy on both the resolved connect-time
451    /// address (issue #455) and any redirect hop, and keys the entry under a
452    /// policy-scoped namespace (see `Self::cache_key`, private) distinct from every other method on
453    /// this cache.
454    ///
455    /// This gives the *resolved address* the same policy scrutiny `deps_cargo::config::RegistryIndex::declared`
456    /// already gives the declared URL string at parse time — it does **not**
457    /// re-check the initial request URL itself: a caller passing an IP-literal `url` whose
458    /// class the policy would reject connects anyway, since `hyper-util`'s connector parses an
459    /// IP literal directly and never calls the configured resolver (see
460    /// `BlockedAddrResolver`'s docs, private). `RegistryIndex::declared` is the sole, by-design gate for
461    /// that residual — every caller of this method already went through it.
462    ///
463    /// If an entry is already cached, a revalidation failure — including a guard rejection
464    /// from a since-rebound or since-tightened-policy address — falls back to serving the
465    /// cached body, logging only a `tracing::warn!` (pre-existing behavior, unrelated to
466    /// this method). This is not a bypass — no new connection to the blocked address is
467    /// made — but it means such a block is invisible to the caller whenever an entry already
468    /// exists for that URL.
469    ///
470    /// # Errors
471    ///
472    /// Same as [`Self::get_cached`].
473    ///
474    /// # Examples
475    ///
476    /// ```no_run
477    /// use deps_core::HttpCache;
478    /// use deps_core::net_policy::RegistryAccessPolicy;
479    /// use std::sync::Arc;
480    ///
481    /// # async fn example() -> deps_core::error::Result<()> {
482    /// let policy = Arc::new(RegistryAccessPolicy::default());
483    /// let cache = HttpCache::with_policy(policy);
484    /// let data = cache
485    ///     .get_cached_workspace("https://index.mycorp.dev/se/rd/serde")
486    ///     .await?;
487    /// println!("Fetched {} bytes", data.len());
488    /// # Ok(())
489    /// # }
490    /// ```
491    pub async fn get_cached_workspace(&self, url: &str) -> Result<Bytes> {
492        self.get_cached_workspace_with_headers(url, &[]).await
493    }
494
495    /// Like [`Self::get_cached_workspace`], but additionally forwards `extra_headers` to the
496    /// underlying request — the headered form needed by a registry client whose
497    /// workspace-declared fetch requires a non-default header (e.g. `deps-npm`'s abbreviated-
498    /// packument `Accept` header for an alternate npm registry).
499    ///
500    /// # Security
501    ///
502    /// `extra_headers` are attached to the **initial** request only. The workspace transport
503    /// pins by [`crate::net_policy::HostClass`], not origin — unlike
504    /// [`Self::get_cached_trusted_origin`], which exists precisely to close this
505    /// gap for a caller that needs it — so a cross-origin redirect hop to any other
506    /// policy-permitted host is followed with `extra_headers` re-sent by reqwest's default
507    /// redirect policy. **This method must never carry a credential.** Harmless for its
508    /// current sole caller (a fixed `Accept` header), but directly load-bearing for any
509    /// future auth-wiring work: reach for [`Self::get_cached_trusted_origin`]
510    /// instead if a header ever needs to stay pinned to one origin.
511    ///
512    /// # Errors
513    ///
514    /// Same as [`Self::get_cached`].
515    pub async fn get_cached_workspace_with_headers(
516        &self,
517        url: &str,
518        extra_headers: &[RequestHeader],
519    ) -> Result<Bytes> {
520        #[expect(
521            clippy::expect_used,
522            reason = "poisoned only if another thread already panicked holding the lock — \
523                      propagate via panic, matching RwLock's poisoning contract"
524        )]
525        let transport = self
526            .workspace
527            .read()
528            .expect("workspace transport lock poisoned")
529            .clone();
530        self.get_cached_via(
531            url,
532            &wire_accept_headers(extra_headers),
533            &transport,
534            KeyAuth::ANONYMOUS,
535            RevalidationFailure::ServeStale,
536            LivePolicy::default(),
537        )
538        .await
539        .map(|response| response.body)
540    }
541
542    /// The credential state in `auth` is meaningful only under [`CacheTier::Pinned`] and
543    /// [`CacheTier::Baseline`] — every other tier ignores it (see [`Self::cache_key`]'s docs).
544    #[tracing::instrument(
545        name = "get_cached_via",
546        skip(self, extra_headers, transport, auth, on_revalidation_failure, policy),
547        fields(url = %RedactedUrl::new(url), cache = tracing::field::Empty)
548    )]
549    pub(super) async fn get_cached_via(
550        &self,
551        url: &str,
552        extra_headers: &[WireHeader<'_>],
553        transport: &Transport,
554        auth: KeyAuth,
555        on_revalidation_failure: RevalidationFailure,
556        policy: LivePolicy<'_>,
557    ) -> Result<CachedResponse> {
558        if self.entries.len() >= MAX_CACHE_ENTRIES
559            || self.total_bytes.load(Ordering::Relaxed) >= MAX_CACHE_BYTES
560        {
561            self.evict_entries();
562        }
563
564        let offline = self.is_offline();
565        // `offline` forces `cache_enabled` true (S1 fix): otherwise `cache.enabled: false`
566        // would leave nothing to serve offline for a URL fetched while caching was disabled.
567        // See `Self::set_offline`'s docs.
568        let cache_enabled = self.cache_enabled.load(Ordering::Relaxed) || offline;
569
570        // Computed once and threaded through every call — recomputing mid-request could read
571        // and write under different keys (see `Self::cache_key`'s docs).
572        let cache_key = self.cache_key(url, transport.tier(), auth);
573
574        if !cache_enabled {
575            // Explicit, not `Empty`: an empty `cache` field would be indistinguishable from
576            // broken instrumentation (#756 S3) on a path that's neither a hit nor a miss.
577            tracing::Span::current().record("cache", "disabled");
578            return self
579                .transport_only_response_via(
580                    url,
581                    extra_headers,
582                    policy.limit,
583                    transport,
584                    policy.quota,
585                    SchemeRule::HttpsOnly,
586                )
587                .await;
588        }
589
590        // Clone+drop the Ref immediately: holding it across `.await` can deadlock a concurrent
591        // task needing write access to the same shard.
592        if let Some(cached) = self.entries.get(cache_key.as_ref()).map(|r| r.clone()) {
593            if offline {
594                // Skips the conditional-request attempt: `ensure_online` would block it and
595                // fall back to this same body anyway, just with a spurious warn + wasted
596                // allocation. The only branch below that is a genuine zero-network "hit"
597                // (#756 S3); every other branch still issued a request.
598                tracing::Span::current().record("cache", "hit");
599                return Ok(cached);
600            }
601            match self
602                .conditional_request_with_headers(
603                    url,
604                    &cached,
605                    extra_headers,
606                    transport,
607                    &cache_key,
608                    policy,
609                )
610                .await
611            {
612                // 304: a round trip happened but no body was re-transferred — distinct from
613                // `hit` (no request) and `refreshed` (full re-fetch).
614                Ok(None) => {
615                    tracing::Span::current().record("cache", "revalidated");
616                    return Ok(cached);
617                }
618                // Stale entry cost a full re-fetch, same as a miss — must not report as a hit.
619                Ok(Some(refreshed)) => {
620                    tracing::Span::current().record("cache", "refreshed");
621                    return Ok(refreshed);
622                }
623                Err(e) => {
624                    debug_assert!(
625                        !matches!(
626                            &e,
627                            DepsError::RateLimited {
628                                source_status: None,
629                                ..
630                            }
631                        ),
632                        "a RateLimited reaching this eviction guard must always carry \
633                         source_status — only http_status_error's confirmed-evidence branch \
634                         produces RateLimited here; None would silently bypass FR-015/NFR-004 \
635                         eviction on a genuine 401/403 credential-revocation signal"
636                    );
637                    // FR-015/NFR-004: a 401/403 revalidation of a *credentialed* entry
638                    // must evict rather than serve the possibly-revoked
639                    // credential's last-known-good body — an anonymous request keeps the
640                    // stale-while-revalidate fallback unchanged.
641                    //
642                    // On a pinned tier, `RateLimited { source_status: Some(401 | 403), .. }`
643                    // evicts too (see `RateLimitRevocation::revokes_credential`)
644                    // (#1295 critic C1): `e` is always this match's own
645                    // `conditional_request_with_headers`'s `Err`, whose only source of that
646                    // variant is `http_status_error`'s confirmed-evidence branch — without this
647                    // arm, a confirmed-evidence 403 would silently bypass eviction and keep
648                    // serving the possibly-revoked credential's stale body. Deliberately
649                    // narrowed to `source_status` 401/403 only, not a bare `RateLimited { .. }`
650                    // (critic N1 regression fix): `confirmed_rate_limit_exhaustion` also
651                    // classifies a 429 this way, but a 429 is mere throttling, not a
652                    // credential-revocation signal — NFR-004's scope is "401/403", and evicting
653                    // on 429 would drop a still-good cached body the client can no longer
654                    // re-fetch until the throttle clears, purely because of a signal unrelated
655                    // to the credential's validity.
656                    if auth.is_credentialed() && policy.rate_limit.revokes_credential(&e) {
657                        if let Some((_, old)) = self.entries.remove(cache_key.as_ref()) {
658                            self.total_bytes
659                                .fetch_sub(old.body.len(), Ordering::Relaxed);
660                        }
661                        tracing::Span::current().record("cache", "evicted");
662                        // #756 round 2 S1: never interpolate `e` — its `Display`/`Debug` embed
663                        // the raw unredacted `url`, defeating this span's `RedactedUrl` field.
664                        // `safe_tracing_summary` extracts only the safe status+cause instead.
665                        let (status, cause) = e.safe_tracing_summary();
666                        tracing::warn!(
667                            status = ?status,
668                            cause,
669                            "evicting authenticated cache entry after revalidation failure"
670                        );
671                        return Err(e);
672                    }
673                    if on_revalidation_failure == RevalidationFailure::Fail {
674                        tracing::Span::current().record("cache", "revalidation-failed");
675                        return Err(e);
676                    }
677                    tracing::Span::current().record("cache", "stale-fallback");
678                    // Same rationale as above: no `e` interpolation.
679                    let (status, cause) = e.safe_tracing_summary();
680                    tracing::warn!(
681                        status = ?status,
682                        cause,
683                        "conditional request failed, using cache"
684                    );
685                    return Ok(cached);
686                }
687            }
688        }
689
690        tracing::Span::current().record("cache", "miss");
691        self.fetch_and_store_with_headers(url, extra_headers, transport, &cache_key, policy)
692            .await
693    }
694
695    /// Performs conditional HTTP request using cached validation headers.
696    ///
697    /// Sends `If-None-Match` (ETag) and/or `If-Modified-Since` headers
698    /// to check if the cached content is still valid.
699    ///
700    /// # Returns
701    ///
702    /// - `Ok(Some(CachedResponse))` - Server returned 200 OK with new content
703    /// - `Ok(None)` - Server returned 304 Not Modified (cache is valid)
704    /// - `Err(_)` - Network or HTTP error occurred
705    async fn conditional_request_with_headers(
706        &self,
707        url: &str,
708        cached: &CachedResponse,
709        extra_headers: &[WireHeader<'_>],
710        transport: &Transport,
711        cache_key: &str,
712        policy: LivePolicy<'_>,
713    ) -> Result<Option<CachedResponse>> {
714        self.ensure_online(url)?;
715        ensure_https(url)?;
716        let note = note_request();
717        self.note_guarded(transport);
718        transport.preflight(url).await?;
719        let mut request = apply_request_headers(transport.client().get(url), extra_headers);
720        if let Some(etag) = &cached.etag {
721            request = request.header(header::IF_NONE_MATCH, etag);
722        }
723        if let Some(last_modified) = &cached.last_modified {
724            request = request.header(header::IF_MODIFIED_SINCE, last_modified);
725        }
726
727        let (response, body_note) = send_noted(request, url, note).await?;
728        observe_live_quota(policy.quota, &response);
729
730        if response.status() == StatusCode::NOT_MODIFIED {
731            body_note.finished();
732            return Ok(None);
733        }
734
735        if !response.status().is_success() {
736            body_note.finished();
737            return Err(http_status_error(
738                url,
739                response.status(),
740                response.headers(),
741            ));
742        }
743
744        let validators = ResponseValidators::from_headers(response.headers());
745        let body = read_body_capped(url, response, policy.limit, body_note).await?;
746        let fresh = validators.into_response(body);
747        self.store_entry(cache_key.to_string(), fresh.clone());
748
749        Ok(Some(fresh))
750    }
751
752    /// Fetches a fresh response from the network and stores it in the cache.
753    ///
754    /// This method bypasses the cache and always makes a network request.
755    /// The response is stored with its ETag and Last-Modified headers for
756    /// future conditional requests.
757    ///
758    /// # Errors
759    ///
760    /// Returns `DepsError::HttpStatus` if the server returns a non-2xx status code
761    /// (or `DepsError::RateLimited` when that status is a 403 with confirmed
762    /// `X-RateLimit-Remaining: 0` evidence — see [`http_status_error`], #1295),
763    /// `DepsError::RegistryError` if the network request fails, or
764    /// `DepsError::ResponseTooLarge` if the response body exceeds the
765    /// configured size cap.
766    pub(super) async fn fetch_and_store_with_headers(
767        &self,
768        url: &str,
769        extra_headers: &[WireHeader<'_>],
770        transport: &Transport,
771        cache_key: &str,
772        policy: LivePolicy<'_>,
773    ) -> Result<CachedResponse> {
774        self.ensure_online(url)?;
775        ensure_https(url)?;
776        let note = note_request();
777        self.note_guarded(transport);
778        transport.preflight(url).await?;
779        // #756 security follow-up (S-A): `RedactedUrl`, not the raw `url` — this is the
780        // direct callee of the now-hardened `get_cached_via`, and at `debug`
781        // level, which is this project's own continuous-improvement convention
782        // (`RUST_LOG=debug`).
783        tracing::debug!(
784            extra_headers = extra_headers.len(),
785            "fetching fresh: {}",
786            RedactedUrl::new(url)
787        );
788
789        let request = apply_request_headers(transport.client().get(url), extra_headers);
790
791        let (response, body_note) = send_noted(request, url, note).await?;
792        observe_live_quota(policy.quota, &response);
793
794        if !response.status().is_success() {
795            body_note.finished();
796            return Err(http_status_error(
797                url,
798                response.status(),
799                response.headers(),
800            ));
801        }
802
803        let validators = ResponseValidators::from_headers(response.headers());
804        let body = read_body_capped(url, response, policy.limit, body_note).await?;
805        let fresh = validators.into_response(body);
806        self.store_entry(cache_key.to_string(), fresh.clone());
807
808        Ok(fresh)
809    }
810
811    /// POSTs `body` as JSON and returns the response body.
812    ///
813    /// Deliberately does not cache: the OSV batch endpoint is a POST with a
814    /// request-body-dependent response and sends no `ETag`/`Last-Modified`
815    /// validators, so entry-map caching would be meaningless here — every
816    /// call reuses the client, HTTPS enforcement, size cap, and timeout
817    /// (via `read_body_capped`) without touching the entry map or
818    /// [`Self::total_bytes`].
819    ///
820    /// # Errors
821    ///
822    /// Returns `DepsError::HttpStatus` if the server returns a non-2xx
823    /// status, `DepsError::RegistryError` if the request fails, or
824    /// `DepsError::ResponseTooLarge` if the response body exceeds the
825    /// configured size cap.
826    pub async fn post_json<T: Serialize + Sync + ?Sized>(
827        &self,
828        url: &str,
829        body: &T,
830    ) -> Result<Bytes> {
831        self.post_json_via(
832            url,
833            body,
834            BodyLimit::DEFAULT,
835            &self.baseline,
836            SchemeRule::HttpsOnly,
837        )
838        .await
839    }
840
841    /// Same as [`Self::post_json`], but additionally takes an explicit [`BodyLimit`]
842    /// (rather than the hardcoded [`BodyLimit::DEFAULT`]) and confines every redirect hop to
843    /// `trusted_origin` via [`crate::net_policy::is_trusted_prefix`] — the same guarantee
844    /// [`Self::get_transport_only_with_headers_limited_trusted_origin`] gives the GET path.
845    ///
846    /// [`Self::post_json`] itself has neither of these: it sends through
847    /// `Self::baseline`'s client (the generic, non-origin-pinned redirect policy) and
848    /// always caps the response at [`BodyLimit::DEFAULT`] (32 MiB) regardless of how much
849    /// smaller a caller's own payloads actually are — a gap for a caller (deps.dev's GOSSIP
850    /// batch endpoint) whose response is expected to be a few KB and whose request body
851    /// carries every declared dependency's name, where an unconfined redirect is a bigger
852    /// concern than for `post_json`'s existing callers.
853    ///
854    /// # Errors
855    ///
856    /// Same as [`Self::post_json`].
857    pub async fn post_json_limited_trusted_origin<T: Serialize + Sync + ?Sized>(
858        &self,
859        url: &str,
860        body: &T,
861        limit: BodyLimit,
862        trusted_origin: &TrustedPrefix,
863    ) -> Result<Bytes> {
864        let transport = self.transport_for_origin(trusted_origin);
865        self.post_json_via(url, body, limit, &transport, SchemeRule::HttpsOnly)
866            .await
867    }
868
869    /// Shared POST body for [`Self::post_json`] and [`Self::post_json_limited_trusted_origin`]
870    /// — mirrors [`Self::transport_only_via`]'s role on the GET path exactly: both public POST
871    /// methods differ only in which `client` (origin-pinned or not) and [`BodyLimit`] they pass
872    /// in, so this is the single place that sends the request, checks the status, and reads the
873    /// capped body.
874    ///
875    /// # Errors
876    ///
877    /// Same as [`Self::post_json`].
878    #[tracing::instrument(
879        skip(self, body, transport),
880        fields(url = %RedactedUrl::new(url))
881    )]
882    async fn post_json_via<T: Serialize + Sync + ?Sized>(
883        &self,
884        url: &str,
885        body: &T,
886        limit: BodyLimit,
887        transport: &Transport,
888        scheme: SchemeRule<'_>,
889    ) -> Result<Bytes> {
890        self.ensure_online(url)?;
891        ensure_scheme(url, scheme)?;
892        let note = note_request();
893        self.note_guarded(transport);
894        transport.preflight(url).await?;
895
896        let (response, body_note) =
897            send_noted(transport.client().post(url).json(body), url, note).await?;
898
899        if !response.status().is_success() {
900            body_note.finished();
901            return Err(http_status_error(
902                url,
903                response.status(),
904                response.headers(),
905            ));
906        }
907
908        read_body_capped(url, response, limit, body_note).await
909    }
910
911    /// [`Self::post_json`] against an operator-selected OSV endpoint: redirect hops are confined
912    /// to `origin`, and plain `http` is accepted only for `origin`'s exact scheme, host and
913    /// port. The waiver lives in this call's arguments, never in the cache.
914    ///
915    /// # Errors
916    ///
917    /// Same as [`Self::post_json`].
918    pub(crate) async fn post_json_operator<T: Serialize + Sync + ?Sized>(
919        &self,
920        url: &str,
921        body: &T,
922        origin: &crate::osv::OperatorOrigin,
923    ) -> Result<Bytes> {
924        let transport = self.transport_for_origin(origin.prefix());
925        self.post_json_via(
926            url,
927            body,
928            BodyLimit::DEFAULT,
929            &transport,
930            SchemeRule::PlainHttpExactOrigin(origin),
931        )
932        .await
933    }
934
935    /// [`Self::get_transport_only`] against an operator-selected OSV endpoint, with the same
936    /// confinement as [`Self::post_json_operator`].
937    ///
938    /// # Errors
939    ///
940    /// Same as [`Self::get_transport_only`].
941    pub(crate) async fn get_transport_only_operator(
942        &self,
943        url: &str,
944        origin: &crate::osv::OperatorOrigin,
945    ) -> Result<Bytes> {
946        let transport = self.transport_for_origin(origin.prefix());
947        self.transport_only_response_via(
948            url,
949            &wire_accept_headers(&[]),
950            BodyLimit::DEFAULT,
951            &transport,
952            None,
953            SchemeRule::PlainHttpExactOrigin(origin),
954        )
955        .await
956        .map(|response| response.body)
957    }
958
959    /// GETs `url` and returns the response body, bypassing the entry-map
960    /// cache entirely — reuses the client, HTTPS enforcement, size cap, and
961    /// timeout, exactly like [`Self::post_json`], but for a plain GET.
962    ///
963    /// For a caller whose own values are already cached elsewhere (e.g.
964    /// `OsvClient`'s record cache, validated by a `modified` timestamp
965    /// rather than `ETag`/`Last-Modified`): reusing [`Self::get_cached`]
966    /// there would double-cache every fetched record in *this* cache's byte
967    /// budget too, competing with registry responses for it even though
968    /// nothing here ever reads that cached copy back.
969    ///
970    /// # Errors
971    ///
972    /// Returns `DepsError::HttpStatus` if the server returns a non-2xx
973    /// status, `DepsError::RegistryError` if the request fails, or
974    /// `DepsError::ResponseTooLarge` if the response body exceeds the
975    /// configured size cap.
976    pub async fn get_transport_only(&self, url: &str) -> Result<Bytes> {
977        self.get_transport_only_with_headers(url, &[]).await
978    }
979
980    /// Same as [`Self::get_transport_only`], but injects extra request headers (e.g. a
981    /// content-negotiating `Accept`) — mirrors how [`Self::get_cached_with_headers`] relates
982    /// to [`Self::get_cached`].
983    ///
984    /// # Errors
985    ///
986    /// Returns `DepsError::HttpStatus` if the server returns a non-2xx
987    /// status, `DepsError::RegistryError` if the request fails, or
988    /// `DepsError::ResponseTooLarge` if the response body exceeds the
989    /// configured size cap.
990    pub async fn get_transport_only_with_headers(
991        &self,
992        url: &str,
993        extra_headers: &[RequestHeader],
994    ) -> Result<Bytes> {
995        self.get_transport_only_with_headers_limited(url, extra_headers, BodyLimit::DEFAULT)
996            .await
997    }
998
999    /// Same as [`Self::get_transport_only_with_headers`], but takes an explicit
1000    /// [`BodyLimit`] instead of the [`BodyLimit::DEFAULT`] (`MAX_RESPONSE_BYTES`) cap.
1001    ///
1002    /// For a caller whose response is legitimately larger than every other registry
1003    /// payload — e.g. `deps-pypi`'s full Simple API project index — without weakening
1004    /// the cap every other caller of this cache relies on. `BodyLimit` clamps at
1005    /// construction, so this can never be widened past `ABSOLUTE_MAX_RESPONSE_BYTES`
1006    /// regardless of what the caller passes in.
1007    ///
1008    /// # Errors
1009    ///
1010    /// Same as [`Self::get_transport_only_with_headers`].
1011    pub async fn get_transport_only_with_headers_limited(
1012        &self,
1013        url: &str,
1014        extra_headers: &[RequestHeader],
1015        limit: BodyLimit,
1016    ) -> Result<Bytes> {
1017        self.transport_only_via(url, extra_headers, limit, &self.baseline)
1018            .await
1019    }
1020
1021    /// Same as [`Self::get_transport_only_with_headers`], but through the workspace-gated
1022    /// transport: every redirect hop is re-classified against the live
1023    /// [`crate::net_policy::RegistryAccessPolicy`], and the body is never entry-cached.
1024    ///
1025    /// For a fetch whose registry was declared by the repository itself (a workspace-declared
1026    /// `.npmrc` registry) and whose payload is too large to hold in the shared cache budget.
1027    ///
1028    /// # Security
1029    ///
1030    /// `extra_headers` are re-sent on a cross-origin redirect hop, as in
1031    /// [`Self::get_cached_workspace_with_headers`]. **This method must never carry a
1032    /// credential.**
1033    ///
1034    /// # Errors
1035    ///
1036    /// Same as [`Self::get_transport_only_with_headers`].
1037    pub async fn get_transport_only_workspace_with_headers(
1038        &self,
1039        url: &str,
1040        extra_headers: &[RequestHeader],
1041    ) -> Result<Bytes> {
1042        #[expect(
1043            clippy::expect_used,
1044            reason = "poisoned only if another thread already panicked holding the lock — \
1045                      propagate via panic, matching RwLock's poisoning contract"
1046        )]
1047        let transport = self
1048            .workspace
1049            .read()
1050            .expect("workspace transport lock poisoned")
1051            .clone();
1052        self.transport_only_via(url, extra_headers, BodyLimit::DEFAULT, &transport)
1053            .await
1054    }
1055
1056    /// Same as [`Self::get_transport_only_with_headers_limited`], but additionally
1057    /// stops any redirect hop that does not match `trusted_origin` via
1058    /// [`crate::net_policy::is_trusted_prefix`]
1059    /// (see [`Self::get_cached_trusted_origin`], which applies the identical policy
1060    /// to the entry-cached path). For a caller carrying a materially larger
1061    /// [`BodyLimit`] than [`BodyLimit::DEFAULT`] — the bigger the budget, the more
1062    /// worth pinning the origin an arbitrary cross-host redirect could point it at.
1063    ///
1064    /// # Errors
1065    ///
1066    /// Same as [`Self::get_transport_only_with_headers_limited`].
1067    pub async fn get_transport_only_with_headers_limited_trusted_origin(
1068        &self,
1069        url: &str,
1070        extra_headers: &[RequestHeader],
1071        limit: BodyLimit,
1072        trusted_origin: &TrustedPrefix,
1073    ) -> Result<Bytes> {
1074        let transport = self.transport_for_origin(trusted_origin);
1075        self.transport_only_via(url, extra_headers, limit, &transport)
1076            .await
1077    }
1078
1079    /// Note: "transport" here means "bypasses the entry-map cache" (see this method's
1080    /// callers' docs) — a different axis from the [`Transport`] type, which pairs a `Client`
1081    /// with its [`CacheTier`]. The name predates that type and is kept as-is to avoid
1082    /// churning every `get_transport_only*` call site for a naming collision that causes no
1083    /// actual ambiguity at the call sites themselves.
1084    #[tracing::instrument(
1085        skip(self, extra_headers, limit, transport),
1086        fields(url = %RedactedUrl::new(url))
1087    )]
1088    async fn transport_only_via(
1089        &self,
1090        url: &str,
1091        extra_headers: &[RequestHeader],
1092        limit: BodyLimit,
1093        transport: &Transport,
1094    ) -> Result<Bytes> {
1095        self.transport_only_response_via(
1096            url,
1097            &wire_accept_headers(extra_headers),
1098            limit,
1099            transport,
1100            None,
1101            SchemeRule::HttpsOnly,
1102        )
1103        .await
1104        .map(|response| response.body)
1105    }
1106
1107    /// [`Self::transport_only_via`] that also keeps the response validators and `Link` header.
1108    async fn transport_only_response_via(
1109        &self,
1110        url: &str,
1111        extra_headers: &[WireHeader<'_>],
1112        limit: BodyLimit,
1113        transport: &Transport,
1114        quota: Option<&Arc<QuotaMeter>>,
1115        scheme: SchemeRule<'_>,
1116    ) -> Result<CachedResponse> {
1117        self.ensure_online(url)?;
1118        ensure_scheme(url, scheme)?;
1119        let note = note_request();
1120        self.note_guarded(transport);
1121        transport.preflight(url).await?;
1122
1123        let request = apply_request_headers(transport.client().get(url), extra_headers);
1124
1125        let (response, body_note) = send_noted(request, url, note).await?;
1126        observe_live_quota(quota, &response);
1127
1128        if !response.status().is_success() {
1129            body_note.finished();
1130            return Err(http_status_error(
1131                url,
1132                response.status(),
1133                response.headers(),
1134            ));
1135        }
1136
1137        let validators = ResponseValidators::from_headers(response.headers());
1138        let body = read_body_capped(url, response, limit, body_note).await?;
1139        Ok(validators.into_response(body))
1140    }
1141}