car-sandbox 0.24.1

Sandboxed execution surface for CAR — process isolation primitives for untrusted agent steps
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
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
//! Docker-backed sandboxed ToolExecutor.

use async_trait::async_trait;
use serde_json::{json, Value};
use std::path::{Component, Path, PathBuf};
use tokio::sync::Mutex;

/// Configuration for a sandbox environment.
#[derive(Debug, Clone)]
pub struct SandboxConfig {
    /// Docker image to use (default: "python:3.11-slim").
    pub image: String,
    /// Working directory to mount into the container.
    pub working_dir: PathBuf,
    /// Additional environment variables.
    pub env: Vec<(String, String)>,
    /// Timeout for individual commands in seconds.
    pub command_timeout_secs: u64,
    /// Whether to keep the container running between commands (faster)
    /// or create a new one per command (more isolated).
    pub persistent: bool,
    /// Memory cap passed to `docker --memory` (e.g. "512m"). `None` = no limit.
    pub memory: Option<String>,
    /// Max process/thread count (`docker --pids-limit`). `None` = no limit.
    pub pids_limit: Option<u64>,
    /// CPU quota (`docker --cpus`, e.g. "1.0"). `None` = no limit.
    pub cpus: Option<String>,
    /// Drop all Linux capabilities and disallow privilege escalation
    /// (`--cap-drop ALL --security-opt no-new-privileges`). Safe for typical
    /// code workloads; on by default.
    pub drop_capabilities: bool,
    /// Read-only root filesystem with a writable tmpfs at `/tmp`. The
    /// `/workspace` mount stays writable. Off by default because some images
    /// need to write outside the workspace (e.g. `pip install`).
    pub read_only_rootfs: bool,
    /// Run container processes as this `UID[:GID]` (`docker --user`). `None` =
    /// the image default (often root). Recommended for untrusted code: set it to
    /// the host user that owns `working_dir` (e.g. `"1000:1000"`) so processes
    /// are non-root AND workspace writes keep correct host ownership. Off by
    /// default because a UID that doesn't own `working_dir` can't write to it.
    pub run_as_user: Option<String>,
}

impl Default for SandboxConfig {
    fn default() -> Self {
        Self {
            image: "python:3.11-slim".into(),
            working_dir: PathBuf::from("."),
            env: Vec::new(),
            command_timeout_secs: 120,
            persistent: true,
            // Hardened-by-default resource caps. These bound a runaway or hostile
            // workload without breaking ordinary code execution.
            memory: Some("512m".into()),
            pids_limit: Some(256),
            cpus: Some("1.0".into()),
            drop_capabilities: true,
            read_only_rootfs: false,
            run_as_user: None,
        }
    }
}

#[derive(Debug, thiserror::Error)]
pub enum SandboxError {
    #[error("Docker not available: {0}")]
    DockerNotAvailable(String),
    #[error("Container failed: {0}")]
    ContainerFailed(String),
    #[error("Command timeout after {0}s")]
    Timeout(u64),
    #[error("IO error: {0}")]
    Io(#[from] std::io::Error),
}

/// A ToolExecutor that runs shell commands inside a Docker container.
///
/// The working directory is mounted at `/workspace`, and the container runs
/// hardened by default: `--network none`, memory/pids/cpu caps, `--cap-drop ALL`
/// and `--security-opt no-new-privileges` (see [`SandboxConfig`]).
///
/// All ops — shell AND the file ops (`read_file`/`write_file`/`edit_file`/
/// `list_dir`) — execute INSIDE the container (`docker exec`), so the mount
/// namespace is the access boundary: a path cannot reach host files and there is
/// no host path to race (no TOCTOU). Caller paths are mapped to `/workspace/...`
/// by [`container_path`] (absolute paths and `..` rejected) and passed as
/// literal `docker exec` args, so they can't inject shell or options.
///
/// Boundary scope: the host is protected because only `working_dir` is
/// bind-mounted — in-container symlinks resolve within the container and cannot
/// reach the host filesystem. `container_path` confines file ops to `/workspace`
/// *lexically*; it does not chase symlinks created inside the container. That is
/// intentional and not an escalation: the only way to create such a symlink is
/// the in-container shell (`tee` writes regular files), and `exec_shell` already
/// grants full in-container access. The container itself — not `/workspace` — is
/// the trust boundary for untrusted code.
pub struct SandboxExecutor {
    config: SandboxConfig,
    /// Container ID for persistent mode.
    container_id: Mutex<Option<String>>,
    /// Files that have been read (for read-before-edit enforcement).
    read_files: std::sync::Mutex<std::collections::HashSet<String>>,
}

impl SandboxExecutor {
    /// Create a new sandbox executor. Does NOT start the container yet —
    /// that happens lazily on first command.
    pub fn new(config: SandboxConfig) -> Self {
        Self {
            config,
            container_id: Mutex::new(None),
            read_files: std::sync::Mutex::new(std::collections::HashSet::new()),
        }
    }

    /// Create with just a working directory, using defaults for everything else.
    pub fn for_dir(working_dir: impl Into<PathBuf>) -> Self {
        Self::new(SandboxConfig {
            working_dir: working_dir.into(),
            ..Default::default()
        })
    }

    /// Ensure the container is running, return its ID.
    async fn ensure_container(&self) -> Result<String, String> {
        let mut guard = self.container_id.lock().await;
        if let Some(ref id) = *guard {
            // Check if still running
            let check = tokio::process::Command::new("docker")
                .args(["inspect", "--format", "{{.State.Running}}", id])
                .output()
                .await
                .map_err(|e| format!("docker inspect failed: {}", e))?;
            if String::from_utf8_lossy(&check.stdout).trim() == "true" {
                return Ok(id.clone());
            }
        }

        // Start a new container
        let cwd = std::fs::canonicalize(&self.config.working_dir)
            .unwrap_or_else(|_| self.config.working_dir.clone());

        let container_name = format!(
            "car-sandbox-{}",
            uuid::Uuid::new_v4().to_string().split('-').next().unwrap()
        );

        let mut args = vec![
            "run".to_string(),
            "-d".into(),
            "--name".into(),
            container_name.clone(),
            "-v".into(),
            format!("{}:/workspace", cwd.display()),
            "-w".into(),
            "/workspace".into(),
            "--network".into(),
            "none".into(), // No network by default for safety
        ];

        // Resource + capability hardening.
        args.extend(hardening_args(&self.config));

        // Add environment variables
        for (k, v) in &self.config.env {
            args.push("-e".into());
            args.push(format!("{}={}", k, v));
        }

        args.push(self.config.image.clone());
        // Keep container alive with a sleep loop
        args.push("sleep".into());
        args.push("infinity".into());

        let output = tokio::process::Command::new("docker")
            .args(&args)
            .output()
            .await
            .map_err(|e| format!("failed to start container: {}", e))?;

        if !output.status.success() {
            let stderr = String::from_utf8_lossy(&output.stderr);
            return Err(format!("docker run failed: {}", stderr));
        }

        let id = String::from_utf8_lossy(&output.stdout).trim().to_string();
        tracing::info!(container_id = %id, image = %self.config.image, "sandbox container started");
        *guard = Some(id.clone());
        Ok(id)
    }

    /// Execute a command inside the container.
    async fn exec_in_container(&self, cmd: &[&str]) -> Result<(String, String, i32), String> {
        let container_id = self.ensure_container().await?;

        let timeout = std::time::Duration::from_secs(self.config.command_timeout_secs);
        let result = tokio::time::timeout(timeout, async {
            tokio::process::Command::new("docker")
                .args(["exec", &container_id])
                .args(cmd)
                .output()
                .await
        })
        .await;

        match result {
            Ok(Ok(output)) => {
                let stdout = String::from_utf8_lossy(&output.stdout).to_string();
                let stderr = String::from_utf8_lossy(&output.stderr).to_string();
                let code = output.status.code().unwrap_or(-1);
                Ok((stdout, stderr, code))
            }
            Ok(Err(e)) => Err(format!("exec failed: {}", e)),
            Err(_) => Err(format!(
                "command timed out after {}s",
                self.config.command_timeout_secs
            )),
        }
    }

    /// Stop and remove the container.
    pub async fn cleanup(&self) {
        let mut guard = self.container_id.lock().await;
        if let Some(ref id) = *guard {
            let _ = tokio::process::Command::new("docker")
                .args(["rm", "-f", id])
                .output()
                .await;
            tracing::info!(container_id = %id, "sandbox container removed");
        }
        *guard = None;
    }

    // --- Tool implementations ---

    async fn exec_shell(&self, params: &Value) -> Result<Value, String> {
        let command = params
            .get("command")
            .and_then(|v| v.as_str())
            .ok_or("missing 'command' parameter")?;

        let (stdout, stderr, exit_code) = self.exec_in_container(&["sh", "-c", command]).await?;

        Ok(json!({
            "stdout": stdout,
            "stderr": stderr,
            "exit_code": exit_code,
        }))
    }

    /// Run a command inside the container, feeding `stdin_data` to its stdin.
    /// Used for writes (`tee`) so content of any size/bytes is delivered without
    /// shell interpolation.
    async fn exec_in_container_stdin(
        &self,
        cmd: &[&str],
        stdin_data: &[u8],
    ) -> Result<(String, String, i32), String> {
        use tokio::io::AsyncWriteExt;
        let container_id = self.ensure_container().await?;
        let timeout = std::time::Duration::from_secs(self.config.command_timeout_secs);

        let run = async {
            let mut child = tokio::process::Command::new("docker")
                .args(["exec", "-i", &container_id])
                .args(cmd)
                .stdin(std::process::Stdio::piped())
                // Discard stdout: `tee` echoes its (possibly large) input to
                // stdout, and we don't read it until after writing all of stdin.
                // Piping it would deadlock once the input exceeds the pipe buffer
                // (~64KB). We only need the file write + exit status + stderr.
                .stdout(std::process::Stdio::null())
                .stderr(std::process::Stdio::piped())
                .spawn()
                .map_err(|e| format!("exec spawn failed: {e}"))?;
            if let Some(mut si) = child.stdin.take() {
                si.write_all(stdin_data)
                    .await
                    .map_err(|e| format!("stdin write: {e}"))?;
                let _ = si.shutdown().await; // close stdin so the writer finishes
            }
            child
                .wait_with_output()
                .await
                .map_err(|e| format!("exec wait: {e}"))
        };

        match tokio::time::timeout(timeout, run).await {
            Ok(Ok(output)) => Ok((
                String::from_utf8_lossy(&output.stdout).to_string(),
                String::from_utf8_lossy(&output.stderr).to_string(),
                output.status.code().unwrap_or(-1),
            )),
            Ok(Err(e)) => Err(e),
            Err(_) => Err(format!(
                "command timed out after {}s",
                self.config.command_timeout_secs
            )),
        }
    }

    async fn exec_read_file(&self, params: &Value) -> Result<Value, String> {
        let path = params
            .get("path")
            .and_then(|v| v.as_str())
            .ok_or("missing 'path' parameter")?;
        let offset = params.get("offset").and_then(|v| v.as_u64()).unwrap_or(0) as usize;
        let limit = params
            .get("limit")
            .and_then(|v| v.as_u64())
            .map(|v| v as usize);

        // Read INSIDE the container so the mount namespace is the boundary — the
        // path can't reach host files, and there is no host path to race
        // (TOCTOU). `--` + literal arg prevents option/shell injection.
        let cpath = container_path(path)?;
        let (content, stderr, code) = self.exec_in_container(&["cat", "--", &cpath]).await?;
        if code != 0 {
            return Err(format!("failed to read file: {}", stderr.trim()));
        }

        let total_lines = content.lines().count();

        let result = if offset > 0 || limit.is_some() {
            let lines: Vec<&str> = content.lines().collect();
            let start = offset.min(lines.len());
            let end = limit
                .map(|l| (start + l).min(lines.len()))
                .unwrap_or(lines.len());
            lines[start..end].join("\n")
        } else {
            content
        };

        // Track as read
        if let Ok(mut set) = self.read_files.lock() {
            set.insert(path.to_string());
        }

        Ok(json!({ "content": result, "total_lines": total_lines }))
    }

    async fn exec_write_file(&self, params: &Value) -> Result<Value, String> {
        let path = params
            .get("path")
            .and_then(|v| v.as_str())
            .ok_or("missing 'path' parameter")?;
        let content = params
            .get("content")
            .and_then(|v| v.as_str())
            .ok_or("missing 'content' parameter")?;

        let cpath = container_path(path)?;
        // Create parent dirs inside the container, then write via `tee` over
        // stdin (binary-safe, no shell interpolation).
        if let Some(parent) = std::path::Path::new(&cpath).parent() {
            let parent = parent.to_string_lossy().to_string();
            let _ = self.exec_in_container(&["mkdir", "-p", "--", &parent]).await;
        }
        let (_out, stderr, code) = self
            .exec_in_container_stdin(&["tee", "--", &cpath], content.as_bytes())
            .await?;
        if code != 0 {
            return Err(format!("failed to write file: {}", stderr.trim()));
        }

        if let Ok(mut set) = self.read_files.lock() {
            set.insert(path.to_string());
        }

        Ok(json!({ "written": path }))
    }

    async fn exec_edit_file(&self, params: &Value) -> Result<Value, String> {
        let path = params
            .get("path")
            .and_then(|v| v.as_str())
            .ok_or("missing 'path' parameter")?;
        let old_text = params
            .get("old_text")
            .and_then(|v| v.as_str())
            .ok_or("missing 'old_text' parameter")?;
        let new_text = params
            .get("new_text")
            .and_then(|v| v.as_str())
            .ok_or("missing 'new_text' parameter")?;

        let cpath = container_path(path)?;
        let (content, stderr, code) = self.exec_in_container(&["cat", "--", &cpath]).await?;
        if code != 0 {
            return Err(format!("failed to read file: {}", stderr.trim()));
        }

        let count = content.matches(old_text).count();
        if count == 0 {
            // Try whitespace-normalized match
            let normalize = |s: &str| -> String {
                s.lines()
                    .map(|l| l.trim_end())
                    .collect::<Vec<_>>()
                    .join("\n")
            };
            let norm_content = normalize(&content);
            let norm_old = normalize(old_text);
            if norm_content.matches(&norm_old).count() == 1 {
                let norm_pos = norm_content.find(&norm_old).unwrap();
                let start_line = norm_content[..norm_pos].matches('\n').count();
                let old_line_count = old_text.lines().count();
                let actual_lines: Vec<&str> = content.lines().collect();
                let end_line = (start_line + old_line_count).min(actual_lines.len());
                let actual_old = actual_lines[start_line..end_line].join("\n");
                if content.matches(&actual_old).count() == 1 {
                    let new_content = content.replacen(&actual_old, new_text, 1);
                    let (_o, e2, c2) = self
                        .exec_in_container_stdin(&["tee", "--", &cpath], new_content.as_bytes())
                        .await?;
                    if c2 != 0 {
                        return Err(format!("failed to write: {}", e2.trim()));
                    }
                    return Ok(json!({
                        "edited": path,
                        "diff_summary": "whitespace-normalized match",
                    }));
                }
            }

            let first_line = old_text.lines().next().unwrap_or("").trim();
            let mut hint = String::new();
            if !first_line.is_empty() {
                for (i, line) in content.lines().enumerate() {
                    if line.contains(first_line) {
                        let lines: Vec<&str> = content.lines().collect();
                        let start = i.saturating_sub(2);
                        let end = (i + old_text.lines().count() + 2).min(lines.len());
                        hint = format!(
                            "\nActual content at lines {}-{}:\n```\n{}\n```",
                            start + 1,
                            end,
                            lines[start..end].join("\n")
                        );
                        break;
                    }
                }
            }
            return Err(format!("old_text not found in {}.{}", path, hint));
        }
        if count > 1 {
            return Err(format!(
                "old_text found {} times in {} — must be unique",
                count, path
            ));
        }

        let new_content = content.replacen(old_text, new_text, 1);
        let (_o, e2, c2) = self
            .exec_in_container_stdin(&["tee", "--", &cpath], new_content.as_bytes())
            .await?;
        if c2 != 0 {
            return Err(format!("failed to write: {}", e2.trim()));
        }

        let old_lines = old_text.lines().count();
        let new_lines = new_text.lines().count();
        let diff_summary = format!("replaced {} lines with {} lines", old_lines, new_lines);

        Ok(json!({
            "edited": path,
            "diff_summary": diff_summary,
            "new_content": if new_text.len() > 2000 { &new_text[..2000] } else { new_text },
        }))
    }

    async fn exec_list_dir(&self, params: &Value) -> Result<Value, String> {
        let path = params.get("path").and_then(|v| v.as_str()).unwrap_or(".");
        let cpath = container_path(path)?;

        // `ls -1p` inside the container: one entry per line, directories marked
        // with a trailing '/'. Hidden entries are excluded (no -a/-A).
        let (stdout, stderr, code) = self.exec_in_container(&["ls", "-1p", "--", &cpath]).await?;
        if code != 0 {
            return Err(format!("failed to read dir: {}", stderr.trim()));
        }

        let mut entries = Vec::new();
        for line in stdout.lines() {
            if line.is_empty() {
                continue;
            }
            let (name, is_dir) = match line.strip_suffix('/') {
                Some(n) => (n, true),
                None => (line, false),
            };
            entries.push(json!({ "name": name, "is_dir": is_dir }));
        }

        Ok(json!({ "entries": entries }))
    }

    async fn exec_grep_files(&self, params: &Value) -> Result<Value, String> {
        let pattern = params
            .get("pattern")
            .and_then(|v| v.as_str())
            .ok_or("missing 'pattern' parameter")?;
        let path = params.get("path").and_then(|v| v.as_str()).unwrap_or(".");
        // Confine to the workspace (same rule as the file ops) — also makes the
        // search-root always `/workspace/...`, so it can't be a grep option.
        let cpath = container_path(path)?;
        let max_results = params
            .get("max_results")
            .and_then(|v| v.as_u64())
            .unwrap_or(50) as usize;

        // Run grep inside the container. pattern/path/limit are passed as
        // positional args ($1/$2/$3), NOT interpolated into the script, so a
        // crafted pattern/path can't inject shell commands.
        let script = "grep -rn -E \
            --include='*.py' --include='*.rs' --include='*.js' --include='*.ts' \
            --include='*.go' --include='*.java' --include='*.toml' --include='*.json' \
            --include='*.yaml' --include='*.yml' --include='*.html' --include='*.css' \
            --include='*.sh' --include='*.txt' --include='*.cfg' --include='*.ini' \
            -- \"$1\" \"$2\" | head -n \"$3\"";
        let max_str = max_results.to_string();
        let (stdout, _stderr, _code) = self
            .exec_in_container(&["sh", "-c", script, "sh", pattern, &cpath, &max_str])
            .await?;
        let lines: Vec<&str> = stdout.lines().take(max_results).collect();

        Ok(json!({
            "matches": lines,
            "count": lines.len(),
            "truncated": stdout.lines().count() > max_results,
        }))
    }

    async fn exec_find_files(&self, params: &Value) -> Result<Value, String> {
        let pattern = params
            .get("pattern")
            .and_then(|v| v.as_str())
            .ok_or("missing 'pattern' parameter")?;
        let path = params.get("path").and_then(|v| v.as_str()).unwrap_or(".");
        // Confine to the workspace; the search root is then always
        // `/workspace/...`, so it can't be misread as a `find` expression token.
        let cpath = container_path(path)?;

        // path/pattern as positional args ($1/$2) — no shell interpolation.
        let script = "find \"$1\" -name \"$2\" \
            -not -path '*/.*' -not -path '*/node_modules/*' -not -path '*/__pycache__/*' \
            | head -50";
        let (stdout, _stderr, _code) = self
            .exec_in_container(&["sh", "-c", script, "sh", &cpath, pattern])
            .await?;
        let files: Vec<&str> = stdout.lines().collect();

        Ok(json!({ "files": files, "count": files.len() }))
    }
}

#[async_trait]
impl car_engine::ToolExecutor for SandboxExecutor {
    async fn execute(&self, tool: &str, params: &Value) -> Result<Value, String> {
        match tool {
            "shell" => self.exec_shell(params).await,
            "read_file" => self.exec_read_file(params).await,
            "write_file" => self.exec_write_file(params).await,
            "edit_file" => self.exec_edit_file(params).await,
            "list_dir" => self.exec_list_dir(params).await,
            "grep_files" => self.exec_grep_files(params).await,
            "find_files" => self.exec_find_files(params).await,
            "git_status" | "git_diff" | "git_log" | "git_add" | "git_commit" => {
                // Git operations run on host via the mounted volume
                let git_cmd = match tool {
                    "git_status" => "git status --short",
                    "git_diff" => {
                        let staged = params
                            .get("staged")
                            .and_then(|v| v.as_bool())
                            .unwrap_or(false);
                        if staged {
                            "git diff --cached"
                        } else {
                            "git diff"
                        }
                    }
                    "git_log" => "git log --oneline -20",
                    _ => return Err(format!("git tool {} not implemented in sandbox", tool)),
                };
                self.exec_shell(&json!({ "command": git_cmd })).await
            }
            _ => Err(format!("unknown tool in sandbox: {}", tool)),
        }
    }
}

impl Drop for SandboxExecutor {
    fn drop(&mut self) {
        // Best-effort cleanup — can't async in Drop, so use blocking
        if let Ok(guard) = self.container_id.try_lock() {
            if let Some(ref id) = *guard {
                let _ = std::process::Command::new("docker")
                    .args(["rm", "-f", id])
                    .output();
            }
        }
    }
}

/// Map a caller-supplied path to an absolute in-container path under
/// `/workspace`. Rejects absolute paths and any `..` component, so the result is
/// always a plain workspace-relative path. The container mount namespace is the
/// real boundary — this is pure string mapping, with no host filesystem access
/// and therefore no check-then-use (TOCTOU) window.
fn container_path(path: &str) -> Result<String, String> {
    if path.is_empty() {
        return Err("path must not be empty (use \".\" for the workspace root)".to_string());
    }
    let rel = Path::new(path);
    if rel.is_absolute() {
        return Err(format!("path '{path}' must be relative to the workspace"));
    }
    let mut out = String::from("/workspace");
    for comp in rel.components() {
        match comp {
            Component::CurDir => {}
            Component::Normal(s) => {
                out.push('/');
                out.push_str(&s.to_string_lossy());
            }
            Component::ParentDir => {
                return Err(format!("path '{path}' may not contain '..'"))
            }
            Component::RootDir | Component::Prefix(_) => {
                return Err(format!("invalid workspace path '{path}'"))
            }
        }
    }
    Ok(out)
}

/// Build the resource/capability `docker run` flags for a config. Pure so the
/// hardening profile is unit-testable without invoking docker.
fn hardening_args(config: &SandboxConfig) -> Vec<String> {
    let mut args = Vec::new();
    if let Some(mem) = &config.memory {
        args.push("--memory".into());
        args.push(mem.clone());
        // Pin swap to the memory limit so the cap can't be evaded via swap.
        args.push("--memory-swap".into());
        args.push(mem.clone());
    }
    if let Some(pids) = config.pids_limit {
        args.push("--pids-limit".into());
        args.push(pids.to_string());
    }
    if let Some(cpus) = &config.cpus {
        args.push("--cpus".into());
        args.push(cpus.clone());
    }
    if config.drop_capabilities {
        args.push("--cap-drop".into());
        args.push("ALL".into());
        args.push("--security-opt".into());
        args.push("no-new-privileges".into());
    }
    if config.read_only_rootfs {
        args.push("--read-only".into());
        // Rootfs is read-only, so give the workload a writable scratch area
        // (the /workspace bind mount stays writable independently).
        args.push("--tmpfs".into());
        args.push("/tmp:rw,size=512m".into());
    }
    if let Some(user) = &config.run_as_user {
        args.push("--user".into());
        args.push(user.clone());
    }
    args
}

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

    #[test]
    fn sandbox_config_defaults() {
        let config = SandboxConfig::default();
        assert_eq!(config.image, "python:3.11-slim");
        assert!(config.persistent);
        assert_eq!(config.command_timeout_secs, 120);
        // Hardened by default.
        assert_eq!(config.memory.as_deref(), Some("512m"));
        assert_eq!(config.pids_limit, Some(256));
        assert_eq!(config.cpus.as_deref(), Some("1.0"));
        assert!(config.drop_capabilities);
        assert!(!config.read_only_rootfs);
    }

    #[test]
    fn default_hardening_flags_are_emitted() {
        let args = hardening_args(&SandboxConfig::default());
        let joined = args.join(" ");
        assert!(joined.contains("--memory 512m"));
        assert!(joined.contains("--memory-swap 512m"));
        assert!(joined.contains("--pids-limit 256"));
        assert!(joined.contains("--cpus 1.0"));
        assert!(joined.contains("--cap-drop ALL"));
        assert!(joined.contains("--security-opt no-new-privileges"));
        // Read-only rootfs is opt-in.
        assert!(!joined.contains("--read-only"));
    }

    #[test]
    fn run_as_user_emitted_when_set() {
        let config = SandboxConfig {
            run_as_user: Some("1000:1000".into()),
            ..Default::default()
        };
        let joined = hardening_args(&config).join(" ");
        assert!(joined.contains("--user 1000:1000"));
        // Off by default.
        assert!(!hardening_args(&SandboxConfig::default())
            .join(" ")
            .contains("--user"));
    }

    #[test]
    fn read_only_rootfs_adds_tmpfs_when_enabled() {
        let config = SandboxConfig {
            read_only_rootfs: true,
            ..Default::default()
        };
        let joined = hardening_args(&config).join(" ");
        assert!(joined.contains("--read-only"));
        assert!(joined.contains("--tmpfs /tmp:rw,size=512m"));
    }

    #[test]
    fn limits_can_be_disabled() {
        let config = SandboxConfig {
            memory: None,
            pids_limit: None,
            cpus: None,
            drop_capabilities: false,
            ..Default::default()
        };
        assert!(hardening_args(&config).is_empty());
    }

    #[test]
    fn container_path_maps_relative_paths_under_workspace() {
        assert_eq!(container_path("file.txt").unwrap(), "/workspace/file.txt");
        assert_eq!(
            container_path("sub/dir/file.txt").unwrap(),
            "/workspace/sub/dir/file.txt"
        );
        // `.` and `./` normalize to the workspace root.
        assert_eq!(container_path(".").unwrap(), "/workspace");
        assert_eq!(container_path("./a").unwrap(), "/workspace/a");
    }

    #[test]
    fn container_path_rejects_absolute_and_traversal() {
        assert!(container_path("/etc/passwd")
            .unwrap_err()
            .contains("must be relative"));
        assert!(container_path("../../etc/passwd")
            .unwrap_err()
            .contains("'..'"));
        assert!(container_path("sub/../../etc")
            .unwrap_err()
            .contains("'..'"));
        assert!(container_path("").unwrap_err().contains("must not be empty"));
    }
}