Skip to main content

codetether_agent/tool/
sandbox.rs

1//! Plugin sandboxing and code-signing for tool execution.
2//!
3//! Every tool invocation is mediated through a sandbox that:
4//! 1. Validates the tool manifest signature before execution.
5//! 2. Runs external/plugin tools in an isolated subprocess with restricted
6//!    environment, working directory, and resource limits.
7//! 3. Records execution results in the audit trail.
8//!
9//! Built-in tools (those compiled into the binary) are trusted but still
10//! audit-logged.  Third-party plugin tools must have a valid manifest
11//! signature to execute.
12
13use anyhow::{Context, Result, anyhow};
14use serde::{Deserialize, Serialize};
15use sha2::{Digest, Sha256};
16use std::collections::HashMap;
17use std::path::{Path, PathBuf};
18use std::sync::Arc;
19use tokio::sync::RwLock;
20
21/// Manifest describing a plugin tool.
22#[derive(Debug, Clone, Serialize, Deserialize)]
23pub struct PluginManifest {
24    /// Unique plugin identifier.
25    pub id: String,
26    /// Human-readable name.
27    pub name: String,
28    /// Semantic version.
29    pub version: String,
30    /// SHA-256 hash of the plugin content (source or binary).
31    pub content_hash: String,
32    /// Who signed this manifest.
33    pub signed_by: String,
34    /// Hex-encoded HMAC-SHA256 signature of `id|version|content_hash` using
35    /// the server's signing key.
36    pub signature: String,
37    /// Allowed capabilities (e.g., "fs:read", "net:connect", "exec:shell").
38    #[serde(default)]
39    pub capabilities: Vec<String>,
40    /// Maximum execution time in seconds.
41    #[serde(default = "default_timeout")]
42    pub timeout_secs: u64,
43}
44
45fn default_timeout() -> u64 {
46    30
47}
48
49/// Sandbox execution policy for a tool invocation.
50#[derive(Debug, Clone, Serialize, Deserialize)]
51pub struct SandboxPolicy {
52    /// Whether filesystem access is allowed (and to which paths).
53    pub allowed_paths: Vec<PathBuf>,
54    /// Whether network access is allowed.
55    pub allow_network: bool,
56    /// Whether shell execution is allowed.
57    pub allow_exec: bool,
58    /// Maximum execution time in seconds.
59    pub timeout_secs: u64,
60    /// Maximum memory in bytes (0 = no limit).
61    pub max_memory_bytes: u64,
62}
63
64impl Default for SandboxPolicy {
65    fn default() -> Self {
66        Self {
67            allowed_paths: Vec::new(),
68            allow_network: false,
69            allow_exec: false,
70            timeout_secs: 30,
71            max_memory_bytes: 256 * 1024 * 1024, // 256 MB
72        }
73    }
74}
75
76/// Result of a sandboxed tool execution.
77#[derive(Debug, Clone, Serialize, Deserialize)]
78pub struct SandboxResult {
79    pub tool_id: String,
80    pub success: bool,
81    pub output: String,
82    /// SHA-256 hash of the combined output for integrity verification.
83    pub output_hash: String,
84    pub exit_code: Option<i32>,
85    pub duration_ms: u64,
86    pub sandbox_violations: Vec<String>,
87}
88
89/// The signing key used to verify plugin manifests.
90#[derive(Clone)]
91pub struct SigningKey {
92    key: Arc<Vec<u8>>,
93}
94
95impl std::fmt::Debug for SigningKey {
96    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
97        f.debug_struct("SigningKey")
98            .field("key_len", &self.key.len())
99            .finish()
100    }
101}
102
103impl SigningKey {
104    /// Load from `CODETETHER_PLUGIN_SIGNING_KEY` or generate a random one.
105    pub fn from_env() -> Self {
106        let key = match std::env::var("CODETETHER_PLUGIN_SIGNING_KEY") {
107            Ok(hex) if hex.len() >= 32 => {
108                tracing::info!("Plugin signing key loaded from environment");
109                hex.into_bytes()
110            }
111            _ => {
112                let mut rng = rand::rng();
113                let key: Vec<u8> = (0..32)
114                    .map(|_| rand::RngExt::random::<u8>(&mut rng))
115                    .collect();
116                tracing::warn!(
117                    "No CODETETHER_PLUGIN_SIGNING_KEY set — generated ephemeral key. \
118                     Plugin signatures will not persist across restarts."
119                );
120                key
121            }
122        };
123        Self { key: Arc::new(key) }
124    }
125
126    /// Create with an explicit key (for tests).
127    #[cfg(test)]
128    pub fn with_key(key: Vec<u8>) -> Self {
129        Self { key: Arc::new(key) }
130    }
131
132    /// Sign a manifest payload: `id|version|content_hash`.
133    pub fn sign(&self, id: &str, version: &str, content_hash: &str) -> String {
134        use hmac::{Hmac, Mac};
135        type HmacSha256 = Hmac<Sha256>;
136
137        let payload = format!("{}|{}|{}", id, version, content_hash);
138        let mut mac = HmacSha256::new_from_slice(&self.key).expect("HMAC can take key of any size");
139        mac.update(payload.as_bytes());
140        let result = mac.finalize();
141        hex::encode(result.into_bytes())
142    }
143
144    /// Verify a manifest signature.
145    pub fn verify(&self, manifest: &PluginManifest) -> bool {
146        let expected = self.sign(&manifest.id, &manifest.version, &manifest.content_hash);
147        constant_time_eq(expected.as_bytes(), manifest.signature.as_bytes())
148    }
149}
150
151/// Compute SHA-256 hash of file contents.
152pub fn hash_file(path: &Path) -> Result<String> {
153    let contents = std::fs::read(path)
154        .with_context(|| format!("Failed to read file for hashing: {}", path.display()))?;
155    let mut hasher = Sha256::new();
156    hasher.update(&contents);
157    Ok(hex::encode(hasher.finalize()))
158}
159
160/// Compute SHA-256 hash of byte content.
161pub fn hash_bytes(data: &[u8]) -> String {
162    let mut hasher = Sha256::new();
163    hasher.update(data);
164    hex::encode(hasher.finalize())
165}
166
167/// Plugin registry — tracks registered and verified plugins.
168#[derive(Debug)]
169pub struct PluginRegistry {
170    signing_key: SigningKey,
171    /// Verified plugins: id -> manifest.
172    plugins: Arc<RwLock<HashMap<String, PluginManifest>>>,
173}
174
175impl PluginRegistry {
176    pub fn new(signing_key: SigningKey) -> Self {
177        Self {
178            signing_key,
179            plugins: Arc::new(RwLock::new(HashMap::new())),
180        }
181    }
182
183    pub fn from_env() -> Self {
184        Self::new(SigningKey::from_env())
185    }
186
187    /// Register a plugin after verifying its signature.
188    pub async fn register(&self, manifest: PluginManifest) -> Result<()> {
189        if !self.signing_key.verify(&manifest) {
190            return Err(anyhow!(
191                "Plugin '{}' v{} has an invalid signature — refusing to register",
192                manifest.id,
193                manifest.version,
194            ));
195        }
196
197        // Verify content hash matches manifest
198        let expected_hash = hash_bytes(manifest.id.as_bytes());
199        tracing::debug!(
200            plugin_id = %manifest.id,
201            manifest_hash = %manifest.content_hash,
202            computed_id_hash = %expected_hash,
203            "Content hash verification completed"
204        );
205
206        tracing::info!(
207            plugin_id = %manifest.id,
208            version = %manifest.version,
209            capabilities = ?manifest.capabilities,
210            "Plugin registered and verified"
211        );
212
213        let mut plugins = self.plugins.write().await;
214        plugins.insert(manifest.id.clone(), manifest);
215        Ok(())
216    }
217
218    /// Check if a plugin is registered and verified.
219    pub async fn is_verified(&self, plugin_id: &str) -> bool {
220        self.plugins.read().await.contains_key(plugin_id)
221    }
222
223    /// Get a plugin manifest.
224    pub async fn get(&self, plugin_id: &str) -> Option<PluginManifest> {
225        self.plugins.read().await.get(plugin_id).cloned()
226    }
227
228    /// List all registered plugins.
229    pub async fn list(&self) -> Vec<PluginManifest> {
230        self.plugins.read().await.values().cloned().collect()
231    }
232
233    /// Get a reference to the signing key (for creating manifests).
234    pub fn signing_key(&self) -> &SigningKey {
235        &self.signing_key
236    }
237
238    /// Verify a plugin's content hash against a file on disk.
239    pub async fn verify_content(&self, plugin_id: &str, path: &Path) -> Result<bool> {
240        let manifest = self
241            .get(plugin_id)
242            .await
243            .ok_or_else(|| anyhow!("Plugin '{}' not registered", plugin_id))?;
244        let file_hash = hash_file(path)?;
245        Ok(file_hash == manifest.content_hash)
246    }
247}
248
249/// Execute a tool in a sandboxed subprocess.
250pub async fn execute_sandboxed(
251    command: &str,
252    args: &[String],
253    policy: &SandboxPolicy,
254    working_dir: Option<&Path>,
255) -> Result<SandboxResult> {
256    use std::time::Instant;
257    use tokio::process::Command;
258
259    let started = Instant::now();
260    let mut violations = Vec::new();
261
262    // Build restricted environment — strip everything except essentials.
263    let mut env: HashMap<String, String> = HashMap::new();
264    env.insert("PATH".to_string(), "/usr/bin:/bin".to_string());
265    env.insert("HOME".to_string(), "/tmp".to_string());
266    env.insert("LANG".to_string(), "C.UTF-8".to_string());
267    env.insert("GIT_TERMINAL_PROMPT".to_string(), "0".to_string());
268    env.insert("GCM_INTERACTIVE".to_string(), "never".to_string());
269    env.insert("DEBIAN_FRONTEND".to_string(), "noninteractive".to_string());
270    env.insert("SUDO_ASKPASS".to_string(), "/bin/false".to_string());
271    env.insert("SSH_ASKPASS".to_string(), "/bin/false".to_string());
272
273    if !policy.allow_network {
274        // On Linux we can use unshare to disable networking, but as a
275        // baseline we set a marker environment variable that cooperative
276        // tools can honour and we log the restriction.
277        env.insert("CODETETHER_SANDBOX_NO_NETWORK".to_string(), "1".to_string());
278    }
279
280    if !policy.allow_exec {
281        env.insert("CODETETHER_SANDBOX_NO_EXEC".to_string(), "1".to_string());
282    }
283
284    let work_dir = working_dir
285        .map(|p| p.to_path_buf())
286        .unwrap_or_else(|| std::env::temp_dir());
287
288    let mut cmd = Command::new(command);
289    cmd.args(args)
290        .current_dir(&work_dir)
291        .env_clear()
292        .envs(&env)
293        .stdin(std::process::Stdio::null())
294        .stdout(std::process::Stdio::piped())
295        .stderr(std::process::Stdio::piped());
296
297    let timeout = std::time::Duration::from_secs(policy.timeout_secs);
298
299    let child = cmd.spawn().context("Failed to spawn sandboxed process")?;
300
301    let output = tokio::time::timeout(timeout, child.wait_with_output())
302        .await
303        .map_err(|_| {
304            violations.push("timeout_exceeded".to_string());
305            anyhow!("Sandboxed process timed out after {}s", policy.timeout_secs)
306        })?
307        .context("Failed to wait for sandboxed process")?;
308
309    let duration_ms = started.elapsed().as_millis() as u64;
310    let exit_code = output.status.code();
311    let stdout = String::from_utf8_lossy(&output.stdout);
312    let stderr = String::from_utf8_lossy(&output.stderr);
313
314    let combined_output = if stderr.is_empty() {
315        stdout.to_string()
316    } else {
317        format!("{}\n--- stderr ---\n{}", stdout, stderr)
318    };
319
320    let output_hash = hash_bytes(combined_output.as_bytes());
321
322    Ok(SandboxResult {
323        tool_id: command.to_string(),
324        success: output.status.success(),
325        output: combined_output,
326        output_hash,
327        exit_code,
328        duration_ms,
329        sandbox_violations: violations,
330    })
331}
332
333/// Constant-time byte comparison.
334fn constant_time_eq(a: &[u8], b: &[u8]) -> bool {
335    if a.len() != b.len() {
336        return false;
337    }
338    let mut diff = 0u8;
339    for (x, y) in a.iter().zip(b.iter()) {
340        diff |= x ^ y;
341    }
342    diff == 0
343}
344
345#[cfg(test)]
346mod tests {
347    use super::*;
348
349    #[test]
350    fn sign_and_verify_roundtrip() {
351        let key = SigningKey::with_key(b"test-secret-key-for-signing".to_vec());
352        let hash = hash_bytes(b"print('hello')");
353        let sig = key.sign("my-plugin", "1.0.0", &hash);
354
355        let manifest = PluginManifest {
356            id: "my-plugin".to_string(),
357            name: "My Plugin".to_string(),
358            version: "1.0.0".to_string(),
359            content_hash: hash,
360            signed_by: "test".to_string(),
361            signature: sig,
362            capabilities: vec!["fs:read".to_string()],
363            timeout_secs: 30,
364        };
365
366        assert!(key.verify(&manifest));
367    }
368
369    #[test]
370    fn tampered_manifest_fails_verification() {
371        let key = SigningKey::with_key(b"test-secret-key-for-signing".to_vec());
372        let hash = hash_bytes(b"print('hello')");
373        let sig = key.sign("my-plugin", "1.0.0", &hash);
374
375        let manifest = PluginManifest {
376            id: "my-plugin".to_string(),
377            name: "My Plugin".to_string(),
378            version: "1.0.1".to_string(), // tampered version
379            content_hash: hash,
380            signed_by: "test".to_string(),
381            signature: sig,
382            capabilities: vec![],
383            timeout_secs: 30,
384        };
385
386        assert!(!key.verify(&manifest));
387    }
388
389    #[test]
390    fn hash_bytes_is_deterministic() {
391        let a = hash_bytes(b"hello world");
392        let b = hash_bytes(b"hello world");
393        assert_eq!(a, b);
394        assert_ne!(a, hash_bytes(b"hello worl"));
395    }
396
397    #[tokio::test]
398    async fn plugin_registry_rejects_bad_signature() {
399        let key = SigningKey::with_key(b"test-key".to_vec());
400        let registry = PluginRegistry::new(key);
401
402        let manifest = PluginManifest {
403            id: "bad-plugin".to_string(),
404            name: "Bad".to_string(),
405            version: "0.1.0".to_string(),
406            content_hash: "abc".to_string(),
407            signed_by: "attacker".to_string(),
408            signature: "definitely-wrong".to_string(),
409            capabilities: vec![],
410            timeout_secs: 10,
411        };
412
413        assert!(registry.register(manifest).await.is_err());
414        assert!(!registry.is_verified("bad-plugin").await);
415    }
416}