repositories / smith
smith
There are many coding harnesses - but this one is fast
owned by admin
smith-core/src/workspace.rs
Raw//! Linux descriptor-confined workspace filesystem (`SMH-SPEC-SPEC0001`, Tools).
//!
//! Guest filesystem effects resolve every component from a held root descriptor.
use smith::error::{Result, SmithError, ToolCode};
use std::path::{Component, Path};
/// Held, descriptor-based authority for one guest workspace.
///
/// Linux opens every descendant with `openat2(2)` and rejects symlinks,
/// magic links, and escapes beneath this directory.
#[derive(Clone)]
pub struct WorkspaceRoot {
#[cfg(target_os = "linux")]
root: std::sync::Arc<rustix::fd::OwnedFd>,
}
impl WorkspaceRoot {
/// Hold `path` as the authority root for later guest filesystem effects.
///
/// # Errors
///
/// Returns a tool error when the host does not support descriptor confinement
/// or `path` cannot be opened as a directory.
pub fn open(path: &Path) -> Result<Self> {
#[cfg(target_os = "linux")]
{
use rustix::fs::{CWD, Mode, OFlags, ResolveFlags, openat2};
let root = openat2(
CWD,
path,
OFlags::RDONLY | OFlags::DIRECTORY | OFlags::CLOEXEC,
Mode::empty(),
ResolveFlags::NO_MAGICLINKS | ResolveFlags::NO_SYMLINKS,
)
.map_err(|error| workspace_error(format!("workspace root is invalid: {error}")))?;
Ok(Self {
root: std::sync::Arc::new(root),
})
}
#[cfg(not(target_os = "linux"))]
{
let _ = path;
Err(workspace_error(
"workspace filesystem effects require Linux descriptor confinement",
))
}
}
/// Derive authority for an existing descendant from this held descriptor.
/// Absolute paths, parent traversal and symlinks never grant authority.
///
/// # Errors
/// Returns a tool error if `path` is not a confined descendant directory.
pub fn narrow(&self, path: &str) -> Result<Self> {
#[cfg(target_os = "linux")]
{
let root = self.open_directory(path).map_err(|error| {
workspace_error(format!("workspace delegation is invalid: {error}"))
})?;
Ok(Self {
root: std::sync::Arc::new(root),
})
}
#[cfg(not(target_os = "linux"))]
{
let _ = path;
Err(workspace_error(
"workspace delegation requires Linux descriptor confinement",
))
}
}
/// Whether `path` identifies this held workspace directory.
///
/// # Errors
///
/// Returns a tool error when `path` cannot be opened as a confined root.
pub fn matches_directory(&self, path: &Path) -> Result<bool> {
#[cfg(target_os = "linux")]
{
use rustix::fs::{CWD, Mode, OFlags, ResolveFlags, fstat, openat2};
let candidate = openat2(
CWD,
path,
OFlags::RDONLY | OFlags::DIRECTORY | OFlags::CLOEXEC,
Mode::empty(),
ResolveFlags::NO_MAGICLINKS | ResolveFlags::NO_SYMLINKS,
)
.map_err(|error| workspace_error(format!("workspace root is invalid: {error}")))?;
let held = fstat(&*self.root)
.map_err(|error| workspace_error(format!("workspace root is invalid: {error}")))?;
let candidate = fstat(&candidate)
.map_err(|error| workspace_error(format!("workspace root is invalid: {error}")))?;
Ok(held.st_dev == candidate.st_dev && held.st_ino == candidate.st_ino)
}
#[cfg(not(target_os = "linux"))]
{
let _ = path;
Ok(false)
}
}
#[cfg(target_os = "linux")]
pub(crate) fn open_file(&self, path: &str) -> std::io::Result<std::fs::File> {
use rustix::fs::{Mode, OFlags};
Ok(self
.open_relative(path, OFlags::RDONLY | OFlags::CLOEXEC, Mode::empty())?
.into())
}
#[cfg(target_os = "linux")]
pub(crate) fn open_directory(&self, path: &str) -> std::io::Result<rustix::fd::OwnedFd> {
use rustix::fs::{Mode, OFlags};
self.open_relative(
path,
OFlags::RDONLY | OFlags::DIRECTORY | OFlags::CLOEXEC,
Mode::empty(),
)
}
#[cfg(target_os = "linux")]
pub(crate) fn is_directory(&self, path: &str) -> bool {
self.open_directory(path).is_ok()
}
#[cfg(target_os = "linux")]
pub(crate) fn write_atomic<E>(
&self,
path: &str,
checkpoint_parent: impl FnOnce(bool) -> std::result::Result<(), E>,
write: impl Fn(&mut std::fs::File) -> std::io::Result<()>,
) -> std::result::Result<(), AtomicWriteError<E>> {
use rustix::fs::{AtFlags, Mode, OFlags, renameat, unlinkat};
let (parent, name) = split_parent(path).map_err(AtomicWriteError::Io)?;
let (parent, parent_created) = self
.open_parent_create(parent)
.map_err(AtomicWriteError::Io)?;
checkpoint_parent(parent_created).map_err(AtomicWriteError::Checkpoint)?;
let temporary = temporary_name(name);
let temporary_fd = Self::open_relative_from(
&parent,
&temporary,
OFlags::WRONLY | OFlags::CREATE | OFlags::EXCL | OFlags::CLOEXEC,
Mode::RUSR | Mode::WUSR,
)
.map_err(AtomicWriteError::Io)?;
let mut temporary_file: std::fs::File = temporary_fd.into();
let result = write(&mut temporary_file).and_then(|()| {
temporary_file.sync_all()?;
renameat(&parent, &temporary, &parent, name).map_err(std::io::Error::from)
});
if result.is_err() {
let _cleanup_result: rustix::io::Result<()> =
unlinkat(&parent, &temporary, AtFlags::empty());
}
result.map_err(AtomicWriteError::Io)
}
#[cfg(target_os = "linux")]
pub(crate) fn list_directory<E>(
&self,
path: &str,
entries_max: usize,
mut checkpoint: impl FnMut() -> std::result::Result<(), E>,
) -> std::result::Result<Vec<String>, DirectoryReadError<E>> {
use rustix::fs::Dir;
let directory = self.open_directory(path).map_err(DirectoryReadError::Io)?;
let mut directory = Dir::new(directory)
.map_err(std::io::Error::from)
.map_err(DirectoryReadError::Io)?;
let mut entries = Vec::with_capacity(entries_max);
while let Some(entry) = directory.read() {
checkpoint().map_err(DirectoryReadError::Checkpoint)?;
let entry = entry
.map_err(std::io::Error::from)
.map_err(DirectoryReadError::Io)?;
let name = entry.file_name().to_string_lossy();
if name != "." && name != ".." {
if entries.len() == entries_max {
return Err(DirectoryReadError::Limit);
}
entries.push(name.into_owned());
}
}
entries.sort_unstable();
Ok(entries)
}
#[cfg(target_os = "linux")]
pub(crate) fn version(&self, path: &str) -> std::io::Result<(u64, i64)> {
use rustix::fs::fstat;
let file = self.open_file(path)?;
let metadata = fstat(&file).map_err(std::io::Error::from)?;
let bytes = u64::try_from(metadata.st_size).unwrap_or(0);
let milliseconds = metadata.st_mtime.saturating_mul(1_000)
+ i64::try_from(metadata.st_mtime_nsec / 1_000_000).unwrap_or(i64::MAX);
Ok((bytes, milliseconds))
}
#[cfg(target_os = "linux")]
fn open_relative(
&self,
path: &str,
flags: rustix::fs::OFlags,
mode: rustix::fs::Mode,
) -> std::io::Result<rustix::fd::OwnedFd> {
Self::open_relative_from(&self.root, path, flags, mode)
}
#[cfg(target_os = "linux")]
fn open_relative_from(
parent: &impl rustix::fd::AsFd,
path: &str,
flags: rustix::fs::OFlags,
mode: rustix::fs::Mode,
) -> std::io::Result<rustix::fd::OwnedFd> {
use rustix::fs::{ResolveFlags, openat2};
validate_relative(path)?;
openat2(
parent,
if path.is_empty() { "." } else { path },
flags,
mode,
ResolveFlags::BENEATH | ResolveFlags::NO_MAGICLINKS | ResolveFlags::NO_SYMLINKS,
)
.map_err(std::io::Error::from)
}
#[cfg(target_os = "linux")]
fn open_parent_create(&self, parent: &str) -> std::io::Result<(rustix::fd::OwnedFd, bool)> {
use rustix::fs::{Mode, OFlags};
use rustix::io::fcntl_dupfd_cloexec;
validate_relative(parent)?;
let mut directory = fcntl_dupfd_cloexec(&self.root, 0).map_err(std::io::Error::from)?;
let mut created = false;
for component in Path::new(parent).components() {
let Component::Normal(component) = component else {
continue;
};
match Self::open_relative_from(
&directory,
component.to_string_lossy().as_ref(),
OFlags::RDONLY | OFlags::DIRECTORY | OFlags::CLOEXEC,
Mode::empty(),
) {
Ok(next) => directory = next,
Err(error) if error.kind() == std::io::ErrorKind::NotFound => {
rustix::fs::mkdirat(&directory, component, Mode::RWXU)
.map_err(std::io::Error::from)?;
created = true;
directory = Self::open_relative_from(
&directory,
component.to_string_lossy().as_ref(),
OFlags::RDONLY | OFlags::DIRECTORY | OFlags::CLOEXEC,
Mode::empty(),
)?;
}
Err(error) => return Err(error),
}
}
Ok((directory, created))
}
}
#[cfg(target_os = "linux")]
pub enum AtomicWriteError<E> {
Checkpoint(E),
Io(std::io::Error),
}
#[cfg(target_os = "linux")]
pub enum DirectoryReadError<E> {
Checkpoint(E),
Io(std::io::Error),
Limit,
}
#[cfg(target_os = "linux")]
fn split_parent(path: &str) -> std::io::Result<(&str, &str)> {
validate_relative(path)?;
let path = Path::new(path);
let name = path
.file_name()
.and_then(|name| name.to_str())
.ok_or_else(|| {
std::io::Error::new(
std::io::ErrorKind::InvalidInput,
"workspace path has no file name",
)
})?;
Ok((path.parent().and_then(Path::to_str).unwrap_or(""), name))
}
#[cfg(target_os = "linux")]
fn validate_relative(path: &str) -> std::io::Result<()> {
if Path::new(path).components().any(|component| {
matches!(
component,
Component::ParentDir | Component::RootDir | Component::Prefix(_)
)
}) {
return Err(std::io::Error::new(
std::io::ErrorKind::PermissionDenied,
"workspace path escapes its granted root",
));
}
Ok(())
}
#[cfg(target_os = "linux")]
fn temporary_name(name: &str) -> String {
use std::sync::atomic::{AtomicUsize, Ordering};
static COUNTER: AtomicUsize = AtomicUsize::new(0);
format!(
".{name}.tmp-{}-{}",
std::process::id(),
COUNTER.fetch_add(1, Ordering::Relaxed)
)
}
fn workspace_error(message: impl Into<String>) -> SmithError {
SmithError::Tool {
code: ToolCode::Validation,
message: message.into(),
}
}
#[cfg(all(test, target_os = "linux"))]
mod tests {
//! SMH-SPEC-SPEC0001: descriptor-scoped workspace delegation never widens.
use super::*;
#[test]
fn narrowed_descriptor_survives_rename_and_rejects_symlink_replacement() {
let dir = std::env::temp_dir().join(format!(
"smith-workspace-narrow-{}",
smith::id::SessionId::new()
));
std::fs::create_dir_all(dir.join("A")).unwrap();
std::fs::create_dir_all(dir.join("B")).unwrap();
std::fs::write(dir.join("A/value"), "allowed").unwrap();
std::fs::write(dir.join("B/value"), "denied").unwrap();
let root = WorkspaceRoot::open(&dir).unwrap();
let narrowed = root.narrow("A").unwrap();
std::fs::rename(dir.join("A"), dir.join("held")).unwrap();
std::os::unix::fs::symlink("B", dir.join("A")).unwrap();
assert!(root.narrow("A").is_err());
for escape in ["../B", "/", "held/../../B"] {
assert!(narrowed.narrow(escape).is_err(), "{escape}");
}
use std::io::Read;
let mut text = String::new();
narrowed
.open_file("value")
.unwrap()
.read_to_string(&mut text)
.unwrap();
assert_eq!(text, "allowed");
std::fs::remove_dir_all(dir).unwrap();
}
}