Skip to main content

keel_enforce/
backend.rs

1use crate::error::EnforceResult;
2use async_trait::async_trait;
3use keel_policy::{Policy, SpaceId};
4use keel_record::RecordSink;
5use std::path::Path;
6use std::process::Stdio;
7use std::sync::Arc;
8
9#[derive(Debug, Clone)]
10pub struct BackendInfo {
11    pub name: &'static str,
12    /// True if the backend applies kernel-level FS isolation.
13    pub kernel_fs: bool,
14    /// True if the backend can restrict child process network.
15    pub child_network: bool,
16}
17
18#[derive(Debug, Clone)]
19pub struct SpawnRequest {
20    pub program: String,
21    pub args: Vec<String>,
22    pub cwd: Option<std::path::PathBuf>,
23    pub env: Vec<(String, String)>,
24}
25
26impl SpawnRequest {
27    pub fn new(program: impl Into<String>) -> Self {
28        Self {
29            program: program.into(),
30            args: Vec::new(),
31            cwd: None,
32            env: Vec::new(),
33        }
34    }
35
36    pub fn args<I, S>(mut self, args: I) -> Self
37    where
38        I: IntoIterator<Item = S>,
39        S: Into<String>,
40    {
41        self.args = args.into_iter().map(Into::into).collect();
42        self
43    }
44
45    pub fn cwd(mut self, cwd: impl Into<std::path::PathBuf>) -> Self {
46        self.cwd = Some(cwd.into());
47        self
48    }
49}
50
51pub struct SpawnedProcess {
52    pub child: tokio::process::Child,
53}
54
55/// A live enforcement context for one space.
56#[async_trait]
57pub trait EnforceBackend: Send + Sync {
58    fn info(&self) -> BackendInfo;
59
60    /// Apply policy for this space. May be irreversible for kernel backends.
61    async fn apply(&self, policy: &Policy, sink: Arc<dyn RecordSink>) -> EnforceResult<()>;
62
63    /// Check whether a path operation would be allowed (best-effort soft check).
64    async fn check_fs(
65        &self,
66        policy: &Policy,
67        path: &Path,
68        write: bool,
69    ) -> EnforceResult<bool>;
70
71    /// Spawn a subprocess under the policy (soft or hard depending on backend).
72    async fn spawn(
73        &self,
74        space_id: &SpaceId,
75        policy: &Policy,
76        req: SpawnRequest,
77        sink: Arc<dyn RecordSink>,
78    ) -> EnforceResult<SpawnedProcess>;
79
80    /// Tear down enforcement for this space (revoke, unmount, etc.).
81    async fn destroy(&self, policy: &Policy, sink: Arc<dyn RecordSink>) -> EnforceResult<()>;
82}
83
84/// Shared helper: build a tokio Command with basic fields.
85pub(crate) fn base_command(req: &SpawnRequest) -> tokio::process::Command {
86    let mut cmd = tokio::process::Command::new(&req.program);
87    cmd.args(&req.args)
88        .stdin(Stdio::null())
89        .stdout(Stdio::piped())
90        .stderr(Stdio::piped());
91    if let Some(cwd) = &req.cwd {
92        cmd.current_dir(cwd);
93    }
94    for (k, v) in &req.env {
95        cmd.env(k, v);
96    }
97    cmd
98}