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
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
//! SARIF conversion utilities for different output formats
//!
//! This module provides utilities to convert SARIF data to various formats
//! including CSV, HTML reports, GitHub Security Advisory format, and more.

use crate::parser::SarifResult as ParseResult;
use crate::types::{Level, Result as SarifResult, Run, SarifLog};
use std::collections::HashMap;
use std::io::Write;

/// Type alias for location information tuple (file, line, column, start_line, start_column, end_line, end_column)
type LocationInfo = (String, Option<i32>, Option<i32>, Option<i32>, Option<i32>, Option<i32>, Option<i32>);

/// Configuration for SARIF conversion operations
#[derive(Debug, Clone)]
pub struct ConversionConfig {
    /// Include full file paths or relative paths
    pub include_full_paths: bool,

    /// Maximum length for truncated messages
    pub max_message_length: Option<usize>,

    /// Filter results by minimum severity level
    pub min_level: Option<Level>,

    /// Include code snippets in output
    pub include_snippets: bool,

    /// Custom field mappings for output formats
    pub field_mappings: HashMap<String, String>,
}

impl Default for ConversionConfig {
    fn default() -> Self {
        Self {
            include_full_paths: false,
            max_message_length: Some(500),
            min_level: None,
            include_snippets: false,
            field_mappings: HashMap::new(),
        }
    }
}

/// CSV conversion utilities
pub struct CsvConverter {
    config: ConversionConfig,
}

impl CsvConverter {
    /// Create a new CSV converter with default configuration
    pub fn new() -> Self {
        Self {
            config: ConversionConfig::default(),
        }
    }

    /// Create a CSV converter with custom configuration
    pub fn with_config(config: ConversionConfig) -> Self {
        Self { config }
    }

    /// Convert SARIF log to CSV format
    pub fn convert_to_csv(&self, sarif: &SarifLog) -> ParseResult<String> {
        let mut output = String::new();

        // CSV header
        output.push_str("Tool,Rule ID,Level,Kind,Message,File,Line,Column,Start Line,Start Column,End Line,End Column\n");

        for run in &sarif.runs {
            let tool_name = &run.tool.driver.name;

            if let Some(results) = &run.results {
                for result in results {
                    if self.should_include_result(result) {
                        output.push_str(&self.result_to_csv_row(tool_name, result));
                        output.push('\n');
                    }
                }
            }
        }

        Ok(output)
    }

    /// Convert a single result to CSV row
    fn result_to_csv_row(&self, tool_name: &str, result: &SarifResult) -> String {
        let rule_id = result.rule_id.as_deref().unwrap_or("N/A");
        let level = result
            .level
            .as_ref()
            .map(|l| format!("{:?}", l))
            .unwrap_or_else(|| "Info".to_string());
        let kind = result
            .kind
            .as_ref()
            .map(|k| format!("{:?}", k))
            .unwrap_or_else(|| "Informational".to_string());
        let message = self.format_message(result.message.text.as_deref().unwrap_or("No message"));

        let (file, line, column, start_line, start_column, end_line, end_column) =
            self.extract_location_info(result);

        format!(
            "{},{},{},{},{},{},{},{},{},{},{},{}",
            self.escape_csv_field(tool_name),
            self.escape_csv_field(rule_id),
            self.escape_csv_field(&level),
            self.escape_csv_field(&kind),
            self.escape_csv_field(&message),
            self.escape_csv_field(&file),
            line.unwrap_or(0),
            column.unwrap_or(0),
            start_line.unwrap_or(0),
            start_column.unwrap_or(0),
            end_line.unwrap_or(0),
            end_column.unwrap_or(0)
        )
    }

    /// Extract location information from a result
    fn extract_location_info(&self, result: &SarifResult) -> LocationInfo {
        if let Some(locations) = &result.locations
            && let Some(location) = locations.first()
            && let Some(physical_location) = &location.physical_location
        {
            let file = if let Some(artifact_location) = &physical_location.artifact_location {
                artifact_location
                    .uri
                    .as_deref()
                    .unwrap_or("Unknown")
                    .to_string()
            } else {
                "Unknown".to_string()
            };

            if let Some(region) = &physical_location.region {
                return (
                    file,
                    region.start_line,
                    region.start_column,
                    region.start_line,
                    region.start_column,
                    region.end_line,
                    region.end_column,
                );
            }

            return (file, None, None, None, None, None, None);
        }

        ("Unknown".to_string(), None, None, None, None, None, None)
    }

    /// Format message according to configuration
    fn format_message(&self, message: &str) -> String {
        if let Some(max_len) = self.config.max_message_length {
            if message.len() > max_len {
                format!("{}...", &message[..max_len])
            } else {
                message.to_string()
            }
        } else {
            message.to_string()
        }
    }

    /// Escape CSV field
    fn escape_csv_field(&self, field: &str) -> String {
        if field.contains(',') || field.contains('"') || field.contains('\n') {
            format!("\"{}\"", field.replace('"', "\"\""))
        } else {
            field.to_string()
        }
    }

    /// Check if result should be included based on configuration
    fn should_include_result(&self, result: &SarifResult) -> bool {
        if let Some(min_level) = &self.config.min_level {
            if let Some(result_level) = &result.level {
                // Simple level comparison (Error > Warning > Note > None)
                match (min_level, result_level) {
                    (Level::Error, Level::Error) => true,
                    (Level::Error, _) => false,
                    (Level::Warning, Level::Error | Level::Warning) => true,
                    (Level::Warning, _) => false,
                    (Level::Note, Level::Error | Level::Warning | Level::Note) => true,
                    (Level::Note, _) => false,
                    (Level::None, _) => true,
                }
            } else {
                // Include results without level if min_level is None
                matches!(min_level, Level::None)
            }
        } else {
            true
        }
    }
}

/// HTML report converter
pub struct HtmlConverter {
    config: ConversionConfig,
}

impl HtmlConverter {
    /// Create a new HTML converter
    pub fn new() -> Self {
        Self {
            config: ConversionConfig::default(),
        }
    }

    /// Create an HTML converter with custom configuration
    pub fn with_config(config: ConversionConfig) -> Self {
        Self { config }
    }

    /// Convert SARIF log to HTML report
    pub fn convert_to_html(&self, sarif: &SarifLog) -> ParseResult<String> {
        let mut html = String::new();

        html.push_str(&self.html_header());
        html.push_str(&self.html_summary(sarif));

        for (run_index, run) in sarif.runs.iter().enumerate() {
            html.push_str(&self.convert_run_to_html(run, run_index));
        }

        html.push_str(&self.html_footer());

        Ok(html)
    }

    /// Generate HTML header with CSS
    fn html_header(&self) -> String {
        r#"<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>SARIF Security Report</title>
    <style>
        body { font-family: Arial, sans-serif; margin: 20px; background-color: #f5f5f5; }
        .container { max-width: 1200px; margin: 0 auto; background-color: white; padding: 20px; border-radius: 8px; box-shadow: 0 2px 4px rgba(0,0,0,0.1); }
        h1, h2, h3 { color: #333; }
        .summary { background-color: #f8f9fa; padding: 15px; border-radius: 5px; margin-bottom: 20px; }
        .run { margin-bottom: 30px; border: 1px solid #ddd; border-radius: 5px; }
        .run-header { background-color: #e9ecef; padding: 10px; border-radius: 5px 5px 0 0; }
        .result { margin: 10px; padding: 15px; border-left: 4px solid #ddd; background-color: #fafafa; }
        .result.error { border-left-color: #dc3545; }
        .result.warning { border-left-color: #ffc107; }
        .result.note { border-left-color: #17a2b8; }
        .result.info { border-left-color: #6c757d; }
        .location { font-family: monospace; background-color: #f1f3f4; padding: 5px; border-radius: 3px; }
        .message { margin: 10px 0; }
        .metadata { font-size: 0.9em; color: #666; }
        .badge { display: inline-block; padding: 2px 8px; border-radius: 3px; font-size: 0.8em; font-weight: bold; }
        .badge.error { background-color: #dc3545; color: white; }
        .badge.warning { background-color: #ffc107; color: black; }
        .badge.note { background-color: #17a2b8; color: white; }
        .badge.info { background-color: #6c757d; color: white; }
    </style>
</head>
<body>
<div class="container">
<h1>SARIF Security Analysis Report</h1>
"#.to_string()
    }

    /// Generate HTML summary section
    fn html_summary(&self, sarif: &SarifLog) -> String {
        let total_runs = sarif.runs.len();
        let mut total_results = 0;
        let mut level_counts = HashMap::new();

        for run in &sarif.runs {
            if let Some(results) = &run.results {
                total_results += results.len();
                for result in results {
                    let level = result
                        .level
                        .as_ref()
                        .map(|l| format!("{:?}", l))
                        .unwrap_or_else(|| "Info".to_string());
                    *level_counts.entry(level).or_insert(0) += 1;
                }
            }
        }

        format!(
            r#"<div class="summary">
    <h2>Summary</h2>
    <p><strong>Total Runs:</strong> {}</p>
    <p><strong>Total Results:</strong> {}</p>
    <p><strong>Breakdown by Level:</strong></p>
    <ul>
        <li>Errors: {}</li>
        <li>Warnings: {}</li>
        <li>Notes: {}</li>
        <li>Info: {}</li>
    </ul>
</div>
"#,
            total_runs,
            total_results,
            level_counts.get("Error").unwrap_or(&0),
            level_counts.get("Warning").unwrap_or(&0),
            level_counts.get("Note").unwrap_or(&0),
            level_counts.get("Info").unwrap_or(&0)
        )
    }

    /// Convert a single run to HTML
    fn convert_run_to_html(&self, run: &Run, run_index: usize) -> String {
        let mut html = String::new();

        html.push_str(&format!(
            r#"<div class="run">
    <div class="run-header">
        <h2>Run {}: {}</h2>
        <div class="metadata">Version: {}</div>
    </div>
"#,
            run_index + 1,
            run.tool.driver.name,
            run.tool.driver.version.as_deref().unwrap_or("Unknown")
        ));

        if let Some(results) = &run.results {
            for result in results {
                if self.should_include_result(result) {
                    html.push_str(&self.convert_result_to_html(result));
                }
            }
        }

        html.push_str("</div>\n");
        html
    }

    /// Convert a single result to HTML
    fn convert_result_to_html(&self, result: &SarifResult) -> String {
        let level = result
            .level
            .as_ref()
            .map(|l| format!("{:?}", l))
            .unwrap_or_else(|| "Info".to_string());
        let level_class = level.to_lowercase();
        let rule_id = result.rule_id.as_deref().unwrap_or("No Rule ID");
        let message = result.message.text.as_deref().unwrap_or("No message");

        let location_html = if let Some(locations) = &result.locations {
            if let Some(location) = locations.first() {
                if let Some(physical_location) = &location.physical_location {
                    let file = if let Some(artifact_location) = &physical_location.artifact_location
                    {
                        artifact_location.uri.as_deref().unwrap_or("Unknown")
                    } else {
                        "Unknown"
                    };

                    if let Some(region) = &physical_location.region {
                        format!(
                            r#"<div class="location">{}:{}:{}</div>"#,
                            file,
                            region.start_line.unwrap_or(0),
                            region.start_column.unwrap_or(0)
                        )
                    } else {
                        format!(r#"<div class="location">{}</div>"#, file)
                    }
                } else {
                    "".to_string()
                }
            } else {
                "".to_string()
            }
        } else {
            "".to_string()
        };

        format!(
            r#"    <div class="result {}">
        <div class="metadata">
            <span class="badge {}">{}</span>
            <strong>Rule:</strong> {}
        </div>
        <div class="message">{}</div>
        {}
    </div>
"#,
            level_class,
            level_class,
            level,
            self.escape_html(rule_id),
            self.escape_html(message),
            location_html
        )
    }

    /// Escape HTML characters
    fn escape_html(&self, text: &str) -> String {
        text.replace('&', "&amp;")
            .replace('<', "&lt;")
            .replace('>', "&gt;")
            .replace('"', "&quot;")
            .replace('\'', "&#x27;")
    }

    /// Generate HTML footer
    fn html_footer(&self) -> String {
        r#"</div>
</body>
</html>
"#
        .to_string()
    }

    /// Check if result should be included (reuse from CSV converter)
    fn should_include_result(&self, result: &SarifResult) -> bool {
        if let Some(min_level) = &self.config.min_level {
            if let Some(result_level) = &result.level {
                match (min_level, result_level) {
                    (Level::Error, Level::Error) => true,
                    (Level::Error, _) => false,
                    (Level::Warning, Level::Error | Level::Warning) => true,
                    (Level::Warning, _) => false,
                    (Level::Note, Level::Error | Level::Warning | Level::Note) => true,
                    (Level::Note, _) => false,
                    (Level::None, _) => true,
                }
            } else {
                matches!(min_level, Level::None)
            }
        } else {
            true
        }
    }
}

/// JSON Lines converter for streaming/big data processing
pub struct JsonLinesConverter {
    config: ConversionConfig,
}

impl JsonLinesConverter {
    /// Create a new JSON Lines converter
    pub fn new() -> Self {
        Self {
            config: ConversionConfig::default(),
        }
    }

    /// Create a JSON Lines converter with custom configuration
    pub fn with_config(config: ConversionConfig) -> Self {
        Self { config }
    }

    /// Convert SARIF log to JSON Lines format (one JSON object per line)
    pub fn convert_to_jsonl(&self, sarif: &SarifLog) -> ParseResult<String> {
        let mut output = String::new();

        for run in &sarif.runs {
            if let Some(results) = &run.results {
                for result in results {
                    if self.should_include_result(result) {
                        let json_line = self.result_to_json_line(&run.tool.driver.name, result)?;
                        output.push_str(&json_line);
                        output.push('\n');
                    }
                }
            }
        }

        Ok(output)
    }

    /// Convert a single result to JSON line
    fn result_to_json_line(&self, tool_name: &str, result: &SarifResult) -> ParseResult<String> {
        let mut json_obj = serde_json::Map::new();

        json_obj.insert(
            "tool".to_string(),
            serde_json::Value::String(tool_name.to_string()),
        );
        json_obj.insert(
            "ruleId".to_string(),
            serde_json::Value::String(result.rule_id.as_deref().unwrap_or("N/A").to_string()),
        );
        json_obj.insert(
            "level".to_string(),
            serde_json::Value::String(
                result
                    .level
                    .as_ref()
                    .map(|l| format!("{:?}", l))
                    .unwrap_or_else(|| "Info".to_string()),
            ),
        );
        json_obj.insert(
            "message".to_string(),
            serde_json::Value::String(
                result
                    .message
                    .text
                    .as_deref()
                    .unwrap_or("No message")
                    .to_string(),
            ),
        );

        if let Some(locations) = &result.locations
            && let Some(location) = locations.first()
            && let Some(physical_location) = &location.physical_location
        {
            if let Some(artifact_location) = &physical_location.artifact_location
                && let Some(uri) = &artifact_location.uri
            {
                json_obj.insert("file".to_string(), serde_json::Value::String(uri.clone()));
            }

            if let Some(region) = &physical_location.region {
                if let Some(line) = region.start_line {
                    json_obj.insert(
                        "line".to_string(),
                        serde_json::Value::Number(serde_json::Number::from(line)),
                    );
                }
                if let Some(column) = region.start_column {
                    json_obj.insert(
                        "column".to_string(),
                        serde_json::Value::Number(serde_json::Number::from(column)),
                    );
                }
            }
        }

        if let Some(guid) = &result.guid {
            json_obj.insert("guid".to_string(), serde_json::Value::String(guid.clone()));
        }

        let json_value = serde_json::Value::Object(json_obj);
        Ok(serde_json::to_string(&json_value)?)
    }

    /// Check if result should be included
    fn should_include_result(&self, result: &SarifResult) -> bool {
        if let Some(min_level) = &self.config.min_level {
            if let Some(result_level) = &result.level {
                match (min_level, result_level) {
                    (Level::Error, Level::Error) => true,
                    (Level::Error, _) => false,
                    (Level::Warning, Level::Error | Level::Warning) => true,
                    (Level::Warning, _) => false,
                    (Level::Note, Level::Error | Level::Warning | Level::Note) => true,
                    (Level::Note, _) => false,
                    (Level::None, _) => true,
                }
            } else {
                matches!(min_level, Level::None)
            }
        } else {
            true
        }
    }
}

/// GitHub Security Advisory format converter
pub struct GitHubSecurityConverter {
    config: ConversionConfig,
}

impl GitHubSecurityConverter {
    /// Create a new GitHub Security converter
    pub fn new() -> Self {
        Self {
            config: ConversionConfig::default(),
        }
    }

    /// Create a GitHub Security converter with custom configuration
    pub fn with_config(config: ConversionConfig) -> Self {
        Self { config }
    }

    /// Convert SARIF to GitHub Security Advisory format
    pub fn convert_to_github_format(&self, sarif: &SarifLog) -> ParseResult<String> {
        let mut advisories = Vec::new();

        for run in &sarif.runs {
            if let Some(results) = &run.results {
                for result in results {
                    if self.should_include_result(result) && self.is_security_relevant(result) {
                        advisories
                            .push(self.result_to_github_advisory(&run.tool.driver.name, result));
                    }
                }
            }
        }

        Ok(serde_json::to_string_pretty(&advisories)?)
    }

    /// Convert result to GitHub advisory format
    fn result_to_github_advisory(
        &self,
        tool_name: &str,
        result: &SarifResult,
    ) -> serde_json::Value {
        let mut advisory = serde_json::Map::new();

        advisory.insert(
            "id".to_string(),
            serde_json::Value::String(
                result
                    .guid
                    .as_deref()
                    .unwrap_or(&format!(
                        "{}_{}",
                        tool_name,
                        result.rule_id.as_deref().unwrap_or("unknown")
                    ))
                    .to_string(),
            ),
        );

        advisory.insert(
            "summary".to_string(),
            serde_json::Value::String(
                result
                    .message
                    .text
                    .as_deref()
                    .unwrap_or("Security issue detected")
                    .to_string(),
            ),
        );

        advisory.insert(
            "severity".to_string(),
            serde_json::Value::String(self.map_level_to_github_severity(result.level.as_ref())),
        );

        if let Some(rule_id) = &result.rule_id {
            advisory.insert(
                "cwe".to_string(),
                serde_json::Value::String(rule_id.clone()),
            );
        }

        if let Some(locations) = &result.locations {
            let mut affected_files = Vec::new();
            for location in locations {
                if let Some(physical_location) = &location.physical_location
                    && let Some(artifact_location) = &physical_location.artifact_location
                    && let Some(uri) = &artifact_location.uri
                {
                    affected_files.push(serde_json::Value::String(uri.clone()));
                }
            }
            if !affected_files.is_empty() {
                advisory.insert(
                    "affected_files".to_string(),
                    serde_json::Value::Array(affected_files),
                );
            }
        }

        serde_json::Value::Object(advisory)
    }

    /// Map SARIF level to GitHub severity
    fn map_level_to_github_severity(&self, level: Option<&Level>) -> String {
        match level {
            Some(Level::Error) => "high".to_string(),
            Some(Level::Warning) => "medium".to_string(),
            Some(Level::Note) => "low".to_string(),
            Some(Level::None) | None => "info".to_string(),
        }
    }

    /// Check if result is security-relevant
    fn is_security_relevant(&self, result: &SarifResult) -> bool {
        // Basic heuristics for security relevance
        if let Some(rule_id) = &result.rule_id {
            let security_patterns = [
                "security",
                "vulnerability",
                "injection",
                "xss",
                "csrf",
                "auth",
                "crypto",
                "sql",
                "nosql",
                "ldap",
                "xpath",
                "command",
                "path",
                "cwe-",
                "cve-",
                "owasp",
            ];

            let rule_lower = rule_id.to_lowercase();
            return security_patterns
                .iter()
                .any(|pattern| rule_lower.contains(pattern));
        }

        if let Some(message) = &result.message.text {
            let message_lower = message.to_lowercase();
            let security_keywords = [
                "security",
                "vulnerability",
                "exploit",
                "attack",
                "malicious",
                "injection",
                "xss",
                "csrf",
                "authentication",
                "authorization",
            ];
            return security_keywords
                .iter()
                .any(|keyword| message_lower.contains(keyword));
        }

        false
    }

    /// Check if result should be included
    fn should_include_result(&self, result: &SarifResult) -> bool {
        if let Some(min_level) = &self.config.min_level {
            if let Some(result_level) = &result.level {
                match (min_level, result_level) {
                    (Level::Error, Level::Error) => true,
                    (Level::Error, _) => false,
                    (Level::Warning, Level::Error | Level::Warning) => true,
                    (Level::Warning, _) => false,
                    (Level::Note, Level::Error | Level::Warning | Level::Note) => true,
                    (Level::Note, _) => false,
                    (Level::None, _) => true,
                }
            } else {
                matches!(min_level, Level::None)
            }
        } else {
            true
        }
    }
}

/// Generic converter that can output to multiple formats
pub struct SarifConverter {
    config: ConversionConfig,
}

impl SarifConverter {
    /// Create a new SARIF converter
    pub fn new() -> Self {
        Self {
            config: ConversionConfig::default(),
        }
    }

    /// Create a SARIF converter with custom configuration
    pub fn with_config(config: ConversionConfig) -> Self {
        Self { config }
    }

    /// Convert to CSV format
    pub fn to_csv(&self, sarif: &SarifLog) -> ParseResult<String> {
        CsvConverter::with_config(self.config.clone()).convert_to_csv(sarif)
    }

    /// Convert to HTML format
    pub fn to_html(&self, sarif: &SarifLog) -> ParseResult<String> {
        HtmlConverter::with_config(self.config.clone()).convert_to_html(sarif)
    }

    /// Convert to JSON Lines format
    pub fn to_jsonl(&self, sarif: &SarifLog) -> ParseResult<String> {
        JsonLinesConverter::with_config(self.config.clone()).convert_to_jsonl(sarif)
    }

    /// Convert to GitHub Security format
    pub fn to_github_security(&self, sarif: &SarifLog) -> ParseResult<String> {
        GitHubSecurityConverter::with_config(self.config.clone()).convert_to_github_format(sarif)
    }

    /// Write conversion output to file
    pub fn write_to_file<W: Write>(&self, output: &str, mut writer: W) -> ParseResult<()> {
        writer.write_all(output.as_bytes())?;
        writer.flush()?;
        Ok(())
    }
}

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

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

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

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

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

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

    #[test]
    fn test_csv_conversion() {
        let sarif = SarifLogBuilder::error_finding(
            "test-tool",
            "TEST001",
            "Test error message",
            "test.rs",
            10,
            5,
            10,
            15,
        )
        .build_unchecked();

        let converter = CsvConverter::new();
        let csv = converter.convert_to_csv(&sarif).unwrap();

        assert!(csv.contains("Tool,Rule ID,Level"));
        assert!(csv.contains("test-tool"));
        assert!(csv.contains("TEST001"));
        assert!(csv.contains("Error"));
        assert!(csv.contains("test.rs"));
    }

    #[test]
    fn test_html_conversion() {
        let sarif = SarifLogBuilder::warning_finding(
            "eslint",
            "no-unused-vars",
            "Variable 'x' is assigned but never used",
            "src/app.js",
            15,
            5,
            15,
            6,
        )
        .build_unchecked();

        let converter = HtmlConverter::new();
        let html = converter.convert_to_html(&sarif).unwrap();

        assert!(html.contains("<!DOCTYPE html>"));
        assert!(html.contains("SARIF Security Analysis Report"));
        assert!(html.contains("eslint"));
        assert!(html.contains("no-unused-vars"));
        assert!(html.contains("Warning"));
    }

    #[test]
    fn test_jsonl_conversion() {
        let sarif =
            SarifLogBuilder::single_error("clippy", "Unused variable detected", "main.rs", 42)
                .build_unchecked();

        let converter = JsonLinesConverter::new();
        let jsonl = converter.convert_to_jsonl(&sarif).unwrap();

        assert!(jsonl.contains("\"tool\":\"clippy\""));
        assert!(jsonl.contains("\"level\":\"Error\""));
        assert!(jsonl.contains("\"file\":\"main.rs\""));
    }

    #[test]
    fn test_github_security_conversion() {
        let sarif = SarifLogBuilder::error_finding(
            "security-scanner",
            "sql-injection",
            "Potential SQL injection vulnerability detected",
            "app.py",
            25,
            10,
            25,
            30,
        )
        .build_unchecked();

        let converter = GitHubSecurityConverter::new();
        let github_format = converter.convert_to_github_format(&sarif).unwrap();

        assert!(github_format.contains("\"severity\": \"high\""));
        assert!(github_format.contains("sql-injection"));
    }

    #[test]
    fn test_conversion_with_filters() {
        let sarif = SarifLogBuilder::new()
            .add_run_with(|run_builder| {
                run_builder
                    .add_result_with(|_result_builder| {
                        crate::builder::ResultBuilder::with_text_message("Error message")
                            .with_level(crate::types::Level::Error)
                    })
                    .add_result_with(|_result_builder| {
                        crate::builder::ResultBuilder::with_text_message("Warning message")
                            .with_level(crate::types::Level::Warning)
                    })
                    .add_result_with(|_result_builder| {
                        crate::builder::ResultBuilder::with_text_message("Note message")
                            .with_level(crate::types::Level::Note)
                    })
            })
            .build_unchecked();

        let config = ConversionConfig {
            min_level: Some(Level::Warning),
            ..Default::default()
        };

        let converter = CsvConverter::with_config(config);
        let csv = converter.convert_to_csv(&sarif).unwrap();

        // Should include Error and Warning but not Note
        assert!(csv.contains("Error"));
        assert!(csv.contains("Warning"));
        assert!(!csv.contains("Note"));
    }

    #[test]
    fn test_generic_converter() {
        let sarif = SarifLogBuilder::single_warning("test-tool", "Test warning", "file.rs", 1)
            .build_unchecked();

        let converter = SarifConverter::new();

        let csv = converter.to_csv(&sarif).unwrap();
        assert!(csv.contains("Warning"));

        let html = converter.to_html(&sarif).unwrap();
        assert!(html.contains("<!DOCTYPE html>"));

        let jsonl = converter.to_jsonl(&sarif).unwrap();
        assert!(jsonl.contains("\"level\":\"Warning\""));
    }
}