vsec 0.0.1

Detect secrets and in Rust codebases
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
// src/discovery/git_history.rs

//! Git history scanner for finding secrets in commit history.
//!
//! This module uses `gix` to traverse git commit history and extract
//! file contents from past commits, allowing detection of secrets
//! that were committed and later deleted.

use std::collections::HashSet;
use std::path::{Path, PathBuf};

use gix::bstr::ByteSlice;

/// Configuration for git history scanning
#[derive(Debug, Clone)]
pub struct GitHistoryConfig {
    /// Maximum number of commits to scan (0 = unlimited)
    pub max_commits: usize,

    /// Only scan commits after this date (format: YYYY-MM-DD)
    pub since: Option<String>,

    /// Only scan commits before this date (format: YYYY-MM-DD)
    pub until: Option<String>,

    /// Branch to scan (None = current branch/HEAD)
    pub branch: Option<String>,

    /// File extensions to include (e.g., ["rs"])
    pub extensions: Vec<String>,
}

impl Default for GitHistoryConfig {
    fn default() -> Self {
        Self {
            max_commits: 0,
            since: None,
            until: None,
            branch: None,
            extensions: vec!["rs".into()],
        }
    }
}

/// A file extracted from git history
#[derive(Debug, Clone)]
pub struct HistoricalFile {
    /// Path of the file (relative to repo root)
    pub path: PathBuf,

    /// Content of the file at this commit
    pub content: String,

    /// Commit hash where this version was found
    pub commit_id: String,

    /// Commit message (first line)
    pub commit_summary: String,

    /// Commit author
    pub author: String,

    /// Commit timestamp (Unix epoch seconds)
    pub timestamp: i64,

    /// Whether this file was deleted in a later commit
    pub was_deleted: bool,
}

/// Result of git history scanning
#[derive(Debug)]
pub struct GitHistoryResult {
    /// Files extracted from history
    pub files: Vec<HistoricalFile>,

    /// Number of commits scanned
    pub commits_scanned: usize,

    /// Errors encountered during scanning
    pub errors: Vec<String>,
}

/// Git history scanner
pub struct GitHistoryScanner {
    config: GitHistoryConfig,
}

impl GitHistoryScanner {
    pub fn new(config: GitHistoryConfig) -> Self {
        Self { config }
    }

    /// Scan git history starting from the given repository path
    pub fn scan(&self, repo_path: &Path) -> Result<GitHistoryResult, GitHistoryError> {
        // Open the repository
        let repo = gix::open(repo_path).map_err(|e| GitHistoryError::RepoOpen(e.to_string()))?;

        let mut result = GitHistoryResult {
            files: Vec::new(),
            commits_scanned: 0,
            errors: Vec::new(),
        };

        // Get the starting point (branch or HEAD)
        let head = if let Some(ref branch_name) = self.config.branch {
            repo.find_reference(&format!("refs/heads/{}", branch_name))
                .map_err(|e| GitHistoryError::BranchNotFound(branch_name.clone(), e.to_string()))?
                .id()
                .detach()
        } else {
            repo.head_id()
                .map_err(|e| GitHistoryError::HeadNotFound(e.to_string()))?
                .detach()
        };

        // Parse date filters
        let since_timestamp = self.parse_date(&self.config.since)?;
        let until_timestamp = self.parse_date(&self.config.until)?;

        // Track files we've seen to identify deletions
        let mut current_files: HashSet<PathBuf> = HashSet::new();
        let mut seen_in_history: HashSet<PathBuf> = HashSet::new();

        // First, collect current files for deletion detection
        if let Ok(commit) = repo.head_commit() {
            if let Ok(tree) = commit.tree() {
                self.collect_tree_files(&repo, &tree, PathBuf::new(), &mut current_files);
            }
        }

        // Traverse commits using simple iteration
        let walk = repo
            .rev_walk([head])
            .all()
            .map_err(|e| GitHistoryError::WalkError(e.to_string()))?;

        for commit_result in walk {
            // Check commit limit
            if self.config.max_commits > 0 && result.commits_scanned >= self.config.max_commits {
                break;
            }

            let commit_info = match commit_result {
                Ok(info) => info,
                Err(e) => {
                    result.errors.push(format!("Failed to get commit: {}", e));
                    continue;
                }
            };

            // Get full commit object
            let commit = match repo.find_commit(commit_info.id) {
                Ok(c) => c,
                Err(e) => {
                    result
                        .errors
                        .push(format!("Failed to find commit {}: {}", commit_info.id, e));
                    continue;
                }
            };

            // Check date filters
            let commit_time = commit.time().map(|t| t.seconds).unwrap_or(0);

            if let Some(since) = since_timestamp {
                if commit_time < since {
                    continue; // Skip commits before 'since' date
                }
            }

            if let Some(until) = until_timestamp {
                if commit_time > until {
                    continue; // Skip commits after 'until' date
                }
            }

            result.commits_scanned += 1;

            // Get commit metadata
            let commit_id_str = commit_info.id.to_string();
            let commit_summary = commit
                .message()
                .ok()
                .and_then(|m| m.title.to_str().ok().map(|s| s.to_string()))
                .unwrap_or_default();
            let author = commit
                .author()
                .ok()
                .map(|a| a.name.to_str().unwrap_or("Unknown").to_string())
                .unwrap_or_else(|| "Unknown".into());

            // Get the commit's tree
            let tree = match commit.tree() {
                Ok(t) => t,
                Err(e) => {
                    result
                        .errors
                        .push(format!("Failed to get tree for {}: {}", commit_info.id, e));
                    continue;
                }
            };

            // Extract Rust files from this commit
            self.extract_files_from_tree(
                &repo,
                &tree,
                PathBuf::new(),
                &commit_id_str,
                &commit_summary,
                &author,
                commit_time,
                &current_files,
                &mut seen_in_history,
                &mut result.files,
            );
        }

        Ok(result)
    }

    /// Collect file paths from a tree (for tracking current state)
    fn collect_tree_files(
        &self,
        repo: &gix::Repository,
        tree: &gix::Tree,
        prefix: PathBuf,
        files: &mut HashSet<PathBuf>,
    ) {
        for entry in tree.iter() {
            let entry = match entry {
                Ok(e) => e,
                Err(_) => continue,
            };

            let name = match entry.filename().to_str() {
                Ok(n) => n,
                Err(_) => continue,
            };

            let path = prefix.join(name);

            match entry.mode().kind() {
                gix::object::tree::EntryKind::Blob => {
                    if self.should_include_file(&path) {
                        files.insert(path);
                    }
                }
                gix::object::tree::EntryKind::Tree => {
                    if let Ok(obj) = entry.object() {
                        if let Ok(subtree) = obj.try_into_tree() {
                            self.collect_tree_files(repo, &subtree, path, files);
                        }
                    }
                }
                _ => {}
            }
        }
    }

    /// Extract files from a commit's tree
    #[allow(clippy::too_many_arguments)]
    fn extract_files_from_tree(
        &self,
        repo: &gix::Repository,
        tree: &gix::Tree,
        prefix: PathBuf,
        commit_id: &str,
        commit_summary: &str,
        author: &str,
        timestamp: i64,
        current_files: &HashSet<PathBuf>,
        seen_in_history: &mut HashSet<PathBuf>,
        output: &mut Vec<HistoricalFile>,
    ) {
        for entry in tree.iter() {
            let entry = match entry {
                Ok(e) => e,
                Err(_) => continue,
            };

            let name = match entry.filename().to_str() {
                Ok(n) => n,
                Err(_) => continue,
            };

            let path = prefix.join(name);

            match entry.mode().kind() {
                gix::object::tree::EntryKind::Blob => {
                    if !self.should_include_file(&path) {
                        continue;
                    }

                    // Skip if we've already seen this file in history
                    // (we only want the version where it first appeared or was deleted)
                    let was_deleted = !current_files.contains(&path);

                    // For deleted files, we want to capture them
                    // For existing files, only capture if not yet seen
                    if !was_deleted && seen_in_history.contains(&path) {
                        continue;
                    }

                    seen_in_history.insert(path.clone());

                    // Get blob content
                    let blob_id = entry.id();
                    let blob = match repo.find_blob(blob_id) {
                        Ok(b) => b,
                        Err(_) => continue,
                    };

                    let content = match blob.data.to_str() {
                        Ok(s) => s.to_string(),
                        Err(_) => continue, // Skip binary files
                    };

                    output.push(HistoricalFile {
                        path,
                        content,
                        commit_id: commit_id.to_string(),
                        commit_summary: commit_summary.to_string(),
                        author: author.to_string(),
                        timestamp,
                        was_deleted,
                    });
                }
                gix::object::tree::EntryKind::Tree => {
                    if let Ok(obj) = entry.object() {
                        if let Ok(subtree) = obj.try_into_tree() {
                            self.extract_files_from_tree(
                                repo,
                                &subtree,
                                path,
                                commit_id,
                                commit_summary,
                                author,
                                timestamp,
                                current_files,
                                seen_in_history,
                                output,
                            );
                        }
                    }
                }
                _ => {}
            }
        }
    }

    /// Check if a file should be included based on extension
    fn should_include_file(&self, path: &Path) -> bool {
        if self.config.extensions.is_empty() {
            return true;
        }

        path.extension()
            .and_then(|e| e.to_str())
            .map(|ext| self.config.extensions.iter().any(|e| e == ext))
            .unwrap_or(false)
    }

    /// Parse a date string (YYYY-MM-DD) to Unix timestamp
    fn parse_date(&self, date: &Option<String>) -> Result<Option<i64>, GitHistoryError> {
        match date {
            None => Ok(None),
            Some(s) => {
                // Simple date parsing for YYYY-MM-DD format
                let parts: Vec<&str> = s.split('-').collect();
                if parts.len() != 3 {
                    return Err(GitHistoryError::InvalidDate(s.clone()));
                }

                let year: i32 = parts[0]
                    .parse()
                    .map_err(|_| GitHistoryError::InvalidDate(s.clone()))?;
                let month: u32 = parts[1]
                    .parse()
                    .map_err(|_| GitHistoryError::InvalidDate(s.clone()))?;
                let day: u32 = parts[2]
                    .parse()
                    .map_err(|_| GitHistoryError::InvalidDate(s.clone()))?;

                // Convert to Unix timestamp (simplified, assumes UTC midnight)
                // Days since Unix epoch (1970-01-01)
                let days = days_since_epoch(year, month, day);
                Ok(Some(days * 86400)) // seconds per day
            }
        }
    }
}

/// Calculate days since Unix epoch for a given date
fn days_since_epoch(year: i32, month: u32, day: u32) -> i64 {
    // Simplified calculation (doesn't handle all edge cases)
    let mut days: i64 = 0;

    // Years
    for y in 1970..year {
        days += if is_leap_year(y) { 366 } else { 365 };
    }

    // Months
    let days_in_months = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
    for m in 1..month {
        days += days_in_months[(m - 1) as usize] as i64;
        if m == 2 && is_leap_year(year) {
            days += 1;
        }
    }

    // Days
    days += (day - 1) as i64;

    days
}

fn is_leap_year(year: i32) -> bool {
    (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0)
}

/// Errors that can occur during git history scanning
#[derive(Debug, thiserror::Error)]
pub enum GitHistoryError {
    #[error("Failed to open repository: {0}")]
    RepoOpen(String),

    #[error("Branch '{0}' not found: {1}")]
    BranchNotFound(String, String),

    #[error("Could not find HEAD: {0}")]
    HeadNotFound(String),

    #[error("Error walking commits: {0}")]
    WalkError(String),

    #[error("Invalid date format '{0}' (expected YYYY-MM-DD)")]
    InvalidDate(String),
}

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

    #[test]
    fn test_date_parsing() {
        let scanner = GitHistoryScanner::new(GitHistoryConfig::default());

        // Valid date
        let result = scanner.parse_date(&Some("2024-01-15".into()));
        assert!(result.is_ok());
        assert!(result.unwrap().is_some());

        // No date
        let result = scanner.parse_date(&None);
        assert!(result.is_ok());
        assert!(result.unwrap().is_none());

        // Invalid format
        let result = scanner.parse_date(&Some("2024/01/15".into()));
        assert!(result.is_err());
    }

    #[test]
    fn test_should_include_file() {
        let scanner = GitHistoryScanner::new(GitHistoryConfig {
            extensions: vec!["rs".into(), "toml".into()],
            ..Default::default()
        });

        assert!(scanner.should_include_file(Path::new("src/main.rs")));
        assert!(scanner.should_include_file(Path::new("Cargo.toml")));
        assert!(!scanner.should_include_file(Path::new("README.md")));
        assert!(!scanner.should_include_file(Path::new("src/lib.py")));
    }

    #[test]
    fn test_days_since_epoch() {
        // 2024-01-01 should be some positive number
        let days = days_since_epoch(2024, 1, 1);
        assert!(days > 0);

        // 1970-01-01 should be 0
        let days = days_since_epoch(1970, 1, 1);
        assert_eq!(days, 0);
    }

    #[test]
    fn test_leap_year() {
        assert!(is_leap_year(2000));
        assert!(is_leap_year(2024));
        assert!(!is_leap_year(2023));
        assert!(!is_leap_year(1900));
    }
}