Skip to main content

allow_core/
finding.rs

1use crate::{CargoAllowError, LedgerProvenance, normalize_path};
2use std::fmt;
3use std::path::PathBuf;
4use std::str::FromStr;
5
6pub const STRUCTURAL_IDENTITY_SCHEMA_ID: &str = "cargo-allow.structural-identity.v1";
7
8#[derive(Debug, Clone, PartialEq, Eq)]
9pub struct Span {
10    pub line: u32,
11    pub column: u32,
12}
13
14#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
15pub enum FindingKind {
16    Panic,
17    Unsafe,
18    LintException,
19    NonRustFile,
20    GeneratedCode,
21    PolicyException,
22}
23
24impl FindingKind {
25    pub const ALL: &[Self] = &[
26        Self::Panic,
27        Self::Unsafe,
28        Self::LintException,
29        Self::NonRustFile,
30        Self::GeneratedCode,
31        Self::PolicyException,
32    ];
33
34    pub fn as_str(self) -> &'static str {
35        match self {
36            Self::Panic => "panic",
37            Self::Unsafe => "unsafe",
38            Self::LintException => "lint_exception",
39            Self::NonRustFile => "non_rust_file",
40            Self::GeneratedCode => "generated_code",
41            Self::PolicyException => "policy_exception",
42        }
43    }
44
45    pub fn requires_source_selector_identity(self) -> bool {
46        matches!(self, Self::Panic | Self::Unsafe | Self::LintException)
47    }
48}
49
50impl fmt::Display for FindingKind {
51    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
52        write!(f, "{}", self.as_str())
53    }
54}
55
56impl FromStr for FindingKind {
57    type Err = CargoAllowError;
58
59    fn from_str(s: &str) -> Result<Self, Self::Err> {
60        match s.trim() {
61            "panic" | "panic_family" | "panic-family" | "indexing" => Ok(Self::Panic),
62            "unsafe" => Ok(Self::Unsafe),
63            "lint_exception" | "lint-exception" | "clippy" | "allow_attribute"
64            | "allow-attribute" | "expect_attribute" | "expect-attribute" => {
65                Ok(Self::LintException)
66            }
67            "non_rust_file" | "non-rust-file" | "non_rust" | "non-rust" | "file" => {
68                Ok(Self::NonRustFile)
69            }
70            "generated_code" | "generated-code" | "generated" => Ok(Self::GeneratedCode),
71            "policy_exception" | "policy-exception" | "policy" => Ok(Self::PolicyException),
72            other => Err(CargoAllowError::new(format!(
73                "unsupported finding kind `{other}`"
74            ))),
75        }
76    }
77}
78
79/// Maximum length (bytes) of any source-derived string field in a
80/// [`StructuralIdentity`]. Caps the DoS / noisy-diff surface from a scanned
81/// file with a megabyte-long identifier (#1919). Generous enough for realistic
82/// Rust paths/identifiers (e.g. deeply-qualified module paths), small enough
83/// that an artifact cannot be inflated by a single field.
84pub const MAX_IDENTITY_FIELD_LEN: usize = 512;
85
86#[derive(Debug, Clone, PartialEq, Eq)]
87pub struct StructuralIdentity {
88    pub language: String,
89    pub crate_name: Option<String>,
90    pub module: Option<String>,
91    pub container: Option<String>,
92    pub ast_kind: String,
93    pub symbol: Option<String>,
94    pub callee: Option<String>,
95    pub macro_name: Option<String>,
96    pub lint: Option<String>,
97    pub receiver_fingerprint: Option<String>,
98    pub target_fingerprint: Option<String>,
99    pub normalized_snippet_hash: Option<String>,
100    pub line_hint: Option<u32>,
101    pub column_hint: Option<u32>,
102}
103
104impl StructuralIdentity {
105    pub fn schema_id() -> &'static str {
106        STRUCTURAL_IDENTITY_SCHEMA_ID
107    }
108
109    pub fn new(language: impl Into<String>, ast_kind: impl Into<String>) -> Self {
110        Self {
111            language: language.into(),
112            crate_name: None,
113            module: None,
114            container: None,
115            ast_kind: ast_kind.into(),
116            symbol: None,
117            callee: None,
118            macro_name: None,
119            lint: None,
120            receiver_fingerprint: None,
121            target_fingerprint: None,
122            normalized_snippet_hash: None,
123            line_hint: None,
124            column_hint: None,
125        }
126    }
127
128    /// Cap every source-derived string field at [`MAX_IDENTITY_FIELD_LEN`] so a
129    /// scanned file with a megabyte-long identifier cannot inflate report/receipt
130    /// artifacts unboundedly (DoS / noisy-diff surface) (#1919). Applied in place
131    /// at the finding-construction choke point before the identity reaches any
132    /// artifact. Hashes (e.g. `normalized_snippet_hash`) are already fixed-width
133    /// and excluded.
134    pub fn truncate_in_place(&mut self) {
135        let cap_opt = |s: &mut Option<String>| {
136            if let Some(value) = s {
137                truncate_identity_field(value);
138            }
139        };
140        let cap_str = |s: &mut String| {
141            truncate_identity_field(s);
142        };
143        cap_str(&mut self.language);
144        cap_opt(&mut self.crate_name);
145        cap_opt(&mut self.module);
146        cap_opt(&mut self.container);
147        cap_str(&mut self.ast_kind);
148        cap_opt(&mut self.symbol);
149        cap_opt(&mut self.callee);
150        cap_opt(&mut self.macro_name);
151        cap_opt(&mut self.lint);
152        cap_opt(&mut self.receiver_fingerprint);
153        cap_opt(&mut self.target_fingerprint);
154    }
155
156    /// Redact the source-text-bearing identity fields (`symbol`, `callee`,
157    /// `container`, `module`, `macro_name`, `lint`) by clearing them, while
158    /// preserving the structural anchors (`normalized_snippet_hash`,
159    /// fingerprints, `ast_kind`, `line_hint`, `column_hint`) that matching
160    /// relies on. Opt-in for CI artifacts where source-text-derived fields are
161    /// an info-leak surface (#1920).
162    pub fn redact_source_text_fields(&mut self) {
163        self.symbol = None;
164        self.callee = None;
165        self.container = None;
166        self.module = None;
167        self.macro_name = None;
168        self.lint = None;
169    }
170
171    pub fn stable_key(&self) -> String {
172        stable_identity_key_from_parts(self.stable_key_parts())
173    }
174
175    pub fn stable_key_parts(&self) -> Vec<(&'static str, String)> {
176        vec![
177            ("language", self.language.clone()),
178            (
179                "crate_name",
180                self.crate_name
181                    .as_deref()
182                    .map(str::trim)
183                    .unwrap_or_default()
184                    .to_string(),
185            ),
186            ("module", self.module.clone().unwrap_or_default()),
187            ("container", self.container.clone().unwrap_or_default()),
188            ("ast_kind", self.ast_kind.clone()),
189            ("symbol", self.symbol.clone().unwrap_or_default()),
190            ("callee", self.callee.clone().unwrap_or_default()),
191            ("macro_name", self.macro_name.clone().unwrap_or_default()),
192            ("lint", self.lint.clone().unwrap_or_default()),
193            (
194                "receiver_fingerprint",
195                self.receiver_fingerprint.clone().unwrap_or_default(),
196            ),
197            (
198                "target_fingerprint",
199                self.target_fingerprint.clone().unwrap_or_default(),
200            ),
201            (
202                "normalized_snippet_hash",
203                self.normalized_snippet_hash.clone().unwrap_or_default(),
204            ),
205        ]
206    }
207}
208
209fn truncate_identity_field(value: &mut String) {
210    if value.len() <= MAX_IDENTITY_FIELD_LEN {
211        return;
212    }
213    let mut end = MAX_IDENTITY_FIELD_LEN;
214    while !value.is_char_boundary(end) {
215        end -= 1;
216    }
217    value.truncate(end);
218}
219
220#[derive(Debug, Clone, PartialEq, Eq)]
221pub struct Finding {
222    pub kind: FindingKind,
223    pub family: Option<String>,
224    pub path: PathBuf,
225    pub span: Option<Span>,
226    pub identity: StructuralIdentity,
227    pub message: String,
228    pub ledger: Option<LedgerProvenance>,
229}
230
231impl Finding {
232    pub fn source_package_name(&self) -> Option<&str> {
233        self.identity
234            .crate_name
235            .as_deref()
236            .map(str::trim)
237            .filter(|name| !name.is_empty())
238    }
239}
240
241pub fn finding_identity_key(finding: &Finding) -> String {
242    let mut parts = vec![
243        ("kind", finding.kind.as_str().to_string()),
244        ("family", finding.family.clone().unwrap_or_default()),
245        ("path", normalize_path(&finding.path)),
246    ];
247    parts.extend(finding.identity.stable_key_parts());
248    stable_identity_key_from_parts(parts)
249}
250
251fn stable_identity_key_from_parts(parts: Vec<(&'static str, String)>) -> String {
252    parts
253        .into_iter()
254        .map(|(name, value)| format!("{name}:{}:{value}", value.len()))
255        .collect::<Vec<_>>()
256        .join("|")
257}
258
259#[cfg(test)]
260#[path = "finding_tests.rs"]
261mod tests;