sarif_rust 0.3.0

A comprehensive Rust library for parsing, generating, and manipulating SARIF (Static Analysis Results Interchange Format) v2.1.0 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
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
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
//! SARIF schema evolution and version migration utilities
//!
//! This module provides functionality for handling different versions of SARIF schemas,
//! migrating between versions, and maintaining backward compatibility.

use crate::types::SarifLog;
use serde_json::{Map, Value};
use std::collections::HashMap;
use std::fmt;

/// Supported SARIF schema versions
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum SchemaVersion {
    /// SARIF 1.0.0
    V1_0_0,
    /// SARIF 2.0.0
    V2_0_0,
    /// SARIF 2.1.0 (current standard)
    V2_1_0,
}

impl fmt::Display for SchemaVersion {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            SchemaVersion::V1_0_0 => write!(f, "1.0.0"),
            SchemaVersion::V2_0_0 => write!(f, "2.0.0"),
            SchemaVersion::V2_1_0 => write!(f, "2.1.0"),
        }
    }
}

impl SchemaVersion {
    /// Parse a version string into a SchemaVersion
    pub fn from_string(version: &str) -> Result<Self, SchemaVersionError> {
        match version {
            "1.0.0" => Ok(SchemaVersion::V1_0_0),
            "2.0.0" => Ok(SchemaVersion::V2_0_0),
            "2.1.0" => Ok(SchemaVersion::V2_1_0),
            _ => Err(SchemaVersionError::UnsupportedVersion(version.to_string())),
        }
    }

    /// Get the schema URI for this version
    pub fn schema_uri(&self) -> String {
        match self {
            SchemaVersion::V1_0_0 => "https://raw.githubusercontent.com/oasis-tcs/sarif-spec/master/Schemata/sarif-schema-1.0.0.json".to_string(),
            SchemaVersion::V2_0_0 => "https://raw.githubusercontent.com/oasis-tcs/sarif-spec/master/Schemata/sarif-schema-2.0.0.json".to_string(),
            SchemaVersion::V2_1_0 => "https://raw.githubusercontent.com/oasis-tcs/sarif-spec/master/Schemata/sarif-schema-2.1.0.json".to_string(),
        }
    }

    /// Check if this version is compatible with another version
    pub fn is_compatible_with(&self, other: &SchemaVersion) -> bool {
        match (self, other) {
            // Same version is always compatible
            (a, b) if a == b => true,
            // 2.0.0 and 2.1.0 are largely compatible
            (SchemaVersion::V2_0_0, SchemaVersion::V2_1_0) => true,
            (SchemaVersion::V2_1_0, SchemaVersion::V2_0_0) => true,
            // 1.0.0 requires migration
            _ => false,
        }
    }
}

/// Errors that can occur during schema evolution operations
#[derive(Debug, thiserror::Error)]
pub enum SchemaVersionError {
    #[error("Unsupported SARIF version: {0}")]
    UnsupportedVersion(String),

    #[error("Migration failed: {0}")]
    MigrationFailed(String),

    #[error("Invalid schema format: {0}")]
    InvalidSchema(String),

    #[error("Version detection failed: {0}")]
    VersionDetectionFailed(String),
}

/// Configuration for schema evolution operations
#[derive(Debug, Clone)]
pub struct SchemaEvolutionConfig {
    /// Target version for migrations
    pub target_version: SchemaVersion,
    /// Whether to preserve unknown fields during migration
    pub preserve_unknown_fields: bool,
    /// Whether to apply strict validation after migration
    pub strict_validation: bool,
    /// Whether to include migration warnings in the result
    pub include_warnings: bool,
}

impl Default for SchemaEvolutionConfig {
    fn default() -> Self {
        Self {
            target_version: SchemaVersion::V2_1_0,
            preserve_unknown_fields: true,
            strict_validation: false,
            include_warnings: true,
        }
    }
}

/// Migration warning information
#[derive(Debug, Clone)]
pub struct MigrationWarning {
    /// Type of warning
    pub warning_type: MigrationWarningType,
    /// Descriptive message
    pub message: String,
    /// JSON path where the issue occurred
    pub path: String,
    /// Original value that was modified
    pub original_value: Option<Value>,
    /// New value after migration
    pub new_value: Option<Value>,
}

/// Types of migration warnings
#[derive(Debug, Clone)]
pub enum MigrationWarningType {
    /// Field was renamed
    FieldRenamed,
    /// Field was removed
    FieldRemoved,
    /// Field was added with default value
    FieldAdded,
    /// Value was transformed
    ValueTransformed,
    /// Unknown field was preserved
    UnknownFieldPreserved,
    /// Structure was restructured
    StructureChanged,
}

/// Result of a migration operation
#[derive(Debug)]
pub struct MigrationResult {
    /// The migrated SARIF log
    pub log: SarifLog,
    /// List of warnings encountered during migration
    pub warnings: Vec<MigrationWarning>,
    /// Source version detected
    pub source_version: SchemaVersion,
    /// Target version used
    pub target_version: SchemaVersion,
}

/// Schema evolution manager for SARIF files
pub struct SchemaEvolutionManager {
    config: SchemaEvolutionConfig,
    migrators: HashMap<(SchemaVersion, SchemaVersion), Box<dyn SchemaMigrator>>,
}

impl SchemaEvolutionManager {
    /// Create a new schema evolution manager
    pub fn new(config: SchemaEvolutionConfig) -> Self {
        let mut manager = Self {
            config,
            migrators: HashMap::new(),
        };

        // Register built-in migrators
        manager.register_migrators();
        manager
    }

    /// Create a manager with default configuration
    pub fn default() -> Self {
        Self::new(SchemaEvolutionConfig::default())
    }

    /// Detect the schema version of a SARIF log
    pub fn detect_version(&self, value: &Value) -> Result<SchemaVersion, SchemaVersionError> {
        // Check for explicit version field
        if let Some(obj) = value.as_object() {
            if let Some(version_val) = obj.get("version")
                && let Some(version_str) = version_val.as_str()
            {
                return SchemaVersion::from_string(version_str);
            }

            // Check schema URI
            if let Some(schema_val) = obj.get("$schema")
                && let Some(schema_str) = schema_val.as_str()
            {
                return self.detect_version_from_schema_uri(schema_str);
            }

            // Heuristic detection based on structure
            return self.detect_version_heuristic(obj);
        }

        Err(SchemaVersionError::VersionDetectionFailed(
            "Unable to determine SARIF version".to_string(),
        ))
    }

    /// Migrate a SARIF log to the target version
    pub fn migrate(&self, value: Value) -> Result<MigrationResult, SchemaVersionError> {
        let source_version = self.detect_version(&value)?;
        let target_version = self.config.target_version.clone();

        // No migration needed if versions are compatible
        if source_version.is_compatible_with(&target_version) && source_version == target_version {
            let log: SarifLog = serde_json::from_value(value)
                .map_err(|e| SchemaVersionError::InvalidSchema(e.to_string()))?;

            return Ok(MigrationResult {
                log,
                warnings: vec![],
                source_version,
                target_version,
            });
        }

        // Perform migration
        let migration_path = self.find_migration_path(&source_version, &target_version)?;
        let mut current_value = value;
        let mut all_warnings = Vec::new();

        for (from, to) in migration_path {
            if let Some(migrator) = self.migrators.get(&(from.clone(), to.clone())) {
                let result = migrator.migrate(current_value)?;
                current_value = result.migrated_value;
                all_warnings.extend(result.warnings);
            } else {
                return Err(SchemaVersionError::MigrationFailed(format!(
                    "No migrator found for {} -> {}",
                    from, to
                )));
            }
        }

        // Parse the final result
        let log: SarifLog = serde_json::from_value(current_value)
            .map_err(|e| SchemaVersionError::InvalidSchema(e.to_string()))?;

        Ok(MigrationResult {
            log,
            warnings: all_warnings,
            source_version,
            target_version,
        })
    }

    /// Register built-in migrators
    fn register_migrators(&mut self) {
        // V1.0.0 -> V2.0.0
        self.migrators.insert(
            (SchemaVersion::V1_0_0, SchemaVersion::V2_0_0),
            Box::new(V1ToV2Migrator::new()),
        );

        // V2.0.0 -> V2.1.0
        self.migrators.insert(
            (SchemaVersion::V2_0_0, SchemaVersion::V2_1_0),
            Box::new(V2ToV2_1Migrator::new()),
        );

        // Direct V1.0.0 -> V2.1.0 (combines both migrations)
        self.migrators.insert(
            (SchemaVersion::V1_0_0, SchemaVersion::V2_1_0),
            Box::new(V1ToV2_1Migrator::new()),
        );
    }

    /// Find the migration path between two versions
    fn find_migration_path(
        &self,
        from: &SchemaVersion,
        to: &SchemaVersion,
    ) -> Result<Vec<(SchemaVersion, SchemaVersion)>, SchemaVersionError> {
        if from == to {
            return Ok(vec![]);
        }

        // Direct migration available
        if self.migrators.contains_key(&(from.clone(), to.clone())) {
            return Ok(vec![(from.clone(), to.clone())]);
        }

        // Multi-step migration
        match (from, to) {
            (SchemaVersion::V1_0_0, SchemaVersion::V2_1_0) => Ok(vec![
                (SchemaVersion::V1_0_0, SchemaVersion::V2_0_0),
                (SchemaVersion::V2_0_0, SchemaVersion::V2_1_0),
            ]),
            _ => Err(SchemaVersionError::MigrationFailed(format!(
                "No migration path found from {} to {}",
                from, to
            ))),
        }
    }

    /// Detect version from schema URI
    fn detect_version_from_schema_uri(
        &self,
        schema_uri: &str,
    ) -> Result<SchemaVersion, SchemaVersionError> {
        if schema_uri.contains("1.0.0") {
            Ok(SchemaVersion::V1_0_0)
        } else if schema_uri.contains("2.0.0") {
            Ok(SchemaVersion::V2_0_0)
        } else if schema_uri.contains("2.1.0") {
            Ok(SchemaVersion::V2_1_0)
        } else {
            Err(SchemaVersionError::VersionDetectionFailed(format!(
                "Unknown schema URI: {}",
                schema_uri
            )))
        }
    }

    /// Detect version using heuristics
    fn detect_version_heuristic(
        &self,
        obj: &Map<String, Value>,
    ) -> Result<SchemaVersion, SchemaVersionError> {
        // Check for V2.1.0 specific fields
        if obj.contains_key("inlineExternalProperties") {
            return Ok(SchemaVersion::V2_1_0);
        }

        // Check for V2.0.0 vs V1.0.0 differences
        if let Some(runs) = obj.get("runs")
            && let Some(runs_array) = runs.as_array()
            && let Some(first_run) = runs_array.first()
            && let Some(run_obj) = first_run.as_object()
        {
            // V2.0.0+ has 'tool' instead of 'toolInfo'
            if run_obj.contains_key("tool") {
                return Ok(SchemaVersion::V2_0_0);
            } else if run_obj.contains_key("toolInfo") {
                return Ok(SchemaVersion::V1_0_0);
            }
        }

        // Default to V2.1.0 if we can't determine
        Ok(SchemaVersion::V2_1_0)
    }
}

/// Trait for schema migrators
trait SchemaMigrator: Send + Sync {
    fn migrate(&self, value: Value) -> Result<MigrationStepResult, SchemaVersionError>;
}

/// Result of a single migration step
struct MigrationStepResult {
    migrated_value: Value,
    warnings: Vec<MigrationWarning>,
}

/// Migrator from SARIF 1.0.0 to 2.0.0
struct V1ToV2Migrator;

impl V1ToV2Migrator {
    fn new() -> Self {
        Self
    }
}

impl SchemaMigrator for V1ToV2Migrator {
    fn migrate(&self, mut value: Value) -> Result<MigrationStepResult, SchemaVersionError> {
        let mut warnings = Vec::new();

        if let Some(obj) = value.as_object_mut() {
            // Update version
            obj.insert("version".to_string(), Value::String("2.0.0".to_string()));

            // Update schema URI
            obj.insert(
                "$schema".to_string(),
                Value::String(SchemaVersion::V2_0_0.schema_uri()),
            );

            // Migrate runs
            if let Some(runs) = obj.get_mut("runs")
                && let Some(runs_array) = runs.as_array_mut()
            {
                for run in runs_array {
                    self.migrate_run_v1_to_v2(run, &mut warnings)?;
                }
            }
        }

        Ok(MigrationStepResult {
            migrated_value: value,
            warnings,
        })
    }
}

impl V1ToV2Migrator {
    fn migrate_run_v1_to_v2(
        &self,
        run: &mut Value,
        warnings: &mut Vec<MigrationWarning>,
    ) -> Result<(), SchemaVersionError> {
        if let Some(run_obj) = run.as_object_mut() {
            // Rename 'toolInfo' to 'tool'
            if let Some(tool_info) = run_obj.remove("toolInfo") {
                run_obj.insert("tool".to_string(), tool_info);
                warnings.push(MigrationWarning {
                    warning_type: MigrationWarningType::FieldRenamed,
                    message: "Renamed 'toolInfo' to 'tool'".to_string(),
                    path: "runs[].toolInfo".to_string(),
                    original_value: None,
                    new_value: None,
                });
            }

            // Migrate results array structure changes
            if let Some(results) = run_obj.get_mut("results")
                && let Some(results_array) = results.as_array_mut()
            {
                for result in results_array {
                    self.migrate_result_v1_to_v2(result, warnings)?;
                }
            }
        }

        Ok(())
    }

    fn migrate_result_v1_to_v2(
        &self,
        result: &mut Value,
        warnings: &mut Vec<MigrationWarning>,
    ) -> Result<(), SchemaVersionError> {
        if let Some(result_obj) = result.as_object_mut() {
            // Migrate location structure
            if let Some(locations) = result_obj.get_mut("locations")
                && let Some(locations_array) = locations.as_array_mut()
            {
                for location in locations_array {
                    self.migrate_location_v1_to_v2(location, warnings)?;
                }
            }
        }

        Ok(())
    }

    fn migrate_location_v1_to_v2(
        &self,
        location: &mut Value,
        warnings: &mut Vec<MigrationWarning>,
    ) -> Result<(), SchemaVersionError> {
        if let Some(location_obj) = location.as_object_mut() {
            // V2.0.0 restructured physical location
            if let Some(result_file) = location_obj.remove("resultFile") {
                let mut physical_location = Map::new();
                physical_location.insert("artifactLocation".to_string(), result_file);

                // Move region information
                if let Some(region) = location_obj.remove("region") {
                    physical_location.insert("region".to_string(), region);
                }

                location_obj.insert(
                    "physicalLocation".to_string(),
                    Value::Object(physical_location),
                );

                warnings.push(MigrationWarning {
                    warning_type: MigrationWarningType::StructureChanged,
                    message: "Restructured location format for SARIF 2.0".to_string(),
                    path: "runs[].results[].locations[]".to_string(),
                    original_value: None,
                    new_value: None,
                });
            }
        }

        Ok(())
    }
}

/// Migrator from SARIF 2.0.0 to 2.1.0
struct V2ToV2_1Migrator;

impl V2ToV2_1Migrator {
    fn new() -> Self {
        Self
    }
}

impl SchemaMigrator for V2ToV2_1Migrator {
    fn migrate(&self, mut value: Value) -> Result<MigrationStepResult, SchemaVersionError> {
        let mut warnings = Vec::new();

        if let Some(obj) = value.as_object_mut() {
            // Update version
            obj.insert("version".to_string(), Value::String("2.1.0".to_string()));

            // Update schema URI
            obj.insert(
                "$schema".to_string(),
                Value::String(SchemaVersion::V2_1_0.schema_uri()),
            );

            // V2.1.0 is largely compatible with V2.0.0
            // Main changes are additions rather than breaking changes
            warnings.push(MigrationWarning {
                warning_type: MigrationWarningType::ValueTransformed,
                message: "Updated to SARIF 2.1.0 - new features available".to_string(),
                path: "version".to_string(),
                original_value: Some(Value::String("2.0.0".to_string())),
                new_value: Some(Value::String("2.1.0".to_string())),
            });
        }

        Ok(MigrationStepResult {
            migrated_value: value,
            warnings,
        })
    }
}

/// Direct migrator from SARIF 1.0.0 to 2.1.0
struct V1ToV2_1Migrator {
    v1_to_v2: V1ToV2Migrator,
    v2_to_v2_1: V2ToV2_1Migrator,
}

impl V1ToV2_1Migrator {
    fn new() -> Self {
        Self {
            v1_to_v2: V1ToV2Migrator::new(),
            v2_to_v2_1: V2ToV2_1Migrator::new(),
        }
    }
}

impl SchemaMigrator for V1ToV2_1Migrator {
    fn migrate(&self, value: Value) -> Result<MigrationStepResult, SchemaVersionError> {
        // First migrate V1 -> V2
        let v2_result = self.v1_to_v2.migrate(value)?;

        // Then migrate V2 -> V2.1
        let v2_1_result = self.v2_to_v2_1.migrate(v2_result.migrated_value)?;

        // Combine warnings
        let mut all_warnings = v2_result.warnings;
        all_warnings.extend(v2_1_result.warnings);

        Ok(MigrationStepResult {
            migrated_value: v2_1_result.migrated_value,
            warnings: all_warnings,
        })
    }
}

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

    #[test]
    fn test_version_detection() {
        let manager = SchemaEvolutionManager::default();

        // Test explicit version
        let v2_1_log = json!({
            "version": "2.1.0",
            "$schema": "https://raw.githubusercontent.com/oasis-tcs/sarif-spec/master/Schemata/sarif-schema-2.1.0.json",
            "runs": []
        });

        assert_eq!(
            manager.detect_version(&v2_1_log).unwrap(),
            SchemaVersion::V2_1_0
        );

        // Test schema URI detection
        let v2_0_log = json!({
            "$schema": "https://raw.githubusercontent.com/oasis-tcs/sarif-spec/master/Schemata/sarif-schema-2.0.0.json",
            "runs": []
        });

        assert_eq!(
            manager.detect_version(&v2_0_log).unwrap(),
            SchemaVersion::V2_0_0
        );
    }

    #[test]
    fn test_v2_0_to_v2_1_migration() {
        let manager = SchemaEvolutionManager::new(SchemaEvolutionConfig {
            target_version: SchemaVersion::V2_1_0,
            ..Default::default()
        });

        let v2_0_log = json!({
            "version": "2.0.0",
            "$schema": "https://raw.githubusercontent.com/oasis-tcs/sarif-spec/master/Schemata/sarif-schema-2.0.0.json",
            "runs": []
        });

        let result = manager.migrate(v2_0_log).unwrap();
        assert_eq!(result.source_version, SchemaVersion::V2_0_0);
        assert_eq!(result.target_version, SchemaVersion::V2_1_0);
        assert!(!result.warnings.is_empty());
    }

    #[test]
    fn test_schema_version_from_string() {
        assert_eq!(
            SchemaVersion::from_string("2.1.0").unwrap(),
            SchemaVersion::V2_1_0
        );
        assert_eq!(
            SchemaVersion::from_string("2.0.0").unwrap(),
            SchemaVersion::V2_0_0
        );
        assert_eq!(
            SchemaVersion::from_string("1.0.0").unwrap(),
            SchemaVersion::V1_0_0
        );

        assert!(SchemaVersion::from_string("3.0.0").is_err());
    }

    #[test]
    fn test_version_compatibility() {
        assert!(SchemaVersion::V2_1_0.is_compatible_with(&SchemaVersion::V2_1_0));
        assert!(SchemaVersion::V2_0_0.is_compatible_with(&SchemaVersion::V2_1_0));
        assert!(SchemaVersion::V2_1_0.is_compatible_with(&SchemaVersion::V2_0_0));
        assert!(!SchemaVersion::V1_0_0.is_compatible_with(&SchemaVersion::V2_0_0));
    }
}