Skip to main content

libtea_core/
model.rs

1//! TEA data model for the pinned OpenAPI 1.0.0 schemas.
2//!
3//! Composite objects ignore unknown JSON fields so a later revision can add
4//! properties without making existing ones unreadable. Fields whose schemas
5//! forbid additional properties (`error` recognition, discovery, well-known)
6//! are handled in the discovery module. Enumerations preserve unknown values.
7
8use serde::{Deserialize, Serialize};
9
10use crate::checksum::Checksum;
11use crate::enums::{
12    ArtifactType, CleEventType, CollectionOwner, CollectionUpdateReasonType,
13    ComplianceDocumentType, IdentifierType, TeaErrorCode,
14};
15use crate::error::ModelError;
16use crate::ids::{
17    ArtifactId, CollectionId, ComponentId, ComponentReleaseId, DistributionId, ProductId,
18    ProductReleaseId, TeaTimestamp,
19};
20
21/// An external identifier attached to a TEA object.
22#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
23#[serde(rename_all = "camelCase")]
24#[non_exhaustive]
25pub struct Identifier {
26    /// Identifier scheme.
27    pub id_type: IdentifierType,
28    /// Identifier value, retained as published.
29    pub id_value: String,
30}
31
32/// A TEA Product.
33#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
34#[serde(rename_all = "camelCase")]
35#[non_exhaustive]
36pub struct Product {
37    /// Product UUID.
38    pub uuid: ProductId,
39    /// Product name.
40    pub name: String,
41    /// Identifiers.
42    pub identifiers: Vec<Identifier>,
43}
44
45/// A component included by a product release.
46#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
47#[non_exhaustive]
48pub struct ComponentRef {
49    /// Component UUID.
50    pub uuid: ComponentId,
51    /// Optional fixed component release.
52    #[serde(default)]
53    pub release: Option<ComponentReleaseId>,
54}
55
56/// A TEA Product Release without its collection.
57#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
58#[serde(rename_all = "camelCase")]
59#[non_exhaustive]
60pub struct ProductRelease {
61    /// Product release UUID.
62    pub uuid: ProductReleaseId,
63    /// Parent product UUID.
64    pub product: ProductId,
65    /// Parent product name, when the server sends it.
66    #[serde(default)]
67    pub product_name: Option<String>,
68    /// Manufacturer version string. This is not SemVer.
69    pub version: String,
70    /// Creation time.
71    pub created_date: TeaTimestamp,
72    /// Release time, when present.
73    #[serde(default)]
74    pub release_date: Option<TeaTimestamp>,
75    /// Whether the release is a pre-release.
76    #[serde(default)]
77    pub pre_release: Option<bool>,
78    /// Identifiers.
79    #[serde(default)]
80    pub identifiers: Option<Vec<Identifier>>,
81    /// Components in this release.
82    pub components: Vec<ComponentRef>,
83}
84
85/// A product release and its latest collection.
86#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
87#[serde(rename_all = "camelCase")]
88#[non_exhaustive]
89pub struct ProductReleaseWithCollection {
90    /// Release fields.
91    #[serde(flatten)]
92    pub release: ProductRelease,
93    /// Latest collection.
94    pub latest_collection: Collection,
95}
96
97/// A TEA Component.
98#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
99#[serde(rename_all = "camelCase")]
100#[non_exhaustive]
101pub struct Component {
102    /// Component UUID.
103    pub uuid: ComponentId,
104    /// Component name.
105    pub name: String,
106    /// Identifiers.
107    pub identifiers: Vec<Identifier>,
108}
109
110/// One distribution of a component release.
111#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
112#[serde(rename_all = "camelCase")]
113#[non_exhaustive]
114pub struct ReleaseDistribution {
115    /// Distribution UUID.
116    pub distribution_id: DistributionId,
117    /// Description.
118    #[serde(default)]
119    pub description: Option<String>,
120    /// Identifiers.
121    #[serde(default)]
122    pub identifiers: Option<Vec<Identifier>>,
123    /// External download URL. A TEA access token is not sent here.
124    #[serde(default)]
125    pub url: Option<String>,
126    /// External signature URL. A TEA access token is not sent here.
127    #[serde(default)]
128    pub signature_url: Option<String>,
129    /// Checksums of the distribution bytes, not the signature.
130    #[serde(default)]
131    pub checksums: Option<Vec<Checksum>>,
132}
133
134/// A TEA Component Release without its collection.
135#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
136#[serde(rename_all = "camelCase")]
137#[non_exhaustive]
138pub struct ComponentRelease {
139    /// Component release UUID.
140    pub uuid: ComponentReleaseId,
141    /// Parent component UUID.
142    pub component: ComponentId,
143    /// Parent component name, when present.
144    #[serde(default)]
145    pub component_name: Option<String>,
146    /// Manufacturer version string.
147    pub version: String,
148    /// Creation time.
149    pub created_date: TeaTimestamp,
150    /// Release time, when present.
151    #[serde(default)]
152    pub release_date: Option<TeaTimestamp>,
153    /// Whether the release is a pre-release.
154    #[serde(default)]
155    pub pre_release: Option<bool>,
156    /// Identifiers.
157    #[serde(default)]
158    pub identifiers: Option<Vec<Identifier>>,
159    /// Distributions.
160    #[serde(default)]
161    pub distributions: Option<Vec<ReleaseDistribution>>,
162}
163
164/// A component release and its latest collection.
165#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
166#[serde(rename_all = "camelCase")]
167#[non_exhaustive]
168pub struct ComponentReleaseWithCollection {
169    /// Release fields.
170    #[serde(flatten)]
171    pub release: ComponentRelease,
172    /// Latest collection.
173    pub latest_collection: Collection,
174}
175
176/// Why a collection version was published.
177#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
178#[non_exhaustive]
179pub struct CollectionUpdateReason {
180    /// Update classification.
181    #[serde(rename = "type")]
182    pub reason_type: CollectionUpdateReasonType,
183    /// Free-text comment. Clients must not interpret this programmatically.
184    #[serde(default)]
185    pub comment: Option<String>,
186}
187
188/// One format of an artifact revision.
189#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
190#[serde(rename_all = "camelCase")]
191#[non_exhaustive]
192pub struct ArtifactFormat {
193    /// Media type. Unique within the revision.
194    pub media_type: String,
195    /// Description.
196    #[serde(default)]
197    pub description: Option<String>,
198    /// External content URL. When set, clients retrieve content from it.
199    #[serde(default)]
200    pub url: Option<String>,
201    /// External detached-signature URL.
202    #[serde(default)]
203    pub signature_url: Option<String>,
204    /// Checksums of the content bytes after HTTP content coding is removed.
205    #[serde(default)]
206    pub checksums: Option<Vec<Checksum>>,
207}
208
209impl ArtifactFormat {
210    /// Enforce `dependentRequired` for `url` and checksum shape.
211    ///
212    /// # Errors
213    ///
214    /// Returns an error when a format with `url` has no checksums, or checksums are empty.
215    pub fn validate(&self) -> Result<(), ModelError> {
216        if let Some(checksums) = &self.checksums {
217            if checksums.is_empty() {
218                return Err(ModelError::Invalid(
219                    "checksums, when present, must contain at least one entry".into(),
220                ));
221            }
222        }
223        if self.url.is_some() && self.checksums.as_ref().map(Vec::is_empty).unwrap_or(true) {
224            return Err(ModelError::Invalid(
225                "an artifact format with url must publish at least one checksum".into(),
226            ));
227        }
228        if self.media_type.is_empty() {
229            return Err(ModelError::Invalid("mediaType must not be empty".into()));
230        }
231        Ok(())
232    }
233}
234
235/// A TEA Artifact revision.
236#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
237#[serde(rename_all = "camelCase")]
238#[non_exhaustive]
239pub struct Artifact {
240    /// Artifact UUID.
241    pub uuid: ArtifactId,
242    /// Revision number, starting at 1.
243    pub version: u64,
244    /// Human-readable name.
245    #[serde(default)]
246    pub name: Option<String>,
247    /// Artifact type.
248    #[serde(rename = "type")]
249    pub artifact_type: ArtifactType,
250    /// Creation time of this revision.
251    pub created_date: TeaTimestamp,
252    /// Distributions this revision applies to. Absent means all distributions.
253    #[serde(default)]
254    pub distribution_ids: Option<Vec<DistributionId>>,
255    /// Available formats.
256    pub formats: Vec<ArtifactFormat>,
257}
258
259impl Artifact {
260    /// Validate revision, formats, and checksum requirements.
261    ///
262    /// # Errors
263    ///
264    /// Returns an error when the revision is outside the normative constraints.
265    pub fn validate(&self) -> Result<(), ModelError> {
266        if self.version < 1 {
267            return Err(ModelError::Invalid("artifact version starts at 1".into()));
268        }
269        if self.formats.is_empty() {
270            return Err(ModelError::Invalid(
271                "artifact formats must not be empty".into(),
272            ));
273        }
274        let mut seen = Vec::new();
275        for format in &self.formats {
276            format.validate()?;
277            if seen
278                .iter()
279                .any(|existing: &String| existing == &format.media_type)
280            {
281                return Err(ModelError::Invalid(format!(
282                    "mediaType `{}` is repeated in one artifact revision",
283                    format.media_type
284                )));
285            }
286            seen.push(format.media_type.clone());
287        }
288        Ok(())
289    }
290
291    /// Find a format by exact media type.
292    #[must_use]
293    pub fn format(&self, media_type: &str) -> Option<&ArtifactFormat> {
294        self.formats
295            .iter()
296            .find(|format| format.media_type == media_type)
297    }
298}
299
300/// A TEA Collection version.
301#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
302#[serde(rename_all = "camelCase")]
303#[non_exhaustive]
304pub struct Collection {
305    /// Collection UUID. Equal to the parent release UUID.
306    pub uuid: CollectionId,
307    /// Collection version, starting at 1.
308    pub version: u64,
309    /// Creation time of this collection version.
310    pub created_date: TeaTimestamp,
311    /// Parent object type.
312    pub belongs_to: CollectionOwner,
313    /// Why this version was published.
314    pub update_reason: CollectionUpdateReason,
315    /// Artifacts. Empty is valid for the initial collection version.
316    pub artifacts: Vec<Artifact>,
317}
318
319impl Collection {
320    /// Validate version and embedded artifacts.
321    ///
322    /// # Errors
323    ///
324    /// Returns an error when a collection or artifact constraint fails.
325    pub fn validate(&self) -> Result<(), ModelError> {
326        if self.version < 1 {
327            return Err(ModelError::Invalid("collection version starts at 1".into()));
328        }
329        for artifact in &self.artifacts {
330            artifact.validate()?;
331        }
332        Ok(())
333    }
334}
335
336/// A page of results.
337#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
338#[serde(rename_all = "camelCase")]
339#[non_exhaustive]
340pub struct Page<T> {
341    /// Whether another page exists.
342    pub has_next: bool,
343    /// Opaque continuation token. Clients copy it verbatim into the next request.
344    #[serde(default)]
345    pub next_page_token: Option<String>,
346    /// Page contents.
347    pub results: Vec<T>,
348}
349
350impl<T> Page<T> {
351    /// Build a page, for example in a test double or an adapter.
352    #[must_use]
353    pub fn new(results: Vec<T>, has_next: bool, next_page_token: Option<String>) -> Self {
354        Self {
355            has_next,
356            next_page_token,
357            results,
358        }
359    }
360}
361
362/// TEA error body.
363///
364/// Unknown `error` strings are preserved. Extra JSON properties are ignored so
365/// recognition matches the discovery document rather than failing closed on an
366/// additive field.
367#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
368#[non_exhaustive]
369pub struct TeaErrorBody {
370    /// Machine-readable error code.
371    pub error: TeaErrorCode,
372    /// Human-readable diagnostic text. Not a programmatic contract.
373    #[serde(default)]
374    pub message: Option<String>,
375}
376
377impl TeaErrorBody {
378    /// Parse a JSON error body.
379    ///
380    /// # Errors
381    ///
382    /// Returns an error when the body is not a TEA error object.
383    pub fn parse(bytes: &[u8]) -> Result<Self, ModelError> {
384        Ok(serde_json::from_slice(bytes)?)
385    }
386}
387
388/// OAuth token error body from `POST /token`.
389#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
390#[non_exhaustive]
391pub struct TokenErrorBody {
392    /// OAuth error code.
393    pub error: String,
394    /// Optional description.
395    #[serde(default)]
396    pub error_description: Option<String>,
397    /// Optional URI.
398    #[serde(default)]
399    pub error_uri: Option<String>,
400}
401
402/// Successful token response. The access token is opaque.
403#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
404#[non_exhaustive]
405pub struct TokenResponse {
406    /// Opaque access token.
407    pub access_token: String,
408    /// Must be `Bearer` for TEA resource access.
409    pub token_type: String,
410    /// Lifetime in seconds, when the server sends it.
411    #[serde(default)]
412    pub expires_in: Option<u64>,
413    /// Granted scope, when present.
414    #[serde(default)]
415    pub scope: Option<String>,
416}
417
418impl TokenResponse {
419    /// Reject a token type other than Bearer.
420    ///
421    /// # Errors
422    ///
423    /// Returns an error when `token_type` is not Bearer, ignoring case.
424    pub fn bearer(self) -> Result<Self, ModelError> {
425        if !self.token_type.eq_ignore_ascii_case("bearer") {
426            return Err(ModelError::Invalid(format!(
427                "token_type must be Bearer, got `{}`",
428                self.token_type
429            )));
430        }
431        if self.access_token.is_empty() {
432            return Err(ModelError::Invalid("access_token is empty".into()));
433        }
434        Ok(self)
435    }
436}
437
438/// CLE support definition.
439#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
440#[non_exhaustive]
441pub struct CleSupportDefinition {
442    /// Support identifier.
443    pub id: String,
444    /// Description.
445    pub description: String,
446    /// Optional URL.
447    #[serde(default)]
448    pub url: Option<String>,
449}
450
451/// CLE definition block.
452#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
453#[non_exhaustive]
454pub struct CleDefinitions {
455    /// Support definitions.
456    #[serde(default)]
457    pub support: Option<Vec<CleSupportDefinition>>,
458}
459
460/// One CLE event in the TEA projection.
461#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
462#[serde(rename_all = "camelCase")]
463#[non_exhaustive]
464pub struct CleEvent {
465    /// Event id.
466    pub id: i64,
467    /// Event type.
468    #[serde(rename = "type")]
469    pub event_type: CleEventType,
470    /// Effective time.
471    pub effective: TeaTimestamp,
472    /// Publication time.
473    pub published: TeaTimestamp,
474    /// Version.
475    #[serde(default)]
476    pub version: Option<String>,
477    /// Version specifiers.
478    #[serde(default)]
479    pub versions: Option<Vec<CleVersionSpecifier>>,
480    /// Support id.
481    #[serde(default)]
482    pub support_id: Option<String>,
483    /// License.
484    #[serde(default)]
485    pub license: Option<String>,
486    /// Superseding version.
487    #[serde(default)]
488    pub superseded_by_version: Option<String>,
489    /// Identifiers.
490    #[serde(default)]
491    pub identifiers: Option<Vec<Identifier>>,
492    /// Related event id.
493    #[serde(default)]
494    pub event_id: Option<i64>,
495    /// Reason.
496    #[serde(default)]
497    pub reason: Option<String>,
498    /// Description.
499    #[serde(default)]
500    pub description: Option<String>,
501    /// References.
502    #[serde(default)]
503    pub references: Option<Vec<String>>,
504}
505
506/// CLE version specifier.
507#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
508#[non_exhaustive]
509pub struct CleVersionSpecifier {
510    /// Exact version.
511    #[serde(default)]
512    pub version: Option<String>,
513    /// Version range.
514    #[serde(default)]
515    pub range: Option<String>,
516}
517
518/// TEA projection of CLE events. This is not a full ECMA-428 document.
519#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
520#[non_exhaustive]
521pub struct Cle {
522    /// Events.
523    pub events: Vec<CleEvent>,
524    /// Definitions.
525    #[serde(default)]
526    pub definitions: Option<CleDefinitions>,
527}
528
529/// Compliance document type re-export helper for callers building identifiers.
530#[derive(Debug, Clone, PartialEq, Eq)]
531pub struct ComplianceDocument(pub ComplianceDocumentType);
532
533/// Deserialize JSON and run `validate` when the type has one.
534///
535/// # Errors
536///
537/// Returns an error on malformed JSON or a failed constraint.
538pub fn parse_json<T>(bytes: &[u8]) -> Result<T, ModelError>
539where
540    T: for<'de> Deserialize<'de>,
541{
542    Ok(serde_json::from_slice(bytes)?)
543}
544
545/// Parse an artifact and validate it.
546///
547/// # Errors
548///
549/// Returns an error when JSON or artifact constraints fail.
550pub fn parse_artifact(bytes: &[u8]) -> Result<Artifact, ModelError> {
551    let artifact: Artifact = parse_json(bytes)?;
552    artifact.validate()?;
553    Ok(artifact)
554}
555
556/// Parse a collection and validate it.
557///
558/// # Errors
559///
560/// Returns an error when JSON or collection constraints fail.
561pub fn parse_collection(bytes: &[u8]) -> Result<Collection, ModelError> {
562    let collection: Collection = parse_json(bytes)?;
563    collection.validate()?;
564    Ok(collection)
565}
566
567/// Parse a product release with its latest collection.
568///
569/// # Errors
570///
571/// Returns an error when JSON or embedded collection constraints fail.
572pub fn parse_product_release(bytes: &[u8]) -> Result<ProductReleaseWithCollection, ModelError> {
573    let value: ProductReleaseWithCollection = parse_json(bytes)?;
574    value.latest_collection.validate()?;
575    Ok(value)
576}
577
578/// Parse a component release with its latest collection.
579///
580/// # Errors
581///
582/// Returns an error when JSON or embedded collection constraints fail.
583pub fn parse_component_release(bytes: &[u8]) -> Result<ComponentReleaseWithCollection, ModelError> {
584    let value: ComponentReleaseWithCollection = parse_json(bytes)?;
585    value.latest_collection.validate()?;
586    Ok(value)
587}
588
589#[cfg(test)]
590mod tests {
591    use super::*;
592
593    #[test]
594    fn artifact_with_url_requires_checksum() {
595        let json = br#"{
596          "uuid": "2ff3ae7c-8eab-4e0b-9b8b-1a0c4c4c1c2d",
597          "version": 1,
598          "type": "BOM",
599          "createdDate": "2026-01-02T03:04:05Z",
600          "formats": [{"mediaType": "application/vnd.cyclonedx+json", "url": "https://cdn.example/sbom.json"}]
601        }"#;
602        assert!(parse_artifact(json).is_err());
603    }
604
605    #[test]
606    fn preserves_unknown_artifact_type() {
607        let json = br#"{
608          "uuid": "2ff3ae7c-8eab-4e0b-9b8b-1a0c4c4c1c2d",
609          "version": 1,
610          "type": "FUTURE_DOC",
611          "createdDate": "2026-01-02T03:04:05.5Z",
612          "formats": [{"mediaType": "application/json", "checksums": [{"algType": "SHA-256", "algValue": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"}]}]
613        }"#;
614        let artifact = parse_artifact(json).unwrap();
615        assert_eq!(artifact.artifact_type.as_str(), "FUTURE_DOC");
616    }
617}