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
//! SBOM Model

use anyhow::{anyhow, bail, Context};
use serde::Deserialize;
use serde_json::Value;
use std::fmt::{Debug, Display, Formatter};

pub enum Parser {
    CycloneDxJson,
    CycloneDxXml,
}

/// A tool to work with multiple SBOM formats and versions
pub enum Sbom {
    #[cfg(feature = "spdx-rs")]
    Spdx(spdx_rs::models::SPDX),
    #[cfg(feature = "cyclonedx-rust")]
    CycloneDx(cyclonedx_rust::CycloneDX),
}

impl Debug for Sbom {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Spdx(doc) => f.debug_tuple("Spdx").field(doc).finish(),
            Self::CycloneDx(_doc) => f
                .debug_tuple("CycloneDx")
                .field(&"unable to display")
                .finish(),
        }
    }
}

#[derive(Default, Debug)]
pub struct ParseAnyError(Vec<(ParserKind, anyhow::Error)>);

impl std::error::Error for ParseAnyError {}

impl From<(ParserKind, anyhow::Error)> for ParseAnyError {
    fn from(value: (ParserKind, anyhow::Error)) -> Self {
        Self(vec![value])
    }
}

impl ParseAnyError {
    pub fn new() -> Self {
        Self(vec![])
    }

    pub fn add(mut self, kind: ParserKind, error: anyhow::Error) -> Self {
        self.0.push((kind, error));
        self
    }
}

impl Display for ParseAnyError {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        write!(f, "failed to parse SBOM:")?;
        if self.0.is_empty() {
            write!(f, "failed to parse SBOM: no parser configured")?;
        } else if self.0.len() == 1 {
            write!(f, "{}: {}", self.0[0].0, self.0[0].1)?;
        } else {
            writeln!(f)?;
            for (kind, err) in &self.0 {
                writeln!(f, "  {kind}: {err}")?;
            }
        }

        Ok(())
    }
}

#[derive(Copy, Clone, Debug, PartialEq, Eq)]
pub enum ParserKind {
    Cyclone13DxJson,
    Cyclone13DxXml,
    Spdx23Json,
    Spdx23Tag,
}

impl std::fmt::Display for ParserKind {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Cyclone13DxJson => write!(f, "CycloneDX 1.3 JSON"),
            Self::Cyclone13DxXml => write!(f, "CycloneDX 1.3 XML"),
            Self::Spdx23Json => write!(f, "SPDX 2.3 JSON"),
            Self::Spdx23Tag => write!(f, "SPDX 2.3 tagged"),
        }
    }
}

impl Sbom {
    /// test if the file is a CycloneDX document, returning the file version
    pub fn is_cyclondx_json(json: &Value) -> anyhow::Result<&str> {
        let format = json["bomFormat"]
            .as_str()
            .ok_or_else(|| anyhow!("Missing field 'bomFormat'"))?;

        if format != "CycloneDX" {
            bail!("Unknown CycloneDX 'bomFormat' value: {format}");
        }

        let spec_version = json["specVersion"]
            .as_str()
            .ok_or_else(|| anyhow!("Missing field 'specVersion'"))?;

        Ok(spec_version)
    }

    /// test if the file is a SPDX document, returning the file version
    pub fn is_spdx_json(json: &Value) -> anyhow::Result<&str> {
        let version = json["spdxVersion"]
            .as_str()
            .ok_or_else(|| anyhow!("Missing field 'spdxVersion'"))?;

        Ok(version)
    }

    /// try parsing with all possible kinds which make sense.
    pub fn try_parse_any(data: &[u8]) -> Result<Self, ParseAnyError> {
        if let Ok(json) = serde_json::from_slice::<Value>(data) {
            // try to parse this as JSON, which eliminates e.g. the "tag" format, which seems to just parse anything

            let err = ParseAnyError::new();

            let err = match Self::is_cyclondx_json(&json) {
                Ok("1.2" | "1.3") => {
                    return Self::try_cyclonedx_json(JsonPayload::Value(json)).map_err(|e| {
                        // drop any previous error, as we know what format and version it is
                        ParseAnyError::from((ParserKind::Cyclone13DxJson, e.into()))
                    });
                }
                Ok(version) => {
                    // We can stop here, and drop any previous error, as we know what the format is.
                    // But we disagree with the version.
                    return Err(ParseAnyError::from((
                        ParserKind::Cyclone13DxJson,
                        anyhow!("Unsupported CycloneDX version: {version}"),
                    )));
                }
                // failed to detect as CycloneDX, record error and move on
                Err(e) => err.add(ParserKind::Cyclone13DxJson, e),
            };

            match Self::is_spdx_json(&json) {
                Ok("SPDX-2.2" | "SPDX-2.3") => {
                    return Self::try_spdx_json(JsonPayload::Value(json)).map_err(|e| {
                        // drop any previous error, as we know what format and version it is
                        ParseAnyError::from((ParserKind::Spdx23Json, e.into()))
                    });
                }
                Ok(version) => {
                    // We can stop here, and drop any previous error, as we know what the format is.
                    // But we disagree with the version.
                    Err(ParseAnyError::from((
                        ParserKind::Spdx23Json,
                        anyhow!("Unsupported SPDX version: {version}"),
                    )))
                }
                Err(e) => Err(err.add(ParserKind::Spdx23Json, e)),
            }
        } else {
            // it is not JSON, it could be XML or "tagged"
            let mut err = ParseAnyError::new();

            match Self::try_cyclonedx_xml(data) {
                Ok(doc) => return Ok(doc),
                Err(e) => err = err.add(ParserKind::Cyclone13DxXml, e.into()),
            }

            match std::str::from_utf8(data)
                .context("interpret bytes as string")
                .and_then(|data| Self::try_spdx_tag(data).map_err(|err| err.into()))
            {
                Ok(doc) => return Ok(doc),
                Err(e) => err = err.add(ParserKind::Spdx23Tag, e),
            }

            Err(err)
        }
    }

    #[cfg(feature = "spdx-rs")]
    pub fn try_spdx_json(data: JsonPayload) -> Result<Self, serde_json::Error> {
        Ok(Self::Spdx(data.parse()?))
    }

    #[cfg(feature = "spdx-rs")]
    pub fn try_spdx_tag(data: &str) -> Result<Self, spdx_rs::error::SpdxError> {
        Ok(Self::Spdx(spdx_rs::parsers::spdx_from_tag_value(data)?))
    }

    #[cfg(feature = "cyclonedx-rust")]
    pub fn try_cyclonedx_json(data: JsonPayload) -> Result<Self, serde_json::Error> {
        Ok(Self::CycloneDx(data.parse()?))
    }

    #[cfg(feature = "cyclonedx-rust")]
    pub fn try_cyclonedx_xml(data: &[u8]) -> Result<Self, cyclonedx_rust::CycloneDXDecodeError> {
        Ok(Self::CycloneDx(cyclonedx_rust::CycloneDX::decode(
            data,
            cyclonedx_rust::CycloneDXFormatType::XML,
        )?))
    }
}

pub enum JsonPayload<'a> {
    Value(Value),
    Bytes(&'a [u8]),
}

impl JsonPayload<'_> {
    pub fn parse<T>(self) -> Result<T, serde_json::Error>
    where
        for<'de> T: Deserialize<'de>,
    {
        match self {
            Self::Value(data) => serde_json::from_value(data),
            Self::Bytes(data) => serde_json::from_slice(data),
        }
    }
}