sbom-tools 0.1.19

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
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
//! Configuration validation for sbom-tools.
//!
//! Provides validation traits and implementations for all configuration types.

use super::types::{
    AppConfig, BehaviorConfig, DiffConfig, EnrichmentConfig, FilterConfig, MatchingConfig,
    MatrixConfig, MultiDiffConfig, OutputConfig, TimelineConfig, TuiConfig, ViewConfig,
};

// ============================================================================
// Configuration Error
// ============================================================================

/// Error type for configuration validation.
#[derive(Debug, Clone)]
pub struct ConfigError {
    /// The field that failed validation
    pub field: String,
    /// Description of the validation error
    pub message: String,
}

impl std::fmt::Display for ConfigError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}: {}", self.field, self.message)
    }
}

impl std::error::Error for ConfigError {}

// ============================================================================
// Validation Trait
// ============================================================================

/// Trait for validatable configuration types.
pub trait Validatable {
    /// Validate the configuration, returning any errors found.
    fn validate(&self) -> Vec<ConfigError>;

    /// Check if the configuration is valid.
    fn is_valid(&self) -> bool {
        self.validate().is_empty()
    }
}

// ============================================================================
// Validation Implementations
// ============================================================================

impl Validatable for AppConfig {
    fn validate(&self) -> Vec<ConfigError> {
        let mut errors = Vec::new();
        errors.extend(self.matching.validate());
        errors.extend(self.filtering.validate());
        errors.extend(self.output.validate());
        errors.extend(self.behavior.validate());
        errors.extend(self.tui.validate());

        if let Some(ref enrichment) = self.enrichment {
            errors.extend(enrichment.validate());
        }

        errors
    }
}

impl Validatable for MatchingConfig {
    fn validate(&self) -> Vec<ConfigError> {
        let mut errors = Vec::new();
        // fuzzy_preset: FuzzyPreset enum makes invalid values unrepresentable at parse time

        if let Some(threshold) = self.threshold
            && !(0.0..=1.0).contains(&threshold)
        {
            errors.push(ConfigError {
                field: "matching.threshold".to_string(),
                message: format!("Threshold must be between 0.0 and 1.0, got {threshold}"),
            });
        }

        errors
    }
}

impl Validatable for FilterConfig {
    fn validate(&self) -> Vec<ConfigError> {
        let mut errors = Vec::new();
        if let Some(ref severity) = self.min_severity {
            let valid_severities = ["critical", "high", "medium", "low", "info"];
            if !valid_severities.contains(&severity.to_lowercase().as_str()) {
                errors.push(ConfigError {
                    field: "filtering.min_severity".to_string(),
                    message: format!(
                        "Invalid severity '{}'. Valid options: {}",
                        severity,
                        valid_severities.join(", ")
                    ),
                });
            }
        }
        errors
    }
}

impl Validatable for OutputConfig {
    fn validate(&self) -> Vec<ConfigError> {
        let mut errors = Vec::new();

        // Validate output file path if specified
        if let Some(ref file_path) = self.file
            && let Some(parent) = file_path.parent()
            && !parent.as_os_str().is_empty()
            && !parent.exists()
        {
            errors.push(ConfigError {
                field: "output.file".to_string(),
                message: format!("Parent directory does not exist: {}", parent.display()),
            });
        }

        // Warn about contradictory streaming configuration
        if self.streaming.disabled && self.streaming.force {
            errors.push(ConfigError {
                field: "output.streaming".to_string(),
                message: "Contradictory streaming config: both 'disabled' and 'force' are true. \
                          'disabled' takes precedence."
                    .to_string(),
            });
        }

        errors
    }
}

impl Validatable for BehaviorConfig {
    fn validate(&self) -> Vec<ConfigError> {
        // BehaviorConfig contains only boolean flags that don't need validation
        Vec::new()
    }
}

impl Validatable for TuiConfig {
    fn validate(&self) -> Vec<ConfigError> {
        let mut errors = Vec::new();

        // theme: ThemeName enum makes invalid values unrepresentable at parse time

        if !(0.0..=1.0).contains(&self.initial_threshold) {
            errors.push(ConfigError {
                field: "tui.initial_threshold".to_string(),
                message: format!(
                    "Initial threshold must be between 0.0 and 1.0, got {}",
                    self.initial_threshold
                ),
            });
        }

        errors
    }
}

impl Validatable for EnrichmentConfig {
    fn validate(&self) -> Vec<ConfigError> {
        let mut errors = Vec::new();

        let valid_providers = ["osv", "nvd"];
        if !valid_providers.contains(&self.provider.as_str()) {
            errors.push(ConfigError {
                field: "enrichment.provider".to_string(),
                message: format!(
                    "Invalid provider '{}'. Valid options: {}",
                    self.provider,
                    valid_providers.join(", ")
                ),
            });
        }

        if self.max_concurrent == 0 {
            errors.push(ConfigError {
                field: "enrichment.max_concurrent".to_string(),
                message: "Max concurrent requests must be at least 1".to_string(),
            });
        }

        errors
    }
}

impl Validatable for DiffConfig {
    fn validate(&self) -> Vec<ConfigError> {
        let mut errors = Vec::new();

        // Validate paths exist
        if !self.paths.old.exists() {
            errors.push(ConfigError {
                field: "paths.old".to_string(),
                message: format!("File not found: {}", self.paths.old.display()),
            });
        }
        if !self.paths.new.exists() {
            errors.push(ConfigError {
                field: "paths.new".to_string(),
                message: format!("File not found: {}", self.paths.new.display()),
            });
        }

        // Validate nested configs
        errors.extend(self.matching.validate());
        errors.extend(self.filtering.validate());

        // Validate rules file if specified
        if let Some(ref rules_file) = self.rules.rules_file
            && !rules_file.exists()
        {
            errors.push(ConfigError {
                field: "rules.rules_file".to_string(),
                message: format!("Rules file not found: {}", rules_file.display()),
            });
        }

        // Validate ecosystem rules file if specified
        if let Some(ref config_file) = self.ecosystem_rules.config_file
            && !config_file.exists()
        {
            errors.push(ConfigError {
                field: "ecosystem_rules.config_file".to_string(),
                message: format!("Ecosystem rules file not found: {}", config_file.display()),
            });
        }

        errors
    }
}

impl Validatable for ViewConfig {
    fn validate(&self) -> Vec<ConfigError> {
        let mut errors = Vec::new();
        if !self.sbom_path.exists() {
            errors.push(ConfigError {
                field: "sbom_path".to_string(),
                message: format!("File not found: {}", self.sbom_path.display()),
            });
        }
        errors
    }
}

impl Validatable for MultiDiffConfig {
    fn validate(&self) -> Vec<ConfigError> {
        let mut errors = Vec::new();

        if !self.baseline.exists() {
            errors.push(ConfigError {
                field: "baseline".to_string(),
                message: format!("Baseline file not found: {}", self.baseline.display()),
            });
        }

        for (i, target) in self.targets.iter().enumerate() {
            if !target.exists() {
                errors.push(ConfigError {
                    field: format!("targets[{i}]"),
                    message: format!("Target file not found: {}", target.display()),
                });
            }
        }

        if self.targets.is_empty() {
            errors.push(ConfigError {
                field: "targets".to_string(),
                message: "At least one target SBOM is required".to_string(),
            });
        }

        errors.extend(self.matching.validate());
        errors
    }
}

impl Validatable for TimelineConfig {
    fn validate(&self) -> Vec<ConfigError> {
        let mut errors = Vec::new();

        for (i, path) in self.sbom_paths.iter().enumerate() {
            if !path.exists() {
                errors.push(ConfigError {
                    field: format!("sbom_paths[{i}]"),
                    message: format!("SBOM file not found: {}", path.display()),
                });
            }
        }

        if self.sbom_paths.len() < 2 {
            errors.push(ConfigError {
                field: "sbom_paths".to_string(),
                message: "Timeline analysis requires at least 2 SBOMs".to_string(),
            });
        }

        errors.extend(self.matching.validate());
        errors
    }
}

impl Validatable for MatrixConfig {
    fn validate(&self) -> Vec<ConfigError> {
        let mut errors = Vec::new();

        for (i, path) in self.sbom_paths.iter().enumerate() {
            if !path.exists() {
                errors.push(ConfigError {
                    field: format!("sbom_paths[{i}]"),
                    message: format!("SBOM file not found: {}", path.display()),
                });
            }
        }

        if self.sbom_paths.len() < 2 {
            errors.push(ConfigError {
                field: "sbom_paths".to_string(),
                message: "Matrix comparison requires at least 2 SBOMs".to_string(),
            });
        }

        if !(0.0..=1.0).contains(&self.cluster_threshold) {
            errors.push(ConfigError {
                field: "cluster_threshold".to_string(),
                message: format!(
                    "Cluster threshold must be between 0.0 and 1.0, got {}",
                    self.cluster_threshold
                ),
            });
        }

        errors.extend(self.matching.validate());
        errors
    }
}

// ============================================================================
// Tests
// ============================================================================

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

    #[test]
    fn test_matching_config_validation() {
        // FuzzyPreset enum makes invalid presets unrepresentable at compile time.
        // Valid config should pass.
        let config = MatchingConfig {
            fuzzy_preset: super::super::FuzzyPreset::Balanced,
            threshold: None,
            include_unchanged: false,
        };
        assert!(config.is_valid());
    }

    #[test]
    fn test_matching_config_threshold_validation() {
        let valid = MatchingConfig {
            fuzzy_preset: super::super::FuzzyPreset::Balanced,
            threshold: Some(0.85),
            include_unchanged: false,
        };
        assert!(valid.is_valid());

        let invalid = MatchingConfig {
            fuzzy_preset: super::super::FuzzyPreset::Balanced,
            threshold: Some(1.5),
            include_unchanged: false,
        };
        assert!(!invalid.is_valid());
    }

    #[test]
    fn test_filter_config_validation() {
        let config = FilterConfig {
            only_changes: true,
            min_severity: Some("high".to_string()),
            exclude_vex_resolved: false,
            fail_on_vex_gap: false,
        };
        assert!(config.is_valid());

        let invalid = FilterConfig {
            only_changes: true,
            min_severity: Some("invalid".to_string()),
            exclude_vex_resolved: false,
            fail_on_vex_gap: false,
        };
        assert!(!invalid.is_valid());
    }

    #[test]
    fn test_tui_config_validation() {
        let valid = TuiConfig::default();
        assert!(valid.is_valid());

        // Theme is now ThemeName enum — invalid values are unrepresentable.
        // Only threshold validation remains testable.
        let invalid = TuiConfig {
            initial_threshold: 2.0,
            ..TuiConfig::default()
        };
        assert!(!invalid.is_valid());
    }

    #[test]
    fn test_enrichment_config_validation() {
        let valid = EnrichmentConfig::default();
        assert!(valid.is_valid());

        let invalid = EnrichmentConfig {
            max_concurrent: 0,
            ..EnrichmentConfig::default()
        };
        assert!(!invalid.is_valid());
    }

    #[test]
    fn test_config_error_display() {
        let error = ConfigError {
            field: "test_field".to_string(),
            message: "test error message".to_string(),
        };
        assert_eq!(error.to_string(), "test_field: test error message");
    }

    #[test]
    fn test_app_config_validation() {
        let valid = AppConfig::default();
        assert!(valid.is_valid());

        // Enum fields make invalid presets unrepresentable.
        // Test with invalid threshold instead.
        let mut invalid = AppConfig::default();
        invalid.matching.threshold = Some(5.0);
        assert!(!invalid.is_valid());
    }
}