use larust_core::axum::http::StatusCode;
use larust_core::AppError;
use std::collections::HashMap;
use std::path::{Component, Path, PathBuf};
pub fn local() -> Disk {
local_at(".")
}
pub fn local_at(root: impl AsRef<Path>) -> Disk {
Disk {
root: root.as_ref().join("storage/app"),
url_prefix: None,
}
}
pub fn public() -> Disk {
public_at(".")
}
pub fn public_at(root: impl AsRef<Path>) -> Disk {
Disk {
root: root.as_ref().join("public"),
url_prefix: Some(String::new()),
}
}
pub struct Disk {
root: PathBuf,
url_prefix: Option<String>,
}
impl Disk {
pub async fn put(&self, path: &str, contents: &[u8]) -> Result<(), AppError> {
let target = safe_join(&self.root, path)?;
reject_symlink_ancestors(&self.root, path).await?;
if let Some(parent) = target.parent() {
tokio::fs::create_dir_all(parent)
.await
.map_err(|source| AppError::Internal(Box::new(source)))?;
}
tokio::fs::write(&target, contents)
.await
.map_err(|source| AppError::Internal(Box::new(source)))
}
pub async fn get(&self, path: &str) -> Result<Option<Vec<u8>>, AppError> {
let target = safe_join(&self.root, path)?;
reject_symlink_ancestors(&self.root, path).await?;
match tokio::fs::read(&target).await {
Ok(bytes) => Ok(Some(bytes)),
Err(source) if source.kind() == std::io::ErrorKind::NotFound => Ok(None),
Err(source) => Err(AppError::Internal(Box::new(source))),
}
}
pub async fn exists(&self, path: &str) -> Result<bool, AppError> {
let target = safe_join(&self.root, path)?;
reject_symlink_ancestors(&self.root, path).await?;
tokio::fs::try_exists(&target)
.await
.map_err(|source| AppError::Internal(Box::new(source)))
}
pub async fn delete(&self, path: &str) -> Result<(), AppError> {
let target = safe_join(&self.root, path)?;
reject_symlink_ancestors(&self.root, path).await?;
match tokio::fs::remove_file(&target).await {
Ok(()) => Ok(()),
Err(source) if source.kind() == std::io::ErrorKind::NotFound => Ok(()),
Err(source) => Err(AppError::Internal(Box::new(source))),
}
}
pub fn url(&self, path: &str) -> Result<Option<String>, AppError> {
let Some(prefix) = self.url_prefix.as_deref() else {
return Ok(None);
};
safe_join(&self.root, path)?;
Ok(Some(format!("{prefix}/{path}")))
}
}
pub struct DiskConfig {
root: PathBuf,
url_prefix: Option<String>,
}
impl DiskConfig {
pub fn private(root: impl Into<PathBuf>) -> Self {
Self {
root: root.into(),
url_prefix: None,
}
}
pub fn public(root: impl Into<PathBuf>, url_prefix: impl Into<String>) -> Self {
Self {
root: root.into(),
url_prefix: Some(url_prefix.into()),
}
}
}
#[derive(Default)]
pub struct FilesystemConfig {
disks: HashMap<String, DiskConfig>,
}
impl FilesystemConfig {
pub fn new() -> Self {
Self::default()
}
#[must_use]
pub fn with_disk(mut self, name: impl Into<String>, config: DiskConfig) -> Self {
self.disks.insert(name.into(), config);
self
}
pub fn disk(&self, name: &str) -> Result<Disk, AppError> {
let config = self.disks.get(name).ok_or_else(|| {
AppError::Config(Box::new(std::io::Error::other(format!(
"no disk named {name:?} in FilesystemConfig - declared disks: {:?}",
{
let mut names: Vec<&str> = self.disks.keys().map(String::as_str).collect();
names.sort_unstable();
names
}
))))
})?;
Ok(Disk {
root: config.root.clone(),
url_prefix: config.url_prefix.clone(),
})
}
}
async fn reject_symlink_ancestors(root: &Path, relative: &str) -> Result<(), AppError> {
let mut current = root.to_path_buf();
for component in Path::new(relative).components() {
current.push(component.as_os_str());
match tokio::fs::symlink_metadata(¤t).await {
Ok(metadata) if metadata.file_type().is_symlink() => return Err(invalid_path()),
Ok(_) => {}
Err(source) if source.kind() == std::io::ErrorKind::NotFound => break,
Err(source) => return Err(AppError::Internal(Box::new(source))),
}
}
Ok(())
}
fn safe_join(root: &Path, relative: &str) -> Result<PathBuf, AppError> {
let mut saw_a_component = false;
for component in Path::new(relative).components() {
if !matches!(component, Component::Normal(_)) {
return Err(invalid_path());
}
saw_a_component = true;
}
if !saw_a_component {
return Err(invalid_path());
}
Ok(root.join(relative))
}
fn invalid_path() -> AppError {
AppError::Http {
status: StatusCode::BAD_REQUEST,
message: "invalid storage path".to_string(),
}
}
#[cfg(test)]
mod tests {
use super::*;
fn disk(root: &Path, url_prefix: Option<&str>) -> Disk {
Disk {
root: root.to_path_buf(),
url_prefix: url_prefix.map(String::from),
}
}
#[tokio::test]
async fn put_get_exists_and_delete_round_trip() {
let dir = tempfile::tempdir().unwrap();
let disk = disk(dir.path(), Some(""));
assert!(!disk.exists("greeting.txt").await.unwrap());
assert_eq!(disk.get("greeting.txt").await.unwrap(), None);
disk.put("greeting.txt", b"hello").await.unwrap();
assert!(disk.exists("greeting.txt").await.unwrap());
assert_eq!(
disk.get("greeting.txt").await.unwrap(),
Some(b"hello".to_vec())
);
disk.put("greeting.txt", b"goodbye").await.unwrap();
assert_eq!(
disk.get("greeting.txt").await.unwrap(),
Some(b"goodbye".to_vec())
);
disk.delete("greeting.txt").await.unwrap();
assert!(!disk.exists("greeting.txt").await.unwrap());
assert_eq!(disk.get("greeting.txt").await.unwrap(), None);
disk.delete("greeting.txt").await.unwrap();
}
#[tokio::test]
async fn put_lazily_creates_missing_parent_directories() {
let dir = tempfile::tempdir().unwrap();
let disk = disk(dir.path(), Some(""));
disk.put("uploads/photo.png", b"fake-bytes").await.unwrap();
assert_eq!(
disk.get("uploads/photo.png").await.unwrap(),
Some(b"fake-bytes".to_vec())
);
}
#[tokio::test]
async fn url_reflects_the_disks_prefix() {
let dir = tempfile::tempdir().unwrap();
let public_like = disk(dir.path(), Some(""));
let local_like = disk(dir.path(), None);
assert_eq!(
public_like.url("uploads/photo.png").unwrap(),
Some("/uploads/photo.png".to_string())
);
assert_eq!(local_like.url("uploads/photo.png").unwrap(), None);
}
#[tokio::test]
async fn url_validates_its_path_the_same_as_put_and_get() {
let dir = tempfile::tempdir().unwrap();
let disk = disk(dir.path(), Some(""));
assert!(disk.url("../secret.txt").is_err());
assert!(disk.url("").is_err());
}
#[test]
fn local_and_public_have_the_expected_shape() {
assert_eq!(local().url("x.txt").unwrap(), None);
assert_eq!(public().url("x.txt").unwrap(), Some("/x.txt".to_string()));
}
#[tokio::test]
async fn an_existing_symlink_ancestor_is_rejected() {
let dir = tempfile::tempdir().unwrap();
let root = dir.path().join("disk");
let outside = dir.path().join("outside");
tokio::fs::create_dir_all(&root).await.unwrap();
tokio::fs::create_dir_all(&outside).await.unwrap();
#[cfg(unix)]
std::os::unix::fs::symlink(&outside, root.join("linked")).unwrap();
#[cfg(windows)]
{
if let Err(e) = std::os::windows::fs::symlink_dir(&outside, root.join("linked")) {
if e.raw_os_error() == Some(1314) {
eprintln!(
"skipping an_existing_symlink_ancestor_is_rejected: \
creating a symlink needs Administrator rights or \
Developer Mode enabled on this machine"
);
return;
}
panic!("unexpected error creating test symlink: {e}");
}
}
let disk = disk(&root, Some(""));
assert!(disk.put("linked/escape.txt", b"blocked").await.is_err());
}
#[tokio::test]
async fn path_traversal_is_rejected_and_never_touches_disk() {
let dir = tempfile::tempdir().unwrap();
let disk_root = dir.path().join("disk_root");
tokio::fs::create_dir_all(&disk_root).await.unwrap();
let disk = disk(&disk_root, Some(""));
let outside_file = dir.path().join("secret.txt");
tokio::fs::write(&outside_file, b"top secret")
.await
.unwrap();
let traversal_attempts = [
"../secret.txt",
"uploads/../../secret.txt",
"/etc/passwd",
"",
];
for path in traversal_attempts {
assert!(
disk.get(path).await.is_err(),
"expected {path:?} to be rejected"
);
assert!(
disk.put(path, b"pwned").await.is_err(),
"expected {path:?} to be rejected"
);
assert!(
disk.delete(path).await.is_err(),
"expected {path:?} to be rejected"
);
}
assert_eq!(tokio::fs::read(&outside_file).await.unwrap(), b"top secret");
}
#[cfg(windows)]
#[tokio::test]
async fn a_windows_drive_prefixed_path_is_rejected() {
let dir = tempfile::tempdir().unwrap();
let disk = disk(dir.path(), Some(""));
assert!(disk.get("C:\\Windows\\System32\\config").await.is_err());
assert!(disk.get("C:foo").await.is_err());
assert!(disk.get("\\\\server\\share\\secret.txt").await.is_err());
}
#[tokio::test]
async fn a_declared_disk_actually_works_like_any_other_disk() {
let dir = tempfile::tempdir().unwrap();
let filesystems = FilesystemConfig::new()
.with_disk("exports", DiskConfig::private(dir.path().join("exports")));
let exports = filesystems.disk("exports").unwrap();
exports.put("2024-01.csv", b"id,total\n").await.unwrap();
assert_eq!(
exports.get("2024-01.csv").await.unwrap(),
Some(b"id,total\n".to_vec())
);
assert_eq!(exports.url("2024-01.csv").unwrap(), None);
}
#[tokio::test]
async fn a_public_declared_disk_returns_a_prefixed_url() {
let dir = tempfile::tempdir().unwrap();
let filesystems = FilesystemConfig::new().with_disk(
"avatars",
DiskConfig::public(dir.path().join("avatars"), "/avatars"),
);
let avatars = filesystems.disk("avatars").unwrap();
assert_eq!(
avatars.url("42.png").unwrap(),
Some("/avatars/42.png".to_string())
);
}
#[test]
fn looking_up_an_undeclared_disk_name_fails_clearly() {
let filesystems = FilesystemConfig::new();
match filesystems.disk("nope") {
Err(error) => assert!(format!("{error}").contains("nope")),
Ok(_) => panic!("expected an error for an undeclared disk name"),
}
}
#[test]
fn declaring_the_same_name_twice_keeps_the_last_one() {
let filesystems = FilesystemConfig::new()
.with_disk("exports", DiskConfig::private("first"))
.with_disk("exports", DiskConfig::public("second", "/second"));
let exports = filesystems.disk("exports").unwrap();
assert_eq!(
exports.url("x.txt").unwrap(),
Some("/second/x.txt".to_string())
);
}
#[tokio::test]
async fn a_declared_disk_still_rejects_path_traversal() {
let dir = tempfile::tempdir().unwrap();
let filesystems = FilesystemConfig::new()
.with_disk("exports", DiskConfig::private(dir.path().join("exports")));
let exports = filesystems.disk("exports").unwrap();
assert!(exports.put("../escape.txt", b"pwned").await.is_err());
}
}