Skip to main content

fallow_security/
identity.rs

1//! Stable identifiers for security candidates.
2//!
3//! JSON, SARIF, and the viz Security lens all join on these two strings, so the
4//! rule id and the per-finding correlation id live here rather than in any one
5//! consumer. A second implementation would let the surfaces drift apart.
6
7use std::path::Path;
8
9use fallow_types::results::{SecurityFinding, SecurityFindingKind};
10
11/// The `category` string distinguishing the server-only-import sink from the
12/// secret-leak sink. Both carry the `ClientServerLeak` kind, so the category is
13/// the only thing that tells them apart. Matches the constant in
14/// `crates/core/src/analyze/security/mod.rs`.
15const SERVER_ONLY_CATEGORY: &str = "server-only-import";
16
17/// The stable rule identifier for a finding.
18///
19/// The secret-leak `ClientServerLeak` keeps its bespoke id; the server-only
20/// variant gets `security/server-only-import` so a SARIF consumer tells
21/// "reaches server-only code" apart from "reads a secret". Each `TaintedSink`
22/// category gets `security/<category>` so candidates group per CWE class.
23#[must_use]
24pub fn security_rule_id(finding: &SecurityFinding) -> String {
25    match finding.kind {
26        SecurityFindingKind::ClientServerLeak
27            if finding.category.as_deref() == Some(SERVER_ONLY_CATEGORY) =>
28        {
29            "security/server-only-import".to_owned()
30        }
31        SecurityFindingKind::ClientServerLeak => "security/client-server-leak".to_owned(),
32        SecurityFindingKind::TaintedSink => format!(
33            "security/{}",
34            finding.category.as_deref().unwrap_or("tainted-sink")
35        ),
36    }
37}
38
39/// The stable per-finding correlation id: an FNV-1a hex digest of
40/// `rule:path:line:col`.
41///
42/// This is the single source of truth for both the JSON `finding_id` field and
43/// the SARIF `partialFingerprints` value, so an agent can join the two and they
44/// never drift. The digest is computed on the project-relative path, so callers
45/// must pass the relativized path (issue #900).
46#[must_use]
47pub fn security_finding_id(finding: &SecurityFinding, relative_path: &Path) -> String {
48    let fingerprint = format!(
49        "{}:{}:{}:{}",
50        security_rule_id(finding),
51        relative_path.to_string_lossy().replace('\\', "/"),
52        finding.line,
53        finding.col,
54    );
55    fallow_types::identity::fnv1a64_hex(fingerprint.as_bytes())
56}
57
58/// Set the `finding_id` and the `stable_finding_id` of each finding in
59/// `findings`.
60///
61/// The shared analysis pipeline calls this once, directly after detection, so
62/// the CLI, MCP and the LSP all read the same id. A path
63/// under `root` is made root-relative before the digest. A path outside `root`
64/// stays as it is, as in the CLI JSON output.
65///
66/// `suppressed` holds the candidates that an inline comment hides. They get
67/// no id, but they keep their tiebreak position for the stable id.
68///
69/// `sink_text` gets the absolute anchor path and the byte span of a sink, and
70/// returns the normalized source text of the sink expression. The stable id
71/// hashes that text. `None` leaves the finding without a stable id.
72pub fn stamp_security_finding_ids(
73    findings: &mut [SecurityFinding],
74    suppressed: &[SecurityFinding],
75    root: &Path,
76    sink_text: impl FnMut(&Path, u32, u32) -> Option<String>,
77) {
78    for finding in findings.iter_mut() {
79        let relative = finding.path.strip_prefix(root).unwrap_or(&finding.path);
80        finding.finding_id = security_finding_id(finding, relative);
81    }
82    crate::stable_id::stamp_stable_security_finding_ids(findings, suppressed, root, sink_text);
83}
84
85#[cfg(test)]
86mod tests {
87    use std::path::{Path, PathBuf};
88
89    use fallow_types::{
90        output::IssueAction,
91        results::{
92            SecurityCandidate, SecurityCandidateBoundary, SecurityCandidateSink, SecurityFinding,
93            SecurityFindingKind, SecuritySeverity, TraceHop, TraceHopRole,
94        },
95    };
96
97    use super::{security_finding_id, security_rule_id, stamp_security_finding_ids};
98
99    fn finding(kind: SecurityFindingKind, category: Option<&str>) -> SecurityFinding {
100        let path = PathBuf::from("/repo/src/a.ts");
101        SecurityFinding {
102            finding_id: String::new(),
103            stable_finding_id: None,
104            stable_id_input: None,
105            kind,
106            category: category.map(str::to_owned),
107            cwe: Some(79),
108            path: path.clone(),
109            line: 12,
110            col: 0,
111            evidence: "candidate".to_owned(),
112            source_backed: false,
113            source_read: None,
114            severity: SecuritySeverity::Low,
115            trace: vec![TraceHop {
116                path: path.clone(),
117                line: 12,
118                col: 0,
119                role: TraceHopRole::Sink,
120            }],
121            actions: Vec::<IssueAction>::new(),
122            dead_code: None,
123            reachability: None,
124            candidate: SecurityCandidate {
125                source_kind: None,
126                sink: SecurityCandidateSink {
127                    path,
128                    line: 12,
129                    col: 0,
130                    category: category.map(str::to_owned),
131                    cwe: Some(79),
132                    callee: None,
133                    url_shape: None,
134                },
135                boundary: SecurityCandidateBoundary::default(),
136                network: None,
137            },
138            taint_flow: None,
139            runtime: None,
140            attack_surface: None,
141        }
142    }
143
144    #[test]
145    fn rule_id_separates_the_two_client_server_leak_variants() {
146        assert_eq!(
147            security_rule_id(&finding(SecurityFindingKind::ClientServerLeak, None)),
148            "security/client-server-leak"
149        );
150        assert_eq!(
151            security_rule_id(&finding(
152                SecurityFindingKind::ClientServerLeak,
153                Some("server-only-import"),
154            )),
155            "security/server-only-import"
156        );
157        assert_eq!(
158            security_rule_id(&finding(
159                SecurityFindingKind::TaintedSink,
160                Some("dangerous-html"),
161            )),
162            "security/dangerous-html"
163        );
164        assert_eq!(
165            security_rule_id(&finding(SecurityFindingKind::TaintedSink, None)),
166            "security/tainted-sink"
167        );
168    }
169
170    #[test]
171    fn finding_id_is_deterministic_and_16_hex_digits() {
172        let finding = finding(SecurityFindingKind::ClientServerLeak, None);
173        let id = security_finding_id(&finding, Path::new("src/app.tsx"));
174
175        assert_eq!(id, security_finding_id(&finding, Path::new("src/app.tsx")));
176        assert_eq!(id.len(), 16);
177        assert!(id.chars().all(|character| character.is_ascii_hexdigit()));
178        assert_ne!(id, security_finding_id(&finding, Path::new("src/b.tsx")));
179    }
180
181    /// Pins the exact digest. SARIF `fallowSecurity/v2` and the JSON
182    /// `finding_id` carry it, so a change breaks every saved id. The expected
183    /// value comes from an independent FNV-1a 64 script over
184    /// `security/client-server-leak:src/app.tsx:12:0`.
185    #[test]
186    fn finding_id_golden_value() {
187        let finding = finding(SecurityFindingKind::ClientServerLeak, None);
188
189        assert_eq!(
190            security_finding_id(&finding, Path::new("src/app.tsx")),
191            "ea8fc221d62fda15"
192        );
193    }
194
195    #[test]
196    fn finding_id_distinguishes_same_rule_sinks_on_one_line() {
197        let mut first = finding(SecurityFindingKind::TaintedSink, Some("dynamic-regex"));
198        first.col = 12;
199        let mut second = first.clone();
200        second.col = 48;
201
202        assert_ne!(
203            security_finding_id(&first, Path::new("src/patterns.ts")),
204            security_finding_id(&second, Path::new("src/patterns.ts"))
205        );
206    }
207
208    #[test]
209    fn finding_id_normalizes_windows_separators() {
210        let finding = finding(SecurityFindingKind::TaintedSink, Some("dangerous-html"));
211
212        assert_eq!(
213            security_finding_id(&finding, Path::new("src\\app.tsx")),
214            security_finding_id(&finding, Path::new("src/app.tsx"))
215        );
216    }
217
218    #[test]
219    fn stamp_uses_the_root_relative_path() {
220        let mut findings = vec![finding(SecurityFindingKind::ClientServerLeak, None)];
221        stamp_security_finding_ids(&mut findings, &[], Path::new("/repo"), |_, _, _| None);
222
223        assert_eq!(
224            findings[0].finding_id,
225            security_finding_id(&findings[0], Path::new("src/a.ts"))
226        );
227    }
228
229    #[test]
230    fn stamp_keeps_a_path_outside_the_root() {
231        let mut findings = vec![finding(SecurityFindingKind::ClientServerLeak, None)];
232        stamp_security_finding_ids(&mut findings, &[], Path::new("/elsewhere"), |_, _, _| None);
233
234        assert_eq!(
235            findings[0].finding_id,
236            security_finding_id(&findings[0], Path::new("/repo/src/a.ts"))
237        );
238    }
239}