sbom-tools 0.1.22

Semantic SBOM diff and analysis tool
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
//! Integration tests for the watch subsystem.

use sbom_tools::watch::{WatchConfig, parse_duration};
use std::path::PathBuf;
use std::time::Duration;

// ============================================================================
// Duration parsing
// ============================================================================

#[test]
fn test_parse_duration_seconds() {
    assert_eq!(parse_duration("30s").unwrap(), Duration::from_secs(30));
}

#[test]
fn test_parse_duration_minutes() {
    assert_eq!(parse_duration("5m").unwrap(), Duration::from_secs(300));
}

#[test]
fn test_parse_duration_hours() {
    assert_eq!(parse_duration("1h").unwrap(), Duration::from_secs(3600));
}

#[test]
fn test_parse_duration_days() {
    assert_eq!(parse_duration("2d").unwrap(), Duration::from_secs(172_800));
}

#[test]
fn test_parse_duration_milliseconds() {
    assert_eq!(parse_duration("500ms").unwrap(), Duration::from_millis(500));
}

#[test]
fn test_parse_duration_invalid() {
    assert!(parse_duration("abc").is_err());
    assert!(parse_duration("").is_err());
    assert!(parse_duration("10").is_err());
    assert!(parse_duration("10x").is_err());
}

// ============================================================================
// Watch loop: initial scan with fixtures
// ============================================================================

#[test]
fn test_watch_loop_no_files_returns_error() {
    let dir = tempfile::tempdir().expect("create temp dir");
    let config = WatchConfig {
        watch_dirs: vec![dir.path().to_path_buf()],
        poll_interval: Duration::from_secs(1),
        enrich_interval: Duration::from_secs(3600),
        debounce: Duration::ZERO,
        output: sbom_tools::config::OutputConfig::default(),
        enrichment: sbom_tools::config::EnrichmentConfig::default(),
        webhook_url: None,
        exit_on_change: false,
        max_snapshots: 10,
        quiet: true,
        dry_run: false,
        cra_standards_enabled: false,
        cra_standards_interval: Duration::from_secs(86_400),
        cra_standards_timeout: Duration::from_secs(10),
    };

    let result = sbom_tools::watch::run_watch_loop(&config);
    assert!(result.is_err());
    let err_msg = result.err().unwrap().to_string();
    assert!(
        err_msg.contains("no SBOM files found"),
        "expected NoFilesFound, got: {err_msg}"
    );
}

#[test]
fn test_watch_loop_nonexistent_dir() {
    let config = WatchConfig {
        watch_dirs: vec![PathBuf::from("/nonexistent/dir/that/does/not/exist")],
        poll_interval: Duration::from_secs(1),
        enrich_interval: Duration::from_secs(3600),
        debounce: Duration::ZERO,
        output: sbom_tools::config::OutputConfig::default(),
        enrichment: sbom_tools::config::EnrichmentConfig::default(),
        webhook_url: None,
        exit_on_change: false,
        max_snapshots: 10,
        quiet: true,
        dry_run: false,
        cra_standards_enabled: false,
        cra_standards_interval: Duration::from_secs(86_400),
        cra_standards_timeout: Duration::from_secs(10),
    };

    // The cli handler checks for dir existence; the loop itself may still
    // get NoFilesFound because the dir isn't scannable.
    let result = sbom_tools::watch::run_watch_loop(&config);
    assert!(result.is_err());
}

#[test]
fn test_watch_loop_exit_on_change() {
    let dir = tempfile::tempdir().expect("create temp dir");
    let fixture_path = dir.path().join("test.cdx.json");

    // Copy a real fixture for initial scan
    let demo = std::fs::read_to_string("tests/fixtures/demo-old.cdx.json").expect("read fixture");
    std::fs::write(&fixture_path, &demo).expect("write fixture");

    let config = WatchConfig {
        watch_dirs: vec![dir.path().to_path_buf()],
        poll_interval: Duration::from_millis(50),
        enrich_interval: Duration::from_secs(3600),
        debounce: Duration::ZERO,
        output: sbom_tools::config::OutputConfig::default(),
        enrichment: sbom_tools::config::EnrichmentConfig::default(),
        webhook_url: None,
        exit_on_change: true,
        max_snapshots: 10,
        quiet: true,
        dry_run: false,
        cra_standards_enabled: false,
        cra_standards_interval: Duration::from_secs(86_400),
        cra_standards_timeout: Duration::from_secs(10),
    };

    // Spawn the watch loop in a thread, modify the file, then verify it exits
    let config_clone = config.clone();
    let fixture_clone = fixture_path.clone();
    let handle = std::thread::spawn(move || sbom_tools::watch::run_watch_loop(&config_clone));

    // Wait a bit for initial scan, then modify the file
    std::thread::sleep(Duration::from_millis(100));
    let demo_new =
        std::fs::read_to_string("tests/fixtures/demo-new.cdx.json").expect("read new fixture");
    std::fs::write(&fixture_clone, &demo_new).expect("modify fixture");

    // Watch loop should exit within a few poll intervals
    let result = handle.join().expect("thread join");
    assert!(result.is_ok(), "watch loop should exit cleanly: {result:?}");
}

#[test]
fn test_watch_loop_initial_scan_parses_fixtures() {
    // Use exit_on_change with an immediate modification to verify parsing works
    let dir = tempfile::tempdir().expect("create temp dir");

    // Write a CycloneDX fixture
    let cdx = std::fs::read_to_string("tests/fixtures/demo-old.cdx.json").expect("read fixture");
    std::fs::write(dir.path().join("app.cdx.json"), &cdx).expect("write");

    // Write an SPDX fixture if available
    let spdx_dir = PathBuf::from("tests/fixtures/spdx");
    if spdx_dir.exists()
        && let Some(Ok(entry)) = std::fs::read_dir(&spdx_dir).ok().and_then(|mut entries| {
            entries.find(|e| {
                e.as_ref().is_ok_and(|e| {
                    e.file_name()
                        .to_string_lossy()
                        .to_lowercase()
                        .ends_with(".spdx.json")
                })
            })
        })
    {
        let content = std::fs::read_to_string(entry.path()).unwrap_or_default();
        if !content.is_empty() {
            std::fs::write(dir.path().join("lib.spdx.json"), content).expect("write spdx");
        }
    }

    let config = WatchConfig {
        watch_dirs: vec![dir.path().to_path_buf()],
        poll_interval: Duration::from_millis(50),
        enrich_interval: Duration::from_secs(3600),
        debounce: Duration::ZERO,
        output: sbom_tools::config::OutputConfig::default(),
        enrichment: sbom_tools::config::EnrichmentConfig::default(),
        webhook_url: None,
        exit_on_change: true,
        max_snapshots: 10,
        quiet: true,
        dry_run: false,
        cra_standards_enabled: false,
        cra_standards_interval: Duration::from_secs(86_400),
        cra_standards_timeout: Duration::from_secs(10),
    };

    let config_clone = config.clone();
    let dir_path = dir.path().to_path_buf();

    let handle = std::thread::spawn(move || sbom_tools::watch::run_watch_loop(&config_clone));

    // Trigger a change so it exits
    std::thread::sleep(Duration::from_millis(100));
    let cdx_new =
        std::fs::read_to_string("tests/fixtures/demo-new.cdx.json").expect("read new fixture");
    std::fs::write(dir_path.join("app.cdx.json"), &cdx_new).expect("modify");

    let result = handle.join().expect("thread join");
    assert!(result.is_ok());
}

// ============================================================================
// Enrichment-aware watch loop (mock OSV API)
// ============================================================================

#[cfg(feature = "enrichment")]
mod enrichment_loop {
    use super::*;
    use httpmock::prelude::*;

    const VULN_ID: &str = "GHSA-watch-test-0001";

    fn sbom_body(version: &str) -> String {
        serde_json::json!({
            "bomFormat": "CycloneDX",
            "specVersion": "1.5",
            "version": 1,
            "components": [{
                "type": "library",
                "name": "lodash",
                "version": version,
                "purl": format!("pkg:npm/lodash@{version}")
            }]
        })
        .to_string()
    }

    fn full_vuln_body() -> serde_json::Value {
        serde_json::json!({
            "id": VULN_ID,
            "summary": "Prototype pollution in lodash",
            "modified": "2026-01-10T00:00:00Z",
            "severity": [
                {"type": "CVSS_V3", "score": "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H"}
            ]
        })
    }

    #[test]
    fn test_watch_loop_enriched_reparse_no_false_resolved_alerts() {
        let server = MockServer::start();
        let health_mock = server.mock(|when, then| {
            when.method(GET).path("/v1/vulns/OSV-2020-1");
            then.status(404);
        });
        let batch_mock = server.mock(|when, then| {
            when.method(POST).path("/v1/querybatch");
            then.status(200).json_body(serde_json::json!({
                "results": [{"vulns": [{"id": VULN_ID, "modified": "2026-01-10T00:00:00Z"}]}]
            }));
        });
        let vuln_mock = server.mock(|when, then| {
            when.method(GET).path(format!("/v1/vulns/{VULN_ID}"));
            then.status(200).json_body(full_vuln_body());
        });

        let watch_dir = tempfile::tempdir().expect("create watch dir");
        let cache_dir = tempfile::tempdir().expect("create cache dir");
        let out_dir = tempfile::tempdir().expect("create out dir");
        let sbom_path = watch_dir.path().join("app.cdx.json");
        std::fs::write(&sbom_path, sbom_body("4.17.20")).expect("write sbom");
        let output_file = out_dir.path().join("events.ndjson");

        let config = WatchConfig {
            watch_dirs: vec![watch_dir.path().to_path_buf()],
            poll_interval: Duration::from_millis(50),
            enrich_interval: Duration::from_millis(150),
            debounce: Duration::ZERO,
            output: sbom_tools::config::OutputConfig {
                format: sbom_tools::reports::ReportFormat::Json,
                file: Some(output_file.clone()),
                ..Default::default()
            },
            enrichment: sbom_tools::config::EnrichmentConfig {
                enabled: true,
                cache_dir: Some(cache_dir.path().to_path_buf()),
                timeout_secs: 5,
                api_base: Some(server.base_url()),
                ..Default::default()
            },
            webhook_url: None,
            exit_on_change: true,
            max_snapshots: 10,
            quiet: true,
            dry_run: false,
            cra_standards_enabled: false,
            cra_standards_interval: Duration::from_secs(86_400),
            cra_standards_timeout: Duration::from_secs(10),
        };

        let config_clone = config.clone();
        let handle = std::thread::spawn(move || sbom_tools::watch::run_watch_loop(&config_clone));

        // Let the initial scan plus at least one periodic enrichment cycle run,
        // then touch the file with a component version bump
        std::thread::sleep(Duration::from_millis(500));
        std::fs::write(&sbom_path, sbom_body("4.17.21")).expect("modify sbom");

        let result = handle.join().expect("thread join");
        assert!(result.is_ok(), "watch loop should exit cleanly: {result:?}");

        // Initial scan, first periodic cycle, and the re-parse must all enrich
        assert!(
            batch_mock.hits() >= 3,
            "expected >=3 querybatch calls, got {}",
            batch_mock.hits()
        );
        assert!(vuln_mock.hits() >= 1);
        assert!(health_mock.hits() >= 3);

        let output = std::fs::read_to_string(&output_file).expect("read ndjson output");
        let events: Vec<serde_json::Value> = output
            .lines()
            .map(|l| serde_json::from_str(l).expect("valid NDJSON line"))
            .collect();

        let changes: Vec<&serde_json::Value> =
            events.iter().filter(|e| e["type"] == "change").collect();
        assert!(!changes.is_empty(), "expected a change event: {events:?}");
        for change in &changes {
            assert_eq!(
                change["resolved_vulns"].as_array().map(Vec::len),
                Some(0),
                "vuln still present must not be alerted as resolved: {change}"
            );
            assert_eq!(
                change["new_vulns"].as_array().map(Vec::len),
                Some(0),
                "known vuln must not be re-alerted as new: {change}"
            );
        }

        assert!(
            !events.iter().any(|e| e["type"] == "new_vulns"),
            "enrichment cycles must not re-announce known vulns: {events:?}"
        );

        let statuses: Vec<&serde_json::Value> =
            events.iter().filter(|e| e["type"] == "status").collect();
        assert!(!statuses.is_empty(), "expected status events: {events:?}");
        for status in &statuses {
            assert_eq!(
                status["vulns"], 1,
                "vuln count must stay at 1 across enrichment cycles: {status}"
            );
        }
    }
}

// ============================================================================
// NDJSON output verification
// ============================================================================

#[test]
fn test_watch_ndjson_output_produces_valid_json() {
    use sbom_tools::reports::ReportFormat;

    let dir = tempfile::tempdir().expect("create temp dir");
    let output_file = dir.path().join("events.ndjson");

    let demo = std::fs::read_to_string("tests/fixtures/demo-old.cdx.json").expect("read fixture");
    let fixture_path = dir.path().join("test.cdx.json");
    std::fs::write(&fixture_path, &demo).expect("write fixture");

    let config = WatchConfig {
        watch_dirs: vec![dir.path().to_path_buf()],
        poll_interval: Duration::from_millis(50),
        enrich_interval: Duration::from_secs(3600),
        debounce: Duration::ZERO,
        output: sbom_tools::config::OutputConfig {
            format: ReportFormat::Json,
            file: Some(output_file.clone()),
            ..Default::default()
        },
        enrichment: sbom_tools::config::EnrichmentConfig::default(),
        webhook_url: None,
        exit_on_change: true,
        max_snapshots: 10,
        quiet: true,
        dry_run: false,
        cra_standards_enabled: false,
        cra_standards_interval: Duration::from_secs(86_400),
        cra_standards_timeout: Duration::from_secs(10),
    };

    let config_clone = config.clone();
    let fixture_clone = fixture_path.clone();

    let handle = std::thread::spawn(move || sbom_tools::watch::run_watch_loop(&config_clone));

    std::thread::sleep(Duration::from_millis(100));
    let demo_new =
        std::fs::read_to_string("tests/fixtures/demo-new.cdx.json").expect("read new fixture");
    std::fs::write(&fixture_clone, &demo_new).expect("modify fixture");

    let result = handle.join().expect("thread join");
    assert!(result.is_ok());

    // Verify NDJSON output
    if output_file.exists() {
        let output = std::fs::read_to_string(&output_file).expect("read output");
        for line in output.lines() {
            let parsed: serde_json::Value =
                serde_json::from_str(line).expect("each line should be valid JSON");
            assert!(
                parsed.get("type").is_some(),
                "each event should have a 'type' field"
            );
        }
    }
}