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