Skip to main content

fallow_security/
stable_id.rs

1//! Line-independent identity for security candidates.
2//!
3//! The location id (`finding_id`) hashes the rule, path, line and column, so
4//! an edit above a sink changes it. The stable id hashes the rule, the
5//! project-relative path and a line-free name of the finding instead. A
6//! stored verdict therefore keeps its candidate after unrelated edits.
7//!
8//! The name of a finding depends on its kind:
9//!
10//! - A sink in script code: the normalized source text of the exact sink
11//!   expression. The extractor records its byte span, and the caller turns
12//!   the span into text.
13//! - A hard-coded secret: the binding name and the detector signal (the
14//!   provider family, or `entropy`). The secret value is never hashed.
15//! - A client-server leak: the project-relative paths of the first and the
16//!   last trace hop, and the names of the env secrets that the server module
17//!   reads.
18//!
19//! A finding without such a name gets no stable id. Examples are a sink in
20//! template markup and a sink whose span does not parse.
21//!
22//! The id has the form `sec1:<16 hex digits>`. When several candidates in one
23//! file have the same hash input, they are sorted by line and column. The
24//! first one keeps the base id. The candidate at sorted position `k` gets the
25//! suffix `~k`. This is the same tiebreak as the dead-code finding ids.
26//! Candidates that an inline comment suppresses keep their position in this
27//! order, so a suppression does not move an id onto another candidate.
28
29use std::path::Path;
30
31use fallow_types::results::{SecurityFinding, SecurityFindingKind};
32use fallow_types::security_stable_id::SecurityStableIdInput;
33use rustc_hash::FxHashMap;
34
35use crate::HARDCODED_SECRET_CATEGORY_ID;
36
37/// The `category` string distinguishing the server-only-import sink from the
38/// secret-leak sink. Both carry the `ClientServerLeak` kind, so the category is
39/// the only thing that tells them apart. Matches the constant in
40/// `crates/core/src/analyze/security/mod.rs`.
41const SERVER_ONLY_CATEGORY: &str = "server-only-import";
42
43/// The stable rule identifier for a finding.
44///
45/// The secret-leak `ClientServerLeak` keeps its bespoke id; the server-only
46/// variant gets `security/server-only-import` so a SARIF consumer tells
47/// "reaches server-only code" apart from "reads a secret". Each `TaintedSink`
48/// category gets `security/<category>` so candidates group per CWE class.
49#[must_use]
50pub fn security_rule_id(finding: &SecurityFinding) -> String {
51    match finding.kind {
52        SecurityFindingKind::ClientServerLeak
53            if finding.category.as_deref() == Some(SERVER_ONLY_CATEGORY) =>
54        {
55            "security/server-only-import".to_owned()
56        }
57        SecurityFindingKind::ClientServerLeak => "security/client-server-leak".to_owned(),
58        SecurityFindingKind::TaintedSink => format!(
59            "security/{}",
60            finding.category.as_deref().unwrap_or("tainted-sink")
61        ),
62    }
63}
64
65/// The version prefix of every stable security id. A change to the hash
66/// inputs moves this prefix, so an old id never matches a new candidate.
67pub const STABLE_SECURITY_ID_SCHEME: &str = "sec1";
68
69/// The project-relative form of `path`, with `/` separators.
70fn relative_path(path: &Path, root: &Path) -> String {
71    path.strip_prefix(root)
72        .unwrap_or(path)
73        .to_string_lossy()
74        .replace('\\', "/")
75}
76
77/// The line-free name of `finding`, or `None` when the finding has none.
78///
79/// `sink_text` gets the absolute anchor path and the byte span of the sink,
80/// and returns the normalized sink text.
81fn finding_name(
82    finding: &SecurityFinding,
83    root: &Path,
84    sink_text: &mut impl FnMut(&Path, u32, u32) -> Option<String>,
85) -> Option<String> {
86    if finding.kind == SecurityFindingKind::ClientServerLeak {
87        let first = finding.trace.first()?;
88        let last = finding.trace.last()?;
89        let mut name = format!(
90            "{}\0{}",
91            relative_path(&first.path, root),
92            relative_path(&last.path, root)
93        );
94        if let Some(SecurityStableIdInput::SecretReads(reads)) = &finding.stable_id_input {
95            for read in reads {
96                name.push('\0');
97                name.push_str(read);
98            }
99        }
100        return Some(name);
101    }
102    match finding.stable_id_input.as_ref()? {
103        SecurityStableIdInput::SecretSignal(signal)
104            if finding.category.as_deref() == Some(HARDCODED_SECRET_CATEGORY_ID) =>
105        {
106            let binding = finding.candidate.sink.callee.as_deref()?;
107            Some(format!("{binding}\0{signal}"))
108        }
109        SecurityStableIdInput::SecretSignal(_) | SecurityStableIdInput::SecretReads(_) => None,
110        &SecurityStableIdInput::SinkSpan { start, end } => {
111            let absolute = if finding.path.is_absolute() {
112                finding.path.clone()
113            } else {
114                root.join(&finding.path)
115            };
116            sink_text(&absolute, start, end)
117        }
118    }
119}
120
121/// The base stable id, without a tiebreak suffix.
122#[must_use]
123pub fn stable_security_base_id(rule_id: &str, relative_path: &str, name: &str) -> String {
124    let hash = fallow_types::identity::fnv1a64_parts(&[
125        STABLE_SECURITY_ID_SCHEME,
126        rule_id,
127        relative_path,
128        name,
129    ]);
130    format!("{STABLE_SECURITY_ID_SCHEME}:{hash}")
131}
132
133/// One member of a group of candidates with the same base id.
134struct GroupMember {
135    line: u32,
136    col: u32,
137    /// The index in `findings`, or `None` for a suppressed candidate.
138    index: Option<usize>,
139}
140
141/// Set the `stable_finding_id` of each finding in `findings`.
142///
143/// `suppressed` holds the candidates that an inline comment hides. They get no
144/// id, but they keep their tiebreak position, so the id of each other finding
145/// does not depend on a suppression.
146///
147/// `sink_text` gets the absolute anchor path and the byte span of a sink, and
148/// returns its normalized source text, or `None` when that text is not known.
149/// A finding without a line-free name keeps `stable_finding_id: None`.
150pub fn stamp_stable_security_finding_ids(
151    findings: &mut [SecurityFinding],
152    suppressed: &[SecurityFinding],
153    root: &Path,
154    mut sink_text: impl FnMut(&Path, u32, u32) -> Option<String>,
155) {
156    let mut groups: FxHashMap<String, Vec<GroupMember>> = FxHashMap::default();
157    let mut base_id = |finding: &SecurityFinding| {
158        let name = finding_name(finding, root, &mut sink_text)?;
159        Some(stable_security_base_id(
160            &security_rule_id(finding),
161            &relative_path(&finding.path, root),
162            &name,
163        ))
164    };
165
166    for (index, finding) in findings.iter_mut().enumerate() {
167        finding.stable_finding_id = None;
168        if let Some(base) = base_id(finding) {
169            groups.entry(base).or_default().push(GroupMember {
170                line: finding.line,
171                col: finding.col,
172                index: Some(index),
173            });
174        }
175    }
176    for finding in suppressed {
177        if let Some(base) = base_id(finding) {
178            groups.entry(base).or_default().push(GroupMember {
179                line: finding.line,
180                col: finding.col,
181                index: None,
182            });
183        }
184    }
185
186    for (base, mut members) in groups {
187        members.sort_by_key(|member| (member.line, member.col, member.index));
188        for (ordinal, member) in members.into_iter().enumerate() {
189            let Some(index) = member.index else {
190                continue;
191            };
192            findings[index].stable_finding_id = Some(if ordinal == 0 {
193                base.clone()
194            } else {
195                format!("{base}~{ordinal}")
196            });
197        }
198    }
199}
200
201#[cfg(test)]
202#[expect(
203    clippy::expect_used,
204    reason = "fixture setup asserts its own invariants directly"
205)]
206mod tests {
207    use std::path::{Path, PathBuf};
208
209    use fallow_types::results::{
210        SecurityCandidate, SecurityCandidateBoundary, SecurityCandidateSink, SecurityFinding,
211        SecurityFindingKind, SecuritySeverity, TraceHop, TraceHopRole,
212    };
213
214    use fallow_types::security_stable_id::SecurityStableIdInput;
215
216    use super::stamp_stable_security_finding_ids;
217
218    fn finding(line: u32, input: Option<SecurityStableIdInput>, category: &str) -> SecurityFinding {
219        let path = PathBuf::from("/repo/src/a.js");
220        SecurityFinding {
221            finding_id: String::new(),
222            stable_finding_id: None,
223            stable_id_input: input,
224            kind: SecurityFindingKind::TaintedSink,
225            category: Some(category.to_owned()),
226            cwe: None,
227            path: path.clone(),
228            line,
229            col: 0,
230            evidence: String::new(),
231            source_backed: false,
232            source_read: None,
233            severity: SecuritySeverity::Low,
234            trace: Vec::new(),
235            actions: Vec::new(),
236            dead_code: None,
237            reachability: None,
238            candidate: SecurityCandidate {
239                source_kind: None,
240                sink: SecurityCandidateSink {
241                    path,
242                    line,
243                    col: 0,
244                    category: Some(category.to_owned()),
245                    cwe: None,
246                    callee: Some("API_KEY".to_owned()),
247                    url_shape: None,
248                },
249                boundary: SecurityCandidateBoundary::default(),
250                network: None,
251            },
252            taint_flow: None,
253            runtime: None,
254            attack_surface: None,
255        }
256    }
257
258    const fn span(start: u32, end: u32) -> Option<SecurityStableIdInput> {
259        let input = SecurityStableIdInput::SinkSpan { start, end };
260        if start < end { Some(input) } else { None }
261    }
262
263    /// Stamp `findings` with a sink text that is the span offsets, or the
264    /// fixed `text` when it is given.
265    fn stamp(findings: &mut [SecurityFinding], text: Option<&str>) {
266        stamp_stable_security_finding_ids(findings, &[], Path::new("/repo"), |path, start, end| {
267            assert_eq!(path, Path::new("/repo/src/a.js"));
268            Some(text.map_or_else(|| format!("{start}..{end}"), str::to_owned))
269        });
270    }
271
272    fn id(finding: &SecurityFinding) -> String {
273        finding.stable_finding_id.clone().expect("stable id")
274    }
275
276    #[test]
277    fn identical_sinks_get_ordinals_in_source_order() {
278        let mut findings = vec![
279            finding(2, span(10, 19), "command-injection"),
280            finding(1, span(0, 9), "command-injection"),
281        ];
282        stamp(&mut findings, Some("exec ( cmd )"));
283        let first = id(&findings[1]);
284        assert!(first.starts_with("sec1:"));
285        assert_eq!(first.len(), "sec1:".len() + 16);
286        assert_eq!(id(&findings[0]), format!("{first}~1"));
287    }
288
289    #[test]
290    fn a_suppressed_sink_keeps_its_ordinal() {
291        let suppressed = vec![finding(1, span(0, 9), "command-injection")];
292        let mut findings = vec![finding(2, span(10, 19), "command-injection")];
293        stamp_stable_security_finding_ids(
294            &mut findings,
295            &suppressed,
296            Path::new("/repo"),
297            |_, _, _| Some("exec ( cmd )".to_owned()),
298        );
299        let mut alone = vec![finding(1, span(0, 9), "command-injection")];
300        stamp(&mut alone, Some("exec ( cmd )"));
301        assert_eq!(id(&findings[0]), format!("{}~1", id(&alone[0])));
302    }
303
304    #[test]
305    fn the_id_follows_the_sink_text_and_not_the_line() {
306        let mut before = vec![finding(1, span(0, 9), "command-injection")];
307        stamp(&mut before, Some("exec ( cmd )"));
308        let mut moved = vec![finding(7, span(80, 89), "command-injection")];
309        stamp(&mut moved, Some("exec ( cmd )"));
310        let mut changed = vec![finding(1, span(0, 11), "command-injection")];
311        stamp(&mut changed, Some("exec ( other )"));
312        assert_eq!(id(&before[0]), id(&moved[0]));
313        assert_ne!(id(&before[0]), id(&changed[0]));
314    }
315
316    #[test]
317    fn a_finding_without_known_sink_text_gets_no_id() {
318        let mut findings = vec![
319            finding(1, None, "dangerous-html"),
320            finding(2, span(0, 9), "dangerous-html"),
321        ];
322        stamp_stable_security_finding_ids(&mut findings, &[], Path::new("/repo"), |_, _, _| None);
323        assert_eq!(findings[0].stable_finding_id, None);
324        assert_eq!(findings[1].stable_finding_id, None);
325    }
326
327    #[test]
328    fn a_hardcoded_secret_hashes_the_binding_and_the_signal() {
329        let secret = |signal: &str| {
330            let input = Some(SecurityStableIdInput::SecretSignal(signal.to_owned()));
331            let mut findings = vec![finding(1, input, "hardcoded-secret")];
332            stamp_stable_security_finding_ids(&mut findings, &[], Path::new("/repo"), |_, _, _| {
333                panic!("a secret never reads the source")
334            });
335            id(&findings[0])
336        };
337        assert_eq!(secret("entropy"), secret("entropy"));
338        assert_ne!(secret("entropy"), secret("Stripe key"));
339    }
340
341    #[test]
342    fn a_client_server_leak_hashes_the_first_and_last_trace_hop() {
343        let leak = |middle: &str| {
344            let hop =
345                |path: &str| TraceHop::new(PathBuf::from(path), 1, 0, TraceHopRole::Intermediate);
346            let mut finding = finding(1, None, "client-server-leak");
347            finding.kind = SecurityFindingKind::ClientServerLeak;
348            finding.trace = vec![
349                hop("/repo/src/a.js"),
350                hop(middle),
351                hop("/repo/src/secret.js"),
352            ];
353            let mut findings = vec![finding];
354            stamp(&mut findings, None);
355            id(&findings[0])
356        };
357        assert_eq!(leak("/repo/src/b.js"), leak("/repo/src/c.js"));
358    }
359
360    #[test]
361    fn a_client_server_leak_hashes_the_secret_names() {
362        let leak = |reads: &[&str]| {
363            let hop =
364                |path: &str| TraceHop::new(PathBuf::from(path), 1, 0, TraceHopRole::Intermediate);
365            let input = SecurityStableIdInput::SecretReads(
366                reads.iter().map(|read| (*read).to_owned()).collect(),
367            );
368            let mut finding = finding(1, Some(input), "client-server-leak");
369            finding.kind = SecurityFindingKind::ClientServerLeak;
370            finding.trace = vec![hop("/repo/src/a.js"), hop("/repo/src/secret.js")];
371            let mut findings = vec![finding];
372            stamp(&mut findings, None);
373            id(&findings[0])
374        };
375        let label = leak(&["process.env.BUILD_LABEL"]);
376        assert_eq!(label, leak(&["process.env.BUILD_LABEL"]));
377        assert_ne!(label, leak(&["process.env.DATABASE_PASSWORD"]));
378    }
379}