Skip to main content

rto_exec/
lib.rs

1//! The analyzer execution seam: one contract, interchangeable backends.
2//!
3//! Running an external analyzer (`cargo-audit`, `semgrep`, successors) can happen
4//! in CI, on a developer's machine, or — later — locally inside a sandbox. This
5//! crate exists so those stop being competing architectures: every backend
6//! implements one [`AnalyzerRunner`] trait, takes one [`AnalysisRequest`], and
7//! returns one [`AnalysisResponse`] of normalized findings plus run evidence. A
8//! caller never learns which backend produced a result, so adding the sandboxed
9//! and subprocess backends later changes no call site.
10//!
11//! Today there is exactly one implementation, [`IngestRunner`], which consumes a
12//! normalized report produced elsewhere. It is the zero-install default, not a
13//! fallback: it needs no container runtime and adds no isolation surface, and
14//! what it produces is byte-for-byte the shape a sandboxed run will produce.
15//!
16//! # What this crate does not do
17//!
18//! It does not *always* produce something to store, either. [`lint`] runs a
19//! linter and returns a report the caller prints: no [`AnalysisRun`], no layer,
20//! no store. A lint name is a symbol in a compiler rather than an assigned
21//! identifier, so it is an opinion about the code as it stands today rather than
22//! a durable fact about the repository (ADR-0020 v1.1) — and everything below
23//! about persistence simply does not apply to it.
24//!
25//! [`AnalysisRun`]: rto_graph::AnalysisRun
26//! [`lint`]: crate::lint
27//!
28//! It does not decide how results are *stored*. Persistence lives in `rto-graph`,
29//! which files findings in their own tables — never `nodes`/`edges`, never a
30//! provenance class, never in the exported graph artifact (ADR-0012). Nothing
31//! here can move the published `GraphArtifact` by a byte, and that is checked by
32//! test rather than assumed.
33//!
34//! No analyzer is implemented here, and no sandbox dependency is pulled in; the
35//! backends arrive behind their own features (ADR-0014).
36//!
37//! @rto:0014
38//! @rto:0012
39//!
40//! # Example
41//!
42//! ```
43//! use rto_exec::{AnalysisRequest, AnalyzerRunner, Consent, IngestRunner, Worktree};
44//! use rto_graph::SourceIdentity;
45//!
46//! let report = br#"{
47//!   "schema": "roteiro.findings/v1",
48//!   "analyzer": "cargo-audit",
49//!   "analyzer_version": "0.21.0",
50//!   "started_at": "2026-08-15T09:00:00Z",
51//!   "ended_at": "2026-08-15T09:00:04Z",
52//!   "exit_status": 1,
53//!   "findings": [{
54//!     "identity": ["RUSTSEC-2024-0001", "openssl", "0.10.5", "lock123"],
55//!     "rule": "RUSTSEC-2024-0001",
56//!     "severity": "high",
57//!     "title": "openssl is vulnerable",
58//!     "message": "upgrade to 0.10.66"
59//!   }]
60//! }"#;
61//!
62//! let request = AnalysisRequest {
63//!     analyzer: "cargo-audit".to_owned(),
64//!     worktree: Worktree::read_only("/repo".as_ref()).expect("worktree"),
65//!     network: rto_graph::NetworkPolicy::Deny,
66//!     consent: Consent::Granted,
67//!     source: SourceIdentity::default(),
68//! };
69//! let response = IngestRunner::new(report.to_vec()).run(&request).expect("ingest");
70//! assert_eq!(response.findings.len(), 1);
71//! assert_eq!(response.run.isolation, rto_graph::Isolation::Ingested);
72//! ```
73
74pub mod adapter;
75/// Where the pinned-asset cache lives, and the precedence that decides it.
76///
77/// Its source carries no `//!` header because `build.rs` pulls the same file in
78/// with `include!`, where an inner doc comment is a syntax error — so the module
79/// documentation lives here instead. `build.rs` needs it to find the sandbox
80/// runtime `roteiro security prefetch` installed, which is the same cache
81/// [`asset_paths::asset_root`] names; read the file's own comments for why that
82/// is shared rather than copied.
83pub mod asset_paths;
84// Asset provisioning is **always compiled**, behind no feature at all.
85//
86// It used to be `cfg(any(exec-subprocess, exec-boxlite))`, on the reading that
87// provisioning belongs to whichever backend consumes the assets. That was the
88// wrong shape and this module half-said so already: it is shared between the
89// backends and owned by neither, and the note on `SANDBOX_RUNTIME_NOTICE` below
90// records that an `exec-subprocess`-only build provisions *for a later
91// `exec-boxlite` build* — provisioning already served a backend that was not
92// compiled in.
93//
94// The bootstrap argument settles it. `AGENTS.md` tells a contributor to run
95// `roteiro security prefetch --allow-download` *before* building
96// `--features exec-boxlite`, because that build script requires the verified
97// archive at compile time. If prefetch lived behind an execution feature, you
98// would need a build with a *different* execution backend compiled in before you
99// could provision the one you actually wanted. That is circular.
100//
101// Nothing here executes anything: it downloads, digests, pins and reports. Every
102// `Command::new` in this crate is in `subprocess.rs` or `boxlite.rs`, and both
103// stay behind their features. Provisioning is not execution.
104pub mod assets;
105#[cfg(feature = "exec-boxlite")]
106pub mod boxlite;
107/// What an analyzer's environment is — for **both** backends, in one place.
108///
109/// Private because it is a seam between this crate's backends rather than a
110/// contract with a caller. It exists as its own module because it used to exist
111/// as two: a `ChildEnv` in [`subprocess`] and a hand-rolled list in [`boxlite`],
112/// which is how `CARGO_TARGET_DIR` came to be listed as a name to *inherit*
113/// under a promise that it was *set*. Read the module for why a guest has no
114/// `inherit` half at all.
115#[cfg(any(feature = "exec-subprocess", feature = "exec-boxlite"))]
116mod child_env;
117mod clock;
118pub mod crossref;
119/// Emitting a `file://` URL for a local path, and reading one back.
120///
121/// Its source carries no `//!` header because `build.rs` pulls the same file in
122/// with `include!`, where an inner doc comment is a syntax error — so the module
123/// documentation lives here instead. `build.rs` is this crate's only emitter: it
124/// prints the `BOXLITE_RUNTIME_URL=` recipe an operator pastes, and parses that
125/// variable back when it is set. What reads the URL in between is `boxlite`'s
126/// own `curl`, which percent-decodes and rejects an unencoded space outright —
127/// read the file's own comments for the measurements, and for why the encoder
128/// and the decoder have to be one file rather than two.
129pub mod file_url;
130/// How a refusal is written, so that a way forward stays one.
131///
132/// Ungated, like [`lint_grant`], and for the same kind of reason: what a refusal
133/// owes its reader is not a property of which backends were compiled in. Read
134/// the module for the failure it makes unrepresentable — three of this crate's
135/// refusals leaked source indentation into shipped output at once, which says
136/// the way they were written invited it.
137pub mod guidance;
138mod ingest;
139/// Running a linter and **reporting** it, with no store anywhere in the path.
140///
141/// The other half of this crate produces artifacts; this module deliberately
142/// does not (ADR-0020 v1.1). It has no [`AnalyzerRunner`] implementation, takes
143/// no [`Consent`], and cannot reach [`rto_graph::Store`] — read its own
144/// documentation for why a lint is not a finding, and why relaxing
145/// [`check_request`] to fit a builder through the reader-class preflight is the
146/// conversion ADR-0014 warns against rather than a refactor.
147#[cfg(feature = "exec-subprocess")]
148pub mod lint;
149/// ADR-0020 §6's grant: may a linter run on **this host**?
150///
151/// Ungated, unlike [`lint`] itself. A policy that existed only where the
152/// capability does would be the conversion ADR-0014 warns about, so the answer
153/// is the same in a build that cannot run a linter as in one that can — see the
154/// module's own documentation.
155pub mod lint_grant;
156/// ADR-0020 conditions 1-2: the **sandboxed builder** — `roteiro lint`'s default.
157///
158/// The boundary half of [`lint`]. It adds one writable mount to what
159/// [`boxlite`] already does and removes nothing: the worktree stays read-only,
160/// [`check_request`]'s preflight is untouched, and the package cache is a
161/// read-only mount of this machine's own rather than a vendored copy. Read its
162/// documentation for why the image is supplied rather than pinned here, and why
163/// a `$CARGO_HOME` root is not what gets mounted.
164///
165/// Gated on **both** backends. The boundary does not imply the escape hatch —
166/// `exec-boxlite` still does not enable `exec-subprocess`, and enabling one must
167/// never switch on the other. This module needs both because it shares
168/// [`lint`]'s report shape and its one host-side `cargo locate-project`, which
169/// is how it learns what to mount.
170#[cfg(all(feature = "exec-boxlite", feature = "exec-subprocess"))]
171pub mod lint_sandbox;
172mod runner;
173/// The per-file digests of the extracted sandbox runtime — **generated**.
174///
175/// Derived from the archives in [`runtime_pins`] by
176/// `scripts/derive-runtime-file-pins.py`, and verified by `build.rs` against
177/// what `boxlite` actually extracted, since those files rather than the archive
178/// are what `include_bytes!` puts in the binary. Same `include!` arrangement,
179/// and so the same standalone constraint; its module documentation lives here
180/// for the same reason [`runtime_pins`]'s does.
181pub mod runtime_file_pins;
182/// The pinned sandbox-runtime archives, and the host-platform selection.
183///
184/// Its source carries no `//!` header because `build.rs` pulls the same file in
185/// with `include!`, where an inner doc comment is a syntax error — so the module
186/// documentation lives here instead. Read the file's own comments for what is
187/// pinned and why it has to be.
188pub mod runtime_pins;
189/// The **sandbox image store**: what it is holding, and dropping it safely.
190///
191/// Ungated, like [`assets`], and the argument is the same one that moved
192/// provisioning off the backend features: reclaiming the bytes a previous build
193/// cached must not require rebuilding with the backend that cached them. Nothing
194/// here executes anything — it reads an index, measures files, and removes what
195/// a pinned digest re-obtains (ADR-0014 v1.6).
196pub mod sandbox_store;
197pub mod snippet;
198#[cfg(feature = "exec-subprocess")]
199pub mod subprocess;
200/// The **read-only documents** `security list` / `security status` return over a
201/// model-facing tool surface.
202///
203/// Ungated, like [`guidance`] and [`lint_grant`], and for a related reason: what
204/// a read owes its reader is not a property of which backends were compiled in.
205/// It is also the one place either document is built — the CLI's `security
206/// status` shares its coverage matrix and staleness rows from here, so
207/// `possibly_stale` and `ready` are one computation rather than three. Read the
208/// module for the two hazards it exists to remove: an empty listing that reads as
209/// a clean one, and a status blob whose two halves have different scopes.
210pub mod tool_security;
211
212pub use adapter::{
213    ADAPTERS, Adapter, AssetPaths, Invocation, LINT_ANALYZERS, NO_SNIPPET, NativeContext,
214    UNKNOWN_VERSION, adapter_for, known_analyzers, snippet_hash, snippet_hash_at,
215};
216// The linter's adapter is re-exported like any other, and — unlike any other —
217// is **not** in [`ADAPTERS`], so `ingest` cannot resolve it and nothing can file
218// its output as a layer. See [`adapter::clippy`].
219pub use adapter::clippy::{Clippy, FeatureSet};
220pub use assets::{
221    ASSETS, AssetKind, AssetSource, AssetSpec, AssetStatus, DownloadFile, Fetcher, InstalledAsset,
222    MissingAsset, SANDBOX, asset, asset_path, asset_root, assets_for, provision, provision_with,
223    resolve, status,
224};
225#[cfg(feature = "exec-boxlite")]
226pub use boxlite::{BoxliteRunner, SandboxError, SandboxProbe, sandbox_probe};
227pub use clock::{age_in_days, rfc3339_from_unix, rfc3339_utc, unix_from_rfc3339};
228pub use crossref::{
229    Correspondence, Report, across_analyzers as cross_reference_across_analyzers, cross_reference,
230};
231pub use guidance::{Guidance, Line as GuidanceLine};
232pub use ingest::{
233    IngestRunner, MAX_REPORT_FINDINGS, NormalizedReport, REPORT_SCHEMA, ReportFinding,
234    normalize_native,
235};
236#[cfg(feature = "exec-subprocess")]
237pub use lint::{LintError, LintOutcome, Toolchain, invocation as lint_invocation, run as run_lint};
238// ADR-0020 §6's grant. Re-exported under `lint_`-prefixed names because the
239// concepts have twins in `rto-remote` (ADR-0019 §3) and a reader who meets
240// `ConfigGrant` in the binary must be able to see which of the two it is.
241pub use lint_grant::{
242    Backend as LintBackend, ConfigGrant as LintConfigGrant, Decision as LintDecision,
243    Reason as LintReason, Requested as LintRequested, decide as decide_lint_host,
244};
245#[cfg(all(feature = "exec-boxlite", feature = "exec-subprocess"))]
246pub use lint_sandbox::BuilderError as LintBuilderError;
247pub use runner::{
248    AnalysisRequest, AnalysisResponse, AnalyzerRunner, Consent, ExecError, Worktree,
249    check_reported_path, check_request, worktree_id,
250};
251pub use runtime_file_pins::{
252    PinnedFile, PinnedRuntimeFiles, RUNTIME_FILES, RUNTIME_FILES_VERSION, runtime_files_for,
253};
254pub use runtime_pins::{
255    PinnedArchive, RUNTIME_ARCHIVES, RUNTIME_ASSET, RUNTIME_FILE, RUNTIME_VERSION, archive_for,
256    runtime_target,
257};
258pub use sandbox_store::{
259    Attribution, CachedImage, ClearReport, ImageBytes, Objects, Preserved, RemovedImage,
260    SANDBOX_CLEAR_SCHEMA, SANDBOX_STATUS_SCHEMA, SANDBOX_STORE_DIR, SandboxStatus, Scope,
261    StoreError, Unattributed, VerifiedImage, clear as sandbox_clear, plan as sandbox_plan,
262    status as sandbox_status, store_root as sandbox_store_root,
263};
264pub use snippet::{NoSnippets, SnippetSource, WorktreeSnippets};
265#[cfg(feature = "exec-subprocess")]
266pub use subprocess::{SubprocessError, SubprocessRunner};
267pub use tool_security::{
268    AnalyzerCoverage, Coverage, CrossReference, CrossReferenceReport, LayerStaleness, MachineScope,
269    Readiness, RepositoryScope, SecurityListReport, TOOL_SECURITY_LIST_SCHEMA,
270    TOOL_SECURITY_STATUS_SCHEMA, ToolFindingsLayer, ToolSecurityList, ToolSecurityStatus,
271    coverage_matrix, coverage_matrix_with, layer_staleness, security_list, security_status,
272};
273
274/// The licence notice for the third-party binaries an `exec-boxlite` build
275/// embeds, compiled in so it cannot be separated from what it describes.
276///
277/// `roteiro security prefetch` prints it before installing the sandbox runtime,
278/// which is the same disclose-then-consent shape `roteiro model pull` uses. It
279/// is compiled into every build, because every build can provision the runtime —
280/// including one with no execution backend at all, which prefetches it for a
281/// later `exec-boxlite` build — so the obligations travel with the artifact
282/// rather than living only in the repository.
283pub const SANDBOX_RUNTIME_NOTICE: &str = include_str!("../NOTICE-boxlite-runtime.md");
284
285/// Lowercase hex SHA-256 of `bytes`.
286///
287/// Used for the report digest that ties an `AnalysisRun` to the exact bytes it
288/// was derived from, and for deriving an opaque worktree id from a path.
289#[must_use]
290pub fn sha256_hex(bytes: &[u8]) -> String {
291    use sha2::{Digest, Sha256};
292    let digest = Sha256::digest(bytes);
293    let mut out = String::with_capacity(64);
294    for byte in digest {
295        use std::fmt::Write as _;
296        let _ = write!(out, "{byte:02x}");
297    }
298    out
299}
300
301#[cfg(test)]
302mod tests {
303    use super::sha256_hex;
304
305    #[test]
306    fn hashes_the_known_vector() {
307        assert_eq!(
308            sha256_hex(b"abc"),
309            "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad"
310        );
311    }
312}