-
-
Notifications
You must be signed in to change notification settings - Fork 44
/
purl.rs
230 lines (213 loc) · 9.97 KB
/
purl.rs
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
use std::str::FromStr;
use cargo_metadata::{camino::Utf8Path, Package};
use cyclonedx_bom::{external_models::uri::validate_purl, prelude::Purl as CdxPurl};
use pathdiff::diff_utf8_paths;
use purl::{PackageError, PackageType, PurlBuilder};
use crate::urlencode::urlencode;
pub fn get_purl(
package: &Package,
root_package: &Package,
workspace_root: &Utf8Path,
subpath: Option<&Utf8Path>,
) -> Result<CdxPurl, PackageError> {
let mut builder = PurlBuilder::new(PackageType::Cargo, &package.name)
.with_version(package.version.to_string());
if let Some(source) = &package.source {
if !source.is_crates_io() {
match source.repr.split_once('+') {
// qualifier names are taken from the spec, which defines these two for all PURL types:
// https://github.com/package-url/purl-spec/blob/master/PURL-SPECIFICATION.rst#known-qualifiers-keyvalue-pairs
Some(("git", _git_path)) => {
builder = builder.with_qualifier("vcs_url", source_to_vcs_url(source))?
}
Some(("registry", registry_url)) => {
builder = builder.with_qualifier("repository_url", urlencode(registry_url))?
}
Some((source, _path)) => log::warn!("Unknown source kind {}", source),
None => {
log::warn!("No '+' separator found in source field from `cargo metadata`")
}
}
}
} else {
// source is None for packages from the local filesystem.
// The manifest path ends with a `Cargo.toml`, so the package directory is its parent
let mut package_dir = package.manifest_path.parent().unwrap().to_owned();
// If the package is within the workspace, encode the relative path instead of the absolute one
// to make the SBOM reproducible(ish) and more clearly signal first-party dependencies.
if package_dir.starts_with(workspace_root) {
let root_package_dir = root_package.manifest_path.parent().unwrap();
debug_assert!(root_package_dir.starts_with(workspace_root));
package_dir = diff_utf8_paths(package_dir, root_package_dir).unwrap();
if package_dir.as_str() == "" {
// if the diff is empty, we are in the current directory
package_dir = ".".into();
}
}
// url-encode the path to the package manifest to make it a valid URL
let manifest_url = format!("file://{}", urlencode(package_dir.as_str()));
// url-encode the whole URL *again* because we are embedding this URL inside another URL (PURL)
builder = builder.with_qualifier("download_url", urlencode(&manifest_url))?
}
if let Some(subpath) = subpath {
builder = builder.with_subpath(to_purl_subpath(subpath));
}
let purl = builder.build()?;
let cdx_purl = CdxPurl::from_str(&purl.to_string()).unwrap();
if cfg!(debug_assertions) {
assert_validation_passes(&cdx_purl);
}
Ok(CdxPurl::from_str(&purl.to_string()).unwrap())
}
/// Converts the `cargo metadata`'s `source` field to a valid PURL `vcs_url`.
/// Assumes that the source kind is `git`, panics if it isn't.
fn source_to_vcs_url(source: &cargo_metadata::Source) -> String {
assert!(source.repr.starts_with("git+"));
urlencode(&source.repr.replace('#', "@"))
}
/// Converts a relative path to PURL subpath
fn to_purl_subpath(path: &Utf8Path) -> String {
assert!(path.is_relative());
let parts: Vec<String> = path.components().map(|c| urlencode(c.as_str())).collect();
parts.join("/")
}
fn assert_validation_passes(purl: &CdxPurl) {
assert!(validate_purl(purl).is_ok());
}
#[cfg(test)]
mod tests {
use super::*;
use percent_encoding::percent_decode;
use purl::Purl;
use serde_json;
const CRATES_IO_PACKAGE_JSON: &str = include_str!("../tests/fixtures/crates_io_package.json");
const GIT_PACKAGE_JSON: &str = include_str!("../tests/fixtures/git_package.json");
const ROOT_PACKAGE_JSON: &str = include_str!("../tests/fixtures/root_package.json");
const WORKSPACE_PACKAGE_JSON: &str = include_str!("../tests/fixtures/workspace_package.json");
#[test]
fn crates_io_purl() {
let crates_io_package: Package = serde_json::from_str(CRATES_IO_PACKAGE_JSON).unwrap();
let purl = get_purl(
&crates_io_package,
&crates_io_package,
Utf8Path::new("/foo/bar"),
None,
)
.unwrap();
// Validate that data roundtripped correctly
let parsed_purl = Purl::from_str(&purl.to_string()).unwrap();
assert_eq!(parsed_purl.name(), "aho-corasick");
assert_eq!(parsed_purl.version(), Some("1.1.2"));
assert!(parsed_purl.qualifiers().is_empty());
assert!(parsed_purl.subpath().is_none());
assert!(parsed_purl.namespace().is_none());
}
#[test]
fn git_purl() {
let git_package: Package = serde_json::from_str(GIT_PACKAGE_JSON).unwrap();
let purl = get_purl(&git_package, &git_package, Utf8Path::new("/foo/bar"), None).unwrap();
// Validate that data roundtripped correctly
let parsed_purl = Purl::from_str(&purl.to_string()).unwrap();
assert_eq!(parsed_purl.name(), "auditable-extract");
assert_eq!(parsed_purl.version(), Some("0.3.2"));
assert_eq!(parsed_purl.qualifiers().len(), 1);
let (qualifier, value) = parsed_purl.qualifiers().iter().next().unwrap();
assert_eq!(qualifier.as_str(), "vcs_url");
assert_eq!(value, "git+https://github.com/rust-secure-code/cargo-auditable.git@da85607fb1a09435d77288ccf05a92b2e8ec3f71");
assert!(parsed_purl.subpath().is_none());
assert!(parsed_purl.namespace().is_none());
}
#[test]
fn toplevel_package_purl() {
let root_package: Package = serde_json::from_str(ROOT_PACKAGE_JSON).unwrap();
let purl = get_purl(
&root_package,
&root_package,
Utf8Path::new("/home/shnatsel/Code/cargo-cyclonedx/"),
None,
)
.unwrap();
// Validate that data roundtripped correctly
let parsed_purl = Purl::from_str(&purl.to_string()).unwrap();
assert_eq!(parsed_purl.name(), "cargo-cyclonedx");
assert_eq!(parsed_purl.version(), Some("0.3.8"));
assert_eq!(parsed_purl.qualifiers().len(), 1);
let (qualifier, value) = parsed_purl.qualifiers().iter().next().unwrap();
assert_eq!(qualifier.as_str(), "download_url");
let decoded_path = percent_decode(value.as_bytes()).decode_utf8().unwrap();
assert_eq!(decoded_path, "file://.");
assert!(parsed_purl.subpath().is_none());
assert!(parsed_purl.namespace().is_none());
}
#[test]
fn toplevel_package_with_subpath() {
let root_package: Package = serde_json::from_str(ROOT_PACKAGE_JSON).unwrap();
let purl = get_purl(
&root_package,
&root_package,
Utf8Path::new("/home/shnatsel/Code/cargo-cyclonedx/"),
Some("src/кириллица/lib.rs".into()),
)
.unwrap();
// Validate that data roundtripped correctly
let parsed_purl = Purl::from_str(&purl.to_string()).unwrap();
assert_eq!(parsed_purl.name(), "cargo-cyclonedx");
assert_eq!(parsed_purl.version(), Some("0.3.8"));
assert_eq!(parsed_purl.qualifiers().len(), 1);
let (qualifier, value) = parsed_purl.qualifiers().iter().next().unwrap();
assert_eq!(qualifier.as_str(), "download_url");
let decoded_path = percent_decode(value.as_bytes()).decode_utf8().unwrap();
assert_eq!(decoded_path, "file://.");
assert_eq!(parsed_purl.subpath().unwrap(), "src/кириллица/lib.rs");
assert!(parsed_purl.namespace().is_none());
}
#[test]
fn workspace_package() {
let root_package: Package = serde_json::from_str(ROOT_PACKAGE_JSON).unwrap();
let workspace_package: Package = serde_json::from_str(WORKSPACE_PACKAGE_JSON).unwrap();
let purl = get_purl(
&workspace_package,
&root_package,
Utf8Path::new("/home/shnatsel/Code/cargo-cyclonedx/"),
None,
)
.unwrap();
// Validate that data roundtripped correctly
let parsed_purl = Purl::from_str(&purl.to_string()).unwrap();
assert_eq!(parsed_purl.name(), "cyclonedx-bom");
assert_eq!(parsed_purl.version(), Some("0.4.1"));
assert_eq!(parsed_purl.qualifiers().len(), 1);
let (qualifier, value) = parsed_purl.qualifiers().iter().next().unwrap();
assert_eq!(qualifier.as_str(), "download_url");
let decoded_path = percent_decode(value.as_bytes()).decode_utf8().unwrap();
assert_eq!(decoded_path, "file://../cyclonedx-bom");
assert!(parsed_purl.subpath().is_none());
assert!(parsed_purl.namespace().is_none());
}
#[test]
fn local_package() {
let root_package: Package = serde_json::from_str(ROOT_PACKAGE_JSON).unwrap();
let workspace_package: Package = serde_json::from_str(WORKSPACE_PACKAGE_JSON).unwrap();
let purl = get_purl(
&workspace_package,
&root_package,
Utf8Path::new("/foo/bar/"),
None,
)
.unwrap();
// Validate that data roundtripped correctly
let parsed_purl = Purl::from_str(&purl.to_string()).unwrap();
assert_eq!(parsed_purl.name(), "cyclonedx-bom");
assert_eq!(parsed_purl.version(), Some("0.4.1"));
assert_eq!(parsed_purl.qualifiers().len(), 1);
let (qualifier, value) = parsed_purl.qualifiers().iter().next().unwrap();
assert_eq!(qualifier.as_str(), "download_url");
let decoded_path = percent_decode(value.as_bytes()).decode_utf8().unwrap();
assert_eq!(
decoded_path,
"file:///home/shnatsel/Code/cargo-cyclonedx/cyclonedx-bom"
);
assert!(parsed_purl.subpath().is_none());
assert!(parsed_purl.namespace().is_none());
}
}