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