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
// src/cli/commands.rs

use std::path::PathBuf;

use anyhow::{Context, Result};
use rayon::prelude::*;

use crate::cli::args::{DebugArgs, ExplainArgs, InitArgs, ScanArgs};
use crate::config;
use crate::discovery::{FileWalker, GitHistoryConfig, GitHistoryScanner};
use crate::output::{self, OutputFormat};
use crate::scanner::{Scanner, ScannerConfig};
use crate::scoring::{ScoringConfig as EngineScoringConfig, SensitivityPreset, ThresholdConfig};

/// Execute the scan command
pub fn cmd_scan(args: ScanArgs, config_path: Option<PathBuf>) -> Result<()> {
    // Load configuration
    let mut config = if let Some(path) = config_path {
        config::load_from_file(&path).context("Failed to load config file")?
    } else {
        config::load_or_default(&args.path).context("Failed to load config")?
    };

    // Apply CLI overrides
    if args.show_scores {
        config.output.show_scores = true;
    }

    // Set up scoring config with threshold from CLI and config file values
    let threshold_config = ThresholdConfig::from_preset(SensitivityPreset::Custom(args.threshold));

    let scoring_config = EngineScoringConfig {
        threshold_config,
        enable_scope_filter: !args.include_tests,
        ignore_values: config.scoring.ignore_values.clone(),
        ignore_value_prefixes: config.scoring.ignore_value_prefixes.clone(),
        ignore_value_suffixes: config.scoring.ignore_value_suffixes.clone(),
        ignore_value_contains: config.scoring.ignore_value_contains.clone(),
        ..Default::default()
    };

    // Create scanner config
    let scanner_config = ScannerConfig {
        scoring: scoring_config,
        ..Default::default()
    };

    // Branch based on whether we're scanning history or current files
    if args.scan_history {
        cmd_scan_history(args, scanner_config, config)
    } else {
        cmd_scan_filesystem(args, scanner_config, config)
    }
}

/// Scan the current filesystem
fn cmd_scan_filesystem(
    args: ScanArgs,
    scanner_config: ScannerConfig,
    config: crate::config::Config,
) -> Result<()> {
    // Discover files
    let walker = FileWalker::new(&args.path)
        .with_ignore_patterns(&args.ignore)
        .with_only_patterns(&args.only)
        .with_include_tests(args.include_tests)
        .with_include_examples(args.include_examples);

    let files = walker.walk().context("Failed to walk directory")?;

    let files_to_scan = if args.max_files > 0 && files.len() > args.max_files {
        files[..args.max_files].to_vec()
    } else {
        files
    };

    eprintln!("Scanning {} files...", files_to_scan.len());

    // Set up thread pool if jobs specified
    if let Some(jobs) = args.jobs {
        rayon::ThreadPoolBuilder::new()
            .num_threads(jobs)
            .build_global()
            .ok();
    }

    // Run scanner
    let scanner = Scanner::new(scanner_config).map_err(|e| anyhow::anyhow!("{}", e))?;
    let result = scanner.scan(files_to_scan);

    eprintln!(
        "Scanned {} files, indexed {} constants",
        result.files_scanned, result.constants_indexed
    );

    // Sort findings by score (highest first)
    let mut findings = result.findings;
    findings.sort_by(|a, b| b.score.total.cmp(&a.score.total));

    // Format output
    let format: OutputFormat = args.format.into();
    let output_str = output::format(&findings, format, &config);

    // Write output
    if let Some(output_path) = args.output {
        std::fs::write(&output_path, &output_str).context("Failed to write output file")?;
        eprintln!("Results written to {}", output_path.display());
    } else {
        println!("{}", output_str);
    }

    // Summary
    eprintln!(
        "\nFound {} potential secret(s) (threshold: {})",
        findings.len(),
        args.threshold
    );

    // Exit code
    if args.fail_on_findings && !findings.is_empty() {
        std::process::exit(1);
    }

    Ok(())
}

/// Scan git history for secrets
fn cmd_scan_history(
    args: ScanArgs,
    scanner_config: ScannerConfig,
    config: crate::config::Config,
) -> Result<()> {
    use indicatif::{ProgressBar, ProgressStyle};

    // Configure git history scanner
    let git_config = GitHistoryConfig {
        max_commits: args.max_commits,
        since: args.since.clone(),
        until: args.until.clone(),
        branch: args.branch.clone(),
        extensions: vec!["rs".into()],
    };

    let history_scanner = GitHistoryScanner::new(git_config);

    // Create spinner for commit scanning phase
    let spinner = ProgressBar::new_spinner();
    spinner.set_style(
        ProgressStyle::default_spinner()
            .template("{spinner:.cyan} {msg}")
            .unwrap(),
    );
    spinner.set_message("Scanning git history...");
    spinner.enable_steady_tick(std::time::Duration::from_millis(100));

    // Scan git history
    let history_result = history_scanner
        .scan(&args.path)
        .map_err(|e| anyhow::anyhow!("Git history scan failed: {}", e))?;

    spinner.finish_with_message(format!(
        "Scanned {} commits, found {} historical files",
        history_result.commits_scanned,
        history_result.files.len()
    ));

    // Report any errors encountered
    if !history_result.errors.is_empty() {
        eprintln!("Warnings during git history scan:");
        for error in &history_result.errors {
            eprintln!("  - {}", error);
        }
    }

    // Set up thread pool if jobs specified
    if let Some(jobs) = args.jobs {
        rayon::ThreadPoolBuilder::new()
            .num_threads(jobs)
            .build_global()
            .ok();
    }

    // Create scanner
    let scanner = Scanner::new(scanner_config).map_err(|e| anyhow::anyhow!("{}", e))?;

    // Create progress bar for file analysis
    let progress = ProgressBar::new(history_result.files.len() as u64);
    progress.set_style(
        ProgressStyle::default_bar()
            .template("{spinner:.green} [{bar:40.cyan/blue}] {pos}/{len} files ({eta})")
            .unwrap()
            .progress_chars("█▓▒░"),
    );
    progress.set_message("Analyzing files...");

    // Scan historical files in parallel
    let all_findings_raw: Vec<_> = history_result
        .files
        .par_iter()
        .flat_map(|hist_file| {
            let mut findings = scanner.scan_content(&hist_file.path, &hist_file.content);

            for finding in &mut findings {
                // Annotate with git history metadata
                finding.metadata.insert(
                    "commit".to_string(),
                    hist_file.commit_id.chars().take(8).collect(),
                );
                finding.metadata.insert(
                    "commit_summary".to_string(),
                    hist_file.commit_summary.clone(),
                );
                finding
                    .metadata
                    .insert("author".to_string(), hist_file.author.clone());

                if hist_file.was_deleted {
                    finding
                        .metadata
                        .insert("status".to_string(), "DELETED".to_string());
                } else {
                    finding
                        .metadata
                        .insert("status".to_string(), "current".to_string());
                }
            }

            progress.inc(1);
            findings
        })
        .collect();

    // Filter by deleted status if requested
    let filtered_findings: Vec<_> = all_findings_raw
        .into_iter()
        .filter(|f| {
            let is_deleted = f.metadata.get("status").map(|s| s == "DELETED").unwrap_or(false);
            if args.exclude_deleted && is_deleted {
                return false;
            }
            if args.only_deleted && !is_deleted {
                return false;
            }
            true
        })
        .collect();

    // Deduplicate findings across git history (same file+line+suspect appears in many commits)
    let mut seen = std::collections::HashSet::new();
    let mut all_findings = Vec::new();
    for finding in filtered_findings {
        let signature = format!(
            "{}:{}:{}",
            finding.location.file.display(),
            finding.location.line,
            finding.suspect.name().unwrap_or("literal")
        );
        if seen.insert(signature) {
            all_findings.push(finding);
        }
    }

    // Count deleted vs current after deduplication
    let deleted_count = all_findings
        .iter()
        .filter(|f| f.metadata.get("status").map(|s| s == "DELETED").unwrap_or(false))
        .count();
    let current_count = all_findings.len() - deleted_count;

    progress.finish_with_message(format!(
        "Analyzed {} historical file versions",
        history_result.files.len()
    ));

    // Sort findings by score (highest first)
    all_findings.sort_by(|a, b| b.score.total.cmp(&a.score.total));

    // Format output
    let format: OutputFormat = args.format.into();
    let output_str = output::format(&all_findings, format, &config);

    // Write output
    if let Some(output_path) = args.output {
        std::fs::write(&output_path, &output_str).context("Failed to write output file")?;
        eprintln!("Results written to {}", output_path.display());
    } else {
        println!("{}", output_str);
    }

    // Summary
    eprintln!(
        "\nFound {} potential secret(s) in git history (threshold: {})",
        all_findings.len(),
        args.threshold
    );
    if deleted_count > 0 {
        eprintln!(
            "  {} in DELETED files (secrets removed but remain in git history)",
            deleted_count
        );
    }
    if current_count > 0 {
        eprintln!("  {} in current files", current_count);
    }
    if args.exclude_deleted {
        eprintln!("  (use --only-deleted to see secrets from deleted files)");
    } else if args.only_deleted {
        eprintln!("  (showing only deleted files; remove --only-deleted to see all)");
    }

    // Exit code
    if args.fail_on_findings && !all_findings.is_empty() {
        std::process::exit(1);
    }

    Ok(())
}

/// Execute the init command
pub fn cmd_init(args: InitArgs) -> Result<()> {
    if args.output.exists() && !args.force {
        anyhow::bail!(
            "File already exists: {}. Use --force to overwrite.",
            args.output.display()
        );
    }

    let config_content = config::generate_default_config(args.minimal);
    std::fs::write(&args.output, config_content).context("Failed to write config file")?;

    println!("Created configuration file: {}", args.output.display());
    Ok(())
}

/// Execute the explain command
pub fn cmd_explain(args: ExplainArgs) -> Result<()> {
    // If results file specified, load and search
    if let Some(results_path) = args.results {
        let content = std::fs::read_to_string(&results_path).context("Failed to read results file")?;

        // Try to find the finding ID in JSON
        if content.contains(&args.finding_id) {
            println!("Finding {} found in results file.", args.finding_id);
            // Parse and display (simplified for now)
            if let Ok(parsed) = serde_json::from_str::<serde_json::Value>(&content) {
                if let Some(findings) = parsed.get("findings").and_then(|f| f.as_array()) {
                    for finding in findings {
                        if finding.get("id").and_then(|id| id.as_str()) == Some(&args.finding_id) {
                            println!("{}", serde_json::to_string_pretty(finding)?);
                            return Ok(());
                        }
                    }
                }
            }
        }
        println!("Finding {} not found in results file.", args.finding_id);
    } else {
        println!(
            "To explain finding {}, please provide a results file with --results",
            args.finding_id
        );
    }

    Ok(())
}

/// Execute the debug command
pub fn cmd_debug(args: DebugArgs) -> Result<()> {
    use crate::parser::parse_file;

    let parsed = parse_file(&args.path).context("Failed to parse file")?;

    println!("File: {}", args.path.display());
    println!("Lines: {}", parsed.line_count());

    if args.show_ast {
        println!("\nAST Items: {}", parsed.ast.items.len());
        for (i, item) in parsed.ast.items.iter().enumerate() {
            println!("  [{}] {:?}", i, item_kind(item));
        }
    }

    // Run analysis
    use crate::analysis::{ComparisonFinder, ConstantFinder};

    let constants = ConstantFinder::find(args.path.clone(), &parsed.ast);
    println!("\nConstants found: {}", constants.len());
    for c in &constants {
        println!(
            "  {} = {:?} (line {})",
            c.name,
            c.value.as_deref().unwrap_or("<non-string>"),
            c.line
        );
    }

    let comparisons = ComparisonFinder::find(args.path.clone(), &parsed.ast);
    println!("\nComparisons found: {}", comparisons.len());
    for comp in &comparisons {
        println!(
            "  {:?} {:?} {:?} (line {})",
            comp.left, comp.operator, comp.right, comp.line
        );
    }

    Ok(())
}

fn item_kind(item: &syn::Item) -> &'static str {
    match item {
        syn::Item::Const(_) => "const",
        syn::Item::Enum(_) => "enum",
        syn::Item::Fn(_) => "fn",
        syn::Item::Impl(_) => "impl",
        syn::Item::Mod(_) => "mod",
        syn::Item::Static(_) => "static",
        syn::Item::Struct(_) => "struct",
        syn::Item::Trait(_) => "trait",
        syn::Item::Type(_) => "type",
        syn::Item::Use(_) => "use",
        _ => "other",
    }
}