aien-sovereign-core-mv
AienOS host runtime: inference scheduling, paged KV state, the aien CLI and Spark verification tooling. Its inference engine is in alpha testing (DGX Spark GB10); Omega is the implementation destination.
Brought by drakestapleton
aien-sovereign-core-mv / crates / aien-drive / src / paths.rs
| 1 | // SPDX-License-Identifier: Apache-2.0 |
| 2 | // Copyright 2026 Drake Stapleton (AIEN / aien-dev) |
| 3 | // |
| 4 | // Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | // you may not use this file except in compliance with the License. |
| 6 | // You may obtain a copy of the License at |
| 7 | // |
| 8 | // http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | // |
| 10 | // Unless required by applicable law or agreed to in writing, software |
| 11 | // distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | // See the License for the specific language governing permissions and |
| 14 | // limitations under the License. |
| 15 | |
| 16 | //! File tools stay inside the command root. |
| 17 | //! |
| 18 | //! Opens use `openat2` with `RESOLVE_BENEATH` and `RESOLVE_NO_SYMLINKS`. |
| 19 | //! A symlink is refused, which also blocks a write through an in-root symlink |
| 20 | //! into `.git`. If `openat2` is unavailable, components are opened with |
| 21 | //! `openat` and `O_NOFOLLOW` from the root directory fd. A symlink, including |
| 22 | //! a dangling one, is refused. The fallback does not create through it. |
| 23 | |
| 24 | use std::fs::File; |
| 25 | use std::io::{Read, Write}; |
| 26 | use std::os::fd::{AsRawFd, FromRawFd, OwnedFd}; |
| 27 | use std::path::{Component, Path, PathBuf}; |
| 28 | |
| 29 | const RESOLVE_BENEATH: u64 = 0x08; |
| 30 | /// Linux `RESOLVE_NO_SYMLINKS` is `0x04`. This is not `RESOLVE_NO_MAGICLINKS` |
| 31 | /// (`0x02`). Keeping `0x04` refuses every symlink, including one whose target |
| 32 | /// is inside the root. |
| 33 | const RESOLVE_NO_SYMLINKS: u64 = 0x04; |
| 34 | |
| 35 | #[repr(C)] |
| 36 | struct OpenHow { |
| 37 | flags: u64, |
| 38 | mode: u64, |
| 39 | resolve: u64, |
| 40 | } |
| 41 | |
| 42 | const SHELL_RC: &[&str] = &[ |
| 43 | ".bashrc", |
| 44 | ".bash_profile", |
| 45 | ".bash_login", |
| 46 | ".profile", |
| 47 | ".zshrc", |
| 48 | ".zshenv", |
| 49 | ".zprofile", |
| 50 | ".zlogin", |
| 51 | ".kshrc", |
| 52 | ".cshrc", |
| 53 | ".tcshrc", |
| 54 | ".shrc", |
| 55 | ]; |
| 56 | |
| 57 | pub(crate) fn read_bytes(root: &Path, user: &str) -> Result<Vec<u8>, String> { |
| 58 | let rel = relative_under_root(root, user)?; |
| 59 | let root_fd = open_root(root)?; |
| 60 | let fd = open_rel(&root_fd, &rel, libc::O_RDONLY, 0)?; |
| 61 | let mut file = File::from(fd); |
| 62 | let mut buf = Vec::new(); |
| 63 | file.read_to_end(&mut buf).map_err(|e| e.to_string())?; |
| 64 | Ok(buf) |
| 65 | } |
| 66 | |
| 67 | pub(crate) fn write_bytes( |
| 68 | root: &Path, |
| 69 | user: &str, |
| 70 | bytes: &[u8], |
| 71 | overwrite: bool, |
| 72 | ) -> Result<usize, String> { |
| 73 | let rel = relative_under_root(root, user)?; |
| 74 | refuse_sensitive_write(&rel)?; |
| 75 | let root_fd = open_root(root)?; |
| 76 | ensure_parents(&root_fd, &rel)?; |
| 77 | let flags = if overwrite { |
| 78 | libc::O_RDWR | libc::O_CREAT |
| 79 | } else { |
| 80 | libc::O_RDWR | libc::O_CREAT | libc::O_EXCL |
| 81 | }; |
| 82 | let fd = open_rel(&root_fd, &rel, flags, 0o644).map_err(|e| { |
| 83 | if e.contains("EEXIST") || e.contains("File exists") { |
| 84 | format!("File {user} exists and overwrite=false") |
| 85 | } else { |
| 86 | e |
| 87 | } |
| 88 | })?; |
| 89 | // A second name for the inode may sit anywhere: a refused path inside the |
| 90 | // root (`.git/hooks/pre-commit`) or a file outside it. The jail cannot |
| 91 | // see the other names, so a multiply linked file is not written. |
| 92 | if link_count(fd.as_raw_fd()).is_none_or(|n| n > 1) { |
| 93 | return Err(format!( |
| 94 | "refusing write to {user}: the file has more than one hard link" |
| 95 | )); |
| 96 | } |
| 97 | if overwrite { |
| 98 | let rc = unsafe { libc::ftruncate(fd.as_raw_fd(), 0) }; |
| 99 | if rc < 0 { |
| 100 | return Err(std::io::Error::last_os_error().to_string()); |
| 101 | } |
| 102 | } |
| 103 | let mut file = File::from(fd); |
| 104 | file.write_all(bytes).map_err(|e| e.to_string())?; |
| 105 | Ok(bytes.len()) |
| 106 | } |
| 107 | |
| 108 | pub(crate) fn list_dir(root: &Path, user: &str) -> Result<Vec<String>, String> { |
| 109 | let rel = relative_under_root(root, user)?; |
| 110 | let root_fd = open_root(root)?; |
| 111 | let fd = open_rel(&root_fd, &rel, libc::O_RDONLY | libc::O_DIRECTORY, 0)?; |
| 112 | let proc = format!("/proc/self/fd/{}", fd.as_raw_fd()); |
| 113 | let mut names: Vec<String> = std::fs::read_dir(&proc) |
| 114 | .map_err(|e| e.to_string())? |
| 115 | .filter_map(|e| e.ok().map(|e| e.file_name().to_string_lossy().into_owned())) |
| 116 | .collect(); |
| 117 | names.sort(); |
| 118 | names.truncate(100); |
| 119 | Ok(names) |
| 120 | } |
| 121 | |
| 122 | pub(crate) fn create_dir(root: &Path, user: &str) -> Result<(), String> { |
| 123 | let rel = relative_under_root(root, user)?; |
| 124 | if rel.as_os_str().is_empty() { |
| 125 | return Ok(()); |
| 126 | } |
| 127 | refuse_sensitive_write(&rel)?; |
| 128 | let root_fd = open_root(root)?; |
| 129 | let mut acc = PathBuf::new(); |
| 130 | for c in rel.components() { |
| 131 | acc.push(c); |
| 132 | refuse_sensitive_write(&acc)?; |
| 133 | match open_rel(&root_fd, &acc, libc::O_RDONLY | libc::O_DIRECTORY, 0) { |
| 134 | Ok(_) => {} |
| 135 | Err(_) => { |
| 136 | mkdir_rel(&root_fd, &acc)?; |
| 137 | } |
| 138 | } |
| 139 | } |
| 140 | Ok(()) |
| 141 | } |
| 142 | |
| 143 | /// Existing object, already opened beneath the root. Callers pass this fd |
| 144 | /// to child processes instead of a path that would be opened again. |
| 145 | pub(crate) fn open_existing(root: &Path, user: &str) -> Result<OwnedFd, String> { |
| 146 | let rel = relative_under_root(root, user)?; |
| 147 | let root_fd = open_root(root)?; |
| 148 | open_rel(&root_fd, &rel, libc::O_RDONLY, 0) |
| 149 | } |
| 150 | |
| 151 | fn refuse_sensitive_write(rel: &Path) -> Result<(), String> { |
| 152 | let mut comps = Vec::new(); |
| 153 | for c in rel.components() { |
| 154 | if let Component::Normal(s) = c { |
| 155 | comps.push(s.to_string_lossy().to_ascii_lowercase()); |
| 156 | } |
| 157 | } |
| 158 | if comps.iter().any(|c| c == ".git" || c == ".ssh") { |
| 159 | return Err("refusing write under a protected directory".into()); |
| 160 | } |
| 161 | if comps.windows(2).any(|w| { |
| 162 | (w[0] == ".github" && w[1] == "workflows") || (w[0] == ".cargo" && w[1] == "config.toml") |
| 163 | }) { |
| 164 | return Err("refusing write under a protected directory".into()); |
| 165 | } |
| 166 | if let Some(name) = comps.last() { |
| 167 | if name == "build.rs" |
| 168 | || name == "makefile" |
| 169 | || name == ".gitattributes" |
| 170 | || name == ".envrc" |
| 171 | || SHELL_RC.iter().any(|rc| name == &rc.to_ascii_lowercase()) |
| 172 | { |
| 173 | return Err("refusing write to a protected file".into()); |
| 174 | } |
| 175 | } |
| 176 | Ok(()) |
| 177 | } |
| 178 | |
| 179 | fn relative_under_root(root: &Path, user: &str) -> Result<PathBuf, String> { |
| 180 | if user.is_empty() { |
| 181 | return Err("path is empty".into()); |
| 182 | } |
| 183 | let root = root |
| 184 | .canonicalize() |
| 185 | .map_err(|e| format!("command root '{}' is not available: {e}", root.display()))?; |
| 186 | let raw = Path::new(user); |
| 187 | let joined = if raw.is_absolute() { |
| 188 | raw.to_path_buf() |
| 189 | } else { |
| 190 | root.join(raw) |
| 191 | }; |
| 192 | let lexical = normalize_lexical(&joined); |
| 193 | if !lexical.starts_with(&root) { |
| 194 | return Err(format!("path '{user}' is outside the command root")); |
| 195 | } |
| 196 | Ok(lexical |
| 197 | .strip_prefix(&root) |
| 198 | .map(Path::to_path_buf) |
| 199 | .unwrap_or_default()) |
| 200 | } |
| 201 | |
| 202 | fn normalize_lexical(path: &Path) -> PathBuf { |
| 203 | let mut out = PathBuf::new(); |
| 204 | for c in path.components() { |
| 205 | match c { |
| 206 | Component::CurDir => {} |
| 207 | Component::ParentDir => { |
| 208 | out.pop(); |
| 209 | } |
| 210 | other => out.push(other.as_os_str()), |
| 211 | } |
| 212 | } |
| 213 | out |
| 214 | } |
| 215 | |
| 216 | fn open_root(root: &Path) -> Result<OwnedFd, String> { |
| 217 | let c = std::ffi::CString::new( |
| 218 | root.canonicalize() |
| 219 | .map_err(|e| e.to_string())? |
| 220 | .as_os_str() |
| 221 | .as_encoded_bytes(), |
| 222 | ) |
| 223 | .map_err(|e| e.to_string())?; |
| 224 | let fd = unsafe { |
| 225 | libc::open( |
| 226 | c.as_ptr(), |
| 227 | libc::O_RDONLY | libc::O_DIRECTORY | libc::O_CLOEXEC, |
| 228 | ) |
| 229 | }; |
| 230 | if fd < 0 { |
| 231 | return Err(std::io::Error::last_os_error().to_string()); |
| 232 | } |
| 233 | Ok(unsafe { OwnedFd::from_raw_fd(fd) }) |
| 234 | } |
| 235 | |
| 236 | fn open_rel(root: &OwnedFd, rel: &Path, flags: i32, mode: u64) -> Result<OwnedFd, String> { |
| 237 | if rel.as_os_str().is_empty() { |
| 238 | let n = unsafe { libc::fcntl(root.as_raw_fd(), libc::F_DUPFD_CLOEXEC, 0) }; |
| 239 | if n < 0 { |
| 240 | return Err(std::io::Error::last_os_error().to_string()); |
| 241 | } |
| 242 | return Ok(unsafe { OwnedFd::from_raw_fd(n) }); |
| 243 | } |
| 244 | let bytes = rel.as_os_str().as_encoded_bytes(); |
| 245 | let c = std::ffi::CString::new(bytes).map_err(|e| e.to_string())?; |
| 246 | let how = OpenHow { |
| 247 | flags: (flags | libc::O_CLOEXEC) as u64, |
| 248 | mode, |
| 249 | resolve: RESOLVE_BENEATH | RESOLVE_NO_SYMLINKS, |
| 250 | }; |
| 251 | if force_enosys() { |
| 252 | return open_rel_fallback(root, rel, flags, mode); |
| 253 | } |
| 254 | let fd = unsafe { |
| 255 | libc::syscall( |
| 256 | libc::SYS_openat2, |
| 257 | root.as_raw_fd(), |
| 258 | c.as_ptr(), |
| 259 | &how as *const OpenHow, |
| 260 | std::mem::size_of::<OpenHow>(), |
| 261 | ) |
| 262 | }; |
| 263 | if fd >= 0 { |
| 264 | return Ok(unsafe { OwnedFd::from_raw_fd(fd as i32) }); |
| 265 | } |
| 266 | let err = std::io::Error::last_os_error(); |
| 267 | if err.raw_os_error() == Some(libc::ENOSYS) { |
| 268 | return open_rel_fallback(root, rel, flags, mode); |
| 269 | } |
| 270 | if err.raw_os_error() == Some(libc::ELOOP) { |
| 271 | return Err("refusing a symlink".into()); |
| 272 | } |
| 273 | if err.raw_os_error() == Some(libc::EXDEV) { |
| 274 | return Err("path leaves the command root".into()); |
| 275 | } |
| 276 | Err(err.to_string()) |
| 277 | } |
| 278 | |
| 279 | fn open_rel_fallback(root: &OwnedFd, rel: &Path, flags: i32, mode: u64) -> Result<OwnedFd, String> { |
| 280 | let mut current = dup_fd(root)?; |
| 281 | let comps: Vec<_> = rel.components().collect(); |
| 282 | if comps.is_empty() { |
| 283 | return Ok(current); |
| 284 | } |
| 285 | for (i, comp) in comps.iter().enumerate() { |
| 286 | let Component::Normal(name) = comp else { |
| 287 | return Err("path leaves the command root".into()); |
| 288 | }; |
| 289 | let last = i + 1 == comps.len(); |
| 290 | let step_flags = if last { |
| 291 | flags | libc::O_NOFOLLOW |
| 292 | } else { |
| 293 | libc::O_RDONLY | libc::O_DIRECTORY | libc::O_NOFOLLOW |
| 294 | }; |
| 295 | let step_mode = if last { mode } else { 0 }; |
| 296 | let next = open_at(¤t, name, step_flags, step_mode)?; |
| 297 | if last { |
| 298 | return Ok(next); |
| 299 | } |
| 300 | current = next; |
| 301 | } |
| 302 | Ok(current) |
| 303 | } |
| 304 | |
| 305 | fn open_at( |
| 306 | dir: &OwnedFd, |
| 307 | name: &std::ffi::OsStr, |
| 308 | flags: i32, |
| 309 | mode: u64, |
| 310 | ) -> Result<OwnedFd, String> { |
| 311 | let c = std::ffi::CString::new(name.as_encoded_bytes()).map_err(|e| e.to_string())?; |
| 312 | let fd = unsafe { |
| 313 | libc::openat( |
| 314 | dir.as_raw_fd(), |
| 315 | c.as_ptr(), |
| 316 | flags | libc::O_CLOEXEC, |
| 317 | mode as libc::mode_t, |
| 318 | ) |
| 319 | }; |
| 320 | if fd >= 0 { |
| 321 | return Ok(unsafe { OwnedFd::from_raw_fd(fd) }); |
| 322 | } |
| 323 | let err = std::io::Error::last_os_error(); |
| 324 | if err.raw_os_error() == Some(libc::ELOOP) { |
| 325 | return Err("refusing a symlink".into()); |
| 326 | } |
| 327 | Err(err.to_string()) |
| 328 | } |
| 329 | |
| 330 | fn dup_fd(fd: &OwnedFd) -> Result<OwnedFd, String> { |
| 331 | let n = unsafe { libc::fcntl(fd.as_raw_fd(), libc::F_DUPFD_CLOEXEC, 0) }; |
| 332 | if n < 0 { |
| 333 | return Err(std::io::Error::last_os_error().to_string()); |
| 334 | } |
| 335 | Ok(unsafe { OwnedFd::from_raw_fd(n) }) |
| 336 | } |
| 337 | |
| 338 | fn link_count(fd: i32) -> Option<u64> { |
| 339 | let mut st: libc::stat = unsafe { std::mem::zeroed() }; |
| 340 | if unsafe { libc::fstat(fd, &mut st) } < 0 { |
| 341 | return None; |
| 342 | } |
| 343 | Some(st.st_nlink as u64) |
| 344 | } |
| 345 | |
| 346 | fn force_enosys() -> bool { |
| 347 | ENOSYS_FOR_TEST.load(std::sync::atomic::Ordering::Relaxed) |
| 348 | } |
| 349 | |
| 350 | static ENOSYS_FOR_TEST: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false); |
| 351 | |
| 352 | #[cfg(test)] |
| 353 | pub(crate) fn set_force_enosys(value: bool) { |
| 354 | ENOSYS_FOR_TEST.store(value, std::sync::atomic::Ordering::Relaxed); |
| 355 | } |
| 356 | |
| 357 | fn ensure_parents(root: &OwnedFd, rel: &Path) -> Result<(), String> { |
| 358 | let mut acc = PathBuf::new(); |
| 359 | let comps: Vec<_> = rel.components().collect(); |
| 360 | if comps.len() <= 1 { |
| 361 | return Ok(()); |
| 362 | } |
| 363 | for c in &comps[..comps.len() - 1] { |
| 364 | acc.push(c); |
| 365 | match open_rel(root, &acc, libc::O_RDONLY | libc::O_DIRECTORY, 0) { |
| 366 | Ok(_) => {} |
| 367 | Err(_) => mkdir_rel(root, &acc)?, |
| 368 | } |
| 369 | } |
| 370 | Ok(()) |
| 371 | } |
| 372 | |
| 373 | fn mkdir_rel(root: &OwnedFd, rel: &Path) -> Result<(), String> { |
| 374 | let parent = rel.parent().unwrap_or(Path::new("")); |
| 375 | let name = rel |
| 376 | .file_name() |
| 377 | .ok_or_else(|| "directory name missing".to_string())?; |
| 378 | let parent_fd = open_rel(root, parent, libc::O_RDONLY | libc::O_DIRECTORY, 0)?; |
| 379 | let c = std::ffi::CString::new(name.as_encoded_bytes()).map_err(|e| e.to_string())?; |
| 380 | let rc = unsafe { libc::mkdirat(parent_fd.as_raw_fd(), c.as_ptr(), 0o755) }; |
| 381 | if rc < 0 { |
| 382 | let err = std::io::Error::last_os_error(); |
| 383 | if err.kind() != std::io::ErrorKind::AlreadyExists { |
| 384 | return Err(err.to_string()); |
| 385 | } |
| 386 | } |
| 387 | Ok(()) |
| 388 | } |
| 389 | |
| 390 | #[cfg(test)] |
| 391 | mod tests { |
| 392 | use super::*; |
| 393 | use std::os::unix::fs::symlink; |
| 394 | |
| 395 | #[test] |
| 396 | fn enosys_fallback_does_not_create_through_a_dangling_symlink() { |
| 397 | let dir = std::env::temp_dir().join(format!("aien-drive-enosys-{}", std::process::id())); |
| 398 | let _ = std::fs::remove_dir_all(&dir); |
| 399 | std::fs::create_dir_all(&dir).unwrap(); |
| 400 | let outside = dir |
| 401 | .parent() |
| 402 | .unwrap() |
| 403 | .join(format!("aien-drive-dangling-{}", std::process::id())); |
| 404 | let _ = std::fs::remove_file(&outside); |
| 405 | symlink(&outside, dir.join("link")).unwrap(); |
| 406 | set_force_enosys(true); |
| 407 | let result = write_bytes(&dir, "link", b"pwned", true); |
| 408 | set_force_enosys(false); |
| 409 | assert!(result.is_err(), "{result:?}"); |
| 410 | assert!(!outside.exists(), "fallback created the symlink target"); |
| 411 | let _ = std::fs::remove_dir_all(&dir); |
| 412 | let _ = std::fs::remove_file(&outside); |
| 413 | } |
| 414 | } |