cargo-cyclonedx 0.5.2

CycloneDX Software Bill of Materials (SBOM) for Rust Crates
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
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
use crate::config::Describe;
/*
 * This file is part of CycloneDX Rust Cargo.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 * SPDX-License-Identifier: Apache-2.0
 */
use crate::config::FilenamePattern;
use crate::config::PlatformSuffix;
use crate::config::SbomConfig;
use crate::config::{IncludedDependencies, ParseMode};
use crate::format::Format;
use crate::purl::get_purl;

use cargo_metadata;
use cargo_metadata::DependencyKind;
use cargo_metadata::Metadata as CargoMetadata;
use cargo_metadata::Node;
use cargo_metadata::NodeDep;
use cargo_metadata::Package;
use cargo_metadata::PackageId;

use cargo_lock::package::Checksum;
use cargo_lock::Lockfile;
use cargo_metadata::camino::Utf8PathBuf;
use cyclonedx_bom::external_models::normalized_string::NormalizedString;
use cyclonedx_bom::external_models::spdx::SpdxExpression;
use cyclonedx_bom::external_models::uri::Uri;
use cyclonedx_bom::models::attached_text::AttachedText;
use cyclonedx_bom::models::bom::Bom;
use cyclonedx_bom::models::component::{Classification, Component, Components, Scope};
use cyclonedx_bom::models::dependency::{Dependencies, Dependency};
use cyclonedx_bom::models::external_reference::{
    ExternalReference, ExternalReferenceType, ExternalReferences,
};
use cyclonedx_bom::models::license::{License, LicenseChoice, Licenses};
use cyclonedx_bom::models::metadata::Metadata;
use cyclonedx_bom::models::metadata::MetadataError;
use cyclonedx_bom::models::organization::OrganizationalContact;
use cyclonedx_bom::models::tool::{Tool, Tools};
use cyclonedx_bom::validation::Validate;
use once_cell::sync::Lazy;
use regex::Regex;

use log::Level;
use std::collections::BTreeMap;
use std::collections::HashMap;
use std::convert::TryFrom;
use std::fs::File;
use std::io::BufWriter;
use std::io::Write;
use std::path::Path;
use std::path::PathBuf;
use thiserror::Error;
use validator::validate_email;

// Maps from PackageId to Package for efficiency - faster lookups than in a Vec
type PackageMap = BTreeMap<PackageId, Package>;
type ResolveMap = BTreeMap<PackageId, Node>;

pub struct SbomGenerator {
    config: SbomConfig,
    workspace_root: Utf8PathBuf,
    crate_hashes: HashMap<cargo_metadata::PackageId, Checksum>,
}

/// Contains a map from `bom_ref` of a subcomponent to the kinds of Cargo targets it has,
/// sourced from `cargo metadata`
#[derive(Debug, Clone)]
pub struct TargetKinds(
    // TODO: refactor it to store Vec<TargetKind> once `cargo_metadata` crate ships enums:
    // https://github.com/oli-obk/cargo_metadata/pull/258
    HashMap<String, Vec<String>>,
);

impl SbomGenerator {
    pub fn create_sboms(
        meta: CargoMetadata,
        config: &SbomConfig,
    ) -> Result<Vec<GeneratedSbom>, GeneratorError> {
        log::trace!("Processing the workspace {}", meta.workspace_root);
        let members: Vec<PackageId> = meta.workspace_members;
        let packages = index_packages(meta.packages);
        let resolve = index_resolve(meta.resolve.unwrap().nodes);

        let mut result = Vec::with_capacity(members.len());
        for member in members.iter() {
            log::trace!("Processing the package {}", member);

            let (dependencies, pruned_resolve) =
                if config.included_dependencies() == IncludedDependencies::AllDependencies {
                    all_dependencies(member, &packages, &resolve)
                } else {
                    top_level_dependencies(member, &packages, &resolve)
                };

            let manifest_path = packages[member].manifest_path.clone().into_std_path_buf();

            let mut crate_hashes = HashMap::new();
            match locate_cargo_lock(&manifest_path) {
                Ok(path) => match Lockfile::load(path) {
                    Ok(lockfile_contents) => crate_hashes = package_hashes(&lockfile_contents),
                    Err(err) => log::warn!(
                        "Failed to parse `Cargo.lock`: {err}\n\
                        Hashes will not be included in the SBOM."
                    ),
                },
                Err(err) => log::warn!(
                    "Failed to locate `Cargo.lock`: {err}\n\
                    Hashes will not be included in the SBOM."
                ),
            }

            let generator = SbomGenerator {
                config: config.clone(),
                workspace_root: meta.workspace_root.to_owned(),
                crate_hashes,
            };
            let (bom, target_kinds) =
                generator.create_bom(member, &dependencies, &pruned_resolve)?;

            let generated = GeneratedSbom {
                bom,
                manifest_path,
                package_name: packages[member].name.clone(),
                sbom_config: generator.config,
                target_kinds,
            };

            result.push(generated);
        }

        Ok(result)
    }

    fn create_bom(
        &self,
        package: &PackageId,
        packages: &PackageMap,
        resolve: &ResolveMap,
    ) -> Result<(Bom, TargetKinds), GeneratorError> {
        let mut bom = Bom::default();
        let root_package = &packages[package];

        let components: Vec<_> = packages
            .values()
            .filter(|p| &p.id != package)
            .map(|component| self.create_component(component, root_package))
            .collect();

        bom.components = Some(Components(components));

        let (metadata, target_kinds) = self.create_metadata(&packages[package])?;

        bom.metadata = Some(metadata);

        bom.dependencies = Some(create_dependencies(resolve));

        Ok((bom, target_kinds))
    }

    fn create_component(&self, package: &Package, root_package: &Package) -> Component {
        let name = package.name.to_owned().trim().to_string();
        let version = package.version.to_string();

        let purl = match get_purl(package, root_package, &self.workspace_root, None) {
            Ok(purl) => Some(purl),
            Err(e) => {
                log::warn!("Package {} has an invalid Purl: {} ", package.name, e);
                None
            }
        };

        let mut component = Component::new(
            Classification::Library,
            &name,
            &version,
            Some(package.id.to_string()),
        );

        component.purl = purl;
        component.scope = Some(Scope::Required);
        component.external_references = Self::get_external_references(package);
        component.licenses = self.get_licenses(package);
        component.hashes = self.get_hashes(package);

        component.description = package
            .description
            .as_ref()
            .map(|s| NormalizedString::new(s));

        component
    }

    /// Same as [Self::create_component] but also includes information
    /// on binaries and libraries comprising it as subcomponents
    fn create_toplevel_component(&self, package: &Package) -> (Component, TargetKinds) {
        let mut top_component = self.create_component(package, package);
        let mut subcomponents: Vec<Component> = Vec::new();
        let mut target_kinds = HashMap::new();
        for tgt in filter_targets(&package.targets) {
            // classification
            #[allow(clippy::if_same_then_else)]
            let cdx_type = if tgt.is_bin() {
                Classification::Application
            // sadly no .is_proc_macro() yet
            } else if tgt.kind.iter().any(|kind| kind == "proc-macro") {
                // There isn't a better way to express it with CycloneDX types
                Classification::Library
            } else if tgt.kind.iter().any(|kind| kind.contains("lib")) {
                Classification::Library
            } else {
                log::warn!(
                    "Target {} is neither a binary nor a library! Kinds: {}",
                    tgt.name,
                    tgt.kind.join(", ")
                );
                continue;
            };

            // bom_ref
            let bom_ref = format!(
                "{} bin-target-{}",
                top_component.bom_ref.as_ref().unwrap(),
                subcomponents.len(), // numbers the components
            );

            // record target kinds now that we have the bom_ref
            target_kinds.insert(bom_ref.clone(), tgt.kind.clone());

            // create the subcomponent
            let mut subcomponent = Component::new(
                cdx_type,
                &tgt.name,
                &package.version.to_string(),
                Some(bom_ref),
            );

            // PURL subpaths are computed relative to the directory with the `Cargo.toml`
            // *for this specific package*, not the workspace root.
            // This is done because the tarball uploaded to crates.io only contains the package,
            // not the workspace, so paths resolved relatively to the workspace root would not be valid.
            //
            // When using a git repo that contains a workspace, Cargo will automatically select
            // the right package out of the workspace. Paths can then be resolved relatively to it.
            // So the information we encode here is sufficient to idenfity the file in git too.
            let package_dir = package
                .manifest_path
                .parent()
                .expect("manifest_path in `cargo metadata` output is not a file!");
            if let Ok(relative_path) = tgt.src_path.strip_prefix(package_dir) {
                subcomponent.purl =
                    get_purl(package, package, &self.workspace_root, Some(relative_path)).ok();
            } else {
                log::warn!(
                    "Source path \"{}\" is not a subpath of workspace root \"{}\"",
                    tgt.src_path,
                    self.workspace_root
                );
            }

            subcomponents.push(subcomponent);
        }
        top_component.components = Some(Components(subcomponents));
        (top_component, TargetKinds(target_kinds))
    }

    fn get_classification(pkg: &Package) -> Classification {
        // Transitive dependencies that contain both libraries and binaries
        // get surfaces only as a library by `cargo metadata`.
        //
        // Both "bin" and "lib" can only occur together in the toplevel package,
        // and we record its constituent parts in detail.
        //
        // We have to make a judgement call how to summarise having both bin and lib targets,
        // and that call is "consider it a binary".
        if pkg.targets.iter().any(|tgt| tgt.is_bin()) {
            return Classification::Application;
        }

        Classification::Library
    }

    fn get_external_references(package: &Package) -> Option<ExternalReferences> {
        let mut references = Vec::new();

        if let Some(documentation) = &package.documentation {
            match Uri::try_from(documentation.to_string()) {
                Ok(uri) => references.push(ExternalReference::new(
                    ExternalReferenceType::Documentation,
                    uri,
                )),
                Err(e) => log::warn!(
                    "Package {} has an invalid documentation URI ({}): {} ",
                    package.name,
                    documentation,
                    e
                ),
            }
        }

        if let Some(website) = &package.homepage {
            match Uri::try_from(website.to_string()) {
                Ok(uri) => {
                    references.push(ExternalReference::new(ExternalReferenceType::Website, uri))
                }
                Err(e) => log::warn!(
                    "Package {} has an invalid homepage URI ({}): {} ",
                    package.name,
                    website,
                    e
                ),
            }
        }

        if let Some(other) = &package.links {
            match Uri::try_from(other.to_string()) {
                Ok(uri) => {
                    references.push(ExternalReference::new(ExternalReferenceType::Other, uri))
                }
                Err(e) => log::warn!(
                    "Package {} has an invalid links URI ({}): {} ",
                    package.name,
                    other,
                    e
                ),
            }
        }

        if let Some(vcs) = &package.repository {
            match Uri::try_from(vcs.to_string()) {
                Ok(uri) => references.push(ExternalReference::new(ExternalReferenceType::Vcs, uri)),
                Err(e) => log::warn!(
                    "Package {} has an invalid repository URI ({}): {} ",
                    package.name,
                    vcs,
                    e
                ),
            }
        }

        if !references.is_empty() {
            return Some(ExternalReferences(references));
        }

        None
    }

    fn get_licenses(&self, package: &Package) -> Option<Licenses> {
        let mut licenses = vec![];

        if let Some(license) = &package.license {
            let parse_mode = self
                .config
                .license_parser
                .as_ref()
                .map(|opts| opts.mode)
                .unwrap_or_default();

            log::trace!(
                "Using license parser mode [{:?}] for package [{}@{}]",
                parse_mode,
                package.name,
                package.version
            );

            let result = match parse_mode {
                ParseMode::Strict => SpdxExpression::try_from(license.to_string()),
                ParseMode::Lax => SpdxExpression::parse_lax(license.to_string()),
            };

            match result {
                Ok(expression) => licenses.push(LicenseChoice::Expression(expression)),
                Err(err) => {
                    let level = match &self.config.license_parser {
                        Some(opts) if opts.accept_named.contains(license) => Level::Info,
                        _ => Level::Warn,
                    };
                    log::log!(
                        level,
                        "Package {} has an invalid license expression ({}), using as named license: {}",
                        package.name,
                        license,
                        err,
                    );
                    licenses.push(LicenseChoice::License(License::named_license(license)))
                }
            }
        }

        // Check for license file.
        // It is possible to specify both a named license and a license file in Cargo.toml.
        // If that happens, we encode both.
        if let Some(license_file) = package.license_file().as_ref() {
            match std::fs::read_to_string(license_file.as_path()) {
                Ok(content) => {
                    let mut license = License::named_license("Unknown");
                    let encoded_text = AttachedText::new(None, content);
                    license.text = Some(encoded_text);
                    licenses.push(LicenseChoice::License(license));
                }
                Err(error) => {
                    log::warn!(
                        "Failed to read license file '{}' for package {}: {}",
                        package.name,
                        license_file,
                        error
                    );
                }
            }
        }

        if licenses.is_empty() {
            log::trace!(
                "Package {} has no licenses or license file specified",
                package.name
            );
            return None;
        }

        Some(Licenses(licenses))
    }

    fn get_hashes(&self, package: &Package) -> Option<cyclonedx_bom::models::hash::Hashes> {
        match self.crate_hashes.get(&package.id) {
            Some(hash) => Some(cyclonedx_bom::models::hash::Hashes(vec![to_bom_hash(hash)])),
            None => {
                // Log level is set to debug because this is perfectly normal:
                // First, only Rust 1.77 and later has `cargo metadata` output pkgid format,
                // so anything prior to that won't match.
                // Second, only packages coming from registries have a checksum associated with them,
                // while local or git packages do not have a checksum and that too is normal.
                log::debug!(
                    "Hash for package ID {} not found in Cargo.lock",
                    &package.id
                );
                None
            }
        }
    }

    fn create_metadata(
        &self,
        package: &Package,
    ) -> Result<(Metadata, TargetKinds), GeneratorError> {
        let authors = Self::create_authors(package);

        let mut metadata = Metadata::new()?;
        if !authors.is_empty() {
            metadata.authors = Some(authors);
        }

        let (mut component, target_kinds) = self.create_toplevel_component(package);

        component.component_type = Self::get_classification(package);

        metadata.component = Some(component);

        let tool = Tool::new("CycloneDX", "cargo-cyclonedx", env!("CARGO_PKG_VERSION"));

        metadata.tools = Some(Tools::List(vec![tool]));

        Ok((metadata, target_kinds))
    }

    fn create_authors(package: &Package) -> Vec<OrganizationalContact> {
        let mut authors = vec![];
        let mut invalid_authors = vec![];

        for author in &package.authors {
            match Self::parse_author(author) {
                Ok(author) => authors.push(author),
                Err(e) => invalid_authors.push((author, e)),
            }
        }

        invalid_authors
            .into_iter()
            .for_each(|(author, error)| log::warn!("Invalid author {}: {:?}", author, error));

        authors
    }

    fn parse_author(author: &str) -> Result<OrganizationalContact, GeneratorError> {
        static AUTHORS_REGEX: Lazy<Regex> = Lazy::new(|| {
            Regex::new(r"^(?P<author>[^<]+)\s*(<(?P<email>[^>]+)>)?$")
                .expect("Failed to compile regex.")
        });

        match AUTHORS_REGEX.captures(author) {
            Some(captures) => {
                let name = captures.name("author").map_or("", |m| m.as_str().trim());
                let email = captures.name("email").map(|m| m.as_str());

                if let Some(email) = email {
                    if !validate_email(email) {
                        return Err(GeneratorError::AuthorParseError(
                            "Invalid email, does not conform to HTML5 spec".to_string(),
                        ));
                    }
                }

                Ok(OrganizationalContact::new(name, email))
            }
            None => Ok(OrganizationalContact::new(author, None)),
        }
    }
}

/// Ignore tests, benches, examples and build scripts.
/// They are not part of the final build artifacts, which is what we are after.
fn filter_targets(
    targets: &[cargo_metadata::Target],
) -> impl Iterator<Item = &cargo_metadata::Target> {
    targets.iter().filter(|tgt| {
        !(tgt.is_bench() || tgt.is_example() || tgt.is_test() || tgt.is_custom_build())
    })
}

fn index_packages(packages: Vec<Package>) -> PackageMap {
    packages
        .into_iter()
        .map(|pkg| (pkg.id.clone(), pkg))
        .collect()
}

fn index_resolve(packages: Vec<Node>) -> ResolveMap {
    packages
        .into_iter()
        .map(|pkg| (pkg.id.clone(), pkg))
        .collect()
}

#[derive(Error, Debug)]
pub enum GeneratorError {
    #[error("Expected a root package in the cargo config: {config_filepath}")]
    RootPackageMissingError { config_filepath: String },

    #[error("Could not process the cargo config: {config_filepath}")]
    CargoConfigError {
        config_filepath: String,
        #[source]
        error: anyhow::Error,
    },

    #[error("Error retrieving package information: {package_id}")]
    PackageError {
        package_id: cargo_metadata::PackageId,
        #[source]
        error: anyhow::Error,
    },

    #[error("Error creating Metadata")]
    MetadataError(#[from] MetadataError),

    #[error("Could not parse author string: {}", .0)]
    AuthorParseError(String),
}

/// Generates the `Dependencies` field in the final SBOM
fn create_dependencies(resolve: &ResolveMap) -> Dependencies {
    let deps = resolve
        .values()
        .map(|node| Dependency {
            dependency_ref: node.id.to_string(),
            dependencies: node.dependencies.iter().map(|d| d.to_string()).collect(),
        })
        .collect();
    Dependencies(deps)
}

fn top_level_dependencies(
    root: &PackageId,
    packages: &PackageMap,
    resolve: &ResolveMap,
) -> (PackageMap, ResolveMap) {
    log::trace!("Adding top-level dependencies to SBOM");

    // Only include packages that have dependency kinds other than "Development"
    let root_node = strip_dev_dependencies(&resolve[root]);

    let mut pkg_result = PackageMap::new();
    // Record the root package, then its direct non-dev dependencies
    pkg_result.insert(root.to_owned(), packages[root].to_owned());
    for id in &root_node.dependencies {
        pkg_result.insert((*id).to_owned(), packages[id].to_owned());
    }

    let mut resolve_result = ResolveMap::new();
    for id in &root_node.dependencies {
        // Clear all dependencies, pretend there is only one level
        let mut node = resolve[id].clone();
        node.deps = Vec::new();
        node.dependencies = Vec::new();
        resolve_result.insert((*id).to_owned(), node);
    }
    // Insert the root node at the end now that we're done iterating over it
    resolve_result.insert(root.to_owned(), root_node);

    (pkg_result, resolve_result)
}

fn all_dependencies(
    root: &PackageId,
    packages: &PackageMap,
    resolve: &ResolveMap,
) -> (PackageMap, ResolveMap) {
    log::trace!("Adding all dependencies to SBOM");

    // Note: using Vec (without deduplication) can theoretically cause quadratic memory usage,
    // but since `Node` does not implement `Ord` or `Hash` it's hard to deduplicate them.
    // These are all pointers and there's not a lot of them, it's highly unlikely to be an issue in practice.
    // We can work around this by using a map instead of a set if need be.
    let mut current_queue: Vec<&Node> = vec![&resolve[root]];
    let mut next_queue: Vec<&Node> = Vec::new();

    let mut out_resolve = ResolveMap::new();

    // Run breadth-first search (BFS) over the dependency graph
    // to determine which nodes are actually depended on by our package
    // (not other packages) and to remove dev-dependencies
    while !current_queue.is_empty() {
        for node in current_queue.drain(..) {
            // If we haven't processed this node yet...
            if !out_resolve.contains_key(&node.id) {
                // Add the node to the output
                out_resolve.insert(node.id.to_owned(), strip_dev_dependencies(node));
                // Queue its dependencies for the next BFS loop iteration
                next_queue.extend(non_dev_dependencies(&node.deps).map(|dep| &resolve[&dep.pkg]));
            }
        }
        std::mem::swap(&mut current_queue, &mut next_queue);
    }

    // Remove everything from `packages` that doesn't appear in the `resolve` we've built
    let out_packages = packages
        .iter()
        .filter(|(id, _pkg)| out_resolve.contains_key(id))
        .map(|(id, pkg)| (id.to_owned(), pkg.to_owned()))
        .collect();

    (out_packages, out_resolve)
}

fn strip_dev_dependencies(node: &Node) -> Node {
    let mut node = node.clone();
    node.deps = non_dev_dependencies(&node.deps).cloned().collect();
    node.dependencies = node.deps.iter().map(|d| d.pkg.to_owned()).collect();
    node
}

/// Filters out dependencies only used for development, and not affecting the final binary.
/// These are specified under `[dev-dependencies]` in Cargo.toml.
fn non_dev_dependencies(input: &[NodeDep]) -> impl Iterator<Item = &NodeDep> {
    input.iter().filter(|p| {
        p.dep_kinds
            .iter()
            .any(|dep| dep.kind != DependencyKind::Development)
    })
}

/// Contains a generated SBOM and context used in its generation
///
/// * `bom` - Generated SBOM
/// * `manifest_path` - Folder containing the `Cargo.toml` manifest
/// * `package_name` - Package from which this SBOM was generated
/// * `sbom_config` - Configuration options used during generation
/// * `target_kinds` - Detailed information on the kinds of targets in `sbom`
pub struct GeneratedSbom {
    pub bom: Bom,
    pub manifest_path: PathBuf,
    pub package_name: String,
    pub sbom_config: SbomConfig,
    pub target_kinds: TargetKinds,
}

impl GeneratedSbom {
    /// Writes SBOM to either a JSON or XML file in the same folder as `Cargo.toml` manifest
    pub fn write_to_files(self) -> Result<(), SbomWriterError> {
        match self.sbom_config.describe.unwrap_or_default() {
            Describe::Crate => {
                let path = self.manifest_path.with_file_name(self.filename(None, &[]));
                Self::write_to_file(self.bom, &path, &self.sbom_config)
            }
            pattern @ (Describe::Binaries | Describe::AllCargoTargets) => {
                for (sbom, target_kind) in
                    Self::per_artifact_sboms(&self.bom, &self.target_kinds, pattern)
                {
                    let meta = sbom.metadata.as_ref().unwrap();
                    let name = meta.component.as_ref().unwrap().name.as_ref();
                    let path = self
                        .manifest_path
                        .with_file_name(self.filename(Some(name), &target_kind));
                    Self::write_to_file(sbom, &path, &self.sbom_config)?;
                }
                Ok(())
            }
        }
    }

    fn write_to_file(bom: Bom, path: &Path, config: &SbomConfig) -> Result<(), SbomWriterError> {
        // If running in debug mode, validate that the SBOM is self-consistent and well-formed
        if cfg!(debug_assertions) {
            let result = bom.validate();
            if result.has_errors() {
                panic!(
                    "The generated SBOM failed validation: {:?}",
                    result.errors()
                );
            }
        }

        use cyclonedx_bom::models::bom::SpecVersion::*;
        let spec_version = config.spec_version.unwrap_or(V1_3);

        log::info!("Outputting {}", path.display());
        let file = File::create(path)?;
        let mut writer = BufWriter::new(file);
        match config.format() {
            Format::Json => {
                bom.output_as_json(&mut writer, spec_version)
                    .map_err(SbomWriterError::JsonWriteError)?;
            }
            Format::Xml => {
                bom.output_as_xml(&mut writer, spec_version)
                    .map_err(SbomWriterError::XmlWriteError)?;
            }
        }

        // Flush the writer explicitly to catch and report any I/O errors
        writer.flush()?;

        Ok(())
    }

    /// Returns an iterator over SBOMs and their associated target kinds
    fn per_artifact_sboms<'a>(
        bom: &'a Bom,
        target_kinds: &'a TargetKinds,
        describe: Describe,
    ) -> impl Iterator<Item = (Bom, Vec<String>)> + 'a {
        let meta = bom.metadata.as_ref().unwrap();
        let crate_component = meta.component.as_ref().unwrap();
        let components = crate_component.components.as_ref().unwrap();
        // Narrow down the set of targets for which we emit a SBOM depending on the configuration
        components
            .0
            .iter()
            .filter(move |component| {
                let target_kind = &target_kinds.0[component.bom_ref.as_ref().unwrap()];
                match describe {
                    Describe::Binaries => {
                        // only record binary artifacts
                        // TODO: refactor this to use an enum, coming Soon(tm) to cargo-metadata:
                        // https://github.com/oli-obk/cargo_metadata/pull/258
                        target_kind.contains(&"bin".to_owned())
                            || target_kind.contains(&"cdylib".to_owned())
                    }
                    Describe::AllCargoTargets => true, // pass everything through
                    Describe::Crate => unreachable!(),
                }
            })
            .map(|component| {
                let target_kind = &target_kinds.0[component.bom_ref.as_ref().unwrap()];
                // In the original SBOM the toplevel component describes a crate.
                // We need to change it to describe a specific binary.
                // Most properties apply to the entire package and should be kept;
                // we just need to update the name, type and purl.
                let mut new_bom = bom.clone();
                let metadata = new_bom.metadata.as_mut().unwrap();
                let toplevel_component = metadata.component.as_mut().unwrap();
                toplevel_component.name = component.name.clone();
                toplevel_component.component_type = component.component_type.clone();
                toplevel_component.purl.clone_from(&component.purl);

                (new_bom, target_kind.clone())
            })
    }

    fn filename(&self, binary_name: Option<&str>, target_kind: &[String]) -> String {
        let output_options = self.sbom_config.output_options();
        let describe = self.sbom_config.describe.unwrap_or_default();

        let mut prefix = match describe {
            Describe::Crate => self.package_name.clone(),
            Describe::Binaries => binary_name.unwrap().to_owned(),
            Describe::AllCargoTargets => binary_name.unwrap().to_owned(),
        };
        let mut extension = ".cdx";

        // Handle overridden filename
        match output_options.filename {
            FilenamePattern::CrateName => (), // already handled above, nothing more to do
            FilenamePattern::Custom(name_override) => {
                prefix = name_override.to_string();
                extension = ""; // do not append the extension to allow writing to literally "bom.xml" as per spec
            }
        }

        let target_kind_suffix = if !target_kind.is_empty() {
            debug_assert!(matches!(
                describe,
                Describe::Binaries | Describe::AllCargoTargets
            ));
            format!("_{}", target_kind.join("-"))
        } else {
            "".to_owned()
        };

        let platform_suffix = match output_options.platform_suffix {
            PlatformSuffix::NotIncluded => "".to_owned(),
            PlatformSuffix::Included => {
                extension = ".cdx"; // only a literal "bom.{xml,json}" is allowed not to have .cdx
                let target_string = self.sbom_config.target.as_ref().unwrap();
                format!("_{}", target_string.as_str())
            }
        };

        format!(
            "{}{}{}{}.{}",
            prefix,
            target_kind_suffix,
            platform_suffix,
            extension,
            self.sbom_config.format()
        )
    }
}

/// Locates the corresponding `Cargo.lock` file given the location of `Cargo.toml`.
/// This must be run **after** `cargo metadata` which will generate the `Cargo.lock` file
/// and make sure it's up to date.
fn locate_cargo_lock(manifest_path: &Path) -> Result<PathBuf, std::io::Error> {
    let manifest_path = manifest_path.canonicalize()?;
    let ancestors = manifest_path.as_path().ancestors();

    for path in ancestors {
        let potential_lockfile = path.join("Cargo.lock");
        if potential_lockfile.is_file() {
            return Ok(potential_lockfile);
        }
    }
    Err(std::io::Error::new(
        std::io::ErrorKind::NotFound,
        "Could not find Cargo.lock in any parent directories",
    ))
}

/// Extracts all available package hashes from the provided `Cargo.lock` file
/// and collects them into a HashMap for fast and reasy lookup
fn package_hashes(lockfile: &Lockfile) -> HashMap<cargo_metadata::PackageId, Checksum> {
    let mut result = HashMap::new();
    for pkg in &lockfile.packages {
        if let Some(hash) = pkg.checksum.as_ref() {
            result.insert(cargo_metadata::PackageId { repr: pkgid(pkg) }, hash.clone());
        }
    }
    result
}

/// Returns a Cargo unique identifier for a package.
/// See `cargo help pkgid` for more info.
fn pkgid(pkg: &cargo_lock::Package) -> String {
    match pkg.source.as_ref() {
        Some(source) => format!("{}#{}@{}", source, pkg.name, pkg.version),
        None => format!("{}@{}", pkg.name, pkg.version),
    }
}

/// Converts a checksum from the `cargo-lock` crate format to `cyclonedx-bom` crate format
fn to_bom_hash(hash: &Checksum) -> cyclonedx_bom::models::hash::Hash {
    use cyclonedx_bom::models::hash::{Hash, HashAlgorithm, HashValue};
    // use a match statement to get a compile-time error
    // if/when more variants are added
    match hash {
        Checksum::Sha256(_) => {
            Hash {
                alg: HashAlgorithm::SHA_256,
                // {:x} means "format as lowercase hex"
                content: HashValue(format!("{hash:x}")),
            }
        }
    }
}

#[derive(Error, Debug)]
pub enum SbomWriterError {
    #[error("I/O error")]
    IoError(#[source] std::io::Error),

    #[error("Error writing JSON file")]
    JsonWriteError(#[source] cyclonedx_bom::errors::JsonWriteError),

    #[error("Error writing XML file")]
    XmlWriteError(#[source] cyclonedx_bom::errors::XmlWriteError),

    #[error("Error serializing to XML")]
    SerializeXmlError(#[source] std::io::Error),
}

impl From<std::io::Error> for SbomWriterError {
    fn from(value: std::io::Error) -> Self {
        Self::IoError(value)
    }
}

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

    #[test]
    fn it_should_parse_author_and_email() {
        let actual = SbomGenerator::parse_author("First Last <user@domain.tld>")
            .expect("Failed to parse author");
        let expected = OrganizationalContact::new("First Last", Some("user@domain.tld"));

        assert_eq!(actual, expected);
    }
    #[test]
    fn it_should_parse_author_only() {
        let actual = SbomGenerator::parse_author("First Last").expect("Failed to parse author");
        let expected = OrganizationalContact::new("First Last", None);

        assert_eq!(actual, expected);
    }

    #[test]
    fn it_should_fail_to_parse_invalid_email() {
        let actual = SbomGenerator::parse_author("First Last <userdomain.tld>")
            .expect_err("Failed to throw error");

        match actual {
            GeneratorError::AuthorParseError(e) => assert_eq!(
                e,
                "Invalid email, does not conform to HTML5 spec".to_string()
            ),
            e => panic!("Expected AuthorParse error got: {:?}", e),
        }
    }

    #[test]
    fn it_should_parse_author_inside_brackets() {
        let actual = SbomGenerator::parse_author("<First Last user@domain.tld>")
            .expect("Failed to parse author");
        let expected = OrganizationalContact::new("<First Last user@domain.tld>", None);

        assert_eq!(actual, expected);
    }
}