cc-audit 3.2.14

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
use super::error::RemoteError;
use std::io::Write;
use std::path::{Path, PathBuf};
use std::process::{Command, Stdio};
use std::sync::LazyLock;
use std::time::Duration;
use tempfile::{NamedTempFile, TempDir};

static TOKEN_URL_PATTERN: LazyLock<regex::Regex> = LazyLock::new(|| {
    regex::Regex::new(r"https://[^@\s]+@").expect("TOKEN_URL_PATTERN is a valid regex literal")
});

static BEARER_PATTERN: LazyLock<regex::Regex> = LazyLock::new(|| {
    regex::Regex::new(r"Bearer\s+\S+").expect("BEARER_PATTERN is a valid regex literal")
});

/// Result of a successful clone operation
pub struct ClonedRepo {
    /// Path to the cloned repository
    pub path: PathBuf,
    /// Original repository URL
    pub url: String,
    /// Git ref that was checked out
    pub git_ref: String,
    /// Commit SHA of the checked out ref
    pub commit_sha: Option<String>,
    /// Temporary directory handle (dropped when ClonedRepo is dropped)
    _temp_dir: TempDir,
}

impl ClonedRepo {
    /// Get the path to the cloned repository
    pub fn path(&self) -> &Path {
        &self.path
    }
}

/// Git repository cloner with security measures
pub struct GitCloner {
    /// Optional authentication token for private repositories
    auth_token: Option<String>,
    /// Clone timeout in seconds
    timeout_secs: u64,
    /// Maximum repository size in MB (0 = unlimited)
    max_size_mb: u64,
}

impl Default for GitCloner {
    fn default() -> Self {
        Self::new()
    }
}

impl GitCloner {
    /// Create a new GitCloner with default settings
    pub fn new() -> Self {
        Self {
            auth_token: None,
            timeout_secs: 300, // 5 minutes
            max_size_mb: 0,    // unlimited
        }
    }

    /// Set authentication token for private repositories
    pub fn with_auth_token(mut self, token: Option<String>) -> Self {
        self.auth_token = token;
        self
    }

    /// Set clone timeout in seconds
    pub fn with_timeout(mut self, secs: u64) -> Self {
        self.timeout_secs = secs;
        self
    }

    /// Set maximum repository size in MB
    pub fn with_max_size(mut self, mb: u64) -> Self {
        self.max_size_mb = mb;
        self
    }

    /// Clone a repository with security measures
    ///
    /// Security measures:
    /// - Uses shallow clone (depth=1)
    /// - Disables git hooks (template and local)
    /// - Uses temporary directory that is automatically cleaned up
    /// - Token is passed via GIT_ASKPASS (not embedded in URL)
    /// - Clone has configurable timeout
    pub fn clone(&self, url: &str, git_ref: &str) -> Result<ClonedRepo, RemoteError> {
        // Validate URL format
        self.validate_url(url)?;

        // Check if git is available
        self.check_git_available()?;

        // Create temporary directory
        let temp_dir = TempDir::new().map_err(|e| RemoteError::TempDir(e.to_string()))?;
        let repo_path = temp_dir.path().to_path_buf();

        // Execute git clone with security measures (token via env, not URL)
        self.execute_clone(url, &repo_path, git_ref)?;

        // Get commit SHA
        let commit_sha = self.get_commit_sha(&repo_path).ok();

        Ok(ClonedRepo {
            path: repo_path,
            url: url.to_string(),
            git_ref: git_ref.to_string(),
            commit_sha,
            _temp_dir: temp_dir,
        })
    }

    /// Validate the repository URL format
    fn validate_url(&self, url: &str) -> Result<(), RemoteError> {
        // Check for basic URL structure
        if !url.starts_with("https://") && !url.starts_with("git@") {
            return Err(RemoteError::InvalidUrl(format!(
                "URL must start with https:// or git@: {}",
                url
            )));
        }

        // Check for GitHub URL format
        if url.starts_with("https://github.com/") || url.starts_with("git@github.com:") {
            // Valid GitHub URL
            return Ok(());
        }

        // Allow other HTTPS URLs but warn about non-GitHub sources
        if url.starts_with("https://") {
            return Ok(());
        }

        Err(RemoteError::InvalidUrl(format!(
            "Unsupported URL format: {}",
            url
        )))
    }

    /// Check if git command is available
    fn check_git_available(&self) -> Result<(), RemoteError> {
        Command::new("git")
            .arg("--version")
            .output()
            .map_err(|_| RemoteError::GitNotFound)?;
        Ok(())
    }

    /// Create a temporary GIT_ASKPASS script that returns the token.
    /// This is more secure than embedding the token in the URL because:
    /// - Token is not visible in process list (ps aux)
    /// - Token is not logged in git error messages
    /// - Script is automatically cleaned up
    fn create_askpass_script(&self) -> Result<Option<NamedTempFile>, RemoteError> {
        let Some(ref token) = self.auth_token else {
            return Ok(None);
        };

        let mut script = NamedTempFile::new().map_err(|e| RemoteError::TempDir(e.to_string()))?;

        // Write a shell script that outputs the token
        // The script receives the prompt as an argument but we ignore it
        writeln!(script, "#!/bin/sh").map_err(|e| RemoteError::TempDir(e.to_string()))?;
        writeln!(script, "echo '{}'", token.replace('\'', "'\"'\"'"))
            .map_err(|e| RemoteError::TempDir(e.to_string()))?;

        // Make the script executable (Unix only)
        #[cfg(unix)]
        {
            use std::os::unix::fs::PermissionsExt;
            let path = script.path();
            std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o700))
                .map_err(|e| RemoteError::TempDir(e.to_string()))?;
        }

        Ok(Some(script))
    }

    /// Sanitize error messages to remove any potential token leakage.
    fn sanitize_error_message(&self, message: &str) -> String {
        let mut sanitized = message.to_string();

        // Remove any token-like patterns from error messages
        if let Some(ref token) = self.auth_token {
            sanitized = sanitized.replace(token, "[REDACTED]");
        }

        // Remove patterns that look like tokens embedded in URLs
        // Pattern: https://TOKEN@github.com or similar
        sanitized = TOKEN_URL_PATTERN
            .replace_all(&sanitized, "https://[REDACTED]@")
            .to_string();

        // Also redact Bearer tokens
        sanitized = BEARER_PATTERN
            .replace_all(&sanitized, "Bearer [REDACTED]")
            .to_string();

        sanitized
    }

    /// Execute git clone command with security measures and timeout.
    fn execute_clone(&self, url: &str, path: &Path, git_ref: &str) -> Result<(), RemoteError> {
        // Create askpass script for secure token handling
        let askpass_script = self.create_askpass_script()?;

        // Build the git clone command with security measures
        let mut cmd = Command::new("git");

        // Disable hooks for security
        cmd.env("GIT_TEMPLATE_DIR", "");

        // Set up authentication via GIT_ASKPASS if we have a token
        if let Some(ref script) = askpass_script {
            cmd.env("GIT_ASKPASS", script.path());
            // Disable terminal prompts to force use of ASKPASS
            cmd.env("GIT_TERMINAL_PROMPT", "0");
        }

        // Clone with shallow depth
        cmd.args([
            "clone",
            "--depth",
            "1",
            "--single-branch",
            "--no-tags",
            "-c",
            "core.hooksPath=/dev/null",
            "-c",
            "advice.detachedHead=false",
        ]);

        // Add branch/ref if not HEAD
        if git_ref != "HEAD" && !git_ref.is_empty() {
            cmd.args(["--branch", git_ref]);
        }

        cmd.arg(url);
        cmd.arg(path);

        // Execute with timeout using a child process
        cmd.stdout(Stdio::piped());
        cmd.stderr(Stdio::piped());

        let mut child = cmd.spawn().map_err(|e| RemoteError::CloneFailed {
            url: url.to_string(),
            message: self.sanitize_error_message(&e.to_string()),
        })?;

        // Wait with timeout
        let timeout = Duration::from_secs(self.timeout_secs);
        let start = std::time::Instant::now();

        loop {
            match child.try_wait() {
                Ok(Some(status)) => {
                    // Process finished
                    let output =
                        child
                            .wait_with_output()
                            .map_err(|e| RemoteError::CloneFailed {
                                url: url.to_string(),
                                message: self.sanitize_error_message(&e.to_string()),
                            })?;

                    if !status.success() {
                        let stderr = String::from_utf8_lossy(&output.stderr);
                        let sanitized_stderr = self.sanitize_error_message(&stderr);

                        // Check for common error patterns
                        if stderr.contains("Repository not found") || stderr.contains("404") {
                            return Err(RemoteError::NotFound(url.to_string()));
                        }

                        if stderr.contains("Authentication failed")
                            || stderr.contains("could not read Username")
                        {
                            return Err(RemoteError::AuthRequired(url.to_string()));
                        }

                        return Err(RemoteError::CloneFailed {
                            url: url.to_string(),
                            message: sanitized_stderr,
                        });
                    }

                    return Ok(());
                }
                Ok(None) => {
                    // Process still running, check timeout
                    if start.elapsed() > timeout {
                        // Kill the process
                        let _ = child.kill();
                        return Err(RemoteError::CloneFailed {
                            url: url.to_string(),
                            message: format!("Clone timed out after {} seconds", self.timeout_secs),
                        });
                    }
                    // Sleep briefly before checking again
                    std::thread::sleep(Duration::from_millis(100));
                }
                Err(e) => {
                    return Err(RemoteError::CloneFailed {
                        url: url.to_string(),
                        message: self.sanitize_error_message(&e.to_string()),
                    });
                }
            }
        }
    }

    /// Get the commit SHA of HEAD
    fn get_commit_sha(&self, path: &Path) -> Result<String, RemoteError> {
        let output = Command::new("git")
            .args(["rev-parse", "HEAD"])
            .current_dir(path)
            .output()
            .map_err(|e| RemoteError::CloneFailed {
                url: "".to_string(),
                message: e.to_string(),
            })?;

        if output.status.success() {
            Ok(String::from_utf8_lossy(&output.stdout).trim().to_string())
        } else {
            Err(RemoteError::CloneFailed {
                url: "".to_string(),
                message: "Failed to get commit SHA".to_string(),
            })
        }
    }
}

/// Parse GitHub URL to extract owner and repo name
pub fn parse_github_url(url: &str) -> Option<(String, String)> {
    // Handle HTTPS URLs: https://github.com/owner/repo or https://github.com/owner/repo.git
    if url.starts_with("https://github.com/") {
        let path = url.trim_start_matches("https://github.com/");
        let path = path.trim_end_matches(".git");
        let parts: Vec<&str> = path.split('/').collect();
        if parts.len() >= 2 {
            return Some((parts[0].to_string(), parts[1].to_string()));
        }
    }

    // Handle SSH URLs: git@github.com:owner/repo.git
    if url.starts_with("git@github.com:") {
        let path = url.trim_start_matches("git@github.com:");
        let path = path.trim_end_matches(".git");
        let parts: Vec<&str> = path.split('/').collect();
        if parts.len() >= 2 {
            return Some((parts[0].to_string(), parts[1].to_string()));
        }
    }

    None
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_parse_github_url_https() {
        let result = parse_github_url("https://github.com/owner/repo");
        assert_eq!(result, Some(("owner".to_string(), "repo".to_string())));

        let result = parse_github_url("https://github.com/owner/repo.git");
        assert_eq!(result, Some(("owner".to_string(), "repo".to_string())));
    }

    #[test]
    fn test_parse_github_url_ssh() {
        let result = parse_github_url("git@github.com:owner/repo.git");
        assert_eq!(result, Some(("owner".to_string(), "repo".to_string())));
    }

    #[test]
    fn test_parse_github_url_invalid() {
        assert!(parse_github_url("https://gitlab.com/owner/repo").is_none());
        assert!(parse_github_url("not-a-url").is_none());
    }

    #[test]
    fn test_validate_url_https() {
        let cloner = GitCloner::new();
        assert!(cloner.validate_url("https://github.com/owner/repo").is_ok());
        assert!(cloner.validate_url("https://example.com/repo").is_ok());
    }

    #[test]
    fn test_validate_url_invalid() {
        let cloner = GitCloner::new();
        assert!(cloner.validate_url("http://github.com/owner/repo").is_err());
        assert!(cloner.validate_url("ftp://github.com/owner/repo").is_err());
    }

    #[test]
    fn test_sanitize_error_message() {
        let cloner = GitCloner::new().with_auth_token(Some("ghp_secret123".to_string()));

        // Test direct token replacement
        let msg = "failed with ghp_secret123 in message";
        assert_eq!(
            cloner.sanitize_error_message(msg),
            "failed with [REDACTED] in message"
        );

        // Test URL token pattern
        let msg = "failed: https://token123@github.com/repo";
        assert!(cloner.sanitize_error_message(msg).contains("[REDACTED]"));
        assert!(!cloner.sanitize_error_message(msg).contains("token123"));
    }

    #[test]
    fn test_sanitize_error_message_no_token() {
        let cloner = GitCloner::new();

        // Without token, message should still sanitize URL patterns
        let msg = "failed: https://sometoken@github.com/repo";
        let sanitized = cloner.sanitize_error_message(msg);
        assert!(sanitized.contains("[REDACTED]"));
    }

    #[test]
    fn test_sanitize_bearer_token() {
        let cloner = GitCloner::new();

        let msg = "Authorization: Bearer ghp_secret123456";
        let sanitized = cloner.sanitize_error_message(msg);
        assert!(!sanitized.contains("ghp_secret123456"));
        assert!(sanitized.contains("[REDACTED]"));
    }

    #[cfg(unix)]
    #[test]
    fn test_create_askpass_script() {
        let cloner = GitCloner::new().with_auth_token(Some("test_token".to_string()));
        let script = cloner.create_askpass_script().unwrap();

        assert!(script.is_some());
        let script = script.unwrap();

        // Verify script exists and is executable
        let path = script.path();
        assert!(path.exists());

        let metadata = std::fs::metadata(path).unwrap();
        use std::os::unix::fs::PermissionsExt;
        assert_eq!(metadata.permissions().mode() & 0o700, 0o700);
    }

    #[test]
    fn test_create_askpass_script_no_token() {
        let cloner = GitCloner::new();
        let script = cloner.create_askpass_script().unwrap();
        assert!(script.is_none());
    }

    #[test]
    fn test_cloner_with_timeout() {
        let cloner = GitCloner::new().with_timeout(60);
        assert_eq!(cloner.timeout_secs, 60);
    }

    #[test]
    fn test_cloner_with_max_size() {
        let cloner = GitCloner::new().with_max_size(100);
        assert_eq!(cloner.max_size_mb, 100);
    }
}