1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
use std::path::{Component, Path, PathBuf};
use super::errors::{Error, ErrorKind, Result};
/// Data-only type for safe path handling.
/// Centralized under `crate::types` for cross-layer reuse.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct SafePath {
/// The root path that this safe path is relative to
root: PathBuf,
/// The relative path component
rel: PathBuf,
}
impl SafePath {
/// Creates a new `SafePath` from a root and candidate path.
///
/// This function ensures that the candidate path is within the root path
/// and does not contain any unsafe components like dotdot (..).
///
/// # Arguments
///
/// * `root` - The root path that the candidate should be within
/// * `candidate` - The path to check and make safe
///
/// # Returns
///
/// * `Result<Self>` - A `SafePath` if the candidate is valid, or an error otherwise
///
/// # Errors
///
/// Returns an error if the root path is not absolute, if the candidate path escapes the root,
/// or if the candidate path contains unsafe components like dotdot (..).
///
/// # Panics
///
/// Panics when `root` is not absolute. This mirrors historical semantics and
/// preserves SPEC/BDD expectations for construction invariants in tests.
///
/// # Example
///
/// ```rust
/// use switchyard::types::safepath::SafePath;
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// let td = tempfile::tempdir()?;
/// let root = td.path();
/// std::fs::create_dir_all(root.join("usr/bin"))?;
/// let sp = SafePath::from_rooted(root, &root.join("usr/bin/ls"))?;
/// assert!(sp.as_path().starts_with(root));
/// # Ok(())
/// # }
/// ```
#[allow(
clippy::panic,
reason = "Root absoluteness is a construction invariant"
)]
pub fn from_rooted(root: &Path, candidate: &Path) -> Result<Self> {
assert!(root.is_absolute(), "root must be absolute");
let effective = if candidate.is_absolute() {
match candidate.strip_prefix(root) {
Ok(p) => p.to_path_buf(),
Err(_) => {
return Err(Error {
kind: ErrorKind::Policy,
msg: "path escapes root".into(),
})
}
}
} else {
candidate.to_path_buf()
};
let mut rel = PathBuf::new();
for seg in effective.components() {
match seg {
Component::CurDir => {}
Component::Normal(p) => rel.push(p),
Component::ParentDir => {
return Err(Error {
kind: ErrorKind::Policy,
msg: "dotdot".into(),
});
}
Component::Prefix(_) | Component::RootDir => {
return Err(Error {
kind: ErrorKind::InvalidPath,
msg: "unsupported component".into(),
});
}
}
}
let norm = root.join(&rel);
if !norm.starts_with(root) {
return Err(Error {
kind: ErrorKind::Policy,
msg: "path escapes root".into(),
});
}
Ok(SafePath {
root: root.to_path_buf(),
rel,
})
}
/// Returns the full path by joining the root and relative components.
///
/// # Returns
///
/// * `PathBuf` - The complete path
#[must_use]
pub fn as_path(&self) -> PathBuf {
self.root.join(&self.rel)
}
/// Returns a reference to the relative path component.
///
/// # Returns
///
/// * `&Path` - Reference to the relative path
#[must_use]
pub fn rel(&self) -> &Path {
&self.rel
}
}
#[cfg(test)]
#[allow(clippy::panic)]
mod tests {
use super::*;
use std::path::Path;
#[test]
fn rejects_dotdot() {
let root = Path::new("/tmp");
assert!(SafePath::from_rooted(root, Path::new("../etc")).is_err());
}
#[test]
fn accepts_absolute_inside_root() {
let root = Path::new("/tmp/root");
let candidate = Path::new("/tmp/root/usr/bin/ls");
let sp = SafePath::from_rooted(root, candidate).unwrap_or_else(|e| {
panic!("Failed to create SafePath for absolute path inside root: {e}")
});
assert!(sp.as_path().starts_with(root));
assert_eq!(sp.rel(), Path::new("usr/bin/ls"));
}
#[test]
fn rejects_absolute_outside_root() {
let root = Path::new("/tmp/root");
let candidate = Path::new("/etc/passwd");
assert!(SafePath::from_rooted(root, candidate).is_err());
}
#[test]
fn normalizes_curdir_components() {
let root = Path::new("/tmp/root");
let candidate = Path::new("./usr/./bin/./ls");
let sp = SafePath::from_rooted(root, candidate).unwrap_or_else(|e| {
panic!("Failed to create SafePath with normalized curdir components: {e}")
});
assert_eq!(sp.rel(), Path::new("usr/bin/ls"));
assert_eq!(sp.as_path(), Path::new("/tmp/root/usr/bin/ls"));
}
}