//! The assistant's Project folder access (#3568): which file commands stay inside the saved //! project's folder. Everything not shown to stay inside asks, so each rule here fails closed: an //! unlisted command, format or parameter, a path that can't be resolved, a link. use super::{ Effect, plan::{Node, Op}, }; use crate::Session; use serde_json::Value; use std::path::{Component, Path, PathBuf}; /// Why the assistant's Project folder access has no folder to work in, so it asks as Ask does. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum NoProjectFolder { /// The project has no file of its own, or its folder is gone. Unsaved, /// The project's file is in the home folder or above it, so "inside" would be everything. TooBroad, } /// What a command does with the one file its `path` names. #[derive(Clone, Copy)] enum Use { /// Reads it, with the files of the same name beside it. Read, /// Writes it, with files of the same name beside it, none of which may be there yet. Create, } /// Native readers whose files can all be bound. Readers with unresolved companion files or /// external references (including KML ground overlays) still ask. const READ: &[&str] = &["csv", "dat", "fgb", "geojson", "geoparquet", "gpkg", "gpx", "json", "parquet", "tsv", "txt", "xlsx"]; /// What Export Map writes. const PICTURES: &[&str] = &["png", "tif", "tiff"]; /// What Export Features and Export Table write. const DATA: &[&str] = &["csv", "fgb", "geojson", "gpkg", "gpx", "kml", "kmz", "parquet", "zip"]; /// The most entries of a folder looked through for files of the same name; a fuller one asks. const MOST_ENTRIES: usize = 100_000; /// The file commands the level runs: what each does with `path`, and the extensions it takes /// there. Each reads or writes nothing its other parameters name. fn file_command(id: &str) -> Option<(Use, &'static [&'static str])> { Some(match id { "layer.addData" | "info.fileLayers" | "info.fileColumns" => (Use::Read, READ), "share.exportMap" => (Use::Create, PICTURES), "share.exportLayer" | "share.exportTable" => (Use::Create, DATA), _ => return None, }) } impl Session { /// The folder of the saved project's file, resolved through links: where the assistant's /// Project folder access works. pub fn assistant_project_folder(&self) -> Result { let folder = self .path .as_deref() .filter(|file| file.is_absolute()) .and_then(Path::parent) .and_then(|folder| folder.canonicalize().ok()) .ok_or(NoProjectFolder::Unsaved)?; let home = std::env::home_dir().and_then(|home| home.canonicalize().ok()); if too_broad(&folder, home.as_deref()) { return Err(NoProjectFolder::TooBroad); } Ok(folder) } } /// Whether `folder` holds so much that working in it would not be working in a project's folder: /// a filesystem's root, the home folder or one above it. fn too_broad(folder: &Path, home: Option<&Path>) -> bool { folder.parent().is_none() || home.is_some_and(|home| home.starts_with(folder)) } /// Whether `node` is a command that only reads files in the project's folder, or only makes new /// ones there. pub(super) fn stays_inside(s: &Session, node: &Node, folder: &Path) -> bool { let Op::Command(spec) = &node.op else { return false }; let Some((how, extensions)) = file_command(spec.id) else { return false }; if !node.children.is_empty() || node.effects.iter().any(|e| !matches!(e, Effect::Files | Effect::Edits | Effect::History)) { return false; } let Some(params) = node.params.as_object() else { return false }; let Some(text) = params.get("path").and_then(Value::as_str) else { return false }; let places = super::effects::PLACE_KEYS; if params .iter() .filter(|(key, _)| key.as_str() != "path") .any(|(key, value)| places.iter().any(|place| key.eq_ignore_ascii_case(place)) || crate::cmd::items::names_place(value, places, 0)) { return false; } // Use the owner's binding, including inputs an export reopens. A generated or unresolved // input cannot be substituted for a path that was checked here. let Some(bound) = &node.file_places else { return false }; let path = Path::new(text); let Some(saved_folder) = s.path.as_deref().and_then(Path::parent) else { return false }; if !bound.iter().any(|place| place == path) || !path.extension().and_then(|ext| ext.to_str()).is_some_and(|ext| extensions.iter().any(|known| ext.eq_ignore_ascii_case(known))) { return false; } let Some((parent, name)) = local_path(saved_folder, folder, path) else { return false }; if !siblings_allow(&parent, name, how) { return false; } bound.iter().all(|place| { if place != path && local_path(saved_folder, folder, place).is_none() { return false; } match std::fs::symlink_metadata(place) { Ok(metadata) => (place != path || matches!(how, Use::Read)) && visible_file(&metadata), Err(error) => error.kind() == std::io::ErrorKind::NotFound && (place != path || matches!(how, Use::Create)), } }) } /// Validates an original spelling before following any directory below the project root. fn local_path<'a>(saved_folder: &Path, folder: &Path, path: &'a Path) -> Option<(PathBuf, &'a str)> { let text = path.to_str()?; if text.trim() != text || text.chars().any(char::is_control) || text.ends_with(['/', '\\']) || text.contains("://") || rustgis_data::source::is_remote_name(text) || !path.is_absolute() || path.components().any(|component| match component { Component::ParentDir => true, Component::Normal(part) if cfg!(windows) => part.to_str().is_none_or(|part| part.contains(':') || part.ends_with(['.', ' '])), _ => false, }) { return None; } let parent = path.parent()?; let name = path.file_name()?.to_str()?; let (root, below) = [folder, saved_folder].into_iter().find_map(|root| parent.strip_prefix(root).ok().map(|below| (root, below)))?; if name.starts_with('.') || !visible_directories(root, below) { return None; } let resolved = parent.canonicalize().ok()?; let below = resolved.strip_prefix(folder).ok()?; (!below.iter().any(hidden)).then_some((resolved, name)) } fn hidden(part: &std::ffi::OsStr) -> bool { part.to_str().is_none_or(|part| part.starts_with('.')) } /// Check each original directory for links before traversing into it. fn visible_directories(root: &Path, below: &Path) -> bool { let mut directory = root.to_path_buf(); if !visible_directory(&directory) { return false; } for part in below { directory.push(part); if hidden(part) || !visible_directory(&directory) { return false; } } true } fn visible_directory(path: &Path) -> bool { std::fs::symlink_metadata(path).is_ok_and(|metadata| metadata.is_dir() && visible_metadata(&metadata)) } fn visible_metadata(metadata: &std::fs::Metadata) -> bool { #[cfg(windows)] { use std::os::windows::fs::MetadataExt; // Hidden files and reparse points can have ordinary names on Windows. const HIDDEN: u32 = 0x2; const REPARSE_POINT: u32 = 0x400; metadata.file_attributes() & (HIDDEN | REPARSE_POINT) == 0 } #[cfg(not(windows))] { let _ = metadata; true } } /// A regular visible file with no other hard link on Unix. fn visible_file(metadata: &std::fs::Metadata) -> bool { #[cfg(unix)] { use std::os::unix::fs::MetadataExt; if metadata.nlink() != 1 { return false; } } metadata.is_file() && visible_metadata(metadata) } /// Looks at the file and those of the same name beside it: /// to read, the file is there and none of them is a link or anything but a file; to create, none /// of them is there. fn siblings_allow(parent: &Path, name: &str, how: Use) -> bool { let name = name.to_lowercase(); let stem = name.rsplit_once('.').map_or(name.as_str(), |(stem, _)| stem); let prefix = format!("{stem}."); let sqlite = name.ends_with(".gpkg"); let sqlite_parts = ["-journal", "-wal", "-shm"].map(|suffix| format!("{name}{suffix}")); let Ok(entries) = std::fs::read_dir(parent) else { return false }; let mut found = false; for (n, entry) in entries.enumerate() { let Ok(entry) = entry else { return false }; let other = entry.file_name().to_string_lossy().to_lowercase(); if n >= MOST_ENTRIES { return false; } if !(other == name || other.starts_with(&prefix) || sqlite && sqlite_parts.contains(&other)) { continue; } // The entry's own type: a link is not followed. if matches!(how, Use::Create) || !entry.metadata().is_ok_and(|metadata| visible_file(&metadata)) { return false; } found |= other == name; } match how { Use::Read => found, Use::Create => true, } } #[cfg(test)] mod tests { use super::*; /// The home folder, those above it and a filesystem's root are no project folder; one inside /// home, or beside it, is. #[test] fn the_home_folder_and_those_above_it_are_too_broad() { let home = Path::new("/home/someone"); for folder in ["/", "/home", "/home/someone"] { assert!(too_broad(Path::new(folder), Some(home)), "{folder}"); } for folder in ["/home/someone/maps", "/home/other", "/data"] { assert!(!too_broad(Path::new(folder), Some(home)), "{folder}"); } assert!(too_broad(Path::new("/"), None)); } }