From 4591e148905e747e6fd8621e5f29c7b0a0abbe54 Mon Sep 17 00:00:00 2001 From: mavrick Date: Tue, 24 Nov 2026 04:24:31 -0600 Subject: [PATCH 1/4] fix(plugins): every web address a plugin gives a command reaches only the internet Plugins reach only the internet: host.fetch refuses this computer and the local network, and service discovery follows it since #2841. The other commands a plugin runs did not: the address it gave stac.*, portal.search, portal.files, portal.add (and its portal), layer.addUrl, map.addTiles, osm.download and the rest was read from wherever it pointed. One check in the policy's admit, which every command a plugin runs passes through: for a command that connects, each web address among its parameters on this computer or the local network is refused with host.fetch's wording before anything is read, and the rest are read only from the internet, wherever their names resolve. Every other caller is unchanged. Also say once, as a warning, when the table of addresses held to the internet is full: from then on every address it has no record of was held to the internet with nothing said. --- crates/engine/src/cmd/plugin_fetch.rs | 58 +++++++++++++++++- crates/engine/src/lib.rs | 14 +++++ crates/engine/src/policy/dispatch.rs | 4 ++ crates/engine/src/tests.rs | 87 +++++++++++++++++++++++++++ crates/tiles/src/cache.rs | 16 +++++ crates/ui-egui/Cargo.toml | 2 +- crates/ui-egui/src/pluginpanel.rs | 8 +++ crates/ui-egui/src/pluginstart.rs | 2 + docs/plugins.md | 10 +-- 9 files changed, 193 insertions(+), 8 deletions(-) diff --git a/crates/engine/src/cmd/plugin_fetch.rs b/crates/engine/src/cmd/plugin_fetch.rs index fddd8989a9..ffb9d358e1 100644 --- a/crates/engine/src/cmd/plugin_fetch.rs +++ b/crates/engine/src/cmd/plugin_fetch.rs @@ -116,19 +116,27 @@ fn cache() -> std::sync::MutexGuard<'static, Cache> { CACHE.lock().unwrap_or_else(|e| e.into_inner()) } -#[cfg(test)] +#[cfg(any(test, feature = "testing"))] thread_local! { /// Tests: let the plugin fetch from this computer (a test server) and, when `wait` is off, /// fetch as the browser does (pending, then run again). pub(crate) static TEST: std::cell::Cell<(bool, bool)> = const { std::cell::Cell::new((false, true)) }; } +/// Tests in other crates: lets the plugins this thread runs reach this computer (their test +/// server), with `host.fetch` and the addresses they give commands, as the engine's own tests do. +#[cfg(feature = "testing")] +#[doc(hidden)] +pub fn plugins_reach_this_computer() { + TEST.with(|t| t.set((true, t.get().1))); +} + fn allow_local() -> bool { - #[cfg(test)] + #[cfg(any(test, feature = "testing"))] { TEST.with(|t| t.get().0) } - #[cfg(not(test))] + #[cfg(not(any(test, feature = "testing")))] { false } @@ -188,6 +196,50 @@ impl Session { Err(e) => Err(e), } } + + /// Holds the web addresses a plugin gives a command that connects as [`Self::named_reach`] + /// holds the service it names, with its wording: each one among the command's parameters (not inside the + /// contents of a file it gives, `data` or `text`) on this computer or the local network is + /// refused, naming it, before anything is read, and the rest are read only from the internet + /// ([`cache::restrict_to_public`]), wherever their names resolve, so what is read from them + /// and what that names is held there too. Addresses nested in a value (a STAC item, a + /// service's documents) are held by the commands that read them. Any other caller's addresses + /// are its own choice, as before. + /// + /// [`cache::restrict_to_public`]: crate::render::rustgis_tiles::cache::restrict_to_public + pub(crate) fn hold_plugin_addresses(&self, params: &Value) -> Result<(), String> { + if !self.policy_plugin() || allow_local() { + return Ok(()); + } + let Some(o) = params.as_object() else { return Ok(()) }; + let named: Vec<&str> = o + .iter() + .filter(|(key, _)| !matches!(key.as_str(), "data" | "text")) + .filter_map(|(_, v)| v.as_str().map(str::trim)) + .filter(|v| is_web_address(v)) + .collect(); + for url in &named { + // An address wrong some other way (spaces in it) is the command's to judge; it is + // held to the internet below all the same. + if let Err(e) = address::check_reach(url, address::Reach::Public) + && address::is_refusal(&e) + { + return Err(crate::sources::message_with_address(url, INTERNET_ONLY)); + } + } + for url in named { + crate::render::rustgis_tiles::cache::restrict_to_public(url); + } + Ok(()) + } +} + +/// Whether `v` is a web address the app fetches (`http://`, `https://` or `s3://`), as given or +/// marked with a saved login, an S3 connection or an anonymous read. +fn is_web_address(v: &str) -> bool { + let plain = crate::render::rustgis_tiles::s3::split_anonymous(v).0; + let plain = rustgis_data::login_address::inner(rustgis_data::s3_address::inner(plain)).to_ascii_lowercase(); + ["http://", "https://", "s3://"].iter().any(|scheme| plain.starts_with(scheme)) } /// The answer for a fetched document: `{url, text}`, and `json` when the text is a JSON object diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 1f7ae7a626..af44f35910 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -1921,6 +1921,7 @@ impl Session { // And the coordinate systems that needed a missing datum grid, after every command. self.say_grid_notes(); self.say_unplaced(); + self.say_public_only_full(); // A plugin's command waiting for its fetches answers `pending` and runs again when they // land: logged then, once. (Another command's `pending`, a download the web app makes, is // logged as it is asked for: nothing runs it again.) @@ -3271,6 +3272,7 @@ impl Session { self.grid_notes_checked = Some(web_time::Instant::now()); self.say_grid_notes(); self.say_unplaced(); + self.say_public_only_full(); } } @@ -3283,6 +3285,18 @@ impl Session { } } + /// Says once that the table of web addresses held to the internet is full + /// ([`render::rustgis_tiles::cache::take_public_only_full`]): from then on, until RustGIS + /// restarts, an address it has no record of is read only from the internet, so the user's own + /// on this computer or the local network is refused. + fn say_public_only_full(&mut self) { + if render::rustgis_tiles::cache::take_public_only_full() { + self.warn( + "web addresses: RustGIS has recorded as many addresses that may reach only the internet as it can hold, so until it restarts an address it hasn't seen before is read only from the internet, not this computer or the local network", + ); + } + } + /// Says, once for each version of a layer's geometry (and again for a larger count, as when the /// globe leaves out what a map in the layer's own system drew), that a layer held in another /// system has features with a place that can't be given in longitude/latitude, which the map diff --git a/crates/engine/src/policy/dispatch.rs b/crates/engine/src/policy/dispatch.rs index 344d3b275c..a67352e54d 100644 --- a/crates/engine/src/policy/dispatch.rs +++ b/crates/engine/src/policy/dispatch.rs @@ -711,6 +711,10 @@ impl Session { } else if decision != Decision::Allow { return Err("this operation needs your approval".into()); } + // Plugins reach only the internet: so does every command one runs that connects. + if node.effects.contains(super::Effect::Network) { + self.hold_plugin_addresses(&node.params)?; + } Ok(Arc::new(node)) } /// Keeps the admitted node and synchronous request predicate through nested execution; restores both on panic. diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index e848ff3d51..f83c6e81a0 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -19627,6 +19627,8 @@ fn plugin_bridges_cannot_run_another_plugins_tools() { fn plugin_downloads_are_left_to_the_app() { let mut s = world(); plugin("eng-url", &["edit", "network"]); + // Its downloads come from this computer (a test server). + fetch_mode(true, true); let (undo, layers) = (s.undo.len(), s.map().layers.len()); // Nothing answers there: a download that waited fails. let url = "http://127.0.0.1:9/places.csv"; @@ -20457,6 +20459,85 @@ fn a_document_a_plugin_supplies_names_only_the_internet() { rustgis_plugins::unload(id); } +/// A server on this computer for the commands that take an address: a GeoJSON file and a STAC +/// API's collections, and the paths it was asked for. +fn local_data_server() -> (String, std::sync::Arc>>) { + let points = br#"{"type":"FeatureCollection","features":[{"type":"Feature","properties":{"n":1},"geometry":{"type":"Point","coordinates":[1,2]}}]}"#; + let collections = br#"{"collections":[{"id":"scenes","title":"Scenes","links":[]}],"links":[]}"#; + serve_files(vec![("/points.geojson".into(), points.to_vec()), ("/stac/collections".into(), collections.to_vec())]) +} + +/// 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 +/// among them), and nothing is added. +#[test] +fn a_plugin_cannot_name_a_local_address_to_a_command() { + let mut s = world(); + let id = "eng-address-local"; + plugin(id, &["network", "edit"]); + let (base, asked) = local_data_server(); + let lan = "http://192.168.21.4"; + let (layers, tiles) = (s.map().layers.len(), s.map().tiles.len()); + let cases = [ + ("stac.collections", json!({"url": format!("{base}/stac")}), format!("{base}/stac")), + ("stac.search", json!({"url": format!("{base}/stac"), "collections": ["scenes"], "bbox": [0, 0, 1, 1]}), format!("{base}/stac")), + ("stac.addAsset", json!({"url": format!("{base}/stac/item.json")}), format!("{base}/stac/item.json")), + ( + "stac.addCube", + json!({"url": format!("{base}/stac"), "collection": "scenes", "asset": "red", "bbox": [0, 0, 1, 1], "start": "2024-01-01", "end": "2024-02-01"}), + format!("{base}/stac"), + ), + ("portal.search", json!({"portal": "ckan", "url": format!("{lan}/ckan"), "query": "parcels"}), format!("{lan}/ckan")), + ( + "portal.files", + json!({"dataset": "0123456789abcdef", "portal": "arcgis-portal", "url": format!("{lan}/portal")}), + format!("{lan}/portal"), + ), + ("portal.add", json!({"url": format!("{base}/points.geojson")}), format!("{base}/points.geojson")), + ("portal.add", json!({"url": format!("{base}/store.zarr"), "use": "zarr"}), format!("{base}/store.zarr")), + ("portal.add", json!({"url": "https://data.example.com/points.geojson", "portal": lan}), lan.to_string()), + ("layer.addUrl", json!({"url": format!("{base}/points.geojson")}), format!("{base}/points.geojson")), + ("map.addTiles", json!({"url": format!("{lan}/tiles/{{z}}/{{x}}/{{y}}.png")}), format!("{lan}/tiles/{{z}}/{{x}}/{{y}}.png")), + ( + "osm.download", + json!({"bbox": [1, 2, 1.01, 2.01], "tags": "building", "url": format!("{base}/api/interpreter")}), + format!("{base}/api/interpreter"), + ), + ]; + for (op, p, url) in cases { + let e = forward(&mut s, id, op, p).unwrap_err(); + assert!( + e.contains(&url) && e.contains("plugins fetch only from the internet, not this computer or the local network"), + "{op}: {e}" + ); + } + assert_eq!(asked.lock().unwrap().as_slice(), &[] as &[String], "nothing was read from this computer"); + assert_eq!((s.map().layers.len(), s.map().tiles.len()), (layers, tiles), "nothing was added"); + // An address on the internet is taken, and read only from there, wherever its name resolves. + let public = "https://tiles.plugin-named.example/{z}/{x}/{y}.png"; + forward(&mut s, id, "map.addTiles", json!({"url": public})).unwrap(); + use crate::render::rustgis_tiles::{address::Reach, cache}; + assert_eq!(cache::ceiling_for("https://tiles.plugin-named.example/3/4/5.png"), Reach::Public); + rustgis_plugins::unload(id); +} + +/// The user's own addresses on this computer are read as ever: only a plugin's are held to the +/// internet. +#[test] +fn the_users_own_local_address_is_still_read() { + let mut s = world(); + let (base, asked) = local_data_server(); + let added = s.run("layer.addUrl", &json!({"url": format!("{base}/points.geojson"), "name": "Mine"})).unwrap(); + assert!(added["layer"].is_u64(), "{added}"); + let listed = s.run("stac.collections", &json!({"url": format!("{base}/stac")})).unwrap(); + assert_eq!(listed["collections"][0]["id"], "scenes", "{listed}"); + s.run("map.addTiles", &json!({"url": format!("{base}/tiles/{{z}}/{{x}}/{{y}}.png"), "name": "Local tiles"})).unwrap(); + assert!(s.map().tiles.iter().any(|t| t.name == "Local tiles")); + let asked = asked.lock().unwrap(); + assert!(asked.iter().any(|p| p == "/points.geojson") && asked.iter().any(|p| p == "/stac/collections"), "{asked:?}"); +} + /// Where nothing may wait (the browser), `host.fetch` answers pending: the command is undone, /// quietly, and runs again once the answer is in, when the cache answers. #[test] @@ -49295,6 +49376,8 @@ fn a_window_asked_for_the_view_keeps_the_view_it_was_asked_in() { let (base, _) = serve_ranges(example(1024, 256)); let mut s = world(); plugin("eng-window-view", &["edit", "network"]); + // Its downloads come from this computer (a test server). + fetch_mode(true, true); let layers = s.map().layers.len(); s.run("map.zoomToExtent", &json!({"extent": [10.3, 45.55, 10.45, 45.7]})).unwrap(); let seen = crate::cmd::workspace::view_extent(&s); @@ -49337,6 +49420,8 @@ fn a_plugin_command_runs_again_when_its_window_is_added() { let (base, _) = serve_ranges(example(1024, 256)); let mut s = world(); plugin("eng-window", &["edit", "network"]); + // Its downloads come from this computer (a test server). + fetch_mode(true, true); let layers = s.map().layers.len(); let url = format!("{base}/scene.tif"); let bbox = json!([10.25, 45.5, 10.5, 45.75]); @@ -51014,6 +51099,8 @@ fn a_plugin_commands_grib_range_is_added_when_the_app_completes_it() { let (base, _) = serve_ranges(file.clone()); let mut s = world(); plugin("eng-grib-range", &["edit", "network"]); + // Its downloads come from this computer (a test server). + fetch_mode(true, true); let url = format!("{base}/run/PREC.grb"); let p = json!({"op": "layer.addUrl", "params": {"url": url, "bytes": [88, 175], "name": "Rain"}}); s.run_leaving_downloads("plugin:eng-grib-range/f", &p).unwrap(); diff --git a/crates/tiles/src/cache.rs b/crates/tiles/src/cache.rs index c83f7551be..89460eb845 100644 --- a/crates/tiles/src/cache.rs +++ b/crates/tiles/src/cache.rs @@ -474,6 +474,8 @@ struct PublicOnly { /// Once capacity is reached, active public restrictions are never evicted; unknown URLs fail /// closed to [`crate::address::Reach::Public`] unless explicitly user-named via [`allow_named`]. saturated: bool, + /// Whether [`take_public_only_full`] has said that capacity was reached. + said_full: bool, } fn public_only() -> &'static Mutex { @@ -605,6 +607,17 @@ pub fn ceiling_for(url: &str) -> crate::address::Reach { } } +/// Whether the addresses recorded as reaching only the internet ([`restrict_to_public`]) have +/// filled their table ([`MAX_PUBLIC_ONLY`] addresses or [`MAX_PUBLIC_TEMPLATES`] templates) and +/// this hasn't said so yet: from then on every address not recorded is read only from the +/// internet, until the restrictions are reset. True once, for the session to say. +pub fn take_public_only_full() -> bool { + let mut p = public_only().lock().unwrap_or_else(|e| e.into_inner()); + let new = p.saturated && !p.said_full; + p.said_full |= p.saturated; + new +} + /// Resets document-origin public restrictions recorded by [`restrict_to_public`] and [`allow_named`]. pub fn clear_public_restrictions() { let mut p = public_only().lock().unwrap_or_else(|e| e.into_inner()); @@ -7848,12 +7861,15 @@ Connection: close let first_tpl = "https://dated.example/{YYYY}/{MM}/{DD}.tif"; restrict_to_public(first_exact); restrict_to_public(first_tpl); + assert!(!take_public_only_full(), "nothing to say before the table fills"); for i in 0..(MAX_PUBLIC_TEMPLATES + 8) { restrict_to_public(&format!("https://t{i}.example/{{z}}/{{x}}/{{y}}.png")); } for i in 0..(MAX_PUBLIC_ONLY + 8) { restrict_to_public(&format!("https://e.example/asset-{i}.tif")); } + assert!(take_public_only_full(), "a full table is said"); + assert!(!take_public_only_full(), "once"); assert_eq!(ceiling_for(first_exact), crate::address::Reach::Public); assert_eq!(ceiling_for("https://dated.example/2025/01/15.tif"), crate::address::Reach::Public); assert_eq!(ceiling_for("https://unseen.example/other.tif"), crate::address::Reach::Public, "saturated table fails closed"); diff --git a/crates/ui-egui/Cargo.toml b/crates/ui-egui/Cargo.toml index b59bbd49de..faeaa52f41 100644 --- a/crates/ui-egui/Cargo.toml +++ b/crates/ui-egui/Cargo.toml @@ -45,7 +45,7 @@ rustix = { version = "1.1", features = ["process", "fs"] } [dev-dependencies] tempfile = "3" # PDF downloads drawn off the frame (#2336). -rustgis-engine = { workspace = true, features = ["pdf"] } +rustgis-engine = { workspace = true, features = ["pdf", "testing"] } rustgis-plugins = { workspace = true, features = ["testing"] } # Copernicus Data Space sign-ins at a fake token endpoint on 127.0.0.1. rustgis-tiles = { workspace = true, features = ["testing"] } diff --git a/crates/ui-egui/src/pluginpanel.rs b/crates/ui-egui/src/pluginpanel.rs index ed3123bfef..0d2b74a9fd 100644 --- a/crates/ui-egui/src/pluginpanel.rs +++ b/crates/ui-egui/src/pluginpanel.rs @@ -1467,6 +1467,8 @@ mod tests { /// the frame, as the browser does, and the layer lands as the plugin asked for it (#1144). #[test] fn a_plugin_adds_data_by_address_off_the_frame() { + // The plugin's downloads come from this computer (a test server or address). + rustgis_engine::cmd::plugins::fetch::plugins_reach_this_computer(); let _turn = crate::fetching::turn(); use rustgis_engine::plugins; use std::io::{Read, Write}; @@ -1514,6 +1516,8 @@ mod tests { /// The real deferred request and probe loop refuse a withdrawn plugin before a fallback send. #[test] fn permission_policy_plugin_deferred_probe_refuses_before_fallback() { + // The plugin's downloads come from this computer (a test server or address). + rustgis_engine::cmd::plugins::fetch::plugins_reach_this_computer(); let _turn = crate::fetching::turn(); use rustgis_engine::{plugins, render::rustgis_tiles::cache}; use std::sync::{ @@ -1587,6 +1591,8 @@ mod tests { /// without first reading its header to see whether it could be read in place. #[test] fn a_scan_by_address_is_downloaded_whole_without_a_probe() { + // The plugin's downloads come from this computer (a test server or address). + rustgis_engine::cmd::plugins::fetch::plugins_reach_this_computer(); let _turn = crate::fetching::turn(); use rustgis_engine::plugins; use std::io::{Read, Write}; @@ -1635,6 +1641,8 @@ mod tests { /// `layer.addUrl` answers what was added (#1330). #[test] fn a_plugin_reads_a_window_off_the_frame() { + // The plugin's downloads come from this computer (a test server or address). + rustgis_engine::cmd::plugins::fetch::plugins_reach_this_computer(); let _turn = crate::fetching::turn(); use rustgis_engine::plugins; use std::sync::atomic::Ordering; diff --git a/crates/ui-egui/src/pluginstart.rs b/crates/ui-egui/src/pluginstart.rs index c2890ab993..6d06f236c4 100644 --- a/crates/ui-egui/src/pluginstart.rs +++ b/crates/ui-egui/src/pluginstart.rs @@ -204,6 +204,8 @@ mod tests { /// Queued plugins leave owned URL requests to the app; string zoom options survive delivery. #[test] fn queued_plugin_downloads_keep_their_claim_and_zoom() { + // The plugin's downloads come from this computer (a test server or address). + rustgis_engine::cmd::plugins::fetch::plugins_reach_this_computer(); let _turn = crate::fetching::turn(); use rustgis_engine::render::rustgis_tiles::cache; use std::sync::{Arc, Mutex}; diff --git a/docs/plugins.md b/docs/plugins.md index 85a42bb4fe..047bded099 100644 --- a/docs/plugins.md +++ b/docs/plugins.md @@ -760,10 +760,12 @@ that needs it left out. address taken from the one before, runs once per step, up to 64 times. The browser follows redirects itself, and the server must allow requests from web pages (CORS). -Service discovery a plugin starts follows the same rule. The service or catalogue address it gives -`service.add`, `service.layers`, `service.coverage`, `service.groupPlan`, `service.import`, -`service.refresh` or `catalog.search` must be on the internet, and the documents read from it, -any `text` the plugin supplies and everything they name are held to the internet too. +The commands a plugin runs follow the same rule. A web address it gives one that connects (the +`url` of `stac.search`, `portal.add`, `layer.addUrl`, `map.addTiles` or `osm.download`, a portal's +address, a service or catalogue to discover) must be on the internet, or the command is refused +before anything is read. The address is then read only from the internet, wherever its name +resolves, and the documents read from it, any `text` the plugin supplies and everything they name +are held to the internet too. Use `host::call("host.fetch", json!({"url": url}))` in the Rust SDK, or `host::call("host.fetch", json!({"url": url, "json": false}))` for the text only. From d86623e992740f96add37265203184403a0c9196 Mon Sep 17 00:00:00 2001 From: mavrick Date: Tue, 24 Nov 2026 05:58:08 -0600 Subject: [PATCH 2/4] fix(plugins): hold every request a plugin's command makes to the internet Recording the address a plugin gives held only that exact address. The requests a command derives from it (a STAC API's collections and search, a portal's search, the next page) and those a saved connection sends (an S3 bucket's listing through the user's connection) still connected wherever their names resolved. While a network command runs under a plugin's authority, every request it makes on that thread is now read only from the internet (cache::held_to_public, consulted by ceiling_for). A copy run ahead leaves the table-full notice for the session that takes its results. --- crates/engine/src/cmd/plugin_fetch.rs | 42 +++++++++++++++-------- crates/engine/src/lib.rs | 6 ++++ crates/engine/src/policy/dispatch.rs | 8 ++++- crates/engine/src/tests.rs | 23 +++++++++++++ crates/tiles/src/cache.rs | 49 ++++++++++++++++++++++++++- docs/plugins.md | 7 ++-- 6 files changed, 115 insertions(+), 20 deletions(-) diff --git a/crates/engine/src/cmd/plugin_fetch.rs b/crates/engine/src/cmd/plugin_fetch.rs index ffb9d358e1..d361f1b19e 100644 --- a/crates/engine/src/cmd/plugin_fetch.rs +++ b/crates/engine/src/cmd/plugin_fetch.rs @@ -197,27 +197,28 @@ impl Session { } } + /// Whether what runs now is held to the internet: a plugin's authority is in the scope (as + /// for [`Self::named_reach`]), unless a test lets it reach its server on this computer. + pub(crate) fn plugin_held(&self) -> bool { + self.policy_plugin() && !allow_local() + } + /// Holds the web addresses a plugin gives a command that connects as [`Self::named_reach`] - /// holds the service it names, with its wording: each one among the command's parameters (not inside the - /// contents of a file it gives, `data` or `text`) on this computer or the local network is - /// refused, naming it, before anything is read, and the rest are read only from the internet - /// ([`cache::restrict_to_public`]), wherever their names resolve, so what is read from them - /// and what that names is held there too. Addresses nested in a value (a STAC item, a - /// service's documents) are held by the commands that read them. Any other caller's addresses - /// are its own choice, as before. + /// holds the service it names, with its wording: each one among the command's parameters + /// (not inside the contents of a file it gives, `data` or `text`) on this computer or the local + /// network is refused, naming it, before anything is read. The rest are recorded as reaching + /// only the internet ([`cache::restrict_to_public`]), wherever their names resolve, so the + /// reads made of them later or elsewhere (a download left to the app, a tile layer drawn) + /// are held there too; while the command runs, all its requests are + /// ([`cache::held_to_public`]). Any other caller's addresses are its own choice, as before. /// /// [`cache::restrict_to_public`]: crate::render::rustgis_tiles::cache::restrict_to_public + /// [`cache::held_to_public`]: crate::render::rustgis_tiles::cache::held_to_public pub(crate) fn hold_plugin_addresses(&self, params: &Value) -> Result<(), String> { - if !self.policy_plugin() || allow_local() { + if !self.plugin_held() { return Ok(()); } - let Some(o) = params.as_object() else { return Ok(()) }; - let named: Vec<&str> = o - .iter() - .filter(|(key, _)| !matches!(key.as_str(), "data" | "text")) - .filter_map(|(_, v)| v.as_str().map(str::trim)) - .filter(|v| is_web_address(v)) - .collect(); + let named = web_addresses(params); for url in &named { // An address wrong some other way (spaces in it) is the command's to judge; it is // held to the internet below all the same. @@ -234,6 +235,17 @@ impl Session { } } +/// The web addresses among a command's own parameters, not inside the contents of a file it +/// gives (`data`, `text`). +fn web_addresses(params: &Value) -> Vec<&str> { + let Some(o) = params.as_object() else { return Vec::new() }; + o.iter() + .filter(|(key, _)| !matches!(key.as_str(), "data" | "text")) + .filter_map(|(_, v)| v.as_str().map(str::trim)) + .filter(|v| is_web_address(v)) + .collect() +} + /// Whether `v` is a web address the app fetches (`http://`, `https://` or `s3://`), as given or /// marked with a saved login, an S3 connection or an anonymous read. fn is_web_address(v: &str) -> bool { diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index af44f35910..906c6b3850 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -3290,6 +3290,12 @@ impl Session { /// restarts, an address it has no record of is read only from the internet, so the user's own /// on this computer or the local network is refused. fn say_public_only_full(&mut self) { + // A copy run ahead (`requests_into`, desktop only) leaves it for the session that takes + // its results. + #[cfg(not(target_arch = "wasm32"))] + if self.requests_into.is_some() { + return; + } if render::rustgis_tiles::cache::take_public_only_full() { self.warn( "web addresses: RustGIS has recorded as many addresses that may reach only the internet as it can hold, so until it restarts an address it hasn't seen before is read only from the internet, not this computer or the local network", diff --git a/crates/engine/src/policy/dispatch.rs b/crates/engine/src/policy/dispatch.rs index a67352e54d..017159116e 100644 --- a/crates/engine/src/policy/dispatch.rs +++ b/crates/engine/src/policy/dispatch.rs @@ -729,7 +729,13 @@ impl Session { } let still = continuation.map(|c| Arc::new(move || c.check().is_ok()) as crate::render::rustgis_tiles::cache::Still); let r = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { - crate::render::rustgis_tiles::cache::with_optional_still(still, || f(self)) + // Plugins reach only the internet: so does every request a command one runs makes, + // the ones it derives from an address it was given (a listing, a search, a next page) + // and the ones a saved connection sends. + let held = node.effects.contains(super::Effect::Network) && self.plugin_held(); + crate::render::rustgis_tiles::cache::with_optional_still(still, || { + crate::render::rustgis_tiles::cache::held_to_public(held, || f(self)) + }) })); let complete = if let Some(cursor) = &mut self.policy.cursor { cursor.frames.pop().is_none_or(|(n, at)| n.len() == at) } else { true }; diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index f83c6e81a0..a1a46af52a 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -20522,6 +20522,29 @@ fn a_plugin_cannot_name_a_local_address_to_a_command() { rustgis_plugins::unload(id); } +/// A plugin's command is held to the internet in every request it makes, not only at the address +/// it gives: a bucket it names is listed through the user's connection that serves it, whose +/// endpoint is on this computer, and the listing is refused there, while the user's own listing of +/// it is read. +#[test] +fn a_plugin_lists_a_bucket_only_from_the_internet() { + #[cfg(not(target_arch = "wasm32"))] + if isolate_process_test("tests::a_plugin_lists_a_bucket_only_from_the_internet") { + return; + } + let listing = br#"plugin-held-bucketfalsea.tif3"#; + let base = serve(listing, 1); + let mut s = world(); + s.run("s3.connect", &json!({"name": "local-minio", "endpoint": base, "buckets": ["plugin-held-bucket"], "anonymous": true})).unwrap(); + let id = "eng-s3-local"; + plugin(id, &["network"]); + let e = forward(&mut s, id, "s3.list", json!({"bucket": "plugin-held-bucket"})).unwrap_err(); + assert!(e.contains("local network"), "{e}"); + let own = s.run("s3.list", &json!({"bucket": "plugin-held-bucket"})).unwrap(); + assert_eq!(own["objects"][0]["url"], "s3://plugin-held-bucket/a.tif", "{own}"); + rustgis_plugins::unload(id); +} + /// The user's own addresses on this computer are read as ever: only a plugin's are held to the /// internet. #[test] diff --git a/crates/tiles/src/cache.rs b/crates/tiles/src/cache.rs index 89460eb845..1ec8930e61 100644 --- a/crates/tiles/src/cache.rs +++ b/crates/tiles/src/cache.rs @@ -588,9 +588,36 @@ pub fn allow_named(url: &str) { } } +thread_local! { + /// Whether this thread's requests are held to the internet ([`held_to_public`]). + static HELD: std::cell::Cell = const { std::cell::Cell::new(false) }; +} + +/// Runs `f` with every address this thread asks for in it read only from the internet when `held` +/// (a plugin's command: plugins reach only the internet), whatever is recorded of the address, +/// so the requests a command derives from the address it was given (a listing, a search, a next +/// page) are held as that address is. Nested calls only add to it; it is restored when `f` +/// returns or panics. Requests made later or on another thread follow what is recorded +/// ([`restrict_to_public`]). +pub fn held_to_public(held: bool, f: impl FnOnce() -> T) -> T { + /// Puts back the hold from before, however `f` ends. + struct Restore(bool); + impl Drop for Restore { + fn drop(&mut self) { + HELD.with(|h| h.set(self.0)); + } + } + let _restore = Restore(HELD.with(|h| h.replace(h.get() || held))); + f() +} + /// The network reach ceiling recorded for `url`: [`crate::address::Reach::Public`] when a web -/// document named it, [`crate::address::Reach::Local`] otherwise. +/// document named it, or while this thread's requests are [`held_to_public`], +/// [`crate::address::Reach::Local`] otherwise. pub fn ceiling_for(url: &str) -> crate::address::Reach { + if HELD.with(std::cell::Cell::get) { + return crate::address::Reach::Public; + } let base = canonical_resource(url); if base.is_empty() { return crate::address::Reach::Local; @@ -7828,6 +7855,26 @@ Connection: close assert_eq!(ceiling_for(tif), crate::address::Reach::Local); } + /// While a thread's requests are held to the internet (a plugin's command), an address with + /// nothing recorded of it, as a listing or search derived from the one given, is read only + /// from the internet: one on this computer is refused, and read again once the hold ends. + #[test] + fn a_held_thread_reads_only_from_the_internet() { + let _turn = turn(); + let ok = "HTTP/1.1 200 OK\r\nContent-Length: 2\r\nConnection: close\r\n\r\nok".to_string(); + let base = serve(vec![ok.clone(), ok]); + let derived = format!("{base}/api/collections"); + assert_eq!(ceiling_for(&derived), crate::address::Reach::Local); + let held = held_to_public(true, || { + held_to_public(false, || assert_eq!(ceiling_for(&derived), crate::address::Reach::Public, "nested, still held")); + download_blocking(&derived) + }); + let e = held.unwrap_err(); + assert!(e.contains("local network"), "{e}"); + assert_eq!(ceiling_for(&derived), crate::address::Reach::Local, "the hold ends with it"); + assert_eq!(download_blocking(&derived).unwrap(), b"ok"); + } + /// A read begun while its resource could reach the local network, and answered after a web /// document restricted it to public addresses, is not kept for a public read (#2055). #[test] diff --git a/docs/plugins.md b/docs/plugins.md index 047bded099..7f196bfc78 100644 --- a/docs/plugins.md +++ b/docs/plugins.md @@ -763,9 +763,10 @@ that needs it left out. The commands a plugin runs follow the same rule. A web address it gives one that connects (the `url` of `stac.search`, `portal.add`, `layer.addUrl`, `map.addTiles` or `osm.download`, a portal's address, a service or catalogue to discover) must be on the internet, or the command is refused -before anything is read. The address is then read only from the internet, wherever its name -resolves, and the documents read from it, any `text` the plugin supplies and everything they name -are held to the internet too. +before anything is read. Every request such a command makes connects only to the internet, +wherever its name resolves: the address itself, the requests made from it (a listing, a search, +the next page), those a saved connection sends, and the documents read from it, any `text` the +plugin supplies and everything they name. Use `host::call("host.fetch", json!({"url": url}))` in the Rust SDK, or `host::call("host.fetch", json!({"url": url, "json": false}))` for the text only. From d502a534a8d51901b693e1d29d1caeff021ca751 Mon Sep 17 00:00:00 2001 From: mavrick Date: Tue, 24 Nov 2026 06:49:57 -0600 Subject: [PATCH 3/4] fix(plugins): workers a plugin's command starts are held to the internet too The hold was a thread-local, so the readers a command starts on threads of its own (a Zarr store's chunks, its read-ahead, a data cube's readers) read the requests they derive from the address with the default reach. The hold is now part of the request context those workers already carry on for cancellation (rustgis_data::source::remote::held_still): a context marked held stays held when it is captured, re-entered or combined, and ceiling_for reads it. The AlphaEarth window reader now carries the context on as the other readers do. --- crates/data/src/source/remote.rs | 32 +++++++++++++++++++++- crates/engine/src/cmd/embeddings.rs | 8 +++--- crates/tiles/src/cache.rs | 41 ++++++++++++++++------------- 3 files changed, 58 insertions(+), 23 deletions(-) diff --git a/crates/data/src/source/remote.rs b/crates/data/src/source/remote.rs index 54adb9284e..3e147fba15 100644 --- a/crates/data/src/source/remote.rs +++ b/crates/data/src/source/remote.rs @@ -99,7 +99,11 @@ pub fn with_optional_still(still: Option, f: impl FnOnce() -> T) -> T } let previous = current_still(); let combined = match (previous.clone(), still) { - (Some(a), Some(b)) => Some(std::sync::Arc::new(move || a() && b()) as Still), + (Some(a), Some(b)) => { + let held = is_held_still(&a) || is_held_still(&b); + let both = std::sync::Arc::new(move || a() && b()) as Still; + Some(if held { held_still(both) } else { both }) + } (Some(a), None) => Some(a), (None, b) => b, }; @@ -121,6 +125,32 @@ pub fn with_captured_still(still: Option, f: impl FnOnce() -> T) -> T f() } +/// The request contexts whose requests may reach only the internet ([`held_still`]). +static HELD: std::sync::Mutex bool + Send + Sync>>> = std::sync::Mutex::new(Vec::new()); + +/// Marks `still` as holding its requests to the internet (a plugin's command: plugins reach only +/// the internet). The mark goes wherever the context does: a worker that re-enters it +/// ([`current_still`], [`with_optional_still`], [`with_captured_still`]) is held too, and so is a +/// context it is combined with. +pub fn held_still(still: Still) -> Still { + let mut held = HELD.lock().unwrap_or_else(|e| e.into_inner()); + held.retain(|w| w.strong_count() > 0); + held.push(std::sync::Arc::downgrade(&still)); + still +} + +/// Whether `still` was marked by [`held_still`]. +fn is_held_still(still: &Still) -> bool { + let at = std::sync::Arc::as_ptr(still).cast::<()>(); + HELD.lock().unwrap_or_else(|e| e.into_inner()).iter().any(|w| std::sync::Weak::as_ptr(w).cast::<()>() == at) +} + +/// Whether this thread's requests may reach only the internet: its request context was marked +/// by [`held_still`]. +pub fn requests_held() -> bool { + current_still().is_some_and(|still| is_held_still(&still)) +} + /// Checked immediately before a request-producing stage, without suspension before sending. pub fn check_still(still: &Option) -> std::result::Result<(), String> { if still.as_ref().is_some_and(|s| !s()) { Err("request cancelled before it was sent".into()) } else { Ok(()) } diff --git a/crates/engine/src/cmd/embeddings.rs b/crates/engine/src/cmd/embeddings.rs index a4575436d0..08ca1728b8 100644 --- a/crates/engine/src/cmd/embeddings.rs +++ b/crates/engine/src/cmd/embeddings.rs @@ -808,10 +808,12 @@ fn read_window(url: &str, area: [f64; 4], cell: Option) -> Result = const { std::cell::Cell::new(false) }; -} - -/// Runs `f` with every address this thread asks for in it read only from the internet when `held` -/// (a plugin's command: plugins reach only the internet), whatever is recorded of the address, -/// so the requests a command derives from the address it was given (a listing, a search, a next -/// page) are held as that address is. Nested calls only add to it; it is restored when `f` -/// returns or panics. Requests made later or on another thread follow what is recorded +/// Runs `f` with every address asked for in it read only from the internet when `held` (a +/// plugin's command: plugins reach only the internet), whatever is recorded of the address, so +/// the requests a command derives from the address it was given (a listing, a search, a next +/// page) are held as that address is. The hold is part of the request context +/// ([`rustgis_data::source::remote::held_still`]): the workers that carry the context on, as they +/// carry cancellation, are held too. Requests made later outside it follow what is recorded /// ([`restrict_to_public`]). pub fn held_to_public(held: bool, f: impl FnOnce() -> T) -> T { - /// Puts back the hold from before, however `f` ends. - struct Restore(bool); - impl Drop for Restore { - fn drop(&mut self) { - HELD.with(|h| h.set(self.0)); - } + if !held { + return f(); } - let _restore = Restore(HELD.with(|h| h.replace(h.get() || held))); - f() + let still = rustgis_data::source::remote::held_still(Arc::new(|| true)); + with_optional_still(Some(still), f) } /// The network reach ceiling recorded for `url`: [`crate::address::Reach::Public`] when a web /// document named it, or while this thread's requests are [`held_to_public`], /// [`crate::address::Reach::Local`] otherwise. pub fn ceiling_for(url: &str) -> crate::address::Reach { - if HELD.with(std::cell::Cell::get) { + if rustgis_data::source::remote::requests_held() { return crate::address::Reach::Public; } let base = canonical_resource(url); @@ -7867,6 +7859,17 @@ Connection: close assert_eq!(ceiling_for(&derived), crate::address::Reach::Local); let held = held_to_public(true, || { held_to_public(false, || assert_eq!(ceiling_for(&derived), crate::address::Reach::Public, "nested, still held")); + // A worker carrying the request context on, as readers carry cancellation, is held. + let context = current_still(); + let worker = derived.clone(); + let ceiling = std::thread::scope(|scope| { + std::thread::Builder::new() + .spawn_scoped(scope, move || with_optional_still(context, || ceiling_for(&worker))) + .unwrap() + .join() + .unwrap() + }); + assert_eq!(ceiling, crate::address::Reach::Public, "a worker carrying the context"); download_blocking(&derived) }); let e = held.unwrap_err(); From 78ccd3fcadacb62d1ab239003fd6af204f3ea0d7 Mon Sep 17 00:00:00 2001 From: mavrick Date: Tue, 24 Nov 2026 07:30:30 -0600 Subject: [PATCH 4/4] test(plugins): the plugins-reach-this-computer hook only in test builds The hook that lets other crates' tests point plugins at their local test server came with the engine's testing feature alone. It now also needs debug assertions, so no release build can carry it, whatever enables the feature. --- crates/engine/src/cmd/plugin_fetch.rs | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/crates/engine/src/cmd/plugin_fetch.rs b/crates/engine/src/cmd/plugin_fetch.rs index d361f1b19e..261aec087f 100644 --- a/crates/engine/src/cmd/plugin_fetch.rs +++ b/crates/engine/src/cmd/plugin_fetch.rs @@ -116,7 +116,7 @@ fn cache() -> std::sync::MutexGuard<'static, Cache> { CACHE.lock().unwrap_or_else(|e| e.into_inner()) } -#[cfg(any(test, feature = "testing"))] +#[cfg(any(test, all(feature = "testing", debug_assertions)))] thread_local! { /// Tests: let the plugin fetch from this computer (a test server) and, when `wait` is off, /// fetch as the browser does (pending, then run again). @@ -125,18 +125,19 @@ thread_local! { /// Tests in other crates: lets the plugins this thread runs reach this computer (their test /// server), with `host.fetch` and the addresses they give commands, as the engine's own tests do. -#[cfg(feature = "testing")] +/// Only in a test build: the `testing` feature with debug assertions, never a release build. +#[cfg(all(feature = "testing", debug_assertions))] #[doc(hidden)] pub fn plugins_reach_this_computer() { TEST.with(|t| t.set((true, t.get().1))); } fn allow_local() -> bool { - #[cfg(any(test, feature = "testing"))] + #[cfg(any(test, all(feature = "testing", debug_assertions)))] { TEST.with(|t| t.get().0) } - #[cfg(not(any(test, feature = "testing")))] + #[cfg(not(any(test, all(feature = "testing", debug_assertions))))] { false }