Skip to main content

strata_vfs/
types.rs

1//! Canonical VFS Types, Paths, Metadata, and Error Definitions.
2
3use std::path::{Component, Path, PathBuf};
4
5/// Canonical virtual filesystem root boundaries.
6#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
7pub enum VfsRoot {
8    /// Persistent application configuration, state, and user databases.
9    AppData,
10    /// Discardable cached files, shaders, network assets.
11    Cache,
12    /// User documents, exported projects, and media files.
13    Documents,
14    /// Transient scratch data discarded on session exit.
15    Temp,
16}
17
18impl VfsRoot {
19    pub fn as_str(&self) -> &'static str {
20        match self {
21            Self::AppData => "app_data",
22            Self::Cache => "cache",
23            Self::Documents => "documents",
24            Self::Temp => "temp",
25        }
26    }
27
28    pub fn parse(s: &str) -> Option<Self> {
29        s.parse().ok()
30    }
31}
32
33impl std::str::FromStr for VfsRoot {
34    type Err = ();
35
36    fn from_str(s: &str) -> Result<Self, Self::Err> {
37        match s.to_ascii_lowercase().as_str() {
38            "app_data" | "appdata" => Ok(Self::AppData),
39            "cache" => Ok(Self::Cache),
40            "documents" | "docs" => Ok(Self::Documents),
41            "temp" | "tmp" => Ok(Self::Temp),
42            _ => Err(()),
43        }
44    }
45}
46
47/// A sandboxed path anchored to a specific `VfsRoot`.
48///
49/// Guaranteed to prevent directory traversal (`../`) escapes.
50#[derive(Debug, Clone, PartialEq, Eq, Hash)]
51pub struct VfsPath {
52    root: VfsRoot,
53    subpath: PathBuf,
54}
55
56impl VfsPath {
57    pub fn new(root: VfsRoot, subpath: impl AsRef<Path>) -> Self {
58        let sub_ref = subpath.as_ref();
59        let raw_str = sub_ref.to_string_lossy();
60        if crate::driver::is_windows_unc_device_namespace(&raw_str) {
61            return Self {
62                root,
63                subpath: sub_ref.to_path_buf(),
64            };
65        }
66        let clean = Self::sanitize_subpath(sub_ref);
67        Self {
68            root,
69            subpath: clean,
70        }
71    }
72
73    /// Root anchor for this path.
74    pub fn root(&self) -> VfsRoot {
75        self.root
76    }
77
78    /// Relative subpath within the virtual root.
79    pub fn subpath(&self) -> &Path {
80        &self.subpath
81    }
82
83    /// Appends subpath components while neutralizing directory traversal attacks.
84    pub fn join(&self, path: impl AsRef<Path>) -> Self {
85        let path_ref = path.as_ref();
86        let raw_str = path_ref.to_string_lossy();
87        if crate::driver::is_windows_unc_device_namespace(&raw_str) {
88            return Self {
89                root: self.root,
90                subpath: self.subpath.join(path_ref),
91            };
92        }
93        let joined = self.subpath.join(path);
94        let clean = Self::sanitize_subpath(&joined);
95        Self {
96            root: self.root,
97            subpath: clean,
98        }
99    }
100
101    /// Serializes path into a universal VFS URI string (e.g. `vfs://app_data/settings.json`).
102    pub fn to_uri(&self) -> String {
103        let sub = self.subpath.to_string_lossy().replace('\\', "/");
104        let sub_clean = sub.trim_start_matches('/');
105        format!("vfs://{}/{}", self.root.as_str(), sub_clean)
106    }
107
108    /// Checks whether a given path string attempts to traverse outside of the virtual root.
109    pub fn has_traversal_escape(subpath: &str) -> bool {
110        let normalized = subpath.replace('\\', "/");
111        let mut depth: isize = 0;
112        for part in normalized.split('/') {
113            if part.is_empty() || part == "." {
114                continue;
115            } else if part == ".." {
116                depth -= 1;
117                if depth < 0 {
118                    return true;
119                }
120            } else {
121                depth += 1;
122            }
123        }
124        false
125    }
126
127    /// Attempts to construct a `VfsPath`, returning `Err(FsError::SecurityViolation)` if traversal escapes the root.
128    pub fn try_new(root: VfsRoot, subpath: impl AsRef<Path>) -> Result<Self, FsError> {
129        let subpath_ref = subpath.as_ref();
130        let subpath_str = subpath_ref.to_string_lossy();
131        if Self::has_traversal_escape(&subpath_str) {
132            return Err(FsError::SecurityViolation(format!(
133                "Directory traversal escape detected in subpath: {}",
134                subpath_str
135            )));
136        }
137        Ok(Self::new(root, subpath_ref))
138    }
139
140    /// Parses a universal VFS URI string, strictly rejecting directory traversal attempts.
141    pub fn from_uri(uri: &str) -> Result<Self, FsError> {
142        let stripped = uri.strip_prefix("vfs://").ok_or_else(|| {
143            FsError::InvalidPath(format!("URI does not start with 'vfs://': {uri}"))
144        })?;
145
146        let mut parts = stripped.splitn(2, '/');
147        let root_str = parts.next().unwrap_or("");
148        let sub_str = parts.next().unwrap_or("");
149
150        let root = VfsRoot::parse(root_str)
151            .ok_or_else(|| FsError::InvalidPath(format!("Unknown VfsRoot in URI: {root_str}")))?;
152
153        if Self::has_traversal_escape(sub_str) {
154            return Err(FsError::SecurityViolation(format!(
155                "Directory traversal escape detected in URI: {uri}"
156            )));
157        }
158
159        Ok(Self::new(root, PathBuf::from(sub_str)))
160    }
161
162    /// Strict path sanitizer preventing directory traversal (`..`) outside root.
163    fn sanitize_subpath(path: &Path) -> PathBuf {
164        let mut clean = PathBuf::new();
165        for comp in path.components() {
166            match comp {
167                Component::Normal(c) => {
168                    let s = c.to_string_lossy();
169                    // Strip Windows drive letters (e.g., "C:", "D:")
170                    if s.len() == 2
171                        && s.ends_with(':')
172                        && s.chars()
173                            .next()
174                            .map(|ch| ch.is_ascii_alphabetic())
175                            .unwrap_or(false)
176                    {
177                        continue;
178                    }
179                    clean.push(c);
180                }
181                Component::CurDir => {}
182                Component::ParentDir => {
183                    // Pop only if not at root, never traversing above
184                    clean.pop();
185                }
186                Component::RootDir | Component::Prefix(_) => {
187                    // Ignore drive letters or absolute root slashes
188                }
189            }
190        }
191        clean
192    }
193}
194
195/// Metadata attributes for a virtual file or directory.
196#[derive(Debug, Clone, PartialEq, Eq)]
197pub struct VfsMetadata {
198    pub is_file: bool,
199    pub is_dir: bool,
200    pub len: u64,
201    pub modified_timestamp_secs: u64,
202}
203
204/// Errors occurring during virtual filesystem operations.
205#[derive(Debug, Clone, PartialEq, Eq)]
206pub enum FsError {
207    NotFound(String),
208    PermissionDenied(String),
209    AlreadyExists(String),
210    InvalidPath(String),
211    IoError(String),
212    SecurityViolation(String),
213}
214
215impl std::fmt::Display for FsError {
216    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
217        match self {
218            Self::NotFound(s) => write!(f, "File or directory not found: {s}"),
219            Self::PermissionDenied(s) => write!(f, "Permission denied: {s}"),
220            Self::AlreadyExists(s) => write!(f, "Already exists: {s}"),
221            Self::InvalidPath(s) => write!(f, "Invalid path: {s}"),
222            Self::IoError(s) => write!(f, "I/O error: {s}"),
223            Self::SecurityViolation(s) => write!(f, "Security violation: {s}"),
224        }
225    }
226}
227
228impl std::error::Error for FsError {}