osv 0.3.0

Rust library for parsing the OSV schema and client API
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
use chrono::{DateTime, Utc};
use lazy_regex::regex_switch;
use serde::de::{self, Visitor};
use serde::{Deserialize, Deserializer, Serialize, Serializer};

/// Package identifies the code library or command that
/// is potentially affected by a particular vulnerability.
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct Package {
    /// The name of the package or dependency.
    pub name: String,

    /// The ecosystem identifies the overall library ecosystem that this
    /// package can be obtained from.
    pub ecosystem: Ecosystem,

    /// The purl field is a string following the [Package URL
    /// specification](https://github.com/package-url/purl-spec) that identifies the
    /// package. This field is optional but recommended.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub purl: Option<String>,
}

/// A commit is a full SHA1 Git hash in hex format.
pub type Commit = String;

/// Version is arbitrary string representing the version of a package.
pub type Version = String;

/// The package ecosystem that the vulnerabilities in the OSV database
/// are associated with.
#[derive(Debug, Eq, Hash, Ord, PartialEq, PartialOrd, Clone)]
#[non_exhaustive]
pub enum Ecosystem {
    AlmaLinux(Option<String>),
    Alpaquita,
    Alpine(Option<String>),
    Android,
    BellSoftHardenedContainers,
    Bioconductor,
    Bitnami,
    Chainguard,
    ConanCenter,
    CRAN,
    CratesIO,
    Debian(Option<String>),
    DWF,
    Echo,
    GHC,
    GSD,
    GitHubActions,
    Go,
    Hackage,
    Hex,
    JavaScript,
    Julia,
    Kubernetes,
    Linux,
    Mageia(String),
    Maven(String),
    MinimOS,
    Npm,
    NuGet,
    OpenEuler,
    OpenSUSE(Option<String>),
    OssFuzz,
    Packagist,
    PhotonOS(Option<String>),
    Pub,
    PyPI,
    Python,
    RedHat(Option<String>),
    RockyLinux(Option<String>),
    RubyGems,
    SUSE(Option<String>),
    SwiftURL,
    Ubuntu {
        version: String,
        metadata: Option<String>,
        fips: Option<String>,
        pro: bool,
        lts: bool,
    },
    UVI,
    VSCode,
    Wolfi,
}

impl Serialize for Ecosystem {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        match self {
            Ecosystem::AlmaLinux(None) => serializer.serialize_str("AlmaLinux"),
            Ecosystem::AlmaLinux(Some(release)) => {
                serializer.serialize_str(&format!("AlmaLinux:{}", release))
            }
            Ecosystem::Alpaquita => serializer.serialize_str("Alpaquita"),
            Ecosystem::Alpine(None) => serializer.serialize_str("Alpine"),
            Ecosystem::Alpine(Some(version)) => {
                serializer.serialize_str(&format!("Alpine:{}", version))
            }
            Ecosystem::Android => serializer.serialize_str("Android"),
            Ecosystem::BellSoftHardenedContainers => {
                serializer.serialize_str("BellSoft Hardened Containers")
            }
            Ecosystem::Bioconductor => serializer.serialize_str("Bioconductor"),
            Ecosystem::Bitnami => serializer.serialize_str("Bitnami"),
            Ecosystem::Chainguard => serializer.serialize_str("Chainguard"),
            Ecosystem::ConanCenter => serializer.serialize_str("ConanCenter"),
            Ecosystem::CRAN => serializer.serialize_str("CRAN"),
            Ecosystem::CratesIO => serializer.serialize_str("crates.io"),
            Ecosystem::Debian(None) => serializer.serialize_str("Debian"),
            Ecosystem::Debian(Some(version)) => {
                serializer.serialize_str(&format!("Debian:{}", version))
            }
            Ecosystem::DWF => serializer.serialize_str("DWF"),
            Ecosystem::Echo => serializer.serialize_str("Echo"),
            Ecosystem::GHC => serializer.serialize_str("GHC"),
            Ecosystem::GSD => serializer.serialize_str("GSD"),
            Ecosystem::GitHubActions => serializer.serialize_str("GitHub Actions"),
            Ecosystem::Go => serializer.serialize_str("Go"),
            Ecosystem::Hackage => serializer.serialize_str("Hackage"),
            Ecosystem::Hex => serializer.serialize_str("Hex"),
            Ecosystem::JavaScript => serializer.serialize_str("JavaScript"),
            Ecosystem::Julia => serializer.serialize_str("Julia"),
            Ecosystem::Kubernetes => serializer.serialize_str("Kubernetes"),
            Ecosystem::Linux => serializer.serialize_str("Linux"),
            Ecosystem::Mageia(release) => serializer.serialize_str(&format!("Mageia:{}", release)),
            Ecosystem::Maven(repository) => {
                let mvn: String = match repository.as_str() {
                    "https://repo.maven.apache.org/maven2" => "Maven".to_string(),
                    _ => format!("Maven:{}", repository),
                };
                serializer.serialize_str(&mvn)
            }
            Ecosystem::MinimOS => serializer.serialize_str("MinimOS"),
            Ecosystem::Npm => serializer.serialize_str("npm"),
            Ecosystem::NuGet => serializer.serialize_str("NuGet"),
            Ecosystem::OpenEuler => serializer.serialize_str("openEuler"),
            Ecosystem::OpenSUSE(None) => serializer.serialize_str("openSUSE"),
            Ecosystem::OpenSUSE(Some(release)) => {
                serializer.serialize_str(&format!("openSUSE:{}", release))
            }
            Ecosystem::OssFuzz => serializer.serialize_str("OSS-Fuzz"),
            Ecosystem::Packagist => serializer.serialize_str("Packagist"),
            Ecosystem::PhotonOS(None) => serializer.serialize_str("Photon OS"),
            Ecosystem::PhotonOS(Some(release)) => {
                serializer.serialize_str(&format!("Photon OS:{}", release))
            }
            Ecosystem::Pub => serializer.serialize_str("Pub"),
            Ecosystem::PyPI => serializer.serialize_str("PyPI"),
            Ecosystem::Python => serializer.serialize_str("Python"),
            Ecosystem::RedHat(None) => serializer.serialize_str("Red Hat"),
            Ecosystem::RedHat(Some(release)) => {
                serializer.serialize_str(&format!("Red Hat:{}", release))
            }
            Ecosystem::RockyLinux(None) => serializer.serialize_str("Rocky Linux"),
            Ecosystem::RockyLinux(Some(release)) => {
                serializer.serialize_str(&format!("Rocky Linux:{}", release))
            }
            Ecosystem::RubyGems => serializer.serialize_str("RubyGems"),
            Ecosystem::SUSE(None) => serializer.serialize_str("SUSE"),
            Ecosystem::SUSE(Some(release)) => {
                serializer.serialize_str(&format!("SUSE:{}", release))
            }
            Ecosystem::SwiftURL => serializer.serialize_str("SwiftURL"),
            Ecosystem::Ubuntu {
                version,
                pro,
                lts,
                metadata,
                fips,
            } => {
                let mut parts: Vec<String> = vec!["Ubuntu".to_string()];
                if *pro {
                    parts.push("Pro".to_string());
                }
                if let Some(stream) = fips {
                    parts.push(stream.clone());
                }
                parts.push(version.clone());
                if *lts {
                    parts.push("LTS".to_string());
                }
                if let Some(meta) = metadata {
                    parts.push("for".to_string());
                    parts.push(meta.clone());
                }
                let serialized = parts.join(":");
                serializer.serialize_str(&serialized)
            }
            Ecosystem::UVI => serializer.serialize_str("UVI"),
            Ecosystem::VSCode => serializer.serialize_str("VSCode"),
            Ecosystem::Wolfi => serializer.serialize_str("Wolfi"),
        }
    }
}

impl<'de> Deserialize<'de> for Ecosystem {
    fn deserialize<D>(deserializer: D) -> Result<Ecosystem, D::Error>
    where
        D: Deserializer<'de>,
    {
        struct EcosystemVisitor;

        impl Visitor<'_> for EcosystemVisitor {
            type Value = Ecosystem;

            fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
                formatter.write_str("a valid string representing an ecosystem")
            }

            fn visit_str<E>(self, value: &str) -> Result<Ecosystem, E>
            where
                E: de::Error,
            {
                match value {
                    "AlmaLinux" | "AlmaLinux:" => Ok(Ecosystem::AlmaLinux(None)),
                    "Alpaquita" => Ok(Ecosystem::Alpaquita),
                    _ if value.starts_with("AlmaLinux:") => Ok(Ecosystem::AlmaLinux(
                        value.strip_prefix("AlmaLinux:").map(|v| v.to_string()),
                    )),
                    "Alpine" => Ok(Ecosystem::Alpine(None)),
                    _ if value.starts_with("Alpine:") => Ok(Ecosystem::Alpine(
                        value.strip_prefix("Alpine:").map(|v| v.to_string()),
                    )),
                    "Android" => Ok(Ecosystem::Android),
                    "BellSoft Hardened Containers" => Ok(Ecosystem::BellSoftHardenedContainers),
                    "Bioconductor" => Ok(Ecosystem::Bioconductor),
                    "Bitnami" => Ok(Ecosystem::Bitnami),
                    "Chainguard" => Ok(Ecosystem::Chainguard),
                    "ConanCenter" => Ok(Ecosystem::ConanCenter),
                    "CRAN" => Ok(Ecosystem::CRAN),
                    "crates.io" => Ok(Ecosystem::CratesIO),
                    "Debian" => Ok(Ecosystem::Debian(None)),
                    _ if value.starts_with("Debian:") => Ok(Ecosystem::Debian(
                        value.strip_prefix("Debian:").map(|v| v.to_string()),
                    )),
                    "DWF" => Ok(Ecosystem::DWF),
                    "Echo" => Ok(Ecosystem::Echo),
                    "GHC" => Ok(Ecosystem::GHC),
                    "GitHub Actions" => Ok(Ecosystem::GitHubActions),
                    "Go" => Ok(Ecosystem::Go),
                    "GSD" => Ok(Ecosystem::GSD),
                    "Hackage" => Ok(Ecosystem::Hackage),
                    "Hex" => Ok(Ecosystem::Hex),
                    "JavaScript" => Ok(Ecosystem::JavaScript),
                    "Julia" => Ok(Ecosystem::Julia),
                    "Kubernetes" => Ok(Ecosystem::Kubernetes),
                    "Linux" => Ok(Ecosystem::Linux),
                    _ if value.starts_with("Mageia:") => Ok(Ecosystem::Mageia(
                        value
                            .strip_prefix("Mageia:")
                            .map(|v| v.to_string())
                            .unwrap(),
                    )),
                    "Maven" | "Maven:" => Ok(Ecosystem::Maven(
                        "https://repo.maven.apache.org/maven2".to_string(),
                    )),
                    _ if value.starts_with("Maven:") => Ok(Ecosystem::Maven(
                        value.strip_prefix("Maven:").map(|v| v.to_string()).unwrap(),
                    )),
                    "MinimOS" => Ok(Ecosystem::MinimOS),
                    "npm" => Ok(Ecosystem::Npm),
                    "NuGet" => Ok(Ecosystem::NuGet),
                    "openEuler" => Ok(Ecosystem::OpenEuler),
                    "openSUSE" => Ok(Ecosystem::OpenSUSE(None)),
                    _ if value.starts_with("openSUSE:") => Ok(Ecosystem::OpenSUSE(
                        value.strip_prefix("openSUSE:").map(|v| v.to_string()),
                    )),
                    "OSS-Fuzz" => Ok(Ecosystem::OssFuzz),
                    "Packagist" => Ok(Ecosystem::Packagist),
                    "Photon OS" | "Photon OS:" => Ok(Ecosystem::PhotonOS(None)),
                    _ if value.starts_with("Photon OS:") => Ok(Ecosystem::PhotonOS(
                        value.strip_prefix("Photon OS:").map(|v| v.to_string()),
                    )),
                    "Pub" => Ok(Ecosystem::Pub),
                    "PyPI" => Ok(Ecosystem::PyPI),
                    "Python" => Ok(Ecosystem::Python),
                    "Red Hat" => Ok(Ecosystem::RedHat(None)),
                    _ if value.starts_with("Red Hat:") => Ok(Ecosystem::RedHat(
                        value.strip_prefix("Red Hat:").map(|v| v.to_string()),
                    )),
                    "Rocky Linux" | "Rocky Linux:" => Ok(Ecosystem::RockyLinux(None)),
                    _ if value.starts_with("Rocky Linux:") => Ok(Ecosystem::RockyLinux(
                        value.strip_prefix("Rocky Linux:").map(|v| v.to_string()),
                    )),
                    "RubyGems" => Ok(Ecosystem::RubyGems),
                    "SUSE" => Ok(Ecosystem::SUSE(None)),
                    _ if value.starts_with("SUSE:") => Ok(Ecosystem::SUSE(
                        value.strip_prefix("SUSE:").map(|v| v.to_string()),
                    )),
                    "SwiftURL" => Ok(Ecosystem::SwiftURL),
                    _ if value.starts_with("Ubuntu:") => {
                        regex_switch!(value,
                            r#"^Ubuntu(?::Pro)?(?::(?<fips>FIPS(?:-preview|-updates)?))?:(?<version>\d+\.\d+)(?::LTS)?(?::for:(?<specialized>.+))?"# => {
                                Ecosystem::Ubuntu {
                                    version: version.to_string(),
                                    metadata: (!specialized.is_empty()).then_some(specialized.to_string()),
                                    fips: (!fips.is_empty()).then_some(fips.to_string()),
                                    pro: value.contains(":Pro"),
                                    lts: value.contains(":LTS"),
                                }
                            }
                        ).ok_or(de::Error::unknown_variant(value, &["Ecosystem"]))
                    }
                    "UVI" => Ok(Ecosystem::UVI),
                    "VSCode" => Ok(Ecosystem::VSCode),
                    "Wolfi" => Ok(Ecosystem::Wolfi),
                    _ => Err(de::Error::unknown_variant(value, &["Ecosystem"])),
                }
            }
        }
        deserializer.deserialize_str(EcosystemVisitor)
    }
}

/// Type of the affected range supplied. This can be an ecosystem
/// specific value, semver, or a git commit hash.
#[derive(Debug, Serialize, Deserialize, Clone)]
#[serde(rename_all = "UPPERCASE")]
#[non_exhaustive]
pub enum RangeType {
    /// The versions introduced and fixed are arbitrary, uninterpreted strings specific to the
    /// package ecosystem
    Ecosystem,

    /// The versions introduced and fixed are full-length Git commit hashes.
    Git,

    /// The versions introduced and fixed are semantic versions as defined by SemVer 2.0.0.
    Semver,

    /// Default for the case where a range type is omitted.
    Unspecified,
}

/// The event captures information about the how and when
/// the package was affected by the vulnerability.
#[derive(Debug, Serialize, Deserialize, Clone)]
#[serde(rename_all = "lowercase")]
#[non_exhaustive]
pub enum Event {
    /// The version or commit in which the vulnerability was
    /// introduced.
    Introduced(String),

    /// The version which the vulnerability was fixed.
    Fixed(String),

    /// Describes the last known affected version
    #[serde(rename = "last_affected")]
    LastAffected(String),

    /// The upper limit on the range being described.
    Limit(String),
}

/// The range of versions of a package for which
/// it is affected by the vulnerability.
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct Range {
    /// The format that the range events are specified in, for
    /// example SEMVER or GIT.
    #[serde(rename = "type")]
    pub range_type: RangeType,

    /// The ranges object’s repo field is the URL of the package’s code repository. The value
    /// should be in a format that’s directly usable as an argument for the version control
    /// system’s clone command
    #[serde(skip_serializing_if = "Option::is_none")]
    pub repo: Option<String>,

    /// Represent a status timeline for how the vulnerability affected the package. For
    /// example when the vulnerability was first introduced into the codebase.
    pub events: Vec<Event>,
}

/// The versions of the package that are affected
/// by a particular vulnerability. The affected ranges can include
/// when the vulnerability was first introduced and also when it
/// was fixed.
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct Affected {
    /// The package that is affected by the vulnerability
    #[serde(skip_serializing_if = "Option::is_none")]
    pub package: Option<Package>,

    /// This `severity` field applies to a specific package, in cases where affected
    /// packages have differing severities for the same vulnerability. If any package
    /// level `severity` fields are set, the top level [`severity`](#severity-field)
    /// must not be set.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub severity: Option<Vec<Severity>>,

    /// The range of versions or git commits that this vulnerability
    /// was first introduced and/or version that it was fixed in.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub ranges: Option<Vec<Range>>,

    /// Each string is a single affected version in whatever version syntax is
    /// used by the given package ecosystem.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub versions: Option<Vec<String>>,

    /// A JSON object that holds any additional information about the
    /// vulnerability as defined by the ecosystem for which the record applies.
    ///
    #[serde(skip_serializing_if = "Option::is_none")]
    pub ecosystem_specific: Option<serde_json::Value>,

    /// A JSON object to hold any additional information about the range
    /// from which this record was obtained. The meaning of the values within
    /// the object is entirely defined by the database.
    ///
    #[serde(skip_serializing_if = "Option::is_none")]
    pub database_specific: Option<serde_json::Value>,
}

/// The type of reference information that has been provided. Examples include
/// links to the original report, external advisories, or information about the
/// fix.
#[derive(Clone, Debug, Default, Serialize, Deserialize)]
#[serde(rename_all = "UPPERCASE")]
#[non_exhaustive]
pub enum ReferenceType {
    /// A published security advisory for the vulnerability.
    Advisory,

    /// An article or blog post describing the vulnerability.
    Article,

    /// A tool, script, scanner, or other mechanism that allows for detection
    /// of the vulnerability in production environments
    Detection,

    /// A social media discussion regarding the vulnerability.
    Discussion,

    /// A demonstration of the validity of a vulnerability claim
    Evidence,

    /// A source code browser link to the fix.
    Fix,

    /// Git commit hash or range where the issue occurred
    Git,

    /// A source code browser link to the introduction of the vulnerability.
    Introduced,

    /// A home web page for the package.
    Package,

    /// A report, typically on a bug or issue tracker, of the vulnerability.
    Report,

    #[default]
    #[serde(rename = "NONE")]
    Undefined,

    /// A web page of some unspecified kind.
    Web,
}

/// Reference to additional information about the vulnerability.
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct Reference {
    /// The type of reference this URL points to.
    #[serde(rename = "type", default)]
    pub reference_type: ReferenceType,

    /// The url where more information can be obtained about
    /// the vulnerability or associated the fix.
    pub url: String,
}

/// The [`SeverityType`](SeverityType) describes the quantitative scoring method used to rate the
/// severity of the vulnerability.
#[derive(Clone, Debug, Serialize, Deserialize, Default)]
#[non_exhaustive]
pub enum SeverityType {
    /// A CVSS vector string representing the unique characteristics and severity of the vulnerability
    /// using a version of the [Common Vulnerability Scoring System notation](https://www.first.org/cvss/v2/)
    /// that is == 2.0 (e.g.`"AV:L/AC:M/Au:N/C:N/I:P/A:C"`).
    #[serde(rename = "CVSS_V2")]
    CVSSv2,

    /// A CVSS vector string representing the unique characteristics and severity of the
    /// vulnerability using a version of the Common Vulnerability Scoring System notation that is
    /// >= 3.0 and < 4.0 (e.g.`"CVSS:3.1/AV:N/AC:H/PR:N/UI:N/S:C/C:H/I:N/A:N"`).
    #[serde(rename = "CVSS_V3")]
    CVSSv3,

    /// A CVSS vector string representing the unique characterictics and severity of the vulnerability
    /// using a version on the [Common Vulnerability Scoring System notation](https://www.first.org/cvss/)
    /// that is >= 4.0 and < 5.0 (e.g. `"CVSS:4.0/AV:N/AC:L/AT:N/PR:H/UI:N/VC:L/VI:L/VA:N/SC:N/SI:N/SA:N"`).
    #[serde(rename = "CVSS_V4")]
    CVSSv4,

    /// A lowercased string representing the [Ubuntu priority](https://ubuntu.com/security/cves/about#priority).
    /// This is based on many factors including severity, importance, risk, estimated number of affected users,
    /// software configuration, active exploitation, and other factors.
    Ubuntu,

    /// The severity score was arrived at by using an unspecified
    /// scoring method.
    #[default]
    #[serde(rename = "UNSPECIFIED")]
    Unspecified,
}

/// The type and score used to describe the severity of a vulnerability using one
/// or more quantitative scoring methods.
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct Severity {
    /// The severity type property must be a [`SeverityType`](SeverityType), which describes the
    /// quantitative method used to calculate the associated score.
    #[serde(rename = "type", default)]
    pub severity_type: SeverityType,

    /// The score property is a string representing the severity score based on the
    /// selected severity type.
    pub score: String,
}

/// The [`CreditType`](CreditType) this optional field should specify
/// the type or role of the individual or entity being credited.
///
/// These values and their definitions correspond directly to the [MITRE CVE specification](https://cveproject.github.io/cve-schema/schema/v5.0/docs/#collapseDescription_oneOf_i0_containers_cna_credits_items_type).
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(rename_all = "UPPERCASE")]
#[non_exhaustive]
pub enum CreditType {
    /// Validated the vulnerability to ensure accuracy or severity.
    Analyst,

    /// Facilitated the coordinated response process.
    Coordinator,

    /// Identified the vulnerability
    Finder,

    /// Any other type or role that does not fall under the categories
    /// described above.
    Other,

    /// Prepared a code change or other remediation plans.
    RemediationDeveloper,

    /// Reviewed vulnerability remediation plans or code changes
    /// for effectiveness and completeness.
    RemediationReviewer,

    /// Tested and verified the vulnerability or its remediation.
    RemediationVerifier,

    /// Notified the vendor of the vulnerability to a CNA.
    Reporter,

    /// Supported the vulnerability identification or remediation activities.
    Sponsor,

    /// Names of tools used in vulnerability discovery or identification.
    Tool,
}

/// Provides a way to give credit for the discovery, confirmation, patch or other events in the
/// life cycle of a vulnerability.
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct Credit {
    pub name: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub contact: Option<Vec<String>>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub credit_type: Option<CreditType>,
}

/// A vulnerability is the standard exchange format that is
/// defined by the OSV schema <https://ossf.github.io/osv-schema/>.
///
/// This is the entity that is returned when vulnerable data exists for
/// a given package or when requesting information about a specific vulnerability
/// by unique identifier.
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct Vulnerability {
    /// The schema_version field is used to indicate which version of the OSV schema a particular
    /// vulnerability was exported with.
    pub schema_version: Option<String>,
    /// The id field is a unique identifier for the vulnerability entry. It is a string of the
    /// format <DB>-<ENTRYID>, where DB names the database and ENTRYID is in the format used by the
    /// database. For example: “OSV-2020-111”, “CVE-2021-3114”, or “GHSA-vp9c-fpxx-744v”.
    pub id: String,

    /// The published field gives the time the entry should be considered to have been published,
    /// as an RFC3339-formatted time stamp in UTC (ending in “Z”).
    pub published: Option<DateTime<Utc>>,

    /// The modified field gives the time the entry was last modified, as an RFC3339-formatted
    /// timestamptime stamp in UTC (ending in “Z”).
    pub modified: DateTime<Utc>,

    /// The withdrawn field gives the time the entry should be considered to have been withdrawn,
    /// as an RFC3339-formatted timestamp in UTC (ending in “Z”). If the field is missing, then the
    /// entry has not been withdrawn. Any rationale for why the vulnerability has been withdrawn
    /// should go into the summary text.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub withdrawn: Option<DateTime<Utc>>,

    /// The aliases field gives a list of IDs of the same vulnerability in other databases, in the
    /// form of the id field. This allows one database to claim that its own entry describes the
    /// same vulnerability as one or more entries in other databases. Or if one database entry has
    /// been deduplicated into another in the same database, the duplicate entry could be written
    /// using only the id, modified, and aliases field, to point to the canonical one.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub aliases: Option<Vec<String>>,

    /// The `upstream` field gives a list of IDs of upstream vulnerabilities that are referred to
    /// by the vulnerability entry.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub upstream: Option<Vec<String>>,

    /// The related field gives a list of IDs of closely related vulnerabilities, such as the same
    /// problem in alternate ecosystems.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub related: Option<Vec<String>>,

    /// The summary field gives a one-line, English textual summary of the vulnerability. It is
    /// recommended that this field be kept short, on the order of no more than 120 characters.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub summary: Option<String>,

    /// The details field gives additional English textual details about the vulnerability. The
    /// details field is CommonMark markdown (a subset of GitHub-Flavored Markdown). Display code
    /// may at its discretion sanitize the input further, such as stripping raw HTML and links that
    /// do not start with http:// or https://. Databases are encouraged not to include those in the
    /// first place. (The goal is to balance flexibility of presentation with not exposing
    /// vulnerability database display sites to unnecessary vulnerabilities.)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub details: Option<String>,

    /// Indicates the specific package ranges that are affected by this vulnerability.
    pub affected: Option<Vec<Affected>>,

    /// An optional list of external reference's that provide more context about this
    /// vulnerability.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub references: Option<Vec<Reference>>,

    /// The severity field is a JSON array that allows generating systems to describe the severity
    /// of a vulnerability using one or more quantitative scoring methods. Each severity item is a
    /// object specifying a type and score property.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub severity: Option<Vec<Severity>>,

    /// Provides a way to give credit for the discovery, confirmation, patch or other events in the
    /// life cycle of a vulnerability.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub credits: Option<Vec<Credit>>,

    /// Top level field to hold any additional information about the vulnerability as defined
    /// by the database from which the record was obtained.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub database_specific: Option<serde_json::Value>,
}

#[cfg(test)]
mod tests {
    use super::*;

    fn check_ser_deser<T: Serialize + Deserialize<'static> + std::fmt::Debug + PartialEq>(
        deser: T,
        ser: &'static str,
    ) {
        assert_eq!(serde_json::to_string(&deser).unwrap(), ser);
        assert_eq!(serde_json::from_str::<T>(ser).unwrap(), deser);
    }

    #[test]
    fn test_no_serialize_null_fields() {
        let vuln = Vulnerability {
            schema_version: Some("1.3.0".to_string()),
            id: "OSV-2020-484".to_string(),
            published: Some(chrono::Utc::now()),
            modified: chrono::Utc::now(),
            withdrawn: None,
            aliases: None,
            upstream: None,
            related: None,
            summary: None,
            details: None,
            affected: None,
            references: None,
            severity: None,
            credits: None,
            database_specific: None,
        };

        let as_json = serde_json::json!(vuln);
        let str_json = as_json.to_string();
        assert!(!str_json.contains("withdrawn"));
        assert!(!str_json.contains("aliases"));
        assert!(!str_json.contains("related"));
        assert!(!str_json.contains("summary"));
        assert!(!str_json.contains("details"));
        assert!(!str_json.contains("references"));
        assert!(!str_json.contains("severity"));
        assert!(!str_json.contains("credits"));
        assert!(!str_json.contains("database_specific"));
    }

    #[test]
    fn test_maven_ecosystem() {
        let maven = Ecosystem::Maven("https://repo.maven.apache.org/maven2".to_string());
        let json_str = r#""Maven""#;
        check_ser_deser(maven, json_str);

        let maven = Ecosystem::Maven("https://repo1.example.com/maven2".to_string());
        let json_str = r#""Maven:https://repo1.example.com/maven2""#;
        check_ser_deser(maven, json_str);

        let json_str = r#""Maven:""#;
        let maven: Ecosystem = serde_json::from_str(json_str).unwrap();
        assert_eq!(
            maven,
            Ecosystem::Maven("https://repo.maven.apache.org/maven2".to_string())
        );
    }

    #[test]
    fn test_ubuntu_ecosystem() {
        let ubuntu = Ecosystem::Ubuntu {
            version: "20.04".to_string(),
            pro: true,
            lts: true,
            fips: None,
            metadata: None,
        };
        let json_str = r#""Ubuntu:Pro:20.04:LTS""#;
        check_ser_deser(ubuntu, json_str);

        let ubuntu = Ecosystem::Ubuntu {
            version: "20.04".to_string(),
            pro: true,
            lts: false,
            fips: None,
            metadata: None,
        };
        let json_str = r#""Ubuntu:Pro:20.04""#;
        check_ser_deser(ubuntu, json_str);

        let ubuntu = Ecosystem::Ubuntu {
            version: "20.04".to_string(),
            pro: false,
            lts: true,
            fips: None,
            metadata: None,
        };
        let json_str = r#""Ubuntu:20.04:LTS""#;
        check_ser_deser(ubuntu, json_str);

        let ubuntu = Ecosystem::Ubuntu {
            version: "20.04".to_string(),
            pro: false,
            lts: false,
            fips: None,
            metadata: None,
        };
        let json_str = r#""Ubuntu:20.04""#;
        check_ser_deser(ubuntu, json_str);

        let json_str = r#""Ubuntu:Pro:24.04:LTS:Realtime:Kernel""#;
        let ubuntu: Ecosystem = serde_json::from_str(json_str).unwrap();
        assert_eq!(
            ubuntu,
            Ecosystem::Ubuntu {
                version: "24.04".to_string(),
                pro: true,
                lts: true,
                fips: None,
                metadata: None,
            }
        );

        let ubuntu = Ecosystem::Ubuntu {
            version: "22.04".to_string(),
            pro: false,
            lts: true,
            fips: None,
            metadata: Some("NVIDIA:BlueField".to_string()),
        };
        let json_str = r#""Ubuntu:22.04:LTS:for:NVIDIA:BlueField""#;
        check_ser_deser(ubuntu, json_str);

        let ubuntu = Ecosystem::Ubuntu {
            version: "22.04".to_string(),
            pro: true,
            lts: true,
            fips: Some("FIPS-preview".to_string()),
            metadata: None,
        };
        let json_str = r#""Ubuntu:Pro:FIPS-preview:22.04:LTS""#;
        check_ser_deser(ubuntu, json_str);

        let ubuntu = Ecosystem::Ubuntu {
            version: "18.04".to_string(),
            pro: true,
            lts: true,
            fips: Some("FIPS-updates".to_string()),
            metadata: None,
        };
        let json_str = r#""Ubuntu:Pro:FIPS-updates:18.04:LTS""#;
        check_ser_deser(ubuntu, json_str);

        let ubuntu = Ecosystem::Ubuntu {
            version: "16.04".to_string(),
            pro: true,
            lts: true,
            fips: Some("FIPS".to_string()),
            metadata: None,
        };

        let json_str = r#""Ubuntu:Pro:FIPS:16.04:LTS""#;
        check_ser_deser(ubuntu, json_str);
    }
}