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#![warn(missing_docs)]
41
42mod cache;
43mod download;
44mod error;
45pub mod page_stream;
46mod service;
47pub mod signature;
48mod transport;
49
50// `url::Url` appears in `ClientBuilder::well_known_fetch_url`; see the semver note in `libtea-core`.
51pub use url;
52
53/// The whole of `libtea-core` (types such as `Tei`, `ListParams`,
54/// `DestinationPolicy`), so a project that only uses this client needs no direct
55/// `libtea-core` dependency. It is the same crate: a type here is the type
56/// `libtea-core` exports, and this crate always uses the same `libtea-core`
57/// version as its own. A breaking release of `libtea-core` is a breaking release
58/// of this crate.
59///
60/// ```
61/// use libtea_client::core::Tei;
62///
63/// let tei = Tei::parse("tei://example.com/uuid/2ff3ae7c-8eab-4e0b-9b8b-1a0c4c4c1c2d").unwrap();
64/// // The same type `libtea-core` exports.
65/// let same: &libtea_core::Tei = &tei;
66/// assert_eq!(same, &tei);
67/// ```
68pub use libtea_core as core;
69
70pub use cache::{cache_clear, cache_stat, CacheConfig, CacheStats};
71pub use download::{FileDownload, FileDownloadOptions, StreamedDownload};
72pub use error::ClientError;
73pub use page_stream::{follow_pages, FollowedPage, PageFollowLimits, PageFollowStop};
74pub use service::{ArtifactFetch, CleFetch, DownloadedArtifact, Service, SignatureFetch};
75pub use signature::{
76    detect_signature_format, FormatOnlyVerifier, SignatureFormat, SignatureVerifier,
77    SignatureVerifyOutcome,
78};
79pub use transport::{ApiKey, Client, ClientBuilder, Limits};
80
81use libtea_core::{tea_error_code, DiscoveryInfo, ProductReleaseId, Tei, WellKnownDocument};
82use url::Url;
83
84use crate::transport::{header_str, map_api_error, operation_url, Call, CONTENT_TYPE_HEADER};
85
86impl ResolvedRelease {
87    /// Build a resolved release, for example from a cached discovery result.
88    #[must_use]
89    pub fn new(
90        product_release: ProductReleaseId,
91        root_url: impl Into<String>,
92        api_version: impl Into<String>,
93    ) -> Self {
94        Self {
95            product_release,
96            root_url: root_url.into(),
97            api_version: api_version.into(),
98        }
99    }
100}
101
102/// A product release selected from `/discovery`, with the server and version to call next.
103#[derive(Debug, Clone, PartialEq, Eq)]
104#[non_exhaustive]
105pub struct ResolvedRelease {
106    /// Product release UUID.
107    pub product_release: ProductReleaseId,
108    /// API root without a version prefix.
109    pub root_url: String,
110    /// Exact advertised version string.
111    pub api_version: String,
112}
113
114impl Client {
115    /// Resolve a TEI through `.well-known/tea` and `/discovery`.
116    ///
117    /// A TEA 404 from `/discovery` stops the search and returns
118    /// [`ClientError::Unresolved`]. It is not treated as a missing route and
119    /// it is not evidence that no updates exist. `401` and `403` do not fail
120    /// over to another endpoint.
121    ///
122    /// # Errors
123    ///
124    /// Returns an error when the TEI cannot be resolved or discovery attempts
125    /// are exhausted.
126    pub async fn discover(&self, tei: &Tei) -> Result<Vec<ResolvedRelease>, ClientError> {
127        let mut attempts = 0u32;
128        let well_known_url = match &self.inner.well_known_override {
129            Some(url) => url.clone(),
130            None => Url::parse(&tei.well_known_url()).map_err(|_| {
131                ClientError::Model(libtea_core::ModelError::Invalid(
132                    "well-known URL is not valid".into(),
133                ))
134            })?,
135        };
136        attempts += 1;
137        let document = match self.fetch_well_known(&well_known_url).await {
138            Ok(document) => document,
139            Err(error) => {
140                tracing::debug!(attempts, "well-known discovery failed");
141                return Err(match error {
142                    ClientError::Transport(_) | ClientError::Timeout | ClientError::TooLarge => {
143                        ClientError::DiscoveryFailed {
144                            stage: "well-known",
145                            attempts,
146                        }
147                    }
148                    other => other,
149                });
150            }
151        };
152        let candidates = document.select(&self.inner.supported)?;
153        let mut last_stage_error = ClientError::DiscoveryFailed {
154            stage: "api",
155            attempts,
156        };
157        for candidate in candidates {
158            if attempts >= self.inner.limits.max_discovery_attempts {
159                return Err(ClientError::DiscoveryFailed {
160                    stage: "api",
161                    attempts,
162                });
163            }
164            attempts += 1;
165            let root = Url::parse(&candidate.root_url).map_err(|_| {
166                ClientError::Model(libtea_core::ModelError::Invalid(
167                    "discovery root URL".into(),
168                ))
169            })?;
170            self.inner.policy.check_url(&root)?;
171            if self.inner.allow_discovered_credentials {
172                self.authorize_origin(&root)?;
173            }
174            let prefix = Url::parse(&libtea_core::versioned_api_prefix(
175                root.as_str().trim_end_matches('/'),
176                &candidate.version,
177            )?)
178            .map_err(|_| {
179                ClientError::Model(libtea_core::ModelError::Invalid(
180                    "versioned discovery URL".into(),
181                ))
182            })?;
183            let discovery_url = operation_url(&prefix, "discovery", &[("tei", tei.as_str())])?;
184            let response = self
185                .inner
186                .send(Call {
187                    method: reqwest::Method::GET,
188                    url: discovery_url,
189                    api_prefix: Some(prefix.clone()),
190                    artifact: false,
191                    body: None,
192                    content_type: None,
193                    basic_auth: false,
194                    if_none_match: None,
195                    if_modified_since: None,
196                    max_body: self.inner.limits.max_json_bytes,
197                })
198                .await;
199            let response = match response {
200                Ok(response) => response,
201                Err(
202                    error @ (ClientError::AuthenticationRequired
203                    | ClientError::Forbidden
204                    | ClientError::Token { .. }),
205                ) => return Err(error),
206                Err(error) => {
207                    last_stage_error = error;
208                    self.inner.backoff(attempts).await;
209                    continue;
210                }
211            };
212            if response.status.as_u16() == 401 || response.status.as_u16() == 403 {
213                return Err(map_api_error(&response));
214            }
215            if response.status.as_u16() == 404 {
216                if let Some(error) = tea_error_code(
217                    header_str(&response.headers, CONTENT_TYPE_HEADER),
218                    &response.body,
219                ) {
220                    let message = libtea_core::TeaErrorBody::parse(&response.body)
221                        .ok()
222                        .and_then(|body| body.message);
223                    return Err(ClientError::Unresolved {
224                        error: libtea_core::escape_control_chars(&error),
225                        message: message.map(|text| libtea_core::escape_control_chars(&text)),
226                    });
227                }
228                last_stage_error = map_api_error(&response);
229                self.inner.backoff(attempts).await;
230                continue;
231            }
232            if !response.status.is_success() {
233                last_stage_error = map_api_error(&response);
234                self.inner.backoff(attempts).await;
235                continue;
236            }
237            let parsed = if self.inner.supported.is_lenient() {
238                DiscoveryInfo::parse_list_lenient(&response.body)
239            } else {
240                DiscoveryInfo::parse_list(&response.body)
241            };
242            let releases = match parsed {
243                Ok(releases) => releases,
244                Err(error) => {
245                    last_stage_error = ClientError::Model(error);
246                    self.inner.backoff(attempts).await;
247                    continue;
248                }
249            };
250            let mut resolved = Vec::with_capacity(releases.len());
251            for release in releases {
252                let server = release.select_server(&self.inner.supported)?;
253                let chosen = server.into_iter().next().ok_or_else(|| {
254                    ClientError::Model(libtea_core::ModelError::Invalid(
255                        "discovery returned no usable server".into(),
256                    ))
257                })?;
258                resolved.push(ResolvedRelease {
259                    product_release: release.product_release,
260                    root_url: chosen.root_url,
261                    api_version: chosen.version,
262                });
263            }
264            return Ok(resolved);
265        }
266        Err(last_stage_error)
267    }
268
269    /// Open a service for a resolved release.
270    ///
271    /// # Errors
272    ///
273    /// Returns an error when the selected base URL is not allowed.
274    pub fn open(&self, release: &ResolvedRelease) -> Result<Service, ClientError> {
275        self.service(&release.root_url, &release.api_version)
276    }
277
278    async fn fetch_well_known(&self, url: &Url) -> Result<WellKnownDocument, ClientError> {
279        self.inner.policy.check_url(url)?;
280        let response = self
281            .inner
282            .send(Call {
283                method: reqwest::Method::GET,
284                url: url.clone(),
285                api_prefix: None,
286                artifact: false,
287                body: None,
288                content_type: None,
289                basic_auth: false,
290                if_none_match: None,
291                if_modified_since: None,
292                max_body: self.inner.limits.max_discovery_bytes,
293            })
294            .await?;
295        if !response.status.is_success() {
296            return Err(map_api_error(&response));
297        }
298        Ok(if self.inner.supported.is_lenient() {
299            WellKnownDocument::parse_lenient(&response.body)?
300        } else {
301            WellKnownDocument::parse(&response.body)?
302        })
303    }
304}
305#[cfg(doctest)]
306mod non_exhaustive_guards;