Skip to main content

libtea_core/
enums.rs

1//! Closed request enums and forward-compatible response enums.
2//!
3//! Response enumerations keep unknown wire values. The OpenAPI schemas list a
4//! closed set, but the discovery document requires clients to accept an
5//! `error` value they do not know. The same representation is used for other
6//! protocol enumerations so a later revision does not become unreadable.
7
8use std::fmt;
9
10use serde::{Deserialize, Deserializer, Serialize, Serializer};
11
12/// How an enumeration value relates to the pinned TEA 1.0.0 schema.
13#[derive(Debug, Clone, Copy, PartialEq, Eq)]
14#[non_exhaustive]
15pub enum EnumKnowledge {
16    /// The value is listed in the pinned schema.
17    Known,
18    /// The value was preserved for forward compatibility.
19    Unknown,
20}
21
22macro_rules! wire_enum {
23    ($(#[$meta:meta])* $name:ident { $($var:ident => $wire:literal),+ $(,)? }) => {
24        $(#[$meta])*
25        ///
26        /// Unknown wire values are kept in [`Self::Other`].
27        #[derive(Debug, Clone, PartialEq, Eq, Hash)]
28        #[non_exhaustive]
29        pub enum $name {
30            $(
31                #[doc = concat!("The `\"", $wire, "\"` wire value.")]
32                $var,
33            )+
34            /// A value this client does not recognize.
35            Other(String),
36        }
37
38        impl $name {
39            /// Parse a wire string without rejecting unknown values.
40            #[must_use]
41            pub fn from_wire(value: &str) -> Self {
42                match value {
43                    $($wire => Self::$var,)+
44                    other => Self::Other(other.to_owned()),
45                }
46            }
47
48            /// Borrow the wire spelling.
49            #[must_use]
50            pub fn as_str(&self) -> &str {
51                match self {
52                    $(Self::$var => $wire,)+
53                    Self::Other(value) => value,
54                }
55            }
56
57            /// Whether this value appears in the pinned schema.
58            #[must_use]
59            pub fn knowledge(&self) -> EnumKnowledge {
60                match self {
61                    Self::Other(_) => EnumKnowledge::Unknown,
62                    _ => EnumKnowledge::Known,
63                }
64            }
65        }
66
67        impl fmt::Display for $name {
68            fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
69                f.write_str(self.as_str())
70            }
71        }
72
73        impl Serialize for $name {
74            fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
75                serializer.serialize_str(self.as_str())
76            }
77        }
78
79        impl<'de> Deserialize<'de> for $name {
80            fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
81                let value = String::deserialize(deserializer)?;
82                Ok(Self::from_wire(&value))
83            }
84        }
85    };
86}
87
88wire_enum!(
89    /// `identifier-type`: the kind of an identifier (CPE, TEI, PURL, compliance document).
90    IdentifierType {
91    Cpe => "CPE",
92    Tei => "TEI",
93    Purl => "PURL",
94    ComplianceDocument => "COMPLIANCE_DOCUMENT",
95});
96
97wire_enum!(
98    /// `compliance-document-type`: the framework a compliance document belongs to.
99    ComplianceDocumentType {
100    Soc2TypeI => "SOC_2_TYPE_I",
101    Soc2TypeIi => "SOC_2_TYPE_II",
102    Soc3 => "SOC_3",
103    Iso27001 => "ISO_27001",
104    Iso27017 => "ISO_27017",
105    Iso27018 => "ISO_27018",
106    Iso27701 => "ISO_27701",
107    Iso42001 => "ISO_42001",
108    PciDss => "PCI_DSS",
109    Hipaa => "HIPAA",
110    Fedramp => "FEDRAMP",
111    Gdpr => "GDPR",
112    CsaStar => "CSA_STAR",
113    Nist80053 => "NIST_800_53",
114    Nist800171 => "NIST_800_171",
115    Cmmc => "CMMC",
116    Hitrust => "HITRUST",
117    Tisax => "TISAX",
118    CyberEssentials => "CYBER_ESSENTIALS",
119    CyberEssentialsPlus => "CYBER_ESSENTIALS_PLUS",
120    EuDeclarationOfConformity => "EU_DECLARATION_OF_CONFORMITY",
121});
122
123wire_enum!(
124    /// `artifact-type`: what an artifact is (BOM, vulnerabilities, attestation, ...).
125    ArtifactType {
126    Attestation => "ATTESTATION",
127    Bom => "BOM",
128    BuildMeta => "BUILD_META",
129    Certification => "CERTIFICATION",
130    Formulation => "FORMULATION",
131    License => "LICENSE",
132    ReleaseNotes => "RELEASE_NOTES",
133    SecurityTxt => "SECURITY_TXT",
134    ThreatModel => "THREAT_MODEL",
135    Vulnerabilities => "VULNERABILITIES",
136    OtherArtifact => "OTHER",
137});
138
139wire_enum!(
140    /// `collection-update-reason-type`: why a collection version was published.
141    CollectionUpdateReasonType {
142    InitialRelease => "INITIAL_RELEASE",
143    VexUpdated => "VEX_UPDATED",
144    ArtifactUpdated => "ARTIFACT_UPDATED",
145    ArtifactAdded => "ARTIFACT_ADDED",
146    ArtifactRemoved => "ARTIFACT_REMOVED",
147});
148
149wire_enum!(
150    /// `collection-belongs-to-type`: whether a collection belongs to a component release or a product release.
151    CollectionOwner {
152    ComponentRelease => "COMPONENT_RELEASE",
153    ProductRelease => "PRODUCT_RELEASE",
154});
155
156wire_enum!(
157    /// `cle-event-type`: a Common Lifecycle Enumeration (CLE) event.
158    CleEventType {
159    Released => "released",
160    EndOfDevelopment => "endOfDevelopment",
161    EndOfSupport => "endOfSupport",
162    EndOfLife => "endOfLife",
163    EndOfDistribution => "endOfDistribution",
164    EndOfMarketing => "endOfMarketing",
165    SupersededBy => "supersededBy",
166    ComponentRenamed => "componentRenamed",
167    Withdrawn => "withdrawn",
168});
169
170wire_enum!(
171    /// `unknown-error-type`: the `error` value of a TEA `error-response`.
172    TeaErrorCode {
173    ObjectUnknown => "OBJECT_UNKNOWN",
174    NotImplemented => "NOT_IMPLEMENTED",
175    NoAcceptableFormat => "NO_ACCEPTABLE_FORMAT",
176    SignatureNotFound => "SIGNATURE_NOT_FOUND",
177    InvalidRequest => "INVALID_REQUEST",
178    InvalidPageToken => "INVALID_PAGE_TOKEN",
179});
180
181wire_enum!(
182    /// `checksum-type`: the algorithm of a declared checksum.
183    ChecksumAlgorithm {
184    Sha1 => "SHA-1",
185    Sha256 => "SHA-256",
186    Sha384 => "SHA-384",
187    Sha512 => "SHA-512",
188    Sha3_256 => "SHA3-256",
189    Sha3_384 => "SHA3-384",
190    Sha3_512 => "SHA3-512",
191    Blake2b256 => "BLAKE2b-256",
192    Blake2b384 => "BLAKE2b-384",
193    Blake2b512 => "BLAKE2b-512",
194    Blake3 => "BLAKE3",
195});
196
197impl ChecksumAlgorithm {
198    /// Digest size in bytes for algorithms listed in `checksum-type`.
199    #[must_use]
200    pub fn digest_len(&self) -> Option<usize> {
201        match self {
202            Self::Sha1 => Some(20),
203            Self::Sha256 | Self::Sha3_256 | Self::Blake2b256 | Self::Blake3 => Some(32),
204            Self::Sha384 | Self::Sha3_384 | Self::Blake2b384 => Some(48),
205            Self::Sha512 | Self::Sha3_512 | Self::Blake2b512 => Some(64),
206            Self::Other(_) => None,
207        }
208    }
209
210    /// Whether this algorithm is too weak for a match to count as
211    /// [`crate::IntegrityOutcome::Verified`] on its own.
212    ///
213    /// `SHA-1` is listed in the pinned `checksum-type` enum but is not
214    /// collision resistant. `MD5` is not in that enum; it is parsed as
215    /// [`Self::Other`], never computed, and also reported as weak.
216    #[must_use]
217    pub fn is_weak(&self) -> bool {
218        match self {
219            Self::Sha1 => true,
220            Self::Other(name) => name.eq_ignore_ascii_case("MD5"),
221            _ => false,
222        }
223    }
224}
225
226/// Sort direction for paginated queries. The default in the specification is `asc`.
227#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
228#[serde(rename_all = "lowercase")]
229#[non_exhaustive]
230pub enum SortOrder {
231    /// Ascending order.
232    Asc,
233    /// Descending order.
234    Desc,
235}
236
237impl SortOrder {
238    /// Wire value.
239    #[must_use]
240    pub fn as_str(self) -> &'static str {
241        match self {
242            Self::Asc => "asc",
243            Self::Desc => "desc",
244        }
245    }
246}
247
248/// `sortField` for product queries.
249#[derive(Debug, Clone, Copy, PartialEq, Eq)]
250#[non_exhaustive]
251pub enum ProductSort {
252    /// Sort by product name.
253    Name,
254}
255
256/// `sortField` for component queries.
257#[derive(Debug, Clone, Copy, PartialEq, Eq)]
258#[non_exhaustive]
259pub enum ComponentSort {
260    /// Sort by component name.
261    Name,
262}
263
264/// `sortField` for product-release and component-release queries.
265#[derive(Debug, Clone, Copy, PartialEq, Eq)]
266#[non_exhaustive]
267pub enum ReleaseSort {
268    /// Sort by `createdDate`.
269    CreatedDate,
270    /// Sort by `releaseDate`.
271    ReleaseDate,
272    /// Sort by the release version string.
273    Version,
274}
275
276/// `sortField` for collection queries.
277#[derive(Debug, Clone, Copy, PartialEq, Eq)]
278#[non_exhaustive]
279pub enum CollectionSort {
280    /// Sort by collection version.
281    Version,
282}
283
284impl ProductSort {
285    /// Wire value.
286    #[must_use]
287    pub fn as_str(self) -> &'static str {
288        "name"
289    }
290}
291
292impl ComponentSort {
293    /// Wire value.
294    #[must_use]
295    pub fn as_str(self) -> &'static str {
296        "name"
297    }
298}
299
300impl ReleaseSort {
301    /// Wire value.
302    #[must_use]
303    pub fn as_str(self) -> &'static str {
304        match self {
305            Self::CreatedDate => "createdDate",
306            Self::ReleaseDate => "releaseDate",
307            Self::Version => "version",
308        }
309    }
310}
311
312impl CollectionSort {
313    /// Wire value.
314    #[must_use]
315    pub fn as_str(self) -> &'static str {
316        "version"
317    }
318}