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