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