246 lines
7.8 KiB
Rust
246 lines
7.8 KiB
Rust
use crate::fs::{FsBackend, FsEntry, FsError};
|
|
|
|
/// Virtual Filesystem (VFS) interface for Prometeu.
|
|
///
|
|
/// The VFS provides a sandboxed, unified path interface for user applications.
|
|
/// Instead of interacting directly with the host's disk, the VM uses
|
|
/// normalized paths (e.g., `/user/save.dat`).
|
|
///
|
|
/// The actual storage is provided by an `FsBackend`, which can be a real
|
|
/// directory on disk, an in-memory map, or even a network resource.
|
|
pub struct VirtualFS {
|
|
/// The active storage implementation.
|
|
backend: Option<Box<dyn FsBackend>>,
|
|
}
|
|
|
|
impl Default for VirtualFS {
|
|
fn default() -> Self {
|
|
Self::new()
|
|
}
|
|
}
|
|
|
|
impl VirtualFS {
|
|
pub fn new() -> Self {
|
|
Self { backend: None }
|
|
}
|
|
|
|
pub fn mount(&mut self, mut backend: Box<dyn FsBackend>) -> Result<(), FsError> {
|
|
backend.mount()?;
|
|
self.backend = Some(backend);
|
|
Ok(())
|
|
}
|
|
|
|
pub fn unmount(&mut self) {
|
|
if let Some(mut backend) = self.backend.take() {
|
|
backend.unmount();
|
|
}
|
|
}
|
|
|
|
pub fn is_mounted(&self) -> bool {
|
|
self.backend.is_some()
|
|
}
|
|
|
|
fn normalize_path(path: &str) -> Result<String, FsError> {
|
|
let mut normalized = path.replace('\\', "/");
|
|
if !normalized.starts_with('/') {
|
|
normalized = format!("/{}", normalized);
|
|
}
|
|
|
|
let mut segments = Vec::new();
|
|
for segment in normalized.split('/') {
|
|
match segment {
|
|
"" | "." => continue,
|
|
".." => {
|
|
return Err(FsError::InvalidPath(
|
|
"parent traversal '..' is not allowed".to_string(),
|
|
));
|
|
}
|
|
_ => segments.push(segment),
|
|
}
|
|
}
|
|
|
|
if segments.is_empty() {
|
|
Ok("/".to_string())
|
|
} else {
|
|
Ok(format!("/{}", segments.join("/")))
|
|
}
|
|
}
|
|
|
|
pub fn list_dir(&self, path: &str) -> Result<Vec<FsEntry>, FsError> {
|
|
let normalized = Self::normalize_path(path)?;
|
|
let backend = self.backend.as_ref().ok_or(FsError::NotMounted)?;
|
|
backend.list_dir(&normalized)
|
|
}
|
|
|
|
pub fn read_file(&self, path: &str) -> Result<Vec<u8>, FsError> {
|
|
let normalized = Self::normalize_path(path)?;
|
|
let backend = self.backend.as_ref().ok_or(FsError::NotMounted)?;
|
|
backend.read_file(&normalized)
|
|
}
|
|
|
|
pub fn write_file(&mut self, path: &str, data: &[u8]) -> Result<(), FsError> {
|
|
let normalized = Self::normalize_path(path)?;
|
|
let backend = self.backend.as_mut().ok_or(FsError::NotMounted)?;
|
|
backend.write_file(&normalized, data)
|
|
}
|
|
|
|
pub fn delete(&mut self, path: &str) -> Result<(), FsError> {
|
|
let normalized = Self::normalize_path(path)?;
|
|
if normalized == "/" {
|
|
return Err(FsError::PermissionDenied);
|
|
}
|
|
let backend = self.backend.as_mut().ok_or(FsError::NotMounted)?;
|
|
backend.delete(&normalized)
|
|
}
|
|
|
|
pub fn exists(&self, path: &str) -> bool {
|
|
let Ok(normalized) = Self::normalize_path(path) else {
|
|
return false;
|
|
};
|
|
self.backend.as_ref().map(|b| b.exists(&normalized)).unwrap_or(false)
|
|
}
|
|
|
|
pub fn is_healthy(&self) -> bool {
|
|
self.backend.as_ref().map(|b| b.is_healthy()).unwrap_or(false)
|
|
}
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod tests {
|
|
use super::*;
|
|
use std::collections::HashMap;
|
|
use std::sync::Arc;
|
|
use std::sync::atomic::{AtomicUsize, Ordering};
|
|
|
|
#[derive(Default)]
|
|
struct CallCounters {
|
|
list_dir: AtomicUsize,
|
|
read_file: AtomicUsize,
|
|
write_file: AtomicUsize,
|
|
delete: AtomicUsize,
|
|
exists: AtomicUsize,
|
|
}
|
|
|
|
struct MockBackend {
|
|
files: HashMap<String, Vec<u8>>,
|
|
healthy: bool,
|
|
calls: Arc<CallCounters>,
|
|
}
|
|
|
|
impl MockBackend {
|
|
fn new() -> Self {
|
|
Self::with_calls(Arc::new(CallCounters::default()))
|
|
}
|
|
|
|
fn with_calls(calls: Arc<CallCounters>) -> Self {
|
|
Self { files: HashMap::new(), healthy: true, calls }
|
|
}
|
|
}
|
|
|
|
impl FsBackend for MockBackend {
|
|
fn mount(&mut self) -> Result<(), FsError> {
|
|
Ok(())
|
|
}
|
|
fn unmount(&mut self) {}
|
|
fn list_dir(&self, _path: &str) -> Result<Vec<FsEntry>, FsError> {
|
|
self.calls.list_dir.fetch_add(1, Ordering::Relaxed);
|
|
Ok(self
|
|
.files
|
|
.keys()
|
|
.map(|name| FsEntry { name: name.clone(), is_dir: false, size: 0 })
|
|
.collect())
|
|
}
|
|
fn read_file(&self, path: &str) -> Result<Vec<u8>, FsError> {
|
|
self.calls.read_file.fetch_add(1, Ordering::Relaxed);
|
|
self.files.get(path).cloned().ok_or(FsError::NotFound)
|
|
}
|
|
fn write_file(&mut self, path: &str, data: &[u8]) -> Result<(), FsError> {
|
|
self.calls.write_file.fetch_add(1, Ordering::Relaxed);
|
|
self.files.insert(path.to_string(), data.to_vec());
|
|
Ok(())
|
|
}
|
|
fn delete(&mut self, path: &str) -> Result<(), FsError> {
|
|
self.calls.delete.fetch_add(1, Ordering::Relaxed);
|
|
self.files.remove(path);
|
|
Ok(())
|
|
}
|
|
fn exists(&self, path: &str) -> bool {
|
|
self.calls.exists.fetch_add(1, Ordering::Relaxed);
|
|
self.files.contains_key(path)
|
|
}
|
|
fn is_healthy(&self) -> bool {
|
|
self.healthy
|
|
}
|
|
}
|
|
|
|
#[test]
|
|
fn test_virtual_fs_operations() {
|
|
let mut vfs = VirtualFS::new();
|
|
let backend = MockBackend::new();
|
|
|
|
vfs.mount(Box::new(backend)).unwrap();
|
|
|
|
let test_file = "/user/test.txt";
|
|
let content = b"hello world";
|
|
|
|
vfs.write_file(test_file, content).unwrap();
|
|
assert!(vfs.exists(test_file));
|
|
|
|
let read_content = vfs.read_file(test_file).unwrap();
|
|
assert_eq!(read_content, content);
|
|
|
|
vfs.delete(test_file).unwrap();
|
|
assert!(!vfs.exists(test_file));
|
|
}
|
|
|
|
#[test]
|
|
fn test_virtual_fs_health() {
|
|
let mut vfs = VirtualFS::new();
|
|
let mut backend = MockBackend::new();
|
|
backend.healthy = false;
|
|
|
|
vfs.mount(Box::new(backend)).unwrap();
|
|
assert!(!vfs.is_healthy());
|
|
}
|
|
|
|
#[test]
|
|
fn test_normalize_path_rejects_parent_traversal() {
|
|
for path in ["../x", "/../x", "/user/../../x", "\\user\\..\\..\\x"] {
|
|
let error = VirtualFS::normalize_path(path).unwrap_err();
|
|
assert!(matches!(error, FsError::InvalidPath(_)));
|
|
}
|
|
}
|
|
|
|
#[test]
|
|
fn test_invalid_paths_never_reach_backend() {
|
|
let calls = Arc::new(CallCounters::default());
|
|
let mut vfs = VirtualFS::new();
|
|
vfs.mount(Box::new(MockBackend::with_calls(calls.clone()))).unwrap();
|
|
|
|
assert!(matches!(vfs.read_file("../secret.txt"), Err(FsError::InvalidPath(_))));
|
|
assert!(matches!(
|
|
vfs.write_file("/user/../../secret.txt", b"nope"),
|
|
Err(FsError::InvalidPath(_))
|
|
));
|
|
assert!(matches!(vfs.delete("\\user\\..\\secret.txt"), Err(FsError::InvalidPath(_))));
|
|
assert!(matches!(vfs.list_dir("/../"), Err(FsError::InvalidPath(_))));
|
|
assert!(!vfs.exists("../x"));
|
|
|
|
assert_eq!(calls.read_file.load(Ordering::Relaxed), 0);
|
|
assert_eq!(calls.write_file.load(Ordering::Relaxed), 0);
|
|
assert_eq!(calls.delete.load(Ordering::Relaxed), 0);
|
|
assert_eq!(calls.list_dir.load(Ordering::Relaxed), 0);
|
|
assert_eq!(calls.exists.load(Ordering::Relaxed), 0);
|
|
}
|
|
|
|
#[test]
|
|
fn test_delete_root_is_rejected_before_backend() {
|
|
let calls = Arc::new(CallCounters::default());
|
|
let mut vfs = VirtualFS::new();
|
|
vfs.mount(Box::new(MockBackend::with_calls(calls.clone()))).unwrap();
|
|
|
|
assert!(matches!(vfs.delete("/"), Err(FsError::PermissionDenied)));
|
|
assert_eq!(calls.delete.load(Ordering::Relaxed), 0);
|
|
}
|
|
}
|