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