use std::path::{Path, PathBuf};
pub trait PathGrants {
fn normalize_existing_file(&self, path: &str) -> Result<PathBuf, String>;
fn path_to_string(&self, path: &Path) -> String;
fn require_granted_normalized(&self, path: &Path, what: &str) -> Result<(), String>;
fn require_existing_file(&self, path: &str) -> Result<String, String>;
fn require_write_target(&self, path: &str) -> Result<String, String>;
fn record_write_target(&self, path: &Path) -> Result<(), String>;
fn grant_existing_file_path(&self, path: &Path) -> Result<String, String>;
fn grant_existing_files(&self, paths: &[PathBuf]) -> Vec<String> {
paths
.iter()
.filter_map(|p| self.grant_existing_file_path(p).ok())
.collect()
}
fn register_known_stored_path(&self, path: &str) -> Result<String, String>;
fn grant_stream_token(&self, display: &str) -> Result<String, String>;
fn revoke_path(&self, display: &str) -> Result<(), String>;
}
pub fn authorize_existing_for_read(path: &str, grants: &dyn PathGrants) -> Result<String, String> {
let normalized = grants.normalize_existing_file(path)?;
grants.require_granted_normalized(&normalized, "path")?;
Ok(grants.path_to_string(&normalized))
}
#[cfg(test)]
pub(crate) mod testing {
use super::*;
use std::collections::HashSet;
use std::sync::Mutex;
#[derive(Default)]
pub struct MemoryGrants {
granted: Mutex<HashSet<PathBuf>>,
}
impl PathGrants for MemoryGrants {
fn normalize_existing_file(&self, path: &str) -> Result<PathBuf, String> {
let canon = std::fs::canonicalize(path).map_err(|e| e.to_string())?;
if canon.is_file() {
Ok(canon)
} else {
Err(format!("not a file: {path}"))
}
}
fn path_to_string(&self, path: &Path) -> String {
path.to_string_lossy().into_owned()
}
fn require_granted_normalized(&self, path: &Path, what: &str) -> Result<(), String> {
if self.granted.lock().unwrap().contains(path) {
Ok(())
} else {
Err(format!("{what} is not authorized"))
}
}
fn require_existing_file(&self, path: &str) -> Result<String, String> {
let normalized = self.normalize_existing_file(path)?;
self.require_granted_normalized(&normalized, "path")?;
Ok(self.path_to_string(&normalized))
}
fn require_write_target(&self, path: &str) -> Result<String, String> {
self.require_existing_file(path)
}
fn record_write_target(&self, _path: &Path) -> Result<(), String> {
Ok(())
}
fn grant_existing_file_path(&self, path: &Path) -> Result<String, String> {
let canon = self.normalize_existing_file(&path.to_string_lossy())?;
self.granted.lock().unwrap().insert(canon.clone());
Ok(self.path_to_string(&canon))
}
fn register_known_stored_path(&self, path: &str) -> Result<String, String> {
self.grant_existing_file_path(Path::new(path))
}
fn grant_stream_token(&self, display: &str) -> Result<String, String> {
Ok(format!("stream:{display}"))
}
fn revoke_path(&self, display: &str) -> Result<(), String> {
self.granted.lock().unwrap().remove(Path::new(display));
Ok(())
}
}
}