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
//! MCP tool pinning handler.

use crate::CheckArgs;
use crate::pinning::{PINNING_FILENAME, ToolPins};
use colored::Colorize;
use std::path::Path;
use std::process::ExitCode;

/// Handle the `pin` command to create or update pins.
pub fn handle_pin(args: &CheckArgs, verbose: bool) -> ExitCode {
    let target_path = args
        .paths
        .first()
        .cloned()
        .unwrap_or_else(|| std::env::current_dir().unwrap_or_default());

    // Find MCP config file
    let mcp_path = find_mcp_config(&target_path);

    let Some(mcp_path) = mcp_path else {
        eprintln!(
            "{} No MCP configuration file found in {}",
            "Error:".red().bold(),
            target_path.display()
        );
        eprintln!(
            "{}",
            "Looked for: mcp.json, .mcp.json, settings.json".dimmed()
        );
        return ExitCode::from(2);
    };

    // Check if we're updating existing pins
    if args.pin_update {
        return handle_pin_update(&target_path, &mcp_path);
    }

    // Check if pins already exist
    if ToolPins::exists(&target_path) && !args.pin_force {
        eprintln!(
            "{} Pins already exist at {}",
            "Warning:".yellow().bold(),
            target_path.join(PINNING_FILENAME).display()
        );
        eprintln!("{}", "Use --pin-update to update existing pins".dimmed());
        eprintln!("{}", "Use --pin-force to overwrite existing pins".dimmed());
        return ExitCode::from(2);
    }

    // Create new pins
    match ToolPins::from_mcp_config(&mcp_path) {
        Ok(pins) => {
            if let Err(e) = pins.save(&target_path) {
                eprintln!("{} Failed to save pins: {}", "Error:".red().bold(), e);
                return ExitCode::from(2);
            }

            println!(
                "{} Pinned {} MCP tool(s) to {}",
                "".green(),
                pins.tools.len(),
                target_path.join(PINNING_FILENAME).display()
            );

            if verbose {
                println!();
                for (name, tool) in &pins.tools {
                    println!("  {} {}", "📌".dimmed(), name);
                    println!("     Source: {}", tool.source.dimmed());
                    println!("     Hash: {}", &tool.hash[..24].dimmed());
                }
            }

            ExitCode::SUCCESS
        }
        Err(e) => {
            eprintln!("{} Failed to read MCP config: {}", "Error:".red().bold(), e);
            ExitCode::from(2)
        }
    }
}

/// Handle the `pin --verify` command.
pub fn handle_pin_verify(args: &CheckArgs) -> ExitCode {
    let target_path = args
        .paths
        .first()
        .cloned()
        .unwrap_or_else(|| std::env::current_dir().unwrap_or_default());

    // Load existing pins
    let pins = match ToolPins::load(&target_path) {
        Ok(p) => p,
        Err(e) => {
            eprintln!("{} Failed to load pins: {}", "Error:".red().bold(), e);
            eprintln!("{}", "Run 'cc-audit --pin' first to create pins.".dimmed());
            return ExitCode::from(2);
        }
    };

    // Find MCP config file
    let mcp_path = find_mcp_config(&target_path);

    let Some(mcp_path) = mcp_path else {
        eprintln!(
            "{} No MCP configuration file found in {}",
            "Error:".red().bold(),
            target_path.display()
        );
        return ExitCode::from(2);
    };

    // Verify pins against current config
    match pins.verify(&mcp_path) {
        Ok(result) => {
            print!("{}", result.format_terminal());

            if result.has_changes {
                ExitCode::from(1)
            } else {
                ExitCode::SUCCESS
            }
        }
        Err(e) => {
            eprintln!("{} Failed to verify pins: {}", "Error:".red().bold(), e);
            ExitCode::from(2)
        }
    }
}

/// Handle the `pin --update` command.
fn handle_pin_update(target_path: &Path, mcp_path: &Path) -> ExitCode {
    // Load existing pins
    let mut pins = match ToolPins::load(target_path) {
        Ok(p) => p,
        Err(_) => {
            eprintln!(
                "{} No existing pins found. Creating new pins.",
                "Note:".cyan()
            );
            match ToolPins::from_mcp_config(mcp_path) {
                Ok(p) => p,
                Err(e) => {
                    eprintln!("{} Failed to read MCP config: {}", "Error:".red().bold(), e);
                    return ExitCode::from(2);
                }
            }
        }
    };

    // Update pins
    if let Err(e) = pins.update(mcp_path) {
        eprintln!("{} Failed to update pins: {}", "Error:".red().bold(), e);
        return ExitCode::from(2);
    }

    // Save updated pins
    if let Err(e) = pins.save(target_path) {
        eprintln!("{} Failed to save pins: {}", "Error:".red().bold(), e);
        return ExitCode::from(2);
    }

    println!(
        "{} Updated pins with {} MCP tool(s)",
        "".green(),
        pins.tools.len()
    );

    ExitCode::SUCCESS
}

/// Find the MCP configuration file in a directory.
fn find_mcp_config(dir: &Path) -> Option<std::path::PathBuf> {
    let candidates = ["mcp.json", ".mcp.json", "settings.json"];

    // If dir is a file, use it directly
    if dir.is_file() {
        return Some(dir.to_path_buf());
    }

    // Check for Claude Code config locations
    let claude_dir = dir.join(".claude");
    if claude_dir.exists() {
        for name in &candidates {
            let path = claude_dir.join(name);
            if path.exists() {
                return Some(path);
            }
        }
    }

    // Check in current directory
    for name in &candidates {
        let path = dir.join(name);
        if path.exists() {
            return Some(path);
        }
    }

    // Check common locations
    let common_paths = [
        dir.join(".vscode/settings.json"),
        dir.join(".cursor/mcp.json"),
    ];

    for path in &common_paths {
        if path.exists() {
            return Some(path.clone());
        }
    }

    None
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::fs;
    use tempfile::TempDir;

    fn create_test_args(paths: Vec<std::path::PathBuf>) -> CheckArgs {
        CheckArgs {
            paths,
            pin: true,
            ..Default::default()
        }
    }

    fn create_test_mcp_config() -> &'static str {
        r#"{
            "mcpServers": {
                "github": {
                    "command": "npx",
                    "args": ["-y", "@anthropic/mcp-server-github"]
                }
            }
        }"#
    }

    #[test]
    fn test_handle_pin_no_mcp_config() {
        let temp_dir = TempDir::new().unwrap();
        let args = create_test_args(vec![temp_dir.path().to_path_buf()]);

        let result = handle_pin(&args, false);
        assert_eq!(result, ExitCode::from(2));
    }

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

        let args = create_test_args(vec![temp_dir.path().to_path_buf()]);

        let result = handle_pin(&args, false);
        assert_eq!(result, ExitCode::SUCCESS);

        let pins_path = temp_dir.path().join(PINNING_FILENAME);
        assert!(pins_path.exists());
    }

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

        // Create pins first
        let args = create_test_args(vec![temp_dir.path().to_path_buf()]);
        handle_pin(&args, false);

        // Try to create again without force
        let args = create_test_args(vec![temp_dir.path().to_path_buf()]);
        let result = handle_pin(&args, false);
        assert_eq!(result, ExitCode::from(2));
    }

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

        // Create pins first
        let args = create_test_args(vec![temp_dir.path().to_path_buf()]);
        handle_pin(&args, false);

        // Create again with force
        let mut args = create_test_args(vec![temp_dir.path().to_path_buf()]);
        args.pin_force = true;
        let result = handle_pin(&args, false);
        assert_eq!(result, ExitCode::SUCCESS);
    }

    #[test]
    fn test_handle_pin_verify_no_pins() {
        let temp_dir = TempDir::new().unwrap();
        let mut args = create_test_args(vec![temp_dir.path().to_path_buf()]);
        args.pin_verify = true;

        let result = handle_pin_verify(&args);
        assert_eq!(result, ExitCode::from(2));
    }

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

        // Create pins
        let args = create_test_args(vec![temp_dir.path().to_path_buf()]);
        handle_pin(&args, false);

        // Verify - no changes
        let mut args = create_test_args(vec![temp_dir.path().to_path_buf()]);
        args.pin_verify = true;
        let result = handle_pin_verify(&args);
        assert_eq!(result, ExitCode::SUCCESS);
    }

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

        // Create pins
        let args = create_test_args(vec![temp_dir.path().to_path_buf()]);
        handle_pin(&args, false);

        // Modify config
        let modified_config = r#"{
            "mcpServers": {
                "github": {
                    "command": "npx",
                    "args": ["-y", "@evil/mcp-server-github"]
                }
            }
        }"#;
        fs::write(&mcp_path, modified_config).unwrap();

        // Verify - should detect changes
        let mut args = create_test_args(vec![temp_dir.path().to_path_buf()]);
        args.pin_verify = true;
        let result = handle_pin_verify(&args);
        assert_eq!(result, ExitCode::from(1));
    }

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

        // Create pins
        let args = create_test_args(vec![temp_dir.path().to_path_buf()]);
        handle_pin(&args, false);

        // Modify config
        let modified_config = r#"{
            "mcpServers": {
                "github": {
                    "command": "npx",
                    "args": ["-y", "@anthropic/mcp-server-github@1.0.0"]
                }
            }
        }"#;
        fs::write(&mcp_path, modified_config).unwrap();

        // Update pins
        let mut args = create_test_args(vec![temp_dir.path().to_path_buf()]);
        args.pin_update = true;
        let result = handle_pin(&args, false);
        assert_eq!(result, ExitCode::SUCCESS);
    }

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

        let found = find_mcp_config(temp_dir.path());
        assert!(found.is_some());
        assert!(found.unwrap().ends_with("mcp.json"));
    }

    #[test]
    fn test_find_mcp_config_claude_dir() {
        let temp_dir = TempDir::new().unwrap();
        let claude_dir = temp_dir.path().join(".claude");
        fs::create_dir(&claude_dir).unwrap();
        fs::write(claude_dir.join("mcp.json"), "{}").unwrap();

        let found = find_mcp_config(temp_dir.path());
        assert!(found.is_some());
    }

    #[test]
    fn test_find_mcp_config_none() {
        let temp_dir = TempDir::new().unwrap();
        let found = find_mcp_config(temp_dir.path());
        assert!(found.is_none());
    }

    #[test]
    fn test_find_mcp_config_file_path() {
        let temp_dir = TempDir::new().unwrap();
        let config_path = temp_dir.path().join("my-config.json");
        fs::write(&config_path, "{}").unwrap();

        let found = find_mcp_config(&config_path);
        assert!(found.is_some());
        assert_eq!(found.unwrap(), config_path);
    }

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

        let args = create_test_args(vec![temp_dir.path().to_path_buf()]);

        let result = handle_pin(&args, true);
        assert_eq!(result, ExitCode::SUCCESS);
    }
}