cvss-rs 0.4.0

A Rust library for representing and deserializing CVSS (Common Vulnerability Scoring System) data.
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
//! Represents the CVSS v3.0 and v3.1 specifications.

use std::fmt;
use std::str::FromStr;

use serde::{Deserialize, Serialize};
use strum::{Display, EnumString};

use crate::utils::{parse_metrics::parse_metric, prefix};
use crate::{version::VersionV3, ParseError, Severity as UnifiedSeverity, Version};

/// Represents a CVSS v3.0 or v3.1 score object.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct CvssV3 {
    /// The CVSS vector string.
    pub vector_string: String,
    /// The specific CVSS v3 version (3.0 or 3.1).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub version: Option<VersionV3>,
    /// The base score, a value between 0.0 and 10.0.
    pub base_score: f64,
    /// The qualitative severity rating for the base score.
    pub base_severity: Severity,
    /// The attack vector metric.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub attack_vector: Option<AttackVector>,
    /// The attack complexity metric.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub attack_complexity: Option<AttackComplexity>,
    /// The privileges required metric.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub privileges_required: Option<PrivilegesRequired>,
    /// The user interaction metric.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub user_interaction: Option<UserInteraction>,
    /// The scope metric.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub scope: Option<Scope>,
    /// The confidentiality impact metric.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub confidentiality_impact: Option<Impact>,
    /// The integrity impact metric.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub integrity_impact: Option<Impact>,
    /// The availability impact metric.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub availability_impact: Option<Impact>,

    // Temporal Metrics
    #[serde(skip_serializing_if = "Option::is_none")]
    pub temporal_score: Option<f64>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub temporal_severity: Option<Severity>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub exploit_code_maturity: Option<ExploitCodeMaturity>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub remediation_level: Option<RemediationLevel>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub report_confidence: Option<ReportConfidence>,

    // Environmental Metrics
    #[serde(skip_serializing_if = "Option::is_none")]
    pub environmental_score: Option<f64>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub environmental_severity: Option<Severity>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub confidentiality_requirement: Option<SecurityRequirement>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub integrity_requirement: Option<SecurityRequirement>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub availability_requirement: Option<SecurityRequirement>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub modified_attack_vector: Option<AttackVector>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub modified_attack_complexity: Option<AttackComplexity>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub modified_privileges_required: Option<PrivilegesRequired>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub modified_user_interaction: Option<UserInteraction>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub modified_scope: Option<Scope>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub modified_confidentiality_impact: Option<Impact>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub modified_integrity_impact: Option<Impact>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub modified_availability_impact: Option<Impact>,
}

/// Represents the qualitative severity rating of a vulnerability.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "UPPERCASE")]
pub enum Severity {
    None,
    Low,
    Medium,
    High,
    Critical,
}

/// Represents the attack vector metric.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, EnumString, Display)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum AttackVector {
    #[strum(serialize = "N")]
    Network,
    #[strum(serialize = "A")]
    AdjacentNetwork,
    #[strum(serialize = "L")]
    Local,
    #[strum(serialize = "P")]
    Physical,
    #[strum(serialize = "X")]
    NotDefined,
}

impl AttackVector {
    /// Returns the numeric score for this metric per CVSS v3.x specification.
    pub fn score(&self) -> f64 {
        match self {
            AttackVector::Network => 0.85,
            AttackVector::AdjacentNetwork => 0.62,
            AttackVector::Local => 0.55,
            AttackVector::Physical => 0.20,
            AttackVector::NotDefined => 0.85, // Defaults to worst case (Network)
        }
    }
}

/// Represents the attack complexity metric.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, EnumString, Display)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum AttackComplexity {
    #[strum(serialize = "L")]
    Low,
    #[strum(serialize = "H")]
    High,
    #[strum(serialize = "X")]
    NotDefined,
}

impl AttackComplexity {
    /// Returns the numeric score for this metric per CVSS v3.x specification.
    pub fn score(&self) -> f64 {
        match self {
            AttackComplexity::Low => 0.77,
            AttackComplexity::High => 0.44,
            AttackComplexity::NotDefined => 0.77, // Defaults to worst case (Low)
        }
    }
}

/// Represents the privileges required metric.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, EnumString, Display)]
#[serde(rename_all = "UPPERCASE")]
pub enum PrivilegesRequired {
    #[strum(serialize = "N")]
    None,
    #[strum(serialize = "L")]
    Low,
    #[strum(serialize = "H")]
    High,
    #[strum(serialize = "X")]
    NotDefined,
}

impl PrivilegesRequired {
    /// Returns the numeric score for this metric, accounting for scope.
    /// Per CVSS v3.x specification, the PR score depends on whether scope is changed.
    pub fn score(&self, scope_changed: bool) -> f64 {
        match self {
            PrivilegesRequired::None => 0.85,
            PrivilegesRequired::Low => {
                if scope_changed {
                    0.68
                } else {
                    0.62
                }
            }
            PrivilegesRequired::High => {
                if scope_changed {
                    0.50
                } else {
                    0.27
                }
            }
            PrivilegesRequired::NotDefined => 0.85, // Defaults to worst case (None)
        }
    }
}

/// Represents the user interaction metric.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, EnumString, Display)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum UserInteraction {
    #[strum(serialize = "N")]
    None,
    #[strum(serialize = "R")]
    Required,
    #[strum(serialize = "X")]
    NotDefined,
}

impl UserInteraction {
    /// Returns the numeric score for this metric per CVSS v3.x specification.
    pub fn score(&self) -> f64 {
        match self {
            UserInteraction::None => 0.85,
            UserInteraction::Required => 0.62,
            UserInteraction::NotDefined => 0.85, // Defaults to worst case (None)
        }
    }
}

/// Represents the scope metric.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, EnumString, Display)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum Scope {
    #[strum(serialize = "U")]
    Unchanged,
    #[strum(serialize = "C")]
    Changed,
    #[strum(serialize = "X")]
    NotDefined,
}

impl Scope {
    /// Returns whether the scope is changed (for use in score calculation).
    pub fn is_changed(&self) -> bool {
        matches!(self, Scope::Changed)
    }
}

/// Represents the impact metrics (confidentiality, integrity, availability).
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, EnumString, Display)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum Impact {
    #[strum(serialize = "H")]
    High,
    #[strum(serialize = "L")]
    Low,
    #[strum(serialize = "N")]
    None,
    #[strum(serialize = "X")]
    NotDefined,
}

impl Impact {
    /// Returns the numeric score for this metric per CVSS v3.x specification.
    pub fn score(&self) -> f64 {
        match self {
            Impact::High => 0.56,
            Impact::Low => 0.22,
            Impact::None => 0.0,
            Impact::NotDefined => 0.56, // Defaults to worst case (High)
        }
    }
}

/// Represents the exploit code maturity metric.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, EnumString, Display)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum ExploitCodeMaturity {
    #[strum(serialize = "U")]
    Unproven,
    #[strum(serialize = "P")]
    ProofOfConcept,
    #[strum(serialize = "F")]
    Functional,
    #[strum(serialize = "H")]
    High,
    #[strum(serialize = "X")]
    NotDefined,
}

impl ExploitCodeMaturity {
    /// Returns the temporal score multiplier for this metric per CVSS v3.x specification.
    pub fn score(&self) -> f64 {
        match self {
            ExploitCodeMaturity::Unproven => 0.91,
            ExploitCodeMaturity::ProofOfConcept => 0.94,
            ExploitCodeMaturity::Functional => 0.97,
            ExploitCodeMaturity::High => 1.0,
            ExploitCodeMaturity::NotDefined => 1.0,
        }
    }
}

/// Represents the remediation level metric.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, EnumString, Display)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum RemediationLevel {
    #[strum(serialize = "O")]
    OfficialFix,
    #[strum(serialize = "T")]
    TemporaryFix,
    #[strum(serialize = "W")]
    Workaround,
    #[strum(serialize = "U")]
    Unavailable,
    #[strum(serialize = "X")]
    NotDefined,
}

impl RemediationLevel {
    /// Returns the temporal score multiplier for this metric per CVSS v3.x specification.
    pub fn score(&self) -> f64 {
        match self {
            RemediationLevel::OfficialFix => 0.95,
            RemediationLevel::TemporaryFix => 0.96,
            RemediationLevel::Workaround => 0.97,
            RemediationLevel::Unavailable => 1.0,
            RemediationLevel::NotDefined => 1.0,
        }
    }
}

/// Represents the report confidence metric.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, EnumString, Display)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum ReportConfidence {
    #[strum(serialize = "U")]
    Unknown,
    #[strum(serialize = "R")]
    Reasonable,
    #[strum(serialize = "C")]
    Confirmed,
    #[strum(serialize = "X")]
    NotDefined,
}

impl ReportConfidence {
    /// Returns the temporal score multiplier for this metric per CVSS v3.x specification.
    pub fn score(&self) -> f64 {
        match self {
            ReportConfidence::Unknown => 0.92,
            ReportConfidence::Reasonable => 0.96,
            ReportConfidence::Confirmed => 1.0,
            ReportConfidence::NotDefined => 1.0,
        }
    }
}

/// Represents the security requirement metric.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, EnumString, Display)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum SecurityRequirement {
    #[strum(serialize = "L")]
    Low,
    #[strum(serialize = "M")]
    Medium,
    #[strum(serialize = "H")]
    High,
    #[strum(serialize = "X")]
    NotDefined,
}

impl SecurityRequirement {
    /// Returns the environmental score multiplier for this metric per CVSS v3.x specification.
    pub fn score(&self) -> f64 {
        match self {
            SecurityRequirement::Low => 0.5,
            SecurityRequirement::Medium => 1.0,
            SecurityRequirement::High => 1.5,
            SecurityRequirement::NotDefined => 1.0,
        }
    }
}

impl CvssV3 {
    pub fn vector_string(&self) -> &str {
        &self.vector_string
    }

    pub fn base_score(&self) -> f64 {
        self.base_score
    }

    pub fn base_severity(&self) -> Option<UnifiedSeverity> {
        Some(match self.base_severity {
            Severity::None => UnifiedSeverity::None,
            Severity::Low => UnifiedSeverity::Low,
            Severity::Medium => UnifiedSeverity::Medium,
            Severity::High => UnifiedSeverity::High,
            Severity::Critical => UnifiedSeverity::Critical,
        })
    }

    /// Calculates the base score from the base metrics.
    /// Returns None if required base metrics are missing.
    pub fn calculated_base_score(&self) -> Option<f64> {
        // All base metrics are required
        let av = self.attack_vector.as_ref()?;
        let ac = self.attack_complexity.as_ref()?;
        let pr = self.privileges_required.as_ref()?;
        let ui = self.user_interaction.as_ref()?;
        let scope = self.scope.as_ref()?;
        let c = self.confidentiality_impact.as_ref()?;
        let i = self.integrity_impact.as_ref()?;
        let a = self.availability_impact.as_ref()?;

        let scope_changed = scope.is_changed();

        // Calculate exploitability sub-score
        let exploitability = 8.22 * av.score() * ac.score() * pr.score(scope_changed) * ui.score();

        // Calculate impact sub-score
        let impact_sub = 1.0 - ((1.0 - c.score()) * (1.0 - i.score()) * (1.0 - a.score()));

        // Calculate ISS (Impact Sub Score)
        // Base score formula is the same for v3.0 and v3.1
        let iss = if scope_changed {
            7.52 * (impact_sub - 0.029) - 3.25 * (impact_sub - 0.02).powf(15.0)
        } else {
            6.42 * impact_sub
        };

        // Calculate base score
        let score = if iss <= 0.0 {
            0.0
        } else if scope_changed {
            Self::roundup(f64::min(1.08 * (exploitability + iss), 10.0))
        } else {
            Self::roundup(f64::min(exploitability + iss, 10.0))
        };

        Some(score)
    }

    /// Calculates the temporal score from base and temporal metrics.
    /// Returns None if required metrics are missing.
    pub fn calculated_temporal_score(&self) -> Option<f64> {
        let base_score = self.calculated_base_score()?;

        // Temporal metrics default to 1.0 (NotDefined) if not present
        let e = self
            .exploit_code_maturity
            .as_ref()
            .map(|m| m.score())
            .unwrap_or(1.0);
        let rl = self
            .remediation_level
            .as_ref()
            .map(|m| m.score())
            .unwrap_or(1.0);
        let rc = self
            .report_confidence
            .as_ref()
            .map(|m| m.score())
            .unwrap_or(1.0);

        let score = Self::roundup(base_score * e * rl * rc);
        Some(score)
    }

    /// Calculates the environmental score from base, temporal, and environmental metrics.
    /// Returns None if required base metrics are missing.
    pub fn calculated_environmental_score(&self) -> Option<f64> {
        // Get base metrics (required)
        let av = self.attack_vector.as_ref()?;
        let ac = self.attack_complexity.as_ref()?;
        let pr = self.privileges_required.as_ref()?;
        let ui = self.user_interaction.as_ref()?;
        let scope = self.scope.as_ref()?;
        let c = self.confidentiality_impact.as_ref()?;
        let i = self.integrity_impact.as_ref()?;
        let a = self.availability_impact.as_ref()?;

        // Modified metrics: if not present or set to NotDefined (X), fall back to base metric
        let mav = self
            .modified_attack_vector
            .as_ref()
            .filter(|v| !matches!(v, AttackVector::NotDefined))
            .unwrap_or(av);
        let mac = self
            .modified_attack_complexity
            .as_ref()
            .filter(|v| !matches!(v, AttackComplexity::NotDefined))
            .unwrap_or(ac);
        let mpr = self
            .modified_privileges_required
            .as_ref()
            .filter(|v| !matches!(v, PrivilegesRequired::NotDefined))
            .unwrap_or(pr);
        let mui = self
            .modified_user_interaction
            .as_ref()
            .filter(|v| !matches!(v, UserInteraction::NotDefined))
            .unwrap_or(ui);
        let ms = self
            .modified_scope
            .as_ref()
            .filter(|v| !matches!(v, Scope::NotDefined))
            .unwrap_or(scope);
        let mc = self
            .modified_confidentiality_impact
            .as_ref()
            .filter(|v| !matches!(v, Impact::NotDefined))
            .unwrap_or(c);
        let mi = self
            .modified_integrity_impact
            .as_ref()
            .filter(|v| !matches!(v, Impact::NotDefined))
            .unwrap_or(i);
        let ma = self
            .modified_availability_impact
            .as_ref()
            .filter(|v| !matches!(v, Impact::NotDefined))
            .unwrap_or(a);

        // Security requirements default to 1.0 (Medium/NotDefined)
        let cr = self
            .confidentiality_requirement
            .as_ref()
            .map(|r| r.score())
            .unwrap_or(1.0);
        let ir = self
            .integrity_requirement
            .as_ref()
            .map(|r| r.score())
            .unwrap_or(1.0);
        let ar = self
            .availability_requirement
            .as_ref()
            .map(|r| r.score())
            .unwrap_or(1.0);

        let scope_changed = ms.is_changed();

        // Calculate modified exploitability
        let m_exploitability =
            8.22 * mav.score() * mac.score() * mpr.score(scope_changed) * mui.score();

        // Calculate modified impact
        let m_impact_sub = f64::min(
            1.0 - ((1.0 - cr * mc.score()) * (1.0 - ir * mi.score()) * (1.0 - ar * ma.score())),
            0.915,
        );

        // Calculate modified ISS
        // CVSS v3.1 uses a different formula than v3.0
        let m_iss = if scope_changed {
            match self.version {
                Some(VersionV3::V3_1) => {
                    // v3.1: 7.52 × (MISS - 0.029) - 3.25 × (MISS × 0.9731 - 0.02)^13
                    7.52 * (m_impact_sub - 0.029) - 3.25 * (m_impact_sub * 0.9731 - 0.02).powf(13.0)
                }
                _ => {
                    // v3.0: 7.52 × (MISS - 0.029) - 3.25 × (MISS - 0.02)^15
                    7.52 * (m_impact_sub - 0.029) - 3.25 * (m_impact_sub - 0.02).powf(15.0)
                }
            }
        } else {
            6.42 * m_impact_sub
        };

        // Calculate environmental score
        let score = if m_iss <= 0.0 {
            0.0
        } else {
            // Temporal metrics for environmental calculation
            let e = self
                .exploit_code_maturity
                .as_ref()
                .map(|m| m.score())
                .unwrap_or(1.0);
            let rl = self
                .remediation_level
                .as_ref()
                .map(|m| m.score())
                .unwrap_or(1.0);
            let rc = self
                .report_confidence
                .as_ref()
                .map(|m| m.score())
                .unwrap_or(1.0);

            if scope_changed {
                Self::roundup(
                    Self::roundup(f64::min(1.08 * (m_exploitability + m_iss), 10.0)) * e * rl * rc,
                )
            } else {
                Self::roundup(Self::roundup(f64::min(m_exploitability + m_iss, 10.0)) * e * rl * rc)
            }
        };

        Some(score)
    }

    /// Rounds up to 1 decimal place as per CVSS v3 specification.
    ///
    /// Per the CVSS v3 spec, to avoid floating point precision issues,
    /// the input is first multiplied by 100,000 and rounded to the nearest integer.
    /// This ensures consistent rounding across different implementations.
    fn roundup(value: f64) -> f64 {
        // Handle floating point precision by normalizing to integer first
        let int_input = (value * 100000.0).round() as i64;
        let normalized = int_input as f64 / 100000.0;
        (normalized * 10.0).ceil() / 10.0
    }
}

impl FromStr for CvssV3 {
    type Err = ParseError;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        // extract and validate version prefix
        let (version, components_str) = prefix::extract_version_from_required_prefix(s)?;

        // validate that the prefix version is either 3.0 or 3.1
        prefix::validate_allowed_prefix_version(&version, &[Version::V3_0, Version::V3_1])?;

        // map to tightened version enum
        let parsed_version = match version {
            Version::V3_0 => VersionV3::V3_0,
            Version::V3_1 => VersionV3::V3_1,
            _ => unreachable!("validated above"),
        };

        // Initialize a CvssV3 with empty fields
        let mut cvss = CvssV3 {
            vector_string: s.to_string(),
            version: Some(parsed_version),
            base_score: 0.0,
            base_severity: Severity::None,
            attack_vector: None,
            attack_complexity: None,
            privileges_required: None,
            user_interaction: None,
            scope: None,
            confidentiality_impact: None,
            integrity_impact: None,
            availability_impact: None,
            temporal_score: None,
            temporal_severity: None,
            exploit_code_maturity: None,
            remediation_level: None,
            report_confidence: None,
            environmental_score: None,
            environmental_severity: None,
            confidentiality_requirement: None,
            integrity_requirement: None,
            availability_requirement: None,
            modified_attack_vector: None,
            modified_attack_complexity: None,
            modified_privileges_required: None,
            modified_user_interaction: None,
            modified_scope: None,
            modified_confidentiality_impact: None,
            modified_integrity_impact: None,
            modified_availability_impact: None,
        };

        // Parse metrics
        for component in components_str.split('/') {
            if component.is_empty() {
                continue;
            }

            let mut parts = component.split(':');
            let key = parts
                .next()
                .ok_or_else(|| ParseError::InvalidComponent {
                    component: component.to_string(),
                })?
                .to_ascii_uppercase();
            let value = parts
                .next()
                .ok_or_else(|| ParseError::InvalidComponent {
                    component: component.to_string(),
                })?
                .to_ascii_uppercase();

            // Check for extra colons
            if parts.next().is_some() {
                return Err(ParseError::InvalidComponent {
                    component: component.to_string(),
                });
            }

            match key.as_str() {
                // Base metrics
                "AV" => parse_metric(&mut cvss.attack_vector, &value, &key)?,
                "AC" => parse_metric(&mut cvss.attack_complexity, &value, &key)?,
                "PR" => parse_metric(&mut cvss.privileges_required, &value, &key)?,
                "UI" => parse_metric(&mut cvss.user_interaction, &value, &key)?,
                "S" => parse_metric(&mut cvss.scope, &value, &key)?,
                "C" => parse_metric(&mut cvss.confidentiality_impact, &value, &key)?,
                "I" => parse_metric(&mut cvss.integrity_impact, &value, &key)?,
                "A" => parse_metric(&mut cvss.availability_impact, &value, &key)?,
                // Temporal metrics
                "E" => parse_metric(&mut cvss.exploit_code_maturity, &value, &key)?,
                "RL" => parse_metric(&mut cvss.remediation_level, &value, &key)?,
                "RC" => parse_metric(&mut cvss.report_confidence, &value, &key)?,
                // Environmental metrics
                "CR" => parse_metric(&mut cvss.confidentiality_requirement, &value, &key)?,
                "IR" => parse_metric(&mut cvss.integrity_requirement, &value, &key)?,
                "AR" => parse_metric(&mut cvss.availability_requirement, &value, &key)?,
                // Modified metrics
                "MAV" => parse_metric(&mut cvss.modified_attack_vector, &value, &key)?,
                "MAC" => parse_metric(&mut cvss.modified_attack_complexity, &value, &key)?,
                "MPR" => parse_metric(&mut cvss.modified_privileges_required, &value, &key)?,
                "MUI" => parse_metric(&mut cvss.modified_user_interaction, &value, &key)?,
                "MS" => parse_metric(&mut cvss.modified_scope, &value, &key)?,
                "MC" => parse_metric(&mut cvss.modified_confidentiality_impact, &value, &key)?,
                "MI" => parse_metric(&mut cvss.modified_integrity_impact, &value, &key)?,
                "MA" => parse_metric(&mut cvss.modified_availability_impact, &value, &key)?,
                _ => {
                    return Err(ParseError::UnknownMetric { metric: key });
                }
            }
        }

        Ok(cvss)
    }
}

impl fmt::Display for CvssV3 {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        // Determine version from the stored vector_string if possible, default to 3.1
        let version = if self.vector_string.starts_with("CVSS:3.0") {
            "3.0"
        } else {
            "3.1"
        };

        write!(f, "CVSS:{}", version)?;

        // Base metrics
        if let Some(av) = &self.attack_vector {
            write!(f, "/AV:{}", av)?;
        }
        if let Some(ac) = &self.attack_complexity {
            write!(f, "/AC:{}", ac)?;
        }
        if let Some(pr) = &self.privileges_required {
            write!(f, "/PR:{}", pr)?;
        }
        if let Some(ui) = &self.user_interaction {
            write!(f, "/UI:{}", ui)?;
        }
        if let Some(s) = &self.scope {
            write!(f, "/S:{}", s)?;
        }
        if let Some(c) = &self.confidentiality_impact {
            write!(f, "/C:{}", c)?;
        }
        if let Some(i) = &self.integrity_impact {
            write!(f, "/I:{}", i)?;
        }
        if let Some(a) = &self.availability_impact {
            write!(f, "/A:{}", a)?;
        }

        // Temporal metrics
        if let Some(e) = &self.exploit_code_maturity {
            write!(f, "/E:{}", e)?;
        }
        if let Some(rl) = &self.remediation_level {
            write!(f, "/RL:{}", rl)?;
        }
        if let Some(rc) = &self.report_confidence {
            write!(f, "/RC:{}", rc)?;
        }

        // Environmental metrics
        if let Some(cr) = &self.confidentiality_requirement {
            write!(f, "/CR:{}", cr)?;
        }
        if let Some(ir) = &self.integrity_requirement {
            write!(f, "/IR:{}", ir)?;
        }
        if let Some(ar) = &self.availability_requirement {
            write!(f, "/AR:{}", ar)?;
        }
        if let Some(mav) = &self.modified_attack_vector {
            write!(f, "/MAV:{}", mav)?;
        }
        if let Some(mac) = &self.modified_attack_complexity {
            write!(f, "/MAC:{}", mac)?;
        }
        if let Some(mpr) = &self.modified_privileges_required {
            write!(f, "/MPR:{}", mpr)?;
        }
        if let Some(mui) = &self.modified_user_interaction {
            write!(f, "/MUI:{}", mui)?;
        }
        if let Some(ms) = &self.modified_scope {
            write!(f, "/MS:{}", ms)?;
        }
        if let Some(mc) = &self.modified_confidentiality_impact {
            write!(f, "/MC:{}", mc)?;
        }
        if let Some(mi) = &self.modified_integrity_impact {
            write!(f, "/MI:{}", mi)?;
        }
        if let Some(ma) = &self.modified_availability_impact {
            write!(f, "/MA:{}", ma)?;
        }

        Ok(())
    }
}