use std::path::{Path, PathBuf};
pub struct ReadyMedia {
pub canonical_path: PathBuf,
pub filename: String,
pub size_bytes: u64,
pub recovered_into_inbox: bool,
}
#[derive(Debug)]
pub enum DeliveryError {
FileNotFound(String),
NotRegularFile(String),
Blocked(String),
OutsideAllowedDirs(String),
RecoveryFailed {
path: PathBuf,
error: String,
},
}
pub fn prepare_delivery(
requested_path: &str,
_cwd: &Path,
inbox_dir: &Path,
outbox_dirs: &[PathBuf],
) -> Result<ReadyMedia, DeliveryError> {
let expanded = shellexpand::tilde(requested_path).to_string();
let path = PathBuf::from(&expanded);
if !path.exists() {
return Err(DeliveryError::FileNotFound(requested_path.to_string()));
}
let metadata = std::fs::metadata(&path)
.map_err(|_| DeliveryError::FileNotFound(requested_path.to_string()))?;
if !metadata.is_file() {
return Err(DeliveryError::NotRegularFile(requested_path.to_string()));
}
let mut canonical = dunce::canonicalize(&path)
.map_err(|_| DeliveryError::FileNotFound(requested_path.to_string()))?;
if is_path_blocked(&canonical) {
return Err(DeliveryError::Blocked(requested_path.to_string()));
}
let mut recovered_into_inbox = false;
if !is_path_allowed(&canonical, inbox_dir, outbox_dirs) {
if !is_recoverable_source(&canonical) {
return Err(DeliveryError::OutsideAllowedDirs(
requested_path.to_string(),
));
}
match recover_into_inbox(&canonical, inbox_dir) {
Ok(copied) => {
canonical = copied;
recovered_into_inbox = true;
}
Err(e) => {
return Err(DeliveryError::RecoveryFailed {
path: canonical,
error: e.to_string(),
});
}
}
}
let filename = canonical
.file_name()
.map(|n| n.to_string_lossy().to_string())
.unwrap_or_else(|| "file".to_string());
let size_bytes = std::fs::metadata(&canonical).map(|m| m.len()).unwrap_or(0);
Ok(ReadyMedia {
canonical_path: canonical,
filename,
size_bytes,
recovered_into_inbox,
})
}
pub const BLOCKED_PATTERNS: &[&str] = &[
".ssh",
".gnupg",
".env",
"credentials",
".key",
".pem",
".aws/credentials",
".netrc",
".docker/config.json",
"config.toml",
];
pub fn is_path_blocked(path: &Path) -> bool {
let path_str = path.to_string_lossy();
for pattern in BLOCKED_PATTERNS {
if pattern.starts_with('.') || pattern.starts_with('/') {
if path_str.contains(&format!("/{}", pattern))
|| path_str.contains(&format!("/{}/", pattern))
{
return true;
}
} else if pattern.starts_with("*.") {
let ext = &pattern[1..]; if path_str.ends_with(ext) {
return true;
}
} else {
if let Some(name) = path.file_name()
&& name.to_string_lossy() == *pattern
{
return true;
}
if path_str.contains(&format!("/{}", pattern))
|| path_str.contains(&format!("/{}/", pattern))
{
return true;
}
}
}
if let Some(ext) = path.extension() {
let ext = ext.to_string_lossy();
if ext == "key" || ext == "pem" {
return true;
}
}
false
}
pub fn is_path_allowed(canonical: &Path, inbox_dir: &Path, outbox_dirs: &[PathBuf]) -> bool {
if canonical.starts_with(inbox_dir) {
return true;
}
outbox_dirs.iter().any(|d| canonical.starts_with(d))
}
pub fn is_recoverable_source(canonical: &Path) -> bool {
let mut roots: Vec<PathBuf> = Vec::new();
if let Ok(t) = dunce::canonicalize(std::env::temp_dir()) {
roots.push(t);
}
for p in ["/tmp", "/private/tmp", "/var/tmp", "/private/var/tmp"] {
if let Ok(c) = dunce::canonicalize(Path::new(p)) {
roots.push(c);
}
}
roots.iter().any(|r| canonical.starts_with(r))
}
pub fn recover_into_inbox(src: &Path, inbox_dir: &Path) -> std::io::Result<PathBuf> {
std::fs::create_dir_all(inbox_dir)?;
let filename = src
.file_name()
.unwrap_or_else(|| std::ffi::OsStr::new("file"));
let dest = inbox_dir.join(filename);
std::fs::copy(src, &dest)?;
dunce::canonicalize(&dest)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn prepare_delivery_recovers_temp_file_into_inbox() {
let tmp = tempfile::tempdir().unwrap();
let inbox = tmp.path().join("inbox");
let src = std::env::temp_dir().join("fd_unit_probe_results.txt");
std::fs::write(&src, b"line1\nline2\n").unwrap();
let ready = prepare_delivery(src.to_str().unwrap(), tmp.path(), &inbox, &[])
.expect("temp-root file should be recoverable");
assert_eq!(ready.filename, "fd_unit_probe_results.txt");
assert_eq!(ready.size_bytes, 12);
assert!(ready.recovered_into_inbox);
assert!(
ready
.canonical_path
.starts_with(dunce::canonicalize(&inbox).unwrap())
);
let _ = std::fs::remove_file(&src);
}
#[test]
fn prepare_delivery_blocks_sensitive_paths() {
let tmp = tempfile::tempdir().unwrap();
let err = prepare_delivery("/etc/passwd", tmp.path(), &tmp.path().join("inbox"), &[]);
assert!(matches!(
err,
Err(DeliveryError::Blocked(_)) | Err(DeliveryError::OutsideAllowedDirs(_))
));
}
#[test]
fn prepare_delivery_reports_missing() {
let tmp = tempfile::tempdir().unwrap();
let err = prepare_delivery(
&tmp.path().join("does_not_exist.txt").to_string_lossy(),
tmp.path(),
&tmp.path().join("inbox"),
&[],
);
assert!(matches!(err, Err(DeliveryError::FileNotFound(_))));
}
#[test]
fn prepare_delivery_never_substitutes_a_matching_basename() {
let tmp = tempfile::tempdir().unwrap();
let inbox = tmp.path().join("inbox");
std::fs::create_dir_all(&inbox).unwrap();
std::fs::write(inbox.join("report.pdf"), b"old artifact").unwrap();
let missing = tmp.path().join("missing").join("report.pdf");
let err = prepare_delivery(&missing.to_string_lossy(), tmp.path(), &inbox, &[]);
assert!(matches!(err, Err(DeliveryError::FileNotFound(_))));
}
}