Skip to main content

aidaemon_tools/
file_delivery.rs

1use 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/// Error variants carry the originally-requested path (or recovery context)
11/// so callers can construct user-facing messages that include the relevant detail.
12#[derive(Debug)]
13pub enum DeliveryError {
14    FileNotFound(String),
15    NotRegularFile(String),
16    Blocked(String),
17    OutsideAllowedDirs(String),
18    /// Recovery copy into the inbox failed. Carries the canonical source path
19    /// (so the caller can render a correct `cp` example) and the error message.
20    RecoveryFailed {
21        path: PathBuf,
22        error: String,
23    },
24}
25
26/// Validate + recover a path for delivery. No transport — callers send `ReadyMedia` through their own sink.
27pub fn prepare_delivery(
28    requested_path: &str,
29    _cwd: &Path,
30    inbox_dir: &Path,
31    outbox_dirs: &[PathBuf],
32) -> Result<ReadyMedia, DeliveryError> {
33    // 1. Expand ~ in the path
34    let expanded = shellexpand::tilde(requested_path).to_string();
35    let path = PathBuf::from(&expanded);
36
37    // 2. Resource selection is exact. Never substitute a different file just
38    // because it has the same basename in an allowed directory.
39    if !path.exists() {
40        return Err(DeliveryError::FileNotFound(requested_path.to_string()));
41    }
42
43    // 3. Must be a regular file
44    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    // 4. Canonicalize to resolve symlinks and prevent traversal
51    let mut canonical = dunce::canonicalize(&path)
52        .map_err(|_| DeliveryError::FileNotFound(requested_path.to_string()))?;
53
54    // 5. Block sensitive files BEFORE any recovery
55    if is_path_blocked(&canonical) {
56        return Err(DeliveryError::Blocked(requested_path.to_string()));
57    }
58
59    // 6. If outside allowed dirs, try auto-recovery from temp roots only
60    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    // 7. Compute filename and size
82    let filename = canonical
83        .file_name()
84        .map(|n| n.to_string_lossy().to_string())
85        .unwrap_or_else(|| "file".to_string());
86
87    // Re-read size from the canonical (possibly recovered) path
88    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
98// ── Blocked path patterns ──────────────────────────────────────────────────
99
100pub 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            // Component-based check: .ssh, .gnupg, .env, .aws/credentials, etc.
118            if path_str.contains(&format!("/{}", pattern))
119                || path_str.contains(&format!("/{}/", pattern))
120            {
121                return true;
122            }
123        } else if pattern.starts_with("*.") {
124            // Extension-based check (not used currently but future-proof)
125            let ext = &pattern[1..]; // ".key", ".pem"
126            if path_str.ends_with(ext) {
127                return true;
128            }
129        } else {
130            // Exact filename check
131            if let Some(name) = path.file_name()
132                && name.to_string_lossy() == *pattern
133            {
134                return true;
135            }
136            // Also check as path component
137            if path_str.contains(&format!("/{}", pattern))
138                || path_str.contains(&format!("/{}/", pattern))
139            {
140                return true;
141            }
142        }
143    }
144    // Also block files ending with .key or .pem
145    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
154// ── Allowed-dir check ──────────────────────────────────────────────────────
155
156pub fn is_path_allowed(canonical: &Path, inbox_dir: &Path, outbox_dirs: &[PathBuf]) -> bool {
157    // `canonical` is canonical, so compare with each folder's canonical form
158    // too (on macOS a temp inbox under /var is /private/var).
159    let within = |dir: &Path| {
160        canonical.starts_with(dir)
161            || dunce::canonicalize(dir).is_ok_and(|d| canonical.starts_with(d))
162    };
163    // Allow files in inbox dir (agent returning processed files)
164    if within(inbox_dir) {
165        return true;
166    }
167    // Check against allowed outbox dirs
168    outbox_dirs.iter().any(|d| within(d))
169}
170
171// ── Recoverable-source check ───────────────────────────────────────────────
172
173/// Whether a canonical path is eligible for auto-recovery into the inbox.
174/// Restricted to system temp roots (the only place agents legitimately write
175/// scratch output) so recovery cannot become an arbitrary-file exfiltration
176/// path. Roots are canonicalized so macOS `/tmp` → `/private/tmp` matches.
177pub 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
190// ── Recovery into inbox ────────────────────────────────────────────────────
191
192/// Copy a readable file from outside the delivery folders into the inbox so
193/// it can be delivered: a copy as it is now, in a folder of its own, so a
194/// later file of the same name (or the same file changed) never alters what
195/// an earlier message shows. Returns the canonical path of the copy, which
196/// keeps the file's name. Caller must have already run the blocked-pattern
197/// check, and decided `src` may be sent (a temp root, `is_recoverable_source`,
198/// or a file its run made).
199pub 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        // A file in a recognized temp root (the tempdir is under the OS temp root in CI).
221        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}