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
//! npm source adapter: full history, scoped names, deprecations, tarballs.
//!
//! The adapter module is included with `#[path]` because `sources/mod.rs` is
//! owned by the integration wave. Every request goes through the scripted
//! [`FakeHttp`] seam; no test touches the live registry, and any HEAD or
//! download attempt fails loudly.
#![allow(dead_code)]
use std::collections::HashMap;
use std::sync::{Arc, Mutex};
use async_trait::async_trait;
use serde_json::Value;
use vuln_notif::release::http::RegistryHttp;
use vuln_notif::release::source::{
ArtifactInfo, ProjectRef, ReleaseSource, SourceCapabilities, StatusInfo, VersionInfo,
};
mod release {
pub mod http {
pub use vuln_notif::release::http::*;
}
pub mod source {
pub use vuln_notif::release::source::*;
}
pub mod versioning {
pub use vuln_notif::release::versioning::*;
}
}
#[path = "../src/release/sources/npm.rs"]
mod npm;
use npm::NpmSource;
const REGISTRY_FIXTURE: &str = include_str!("fixtures/sources/npm/registry.json");
const SCOPED_FIXTURE: &str = include_str!("fixtures/sources/npm/scoped.json");
const REGISTRY_URL: &str = "https://registry.npmjs.org/acme-widget";
const SCOPED_URL: &str = "https://registry.npmjs.org/@acme%2Fscoped-widget";
// ---------------------------------------------------------------------------
// Local scripted registry HTTP fake
// ---------------------------------------------------------------------------
#[derive(Debug, Clone)]
enum Reply {
Json(Value),
Error(String),
}
#[derive(Default)]
struct FakeHttp {
replies: Mutex<HashMap<String, Reply>>,
calls: Mutex<Vec<String>>,
}
impl FakeHttp {
fn new(routes: Vec<(&str, Reply)>) -> Self {
Self {
replies: Mutex::new(
routes
.into_iter()
.map(|(url, reply)| (url.to_owned(), reply))
.collect(),
),
calls: Mutex::new(Vec::new()),
}
}
fn calls(&self) -> Vec<String> {
self.calls.lock().unwrap().clone()
}
fn take(&self, kind: &str, url: &str) -> anyhow::Result<Reply> {
self.calls.lock().unwrap().push(format!("{kind} {url}"));
self.replies
.lock()
.unwrap()
.get(url)
.cloned()
.ok_or_else(|| anyhow::anyhow!("unexpected {kind} {url}"))
}
}
#[async_trait]
impl RegistryHttp for FakeHttp {
async fn get_json(&self, url: &str) -> anyhow::Result<Value> {
match self.take("json", url)? {
Reply::Json(value) => Ok(value),
Reply::Error(message) => Err(anyhow::anyhow!(message)),
}
}
async fn get_text(&self, url: &str) -> anyhow::Result<String> {
Err(anyhow::anyhow!("unexpected text fetch for {url}"))
}
async fn head_size(&self, url: &str) -> anyhow::Result<u64> {
Err(anyhow::anyhow!("unexpected HEAD for {url}"))
}
async fn download(&self, url: &str) -> anyhow::Result<Vec<u8>> {
Err(anyhow::anyhow!("unexpected download for {url}"))
}
}
// ---------------------------------------------------------------------------
// Helpers
// ---------------------------------------------------------------------------
fn fixture(text: &str) -> Value {
serde_json::from_str(text).expect("fixture JSON")
}
fn project(name: &str) -> ProjectRef {
ProjectRef {
purl_type: "npm".to_owned(),
name: name.to_owned(),
purl: format!("pkg:npm/{name}"),
}
}
fn version(raw: &str) -> VersionInfo {
VersionInfo {
raw: raw.to_owned(),
version: raw.to_owned(),
deprecated: false,
reason: String::new(),
}
}
// ---------------------------------------------------------------------------
// Versions
// ---------------------------------------------------------------------------
#[tokio::test]
async fn npm_versions_include_prereleases_and_deprecation_reasons() {
let http = Arc::new(FakeHttp::new(vec![(
REGISTRY_URL,
Reply::Json(fixture(REGISTRY_FIXTURE)),
)]));
let source = NpmSource::new(http.clone());
let project = project("acme-widget");
let versions = source.versions(&project).await.expect("npm versions");
assert_eq!(
versions
.iter()
.map(|entry| {
(
entry.raw.as_str(),
entry.version.as_str(),
entry.deprecated,
entry.reason.as_str(),
)
})
.collect::<Vec<_>>(),
vec![
("2.0.0-rc.1", "2.0.0-rc.1", false, ""),
("1.5.0-beta.2", "1.5.0-beta.2", false, ""),
("1.4.0", "1.4.0", false, ""),
("1.3.0", "1.3.0", false, ""),
(
"1.2.0",
"1.2.0",
true,
"Deprecated due to a security vulnerability; upgrade to 1.4.0",
),
("1.1.0-beta.1", "1.1.0-beta.1", false, ""),
("1.0.0", "1.0.0", false, ""),
("0.9.0", "0.9.0", true, "use 1.x"),
]
);
assert_eq!(http.calls(), vec![format!("json {REGISTRY_URL}")]);
let again = source.versions(&project).await.expect("repeat versions");
assert_eq!(again, versions, "newest-first order is deterministic");
}
// ---------------------------------------------------------------------------
// Artifacts
// ---------------------------------------------------------------------------
#[tokio::test]
async fn npm_artifacts_use_tarball_metadata_and_never_relabel_digests() {
let http = Arc::new(FakeHttp::new(vec![(
REGISTRY_URL,
Reply::Json(fixture(REGISTRY_FIXTURE)),
)]));
let source = NpmSource::new(http.clone());
let project = project("acme-widget");
assert_eq!(
source.artifacts(&project, &version("1.4.0")).await.unwrap(),
vec![ArtifactInfo {
file_name: "acme-widget-1.4.0.tgz".to_owned(),
url: "https://registry.npmjs.org/acme-widget/-/acme-widget-1.4.0.tgz".to_owned(),
sha256: None,
size: Some(456789),
mime_type: Some("application/gzip".to_owned()),
}]
);
for raw in ["1.0.0", "1.3.0"] {
let artifacts = source.artifacts(&project, &version(raw)).await.unwrap();
assert_eq!(artifacts.len(), 1, "{raw}");
assert_eq!(
artifacts[0].sha256, None,
"{raw}: SHA-1/SHA-512 must not be relabeled as SHA-256"
);
}
assert!(
source
.artifacts(&project, &version("9.9.9"))
.await
.unwrap()
.is_empty()
);
assert!(
http.calls().iter().all(|call| call.starts_with("json ")),
"declared metadata needs no HEAD or download: {:?}",
http.calls()
);
}
// ---------------------------------------------------------------------------
// Statuses
// ---------------------------------------------------------------------------
#[tokio::test]
async fn npm_statuses_report_deprecation_with_registry_kind() {
let http = Arc::new(FakeHttp::new(vec![(
REGISTRY_URL,
Reply::Json(fixture(REGISTRY_FIXTURE)),
)]));
let source = NpmSource::new(http);
let project = project("acme-widget");
assert_eq!(
source.statuses(&project, &version("1.2.0")).await.unwrap(),
vec![StatusInfo {
status: "deprecated".to_owned(),
kind: Some("registry".to_owned()),
reason: "Deprecated due to a security vulnerability; upgrade to 1.4.0".to_owned(),
}],
"a security-looking message is still a registry deprecation"
);
assert_eq!(
source.statuses(&project, &version("0.9.0")).await.unwrap(),
vec![StatusInfo {
status: "deprecated".to_owned(),
kind: Some("registry".to_owned()),
reason: "use 1.x".to_owned(),
}]
);
assert!(
source
.statuses(&project, &version("1.4.0"))
.await
.unwrap()
.is_empty()
);
assert!(
source
.statuses(&project, &version("9.9.9"))
.await
.unwrap()
.is_empty()
);
}
// ---------------------------------------------------------------------------
// Project metadata
// ---------------------------------------------------------------------------
#[tokio::test]
async fn npm_project_meta_exposes_dist_tags_as_channels() {
let http = Arc::new(FakeHttp::new(vec![(
REGISTRY_URL,
Reply::Json(fixture(REGISTRY_FIXTURE)),
)]));
let source = NpmSource::new(http);
let meta = source
.project_meta(&project("acme-widget"))
.await
.expect("npm meta");
assert_eq!(meta["name"], "acme-widget");
assert_eq!(
meta["description"],
"Synthetic npm package for source tests"
);
assert_eq!(meta["homepage"], "https://example.invalid/acme-widget");
assert_eq!(
meta["repository"],
"git+https://example.invalid/acme-widget.git"
);
assert_eq!(meta["license"], "MIT");
assert_eq!(meta["channels"]["latest"], "1.4.0");
assert_eq!(meta["channels"]["next"], "2.0.0-rc.1");
assert_eq!(meta["channels"]["beta"], "1.5.0-beta.2");
}
// ---------------------------------------------------------------------------
// Scoped names
// ---------------------------------------------------------------------------
#[tokio::test]
async fn npm_scoped_names_are_percent_encoded_and_keep_display_name() {
assert_eq!(NpmSource::registry_url("acme-widget"), REGISTRY_URL);
assert_eq!(
NpmSource::registry_url("@acme/scoped-widget"),
SCOPED_URL,
"the scope separator must be percent-encoded"
);
let http = Arc::new(FakeHttp::new(vec![(
SCOPED_URL,
Reply::Json(fixture(SCOPED_FIXTURE)),
)]));
let source = NpmSource::new(http.clone());
let project = project("@acme/scoped-widget");
let versions = source.versions(&project).await.expect("scoped versions");
assert_eq!(
versions
.iter()
.map(|entry| { (entry.raw.as_str(), entry.deprecated, entry.reason.as_str(),) })
.collect::<Vec<_>>(),
vec![
("1.1.0-canary.0", true, "canary builds are unsupported"),
("1.0.0", false, ""),
]
);
assert_eq!(http.calls(), vec![format!("json {SCOPED_URL}")]);
let meta = source.project_meta(&project).await.expect("scoped meta");
assert_eq!(meta["name"], "@acme/scoped-widget");
assert_eq!(
meta["repository"],
"https://example.invalid/scoped-widget.git"
);
assert_eq!(meta["license"], "Apache-2.0");
assert_eq!(meta["channels"]["latest"], "1.0.0");
assert_eq!(meta["channels"]["canary"], "1.1.0-canary.0");
let artifacts = source
.artifacts(&project, &version("1.0.0"))
.await
.expect("scoped artifacts");
assert_eq!(
artifacts,
vec![ArtifactInfo {
file_name: "scoped-widget-1.0.0.tgz".to_owned(),
url: "https://registry.npmjs.org/@acme/scoped-widget/-/scoped-widget-1.0.0.tgz"
.to_owned(),
sha256: None,
size: Some(2222),
mime_type: Some("application/gzip".to_owned()),
}]
);
}
// ---------------------------------------------------------------------------
// Transport behavior
// ---------------------------------------------------------------------------
#[tokio::test]
async fn npm_propagates_transport_errors() {
let http = Arc::new(FakeHttp::new(vec![(
REGISTRY_URL,
Reply::Error("HTTP 503 Service Unavailable for https://registry.npmjs.org".to_owned()),
)]));
let source = NpmSource::new(http.clone());
let error = source
.versions(&project("acme-widget"))
.await
.expect_err("transport errors propagate");
assert!(error.to_string().contains("503"));
assert_eq!(http.calls(), vec![format!("json {REGISTRY_URL}")]);
}
#[test]
fn npm_advertises_full_history_capabilities() {
let http: Arc<dyn RegistryHttp> = Arc::new(FakeHttp::default());
let source = NpmSource::new(http);
assert_eq!(source.name(), "npm");
assert_eq!(
source.capabilities(),
SourceCapabilities {
versions: true,
artifacts: true,
statuses: true,
project_meta: true,
}
);
}