Skip to main content

libtea_client/
transport.rs

1//! HTTP transport with manual redirects, body limits, and credential scoping.
2
3use std::collections::BTreeSet;
4use std::net::SocketAddr;
5use std::sync::atomic::{AtomicU64, Ordering};
6use std::sync::{Arc, Mutex};
7use std::time::{Duration, Instant};
8
9use bytes::Bytes;
10use futures_util::StreamExt;
11use libtea_core::checksum::ContentDecoder;
12use libtea_core::http_cache::{
13    cache_key, parse_retry_after, storage_decision, CacheControl, CacheEntryMeta, NotStored,
14    STORED_HEADERS,
15};
16use libtea_core::{
17    classify_ip, origin_key, parse_api_base, tea_error_code, ApiVersion, ChecksumPolicy,
18    DestinationPolicy, SupportedApi, TeaErrorBody, TokenResponse,
19};
20use reqwest::header::{
21    AUTHORIZATION, CACHE_CONTROL, CONTENT_ENCODING, CONTENT_TYPE, LOCATION, RETRY_AFTER, VARY,
22    WWW_AUTHENTICATE,
23};
24use reqwest::{Method, StatusCode};
25use tokio::sync::Semaphore;
26use url::Url;
27
28use crate::cache::{now_secs, Cache, CacheConfig};
29use crate::error::ClientError;
30
31/// Bounds for untrusted TEA responses.
32///
33/// `#[non_exhaustive]`: start from [`Limits::default`] and use the `with_*`
34/// setters (or assign fields on a default value).
35#[derive(Debug, Clone)]
36#[non_exhaustive]
37pub struct Limits {
38    /// Maximum `.well-known/tea` document size.
39    pub max_discovery_bytes: usize,
40    /// Maximum JSON API response size.
41    pub max_json_bytes: usize,
42    /// Maximum artifact or signature size, before and after content decoding.
43    pub max_artifact_bytes: usize,
44    /// Maximum redirects for one operation.
45    pub max_redirects: usize,
46    /// Overall time for one request that is not an artifact download: the
47    /// response headers and the whole body (discovery, JSON metadata, the token
48    /// exchange). Artifact `GET`s use [`Self::download_timeout`] instead.
49    pub request_timeout: Duration,
50    /// Overall time for one artifact or signature download, body included.
51    /// A transfer that keeps making progress is not cut off by the shorter
52    /// [`Self::request_timeout`]; this is the ceiling for the whole transfer.
53    /// Default 30 minutes.
54    pub download_timeout: Duration,
55    /// Longest the connection may stay silent: the limit on any single wait for
56    /// the next bytes of a response, for every request. A stalled transfer
57    /// fails after this long even if the total time has not run out. Default
58    /// 30 seconds. Must not be zero.
59    pub idle_timeout: Duration,
60    /// TCP connect timeout.
61    pub connect_timeout: Duration,
62    /// Extra attempts for idempotent GET transport failures, HTTP 429 and HTTP 503.
63    pub max_retries: u32,
64    /// Longest `Retry-After` the client will wait out before retrying a `429`
65    /// or `503`. A longer one fails at once with [`ClientError::Throttled`],
66    /// which carries the server's value.
67    pub max_retry_after: Duration,
68    /// Total discovery attempts across the well-known fetch and API candidates.
69    pub max_discovery_attempts: u32,
70    /// Base delay between discovery attempts. Zero disables the delay.
71    pub initial_backoff: Duration,
72    /// Maximum concurrent HTTP operations.
73    pub max_in_flight: usize,
74}
75
76impl Default for Limits {
77    fn default() -> Self {
78        Self {
79            max_discovery_bytes: 1024 * 1024,
80            max_json_bytes: 8 * 1024 * 1024,
81            max_artifact_bytes: 256 * 1024 * 1024,
82            max_redirects: 5,
83            request_timeout: Duration::from_secs(30),
84            download_timeout: Duration::from_secs(30 * 60),
85            idle_timeout: Duration::from_secs(30),
86            connect_timeout: Duration::from_secs(10),
87            max_retries: 2,
88            max_retry_after: Duration::from_secs(30),
89            max_discovery_attempts: 4,
90            initial_backoff: Duration::from_millis(200),
91            max_in_flight: 8,
92        }
93    }
94}
95
96impl Limits {
97    /// Set [`Self::max_discovery_bytes`].
98    #[must_use]
99    pub fn with_max_discovery_bytes(mut self, value: usize) -> Self {
100        self.max_discovery_bytes = value;
101        self
102    }
103
104    /// Set [`Self::max_json_bytes`].
105    #[must_use]
106    pub fn with_max_json_bytes(mut self, value: usize) -> Self {
107        self.max_json_bytes = value;
108        self
109    }
110
111    /// Set [`Self::max_artifact_bytes`].
112    #[must_use]
113    pub fn with_max_artifact_bytes(mut self, value: usize) -> Self {
114        self.max_artifact_bytes = value;
115        self
116    }
117
118    /// Set [`Self::max_redirects`].
119    #[must_use]
120    pub fn with_max_redirects(mut self, value: usize) -> Self {
121        self.max_redirects = value;
122        self
123    }
124
125    /// Set [`Self::request_timeout`].
126    #[must_use]
127    pub fn with_request_timeout(mut self, value: Duration) -> Self {
128        self.request_timeout = value;
129        self
130    }
131
132    /// Set [`Self::download_timeout`].
133    #[must_use]
134    pub fn with_download_timeout(mut self, value: Duration) -> Self {
135        self.download_timeout = value;
136        self
137    }
138
139    /// Set [`Self::idle_timeout`].
140    #[must_use]
141    pub fn with_idle_timeout(mut self, value: Duration) -> Self {
142        self.idle_timeout = value;
143        self
144    }
145
146    /// Set [`Self::connect_timeout`].
147    #[must_use]
148    pub fn with_connect_timeout(mut self, value: Duration) -> Self {
149        self.connect_timeout = value;
150        self
151    }
152
153    /// Set [`Self::max_retries`].
154    #[must_use]
155    pub fn with_max_retries(mut self, value: u32) -> Self {
156        self.max_retries = value;
157        self
158    }
159
160    /// Set [`Self::max_discovery_attempts`].
161    #[must_use]
162    pub fn with_max_discovery_attempts(mut self, value: u32) -> Self {
163        self.max_discovery_attempts = value;
164        self
165    }
166
167    /// Set [`Self::initial_backoff`].
168    #[must_use]
169    pub fn with_initial_backoff(mut self, value: Duration) -> Self {
170        self.initial_backoff = value;
171        self
172    }
173
174    /// Set [`Self::max_retry_after`].
175    #[must_use]
176    pub fn with_max_retry_after(mut self, value: Duration) -> Self {
177        self.max_retry_after = value;
178        self
179    }
180
181    /// Set [`Self::max_in_flight`].
182    #[must_use]
183    pub fn with_max_in_flight(mut self, value: usize) -> Self {
184        self.max_in_flight = value;
185        self
186    }
187}
188
189/// API key identifier and secret. The secret is redacted in `Debug`.
190pub struct ApiKey {
191    id: String,
192    secret: String,
193}
194
195impl ApiKey {
196    /// Build a key pair.
197    #[must_use]
198    pub fn new(id: impl Into<String>, secret: impl Into<String>) -> Self {
199        Self {
200            id: id.into(),
201            secret: secret.into(),
202        }
203    }
204}
205
206impl std::fmt::Debug for ApiKey {
207    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
208        f.debug_struct("ApiKey")
209            .field("id", &self.id)
210            .field("secret", &"<redacted>")
211            .finish()
212    }
213}
214
215#[derive(Clone)]
216struct StoredToken {
217    value: String,
218    expires_at: Option<Instant>,
219}
220
221impl std::fmt::Debug for StoredToken {
222    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
223        f.debug_struct("StoredToken")
224            .field("value", &"<redacted>")
225            .field("expires_at", &self.expires_at)
226            .finish()
227    }
228}
229
230/// Single-flight state for one origin's token exchange.
231#[derive(Default)]
232struct RefreshSlot {
233    /// Number of exchanges for this origin that ran to completion.
234    completed: AtomicU64,
235    /// Failure of the most recent completed exchange, `None` after a success.
236    last_failure: tokio::sync::Mutex<Option<SharedFailure>>,
237}
238
239/// A caller's hold on one origin's [`RefreshSlot`].
240///
241/// Dropping the last lease removes the slot from the map, including when the
242/// holder is cancelled. The map therefore only holds origins with a refresh in
243/// progress or queued, and a stored failure never outlives its burst.
244struct SlotLease<'a> {
245    inner: &'a ClientInner,
246    origin: String,
247    slot: Arc<RefreshSlot>,
248}
249
250impl<'a> SlotLease<'a> {
251    fn acquire(inner: &'a ClientInner, origin: String) -> Self {
252        let mut slots = inner
253            .token_refresh
254            .lock()
255            .unwrap_or_else(|err| err.into_inner());
256        let slot = Arc::clone(slots.entry(origin.clone()).or_default());
257        Self {
258            inner,
259            origin,
260            slot,
261        }
262    }
263}
264
265impl Drop for SlotLease<'_> {
266    fn drop(&mut self) {
267        let mut slots = self
268            .inner
269            .token_refresh
270            .lock()
271            .unwrap_or_else(|err| err.into_inner());
272        // Leases are only cloned under this lock, so the count is exact here:
273        // one reference in the map and one held by this lease.
274        let last = slots
275            .get(&self.origin)
276            .is_some_and(|stored| Arc::ptr_eq(stored, &self.slot))
277            && Arc::strong_count(&self.slot) == 2;
278        if last {
279            slots.remove(&self.origin);
280        }
281    }
282}
283
284/// Cloneable summary of a token exchange failure, handed to queued waiters.
285#[derive(Clone)]
286enum SharedFailure {
287    Timeout,
288    Token(String),
289    Api {
290        status: u16,
291        tea_error: Option<String>,
292    },
293    AuthenticationRequired,
294    Other,
295}
296
297impl SharedFailure {
298    fn from_error(error: &ClientError) -> Self {
299        match error {
300            ClientError::Timeout => Self::Timeout,
301            ClientError::Token { error } => Self::Token(error.clone()),
302            ClientError::Api {
303                status, tea_error, ..
304            } => Self::Api {
305                status: *status,
306                tea_error: tea_error.clone(),
307            },
308            ClientError::AuthenticationRequired => Self::AuthenticationRequired,
309            _ => Self::Other,
310        }
311    }
312
313    fn to_error(&self) -> ClientError {
314        match self {
315            Self::Timeout => ClientError::Timeout,
316            Self::Token(error) => ClientError::Token {
317                error: error.clone(),
318            },
319            Self::Api { status, tea_error } => ClientError::Api {
320                status: *status,
321                tea_error: tea_error.clone(),
322                message: None,
323            },
324            Self::AuthenticationRequired => ClientError::AuthenticationRequired,
325            Self::Other => ClientError::Transport("token exchange failed".into()),
326        }
327    }
328}
329
330pub(crate) struct ClientInner {
331    http: reqwest::Client,
332    pub(crate) limits: Limits,
333    pub(crate) policy: DestinationPolicy,
334    pub(crate) supported: SupportedApi,
335    credentials: Option<ApiKey>,
336    /// Origins this client may send the API key to.
337    credential_origins: Mutex<BTreeSet<String>>,
338    pub(crate) allow_discovered_credentials: bool,
339    pub(crate) checksum_policy: ChecksumPolicy,
340    tokens: Mutex<std::collections::HashMap<String, StoredToken>>,
341    /// Per-origin single-flight gates for `POST /token`.
342    ///
343    /// At most one `POST /token` per origin runs at a time on a given
344    /// [`Client`]; different origins do not wait for each other. Waiters
345    /// re-check the bearer cache under the lock and skip another exchange when
346    /// a usable bearer is already stored. Waiters that queued while an
347    /// exchange for that origin was in flight share its failure instead of
348    /// repeating it. See `docs/auth.md` for the exact bound. An entry exists
349    /// only while a refresh for that origin is running or queued
350    /// ([`SlotLease`] removes it), so origin churn cannot grow the map.
351    /// Ordinary GETs are not held behind these locks.
352    token_refresh: Mutex<std::collections::HashMap<String, Arc<RefreshSlot>>>,
353    semaphore: Arc<Semaphore>,
354    pub(crate) well_known_override: Option<Url>,
355    pub(crate) cache: Option<Arc<Cache>>,
356}
357
358/// TEA consumer client.
359///
360/// Cloning shares the connection pool, token cache, and limits.
361#[derive(Clone)]
362pub struct Client {
363    pub(crate) inner: Arc<ClientInner>,
364}
365
366/// Builder for [`Client`].
367pub struct ClientBuilder {
368    limits: Limits,
369    policy: DestinationPolicy,
370    supported: SupportedApi,
371    credentials: Option<ApiKey>,
372    allow_discovered_credentials: bool,
373    well_known_override: Option<Url>,
374    roots_pem: Vec<u8>,
375    checksum_policy: ChecksumPolicy,
376    ignore_env_proxies: bool,
377    lenient_versions: bool,
378    cache: Option<CacheConfig>,
379    offline: bool,
380}
381
382impl Default for ClientBuilder {
383    fn default() -> Self {
384        Self {
385            limits: Limits::default(),
386            policy: DestinationPolicy::public_https(),
387            supported: SupportedApi::tea_1_0_0(),
388            credentials: None,
389            allow_discovered_credentials: false,
390            well_known_override: None,
391            roots_pem: Vec::new(),
392            checksum_policy: ChecksumPolicy::default(),
393            ignore_env_proxies: false,
394            lenient_versions: false,
395            cache: None,
396            offline: false,
397        }
398    }
399}
400
401impl ClientBuilder {
402    /// Create a builder with production defaults: HTTPS, public addresses, TEA 1.0.0.
403    #[must_use]
404    pub fn new() -> Self {
405        Self::default()
406    }
407
408    /// Keep a persistent response cache in `dir` (*experimental*; off by default).
409    ///
410    /// `GET` responses are stored and revalidated with `ETag` / `Last-Modified`
411    /// conditional requests. The directory is created private (mode 0700, files
412    /// 0600 on Unix); a symbolic link or a directory open to other users makes
413    /// [`ClientBuilder::build`] fail. Responses to requests that carried
414    /// credentials, `Cache-Control: no-store` and (by default) `private`
415    /// responses are not stored. Cache contents are never trusted: artifact
416    /// bytes are checked against their declared checksums on every use.
417    /// See `docs/cache.md` and [`CacheConfig`] for the limits.
418    #[must_use]
419    pub fn cache_dir(mut self, dir: impl Into<std::path::PathBuf>) -> Self {
420        self.cache = Some(CacheConfig::new(dir));
421        self
422    }
423
424    /// Enable the cache with explicit settings (*experimental*).
425    #[must_use]
426    pub fn cache(mut self, config: CacheConfig) -> Self {
427        self.cache = Some(config);
428        self
429    }
430
431    /// Answer only from the cache and never open a connection (*experimental*).
432    ///
433    /// A cacheable `GET` that is not in the cache (or whose entry is older than
434    /// [`CacheConfig::max_age`]) fails with [`ClientError::Offline`]; any other
435    /// request fails the same way. Requires [`ClientBuilder::cache_dir`] or
436    /// [`ClientBuilder::cache`]; [`ClientBuilder::build`] fails without one.
437    #[must_use]
438    pub fn offline(mut self, offline: bool) -> Self {
439        self.offline = offline;
440        self
441    }
442
443    /// Replace resource limits.
444    #[must_use]
445    pub fn limits(mut self, limits: Limits) -> Self {
446        self.limits = limits;
447        self
448    }
449
450    /// Replace the destination policy.
451    ///
452    /// The default rejects cleartext HTTP, loopback, link-local, and private addresses.
453    #[must_use]
454    pub fn destination_policy(mut self, policy: DestinationPolicy) -> Self {
455        self.policy = policy;
456        self
457    }
458
459    /// Versions this client is willing to speak. Build metadata on the server is ignored.
460    #[must_use]
461    pub fn supported_versions(mut self, supported: SupportedApi) -> Self {
462        self.supported = supported;
463        self
464    }
465
466    /// API key used at `POST /token` for origins the caller has explicitly selected.
467    ///
468    /// Discovery does not send this key to endpoints learned from `.well-known/tea`
469    /// unless [`Self::allow_discovered_credentials`] is set. A [`crate::Service`]
470    /// built from a caller-supplied base URL may use the key at that origin.
471    #[must_use]
472    pub fn api_key(mut self, key: ApiKey) -> Self {
473        self.credentials = Some(key);
474        self
475    }
476
477    /// Allow the API key to be presented to token endpoints chosen by discovery.
478    ///
479    /// Leave this unset when the well-known document is not a trusted source of
480    /// credential destinations.
481    #[must_use]
482    pub fn allow_discovered_credentials(mut self, allow: bool) -> Self {
483        self.allow_discovered_credentials = allow;
484        self
485    }
486
487    /// Fetch the well-known document from this URL instead of `https://{tei-domain}/.well-known/tea`.
488    ///
489    /// The override is still subject to [`DestinationPolicy`]. It exists so tests
490    /// and explicitly configured fixtures can supply the document without changing
491    /// production URL construction.
492    #[must_use]
493    pub fn well_known_fetch_url(mut self, url: Url) -> Self {
494        self.well_known_override = Some(url);
495        self
496    }
497
498    /// Accept API versions that are not exactly a supported one (default `false`).
499    ///
500    /// When `true`, `/.well-known/tea` and `/discovery` may advertise `1` or
501    /// `1.0` (read as `1.0.0`; the advertised spelling stays in the request
502    /// path, so `1` calls `/v1/…`), and any *stable* version with the same
503    /// major as a supported version is accepted, for example `1.0.1` and
504    /// `1.1.0` for a client that supports `1.0.0`. Pre-releases (`1.2.0-rc.1`)
505    /// are accepted only on an exact match.
506    ///
507    /// Selection order: exact supported versions first (highest version, then
508    /// priority), then same-major stable versions (highest first). An exact
509    /// match is never outranked by a version this client was not written for.
510    ///
511    /// **Risk:** this client's models were checked against the pinned 1.0.0
512    /// schemas only. A server that passes the version check may still send
513    /// responses that fail to parse or that are misread. The default (`false`)
514    /// is unchanged from earlier behavior.
515    #[must_use]
516    pub fn lenient_versions(mut self, lenient: bool) -> Self {
517        self.lenient_versions = lenient;
518        self
519    }
520
521    /// Accept artifact downloads whose only declared checksums use weak
522    /// algorithms (SHA-1).
523    ///
524    /// Off by default: such a download fails with [`ClientError::Integrity`]
525    /// and [`libtea_core::IntegrityOutcome::Weak`]. When set, a full match is
526    /// reported as [`libtea_core::IntegrityOutcome::Verified`] and each
527    /// [`libtea_core::ChecksumCheck::weak`] stays `true`.
528    #[must_use]
529    pub fn allow_weak_checksums(mut self, allow: bool) -> Self {
530        self.checksum_policy = self.checksum_policy.with_allow_weak(allow);
531        self
532    }
533
534    /// Ignore `HTTP_PROXY` / `HTTPS_PROXY` / `ALL_PROXY` (and lowercase forms).
535    ///
536    /// By default environment proxies are honored. Through a proxy, the
537    /// proxy resolves the target hostname, so the DNS-based
538    /// [`DestinationPolicy`] checks are **not** enforced for hostnames; only
539    /// scheme, userinfo, literal-IP, and redirect checks still apply. Set this
540    /// to `true` to connect directly and keep the DNS checks.
541    #[must_use]
542    pub fn ignore_env_proxies(mut self, ignore: bool) -> Self {
543        self.ignore_env_proxies = ignore;
544        self
545    }
546
547    /// Add a PEM trust anchor. System or webpki roots remain in use as well.
548    #[must_use]
549    pub fn add_root_pem(mut self, pem: impl Into<Vec<u8>>) -> Self {
550        self.roots_pem.extend(pem.into());
551        self.roots_pem.extend(b"\n");
552        self
553    }
554
555    /// Build the client.
556    ///
557    /// # Errors
558    ///
559    /// Returns an error when TLS or the HTTP client cannot be constructed.
560    pub fn build(self) -> Result<Client, ClientError> {
561        if self.limits.idle_timeout.is_zero() || self.limits.download_timeout.is_zero() {
562            return Err(ClientError::Model(libtea_core::ModelError::Invalid(
563                "idle_timeout and download_timeout must not be zero".into(),
564            )));
565        }
566        if self.limits.max_in_flight == 0 {
567            return Err(ClientError::Model(libtea_core::ModelError::Invalid(
568                "max_in_flight must be at least 1".into(),
569            )));
570        }
571        let cache = match self.cache {
572            Some(config) => Some(Arc::new(Cache::open(config, self.offline)?)),
573            None if self.offline => {
574                return Err(ClientError::Model(libtea_core::ModelError::Invalid(
575                    "offline mode needs a cache directory".into(),
576                )));
577            }
578            None => None,
579        };
580        let mut builder = reqwest::Client::builder()
581            .redirect(reqwest::redirect::Policy::none())
582            .connect_timeout(self.limits.connect_timeout)
583            // No client-wide total timeout: a total would end a large artifact
584            // download that is still making progress. Each request gets its own
585            // total (`request_timeout` or `download_timeout`, see `open_once`),
586            // and a stall is caught by the per-read timeout.
587            .read_timeout(self.limits.idle_timeout)
588            .user_agent(concat!("libtea/", env!("CARGO_PKG_VERSION")))
589            .min_tls_version(reqwest::tls::Version::TLS_1_2)
590            .https_only(false)
591            .dns_resolver(Arc::new(PolicyResolver {
592                policy: self.policy.clone(),
593            }));
594        if self.ignore_env_proxies {
595            builder = builder.no_proxy();
596        }
597        if !self.roots_pem.is_empty() {
598            let cert = reqwest::Certificate::from_pem(&self.roots_pem)
599                .map_err(|err| ClientError::Transport(format!("invalid trust anchor: {err}")))?;
600            builder = builder.add_root_certificate(cert);
601        }
602        let http = builder
603            .build()
604            .map_err(|err| ClientError::Transport(format!("HTTP client setup failed: {err}")))?;
605        Ok(Client {
606            inner: Arc::new(ClientInner {
607                http,
608                semaphore: Arc::new(Semaphore::new(self.limits.max_in_flight)),
609                limits: self.limits,
610                policy: self.policy,
611                supported: if self.lenient_versions {
612                    self.supported.with_lenient(true)
613                } else {
614                    self.supported
615                },
616                credentials: self.credentials,
617                credential_origins: Mutex::new(BTreeSet::new()),
618                allow_discovered_credentials: self.allow_discovered_credentials,
619                tokens: Mutex::new(std::collections::HashMap::new()),
620                token_refresh: Mutex::new(std::collections::HashMap::new()),
621                checksum_policy: self.checksum_policy,
622                well_known_override: self.well_known_override,
623                cache,
624            }),
625        })
626    }
627}
628
629impl Client {
630    /// Production client for TEA 1.0.0.
631    ///
632    /// # Errors
633    ///
634    /// Returns an error when the HTTP client cannot be constructed.
635    pub fn new() -> Result<Self, ClientError> {
636        ClientBuilder::new().build()
637    }
638
639    /// Start a builder.
640    #[must_use]
641    pub fn builder() -> ClientBuilder {
642        ClientBuilder::new()
643    }
644
645    /// Bind a caller-supplied API base.
646    ///
647    /// The base origin becomes an allowed destination for this client's API key.
648    ///
649    /// # Errors
650    ///
651    /// Returns an error when the base URL or version is not usable.
652    pub fn service(&self, root: &str, version: &str) -> Result<crate::Service, ClientError> {
653        let root_url = parse_api_base(root)?;
654        self.inner.policy.check_url(&root_url)?;
655        let version = if self.inner.supported.is_lenient() {
656            ApiVersion::parse_lenient(version)?
657        } else {
658            ApiVersion::parse(version)?
659        };
660        self.authorize_origin(&root_url)?;
661        crate::Service::from_parts(self.clone(), root_url, version.as_str().to_owned())
662    }
663
664    pub(crate) fn authorize_origin(&self, url: &Url) -> Result<(), ClientError> {
665        let origin = origin_key(url)?;
666        self.inner
667            .credential_origins
668            .lock()
669            .unwrap_or_else(|err| err.into_inner())
670            .insert(origin);
671        Ok(())
672    }
673}
674
675tokio::task_local! {
676    static REQUEST_URL: Url;
677}
678
679struct PolicyResolver {
680    policy: DestinationPolicy,
681}
682
683impl reqwest::dns::Resolve for PolicyResolver {
684    fn resolve(&self, name: reqwest::dns::Name) -> reqwest::dns::Resolving {
685        let host = name.as_str().to_owned();
686        let policy = self.policy.clone();
687        Box::pin(async move {
688            let looked_up = tokio::net::lookup_host((host.as_str(), 0))
689                .await
690                .map_err(|err| Box::new(err) as Box<dyn std::error::Error + Send + Sync>)?;
691            let mut allowed = Vec::new();
692            for addr in looked_up {
693                let ip = addr.ip();
694                if address_allowed(&policy, ip) {
695                    allowed.push(SocketAddr::new(ip, addr.port()));
696                }
697            }
698            if allowed.is_empty() {
699                return Err(Box::new(std::io::Error::new(
700                    std::io::ErrorKind::PermissionDenied,
701                    "resolved addresses are not allowed by destination policy",
702                ))
703                    as Box<dyn std::error::Error + Send + Sync>);
704            }
705            let addrs: reqwest::dns::Addrs = Box::new(allowed.into_iter());
706            Ok(addrs)
707        })
708    }
709}
710
711/// A non-public address is kept only for the request URL's exact origin.
712///
713/// When the resolver runs outside a request scope, only public addresses are kept.
714fn address_allowed(policy: &DestinationPolicy, ip: std::net::IpAddr) -> bool {
715    REQUEST_URL
716        .try_with(|url| policy.allows_resolved_ip(url, ip).is_ok())
717        .unwrap_or_else(|_| classify_ip(ip).is_public())
718}
719
720pub(crate) struct RawResponse {
721    pub status: StatusCode,
722    pub headers: reqwest::header::HeaderMap,
723    pub body: Bytes,
724    pub final_url: Url,
725    /// Artifact bodies are decoded while they are read. JSON bodies are not.
726    pub content_decoded: bool,
727    /// Set when the response may be stored once its body has been checked.
728    pending_cache: Option<Box<PendingCache>>,
729    /// Set when the body came out of the cache, so a failed check can evict it.
730    from_cache: Option<Box<CacheOrigin>>,
731    /// Bearer token attached to the request that produced this response.
732    presented_bearer: Option<String>,
733}
734
735/// Everything needed to store a response after the caller has checked it.
736pub(crate) struct PendingCache {
737    cache: Arc<Cache>,
738    key: String,
739    request_url: String,
740    headers: Vec<(String, String)>,
741    /// A revalidated entry whose age restarts when the body has been checked.
742    /// `None` for a response that is new to the cache.
743    meta: Option<CacheEntryMeta>,
744}
745
746/// Where a cached body came from.
747pub(crate) struct CacheOrigin {
748    cache: Arc<Cache>,
749    key: String,
750}
751
752impl RawResponse {
753    /// Store this response in the cache. Call only after its body passed the
754    /// checks that matter (artifact checksums); a no-op when nothing is pending.
755    pub(crate) async fn commit_cache(&self) {
756        let Some(pending) = &self.pending_cache else {
757            return;
758        };
759        if self.body.len() as u64 > pending.cache.config.max_entry_bytes {
760            return;
761        }
762        let meta = match &pending.meta {
763            Some(meta) => meta.clone(),
764            None => CacheEntryMeta::new(
765                &pending.key,
766                &pending.request_url,
767                200,
768                now_secs(),
769                self.content_decoded,
770                &pending.headers,
771            ),
772        };
773        pending
774            .cache
775            .store(&pending.key, meta, self.body.to_vec())
776            .await;
777    }
778
779    /// The caller's check of this body failed. If it came from the cache, drop
780    /// the entry so it is neither served again nor renewed by a `304`.
781    pub(crate) async fn evict_cached(&self) {
782        if let Some(origin) = &self.from_cache {
783            origin.cache.remove(&origin.key).await;
784        }
785    }
786}
787
788/// A response whose headers are read and whose body is not.
789struct Opened {
790    status: StatusCode,
791    headers: reqwest::header::HeaderMap,
792    final_url: Url,
793    presented_bearer: Option<String>,
794    response: reqwest::Response,
795}
796
797/// First stage of a streamed artifact download.
798pub(crate) enum StreamStart {
799    /// A success status; the body is unread.
800    Body(OpenBody),
801    /// `304`, or an error status with its bounded body, for `map_api_error`.
802    Other(RawResponse),
803}
804
805/// A success response with an unread body.
806pub(crate) struct OpenBody {
807    pub status: StatusCode,
808    /// Whether the request carried a bearer token.
809    pub authenticated: bool,
810    pub headers: reqwest::header::HeaderMap,
811    pub final_url: Url,
812    response: reqwest::Response,
813}
814
815impl OpenBody {
816    /// The next raw (still content-coded) body chunk.
817    pub(crate) async fn chunk(&mut self) -> Result<Option<Bytes>, ClientError> {
818        self.response.chunk().await.map_err(ClientError::transport)
819    }
820}
821
822pub(crate) struct Call {
823    pub method: Method,
824    pub url: Url,
825    pub api_prefix: Option<Url>,
826    pub artifact: bool,
827    pub body: Option<String>,
828    pub content_type: Option<&'static str>,
829    pub basic_auth: bool,
830    pub if_none_match: Option<String>,
831    pub if_modified_since: Option<String>,
832    pub max_body: usize,
833}
834
835impl ClientInner {
836    /// Send a request, through the cache when one is configured and the call is
837    /// a plain `GET`.
838    pub(crate) async fn send(&self, mut call: Call) -> Result<RawResponse, ClientError> {
839        let Some(cache) = self.cache.clone() else {
840            return self.send_network(call).await;
841        };
842        let eligible = call.method == Method::GET
843            && call.if_none_match.is_none()
844            && call.if_modified_since.is_none();
845        let key = if eligible {
846            self.cache_key_for(&call.url)
847        } else {
848            None
849        };
850        let Some(key) = key else {
851            if cache.offline {
852                return Err(ClientError::Offline);
853            }
854            return self.send_network(call).await;
855        };
856
857        // A cache hit is subject to the same destination rules as a request:
858        // another client, with a more permissive policy, may have stored it.
859        self.policy.check_url(&call.url)?;
860        let mut existing = cache.load(&key).await;
861        // ...and to the same size limit, as it is today. Limits can be lowered
862        // after an entry was stored, and an entry can be planted.
863        if existing
864            .as_ref()
865            .is_some_and(|(_, body)| body.len() > call.max_body)
866        {
867            cache.remove(&key).await;
868            if cache.offline {
869                return Err(ClientError::TooLarge);
870            }
871            existing = None;
872        }
873        if cache.offline {
874            return existing
875                .map(|(meta, body)| {
876                    let mut raw = raw_from_entry(&call.url, &meta, body);
877                    raw.from_cache = Some(Box::new(CacheOrigin {
878                        cache: Arc::clone(&cache),
879                        key: key.clone(),
880                    }));
881                    raw
882                })
883                .ok_or(ClientError::Offline);
884        }
885        if let Some((meta, _)) = &existing {
886            call.if_none_match = meta.header("etag").map(str::to_owned);
887            call.if_modified_since = meta.header("last-modified").map(str::to_owned);
888        }
889        let url = call.url.clone();
890        let artifact = call.artifact;
891        let mut response = self.send_network(call).await?;
892
893        match response.status.as_u16() {
894            304 => {
895                let Some((meta, body)) = existing else {
896                    return Ok(response);
897                };
898                let revalidated = self.revalidated_meta(
899                    &cache,
900                    meta.clone(),
901                    &response.headers,
902                    response.presented_bearer.is_some(),
903                );
904                let mut raw = raw_from_entry(&url, revalidated.as_ref().unwrap_or(&meta), body);
905                raw.from_cache = Some(Box::new(CacheOrigin {
906                    cache: Arc::clone(&cache),
907                    key: key.clone(),
908                }));
909                match revalidated {
910                    // The entry's age restarts only after the body has passed the
911                    // caller's checks; a JSON body has none, so renew it now.
912                    Some(meta) => {
913                        raw.pending_cache = Some(Box::new(PendingCache {
914                            cache: Arc::clone(&cache),
915                            key,
916                            request_url: display_url(&url),
917                            headers: Vec::new(),
918                            meta: Some(meta),
919                        }));
920                        if !artifact {
921                            raw.commit_cache().await;
922                        }
923                    }
924                    // The new directives forbid keeping it.
925                    None => cache.remove(&key).await,
926                }
927                Ok(raw)
928            }
929            200 => {
930                let headers = storable_headers(&response.headers);
931                let decision = decide_storage(
932                    &response.headers,
933                    response.presented_bearer.is_some(),
934                    cache.config.authenticated,
935                );
936                match decision {
937                    Ok(()) => {
938                        let pending = PendingCache {
939                            cache: Arc::clone(&cache),
940                            key,
941                            request_url: display_url(&url),
942                            headers,
943                            meta: None,
944                        };
945                        response.pending_cache = Some(Box::new(pending));
946                        // Artifact bytes are stored only after the caller has
947                        // checked them; everything else is stored now.
948                        if !artifact {
949                            response.commit_cache().await;
950                        }
951                    }
952                    Err(NotStored::NoStore) => cache.remove(&key).await,
953                    Err(_) => {}
954                }
955                Ok(response)
956            }
957            404 | 410 => {
958                cache.remove(&key).await;
959                Ok(response)
960            }
961            _ => Ok(response),
962        }
963    }
964
965    /// Cache key for a `GET` of `url`, or `None` when the origin has no key.
966    pub(crate) fn cache_key_for(&self, url: &Url) -> Option<String> {
967        let mut normalized = url.clone();
968        normalized.set_fragment(None);
969        let _ = normalized.set_username("");
970        let _ = normalized.set_password(None);
971        let origin = origin_key(&normalized).ok()?;
972        Some(cache_key(
973            "GET",
974            normalized.as_str(),
975            &origin,
976            self.credentials.as_ref().map(|key| key.id.as_str()),
977        ))
978    }
979
980    /// A `304` confirmed the stored entry: take the new validators and
981    /// directives and restart its age. Returns the entry as it should now be
982    /// stored, or `None` when the new directives forbid keeping it. Nothing is
983    /// written here: the caller stores it once the body has been checked.
984    pub(crate) fn revalidated_meta(
985        &self,
986        cache: &Cache,
987        mut meta: CacheEntryMeta,
988        headers: &reqwest::header::HeaderMap,
989        authenticated: bool,
990    ) -> Option<CacheEntryMeta> {
991        merge_validated_headers(&mut meta, headers);
992        meta.validated_at = now_secs().max(meta.stored_at);
993        let lines: Vec<&str> = meta.header("cache-control").into_iter().collect();
994        storage_decision(
995            200,
996            &CacheControl::parse(&lines),
997            meta.header("vary"),
998            authenticated,
999            cache.config.authenticated,
1000        )
1001        .is_ok()
1002        .then_some(meta)
1003    }
1004
1005    async fn wait_after_throttle(
1006        &self,
1007        attempt: u32,
1008        error: ClientError,
1009    ) -> Result<(), ClientError> {
1010        let seconds = match &error {
1011            ClientError::Throttled {
1012                retry_after_secs, ..
1013            } => *retry_after_secs,
1014            _ => return Err(error),
1015        };
1016        match seconds {
1017            Some(seconds) => {
1018                let wait = Duration::from_secs(seconds);
1019                if wait > self.limits.max_retry_after {
1020                    return Err(error);
1021                }
1022                if !wait.is_zero() {
1023                    tokio::time::sleep(wait).await;
1024                }
1025            }
1026            None => self.backoff(attempt).await,
1027        }
1028        Ok(())
1029    }
1030
1031    async fn send_network(&self, call: Call) -> Result<RawResponse, ClientError> {
1032        let mut attempt = 0u32;
1033        let mut refreshed = false;
1034        loop {
1035            match self.send_once(&call).await {
1036                Ok(response)
1037                    if response.status == StatusCode::UNAUTHORIZED
1038                        && self
1039                            .retry_after_unauthorized(
1040                                &call,
1041                                &response.headers,
1042                                response.presented_bearer.as_deref(),
1043                                &mut refreshed,
1044                            )
1045                            .await? =>
1046                {
1047                    continue;
1048                }
1049                Ok(response) => return Ok(response),
1050                Err(ClientError::Timeout) | Err(ClientError::Transport(_))
1051                    if call.method == Method::GET && attempt < self.limits.max_retries =>
1052                {
1053                    attempt += 1;
1054                    self.backoff(attempt).await;
1055                }
1056                Err(error @ ClientError::Throttled { .. })
1057                    if call.method == Method::GET && attempt < self.limits.max_retries =>
1058                {
1059                    attempt += 1;
1060                    self.wait_after_throttle(attempt, error).await?;
1061                }
1062                Err(other) => return Err(other),
1063            }
1064        }
1065    }
1066
1067    /// Decide what a `401` means for `call`. `Ok(true)` asks the caller to send
1068    /// the request again with a refreshed token; `Ok(false)` hands the `401`
1069    /// response back.
1070    async fn retry_after_unauthorized(
1071        &self,
1072        call: &Call,
1073        headers: &reqwest::header::HeaderMap,
1074        presented_bearer: Option<&str>,
1075        refreshed: &mut bool,
1076    ) -> Result<bool, ClientError> {
1077        if call.basic_auth {
1078            return Ok(false);
1079        }
1080        if *refreshed {
1081            // Drop the bearer token this retry presented, and only when
1082            // that value is still the cache entry. A newer token stored
1083            // for this origin while the 401 was in flight stays cached.
1084            if let Some(presented) = presented_bearer {
1085                self.discard_token_if_current(call.api_prefix.as_ref(), presented);
1086            }
1087            return Ok(false);
1088        }
1089        let challenge = header_str(headers, WWW_AUTHENTICATE).map(str::to_owned);
1090        if self.should_refresh_token(challenge.as_deref(), call.api_prefix.as_ref()) {
1091            let prefix = call
1092                .api_prefix
1093                .as_ref()
1094                .ok_or(ClientError::AuthenticationRequired)?;
1095            self.refresh_token_coalesced(prefix, presented_bearer)
1096                .await?;
1097            *refreshed = true;
1098            return Ok(true);
1099        }
1100        if challenge.as_deref().is_some_and(is_bearer_challenge) {
1101            return Err(ClientError::AuthenticationRequired);
1102        }
1103        Ok(false)
1104    }
1105
1106    /// Like [`ClientInner::send`] for an artifact `GET`, but a success body is
1107    /// left unread so the caller can stream it.
1108    ///
1109    /// Redirects, destination policy, token refresh and the `401`/`503`
1110    /// handling are shared with `send`. Because a stream cannot be replayed, a
1111    /// transport failure while the body is read is not retried; failures
1112    /// before the body starts are retried like any other `GET`.
1113    pub(crate) async fn send_streaming(&self, call: Call) -> Result<StreamStart, ClientError> {
1114        let mut attempt = 0u32;
1115        let mut refreshed = false;
1116        loop {
1117            match self.open_once(&call).await {
1118                Ok(opened)
1119                    if opened.status == StatusCode::UNAUTHORIZED
1120                        && self
1121                            .retry_after_unauthorized(
1122                                &call,
1123                                &opened.headers,
1124                                opened.presented_bearer.as_deref(),
1125                                &mut refreshed,
1126                            )
1127                            .await? =>
1128                {
1129                    continue;
1130                }
1131                Ok(opened) => return self.start_stream(opened, &call).await,
1132                Err(ClientError::Timeout) | Err(ClientError::Transport(_))
1133                    if call.method == Method::GET && attempt < self.limits.max_retries =>
1134                {
1135                    attempt += 1;
1136                    self.backoff(attempt).await;
1137                }
1138                Err(error @ ClientError::Throttled { .. })
1139                    if call.method == Method::GET && attempt < self.limits.max_retries =>
1140                {
1141                    attempt += 1;
1142                    self.wait_after_throttle(attempt, error).await?;
1143                }
1144                Err(other) => return Err(other),
1145            }
1146        }
1147    }
1148
1149    async fn start_stream(&self, opened: Opened, call: &Call) -> Result<StreamStart, ClientError> {
1150        if opened.status.is_success() {
1151            if opened
1152                .response
1153                .content_length()
1154                .is_some_and(|len| len > call.max_body as u64)
1155            {
1156                return Err(ClientError::TooLarge);
1157            }
1158            return Ok(StreamStart::Body(OpenBody {
1159                status: opened.status,
1160                authenticated: opened.presented_bearer.is_some(),
1161                headers: opened.headers,
1162                final_url: opened.final_url,
1163                response: opened.response,
1164            }));
1165        }
1166        // 304 and error statuses carry no artifact. Error bodies are read as
1167        // ordinary bounded JSON so the same error mapping applies.
1168        let metadata_only = opened.status == StatusCode::NOT_MODIFIED;
1169        let body = if metadata_only {
1170            Bytes::new()
1171        } else {
1172            read_limited(opened.response, self.limits.max_json_bytes).await?
1173        };
1174        Ok(StreamStart::Other(RawResponse {
1175            status: opened.status,
1176            headers: opened.headers,
1177            body,
1178            final_url: opened.final_url,
1179            content_decoded: false,
1180            pending_cache: None,
1181            from_cache: None,
1182            presented_bearer: opened.presented_bearer,
1183        }))
1184    }
1185
1186    async fn send_once(&self, call: &Call) -> Result<RawResponse, ClientError> {
1187        let Opened {
1188            status,
1189            headers,
1190            final_url,
1191            presented_bearer,
1192            response,
1193        } = self.open_once(call).await?;
1194        let metadata_only = call.method == Method::HEAD || status == StatusCode::NOT_MODIFIED;
1195        let (body, content_decoded) = if metadata_only {
1196            // Content-Length on HEAD and 304 describes the selected
1197            // representation, not a message body.
1198            drop(response);
1199            (Bytes::new(), false)
1200        } else if call.artifact {
1201            let coding = header_str(&headers, CONTENT_ENCODING).map(str::to_owned);
1202            let decoded = read_decoded(response, call.max_body, coding.as_deref()).await?;
1203            (Bytes::from(decoded), true)
1204        } else {
1205            (read_limited(response, call.max_body).await?, false)
1206        };
1207        tracing::debug!(
1208            url = %redact_url_for_log(&final_url),
1209            status = status.as_u16(),
1210            "tea response"
1211        );
1212        Ok(RawResponse {
1213            status,
1214            headers,
1215            body,
1216            final_url,
1217            content_decoded,
1218            pending_cache: None,
1219            from_cache: None,
1220            presented_bearer,
1221        })
1222    }
1223
1224    /// Send the request, follow redirects under the destination policy and
1225    /// return the final response with its body unread.
1226    async fn open_once(&self, call: &Call) -> Result<Opened, ClientError> {
1227        let mut url = call.url.clone();
1228        let mut redirects = 0usize;
1229        loop {
1230            self.policy.check_url(&url)?;
1231            let _permit = self
1232                .semaphore
1233                .clone()
1234                .acquire_owned()
1235                .await
1236                .map_err(|_| ClientError::Transport("request limiter closed".into()))?;
1237            let mut request = self.http.request(call.method.clone(), url.clone());
1238            let total = if call.artifact && call.method == Method::GET {
1239                self.limits.download_timeout
1240            } else {
1241                self.limits.request_timeout
1242            };
1243            request = request.timeout(total);
1244            if call.artifact {
1245                request = request.header("accept-encoding", "gzip, deflate, identity");
1246            }
1247            if let Some(etag) = &call.if_none_match {
1248                request = request.header("if-none-match", etag);
1249            }
1250            if let Some(date) = &call.if_modified_since {
1251                request = request.header("if-modified-since", date);
1252            }
1253            let presented_bearer = if call.basic_auth {
1254                let header = self.basic_header(&url)?;
1255                request = request.header(AUTHORIZATION, header);
1256                None
1257            } else if let Some(token) = self.bearer_for(&url, call.api_prefix.as_ref()) {
1258                request = request.header(AUTHORIZATION, format!("Bearer {token}"));
1259                Some(token)
1260            } else {
1261                None
1262            };
1263            if let Some(content_type) = call.content_type {
1264                request = request.header(CONTENT_TYPE, content_type);
1265            }
1266            if let Some(body) = &call.body {
1267                request = request.body(body.clone());
1268            }
1269            tracing::debug!(
1270                url = %redact_url_for_log(&url),
1271                method = %call.method,
1272                "tea request"
1273            );
1274            let response = REQUEST_URL
1275                .scope(url.clone(), request.send())
1276                .await
1277                .map_err(ClientError::transport)?;
1278            let status = response.status();
1279            if matches!(
1280                status,
1281                StatusCode::MOVED_PERMANENTLY
1282                    | StatusCode::FOUND
1283                    | StatusCode::SEE_OTHER
1284                    | StatusCode::TEMPORARY_REDIRECT
1285                    | StatusCode::PERMANENT_REDIRECT
1286            ) && call.method != Method::POST
1287            {
1288                redirects += 1;
1289                if redirects > self.limits.max_redirects {
1290                    return Err(ClientError::TooManyRedirects);
1291                }
1292                let location = response
1293                    .headers()
1294                    .get(LOCATION)
1295                    .and_then(|value| value.to_str().ok())
1296                    .ok_or(ClientError::BadRedirect)?;
1297                let next = url.join(location).map_err(|_| ClientError::BadRedirect)?;
1298                self.policy.check_url(&next)?;
1299                drop(response);
1300                url = next;
1301                continue;
1302            }
1303            if matches!(
1304                status,
1305                StatusCode::TOO_MANY_REQUESTS | StatusCode::SERVICE_UNAVAILABLE
1306            ) && call.method == Method::GET
1307            {
1308                let retry_after_secs = response
1309                    .headers()
1310                    .get(RETRY_AFTER)
1311                    .and_then(|value| value.to_str().ok())
1312                    .and_then(|value| parse_retry_after(value, now_secs()));
1313                drop(response);
1314                return Err(ClientError::Throttled {
1315                    status: status.as_u16(),
1316                    retry_after_secs,
1317                });
1318            }
1319            let headers = response.headers().clone();
1320            return Ok(Opened {
1321                status,
1322                headers,
1323                final_url: url,
1324                presented_bearer,
1325                response,
1326            });
1327        }
1328    }
1329
1330    fn should_refresh_token(&self, challenge: Option<&str>, api_prefix: Option<&Url>) -> bool {
1331        let Some(challenge) = challenge else {
1332            return false;
1333        };
1334        if !is_bearer_challenge(challenge) {
1335            return false;
1336        }
1337        let error = challenge_error(challenge);
1338        if matches!(error.as_deref(), Some(code) if !code.eq_ignore_ascii_case("invalid_token")) {
1339            return false;
1340        }
1341        let Some(prefix) = api_prefix else {
1342            return false;
1343        };
1344        self.credentials.is_some() && origin_allowed(self, prefix)
1345    }
1346
1347    fn bearer_for(&self, url: &Url, api_prefix: Option<&Url>) -> Option<String> {
1348        let prefix = api_prefix?;
1349        if !url_under_prefix(url, prefix) {
1350            return None;
1351        }
1352        let origin = origin_key(url).ok()?;
1353        let tokens = self.tokens.lock().unwrap_or_else(|err| err.into_inner());
1354        let stored = tokens.get(&origin)?;
1355        if stored.expires_at.is_some_and(|when| when <= Instant::now()) {
1356            return None;
1357        }
1358        Some(stored.value.clone())
1359    }
1360
1361    fn basic_header(&self, url: &Url) -> Result<String, ClientError> {
1362        if !origin_allowed(self, url) {
1363            return Err(ClientError::AuthenticationRequired);
1364        }
1365        let Some(key) = &self.credentials else {
1366            return Err(ClientError::AuthenticationRequired);
1367        };
1368        let id = form_encode(&key.id);
1369        let secret = form_encode(&key.secret);
1370        let encoded = base64::Engine::encode(
1371            &base64::engine::general_purpose::STANDARD,
1372            format!("{id}:{secret}"),
1373        );
1374        Ok(format!("Basic {encoded}"))
1375    }
1376
1377    /// Coalesce concurrent token exchanges for one origin.
1378    ///
1379    /// Waiters that find a cached bearer different from the value that just
1380    /// received `401` reuse that token and skip another `POST /token`. A
1381    /// waiter that queued while an exchange was in flight and finds that it
1382    /// failed returns the same failure. If the exchanging task is cancelled,
1383    /// nothing is recorded and the next waiter performs its own exchange.
1384    async fn refresh_token_coalesced(
1385        &self,
1386        api_prefix: &Url,
1387        presented: Option<&str>,
1388    ) -> Result<(), ClientError> {
1389        let lease = SlotLease::acquire(self, origin_key(api_prefix)?);
1390        let slot = &lease.slot;
1391        let seen = slot.completed.load(Ordering::Acquire);
1392        let mut last_failure = slot.last_failure.lock().await;
1393        if let Some(current) = self.bearer_for(api_prefix, Some(api_prefix)) {
1394            let reusable = match presented {
1395                Some(old) => current != old,
1396                None => true,
1397            };
1398            if reusable {
1399                return Ok(());
1400            }
1401        }
1402        if slot.completed.load(Ordering::Acquire) != seen {
1403            if let Some(failure) = last_failure.as_ref() {
1404                return Err(failure.to_error());
1405            }
1406        }
1407        let result = self.fetch_token(api_prefix).await;
1408        *last_failure = result.as_ref().err().map(SharedFailure::from_error);
1409        slot.completed.fetch_add(1, Ordering::Release);
1410        result
1411    }
1412
1413    pub(crate) async fn fetch_token(&self, api_prefix: &Url) -> Result<(), ClientError> {
1414        if !origin_allowed(self, api_prefix) {
1415            return Err(ClientError::AuthenticationRequired);
1416        }
1417        let url = api_prefix.join("token").map_err(|_| {
1418            ClientError::Model(libtea_core::ModelError::Invalid("token URL".into()))
1419        })?;
1420        let call = Call {
1421            method: Method::POST,
1422            url,
1423            api_prefix: Some(api_prefix.clone()),
1424            artifact: false,
1425            body: Some("grant_type=client_credentials".into()),
1426            content_type: Some("application/x-www-form-urlencoded"),
1427            basic_auth: true,
1428            if_none_match: None,
1429            if_modified_since: None,
1430            max_body: self.limits.max_json_bytes,
1431        };
1432        let response = self.send_once(&call).await?;
1433        if response.status == StatusCode::NOT_FOUND {
1434            return Err(ClientError::Api {
1435                status: 404,
1436                tea_error: tea_error_code(
1437                    header_str(&response.headers, CONTENT_TYPE),
1438                    &response.body,
1439                )
1440                .map(|code| libtea_core::escape_control_chars(&code)),
1441                message: None,
1442            });
1443        }
1444        if !response.status.is_success() {
1445            let code = serde_json::from_slice::<serde_json::Value>(&response.body)
1446                .ok()
1447                .and_then(|value| {
1448                    value
1449                        .get("error")
1450                        .and_then(|error| error.as_str())
1451                        .map(str::to_owned)
1452                })
1453                .unwrap_or_else(|| response.status.as_str().to_owned());
1454            return Err(ClientError::Token {
1455                error: libtea_core::escape_control_chars(&code),
1456            });
1457        }
1458        let token: TokenResponse = serde_json::from_slice(&response.body)?;
1459        let token = token.bearer()?;
1460        let expires_at = token_expires_at(token.expires_in, Instant::now());
1461        let origin = origin_key(api_prefix)?;
1462        self.tokens
1463            .lock()
1464            .unwrap_or_else(|err| err.into_inner())
1465            .insert(
1466                origin,
1467                StoredToken {
1468                    value: token.access_token,
1469                    expires_at,
1470                },
1471            );
1472        Ok(())
1473    }
1474
1475    fn discard_token_if_current(&self, api_prefix: Option<&Url>, presented: &str) {
1476        let Some(prefix) = api_prefix else {
1477            return;
1478        };
1479        let Ok(origin) = origin_key(prefix) else {
1480            return;
1481        };
1482        let mut tokens = self.tokens.lock().unwrap_or_else(|err| err.into_inner());
1483        let still_current = tokens
1484            .get(&origin)
1485            .is_some_and(|stored| stored.value == presented);
1486        if still_current {
1487            tokens.remove(&origin);
1488        }
1489    }
1490
1491    pub(crate) async fn backoff(&self, attempt: u32) {
1492        let shift = attempt.min(5);
1493        let delay = self.limits.initial_backoff.saturating_mul(1 << shift);
1494        if !delay.is_zero() {
1495            tokio::time::sleep(delay).await;
1496        }
1497    }
1498}
1499
1500fn origin_allowed(inner: &ClientInner, url: &Url) -> bool {
1501    origin_key(url)
1502        .map(|origin| {
1503            inner
1504                .credential_origins
1505                .lock()
1506                .unwrap_or_else(|err| err.into_inner())
1507                .contains(&origin)
1508        })
1509        .unwrap_or(false)
1510}
1511
1512fn is_bearer_challenge(value: &str) -> bool {
1513    value
1514        .split_whitespace()
1515        .next()
1516        .is_some_and(|scheme| scheme.eq_ignore_ascii_case("bearer"))
1517}
1518
1519fn challenge_error(value: &str) -> Option<String> {
1520    value.split(',').find_map(|part| {
1521        let (name, raw) = part.trim().split_once('=')?;
1522        if name.trim().eq_ignore_ascii_case("error") {
1523            Some(raw.trim().trim_matches('"').to_owned())
1524        } else {
1525            None
1526        }
1527    })
1528}
1529
1530pub(crate) fn url_under_prefix(url: &Url, prefix: &Url) -> bool {
1531    url.scheme() == prefix.scheme()
1532        && url.host_str() == prefix.host_str()
1533        && url.port_or_known_default() == prefix.port_or_known_default()
1534        && url.path().starts_with(prefix.path())
1535}
1536
1537fn form_encode(value: &str) -> String {
1538    url::form_urlencoded::byte_serialize(value.as_bytes()).collect()
1539}
1540
1541/// Local expiry of a token response.
1542///
1543/// TEA leaves lifetime to the implementation and says servers should send
1544/// `expires_in`. A five-second margin applies only when the lifetime is longer
1545/// than that margin, so a short positive lifetime is still usable. `0` is
1546/// already expired. A missing value, or a lifetime `Instant` cannot represent,
1547/// has no local expiry and is replaced when the server returns `invalid_token`.
1548fn token_expires_at(expires_in: Option<u64>, now: Instant) -> Option<Instant> {
1549    let seconds = expires_in?;
1550    let usable = if seconds > 5 { seconds - 5 } else { seconds };
1551    if usable == 0 {
1552        return Some(now);
1553    }
1554    now.checked_add(Duration::from_secs(usable))
1555}
1556
1557async fn read_decoded(
1558    response: reqwest::Response,
1559    max: usize,
1560    coding: Option<&str>,
1561) -> Result<Vec<u8>, ClientError> {
1562    if response
1563        .content_length()
1564        .is_some_and(|len| len > max as u64)
1565    {
1566        return Err(ClientError::TooLarge);
1567    }
1568    let mut decoder = ContentDecoder::new(coding, max)?;
1569    let mut stream = response.bytes_stream();
1570    while let Some(chunk) = stream.next().await {
1571        let chunk = chunk.map_err(ClientError::transport)?;
1572        decoder.push(&chunk)?;
1573    }
1574    Ok(decoder.finish()?)
1575}
1576
1577async fn read_limited(response: reqwest::Response, max: usize) -> Result<Bytes, ClientError> {
1578    if response
1579        .content_length()
1580        .is_some_and(|len| len > max as u64)
1581    {
1582        return Err(ClientError::TooLarge);
1583    }
1584    let mut collected = Vec::new();
1585    let mut stream = response.bytes_stream();
1586    while let Some(chunk) = stream.next().await {
1587        let chunk = chunk.map_err(ClientError::transport)?;
1588        if collected.len().saturating_add(chunk.len()) > max {
1589            return Err(ClientError::TooLarge);
1590        }
1591        collected.extend_from_slice(&chunk);
1592    }
1593    Ok(Bytes::from(collected))
1594}
1595
1596/// The request URL without query, fragment or userinfo, for display in entries.
1597pub(crate) fn display_url(url: &Url) -> String {
1598    let mut shown = url.clone();
1599    shown.set_query(None);
1600    shown.set_fragment(None);
1601    let _ = shown.set_username("");
1602    let _ = shown.set_password(None);
1603    shown.to_string()
1604}
1605
1606/// The allow-listed response headers, several lines of one header joined by `, `.
1607pub(crate) fn storable_headers(headers: &reqwest::header::HeaderMap) -> Vec<(String, String)> {
1608    STORED_HEADERS
1609        .iter()
1610        .filter_map(|name| {
1611            let values: Vec<&str> = headers
1612                .get_all(*name)
1613                .iter()
1614                .filter_map(|value| value.to_str().ok())
1615                .collect();
1616            (!values.is_empty()).then(|| ((*name).to_owned(), values.join(", ")))
1617        })
1618        .collect()
1619}
1620
1621/// Apply the storage rules to a response's headers.
1622pub(crate) fn decide_storage(
1623    headers: &reqwest::header::HeaderMap,
1624    authenticated: bool,
1625    allow_authenticated: bool,
1626) -> Result<(), NotStored> {
1627    let lines: Vec<&str> = headers
1628        .get_all(CACHE_CONTROL)
1629        .iter()
1630        .filter_map(|value| value.to_str().ok())
1631        .collect();
1632    storage_decision(
1633        200,
1634        &CacheControl::parse(&lines),
1635        header_str(headers, VARY),
1636        authenticated,
1637        allow_authenticated,
1638    )
1639}
1640
1641/// Take validators and cache directives from a `304` into the stored entry.
1642fn merge_validated_headers(meta: &mut CacheEntryMeta, headers: &reqwest::header::HeaderMap) {
1643    for (name, value) in storable_headers(headers) {
1644        if matches!(
1645            name.as_str(),
1646            "etag" | "last-modified" | "cache-control" | "vary"
1647        ) && libtea_core::http_cache::is_storable_header(&name, &value)
1648        {
1649            meta.headers.retain(|(existing, _)| existing != &name);
1650            meta.headers.push((name, value));
1651        }
1652    }
1653}
1654
1655/// A `200` response rebuilt from a cache entry.
1656fn raw_from_entry(url: &Url, meta: &CacheEntryMeta, body: Vec<u8>) -> RawResponse {
1657    let mut headers = reqwest::header::HeaderMap::new();
1658    for (name, value) in &meta.headers {
1659        if let (Ok(name), Ok(value)) = (
1660            reqwest::header::HeaderName::from_bytes(name.as_bytes()),
1661            reqwest::header::HeaderValue::from_str(value),
1662        ) {
1663            headers.append(name, value);
1664        }
1665    }
1666    RawResponse {
1667        status: StatusCode::OK,
1668        headers,
1669        body: Bytes::from(body),
1670        final_url: url.clone(),
1671        content_decoded: meta.decoded,
1672        pending_cache: None,
1673        from_cache: None,
1674        presented_bearer: None,
1675    }
1676}
1677
1678pub(crate) fn header_str(
1679    headers: &reqwest::header::HeaderMap,
1680    name: reqwest::header::HeaderName,
1681) -> Option<&str> {
1682    headers.get(name).and_then(|value| value.to_str().ok())
1683}
1684
1685pub(crate) fn map_api_error(response: &RawResponse) -> ClientError {
1686    if response.status == StatusCode::FORBIDDEN {
1687        return ClientError::Forbidden;
1688    }
1689    let content_type = header_str(&response.headers, CONTENT_TYPE);
1690    let tea = tea_error_code(content_type, &response.body);
1691    let message = if tea.is_some() {
1692        serde_json::from_slice::<TeaErrorBody>(&response.body)
1693            .ok()
1694            .and_then(|body| body.message)
1695    } else {
1696        None
1697    };
1698    // Server text: escape control characters before it reaches an error value.
1699    ClientError::Api {
1700        status: response.status.as_u16(),
1701        tea_error: tea.map(|code| libtea_core::escape_control_chars(&code)),
1702        message: message.map(|text| libtea_core::escape_control_chars(&text)),
1703    }
1704}
1705
1706pub(crate) fn operation_url(
1707    prefix: &Url,
1708    path: &str,
1709    query: &[(&str, &str)],
1710) -> Result<Url, ClientError> {
1711    let mut url = prefix.join(path.trim_start_matches('/')).map_err(|_| {
1712        ClientError::Model(libtea_core::ModelError::Invalid("operation URL".into()))
1713    })?;
1714    if !query.is_empty() {
1715        let mut pairs = url.query_pairs_mut();
1716        pairs.clear();
1717        for (name, value) in query {
1718            pairs.append_pair(name, value);
1719        }
1720    }
1721    Ok(url)
1722}
1723
1724pub(crate) use reqwest::header::CONTENT_TYPE as CONTENT_TYPE_HEADER;
1725
1726/// Log and error text must not keep query values (tokens, signed URLs, filters).
1727pub(crate) fn redact_url_for_log(url: &Url) -> String {
1728    let mut safe = url.clone();
1729    let _ = safe.set_username("");
1730    let _ = safe.set_password(None);
1731    safe.set_fragment(None);
1732    if url.query().is_none() {
1733        return safe.to_string();
1734    }
1735    let keys: Vec<String> = url.query_pairs().map(|(k, _)| k.into_owned()).collect();
1736    {
1737        let mut pairs = safe.query_pairs_mut();
1738        pairs.clear();
1739        for key in keys {
1740            pairs.append_pair(&key, "redacted");
1741        }
1742    }
1743    safe.to_string()
1744}
1745
1746/// Sanitize free-form transport error text.
1747///
1748/// Structured URL removal happens in [`ClientError::transport`] via
1749/// `reqwest::Error::without_url`. This helper only rewrites residual absolute
1750/// HTTP(S) spans. Each span is the full whitespace-bounded token starting at
1751/// the scheme. That token is rewritten with [`redact_url_for_log`] only when
1752/// `Url::parse` accepts the entire token. Otherwise the whole message becomes
1753/// a generic `"request failed"` — partial rewrites must not leave query-value
1754/// fragments (for example after a quote bound or after trimming `!`).
1755pub(crate) fn sanitize_transport_text(text: &str) -> String {
1756    match try_redact_sensitive_text(text) {
1757        Some(redacted) => redacted,
1758        None => "request failed".into(),
1759    }
1760}
1761
1762/// Rewrite residual absolute HTTP(S) URLs, or `None` when a span is ambiguous.
1763pub(crate) fn try_redact_sensitive_text(text: &str) -> Option<String> {
1764    let mut output = String::with_capacity(text.len());
1765    let mut rest = text;
1766    while let Some(start) = next_url_start(rest) {
1767        output.push_str(&rest[..start]);
1768        let after = &rest[start..];
1769        let end = after.find(char::is_whitespace).unwrap_or(after.len());
1770        let token = &after[..end];
1771        match Url::parse(token) {
1772            Ok(url) if url.scheme() == "http" || url.scheme() == "https" => {
1773                output.push_str(&redact_url_for_log(&url));
1774                rest = &after[end..];
1775            }
1776            _ => return None,
1777        }
1778    }
1779    output.push_str(rest);
1780    Some(output)
1781}
1782
1783fn next_url_start(text: &str) -> Option<usize> {
1784    match (text.find("http://"), text.find("https://")) {
1785        (Some(a), Some(b)) => Some(a.min(b)),
1786        (Some(a), None) => Some(a),
1787        (None, Some(b)) => Some(b),
1788        (None, None) => None,
1789    }
1790}
1791
1792#[cfg(test)]
1793mod token_expiry_tests {
1794    use std::time::{Duration, Instant};
1795
1796    use super::token_expires_at;
1797
1798    #[test]
1799    fn expiry_margin_does_not_consume_a_short_lifetime() {
1800        let now = Instant::now();
1801        assert_eq!(token_expires_at(None, now), None);
1802        assert_eq!(token_expires_at(Some(0), now), Some(now));
1803        assert_eq!(
1804            token_expires_at(Some(4), now),
1805            Some(now + Duration::from_secs(4))
1806        );
1807        assert_eq!(
1808            token_expires_at(Some(5), now),
1809            Some(now + Duration::from_secs(5))
1810        );
1811        assert_eq!(
1812            token_expires_at(Some(3600), now),
1813            Some(now + Duration::from_secs(3595))
1814        );
1815        assert_eq!(token_expires_at(Some(u64::MAX), now), None);
1816    }
1817}
1818
1819#[cfg(test)]
1820mod url_redaction_tests {
1821    use super::{redact_url_for_log, sanitize_transport_text, try_redact_sensitive_text};
1822    use url::Url;
1823
1824    #[test]
1825    fn query_values_are_redacted_and_keys_remain() {
1826        let url = Url::parse(
1827            "https://tea.example/v1.0.0/artifact/x/latest/download?mediaType=application%2Fjson&pageToken=secret-token",
1828        )
1829        .unwrap();
1830        let redacted = redact_url_for_log(&url);
1831        assert!(redacted.contains("mediaType=redacted"));
1832        assert!(redacted.contains("pageToken=redacted"));
1833        assert!(!redacted.contains("secret-token"));
1834        assert!(!redacted.contains("application/json"));
1835        assert!(!redacted.contains("application%2Fjson"));
1836    }
1837
1838    #[test]
1839    fn userinfo_is_stripped_from_logged_urls() {
1840        let url = Url::parse("https://user:pass@tea.example/v1.0.0/token?grant=secret").unwrap();
1841        let redacted = redact_url_for_log(&url);
1842        assert!(!redacted.contains("user"));
1843        assert!(!redacted.contains("pass"));
1844        assert!(redacted.contains("grant=redacted"));
1845        assert!(redacted.starts_with("https://tea.example/"));
1846    }
1847
1848    #[test]
1849    fn urls_without_query_are_unchanged_aside_from_userinfo() {
1850        let url = Url::parse("https://tea.example/v1.0.0/products").unwrap();
1851        assert_eq!(
1852            redact_url_for_log(&url),
1853            "https://tea.example/v1.0.0/products"
1854        );
1855    }
1856
1857    #[test]
1858    fn embedded_urls_in_transport_text_are_redacted() {
1859        let text = "error downloading https://cdn.example/file?sig=abc123&Expires=99 (timeout)";
1860        let redacted = try_redact_sensitive_text(text).expect("whitespace-bounded URL");
1861        assert!(redacted.contains("sig=redacted"));
1862        assert!(redacted.contains("Expires=redacted"));
1863        assert!(!redacted.contains("abc123"));
1864        assert!(redacted.contains("(timeout)"));
1865    }
1866
1867    #[test]
1868    fn earliest_url_is_chosen_when_https_precedes_http() {
1869        // `find("http://").or_else(|| find("https://"))` would skip the leading
1870        // https URL and leave `t=two` in the unredacted prefix.
1871        let text = "fallback https://secure.example/b?t=two then http://plain.example/a?t=one";
1872        let redacted = try_redact_sensitive_text(text).expect("mixed schemes");
1873        assert!(redacted.contains("https://secure.example/b?t=redacted"));
1874        assert!(redacted.contains("http://plain.example/a?t=redacted"));
1875        assert!(!redacted.contains("t=one"));
1876        assert!(!redacted.contains("t=two"));
1877    }
1878
1879    #[test]
1880    fn trailing_punctuation_stays_inside_the_query_and_is_redacted() {
1881        // Sentence punctuation is not peeled off; it is part of the token/query.
1882        let text = "failed: https://cdn.example/item?token=secret.";
1883        let redacted = try_redact_sensitive_text(text).expect("period in query");
1884        assert!(redacted.contains("token=redacted"));
1885        assert!(!redacted.contains("secret"));
1886        assert!(!redacted.contains("secret."));
1887    }
1888
1889    #[test]
1890    fn quote_inside_query_does_not_leave_a_secret_suffix() {
1891        // Stopping at `"` used to emit: ...?sig=redacted"SECRET_SUFFIX
1892        let text = "https://cdn.example/a?sig=prefix\"SECRET_SUFFIX";
1893        let redacted = try_redact_sensitive_text(text).expect("quote in query");
1894        assert_eq!(redacted, "https://cdn.example/a?sig=redacted");
1895        assert!(!redacted.contains("SECRET_SUFFIX"));
1896        assert!(!redacted.contains("prefix"));
1897        assert!(!sanitize_transport_text(text).contains("SECRET_SUFFIX"));
1898    }
1899
1900    #[test]
1901    fn trailing_exclamation_marks_stay_in_the_query_and_are_redacted() {
1902        // Trimming `!` used to emit: ...?sig=redacted!!!
1903        let text = "https://cdn.example/a?sig=secret!!!";
1904        let redacted = try_redact_sensitive_text(text).expect("bang in query");
1905        assert_eq!(redacted, "https://cdn.example/a?sig=redacted");
1906        assert!(!redacted.contains('!'));
1907        assert!(!redacted.contains("secret"));
1908        assert!(!sanitize_transport_text(text).contains("secret"));
1909    }
1910
1911    #[test]
1912    fn commas_semicolons_and_parentheses_do_not_leak_query_secrets() {
1913        let text = concat!(
1914            "a=https://cdn.example/a?sig=comma-secret, ",
1915            "b=(https://cdn.example/b?sig=paren-secret); ",
1916            "c=https://cdn.example/c?sig=semi-secret; trailing"
1917        );
1918        let redacted = try_redact_sensitive_text(text).expect("punctuation in query");
1919        assert!(!redacted.contains("comma-secret"));
1920        assert!(!redacted.contains("paren-secret"));
1921        assert!(!redacted.contains("semi-secret"));
1922        assert_eq!(redacted.matches("sig=redacted").count(), 3);
1923        assert!(redacted.contains("trailing"));
1924    }
1925
1926    #[test]
1927    fn fragments_are_stripped_and_query_secrets_are_redacted() {
1928        let url = Url::parse("https://cdn.example/item?token=frag-secret#section-name").unwrap();
1929        let redacted = redact_url_for_log(&url);
1930        assert!(redacted.contains("token=redacted"));
1931        assert!(!redacted.contains("frag-secret"));
1932        assert!(!redacted.contains("section-name"));
1933        assert!(!redacted.contains('#'));
1934
1935        let text = "see https://cdn.example/item?token=frag-secret#section-name please";
1936        let embedded = try_redact_sensitive_text(text).expect("fragment token");
1937        assert!(!embedded.contains("frag-secret"));
1938        assert!(!embedded.contains("section-name"));
1939        assert!(embedded.contains("token=redacted"));
1940        assert!(embedded.ends_with(" please"));
1941    }
1942
1943    #[test]
1944    fn mixed_schemes_and_delimiters_redact_every_query_value() {
1945        let text = concat!(
1946            "https://one.example/x?a=one-secret, ",
1947            "http://two.example/y?b=two-secret; ",
1948            "(https://three.example/z?c=three-secret)."
1949        );
1950        let redacted = try_redact_sensitive_text(text).expect("mixed tokens");
1951        assert!(!redacted.contains("one-secret"));
1952        assert!(!redacted.contains("two-secret"));
1953        assert!(!redacted.contains("three-secret"));
1954        assert!(redacted.contains("https://one.example/x?a=redacted"));
1955        assert!(redacted.contains("http://two.example/y?b=redacted"));
1956        assert!(redacted.contains("https://three.example/z?c=redacted"));
1957    }
1958
1959    /// The redaction and challenge parsers slice `str` by byte offsets from
1960    /// `find`; every combination of multi-byte and delimiter pieces must stay
1961    /// on character boundaries.
1962    #[test]
1963    fn text_helpers_do_not_panic_on_unicode() {
1964        const PIECES: [&str; 14] = [
1965            "http://",
1966            "https://",
1967            "a",
1968            "?",
1969            "=",
1970            "&",
1971            " ",
1972            ",",
1973            "\"",
1974            "\u{e9}",
1975            "\u{20ac}",
1976            "\u{1f600}",
1977            "\u{2003}",
1978            "%",
1979        ];
1980        let mut inputs = vec![String::new()];
1981        for _ in 0..4 {
1982            let mut next = Vec::new();
1983            for prefix in &inputs {
1984                for piece in PIECES {
1985                    next.push(format!("{prefix}{piece}"));
1986                }
1987            }
1988            inputs.extend(next);
1989            inputs.dedup();
1990        }
1991        for text in &inputs {
1992            let _ = sanitize_transport_text(text);
1993            let _ = try_redact_sensitive_text(text);
1994            let _ = super::challenge_error(text);
1995            let _ = super::is_bearer_challenge(text);
1996            if let Ok(url) = Url::parse(text) {
1997                let _ = redact_url_for_log(&url);
1998            }
1999        }
2000        assert!(inputs.len() > 10_000);
2001    }
2002
2003    #[test]
2004    fn ambiguous_residual_url_falls_back_to_a_generic_message() {
2005        // A scheme match whose whitespace token is not a parseable absolute URL
2006        // must not be partially rewritten.
2007        let text = "broken http://";
2008        assert!(try_redact_sensitive_text(text).is_none());
2009        assert_eq!(sanitize_transport_text(text), "request failed");
2010    }
2011}
2012
2013#[cfg(test)]
2014mod refresh_slot_tests {
2015    use std::time::Duration;
2016
2017    use super::{ApiKey, ClientBuilder, ClientError};
2018    use url::Url;
2019
2020    fn slot_count(client: &crate::Client) -> usize {
2021        client
2022            .inner
2023            .token_refresh
2024            .lock()
2025            .unwrap_or_else(|err| err.into_inner())
2026            .len()
2027    }
2028
2029    /// Many distinct origins must not leave one lock entry each behind.
2030    #[tokio::test]
2031    async fn refresh_slots_do_not_grow_with_origin_churn() {
2032        let client = ClientBuilder::new()
2033            .api_key(ApiKey::new("id", "secret"))
2034            .build()
2035            .unwrap();
2036        for index in 0..500 {
2037            let prefix = Url::parse(&format!("https://h{index}.example/v1.0.0/")).unwrap();
2038            // Not an authorized origin, so the exchange fails before any I/O.
2039            let error = client
2040                .inner
2041                .refresh_token_coalesced(&prefix, None)
2042                .await
2043                .unwrap_err();
2044            assert!(matches!(error, ClientError::AuthenticationRequired));
2045        }
2046        assert_eq!(slot_count(&client), 0);
2047    }
2048
2049    /// A refresh that is cancelled mid-exchange removes its entry too.
2050    #[tokio::test]
2051    async fn a_cancelled_refresh_leaves_no_slot() {
2052        // Accepts connections and never answers.
2053        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
2054        let address = listener.local_addr().unwrap();
2055        let hold = tokio::spawn(async move {
2056            let mut open = Vec::new();
2057            while let Ok((socket, _)) = listener.accept().await {
2058                open.push(socket);
2059            }
2060        });
2061        let origin = Url::parse(&format!("http://{address}")).unwrap();
2062        let client = ClientBuilder::new()
2063            .api_key(ApiKey::new("id", "secret"))
2064            .destination_policy(libtea_core::DestinationPolicy::allow_origin(&origin).unwrap())
2065            .build()
2066            .unwrap();
2067        let prefix = origin.join("v1.0.0/").unwrap();
2068        client.authorize_origin(&prefix).unwrap();
2069        let inner = std::sync::Arc::clone(&client.inner);
2070        let task = tokio::spawn(async move {
2071            let _ = inner.refresh_token_coalesced(&prefix, None).await;
2072        });
2073        tokio::time::sleep(Duration::from_millis(200)).await;
2074        assert_eq!(slot_count(&client), 1, "the exchange is in flight");
2075        task.abort();
2076        let _ = task.await;
2077        assert_eq!(slot_count(&client), 0);
2078        hold.abort();
2079    }
2080}