uv-sbom 2.0.1

SBOM generation tool for uv projects - Generate CycloneDX SBOMs from uv.lock files
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
//! Configuration file support for uv-sbom.
//!
//! Provides YAML-based configuration through `uv-sbom.config.yml` files,
//! including data structures, file loading, and validation.

use anyhow::{bail, Context};
use serde::Deserialize;
use std::collections::HashMap;
use std::path::Path;

use crate::shared::Result;

pub const CONFIG_FILENAME: &str = "uv-sbom.config.yml";

/// Template content for `uv-sbom.config.yml`.
const CONFIG_TEMPLATE: &str = r#"# uv-sbom configuration file
# Documentation: https://github.com/Taketo-Yoda/uv-sbom#configuration

# Output format: json | markdown
# format: json

# Package exclusion patterns (supports wildcards)
# exclude_packages:
#   - "debug-*"
#   - "test-*"

# Disable CVE vulnerability checking (enabled by default; set to false to opt out)
# check_cve: true

# Severity threshold: low | medium | high | critical
# severity_threshold: high

# CVSS score threshold (0.0 - 10.0)
# cvss_threshold: 7.0

# CVEs to ignore during vulnerability checks
# ignore_cves:
#   - id: CVE-2024-1234
#     reason: "False positive: code path not reachable"
#   - id: CVE-2024-5678

# Enable license compliance checking
# check_license: false

# License compliance policy
# license_policy:
#   allow:
#     - "MIT"
#     - "Apache-2.0"
#     - "BSD-*"
#   deny:
#     - "AGPL-*"
#     - "GPL-*"
#   unknown: warn

# Suggest upgrade paths to fix vulnerable transitive dependencies (requires check_cve: true)
# suggest_fix: false
"#;

/// Generate a config template file in the specified directory.
///
/// Returns the absolute path of the created file on success.
/// Returns an error if the file already exists.
pub fn generate_config_template(dir: &Path) -> Result<std::path::PathBuf> {
    let file_path = dir.join(CONFIG_FILENAME);

    if file_path.exists() {
        let abs_path = dir.canonicalize().unwrap_or_else(|_| dir.to_path_buf());
        bail!(
            "{} already exists in {}. Use a different directory or remove the existing file.",
            CONFIG_FILENAME,
            abs_path.display()
        );
    }

    std::fs::write(&file_path, CONFIG_TEMPLATE).with_context(|| {
        format!(
            "Failed to write config template to: {}",
            file_path.display()
        )
    })?;

    let abs_path = file_path
        .canonicalize()
        .unwrap_or_else(|_| file_path.clone());
    Ok(abs_path)
}

/// Top-level configuration file schema.
#[derive(Debug, Deserialize, Default)]
pub struct ConfigFile {
    pub format: Option<String>,
    pub exclude_packages: Option<Vec<String>>,
    pub check_cve: Option<bool>,
    pub severity_threshold: Option<String>,
    pub cvss_threshold: Option<f64>,
    pub ignore_cves: Option<Vec<IgnoreCve>>,
    pub check_license: Option<bool>,
    pub license_policy: Option<LicensePolicyConfig>,
    pub suggest_fix: Option<bool>,
    /// Captures unknown fields for warnings.
    #[serde(flatten)]
    pub unknown_fields: HashMap<String, serde_yaml_ng::Value>,
}

/// License policy configuration from config file.
#[derive(Debug, Clone, PartialEq, Deserialize, Default)]
pub struct LicensePolicyConfig {
    pub allow: Option<Vec<String>>,
    pub deny: Option<Vec<String>>,
    pub unknown: Option<String>,
}

/// A CVE entry to ignore during vulnerability checks.
#[derive(Debug, Clone, PartialEq, Deserialize)]
pub struct IgnoreCve {
    pub id: String,
    pub reason: Option<String>,
}

impl IgnoreCve {
    /// Returns the reason for ignoring this CVE, if provided
    pub fn reason(&self) -> Option<&str> {
        self.reason.as_deref()
    }
}

/// Load config from an explicit path. Returns an error if the file is not found.
pub fn load_config_from_path(path: &Path) -> Result<ConfigFile> {
    let content = std::fs::read_to_string(path).with_context(|| {
        format!(
            "Failed to read config file: {}\n\n💡 Hint: Check that the file exists and is readable.",
            path.display()
        )
    })?;

    let config: ConfigFile = serde_yaml_ng::from_str(&content).with_context(|| {
        format!(
            "Failed to parse config file: {}\n\n💡 Hint: Ensure the file contains valid YAML syntax.",
            path.display()
        )
    })?;

    validate_config(&config)?;
    warn_unknown_fields(&config);

    Ok(config)
}

/// Auto-discover config in a directory. Returns `None` silently if not found.
pub fn discover_config(dir: &Path) -> Result<Option<ConfigFile>> {
    let config_path = dir.join(CONFIG_FILENAME);

    if !config_path.exists() {
        return Ok(None);
    }

    let config = load_config_from_path(&config_path)?;
    Ok(Some(config))
}

/// Validate the loaded configuration.
fn validate_config(config: &ConfigFile) -> Result<()> {
    if let Some(ref ignore_cves) = config.ignore_cves {
        for (i, entry) in ignore_cves.iter().enumerate() {
            if entry.id.trim().is_empty() {
                bail!(
                    "Invalid config: ignore_cves[{}].id must not be empty.\n\n\
                     💡 Hint: Each ignore_cves entry must have a non-empty 'id' field (e.g., \"CVE-2024-1234\").",
                    i
                );
            }
        }
    }

    if let Some(ref lp) = config.license_policy {
        if let Some(ref unknown) = lp.unknown {
            let valid = ["warn", "deny", "allow"];
            if !valid.contains(&unknown.to_lowercase().as_str()) {
                bail!(
                    "Invalid config: license_policy.unknown must be one of: warn, deny, allow. Got: \"{}\"",
                    unknown
                );
            }
        }
    }

    Ok(())
}

/// Warn about unknown fields in the config file.
fn warn_unknown_fields(config: &ConfigFile) {
    for key in config.unknown_fields.keys() {
        eprintln!(
            "⚠️  Warning: Unknown config field '{}' will be ignored.",
            key
        );
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::fs;
    use tempfile::TempDir;

    #[test]
    fn test_load_valid_config() {
        let dir = TempDir::new().unwrap();
        let config_path = dir.path().join("config.yml");
        fs::write(
            &config_path,
            r#"
format: markdown
exclude_packages:
  - setuptools
  - pip
check_cve: true
severity_threshold: HIGH
cvss_threshold: 7.0
ignore_cves:
  - id: CVE-2024-1234
    reason: "Not applicable to our usage"
  - id: CVE-2024-5678
"#,
        )
        .unwrap();

        let config = load_config_from_path(&config_path).unwrap();
        assert_eq!(config.format.as_deref(), Some("markdown"));
        assert_eq!(
            config.exclude_packages.as_deref(),
            Some(&["setuptools".to_string(), "pip".to_string()][..])
        );
        assert_eq!(config.check_cve, Some(true));
        assert_eq!(config.severity_threshold.as_deref(), Some("HIGH"));
        assert_eq!(config.cvss_threshold, Some(7.0));
        let cves = config.ignore_cves.unwrap();
        assert_eq!(cves.len(), 2);
        assert_eq!(cves[0].id, "CVE-2024-1234");
        assert_eq!(
            cves[0].reason.as_deref(),
            Some("Not applicable to our usage")
        );
        assert_eq!(cves[1].id, "CVE-2024-5678");
        assert!(cves[1].reason.is_none());
    }

    #[test]
    fn test_discover_config_found() {
        let dir = TempDir::new().unwrap();
        let config_path = dir.path().join(CONFIG_FILENAME);
        fs::write(
            &config_path,
            r#"
format: json
check_cve: false
"#,
        )
        .unwrap();

        let config = discover_config(dir.path()).unwrap();
        assert!(config.is_some());
        let config = config.unwrap();
        assert_eq!(config.format.as_deref(), Some("json"));
        assert_eq!(config.check_cve, Some(false));
    }

    #[test]
    fn test_discover_config_not_found() {
        let dir = TempDir::new().unwrap();
        let config = discover_config(dir.path()).unwrap();
        assert!(config.is_none());
    }

    #[test]
    fn test_load_config_missing_file() {
        let result = load_config_from_path(Path::new("/nonexistent/config.yml"));
        assert!(result.is_err());
        let err = format!("{}", result.unwrap_err());
        assert!(err.contains("Failed to read config file"));
    }

    #[test]
    fn test_load_config_parse_error() {
        let dir = TempDir::new().unwrap();
        let config_path = dir.path().join("bad.yml");
        fs::write(&config_path, "invalid: yaml: [[[broken").unwrap();

        let result = load_config_from_path(&config_path);
        assert!(result.is_err());
        let err = format!("{}", result.unwrap_err());
        assert!(err.contains("Failed to parse config file"));
    }

    #[test]
    fn test_empty_cve_id_validation_error() {
        let dir = TempDir::new().unwrap();
        let config_path = dir.path().join("config.yml");
        fs::write(
            &config_path,
            r#"
ignore_cves:
  - id: ""
    reason: "empty id"
"#,
        )
        .unwrap();

        let result = load_config_from_path(&config_path);
        assert!(result.is_err());
        let err = format!("{}", result.unwrap_err());
        assert!(err.contains("must not be empty"));
    }

    #[test]
    fn test_whitespace_only_cve_id_validation_error() {
        let dir = TempDir::new().unwrap();
        let config_path = dir.path().join("config.yml");
        fs::write(
            &config_path,
            r#"
ignore_cves:
  - id: "   "
    reason: "whitespace only"
"#,
        )
        .unwrap();

        let result = load_config_from_path(&config_path);
        assert!(result.is_err());
        let err = format!("{}", result.unwrap_err());
        assert!(err.contains("must not be empty"));
    }

    #[test]
    fn test_unknown_fields_warning() {
        let dir = TempDir::new().unwrap();
        let config_path = dir.path().join("config.yml");
        fs::write(
            &config_path,
            r#"
format: json
unknown_field: true
another_unknown: value
"#,
        )
        .unwrap();

        let config = load_config_from_path(&config_path).unwrap();
        assert_eq!(config.unknown_fields.len(), 2);
        assert!(config.unknown_fields.contains_key("unknown_field"));
        assert!(config.unknown_fields.contains_key("another_unknown"));
    }

    #[test]
    fn test_default_config() {
        let config = ConfigFile::default();
        assert!(config.format.is_none());
        assert!(config.exclude_packages.is_none());
        assert!(config.check_cve.is_none());
        assert!(config.severity_threshold.is_none());
        assert!(config.cvss_threshold.is_none());
        assert!(config.ignore_cves.is_none());
        assert!(config.unknown_fields.is_empty());
    }

    #[test]
    fn test_template_is_valid_yaml_when_uncommented() {
        // Remove comment markers from YAML config lines (skip header comments)
        let uncommented: String = CONFIG_TEMPLATE
            .lines()
            .filter_map(|line| {
                let trimmed = line.trim_start();
                if let Some(content) = trimmed.strip_prefix("# ") {
                    // Skip non-YAML header lines (no colon = not a key-value pair or list item)
                    if content.contains(':')
                        || content.starts_with("  - ")
                        || content.starts_with("- ")
                    {
                        Some(content.to_string())
                    } else {
                        None
                    }
                } else if trimmed == "#" {
                    None
                } else {
                    Some(line.to_string())
                }
            })
            .collect::<Vec<_>>()
            .join("\n");

        let result: std::result::Result<ConfigFile, _> = serde_yaml_ng::from_str(&uncommented);
        assert!(
            result.is_ok(),
            "Template should be valid YAML when uncommented: {:?}\nContent:\n{}",
            result.err(),
            uncommented
        );
    }

    #[test]
    fn test_generate_config_template_creates_file() {
        let dir = TempDir::new().unwrap();
        let result = generate_config_template(dir.path());
        assert!(result.is_ok());

        let created_path = result.unwrap();
        assert!(created_path.exists());

        let content = fs::read_to_string(&created_path).unwrap();
        assert!(content.contains("uv-sbom configuration file"));
        assert!(content.contains("format: json"));
        assert!(content.contains("exclude_packages:"));
        assert!(content.contains("check_cve:"));
        assert!(content.contains("ignore_cves:"));
    }

    #[test]
    fn test_generate_config_template_fails_if_exists() {
        let dir = TempDir::new().unwrap();
        let config_path = dir.path().join(CONFIG_FILENAME);
        fs::write(&config_path, "existing content").unwrap();

        let result = generate_config_template(dir.path());
        assert!(result.is_err());
        let err = format!("{}", result.unwrap_err());
        assert!(err.contains("already exists"));
    }
}