funera-core 0.3.0

Core LLM agent engine — ReAct loop, providers, tools, skills, middleware, security
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
650
use std::path::PathBuf;

use serde::{Deserialize, Serialize};

#[cfg(all(feature = "sandbox", not(target_os = "windows")))]
use nono::{AccessMode, CapabilitySet};

#[cfg(all(feature = "sandbox", not(target_os = "windows")))]
use std::os::unix::process::CommandExt;

#[cfg(all(feature = "sandbox", target_os = "windows"))]
use super::sandbox_win::WindowsSandbox;

/// Policy config for kernel-enforced sandboxing.
///
/// On Linux/macOS the policy maps to a [`nono::CapabilitySet`] that grants
/// Landlock (Linux 5.13+) or Seatbelt (macOS) access rights. On Windows it
/// configures a Write-Restricted Token + ACLs via [`WindowsSandbox`].
///
/// When `enabled` is true and the platform supports it, each tool
/// subprocess will be restricted to only the granted capabilities.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SandboxPolicy {
    /// Master switch — set to `false` to disable kernel sandboxing
    /// while keeping the policy definition in the config.
    #[serde(default = "default_enabled")]
    pub enabled: bool,

    /// Paths the tool subprocess may read (and traverse, list, …).
    #[serde(default)]
    pub read_paths: Vec<PathBuf>,

    /// Paths the tool subprocess may both read and write.
    #[serde(default)]
    pub read_write_paths: Vec<PathBuf>,

    /// Paths the tool subprocess may execute (binaries, scripts, …).
    #[serde(default)]
    pub execute_paths: Vec<PathBuf>,

    /// When `true`, all outbound network access is blocked at the
    /// kernel level (via Landlock scoped network, or seccomp fallback).
    #[serde(default = "default_block_network")]
    pub block_network: bool,

    /// Maximum resident memory for the process tree, in bytes.
    /// `None` means no memory limit.
    #[serde(default)]
    pub memory_limit_bytes: Option<u64>,
}

fn default_enabled() -> bool {
    true
}
fn default_block_network() -> bool {
    true
}

impl Default for SandboxPolicy {
    //TODO: better sandbox default
    fn default() -> Self {
        Self {
            enabled: true,
            read_paths: vec![],
            read_write_paths: vec![],
            execute_paths: vec![],
            block_network: true,
            memory_limit_bytes: None,
        }
    }
}

impl SandboxPolicy {
    /// Fully permissive: sandboxing disabled.
    pub fn disabled() -> Self {
        Self {
            enabled: false,
            ..Default::default()
        }
    }

    /// Strict policy: only the given read-write dir allowed, network blocked.
    pub fn strict_read_write(dir: PathBuf) -> Self {
        Self {
            enabled: true,
            read_paths: vec![],
            read_write_paths: vec![dir],
            execute_paths: vec![],
            block_network: true,
            memory_limit_bytes: None,
        }
    }

    /// Build a capability set from this policy for kernel-enforced
    /// sandboxing (Landlock on Linux, Seatbelt on macOS).
    ///
    /// Returns an error if any path cannot be resolved or if the
    /// platform lacks sandbox support. Callers should check
    /// [`enabled`](Self::enabled) first.
    ///
    /// **Not available on Windows** — the underlying `nono` crate does not
    /// support Windows natively. On Windows, callers should use
    /// [`Sandbox`] instead, which delegates to [`WindowsSandbox`].
    #[cfg(all(feature = "sandbox", not(target_os = "windows")))]
    pub fn to_capability_set(&self) -> Result<CapabilitySet, nono::NonoError> {
        let mut caps = CapabilitySet::new();

        for path in &self.read_paths {
            caps = caps.allow_path(path, AccessMode::Read)?;
        }
        for path in &self.read_write_paths {
            caps = caps.allow_path(path, AccessMode::ReadWrite)?;
        }
        for path in &self.execute_paths {
            caps = caps.allow_path(path, AccessMode::Read)?;
        }

        if self.block_network {
            caps = caps.block_network();
        }

        Ok(caps)
    }

    /// Check whether a path is within the sandbox boundary.
    ///
    /// A path is considered inside if it is a descendant (or exact match)
    /// of any configured `read_path`, `read_write_path`, or `execute_path`.
    /// Paths outside this perimeter are rejected by the boundary check.
    #[cfg(feature = "sandbox")]
    pub fn is_within_boundary(&self, path: &std::path::Path) -> bool {
        if !self.enabled {
            return true;
        }
        let canonical = path.canonicalize().unwrap_or_else(|_| path.to_path_buf());
        for root in self.read_paths.iter().chain(self.read_write_paths.iter()) {
            let root_canon = root.canonicalize().unwrap_or_else(|_| root.clone());
            if canonical.starts_with(&root_canon) {
                return true;
            }
        }
        false
    }

    /// A human-readable summary for diagnostics / auditing.
    pub fn summary(&self) -> String {
        if !self.enabled {
            return "sandbox disabled".into();
        }
        let parts: Vec<String> = std::iter::once(if self.block_network {
            "no-net".into()
        } else {
            "net-allowed".into()
        })
        .chain(self.read_paths.iter().map(|p| format!("r:{}", p.display())))
        .chain(
            self.read_write_paths
                .iter()
                .map(|p| format!("rw:{}", p.display())),
        )
        .chain(
            self.execute_paths
                .iter()
                .map(|p| format!("x:{}", p.display())),
        )
        .collect();
        parts.join(", ")
    }
}

// ── platform-independent Sandbox runner ────────────────────────────

/// A sandbox runner that enforces [`SandboxPolicy`] on any supported OS.
///
/// | Platform | Mechanism |
/// |----------|-----------|
/// | Linux   | Landlock via `nono` `pre_exec` hook |
/// | macOS   | Seatbelt via `nono` `pre_exec` hook |
/// | Windows | Write-Restricted Token + ACLs |
///
/// # Failover
///
/// If the platform-specific mechanism cannot be applied (e.g. kernel too old,
/// missing privileges), execution falls back to a normal subprocess with
/// network restrictions only.
pub struct Sandbox {
    #[cfg(all(feature = "sandbox", target_os = "windows"))]
    inner: WindowsSandbox,
    #[cfg(all(feature = "sandbox", not(target_os = "windows")))]
    policy: SandboxPolicy,
    #[cfg(not(feature = "sandbox"))]
    _private: (),
}

impl Sandbox {
    /// Build a sandbox runner from the given policy.
    ///
    /// On supported platforms, sets up the necessary ACLs / capabilities.
    /// Returns an error if the setup itself fails (not if the OS lacks
    /// sandbox support — that is handled at execution time via failover).
    pub fn new(policy: &SandboxPolicy) -> Result<Self, anyhow::Error> {
        #[cfg(all(feature = "sandbox", target_os = "windows"))]
        {
            let inner = WindowsSandbox::new(policy)?;
            Ok(Self { inner })
        }
        #[cfg(all(feature = "sandbox", not(target_os = "windows")))]
        {
            Ok(Self {
                policy: policy.clone(),
            })
        }
        #[cfg(not(feature = "sandbox"))]
        {
            let _ = policy;
            Ok(Self { _private: () })
        }
    }

    /// Execute a shell command under sandbox restrictions.
    ///
    /// Parameters `shell` (e.g. `"sh"` / `"cmd"`), `shell_flag` (`"-c"` / `"/c"`)
    /// and `command` are assembled into a full command line internally.
    ///
    /// Returns `(stdout, stderr, exit_code)`.
    pub async fn execute(
        &self,
        shell: &str,
        shell_flag: &str,
        command: &str,
        workdir: Option<&str>,
        timeout: std::time::Duration,
    ) -> Result<(String, String, i32), anyhow::Error> {
        #[cfg(all(feature = "sandbox", target_os = "windows"))]
        {
            self.inner
                .execute(shell, shell_flag, command, workdir, timeout)
                .await
        }
        #[cfg(all(feature = "sandbox", not(target_os = "windows")))]
        {
            execute_unix_sandbox(&self.policy, shell, shell_flag, command, workdir, timeout).await
        }
        #[cfg(not(feature = "sandbox"))]
        {
            let _ = (shell_flag, shell);
            failover_execute(command, workdir, timeout).await
        }
    }
}

// ── Unix sandbox executor (nono Landlock / Seatbelt) ──────────────

/// Standard system paths required for shell, cat, echo, pwd etc.
/// Landlock needs every path the subprocess will access to be
/// explicitly allowed, including shared libraries, the dynamic
/// linker, and the executables themselves.
///
/// This is a public helper exposed for testing and for tools that
/// build sandbox policies programmatically.
#[cfg(all(feature = "sandbox", not(target_os = "windows")))]
pub fn system_sandbox_read_paths() -> Vec<PathBuf> {
    vec![
        "/usr".into(),
        "/bin".into(),
        "/lib".into(),
        "/lib64".into(),
        "/etc".into(),
    ]
}

#[cfg(all(feature = "sandbox", not(target_os = "windows")))]
async fn execute_unix_sandbox(
    policy: &SandboxPolicy,
    shell: &str,
    shell_flag: &str,
    command: &str,
    workdir: Option<&str>,
    timeout: std::time::Duration,
) -> Result<(String, String, i32), anyhow::Error> {
    let mut caps = policy
        .to_capability_set()
        .map_err(|e| anyhow::anyhow!("failed to build sandbox capability set: {e}"))?;

    for path in &system_sandbox_read_paths() {
        caps = caps
            .allow_path(path, nono::AccessMode::Read)
            .map_err(|e| anyhow::anyhow!("failed to allow system path {}: {e}", path.display()))?;
    }

    let command_owned = command.to_owned();
    let shell_owned = shell.to_owned();
    let flag_owned = shell_flag.to_owned();
    let workdir_owned = workdir.map(|d| d.to_owned());

    let mut std_cmd = std::process::Command::new(&shell_owned);
    std_cmd
        .arg(&flag_owned)
        .arg(&command_owned)
        .stdout(std::process::Stdio::piped())
        .stderr(std::process::Stdio::piped());

    if let Some(ref dir) = workdir_owned {
        std_cmd.current_dir(dir);
    }

    unsafe {
        std_cmd.pre_exec(move || match nono::Sandbox::is_supported() {
            true => nono::Sandbox::apply_auto(&caps)
                .map(|_| ())
                .map_err(|e| std::io::Error::other(format!("sandbox apply failed: {e}"))),
            false => Ok(()),
        });
    }

    let mut tokio_cmd = tokio::process::Command::from(std_cmd);

    let output = tokio::time::timeout(timeout, tokio_cmd.output())
        .await
        .map_err(|_| anyhow::anyhow!("command timed out"))?
        .map_err(|e| anyhow::anyhow!("command failed: {e}"))?;

    let stdout = String::from_utf8_lossy(&output.stdout).to_string();
    let stderr = String::from_utf8_lossy(&output.stderr).to_string();
    let exit_code = output.status.code().unwrap_or(-1);

    Ok((stdout, stderr, exit_code))
}

#[cfg(all(not(feature = "sandbox"), target_os = "windows"))]
async fn failover_execute(
    command: &str,
    workdir: Option<&str>,
    timeout: std::time::Duration,
) -> Result<(String, String, i32), anyhow::Error> {
    let mut cmd = tokio::process::Command::new("cmd");
    cmd.arg("/c")
        .arg(command)
        .stdout(std::process::Stdio::piped())
        .stderr(std::process::Stdio::piped());
    if let Some(dir) = workdir {
        cmd.current_dir(dir);
    }
    let output = tokio::time::timeout(timeout, cmd.output())
        .await
        .map_err(|_| anyhow::anyhow!("command timed out"))?
        .map_err(|e| anyhow::anyhow!("command failed: {e}"))?;
    let stdout = String::from_utf8_lossy(&output.stdout).to_string();
    let stderr = String::from_utf8_lossy(&output.stderr).to_string();
    let exit_code = output.status.code().unwrap_or(-1);
    Ok((stdout, stderr, exit_code))
}

#[cfg(all(not(feature = "sandbox"), not(target_os = "windows")))]
async fn failover_execute(
    command: &str,
    workdir: Option<&str>,
    timeout: std::time::Duration,
) -> Result<(String, String, i32), anyhow::Error> {
    let mut cmd = tokio::process::Command::new("sh");
    cmd.arg("-c")
        .arg(command)
        .stdout(std::process::Stdio::piped())
        .stderr(std::process::Stdio::piped());
    if let Some(dir) = workdir {
        cmd.current_dir(dir);
    }
    let output = tokio::time::timeout(timeout, cmd.output())
        .await
        .map_err(|_| anyhow::anyhow!("command timed out"))?
        .map_err(|e| anyhow::anyhow!("command failed: {e}"))?;
    let stdout = String::from_utf8_lossy(&output.stdout).to_string();
    let stderr = String::from_utf8_lossy(&output.stderr).to_string();
    let exit_code = output.status.code().unwrap_or(-1);
    Ok((stdout, stderr, exit_code))
}

// ── format stdio triple to the string used by ShellTool ────────────

/// Format (stdout, stderr, exit_code) into the same format as
/// `format_output` for `std::process::Output`.
pub fn format_triple_output(stdout: &str, stderr: &str, exit_code: i32) -> String {
    let mut result = String::new();
    if !stdout.is_empty() {
        result.push_str("stdout:\n");
        result.push_str(stdout);
    }
    if !stderr.is_empty() {
        if !result.is_empty() {
            result.push('\n');
        }
        result.push_str("stderr:\n");
        result.push_str(stderr);
    }
    if exit_code == 0 {
        if result.is_empty() {
            result.push_str("(command completed with no output)");
        }
    } else {
        result.push_str(&format!("\n(exit code: {exit_code})"));
    }
    result
}

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

    // ── summary tests ──────────────────────────────────────────────

    #[test]
    fn summary_disabled() {
        let p = SandboxPolicy::disabled();
        assert_eq!(p.summary(), "sandbox disabled");
    }

    #[test]
    fn summary_with_multiple_path_types() {
        let p = SandboxPolicy {
            read_paths: vec!["/etc".into(), "/usr/share".into()],
            read_write_paths: vec!["/data".into()],
            execute_paths: vec!["/usr/bin".into()],
            block_network: true,
            ..Default::default()
        };
        let s = p.summary();
        assert!(s.contains("no-net"));
        assert!(s.contains("r:/etc"));
        assert!(s.contains("r:/usr/share"));
        assert!(s.contains("rw:/data"));
        assert!(s.contains("x:/usr/bin"));
    }

    #[test]
    fn summary_with_network_allowed() {
        let p = SandboxPolicy {
            block_network: false,
            ..Default::default()
        };
        let s = p.summary();
        assert!(s.contains("net-allowed"));
        assert!(!s.contains("no-net"));
    }

    #[test]
    fn summary_empty_policy_paths() {
        let p = SandboxPolicy::default();
        let s = p.summary();
        assert!(s.contains("no-net"));
        // no path entries should appear for empty vectors
        assert!(!s.contains("r:"));
        assert!(!s.contains("rw:"));
        assert!(!s.contains("x:"));
    }

    #[test]
    fn summary_disabled_idempotent_with_paths_set() {
        let mut p = SandboxPolicy::disabled();
        p.read_write_paths.push("/project".into());
        // still disabled regardless of paths
        assert!(!p.enabled);
        assert_eq!(p.summary(), "sandbox disabled");
    }

    // ── serialization tests ────────────────────────────────────────

    #[test]
    fn serialization_roundtrip() {
        let p = SandboxPolicy {
            enabled: true,
            read_paths: vec!["/etc".into()],
            read_write_paths: vec!["/data".into(), "/tmp".into()],
            execute_paths: vec!["/usr/local/bin".into()],
            block_network: false,
            memory_limit_bytes: Some(512_000_000),
        };
        let json = serde_json::to_string(&p).expect("serialize");
        let de: SandboxPolicy = serde_json::from_str(&json).expect("deserialize");
        assert_eq!(de.enabled, p.enabled);
        assert_eq!(de.read_paths, p.read_paths);
        assert_eq!(de.read_write_paths, p.read_write_paths);
        assert_eq!(de.execute_paths, p.execute_paths);
        assert_eq!(de.block_network, p.block_network);
        assert_eq!(de.memory_limit_bytes, p.memory_limit_bytes);
    }

    #[test]
    fn serialization_minimal() {
        let json = r#"{"read_write_paths": ["/project"]}"#;
        let p: SandboxPolicy = serde_json::from_str(json).expect("deserialize minimal");
        assert!(p.enabled); // default
        assert!(p.block_network); // default
        assert_eq!(p.read_write_paths, vec![PathBuf::from("/project")]);
        assert!(p.read_paths.is_empty());
        assert_eq!(p.memory_limit_bytes, None);
    }

    #[test]
    fn serialization_disabled_explicit() {
        let p = SandboxPolicy::disabled();
        let json = serde_json::to_string(&p).expect("serialize");
        let de: SandboxPolicy = serde_json::from_str(&json).expect("deserialize");
        assert!(!de.enabled);
    }

    // ── constructor & builder tests ────────────────────────────────

    #[test]
    fn default_values_are_safe() {
        let p = SandboxPolicy::default();
        assert!(p.enabled, "sandbox defaults to enabled");
        assert!(p.block_network, "network defaults to blocked");
        assert!(p.memory_limit_bytes.is_none());
        assert!(p.read_paths.is_empty());
        assert!(p.read_write_paths.is_empty());
        assert!(p.execute_paths.is_empty());
    }

    #[test]
    fn disabled_policy_only_toggles_enabled() {
        // disabled() only sets enabled=false; other fields keep their
        // defaults so the config can be round-tripped without data loss.
        let p = SandboxPolicy::disabled();
        assert!(!p.enabled);
        assert!(p.block_network); // unchanged from default
        assert!(p.read_paths.is_empty());
    }

    #[test]
    fn strict_read_write_sets_correct_fields() {
        let p = SandboxPolicy::strict_read_write("/workspace".into());
        assert!(p.enabled);
        assert!(p.block_network);
        assert_eq!(p.read_write_paths, vec![PathBuf::from("/workspace")]);
        assert!(p.read_paths.is_empty());
        assert!(p.execute_paths.is_empty());
    }

    // ── to_capability_set tests (non-Windows only) ─────────────────

    #[cfg(all(feature = "sandbox", not(target_os = "windows")))]
    #[test]
    fn to_capability_set_assigns_read_paths() {
        // /tmp is guaranteed to exist on every Linux/macOS system
        let p = SandboxPolicy {
            read_paths: vec!["/tmp".into()],
            ..Default::default()
        };
        let _caps = p.to_capability_set().expect("build caps with read paths");
    }

    #[cfg(all(feature = "sandbox", not(target_os = "windows")))]
    #[test]
    fn to_capability_set_assigns_read_write_paths() {
        let p = SandboxPolicy {
            read_write_paths: vec!["/tmp".into()],
            ..Default::default()
        };
        let _caps = p
            .to_capability_set()
            .expect("build caps with read-write paths");
    }

    #[cfg(all(feature = "sandbox", not(target_os = "windows")))]
    #[test]
    fn to_capability_set_assigns_execute_paths() {
        let p = SandboxPolicy {
            execute_paths: vec!["/tmp".into()],
            ..Default::default()
        };
        let _caps = p
            .to_capability_set()
            .expect("build caps with execute paths");
    }

    #[cfg(all(feature = "sandbox", not(target_os = "windows")))]
    #[test]
    fn to_capability_set_block_network() {
        let p = SandboxPolicy {
            block_network: true,
            ..Default::default()
        };
        let _caps = p
            .to_capability_set()
            .expect("build caps with network blocked");
    }

    #[cfg(all(feature = "sandbox", not(target_os = "windows")))]
    #[test]
    fn to_capability_set_network_not_blocked_when_false() {
        let p = SandboxPolicy {
            block_network: false,
            ..Default::default()
        };
        let _caps = p
            .to_capability_set()
            .expect("build caps without network block");
    }

    #[cfg(all(feature = "sandbox", not(target_os = "windows")))]
    #[test]
    fn to_capability_set_empty_policy_creates_minimal_caps() {
        let p = SandboxPolicy::default();
        let _caps = p.to_capability_set().expect("build caps from empty policy");
    }

    // ── is_within_boundary tests (sandbox feature) ────────────────

    #[cfg(feature = "sandbox")]
    mod boundary_tests {
        use super::*;
        use std::path::Path;

        #[test]
        fn is_within_boundary_disabled() {
            let p = SandboxPolicy {
                enabled: false,
                ..Default::default()
            };
            assert!(p.is_within_boundary(Path::new("/any/path")));
        }

        #[test]
        fn is_within_boundary_inside_root() {
            let p = SandboxPolicy {
                read_write_paths: vec!["src".into()],
                ..Default::default()
            };
            assert!(p.is_within_boundary(Path::new("src/lib.rs")));
        }

        #[test]
        fn is_within_boundary_outside_root() {
            let p = SandboxPolicy {
                read_write_paths: vec!["src".into()],
                ..Default::default()
            };
            assert!(!p.is_within_boundary(Path::new("/etc/passwd")));
        }

        #[test]
        fn is_within_boundary_read_paths() {
            let p = SandboxPolicy {
                read_paths: vec!["/usr/share".into()],
                ..Default::default()
            };
            assert!(p.is_within_boundary(Path::new("/usr/share/man")));
        }
    }
}