interplane.Get Omega
Read in your language

aegis-runtime-mv

Native Rust agent runtime: Axum WebSocket/SSE/REST gateway, heartbeat scheduler, dependency-aware task workflow, SQLite storage. Attachment of AienOS. Pre-alpha.

Brought by drakestapleton

branch main Branches Tags History

aegis-runtime-mv / src / security.rs

511 lines · 18321 bytes Raw Blame History
1//! Capability-bound workspace security and canonical path resolution.
2//! Enforces containment for filesystem access and shell execution within authorized workspace roots.
3
4use std::ffi::CString;
5use std::fs::File;
6use std::io::Write;
7use std::os::fd::{AsRawFd, FromRawFd};
8use std::os::unix::ffi::OsStrExt;
9use std::os::unix::fs::MetadataExt;
10use std::path::{Component, Path, PathBuf};
11use std::process::Command;
12
13#[derive(Debug, Clone, PartialEq, Eq)]
14pub enum SecurityError {
15 AccessDenied(String),
16 PathNotFound(String),
17 InvalidPath(String),
18 IoError(String),
19 CommandFailed(String),
20}
21
22impl std::fmt::Display for SecurityError {
23 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
24 match self {
25 Self::AccessDenied(msg) => write!(f, "Security rejection: {}", msg),
26 Self::PathNotFound(msg) => write!(f, "Path not found: {}", msg),
27 Self::InvalidPath(msg) => write!(f, "{}", msg),
28 Self::IoError(msg) => write!(f, "I/O error: {}", msg),
29 Self::CommandFailed(msg) => write!(f, "Command execution failed: {}", msg),
30 }
31 }
32}
33
34impl std::error::Error for SecurityError {}
35
36#[derive(Debug, Clone)]
37pub struct WorkspaceCapability {
38 root: PathBuf,
39 root_dir: std::sync::Arc<File>,
40}
41
42impl Default for WorkspaceCapability {
43 fn default() -> Self {
44 Self::detect()
45 }
46}
47
48impl WorkspaceCapability {
49 /// Constructs a capability strictly bound to the specified root directory.
50 pub fn new<P: AsRef<Path>>(root: P) -> Result<Self, SecurityError> {
51 let p = root.as_ref();
52 if !p.exists() {
53 std::fs::create_dir_all(p).map_err(|e| {
54 SecurityError::IoError(format!(
55 "Failed to create workspace directory {}: {}",
56 p.display(),
57 e
58 ))
59 })?;
60 }
61 let canonical = p.canonicalize().map_err(|e| {
62 SecurityError::IoError(format!(
63 "Failed to canonicalize workspace root {}: {}",
64 p.display(),
65 e
66 ))
67 })?;
68 // Walk the canonical root from / with no-follow directory opens too:
69 // canonicalize followed by File::open would race a replaced ancestor.
70 let mut root_dir = File::open("/")
71 .map_err(|e| SecurityError::IoError(format!("Failed to open filesystem root: {e}")))?;
72 for component in canonical.components() {
73 if let Component::Normal(name) = component {
74 let name = CString::new(name.as_bytes())
75 .map_err(|_| SecurityError::InvalidPath("NUL in workspace root".into()))?;
76 let fd = unsafe {
77 libc::openat(
78 root_dir.as_raw_fd(),
79 name.as_ptr(),
80 libc::O_RDONLY | libc::O_DIRECTORY | libc::O_NOFOLLOW | libc::O_CLOEXEC,
81 )
82 };
83 if fd < 0 {
84 return Err(SecurityError::AccessDenied(format!(
85 "Unsafe workspace root: {}",
86 std::io::Error::last_os_error()
87 )));
88 }
89 root_dir = unsafe { File::from_raw_fd(fd) };
90 }
91 }
92 Ok(Self {
93 root: canonical,
94 root_dir: std::sync::Arc::new(root_dir),
95 })
96 }
97
98 pub fn root(&self) -> &Path {
99 &self.root
100 }
101
102 /// Automatically detects the active workspace root.
103 pub fn detect() -> Self {
104 if let Ok(ws) = std::env::var("AEGIS_WORKSPACE") {
105 if let Ok(cap) = Self::new(&ws) {
106 return cap;
107 }
108 }
109 if let Ok(cwd) = std::env::current_dir() {
110 if let Ok(cap) = Self::new(&cwd) {
111 return cap;
112 }
113 }
114 if let Ok(home) = std::env::var("HOME") {
115 let candidate = PathBuf::from(home).join("workspace");
116 if candidate.exists() {
117 if let Ok(cap) = Self::new(&candidate) {
118 return cap;
119 }
120 }
121 }
122 Self::new(".").expect("Aegis requires a readable workspace directory")
123 }
124
125 /// Resolves an existing file path for reading, strictly verifying that it resides within the workspace root.
126 /// Canonicalizes the path and rejects traversal escaping the root.
127 pub fn resolve_read_path(&self, requested: &str) -> Result<PathBuf, SecurityError> {
128 let trimmed = requested.trim();
129 if trimmed.is_empty() {
130 return Err(SecurityError::InvalidPath(
131 "Path cannot be empty".to_string(),
132 ));
133 }
134
135 let candidate = if Path::new(trimmed).is_absolute() {
136 PathBuf::from(trimmed)
137 } else {
138 self.root.join(trimmed)
139 };
140
141 if !candidate.exists() {
142 return Err(SecurityError::PathNotFound(format!(
143 "File does not exist: {}",
144 trimmed
145 )));
146 }
147
148 let canonical = candidate.canonicalize().map_err(|e| {
149 SecurityError::IoError(format!("Failed to canonicalize path {}: {}", trimmed, e))
150 })?;
151
152 if !canonical.starts_with(&self.root) {
153 return Err(SecurityError::AccessDenied(format!(
154 "Path {} escapes authorized workspace root {}",
155 canonical.display(),
156 self.root.display()
157 )));
158 }
159
160 Ok(canonical)
161 }
162
163 /// Open each component relative to the held workspace directory. No path-based
164 /// containment check is reused for the final open, and no symlink is followed.
165 pub fn write_file(&self, requested: &str, content: &str) -> Result<PathBuf, SecurityError> {
166 let trimmed = requested.trim();
167 if trimmed.is_empty() {
168 return Err(SecurityError::InvalidPath("Path cannot be empty".into()));
169 }
170 let target = if Path::new(trimmed).is_absolute() {
171 normalize_path(Path::new(trimmed))
172 } else {
173 normalize_path(&self.root.join(trimmed))
174 };
175 let relative = target.strip_prefix(&self.root).map_err(|_| {
176 SecurityError::AccessDenied(format!("Path {} escapes workspace", target.display()))
177 })?;
178 let mut names = relative.components().map(|c| c.as_os_str()).peekable();
179 if names.peek().is_none() {
180 return Err(SecurityError::InvalidPath("Path must name a file".into()));
181 }
182 let mut dir = self
183 .root_dir
184 .try_clone()
185 .map_err(|e| SecurityError::IoError(e.to_string()))?;
186 while let Some(name) = names.next() {
187 let name = CString::new(name.as_bytes())
188 .map_err(|_| SecurityError::InvalidPath("NUL in path".into()))?;
189 if names.peek().is_some() {
190 let mut fd = unsafe {
191 libc::openat(
192 dir.as_raw_fd(),
193 name.as_ptr(),
194 libc::O_RDONLY | libc::O_DIRECTORY | libc::O_NOFOLLOW | libc::O_CLOEXEC,
195 )
196 };
197 if fd < 0 && std::io::Error::last_os_error().kind() == std::io::ErrorKind::NotFound
198 {
199 let rc = unsafe { libc::mkdirat(dir.as_raw_fd(), name.as_ptr(), 0o777) };
200 if rc < 0
201 && std::io::Error::last_os_error().kind()
202 != std::io::ErrorKind::AlreadyExists
203 {
204 return Err(SecurityError::IoError(
205 std::io::Error::last_os_error().to_string(),
206 ));
207 }
208 fd = unsafe {
209 libc::openat(
210 dir.as_raw_fd(),
211 name.as_ptr(),
212 libc::O_RDONLY | libc::O_DIRECTORY | libc::O_NOFOLLOW | libc::O_CLOEXEC,
213 )
214 };
215 }
216 if fd < 0 {
217 return Err(SecurityError::AccessDenied(format!(
218 "Unsafe workspace directory: {}",
219 std::io::Error::last_os_error()
220 )));
221 }
222 dir = unsafe { File::from_raw_fd(fd) };
223 } else {
224 let fd = unsafe {
225 libc::openat(
226 dir.as_raw_fd(),
227 name.as_ptr(),
228 libc::O_WRONLY
229 | libc::O_CREAT
230 | libc::O_NOFOLLOW
231 | libc::O_CLOEXEC
232 | libc::O_NONBLOCK,
233 0o666,
234 )
235 };
236 if fd < 0 {
237 return Err(SecurityError::AccessDenied(format!(
238 "Unsafe workspace file: {}",
239 std::io::Error::last_os_error()
240 )));
241 }
242 let mut file = unsafe { File::from_raw_fd(fd) };
243 let metadata = file
244 .metadata()
245 .map_err(|e| SecurityError::IoError(e.to_string()))?;
246 if !metadata.is_file() || metadata.nlink() != 1 {
247 return Err(SecurityError::AccessDenied(
248 "Target is not a private regular file".into(),
249 ));
250 }
251 file.set_len(0)
252 .map_err(|e| SecurityError::IoError(e.to_string()))?;
253 file.write_all(content.as_bytes())
254 .map_err(|e| SecurityError::IoError(e.to_string()))?;
255 }
256 }
257 Ok(target)
258 }
259 /// Resolves an existing directory path (for listing or working directory), ensuring it stays within root.
260 pub fn resolve_dir_path(&self, requested: Option<&str>) -> Result<PathBuf, SecurityError> {
261 let target = match requested {
262 Some(d) if !d.trim().is_empty() && d.trim() != "." => {
263 let p = Path::new(d.trim());
264 if p.is_absolute() {
265 p.to_path_buf()
266 } else {
267 self.root.join(p)
268 }
269 }
270 _ => self.root.clone(),
271 };
272
273 if !target.exists() {
274 return Err(SecurityError::PathNotFound(format!(
275 "Directory does not exist: {}",
276 target.display()
277 )));
278 }
279
280 let canonical = target.canonicalize().map_err(|e| {
281 SecurityError::IoError(format!(
282 "Failed to canonicalize directory {}: {}",
283 target.display(),
284 e
285 ))
286 })?;
287
288 if !canonical.is_dir() {
289 return Err(SecurityError::InvalidPath(format!(
290 "Path is not a directory: {}",
291 canonical.display()
292 )));
293 }
294
295 if !canonical.starts_with(&self.root) {
296 return Err(SecurityError::AccessDenied(format!(
297 "Directory {} escapes authorized workspace root {}",
298 canonical.display(),
299 self.root.display()
300 )));
301 }
302
303 Ok(canonical)
304 }
305
306 /// The only shell entry. The membrane runs first. A command then has to
307 /// match a whole local form before the workspace-bound executor runs.
308 pub fn dispatch_shell(
309 &self,
310 command: &str,
311 cwd: Option<&str>,
312 timeout_secs: u64,
313 ) -> Result<String, SecurityError> {
314 let args = serde_json::json!({ "command": command });
315 crate::enforcement::pre_dispatch_check("bash_eval", &args)
316 .map_err(SecurityError::AccessDenied)?;
317 admit_local_command(command)?;
318 self.execute_shell(command, cwd, timeout_secs)
319 }
320
321 /// `dispatch_shell` behind the probe gate. HTTP, WebSocket and heartbeat
322 /// shell paths use this.
323 pub async fn dispatch_shell_gated(
324 &self,
325 command: &str,
326 cwd: Option<&str>,
327 timeout_secs: u64,
328 ) -> Result<String, SecurityError> {
329 let args = serde_json::json!({ "command": command });
330 crate::enforcement::probe_gate("bash_eval", &args)
331 .await
332 .map_err(SecurityError::AccessDenied)?;
333 self.dispatch_shell(command, cwd, timeout_secs)
334 }
335
336 /// Low-level executor. Callers use `dispatch_shell`.
337 pub(crate) fn execute_shell(
338 &self,
339 command: &str,
340 cwd: Option<&str>,
341 timeout_secs: u64,
342 ) -> Result<String, SecurityError> {
343 let trimmed_cmd = command.trim();
344 if trimmed_cmd.is_empty() {
345 return Err(SecurityError::InvalidPath(
346 "Command cannot be empty".to_string(),
347 ));
348 }
349
350 let working_dir = self.resolve_dir_path(cwd)?;
351
352 let escaped_cmd = trimmed_cmd.replace('\'', "'\\''");
353 let wrapped_cmd = format!("timeout {}s bash -c '{}'", timeout_secs, escaped_cmd);
354
355 let output = Command::new("sh")
356 .arg("-c")
357 .arg(&wrapped_cmd)
358 .current_dir(&working_dir)
359 .output()
360 .map_err(|e| {
361 SecurityError::CommandFailed(format!("Failed to execute command: {}", e))
362 })?;
363
364 let stdout = String::from_utf8_lossy(&output.stdout).to_string();
365 let stderr = String::from_utf8_lossy(&output.stderr).to_string();
366
367 if !output.status.success() {
368 let code = output.status.code().unwrap_or(-1);
369 if code == 124 {
370 return Err(SecurityError::CommandFailed(format!(
371 "Command timed out after {} seconds: {}",
372 timeout_secs, trimmed_cmd
373 )));
374 }
375 return Err(SecurityError::CommandFailed(format!(
376 "Exit code {}: {}",
377 code,
378 if !stderr.trim().is_empty() {
379 stderr.trim()
380 } else {
381 stdout.trim()
382 }
383 )));
384 }
385
386 Ok(stdout)
387 }
388}
389
390/// A local command is one exact form from the catalog. The first word is not enough.
391pub fn admit_local_command(command: &str) -> Result<(), SecurityError> {
392 if command.chars().any(|c| {
393 matches!(
394 c,
395 ';' | '|'
396 | '&'
397 | '$'
398 | '<'
399 | '>'
400 | '`'
401 | '\\'
402 | '\n'
403 | '\r'
404 | '('
405 | ')'
406 | '{'
407 | '}'
408 | '!'
409 | '*'
410 | '?'
411 | '['
412 | ']'
413 | '\''
414 | '"'
415 )
416 }) {
417 return Err(SecurityError::AccessDenied(
418 "Command is not a local form. Shell joining, substitution, and quoting are not local execution.".to_string(),
419 ));
420 }
421 let argv: Vec<&str> = command.split_whitespace().collect();
422 let allowed = [
423 ["git", "status"].as_slice(),
424 ["git", "diff"].as_slice(),
425 ["git", "log", "-1", "--oneline"].as_slice(),
426 ["ls"].as_slice(),
427 ];
428 if allowed.iter().any(|form| form == &argv) {
429 return Ok(());
430 }
431 Err(SecurityError::AccessDenied(
432 "Command is not eligible for local shell. Local execution is only the catalogued forms: git status, git diff, git log -1 --oneline, and ls. Anything else needs a typed tool.".to_string(),
433 ))
434}
435
436pub fn normalize_path(path: &Path) -> PathBuf {
437 let mut stack = Vec::new();
438 for comp in path.components() {
439 match comp {
440 Component::CurDir => {}
441 Component::ParentDir => {
442 stack.pop();
443 }
444 c => {
445 stack.push(c.as_os_str());
446 }
447 }
448 }
449 stack.iter().collect()
450}
451
452#[cfg(test)]
453mod tests {
454 use super::*;
455 use tempfile::tempdir;
456
457 #[test]
458 fn test_workspace_capability_read_write_containment() {
459 let dir = tempdir().unwrap();
460 let cap = WorkspaceCapability::new(dir.path()).unwrap();
461
462 let write_target = cap.write_file("nested/test.txt", "secure data").unwrap();
463 assert!(write_target.starts_with(cap.root()));
464
465 let read_target = cap.resolve_read_path("nested/test.txt").unwrap();
466 assert_eq!(read_target, write_target.canonicalize().unwrap());
467
468 let escape_read = cap.resolve_read_path("../../etc/passwd");
469 assert!(escape_read.is_err());
470
471 let escape_write = cap.write_file("../../../evil.sh", "not written");
472 assert!(escape_write.is_err());
473 }
474
475 #[test]
476 fn test_workspace_capability_shell_execution() {
477 let dir = tempdir().unwrap();
478 let cap = WorkspaceCapability::new(dir.path()).unwrap();
479
480 let out = cap
481 .execute_shell("echo 'contained shell'", None, 5)
482 .unwrap();
483 assert!(out.contains("contained shell"));
484
485 let res = cap.execute_shell("ls", Some("/etc"), 5);
486 assert!(res.is_err());
487 }
488
489 #[test]
490 fn local_catalog_requires_the_whole_command() {
491 assert!(admit_local_command("git status").is_ok());
492 assert!(admit_local_command("git diff").is_ok());
493 assert!(admit_local_command("ls").is_ok());
494 assert!(admit_local_command("git").is_err());
495 assert!(admit_local_command("git push").is_err());
496 assert!(admit_local_command("git status --porcelain").is_err());
497 assert!(admit_local_command("curl example.invalid").is_err());
498 assert!(admit_local_command("git status; curl example.invalid").is_err());
499 assert!(admit_local_command("echo $(curl example.invalid)").is_err());
500 }
501
502 #[test]
503 fn dispatch_shell_refuses_unclassified_text() {
504 let dir = tempdir().unwrap();
505 let cap = WorkspaceCapability::new(dir.path()).unwrap();
506 let refused = cap.dispatch_shell("echo hello", None, 5);
507 assert!(refused.is_err());
508 let allowed = cap.dispatch_shell("ls", None, 5);
509 assert!(allowed.is_ok());
510 }
511}