ito-core 0.1.31

Core functionality and business logic for Ito
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
//! Process execution boundary for core-side command invocation.

use std::fs;
use std::io;
use std::path::{Component, Path, PathBuf};
use std::process::{Command, Stdio};
use std::sync::atomic::{AtomicU64, Ordering};
use std::thread;
use std::time::{Duration, Instant};

#[cfg(unix)]
use std::os::unix::ffi::OsStrExt;

#[cfg(windows)]
use std::os::windows::ffi::OsStrExt;

const MAX_TOTAL_ARG_BYTES: usize = 256 * 1024;
static OUTPUT_COUNTER: AtomicU64 = AtomicU64::new(0);

/// Process invocation request.
#[derive(Debug, Clone, Default)]
pub struct ProcessRequest {
    /// Executable name or absolute path.
    pub program: String,
    /// Positional arguments.
    pub args: Vec<String>,
    /// Optional working directory.
    pub current_dir: Option<PathBuf>,
}

impl ProcessRequest {
    /// Create a new request for the given program.
    ///
    /// The program can be an executable name (resolved via PATH) or an absolute path.
    /// Use the builder methods to configure arguments and working directory.
    pub fn new(program: impl Into<String>) -> Self {
        Self {
            program: program.into(),
            args: Vec::new(),
            current_dir: None,
        }
    }

    /// Add a single argument to the process invocation.
    ///
    /// This is a builder method that returns `self` for chaining.
    /// Arguments are passed to the process in the order they are added.
    pub fn arg(mut self, arg: impl Into<String>) -> Self {
        self.args.push(arg.into());
        self
    }

    /// Add multiple arguments to the process invocation.
    ///
    /// This is a builder method that returns `self` for chaining.
    /// Arguments are appended in iteration order after any previously added arguments.
    pub fn args<I, S>(mut self, args: I) -> Self
    where
        I: IntoIterator<Item = S>,
        S: Into<String>,
    {
        for arg in args {
            self.args.push(arg.into());
        }
        self
    }

    /// Set the working directory for the process.
    ///
    /// If not set, the process inherits the current working directory.
    /// This is a builder method that returns `self` for chaining.
    pub fn current_dir(mut self, dir: impl Into<PathBuf>) -> Self {
        self.current_dir = Some(dir.into());
        self
    }
}

/// Structured process execution output.
#[derive(Debug, Clone)]
pub struct ProcessOutput {
    /// Exit status code, or -1 if unavailable.
    pub exit_code: i32,
    /// Whether the process exited successfully.
    pub success: bool,
    /// Captured stdout.
    pub stdout: String,
    /// Captured stderr.
    pub stderr: String,
    /// True if execution was forcibly terminated due to timeout.
    pub timed_out: bool,
}

/// Process execution failure modes.
#[derive(Debug, thiserror::Error)]
pub enum ProcessExecutionError {
    /// Spawn failed before a child process was created.
    #[error("failed to spawn '{program}': {source}")]
    Spawn {
        /// Program being executed.
        program: String,
        /// Underlying I/O error.
        source: io::Error,
    },
    /// Waiting for process completion failed.
    #[error("failed waiting for '{program}': {source}")]
    Wait {
        /// Program being executed.
        program: String,
        /// Underlying I/O error.
        source: io::Error,
    },
    /// Creating a temporary output file failed.
    #[error("failed to create temp output file '{path}': {source}")]
    CreateTemp {
        /// Temp path used for output capture.
        path: PathBuf,
        /// Underlying I/O error.
        source: io::Error,
    },
    /// Reading a temporary output file failed.
    #[error("failed to read temp output file '{path}': {source}")]
    ReadTemp {
        /// Temp path used for output capture.
        path: PathBuf,
        /// Underlying I/O error.
        source: io::Error,
    },
    /// Invalid process request contents.
    #[error("invalid process request: {detail}")]
    InvalidRequest {
        /// Reason the request is invalid.
        detail: String,
    },
}

/// Abstraction for process execution.
pub trait ProcessRunner {
    /// Execute a process and wait for completion, capturing all output.
    ///
    /// This method blocks until the process exits or fails to start.
    /// Both stdout and stderr are captured and returned in the result.
    fn run(&self, request: &ProcessRequest) -> Result<ProcessOutput, ProcessExecutionError>;

    /// Execute a process with a timeout, capturing all output.
    ///
    /// If the process doesn't complete within the timeout, it will be killed
    /// and the result will have `timed_out` set to true. Output captured
    /// before the timeout is still returned.
    fn run_with_timeout(
        &self,
        request: &ProcessRequest,
        timeout: Duration,
    ) -> Result<ProcessOutput, ProcessExecutionError>;
}

/// Default runner backed by `std::process::Command`.
#[derive(Debug, Default)]
pub struct SystemProcessRunner;

impl ProcessRunner for SystemProcessRunner {
    fn run(&self, request: &ProcessRequest) -> Result<ProcessOutput, ProcessExecutionError> {
        validate_request(request)?;
        let mut command = build_command(request);
        let output = command
            .output()
            .map_err(|source| ProcessExecutionError::Spawn {
                program: request.program.clone(),
                source,
            })?;
        Ok(ProcessOutput {
            exit_code: output.status.code().unwrap_or(-1),
            success: output.status.success(),
            stdout: String::from_utf8_lossy(&output.stdout).to_string(),
            stderr: String::from_utf8_lossy(&output.stderr).to_string(),
            timed_out: false,
        })
    }

    /// Executes the given process request and returns its captured output, enforcing the supplied timeout.
    ///
    /// On timeout the child process is killed; any output written before termination is returned and `timed_out` is set to `true`.
    ///
    /// # Returns
    ///
    /// A `ProcessOutput` containing the process exit code (or -1 if unavailable), a `success` flag (false if timed out or exit indicates failure), captured `stdout` and `stderr` as `String`s, and `timed_out` indicating whether the process was terminated due to the timeout.
    ///
    /// # Examples
    ///
    /// ```
    /// use std::time::Duration;
    /// use ito_core::process::{ProcessRequest, ProcessRunner, SystemProcessRunner};
    ///
    /// let runner = SystemProcessRunner::default();
    /// let req = ProcessRequest::new("sh")
    ///     .arg("-c")
    ///     .arg("echo hello; sleep 0.01; echo world");
    /// let out = runner.run_with_timeout(&req, Duration::from_secs(1)).unwrap();
    /// assert!(out.stdout.contains("hello"));
    /// assert!(out.stdout.contains("world"));
    /// assert!(!out.timed_out);
    /// ```
    fn run_with_timeout(
        &self,
        request: &ProcessRequest,
        timeout: Duration,
    ) -> Result<ProcessOutput, ProcessExecutionError> {
        validate_request(request)?;
        let now_ms = chrono::Utc::now().timestamp_millis();
        let pid = std::process::id();
        let stdout_path = temp_output_path("stdout", pid, now_ms);
        let stderr_path = temp_output_path("stderr", pid, now_ms);

        let stdout_file = fs::OpenOptions::new()
            .write(true)
            .create_new(true)
            .open(&stdout_path)
            .map_err(|source| ProcessExecutionError::CreateTemp {
                path: stdout_path.clone(),
                source,
            })?;
        let stderr_file = fs::OpenOptions::new()
            .write(true)
            .create_new(true)
            .open(&stderr_path)
            .map_err(|source| ProcessExecutionError::CreateTemp {
                path: stderr_path.clone(),
                source,
            })?;

        let mut command = build_command(request);
        let mut child = command
            .stdin(Stdio::null())
            .stdout(Stdio::from(stdout_file))
            .stderr(Stdio::from(stderr_file))
            .spawn()
            .map_err(|source| ProcessExecutionError::Spawn {
                program: request.program.clone(),
                source,
            })?;

        let started = Instant::now();
        let mut timed_out = false;
        let mut exit_code = -1;
        let mut success = false;

        loop {
            if let Some(status) =
                child
                    .try_wait()
                    .map_err(|source| ProcessExecutionError::Wait {
                        program: request.program.clone(),
                        source,
                    })?
            {
                exit_code = status.code().unwrap_or(-1);
                success = status.success();
                break;
            }

            if started.elapsed() >= timeout {
                timed_out = true;
                let _ = child.kill();
                let _ = child.wait();
                break;
            }

            thread::sleep(Duration::from_millis(10));
        }

        let stdout =
            fs::read_to_string(&stdout_path).map_err(|source| ProcessExecutionError::ReadTemp {
                path: stdout_path.clone(),
                source,
            })?;
        let stderr =
            fs::read_to_string(&stderr_path).map_err(|source| ProcessExecutionError::ReadTemp {
                path: stderr_path.clone(),
                source,
            })?;
        let _ = fs::remove_file(&stdout_path);
        let _ = fs::remove_file(&stderr_path);

        Ok(ProcessOutput {
            exit_code,
            success: !timed_out && success,
            stdout,
            stderr,
            timed_out,
        })
    }
}

fn build_command(request: &ProcessRequest) -> Command {
    let mut command = Command::new(&request.program);
    if is_git_program(&request.program) {
        command.env_remove("GIT_DIR");
        command.env_remove("GIT_WORK_TREE");
    }
    command.args(&request.args);
    if let Some(dir) = &request.current_dir {
        command.current_dir(dir);
    }
    command
}

fn is_git_program(program: &str) -> bool {
    if program == "git" {
        return true;
    }
    matches!(
        Path::new(program)
            .file_name()
            .and_then(|name| name.to_str()),
        Some("git") | Some("git.exe")
    )
}

fn validate_request(request: &ProcessRequest) -> Result<(), ProcessExecutionError> {
    validate_program(&request.program)?;
    validate_args(&request.program, &request.args)?;
    validate_current_dir(&request.current_dir)?;
    Ok(())
}

fn validate_program(program: &str) -> Result<(), ProcessExecutionError> {
    if program.is_empty() {
        return Err(ProcessExecutionError::InvalidRequest {
            detail: "program is empty".to_string(),
        });
    }

    if program.contains('\0') {
        return Err(ProcessExecutionError::InvalidRequest {
            detail: "program contains NUL byte".to_string(),
        });
    }

    let program_path = Path::new(program);
    if program_path.is_absolute() {
        if contains_dot_components(program_path) {
            return Err(ProcessExecutionError::InvalidRequest {
                detail: "program path contains '.' or '..'".to_string(),
            });
        }
        return Ok(());
    }

    let mut components = program_path.components();
    let Some(component) = components.next() else {
        return Err(ProcessExecutionError::InvalidRequest {
            detail: "program path is empty".to_string(),
        });
    };

    match component {
        Component::Normal(_) => {}
        Component::CurDir => {
            return Err(ProcessExecutionError::InvalidRequest {
                detail: "program path must not be '.'".to_string(),
            });
        }
        Component::ParentDir => {
            return Err(ProcessExecutionError::InvalidRequest {
                detail: "program path must not include '..'".to_string(),
            });
        }
        Component::RootDir => {
            return Err(ProcessExecutionError::InvalidRequest {
                detail: "program path must be absolute when rooted".to_string(),
            });
        }
        Component::Prefix(_) => {
            return Err(ProcessExecutionError::InvalidRequest {
                detail: "program path prefix is not an executable name".to_string(),
            });
        }
    }

    if components.next().is_some() {
        return Err(ProcessExecutionError::InvalidRequest {
            detail: "program must be an executable name or absolute path".to_string(),
        });
    }

    Ok(())
}

fn validate_args(program: &str, args: &[String]) -> Result<(), ProcessExecutionError> {
    let mut total_bytes = program.len();
    if total_bytes > MAX_TOTAL_ARG_BYTES {
        return Err(ProcessExecutionError::InvalidRequest {
            detail: "program name exceeds maximum size".to_string(),
        });
    }

    for arg in args {
        if arg.contains('\0') {
            return Err(ProcessExecutionError::InvalidRequest {
                detail: "argument contains NUL byte".to_string(),
            });
        }

        total_bytes = total_bytes.saturating_add(arg.len());
        if total_bytes > MAX_TOTAL_ARG_BYTES {
            return Err(ProcessExecutionError::InvalidRequest {
                detail: "arguments exceed maximum total size".to_string(),
            });
        }
    }

    Ok(())
}

fn validate_current_dir(dir: &Option<PathBuf>) -> Result<(), ProcessExecutionError> {
    let Some(dir) = dir else {
        return Ok(());
    };

    if os_str_has_nul(dir.as_os_str()) {
        return Err(ProcessExecutionError::InvalidRequest {
            detail: "current_dir contains NUL byte".to_string(),
        });
    }

    if contains_dot_components(dir) {
        return Err(ProcessExecutionError::InvalidRequest {
            detail: "current_dir must not include '.' or '..'".to_string(),
        });
    }

    Ok(())
}

fn contains_dot_components(path: &Path) -> bool {
    for component in path.components() {
        match component {
            Component::CurDir | Component::ParentDir => return true,
            Component::Normal(_) | Component::RootDir | Component::Prefix(_) => {}
        }
    }
    false
}

#[cfg(unix)]
fn os_str_has_nul(value: &std::ffi::OsStr) -> bool {
    value.as_bytes().contains(&0)
}

#[cfg(windows)]
fn os_str_has_nul(value: &std::ffi::OsStr) -> bool {
    value.encode_wide().any(|unit| unit == 0)
}

fn temp_output_path(stream: &str, pid: u32, now_ms: i64) -> PathBuf {
    let counter = OUTPUT_COUNTER.fetch_add(1, Ordering::Relaxed);
    let mut path = std::env::temp_dir();
    path.push(format!("ito-process-{stream}-{pid}-{now_ms}-{counter}.log"));
    path
}

#[cfg(test)]
mod tests {
    use super::*;

    /// Verifies that SystemProcessRunner captures both standard output and standard error and reports the exit status and timeout flag correctly.
    ///
    /// # Examples
    ///
    /// ```
    /// let runner = SystemProcessRunner;
    /// let request = ProcessRequest::new("sh").args(["-c", "echo out; echo err >&2"]);
    /// let output = runner.run(&request).unwrap();
    /// assert!(output.success);
    /// assert_eq!(output.exit_code, 0);
    /// assert!(output.stdout.contains("out"));
    /// assert!(output.stderr.contains("err"));
    /// assert!(!output.timed_out);
    /// ```
    #[test]
    fn captures_stdout_and_stderr() {
        let runner = SystemProcessRunner;
        let request = ProcessRequest::new("sh").args(["-c", "echo out; echo err >&2"]);
        let output = runner.run(&request).unwrap();
        assert!(output.success);
        assert_eq!(output.exit_code, 0);
        assert!(output.stdout.contains("out"));
        assert!(output.stderr.contains("err"));
        assert!(!output.timed_out);
    }

    #[test]
    fn captures_non_zero_exit() {
        let runner = SystemProcessRunner;
        let request = ProcessRequest::new("sh").args(["-c", "echo boom >&2; exit 7"]);
        let output = runner.run(&request).unwrap();
        assert!(!output.success);
        assert_eq!(output.exit_code, 7);
        assert!(output.stderr.contains("boom"));
    }

    #[test]
    fn missing_executable_is_spawn_failure() {
        let runner = SystemProcessRunner;
        let request = ProcessRequest::new("__ito_missing_executable__");
        let result = runner.run(&request);
        match result {
            Err(ProcessExecutionError::Spawn { .. }) => {}
            other => panic!("expected spawn error, got {other:?}"),
        }
    }

    #[test]
    fn rejects_empty_program() {
        let request = ProcessRequest::new("");
        let result = validate_request(&request);
        match result {
            Err(ProcessExecutionError::InvalidRequest { detail }) => {
                assert!(detail.contains("program is empty"));
            }
            other => panic!("expected invalid request, got {other:?}"),
        }
    }

    #[test]
    fn rejects_nul_in_program() {
        let request = ProcessRequest::new("sh\0bad");
        let result = validate_request(&request);
        match result {
            Err(ProcessExecutionError::InvalidRequest { detail }) => {
                assert!(detail.contains("program contains NUL byte"));
            }
            other => panic!("expected invalid request, got {other:?}"),
        }
    }

    #[test]
    fn rejects_relative_program_with_components() {
        let request = ProcessRequest::new("bin/sh");
        let result = validate_request(&request);
        match result {
            Err(ProcessExecutionError::InvalidRequest { detail }) => {
                assert!(detail.contains("executable name or absolute path"));
            }
            other => panic!("expected invalid request, got {other:?}"),
        }
    }

    #[test]
    fn rejects_current_dir_with_parent_component() {
        let request = ProcessRequest::new("sh").current_dir("../tmp");
        let result = validate_request(&request);
        match result {
            Err(ProcessExecutionError::InvalidRequest { detail }) => {
                assert!(detail.contains("current_dir must not include"));
            }
            other => panic!("expected invalid request, got {other:?}"),
        }
    }

    #[test]
    fn rejects_nul_in_argument() {
        let request = ProcessRequest::new("sh").arg("a\0b");
        let result = validate_request(&request);
        match result {
            Err(ProcessExecutionError::InvalidRequest { detail }) => {
                assert!(detail.contains("argument contains NUL byte"));
            }
            other => panic!("expected invalid request, got {other:?}"),
        }
    }

    #[test]
    fn rejects_excessive_argument_bytes() {
        let oversized = "a".repeat(MAX_TOTAL_ARG_BYTES);
        let request = ProcessRequest::new("sh").arg(oversized);
        let result = validate_request(&request);
        match result {
            Err(ProcessExecutionError::InvalidRequest { detail }) => {
                assert!(detail.contains("arguments exceed maximum total size"));
            }
            other => panic!("expected invalid request, got {other:?}"),
        }
    }

    #[test]
    fn run_returns_invalid_request_before_spawn() {
        let runner = SystemProcessRunner;
        let request = ProcessRequest::new("bin/sh");
        let result = runner.run(&request);
        match result {
            Err(ProcessExecutionError::InvalidRequest { detail }) => {
                assert!(detail.contains("executable name or absolute path"));
            }
            other => panic!("expected invalid request, got {other:?}"),
        }
    }
}