use std::{ fmt, fs::{File, OpenOptions}, io::{self, Read, Seek, SeekFrom}, path::Path, time::{Duration, Instant}, }; use uuid::Uuid; /// A file selected by the local user and kept open by the Rust layer. /// /// The real path is deliberately not exposed. Keeping the handle open also /// prevents a later server payload from swapping the selected path. pub struct AuthorizedFile { token: Uuid, file: File, display_name: String, expires_at: Instant, } impl AuthorizedFile { pub fn open_local_selection(path: &Path, ttl: Duration) -> io::Result { let file = OpenOptions::new().read(true).open(path)?; if !file.metadata()?.is_file() { return Err(io::Error::new( io::ErrorKind::InvalidInput, "the selected object is not a regular file", )); } let display_name = path .file_name() .and_then(|value| value.to_str()) .unwrap_or("selected-file") .to_owned(); Ok(Self { token: Uuid::new_v4(), file, display_name, expires_at: Instant::now() + ttl, }) } pub fn token(&self) -> Uuid { self.token } pub fn display_name(&self) -> &str { &self.display_name } pub fn is_expired(&self) -> bool { Instant::now() >= self.expires_at } pub(crate) fn ensure_active(&self) -> io::Result<()> { if self.is_expired() { return Err(io::Error::new( io::ErrorKind::PermissionDenied, "the local file authorization has expired", )); } Ok(()) } pub(crate) fn try_clone_file(&self) -> io::Result { self.ensure_active()?; self.file.try_clone() } pub(crate) fn read_bounded(&self, maximum_bytes: usize) -> io::Result> { self.ensure_active()?; let mut file = self.file.try_clone()?; let length = file.metadata()?.len(); if length > maximum_bytes as u64 { return Err(io::Error::new( io::ErrorKind::InvalidData, "the selected file exceeds the configured read limit", )); } file.seek(SeekFrom::Start(0))?; let mut bytes = Vec::with_capacity(length as usize); file.read_to_end(&mut bytes)?; Ok(bytes) } } impl fmt::Debug for AuthorizedFile { fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { formatter .debug_struct("AuthorizedFile") .field("token", &self.token) .field("display_name", &self.display_name) .field("expired", &self.is_expired()) .finish_non_exhaustive() } }