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