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