foxguard 0.8.1

A security scanner as fast as a linter, written in Rust. 170+ built-in rules across 11 languages.
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
use crate::baseline::{load_baseline, suppress_with_baseline_at_root, write_baseline_at_root};
use crate::cli::{DiffArgs, OutputFormat, ScanArgs, SecretsArgs, TuiArgs};
use crate::config::{
    apply_scan_defaults, apply_scan_thresholds, apply_secrets_defaults, apply_severity_overrides,
    load_for_scan, suppress_with_scan_ignores, FoxguardConfig,
};
use crate::diff::run_diff_with_warnings;
use crate::engine::{
    scan_directory_with_notices, scan_paths_with_root_with_notices, PathExcludeMatcher, ScanResult,
    ScanStats,
};
use crate::git::changed_files;
use crate::rules::semgrep_compat::load_semgrep_rules;
use crate::rules::RuleRegistry;
use crate::secrets::{
    scan_directory_with_config_and_notices, scan_paths_with_config_and_notices, SecretScanConfig,
};
use crate::Finding;
use std::path::{Path, PathBuf};

pub struct ScanExecution {
    pub args: ScanArgs,
    pub findings: Vec<Finding>,
    pub files_scanned: usize,
    pub stats: ScanStats,
    pub duration: std::time::Duration,
    pub notices: Vec<String>,
}

pub struct SecretsExecution {
    pub args: SecretsArgs,
    pub findings: Vec<Finding>,
    pub files_scanned: usize,
    pub duration: std::time::Duration,
    pub notices: Vec<String>,
}

pub struct DiffExecution {
    pub args: DiffArgs,
    pub findings: Vec<Finding>,
    pub files_scanned: usize,
    pub duration: std::time::Duration,
    pub total_current: usize,
    pub existing_count: usize,
    pub notices: Vec<String>,
}

pub struct DiffSummary {
    pub target: String,
    pub total_current: usize,
    pub existing_count: usize,
}

pub enum TuiMode {
    Scan,
    Diff { target: String },
    Secrets,
}

pub struct TuiExecution {
    pub mode: TuiMode,
    pub path: String,
    pub findings: Vec<Finding>,
    pub files_scanned: usize,
    pub duration: std::time::Duration,
    pub explain: bool,
    pub diff_summary: Option<DiffSummary>,
    pub notices: Vec<String>,
}

pub fn resolve_scan_args(scan: &ScanArgs) -> Result<ScanArgs, String> {
    let mut scan = scan.clone();
    let config = load_for_scan(Path::new(&scan.path), scan.config.as_deref())?;
    apply_scan_defaults(&mut scan, config.as_ref());
    Ok(scan)
}

pub fn resolve_secrets_args(args: &SecretsArgs) -> Result<SecretsArgs, String> {
    let mut args = args.clone();
    let config = load_for_scan(Path::new(&args.path), args.config.as_deref())?;
    apply_secrets_defaults(&mut args, config.as_ref());
    Ok(args)
}

pub fn scan_findings(scan: &ScanArgs) -> Result<ScanResult, String> {
    let execution = execute_scan(scan)?;
    Ok(ScanResult {
        findings: execution.findings,
        files_scanned: execution.files_scanned,
        stats: execution.stats,
        duration: execution.duration,
    })
}

pub fn execute_scan(scan: &ScanArgs) -> Result<ScanExecution, String> {
    let scan = resolve_scan_args(scan)?;
    let config = load_for_scan(Path::new(&scan.path), scan.config.as_deref())?;
    validate_root_path(&scan.path)?;
    validate_rules_path(scan.rules.as_deref())?;
    let identity_root = finding_identity_root(Path::new(&scan.path), config.as_ref());

    // Install any `scan.thresholds.*` overrides into process-wide state
    // before the rules run. Must happen after config load and before
    // `scan_directory_with_notices` dispatches parallel rule execution.
    apply_scan_thresholds(config.as_ref());

    let mut registry = build_registry(scan.no_builtins, scan.rules.as_deref())?;
    if let Some(ref config) = config {
        if !config.scan.rule_options.is_empty() {
            let warnings = registry.configure_rules(&config.scan.rule_options)?;
            for w in &warnings {
                eprintln!("warning: {}", w);
            }
        }
    }
    let excludes = PathExcludeMatcher::new(&scan.exclude)?;
    let targets = collect_changed_targets(&scan.path, scan.changed)?;

    // In PQ mode, filter to only PQ-related rules
    let pq_enable: Vec<String>;
    let rule_filter_unknown = if scan.pq_mode {
        pq_enable = registry
            .all_rules()
            .iter()
            .map(|r| r.id().to_string())
            .filter(|id| is_pq_rule_id(id))
            .collect();
        if pq_enable.is_empty() {
            eprintln!(
                "Warning: no PQ rules registered in this build. \
                 Install a version with post-quantum crypto rules to use 'foxguard pqc'."
            );
        }
        registry.apply_rule_filter(&pq_enable, &[])
    } else if let Some(config) = config.as_ref() {
        registry.apply_rule_filter(&config.scan.enable_rules, &config.scan.disable_rules)
    } else {
        registry.apply_rule_filter(&[], &[])
    };

    let (result, mut notices) = if let Some(files) = targets {
        scan_paths_with_root_with_notices(
            Path::new(&scan.path),
            &files,
            &registry,
            scan.max_file_size,
            Some(&excludes),
        )
    } else {
        scan_directory_with_notices(&scan.path, &registry, scan.max_file_size, Some(&excludes))
    };

    if !rule_filter_unknown.is_empty() {
        notices.insert(
            0,
            format!(
                "Warning: unknown rule id{} in config (enable_rules/disable_rules): {}",
                if rule_filter_unknown.len() == 1 {
                    ""
                } else {
                    "s"
                },
                rule_filter_unknown.join(", ")
            ),
        );
    }

    let files_scanned = result.files_scanned;
    let duration = result.duration;
    let stats = result.stats;
    let mut findings = result.findings;
    append_scan_stats_notice(&mut notices, &stats);

    // CNSA 2.0 deadline annotation. Runs regardless of the `--cnsa2`
    // opt-in flag because SARIF always carries the field in `properties`
    // — it's metadata. The flag only controls terminal surface (see
    // `src/main.rs`).
    crate::compliance::annotate_cnsa2_deadlines(&mut findings, &registry);

    let known_rule_ids = collect_rule_ids(&registry);
    let override_warnings =
        apply_severity_overrides(&mut findings, config.as_ref(), &known_rule_ids);
    notices.extend(override_warnings);

    if let Some(min_conf) = scan.min_confidence {
        findings.retain(|f| f.confidence >= min_conf);
    }

    // Filter taint findings exceeding max_hops threshold
    if let Some(ref cfg) = config {
        if let Some(max) = cfg.scan.thresholds.taint.max_hops {
            findings.retain(|f| f.taint_hops.is_none_or(|h| (h as usize) <= max));
        }
    }

    if let Some(ref min_severity) = scan.severity {
        let min = min_severity.to_severity();
        findings.retain(|f| f.severity >= min);
    }

    findings = suppress_with_scan_ignores(findings, config.as_ref(), &identity_root);

    if let Some(ref path) = scan.write_baseline {
        write_baseline_at_root(Path::new(path), &findings, &identity_root)?;
        notices.push(format!("Wrote baseline to {}", path));
    }

    let baseline = match scan.baseline.as_ref() {
        Some(path) => load_baseline(Path::new(path))?,
        None => None,
    };

    findings = suppress_with_baseline_at_root(findings, baseline.as_ref(), &identity_root);

    if files_scanned == 0 {
        if stats.files_discovered == 0 {
            notices.push(
                "Warning: no files found. Supported: .js, .ts, .py, .go, .rb, .java, .php, .rs, .cs, .swift, .kt"
                    .to_string(),
            );
        } else {
            notices.push(
                "Warning: no files were scanned. See skipped-file summary for reasons.".to_string(),
            );
        }
    }

    Ok(ScanExecution {
        args: scan,
        findings,
        files_scanned,
        stats,
        duration,
        notices,
    })
}

pub fn execute_secrets(args: &SecretsArgs) -> Result<SecretsExecution, String> {
    let args = resolve_secrets_args(args)?;
    let config_for_identity = load_for_scan(Path::new(&args.path), args.config.as_deref())?;
    let identity_root = finding_identity_root(Path::new(&args.path), config_for_identity.as_ref());
    validate_root_path(&args.path)?;

    let scan_path = Path::new(&args.path);
    let config = SecretScanConfig::from_inputs(
        scan_path,
        &args.exclude_paths,
        args.exclude_path_file.as_deref().map(Path::new),
        &args.ignored_rules,
    )?;

    let (mut findings, mut notices, files_scanned, duration) =
        match collect_changed_targets(&args.path, args.changed)? {
            Some(files) => {
                let file_count = files.len();
                let started = std::time::Instant::now();
                let (findings, notices) = scan_paths_with_config_and_notices(
                    scan_path,
                    &files,
                    &config,
                    args.max_file_size,
                );
                (findings, notices, file_count, started.elapsed())
            }
            None => {
                let started = std::time::Instant::now();
                let (findings, notices) =
                    scan_directory_with_config_and_notices(&args.path, &config, args.max_file_size);
                let files_scanned = count_secret_files(scan_path);
                (findings, notices, files_scanned, started.elapsed())
            }
        };

    if let Some(ref path) = args.write_baseline {
        write_baseline_at_root(Path::new(path), &findings, &identity_root)?;
        notices.push(format!("Wrote secrets baseline to {}", path));
    }

    let baseline = match args.baseline.as_ref() {
        Some(path) => load_baseline(Path::new(path))?,
        None => None,
    };
    findings = suppress_with_baseline_at_root(findings, baseline.as_ref(), &identity_root);

    Ok(SecretsExecution {
        args,
        findings,
        files_scanned,
        duration,
        notices,
    })
}

pub fn execute_diff(args: &DiffArgs) -> Result<DiffExecution, String> {
    validate_root_path(&args.path)?;
    let config = load_for_scan(Path::new(&args.path), None)?;
    let identity_root = finding_identity_root(Path::new(&args.path), config.as_ref());
    apply_scan_thresholds(config.as_ref());
    let mut registry = build_registry(args.no_builtins, args.rules.as_deref())?;
    let rule_filter_unknown = if let Some(config) = config.as_ref() {
        registry.apply_rule_filter(&config.scan.enable_rules, &config.scan.disable_rules)
    } else {
        registry.apply_rule_filter(&[], &[])
    };
    let ((scan_result, mut diff_result), mut notices) =
        run_diff_with_warnings(&args.path, &args.target, &registry, args.max_file_size)?;
    append_scan_stats_notice(&mut notices, &scan_result.stats);

    if !rule_filter_unknown.is_empty() {
        notices.insert(
            0,
            format!(
                "Warning: unknown rule id{} in config (enable_rules/disable_rules): {}",
                if rule_filter_unknown.len() == 1 {
                    ""
                } else {
                    "s"
                },
                rule_filter_unknown.join(", ")
            ),
        );
    }

    // Annotate CNSA 2.0 deadlines on the new findings surfaced by this diff.
    crate::compliance::annotate_cnsa2_deadlines(&mut diff_result.new_findings, &registry);

    let known_rule_ids = collect_rule_ids(&registry);
    let override_warnings = apply_severity_overrides(
        &mut diff_result.new_findings,
        config.as_ref(),
        &known_rule_ids,
    );
    notices.extend(override_warnings);

    if let Some(ref min_severity) = args.severity {
        let min = min_severity.to_severity();
        diff_result.new_findings.retain(|f| f.severity >= min);
    }

    diff_result.new_findings =
        suppress_with_scan_ignores(diff_result.new_findings, config.as_ref(), &identity_root);

    notices.push(format!(
        "foxguard diff vs {}: {} new issue{} ({} total, {} existing)",
        args.target,
        diff_result.new_findings.len(),
        if diff_result.new_findings.len() == 1 {
            ""
        } else {
            "s"
        },
        diff_result.total_current,
        diff_result.existing_count
    ));

    Ok(DiffExecution {
        args: args.clone(),
        findings: diff_result.new_findings,
        files_scanned: scan_result.files_scanned,
        duration: scan_result.duration,
        total_current: diff_result.total_current,
        existing_count: diff_result.existing_count,
        notices,
    })
}

fn append_scan_stats_notice(notices: &mut Vec<String>, stats: &ScanStats) {
    if let Some(summary) = stats.skipped_summary() {
        notices.push(format!(
            "Skipped {} file{}: {}.",
            stats.files_skipped,
            if stats.files_skipped == 1 { "" } else { "s" },
            summary
        ));
    }
}

pub fn execute_tui(args: &TuiArgs) -> Result<TuiExecution, String> {
    if args.secrets {
        let result = execute_secrets(&tui_secrets_args(args))?;
        return Ok(TuiExecution {
            mode: TuiMode::Secrets,
            path: result.args.path.clone(),
            findings: result.findings,
            files_scanned: result.files_scanned,
            duration: result.duration,
            explain: false,
            diff_summary: None,
            notices: result.notices,
        });
    }

    if let Some(target) = args.diff.as_ref() {
        let result = execute_diff(&tui_diff_args(args, target))?;
        return Ok(TuiExecution {
            mode: TuiMode::Diff {
                target: result.args.target.clone(),
            },
            path: result.args.path.clone(),
            findings: result.findings,
            files_scanned: result.files_scanned,
            duration: result.duration,
            explain: args.explain,
            diff_summary: Some(DiffSummary {
                target: result.args.target,
                total_current: result.total_current,
                existing_count: result.existing_count,
            }),
            notices: result.notices,
        });
    }

    let result = execute_scan(&tui_scan_args(args))?;
    Ok(TuiExecution {
        mode: TuiMode::Scan,
        path: result.args.path.clone(),
        findings: result.findings,
        files_scanned: result.files_scanned,
        duration: result.duration,
        explain: result.args.explain,
        diff_summary: None,
        notices: result.notices,
    })
}

fn tui_scan_args(args: &TuiArgs) -> ScanArgs {
    ScanArgs {
        path: args.path.clone(),
        config: args.config.clone(),
        format: OutputFormat::Terminal,
        severity: args.severity,
        rules: args.rules.clone(),
        no_builtins: args.no_builtins,
        changed: args.changed,
        exclude: args.exclude.clone(),
        baseline: args.baseline.clone(),
        write_baseline: None,
        explain: args.explain,
        github_pr: None,
        quiet: false,
        max_file_size: args.max_file_size,
        fix: false,
        show_confidence: false,
        min_confidence: None,
        pq_mode: args.pq_mode,
        cnsa2: args.pq_mode,
    }
}

fn tui_diff_args(args: &TuiArgs, target: &str) -> DiffArgs {
    DiffArgs {
        target: target.to_string(),
        path: args.path.clone(),
        format: OutputFormat::Terminal,
        severity: args.severity,
        rules: args.rules.clone(),
        no_builtins: args.no_builtins,
        max_file_size: args.max_file_size,
    }
}

fn tui_secrets_args(args: &TuiArgs) -> SecretsArgs {
    SecretsArgs {
        path: args.path.clone(),
        config: args.config.clone(),
        format: OutputFormat::Terminal,
        changed: args.changed,
        baseline: args.baseline.clone(),
        write_baseline: None,
        exclude_paths: Vec::new(),
        exclude_path_file: None,
        ignored_rules: Vec::new(),
        max_file_size: args.max_file_size,
    }
}

fn collect_rule_ids(registry: &RuleRegistry) -> std::collections::HashSet<String> {
    registry
        .all_rules()
        .iter()
        .map(|rule| rule.id().to_string())
        .collect()
}

fn finding_identity_root(scan_path: &Path, config: Option<&FoxguardConfig>) -> PathBuf {
    crate::path_identity::project_root(
        scan_path,
        config.map(|config| config.project_root.as_path()),
    )
}

fn build_registry(no_builtins: bool, rules: Option<&str>) -> Result<RuleRegistry, String> {
    validate_rules_path(rules)?;

    let mut registry = if no_builtins {
        RuleRegistry::empty()
    } else {
        RuleRegistry::new()
    };

    if let Some(rules_path) = rules {
        let semgrep_rules = load_semgrep_rules(Path::new(rules_path));
        for rule in semgrep_rules {
            registry.register(rule);
        }
    }

    Ok(registry)
}

fn validate_root_path(path: &str) -> Result<(), String> {
    if !Path::new(path).exists() {
        return Err(format!("path '{}' does not exist", path));
    }
    Ok(())
}

fn validate_rules_path(rules: Option<&str>) -> Result<(), String> {
    if let Some(rules_path) = rules {
        let path = Path::new(rules_path);
        if !path.exists() {
            return Err(format!("rules path '{}' does not exist", rules_path));
        }
    }

    Ok(())
}

/// Returns `true` if the rule ID belongs to the PQ audit rule set.
fn is_pq_rule_id(id: &str) -> bool {
    id.contains("pq-vulnerable")
        || id.contains("hardcoded-crypto-algorithm")
        || id == "config/dockerfile-insecure-tls-env"
}

fn collect_changed_targets(path: &str, changed: bool) -> Result<Option<Vec<PathBuf>>, String> {
    if !changed {
        return Ok(None);
    }

    let scan_root = Path::new(path);
    let files =
        changed_files(scan_root).map_err(|e| format!("failed to resolve changed files: {}", e))?;
    Ok(Some(files))
}

fn count_secret_files(scan_path: &Path) -> usize {
    if scan_path.is_file() {
        return 1;
    }

    ignore::WalkBuilder::new(scan_path)
        .hidden(true)
        .git_ignore(true)
        .build()
        .filter_map(|entry| entry.ok())
        .filter(|entry| entry.file_type().is_some_and(|ft| ft.is_file()))
        .count()
}