csaf-models 0.3.1

CSAF 2.0/2.1 data models, SQLite management, and user models
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
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
// SPDX-License-Identifier: Apache-2.0
// Copyright (c) 2026 Pierre Gronau, ndaal in Cologne

//! Full CSAF 2.0 and 2.1 document serde types.
//!
//! These types are derived from the OASIS CSAF 2.1 JSON schema and the 15 test
//! advisory files in `test/csaf/`. They support both serialization and
//! deserialization with strict field validation.

use serde::{Deserialize, Serialize};

// ---------------------------------------------------------------------------
// Top-level CSAF document
// ---------------------------------------------------------------------------

/// A complete CSAF document (versions 2.0 and 2.1).
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct CsafDocument {
    /// JSON schema URL.
    #[serde(rename = "$schema", skip_serializing_if = "Option::is_none")]
    pub schema: Option<String>,

    /// Core document metadata.
    pub document: Document,

    /// Product tree describing affected products.
    pub product_tree: ProductTree,

    /// List of vulnerabilities described by this advisory.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub vulnerabilities: Vec<Vulnerability>,
}

// ---------------------------------------------------------------------------
// Document metadata
// ---------------------------------------------------------------------------

/// Core document metadata section.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct Document {
    /// Document category (e.g. `csaf_security_advisory`, `csaf_vex`,
    /// `csaf_informational_advisory`).
    pub category: String,

    /// CSAF version (`"2.0"` or `"2.1"`).
    pub csaf_version: String,

    /// Distribution restrictions.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub distribution: Option<Distribution>,

    /// Document language (BCP 47 tag, e.g. `"en"`).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub lang: Option<String>,

    /// Informational notes about the document.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub notes: Vec<Note>,

    /// Publisher information.
    pub publisher: Publisher,

    /// External references.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub references: Vec<Reference>,

    /// Document title.
    pub title: String,

    /// Document lifecycle tracking.
    pub tracking: Tracking,
}

/// Distribution restrictions (TLP labelling and free-form restrictions).
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct Distribution {
    /// TLP information.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub tlp: Option<Tlp>,

    /// Free-form textual distribution restrictions beyond TLP. Used to
    /// carry Verschlusssache / NATO classification strings when the user
    /// selects `distribution_text` or `both` as the storage mode.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub text: Option<String>,
}

/// Traffic Light Protocol label.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct Tlp {
    /// TLP label (`CLEAR`, `GREEN`, `AMBER`, `AMBER+STRICT`, `RED`).
    pub label: String,

    /// Optional TLP specification URL.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub url: Option<String>,
}

/// A textual note within the document or vulnerability.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct Note {
    /// Note category (`summary`, `description`, `general`, `legal_disclaimer`,
    /// `other`, `faq`, `details`).
    pub category: String,

    /// Note text content.
    pub text: String,

    /// Optional note title.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub title: Option<String>,

    /// Optional target audience.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub audience: Option<String>,
}

/// Publisher identity and role.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct Publisher {
    /// Publisher category (`vendor`, `discoverer`, `coordinator`, `user`,
    /// `other`, `translator`).
    pub category: String,

    /// Contact information.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub contact_details: Option<String>,

    /// Issuing authority description.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub issuing_authority: Option<String>,

    /// Publisher name.
    pub name: String,

    /// Publisher namespace URI.
    pub namespace: String,
}

/// A reference to an external resource.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct Reference {
    /// Reference category (`self`, `external`).
    pub category: String,

    /// Description of the reference.
    pub summary: String,

    /// URL of the referenced resource.
    pub url: String,
}

// ---------------------------------------------------------------------------
// Tracking
// ---------------------------------------------------------------------------

/// Document lifecycle tracking information.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct Tracking {
    /// Date of the current release.
    pub current_release_date: String,

    /// Generator tool information.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub generator: Option<Generator>,

    /// Document tracking identifier (e.g. `ndaal-sa-2026-001`).
    pub id: String,

    /// Date of the initial release.
    pub initial_release_date: String,

    /// Revision history entries.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub revision_history: Vec<Revision>,

    /// Document status (`draft`, `interim`, `final`).
    pub status: String,

    /// Document version (semver-like, e.g. `"1.0.0"`).
    pub version: String,

    /// Aliases for this tracking ID.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub aliases: Vec<String>,
}

/// Generator engine metadata.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct Generator {
    /// Generator engine details.
    pub engine: Engine,

    /// Generation date.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub date: Option<String>,
}

/// Generator engine identification.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct Engine {
    /// Engine name.
    pub name: String,

    /// Engine version.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub version: Option<String>,
}

/// A single revision history entry.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct Revision {
    /// Revision date.
    pub date: String,

    /// Revision number (semver-like).
    pub number: String,

    /// Summary of changes in this revision.
    pub summary: String,
}

// ---------------------------------------------------------------------------
// Product tree
// ---------------------------------------------------------------------------

/// Product hierarchy tree.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct ProductTree {
    /// Branch hierarchy of vendors, products, and versions.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub branches: Vec<Branch>,

    /// Full product names defined outside the branch hierarchy.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub full_product_names: Vec<FullProductName>,

    /// Product groupings for vulnerability status.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub product_groups: Vec<ProductGroup>,

    /// Relationships between products.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub relationships: Vec<Relationship>,
}

/// A branch in the product tree hierarchy.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct Branch {
    /// Branch category (`vendor`, `product_name`, `product_version`,
    /// `product_version_range`, `product_family`, `architecture`, `language`,
    /// `legacy`, `patch_level`, `service_pack`, `specification`, `host_name`).
    pub category: String,

    /// Branch display name.
    pub name: String,

    /// Child branches.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub branches: Vec<Self>,

    /// Product definition at this branch level.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub product: Option<FullProductName>,
}

/// A full product name definition.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct FullProductName {
    /// Human-readable product name.
    pub name: String,

    /// Unique product identifier within this document.
    pub product_id: String,

    /// CPE identifier.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub cpe: Option<String>,

    /// PURL identifier.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub purl: Option<String>,
}

/// A grouping of products.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct ProductGroup {
    /// Group identifier.
    pub group_id: String,

    /// Product IDs in this group.
    pub product_ids: Vec<String>,

    /// Optional group summary.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub summary: Option<String>,
}

/// A relationship between products.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct Relationship {
    /// Relationship category.
    pub category: String,

    /// Full product name for the relationship.
    pub full_product_name: FullProductName,

    /// Product reference.
    pub product_reference: String,

    /// Relates-to product reference.
    pub relates_to_product_reference: String,
}

// ---------------------------------------------------------------------------
// Vulnerabilities
// ---------------------------------------------------------------------------

/// A vulnerability entry within a CSAF document.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct Vulnerability {
    /// CVE identifier (e.g. `CVE-2024-1234`).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub cve: Option<String>,

    /// CWE weakness classification.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub cwe: Option<Cwe>,

    /// Date the vulnerability was discovered.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub discovery_date: Option<String>,

    /// Additional identifiers.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub ids: Vec<VulnerabilityId>,

    /// Informational notes about the vulnerability.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub notes: Vec<Note>,

    /// Product status classifications.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub product_status: Option<ProductStatus>,

    /// Remediation steps.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub remediations: Vec<Remediation>,

    /// CVSS scoring metrics.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub metrics: Vec<Metric>,

    /// Threat information.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub threats: Vec<Threat>,

    /// Vulnerability title.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub title: Option<String>,

    /// Release date.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub release_date: Option<String>,

    /// Vulnerability references.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub references: Vec<Reference>,

    /// Involvements.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub involvements: Vec<Involvement>,

    /// Flags.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub flags: Vec<Flag>,
}

/// CWE (Common Weakness Enumeration) reference.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct Cwe {
    /// CWE identifier (e.g. `CWE-79`).
    pub id: String,

    /// CWE name.
    pub name: String,
}

/// Additional vulnerability identifier.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct VulnerabilityId {
    /// Identifier system name (e.g. `RustSec`).
    pub system_name: String,

    /// Identifier value.
    pub text: String,
}

/// Product status classifications for a vulnerability.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct ProductStatus {
    /// Products confirmed to be affected.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub known_affected: Vec<String>,

    /// Products confirmed to be not affected.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub known_not_affected: Vec<String>,

    /// Products with the vulnerability fixed.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub fixed: Vec<String>,

    /// Products under investigation.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub under_investigation: Vec<String>,

    /// First affected product versions.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub first_affected: Vec<String>,

    /// First fixed product versions.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub first_fixed: Vec<String>,

    /// Last affected product versions.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub last_affected: Vec<String>,

    /// Recommended product versions.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub recommended: Vec<String>,
}

/// Remediation action for a vulnerability.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct Remediation {
    /// Remediation category (`vendor_fix`, `mitigation`, `workaround`,
    /// `no_fix_planned`, `none_available`).
    pub category: String,

    /// Remediation description.
    pub details: String,

    /// Affected product IDs.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub product_ids: Vec<String>,

    /// Affected product group IDs.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub group_ids: Vec<String>,

    /// Remediation URL.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub url: Option<String>,

    /// Remediation date.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub date: Option<String>,

    /// Restart required.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub restart_required: Option<RestartRequired>,

    /// Entitlements.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub entitlements: Vec<String>,
}

/// Restart requirement specification.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct RestartRequired {
    /// Restart category.
    pub category: String,

    /// Additional details.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub details: Option<String>,
}

/// CVSS scoring metric container.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct Metric {
    /// Metric content containing CVSS scores.
    pub content: MetricContent,

    /// Product IDs this metric applies to.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub products: Vec<String>,

    /// Source of the metric.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub source: Option<String>,
}

/// Metric content containing one or both CVSS versions.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct MetricContent {
    /// CVSS v3.1 scoring.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub cvss_v3: Option<CvssV3>,

    /// CVSS v4.0 scoring.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub cvss_v4: Option<CvssV4>,
}

/// CVSS v3.1 scoring data.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct CvssV3 {
    /// CVSS version (always `"3.1"`).
    pub version: String,

    /// CVSS vector string.
    #[serde(rename = "vectorString")]
    pub vector_string: String,

    /// Base score (0.0 to 10.0).
    #[serde(rename = "baseScore")]
    pub base_score: f64,

    /// Base severity (`NONE`, `LOW`, `MEDIUM`, `HIGH`, `CRITICAL`).
    #[serde(rename = "baseSeverity")]
    pub base_severity: String,

    /// Attack vector.
    #[serde(rename = "attackVector", skip_serializing_if = "Option::is_none")]
    pub attack_vector: Option<String>,

    /// Attack complexity.
    #[serde(rename = "attackComplexity", skip_serializing_if = "Option::is_none")]
    pub attack_complexity: Option<String>,

    /// Privileges required.
    #[serde(rename = "privilegesRequired", skip_serializing_if = "Option::is_none")]
    pub privileges_required: Option<String>,

    /// User interaction.
    #[serde(rename = "userInteraction", skip_serializing_if = "Option::is_none")]
    pub user_interaction: Option<String>,

    /// Scope.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub scope: Option<String>,

    /// Confidentiality impact.
    #[serde(
        rename = "confidentialityImpact",
        skip_serializing_if = "Option::is_none"
    )]
    pub confidentiality_impact: Option<String>,

    /// Integrity impact.
    #[serde(rename = "integrityImpact", skip_serializing_if = "Option::is_none")]
    pub integrity_impact: Option<String>,

    /// Availability impact.
    #[serde(rename = "availabilityImpact", skip_serializing_if = "Option::is_none")]
    pub availability_impact: Option<String>,
}

/// CVSS v4.0 scoring data.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct CvssV4 {
    /// CVSS version (always `"4.0"`).
    pub version: String,

    /// CVSS vector string.
    #[serde(rename = "vectorString")]
    pub vector_string: String,

    /// Base score (0.0 to 10.0).
    #[serde(rename = "baseScore")]
    pub base_score: f64,

    /// Base severity (`NONE`, `LOW`, `MEDIUM`, `HIGH`, `CRITICAL`).
    #[serde(rename = "baseSeverity")]
    pub base_severity: String,

    /// Attack vector.
    #[serde(rename = "attackVector", skip_serializing_if = "Option::is_none")]
    pub attack_vector: Option<String>,

    /// Attack complexity.
    #[serde(rename = "attackComplexity", skip_serializing_if = "Option::is_none")]
    pub attack_complexity: Option<String>,

    /// Attack requirements.
    #[serde(rename = "attackRequirements", skip_serializing_if = "Option::is_none")]
    pub attack_requirements: Option<String>,

    /// Privileges required.
    #[serde(rename = "privilegesRequired", skip_serializing_if = "Option::is_none")]
    pub privileges_required: Option<String>,

    /// User interaction.
    #[serde(rename = "userInteraction", skip_serializing_if = "Option::is_none")]
    pub user_interaction: Option<String>,

    /// Confidentiality impact (vulnerable component).
    #[serde(
        rename = "confidentialityImpact",
        skip_serializing_if = "Option::is_none"
    )]
    pub confidentiality_impact: Option<String>,

    /// Integrity impact (vulnerable component).
    #[serde(rename = "integrityImpact", skip_serializing_if = "Option::is_none")]
    pub integrity_impact: Option<String>,

    /// Availability impact (vulnerable component).
    #[serde(rename = "availabilityImpact", skip_serializing_if = "Option::is_none")]
    pub availability_impact: Option<String>,

    /// Confidentiality impact (subsequent system).
    #[serde(
        rename = "subConfidentialityImpact",
        skip_serializing_if = "Option::is_none"
    )]
    pub sub_confidentiality_impact: Option<String>,

    /// Integrity impact (subsequent system).
    #[serde(rename = "subIntegrityImpact", skip_serializing_if = "Option::is_none")]
    pub sub_integrity_impact: Option<String>,

    /// Availability impact (subsequent system).
    #[serde(
        rename = "subAvailabilityImpact",
        skip_serializing_if = "Option::is_none"
    )]
    pub sub_availability_impact: Option<String>,
}

/// Threat information.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct Threat {
    /// Threat category (`exploit_status`, `impact`, `target_set`).
    pub category: String,

    /// Threat description.
    pub details: String,

    /// Affected product IDs.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub product_ids: Vec<String>,

    /// Affected product group IDs.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub group_ids: Vec<String>,

    /// Date of threat assessment.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub date: Option<String>,
}

/// Involvement information.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct Involvement {
    /// Party involved.
    pub party: String,

    /// Status of involvement.
    pub status: String,

    /// Summary.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub summary: Option<String>,
}

/// Flag on a vulnerability.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct Flag {
    /// Label.
    pub label: String,

    /// Date.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub date: Option<String>,

    /// Product IDs.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub product_ids: Vec<String>,

    /// Group IDs.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub group_ids: Vec<String>,
}

// ---------------------------------------------------------------------------
// Helper: extract all product IDs from the product tree
// ---------------------------------------------------------------------------

impl CsafDocument {
    /// Extract all product IDs defined in the product tree.
    #[must_use]
    pub fn all_product_ids(&self) -> Vec<String> {
        let mut ids = Vec::new();
        collect_product_ids_from_branches(&self.product_tree.branches, &mut ids);
        for fpn in &self.product_tree.full_product_names {
            ids.push(fpn.product_id.clone());
        }
        ids
    }

    /// Get the tracking ID.
    #[must_use]
    pub fn tracking_id(&self) -> &str {
        &self.document.tracking.id
    }

    /// Get the CSAF version.
    #[must_use]
    pub fn csaf_version(&self) -> &str {
        &self.document.csaf_version
    }

    /// Get the document category.
    #[must_use]
    pub fn category(&self) -> &str {
        &self.document.category
    }
}

/// Recursively collect product IDs from branch hierarchy.
fn collect_product_ids_from_branches(branches: &[Branch], ids: &mut Vec<String>) {
    for branch in branches {
        if let Some(product) = &branch.product {
            ids.push(product.product_id.clone());
        }
        collect_product_ids_from_branches(&branch.branches, ids);
    }
}

// ---------------------------------------------------------------------------
// Summary metadata (for listing/search, stored separately from full doc)
// ---------------------------------------------------------------------------

/// Lightweight metadata extracted from a CSAF document for listing and search.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct CsafMeta {
    /// Tracking identifier.
    pub tracking_id: String,

    /// Document title.
    pub title: String,

    /// Document category.
    pub category: String,

    /// CSAF version.
    pub csaf_version: String,

    /// Document status.
    pub status: String,

    /// Current release date (ISO 8601).
    pub current_release_date: String,

    /// Initial release date (ISO 8601).
    pub initial_release_date: String,

    /// Document version.
    pub version: String,

    /// Publisher name.
    pub publisher_name: String,

    /// TLP label.
    pub tlp_label: Option<String>,

    /// Number of vulnerabilities.
    pub vulnerability_count: usize,

    /// Highest CVSS v3.1 base score across all vulnerabilities.
    pub max_cvss_v3_score: Option<f64>,

    /// Highest CVSS v4.0 base score across all vulnerabilities.
    pub max_cvss_v4_score: Option<f64>,
}

impl CsafMeta {
    /// Extract summary metadata from a full CSAF document.
    #[must_use]
    pub fn from_document(doc: &CsafDocument) -> Self {
        let tlp_label = doc
            .document
            .distribution
            .as_ref()
            .and_then(|d| d.tlp.as_ref())
            .map(|t| t.label.clone());

        let mut max_v3: Option<f64> = None;
        let mut max_v4: Option<f64> = None;

        for vuln in &doc.vulnerabilities {
            for metric in &vuln.metrics {
                if let Some(v3) = &metric.content.cvss_v3 {
                    let current = max_v3.unwrap_or(0.0);
                    if v3.base_score > current {
                        max_v3 = Some(v3.base_score);
                    }
                }
                if let Some(v4) = &metric.content.cvss_v4 {
                    let current = max_v4.unwrap_or(0.0);
                    if v4.base_score > current {
                        max_v4 = Some(v4.base_score);
                    }
                }
            }
        }

        Self {
            tracking_id: doc.document.tracking.id.clone(),
            title: doc.document.title.clone(),
            category: doc.document.category.clone(),
            csaf_version: doc.document.csaf_version.clone(),
            status: doc.document.tracking.status.clone(),
            current_release_date: doc.document.tracking.current_release_date.clone(),
            initial_release_date: doc.document.tracking.initial_release_date.clone(),
            version: doc.document.tracking.version.clone(),
            publisher_name: doc.document.publisher.name.clone(),
            tlp_label,
            vulnerability_count: doc.vulnerabilities.len(),
            max_cvss_v3_score: max_v3,
            max_cvss_v4_score: max_v4,
        }
    }
}

#[cfg(test)]
// Dense assertion blocks in tests are allowed to keep one round-trip
// test per fixture readable; clippy's cognitive-complexity threshold
// is tuned for production code paths.
#[allow(clippy::cognitive_complexity)]
mod tests {
    use super::*;

    #[test]
    fn test_deserialize_csaf_security_advisory() {
        let json = include_str!("../../../test/csaf/2026/003/ndaal-sa-2026-003.json");
        let doc: CsafDocument =
            serde_json::from_str(json).expect("Failed to deserialize CSAF document");

        assert_eq!(doc.document.category, "csaf_security_advisory");
        assert_eq!(doc.document.csaf_version, "2.1");
        assert_eq!(doc.document.tracking.id, "ndaal-sa-2026-003");
        assert_eq!(doc.document.tracking.status, "final");
        assert_eq!(
            doc.document.publisher.name,
            "ndaal Gesellschaft f\u{fc}r Sicherheit in der Informationstechnik mbH & Co KG"
        );
        assert_eq!(doc.vulnerabilities.len(), 1);

        let vuln = &doc.vulnerabilities[0];
        assert_eq!(vuln.cve.as_deref(), Some("CVE-0000-0001"));
        assert_eq!(vuln.metrics.len(), 1);

        let metric = &vuln.metrics[0];
        let v3 = metric.content.cvss_v3.as_ref().expect("CVSS v3 missing");
        assert!((v3.base_score - 9.8).abs() < f64::EPSILON);
        assert_eq!(v3.base_severity, "CRITICAL");

        let v4 = metric.content.cvss_v4.as_ref().expect("CVSS v4 missing");
        assert!((v4.base_score - 9.3).abs() < f64::EPSILON);
    }

    #[test]
    fn test_deserialize_csaf_vex() {
        let json = include_str!("../../../test/csaf/2026/015/ndaal-sa-2026-015.json");
        let doc: CsafDocument =
            serde_json::from_str(json).expect("Failed to deserialize VEX document");

        assert_eq!(doc.document.category, "csaf_vex");
        assert_eq!(doc.document.tracking.id, "ndaal-sa-2026-015");
    }

    #[test]
    fn test_deserialize_all_test_files() {
        let test_dir =
            std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../test/csaf/2026");

        for entry in std::fs::read_dir(&test_dir).expect("test dir missing") {
            let entry = entry.expect("dir entry error");
            if !entry.file_type().expect("file type error").is_dir() {
                continue;
            }
            for file in std::fs::read_dir(entry.path()).expect("subdir read error") {
                let file = file.expect("file entry error");
                let path = file.path();
                if path.extension().is_some_and(|e| e == "json") {
                    let content = std::fs::read_to_string(&path)
                        .unwrap_or_else(|e| panic!("Failed to read {}: {e}", path.display()));
                    let result: Result<CsafDocument, _> = serde_json::from_str(&content);
                    assert!(
                        result.is_ok(),
                        "Failed to parse {}: {:?}",
                        path.display(),
                        result.err()
                    );
                }
            }
        }
    }

    #[test]
    fn test_csaf_meta_extraction() {
        let json = include_str!("../../../test/csaf/2026/003/ndaal-sa-2026-003.json");
        let doc: CsafDocument = serde_json::from_str(json).expect("parse error");
        let meta = CsafMeta::from_document(&doc);

        assert_eq!(meta.tracking_id, "ndaal-sa-2026-003");
        assert_eq!(meta.category, "csaf_security_advisory");
        assert_eq!(meta.vulnerability_count, 1);
        assert!(
            meta.max_cvss_v3_score
                .is_some_and(|s| (s - 9.8).abs() < f64::EPSILON)
        );
        assert!(
            meta.max_cvss_v4_score
                .is_some_and(|s| (s - 9.3).abs() < f64::EPSILON)
        );
        assert_eq!(meta.tlp_label.as_deref(), Some("CLEAR"));
    }

    #[test]
    fn test_all_product_ids() {
        let json = include_str!("../../../test/csaf/2026/003/ndaal-sa-2026-003.json");
        let doc: CsafDocument = serde_json::from_str(json).expect("parse error");
        let ids = doc.all_product_ids();

        assert!(ids.contains(&"CSAFPID-001".to_owned()));
        assert!(ids.contains(&"CSAFPID-002".to_owned()));
    }

    #[test]
    fn test_roundtrip_serialization() {
        let json = include_str!("../../../test/csaf/2026/003/ndaal-sa-2026-003.json");
        let doc: CsafDocument = serde_json::from_str(json).expect("parse error");
        let serialized = serde_json::to_string_pretty(&doc).expect("serialize error");
        let doc2: CsafDocument = serde_json::from_str(&serialized).expect("re-parse error");
        assert_eq!(doc, doc2);
    }
}