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
// SPDX-FileCopyrightText: 2021 HH Partners
//
// SPDX-License-Identifier: MIT

use std::collections::HashSet;

use log::info;
use serde::{Deserialize, Serialize};
use uuid::Uuid;

use super::{
    Algorithm, Annotation, DocumentCreationInformation, FileInformation,
    OtherLicensingInformationDetected, PackageInformation, Relationship, Snippet,
};

/// A representation of an [SPDX Document]
///
/// This is the main struct of this crate. The struct implements [`Serialize`] and [`Deserialize`]
/// to allow it to be serialized into and deserialized from any data format supported by [Serde].
///
/// # SPDX specification version
///
/// The crate has been developed around SPDX version 2.2.1. Fields deprecated in 2.2.1, like
/// [review information] are not supported. The plan is to support newer versions as they are
/// released.
///
/// # Data formats
///
/// The crate has been developed for usage with JSON SPDX documents. The naming of the fields should
/// conform to the spec for at least JSON. Other formats, like YAML may work, but no guarantees are
/// made.
///
/// The crate also allows for deserializing the struct from SPDX documents in [tag-value format]
/// with [`crate::parsers::spdx_from_tag_value`].
///
/// [SPDX Document]: https://spdx.github.io/spdx-spec/composition-of-an-SPDX-document/
/// [Serde]: https://serde.rs
/// [review information]: https://spdx.github.io/spdx-spec/review-information-deprecated/
/// [tag-value format]: https://spdx.github.io/spdx-spec/conformance/
#[derive(Serialize, Deserialize, Debug, PartialEq, Eq, Clone)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct SPDX {
    /// <https://spdx.github.io/spdx-spec/2-document-creation-information/>
    #[serde(flatten)]
    pub document_creation_information: DocumentCreationInformation,

    /// <https://spdx.github.io/spdx-spec/3-package-information/>
    #[serde(rename = "packages")]
    #[serde(default)]
    pub package_information: Vec<PackageInformation>,

    /// <https://spdx.github.io/spdx-spec/6-other-licensing-information-detected/>
    #[serde(rename = "hasExtractedLicensingInfos")]
    #[serde(default)]
    pub other_licensing_information_detected: Vec<OtherLicensingInformationDetected>,

    /// <https://spdx.github.io/spdx-spec/4-file-information/>
    #[serde(rename = "files")]
    #[serde(default)]
    pub file_information: Vec<FileInformation>,

    /// <https://spdx.github.io/spdx-spec/5-snippet-information/>
    #[serde(rename = "snippets")]
    #[serde(default)]
    pub snippet_information: Vec<Snippet>,

    /// <https://spdx.github.io/spdx-spec/7-relationships-between-SPDX-elements/>
    #[serde(default)]
    pub relationships: Vec<Relationship>,

    /// <https://spdx.github.io/spdx-spec/8-annotations/>
    #[serde(default)]
    pub annotations: Vec<Annotation>,

    /// Counter for creating SPDXRefs. Is not part of the spec, so don't serialize.
    #[serde(skip)]
    pub spdx_ref_counter: i32,
}

impl SPDX {
    /// Create new SPDX struct.
    pub fn new(name: &str) -> Self {
        info!("Creating SPDX.");

        Self {
            document_creation_information: DocumentCreationInformation {
                document_name: name.to_string(),
                spdx_document_namespace: format!(
                    "http://spdx.org/spdxdocs/{}-{}",
                    name,
                    Uuid::new_v4()
                ),
                ..DocumentCreationInformation::default()
            },
            package_information: Vec::new(),
            other_licensing_information_detected: Vec::new(),
            file_information: Vec::new(),
            relationships: Vec::new(),
            spdx_ref_counter: 0,
            annotations: Vec::new(),
            snippet_information: Vec::new(),
        }
    }

    /// Get unique hashes for all files the SPDX.
    pub fn get_unique_hashes(&self, algorithm: Algorithm) -> HashSet<String> {
        info!("Getting unique hashes for files in SPDX.");

        let mut unique_hashes: HashSet<String> = HashSet::new();

        for file_information in &self.file_information {
            if let Some(checksum) = file_information.checksum(algorithm) {
                unique_hashes.insert(checksum.to_string());
            }
        }

        unique_hashes
    }

    /// Find related files of the package with the provided id.
    pub fn get_files_for_package(
        &self,
        package_spdx_id: &str,
    ) -> Vec<(&FileInformation, &Relationship)> {
        info!("Finding related files for package {}.", &package_spdx_id);

        let relationships = self
            .relationships
            .iter()
            .filter(|relationship| relationship.spdx_element_id == package_spdx_id);

        let mut result: Vec<(&FileInformation, &Relationship)> = Vec::new();

        for relationship in relationships {
            let file = self
                .file_information
                .iter()
                .find(|file| file.file_spdx_identifier == relationship.related_spdx_element);
            if let Some(file) = file {
                result.push((file, relationship));
            };
        }

        result
    }

    /// Get all license identifiers from the SPDX.
    ///
    /// # Errors
    ///
    /// Returns [`SpdxError`] if parsing of the expressions fails.
    pub fn get_license_ids(&self) -> HashSet<String> {
        info!("Getting all license identifiers from SPDX.");

        let mut license_ids = HashSet::new();

        for file in &self.file_information {
            if let Some(concluded_license) = &file.concluded_license {
                for license in concluded_license.identifiers() {
                    if license != "NOASSERTION" && license != "NONE" {
                        license_ids.insert(license.clone());
                    }
                }
            }
        }

        license_ids
    }

    /// Get all relationships where the given SPDX ID is the SPDX element id.
    pub fn relationships_for_spdx_id(&self, spdx_id: &str) -> Vec<&Relationship> {
        self.relationships
            .iter()
            .filter(|relationship| relationship.spdx_element_id == spdx_id)
            .collect()
    }

    /// Get all relationships where the given SPDX ID is the related SPDX element id.
    pub fn relationships_for_related_spdx_id(&self, spdx_id: &str) -> Vec<&Relationship> {
        self.relationships
            .iter()
            .filter(|relationship| relationship.related_spdx_element == spdx_id)
            .collect()
    }
}

#[cfg(test)]
mod test {
    use std::{fs::read_to_string, iter::FromIterator};

    use spdx_expression::SpdxExpression;

    use crate::models::RelationshipType;

    use super::*;

    #[test]
    fn deserialize_simple_spdx() {
        let spdx_file: SPDX = serde_json::from_str(
            &read_to_string("tests/data/SPDXJSONExample-v2.2.spdx.json").unwrap(),
        )
        .unwrap();

        assert_eq!(
            spdx_file.document_creation_information.document_name,
            "SPDX-Tools-v2.0".to_string()
        );
    }

    #[test]
    fn find_related_files_for_package() {
        let spdx_file: SPDX = serde_json::from_str(
            &read_to_string("tests/data/SPDXJSONExample-v2.2.spdx.json").unwrap(),
        )
        .unwrap();

        let package_1_files = spdx_file.get_files_for_package("SPDXRef-Package");

        assert_eq!(package_1_files.len(), 1);

        let file = package_1_files
            .iter()
            .find(|package_and_relationship| {
                package_and_relationship.0.file_name == *"./lib-source/jena-2.6.3-sources.jar"
            })
            .expect("Should always be found");

        assert_eq!(file.0.file_spdx_identifier, "SPDXRef-JenaLib");
        assert_eq!(file.1.relationship_type, RelationshipType::Contains);

        assert_eq!(
            file.0.concluded_license,
            Some(SpdxExpression::parse("LicenseRef-1").unwrap())
        );
    }

    #[test]
    fn get_all_licenses_from_spdx() {
        let spdx_file: SPDX = serde_json::from_str(
            &read_to_string("tests/data/SPDXJSONExample-v2.2.spdx.json").unwrap(),
        )
        .unwrap();

        let actual = spdx_file.get_license_ids();

        let expected = HashSet::from_iter([
            "Apache-2.0".into(),
            "LicenseRef-1".into(),
            "LGPL-2.0-only".into(),
            "LicenseRef-2".into(),
        ]);

        assert_eq!(expected, actual);
    }

    #[test]
    fn get_relationships_for_spdx_id() {
        let spdx_file: SPDX = serde_json::from_str(
            &read_to_string("tests/data/SPDXJSONExample-v2.2.spdx.json").unwrap(),
        )
        .unwrap();

        let relationships = spdx_file.relationships_for_spdx_id("SPDXRef-Package");
        let relationship_1 = Relationship {
            spdx_element_id: "SPDXRef-Package".into(),
            related_spdx_element: "SPDXRef-Saxon".into(),
            relationship_type: RelationshipType::DynamicLink,
            comment: None,
        };
        let relationship_2 = Relationship {
            spdx_element_id: "SPDXRef-Package".into(),
            related_spdx_element: "SPDXRef-JenaLib".into(),
            relationship_type: RelationshipType::Contains,
            comment: None,
        };
        let expected_relationships = vec![&relationship_1, &relationship_2];

        assert_eq!(relationships, expected_relationships);
    }

    #[test]
    fn get_relationships_for_related_spdx_id() {
        let spdx_file: SPDX = serde_json::from_str(
            &read_to_string("tests/data/SPDXJSONExample-v2.2.spdx.json").unwrap(),
        )
        .unwrap();

        let relationships = spdx_file.relationships_for_related_spdx_id("SPDXRef-Package");
        let relationship_1 = Relationship {
            spdx_element_id: "SPDXRef-DOCUMENT".into(),
            related_spdx_element: "SPDXRef-Package".into(),
            relationship_type: RelationshipType::Contains,
            comment: None,
        };
        let relationship_2 = Relationship {
            spdx_element_id: "SPDXRef-DOCUMENT".into(),
            related_spdx_element: "SPDXRef-Package".into(),
            relationship_type: RelationshipType::Describes,
            comment: None,
        };
        let relationship_3 = Relationship {
            spdx_element_id: "SPDXRef-JenaLib".into(),
            related_spdx_element: "SPDXRef-Package".into(),
            relationship_type: RelationshipType::Contains,
            comment: None,
        };
        let expected_relationships = vec![&relationship_1, &relationship_2, &relationship_3];

        assert_eq!(relationships, expected_relationships);
    }

    #[test]
    fn get_unique_hashes_for_files() {
        let spdx_file: SPDX = serde_json::from_str(
            &read_to_string("tests/data/SPDXJSONExample-v2.2.spdx.json").unwrap(),
        )
        .unwrap();
        let hashes = spdx_file.get_unique_hashes(Algorithm::SHA1);

        let expected = [
            "2fd4e1c67a2d28fced849ee1bb76e7391b93eb12".to_string(),
            "c2b4e1c67a2d28fced849ee1bb76e7391b93f125".to_string(),
            "3ab4e1c67a2d28fced849ee1bb76e7391b93f125".to_string(),
            "d6a770ba38583ed4bb4525bd96e50461655d2758".to_string(),
        ]
        .iter()
        .cloned()
        .collect::<HashSet<_>>();

        assert_eq!(hashes, expected);
    }
}