Skip to main content

libtea_core/
lib.rs

1//! Domain types and protocol rules for the Transparency Exchange API consumer.
2//!
3//! **Independent implementation.** Not an official CycloneDX project release.
4//! Not a conformance certificate. [`IntegrityOutcome::Verified`] means declared
5//! digests matched **decoded** artifact bytes only — it is **not** publisher
6//! authenticity and not cryptographic signature verification.
7//!
8//! This crate does not open network connections, read the filesystem, or depend
9//! on an async runtime. [`libtea_client`](https://docs.rs/libtea-client) performs HTTP.
10//!
11//! The pinned specification is TEA OpenAPI `1.0.0` from
12//! <https://github.com/CycloneDX/transparency-exchange-api> commit
13//! `962a0228af1bfcc1232ac3f79239317ff33fdb04`.
14//!
15//! The crate README follows; its Rust snippets run as doctests.
16//!
17#![doc = include_str!("../README.md")]
18#![forbid(unsafe_code)]
19#![warn(missing_docs)]
20
21pub mod checksum;
22pub mod discovery;
23pub mod enums;
24pub mod error;
25pub mod http_cache;
26pub mod ids;
27pub mod lifecycle;
28pub mod lock;
29pub mod model;
30pub mod pep440;
31pub mod policy;
32pub mod purl;
33pub mod signature_format;
34pub mod tei;
35pub mod vers;
36pub mod version;
37
38// Third-party crates whose types appear in this crate's public API. Re-exported
39// so callers name the exact version this crate was built against; a major
40// version bump of any of them is a breaking change of `libtea-core`.
41pub use semver;
42pub use url;
43pub use uuid;
44
45pub use checksum::{
46    verify_checksums, verify_checksums_with_policy, Checksum, ChecksumCheck, ChecksumPolicy,
47    ChecksumVerifier, IntegrityOutcome, IntegrityReport,
48};
49pub use discovery::{is_json_content_type, tea_error_code, DiscoveryInfo, WellKnownDocument};
50pub use enums::{ChecksumAlgorithm, SortOrder};
51pub use error::{escape_control_chars, ModelError, PolicyError, TeiError};
52pub use ids::{
53    ArtifactId, CollectionId, ComponentId, ComponentReleaseId, DistributionId, ProductId,
54    ProductReleaseId, TeaTimestamp, TeaUuid,
55};
56pub use lifecycle::{LifecycleStatus, Unevaluated};
57pub use lock::{
58    diff as diff_locks, ChangedArtifact, FieldChange, LockDiff, LockFile, LockedArtifact,
59    LockedChecksum, LockedIntegrity, LOCK_SCHEMA_VERSION,
60};
61pub use model::{
62    parse_artifact, parse_collection, parse_component_release, parse_product_release, Artifact,
63    ArtifactFormat, Cle, Collection, Component, ComponentRef, ComponentRelease,
64    ComponentReleaseWithCollection, Identifier, Page, Product, ProductRelease,
65    ProductReleaseWithCollection, TeaErrorBody, TokenResponse,
66};
67pub use pep440::{Pep440Error, Pep440Version};
68pub use policy::{classify_ip, origin_key, parse_api_base, DestinationPolicy, IpClass};
69pub use purl::{same_package_url, CanonicalPurl, Purl, PurlError, PurlRules, PurlTypeError};
70pub use signature_format::{detect_signature_format, SignatureFormat};
71pub use tei::{encode_query_component, Tei};
72pub use version::{
73    select_endpoints, versioned_api_prefix, ApiVersion, SelectedEndpoint, SupportedApi,
74};
75
76/// Pinned TEA specification identity.
77pub mod spec {
78    /// Primary specification repository.
79    pub const REPOSITORY: &str = "https://github.com/CycloneDX/transparency-exchange-api";
80    /// Branch that was audited.
81    pub const BRANCH: &str = "main";
82    /// Commit SHA of the audited revision.
83    pub const COMMIT: &str = "962a0228af1bfcc1232ac3f79239317ff33fdb04";
84    /// Committer date of that commit.
85    pub const COMMIT_DATE: &str = "2026-10-08T06:28:26Z";
86    /// Retrieval date used for this SDK.
87    pub const RETRIEVAL_DATE: &str = "2026-10-10";
88    /// `info.version` of the OpenAPI document.
89    pub const SPEC_VERSION: &str = "1.0.0";
90    /// OpenAPI version of that document.
91    pub const OPENAPI_VERSION: &str = "3.1.1";
92}
93
94/// Query parameters shared by list operations.
95///
96/// [`Default`] leaves every field unset. The request then carries no list
97/// query parameters, and the server applies its own page size and sort. `S`
98/// does not need to implement [`Default`], so this works for [`enums::ComponentSort`]
99/// and the other built-in sort enums.
100///
101/// # Continuing a page
102///
103/// Keep the same [`ListParams`] value and replace only [`page_token`](Self::page_token)
104/// with [`Page::next_page_token`](crate::Page::next_page_token). That preserves
105/// `pageSize`, sort fields, and identifier filters. Building a new value that
106/// sets only the token drops those fields and can change the result set.
107///
108/// Callers must detect pagination anomalies themselves (empty intermediate pages,
109/// repeated tokens, missing tokens when `has_next` is true, or server errors).
110/// This crate does not auto-paginate and does not break loops on a repeated token.
111///
112/// ```ignore
113/// let mut query = ListParams::default()
114///     .with_page_size(1)
115///     .with_id_type(IdentifierType::Purl);
116/// let first = service.query_products(&query).await?;
117/// query.page_token = first.next_page_token.clone();
118/// let second = service.query_products(&query).await?;
119/// ```
120///
121/// The struct is `#[non_exhaustive]`: build it with [`ListParams::default`]
122/// and the `with_*` setters, or assign the public fields of a default value.
123#[derive(Debug, Clone, PartialEq, Eq)]
124#[non_exhaustive]
125pub struct ListParams<S> {
126    /// `pageSize`, from 1 to 100.
127    pub page_size: Option<u32>,
128    /// Opaque `pageToken` copied from the previous page.
129    pub page_token: Option<String>,
130    /// Resource-specific `sortField`.
131    pub sort_field: Option<S>,
132    /// `sortOrder`.
133    pub sort_order: Option<enums::SortOrder>,
134    /// `idType` filter.
135    ///
136    /// This may be sent without [`id_value`](Self::id_value). TEA 1.0 uses that
137    /// form for compliance-document discovery (`idType=COMPLIANCE_DOCUMENT`).
138    pub id_type: Option<enums::IdentifierType>,
139    /// `idValue` filter.
140    ///
141    /// Sent only together with [`id_type`](Self::id_type). This SDK rejects a
142    /// value with no type before the request. The pinned specification does
143    /// not settle that value-only case, so the rejection is not a claim that
144    /// TEA 1.0 forbids it.
145    pub id_value: Option<String>,
146}
147
148impl<S> Default for ListParams<S> {
149    fn default() -> Self {
150        Self {
151            page_size: None,
152            page_token: None,
153            sort_field: None,
154            sort_order: None,
155            id_type: None,
156            id_value: None,
157        }
158    }
159}
160
161impl<S> ListParams<S> {
162    /// Set `pageSize`.
163    #[must_use]
164    pub fn with_page_size(mut self, size: u32) -> Self {
165        self.page_size = Some(size);
166        self
167    }
168
169    /// Set the opaque `pageToken` from a previous page.
170    #[must_use]
171    pub fn with_page_token(mut self, token: impl Into<String>) -> Self {
172        self.page_token = Some(token.into());
173        self
174    }
175
176    /// Set `sortField`.
177    #[must_use]
178    pub fn with_sort_field(mut self, field: S) -> Self {
179        self.sort_field = Some(field);
180        self
181    }
182
183    /// Set `sortOrder`.
184    #[must_use]
185    pub fn with_sort_order(mut self, order: enums::SortOrder) -> Self {
186        self.sort_order = Some(order);
187        self
188    }
189
190    /// Set the `idType` filter.
191    #[must_use]
192    pub fn with_id_type(mut self, id_type: enums::IdentifierType) -> Self {
193        self.id_type = Some(id_type);
194        self
195    }
196
197    /// Set the `idValue` filter. Requires [`Self::with_id_type`] as well.
198    #[must_use]
199    pub fn with_id_value(mut self, id_value: impl Into<String>) -> Self {
200        self.id_value = Some(id_value.into());
201        self
202    }
203
204    /// Validate pagination bounds and identifier filters.
205    ///
206    /// `idType` alone is accepted. Both fields together are accepted. Neither
207    /// field is accepted. `idValue` without `idType` is rejected.
208    ///
209    /// # Errors
210    ///
211    /// Returns an error when `pageSize` is outside 1..=100 or `idValue` is set
212    /// without `idType`.
213    pub fn validate(&self) -> Result<(), ModelError> {
214        if let Some(size) = self.page_size {
215            if !(1..=100).contains(&size) {
216                return Err(ModelError::Invalid("pageSize must be from 1 to 100".into()));
217            }
218        }
219        if self.id_value.is_some() && self.id_type.is_none() {
220            return Err(ModelError::Invalid("idValue requires idType".into()));
221        }
222        Ok(())
223    }
224}
225
226#[cfg(doctest)]
227mod non_exhaustive_guards;
228
229#[cfg(test)]
230mod tests {
231    use super::ListParams;
232    use crate::enums::{ComponentSort, IdentifierType, SortOrder};
233
234    struct SortWithoutDefault;
235
236    fn params(id_type: Option<IdentifierType>, id_value: Option<&str>) -> ListParams<()> {
237        ListParams {
238            page_size: None,
239            page_token: None,
240            sort_field: None,
241            sort_order: None,
242            id_type,
243            id_value: id_value.map(str::to_owned),
244        }
245    }
246
247    #[test]
248    fn neither_identifier_field_is_accepted() {
249        assert!(params(None, None).validate().is_ok());
250    }
251
252    #[test]
253    fn both_identifier_fields_are_accepted() {
254        assert!(
255            params(Some(IdentifierType::Purl), Some("pkg:generic/widget@1"))
256                .validate()
257                .is_ok()
258        );
259    }
260
261    #[test]
262    fn id_type_without_id_value_is_accepted() {
263        assert!(params(Some(IdentifierType::ComplianceDocument), None)
264            .validate()
265            .is_ok());
266    }
267
268    #[test]
269    fn id_value_without_id_type_requires_id_type() {
270        let error = params(None, Some("pkg:generic/widget@1"))
271            .validate()
272            .unwrap_err();
273        assert_eq!(error.to_string(), "idValue requires idType");
274    }
275
276    #[test]
277    fn default_leaves_every_field_unset_without_a_default_sort() {
278        let query = ListParams::<SortWithoutDefault>::default();
279        assert!(query.page_size.is_none());
280        assert!(query.page_token.is_none());
281        assert!(query.sort_field.is_none());
282        assert!(query.sort_order.is_none());
283        assert!(query.id_type.is_none());
284        assert!(query.id_value.is_none());
285        assert!(query.validate().is_ok());
286
287        let components = ListParams::<ComponentSort>::default();
288        assert!(components.sort_field.is_none());
289        assert!(components.validate().is_ok());
290
291        let value_only = ListParams::<ComponentSort> {
292            id_value: Some("pkg:generic/widget@1".to_owned()),
293            ..ListParams::default()
294        };
295        assert_eq!(
296            value_only.validate().unwrap_err().to_string(),
297            "idValue requires idType"
298        );
299    }
300
301    #[test]
302    fn page_size_bounds_are_unchanged_for_a_type_only_filter() {
303        let mut query = params(Some(IdentifierType::ComplianceDocument), None);
304        query.page_size = Some(0);
305        query.sort_order = Some(SortOrder::Desc);
306        assert!(query.validate().is_err());
307        query.page_size = Some(101);
308        assert!(query.validate().is_err());
309        query.page_size = Some(1);
310        assert!(query.validate().is_ok());
311        query.page_size = Some(100);
312        assert!(query.validate().is_ok());
313    }
314}