aidaemon_tools/
file_delivery.rs1use std::path::{Path, PathBuf};
2
3pub struct ReadyMedia {
4 pub canonical_path: PathBuf,
5 pub filename: String,
6 pub size_bytes: u64,
7 pub recovered_into_inbox: bool,
8}
9
10#[derive(Debug)]
13pub enum DeliveryError {
14 FileNotFound(String),
15 NotRegularFile(String),
16 Blocked(String),
17 OutsideAllowedDirs(String),
18 RecoveryFailed {
21 path: PathBuf,
22 error: String,
23 },
24}
25
26pub fn prepare_delivery(
28 requested_path: &str,
29 _cwd: &Path,
30 inbox_dir: &Path,
31 outbox_dirs: &[PathBuf],
32) -> Result<ReadyMedia, DeliveryError> {
33 let expanded = shellexpand::tilde(requested_path).to_string();
35 let path = PathBuf::from(&expanded);
36
37 if !path.exists() {
40 return Err(DeliveryError::FileNotFound(requested_path.to_string()));
41 }
42
43 let metadata = std::fs::metadata(&path)
45 .map_err(|_| DeliveryError::FileNotFound(requested_path.to_string()))?;
46 if !metadata.is_file() {
47 return Err(DeliveryError::NotRegularFile(requested_path.to_string()));
48 }
49
50 let mut canonical = dunce::canonicalize(&path)
52 .map_err(|_| DeliveryError::FileNotFound(requested_path.to_string()))?;
53
54 if is_path_blocked(&canonical) {
56 return Err(DeliveryError::Blocked(requested_path.to_string()));
57 }
58
59 let mut recovered_into_inbox = false;
61 if !is_path_allowed(&canonical, inbox_dir, outbox_dirs) {
62 if !is_recoverable_source(&canonical) {
63 return Err(DeliveryError::OutsideAllowedDirs(
64 requested_path.to_string(),
65 ));
66 }
67 match recover_into_inbox(&canonical, inbox_dir) {
68 Ok(copied) => {
69 canonical = copied;
70 recovered_into_inbox = true;
71 }
72 Err(e) => {
73 return Err(DeliveryError::RecoveryFailed {
74 path: canonical,
75 error: e.to_string(),
76 });
77 }
78 }
79 }
80
81 let filename = canonical
83 .file_name()
84 .map(|n| n.to_string_lossy().to_string())
85 .unwrap_or_else(|| "file".to_string());
86
87 let size_bytes = std::fs::metadata(&canonical).map(|m| m.len()).unwrap_or(0);
89
90 Ok(ReadyMedia {
91 canonical_path: canonical,
92 filename,
93 size_bytes,
94 recovered_into_inbox,
95 })
96}
97
98pub const BLOCKED_PATTERNS: &[&str] = &[
101 ".ssh",
102 ".gnupg",
103 ".env",
104 "credentials",
105 ".key",
106 ".pem",
107 ".aws/credentials",
108 ".netrc",
109 ".docker/config.json",
110 "config.toml",
111];
112
113pub fn is_path_blocked(path: &Path) -> bool {
114 let path_str = path.to_string_lossy();
115 for pattern in BLOCKED_PATTERNS {
116 if pattern.starts_with('.') || pattern.starts_with('/') {
117 if path_str.contains(&format!("/{}", pattern))
119 || path_str.contains(&format!("/{}/", pattern))
120 {
121 return true;
122 }
123 } else if pattern.starts_with("*.") {
124 let ext = &pattern[1..]; if path_str.ends_with(ext) {
127 return true;
128 }
129 } else {
130 if let Some(name) = path.file_name()
132 && name.to_string_lossy() == *pattern
133 {
134 return true;
135 }
136 if path_str.contains(&format!("/{}", pattern))
138 || path_str.contains(&format!("/{}/", pattern))
139 {
140 return true;
141 }
142 }
143 }
144 if let Some(ext) = path.extension() {
146 let ext = ext.to_string_lossy();
147 if ext == "key" || ext == "pem" {
148 return true;
149 }
150 }
151 false
152}
153
154pub fn is_path_allowed(canonical: &Path, inbox_dir: &Path, outbox_dirs: &[PathBuf]) -> bool {
157 let within = |dir: &Path| {
160 canonical.starts_with(dir)
161 || dunce::canonicalize(dir).is_ok_and(|d| canonical.starts_with(d))
162 };
163 if within(inbox_dir) {
165 return true;
166 }
167 outbox_dirs.iter().any(|d| within(d))
169}
170
171pub fn is_recoverable_source(canonical: &Path) -> bool {
178 let mut roots: Vec<PathBuf> = Vec::new();
179 if let Ok(t) = dunce::canonicalize(std::env::temp_dir()) {
180 roots.push(t);
181 }
182 for p in ["/tmp", "/private/tmp", "/var/tmp", "/private/var/tmp"] {
183 if let Ok(c) = dunce::canonicalize(Path::new(p)) {
184 roots.push(c);
185 }
186 }
187 roots.iter().any(|r| canonical.starts_with(r))
188}
189
190pub fn recover_into_inbox(src: &Path, inbox_dir: &Path) -> std::io::Result<PathBuf> {
200 let filename = src
201 .file_name()
202 .unwrap_or_else(|| std::ffi::OsStr::new("file"));
203 let folder = inbox_dir
204 .join("sent")
205 .join(&uuid::Uuid::new_v4().simple().to_string()[..12]);
206 std::fs::create_dir_all(&folder)?;
207 let dest = folder.join(filename);
208 std::fs::copy(src, &dest)?;
209 dunce::canonicalize(&dest)
210}
211
212#[cfg(test)]
213mod tests {
214 use super::*;
215
216 #[test]
217 fn prepare_delivery_recovers_temp_file_into_inbox() {
218 let tmp = tempfile::tempdir().unwrap();
219 let inbox = tmp.path().join("inbox");
220 let src = std::env::temp_dir().join("fd_unit_probe_results.txt");
222 std::fs::write(&src, b"line1\nline2\n").unwrap();
223
224 let ready = prepare_delivery(src.to_str().unwrap(), tmp.path(), &inbox, &[])
225 .expect("temp-root file should be recoverable");
226
227 assert_eq!(ready.filename, "fd_unit_probe_results.txt");
228 assert_eq!(ready.size_bytes, 12);
229 assert!(ready.recovered_into_inbox);
230 assert!(
231 ready
232 .canonical_path
233 .starts_with(dunce::canonicalize(&inbox).unwrap())
234 );
235 let _ = std::fs::remove_file(&src);
236 }
237
238 #[test]
239 fn each_recovered_copy_keeps_what_it_was_when_sent() {
240 let tmp = tempfile::tempdir().unwrap();
241 let inbox = tmp.path().join("inbox");
242 let src = tmp.path().join("shot.png");
243 std::fs::write(&src, b"first").unwrap();
244 let first = recover_into_inbox(&src, &inbox).unwrap();
245 std::fs::write(&src, b"second").unwrap();
246 let second = recover_into_inbox(&src, &inbox).unwrap();
247 assert_ne!(first, second);
248 assert_eq!(first.file_name(), second.file_name());
249 assert_eq!(std::fs::read(&first).unwrap(), b"first");
250 assert_eq!(std::fs::read(&second).unwrap(), b"second");
251 }
252
253 #[test]
254 fn prepare_delivery_blocks_sensitive_paths() {
255 let tmp = tempfile::tempdir().unwrap();
256 let err = prepare_delivery("/etc/passwd", tmp.path(), &tmp.path().join("inbox"), &[]);
257 assert!(matches!(
258 err,
259 Err(DeliveryError::Blocked(_)) | Err(DeliveryError::OutsideAllowedDirs(_))
260 ));
261 }
262
263 #[test]
264 fn prepare_delivery_reports_missing() {
265 let tmp = tempfile::tempdir().unwrap();
266 let err = prepare_delivery(
267 &tmp.path().join("does_not_exist.txt").to_string_lossy(),
268 tmp.path(),
269 &tmp.path().join("inbox"),
270 &[],
271 );
272 assert!(matches!(err, Err(DeliveryError::FileNotFound(_))));
273 }
274
275 #[test]
276 fn prepare_delivery_never_substitutes_a_matching_basename() {
277 let tmp = tempfile::tempdir().unwrap();
278 let inbox = tmp.path().join("inbox");
279 std::fs::create_dir_all(&inbox).unwrap();
280 std::fs::write(inbox.join("report.pdf"), b"old artifact").unwrap();
281
282 let missing = tmp.path().join("missing").join("report.pdf");
283 let err = prepare_delivery(&missing.to_string_lossy(), tmp.path(), &inbox, &[]);
284 assert!(matches!(err, Err(DeliveryError::FileNotFound(_))));
285 }
286}