Skip to main content

artifactize_core/
runtime.rs

1//! Runtime verdicts come only from ordinary command exit codes.
2//! Commands are trusted, not sandboxed; detached descendants can escape group cleanup.
3
4mod environment;
5
6use std::{
7    ffi::OsString,
8    future::Future,
9    io,
10    path::{Path, PathBuf},
11    time::Duration,
12};
13
14use thiserror::Error;
15use tokio_util::sync::CancellationToken;
16
17use crate::process::{self, ChildIdentity, Output};
18
19/// Stop undeclared runtime commands after thirty seconds so a stalled check
20/// cannot occupy a verification job indefinitely; owners can declare a longer timeout.
21pub const DEFAULT_TIMEOUT: Duration = Duration::from_secs(30);
22/// Share configuration and CLI's signed 32-bit millisecond protocol bound.
23pub const MAX_TIMEOUT: Duration = Duration::from_millis(crate::config::validation::MAX_TIMEOUT_MS);
24
25/// A single runtime invocation with private output and temporary directories, in the
26/// author's own environment.
27/// The caller owns the run directory and retains its contents for receipts/pruning.
28#[derive(Debug)]
29pub struct Command {
30    /// Resolved artifact cwd; defaults to the canonical workspace.
31    pub cwd: PathBuf,
32    command: process::Command,
33    directory: PathBuf,
34}
35
36impl Command {
37    /// Prepare literal argv. The command inherits the caller's environment except artifactize's
38    /// own `ARTIFACTIZE_*` variables. Each invocation gets independent 0700 output and
39    /// temporary directories below external `run_dir`.
40    pub fn prepare(
41        program: OsString,
42        args: Vec<OsString>,
43        workspace: &Path,
44        run_dir: &Path,
45        timeout: Option<Duration>,
46    ) -> Result<Self, Error> {
47        let timeout = timeout.unwrap_or(DEFAULT_TIMEOUT);
48        if timeout.is_zero() || timeout > MAX_TIMEOUT {
49            return Err(Error::InvalidTimeout);
50        }
51        let (cwd, directory, env) = environment::prepare(workspace, run_dir)?;
52        Ok(Self {
53            command: process::Command {
54                program,
55                args,
56                cwd: cwd.clone(),
57                env,
58                timeout,
59            },
60            cwd,
61            directory,
62        })
63    }
64
65    pub(crate) fn session_environment(&mut self, directory: &Path) {
66        crate::platform::environment::set(
67            &mut self.command.env,
68            "ARTIFACTIZE_SESSION_DIR",
69            directory,
70        );
71    }
72
73    /// Share the session directory of the environment a tool session's start ran in.
74    pub(crate) fn inherit_session(
75        &mut self,
76        environment: &std::collections::BTreeMap<OsString, OsString>,
77    ) {
78        if let Some(value) =
79            crate::platform::environment::lookup(environment, "ARTIFACTIZE_SESSION_DIR")
80        {
81            crate::platform::environment::set(
82                &mut self.command.env,
83                "ARTIFACTIZE_SESSION_DIR",
84                value,
85            );
86        }
87    }
88
89    pub(crate) fn into_process(mut self) -> process::Command {
90        self.command.cwd = self.cwd;
91        self.command
92    }
93
94    pub fn directory(&self) -> &Path {
95        &self.directory
96    }
97
98    pub fn timeout(&self) -> Duration {
99        self.command.timeout
100    }
101
102    /// Fingerprint scripts validate raw stdout and launch independently of each other.
103    pub(crate) async fn fingerprint(
104        mut self,
105        input: Vec<u8>,
106        cancellation: CancellationToken,
107    ) -> Result<Output, process::Error> {
108        self.command.cwd = self.cwd;
109        process::run_fingerprint(self.command, input, cancellation).await
110    }
111
112    /// Tool protocols use a larger bounded capture than runtime audit output.
113    pub(crate) async fn tool_output(
114        mut self,
115        input: Vec<u8>,
116        output_limit: usize,
117        cancellation: CancellationToken,
118    ) -> Result<Output, process::Error> {
119        self.command.cwd = self.cwd;
120        process::run_unregistered(self.command, Some(input), output_limit, cancellation).await
121    }
122}
123
124#[derive(
125    Debug,
126    Clone,
127    Copy,
128    PartialEq,
129    Eq,
130    PartialOrd,
131    Ord,
132    serde::Serialize,
133    serde::Deserialize,
134    clap::ValueEnum,
135)]
136#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
137#[value(rename_all = "SCREAMING_SNAKE_CASE")]
138pub enum Verdict {
139    Green,
140    Red,
141}
142
143impl Verdict {
144    pub fn as_str(self) -> &'static str {
145        match self {
146            Self::Green => "GREEN",
147            Self::Red => "RED",
148        }
149    }
150}
151
152impl std::fmt::Display for Verdict {
153    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
154        formatter.write_str(self.as_str())
155    }
156}
157
158#[derive(Debug)]
159pub struct ReviewResult {
160    pub exit_code: i32,
161    pub output: Output,
162}
163
164impl ReviewResult {
165    pub fn verdict(&self) -> Verdict {
166        if self.exit_code == 0 {
167            Verdict::Green
168        } else {
169            Verdict::Red
170        }
171    }
172}
173
174/// Operational errors carry no review verdict.
175#[derive(Debug)]
176pub enum Outcome {
177    Completed(ReviewResult),
178    OperationalError(Error),
179}
180
181#[derive(Debug, Error)]
182pub enum Error {
183    #[error("timeoutMs must be between 1 and 2147483647")]
184    InvalidTimeout,
185    #[error("runtime output directory must be outside the review workspace")]
186    OutputInsideWorkspace,
187    #[error("runtime environment preparation failed: {0}")]
188    Environment(#[from] io::Error),
189    #[error(transparent)]
190    Process(#[from] process::Error),
191    #[error("runtime process terminated without a verdict (signal {signal:?})")]
192    AbnormalExit {
193        signal: Option<i32>,
194        output: Box<Output>,
195    },
196}
197
198/// Owns the supervisor and its process cleanup independently of the result waiter.
199pub struct Execution {
200    cancellation: CancellationToken,
201    supervisor: tokio::task::JoinHandle<Outcome>,
202}
203
204impl Execution {
205    /// Wait for the result and all cleanup. Dropping a pending wait cancels the process;
206    /// the owner can still wait for cleanup. The result may only be taken once.
207    pub async fn wait(&mut self) -> Outcome {
208        let _cancel_on_drop = self.cancellation.clone().drop_guard();
209        crate::task::joined((&mut self.supervisor).await)
210            .unwrap_or_else(|error| Outcome::OperationalError(Error::Process(error.into())))
211    }
212}
213
214impl Drop for Execution {
215    fn drop(&mut self) {
216        self.cancellation.cancel();
217    }
218}
219
220/// Execute prepared argv with one deadline covering registration and execution.
221/// Process capture is raw and bounded; only runtime audit text is cleaned.
222pub async fn execute<F, R>(
223    command: Command,
224    cancellation: CancellationToken,
225    register: F,
226) -> Outcome
227where
228    F: FnOnce(ChildIdentity) -> R + Send + 'static,
229    R: Future<Output = io::Result<()>> + Send + 'static,
230{
231    start(command, cancellation, register).wait().await
232}
233
234/// Start an execution whose supervisor can be joined even if its result waiter is dropped.
235pub fn start<F, R>(command: Command, cancellation: CancellationToken, register: F) -> Execution
236where
237    F: FnOnce(ChildIdentity) -> R + Send + 'static,
238    R: Future<Output = io::Result<()>> + Send + 'static,
239{
240    let cancellation = cancellation.child_token();
241    let supervisor = tokio::spawn(supervise(command, cancellation.clone(), register));
242    Execution {
243        cancellation,
244        supervisor,
245    }
246}
247
248async fn supervise<F, R>(
249    mut command: Command,
250    cancellation: CancellationToken,
251    register: F,
252) -> Outcome
253where
254    F: FnOnce(ChildIdentity) -> R + Send + 'static,
255    R: Future<Output = io::Result<()>> + Send + 'static,
256{
257    command.command.cwd = command.cwd;
258    // The command's temporary directory is only its own scratch space: it goes with the run,
259    // while the output directory stays for receipts and pruning.
260    let scratch = command.directory.join("tmp");
261    let result =
262        process::run_logged(command.command, command.directory, cancellation, register).await;
263    let cleanup = crate::task::joined(
264        tokio::task::spawn_blocking(move || crate::platform::remove_tree(&scratch)).await,
265    )
266    .map_err(io::Error::other)
267    .and_then(std::convert::identity);
268    if let Err(error) = cleanup
269        && error.kind() != io::ErrorKind::NotFound
270        && result.is_ok()
271    {
272        return Outcome::OperationalError(Error::Environment(error));
273    }
274    match result {
275        Ok(mut output) => {
276            output.stdout = clean_output(&output.stdout);
277            output.stderr = clean_output(&output.stderr);
278            match output.status.end() {
279                crate::platform::ProcessEnd::Exited(exit_code) => {
280                    Outcome::Completed(ReviewResult { exit_code, output })
281                }
282                crate::platform::ProcessEnd::Signaled(signal) => {
283                    Outcome::OperationalError(Error::AbnormalExit {
284                        signal,
285                        output: Box::new(output),
286                    })
287                }
288            }
289        }
290        Err(error) => Outcome::OperationalError(Error::Process(error)),
291    }
292}
293
294pub(crate) use artifactize_tools::result::clean_output;