rto_exec/adapter.rs
1//! Per-analyzer adapters: native analyzer output in, a [`NormalizedReport`] out.
2//!
3//! An adapter is the **only** analyzer-specific code in this crate. It knows one
4//! tool's native JSON, how to name that tool's findings so they are recognisable
5//! across runs, and which argv produces that JSON. Everything downstream — the
6//! validation, the identity keys, the ordering, the store — is shared.
7//!
8//! # Why this is the seam, and not the runner
9//!
10//! ADR-0012 requires that "a finding is the same artifact whether it was produced
11//! locally in a sandbox or ingested from a CI report". The cheap way to satisfy
12//! that is to write the conversion twice and add a test comparing the two. This
13//! crate does the other thing: **there is one conversion**, and both paths call
14//! it. A subprocess run captures the analyzer's stdout and hands those bytes to
15//! the adapter; `roteiro security ingest` reads a file of the same native bytes
16//! and hands them to the same adapter. Equality of the resulting [`Finding`]s is
17//! therefore a property of the code, and the tests that assert it are guarding
18//! against a future refactor rather than establishing the invariant.
19//!
20//! [`Finding`]: rto_graph::Finding
21//!
22//! # Adding an analyzer needs no migration
23//!
24//! [`rto_graph::FindingKey`] is `finding:<analyzer>:<that analyzer's own ordered
25//! identity components>`. An adapter chooses the recipe; the schema never learns
26//! what the components mean. So a new analyzer is a new file in `adapters/`, an
27//! entry in [`ADAPTERS`], and nothing else — no schema change, no migration.
28//!
29//! @rto:0012
30//! @rto:0014
31//! @rto:0018
32
33use rto_graph::SourceIdentity;
34
35use crate::ingest::NormalizedReport;
36use crate::runner::ExecError;
37use crate::snippet::SnippetSource;
38
39pub mod cargo_audit;
40pub mod semgrep;
41
42/// Everything an adapter may need that is *not* in the analyzer's own output.
43///
44/// Native analyzer output is missing things the evidence chain requires — no
45/// mainstream analyzer stamps its report with the wall-clock window it ran in,
46/// and `cargo audit` does not even record its own version. Rather than let an
47/// adapter invent them, the caller supplies what it actually knows, and an
48/// adapter that has nothing better says so ([`UNKNOWN_VERSION`]).
49#[derive(Clone)]
50pub struct NativeContext<'a> {
51 /// When the run started, RFC 3339 UTC. A subprocess run measures it; an
52 /// ingest of a report file uses the file's modification time, which is the
53 /// only timestamp evidence a bare report carries.
54 pub started_at: String,
55 /// When the run ended, RFC 3339 UTC.
56 pub ended_at: String,
57 /// The analyzer's version, where the caller learned it out of band (a
58 /// subprocess run asks the binary). `None` leaves the adapter to use
59 /// whatever the report itself carries.
60 pub analyzer_version: Option<String>,
61 /// The analyzer's process exit status, where the caller observed it.
62 pub exit_status: i32,
63 /// The source identity the run was against. Some identity recipes need it —
64 /// `cargo-audit` keys findings by lockfile blob, so a finding stays distinct
65 /// when the lockfile changes underneath the same advisory.
66 pub source: &'a SourceIdentity,
67 /// Digest of the rule set the analyzer ran with, where one applies.
68 pub rules_digest: Option<String>,
69 /// The pinned advisory database the caller provisioned, where one applies.
70 ///
71 /// A fallback, not an override: an adapter prefers what the analyzer's own
72 /// report says about the database it consulted, and uses this only when the
73 /// report says nothing. `cargo audit` says nothing whenever it is pointed at
74 /// a database with `--db`, which is every pinned run — so without this, the
75 /// reproducible configuration would be the one with no staleness evidence.
76 pub advisory_db: Option<rto_graph::AdvisoryDb>,
77 /// Where to read the source a finding points at, for identity recipes that
78 /// include a snippet hash.
79 ///
80 /// It is here rather than inside an adapter because the *caller* knows which
81 /// checkout the report describes, and because both execution paths must read
82 /// the same one — that is what makes a subprocess run and an ingest of its
83 /// output produce identical finding keys.
84 pub snippets: &'a dyn SnippetSource,
85}
86
87// Hand-written because `&dyn SnippetSource` is not `Debug` and does not need to
88// be: what a debug print of a context should show is the evidence it carries,
89// not the identity of the thing that reads files.
90impl std::fmt::Debug for NativeContext<'_> {
91 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
92 f.debug_struct("NativeContext")
93 .field("started_at", &self.started_at)
94 .field("ended_at", &self.ended_at)
95 .field("analyzer_version", &self.analyzer_version)
96 .field("exit_status", &self.exit_status)
97 .field("source", self.source)
98 .field("rules_digest", &self.rules_digest)
99 .field("advisory_db", &self.advisory_db)
100 .finish_non_exhaustive()
101 }
102}
103
104impl NativeContext<'_> {
105 /// The version to record: what the caller learned, else what the report
106 /// carried, else [`UNKNOWN_VERSION`].
107 ///
108 /// Never empty — [`crate::IngestRunner`] refuses a report that cannot say
109 /// what version produced it, and "unknown" is a truthful answer where an
110 /// empty string is a missing one.
111 #[must_use]
112 pub fn version_or(&self, from_report: Option<&str>) -> String {
113 self.analyzer_version
114 .as_deref()
115 .or(from_report)
116 .map(str::trim)
117 .filter(|v| !v.is_empty())
118 .unwrap_or(UNKNOWN_VERSION)
119 .to_owned()
120 }
121}
122
123/// Recorded as an analyzer's version when neither the caller nor the report
124/// knows it — which is the ordinary case for a `cargo audit` report ingested
125/// from CI, since its JSON has no version field.
126pub const UNKNOWN_VERSION: &str = "unknown";
127
128/// How an analyzer is invoked as a child process.
129///
130/// Returned by [`Adapter::command`] and consumed by the subprocess runner, so
131/// the argv lives beside the parser that understands its output rather than in
132/// the runner, which knows no analyzer.
133#[derive(Debug, Clone, PartialEq, Eq)]
134pub struct Invocation {
135 /// The program to execute, looked up on `PATH` unless it is a path.
136 pub program: String,
137 /// Its arguments, in order.
138 pub args: Vec<String>,
139 /// Exit statuses that mean "the analyzer ran and produced a report".
140 ///
141 /// Analyzers overload the exit status: `semgrep` exits `1` when it found
142 /// something, `cargo audit` exits `1` on a vulnerability. Treating non-zero
143 /// as failure would discard exactly the runs that matter, so each adapter
144 /// declares which statuses carry a usable report and every other status is a
145 /// hard failure.
146 pub success_statuses: Vec<i32>,
147}
148
149/// One analyzer's native output format and invocation.
150pub trait Adapter: Sync + std::fmt::Debug {
151 /// The analyzer id — the value that appears in every layer key and finding
152 /// key this adapter produces.
153 fn analyzer(&self) -> &'static str;
154
155 /// A one-line description of what it looks for, for `roteiro security
156 /// status` and `--help`.
157 fn summary(&self) -> &'static str;
158
159 /// The languages this adapter produces findings for, as the coverage matrix
160 /// in ADR-0018 states them. Reported by the CLI so the claim is inspectable
161 /// rather than only documented.
162 fn languages(&self) -> &'static [&'static str];
163
164 /// Which pinned assets the analyzer needs before it can run offline (see
165 /// [`crate::assets`]). An empty slice means it needs none.
166 fn asset_ids(&self) -> &'static [&'static str];
167
168 /// The argv that makes the analyzer emit the native format
169 /// [`Adapter::normalize`] parses, with egress configured off.
170 ///
171 /// `assets` maps an id from [`Adapter::asset_ids`] to the verified local
172 /// path it was provisioned to.
173 fn command(&self, assets: &AssetPaths<'_>) -> Invocation;
174
175 /// Parse native output into a normalized report.
176 ///
177 /// # Errors
178 /// Returns [`ExecError::MalformedReport`] when the bytes are not this
179 /// analyzer's format, or [`ExecError::Json`] when they are not JSON at all.
180 /// A partially-parsed report is never returned: either the whole thing
181 /// converts or the run fails.
182 fn normalize(
183 &self,
184 native: &[u8],
185 ctx: &NativeContext<'_>,
186 ) -> Result<NormalizedReport, ExecError>;
187}
188
189/// Verified local paths of an analyzer's provisioned assets, keyed by asset id.
190#[derive(Debug, Clone, Copy, Default)]
191pub struct AssetPaths<'a> {
192 entries: &'a [(&'a str, std::path::PathBuf)],
193}
194
195impl<'a> AssetPaths<'a> {
196 /// Wrap a resolved id → path list.
197 #[must_use]
198 pub fn new(entries: &'a [(&'a str, std::path::PathBuf)]) -> Self {
199 Self { entries }
200 }
201
202 /// The path provisioned for `id`, or `None` if it was not resolved.
203 ///
204 /// An adapter that asked for an asset in [`Adapter::asset_ids`] will always
205 /// find it here, because the runner refuses to start otherwise — see
206 /// [`ExecError::AssetsUnavailableOffline`].
207 #[must_use]
208 pub fn get(&self, id: &str) -> Option<&std::path::Path> {
209 self.entries
210 .iter()
211 .find(|(key, _)| *key == id)
212 .map(|(_, path)| path.as_path())
213 }
214
215 /// The path provisioned for `id` as a string, or an empty string. Adapters
216 /// build argv from this; an unresolved asset cannot reach here.
217 #[must_use]
218 pub fn arg(&self, id: &str) -> String {
219 self.get(id)
220 .map(|p| p.to_string_lossy().into_owned())
221 .unwrap_or_default()
222 }
223}
224
225/// Every analyzer this build knows how to normalise.
226///
227/// Ingest consults this table, so a report from any of them can be read in from
228/// CI whether or not this build can *execute* the analyzer — which is the whole
229/// point of ADR-0014's "ingest is always available".
230pub static ADAPTERS: &[&dyn Adapter] = &[&semgrep::Semgrep, &cargo_audit::CargoAudit];
231
232/// The adapter for `analyzer`, or `None` if this build has none.
233#[must_use]
234pub fn adapter_for(analyzer: &str) -> Option<&'static dyn Adapter> {
235 ADAPTERS.iter().copied().find(|a| a.analyzer() == analyzer)
236}
237
238/// Every analyzer id this build can normalise, sorted — for error messages that
239/// tell a caller what it *could* have asked for.
240#[must_use]
241pub fn known_analyzers() -> Vec<&'static str> {
242 let mut ids: Vec<&'static str> = ADAPTERS.iter().map(|a| a.analyzer()).collect();
243 ids.sort_unstable();
244 ids
245}
246
247/// Recorded in place of a snippet hash when the source could not be read — an
248/// ingested report about a tree this checkout does not have.
249///
250/// A named marker rather than a hash of the empty string, so a reader of a
251/// finding key can tell "the code was empty" from "the code was unavailable".
252pub const NO_SNIPPET: &str = "no-snippet";
253
254/// Short SHA-256 prefix of a snippet, used by identity recipes that need to
255/// notice that the *code* at a location changed even though the location did
256/// not.
257///
258/// Sixteen hex characters is 64 bits — far more than enough to keep two
259/// snippets at the same rule and offset distinct, and short enough that a
260/// rendered key stays readable in a terminal. Leading and trailing whitespace is
261/// stripped first, so a reformat that only moved indentation is not a new
262/// finding.
263#[must_use]
264pub fn snippet_hash(snippet: &str) -> String {
265 crate::sha256_hex(snippet.trim().as_bytes())[..16].to_owned()
266}
267
268/// [`snippet_hash`] of what `snippets` holds for the span, or [`NO_SNIPPET`].
269#[must_use]
270pub fn snippet_hash_at(snippets: &dyn SnippetSource, path: &str, start: u32, end: u32) -> String {
271 snippets
272 .snippet(path, start, end)
273 .map_or_else(|| NO_SNIPPET.to_owned(), |text| snippet_hash(&text))
274}
275
276#[cfg(test)]
277mod tests {
278 use super::{
279 AssetPaths, NO_SNIPPET, NativeContext, UNKNOWN_VERSION, adapter_for, known_analyzers,
280 snippet_hash, snippet_hash_at,
281 };
282 use rto_graph::SourceIdentity;
283
284 fn ctx(version: Option<&str>) -> NativeContext<'static> {
285 static SOURCE: std::sync::LazyLock<SourceIdentity> =
286 std::sync::LazyLock::new(SourceIdentity::default);
287 NativeContext {
288 started_at: "2026-08-15T09:00:00Z".to_owned(),
289 ended_at: "2026-08-15T09:00:04Z".to_owned(),
290 analyzer_version: version.map(str::to_owned),
291 exit_status: 0,
292 source: &SOURCE,
293 rules_digest: None,
294 advisory_db: None,
295 snippets: &crate::snippet::NoSnippets,
296 }
297 }
298
299 #[test]
300 fn the_registry_answers_for_every_analyzer_it_lists() {
301 for id in known_analyzers() {
302 assert_eq!(adapter_for(id).expect("registered").analyzer(), id);
303 }
304 assert!(adapter_for("no-such-analyzer").is_none());
305 }
306
307 /// Every shipped adapter claims at least one language and a summary, because
308 /// `roteiro security status` prints the coverage matrix from this table —
309 /// an adapter that claims nothing would silently shrink the reported
310 /// coverage.
311 #[test]
312 fn every_adapter_states_its_coverage() {
313 for id in known_analyzers() {
314 let adapter = adapter_for(id).expect("registered");
315 assert!(!adapter.languages().is_empty(), "{id} claims no language");
316 assert!(!adapter.summary().is_empty(), "{id} has no summary");
317 }
318 }
319
320 #[test]
321 fn a_version_is_taken_from_the_caller_then_the_report_then_unknown() {
322 assert_eq!(ctx(Some("1.2.3")).version_or(Some("0.0.1")), "1.2.3");
323 assert_eq!(ctx(None).version_or(Some("0.0.1")), "0.0.1");
324 assert_eq!(ctx(None).version_or(None), UNKNOWN_VERSION);
325 // Whitespace is not a version: an all-blank field would be refused
326 // downstream as missing evidence, so it is treated as absent here.
327 assert_eq!(ctx(Some(" ")).version_or(None), UNKNOWN_VERSION);
328 }
329
330 #[test]
331 fn snippet_hashes_are_short_stable_and_whitespace_insensitive() {
332 let hash = snippet_hash("eval(user_input)");
333 assert_eq!(hash.len(), 16);
334 assert_eq!(hash, snippet_hash(" eval(user_input)\n"));
335 assert_ne!(hash, snippet_hash("eval(other_input)"));
336 }
337
338 /// A report about a tree this checkout does not have still yields a
339 /// well-formed identity, and one that says why it is weaker.
340 #[test]
341 fn an_unavailable_snippet_is_named_not_hashed_as_empty() {
342 let hash = snippet_hash_at(&crate::snippet::NoSnippets, "a.py", 0, 4);
343 assert_eq!(hash, NO_SNIPPET);
344 assert_ne!(hash, snippet_hash(""));
345 }
346
347 #[test]
348 fn asset_paths_resolve_only_what_was_provisioned() {
349 let entries = [("semgrep-rules", std::path::PathBuf::from("/cache/r.yaml"))];
350 let paths = AssetPaths::new(&entries);
351 assert_eq!(paths.arg("semgrep-rules"), "/cache/r.yaml");
352 assert!(paths.get("advisory-db").is_none());
353 assert!(paths.arg("advisory-db").is_empty());
354 }
355}