Skip to main content

cargo_frisk/
lib.rs

1//! `cargo frisk` — see what you are *actually* shipping to crates.io.
2//!
3//! Secret scanners check what git tracks. `cargo frisk` checks what cargo ships,
4//! and those are not the same set of files. The product is the diff between the
5//! packaged `.crate` tarball and `git ls-files`; content inspection is an
6//! annotation on that diff, not the headline.
7//!
8//! ```no_run
9//! use cargo_frisk::{run, Options};
10//!
11//! let outcome = run(&Options::default())?;
12//! println!("{} findings", outcome.findings().count());
13//! # Ok::<(), anyhow::Error>(())
14//! ```
15
16use std::fmt;
17use std::path::PathBuf;
18
19use serde::{Deserialize, Serialize};
20
21pub mod archive;
22pub mod cli;
23pub mod config;
24pub mod diff;
25pub mod gitset;
26pub mod package;
27pub mod report;
28pub mod rules;
29pub mod scan;
30
31mod run;
32
33pub use run::run;
34
35/// How bad a finding is.
36///
37/// The ordering is meaningful: `Low < Medium < High < Critical`. A run fails
38/// when any finding is at or above the configured [`Threshold`].
39#[derive(
40    Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize, Default, Hash,
41)]
42#[serde(rename_all = "lowercase")]
43pub enum Severity {
44    Low,
45    #[default]
46    Medium,
47    High,
48    Critical,
49}
50
51impl Severity {
52    /// One step down the ladder. `Low` is the floor.
53    pub fn downgrade(self) -> Self {
54        match self {
55            Severity::Critical => Severity::High,
56            Severity::High => Severity::Medium,
57            Severity::Medium | Severity::Low => Severity::Low,
58        }
59    }
60
61    pub fn as_str(self) -> &'static str {
62        match self {
63            Severity::Low => "low",
64            Severity::Medium => "medium",
65            Severity::High => "high",
66            Severity::Critical => "critical",
67        }
68    }
69
70    /// SARIF `level` for this severity. SARIF only has note/warning/error.
71    pub fn sarif_level(self) -> &'static str {
72        match self {
73            Severity::Low => "note",
74            Severity::Medium | Severity::High => "warning",
75            Severity::Critical => "error",
76        }
77    }
78}
79
80impl fmt::Display for Severity {
81    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
82        f.write_str(self.as_str())
83    }
84}
85
86impl std::str::FromStr for Severity {
87    type Err = String;
88
89    fn from_str(s: &str) -> Result<Self, Self::Err> {
90        match s.to_ascii_lowercase().as_str() {
91            "low" => Ok(Severity::Low),
92            "medium" | "med" => Ok(Severity::Medium),
93            "high" => Ok(Severity::High),
94            "critical" | "crit" => Ok(Severity::Critical),
95            other => Err(format!(
96                "unknown severity `{other}` (expected low, medium, high or critical)"
97            )),
98        }
99    }
100}
101
102/// The severity at or above which the run fails with exit code 1.
103///
104/// `Threshold::Never` never fails, which is how you run frisk purely as a
105/// reporter in a pipeline that only cares about the SARIF upload.
106#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
107#[serde(rename_all = "lowercase")]
108pub enum Threshold {
109    At(Severity),
110    Never,
111}
112
113impl Default for Threshold {
114    fn default() -> Self {
115        // False positives are the main product risk. Fail on the strictest
116        // bucket only; everything below it warns.
117        Threshold::At(Severity::Critical)
118    }
119}
120
121impl Threshold {
122    pub fn is_met_by(self, severity: Severity) -> bool {
123        match self {
124            Threshold::At(min) => severity >= min,
125            Threshold::Never => false,
126        }
127    }
128
129    pub fn as_str(self) -> &'static str {
130        match self {
131            Threshold::At(s) => s.as_str(),
132            Threshold::Never => "none",
133        }
134    }
135}
136
137impl std::str::FromStr for Threshold {
138    type Err = String;
139
140    fn from_str(s: &str) -> Result<Self, Self::Err> {
141        match s.to_ascii_lowercase().as_str() {
142            "none" | "never" | "off" => Ok(Threshold::Never),
143            other => other.parse().map(Threshold::At),
144        }
145    }
146}
147
148/// Which half of the tool produced a finding.
149#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
150#[serde(rename_all = "kebab-case")]
151pub enum FindingKind {
152    /// The packaged file set disagrees with the git-tracked file set.
153    Diff,
154    /// A packaged file's path or contents matched a rule.
155    Secret,
156}
157
158impl FindingKind {
159    pub fn as_str(self) -> &'static str {
160        match self {
161            FindingKind::Diff => "diff",
162            FindingKind::Secret => "secret",
163        }
164    }
165}
166
167/// One reportable thing about one packaged file.
168#[derive(Debug, Clone, Serialize, Deserialize)]
169pub struct Finding {
170    /// Stable rule identifier — usable in `ignore-rules` and `frisk:allow(...)`.
171    pub rule: String,
172    pub kind: FindingKind,
173    pub severity: Severity,
174    /// Severity before any downgrade was applied.
175    pub original_severity: Severity,
176    /// Path inside the package, with the `<name>-<version>/` prefix stripped.
177    pub path: String,
178    /// 1-indexed line, for content matches.
179    pub line: Option<usize>,
180    pub message: String,
181    /// Masked evidence. Never the raw secret.
182    pub evidence: Option<String>,
183    /// Why the severity was adjusted, if it was.
184    pub notes: Vec<String>,
185}
186
187/// A packaged file we deliberately did not scan, and why.
188#[derive(Debug, Clone, Serialize, Deserialize)]
189pub struct Unscanned {
190    pub path: String,
191    pub size: u64,
192    pub reason: UnscannedReason,
193}
194
195#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
196#[serde(rename_all = "kebab-case")]
197pub enum UnscannedReason {
198    /// NUL byte in the first 8 KB.
199    Binary,
200    /// Larger than the per-file scan cap.
201    TooLarge,
202}
203
204impl UnscannedReason {
205    pub fn as_str(self) -> &'static str {
206        match self {
207            UnscannedReason::Binary => "binary",
208            UnscannedReason::TooLarge => "too-large",
209        }
210    }
211}
212
213/// The result of frisking one package.
214#[derive(Debug, Clone, Serialize, Deserialize)]
215pub struct PackageReport {
216    pub name: String,
217    pub version: String,
218    /// The package directory relative to the workspace root, `/`-terminated,
219    /// or empty for a root package. SARIF locations need repository-relative
220    /// URIs for GitHub to annotate the right line of the right file.
221    pub relative_root: String,
222    /// Total uncompressed size of the packaged files, in bytes.
223    pub total_size: u64,
224    pub git: GitState,
225    /// The threshold in force for this package. Workspace members can disagree,
226    /// so it is resolved per package rather than per run.
227    pub threshold: Threshold,
228    pub diff: diff::DiffSummary,
229    pub findings: Vec<Finding>,
230    pub unscanned: Vec<Unscanned>,
231    pub warnings: Vec<String>,
232}
233
234impl PackageReport {
235    /// How many files the tarball actually contains.
236    pub fn file_count(&self) -> usize {
237        self.diff.both.len() + self.diff.shipped_not_tracked.len() + self.diff.cargo_generated.len()
238    }
239
240    /// True when at least one of this package's findings meets its threshold.
241    pub fn should_fail(&self) -> bool {
242        self.findings
243            .iter()
244            .any(|f| self.threshold.is_met_by(f.severity))
245    }
246}
247
248/// Whether we had a git file set to diff against.
249#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
250#[serde(rename_all = "kebab-case")]
251pub enum GitState {
252    /// `git ls-files` succeeded; the diff is meaningful.
253    Tracked,
254    /// Not a git repository, or git is unavailable. We degrade to a listing.
255    Unavailable,
256}
257
258/// Everything a single `cargo frisk` invocation produced.
259#[derive(Debug, Clone, Serialize, Deserialize)]
260pub struct Outcome {
261    pub packages: Vec<PackageReport>,
262}
263
264impl Outcome {
265    pub fn findings(&self) -> impl Iterator<Item = &Finding> {
266        self.packages.iter().flat_map(|p| p.findings.iter())
267    }
268
269    /// The highest severity observed, if anything was found at all.
270    pub fn max_severity(&self) -> Option<Severity> {
271        self.findings().map(|f| f.severity).max()
272    }
273
274    /// True when any package has a finding at or above its own threshold.
275    pub fn should_fail(&self) -> bool {
276        self.packages.iter().any(PackageReport::should_fail)
277    }
278
279    /// The process exit code this outcome implies. Tool errors are exit 2 and
280    /// are surfaced as an `Err` from [`run`], never through here.
281    pub fn exit_code(&self) -> i32 {
282        i32::from(self.should_fail())
283    }
284}
285
286/// What to frisk and how.
287#[derive(Debug, Clone, Default)]
288pub struct Options {
289    /// Path to a `Cargo.toml`. Defaults to discovery from the current directory.
290    pub manifest_path: Option<PathBuf>,
291    /// Restrict to these package names. Empty means "the default selection".
292    pub packages: Vec<String>,
293    /// Select every workspace member.
294    pub workspace: bool,
295    /// Override the configured fail threshold.
296    pub fail_on: Option<Threshold>,
297    /// Skip content and path rules entirely; report the diff only.
298    pub no_scan: bool,
299    /// Additional rules in gitleaks TOML format.
300    pub gitleaks_config: Option<PathBuf>,
301    /// Rule ids to drop, on top of anything in `[package.metadata.frisk]`.
302    pub ignore_rules: Vec<String>,
303    /// Globs to drop, on top of anything in `[package.metadata.frisk]`.
304    pub ignore_paths: Vec<String>,
305    /// Per-file scan cap in bytes. Files above this are reported as unscanned.
306    pub max_file_size: Option<u64>,
307    /// Print the `cargo package` output as it happens.
308    pub verbose: bool,
309}
310
311/// Default per-file scan cap: 5 MB.
312pub const DEFAULT_MAX_FILE_SIZE: u64 = 5 * 1024 * 1024;
313
314#[cfg(test)]
315mod tests {
316    use super::*;
317
318    #[test]
319    fn severity_orders_low_to_critical() {
320        assert!(Severity::Low < Severity::Medium);
321        assert!(Severity::Medium < Severity::High);
322        assert!(Severity::High < Severity::Critical);
323    }
324
325    #[test]
326    fn downgrade_bottoms_out_at_low() {
327        assert_eq!(Severity::Critical.downgrade(), Severity::High);
328        assert_eq!(Severity::Low.downgrade(), Severity::Low);
329    }
330
331    #[test]
332    fn threshold_never_never_fails() {
333        assert!(!Threshold::Never.is_met_by(Severity::Critical));
334        assert!(Threshold::At(Severity::Critical).is_met_by(Severity::Critical));
335        assert!(!Threshold::At(Severity::Critical).is_met_by(Severity::High));
336    }
337
338    #[test]
339    fn threshold_parses_none() {
340        assert_eq!("none".parse::<Threshold>().unwrap(), Threshold::Never);
341        assert_eq!(
342            "high".parse::<Threshold>().unwrap(),
343            Threshold::At(Severity::High)
344        );
345        assert!("nope".parse::<Threshold>().is_err());
346    }
347}