uv-sbom 2.2.0

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
use crate::config::IgnoreCve;
use crate::i18n::Locale;
use crate::sbom_generation::domain::license_policy::LicensePolicy;
use crate::sbom_generation::domain::vulnerability::Severity;
use crate::shared::error::SbomError;
use crate::shared::Result;
use std::path::PathBuf;

/// SbomRequest - Internal request DTO for SBOM generation use case
///
/// This DTO represents the internal request structure used within
/// the application layer. It may differ from the external API request.
#[derive(Debug, Clone)]
pub struct SbomRequest {
    /// Path to the project directory containing uv.lock
    pub project_path: PathBuf,
    /// Whether to include dependency graph information
    pub include_dependency_info: bool,
    /// Patterns for excluding packages from the SBOM
    pub exclude_patterns: Vec<String>,
    /// Whether to perform dry-run validation only (skip network operations and output generation)
    pub dry_run: bool,
    /// Whether to check for vulnerabilities using OSV API
    pub check_cve: bool,
    /// Severity threshold for vulnerability filtering
    pub severity_threshold: Option<Severity>,
    /// CVSS threshold for vulnerability filtering
    pub cvss_threshold: Option<f32>,
    /// CVE IDs to ignore during vulnerability checks
    pub ignore_cves: Vec<IgnoreCve>,
    /// Whether to check license compliance
    pub check_license: bool,
    /// License compliance policy (only used when check_license is true)
    pub license_policy: Option<LicensePolicy>,
    /// Whether to suggest direct dependency upgrade versions to fix transitive vulnerabilities.
    /// Only meaningful when `check_cve` is true.
    pub suggest_fix: bool,
    /// Output locale for human-readable formats
    pub locale: Locale,
}

impl SbomRequest {
    /// Creates a new SbomRequestBuilder for constructing SbomRequest instances.
    ///
    /// This is the recommended way to create SbomRequest instances.
    ///
    /// # Example
    ///
    /// ```
    /// use uv_sbom::application::dto::SbomRequest;
    ///
    /// let request = SbomRequest::builder()
    ///     .project_path(".")
    ///     .build()
    ///     .unwrap();
    /// ```
    pub fn builder() -> SbomRequestBuilder {
        SbomRequestBuilder::new()
    }
}

/// Builder for SbomRequest that enables stepwise construction of request objects.
///
/// This implements the Builder pattern for creating SbomRequest instances
/// with sensible defaults and a fluent API.
///
/// # Example
///
/// ```
/// use uv_sbom::application::dto::SbomRequest;
///
/// // Simple usage - only project_path is required
/// let request = SbomRequest::builder()
///     .project_path(".")
///     .build()
///     .unwrap();
///
/// // With options
/// let request = SbomRequest::builder()
///     .project_path("/path/to/project")
///     .include_dependency_info(true)
///     .check_cve(true)
///     .exclude_patterns(vec!["test-*".to_string()])
///     .build()
///     .unwrap();
/// ```
#[derive(Debug, Clone)]
pub struct SbomRequestBuilder {
    project_path: Option<PathBuf>,
    include_dependency_info: bool,
    exclude_patterns: Vec<String>,
    dry_run: bool,
    check_cve: bool,
    severity_threshold: Option<Severity>,
    cvss_threshold: Option<f32>,
    ignore_cves: Vec<IgnoreCve>,
    check_license: bool,
    license_policy: Option<LicensePolicy>,
    suggest_fix: bool,
    locale: Locale,
}

impl SbomRequestBuilder {
    /// Creates a new SbomRequestBuilder with default values.
    ///
    /// Default values:
    /// - project_path: None (required)
    /// - include_dependency_info: false
    /// - exclude_patterns: empty Vec
    /// - dry_run: false
    /// - check_cve: false
    /// - severity_threshold: None
    /// - cvss_threshold: None
    pub fn new() -> Self {
        Self {
            project_path: None,
            include_dependency_info: false,
            exclude_patterns: Vec::new(),
            dry_run: false,
            check_cve: false,
            severity_threshold: None,
            cvss_threshold: None,
            ignore_cves: Vec::new(),
            check_license: false,
            license_policy: None,
            suggest_fix: false,
            locale: Locale::default(),
        }
    }

    /// Sets the project path (required).
    ///
    /// This is the path to the project directory containing uv.lock.
    pub fn project_path(mut self, path: impl Into<PathBuf>) -> Self {
        self.project_path = Some(path.into());
        self
    }

    /// Sets whether to include dependency graph information.
    pub fn include_dependency_info(mut self, include: bool) -> Self {
        self.include_dependency_info = include;
        self
    }

    /// Sets the exclusion patterns for filtering packages.
    pub fn exclude_patterns(mut self, patterns: Vec<String>) -> Self {
        self.exclude_patterns = patterns;
        self
    }

    /// Sets whether to perform dry-run validation only.
    pub fn dry_run(mut self, dry_run: bool) -> Self {
        self.dry_run = dry_run;
        self
    }

    /// Sets whether to check for vulnerabilities.
    pub fn check_cve(mut self, check: bool) -> Self {
        self.check_cve = check;
        self
    }

    /// Sets the severity threshold from an Option value.
    ///
    /// This is useful when the threshold comes from CLI arguments
    /// which may or may not be specified.
    pub fn severity_threshold_opt(mut self, severity: Option<Severity>) -> Self {
        self.severity_threshold = severity;
        self
    }

    /// Sets the CVSS threshold from an Option value.
    ///
    /// This is useful when the threshold comes from CLI arguments
    /// which may or may not be specified.
    pub fn cvss_threshold_opt(mut self, cvss: Option<f32>) -> Self {
        self.cvss_threshold = cvss;
        self
    }

    /// Sets the CVE IDs to ignore during vulnerability checks.
    pub fn ignore_cves(mut self, cves: Vec<IgnoreCve>) -> Self {
        self.ignore_cves = cves;
        self
    }

    /// Sets whether to check license compliance.
    pub fn check_license(mut self, check: bool) -> Self {
        self.check_license = check;
        self
    }

    /// Sets the license compliance policy.
    pub fn license_policy(mut self, policy: Option<LicensePolicy>) -> Self {
        self.license_policy = policy;
        self
    }

    /// Sets whether to suggest upgrade paths for vulnerable transitive dependencies.
    pub fn suggest_fix(mut self, suggest: bool) -> Self {
        self.suggest_fix = suggest;
        self
    }

    /// Sets the output locale for human-readable formats.
    pub fn locale(mut self, locale: Locale) -> Self {
        self.locale = locale;
        self
    }

    /// Builds the SbomRequest, validating that all required fields are set.
    ///
    /// # Errors
    ///
    /// Returns an error if project_path is not set.
    pub fn build(self) -> Result<SbomRequest> {
        let project_path = self.project_path.ok_or_else(|| SbomError::Validation {
            message: "project_path is required".into(),
        })?;

        Ok(SbomRequest {
            project_path,
            include_dependency_info: self.include_dependency_info,
            exclude_patterns: self.exclude_patterns,
            dry_run: self.dry_run,
            check_cve: self.check_cve,
            severity_threshold: self.severity_threshold,
            cvss_threshold: self.cvss_threshold,
            ignore_cves: self.ignore_cves,
            check_license: self.check_license,
            license_policy: self.license_policy,
            suggest_fix: self.suggest_fix,
            locale: self.locale,
        })
    }
}

impl Default for SbomRequestBuilder {
    fn default() -> Self {
        Self::new()
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::config::IgnoreCve;

    #[test]
    fn test_builder_with_only_project_path() {
        let request = SbomRequest::builder()
            .project_path("/test/project")
            .build()
            .unwrap();

        assert_eq!(request.project_path, PathBuf::from("/test/project"));
        assert!(!request.include_dependency_info);
        assert!(request.exclude_patterns.is_empty());
        assert!(!request.dry_run);
        assert!(!request.check_cve);
        assert!(request.severity_threshold.is_none());
        assert!(request.cvss_threshold.is_none());
        assert!(request.ignore_cves.is_empty());
    }

    #[test]
    fn test_builder_without_project_path_fails() {
        let result = SbomRequest::builder().build();

        assert!(result.is_err());
        let err = result.unwrap_err();
        assert!(err.to_string().contains("project_path is required"));
    }

    #[test]
    fn test_builder_with_all_options() {
        let request = SbomRequest::builder()
            .project_path("/test/project")
            .include_dependency_info(true)
            .exclude_patterns(vec!["test-*".to_string()])
            .dry_run(true)
            .check_cve(true)
            .severity_threshold_opt(Some(Severity::High))
            .cvss_threshold_opt(Some(7.5))
            .ignore_cves(vec![IgnoreCve {
                id: "CVE-2024-1234".to_string(),
                reason: Some("test".to_string()),
            }])
            .build()
            .unwrap();

        assert_eq!(request.project_path, PathBuf::from("/test/project"));
        assert!(request.include_dependency_info);
        assert_eq!(request.exclude_patterns, vec!["test-*".to_string()]);
        assert!(request.dry_run);
        assert!(request.check_cve);
        assert_eq!(request.severity_threshold, Some(Severity::High));
        assert_eq!(request.cvss_threshold, Some(7.5));
        assert_eq!(request.ignore_cves.len(), 1);
        assert_eq!(request.ignore_cves[0].id, "CVE-2024-1234");
    }

    #[test]
    fn test_exclude_patterns_accumulates() {
        let request = SbomRequest::builder()
            .project_path("/test/project")
            .exclude_patterns(vec![
                "pattern1".to_string(),
                "pattern2".to_string(),
                "pattern3".to_string(),
            ])
            .build()
            .unwrap();

        assert_eq!(request.exclude_patterns.len(), 3);
        assert_eq!(
            request.exclude_patterns,
            vec!["pattern1", "pattern2", "pattern3"]
        );
    }

    #[test]
    fn test_exclude_patterns_replaces_previous() {
        let request = SbomRequest::builder()
            .project_path("/test/project")
            .exclude_patterns(vec!["old-pattern".to_string()])
            .exclude_patterns(vec!["new-pattern".to_string()])
            .build()
            .unwrap();

        assert_eq!(request.exclude_patterns, vec!["new-pattern".to_string()]);
    }

    #[test]
    fn test_severity_threshold_opt_with_some() {
        let request = SbomRequest::builder()
            .project_path("/test/project")
            .severity_threshold_opt(Some(Severity::Critical))
            .build()
            .unwrap();

        assert_eq!(request.severity_threshold, Some(Severity::Critical));
    }

    #[test]
    fn test_severity_threshold_opt_with_none() {
        let request = SbomRequest::builder()
            .project_path("/test/project")
            .severity_threshold_opt(None)
            .build()
            .unwrap();

        assert!(request.severity_threshold.is_none());
    }

    #[test]
    fn test_cvss_threshold_opt_with_some() {
        let request = SbomRequest::builder()
            .project_path("/test/project")
            .cvss_threshold_opt(Some(8.0))
            .build()
            .unwrap();

        assert_eq!(request.cvss_threshold, Some(8.0));
    }

    #[test]
    fn test_cvss_threshold_opt_with_none() {
        let request = SbomRequest::builder()
            .project_path("/test/project")
            .cvss_threshold_opt(None)
            .build()
            .unwrap();

        assert!(request.cvss_threshold.is_none());
    }

    #[test]
    fn test_builder_default_trait() {
        let builder = SbomRequestBuilder::default();
        let builder_new = SbomRequestBuilder::new();

        // Both should have same default state
        assert!(builder.project_path.is_none());
        assert!(builder_new.project_path.is_none());
        assert!(!builder.include_dependency_info);
        assert!(!builder_new.include_dependency_info);
    }

    #[test]
    fn test_project_path_accepts_string() {
        let request = SbomRequest::builder()
            .project_path("./relative/path")
            .build()
            .unwrap();

        assert_eq!(request.project_path, PathBuf::from("./relative/path"));
    }

    #[test]
    fn test_project_path_accepts_pathbuf() {
        let path = PathBuf::from("/absolute/path");
        let request = SbomRequest::builder()
            .project_path(path.clone())
            .build()
            .unwrap();

        assert_eq!(request.project_path, path);
    }
}