diff --git a/crates/engine/src/cmd/field.rs b/crates/engine/src/cmd/field.rs index a84ddadedf..864446b084 100644 --- a/crates/engine/src/cmd/field.rs +++ b/crates/engine/src/cmd/field.rs @@ -1457,7 +1457,10 @@ pub(crate) fn bring_back(s: &mut Session, p: &Value) -> Result { if outbound { return Err("this field package was made here to go to the field, not sent back from it: Bring Back reads the package the phone sends with Send Field Package. Nothing was changed".into()); } - let project = Project::from_import_json(&text, None)?; + // Held within where the package came from ([`Session::file_reach`]) before its read reads + // anything it names. + let (project, named) = Project::from_import_json_within(&text, None, s.file_reach(p))?; + named.say(s, "the field package"); let ai = if let Some(area) = legacy_area { let raw: Value = serde_json::from_str(&text).map_err(|e| e.to_string())?; // Only entirely absent identities qualify. Null/empty/malformed metadata is not a @@ -1871,8 +1874,9 @@ pub(crate) fn unpack_into(bytes: &[u8], dir: &Path) -> Result<(String, Vec Vec { /// photos stay usable after opening a recovery copy, which has no unpack directory of its own. /// References that cannot store an absolute path are left relative and reported on open. A package /// that went out from home has the rows it gives taken (`Project::given`), for -/// `offline.keepRows` to keep on this device. -pub(crate) fn project_in(text: &str, dir: &Path) -> Result { - let mut project = Project::from_import_json(text, Some(dir))?; +/// `offline.keepRows` to keep on this device. What the project names is held within `reach` before +/// anything it names is read ([`Project::from_import_json_within`]). +pub(crate) fn project_in_within( + text: &str, + dir: &Path, + reach: crate::render::rustgis_tiles::address::Reach, +) -> Result<(Project, crate::received::Named), String> { + let (mut project, named) = Project::from_import_json_within(text, Some(dir), reach)?; let photos = std::path::absolute(dir.join(PHOTOS)).map_err(|e| e.to_string())?; let mut relative = 0_usize; // Photos from home that keep their names there, the unpack folder's name not being text. @@ -2002,7 +2011,13 @@ pub(crate) fn project_in(text: &str, dir: &Path) -> Result { ), )); } - Ok(project) + Ok((project, named)) +} + +/// [`project_in_within`] for a package of the user's own. +#[cfg(test)] +pub(crate) fn project_in(text: &str, dir: &Path) -> Result { + project_in_within(text, dir, crate::render::rustgis_tiles::address::Reach::Local).map(|(p, _)| p) } /// Removes the offline areas past the first `had` of this project: those a field package just made, diff --git a/crates/engine/src/cmd/geolibre.rs b/crates/engine/src/cmd/geolibre.rs index 28034852c3..b4aab8d822 100644 --- a/crates/engine/src/cmd/geolibre.rs +++ b/crates/engine/src/cmd/geolibre.rs @@ -1,5 +1,6 @@ //! Opens a GeoLibre project as a new map, resolving sources through existing commands. use super::ps; +use crate::render::rustgis_tiles::address::Reach; use crate::{CmdResult, CommandSpec as C, Session}; use rustgis_map::geolibre::{self, Report, array, boolean, number, string}; use serde_json::{Value, json}; @@ -11,9 +12,14 @@ pub fn commands() -> Vec { )] } -/// Reads at most 64 MiB, before decoding or parsing hostile project data. -fn project_text(p: &Value) -> Result { +/// Reads at most 64 MiB, before decoding or parsing hostile project data. Returns the text and, +/// for one downloaded from `url`, the reach it was read at. +fn project_text(p: &Value) -> Result<(String, Option), String> { use std::io::Read; + #[cfg(not(target_arch = "wasm32"))] + let mut read_at = None; + #[cfg(target_arch = "wasm32")] + let read_at = None; let bytes = if let Some(data) = ps(p, "data") { if data.len() > geolibre::MAX_TEXT / 3 * 4 + 4 { return Err("GeoLibre data exceeds 64 MiB".into()); @@ -24,14 +30,25 @@ fn project_text(p: &Value) -> Result { if text.len() > geolibre::MAX_TEXT { return Err("GeoLibre text exceeds 64 MiB".into()); } - return Ok(text.into()); + return Ok((text.into(), None)); } else if let Some(url) = ps(p, "url") { if !rustgis_map::tiles::is_web(url) { return Err("url must be http:// or https://".into()); } #[cfg(not(target_arch = "wasm32"))] { - crate::render::rustgis_tiles::cache::download_blocking_limited(&geolibre::download_url(url), geolibre::MAX_TEXT)? + use crate::render::rustgis_tiles::cache; + let url = geolibre::download_url(url); + let fetched = cache::download_blocking_with_origin_within( + &url, + geolibre::MAX_TEXT, + cache::BLOCKING_TIMEOUT, + &[], + cache::ceiling_for(&url), + ) + .map_err(cache::large_file_hint)?; + read_at = Some(fetched.origin.reach()); + fetched.bytes } #[cfg(target_arch = "wasm32")] { @@ -51,7 +68,8 @@ fn project_text(p: &Value) -> Result { if bytes.len() > geolibre::MAX_TEXT { return Err("GeoLibre project exceeds 64 MiB".into()); } - String::from_utf8(bytes).map_err(|_| "GeoLibre project must be UTF-8 JSON".into()) + let text = String::from_utf8(bytes).map_err(|_| "GeoLibre project must be UTF-8 JSON".to_string())?; + Ok((text, read_at)) } /// Parses before mutating the session; an unreadable layer is noted and the others continue. @@ -68,9 +86,15 @@ fn import_project(s: &mut Session, p: &Value) -> CmdResult { } return s.request_import_url(&q); } - let text = project_text(p)?; + let (text, read_at) = project_text(p)?; let mut report = Report::default(); let project = geolibre::read_project(&text, &mut report)?; + // What it names reaches no wider than where it came from ([`Session::file_reach`]): held + // before any of it is read. + let reach = read_at.map_or_else(|| s.file_reach(p), |read| s.file_reach(p).min(read)); + let held = reach == Reach::Public; + let addresses = std::iter::once(project.basemap.as_str()).chain(project.layers.iter().map(source_address)); + let named = crate::received::hold(addresses, reach); if cfg!(target_arch = "wasm32") || s.leave_downloads { ensure_download_capacity(s, &project.layers, cfg!(target_arch = "wasm32"))?; } @@ -112,7 +136,7 @@ fn import_project(s: &mut Session, p: &Value) -> CmdResult { let requests = s.url_requests.len(); let folder = group_look(&group_index, string(record, "groupId")); let mut layer_report = Report::default(); - let completed = match add_layer(s, record, dir.as_deref(), &mut layer_report, folder) { + let completed = match add_layer(s, record, dir.as_deref(), &mut layer_report, folder, held) { Ok(Added::Feature(id)) => { added.push(name.to_string()); order.push(id); @@ -169,6 +193,7 @@ fn import_project(s: &mut Session, p: &Value) -> CmdResult { s.map_mut().camera = project.camera; s.map_mut().bookmarks = project.bookmarks; let skipped = project.layers.len().saturating_sub(added.len()); + named.say(s, &format!("the GeoLibre project '{}'", project.name)); s.notify( format!( "Imported {} of {} GeoLibre layers; {} drawn differently, {skipped} left out (see the import's notes)", @@ -257,7 +282,10 @@ enum Added { /// Adds data or tiles, retaining the original layer's presentation. Tile layers have their own /// order in RustGIS, so mixing them with features is explicitly reported. -fn add_layer(s: &mut Session, r: &Value, dir: Option<&str>, report: &mut Report, folder: (bool, f64)) -> Result { +/// `held`: what the project names reaches only the internet, as a document read from there +/// ([`crate::received::hold`] recorded its addresses so), and a URL layer is added as one such a +/// document names. +fn add_layer(s: &mut Session, r: &Value, dir: Option<&str>, report: &mut Report, folder: (bool, f64), held: bool) -> Result { #[cfg(not(target_arch = "wasm32"))] let _ = folder; let name = string(r, "name"); @@ -307,7 +335,11 @@ fn add_layer(s: &mut Session, r: &Value, dir: Option<&str>, report: &mut Report, let mut saved = r.clone(); saved["visible"] = json!(boolean(r, "visible", true) && folder.0); saved["opacity"] = json!(number(r, "opacity", 1.0).clamp(0.0, 1.0) * folder.1); - s.request_import_url(&json!({"url":address,"whole":true,"name":name,"geolibreLayer":{"token":token,"record":saved}}))?; + let mut q = json!({"url":address,"whole":true,"name":name,"geolibreLayer":{"token":token,"record":saved}}); + if held { + q["fromDocument"] = json!(true); + } + s.request_import_url(&q)?; report.approximated(name, "MBTiles archive is downloading; wait before saving"); } report.approximated(name, "tile overlays draw above feature layers; tile vector styling uses RustGIS defaults"); @@ -379,6 +411,11 @@ fn add_layer(s: &mut Session, r: &Value, dir: Option<&str>, report: &mut Report, } } q["geolibreLayer"] = json!({"token":token,"record":r}); + // Added, when it lands, as an address a document read from the internet named: never + // taken as the user's own, which would lift the hold. + if held { + q["fromDocument"] = json!(true); + } s.request_import_url(&q)?; report.approximated(name, "URL data is downloading; its saved style is applied when the download completes"); return Ok(Added::Feature(id)); @@ -394,6 +431,11 @@ fn add_layer(s: &mut Session, r: &Value, dir: Option<&str>, report: &mut Report, } s.run_part("layer.addZarr", &q)? } else { + // Added as an address a document read from the internet named: never taken as the + // user's own, which would lift the hold. + if remote && held { + q["fromDocument"] = json!(true); + } s.run_part(if remote { "layer.addUrl" } else { "layer.addData" }, &q)? } }; diff --git a/crates/engine/src/cmd/items.rs b/crates/engine/src/cmd/items.rs index 45ce47278f..9ead1b0e09 100644 --- a/crates/engine/src/cmd/items.rs +++ b/crates/engine/src/cmd/items.rs @@ -75,7 +75,8 @@ pub fn commands() -> Vec { .params(r#"{"layer"?, "path": "*.rgislyr"}"#), C::new("layer.addLayerFile", "Add Layer File", "Home › Add", |s, p| { let text = read_text(p)?; - super::layer::add_layer_text(s, &text) + let reach = s.file_reach(p); + super::layer::add_layer_text_within(s, &text, reach) }).roles(&[]).effects(crate::policy::Effects::NONE.with(crate::policy::Effect::Files)) .params(r#"{"path"?: "*.rgislyr", "text"?: layer file JSON, "data"?: base64 file}"#), // Styles. @@ -225,7 +226,9 @@ pub fn commands() -> Vec { let name = super::within("name", "a project's name", name, 200)?; let text = read_text(p)?; super::connections::clear_active(); - let mut proj = match Project::from_import_json(&text, None) { + // What it names is held within this as it is read, before anything it names is read. + let reach = s.file_reach(p); + let (mut proj, named) = match Project::from_import_json_within(&text, None, reach) { Ok(proj) => proj, Err(error) => { super::connections::restore_active(s); @@ -234,6 +237,7 @@ pub fn commands() -> Vec { }; proj.name = name; super::project::reset_to(s, proj); + named.say(s, "the template"); s.path = None; super::connections::resolve_project(s); super::connections::note_waiting(s); @@ -526,7 +530,10 @@ fn import_maps(s: &mut Session, p: &Value) -> CmdResult { crate::project::check_format(&text, "map file, project or package")?; let dir = ps(p, "path").and_then(|path| std::path::absolute(path).ok()).and_then(|p| p.parent().map(Path::to_path_buf)); super::connections::clear_active(); - let maps: Vec = match serde_json::from_str::(&text) { + // What they name is held within this before anything they name is read: a map file's before + // its maps are added, a project's as it is read. + let reach = s.file_reach(p); + let (maps, named): (Vec, _) = match serde_json::from_str::(&text) { Ok(mut m) => { if crate::project::ensure_map_imports_complete(&m).is_err() { super::connections::restore_active(s); @@ -544,10 +551,11 @@ fn import_maps(s: &mut Session, p: &Value) -> CmdResult { for notice in crate::project::picture_notices(&m.layers, []) { s.notify_text(notice, false); } - vec![m] + let named = crate::received::hold(m.addresses_mut(), reach); + (vec![m], named) } - Err(_) => match Project::from_import_maps_json(&text, dir.as_deref(), MAX_IMPORTED_MAPS) { - Ok(mut project) => { + Err(_) => match Project::from_import_maps_json_within(&text, dir.as_deref(), MAX_IMPORTED_MAPS, reach) { + Ok((mut project, named)) => { let parts = [crate::project::ReadPart::Labels, crate::project::ReadPart::Diagrams, crate::project::ReadPart::Maps]; for notice in project.take_read_notices(&parts) { s.notify_text(notice, false); @@ -557,7 +565,7 @@ fn import_maps(s: &mut Session, p: &Value) -> CmdResult { for (_, notice) in crate::project::label_losses::hidden(imported) { s.notify(notice, false); } - project.maps + (project.maps, named) } Err(error) => { super::connections::restore_active(s); @@ -565,6 +573,7 @@ fn import_maps(s: &mut Session, p: &Value) -> CmdResult { } }, }; + named.say(s, "the map file"); let mut names = Vec::new(); let first_map = s.project.maps.len(); let mut detached_offline = 0; @@ -706,11 +715,13 @@ fn import_styles(s: &mut Session, p: &Value) -> CmdResult { } m.layers } else { - // A project parse opens sources even though this import only takes their styles. + // A project parse opens sources even though this import only takes their styles: held + // within where the file came from first ([`Session::file_reach`]). super::connections::clear_active(); - let project = Project::from_import_json(&text, None); + let project = Project::from_import_json_within(&text, None, s.file_reach(p)); super::connections::restore_active(s); - let mut project = project.map_err(|e| not_a(e, "layer file, map file or project"))?; + let (mut project, named) = project.map_err(|e| not_a(e, "layer file, map file or project"))?; + named.say(s, "the style file"); // Styles take the layers' renderers and labels, not their diagrams or the layouts. for notice in project.take_read_notices(&[crate::project::ReadPart::Labels]) { s.notify_text(notice, false); diff --git a/crates/engine/src/cmd/layer.rs b/crates/engine/src/cmd/layer.rs index 7c51753a1d..30df5bdab5 100644 --- a/crates/engine/src/cmd/layer.rs +++ b/crates/engine/src/cmd/layer.rs @@ -4669,8 +4669,15 @@ fn add_layer_file(s: &mut Session, path: &str) -> CmdResult { add_layer_text(s, &text) } -/// Adds a layer from a layer file's JSON. +/// Adds a layer from a layer file's JSON, read from the user's own disk or given by the user. pub(crate) fn add_layer_text(s: &mut Session, text: &str) -> CmdResult { + let reach = s.file_reach(&Value::Null); + add_layer_text_within(s, text, reach) +} + +/// [`add_layer_text`] for a layer file whose addresses reach no wider than `reach` +/// ([`Session::file_reach`]). +pub(crate) fn add_layer_text_within(s: &mut Session, text: &str, reach: crate::render::rustgis_tiles::address::Reach) -> CmdResult { crate::project::check_format(text, "layer file")?; let mut layer: rustgis_map::Layer = serde_json::from_str(text).map_err(|e| format!("not a RustGIS layer file: {e}"))?; if layer.dataset.source.as_deref().is_some_and(|source| source.starts_with("geolibre-pending:")) { @@ -4685,6 +4692,9 @@ pub(crate) fn add_layer_text(s: &mut Session, text: &str) -> CmdResult { // A binding in a file is no authority to use a login here. crate::s3_connections::clear_bindings(layer.addresses_mut()); crate::project::clear_login_bindings(layer.addresses_mut()); + // Before anything it names is read (the repair below reads it). + let named = crate::received::hold(layer.addresses_mut(), reach); + named.say(s, &format!("the layer file '{}'", layer.name)); // A fresh id and a unique name in this map; the rest goes through project repair. let base = layer.name.clone(); let mut i = 1; @@ -6870,12 +6880,21 @@ fn add_download(s: &mut Session, p: &Value) -> CmdResult { let bounds = if service { super::service::bounds_of(p.get("bounds"))? } else { None }; let i = s.downloaded.iter().position(|(d, _)| *d == id).ok_or("no such download (it was dropped when another project opened)")?; let (_, bytes) = s.downloaded.remove(i); + let read_at = s.downloaded_reach.iter().position(|(d, _)| *d == id).map(|i| s.downloaded_reach.remove(i).1); if p.get("geolibreProject").and_then(Value::as_bool) == Some(true) { if bytes.len() > rustgis_map::geolibre::MAX_TEXT { return Err("GeoLibre project exceeds 64 MiB".into()); } let text = String::from_utf8(bytes).map_err(|_| "GeoLibre project must be UTF-8 JSON")?; - return s.run_part("project.importGeolibre", &json!({"text":text})); + // Received from where it was read: what it names reaches no wider ([`Session::file_reach`]). + // The app says where its download connected ([`Session::download_read_at`]; the browser's + // fetch, by its address's name); one that doesn't say reaches only the internet. + use crate::render::rustgis_tiles::{address::Reach, cache}; + let reach = read_at.unwrap_or(Reach::Public).min(cache::ceiling_for(&url)); + let was = s.receiving(Some(reach)); + let r = s.run_part("project.importGeolibre", &json!({"text":text})); + s.receiving(was); + return r; } if p.get("geolibreLayer").is_some() { let name = if b(p, "geolibreZarr") == Some(true) { "zarr.tif".into() } else { url_file_name(&url, &bytes)? }; diff --git a/crates/engine/src/cmd/project.rs b/crates/engine/src/cmd/project.rs index 42513025d6..2eb42d30ed 100644 --- a/crates/engine/src/cmd/project.rs +++ b/crates/engine/src/cmd/project.rs @@ -663,20 +663,25 @@ fn open(s: &mut Session, p: &Value) -> CmdResult { let origin = if is_package { path.canonicalize() } else { std::path::absolute(&path) } .map_err(|error| format!("{}: {error}", path.display()))?; super::connections::clear_active(); + // What it names is held within this as it is read, before anything it names is read. + let reach = s.file_reach(p); let proj = (|| -> Result<_, String> { if is_field { let bytes = crate::project::read_file(&path, MAX_PACKAGE)?; let stem = path.file_stem().map(|s| s.to_string_lossy().into_owned()).unwrap_or_default(); let (dir, text, notes) = super::field::unpack(&bytes, &stem)?; - Ok((super::field::project_in(&text, &dir)?, notes)) + let (proj, named) = super::field::project_in_within(&text, &dir, reach)?; + Ok((proj, named, notes)) } else if is_package { let bytes = crate::project::read_file(&path, MAX_PACKAGE)?; - Ok((Project::from_import_json(&super::items::package_text(&bytes)?, None)?, Vec::new())) + let (proj, named) = Project::from_import_json_within(&super::items::package_text(&bytes)?, None, reach)?; + Ok((proj, named, Vec::new())) } else { - Ok((Project::load(&path)?, Vec::new())) + let (proj, named) = Project::load_within(&path, Some(reach))?; + Ok((proj, named, Vec::new())) } })(); - let (proj, notes) = match proj { + let (proj, named, notes) = match proj { Ok(proj) => proj, Err(error) => { super::connections::restore_active(s); @@ -709,6 +714,7 @@ fn open(s: &mut Session, p: &Value) -> CmdResult { s.path = Some(origin); } s.notify(format!("Opened {}", s.project.name), false); + named.say(s, &format!("the project '{}'", s.project.name)); for note in notes { s.warn(note); } @@ -747,8 +753,10 @@ fn open_text(s: &mut Session, p: &Value) -> CmdResult { let text = super::ps(p, "text").ok_or("text is required")?; let package = super::b(p, "package").unwrap_or(false); super::connections::clear_active(); - let proj = if package { Project::from_import_json(text, None) } else { Project::from_json(text) }; - let proj = match proj { + // What it names is held within this as it is read, before anything it names is read. + let reach = s.file_reach(p); + let proj = if package { Project::from_import_json_within(text, None, reach) } else { Project::from_json_within(text, reach) }; + let (proj, named) = match proj { Ok(proj) => proj, Err(error) => { super::connections::restore_active(s); @@ -764,6 +772,7 @@ fn open_text(s: &mut Session, p: &Value) -> CmdResult { } s.path = None; s.notify(format!("Opened {}", s.project.name), false); + named.say(s, &format!("the project '{}'", s.project.name)); super::connections::resolve_project(s); super::connections::note_waiting(s); Ok(Value::Null) diff --git a/crates/engine/src/cmd/zarr.rs b/crates/engine/src/cmd/zarr.rs index f9403c4874..071596b8fe 100644 --- a/crates/engine/src/cmd/zarr.rs +++ b/crates/engine/src/cmd/zarr.rs @@ -131,6 +131,13 @@ fn fetch_items(root: &str, keys: &[(String, String)]) -> Result<(HashMap Result<(HashMap { let len = b.len() as u64; @@ -240,6 +247,21 @@ mod transport_tests { assert_eq!(sends, 0); assert_eq!(listener.accept().unwrap_err().kind(), std::io::ErrorKind::WouldBlock); } + + /// The files of a store a document read from the internet named are fetched within the + /// store's hold, though the hold never saw their own addresses: one on this computer isn't + /// asked for. + #[test] + fn a_held_stores_files_are_held_too() { + use crate::render::rustgis_tiles::cache; + let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap(); + listener.set_nonblocking(true).unwrap(); + let root = format!("http://{}/held.zarr", listener.local_addr().unwrap()); + cache::restrict_to_public(&root); + let result = super::fetch(&root, &["zarr.json".into()]); + assert_eq!(listener.accept().map(|_| ()).unwrap_err().kind(), std::io::ErrorKind::WouldBlock, "a file of the store was asked for"); + assert!(result.is_err(), "{result:?}"); + } } /// Rounds of [`zarr::member_keys`] a store whose root lists no arrays is read in: the variable diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index dfabc65653..3ee1d93e93 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -31,6 +31,7 @@ pub use peer::Peer; pub(crate) use roles::{Document, ParamRole, Role}; mod parameters; pub mod project_log; +mod received; pub use parameters::{params_envelope, script_line, split_script_id}; pub use project_log::{LogCopy, log_identifier, log_params}; pub mod s3_connections; @@ -748,6 +749,7 @@ struct PutAside { plugin_runs: Vec, downloading: Vec, downloaded: Vec<(u64, Vec)>, + downloaded_reach: Vec<(u64, render::rustgis_tiles::address::Reach)>, url_requests: Vec, policy_work: policy::downloads::Work, landed_reads: Vec<(u64, LandedRead)>, @@ -1080,6 +1082,8 @@ pub struct Session { downloading: Vec, /// Downloads that landed, waiting for `layer.addDownload`. pub(crate) downloaded: Vec<(u64, Vec)>, + /// Where downloads connected, as the front end saw it ([`Session::download_read_at`]). + pub(crate) downloaded_reach: Vec<(u64, render::rustgis_tiles::address::Reach)>, /// Downloads that landed already read (an ArcGIS layer's protocol buffer pages, joined), /// waiting for `layer.addDownload` too. pub(crate) landed_reads: Vec<(u64, LandedRead)>, @@ -1106,6 +1110,10 @@ pub struct Session { /// Set by [`Session::run_leaving_downloads`]: `layer.addUrl` leaves what it would wait for /// to the front end ([`Session::request_url`]), as in the browser. leave_downloads: bool, + /// Set by [`Session::receiving`]: the files the commands run now open were downloaded from an + /// address reached at this reach, which what they name is held within + /// ([`Session::file_reach`]). + received: Option, /// Set by [`prefs::opt_in`]: the command line and Python read the remembered Earthdata token /// for a command that names a data host, before it binds its accounts. saved_secrets_opted_in: bool, @@ -1552,6 +1560,7 @@ impl Session { plugin_watch: Default::default(), downloading: Vec::new(), downloaded: Vec::new(), + downloaded_reach: Vec::new(), landed_reads: Vec::new(), #[cfg(not(target_arch = "wasm32"))] landed_windows: Vec::new(), @@ -1565,6 +1574,7 @@ impl Session { request_only: false, shared_steps: StepTally::default(), leave_downloads: false, + received: None, saved_secrets_opted_in: false, plugin_retries: Vec::new(), url_waits: cmd::plugins::fetch::UrlWaits::default(), @@ -1652,6 +1662,20 @@ impl Session { landed } + /// Says where a download under way connected (`cache::Fetched::origin`), before its bytes are + /// handed over: a GeoLibre project downloaded so is read within that reach + /// (`layer.addDownload`), and one handed over without it reaches only the internet. + pub fn download_read_at(&mut self, id: u64, reach: render::rustgis_tiles::address::Reach) { + if !self.downloading.contains(&id) { + return; + } + // As many as downloads under way can be: past that, the oldest are forgotten. + if self.downloaded_reach.len() >= 64 { + self.downloaded_reach.remove(0); + } + self.downloaded_reach.push((id, reach)); + } + /// Hands over a download read already (an ArcGIS layer's protocol buffer pages, joined, see /// [`ogc::Step::Decoded`](rustgis_data::ogc::Step::Decoded)), for `layer.addDownload {"id"}` /// as [`Session::download_landed`] does. @@ -2613,6 +2637,7 @@ impl Session { plugin_runs: take(&mut self.plugin_runs), downloading: take(&mut self.downloading), downloaded: take(&mut self.downloaded), + downloaded_reach: take(&mut self.downloaded_reach), landed_reads: take(&mut self.landed_reads), #[cfg(not(target_arch = "wasm32"))] landed_windows: take(&mut self.landed_windows), @@ -2671,6 +2696,7 @@ impl Session { plugin_runs, downloading, downloaded, + downloaded_reach, landed_reads, #[cfg(not(target_arch = "wasm32"))] landed_windows, @@ -2703,6 +2729,7 @@ impl Session { (self.pending, self.plugin_runs, self.plugin_retries, self.url_waits) = (pending, plugin_runs, plugin_retries, url_waits); self.file_outputs = file_outputs; (self.downloading, self.downloaded, self.url_requests) = (downloading, downloaded, url_requests); + self.downloaded_reach = downloaded_reach; self.restore_policy_work(policy_work); self.landed_reads = landed_reads; #[cfg(not(target_arch = "wasm32"))] diff --git a/crates/engine/src/project.rs b/crates/engine/src/project.rs index 136a9b3129..d35c868578 100644 --- a/crates/engine/src/project.rs +++ b/crates/engine/src/project.rs @@ -7,6 +7,8 @@ use rustgis_map::Map; use serde::{Deserialize, Serialize}; use crate::GpRecord; +use crate::received::Named; +use crate::render::rustgis_tiles::address::Reach; #[path = "project_capabilities.rs"] mod capabilities; @@ -1905,28 +1907,69 @@ impl Project { /// Reads a project from its JSON text (a browser upload). pub fn from_json(text: &str) -> Result { - Self::read_json(text, true, None, true, None) + Self::read_json(text, true, None, true, None, None).map(|(p, _)| p) + } + + /// [`Project::from_json`] for a file whose addresses reach no wider than `reach` + /// ([`crate::Session::file_reach`]), held so before anything it names is read. + pub(crate) fn from_json_within(text: &str, reach: Reach) -> Result<(Project, Named), String> { + Self::read_json(text, true, None, true, None, Some(reach)) } /// Reads imported JSON (including package contents) without restoring a saved file's secrets. + /// A command reads through [`Project::from_import_json_within`], which holds what it names. + #[cfg(test)] pub(crate) fn from_import_json(text: &str, dir: Option<&Path>) -> Result { - Self::read_json(text, false, dir, true, None) + Self::read_json(text, false, dir, true, None, None).map(|(p, _)| p) + } + + /// Whether imported JSON reads as a project, refused as [`Project::from_import_json`] refuses + /// it, without its repair: nothing it names is read. + pub(crate) fn check_import_json(text: &str, dir: Option<&Path>) -> Result<(), String> { + Self::read_json(text, false, dir, false, None, None).map(|_| ()) + } + + /// [`Project::from_import_json`] within `reach`, as [`Project::from_json_within`]. + pub(crate) fn from_import_json_within(text: &str, dir: Option<&Path>, reach: Reach) -> Result<(Project, Named), String> { + Self::read_json(text, false, dir, true, None, Some(reach)) } /// Repairs only the maps the import will retain, so excluded maps produce no notices. + #[cfg(test)] pub(crate) fn from_import_maps_json(text: &str, dir: Option<&Path>, limit: usize) -> Result { - Self::read_json(text, false, dir, true, Some(limit)) + Self::read_json(text, false, dir, true, Some(limit), None).map(|(p, _)| p) + } + + /// Repairs only the maps the import will retain, so excluded maps produce no notices, holding + /// their addresses within `reach`, as [`Project::from_json_within`]. + pub(crate) fn from_import_maps_json_within( + text: &str, + dir: Option<&Path>, + limit: usize, + reach: Reach, + ) -> Result<(Project, Named), String> { + Self::read_json(text, false, dir, true, Some(limit), Some(reach)) } /// Peer census must precede normalization: duplicate ids cannot become proof of a unique /// matching slot after the normalizer renumbers or drops them. Saved-text restore is absent. pub(crate) fn from_peer_raw(text: &str) -> Result { - Self::read_json(text, false, None, false, None) + Self::read_json(text, false, None, false, None, None).map(|(p, _)| p) } /// Validates compatibility before typed decoding. Saved files may restore exact fields; /// peer input stays unnormalized until its slot census has rejected ambiguous identities. - fn read_json(text: &str, restore: bool, dir: Option<&Path>, normalize: bool, map_limit: Option) -> Result { + /// With `held`, every address the project keeps is held within that reach + /// ([`crate::received::hold`]) before its repair reads anything it names (rasters read in + /// place, streamed sources). + fn read_json( + text: &str, + restore: bool, + dir: Option<&Path>, + normalize: bool, + map_limit: Option, + held: Option, + ) -> Result<(Project, Named), String> { check_format(text, "project")?; let refused = |e: serde_json::Error| { let msg = e.to_string(); @@ -1982,6 +2025,7 @@ impl Project { if let Some(limit) = map_limit { p.maps.truncate(limit); } + let named = held.map(|reach| crate::received::hold(p.addresses_mut(), reach)).unwrap_or_default(); // Maps imported from a project are read as it opens, and said as imported. let repair_notices = match (normalize, map_limit) { (false, _) => Vec::new(), @@ -2053,12 +2097,18 @@ impl Project { )); } p.read_notices.extend(unknown.notices(map_limit)); - Ok(p) + Ok((p, named)) } /// Opens a project file (a regular file within [`max_bytes`]; see `read_file`), resolving /// its relative paths against its folder. pub fn load(path: &Path) -> Result { + Self::load_within(path, None).map(|(p, _)| p) + } + + /// [`Project::load`], holding what the file names within `held`, as + /// [`Project::from_json_within`]. + pub(crate) fn load_within(path: &Path, held: Option) -> Result<(Project, Named), String> { let max = max_bytes(); // Past the limit: said with its size and the limit here, before anything is read. if let Ok(meta) = std::fs::metadata(path) @@ -2089,7 +2139,7 @@ impl Project { let bytes = read_file(path, max)?; let text = String::from_utf8(bytes).map_err(|_| format!("{} isn't a RustGIS project", path.display()))?; let dir = std::path::absolute(path).ok().and_then(|p| p.parent().map(Path::to_path_buf)); - Self::read_json(&text, true, dir.as_deref(), true, None) + Self::read_json(&text, true, dir.as_deref(), true, None, held) } } diff --git a/crates/engine/src/received.rs b/crates/engine/src/received.rs new file mode 100644 index 0000000000..7c6a69a279 --- /dev/null +++ b/crates/engine/src/received.rs @@ -0,0 +1,534 @@ +//! What the addresses a file names may reach, by where the file came from. +//! +//! A project, map file, layer file, template or package the user opens from their own disk is +//! theirs: what it names reaches as far as the user's own addresses do. One that arrived from the +//! internet (opened by its web address, a GeoLibre project downloaded, or file text the Assistant, +//! MCP or a plugin supplied, which says nothing trustworthy about where it was read) is a document +//! read from the internet, and what it names reaches only the internet, as what any other such +//! document names does ([`cache::restrict_to_public`]). Either way, the addresses it names on this +//! computer or the local network are said as it opens. + +use crate::Session; +use crate::render::rustgis_tiles::{address, address::Reach, cache, logins}; +use serde_json::Value; +use std::collections::HashSet; + +/// How many addresses a notice names; the count covers them all. +const NAMED: usize = 3; + +impl Session { + /// The widest reach what a file being read names may have (`p`: the command's parameters). + /// A file downloaded by its web address is read within the reach it was read at + /// ([`Session::receiving`]); file text or data supplied by anything but the user (the + /// Assistant, MCP, a plugin) within the internet; a file read from a path, or given by the user, + /// within this computer and the local network, as before. That includes a path an attached + /// agent opens, even one it wrote: what the file names reaches no further than the agent's own + /// approved commands do already (its `layer.addUrl` of a local server reads from there). + pub(crate) fn file_reach(&self, p: &Value) -> Reach { + let supplied = ["text", "data"].iter().any(|k| p.get(k).is_some_and(Value::is_string)); + let given = if supplied && !self.policy_user() { Reach::Public } else { Reach::Local }; + self.received.map_or(given, |read| given.min(read.min(Reach::Local))) + } + + /// Reads the files the commands run next open as downloaded from an address reached at + /// `reach` (the app's open by web address: `Reach::Public` when the download came from the + /// internet), until it is called again with `None`. Returns what it replaced, for the caller + /// to put back. + pub fn receiving(&mut self, reach: Option) -> Option { + std::mem::replace(&mut self.received, reach) + } +} + +/// What a file names on this computer or the local network, gathered as it is read +/// ([`hold`]), for [`Named::say`]. +#[derive(Debug, Default)] +#[must_use = "say what the file names"] +pub(crate) struct Named { + /// The distinct addresses named there that are read from there. + read: Few, + /// The distinct addresses named there that are held to the internet: all of them when the file + /// arrived from there, else those something received from there named first. + held: Few, + /// Whether the file arrived from the internet. + received: bool, + /// Every distinct address counted, so each counts once however often the file names it. + seen: HashSet, +} + +/// How many addresses there are, and the first few, for a notice. +#[derive(Debug, Default)] +struct Few { + first: Vec, + count: usize, +} + +impl Few { + fn add(&mut self, a: &str) { + if self.first.len() < NAMED { + self.first.push(a.to_string()); + } + self.count += 1; + } + + /// The first few as a notice shows them, and how many more. + fn shown(&self) -> String { + let mut shown: Vec = self.first.iter().map(|a| crate::sources::address_in_message(a)).collect(); + if self.count > NAMED { + shown.push(format!("and {} more", self.count - NAMED)); + } + shown.join(", ") + } +} + +/// What an address a file names is fetched from. +enum Fetched { + /// This web address, whatever wraps it: a tile template (`pmtiles:`, `cog:`), an anonymous + /// read, a saved S3 connection or a login. + Web(String), + /// An S3 address whose destination can't be told: held all the same, though not counted. + Unknown, + /// Not the web (a file, a database). + Not, +} + +fn fetched_from(a: &str) -> Fetched { + use crate::render::rustgis_tiles::s3; + let archive = crate::sources::template_archive(a).map_or(a, |(_, archive)| archive); + let (plain, _) = s3::split_anonymous(archive); + let web = match s3::bound_destination(plain) { + Ok(Some(destination)) => destination, + Ok(None) if s3::is_s3(plain) => match s3::https_url(plain) { + Ok(web) => web, + Err(_) => return Fetched::Unknown, + }, + Ok(None) => logins::inner(plain).to_string(), + Err(_) => return Fetched::Unknown, + }; + if rustgis_map::tiles::is_web(&web) { Fetched::Web(web) } else { Fetched::Not } +} + +/// Holds every web address a file names (`addresses`, its whole list as login bindings are cleared +/// from it) within `reach`, before anything it names is read: within the internet, each is +/// recorded so ([`cache::restrict_to_public`]), with a Shapefile's parts, so it is fetched only +/// from there, however its name resolves; an address inside a tile template or a wrapper is held +/// by what it is fetched from. Within the local network, nothing is recorded, and the addresses +/// reach as before. Returns what the file names on this computer or the local network. +pub(crate) fn hold(addresses: impl IntoIterator>, reach: Reach) -> Named { + let received = reach == Reach::Public; + let mut named = Named { received, ..Named::default() }; + // Recorded together: the cache forgets their earlier reads in one pass, not one per address. + let mut held = Vec::new(); + for a in addresses { + let a = a.as_ref(); + let web = match fetched_from(a) { + Fetched::Web(web) => Some(web), + Fetched::Unknown => None, + Fetched::Not => continue, + }; + if received { + held.push(a.to_string()); + held.extend(rustgis_data::io::shapefile_part_urls(a).unwrap_or_default().into_iter().map(|(_, part)| part)); + } + // Only what can be read there: a forbidden address (link-local, a cloud's metadata) never is. + if web.is_some_and(|web| address::reach(&web) == Reach::Local) && named.seen.insert(a.to_string()) { + if received || cache::ceiling_for(a) == Reach::Public { + named.held.add(a); + } else { + named.read.add(a); + } + } + } + cache::restrict_all_to_public(held.iter().map(String::as_str)); + named +} + +impl Named { + /// Says, once, what `what` (a project, a map file, a layer file) names on this computer or the + /// local network, with how many and the first few: held to the internet, or read from there as + /// the user's own, and which of those stay held because something received from the internet + /// named them first. (Filling the record of held addresses is said after the command, as any + /// way of filling it is: `Session::say_public_only_full`.) + pub(crate) fn say(self, s: &mut Session, what: &str) { + let (read, held) = (self.read.count, self.held.count); + let kept = "stay held to the internet, as something received from the internet named them first, and aren't read"; + let said = match (self.received, read, held) { + (_, 0, 0) => None, + (true, _, _) => Some(format!( + "{what} came from the internet, so the {held} address(es) it names on this computer or the local network are held to the internet and aren't read: {}", + self.held.shown() + )), + (false, _, 0) => { + Some(format!("{what} reads from {read} address(es) on this computer or the local network: {}", self.read.shown())) + } + (false, 0, _) => { + Some(format!("{what} names {held} address(es) on this computer or the local network that {kept}: {}", self.held.shown())) + } + (false, _, _) => Some(format!( + "{what} reads from {read} address(es) on this computer or the local network: {}. {held} more it names there {kept}: {}", + self.read.shown(), + self.held.shown() + )), + }; + if let Some(said) = said { + s.notify(said, false); + } + } +} + +#[cfg(all(test, not(target_arch = "wasm32")))] +#[expect( + clippy::unwrap_used, + clippy::panic, + reason = "a test module gated on more than `test`, which clippy's allow-unwrap-in-tests does not see" +)] +mod tests { + use super::*; + use crate::Project; + use crate::policy::{AgentAccess, Call, Effects, Outcome, Revocation, Scope}; + use serde_json::json; + + /// Authority that is never revoked, for running a command as an agent would. + struct Live; + impl Revocation for Live { + fn allows(&self, _: Effects) -> bool { + true + } + } + + /// Runs `id` as an attached agent (MCP) with full access does, approved. (The Assistant + /// refuses to run these documents at all.) + fn as_agent(s: &mut Session, id: &str, p: &Value) -> crate::CmdResult { + let scope = Scope::agent(AgentAccess::Full, false, "mcp", None, std::sync::Arc::new(Live)); + let call = Call::command(id, p.clone()); + match s.review(&scope, &call) { + Outcome::NeedsApproval(permit) => s.run_permitted(scope, permit.allow(), &call), + Outcome::Allowed => s.run_scoped(scope, &call), + Outcome::Refused(e) => panic!("{id} refused: {e}"), + } + } + + /// A project naming a tile server on this computer, a layer's source on the local network and + /// a tile server on the internet (hosts unique to `tag`, so tests running together don't share + /// a record), with those three addresses. + fn project(tag: &str) -> (Session, [String; 3]) { + let local = format!("http://localhost:18080/{tag}/{{z}}/{{x}}/{{y}}.png"); + let lan = format!("http://192.168.1.10/{tag}/roads.fgb"); + let public = format!("https://{tag}.example/tiles/{{z}}/{{x}}/{{y}}.png"); + let mut s = Session::new(Project::default()); + s.project.name = tag.into(); + s.run("map.addTiles", &json!({"url": local, "name": "Mine"})).unwrap(); + s.run("map.addTiles", &json!({"url": public, "name": "Theirs"})).unwrap(); + let roads = r#"{"type":"FeatureCollection","features":[{"type":"Feature","properties":{"n":1},"geometry":{"type":"Point","coordinates":[8.5,47.4]}}]}"#; + s.run("layer.addDataText", &json!({"fileName": "roads.geojson", "text": roads})).unwrap(); + let id = s.map().layers.last().map(|l| l.id).unwrap(); + s.map_mut().layer_mut(id).unwrap().dataset.source = Some(lan.clone()); + (s, [local, lan, public]) + } + + /// The reach each address has now, after the record of them is put back as a new process has + /// it (the user's own: [`cache::allow_named`]) before `open` runs. + fn reach_after(addresses: &[String; 3], open: impl FnOnce()) -> [Reach; 3] { + for a in addresses { + cache::allow_named(a); + } + open(); + [0, 1, 2].map(|i| cache::ceiling_for(&addresses[i])) + } + + /// The notices that say what a file names on this computer or the local network. + fn said(s: &Session) -> Vec { + s.notices.iter().filter(|n| n.text.contains("on this computer or the local network")).map(|n| n.text.clone()).collect() + } + + /// A project opened from the user's own disk, or given by the user, reads its servers on this + /// computer and the local network as before, and says so once, with how many and which. One + /// that names none says nothing. + #[test] + fn a_project_from_your_own_disk_keeps_its_local_servers_and_names_them() { + let (mut s, addresses) = project("own-disk-reach"); + let (text, _) = s.project.saved_text(None).unwrap(); + let dir = std::env::temp_dir().join(format!("rustgis-own-disk-reach-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + let path = dir.join("own.rgis"); + std::fs::write(&path, &text).unwrap(); + let mut opened = Session::new(Project::default()); + let reach = reach_after(&addresses, || { + opened.run("project.open", &json!({"path": path.display().to_string()})).unwrap(); + }); + assert_eq!(reach, [Reach::Local; 3], "opened from disk"); + let notices = said(&opened); + assert_eq!(notices.len(), 1, "{notices:?}"); + assert!(notices[0].starts_with("the project 'own' reads from 2 address(es)"), "{notices:?}"); + assert!(notices[0].contains("localhost:18080") && notices[0].contains("192.168.1.10"), "{notices:?}"); + let mut given = Session::new(Project::default()); + let reach = reach_after(&addresses, || { + given.run("project.openText", &json!({"text": text})).unwrap(); + }); + assert_eq!(reach, [Reach::Local; 3], "given by the user"); + assert_eq!(said(&given).len(), 1); + std::fs::remove_dir_all(dir).unwrap(); + // Nothing on this computer or the local network: nothing said. + let mut plain = Session::new(Project::default()); + plain.run("map.addTiles", &json!({"url": "https://own-disk-plain.example/{z}/{x}/{y}.png", "name": "Theirs"})).unwrap(); + let (text, _) = plain.project.saved_text(None).unwrap(); + let mut opened = Session::new(Project::default()); + opened.run("project.openText", &json!({"text": text})).unwrap(); + assert_eq!(said(&opened), Vec::::new()); + } + + /// A project received from the internet (downloaded from there, or given as text by an + /// attached agent) reaches only the internet: every address it names is held there, before any is + /// read, and the ones it names on this computer or the local network are said, once. One + /// downloaded from a server on the local network reads from there as the user's own. + #[test] + fn a_project_received_from_the_internet_reaches_only_the_internet() { + let (mut s, addresses) = project("received-reach"); + let (text, _) = s.project.saved_text(None).unwrap(); + let mut downloaded = Session::new(Project::default()); + let reach = reach_after(&addresses, || { + let was = downloaded.receiving(Some(Reach::Public)); + downloaded.run("project.openText", &json!({"text": text, "fileName": "shared.rgis"})).unwrap(); + downloaded.receiving(was); + }); + assert_eq!(reach, [Reach::Public; 3], "downloaded from the internet"); + let notices = said(&downloaded); + assert_eq!(notices.len(), 1, "{notices:?}"); + assert!(notices[0].starts_with("the project 'shared' came from the internet, so the 2 address(es)"), "{notices:?}"); + assert!(notices[0].contains("held to the internet"), "{notices:?}"); + assert_eq!(downloaded.received, None, "put back"); + let mut supplied = Session::new(Project::default()); + let reach = reach_after(&addresses, || { + as_agent(&mut supplied, "project.openText", &json!({"text": text})).unwrap(); + }); + assert_eq!(reach, [Reach::Public; 3], "given by an agent"); + let mut from_lan = Session::new(Project::default()); + let reach = reach_after(&addresses, || { + from_lan.receiving(Some(Reach::Local)); + from_lan.run("project.openText", &json!({"text": text})).unwrap(); + }); + assert_eq!(reach, [Reach::Local; 3], "downloaded from the local network"); + assert!(said(&from_lan)[0].contains("reads from 2 address(es)")); + } + + /// A map file, a layer file and a template given as text by an attached agent hold what they + /// name to the internet too; the same files given by the user don't. + #[test] + fn map_layer_and_template_files_an_agent_gives_reach_only_the_internet() { + let (mut s, addresses) = project("item-reach"); + let (template, _) = s.project.saved_text(None).unwrap(); + let map = String::from_utf8(crate::project::map_file_bytes(s.map()).unwrap()).unwrap(); + let layer = String::from_utf8(crate::project::layer_file_bytes(s.map().layers.last().unwrap()).unwrap()).unwrap(); + for (id, text, held) in [ + ("map.import", &map, [true, true, true]), + ("layer.addLayerFile", &layer, [false, true, false]), + ("project.fromTemplate", &template, [true, true, true]), + ] { + let p = json!({"text": text}); + let mut by_user = Session::new(Project::default()); + assert_eq!(reach_after(&addresses, || drop(by_user.run(id, &p).unwrap())), [Reach::Local; 3], "{id} by the user"); + assert_eq!(said(&by_user).len(), 1, "{id}"); + let mut supplied = Session::new(Project::default()); + let reach = reach_after(&addresses, || drop(as_agent(&mut supplied, id, &p).unwrap())); + assert_eq!(reach, held.map(|h| if h { Reach::Public } else { Reach::Local }), "{id} by an agent"); + let notices = said(&supplied); + assert_eq!(notices.len(), 1, "{id}: {notices:?}"); + assert!(notices[0].contains("came from the internet"), "{id}: {notices:?}"); + } + } + + /// A GeoLibre project an attached agent gives holds its background and layers to the internet + /// before any is read; the same project given by the user doesn't. + #[test] + fn a_geolibre_project_an_agent_gives_reaches_only_the_internet() { + let tiles = "http://localhost:18082/geolibre-reach/{z}/{x}/{y}.png".to_string(); + let style = "http://localhost:18083/geolibre-reach/style.json".to_string(); + let public = "https://geolibre-reach.example/{z}/{x}/{y}.png".to_string(); + let text = json!({ + "version": "0.2.0", + "name": "Received", + "mapView": {}, + "basemapStyleUrl": style, + "layers": [ + {"id": "a", "name": "Mine", "type": "xyz", "source": {"tiles": [tiles]}}, + {"id": "b", "name": "Theirs", "type": "xyz", "source": {"tiles": [public]}}, + ], + }) + .to_string(); + let addresses = [tiles, style, public]; + let p = json!({"text": text}); + let mut by_user = Session::new(Project::default()); + assert_eq!(reach_after(&addresses, || drop(by_user.run("project.importGeolibre", &p))), [Reach::Local; 3]); + assert!(said(&by_user).first().is_some_and(|n| n.contains("reads from 2 address(es)")), "{:?}", said(&by_user)); + let mut supplied = Session::new(Project::default()); + let reach = reach_after(&addresses, || drop(as_agent(&mut supplied, "project.importGeolibre", &p))); + assert_eq!(reach, [Reach::Public; 3]); + let notices = said(&supplied); + assert_eq!(notices.len(), 1, "{notices:?}"); + assert!(notices[0].starts_with("the GeoLibre project 'Received' came from the internet, so the 2 address(es)"), "{notices:?}"); + } + + /// A GeoLibre project downloaded from the internet whose layer the app downloads later (as + /// the desktop app and the browser do) asks for it as an address a document read from there + /// named, so adding it when it lands keeps the hold; the user's own asks as before. + #[test] + fn a_received_geolibre_layer_downloaded_later_stays_held() { + let data = "https://geolibre-later.example/roads.geojson".to_string(); + let text = json!({ + "version": "0.2.0", + "name": "Later", + "mapView": {}, + "basemapStyleUrl": "", + "layers": [{"id": "a", "name": "Roads", "type": "geojson", "source": {"url": data}}], + }) + .to_string(); + let p = json!({"text": text}); + for received in [Some(Reach::Public), None] { + let mut s = Session::new(Project::default()); + let reach = reach_after(&[data.clone(), data.clone(), data.clone()], || { + s.receiving(received); + s.run_leaving_downloads("project.importGeolibre", &p).unwrap(); + s.receiving(None); + }); + let asked: Vec<&Value> = s.url_requests.iter().map(|r| r.params()).collect(); + assert_eq!(asked.len(), 1, "{asked:?}"); + let from_document = asked[0].get("fromDocument").and_then(Value::as_bool) == Some(true); + assert_eq!((reach[0], from_document), if received.is_some() { (Reach::Public, true) } else { (Reach::Local, false) }); + } + } + + /// An address inside a tile template or a wrapper is held by what it is fetched from: a + /// received project's PMTiles archives on the local network, one read anonymously, are held + /// there and said. + #[test] + fn a_received_projects_wrapped_archives_are_held_too() { + use crate::render::rustgis_tiles::{pmtiles, s3}; + use rustgis_map::tiles::{TileKind, TileLayer}; + let plain = "http://192.168.1.5:8080/wrapped-reach/a.pmtiles".to_string(); + let anonymous = "http://192.168.1.6/wrapped-reach/b.pmtiles".to_string(); + let mut s = Session::new(Project::default()); + s.project.name = "wrapped".into(); + s.map_mut().tiles.push(TileLayer::new("A", TileKind::PmTiles, pmtiles::template(&plain))); + s.map_mut().tiles.push(TileLayer::new("B", TileKind::PmTiles, pmtiles::template(&s3::anonymous(&anonymous)))); + // Never read from anywhere, so not counted. + s.map_mut().tiles.push(TileLayer::new("C", TileKind::Raster, "http://169.254.169.254/wrapped-reach/{z}/{x}/{y}.png")); + let (text, _) = s.project.saved_text(None).unwrap(); + let mut downloaded = Session::new(Project::default()); + cache::allow_named(&plain); + cache::allow_named(&anonymous); + downloaded.receiving(Some(Reach::Public)); + downloaded.run("project.openText", &json!({"text": text})).unwrap(); + downloaded.receiving(None); + assert_eq!([&plain, &anonymous].map(|a| cache::ceiling_for(a)), [Reach::Public; 2]); + let notices = said(&downloaded); + assert_eq!(notices.len(), 1, "{notices:?}"); + assert!(notices[0].starts_with("the project 'wrapped' came from the internet, so the 2 address(es)"), "{notices:?}"); + } + + /// A project of the user's own, opened after a received one named some of its servers, says + /// which stay held to the internet rather than that it reads from them; the rest it reads. + #[test] + fn your_own_project_says_which_addresses_a_received_one_left_held() { + let (mut s, addresses) = project("held-before"); + let (received, _) = s.project.saved_text(None).unwrap(); + let mine = "http://localhost:18081/held-before/{z}/{x}/{y}.png"; + s.run("map.addTiles", &json!({"url": mine, "name": "Also mine"})).unwrap(); + let (own, _) = s.project.saved_text(None).unwrap(); + // As a new process has the record. + for a in addresses.iter().map(String::as_str).chain([mine]) { + cache::allow_named(a); + } + let mut downloaded = Session::new(Project::default()); + downloaded.receiving(Some(Reach::Public)); + downloaded.run("project.openText", &json!({"text": received})).unwrap(); + downloaded.receiving(None); + // The user's own project next, in the same process. + let mut opened = Session::new(Project::default()); + opened.run("project.openText", &json!({"text": own})).unwrap(); + assert_eq!([0, 1].map(|i| cache::ceiling_for(&addresses[i])), [Reach::Public; 2]); + assert_eq!(cache::ceiling_for(mine), Reach::Local); + let notices = said(&opened); + assert_eq!(notices.len(), 1, "{notices:?}"); + assert!( + notices[0].starts_with("the project 'held-before' reads from 1 address(es) on this computer or the local network: ") + && notices[0].contains("localhost:18081") + && notices[0].contains(". 2 more it names there stay held to the internet"), + "{notices:?}" + ); + } + + /// A received project reads nothing it names before holding it: its raster read in place + /// from a server on this computer is never asked for. + #[test] + fn a_received_project_reads_nothing_before_it_is_held() { + let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap(); + listener.set_nonblocking(true).unwrap(); + let scene = format!("http://{}/read-order/scene.tif", listener.local_addr().unwrap()); + let mut s = Session::new(Project::default()); + s.map_mut().add_raster("Scene".to_string(), rustgis_map::raster::RasterLayer::unread_in_place(scene.clone())); + let (text, _) = s.project.saved_text(None).unwrap(); + cache::allow_named(&scene); + let mut downloaded = Session::new(Project::default()); + downloaded.receiving(Some(Reach::Public)); + downloaded.run("project.openText", &json!({"text": text})).unwrap(); + downloaded.receiving(None); + downloaded.wait_in_place_reads(); + assert_eq!(cache::ceiling_for(&scene), Reach::Public); + assert_eq!( + listener.accept().map(|_| ()).unwrap_err().kind(), + std::io::ErrorKind::WouldBlock, + "the raster was read before the hold" + ); + } + + /// A style file and a field package an attached agent gives hold what they name to the + /// internet too, before reading them reads anything they name. + #[test] + fn style_files_and_field_packages_an_agent_gives_are_held_too() { + use base64::Engine; + let (mut s, addresses) = project("style-reach"); + let (text, _) = s.project.saved_text(None).unwrap(); + let mut styled = Session::new(Project::default()); + let reach = reach_after(&addresses, || drop(as_agent(&mut styled, "style.import", &json!({"text": text})))); + assert_eq!(reach, [Reach::Public; 3], "style.import"); + let notices = said(&styled); + assert!(notices.first().is_some_and(|n| n.starts_with("the style file came from the internet")), "{notices:?}"); + let package = rustgis_data::zip::write(&[("back.rgis".into(), text.into_bytes())]).unwrap(); + let data = base64::engine::general_purpose::STANDARD.encode(package); + let mut home = Session::new(Project::default()); + let reach = reach_after(&addresses, || drop(as_agent(&mut home, "offline.bringBack", &json!({"data": data})))); + assert_eq!(reach, [Reach::Public; 3], "offline.bringBack"); + } + + /// A GeoLibre project the app downloads is read within where its download connected: from a + /// server on the local network, as the user's own, though its name doesn't look local; and + /// when the app doesn't say where, within the internet. + #[test] + fn a_downloaded_geolibre_project_reaches_as_far_as_where_it_was_read() { + let tiles = "http://localhost:18084/download-reach/{z}/{x}/{y}.png"; + let text = json!({ + "version": "0.2.0", + "name": "Downloaded", + "mapView": {}, + "basemapStyleUrl": "", + "layers": [{"id": "a", "name": "Mine", "type": "xyz", "source": {"tiles": [tiles]}}], + }) + .to_string(); + for (read_at, reach) in [(Some(Reach::Local), Reach::Local), (None, Reach::Public)] { + cache::allow_named(tiles); + let mut s = Session::new(Project::default()); + // As the browser's `project.importGeolibre {"url"}` asks the app for it. + s.request_import_url(&json!({"url": "http://nas/download-reach.json", "geolibreProject": true})).unwrap(); + let request = s.take_url_requests().pop().unwrap(); + let id = s.download_started_for(&request).unwrap(); + if let Some(read_at) = read_at { + s.download_read_at(id, read_at); + } + assert!(s.download_landed(id, text.clone().into_bytes())); + let mut params = request.params().clone(); + params["id"] = json!(id); + s.complete_download(id, ¶ms).unwrap(); + assert_eq!(cache::ceiling_for(tiles), reach, "read at {read_at:?}"); + } + } +} diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 205b324d80..e48969ef91 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -20673,6 +20673,28 @@ fn local_data_server() -> (String, std::sync::Arc>> serve_files(vec![("/points.geojson".into(), points.to_vec()), ("/stac/collections".into(), collections.to_vec())]) } +/// Project text a plugin gives is held by both holds: what it names is held to the internet as a +/// received file's is, said, and nothing it names is read from this computer, a raster read in +/// place among them. +#[test] +fn project_text_a_plugin_gives_reads_nothing_from_this_computer() { + use crate::render::rustgis_tiles::{address::Reach, cache}; + let mut s = world(); + let id = "eng-received-text"; + plugin(id, &["network", "edit", "files"]); + let (base, asked) = local_data_server(); + let scene = format!("{base}/received/scene.tif"); + let mut given = Session::new(Project::default()); + given.map_mut().add_raster("Scene".to_string(), rustgis_map::raster::RasterLayer::unread_in_place(scene.clone())); + let (text, _) = given.project.saved_text(None).unwrap(); + cache::allow_named(&scene); + forward(&mut s, id, "map.import", json!({"text": text})).unwrap(); + s.wait_in_place_reads(); + assert_eq!(cache::ceiling_for(&scene), Reach::Public); + assert_eq!(asked.lock().unwrap().as_slice(), &[] as &[String], "nothing was read from this computer"); + assert!(s.notices.iter().any(|n| n.text.starts_with("the map file came from the internet, so the 1 address(es)"))); +} + /// Plugins reach only the internet, and so does every command a plugin runs that connects: an /// address it gives on this computer or the local network is refused before anything is read, /// naming it and why (the STAC, open data portal, web file, tile and OpenStreetMap commands diff --git a/crates/tiles/src/cache.rs b/crates/tiles/src/cache.rs index a9676cd787..61079ed663 100644 --- a/crates/tiles/src/cache.rs +++ b/crates/tiles/src/cache.rs @@ -493,67 +493,69 @@ fn canonical_resource(url: &str) -> &str { /// Marks `url` as document-derived so range reads, headers, tiles and downloads of it connect /// only to public internet addresses, and forgets any earlier local read of it. pub fn restrict_to_public(url: &str) { - let base = canonical_resource(url); - if base.is_empty() { - return; - } - let added = { - let mut p = public_only().lock().unwrap_or_else(|e| e.into_inner()); - let removed_named = p.named_local.remove(base); - if removed_named { - p.named_order.retain(|item| item != base); - } - let mut changed = removed_named; - if let Some(tpl) = PublicTemplate::parse(base) - && !p.templates.contains(&tpl) - { - if p.templates.len() < MAX_PUBLIC_TEMPLATES { - p.templates.push(tpl); - changed = true; - } else if !p.saturated { - p.saturated = true; - changed = true; - } - } - if !p.exact.contains(base) { - if p.exact.len() < MAX_PUBLIC_ONLY { - p.exact.insert(base.to_string()); - changed = true; - } else if !p.saturated { - p.saturated = true; - changed = true; - } - } - changed - }; - if added { - let aliases: Vec = - lock().slots.keys().filter(|key| canonical_resource(key) == base).map(|key| resource_of(key).to_string()).collect(); - forget(base); - if base != url { - forget(url); - } - for alias in aliases { - forget(&alias); + restrict_all_to_public([url]); +} + +/// [`restrict_to_public`] for every address of `urls` (a received file's): each is recorded, +/// then their earlier reads are forgotten ([`forget_resources`]), the cached answers gone through +/// once for all of them rather than once for each. +pub fn restrict_all_to_public<'a>(urls: impl IntoIterator) { + let mut bases = std::collections::HashSet::new(); + let mut spellings = std::collections::HashSet::new(); + for url in urls { + let base = canonical_resource(url); + if base.is_empty() || !record_public(base) { + continue; } - forget_restricted_aliases(base); + bases.insert(base.to_string()); + spellings.insert(forgotten_as(base).to_string()); + spellings.insert(forgotten_as(url).to_string()); } + if bases.is_empty() { + return; + } + // Every spelling cached of the same resource: the plain one, the anonymous one and the + // login-wrapped ones alike ([`forget`] compares the spelling it was given). + let aliases: Vec = lock() + .slots + .keys() + .filter(|key| bases.contains(canonical_resource(key))) + .map(|key| forgotten_as(resource_of(key)).to_string()) + .collect(); + spellings.extend(aliases); + forget_resources(&spellings, &bases); } -/// Forgets the cached answers of every address whose canonical resource is `base`: the plain -/// spelling, the anonymous one and the login-wrapped ones alike ([`forget`] compares the spelling -/// it was given). Reads under way are kept, as [`forget`] keeps them, and [`request`] and -/// [`peek_from`] refuse what they complete under a wider reach. -fn forget_restricted_aliases(base: &str) { - let mut c = lock(); - c.slots.retain(|key, slot| { - if canonical_resource(key) != base { - return true; +/// Records `base` (a canonical resource) as held to public internet addresses. Whether that +/// changed what is held, so its earlier reads must be forgotten. +fn record_public(base: &str) -> bool { + let mut p = public_only().lock().unwrap_or_else(|e| e.into_inner()); + let removed_named = p.named_local.remove(base); + if removed_named { + p.named_order.retain(|item| item != base); + } + let mut changed = removed_named; + if let Some(tpl) = PublicTemplate::parse(base) + && !p.templates.contains(&tpl) + { + if p.templates.len() < MAX_PUBLIC_TEMPLATES { + p.templates.push(tpl); + changed = true; + } else if !p.saturated { + p.saturated = true; + changed = true; } - slot.other = None; - matches!(slot.entry, Entry::Pending) && !crate::mbtiles::is_tile(key) - }); - c.bytes = c.slots.values().map(Slot::bytes).sum(); + } + if !p.exact.contains(base) { + if p.exact.len() < MAX_PUBLIC_ONLY { + p.exact.insert(base.to_string()); + changed = true; + } else if !p.saturated { + p.saturated = true; + changed = true; + } + } + changed } /// The origin a direct warp address's base is asked under. The restriction recorded for the warp @@ -1166,15 +1168,30 @@ fn resource_of(key: &str) -> &str { /// whose address stays the same, read again with other keys). Reads under way are kept, except an /// MBTiles file's tiles: it is forgotten when it may be replaced, and its old tiles mustn't stay. pub fn forget(url: &str) { + forget_resources(&std::collections::HashSet::from([forgotten_as(url).to_string()]), &std::collections::HashSet::new()); +} + +/// The resource [`forget`] forgets for `url`: without a download limit, and without a COG's look. +fn forgotten_as(url: &str) -> &str { let url = split_download_limit(url).0; // PMTiles and MBTiles paths are taken whole (see `resource_of`), even with a look-like name. let pmtiles = url.rsplit_once('.').is_some_and(|(_, ext)| ext.eq_ignore_ascii_case("pmtiles")); - let url = if pmtiles || crate::mbtiles::check(url).is_ok() { url } else { crate::cog::split(url).0 }; + if pmtiles || crate::mbtiles::check(url).is_ok() { url } else { crate::cog::split(url).0 } +} + +/// Forgets every resource of `resources` ([`forgotten_as`]) as [`forget`] does, and every cached +/// answer whose canonical resource is one of `bases`. The cached answers are gone through once for +/// all of them; the archives, COG tiles and remote files of each resource are forgotten one +/// resource at a time, each going through its own cache. Reads under way are kept, and [`request`] +/// and [`peek_from`] refuse what they complete under a wider reach. +fn forget_resources(resources: &std::collections::HashSet, bases: &std::collections::HashSet) { // First: a tile answered from here on is dropped, and one answered before goes with the rest. - crate::mbtiles::forget_archive(url); + for url in resources { + crate::mbtiles::forget_archive(url); + } let mut c = lock(); c.slots.retain(|k, s| { - if resource_of(k) != url { + if !resources.contains(resource_of(k)) && !bases.contains(canonical_resource(k)) { return true; } s.other = None; @@ -1182,12 +1199,14 @@ pub fn forget(url: &str) { }); c.bytes = c.slots.values().map(Slot::bytes).sum(); drop(c); - crate::pmtiles::forget_archive(url); - crate::cog::forget_file(url); + for url in resources { + crate::pmtiles::forget_archive(url); + crate::cog::forget_file(url); + rustgis_data::source::remote::forget_file(url); + } // Map tiles made from a service's pictures, kept only while one is missing or on its way, // and their plans: all are made again (those kept in the cache stay till `clear`). crate::warp::forget(); - rustgis_data::source::remote::forget_file(url); GENERATION.fetch_add(1, Ordering::Relaxed); } @@ -1948,6 +1967,13 @@ pub fn download_blocking_omitting(url: &str, omit: &'static [u16]) -> Result Result, String> { + download_blocking_with_origin_within(url, MAX_DOWNLOAD, BLOCKING_TIMEOUT, omit, ceiling).map(|f| f.bytes).map_err(large_file_hint) +} + /// A waited-for download's error, with where a large file goes instead when it timed out. #[cfg(not(target_arch = "wasm32"))] pub fn large_file_hint(e: String) -> String { diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index ec2381883f..8275f6b659 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -314,6 +314,8 @@ pub struct Download { pub slot: Slot, String>>, /// How far it has come (the status bar's). pub progress: std::sync::Arc, + /// Where it connected, for a GeoLibre project ([`rustgis_engine::Session::download_read_at`]). + pub reach: Slot, } /// A download or a window's read under way, for the status bar ([`RustGisApp::downloads_under_way`]). @@ -1048,9 +1050,9 @@ pub struct UiState { /// Data downloading from web addresses (Home › Add › Add Data › From URL). pub downloads: Vec, /// A project downloading from its web address (`ui.openUrl`, a `?project=` link): the - /// session's download id, the address and where the download lands. A later one replaces it; - /// opening another project meanwhile drops it. - pub project_download: Option<(u64, String, Slot, String>>)>, + /// session's download id, the address and where the download lands, with the reach it was + /// read at. A later one replaces it; opening another project meanwhile drops it. + pub project_download: Option<(u64, String, Slot, Reach), String>>)>, /// The SQL pane's editor, results and history. pub sql: sqlpane::State, /// GeoTIFFs, FlatGeobufs and GeoParquets by address whose headers are being read: those @@ -4609,16 +4611,20 @@ impl RustGisApp { let url = p.get("url").and_then(Value::as_str).map(str::trim).filter(|u| !u.is_empty()).ok_or("url is required")?; let url = rustgis_engine::map::geolibre::download_url(url); let url = url.as_str(); - let slot: Slot, String>> = Slot::default(); + let slot: Slot, Reach), String>> = Slot::default(); let land = slot.clone(); - rustgis_engine::render::rustgis_tiles::cache::download_limited( + // With where it was read: what the project names reaches no wider. + rustgis_engine::render::rustgis_tiles::cache::download_detailed_with_origin( url, if rustgis_engine::map::geolibre::is_project_file(url) { rustgis_engine::map::geolibre::MAX_TEXT } else { rustgis_engine::render::rustgis_tiles::cache::MAX_DOWNLOAD }, - Box::new(move |r| *land.lock().unwrap_or_else(|e| e.into_inner()) = Some(r)), + Box::new(move |r| { + let r = r.map(|fetched| (fetched.bytes, fetched.origin.reach())).map_err(|failure| failure.message); + *land.lock().unwrap_or_else(|e| e.into_inner()) = Some(r); + }), ); self.session.notify(i18n::fmt("Opening {url}…", &[("url", &rustgis_engine::sources::address_in_message(url))]), false); let id = self.session.download_started(); @@ -5951,7 +5957,13 @@ impl RustGisApp { } return self.poll_data_downloads(); } - if let Err(e) = r.and_then(|bytes| self.open_project_bytes(project_file_name(&url), &bytes)) { + // Opened as received from where it was read: what it names reaches no wider. + if let Err(e) = r.and_then(|(bytes, reach)| { + let was = self.session.receiving(Some(reach)); + let r = self.open_project_bytes(project_file_name(&url), &bytes); + self.session.receiving(was); + r + }) { self.session.notify(rustgis_engine::sources::message_with_address(&url, &e), true); } } @@ -6221,9 +6233,31 @@ impl RustGisApp { let watch = std::sync::Arc::downgrade(&slot); let wanted: rustgis_engine::render::rustgis_tiles::cache::Still = std::sync::Arc::new(move || watch.strong_count() > 1); let progress = std::sync::Arc::::default(); + let reach: Slot = Slot::default(); + let read_at = reach.clone(); + let project = q.get("geolibreProject").and_then(Value::as_bool) == Some(true); // A Shapefile address brings its companion parts under the same download owner. rustgis_engine::render::rustgis_tiles::cache::with_still(wanted, || { rustgis_engine::render::rustgis_tiles::cache::with_progress(Some(progress.clone()), || { + // A GeoLibre project, with where it was read: what it names reaches no wider. + if project && !public { + return rustgis_engine::render::rustgis_tiles::cache::download_detailed_with_origin( + &url, + rustgis_engine::map::geolibre::MAX_TEXT, + Box::new(move |r| { + let r = r + .map(|fetched| { + *read_at.lock().unwrap_or_else(|e| e.into_inner()) = Some(fetched.origin.reach()); + fetched.bytes + }) + .map_err(|failure| failure.message); + *land.lock().unwrap_or_else(|e| e.into_inner()) = Some(r); + }), + ); + } + if project { + *read_at.lock().unwrap_or_else(|e| e.into_inner()) = Some(Reach::Public); + } rustgis_engine::cmd::layer::download_data_from( &url, public, @@ -6239,7 +6273,7 @@ impl RustGisApp { ) }) }); - self.ui.downloads.push(Download { id, url, params: q, slot, progress }); + self.ui.downloads.push(Download { id, url, params: q, slot, progress, reach }); Ok(Value::Null) }) @@ -6322,13 +6356,20 @@ impl RustGisApp { } } let mut landed = Vec::new(); + let mut read_at = Vec::new(); self.ui.downloads.retain(|d| match d.slot.lock().unwrap_or_else(|e| e.into_inner()).take() { Some(r) => { landed.push((d.id, d.url.clone(), d.params.clone(), r)); + if let Some(reach) = d.reach.lock().unwrap_or_else(|e| e.into_inner()).take() { + read_at.push((d.id, reach)); + } false } None => true, }); + for (id, reach) in read_at { + self.session.download_read_at(id, reach); + } for (id, url, mut p, r) in landed { let origin = connectiontree::take_origin_key(&mut p); // A range's answer shorter than the range is refused, never read as the record. diff --git a/docs/installation.md b/docs/installation.md index f99f025015..e24bdfa772 100644 --- a/docs/installation.md +++ b/docs/installation.md @@ -197,7 +197,9 @@ builds the project on the fly. Its maps, layers, symbology and view open as save shares a styled map. The project replaces the start-up one, so `?data=`, `?stac=`, `?style=`, `?tiles=` and `?zarr=` are left out beside it (a notice says so). The data the project points to is read as it would be from a saved file, and its servers must allow the browser to fetch it -(CORS), as must the project's. +(CORS), as must the project's. A project from the internet reaches only the internet: an address +it names on this computer or the local network isn't read, and a notice says how many and names +the first three. `?stac=
` opens STAC Search on a [STAC](https://stacspec.org) item or collection: an item's footprint is drawn and its default asset (its true-colour `visual` image, else its first diff --git a/docs/user-guide/workspace.md b/docs/user-guide/workspace.md index 06f4bab70d..8240513820 100644 --- a/docs/user-guide/workspace.md +++ b/docs/user-guide/workspace.md @@ -38,6 +38,13 @@ longitude/latitude are saved as before and don't need it. command line. A package opens as a new, unsaved project; Save writes a plain `.rgis` file. Opening or creating a project clears undo history; saving does not. +A project, package, template, map, layer or style file, or a field package brought back, received +from the internet reaches only the internet: one opened by its web address (`?project=`), or given +as text by the AI Assistant, MCP or a plugin. An address it names on this computer or the local network isn't read. A file you +open from your own disk reaches your own servers as before. Either way, opening a file that names +such addresses says how many, and names the first three. One that something received from the +internet named earlier in the session stays held, and the notice says so. + This version already reads format 2, a newer `.rgis` format ([#1853](https://github.com/opengeos/RustGIS/issues/1853)), when the file needs nothing this version lacks, and saves it in the format it writes today. A project, package, template, map, @@ -223,6 +230,8 @@ An absolute data path is tried first, then its filename under `dir` (the project default). A desktop project may reference files outside that folder; import projects you trust to select those files. Browser imports can use inline GeoJSON and web addresses; local paths need desktop. A web app link such as `?project=https://example.org/watershed.geolibre` imports the same map. +A GeoLibre project read from the internet (by `url`, a link, or JSON the AI Assistant, MCP or a +plugin gives) reaches only the internet, as other [received projects](#projects) do. This startup link takes precedence over other data/style links so download timing cannot change which map receives them.