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