deps_core/cache/auth.rs
1//! Request credential headers, per-request auth, and the wire-header application path.
2
3use super::response::CredentialPartition;
4use crate::error::{DepsError, Result};
5use crate::net_policy::TrustedPrefix;
6use crate::rate_limit::QuotaMeter;
7use crate::redact::RedactedUrl;
8use crate::secret::{AuthorizationValue, Redacted, auth_digest};
9use reqwest::{Url, header};
10use std::sync::Arc;
11
12/// A non-credential header an [`HttpCache`](crate::cache::HttpCache) request carries.
13///
14/// Every header this workspace sends beyond the conditional-request validators is either a
15/// fixed content-negotiation `Accept` value or a credential. Credentials are not representable
16/// here: they travel as a [`RequestAuth`], which only the origin-confined cached APIs accept.
17///
18/// # Examples
19///
20/// ```
21/// use deps_core::cache::RequestHeader;
22///
23/// let headers = [RequestHeader::Accept("application/json")];
24/// assert_eq!(headers.len(), 1);
25/// ```
26#[derive(Debug, Clone, Copy)]
27pub enum RequestHeader {
28 /// A fixed `Accept` value.
29 Accept(&'static str),
30}
31
32/// The header a credentialed request carries.
33///
34/// Both values are sent marked sensitive. An `Authorization` value is an
35/// [`AuthorizationValue`], which only the shared `Basic`/`Bearer`/verbatim constructors build.
36#[derive(Debug, Clone, Copy)]
37pub enum CredentialHeader<'a> {
38 /// `Authorization`.
39 Authorization(&'a AuthorizationValue),
40 /// GitLab's `PRIVATE-TOKEN`, carrying the raw token.
41 GitlabPrivateToken(&'a Redacted),
42}
43
44impl CredentialHeader<'_> {
45 fn expose_secret(&self) -> &str {
46 match self {
47 Self::Authorization(value) => value.expose_secret(),
48 Self::GitlabPrivateToken(token) => token.expose_secret(),
49 }
50 }
51}
52
53/// Whether a confirmed rate limit (a `401`/`403` with exhausted `X-RateLimit-Remaining`) on a
54/// credentialed revalidation means the credential may be revoked.
55///
56/// A per-source decision made by the caller that owns the credential, not a side effect of the
57/// transport tier.
58///
59/// # Examples
60///
61/// ```
62/// use deps_core::cache::RateLimitRevocation;
63///
64/// assert_eq!(RateLimitRevocation::default(), RateLimitRevocation::Revokes);
65/// ```
66#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
67pub enum RateLimitRevocation {
68 /// Treat it like any other `401`/`403`: evict the entry instead of serving it stale (#1295).
69 #[default]
70 Revokes,
71 /// Treat it as throttling only: the credential is fine, so the entry is served stale. For
72 /// sources whose rate limiter answers `403` (GitHub).
73 Throttles,
74}
75
76impl RateLimitRevocation {
77 /// Whether `error`, from revalidating a credentialed entry, means the credential may be
78 /// revoked, so the entry must be evicted instead of served stale (FR-015/NFR-004).
79 ///
80 /// A plain `401`/`403` always counts. Written without a catch-all so a new [`DepsError`]
81 /// variant must be classified here.
82 pub(super) fn revokes_credential(self, error: &DepsError) -> bool {
83 match error {
84 DepsError::HttpStatus {
85 status: 401 | 403, ..
86 } => true,
87 DepsError::RateLimited {
88 source_status: Some(401 | 403),
89 ..
90 } => match self {
91 Self::Revokes => true,
92 Self::Throttles => false,
93 },
94 DepsError::HttpStatus { .. }
95 | DepsError::RateLimited { .. }
96 | DepsError::ParseError { .. }
97 | DepsError::RegistryError { .. }
98 | DepsError::InsecureScheme { .. }
99 | DepsError::BudgetExceeded(_)
100 | DepsError::RecentlyFailed
101 | DepsError::PackageNotFound { .. }
102 | DepsError::ApiResponse { .. }
103 | DepsError::ResponseTooLarge { .. }
104 | DepsError::InvalidVersionReq(_)
105 | DepsError::InvalidPackageName(_)
106 | DepsError::Io(_)
107 | DepsError::Json(_)
108 | DepsError::UnsupportedEcosystem(_)
109 | DepsError::AmbiguousEcosystem(_)
110 | DepsError::InvalidUri(_)
111 | DepsError::Offline { .. }
112 | DepsError::ChainResolutionHalted
113 | DepsError::PaginatedListIncomplete { .. }
114 | DepsError::CredentialOutsideTrustedPrefix { .. }
115 | DepsError::HostBlockedByPolicy { .. } => false,
116 }
117 }
118}
119
120/// The credential state of one origin-confined cached request.
121///
122/// A credentialed body is always stored under a partition derived from the credential, and an
123/// anonymous request never reads it back, so removing or rotating a token cannot make a later
124/// request see a body fetched under the old one. The cache key carries the variant too, so the
125/// same [`CredentialPartition`] used with a credential and anonymously yields two entries.
126///
127/// # Examples
128///
129/// ```
130/// use deps_core::cache::{CredentialHeader, CredentialPartition, RequestAuth};
131/// use deps_core::net_policy::TrustedPrefix;
132/// use deps_core::secret::{Redacted, bearer_auth_header};
133///
134/// let prefix = TrustedPrefix::parse("https://index.mycorp.dev/").unwrap();
135/// let token = bearer_auth_header(&Redacted::new("secret-token".to_string()));
136/// let auth = RequestAuth::credential(CredentialHeader::Authorization(&token), &prefix);
137/// assert!(!format!("{auth:?}").contains("secret-token"));
138/// let _anonymous = RequestAuth::anonymous(Some(CredentialPartition::new(1)));
139/// ```
140#[derive(Debug, Clone, Copy)]
141pub enum RequestAuth<'a> {
142 /// No credential; `partition` separates cache entries by the caller's credential state.
143 Anonymous {
144 /// The caller's credential-state partition, `None` for the plain per-URL entry.
145 partition: Option<CredentialPartition>,
146 /// The meter fed from the live responses of this request, if any.
147 quota: Option<&'a Arc<QuotaMeter>>,
148 },
149 /// A credential, always cached under its own partition.
150 Credential {
151 /// The header to send.
152 header: CredentialHeader<'a>,
153 /// The partition the response is stored under.
154 partition: CredentialPartition,
155 /// What a confirmed rate limit on revalidation means for this credential.
156 on_rate_limit: RateLimitRevocation,
157 /// The meter fed from the live responses of this request, if any.
158 quota: Option<&'a Arc<QuotaMeter>>,
159 },
160}
161
162impl<'a> RequestAuth<'a> {
163 /// A request with no credential and no partition.
164 pub const ANONYMOUS: Self = Self::anonymous(None);
165
166 /// An anonymous request stored under `partition`.
167 #[must_use]
168 pub const fn anonymous(partition: Option<CredentialPartition>) -> Self {
169 Self::Anonymous {
170 partition,
171 quota: None,
172 }
173 }
174
175 /// A credentialed request whose partition is a salted digest of `prefix` and the secret.
176 #[must_use]
177 pub fn credential(header: CredentialHeader<'a>, prefix: &TrustedPrefix) -> Self {
178 Self::credential_in(
179 header,
180 CredentialPartition::new(auth_digest_of(prefix.as_str(), header.expose_secret())),
181 )
182 }
183
184 /// A credentialed request stored under a caller-chosen `partition`.
185 #[must_use]
186 pub const fn credential_in(
187 header: CredentialHeader<'a>,
188 partition: CredentialPartition,
189 ) -> Self {
190 Self::Credential {
191 header,
192 partition,
193 on_rate_limit: RateLimitRevocation::Revokes,
194 quota: None,
195 }
196 }
197
198 /// Sets what a confirmed rate limit means for this request's credential. No effect on an
199 /// anonymous request.
200 #[must_use]
201 pub const fn with_rate_limit(self, on_rate_limit: RateLimitRevocation) -> Self {
202 match self {
203 Self::Credential {
204 header,
205 partition,
206 quota,
207 ..
208 } => Self::Credential {
209 header,
210 partition,
211 on_rate_limit,
212 quota,
213 },
214 Self::Anonymous { .. } => self,
215 }
216 }
217
218 /// Feeds `meter` from the rate-limit headers of every response this request receives over
219 /// the network, whichever variant it is.
220 ///
221 /// Recording happens inside the fetch layer when a response arrives, never from a stored
222 /// cache entry, so a stale reading cannot be replayed into the meter.
223 #[must_use]
224 pub const fn with_quota_meter(self, meter: &'a Arc<QuotaMeter>) -> Self {
225 match self {
226 Self::Anonymous { partition, .. } => Self::Anonymous {
227 partition,
228 quota: Some(meter),
229 },
230 Self::Credential {
231 header,
232 partition,
233 on_rate_limit,
234 ..
235 } => Self::Credential {
236 header,
237 partition,
238 on_rate_limit,
239 quota: Some(meter),
240 },
241 }
242 }
243
244 pub(super) const fn quota(&self) -> Option<&'a Arc<QuotaMeter>> {
245 match *self {
246 Self::Anonymous { quota, .. } | Self::Credential { quota, .. } => quota,
247 }
248 }
249
250 pub(super) fn key_auth(&self) -> KeyAuth {
251 match *self {
252 Self::Anonymous { partition, .. } => KeyAuth::Anonymous(partition),
253 Self::Credential { partition, .. } => KeyAuth::Credential(partition),
254 }
255 }
256
257 /// Fails closed unless a credentialed request's `url` lies under `prefix`.
258 ///
259 /// The redirect policy confines every hop to `prefix`'s origin, which includes its scheme,
260 /// so a request that starts under an `https` prefix can never be redirected onto plain
261 /// `http` with the credential attached. That only holds when the initial URL is itself
262 /// under the prefix, so the credential is withheld otherwise.
263 pub(super) fn ensure_within(&self, url: &str, prefix: &TrustedPrefix) -> Result<()> {
264 match self {
265 Self::Anonymous { .. } => Ok(()),
266 Self::Credential { .. } => {
267 if Url::parse(url).is_ok_and(|parsed| prefix.permits(&parsed)) {
268 Ok(())
269 } else {
270 Err(DepsError::CredentialOutsideTrustedPrefix {
271 url: RedactedUrl::new(url),
272 })
273 }
274 }
275 }
276 }
277
278 pub(super) fn rate_limit(&self) -> RateLimitRevocation {
279 match *self {
280 Self::Anonymous { .. } => RateLimitRevocation::default(),
281 Self::Credential { on_rate_limit, .. } => on_rate_limit,
282 }
283 }
284}
285
286/// The credential state a cache key is derived from.
287#[derive(Debug, Clone, Copy, PartialEq, Eq)]
288pub(super) enum KeyAuth {
289 Anonymous(Option<CredentialPartition>),
290 Credential(CredentialPartition),
291}
292
293impl KeyAuth {
294 pub(super) const ANONYMOUS: Self = Self::Anonymous(None);
295
296 pub(super) const fn is_credentialed(self) -> bool {
297 matches!(self, Self::Credential(_))
298 }
299}
300
301/// A header as sent on the wire: a fixed `Accept`, or a credential.
302#[derive(Debug, Clone, Copy)]
303pub(super) enum WireHeader<'a> {
304 Accept(&'static str),
305 Credential(CredentialHeader<'a>),
306}
307
308impl From<RequestHeader> for WireHeader<'_> {
309 fn from(header: RequestHeader) -> Self {
310 match header {
311 RequestHeader::Accept(value) => Self::Accept(value),
312 }
313 }
314}
315
316pub(super) fn wire_headers<'a>(
317 accept: &[RequestHeader],
318 auth: &RequestAuth<'a>,
319) -> Vec<WireHeader<'a>> {
320 let mut headers: Vec<WireHeader<'a>> = wire_accept_headers(accept);
321 match auth {
322 RequestAuth::Credential { header, .. } => headers.push(WireHeader::Credential(*header)),
323 RequestAuth::Anonymous { .. } => {}
324 }
325 headers
326}
327
328pub(super) fn wire_accept_headers(accept: &[RequestHeader]) -> Vec<WireHeader<'static>> {
329 accept.iter().copied().map(WireHeader::from).collect()
330}
331
332pub(super) fn accept_headers(accept: Option<&'static str>) -> Vec<RequestHeader> {
333 accept.map(RequestHeader::Accept).into_iter().collect()
334}
335
336fn auth_digest_of(origin: &str, secret: &str) -> u64 {
337 // A `Some` secret always digests; the variant tag in the cache key keeps `0` unambiguous anyway.
338 auth_digest(origin, Some(secret)).unwrap_or_default()
339}
340
341/// Adds `name: secret` to `request`, marked sensitive.
342///
343/// A value that is not a valid header value is passed through raw so
344/// `RequestBuilder::send` fails exactly as it would for any malformed header, with no value
345/// in the error.
346fn sensitive_header(
347 request: reqwest::RequestBuilder,
348 name: header::HeaderName,
349 secret: &str,
350) -> reqwest::RequestBuilder {
351 match header::HeaderValue::from_str(secret) {
352 Ok(mut value) => {
353 value.set_sensitive(true);
354 request.header(name, value)
355 }
356 Err(_) => request.header(name, secret),
357 }
358}
359
360/// Attaches `headers` to `request`, marking every credential value sensitive.
361///
362/// A credential value that is not a valid header value is passed through raw so
363/// `RequestBuilder::send` fails exactly as it would for any malformed header, with no value
364/// in the error.
365pub(super) fn apply_request_headers(
366 mut request: reqwest::RequestBuilder,
367 headers: &[WireHeader<'_>],
368) -> reqwest::RequestBuilder {
369 for header in headers {
370 request = match header {
371 WireHeader::Accept(value) => request.header(header::ACCEPT, *value),
372 WireHeader::Credential(CredentialHeader::Authorization(value)) => {
373 sensitive_header(request, header::AUTHORIZATION, value.expose_secret())
374 }
375 WireHeader::Credential(CredentialHeader::GitlabPrivateToken(token)) => {
376 sensitive_header(
377 request,
378 header::HeaderName::from_static("private-token"),
379 token.expose_secret(),
380 )
381 }
382 };
383 }
384 request
385}