orchestrator-runner 0.2.5

Command runner, sandbox, output capture, and network allowlist
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
use super::profile::ResolvedExecutionProfile;
use anyhow::Result;
#[cfg(target_os = "linux")]
use orchestrator_config::config::ExecutionFsMode;
use orchestrator_config::config::{ExecutionNetworkMode, ExecutionProfileMode, RunnerConfig};
use std::io;

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[allow(dead_code)] // Variants are platform-specific; not all used on every OS.
pub(crate) enum SandboxBackend {
    Host,
    MacosSeatbelt,
    LinuxNative,
    Unavailable,
}

impl SandboxBackend {
    pub(crate) fn label(self) -> &'static str {
        match self {
            Self::Host => "host",
            Self::MacosSeatbelt => "macos_seatbelt",
            Self::LinuxNative => "linux_native",
            Self::Unavailable => "sandbox_unavailable",
        }
    }
}

#[derive(Debug, Clone)]
pub(crate) struct LinuxSandboxSupport {
    pub(crate) backend: SandboxBackend,
    pub(crate) missing_requirements: Vec<String>,
}

impl LinuxSandboxSupport {
    pub(crate) fn available(&self) -> bool {
        self.backend == SandboxBackend::LinuxNative && self.missing_requirements.is_empty()
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
/// Resource limits that can trigger sandbox spawn failures.
pub enum SandboxResourceKind {
    /// Memory limit exhaustion.
    Memory,
    /// CPU time limit exhaustion.
    Cpu,
    /// Process-count limit exhaustion.
    Processes,
    /// File-descriptor limit exhaustion.
    OpenFiles,
}

impl SandboxResourceKind {
    /// Returns the stable event payload label for the resource kind.
    pub fn as_str(&self) -> &'static str {
        match self {
            Self::Memory => "memory",
            Self::Cpu => "cpu",
            Self::Processes => "processes",
            Self::OpenFiles => "open_files",
        }
    }
}

#[derive(Debug)]
/// Structured error emitted when sandbox backend selection or execution fails.
pub struct SandboxBackendError {
    /// Name of the execution profile that triggered the error.
    pub execution_profile: String,
    /// Label of the selected or attempted sandbox backend.
    pub backend: &'static str,
    /// Event type emitted to observability and callers.
    pub event_type: &'static str,
    /// Stable reason code for programmatic handling.
    pub reason_code: &'static str,
    /// Resource limit kind when the error was caused by resource exhaustion.
    pub resource_kind: Option<SandboxResourceKind>,
    message: String,
}

impl SandboxBackendError {
    pub(crate) fn unsupported_network_allowlist(
        execution_profile: &ResolvedExecutionProfile,
        backend: SandboxBackend,
    ) -> Self {
        Self {
            execution_profile: execution_profile.name.clone(),
            backend: backend.label(),
            event_type: "sandbox_network_blocked",
            reason_code: "unsupported_backend_feature",
            resource_kind: None,
            message: format!(
                "sandbox backend '{}' does not support network allowlists for execution profile '{}'",
                backend.label(),
                execution_profile.name
            ),
        }
    }

    pub(crate) fn backend_unavailable(
        execution_profile: &ResolvedExecutionProfile,
        backend: SandboxBackend,
        detail: Option<&str>,
    ) -> Self {
        let suffix = detail
            .filter(|value| !value.trim().is_empty())
            .map(|value| format!(": {value}"))
            .unwrap_or_default();
        Self {
            execution_profile: execution_profile.name.clone(),
            backend: backend.label(),
            event_type: "sandbox_denied",
            reason_code: "sandbox_backend_unavailable",
            resource_kind: None,
            message: format!(
                "sandbox backend '{}' is unavailable for execution profile '{}'{}",
                backend.label(),
                execution_profile.name,
                suffix
            ),
        }
    }

    pub(crate) fn resource_exhausted(
        execution_profile: &ResolvedExecutionProfile,
        resource_kind: SandboxResourceKind,
        source: &io::Error,
    ) -> Self {
        let reason_code = match resource_kind {
            SandboxResourceKind::Memory => "memory_limit_exceeded",
            SandboxResourceKind::Cpu => "cpu_limit_exceeded",
            SandboxResourceKind::Processes => "processes_limit_exceeded",
            SandboxResourceKind::OpenFiles => "open_files_limit_exceeded",
        };
        Self {
            execution_profile: execution_profile.name.clone(),
            backend: sandbox_backend_label(execution_profile),
            event_type: "sandbox_resource_exceeded",
            reason_code,
            resource_kind: Some(resource_kind),
            message: format!(
                "sandbox process spawn failed under execution profile '{}': {}",
                execution_profile.name, source
            ),
        }
    }
}

impl std::fmt::Display for SandboxBackendError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(&self.message)
    }
}

impl std::error::Error for SandboxBackendError {}

/// Returns the effective sandbox backend label for an execution profile.
pub fn sandbox_backend_label(execution_profile: &ResolvedExecutionProfile) -> &'static str {
    select_sandbox_backend(execution_profile).label()
}

/// Validates that the current host can satisfy the requested execution profile.
pub fn validate_execution_profile_support(
    execution_profile: &ResolvedExecutionProfile,
) -> Result<()> {
    if execution_profile.mode != ExecutionProfileMode::Sandbox {
        return Ok(());
    }
    let backend = select_sandbox_backend(execution_profile);
    match backend {
        SandboxBackend::Host => Ok(()),
        SandboxBackend::MacosSeatbelt => {
            if execution_profile.network_mode == ExecutionNetworkMode::Allowlist {
                return Err(SandboxBackendError::unsupported_network_allowlist(
                    execution_profile,
                    backend,
                )
                .into());
            }
            Ok(())
        }
        SandboxBackend::LinuxNative => {
            let support = detect_linux_sandbox_support(execution_profile);
            if support.available() {
                Ok(())
            } else {
                Err(SandboxBackendError::backend_unavailable(
                    execution_profile,
                    support.backend,
                    Some(&support.missing_requirements.join(", ")),
                )
                .into())
            }
        }
        SandboxBackend::Unavailable => {
            Err(SandboxBackendError::backend_unavailable(execution_profile, backend, None).into())
        }
    }
}

/// Returns non-fatal preflight issues for the execution profile's sandbox backend.
pub fn sandbox_backend_preflight_issues(
    execution_profile: &ResolvedExecutionProfile,
) -> Vec<String> {
    if execution_profile.mode != ExecutionProfileMode::Sandbox {
        return Vec::new();
    }
    match select_sandbox_backend(execution_profile) {
        SandboxBackend::LinuxNative => {
            detect_linux_sandbox_support(execution_profile).missing_requirements
        }
        SandboxBackend::MacosSeatbelt
            if execution_profile.network_mode == ExecutionNetworkMode::Allowlist =>
        {
            vec!["macos_seatbelt does not support network_mode=allowlist".to_string()]
        }
        SandboxBackend::Unavailable => {
            vec!["sandbox backend is unavailable on this platform".to_string()]
        }
        _ => Vec::new(),
    }
}

pub(crate) fn select_sandbox_backend(
    execution_profile: &ResolvedExecutionProfile,
) -> SandboxBackend {
    match execution_profile.mode {
        ExecutionProfileMode::Host => SandboxBackend::Host,
        ExecutionProfileMode::Sandbox => {
            #[cfg(target_os = "macos")]
            {
                SandboxBackend::MacosSeatbelt
            }
            #[cfg(target_os = "linux")]
            {
                SandboxBackend::LinuxNative
            }
            #[cfg(not(any(target_os = "macos", target_os = "linux")))]
            {
                SandboxBackend::Unavailable
            }
        }
    }
}

pub(crate) fn detect_linux_sandbox_support(
    execution_profile: &ResolvedExecutionProfile,
) -> LinuxSandboxSupport {
    #[cfg(target_os = "linux")]
    {
        use super::sandbox_linux::command_exists;

        let mut missing = Vec::new();
        for binary in ["ip", "nft"] {
            if !command_exists(binary) {
                missing.push(format!("missing '{binary}' in PATH"));
            }
        }
        if execution_profile.fs_mode != ExecutionFsMode::Inherit {
            missing.push(
                "linux_native currently requires fs_mode=inherit until a Linux filesystem backend is implemented"
                    .to_string(),
            );
        }
        if nix::unistd::geteuid().as_raw() != 0 {
            missing.push("linux_native requires the daemon to run as root".to_string());
        }
        LinuxSandboxSupport {
            backend: SandboxBackend::LinuxNative,
            missing_requirements: missing,
        }
    }
    #[cfg(not(target_os = "linux"))]
    {
        let _ = execution_profile;
        LinuxSandboxSupport {
            backend: SandboxBackend::Unavailable,
            missing_requirements: vec![
                "linux_native backend is only available on Linux".to_string(),
            ],
        }
    }
}

pub(crate) fn classify_sandbox_spawn_error(
    execution_profile: &ResolvedExecutionProfile,
    err: &io::Error,
) -> Option<SandboxBackendError> {
    if execution_profile.mode != ExecutionProfileMode::Sandbox {
        return None;
    }
    let lower = err.to_string().to_lowercase();
    if execution_profile.max_memory_mb.is_some()
        && (lower.contains("cannot allocate memory")
            || lower.contains("not enough space")
            || lower.contains("not enough memory")
            || lower.contains("memory"))
    {
        return Some(SandboxBackendError::resource_exhausted(
            execution_profile,
            SandboxResourceKind::Memory,
            err,
        ));
    }
    if execution_profile.max_processes.is_some()
        && lower.contains("resource temporarily unavailable")
    {
        return Some(SandboxBackendError::resource_exhausted(
            execution_profile,
            SandboxResourceKind::Processes,
            err,
        ));
    }
    if execution_profile.max_open_files.is_some() && lower.contains("too many open files") {
        return Some(SandboxBackendError::resource_exhausted(
            execution_profile,
            SandboxResourceKind::OpenFiles,
            err,
        ));
    }
    let mut configured_limits = Vec::new();
    if execution_profile.max_memory_mb.is_some() {
        configured_limits.push(SandboxResourceKind::Memory);
    }
    if execution_profile.max_processes.is_some() {
        configured_limits.push(SandboxResourceKind::Processes);
    }
    if execution_profile.max_open_files.is_some() {
        configured_limits.push(SandboxResourceKind::OpenFiles);
    }
    if execution_profile.max_cpu_seconds.is_some() {
        configured_limits.push(SandboxResourceKind::Cpu);
    }
    if configured_limits.len() == 1 {
        return Some(SandboxBackendError::resource_exhausted(
            execution_profile,
            configured_limits.remove(0),
            err,
        ));
    }
    None
}

pub(crate) fn build_command_for_profile(
    runner: &RunnerConfig,
    command: &str,
    cwd: &std::path::Path,
    execution_profile: &ResolvedExecutionProfile,
) -> Result<tokio::process::Command> {
    let mut cmd = match execution_profile.mode {
        ExecutionProfileMode::Host => {
            let mut cmd = tokio::process::Command::new(&runner.shell);
            cmd.arg(&runner.shell_arg).arg(command);
            cmd
        }
        ExecutionProfileMode::Sandbox => build_sandbox_command(runner, command, execution_profile)?,
    };
    cmd.current_dir(cwd);
    Ok(cmd)
}

pub(crate) fn build_sandbox_command(
    runner: &RunnerConfig,
    command: &str,
    execution_profile: &ResolvedExecutionProfile,
) -> Result<tokio::process::Command> {
    let backend = select_sandbox_backend(execution_profile);
    match backend {
        SandboxBackend::MacosSeatbelt => {
            #[cfg(target_os = "macos")]
            {
                use super::sandbox_macos::build_macos_sandbox_profile;
                let mut cmd = tokio::process::Command::new("/usr/bin/sandbox-exec");
                cmd.arg("-p")
                    .arg(build_macos_sandbox_profile(execution_profile))
                    .arg(&runner.shell)
                    .arg(&runner.shell_arg)
                    .arg(command);
                Ok(cmd)
            }
            #[cfg(not(target_os = "macos"))]
            {
                let _ = (runner, command);
                Err(
                    SandboxBackendError::backend_unavailable(execution_profile, backend, None)
                        .into(),
                )
            }
        }
        SandboxBackend::LinuxNative => {
            #[cfg(target_os = "linux")]
            {
                use super::sandbox_linux::build_linux_sandbox_command;
                build_linux_sandbox_command(runner, command, execution_profile)
            }
            #[cfg(not(target_os = "linux"))]
            {
                let _ = (runner, command);
                Err(
                    SandboxBackendError::backend_unavailable(execution_profile, backend, None)
                        .into(),
                )
            }
        }
        _ => Err(SandboxBackendError::backend_unavailable(execution_profile, backend, None).into()),
    }
}