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::new(path.clone(), 12, 0, TraceHopRole::Sink)],
116            actions: Vec::<IssueAction>::new(),
117            dead_code: None,
118            reachability: None,
119            candidate: SecurityCandidate {
120                source_kind: None,
121                sink: SecurityCandidateSink {
122                    path,
123                    line: 12,
124                    col: 0,
125                    category: category.map(str::to_owned),
126                    cwe: Some(79),
127                    callee: None,
128                    url_shape: None,
129                },
130                boundary: SecurityCandidateBoundary::default(),
131                network: None,
132            },
133            taint_flow: None,
134            runtime: None,
135            attack_surface: None,
136        }
137    }
138
139    #[test]
140    fn rule_id_separates_the_two_client_server_leak_variants() {
141        assert_eq!(
142            security_rule_id(&finding(SecurityFindingKind::ClientServerLeak, None)),
143            "security/client-server-leak"
144        );
145        assert_eq!(
146            security_rule_id(&finding(
147                SecurityFindingKind::ClientServerLeak,
148                Some("server-only-import"),
149            )),
150            "security/server-only-import"
151        );
152        assert_eq!(
153            security_rule_id(&finding(
154                SecurityFindingKind::TaintedSink,
155                Some("dangerous-html"),
156            )),
157            "security/dangerous-html"
158        );
159        assert_eq!(
160            security_rule_id(&finding(SecurityFindingKind::TaintedSink, None)),
161            "security/tainted-sink"
162        );
163    }
164
165    #[test]
166    fn finding_id_is_deterministic_and_16_hex_digits() {
167        let finding = finding(SecurityFindingKind::ClientServerLeak, None);
168        let id = security_finding_id(&finding, Path::new("src/app.tsx"));
169
170        assert_eq!(id, security_finding_id(&finding, Path::new("src/app.tsx")));
171        assert_eq!(id.len(), 16);
172        assert!(id.chars().all(|character| character.is_ascii_hexdigit()));
173        assert_ne!(id, security_finding_id(&finding, Path::new("src/b.tsx")));
174    }
175
176    /// Pins the exact digest. SARIF `fallowSecurity/v2` and the JSON
177    /// `finding_id` carry it, so a change breaks every saved id. The expected
178    /// value comes from an independent FNV-1a 64 script over
179    /// `security/client-server-leak:src/app.tsx:12:0`.
180    #[test]
181    fn finding_id_golden_value() {
182        let finding = finding(SecurityFindingKind::ClientServerLeak, None);
183
184        assert_eq!(
185            security_finding_id(&finding, Path::new("src/app.tsx")),
186            "ea8fc221d62fda15"
187        );
188    }
189
190    #[test]
191    fn finding_id_distinguishes_same_rule_sinks_on_one_line() {
192        let mut first = finding(SecurityFindingKind::TaintedSink, Some("dynamic-regex"));
193        first.col = 12;
194        let mut second = first.clone();
195        second.col = 48;
196
197        assert_ne!(
198            security_finding_id(&first, Path::new("src/patterns.ts")),
199            security_finding_id(&second, Path::new("src/patterns.ts"))
200        );
201    }
202
203    #[test]
204    fn finding_id_normalizes_windows_separators() {
205        let finding = finding(SecurityFindingKind::TaintedSink, Some("dangerous-html"));
206
207        assert_eq!(
208            security_finding_id(&finding, Path::new("src\\app.tsx")),
209            security_finding_id(&finding, Path::new("src/app.tsx"))
210        );
211    }
212
213    #[test]
214    fn stamp_uses_the_root_relative_path() {
215        let mut findings = vec![finding(SecurityFindingKind::ClientServerLeak, None)];
216        stamp_security_finding_ids(&mut findings, &[], Path::new("/repo"), |_, _, _| None);
217
218        assert_eq!(
219            findings[0].finding_id,
220            security_finding_id(&findings[0], Path::new("src/a.ts"))
221        );
222    }
223
224    #[test]
225    fn stamp_keeps_a_path_outside_the_root() {
226        let mut findings = vec![finding(SecurityFindingKind::ClientServerLeak, None)];
227        stamp_security_finding_ids(&mut findings, &[], Path::new("/elsewhere"), |_, _, _| None);
228
229        assert_eq!(
230            findings[0].finding_id,
231            security_finding_id(&findings[0], Path::new("/repo/src/a.ts"))
232        );
233    }
234}