patchsense 0.1.1

Prioritize vulnerabilities from lockfiles using OSV, EPSS, and CISA KEV
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
//! `patchsense scan` against a local OSV stand-in. Nothing leaves the machine.

use std::path::PathBuf;

use assert_cmd::Command;
use predicates::prelude::*;
use serde_json::{json, Value};
use wiremock::matchers::{method, path};
use wiremock::{Mock, MockServer, Request, ResponseTemplate};

fn repo_path(relative: &str) -> PathBuf {
    PathBuf::from(env!("CARGO_MANIFEST_DIR")).join(relative)
}

async fn mount_empty_enrichment(server: &MockServer) {
    Mock::given(method("GET"))
        .and(path("/data/v1/epss"))
        .respond_with(ResponseTemplate::new(200).set_body_json(json!({ "data": [] })))
        .mount(server)
        .await;
    Mock::given(method("GET"))
        .and(path("/kev.json"))
        .respond_with(ResponseTemplate::new(200).set_body_json(json!({
            "catalogVersion": "test",
            "vulnerabilities": []
        })))
        .mount(server)
        .await;
}

fn enrichment_env(command: &mut Command, server: &MockServer) {
    command.env("PATCHSENSE_EPSS_URL", server.uri());
    command.env(
        "PATCHSENSE_KEV_URL",
        format!("{}/kev.json", server.uri().trim_end_matches('/')),
    );
}

fn querybatch_body(request: &Request) -> ResponseTemplate {
    let body: Value = serde_json::from_slice(&request.body).unwrap_or(json!({}));
    let queries = body["queries"].as_array().cloned().unwrap_or_default();
    let results: Vec<Value> = queries
        .iter()
        .map(|query| {
            if query["package"]["name"] == "lodash" {
                json!({
                    "vulns": [{
                        "id": "GHSA-35jh-r3h4-6jhm",
                        "modified": "2024-01-01T00:00:00Z"
                    }]
                })
            } else {
                json!({})
            }
        })
        .collect();
    ResponseTemplate::new(200).set_body_json(json!({ "results": results }))
}

#[tokio::test]
async fn scan_prints_lodash_advisory_from_the_npm_fixture() {
    let server = MockServer::start().await;
    Mock::given(method("POST"))
        .and(path("/v1/querybatch"))
        .respond_with(querybatch_body)
        .mount(&server)
        .await;
    let advisory = std::fs::read_to_string(repo_path(
        "../../tests/fixtures/osv/vulns/GHSA-35jh-r3h4-6jhm.json",
    ))
    .expect("advisory fixture");
    Mock::given(method("GET"))
        .and(path("/v1/vulns/GHSA-35jh-r3h4-6jhm"))
        .respond_with(ResponseTemplate::new(200).set_body_string(advisory))
        .mount(&server)
        .await;
    mount_empty_enrichment(&server).await;

    let mut command = Command::cargo_bin("patchsense").expect("binary");
    command
        .arg("scan")
        .arg("--no-cache")
        .arg(repo_path("../../tests/fixtures/npm/lodash"))
        .env("PATCHSENSE_OSV_URL", server.uri())
        .env("NO_COLOR", "1");
    enrichment_env(&mut command, &server);
    command
        .assert()
        .success()
        .stdout(predicate::str::contains("\"schema_version\": 1"))
        .stdout(predicate::str::contains("GHSA-35jh-r3h4-6jhm"))
        .stdout(predicate::str::contains("CVE-2021-23337"))
        .stdout(predicate::str::contains("4.17.21"))
        .stdout(predicate::str::contains("Command Injection in lodash"));
}

#[tokio::test]
async fn scan_without_a_lockfile_exits_2() {
    let dir = tempfile::tempdir().expect("tempdir");
    let mut command = Command::cargo_bin("patchsense").expect("binary");
    command
        .arg("scan")
        .arg(dir.path())
        .env("PATCHSENSE_OSV_URL", "http://127.0.0.1:9")
        .env("NO_COLOR", "1");
    command
        .assert()
        .code(2)
        .stderr(predicate::str::contains("no supported lockfile"));
}

#[tokio::test]
async fn broken_lockfile_beside_a_valid_one_warns_and_exits_0() {
    let server = MockServer::start().await;
    Mock::given(method("POST"))
        .and(path("/v1/querybatch"))
        .respond_with(querybatch_body)
        .mount(&server)
        .await;
    let advisory = std::fs::read_to_string(repo_path(
        "../../tests/fixtures/osv/vulns/GHSA-35jh-r3h4-6jhm.json",
    ))
    .expect("advisory fixture");
    Mock::given(method("GET"))
        .and(path("/v1/vulns/GHSA-35jh-r3h4-6jhm"))
        .respond_with(ResponseTemplate::new(200).set_body_string(advisory))
        .mount(&server)
        .await;
    mount_empty_enrichment(&server).await;

    let dir = tempfile::tempdir().expect("tempdir");
    std::fs::create_dir(dir.path().join("a-bad")).expect("dir");
    std::fs::create_dir(dir.path().join("b-good")).expect("dir");
    std::fs::write(dir.path().join("a-bad/package-lock.json"), "{").expect("bad");
    std::fs::write(
        dir.path().join("b-good/package-lock.json"),
        r#"{"lockfileVersion":1,"dependencies":{"lodash":{"version":"4.17.14"}}}"#,
    )
    .expect("good");

    let mut command = Command::cargo_bin("patchsense").expect("binary");
    command
        .arg("scan")
        .arg("--no-cache")
        .arg(dir.path())
        .env("PATCHSENSE_OSV_URL", server.uri())
        .env("NO_COLOR", "1");
    enrichment_env(&mut command, &server);
    command
        .assert()
        .success()
        .stdout(predicate::str::contains("lodash"))
        .stdout(predicate::str::contains("4.17.14"))
        .stdout(predicate::str::contains("\"schema_version\": 1"))
        .stderr(predicate::str::contains("a-bad/package-lock.json"));
}

#[tokio::test]
async fn every_broken_lockfile_exits_2() {
    let dir = tempfile::tempdir().expect("tempdir");
    std::fs::create_dir(dir.path().join("a")).expect("dir");
    std::fs::create_dir(dir.path().join("b")).expect("dir");
    std::fs::write(dir.path().join("a/package-lock.json"), "{").expect("bad");
    std::fs::write(dir.path().join("b/package-lock.json"), "[]").expect("bad");
    let mut command = Command::cargo_bin("patchsense").expect("binary");
    command
        .arg("scan")
        .arg(dir.path())
        .env("PATCHSENSE_OSV_URL", "http://127.0.0.1:9")
        .env("NO_COLOR", "1");
    command
        .assert()
        .code(2)
        .stderr(predicate::str::contains("package-lock.json"));
}

#[tokio::test]
async fn no_keep_going_exits_2_when_one_file_fails() {
    let dir = tempfile::tempdir().expect("tempdir");
    std::fs::create_dir(dir.path().join("a-bad")).expect("dir");
    std::fs::create_dir(dir.path().join("b-good")).expect("dir");
    std::fs::write(dir.path().join("a-bad/package-lock.json"), "{").expect("bad");
    std::fs::write(
        dir.path().join("b-good/package-lock.json"),
        r#"{"lockfileVersion":1,"dependencies":{"lodash":{"version":"4.17.14"}}}"#,
    )
    .expect("good");
    let mut command = Command::cargo_bin("patchsense").expect("binary");
    command
        .arg("scan")
        .arg("--no-keep-going")
        .arg(dir.path())
        .env("PATCHSENSE_OSV_URL", "http://127.0.0.1:9")
        .env("NO_COLOR", "1");
    command
        .assert()
        .code(2)
        .stderr(predicate::str::contains("a-bad/package-lock.json"));
}

#[tokio::test]
async fn ecosystem_filter_and_unknown_ecosystem() {
    let dir = tempfile::tempdir().expect("tempdir");
    std::fs::write(
        dir.path().join("package-lock.json"),
        r#"{"lockfileVersion":1,"dependencies":{"lodash":{"version":"4.17.14"}}}"#,
    )
    .expect("lock");
    let mut command = Command::cargo_bin("patchsense").expect("binary");
    command
        .arg("scan")
        .arg(dir.path())
        .arg("--ecosystem")
        .arg("pypi")
        .env("PATCHSENSE_OSV_URL", "http://127.0.0.1:9")
        .env("NO_COLOR", "1");
    command
        .assert()
        .success()
        .stdout(predicate::str::contains("\"schema_version\": 1"))
        .stdout(predicate::str::contains("\"findings\": []"));

    let mut command = Command::cargo_bin("patchsense").expect("binary");
    command
        .arg("scan")
        .arg(dir.path())
        .arg("--ecosystem")
        .arg("not-an-ecosystem")
        .env("NO_COLOR", "1");
    command
        .assert()
        .code(2)
        .stderr(predicate::str::contains("unknown ecosystem"));
}

#[tokio::test]
async fn kev_advisory_fails_critical_and_passes_never() {
    let server = MockServer::start().await;
    Mock::given(method("POST"))
        .and(path("/v1/querybatch"))
        .respond_with(ResponseTemplate::new(200).set_body_json(json!({
            "results": [{
                "vulns": [{
                    "id": "GHSA-kev0-0000-0000",
                    "modified": "2026-01-01T00:00:00Z"
                }]
            }]
        })))
        .mount(&server)
        .await;
    Mock::given(method("GET"))
        .and(path("/v1/vulns/GHSA-kev0-0000-0000"))
        .respond_with(ResponseTemplate::new(200).set_body_json(json!({
            "id": "GHSA-kev0-0000-0000",
            "aliases": ["CVE-2021-23337"],
            "summary": "Known exploited lodash",
            "severity": [{
                "type": "CVSS_V3",
                "score": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H"
            }],
            "affected": [{
                "package": {"ecosystem": "npm", "name": "lodash"},
                "ranges": [{
                    "type": "SEMVER",
                    "events": [{"introduced": "0"}, {"fixed": "4.17.21"}]
                }]
            }]
        })))
        .mount(&server)
        .await;
    Mock::given(method("GET"))
        .and(path("/data/v1/epss"))
        .respond_with(ResponseTemplate::new(200).set_body_json(json!({
            "data": [{
                "cve": "CVE-2021-23337",
                "epss": "0.20",
                "percentile": "0.90",
                "date": "2026-10-24"
            }]
        })))
        .mount(&server)
        .await;
    Mock::given(method("GET"))
        .and(path("/kev.json"))
        .respond_with(ResponseTemplate::new(200).set_body_json(json!({
            "catalogVersion": "test",
            "vulnerabilities": [{
                "cveID": "CVE-2021-23337",
                "dateAdded": "2021-11-03",
                "dueDate": "2021-11-17",
                "knownRansomwareCampaignUse": "Known",
                "vulnerabilityName": "Lodash Command Injection",
                "requiredAction": "Apply updates"
            }]
        })))
        .mount(&server)
        .await;

    let dir = tempfile::tempdir().expect("tempdir");
    std::fs::write(
        dir.path().join("package-lock.json"),
        r#"{"lockfileVersion":1,"dependencies":{"lodash":{"version":"4.17.14"}}}"#,
    )
    .expect("lock");

    let mut critical = Command::cargo_bin("patchsense").expect("binary");
    critical
        .arg("scan")
        .arg("--no-cache")
        .arg(dir.path())
        .arg("--fail-on")
        .arg("critical")
        .env("PATCHSENSE_OSV_URL", server.uri())
        .env("NO_COLOR", "1");
    enrichment_env(&mut critical, &server);
    critical.assert().code(1);

    let mut never = Command::cargo_bin("patchsense").expect("binary");
    never
        .arg("scan")
        .arg("--no-cache")
        .arg(dir.path())
        .arg("--fail-on")
        .arg("never")
        .env("PATCHSENSE_OSV_URL", server.uri())
        .env("NO_COLOR", "1");
    enrichment_env(&mut never, &server);
    never.assert().success();
}

#[tokio::test]
async fn one_scan_writes_three_files_and_queries_osv_once() {
    let server = MockServer::start().await;
    Mock::given(method("POST"))
        .and(path("/v1/querybatch"))
        .respond_with(querybatch_body)
        .expect(1)
        .mount(&server)
        .await;
    let advisory = std::fs::read_to_string(repo_path(
        "../../tests/fixtures/osv/vulns/GHSA-35jh-r3h4-6jhm.json",
    ))
    .expect("advisory fixture");
    Mock::given(method("GET"))
        .and(path("/v1/vulns/GHSA-35jh-r3h4-6jhm"))
        .respond_with(ResponseTemplate::new(200).set_body_string(advisory))
        .expect(1)
        .mount(&server)
        .await;
    mount_empty_enrichment(&server).await;

    let dir = tempfile::tempdir().expect("tempdir");
    std::fs::write(
        dir.path().join("package-lock.json"),
        r#"{"lockfileVersion":1,"dependencies":{"lodash":{"version":"4.17.14"}}}"#,
    )
    .expect("lock");
    let out = tempfile::tempdir().expect("outdir");
    let json_path = out.path().join("report.json");
    let sarif_path = out.path().join("report.sarif");
    let gitlab_path = out.path().join("gl-dependency-scanning-report.json");

    let mut command = Command::cargo_bin("patchsense").expect("binary");
    command
        .arg("scan")
        .arg("--no-cache")
        .arg(dir.path())
        .arg("--format")
        .arg("json")
        .arg("--output")
        .arg(&json_path)
        .arg("--format")
        .arg("sarif")
        .arg("--output")
        .arg(&sarif_path)
        .arg("--format")
        .arg("gitlab")
        .arg("--output")
        .arg(&gitlab_path)
        .env("PATCHSENSE_OSV_URL", server.uri())
        .env("NO_COLOR", "1");
    enrichment_env(&mut command, &server);
    command
        .assert()
        .success()
        .stdout(predicate::str::is_empty());

    server.verify().await;
    let requests = server.received_requests().await.expect("requests");
    let batches = requests
        .iter()
        .filter(|request| request.url.path() == "/v1/querybatch")
        .count();
    assert_eq!(batches, 1);

    let json = std::fs::read_to_string(&json_path).expect("json");
    assert!(json.contains("\"schema_version\": 1"));
    assert!(json.contains("GHSA-35jh-r3h4-6jhm"));
    assert!(json.contains("CVE-2021-23337"));
    let sarif = std::fs::read_to_string(&sarif_path).expect("sarif");
    assert!(sarif.contains("\"version\": \"2.1.0\""));
    assert!(sarif.contains("GHSA-35jh-r3h4-6jhm"));
    let gitlab = std::fs::read_to_string(&gitlab_path).expect("gitlab");
    assert!(gitlab.contains("dependency_scanning"));
    assert!(gitlab.contains("GHSA-35jh-r3h4-6jhm"));
}

#[test]
fn two_formats_without_output_exit_2() {
    let dir = tempfile::tempdir().expect("tempdir");
    let mut command = Command::cargo_bin("patchsense").expect("binary");
    command
        .arg("scan")
        .arg(dir.path())
        .arg("--format")
        .arg("json")
        .arg("--format")
        .arg("sarif")
        .env("NO_COLOR", "1");
    command
        .assert()
        .code(2)
        .stderr(predicate::str::contains("stdout"));
}

#[test]
fn invalid_config_exits_2() {
    let dir = tempfile::tempdir().expect("tempdir");
    let config = dir.path().join("patchsense.toml");
    std::fs::write(&config, "not_a_field = true\n").expect("config");
    let mut command = Command::cargo_bin("patchsense").expect("binary");
    command
        .arg("scan")
        .arg("--config")
        .arg(&config)
        .arg(dir.path())
        .env("NO_COLOR", "1");
    command
        .assert()
        .code(2)
        .stderr(predicate::str::contains("not_a_field"));
}

#[test]
fn ttl_that_is_not_a_number_names_the_key_and_exits_2() {
    let dir = tempfile::tempdir().expect("tempdir");
    let config = dir.path().join("patchsense.toml");
    std::fs::write(&config, "[cache]\nttl_hours_osv = nan\n").expect("config");
    let mut command = Command::cargo_bin("patchsense").expect("binary");
    command
        .arg("scan")
        .arg("--config")
        .arg(&config)
        .arg(dir.path())
        .env("NO_COLOR", "1");
    command.assert().code(2).stderr(predicate::str::contains(
        "ttl_hours_osv must be a whole number of hours",
    ));
}

#[tokio::test]
async fn offline_one_hour_ttl_exits_2_when_the_cache_is_two_hours_old() {
    let server = MockServer::start().await;
    Mock::given(method("POST"))
        .and(path("/v1/querybatch"))
        .respond_with(querybatch_body)
        .mount(&server)
        .await;
    let advisory = std::fs::read_to_string(repo_path(
        "../../tests/fixtures/osv/vulns/GHSA-35jh-r3h4-6jhm.json",
    ))
    .expect("advisory fixture");
    Mock::given(method("GET"))
        .and(path("/v1/vulns/GHSA-35jh-r3h4-6jhm"))
        .respond_with(ResponseTemplate::new(200).set_body_string(advisory))
        .mount(&server)
        .await;
    mount_empty_enrichment(&server).await;

    let dir = tempfile::tempdir().expect("tempdir");
    let config = dir.path().join("patchsense.toml");
    std::fs::write(
        &config,
        "[cache]\nttl_hours_osv = 1\nttl_hours_epss = 1\nttl_hours_kev = 1\n",
    )
    .expect("config");
    let cache = dir.path().join("cache");
    std::fs::create_dir(&cache).expect("cache dir");

    let mut warm = Command::cargo_bin("patchsense").expect("binary");
    warm.arg("scan")
        .arg("--fail-on")
        .arg("never")
        .arg("--config")
        .arg(&config)
        .arg("--cache-dir")
        .arg(&cache)
        .arg(repo_path("../../tests/fixtures/npm/lodash"))
        .env("PATCHSENSE_OSV_URL", server.uri())
        .env("NO_COLOR", "1");
    enrichment_env(&mut warm, &server);
    warm.assert().success();

    let db = rusqlite::Connection::open(cache.join("cache.db")).expect("cache.db");
    for sql in [
        "UPDATE osv_vuln SET fetched_at = fetched_at - ?1",
        "UPDATE osv_query SET fetched_at = fetched_at - ?1",
        "UPDATE epss SET fetched_at = fetched_at - ?1",
        "UPDATE kev SET fetched_at = fetched_at - ?1",
    ] {
        db.execute(sql, [7_200_i64]).expect(sql);
    }

    let mut offline = Command::cargo_bin("patchsense").expect("binary");
    offline
        .arg("scan")
        .arg("--offline")
        .arg("--fail-on")
        .arg("never")
        .arg("--config")
        .arg(&config)
        .arg("--cache-dir")
        .arg(&cache)
        .arg(repo_path("../../tests/fixtures/npm/lodash"))
        .env("PATCHSENSE_OSV_URL", "http://127.0.0.1:9")
        .env("NO_COLOR", "1");
    offline
        .assert()
        .code(2)
        .stderr(predicate::str::contains("offline cache expired"))
        .stderr(predicate::str::contains("2h old"))
        .stderr(predicate::str::contains("1h TTL"));
}