cc-audit 3.6.0

Security auditor for Claude Code skills, hooks, and MCP servers
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
//! Scan mode handlers.

use crate::run::EffectiveConfig;
use crate::{
    CheckArgs, Config, WatchModeResult, format_result_check_args, run_scan_with_check_args_config,
    setup_watch_mode, watch_iteration,
};
use std::fs;
use std::path::{Path, PathBuf};
use std::process::ExitCode;
use tracing::{debug, info, warn};

use super::{
    filter_against_baseline, handle_baseline, handle_check_drift, handle_compare, handle_fix,
    handle_hook_mode, handle_pin, handle_pin_verify, handle_report_fp, handle_save_baseline,
    handle_save_profile, handle_sbom, handle_show_profile, require_config,
};

/// Validate that a path is safe to write to.
/// Prevents symlink attacks and path traversal issues.
fn validate_output_path(path: &Path) -> Result<(), String> {
    // Check for path traversal attempts
    let path_str = path.to_string_lossy();
    if path_str.contains("..") {
        return Err("Path contains parent directory reference (..)".to_string());
    }

    // If path exists, check it's not a symlink
    if path.exists() {
        let metadata = std::fs::symlink_metadata(path).map_err(|e| e.to_string())?;
        if metadata.file_type().is_symlink() {
            return Err("Output path is a symbolic link".to_string());
        }
    }

    // Check parent directory exists and is writable
    if let Some(parent) = path.parent() {
        if !parent.as_os_str().is_empty() && !parent.exists() {
            return Err(format!(
                "Parent directory does not exist: {}",
                parent.display()
            ));
        }

        // Check parent is not a symlink
        if parent.exists() {
            let metadata = std::fs::symlink_metadata(parent).map_err(|e| e.to_string())?;
            if metadata.file_type().is_symlink() {
                return Err("Parent directory is a symbolic link".to_string());
            }
        }
    }

    Ok(())
}

/// Validate that a path is safe to read from.
fn validate_input_path(path: &Path) -> Result<(), String> {
    if !path.exists() {
        return Err(format!("Path does not exist: {}", path.display()));
    }

    // Check for symlinks to prevent symlink attacks
    let metadata = std::fs::symlink_metadata(path).map_err(|e| e.to_string())?;
    if metadata.file_type().is_symlink() {
        warn!(
            path = %path.display(),
            "Input path is a symbolic link, following symlink"
        );
        // We allow symlinks for reading but log a warning
    }

    Ok(())
}

/// Handle `cc-audit check` subcommand.
pub fn handle_check(args: &CheckArgs, verbose: bool) -> ExitCode {
    info!(paths = ?args.paths, "Starting check command");

    // Determine project root for config lookup
    // For --compare, use the first compare path; otherwise use paths
    let project_root = if let Some(ref compare_paths) = args.compare {
        compare_paths.first().and_then(|p| {
            if p.is_dir() {
                Some(p.as_path())
            } else {
                p.parent()
            }
        })
    } else {
        args.paths.first().and_then(|p| {
            if p.is_dir() {
                Some(p.as_path())
            } else {
                p.parent()
            }
        })
    };

    // Load config: prefer --config option, then require config file
    let config = if let Some(ref config_path) = args.config {
        match Config::from_file(config_path) {
            Ok(c) => c,
            Err(e) => {
                eprintln!(
                    "Error: Failed to load configuration from {}: {}",
                    config_path.display(),
                    e
                );
                return ExitCode::from(2);
            }
        }
    } else {
        match require_config(project_root) {
            Ok((config, _path)) => config,
            Err(exit_code) => return exit_code,
        }
    };

    // Handle --save-baseline <file>
    if let Some(ref baseline_path) = args.save_baseline {
        return handle_save_baseline(&args.paths, baseline_path);
    }

    // Handle baseline creation (--baseline)
    if args.baseline {
        return handle_baseline(&args.paths);
    }

    // Handle drift detection
    if args.check_drift {
        return handle_check_drift(args);
    }

    // Handle --compare <path1> <path2>
    if let Some(ref paths) = args.compare {
        return handle_compare(args, paths);
    }

    // Handle --fix or --fix-dry-run
    if args.fix || args.fix_dry_run {
        return handle_fix(args);
    }

    // Handle --hook-mode (Claude Code Hook integration)
    if args.hook_mode {
        return handle_hook_mode();
    }

    // Handle --pin (create MCP tool pins)
    if args.pin || args.pin_update {
        return handle_pin(args, verbose);
    }

    // Handle --pin-verify (verify MCP tool pins)
    if args.pin_verify {
        return handle_pin_verify(args);
    }

    // Handle --save-profile
    if let Some(ref profile_name) = args.save_profile {
        return handle_save_profile(args, profile_name, verbose);
    }

    // Handle --report-fp (false positive reporting)
    if args.report_fp {
        return handle_report_fp(args);
    }

    // Handle --sbom (SBOM generation)
    if args.sbom {
        return handle_sbom(args);
    }

    // Handle --profile (info mode when no paths to scan)
    if let Some(ref profile_name) = args.profile
        && args.paths.len() == 1
        && args.paths[0].as_os_str() == "."
        && !args.paths[0].exists()
    {
        return handle_show_profile(profile_name);
    }

    // Handle watch mode
    if args.watch {
        return run_watch_mode_check_args(args);
    }

    // Normal scan mode
    run_normal_mode_check_args(args, config)
}

/// Run watch mode with CheckArgs.
fn run_watch_mode_check_args(args: &CheckArgs) -> ExitCode {
    info!("Starting watch mode");
    println!("Starting watch mode...");
    println!("Press Ctrl+C to stop\n");

    let watcher = match setup_watch_mode(args) {
        Ok(w) => w,
        Err(WatchModeResult::WatcherCreationFailed(e)) => {
            eprintln!("Failed to create file watcher: {}", e);
            return ExitCode::from(2);
        }
        Err(WatchModeResult::WatchPathFailed(path, e)) => {
            eprintln!("Failed to watch {}: {}", path, e);
            return ExitCode::from(2);
        }
        Err(WatchModeResult::Success) => unreachable!(),
    };

    // Initial scan
    if let Some(output) = watch_iteration(args) {
        println!("{}", output);
    }

    // Watch loop
    loop {
        if watcher.wait_for_change() {
            // Clear screen for better readability
            print!("\x1B[2J\x1B[1;1H");
            println!("File change detected, re-scanning...\n");

            if let Some(output) = watch_iteration(args) {
                println!("{}", output);
            }
        } else {
            // Watcher disconnected
            break;
        }
    }

    ExitCode::SUCCESS
}

/// Run normal scan mode with CheckArgs and pre-loaded config.
fn run_normal_mode_check_args(args: &CheckArgs, config: Config) -> ExitCode {
    let effective = EffectiveConfig::from_check_args_and_config(args, &config);

    // Get the effective output path (CLI or config file)
    let effective_output_path: Option<PathBuf> = effective.output.as_ref().map(PathBuf::from);

    // Validate output path before scanning
    if let Some(ref output_path) = effective_output_path
        && let Err(e) = validate_output_path(output_path)
    {
        eprintln!("Invalid output path: {}", e);
        return ExitCode::from(2);
    }

    // Validate baseline path if specified
    if let Some(ref baseline_path) = args.baseline_file
        && let Err(e) = validate_input_path(baseline_path)
    {
        eprintln!("Invalid baseline path: {}", e);
        return ExitCode::from(2);
    }

    match run_scan_with_check_args_config(args, config) {
        Some(mut result) => {
            // Filter against baseline if --baseline-file is specified
            if let Some(ref baseline_path) = args.baseline_file {
                result = filter_against_baseline(result, baseline_path);
            }

            let output = format_result_check_args(args, &result);

            // Write to file if output path is specified (CLI or config)
            if let Some(ref output_path) = effective_output_path {
                match fs::write(output_path, &output) {
                    Ok(()) => {
                        println!("Output written to {}", output_path.display());
                    }
                    Err(e) => {
                        eprintln!("Failed to write output to {}: {}", output_path.display(), e);
                        return ExitCode::from(2);
                    }
                }
            } else {
                println!("{}", output);
            }

            debug!(
                errors = result.summary.errors,
                warnings = result.summary.warnings,
                findings = result.findings.len(),
                "Scan completed"
            );

            // Determine exit code based on mode
            let warn_only = effective.warn_only;

            if warn_only {
                ExitCode::SUCCESS
            } else if effective.strict {
                if result.summary.errors > 0 || result.summary.warnings > 0 {
                    ExitCode::from(1)
                } else {
                    ExitCode::SUCCESS
                }
            } else if result.summary.passed {
                ExitCode::SUCCESS
            } else {
                ExitCode::from(1)
            }
        }
        None => {
            debug!("Scan returned no result");
            ExitCode::from(2)
        }
    }
}

/// Run normal scan mode with CheckArgs (for external callers).
pub fn run_normal_check_mode(args: &CheckArgs) -> ExitCode {
    // Determine project root for config lookup
    let project_root = args.paths.first().and_then(|p| {
        if p.is_dir() {
            Some(p.as_path())
        } else {
            p.parent()
        }
    });

    // Load config
    let config = Config::load(project_root);

    run_normal_mode_check_args(args, config)
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::CheckArgs;
    use std::io::Write;
    use std::path::PathBuf;
    use tempfile::TempDir;

    fn create_test_check_args(paths: Vec<PathBuf>) -> CheckArgs {
        CheckArgs {
            paths,
            ..Default::default()
        }
    }

    /// Create a minimal config file in the given directory for tests
    fn create_test_config(dir: &Path) {
        let config_content = "# Minimal test config\n";
        fs::write(dir.join(".cc-audit.yaml"), config_content).unwrap();
    }

    #[test]
    fn test_run_normal_check_mode_valid_path() {
        let temp_dir = TempDir::new().unwrap();
        create_test_config(temp_dir.path());
        let file_path = temp_dir.path().join("SKILL.md");

        let mut file = fs::File::create(&file_path).unwrap();
        writeln!(
            file,
            "---\nname: test\ndescription: Test skill\n---\n# Test"
        )
        .unwrap();

        let args = create_test_check_args(vec![temp_dir.path().to_path_buf()]);
        let exit_code = run_normal_check_mode(&args);
        // Should succeed with no findings
        assert_eq!(exit_code, ExitCode::SUCCESS);
    }

    #[test]
    fn test_run_normal_check_mode_with_warn_only() {
        let temp_dir = TempDir::new().unwrap();
        create_test_config(temp_dir.path());
        let file_path = temp_dir.path().join("SKILL.md");

        let mut file = fs::File::create(&file_path).unwrap();
        writeln!(
            file,
            "---\nname: test\ndescription: Test skill\n---\n# Test"
        )
        .unwrap();

        let mut args = create_test_check_args(vec![temp_dir.path().to_path_buf()]);
        args.warn_only = true;
        let exit_code = run_normal_check_mode(&args);
        // warn_only always succeeds
        assert_eq!(exit_code, ExitCode::SUCCESS);
    }

    #[test]
    fn test_run_normal_check_mode_with_output_file() {
        let temp_dir = TempDir::new().unwrap();
        create_test_config(temp_dir.path());
        let file_path = temp_dir.path().join("SKILL.md");
        let output_path = temp_dir.path().join("output.json");

        let mut file = fs::File::create(&file_path).unwrap();
        writeln!(
            file,
            "---\nname: test\ndescription: Test skill\n---\n# Test"
        )
        .unwrap();

        let mut args = create_test_check_args(vec![temp_dir.path().to_path_buf()]);
        args.output = Some(output_path.clone());
        let exit_code = run_normal_check_mode(&args);
        assert_eq!(exit_code, ExitCode::SUCCESS);
        assert!(output_path.exists());
    }

    #[test]
    fn test_run_normal_check_mode_with_strict() {
        let temp_dir = TempDir::new().unwrap();
        create_test_config(temp_dir.path());
        let file_path = temp_dir.path().join("SKILL.md");

        let mut file = fs::File::create(&file_path).unwrap();
        writeln!(
            file,
            "---\nname: test\ndescription: Test skill\n---\n# Test"
        )
        .unwrap();

        let mut args = create_test_check_args(vec![temp_dir.path().to_path_buf()]);
        args.strict = true;
        let exit_code = run_normal_check_mode(&args);
        // Should succeed with no findings
        assert_eq!(exit_code, ExitCode::SUCCESS);
    }

    #[test]
    fn test_run_normal_check_mode_with_baseline() {
        let temp_dir = TempDir::new().unwrap();
        create_test_config(temp_dir.path());
        let file_path = temp_dir.path().join("SKILL.md");
        let baseline_path = temp_dir.path().join("baseline.json");

        let mut file = fs::File::create(&file_path).unwrap();
        writeln!(
            file,
            "---\nname: test\ndescription: Test skill\n---\n# Test"
        )
        .unwrap();

        // Create empty baseline
        let mut baseline_file = fs::File::create(&baseline_path).unwrap();
        writeln!(baseline_file, "[]").unwrap();

        let mut args = create_test_check_args(vec![temp_dir.path().to_path_buf()]);
        args.baseline_file = Some(baseline_path);
        let exit_code = run_normal_check_mode(&args);
        assert_eq!(exit_code, ExitCode::SUCCESS);
    }

    #[test]
    fn test_run_normal_check_mode_output_write_fail() {
        let temp_dir = TempDir::new().unwrap();
        create_test_config(temp_dir.path());
        let file_path = temp_dir.path().join("SKILL.md");

        let mut file = fs::File::create(&file_path).unwrap();
        writeln!(
            file,
            "---\nname: test\ndescription: Test skill\n---\n# Test"
        )
        .unwrap();

        let mut args = create_test_check_args(vec![temp_dir.path().to_path_buf()]);
        // Use a path that should fail to write
        args.output = Some(PathBuf::from("/nonexistent/directory/output.json"));
        let exit_code = run_normal_check_mode(&args);
        // Should fail with exit code 2
        assert_eq!(exit_code, ExitCode::from(2));
    }

    #[test]
    fn test_validate_output_path_valid() {
        let temp_dir = TempDir::new().unwrap();
        let output_path = temp_dir.path().join("output.json");

        assert!(validate_output_path(&output_path).is_ok());
    }

    #[test]
    fn test_validate_output_path_traversal() {
        let path = PathBuf::from("/tmp/../etc/passwd");
        let result = validate_output_path(&path);
        assert!(result.is_err());
        assert!(result.unwrap_err().contains("parent directory reference"));
    }

    #[test]
    fn test_validate_output_path_nonexistent_parent() {
        let path = PathBuf::from("/nonexistent_dir_12345/output.json");
        let result = validate_output_path(&path);
        assert!(result.is_err());
        assert!(result.unwrap_err().contains("does not exist"));
    }

    #[cfg(unix)]
    #[test]
    fn test_validate_output_path_symlink() {
        use std::os::unix::fs::symlink;

        let temp_dir = TempDir::new().unwrap();
        let target = temp_dir.path().join("target.json");
        let link = temp_dir.path().join("link.json");

        // Create target file
        fs::write(&target, "test").unwrap();
        // Create symlink
        symlink(&target, &link).unwrap();

        let result = validate_output_path(&link);
        assert!(result.is_err());
        assert!(result.unwrap_err().contains("symbolic link"));
    }

    #[test]
    fn test_validate_input_path_valid() {
        let temp_dir = TempDir::new().unwrap();
        let file_path = temp_dir.path().join("test.json");
        fs::write(&file_path, "[]").unwrap();

        assert!(validate_input_path(&file_path).is_ok());
    }

    #[test]
    fn test_validate_input_path_nonexistent() {
        let path = PathBuf::from("/nonexistent_file_12345.json");
        let result = validate_input_path(&path);
        assert!(result.is_err());
        assert!(result.unwrap_err().contains("does not exist"));
    }

    #[cfg(unix)]
    #[test]
    fn test_validate_output_path_parent_symlink() {
        use std::os::unix::fs::symlink;

        let temp_dir = TempDir::new().unwrap();
        let real_dir = temp_dir.path().join("real_dir");
        let link_dir = temp_dir.path().join("link_dir");

        // Create real directory
        fs::create_dir(&real_dir).unwrap();
        // Create symlink to directory
        symlink(&real_dir, &link_dir).unwrap();

        // Try to validate a path within the symlinked directory
        let path = link_dir.join("output.json");
        let result = validate_output_path(&path);
        assert!(result.is_err());
        assert!(result.unwrap_err().contains("symbolic link"));
    }

    #[cfg(unix)]
    #[test]
    fn test_validate_input_path_symlink() {
        use std::os::unix::fs::symlink;

        let temp_dir = TempDir::new().unwrap();
        let target = temp_dir.path().join("target.json");
        let link = temp_dir.path().join("link.json");

        // Create target file
        fs::write(&target, "[]").unwrap();
        // Create symlink
        symlink(&target, &link).unwrap();

        // Should succeed (symlinks are allowed for reading but logged)
        let result = validate_input_path(&link);
        assert!(result.is_ok());
    }

    #[test]
    fn test_validate_output_path_empty_parent() {
        // Test path with no parent (just a filename)
        let path = PathBuf::from("output.json");
        // This should be valid (empty parent means current directory)
        let result = validate_output_path(&path);
        assert!(result.is_ok());
    }

    #[test]
    fn test_validate_output_path_existing_file() {
        let temp_dir = TempDir::new().unwrap();
        let output_path = temp_dir.path().join("existing.json");

        // Create the file first
        fs::write(&output_path, "{}").unwrap();

        // Should be valid (existing regular file)
        let result = validate_output_path(&output_path);
        assert!(result.is_ok());
    }
}