Skip to main content

libtea_client/
lib.rs

1//! Async consumer client for the Transparency Exchange API 1.0.0.
2//!
3//! **Independent implementation.** Not an official CycloneDX project release.
4//! Not a conformance certificate. Checksum
5//! [`libtea_core::IntegrityOutcome::Verified`] means declared digests matched
6//! **decoded** artifact bytes only — it is **not** publisher authenticity and
7//! not cryptographic signature verification. See [`signature`].
8//!
9//! Transport uses rustls. Certificate verification stays enabled. Discovery
10//! and artifact URLs are checked against [`libtea_core::DestinationPolicy`] before each
11//! connection, including addresses returned by DNS.
12//!
13//! **Proxies:** `HTTP_PROXY` / `HTTPS_PROXY` / `ALL_PROXY` (and lowercase forms)
14//! are honored by default. Through a proxy the DNS-based destination checks
15//! are **not** enforced, because the proxy, not this client, resolves the
16//! hostname; scheme, userinfo, literal-IP, and redirect checks still apply.
17//! [`ClientBuilder::ignore_env_proxies`] connects directly and keeps the DNS
18//! checks.
19//!
20//! **Weak checksums:** a match on SHA-1 checksums only is
21//! [`libtea_core::IntegrityOutcome::Weak`] and the download fails with
22//! [`ClientError::Integrity`], unless [`ClientBuilder::allow_weak_checksums`]
23//! is set.
24//!
25//! Token refresh is single-flight per origin on a [`Client`]: one async lock
26//! per API origin serializes `POST /token` for that origin; other origins do
27//! not wait for it. For a same-origin burst of resource `401`s with no usable
28//! cached bearer, waiters coalesce to **one** `POST /token`: they reuse the
29//! stored bearer after a success, and waiters that queued during a failed
30//! exchange return its failure. A waiter that finds a just-stored token
31//! already expired (very short lifetime) exchanges again. `POST /token` is
32//! bounded by [`Limits::request_timeout`]. This is a per-burst bound, not a
33//! process-wide exactly-once guarantee (see `docs/auth.md`).
34
35//!
36//! The crate README follows; its Rust snippets are compiled as doctests.
37//!
38#![doc = include_str!("../README.md")]
39#![forbid(unsafe_code)]
40
41mod cache;
42mod download;
43mod error;
44pub mod page_stream;
45mod service;
46pub mod signature;
47mod transport;
48
49// `url::Url` appears in `ClientBuilder::well_known_fetch_url`; see the semver note in `libtea-core`.
50pub use url;
51
52pub use cache::{cache_clear, cache_stat, CacheConfig, CacheStats};
53pub use download::{FileDownload, FileDownloadOptions, StreamedDownload};
54pub use error::ClientError;
55pub use page_stream::{follow_pages, FollowedPage, PageFollowLimits, PageFollowStop};
56pub use service::{ArtifactFetch, CleFetch, DownloadedArtifact, Service, SignatureFetch};
57pub use signature::{SignatureVerifier, SignatureVerifyOutcome};
58pub use transport::{ApiKey, Client, ClientBuilder, Limits};
59
60use libtea_core::{tea_error_code, DiscoveryInfo, ProductReleaseId, Tei, WellKnownDocument};
61use url::Url;
62
63use crate::transport::{header_str, map_api_error, operation_url, Call, CONTENT_TYPE_HEADER};
64
65impl ResolvedRelease {
66    /// Build a resolved release, for example from a cached discovery result.
67    #[must_use]
68    pub fn new(
69        product_release: ProductReleaseId,
70        root_url: impl Into<String>,
71        api_version: impl Into<String>,
72    ) -> Self {
73        Self {
74            product_release,
75            root_url: root_url.into(),
76            api_version: api_version.into(),
77        }
78    }
79}
80
81/// A product release selected from `/discovery`, with the server and version to call next.
82#[derive(Debug, Clone, PartialEq, Eq)]
83#[non_exhaustive]
84pub struct ResolvedRelease {
85    /// Product release UUID.
86    pub product_release: ProductReleaseId,
87    /// API root without a version prefix.
88    pub root_url: String,
89    /// Exact advertised version string.
90    pub api_version: String,
91}
92
93impl Client {
94    /// Resolve a TEI through `.well-known/tea` and `/discovery`.
95    ///
96    /// A TEA 404 from `/discovery` stops the search and returns
97    /// [`ClientError::Unresolved`]. It is not treated as a missing route and
98    /// it is not evidence that no updates exist. `401` and `403` do not fail
99    /// over to another endpoint.
100    ///
101    /// # Errors
102    ///
103    /// Returns an error when the TEI cannot be resolved or discovery attempts
104    /// are exhausted.
105    pub async fn discover(&self, tei: &Tei) -> Result<Vec<ResolvedRelease>, ClientError> {
106        let mut attempts = 0u32;
107        let well_known_url = match &self.inner.well_known_override {
108            Some(url) => url.clone(),
109            None => Url::parse(&tei.well_known_url()).map_err(|_| {
110                ClientError::Model(libtea_core::ModelError::Invalid(
111                    "well-known URL is not valid".into(),
112                ))
113            })?,
114        };
115        attempts += 1;
116        let document = match self.fetch_well_known(&well_known_url).await {
117            Ok(document) => document,
118            Err(error) => {
119                tracing::debug!(attempts, "well-known discovery failed");
120                return Err(match error {
121                    ClientError::Transport(_) | ClientError::Timeout | ClientError::TooLarge => {
122                        ClientError::DiscoveryFailed {
123                            stage: "well-known",
124                            attempts,
125                        }
126                    }
127                    other => other,
128                });
129            }
130        };
131        let candidates = document.select(&self.inner.supported)?;
132        let mut last_stage_error = ClientError::DiscoveryFailed {
133            stage: "api",
134            attempts,
135        };
136        for candidate in candidates {
137            if attempts >= self.inner.limits.max_discovery_attempts {
138                return Err(ClientError::DiscoveryFailed {
139                    stage: "api",
140                    attempts,
141                });
142            }
143            attempts += 1;
144            let root = Url::parse(&candidate.root_url).map_err(|_| {
145                ClientError::Model(libtea_core::ModelError::Invalid(
146                    "discovery root URL".into(),
147                ))
148            })?;
149            self.inner.policy.check_url(&root)?;
150            if self.inner.allow_discovered_credentials {
151                self.authorize_origin(&root)?;
152            }
153            let prefix = Url::parse(&libtea_core::versioned_api_prefix(
154                root.as_str().trim_end_matches('/'),
155                &candidate.version,
156            )?)
157            .map_err(|_| {
158                ClientError::Model(libtea_core::ModelError::Invalid(
159                    "versioned discovery URL".into(),
160                ))
161            })?;
162            let discovery_url = operation_url(&prefix, "discovery", &[("tei", tei.as_str())])?;
163            let response = self
164                .inner
165                .send(Call {
166                    method: reqwest::Method::GET,
167                    url: discovery_url,
168                    api_prefix: Some(prefix.clone()),
169                    artifact: false,
170                    body: None,
171                    content_type: None,
172                    basic_auth: false,
173                    if_none_match: None,
174                    if_modified_since: None,
175                    max_body: self.inner.limits.max_json_bytes,
176                })
177                .await;
178            let response = match response {
179                Ok(response) => response,
180                Err(
181                    error @ (ClientError::AuthenticationRequired
182                    | ClientError::Forbidden
183                    | ClientError::Token { .. }),
184                ) => return Err(error),
185                Err(error) => {
186                    last_stage_error = error;
187                    self.inner.backoff(attempts).await;
188                    continue;
189                }
190            };
191            if response.status.as_u16() == 401 || response.status.as_u16() == 403 {
192                return Err(map_api_error(&response));
193            }
194            if response.status.as_u16() == 404 {
195                if let Some(error) = tea_error_code(
196                    header_str(&response.headers, CONTENT_TYPE_HEADER),
197                    &response.body,
198                ) {
199                    let message = libtea_core::TeaErrorBody::parse(&response.body)
200                        .ok()
201                        .and_then(|body| body.message);
202                    return Err(ClientError::Unresolved {
203                        error: libtea_core::escape_control_chars(&error),
204                        message: message.map(|text| libtea_core::escape_control_chars(&text)),
205                    });
206                }
207                last_stage_error = map_api_error(&response);
208                self.inner.backoff(attempts).await;
209                continue;
210            }
211            if !response.status.is_success() {
212                last_stage_error = map_api_error(&response);
213                self.inner.backoff(attempts).await;
214                continue;
215            }
216            let parsed = if self.inner.supported.is_lenient() {
217                DiscoveryInfo::parse_list_lenient(&response.body)
218            } else {
219                DiscoveryInfo::parse_list(&response.body)
220            };
221            let releases = match parsed {
222                Ok(releases) => releases,
223                Err(error) => {
224                    last_stage_error = ClientError::Model(error);
225                    self.inner.backoff(attempts).await;
226                    continue;
227                }
228            };
229            let mut resolved = Vec::with_capacity(releases.len());
230            for release in releases {
231                let server = release.select_server(&self.inner.supported)?;
232                let chosen = server.into_iter().next().ok_or_else(|| {
233                    ClientError::Model(libtea_core::ModelError::Invalid(
234                        "discovery returned no usable server".into(),
235                    ))
236                })?;
237                resolved.push(ResolvedRelease {
238                    product_release: release.product_release,
239                    root_url: chosen.root_url,
240                    api_version: chosen.version,
241                });
242            }
243            return Ok(resolved);
244        }
245        Err(last_stage_error)
246    }
247
248    /// Open a service for a resolved release.
249    ///
250    /// # Errors
251    ///
252    /// Returns an error when the selected base URL is not allowed.
253    pub fn open(&self, release: &ResolvedRelease) -> Result<Service, ClientError> {
254        self.service(&release.root_url, &release.api_version)
255    }
256
257    async fn fetch_well_known(&self, url: &Url) -> Result<WellKnownDocument, ClientError> {
258        self.inner.policy.check_url(url)?;
259        let response = self
260            .inner
261            .send(Call {
262                method: reqwest::Method::GET,
263                url: url.clone(),
264                api_prefix: None,
265                artifact: false,
266                body: None,
267                content_type: None,
268                basic_auth: false,
269                if_none_match: None,
270                if_modified_since: None,
271                max_body: self.inner.limits.max_discovery_bytes,
272            })
273            .await?;
274        if !response.status.is_success() {
275            return Err(map_api_error(&response));
276        }
277        Ok(if self.inner.supported.is_lenient() {
278            WellKnownDocument::parse_lenient(&response.body)?
279        } else {
280            WellKnownDocument::parse(&response.body)?
281        })
282    }
283}
284#[cfg(doctest)]
285mod non_exhaustive_guards;