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;
138/// Whether an image reference is pinned by a digest — the one place that decides.
139///
140/// Ungated, like [`guidance`], and for a reason of the same shape: the rule is
141/// about a string somebody wrote in a config file, not about which backends were
142/// compiled in. `roteiro config` reports an unpinned reference in a build with no
143/// sandbox at all, and a second copy of the check written for that purpose is how
144/// one of the two ends up laxer than the other.
145pub mod image_ref;
146mod ingest;
147/// Running a linter and **reporting** it, with no store anywhere in the path.
148///
149/// The other half of this crate produces artifacts; this module deliberately
150/// does not (ADR-0020 v1.1). It has no [`AnalyzerRunner`] implementation, takes
151/// no [`Consent`], and cannot reach [`rto_graph::Store`] — read its own
152/// documentation for why a lint is not a finding, and why relaxing
153/// [`check_request`] to fit a builder through the reader-class preflight is the
154/// conversion ADR-0014 warns against rather than a refactor.
155#[cfg(feature = "exec-subprocess")]
156pub mod lint;
157/// ADR-0020 §6's grant: may a linter run on **this host**?
158///
159/// Ungated, unlike [`lint`] itself. A policy that existed only where the
160/// capability does would be the conversion ADR-0014 warns about, so the answer
161/// is the same in a build that cannot run a linter as in one that can — see the
162/// module's own documentation.
163pub mod lint_grant;
164/// ADR-0020 conditions 1-2: the **sandboxed builder** — `roteiro lint`'s default.
165///
166/// The boundary half of [`lint`]. It adds one writable mount to what
167/// [`boxlite`] already does and removes nothing: the worktree stays read-only,
168/// [`check_request`]'s preflight is untouched, and the package cache is a
169/// read-only mount of this machine's own rather than a vendored copy. Read its
170/// documentation for why the image is supplied rather than pinned here, and why
171/// a `$CARGO_HOME` root is not what gets mounted.
172///
173/// Gated on **both** backends. The boundary does not imply the escape hatch —
174/// `exec-boxlite` still does not enable `exec-subprocess`, and enabling one must
175/// never switch on the other. This module needs both because it shares
176/// [`lint`]'s report shape and its one host-side `cargo locate-project`, which
177/// is how it learns what to mount.
178#[cfg(all(feature = "exec-boxlite", feature = "exec-subprocess"))]
179pub mod lint_sandbox;
180mod runner;
181/// The per-file digests of the extracted sandbox runtime — **generated**.
182///
183/// Derived from the archives in [`runtime_pins`] by
184/// `scripts/derive-runtime-file-pins.py`, and verified by `build.rs` against
185/// what `boxlite` actually extracted, since those files rather than the archive
186/// are what `include_bytes!` puts in the binary. Same `include!` arrangement,
187/// and so the same standalone constraint; its module documentation lives here
188/// for the same reason [`runtime_pins`]'s does.
189pub mod runtime_file_pins;
190/// The pinned sandbox-runtime archives, and the host-platform selection.
191///
192/// Its source carries no `//!` header because `build.rs` pulls the same file in
193/// with `include!`, where an inner doc comment is a syntax error — so the module
194/// documentation lives here instead. Read the file's own comments for what is
195/// pinned and why it has to be.
196pub mod runtime_pins;
197/// The **sandbox image store**: what it is holding, and dropping it safely.
198///
199/// Ungated, like [`assets`], and the argument is the same one that moved
200/// provisioning off the backend features: reclaiming the bytes a previous build
201/// cached must not require rebuilding with the backend that cached them. Nothing
202/// here executes anything — it reads an index, measures files, and removes what
203/// a pinned digest re-obtains (ADR-0014 v1.6).
204pub mod sandbox_store;
205pub mod snippet;
206#[cfg(feature = "exec-subprocess")]
207pub mod subprocess;
208/// The **read-only documents** `security list` / `security status` return over a
209/// model-facing tool surface.
210///
211/// Ungated, like [`guidance`] and [`lint_grant`], and for a related reason: what
212/// a read owes its reader is not a property of which backends were compiled in.
213/// It is also the one place either document is built — the CLI's `security
214/// status` shares its coverage matrix and staleness rows from here, so
215/// `possibly_stale` and `ready` are one computation rather than three. Read the
216/// module for the two hazards it exists to remove: an empty listing that reads as
217/// a clean one, and a status blob whose two halves have different scopes.
218pub mod tool_security;
219
220pub use adapter::{
221    ADAPTERS, Adapter, AssetPaths, Invocation, LINT_ANALYZERS, NO_SNIPPET, NativeContext,
222    UNKNOWN_VERSION, adapter_for, known_analyzers, snippet_hash, snippet_hash_at,
223};
224// The linter's adapter is re-exported like any other, and — unlike any other —
225// is **not** in [`ADAPTERS`], so `ingest` cannot resolve it and nothing can file
226// its output as a layer. See [`adapter::clippy`].
227pub use adapter::clippy::{Clippy, FeatureSet};
228pub use assets::{
229    ASSETS, AssetKind, AssetSource, AssetSpec, AssetStatus, DownloadFile, Fetcher, InstalledAsset,
230    MissingAsset, SANDBOX, asset, asset_path, asset_root, assets_for, provision, provision_with,
231    resolve, status,
232};
233#[cfg(feature = "exec-boxlite")]
234pub use boxlite::{BoxliteRunner, SandboxError, SandboxProbe, sandbox_probe};
235pub use clock::{age_in_days, rfc3339_from_unix, rfc3339_utc, unix_from_rfc3339};
236pub use crossref::{
237    Correspondence, Report, across_analyzers as cross_reference_across_analyzers, cross_reference,
238};
239pub use guidance::{Guidance, Line as GuidanceLine};
240pub use image_ref::{NotPinned, PinDefect, pinned_digest as image_pinned_digest};
241pub use ingest::{
242    IngestRunner, MAX_REPORT_FINDINGS, NormalizedReport, REPORT_SCHEMA, ReportFinding,
243    normalize_native,
244};
245#[cfg(feature = "exec-subprocess")]
246pub use lint::{LintError, LintOutcome, Toolchain, invocation as lint_invocation, run as run_lint};
247// ADR-0020 §6's grant. Re-exported under `lint_`-prefixed names because the
248// concepts have twins in `rto-remote` (ADR-0019 §3) and a reader who meets
249// `ConfigGrant` in the binary must be able to see which of the two it is.
250pub use lint_grant::{
251    Backend as LintBackend, ConfigGrant as LintConfigGrant, Decision as LintDecision,
252    Reason as LintReason, Requested as LintRequested, decide as decide_lint_host,
253};
254#[cfg(all(feature = "exec-boxlite", feature = "exec-subprocess"))]
255pub use lint_sandbox::BuilderError as LintBuilderError;
256pub use runner::{
257    AnalysisRequest, AnalysisResponse, AnalyzerRunner, Consent, ExecError, Worktree,
258    check_reported_path, check_request, worktree_id,
259};
260pub use runtime_file_pins::{
261    PinnedFile, PinnedRuntimeFiles, RUNTIME_FILES, RUNTIME_FILES_VERSION, runtime_files_for,
262};
263pub use runtime_pins::{
264    PinnedArchive, RUNTIME_ARCHIVES, RUNTIME_ASSET, RUNTIME_FILE, RUNTIME_VERSION, archive_for,
265    runtime_target,
266};
267pub use sandbox_store::{
268    Attribution, CachedImage, ClearReport, ImageBytes, Objects, Preserved, RemovedImage,
269    SANDBOX_CLEAR_SCHEMA, SANDBOX_STATUS_SCHEMA, SANDBOX_STORE_DIR, SandboxStatus, Scope,
270    StoreError, Unattributed, VerifiedImage, clear as sandbox_clear, plan as sandbox_plan,
271    status as sandbox_status, store_root as sandbox_store_root,
272};
273pub use snippet::{NoSnippets, SnippetSource, WorktreeSnippets};
274#[cfg(feature = "exec-subprocess")]
275pub use subprocess::{SubprocessError, SubprocessRunner};
276pub use tool_security::{
277    AnalyzerCoverage, Coverage, CrossReference, CrossReferenceReport, LayerStaleness, MachineScope,
278    Readiness, RepositoryScope, SecurityListReport, TOOL_SECURITY_LIST_SCHEMA,
279    TOOL_SECURITY_STATUS_SCHEMA, ToolFindingsLayer, ToolSecurityList, ToolSecurityStatus,
280    coverage_matrix, coverage_matrix_with, layer_staleness, security_list, security_status,
281};
282
283/// The licence notice for the third-party binaries an `exec-boxlite` build
284/// embeds, compiled in so it cannot be separated from what it describes.
285///
286/// `roteiro security prefetch` prints it before installing the sandbox runtime,
287/// which is the same disclose-then-consent shape `roteiro model pull` uses. It
288/// is compiled into every build, because every build can provision the runtime —
289/// including one with no execution backend at all, which prefetches it for a
290/// later `exec-boxlite` build — so the obligations travel with the artifact
291/// rather than living only in the repository.
292pub const SANDBOX_RUNTIME_NOTICE: &str = include_str!("../NOTICE-boxlite-runtime.md");
293
294/// Lowercase hex SHA-256 of `bytes`.
295///
296/// Used for the report digest that ties an `AnalysisRun` to the exact bytes it
297/// was derived from, and for deriving an opaque worktree id from a path.
298#[must_use]
299pub fn sha256_hex(bytes: &[u8]) -> String {
300    use sha2::{Digest, Sha256};
301    let digest = Sha256::digest(bytes);
302    let mut out = String::with_capacity(64);
303    for byte in digest {
304        use std::fmt::Write as _;
305        let _ = write!(out, "{byte:02x}");
306    }
307    out
308}
309
310#[cfg(test)]
311mod tests {
312    use super::sha256_hex;
313
314    #[test]
315    fn hashes_the_known_vector() {
316        assert_eq!(
317            sha256_hex(b"abc"),
318            "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad"
319        );
320    }
321}