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;
189pub mod snippet;
190#[cfg(feature = "exec-subprocess")]
191pub mod subprocess;
192/// The **read-only documents** `security list` / `security status` return over a
193/// model-facing tool surface.
194///
195/// Ungated, like [`guidance`] and [`lint_grant`], and for a related reason: what
196/// a read owes its reader is not a property of which backends were compiled in.
197/// It is also the one place either document is built — the CLI's `security
198/// status` shares its coverage matrix and staleness rows from here, so
199/// `possibly_stale` and `ready` are one computation rather than three. Read the
200/// module for the two hazards it exists to remove: an empty listing that reads as
201/// a clean one, and a status blob whose two halves have different scopes.
202pub mod tool_security;
203
204pub use adapter::{
205 ADAPTERS, Adapter, AssetPaths, Invocation, LINT_ANALYZERS, NO_SNIPPET, NativeContext,
206 UNKNOWN_VERSION, adapter_for, known_analyzers, snippet_hash, snippet_hash_at,
207};
208// The linter's adapter is re-exported like any other, and — unlike any other —
209// is **not** in [`ADAPTERS`], so `ingest` cannot resolve it and nothing can file
210// its output as a layer. See [`adapter::clippy`].
211pub use adapter::clippy::{Clippy, FeatureSet};
212pub use assets::{
213 ASSETS, AssetKind, AssetSource, AssetSpec, AssetStatus, DownloadFile, Fetcher, InstalledAsset,
214 MissingAsset, SANDBOX, asset, asset_path, asset_root, assets_for, provision, provision_with,
215 resolve, status,
216};
217#[cfg(feature = "exec-boxlite")]
218pub use boxlite::{BoxliteRunner, SandboxError, SandboxProbe, sandbox_probe};
219pub use clock::{age_in_days, rfc3339_from_unix, rfc3339_utc, unix_from_rfc3339};
220pub use crossref::{
221 Correspondence, Report, across_analyzers as cross_reference_across_analyzers, cross_reference,
222};
223pub use guidance::{Guidance, Line as GuidanceLine};
224pub use ingest::{
225 IngestRunner, MAX_REPORT_FINDINGS, NormalizedReport, REPORT_SCHEMA, ReportFinding,
226 normalize_native,
227};
228#[cfg(feature = "exec-subprocess")]
229pub use lint::{LintError, LintOutcome, Toolchain, invocation as lint_invocation, run as run_lint};
230// ADR-0020 §6's grant. Re-exported under `lint_`-prefixed names because the
231// concepts have twins in `rto-remote` (ADR-0019 §3) and a reader who meets
232// `ConfigGrant` in the binary must be able to see which of the two it is.
233pub use lint_grant::{
234 Backend as LintBackend, ConfigGrant as LintConfigGrant, Decision as LintDecision,
235 Reason as LintReason, Requested as LintRequested, decide as decide_lint_host,
236};
237#[cfg(all(feature = "exec-boxlite", feature = "exec-subprocess"))]
238pub use lint_sandbox::BuilderError as LintBuilderError;
239pub use runner::{
240 AnalysisRequest, AnalysisResponse, AnalyzerRunner, Consent, ExecError, Worktree,
241 check_reported_path, check_request, worktree_id,
242};
243pub use runtime_file_pins::{
244 PinnedFile, PinnedRuntimeFiles, RUNTIME_FILES, RUNTIME_FILES_VERSION, runtime_files_for,
245};
246pub use runtime_pins::{
247 PinnedArchive, RUNTIME_ARCHIVES, RUNTIME_ASSET, RUNTIME_FILE, RUNTIME_VERSION, archive_for,
248 runtime_target,
249};
250pub use snippet::{NoSnippets, SnippetSource, WorktreeSnippets};
251#[cfg(feature = "exec-subprocess")]
252pub use subprocess::{SubprocessError, SubprocessRunner};
253pub use tool_security::{
254 AnalyzerCoverage, Coverage, CrossReference, CrossReferenceReport, LayerStaleness, MachineScope,
255 Readiness, RepositoryScope, SecurityListReport, TOOL_SECURITY_LIST_SCHEMA,
256 TOOL_SECURITY_STATUS_SCHEMA, ToolFindingsLayer, ToolSecurityList, ToolSecurityStatus,
257 coverage_matrix, coverage_matrix_with, layer_staleness, security_list, security_status,
258};
259
260/// The licence notice for the third-party binaries an `exec-boxlite` build
261/// embeds, compiled in so it cannot be separated from what it describes.
262///
263/// `roteiro security prefetch` prints it before installing the sandbox runtime,
264/// which is the same disclose-then-consent shape `roteiro model pull` uses. It
265/// is compiled into every build, because every build can provision the runtime —
266/// including one with no execution backend at all, which prefetches it for a
267/// later `exec-boxlite` build — so the obligations travel with the artifact
268/// rather than living only in the repository.
269pub const SANDBOX_RUNTIME_NOTICE: &str = include_str!("../NOTICE-boxlite-runtime.md");
270
271/// Lowercase hex SHA-256 of `bytes`.
272///
273/// Used for the report digest that ties an `AnalysisRun` to the exact bytes it
274/// was derived from, and for deriving an opaque worktree id from a path.
275#[must_use]
276pub fn sha256_hex(bytes: &[u8]) -> String {
277 use sha2::{Digest, Sha256};
278 let digest = Sha256::digest(bytes);
279 let mut out = String::with_capacity(64);
280 for byte in digest {
281 use std::fmt::Write as _;
282 let _ = write!(out, "{byte:02x}");
283 }
284 out
285}
286
287#[cfg(test)]
288mod tests {
289 use super::sha256_hex;
290
291 #[test]
292 fn hashes_the_known_vector() {
293 assert_eq!(
294 sha256_hex(b"abc"),
295 "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad"
296 );
297 }
298}