Skip to main content

rto_exec/
runner.rs

1//! The contract every analyzer backend satisfies.
2
3use std::path::{Component, Path, PathBuf};
4
5use rto_graph::{
6    AnalysisRun, Finding, FindingsError, Isolation, NetworkPolicy, RunnerKind, SourceIdentity,
7    WorktreeAccess, WorktreeId, analyzer_id_error, is_valid_analyzer_id,
8};
9
10use crate::sha256_hex;
11
12/// Errors an analyzer backend can raise.
13#[derive(Debug, thiserror::Error)]
14#[non_exhaustive]
15pub enum ExecError {
16    /// The request did not carry explicit user consent. Running an analyzer is
17    /// never implicit, whatever the backend.
18    #[error("analyzer run requires explicit user consent")]
19    ConsentRequired,
20    /// The request asked for a network policy this backend will not honour.
21    /// Egress is denied; an analyzer's inputs are pre-provisioned, never fetched
22    /// mid-run.
23    #[error("unsupported network policy: this runner only accepts `deny`")]
24    UnsupportedNetworkPolicy,
25    /// The request asked for a writable worktree. Analyzers parse source,
26    /// manifests and lockfiles; none of them needs to write to the tree.
27    #[error("the analyzed worktree must be read-only")]
28    WorktreeNotReadOnly,
29    /// The requested analyzer id is not well-formed: an analyzer id is
30    /// 1..=`MAX_ANALYZER_ID` characters of lowercase `[a-z0-9._-]`.
31    ///
32    /// The message is produced by [`rto_graph::analyzer_id_error`], the same
33    /// function `rto-graph`'s own rejection uses, so an id refused here reads
34    /// exactly as it would had the store caught it — and it names the rule that
35    /// was broken, not just the contract.
36    #[error("{}", analyzer_id_error(.0))]
37    InvalidAnalyzerId(String),
38    /// The report describes a different analyzer than the one requested — a
39    /// mixed-up file, or a report substituted for another.
40    #[error("report is from analyzer {reported:?}, but {requested:?} was requested")]
41    AnalyzerMismatch {
42        /// The analyzer the caller asked for.
43        requested: String,
44        /// The analyzer the report claims to be from.
45        reported: String,
46    },
47    /// The report's schema tag is not one this build understands.
48    #[error("unsupported report schema: {found:?} (expected {expected:?})")]
49    UnsupportedSchema {
50        /// The tag the report carried.
51        found: String,
52        /// The tag this build accepts.
53        expected: &'static str,
54    },
55    /// The report is structurally valid JSON but does not describe a usable run.
56    #[error("malformed report: {0}")]
57    MalformedReport(String),
58    /// The report declares more findings than will be accepted in one run.
59    #[error("report declares {count} findings, more than the {max} accepted in one run")]
60    TooManyFindings {
61        /// How many the report declared.
62        count: usize,
63        /// The accepted ceiling.
64        max: usize,
65    },
66    /// Two findings in one report share an identity, so one would silently
67    /// shadow the other.
68    #[error("duplicate finding identity in report: {0}")]
69    DuplicateFinding(String),
70    /// A finding claimed a path outside the analyzed worktree.
71    #[error("finding path escapes the worktree: {0:?}")]
72    PathEscapesWorktree(String),
73    /// A finding's identity components were not usable as a stable key.
74    #[error("finding identity: {0}")]
75    Identity(#[from] FindingsError),
76    /// The analyzer's pinned inputs are not provisioned, and Roteiro will not
77    /// fetch them mid-run.
78    ///
79    /// This is ADR-0014's named cold-cache failure. The message carries
80    /// everything needed to act on it without a second command: which analyzer,
81    /// which assets, the digest pinned for each, why each one could not be used,
82    /// and the exact `prefetch` invocation. The `assets-unavailable-offline`
83    /// token is part of the message so the failure is greppable and scriptable
84    /// rather than merely readable.
85    #[cfg(feature = "exec-subprocess")]
86    #[error(
87        "assets-unavailable-offline: {analyzer} cannot run because its pinned inputs are not \
88         provisioned\n  missing: {}\n  fix it with: {command}\n  \
89         (roteiro never fetches analyzer assets during a run, and never falls back to whatever \
90         the host has installed)",
91        .missing.iter().map(ToString::to_string).collect::<Vec<_>>().join("\n           ")
92    )]
93    AssetsUnavailableOffline {
94        /// The analyzer whose run was refused.
95        analyzer: String,
96        /// Every asset that was missing, unverifiable, or changed underneath its
97        /// record.
98        missing: Vec<crate::assets::MissingAsset>,
99        /// The exact command that provisions them.
100        command: String,
101    },
102    /// The analyzer binary could not be executed, or exited with a status that
103    /// does not carry a usable report.
104    #[cfg(feature = "exec-subprocess")]
105    #[error(transparent)]
106    Subprocess(#[from] crate::subprocess::SubprocessError),
107    /// Provisioning an asset failed.
108    #[cfg(feature = "exec-subprocess")]
109    #[error(transparent)]
110    Asset(#[from] crate::assets::AssetError),
111    /// This build has no adapter for the requested analyzer, so it can neither
112    /// run it nor read its native output.
113    #[error("no adapter for analyzer {requested:?} in this build (known: {known})")]
114    UnknownAnalyzer {
115        /// The analyzer the caller asked for.
116        requested: String,
117        /// The analyzer ids this build does know, comma-separated.
118        known: String,
119    },
120    /// The report was not valid JSON.
121    #[error("report is not valid JSON: {0}")]
122    Json(#[from] serde_json::Error),
123}
124
125/// Explicit user consent to run an analyzer.
126///
127/// Consent is part of the *request*, not of a backend, so no backend can be
128/// wired up in a way that skips it. For `roteiro security ingest` the user's
129/// invocation naming a report file **is** the consent; a backend that fetches
130/// assets or executes a container will need an interactive grant instead.
131#[derive(Debug, Clone, Copy, PartialEq, Eq)]
132pub enum Consent {
133    /// The user explicitly asked for this run.
134    Granted,
135    /// No consent was given; the run must not proceed.
136    Withheld,
137}
138
139/// The worktree an analyzer is pointed at.
140#[derive(Debug, Clone, PartialEq, Eq)]
141pub struct Worktree {
142    /// Filesystem location of the checkout.
143    pub path: PathBuf,
144    /// The opaque id that scopes this checkout's findings layer.
145    pub id: WorktreeId,
146    /// How the tree is exposed to the analyzer.
147    pub access: WorktreeAccess,
148}
149
150impl Worktree {
151    /// A read-only worktree at `path`, with its id derived from that path by
152    /// [`worktree_id`].
153    ///
154    /// # Errors
155    /// Returns [`ExecError::Identity`] if the derived id is not well-formed,
156    /// which cannot happen for a hex digest but is surfaced rather than
157    /// unwrapped.
158    pub fn read_only(path: &Path) -> Result<Self, ExecError> {
159        Ok(Self {
160            path: path.to_path_buf(),
161            id: worktree_id(path)?,
162            access: WorktreeAccess::ReadOnly,
163        })
164    }
165}
166
167/// Derive a stable, opaque id for the checkout at `path`.
168///
169/// The id is the first 16 hex characters of the SHA-256 of the path in absolute
170/// form. It is deliberately *not* the path itself: a layer key is stored and
171/// printed, and a local filesystem path is user-identifying data that has no
172/// business in a persisted record. Resolution is lexical (`std::path::absolute`),
173/// so the id is stable and does not depend on the checkout existing.
174///
175/// # Errors
176/// Returns [`ExecError::Identity`] if the derived token is somehow not a
177/// well-formed [`WorktreeId`].
178pub fn worktree_id(path: &Path) -> Result<WorktreeId, ExecError> {
179    // A path that cannot be made absolute (no working directory) still has a
180    // usable lexical form; fall back to it rather than failing the run.
181    let absolute = std::path::absolute(path).unwrap_or_else(|_| path.to_path_buf());
182    let digest = sha256_hex(absolute.to_string_lossy().as_bytes());
183    Ok(WorktreeId::new(&digest[..16])?)
184}
185
186/// What a caller asks a backend to do.
187///
188/// The same request shape serves every backend, which is the whole point of the
189/// seam: a caller that ingests a CI report today and runs a sandboxed analyzer
190/// tomorrow builds the identical value.
191#[derive(Debug, Clone, PartialEq, Eq)]
192pub struct AnalysisRequest {
193    /// Which analyzer to run.
194    pub analyzer: String,
195    /// The read-only worktree to analyze.
196    pub worktree: Worktree,
197    /// Egress policy for the run.
198    pub network: NetworkPolicy,
199    /// Explicit user consent.
200    pub consent: Consent,
201    /// The source identity the run is against (commit / tree / lockfile blob),
202    /// as far as the caller knows it. A backend may fill in more.
203    pub source: SourceIdentity,
204}
205
206/// What a backend returns: normalized findings plus the evidence for the run
207/// that produced them.
208#[derive(Debug, Clone, PartialEq, Eq)]
209pub struct AnalysisResponse {
210    /// The run record, ready to persist.
211    pub run: AnalysisRun,
212    /// The findings it produced, ordered by their stable identity key.
213    pub findings: Vec<Finding>,
214}
215
216/// One analyzer backend.
217///
218/// Implementations differ only in *where* the analyzer ran; the request and the
219/// response are the same, so CI ingestion and a local sandboxed run are the same
220/// code path from a caller's point of view. Every implementation must call
221/// [`check_request`] before doing any work, so the consent, network and
222/// worktree-access guarantees hold uniformly rather than per-backend.
223pub trait AnalyzerRunner {
224    /// Which backend this is — recorded on every run it produces.
225    fn kind(&self) -> RunnerKind;
226
227    /// The isolation boundary this backend actually provides. Recorded honestly:
228    /// a backend with no boundary reports [`Isolation::None`], never something
229    /// stronger.
230    fn isolation(&self) -> Isolation;
231
232    /// Execute the request.
233    ///
234    /// # Errors
235    /// Returns [`ExecError`] if the request violates the shared contract (see
236    /// [`check_request`]) or the backend cannot produce a usable result. A failed
237    /// run yields no partial result: either a complete [`AnalysisResponse`] or an
238    /// error.
239    fn run(&self, request: &AnalysisRequest) -> Result<AnalysisResponse, ExecError>;
240}
241
242/// The preflight every backend shares: explicit consent, denied egress, a
243/// read-only worktree, and a well-formed analyzer id.
244///
245/// It lives outside the trait so the guarantees are stated once and cannot drift
246/// between backends — a subprocess backend that forgot the consent check would
247/// otherwise be a one-line omission.
248///
249/// # Errors
250/// Returns [`ExecError::ConsentRequired`], [`ExecError::UnsupportedNetworkPolicy`],
251/// [`ExecError::WorktreeNotReadOnly`], or [`ExecError::InvalidAnalyzerId`] — the
252/// last when the analyzer id is not 1..=[`rto_graph::MAX_ANALYZER_ID`]
253/// characters of lowercase `[a-z0-9._-]`.
254pub fn check_request(request: &AnalysisRequest) -> Result<(), ExecError> {
255    if request.consent != Consent::Granted {
256        return Err(ExecError::ConsentRequired);
257    }
258    if request.network != NetworkPolicy::Deny {
259        return Err(ExecError::UnsupportedNetworkPolicy);
260    }
261    if request.worktree.access != WorktreeAccess::ReadOnly {
262        return Err(ExecError::WorktreeNotReadOnly);
263    }
264    if !is_valid_analyzer_id(&request.analyzer) {
265        return Err(ExecError::InvalidAnalyzerId(request.analyzer.clone()));
266    }
267    Ok(())
268}
269
270/// Reject a reported path that is absolute or climbs out of the worktree.
271///
272/// A finding is a claim about a file *in the analyzed tree*. A report that names
273/// `/etc/shadow` or `../../secrets` is either broken or hostile, and either way
274/// its claim cannot be checked, so it is refused rather than stored.
275///
276/// # Errors
277/// Returns [`ExecError::PathEscapesWorktree`] for an empty, absolute, prefixed or
278/// parent-climbing path.
279pub fn check_reported_path(path: &str) -> Result<(), ExecError> {
280    let escapes = path.is_empty()
281        || Path::new(path).components().any(|c| {
282            matches!(
283                c,
284                Component::RootDir | Component::Prefix(_) | Component::ParentDir
285            )
286        });
287    if escapes {
288        return Err(ExecError::PathEscapesWorktree(path.to_owned()));
289    }
290    Ok(())
291}
292
293#[cfg(test)]
294mod tests {
295    use super::{
296        AnalysisRequest, Consent, ExecError, Worktree, check_reported_path, check_request,
297        worktree_id,
298    };
299    use rto_graph::{NetworkPolicy, SourceIdentity, WorktreeAccess};
300
301    fn request() -> AnalysisRequest {
302        AnalysisRequest {
303            analyzer: "cargo-audit".to_owned(),
304            worktree: Worktree::read_only("/repo".as_ref()).expect("worktree"),
305            network: NetworkPolicy::Deny,
306            consent: Consent::Granted,
307            source: SourceIdentity::default(),
308        }
309    }
310
311    #[test]
312    fn a_well_formed_request_passes_preflight() {
313        check_request(&request()).expect("preflight");
314    }
315
316    #[test]
317    fn preflight_refuses_a_run_without_consent() {
318        let mut req = request();
319        req.consent = Consent::Withheld;
320        assert!(matches!(
321            check_request(&req),
322            Err(ExecError::ConsentRequired)
323        ));
324    }
325
326    #[test]
327    fn preflight_refuses_a_writable_worktree() {
328        let mut req = request();
329        req.worktree.access = WorktreeAccess::ReadWrite;
330        assert!(matches!(
331            check_request(&req),
332            Err(ExecError::WorktreeNotReadOnly)
333        ));
334    }
335
336    #[test]
337    fn preflight_refuses_a_malformed_analyzer_id() {
338        let mut req = request();
339        req.analyzer = "Cargo Audit".to_owned();
340        assert!(matches!(
341            check_request(&req),
342            Err(ExecError::InvalidAnalyzerId(_))
343        ));
344    }
345
346    /// The preflight enforces a length limit as well as a character set, so the
347    /// rejection has to say so. Being told an over-long id must be "non-empty" —
348    /// which it plainly was — is no help at all.
349    #[test]
350    fn preflight_refuses_an_over_long_analyzer_id_and_says_why() {
351        let mut req = request();
352        req.analyzer = "a".repeat(rto_graph::MAX_ANALYZER_ID + 1);
353        let err = check_request(&req).expect_err("an over-long id must be refused");
354        assert!(matches!(err, ExecError::InvalidAnalyzerId(_)));
355        let message = err.to_string();
356        assert!(
357            message.contains("over the 64-character limit"),
358            "the rejection must name the length rule: {message}"
359        );
360        assert!(
361            message.contains("1 to 64 characters of lowercase [a-z0-9._-]"),
362            "and state the whole contract: {message}"
363        );
364    }
365
366    /// One rejection, one wording. Both layers format through
367    /// `rto_graph::analyzer_id_error`, so an id refused at the seam reads exactly
368    /// as it would had the store caught it — a caller cannot be told two stories
369    /// about the same input depending on how deep the check happened to run.
370    #[test]
371    fn the_two_layers_word_a_rejection_identically() {
372        for id in [
373            "",
374            "Semgrep",
375            "a:b",
376            &"a".repeat(rto_graph::MAX_ANALYZER_ID + 1),
377        ] {
378            let seam = ExecError::InvalidAnalyzerId(id.to_owned()).to_string();
379            let store = rto_graph::FindingsError::InvalidAnalyzerId(id.to_owned()).to_string();
380            assert_eq!(seam, store, "{id:?} reads differently in the two layers");
381            assert_eq!(seam, rto_graph::analyzer_id_error(id));
382        }
383    }
384
385    #[test]
386    fn worktree_ids_are_opaque_stable_and_path_scoped() {
387        let a = worktree_id("/repo/one".as_ref()).expect("a");
388        let b = worktree_id("/repo/two".as_ref()).expect("b");
389        assert_ne!(a, b, "different checkouts get different layers");
390        assert_eq!(a, worktree_id("/repo/one".as_ref()).expect("again"));
391        assert_eq!(a.as_str().len(), 16);
392        assert!(
393            !a.as_str().contains("repo"),
394            "the id must not embed the path"
395        );
396    }
397
398    #[test]
399    fn reported_paths_must_stay_inside_the_worktree() {
400        check_reported_path("src/tls.rs").expect("relative path is fine");
401        for bad in ["", "/etc/shadow", "../../secrets", "src/../../etc/passwd"] {
402            assert!(
403                matches!(
404                    check_reported_path(bad),
405                    Err(ExecError::PathEscapesWorktree(_))
406                ),
407                "{bad:?} should be refused"
408            );
409        }
410    }
411}