mino 1.6.0

Secure AI agent sandbox using rootless containers
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
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
//! Orchestration module for container runtimes
//!
//! Provides platform-agnostic container management:
//! - macOS: OrbStack VM + Podman
//! - Linux: Native rootless Podman

mod factory;
#[cfg(test)]
pub(crate) mod mock;
mod native_podman;
pub mod orbstack;
mod orbstack_runtime;
pub mod podman;
mod runtime;

pub use factory::{create_runtime, create_runtime_with_vm, Platform};
pub use orbstack::OrbStack;
pub use podman::ContainerConfig;
pub use runtime::{ContainerRuntime, VolumeInfo};

use std::collections::HashMap;
use tokio::io::{AsyncBufReadExt, BufReader};

use crate::error::MinoResult;

/// Max number of output lines to include in build error messages.
const BUILD_ERROR_TAIL_LINES: usize = 50;

/// Extract the useful tail of build output for error diagnostics.
///
/// Combines stdout and stderr, then returns the last `BUILD_ERROR_TAIL_LINES`
/// lines so error messages are actionable without being overwhelming.
pub(crate) fn build_error_output(stdout: &str, stderr: &str) -> String {
    let lines: Vec<&str> = stdout.lines().chain(stderr.lines()).collect();
    let total = lines.len();
    let tail: Vec<&str> = if total > BUILD_ERROR_TAIL_LINES {
        lines[total - BUILD_ERROR_TAIL_LINES..].to_vec()
    } else {
        lines
    };
    tail.join("\n")
}

/// Stream stdout+stderr from a child process, calling `on_output` for each line.
///
/// Returns all collected output lines for error reporting. This is a standalone
/// async function (not behind `async_trait`) to avoid lifetime issues with the
/// `dyn Fn` callback.
pub(crate) async fn stream_child_output(
    child: &mut tokio::process::Child,
    on_output: &(dyn Fn(String) + Send + Sync),
) -> Vec<String> {
    let stderr = child.stderr.take().expect("stderr piped");
    let stdout = child.stdout.take().expect("stdout piped");

    let mut stderr_reader = BufReader::new(stderr).lines();
    let mut stdout_reader = BufReader::new(stdout).lines();

    let mut all_output = Vec::new();
    let mut stderr_done = false;
    let mut stdout_done = false;

    while !stderr_done || !stdout_done {
        tokio::select! {
            line = stderr_reader.next_line(), if !stderr_done => {
                match line {
                    Ok(Some(line)) => {
                        on_output(line.clone());
                        all_output.push(line);
                    }
                    _ => stderr_done = true,
                }
            }
            line = stdout_reader.next_line(), if !stdout_done => {
                match line {
                    Ok(Some(line)) => {
                        on_output(line.clone());
                        all_output.push(line);
                    }
                    _ => stdout_done = true,
                }
            }
        }
    }

    all_output
}

/// Follow a child process's stderr/stdout until a marker line is found or timeout expires.
///
/// Returns `true` if the marker was found, `false` on timeout. Calls `on_line`
/// for each line received. The child process is killed on timeout or once marker is found.
///
/// Uses `String` callback (same pattern as `stream_child_output`) to avoid
/// lifetime issues with `async_trait` desugaring.
pub(crate) async fn follow_until_marker(
    child: &mut tokio::process::Child,
    marker: &str,
    timeout: std::time::Duration,
    on_line: &(dyn Fn(String) + Send + Sync),
) -> bool {
    let stderr = child.stderr.take().expect("stderr piped");
    let stdout = child.stdout.take().expect("stdout piped");

    let mut stderr_reader = BufReader::new(stderr).lines();
    let mut stdout_reader = BufReader::new(stdout).lines();

    let mut stderr_done = false;
    let mut stdout_done = false;
    let mut found = false;

    let sleep = tokio::time::sleep(timeout);
    tokio::pin!(sleep);

    while !found && (!stderr_done || !stdout_done) {
        tokio::select! {
            _ = &mut sleep => {
                // Timeout — kill the logs process
                let _ = child.kill().await;
                let _ = child.wait().await; // reap to avoid zombie
                break;
            }
            result = stderr_reader.next_line(), if !stderr_done => {
                match result {
                    Ok(Some(line)) => {
                        if line.contains(marker) {
                            found = true;
                        }
                        on_line(line);
                    }
                    _ => stderr_done = true,
                }
            }
            result = stdout_reader.next_line(), if !stdout_done => {
                match result {
                    Ok(Some(line)) => {
                        if line.contains(marker) {
                            found = true;
                        }
                        on_line(line);
                    }
                    _ => stdout_done = true,
                }
            }
        }
    }

    if found {
        // Marker found — kill the tailing process (we don't need more logs)
        let _ = child.kill().await;
        let _ = child.wait().await; // reap to avoid zombie
    }

    found
}

/// Parse `du -sb` output to extract the byte size.
///
/// `du -sb` prints `<bytes>\t<path>` -- this extracts and parses the leading
/// number, returning `None` if the output cannot be parsed.
pub(crate) fn parse_du_bytes(output: &[u8]) -> Option<u64> {
    let text = String::from_utf8_lossy(output);
    text.split_whitespace()
        .next()
        .and_then(|s| s.parse::<u64>().ok())
}

/// Collect volume disk usage results from a batch of parallel futures.
///
/// Each future should resolve to `Ok(Some((name, size)))` on success or
/// `Ok(None)` when the size could not be determined. Errors propagate.
pub(crate) fn collect_disk_usage(
    results: Vec<MinoResult<Option<(String, u64)>>>,
) -> MinoResult<HashMap<String, u64>> {
    results.into_iter().filter_map(|r| r.transpose()).collect()
}

/// Extract labels from a Podman volume JSON object.
///
/// Podman represents volume labels as `{"Labels": {"key": "value", ...}}`.
/// Non-string values are silently skipped. Returns an empty map when the
/// `Labels` field is missing, null, or not an object.
pub(crate) fn parse_volume_labels(vol: &serde_json::Value) -> HashMap<String, String> {
    vol["Labels"]
        .as_object()
        .map(|obj| {
            obj.iter()
                .filter_map(|(k, v)| v.as_str().map(|s| (k.clone(), s.to_string())))
                .collect()
        })
        .unwrap_or_default()
}

/// Parse `podman volume ls --format json` output into a filtered list of `VolumeInfo`.
///
/// Volumes whose names do not start with `prefix` are excluded. Empty or
/// whitespace-only stdout is treated as an empty list (not a parse error).
pub(crate) fn parse_volume_list_json(stdout: &str, prefix: &str) -> MinoResult<Vec<VolumeInfo>> {
    if stdout.trim().is_empty() {
        return Ok(Vec::new());
    }

    let volumes: Vec<serde_json::Value> = serde_json::from_str(stdout)?;

    let result = volumes
        .iter()
        .filter_map(|vol| {
            let name = vol["Name"].as_str()?;
            if !name.starts_with(prefix) {
                return None;
            }
            Some(volume_info_from_json(vol, name))
        })
        .collect();

    Ok(result)
}

/// Build a `VolumeInfo` from a Podman volume JSON object using the given name.
fn volume_info_from_json(vol: &serde_json::Value, name: &str) -> VolumeInfo {
    VolumeInfo {
        name: name.to_string(),
        labels: parse_volume_labels(vol),
        mountpoint: vol["Mountpoint"].as_str().map(String::from),
        created_at: vol["CreatedAt"].as_str().map(String::from),
        size_bytes: None,
    }
}

/// Parse `podman volume inspect --format json` output into an optional `VolumeInfo`.
///
/// Podman inspect returns a JSON array even for a single volume. Returns `None`
/// when the array is empty. The `name` parameter is used as the canonical volume
/// name (preserving existing behavior where callers pass the requested name rather
/// than trusting the JSON `Name` field).
pub(crate) fn parse_volume_inspect_json(
    stdout: &str,
    name: &str,
) -> MinoResult<Option<VolumeInfo>> {
    if stdout.trim().is_empty() {
        return Ok(None);
    }

    let volumes: Vec<serde_json::Value> = serde_json::from_str(stdout)?;

    Ok(volumes.first().map(|vol| volume_info_from_json(vol, name)))
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::error::MinoError;
    use std::sync::{Arc, Mutex};

    // -- parse_du_bytes --

    #[test]
    fn parse_du_bytes_valid() {
        let output = b"12345\t/var/lib/containers/storage/volumes/vol/_data\n";
        assert_eq!(parse_du_bytes(output), Some(12345));
    }

    #[test]
    fn parse_du_bytes_large_value() {
        let output = b"1073741824\t/some/path\n";
        assert_eq!(parse_du_bytes(output), Some(1_073_741_824));
    }

    #[test]
    fn parse_du_bytes_empty() {
        assert_eq!(parse_du_bytes(b""), None);
    }

    #[test]
    fn parse_du_bytes_non_numeric() {
        assert_eq!(parse_du_bytes(b"abc\t/path\n"), None);
    }

    #[test]
    fn parse_du_bytes_whitespace_only() {
        assert_eq!(parse_du_bytes(b"   \t  \n"), None);
    }

    // -- collect_disk_usage --

    #[test]
    fn collect_disk_usage_happy_path() {
        let results = vec![
            Ok(Some(("vol-a".to_string(), 100))),
            Ok(Some(("vol-b".to_string(), 200))),
        ];
        let sizes = collect_disk_usage(results).unwrap();
        assert_eq!(sizes.len(), 2);
        assert_eq!(sizes["vol-a"], 100);
        assert_eq!(sizes["vol-b"], 200);
    }

    #[test]
    fn collect_disk_usage_skips_none() {
        let results = vec![
            Ok(Some(("vol-a".to_string(), 100))),
            Ok(None),
            Ok(Some(("vol-c".to_string(), 300))),
        ];
        let sizes = collect_disk_usage(results).unwrap();
        assert_eq!(sizes.len(), 2);
        assert_eq!(sizes["vol-a"], 100);
        assert_eq!(sizes["vol-c"], 300);
    }

    #[test]
    fn collect_disk_usage_empty() {
        let results: Vec<MinoResult<Option<(String, u64)>>> = vec![];
        let sizes = collect_disk_usage(results).unwrap();
        assert!(sizes.is_empty());
    }

    #[test]
    fn collect_disk_usage_propagates_error() {
        let results = vec![
            Ok(Some(("vol-a".to_string(), 100))),
            Err(MinoError::Internal("test error".to_string())),
        ];
        let err = collect_disk_usage(results).unwrap_err();
        assert!(err.to_string().contains("test error"));
    }

    // -- parse_volume_labels --

    #[test]
    fn parse_volume_labels_from_valid_object() {
        let vol = serde_json::json!({
            "Labels": {
                "io.mino.cache": "true",
                "io.mino.cache.ecosystem": "npm"
            }
        });
        let labels = parse_volume_labels(&vol);
        assert_eq!(labels.len(), 2);
        assert_eq!(labels["io.mino.cache"], "true");
        assert_eq!(labels["io.mino.cache.ecosystem"], "npm");
    }

    #[test]
    fn parse_volume_labels_null() {
        let vol = serde_json::json!({ "Labels": null });
        let labels = parse_volume_labels(&vol);
        assert!(labels.is_empty());
    }

    #[test]
    fn parse_volume_labels_missing() {
        let vol = serde_json::json!({ "Name": "test" });
        let labels = parse_volume_labels(&vol);
        assert!(labels.is_empty());
    }

    #[test]
    fn parse_volume_labels_non_string_values() {
        let vol = serde_json::json!({
            "Labels": {
                "str_label": "value",
                "int_label": 42,
                "bool_label": true
            }
        });
        let labels = parse_volume_labels(&vol);
        assert_eq!(labels.len(), 1);
        assert_eq!(labels["str_label"], "value");
    }

    #[test]
    fn parse_volume_labels_empty_object() {
        let vol = serde_json::json!({ "Labels": {} });
        let labels = parse_volume_labels(&vol);
        assert!(labels.is_empty());
    }

    // -- parse_volume_list_json --

    #[test]
    fn parse_volume_list_json_single_volume() {
        let json = r#"[{
            "Name": "mino-cache-npm-abc123",
            "Labels": {"io.mino.cache": "true"},
            "Mountpoint": "/var/lib/volumes/test/_data",
            "CreatedAt": "2026-03-10T12:00:00Z"
        }]"#;
        let result = parse_volume_list_json(json, "mino-cache-").unwrap();
        assert_eq!(result.len(), 1);
        assert_eq!(result[0].name, "mino-cache-npm-abc123");
        assert_eq!(result[0].labels["io.mino.cache"], "true");
        assert_eq!(
            result[0].mountpoint.as_deref(),
            Some("/var/lib/volumes/test/_data")
        );
        assert_eq!(
            result[0].created_at.as_deref(),
            Some("2026-03-10T12:00:00Z")
        );
        assert!(result[0].size_bytes.is_none());
    }

    #[test]
    fn parse_volume_list_json_multiple_with_prefix_filter() {
        let json = r#"[
            {"Name": "mino-cache-npm-abc", "Labels": {}},
            {"Name": "other-volume", "Labels": {}},
            {"Name": "mino-cache-cargo-def", "Labels": {}}
        ]"#;
        let result = parse_volume_list_json(json, "mino-cache-").unwrap();
        assert_eq!(result.len(), 2);
        assert_eq!(result[0].name, "mino-cache-npm-abc");
        assert_eq!(result[1].name, "mino-cache-cargo-def");
    }

    #[test]
    fn parse_volume_list_json_empty_string() {
        let result = parse_volume_list_json("", "mino-cache-").unwrap();
        assert!(result.is_empty());
    }

    #[test]
    fn parse_volume_list_json_whitespace_only() {
        let result = parse_volume_list_json("   \n  \t  ", "mino-cache-").unwrap();
        assert!(result.is_empty());
    }

    #[test]
    fn parse_volume_list_json_empty_array() {
        let result = parse_volume_list_json("[]", "mino-cache-").unwrap();
        assert!(result.is_empty());
    }

    #[test]
    fn parse_volume_list_json_no_prefix_match() {
        let json = r#"[{"Name": "other-volume", "Labels": {}}]"#;
        let result = parse_volume_list_json(json, "mino-cache-").unwrap();
        assert!(result.is_empty());
    }

    #[test]
    fn parse_volume_list_json_null_labels() {
        let json = r#"[{"Name": "mino-cache-npm-abc", "Labels": null}]"#;
        let result = parse_volume_list_json(json, "mino-cache-").unwrap();
        assert_eq!(result.len(), 1);
        assert!(result[0].labels.is_empty());
    }

    #[test]
    fn parse_volume_list_json_missing_optional_fields() {
        let json = r#"[{"Name": "mino-cache-npm-abc"}]"#;
        let result = parse_volume_list_json(json, "mino-cache-").unwrap();
        assert_eq!(result.len(), 1);
        assert!(result[0].labels.is_empty());
        assert!(result[0].mountpoint.is_none());
        assert!(result[0].created_at.is_none());
    }

    #[test]
    fn parse_volume_list_json_invalid_json() {
        let err = parse_volume_list_json("not json", "mino-cache-").unwrap_err();
        assert!(matches!(err, MinoError::Json(_)));
    }

    // -- parse_volume_inspect_json --

    #[test]
    fn parse_volume_inspect_json_single_volume() {
        let json = r#"[{
            "Name": "mino-cache-npm-abc123",
            "Mountpoint": "/var/lib/volumes/test/_data",
            "CreatedAt": "2026-03-10T12:00:00Z"
        }]"#;
        let result = parse_volume_inspect_json(json, "my-vol").unwrap().unwrap();
        // Uses the passed name, not the JSON Name field
        assert_eq!(result.name, "my-vol");
        assert_eq!(
            result.mountpoint.as_deref(),
            Some("/var/lib/volumes/test/_data")
        );
        assert_eq!(result.created_at.as_deref(), Some("2026-03-10T12:00:00Z"));
    }

    #[test]
    fn parse_volume_inspect_json_empty_string() {
        let result = parse_volume_inspect_json("", "my-vol").unwrap();
        assert!(result.is_none());
    }

    #[test]
    fn parse_volume_inspect_json_whitespace_only() {
        let result = parse_volume_inspect_json("   \n  \t  ", "my-vol").unwrap();
        assert!(result.is_none());
    }

    #[test]
    fn parse_volume_inspect_json_empty_array() {
        let result = parse_volume_inspect_json("[]", "my-vol").unwrap();
        assert!(result.is_none());
    }

    #[test]
    fn parse_volume_inspect_json_with_labels() {
        let json = r#"[{
            "Name": "vol",
            "Labels": {"io.mino.cache.state": "complete", "io.mino.cache.hash": "abc123"}
        }]"#;
        let result = parse_volume_inspect_json(json, "vol").unwrap().unwrap();
        assert_eq!(result.labels.len(), 2);
        assert_eq!(result.labels["io.mino.cache.state"], "complete");
        assert_eq!(result.labels["io.mino.cache.hash"], "abc123");
    }

    #[test]
    fn parse_volume_inspect_json_null_labels() {
        let json = r#"[{"Name": "vol", "Labels": null}]"#;
        let result = parse_volume_inspect_json(json, "vol").unwrap().unwrap();
        assert!(result.labels.is_empty());
    }

    #[test]
    fn parse_volume_inspect_json_missing_optional_fields() {
        let json = r#"[{"Name": "vol"}]"#;
        let result = parse_volume_inspect_json(json, "vol").unwrap().unwrap();
        assert!(result.mountpoint.is_none());
        assert!(result.created_at.is_none());
        assert!(result.size_bytes.is_none());
    }

    #[test]
    fn parse_volume_inspect_json_invalid_json() {
        let err = parse_volume_inspect_json("not json", "vol").unwrap_err();
        assert!(matches!(err, MinoError::Json(_)));
    }

    #[test]
    fn parse_volume_inspect_json_non_string_label_values() {
        let json = r#"[{
            "Name": "vol",
            "Labels": {"valid": "yes", "number": 99, "nested": {"a": 1}}
        }]"#;
        let result = parse_volume_inspect_json(json, "vol").unwrap().unwrap();
        assert_eq!(result.labels.len(), 1);
        assert_eq!(result.labels["valid"], "yes");
    }

    // -- follow_until_marker --

    /// Spawn a child process with piped stdout/stderr for marker tests.
    fn spawn_marker_test(script: &str) -> tokio::process::Child {
        tokio::process::Command::new("sh")
            .arg("-c")
            .arg(script)
            .stdout(std::process::Stdio::piped())
            .stderr(std::process::Stdio::piped())
            .spawn()
            .expect("failed to spawn")
    }

    /// Create a line-collecting callback for marker tests.
    fn collecting_callback() -> (impl Fn(String) + Send + Sync, Arc<Mutex<Vec<String>>>) {
        let lines = Arc::new(Mutex::new(Vec::<String>::new()));
        let lines_clone = lines.clone();
        let on_line = move |line: String| {
            lines_clone.lock().unwrap().push(line);
        };
        (on_line, lines)
    }

    #[tokio::test]
    async fn follow_until_marker_found_on_stdout() {
        let mut child =
            spawn_marker_test("echo 'line one'; echo 'READY_MARKER'; echo 'line three'");
        let (on_line, lines) = collecting_callback();

        let found = follow_until_marker(
            &mut child,
            "READY_MARKER",
            std::time::Duration::from_secs(5),
            &on_line,
        )
        .await;

        assert!(found, "marker should have been found");
        let captured = lines.lock().unwrap();
        assert!(
            captured.iter().any(|l| l.contains("READY_MARKER")),
            "captured lines should include the marker"
        );
    }

    #[tokio::test]
    async fn follow_until_marker_found_on_stderr() {
        let mut child = spawn_marker_test("echo 'stderr READY_MARKER' >&2");

        let found = follow_until_marker(
            &mut child,
            "READY_MARKER",
            std::time::Duration::from_secs(5),
            &|_| {},
        )
        .await;

        assert!(found, "marker should have been found on stderr");
    }

    #[tokio::test]
    async fn follow_until_marker_timeout_when_not_found() {
        // sleep 60 will never produce the marker, so we expect a timeout
        let mut child = tokio::process::Command::new("sleep")
            .arg("60")
            .stdout(std::process::Stdio::piped())
            .stderr(std::process::Stdio::piped())
            .spawn()
            .expect("failed to spawn");

        let found = follow_until_marker(
            &mut child,
            "NEVER_APPEARS",
            std::time::Duration::from_millis(100),
            &|_| {},
        )
        .await;

        assert!(!found, "should return false on timeout");
    }

    #[tokio::test]
    async fn follow_until_marker_eof_without_marker() {
        let mut child = spawn_marker_test("echo 'no marker here'; echo 'still no marker'");
        let (on_line, lines) = collecting_callback();

        let found = follow_until_marker(
            &mut child,
            "MISSING_MARKER",
            std::time::Duration::from_secs(5),
            &on_line,
        )
        .await;

        assert!(
            !found,
            "should return false when EOF reached without marker"
        );
        let captured = lines.lock().unwrap();
        assert_eq!(captured.len(), 2, "should have captured both output lines");
    }
}