From 8b37d3c53ed69d6df07d532537260f27ae8fac4b Mon Sep 17 00:00:00 2001 From: mavrick Date: Mon, 23 Nov 2026 01:55:30 -0600 Subject: [PATCH 01/10] fix(services): follow what catalogues, portals and WMS identify name within the reach their documents were read at Service discovery's link and layer checks, the tile set walk and a template given to service.add judged a document by how its address is spelled, so a service at a public-looking name on the local network had its local links and layers refused. They now judge by the reach the document was read at. WMS identify asks within the layer's reach: a layer a document read from the internet listed, or whose capabilities were read from there, asks only there, and a refused request is said. Catalogue records, Search Open Data results, Earthaccess granules and geoBoundaries files keep the reach of the answer that listed them, through to the layers added from them (ui.addService takes fromDocument). The Data Sources tree records the service documents it reads. The deprecated IPv6 site-local range fec0::/10 is local; Teredo stays public. --- crates/engine/src/cmd/connection_browse.rs | 90 ++++- crates/engine/src/cmd/portals.rs | 39 ++- crates/engine/src/cmd/select.rs | 62 ++-- crates/engine/src/cmd/select_info.rs | 113 +++++-- crates/engine/src/cmd/service.rs | 362 ++++++++++++++++----- crates/engine/src/tests.rs | 71 +++- crates/engine/src/tests/ogc_dataset.rs | 18 +- crates/tiles/src/address.rs | 27 +- crates/tiles/src/portal.rs | 109 ++++--- crates/ui-egui/src/connectiontree.rs | 56 +++- crates/ui-egui/src/cswui.rs | 66 +++- crates/ui-egui/src/earthaccessui.rs | 79 ++++- crates/ui-egui/src/lib.rs | 39 ++- crates/ui-egui/src/mapview.rs | 72 +++- crates/ui-egui/src/opendataui.rs | 150 ++++++--- crates/ui-egui/src/portalsui.rs | 64 +++- crates/ui-egui/src/serviceui.rs | 147 +++++++-- crates/ui-egui/src/zarrui.rs | 47 ++- 18 files changed, 1283 insertions(+), 328 deletions(-) diff --git a/crates/engine/src/cmd/connection_browse.rs b/crates/engine/src/cmd/connection_browse.rs index e50b07cebc..525b761c7b 100644 --- a/crates/engine/src/cmd/connection_browse.rs +++ b/crates/engine/src/cmd/connection_browse.rs @@ -34,6 +34,9 @@ enum Level { Service { url: String, kind: Option, + /// How far it may reach: the connection's own address is the user's choice; one a + /// catalogue's record links to reaches no further than where that catalogue was read. + reach: address::Reach, }, Catalogue, StacRoot { @@ -73,8 +76,10 @@ fn level(c: &Connection, node: &str, observed: Option<&address::Origin>) -> Resu } Level::Database } - "service" => Level::Service { url: c.address.clone(), kind: None }, - "wms" | "wmts" | "wfs" | "wcs" | "ogcapi" | "arcgis" => Level::Service { url: c.address.clone(), kind: Some(c.kind.clone()) }, + "service" => Level::Service { url: c.address.clone(), kind: None, reach: address::Reach::Local }, + "wms" | "wmts" | "wfs" | "wcs" | "ogcapi" | "arcgis" => { + Level::Service { url: c.address.clone(), kind: Some(c.kind.clone()), reach: address::Reach::Local } + } "csw" => Level::Catalogue, "stac" => Level::StacRoot { api: stac::api(Some(&c.address))? }, "s3" => Level::S3Root, @@ -86,9 +91,12 @@ fn level(c: &Connection, node: &str, observed: Option<&address::Origin>) -> Resu return Err(not_a_node()); } let (t, url) = rest.split_once(':').filter(|(t, _)| SERVICE_TYPES.contains(t)).ok_or_else(not_a_node)?; - // Judged as a document of the connection would be: a link may not lead into the local network. - address::check(url, Some(&c.address))?; - return Ok(Level::Service { url: url.to_string(), kind: (t != "auto").then(|| t.to_string()) }); + // Judged by where the document listing it was read (a catalogue's records, recorded when + // they were browsed), not by how the connection's address is spelled; one not recorded, + // conservatively, as a document at that address would be. + let origin = observed.cloned().unwrap_or_else(|| address::Origin::named(&c.address)); + origin.check(url)?; + return Ok(Level::Service { url: url.to_string(), kind: (t != "auto").then(|| t.to_string()), reach: origin.reach() }); } // A schema's or a geodatabase dataset's name, as `schemas` and `geodatabase_tree` encode it. let named = |encoded: &str| { @@ -169,7 +177,7 @@ fn s3_login(s: &mut Session, c: &Connection, level: &Level) -> Result) -> Result, String> { Ok(match level { Level::Database | Level::DatabaseSchema { .. } | Level::DatabaseDataset { .. } => None, - Level::Service { url, kind } => Some(rustgis_data::ogc::capabilities_url(url, kind.as_deref())), + Level::Service { url, kind, .. } => Some(rustgis_data::ogc::capabilities_url(url, kind.as_deref())), Level::Catalogue => Some(super::super::service::records_request(s, &json!({"url": c.address}))?), Level::StacRoot { api } => Some(if stac::catalog::is_static(api) { api.clone() } else { stac::collections_url(api) }), Level::StacCollection { api, id } => { @@ -242,6 +250,7 @@ pub(super) fn browse(s: &mut Session, p: &Value) -> CmdResult { let level = level(&c, node, observed.as_ref())?; let ceiling = match &level { Level::StacCatalog { origin, .. } | Level::StacItem { origin, .. } => origin.reach(), + Level::Service { reach, .. } => *reach, _ => address::Reach::Local, }; let conn = s3_login(s, &c, &level)?; @@ -267,7 +276,7 @@ pub(super) fn browse(s: &mut Session, p: &Value) -> CmdResult { Level::Database => database_schemas(s, &c, &mut out)?, Level::DatabaseSchema { schema } => database_schema(s, &c, schema, &mut out)?, Level::DatabaseDataset { dataset } => database_dataset(s, &c, dataset, &mut out)?, - Level::Service { url, kind } => service(s, p, &mut out, &c, url, kind.as_deref())?, + Level::Service { url, kind, .. } => service(s, p, &mut out, &c, url, kind.as_deref())?, Level::S3Root if url.is_none() => { buckets(c.options.get("buckets").map(String::as_str).unwrap_or("").split(',').map(str::to_string)) } @@ -288,7 +297,7 @@ pub(super) fn browse(s: &mut Session, p: &Value) -> CmdResult { }; let bytes = text.as_bytes(); let found = match &level { - Level::Catalogue => catalogue(s, &c, &text, &mut out)?, + Level::Catalogue => catalogue(s, &c, &text, &origin, node.is_empty(), &mut out)?, Level::StacRoot { api } if stac::catalog::is_static(api) => catalogs(s, bytes, &origin)?, Level::StacRoot { .. } => collections(bytes)?, Level::StacCatalog { .. } => catalogs(s, bytes, &origin)?, @@ -674,10 +683,17 @@ fn service(s: &mut Session, p: &Value, out: &mut Value, c: &Connection, url: &st Ok(found) } -/// A catalogue's records, each with the services and files it links to. -fn catalogue(s: &mut Session, c: &Connection, text: &str, out: &mut Value) -> Result { +/// A catalogue's records, each with the services and files it links to, read at `origin`: what +/// they link to reaches no further than that, the services when they are opened ([`level`]) and +/// the files when they are added (`fromDocument`). +fn catalogue(s: &mut Session, c: &Connection, text: &str, origin: &address::Origin, root: bool, out: &mut Value) -> Result { let url = crate::service_logins::request(s, Some(&c.id), &c.address)?; - let r = super::super::service::catalog_search(s, &json!({"url": url, "connection": c.id, "text": text}))?; + let params = json!({"url": url, "connection": c.id, "text": text}); + // `catalog.search` judges the answer by its address's record. + if origin.reach() == address::Reach::Public { + crate::render::rustgis_tiles::cache::restrict_to_public(&super::super::service::records_request(s, ¶ms)?); + } + let r = super::super::service::catalog_search(s, ¶ms)?; if let Some(n) = r.get("notes") { out["notes"] = n.clone(); } @@ -713,11 +729,15 @@ fn catalogue(s: &mut Session, c: &Connection, text: &str, out: &mut Value) -> Re let last = url.split(['?', '#']).next().unwrap_or("").trim_end_matches('/').rsplit('/').next().unwrap_or(""); let shown: String = if name.is_empty() { last } else { name.as_str() }.chars().take(200).collect(); let named: String = title.chars().take(200).collect(); + let mut params = json!({"url": url, "name": named}); + if l.get("fromDocument").and_then(Value::as_bool) == Some(true) { + params["fromDocument"] = json!(true); + } Some(json!({ "key": url, "name": shown, "what": "download", - "add": {"command": "layer.addUrl", "params": {"url": url, "name": named}}, + "add": {"command": "layer.addUrl", "params": params}, })) } _ => None, @@ -731,6 +751,10 @@ fn catalogue(s: &mut Session, c: &Connection, text: &str, out: &mut Value) -> Re let mut found = Found::new(children); found.matched = r.get("matched").and_then(Value::as_u64); found.truncated |= dropped || r.get("next").is_some_and(|n| !n.is_null()); + // The services the records link to, opened later, keep where the records were read. + let services: Vec = + found.children.iter().filter_map(|r| r.get("children")).filter_map(Value::as_array).flatten().cloned().collect(); + remember_node_origins(s, c, &services, origin, root)?; Ok(found) } @@ -1063,6 +1087,48 @@ mod tests { } } } + /// A catalogue connection's records are judged by where its answer was read, and what they link + /// to keeps that: a catalogue at a public-looking name read on the local network keeps a + /// service on a private address and opens it as the user's own; one read from the internet + /// leaves that out, opens the service it keeps only from the internet, and has its files added + /// the same way (`fromDocument`). + #[test] + fn a_catalogue_connections_links_keep_where_its_answer_was_read() { + use crate::render::rustgis_tiles::address::Origin; + for (n, peer) in [(1, "10.0.0.5"), (2, "93.184.216.34")] { + let public = n == 2; + let mut session = crate::Session::new(crate::Project::default()); + let address = format!("https://csw-{n}.corp-looks-public.example/csw"); + let saved = session.run("connection.new", &json!({"kind":"csw","address":address})).unwrap(); + let connection = session.connections.connections.iter().find(|c| c.id == saved["id"].as_str().unwrap()).unwrap().clone(); + let (local, web, file) = ( + format!("http://10.0.{n}.4/wms"), + format!("https://csw-wms-{n}.example/wms"), + format!("https://csw-files-{n}.example/a.geojson"), + ); + let text = format!( + r#"aRoads{local}{web}{file}"# + ); + let origin = Origin::connected(&connection.address, peer.parse().unwrap()).unwrap(); + let mut out = json!({}); + let found = super::catalogue(&mut session, &connection, &text, &origin, true, &mut out).unwrap(); + let links = found.children[0]["children"].as_array().cloned().unwrap_or_default(); + let nodes: Vec<_> = links.iter().filter_map(|l| l["node"].as_str().map(str::to_string)).collect(); + let want = if public { + vec![format!("service:wms:{web}")] + } else { + vec![format!("service:wms:{local}"), format!("service:wms:{web}")] + }; + assert_eq!(nodes, want, "{links:?}"); + for node in &nodes { + let probe = super::browse(&mut session, &json!({"id":connection.id,"node":node,"probe":true})).unwrap(); + assert_eq!(probe.get("fromDocument").and_then(Value::as_bool).unwrap_or(false), public, "{node}: {probe}"); + } + let download = links.iter().find(|l| l["what"] == "download").unwrap(); + assert_eq!(download["add"]["params"].get("fromDocument").and_then(Value::as_bool).unwrap_or(false), public, "{download}"); + } + } + #[test] fn admitted_intranet_nodes_keep_their_origin_and_cannot_be_granted_by_json() { use crate::render::rustgis_tiles::address::Origin; diff --git a/crates/engine/src/cmd/portals.rs b/crates/engine/src/cmd/portals.rs index 27ec86455c..8425f47896 100644 --- a/crates/engine/src/cmd/portals.rs +++ b/crates/engine/src/cmd/portals.rs @@ -63,7 +63,7 @@ fn osm_download(s: &mut Session, p: &Value) -> CmdResult { let url = q.url(ps(p, "url"))?; let bytes = match ps(p, "answer") { Some(a) => a.as_bytes().to_vec(), - None => fetch(&url)?, + None => fetch(&url)?.0, }; let answer = overpass::parse(&bytes)?; let name = ps(p, "name").map(str::trim).filter(|n| !n.is_empty()).map(str::to_string).unwrap_or_else(|| q.title()); @@ -92,8 +92,10 @@ fn boundaries_add(s: &mut Session, p: &Value) -> CmdResult { let (text, title) = match ps(p, "text") { Some(t) => (t.to_string(), None), None => { - let meta = boundaries::parse_meta(&fetch(&boundaries::meta_url(&country, &level))?)?; - let bytes = fetch(&meta.geojson)?; + let (meta, reach) = fetch(&boundaries::meta_url(&country, &level))?; + let meta = boundaries::parse_meta(&meta)?; + // The answer names where the boundaries are: they are read no further than it was. + let (bytes, _) = fetch_within(&meta.geojson, reach)?; (String::from_utf8(bytes).map_err(|_| "the boundaries aren't UTF-8 text".to_string())?, Some(meta.name)) } }; @@ -113,7 +115,7 @@ fn boundaries_add(s: &mut Session, p: &Value) -> CmdResult { } fn boundaries_countries(_s: &mut Session, _p: &Value) -> CmdResult { - let list = boundaries::parse_countries(&fetch(&boundaries::countries_url())?)?; + let list = boundaries::parse_countries(&fetch(&boundaries::countries_url())?.0)?; Ok(json!({"count": list.len(), "countries": list.iter().map(|(iso, name)| json!({"iso": iso, "name": name})).collect::>()})) } @@ -155,7 +157,8 @@ pub fn dataset_json(d: &portal::Dataset) -> Value { fn portal_search(s: &mut Session, p: &Value) -> CmdResult { let (portal, query, area, limit) = portal_query(s, p)?; let url = portal.search_url(&query, area, limit); - let found = portal.parse(&url, &fetch(&url)?, area, &query)?; + let (bytes, reach) = fetch(&url)?; + let found = portal.parse(reach, &bytes, area, &query)?; Ok(json!({"portal": portal.label(), "count": found.len(), "datasets": found.iter().map(dataset_json).collect::>()})) } @@ -170,7 +173,8 @@ pub fn files_query(p: &Value) -> Result<(Portal, String), String> { fn portal_files(_s: &mut Session, p: &Value) -> CmdResult { let (portal, url) = files_query(p)?; - let files = portal.parse_listing(&url, &fetch(&url)?)?; + let (bytes, reach) = fetch(&url)?; + let files = portal.parse_listing(&url, reach, &bytes)?; let list: Vec = files .iter() .map(|r| match &r.using { @@ -251,10 +255,22 @@ fn first_layer(s: &mut Session, url: &str, kind: &str) -> Result } /// A fetch the command waits for (the command line and the assistant; the app fetches off the -/// frame and passes the answer). +/// frame and passes the answer), with the reach it was read at: the addresses the answer gives are +/// judged by it. +fn fetch(url: &str) -> Result<(Vec, crate::render::rustgis_tiles::address::Reach), String> { + fetch_within(url, crate::render::rustgis_tiles::address::Reach::Local) +} + +/// [`fetch`], connecting no wider than `ceiling` (the reach of the answer that named `url`). #[cfg(not(target_arch = "wasm32"))] -fn fetch(url: &str) -> Result, String> { - crate::render::rustgis_tiles::cache::download_blocking(url).map_err(|e| { +fn fetch_within( + url: &str, + ceiling: crate::render::rustgis_tiles::address::Reach, +) -> Result<(Vec, crate::render::rustgis_tiles::address::Reach), String> { + use crate::render::rustgis_tiles::cache; + let fetched = cache::download_blocking_with_origin_within(url, cache::MAX_DOWNLOAD, cache::BLOCKING_TIMEOUT, &[], ceiling) + .map_err(cache::large_file_hint); + fetched.map(|f| (f.bytes, f.origin.reach())).map_err(|e| { if e.contains("timeout") || e.contains("timed out") { "the server didn't answer within a minute (it may be busy): try again later, or a smaller area".to_string() } else if e.contains("504") || e.contains("429") { @@ -266,7 +282,10 @@ fn fetch(url: &str) -> Result, String> { } #[cfg(target_arch = "wasm32")] -fn fetch(_url: &str) -> Result, String> { +fn fetch_within( + _url: &str, + _: crate::render::rustgis_tiles::address::Reach, +) -> Result<(Vec, crate::render::rustgis_tiles::address::Reach), String> { Err("in the web app, use Home › Add › Web Data › OpenStreetMap…, Boundaries… or Search Open Data…".into()) } diff --git a/crates/engine/src/cmd/select.rs b/crates/engine/src/cmd/select.rs index e39cb0f505..173686320c 100644 --- a/crates/engine/src/cmd/select.rs +++ b/crates/engine/src/cmd/select.rs @@ -428,38 +428,46 @@ fn identify(s: &mut Session, p: &Value) -> CmdResult { // all the map's layers, as all were before #808, isn't asked over what they found). let over_top = |i: usize| map.tiles.get(i).is_some_and(|t| t.over.is_some()) && top.is_some_and(|top| place(rustgis_map::Drawn::Tile(i)) < top); - let asks = if web && (!first_layer || results.is_empty() || info::topmost(s, lon, lat).is_some_and(over_top)) { + let (asks, refused) = if web && (!first_layer || results.is_empty() || info::topmost(s, lon, lat).is_some_and(over_top)) { info::requests(s, lon, lat, first_layer, picked) } else { - Vec::new() + (Vec::new(), None) }; - let mut out = match results.first().cloned() { - Some(first) => first, - // Only the tile layer picked is asked, not a raster's pixel. - None if picked.is_some() && asks.is_empty() => return Ok(Value::Null), - None if picked.is_some() => json!({}), - // Nothing found (Topmost and Visible looked at the rasters already): Selectable and - // Selected in Layers report the pixel of the topmost raster instead. - None if mode == PopupMode::SelectedInContents && active.and_then(|id| map.layer(id)).is_some_and(|l| !l.is_raster()) => { - return Ok(Value::Null); - } - // (Topmost and Visible found no pixel either: no raster has one there.) - None => match if matches!(mode, PopupMode::Topmost | PopupMode::Visible) { None } else { super::raster::identify(s, lon, lat) } { - Some(pixel) => pixel, - None if asks.is_empty() => return Ok(Value::Null), - None => json!({}), - }, - }; - if let Value::Object(o) = &mut out { - // A raster's pixel found alone answers as before, without a list. - if results.len() > 1 || results.first().is_some_and(|r| r["raster"] != true) { - o.insert("results".into(), Value::Array(results)); - } - if !asks.is_empty() { - o.insert("featureInfo".into(), Value::Array(asks)); + let out = (|| -> CmdResult { + let mut out = match results.first().cloned() { + Some(first) => first, + // Only the tile layer picked is asked, not a raster's pixel. + None if picked.is_some() && asks.is_empty() => return Ok(Value::Null), + None if picked.is_some() => json!({}), + // Nothing found (Topmost and Visible looked at the rasters already): Selectable and + // Selected in Layers report the pixel of the topmost raster instead. + None if mode == PopupMode::SelectedInContents && active.and_then(|id| map.layer(id)).is_some_and(|l| !l.is_raster()) => { + return Ok(Value::Null); + } + // (Topmost and Visible found no pixel either: no raster has one there.) + None => match if matches!(mode, PopupMode::Topmost | PopupMode::Visible) { None } else { super::raster::identify(s, lon, lat) } + { + Some(pixel) => pixel, + None if asks.is_empty() => return Ok(Value::Null), + None => json!({}), + }, + }; + if let Value::Object(o) = &mut out { + // A raster's pixel found alone answers as before, without a list. + if results.len() > 1 || results.first().is_some_and(|r| r["raster"] != true) { + o.insert("results".into(), Value::Array(results)); + } + if !asks.is_empty() { + o.insert("featureInfo".into(), Value::Array(asks)); + } } + Ok(out) + })(); + // A WMS layer whose request reaches past it isn't asked, and says so. + if let Some(notice) = refused { + s.notify(notice, false); } - Ok(out) + out } /// Whether identify lists a tile layer's features: archives, vector tiles and overlays added as diff --git a/crates/engine/src/cmd/select_info.rs b/crates/engine/src/cmd/select_info.rs index dbfe373f3f..d283a385cd 100644 --- a/crates/engine/src/cmd/select_info.rs +++ b/crates/engine/src/cmd/select_info.rs @@ -5,6 +5,10 @@ //! //! A layer added from the service knows its request from the capabilities; one from a project //! (which doesn't keep it) is asked for its service's capabilities first. +//! +//! Both requests are made within the layer's reach ([`reach_of`]): a layer a document read from +//! the internet listed, or whose capabilities were read from there, asks only there, however the +//! service's names resolve; the listed requests say so (`"public": true`) for the app's fetch. use rustgis_data::ogc::{self, FeatureInfo, InfoFeature}; use rustgis_geom::Coord; @@ -12,6 +16,7 @@ use rustgis_map::tiles::TileKind; use serde_json::{Value, json}; use super::super::{b, f, ps}; +use crate::render::rustgis_tiles::{address::Reach, cache}; use crate::{CmdResult, CommandSpec as C, Session}; /// Most WMS layers one identify asks. @@ -61,44 +66,69 @@ fn askable(t: &rustgis_map::tiles::TileLayer, picked: bool) -> bool { } } +/// How far a WMS tile layer's identify requests may reach: only the internet when its template is +/// held there (a document read from the internet listed the layer) or its capabilities were read +/// from there ([`cache::ceiling_for`] records both), else as far as the user's own address. +fn reach_of(t: &rustgis_map::tiles::TileLayer) -> Reach { + let caps = ogc::wms_layer_of(&t.url).map_or(Reach::Local, |(caps, _)| cache::ceiling_for(&caps)); + cache::ceiling_for(&t.url).min(caps) +} + /// What to fetch to ask a WMS tile layer about a point: the GetFeatureInfo request, or the -/// service's capabilities when the layer doesn't know it. `None` when it can't be asked there. -fn next_fetch(t: &rustgis_map::tiles::TileLayer, lon: f64, lat: f64, at: Coord, m_per_px: f64) -> Option { +/// service's capabilities when the layer doesn't know it. `None` when it can't be asked there; +/// an error, naming the address and why, when what it would ask reaches past the layer. +fn next_fetch(t: &rustgis_map::tiles::TileLayer, lon: f64, lat: f64, at: Coord, m_per_px: f64) -> Option> { if t.bounds.is_some_and(|[w, s, e, n]| !(w <= lon && lon <= e && s <= lat && lat <= n)) { return None; } match &t.feature_info { Some(fi) => ask(t, fi, at, m_per_px), // The capabilities address comes from the layer's template (a project's, untrusted too). - None => ogc::wms_layer_of(&t.url) - .filter(|(caps, _)| crate::render::rustgis_tiles::address::check(caps, Some(&t.url)).is_ok()) - .map(|(caps, _)| json!({"tileLayer": t.name, "capabilities": caps})), + None => ogc::wms_layer_of(&t.url).map(|(caps, _)| fetch_value(t, "capabilities", caps)), } } /// A WMS tile layer's GetFeatureInfo request for a point, in `fi`'s terms. -fn ask(t: &rustgis_map::tiles::TileLayer, fi: &FeatureInfo, at: Coord, m_per_px: f64) -> Option { - // The request's address comes from the capabilities (hostile input): it must not reach into - // the local network from a service on the web. - // At the time the layer draws (a WMS layer with a time dimension). - fi.request(at.x, at.y, m_per_px) - .map(|url| ogc::at_map_time(url, &t.url)) - .filter(|url| crate::render::rustgis_tiles::address::check(url, Some(&t.url)).is_ok()) - .map(|url| json!({"tileLayer": t.name, "url": url})) +fn ask(t: &rustgis_map::tiles::TileLayer, fi: &FeatureInfo, at: Coord, m_per_px: f64) -> Option> { + // The request's address comes from the capabilities (hostile input): it must not reach past + // the layer's reach. At the time the layer draws (a WMS layer with a time dimension). + fi.request(at.x, at.y, m_per_px).map(|url| ogc::at_map_time(url, &t.url)).map(|url| fetch_value(t, "url", url)) +} + +/// What identify lists for a layer to fetch (`key`: `url` or `capabilities`), when `url` is within +/// the layer's reach ([`reach_of`]), with `"public"` when that is only the internet; otherwise why +/// not, naming the address. +fn fetch_value(t: &rustgis_map::tiles::TileLayer, key: &str, url: String) -> Result { + let reach = reach_of(t); + crate::render::rustgis_tiles::address::check_reach(&url, reach)?; + let mut out = json!({"tileLayer": t.name, key: url}); + if reach == Reach::Public { + out["public"] = json!(true); + } + Ok(out) } /// The WMS tile layers drawn at a point to ask what is there, topmost first as drawn (a higher -/// depth priority on top, #2488; only the topmost when `first_layer`), each with what to fetch. -pub(super) fn requests(s: &Session, lon: f64, lat: f64, first_layer: bool, picked: Option) -> Vec { - let Some((at, m_per_px)) = merc_at(s, lon, lat) else { return Vec::new() }; +/// depth priority on top, #2488; only the topmost when `first_layer`), each with what to fetch; +/// and the notice for those whose request was refused (it reaches past the layer), naming the +/// first of them, its address and why. +pub(super) fn requests(s: &Session, lon: f64, lat: f64, first_layer: bool, picked: Option) -> (Vec, Option) { + let Some((at, m_per_px)) = merc_at(s, lon, lat) else { return (Vec::new(), None) }; let wanted = if first_layer { 1 } else { MAX_ASKED }; let map = s.map(); + let mut refused = Vec::new(); let mut asks: Vec = map .tiles_in_draw_order() .into_iter() .filter_map(|i| Some((i, map.tiles.get(i)?))) .filter(|(i, t)| picked.is_none_or(|p| p == *i) && askable(t, picked.is_some())) - .filter_map(|(_, t)| next_fetch(t, lon, lat, at, m_per_px)) + .filter_map(|(_, t)| match next_fetch(t, lon, lat, at, m_per_px)? { + Ok(ask) => Some(ask), + Err(e) => { + refused.push((t.name.clone(), e)); + None + } + }) .take(wanted) .collect(); if !s.policy_user() { @@ -106,7 +136,11 @@ pub(super) fn requests(s: &Session, lon: f64, lat: f64, first_layer: bool, picke crate::sources::redact_url_fields(ask); } } - asks + let notice = refused.first().map(|(layer, e)| match refused.len() { + 1 => format!("{layer} wasn't asked what is here: {e}"), + n => format!("{n} WMS layers weren't asked what is here, such as {layer}: {e}"), + }); + (asks, notice) } /// The index of the topmost WMS tile layer, as drawn, that can be asked what is at a point (it @@ -116,7 +150,7 @@ pub(super) fn topmost(s: &Session, lon: f64, lat: f64) -> Option { let map = s.map(); map.tiles_in_draw_order() .into_iter() - .find(|i| map.tiles.get(*i).is_some_and(|t| askable(t, false) && next_fetch(t, lon, lat, at, m_per_px).is_some())) + .find(|i| map.tiles.get(*i).is_some_and(|t| askable(t, false) && next_fetch(t, lon, lat, at, m_per_px).is_some_and(|r| r.is_ok()))) } /// The answer's features as identify's results. @@ -206,11 +240,14 @@ fn feature_info(s: &mut Session, p: &Value) -> CmdResult { _ => None, }; if !s.policy_user() - && let Some(out) = &mut retry + && let Some(Ok(out)) = &mut retry { crate::sources::redact_url_fields(out); } - retry.ok_or_else(|| named(e)) + match retry { + Some(next) => next.map_err(named), + None => Err(named(e)), + } } }; } @@ -220,7 +257,7 @@ fn feature_info(s: &mut Session, p: &Value) -> CmdResult { let next = |s: &Session| s.map().tiles.get(index).and_then(|t| next_fetch(t, lon, lat, at, m_per_px)); if b(p, "request") == Some(true) { // Nothing to ask (not queryable, or outside the layer): no results. - let mut out = next(s).unwrap_or_else(|| json!({"results": []})); + let mut out = next(s).transpose().map_err(named)?.unwrap_or_else(|| json!({"results": []})); if !s.policy_user() { crate::sources::redact_url_fields(&mut out); } @@ -233,27 +270,39 @@ fn feature_info(s: &mut Session, p: &Value) -> CmdResult { } #[cfg(not(target_arch = "wasm32"))] { - let fetch = |url: &str| { - crate::render::rustgis_tiles::cache::download_blocking_limited(url, ogc::MAX_INFO_BYTES).map_err(|e| format!("{name}: {e}")) + // Within the layer's reach, which the listed step says. + let fetch = |step: &Value, url: &str| { + let ceiling = if step["public"] == true { Reach::Public } else { Reach::Local }; + cache::download_blocking_with_origin_within(url, ogc::MAX_INFO_BYTES, cache::BLOCKING_TIMEOUT, &[], ceiling) + .map_err(cache::large_file_hint) + .map_err(|e| format!("{name}: {e}")) }; - let mut step = next(s); - if let Some(caps) = step.as_ref().and_then(|v| v["capabilities"].as_str()).map(str::to_string) { - learn(s, index, &fetch(&caps)?).map_err(named)?; - step = next(s); + let mut step = next(s).transpose().map_err(named)?; + if let Some(v) = &step + && let Some(caps) = v["capabilities"].as_str() + { + let fetched = fetch(v, caps)?; + // Capabilities read from the internet hold the requests they name there. + if fetched.origin.reach() == Reach::Public { + cache::restrict_to_public(caps); + } + learn(s, index, &fetched.bytes).map_err(named)?; + step = next(s).transpose().map_err(named)?; } // Each of the service's errors asks in a format read after the last, so this ends. loop { - let Some(url) = step.as_ref().and_then(|v| v["url"].as_str()).map(str::to_string) else { + let Some(v) = step.as_ref() else { return Ok(json!({"results": []})) }; + let Some(url) = v["url"].as_str().map(str::to_string) else { return Ok(json!({"results": []})); }; - let answer = fetch(&url)?; + let answer = fetch(v, &url)?.bytes; match ogc::read_feature_info(&answer) { Ok(features) => { answered(s, index, &url); return Ok(results(&name, features)); } Err(e) => match retry(s, index, &url, lon, lat, at, m_per_px) { - Some(next) if ogc::may_answer_in_another_format(&answer) => step = Some(next), + Some(next) if ogc::may_answer_in_another_format(&answer) => step = Some(next.map_err(named)?), _ => return Err(named(e)), }, } @@ -263,7 +312,7 @@ fn feature_info(s: &mut Session, p: &Value) -> CmdResult { /// After the service answered `request` with its error: the request in the next answer format /// the layer offers, when there is one. The layer keeps its own until another format answers. -fn retry(s: &Session, index: usize, request: &str, lon: f64, lat: f64, at: Coord, m_per_px: f64) -> Option { +fn retry(s: &Session, index: usize, request: &str, lon: f64, lat: f64, at: Coord, m_per_px: f64) -> Option> { let t = s.map().tiles.get(index)?; if t.bounds.is_some_and(|[w, s, e, n]| !(w <= lon && lon <= e && s <= lat && lat <= n)) { return None; diff --git a/crates/engine/src/cmd/service.rs b/crates/engine/src/cmd/service.rs index f07598500c..2f393c4108 100644 --- a/crates/engine/src/cmd/service.rs +++ b/crates/engine/src/cmd/service.rs @@ -41,7 +41,7 @@ pub fn commands() -> Vec { r#"{"url": "a WCS address", "type"?: "wcs", "layer": "the coverage's name", "text"?: "the capabilities document, when already fetched", "documents"?: "additional fetched documents, as service.layers", "source_url"?: "the listed coverage's source_url", "describe"?: "its DescribeCoverage answer, when already fetched", "bbox"?: [west, south, east, north] | "view" (the default) | "full", "connection"?: "the saved web-service connection id whose login the request uses", "anonymous"?: boolean (never use a saved login for the coverage or its description)} → the GetCoverage address of a GeoTIFF (layer.addUrl adds it)"#, ), C::new("catalog.search", "Search Catalogue", "Home › Add", catalog_search).roles(&[]).effects(crate::policy::Effects::NONE.with(crate::policy::Effect::Network)).view().params( - r#"{"url": "a catalogue's CSW address", "query"?: "words anywhere in the records", "bbox"?: [west, south, east, north] | "view" (none by default), "start"?: "the first record's position (a page's next)", "text"?: "the GetRecords answer, when already fetched", "connection"?: "as service.layers"} → records with their service and download links (service.add or layer.addUrl add them)"#, + r#"{"url": "a catalogue's CSW address", "query"?: "words anywhere in the records", "bbox"?: [west, south, east, north] | "view" (none by default), "start"?: "the first record's position (a page's next)", "text"?: "the GetRecords answer, when already fetched", "connection"?: "as service.layers"} → records with their service and download links (service.add or layer.addUrl add them; a link with "fromDocument": true came from a catalogue read from the internet: give layer.addUrl that too)"#, ), ]; commands.extend(group::commands()); @@ -289,15 +289,19 @@ fn read_documents_with( loop { rustgis_data::progress::check().map_err(|e| e.to_string())?; let crossed_origin = histories.get(&parent).copied().unwrap_or(false) || crosses_origin(&parent, &address); - // The service's own address is the user's choice; a linked one inherits its document's - // reach (a document not recorded, which can't happen, reaches only the internet). + // The service's own address is the user's choice, unless a document read from the + // internet named it (a catalogue's record: [`cache::ceiling_for`] holds it there); a linked + // one inherits its document's reach (a document not recorded, which can't happen, reaches + // only the internet). Either is judged by that reach, never by how the document's address + // is spelled: a public-looking name may connect on the local network, and its local links + // are then the service's own. let inherited = if seen.is_empty() { - Reach::Local + cache::ceiling_for(original) } else { reaches.get(crate::render::rustgis_tiles::logins::inner(&parent)).copied().unwrap_or(Reach::Public) }; let ceiling = inherited.min(cache::ceiling_for(&address)); - let rejected = match crate::render::rustgis_tiles::address::check(&address, Some(&parent)) { + let rejected = match crate::render::rustgis_tiles::address::check_reach(&address, ceiling) { Ok(()) => false, Err(_) if dataset_document => true, Err(e) => return result.failed(s, e, dataset.as_ref()), @@ -309,7 +313,8 @@ fn read_documents_with( if seen.len() >= MAX_SERVICE_DOCUMENTS { return result.failed(s, "the service discovery exceeds 32 documents".into(), dataset.as_ref()); } - let mut parse = |bytes: &[u8]| { + // `reach`: where the document was read, which the addresses it names are judged by. + let mut parse = |bytes: &[u8], reach: Reach| { if dataset_document { dataset_bytes = dataset_bytes.saturating_add(bytes.len()); if dataset_bytes > MAX_DATASET_BYTES { @@ -318,7 +323,7 @@ fn read_documents_with( dataset .as_mut() .ok_or_else(|| "missing dataset discovery plan".to_string())? - .read(bytes, |template, from| crate::render::rustgis_tiles::address::check(template, Some(from)).is_ok()) + .read(bytes, |template, _| crate::render::rustgis_tiles::address::check_reach(template, reach).is_ok()) } else { rustgis_data::ogc::parse(&address, bytes) } @@ -346,14 +351,14 @@ fn read_documents_with( result.dataset_notes(dataset.as_ref()); return Ok(result); }; - parse(text.as_bytes()) + parse(text.as_bytes(), ceiling) } else if left { let Some(read) = s.left_document(&address).map_err(|e| crate::sources::message_with_address(original, &e))? else { result.next = Some(address); result.dataset_notes(dataset.as_ref()); return Ok(result); }; - read.and_then(|bytes| parse(&bytes)) + read.and_then(|bytes| parse(&bytes, ceiling)) } else { fetch(&address, ceiling) .map(|fetched| { @@ -363,10 +368,10 @@ fn read_documents_with( if observed == Some(Reach::Public) { cache::restrict_to_public(&address); } - fetched.bytes + (fetched.bytes, fetched.origin.reach()) }) .map_err(|e| crate::sources::message_with_address(original, &e)) - .and_then(|bytes| parse(&bytes)) + .and_then(|(bytes, reach)| parse(&bytes, reach)) }; // Natively, where the fetch connected; otherwise what the app's fetch was held to. let reach = observed.unwrap_or(ceiling); @@ -375,7 +380,7 @@ fn read_documents_with( Ok(s) => { let before = s.layers.len(); result.incomplete |= s.incomplete; - let vetted = vet(s, &address); + let vetted = vet(s, reach); result.excluded_layers |= vetted.layers.len() != before; vetted } @@ -386,7 +391,7 @@ fn read_documents_with( let hint = explicit_map.filter(|(_, source)| source.is_none_or(|source| same_address(source, &address))).map(|(tiles, _)| tiles); let explicit = if let Some(template) = hint { - let template = match checked_template(&address, template) { + let template = match checked_template(reach, template) { Ok(template) => template, Err(error) => { result.service.withheld_addresses = result.service.withheld_addresses.saturating_add(service.withheld_addresses); @@ -484,8 +489,10 @@ fn fetch_document(url: &str, ceiling: Reach) -> Result { /// Leaves out the layers whose addresses a document on the web may not send RustGIS to: the /// capabilities are hostile input, and their endpoints and links must not reach into the local -/// network (unless the service itself is there) or a forbidden address. -fn vet(mut svc: Service, caps: &str) -> Service { +/// network (unless the service itself is there) or a forbidden address. `reach` is where the +/// capabilities were read, as their fetch observed it: a service at a public-looking name that +/// connected on the local network keeps its local layers. +fn vet(mut svc: Service, reach: Reach) -> Service { let before = svc.layers.len(); svc.layers.retain(|l| { let u = match &l.offer { @@ -493,7 +500,7 @@ fn vet(mut svc: Service, caps: &str) -> Service { Offer::Features { url } | Offer::Style { url } | Offer::Service { url } => url, Offer::Coverage(Coverage { endpoint, .. }) => endpoint, }; - crate::render::rustgis_tiles::address::check(u, Some(caps)).is_ok() + crate::render::rustgis_tiles::address::check_reach(u, reach).is_ok() }); let dropped = before - svc.layers.len(); if dropped > 0 { @@ -746,13 +753,13 @@ fn download_layer_with( } /// A tile template given for a service's layer: a web address with `{z}`, `{x}` and `{y}`, that -/// the service's document may point to. -fn checked_template(service: &str, t: &str) -> Result { +/// a document read within `reach` (as its fetch observed it) may point to. +fn checked_template(reach: Reach, t: &str) -> Result { let t = t.trim(); if !(t.contains("{z}") && t.contains("{x}") && t.contains("{y}")) || t.len() > 2000 { return Err(crate::sources::message_with_address(t, "not a tile template")); } - crate::render::rustgis_tiles::address::check(t, Some(service))?; + crate::render::rustgis_tiles::address::check_reach(t, reach)?; // The resolver already chose the destination's login, including its absence after a // foreign hop. The original service is only the address-policy context here. Ok(t.to_string()) @@ -781,15 +788,12 @@ fn crosses_origin(from: &str, to: &str) -> bool { /// read from the internet), as their fetches observed it. #[cfg(not(target_arch = "wasm32"))] fn advertised_template(source: &str, list: &str, vector: bool, withheld: &mut u32, public: bool) -> AdvertisedTemplate { - let mut reach = if public { Reach::Public } else { Reach::Local }; - let mut out = advertised_template_with(source, list, vector, withheld, |doc| { + let reach = if public { Reach::Public } else { Reach::Local }; + advertised_template_with(source, list, vector, withheld, reach, |doc, reach| { let fetched = cache::download_blocking_with_origin_within(doc, cache::MAX_DOWNLOAD, cache::BLOCKING_TIMEOUT, &[], reach) .map_err(cache::large_file_hint)?; - reach = reach.min(fetched.origin.reach()); - Ok(fetched.bytes) - }); - out.public = reach == Reach::Public; - out + Ok((fetched.bytes, fetched.origin.reach())) + }) } /// Resolves at most two advertised documents while retaining every foreign hop, even on failure. @@ -799,38 +803,50 @@ fn advertised_template_with( list: &str, vector: bool, withheld: &mut u32, - mut read: impl FnMut(&str) -> Result, String>, + reach: Reach, + mut read: impl FnMut(&str, Reach) -> Result<(Vec, Reach), String>, ) -> AdvertisedTemplate { - let read = |doc: &str| Ok::<_, std::convert::Infallible>(read(doc).map_err(|e| crate::sources::message_with_address(doc, &e))); - match walk_template(source, list, vector, withheld, read) { + let read = + |doc: &str, reach| Ok::<_, std::convert::Infallible>(read(doc, reach).map_err(|e| crate::sources::message_with_address(doc, &e))); + match walk_template(source, list, vector, withheld, reach, read) { Ok(out) => out, Err(never) => match never {}, } } /// The walk [`advertised_template_with`] and [`left_template`] share: at most two documents from -/// `list`, each read by `read` (its body, or why it couldn't be read; `Err` stops the walk), keeping -/// every foreign hop and counting the addresses whose query was withheld. A fallback to the -/// standard tile address comes back as the notice to give, in `fallback`. +/// `list`, each read by `read` within the reach of the document before it (the service's, `reach`, +/// first), giving its body and the reach it was read at, or why it couldn't be read (`Err` stops +/// the walk), keeping every foreign hop and counting the addresses whose query was withheld. Each +/// address a document names is judged by where that document was read, never by how its address +/// is spelled, and `public` says the walk ended at the internet. A fallback to the standard tile +/// address comes back as the notice to give, in `fallback`. fn walk_template, E>( source: &str, list: &str, vector: bool, withheld: &mut u32, - mut read: impl FnMut(&str) -> Result, E>, + reach: Reach, + mut read: impl FnMut(&str, Reach) -> Result, E>, ) -> Result { use rustgis_data::ogc::{TilesStep, resolve_tiles}; - let mut out = AdvertisedTemplate { template: None, crossed_origin: crosses_origin(source, list), fallback: None, public: false }; + let mut out = + AdvertisedTemplate { template: None, crossed_origin: crosses_origin(source, list), fallback: None, public: reach == Reach::Public }; + let mut reach = reach; let mut doc = list.to_string(); for _ in 0..2 { let shown = crate::sources::address_in_message(&doc); - if let Err(e) = crate::render::rustgis_tiles::address::check(&doc, Some(list)) { + if let Err(e) = crate::render::rustgis_tiles::address::check_reach(&doc, reach.min(cache::ceiling_for(&doc))) { let e = crate::sources::message_with_address(&doc, &e); out.fallback = Some(format!("{shown}: this tile set document was refused, so the standard tile address is used: {e}")); return Ok(out); } - let body = match read(&doc)? { - Ok(body) => body, + let body = match read(&doc, reach.min(cache::ceiling_for(&doc)))? { + Ok((body, read_at)) => { + reach = reach.min(read_at); + out.public = reach == Reach::Public; + body + } Err(e) => { out.fallback = Some(format!("{shown}: its tile sets couldn't be read, so the standard tile address is used: {e}")); return Ok(out); @@ -844,7 +860,7 @@ fn walk_template, E>( match resolved.step { TilesStep::Template(t) => { out.crossed_origin |= crosses_origin(&doc, &t); - match checked_template(list, &t) { + match checked_template(reach, &t) { Ok(t) => out.template = Some(t), // (Its error names the template, which may carry keys.) Err(e) => { @@ -897,18 +913,16 @@ fn left_template( withheld: &mut u32, public: bool, ) -> Result { - let mut public = public; - let walked = walk_template(source, list, vector, withheld, |doc: &str| { - if public { + let reach = if public { Reach::Public } else { Reach::Local }; + let walked = walk_template(source, list, vector, withheld, reach, |doc: &str, within| { + if within == Reach::Public { cache::restrict_to_public(doc); } match s.left_document(doc) { Err(e) => Err(LeftStop::Failed(e)), Ok(None) => Err(LeftStop::Waiting(doc.to_string())), - Ok(Some(read)) => { - public |= read.is_ok() && cache::ceiling_for(doc) == Reach::Public; - Ok(read) - } + // The app's read records one from the internet ([`cache::ceiling_for`]). + Ok(Some(read)) => Ok(read.map(|bytes| (bytes, cache::ceiling_for(doc)))), } }); match walked { @@ -916,7 +930,6 @@ fn left_template( if let Some(text) = out.fallback.take() { s.notify(text, false); } - out.public = public; Ok(LeftTemplate::Read(out)) } Err(LeftStop::Waiting(doc)) => Ok(LeftTemplate::Waiting(doc)), @@ -1346,7 +1359,11 @@ fn add_discovered(s: &mut Session, p: &Value, url: &str, want: &str, found: &Dis let advertised = match (&layer.tilesets, ps(p, "tiles")) { // The app read it, and recorded a template from a document on the internet as such. (Some(list), Some(t)) => AdvertisedTemplate { - template: Some(checked_template(source, t)?), + // Judged by where the app read its documents (recorded from the internet, or not). + template: Some(checked_template( + (if public { Reach::Public } else { Reach::Local }).min(cache::ceiling_for(list)).min(cache::ceiling_for(t)), + t, + )?), crossed_origin: crosses_origin(source, list) || crosses_origin(list, t), fallback: None, public: cache::ceiling_for(t) == Reach::Public, @@ -1796,11 +1813,16 @@ pub(super) fn catalog_search(s: &mut Session, p: &Value) -> CmdResult { let p = bound.as_ref(); let url = url_of(p)?; let request = records_request(s, p)?; - let page = match ps(p, "text") { - Some(text) => { - rustgis_data::ogc::parse_records(&request, text.as_bytes()).map_err(|e| crate::sources::message_with_address(url, &e))? - } - None => fetch_records(url, &request)?, + // Where the answer was read: natively, where the fetch connected; otherwise what the app's + // fetch recorded of it ([`cache::ceiling_for`]). The catalogue's own address is the user's + // choice, unless a document read from the internet named it. + let within = cache::ceiling_for(url).min(cache::ceiling_for(&request)); + let (page, reach) = match ps(p, "text") { + Some(text) => ( + rustgis_data::ogc::parse_records(&request, text.as_bytes()).map_err(|e| crate::sources::message_with_address(url, &e))?, + within, + ), + None => fetch_records(url, &request, within)?, }; let mut dropped = 0usize; let records: Vec = page @@ -1810,12 +1832,21 @@ pub(super) fn catalog_search(s: &mut Session, p: &Value) -> CmdResult { let links: Vec = r .links .iter() + // Judged by where the answer was read, not by how the catalogue's address is + // spelled: a public-looking name may connect on the local network. .filter(|l| { - let ok = crate::render::rustgis_tiles::address::check(&l.url, Some(&request)).is_ok(); + let ok = crate::render::rustgis_tiles::address::check_reach(&l.url, reach).is_ok(); dropped += usize::from(!ok); ok }) - .map(|l| json!({"url": crate::render::rustgis_tiles::logins::inherit(&request, &l.url), "kind": l.kind, "name": l.name, "protocol": l.protocol})) + .map(|l| { + let mut link = json!({"url": crate::render::rustgis_tiles::logins::inherit(&request, &l.url), "kind": l.kind, "name": l.name, "protocol": l.protocol}); + // Read from the internet, the link leads only there: whoever follows it passes this on. + if reach == Reach::Public { + link["fromDocument"] = json!(true); + } + link + }) .collect(); json!({"id": r.id, "title": r.title, "abstract": r.summary, "bbox": r.bbox, "links": links}) }) @@ -1831,15 +1862,18 @@ pub(super) fn catalog_search(s: &mut Session, p: &Value) -> CmdResult { Ok(out) } +/// Reads a page of records within `ceiling`, with the reach the fetch connected at. #[cfg(not(target_arch = "wasm32"))] -fn fetch_records(url: &str, request: &str) -> Result { - let bytes = - crate::render::rustgis_tiles::cache::download_blocking(request).map_err(|e| crate::sources::message_with_address(url, &e))?; - rustgis_data::ogc::parse_records(request, &bytes).map_err(|e| crate::sources::message_with_address(url, &e)) +fn fetch_records(url: &str, request: &str, ceiling: Reach) -> Result<(rustgis_data::ogc::RecordPage, Reach), String> { + let fetched = cache::download_blocking_with_origin_within(request, cache::MAX_DOWNLOAD, cache::BLOCKING_TIMEOUT, &[], ceiling) + .map_err(cache::large_file_hint) + .map_err(|e| crate::sources::message_with_address(url, &e))?; + let page = rustgis_data::ogc::parse_records(request, &fetched.bytes).map_err(|e| crate::sources::message_with_address(url, &e))?; + Ok((page, fetched.origin.reach())) } #[cfg(target_arch = "wasm32")] -fn fetch_records(url: &str, _: &str) -> Result { +fn fetch_records(url: &str, _: &str, _: Reach) -> Result<(rustgis_data::ogc::RecordPage, Reach), String> { Err(crate::sources::message_with_address(url, "in the web app, use Home › Add › Add Data › From Service › Search Catalogue")) } @@ -1864,13 +1898,14 @@ mod tests { // A document asked for past the first, where none should be: it names nothing, said. let nothing_more = |_: &str| json!({}); // What the list leads to, read in turn: the template it ends with, and what was said. - let read = |first: Value, then: &dyn Fn(&str) -> Value| { + // (`public`: the service's document was read from the internet.) + let read = |first: Value, then: &dyn Fn(&str) -> Value, public: bool| { let mut s = Session::new(crate::sample::world_project()); s.call_requests = Some(Vec::new()); land(&mut s, list, first); let mark = s.notice_mark(); for _ in 0..3 { - match left_template(&mut s, source, list, false, &mut 0, false).unwrap() { + match left_template(&mut s, source, list, false, &mut 0, public).unwrap() { LeftTemplate::Read(out) => { let said: Vec = s.notices_since(mark).iter().map(|n| n.text.clone()).collect(); return (out.template, said); @@ -1880,15 +1915,15 @@ mod tests { } panic!("it never read a template"); }; - let (t, said) = read(tilesets("https://x.org/t/1"), &|doc| tilesets(&format!("{doc}/more"))); + let (t, said) = read(tilesets("https://x.org/t/1"), &|doc| tilesets(&format!("{doc}/more")), false); assert!(t.is_none() && said.len() == 1 && said[0].contains("past two documents"), "{said:?}"); - let (t, said) = read(template("https://x.org/paint/{tileMatrix}.png?token=hunter2"), ¬hing_more); + let (t, said) = read(template("https://x.org/paint/{tileMatrix}.png?token=hunter2"), ¬hing_more, false); assert!(t.is_none() && said.len() == 1 && said[0].contains("tile template was refused"), "{said:?}"); assert!(!said[0].contains("hunter2"), "{said:?}"); - // A document on the web pointing into the local network. - let (t, said) = read(tilesets("http://127.0.0.1/t/1"), ¬hing_more); + // A document read from the internet pointing into the local network. + let (t, said) = read(tilesets("http://127.0.0.1/t/1"), ¬hing_more, true); assert!(t.is_none() && said.len() == 1 && said[0].contains("document was refused"), "{said:?}"); - let (t, said) = read(template("https://x.org/paint/{tileMatrix}/{tileCol}/{tileRow}.png"), ¬hing_more); + let (t, said) = read(template("https://x.org/paint/{tileMatrix}/{tileCol}/{tileRow}.png"), ¬hing_more, false); assert_eq!(t.as_deref(), Some("https://x.org/paint/{z}/{x}/{y}.png")); assert!(said.is_empty(), "{said:?}"); } @@ -1977,22 +2012,30 @@ mod tests { fn advertised_template_fallbacks_are_said() { let list = "https://tiles-fallback.example.invalid/tiles?f=json"; let mut withheld = 0; - let none = advertised_template_with(list, list, false, &mut withheld, |_| Ok(b"{}".to_vec())); + let none = advertised_template_with(list, list, false, &mut withheld, Reach::Local, |_, _| Ok((b"{}".to_vec(), Reach::Local))); assert!(none.template.is_none()); assert!(none.fallback.as_ref().is_some_and(|n| n.contains("names no tiles")), "{:?}", none.fallback); - let refused = advertised_template_with(list, "file:///etc/tiles", false, &mut withheld, |_| Ok(b"{}".to_vec())); + let refused = advertised_template_with(list, "file:///etc/tiles", false, &mut withheld, Reach::Local, |_, _| { + Ok((b"{}".to_vec(), Reach::Local)) + }); assert!(refused.fallback.as_ref().is_some_and(|n| n.contains("was refused")), "{:?}", refused.fallback); let next = json!({"tilesets":[{"tileMatrixSetId":"WebMercatorQuad","links":[{"rel":"self","href":"https://tiles-fallback.example.invalid/next"}]}]}); - let far = advertised_template_with(list, list, false, &mut withheld, |_| Ok(serde_json::to_vec(&next).unwrap_or_default())); + let far = advertised_template_with(list, list, false, &mut withheld, Reach::Local, |_, _| { + Ok((serde_json::to_vec(&next).unwrap_or_default(), Reach::Local)) + }); assert!(far.fallback.as_ref().is_some_and(|n| n.contains("past two documents")), "{:?}", far.fallback); // The address named in the notice says its secret query went; one without a query says nothing. let keyed = "https://tiles-fallback.example.invalid/tiles?key=hunter2"; - let far = advertised_template_with(keyed, keyed, false, &mut withheld, |_| Ok(serde_json::to_vec(&next).unwrap_or_default())); + let far = advertised_template_with(keyed, keyed, false, &mut withheld, Reach::Local, |_, _| { + Ok((serde_json::to_vec(&next).unwrap_or_default(), Reach::Local)) + }); let said = far.fallback.unwrap_or_default(); assert!(said.starts_with("https://tiles-fallback.example.invalid/tiles[query omitted]: its tile sets lead on past"), "{said}"); assert!(!said.contains("hunter2"), "{said}"); let bare = "https://tiles-fallback.example.invalid/tiles"; - let far = advertised_template_with(bare, bare, false, &mut withheld, |_| Ok(serde_json::to_vec(&next).unwrap_or_default())); + let far = advertised_template_with(bare, bare, false, &mut withheld, Reach::Local, |_, _| { + Ok((serde_json::to_vec(&next).unwrap_or_default(), Reach::Local)) + }); let said = far.fallback.unwrap_or_default(); assert!( said.starts_with("https://tiles-fallback.example.invalid/tiles: its tile sets lead on past") && !said.contains("omitted]"), @@ -2023,20 +2066,23 @@ mod tests { let template = format!("{a}/paint/{{z}}/{{x}}/{{y}}.png"); let mut reads = Vec::new(); let mut withheld = 0; - let resolved = advertised_template_with(&source, &list, false, &mut withheld, |url| { + let resolved = advertised_template_with(&source, &list, false, &mut withheld, Reach::Local, |url, _| { let first = reads.is_empty(); let header = tiles::logins::apply(url).unwrap().and_then(|a| a.header); assert_eq!(header.is_some(), first && list_origin == a); reads.push(tiles::logins::inner(url).to_string()); if first { - Ok(serde_json::to_vec( - &json!({"tilesets":[{"tileMatrixSetId":"WebMercatorQuad","links":[{"rel":"self","href":next}]}]}), - ) - .unwrap()) + Ok(( + serde_json::to_vec( + &json!({"tilesets":[{"tileMatrixSetId":"WebMercatorQuad","links":[{"rel":"self","href":next}]}]}), + ) + .unwrap(), + Reach::Local, + )) } else if fail { Err("fixture tileset unavailable".into()) } else { - Ok(serde_json::to_vec(&json!({"links":[{"rel":"item","type":"image/png","href":format!("{a}/paint/{{tileMatrix}}/{{tileCol}}/{{tileRow}}.png")}]})).unwrap()) + Ok((serde_json::to_vec(&json!({"links":[{"rel":"item","type":"image/png","href":format!("{a}/paint/{{tileMatrix}}/{{tileCol}}/{{tileRow}}.png")}]})).unwrap(), Reach::Local)) } }); assert_eq!(reads, [format!("{list_origin}/tiles?f=json"), format!("{next}?f=json")]); @@ -2160,6 +2206,168 @@ mod tests { } } + /// A service at a public-looking name that connected on the local network keeps its local links + /// and layers: the document its landing links to and the features layer that document lists, + /// both on a private address, are judged by where the landing was read, not by how its name is + /// spelled. Read from the internet, the same link is refused, naming the address and why. + #[test] + fn a_service_on_the_local_network_keeps_its_local_links_whatever_its_name() { + use crate::render::rustgis_tiles::address::Origin; + for (n, observed) in [(1, Reach::Local), (2, Reach::Public)] { + let linked = format!("http://10.0.{n}.5/collections"); + let landing = json!({"links":[{"rel":"data","type":"application/json","href":linked}]}); + let items = format!("{linked}/parcels/items"); + let collections = json!({"collections":[{"id":"parcels","title":"Parcels","links":[{"rel":"items","type":"application/geo+json","href":items}]}]}); + let mut asked = Vec::new(); + let mut s = Session::new(crate::Project::default()); + let p = json!({"url": format!("https://gis-{n}.corp-looks-public.example/ogc"), "type": "ogcapi"}); + let found = read_documents_with(&mut s, &p, false, None, &mut |url, ceiling| { + asked.push((url.to_string(), ceiling)); + let body = if asked.len() == 1 { &landing } else { &collections }; + let origin = Origin::with_observed_reach(url, observed.min(ceiling))?; + Ok(cache::Fetched { bytes: serde_json::to_vec(body).unwrap_or_default(), origin }) + }); + if observed == Reach::Local { + let found = found.unwrap(); + assert_eq!(asked.get(1), Some(&(linked.clone(), Reach::Local)), "{asked:?}"); + assert!(!found.excluded_layers, "{:?}", found.service.notes); + let offers: Vec<_> = found.service.layers.iter().map(|l| l.offer.clone()).collect(); + assert!(matches!(offers.as_slice(), [Offer::Features { url }] if url.starts_with(&items)), "{offers:?}"); + } else { + let e = found.err().unwrap_or_default(); + assert!(e.contains(&linked) && e.contains("local network"), "{e}"); + assert_eq!(asked.len(), 1, "the link is not fetched: {asked:?}"); + } + } + } + + /// The layers a service's document lists are judged by where the document was read: a + /// collections document at a public-looking name read on the local network keeps a features + /// layer on a private address; read from the internet, the layer is left out, as said. + #[test] + fn a_documents_layers_are_judged_by_where_it_was_read() { + use crate::render::rustgis_tiles::address::Origin; + for (n, observed) in [(11, Reach::Local), (12, Reach::Public)] { + let items = format!("http://10.0.{n}.5/collections/parcels/items"); + let collections = json!({"collections":[{"id":"parcels","title":"Parcels","links":[{"rel":"items","type":"application/geo+json","href":items}]}]}); + let mut s = Session::new(crate::Project::default()); + let p = json!({"url": format!("https://gis-{n}.corp-looks-public.example/collections"), "type": "ogcapi"}); + let found = read_documents_with(&mut s, &p, false, None, &mut |url, ceiling| { + let origin = Origin::with_observed_reach(url, observed.min(ceiling))?; + Ok(cache::Fetched { bytes: serde_json::to_vec(&collections).unwrap_or_default(), origin }) + }) + .unwrap(); + assert_eq!(found.service.layers.len(), usize::from(observed == Reach::Local), "{:?}", found.service.notes); + assert_eq!(found.excluded_layers, observed == Reach::Public); + if observed == Reach::Public { + assert!(found.service.notes.iter().any(|n| n.contains("won't fetch")), "{:?}", found.service.notes); + } + } + } + + /// A tile set walk judges the tile set it is led to and the template it ends at by where the + /// document naming them was read: from a list at a public-looking name read on the local + /// network, a tile set and a template on a private address are used; from the same list read + /// from the internet, the tile set is refused and the standard tile address used, as said. + #[test] + fn a_tile_set_walk_judges_what_each_document_names_by_where_it_was_read() { + for (n, observed) in [(3, Reach::Local), (4, Reach::Public)] { + let list = format!("https://tiles-{n}.corp-looks-public.example/tiles?f=json"); + let tileset = format!("http://10.0.{n}.7/tileset"); + let first = json!({"tilesets":[{"tileMatrixSetId":"WebMercatorQuad","links":[{"rel":"self","href":tileset}]}]}); + let second = json!({"links":[{"rel":"item","type":"image/png","href":format!("http://10.0.{n}.7/map/{{tileMatrix}}/{{tileRow}}/{{tileCol}}.png")}]}); + let mut asked = Vec::new(); + let mut withheld = 0; + let out = advertised_template_with(&list, &list, false, &mut withheld, Reach::Local, |doc, ceiling| { + asked.push((doc.to_string(), ceiling)); + let body = if asked.len() == 1 { &first } else { &second }; + Ok((serde_json::to_vec(body).unwrap_or_default(), observed.min(ceiling))) + }); + if observed == Reach::Local { + assert_eq!(asked.get(1).map(|(_, c)| *c), Some(Reach::Local), "{asked:?}"); + assert!(out.template.as_deref().is_some_and(|t| t.starts_with(&format!("http://10.0.{n}.7/map/"))), "{:?}", out.fallback); + assert!(!out.public); + } else { + assert_eq!(asked.len(), 1, "{asked:?}"); + assert!(out.template.is_none()); + let said = out.fallback.unwrap_or_default(); + assert!(said.contains("was refused") && said.contains("local network"), "{said}"); + assert!(out.public, "the standard address in its place comes from there too"); + } + } + } + + /// The tile template a dataset document names is judged by where that document was read: a + /// map tile list at a public-looking name read on the local network keeps a template on a + /// private address; read from the internet, the template is left out. + #[test] + fn a_dataset_template_is_judged_by_where_its_document_was_read() { + use crate::render::rustgis_tiles::address::Origin; + for (n, observed) in [(5, Reach::Local), (6, Reach::Public)] { + let map = format!("https://map-{n}.corp-looks-public.example/tiles?f=json"); + let metadata = format!("https://map-{n}.corp-looks-public.example/metadata?f=json"); + let landing = json!({"links":[{"rel":"tilesets-map","href":map}]}); + let map_list = json!({"tilesets":[{"tileMatrixSetId":"WebMercatorQuad","dataType":"map","links":[ + {"rel":"self","type":"application/json","href":metadata}]}]}); + let map_metadata = json!({"tileMatrixSetId":"WebMercatorQuad","links":[ + {"rel":"item","type":"image/png","href":format!("http://10.0.{n}.9/map/{{tileMatrix}}/{{tileRow}}/{{tileCol}}.png")}]}); + let mut s = Session::new(crate::Project::default()); + let p = json!({"url": format!("https://dataset-{n}.corp-looks-public.example/ogc"), "type": "ogcapi"}); + let found = read_documents_with(&mut s, &p, false, None, &mut |url, ceiling| { + let body = match url { + u if u == map => &map_list, + u if u == metadata => &map_metadata, + _ => &landing, + }; + let origin = Origin::with_observed_reach(url, observed.min(ceiling))?; + Ok(cache::Fetched { bytes: serde_json::to_vec(body).unwrap_or_default(), origin }) + }) + .unwrap(); + let templates: Vec<_> = found + .service + .layers + .iter() + .filter_map(|l| match &l.offer { + Offer::Tiles { template } => Some(template.clone()), + _ => None, + }) + .collect(); + assert_eq!(templates.len(), usize::from(observed == Reach::Local), "{templates:?} {:?}", found.service.notes); + assert!(templates.iter().all(|t| t.starts_with(&format!("http://10.0.{n}.9/"))), "{templates:?}"); + } + } + + /// A catalogue's links are judged by where its answer was read: one at a public-looking name + /// read on the local network keeps a link on a private address; one read from the internet + /// (the app's record of its answer) leaves it out, says so, and marks the links it keeps + /// `fromDocument`, which the app passes on when it follows them. + #[test] + fn a_catalogues_links_are_judged_by_where_its_answer_was_read() { + for (n, public) in [(7, false), (8, true)] { + let url = format!("https://csw-{n}.corp-looks-public.example/csw"); + let answer = format!( + r#"aAhttp://10.0.{n}.4/wmshttps://wms-{n}.example/wms"# + ); + let mut s = Session::new(crate::Project::default()); + let p = json!({"url": url, "text": answer}); + if public { + cache::restrict_to_public(&records_request(&s, &p).unwrap()); + } + let out = catalog_search(&mut s, &p).unwrap(); + let links = out["records"][0]["links"].as_array().cloned().unwrap_or_default(); + let urls: Vec<_> = links.iter().filter_map(|l| l["url"].as_str()).collect(); + if public { + assert_eq!(urls, [format!("https://wms-{n}.example/wms")], "{out}"); + assert!(out["notes"][0].as_str().is_some_and(|n| n.starts_with("1 links")), "{out}"); + assert!(links.iter().all(|l| l["fromDocument"] == true), "{out}"); + } else { + assert_eq!(urls, [format!("http://10.0.{n}.4/wms"), format!("https://wms-{n}.example/wms")], "{out}"); + assert!(out.get("notes").is_none(), "{out}"); + assert!(links.iter().all(|l| l.get("fromDocument").is_none()), "{out}"); + } + } + } + /// A document read natively from the internet is recorded as such, so the app, which knows a /// listed layer's document only by its address (`source_url`), fetches what the layer links to /// from the internet too ([`cache::ceiling_for`], as Add From Service's `from_public` reads it). diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index e500d55ebb..fad980537c 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -25077,15 +25077,40 @@ fn identify_asks_wms_layers() { added.run("map.goToXY", &json!({"lon": 8.5, "lat": 47.4, "scale": 10000})).unwrap(); let v = added.run("identify", &json!({"lon": 8.5, "lat": 47.4, "mode": "visible"})).unwrap(); assert_eq!(v["featureInfo"][0]["tileLayer"], "Mine", "{v}"); - // A service on the web whose GetFeatureInfo points into the local network isn't asked. - let local = WMS.replace("https://maps.example.com/info?", "http://192.168.1.5/info?"); - let mut s = Session::new(Project::default()); - s.run("service.add", &json!({"url": url, "layer": "roads", "text": local})).unwrap(); - s.run("map.goToXY", &json!({"lon": 8.5, "lat": 47.4, "scale": 10000})).unwrap(); - let v = s.run("identify", &json!({"lon": 8.5, "lat": 47.4, "mode": "visible"})).unwrap(); - assert!(v.is_null(), "{v}"); - let r = s.run("identify.featureInfo", &json!({"layer": "Roads", "lon": 8.5, "lat": 47.4, "request": true})).unwrap(); - assert_eq!(r, json!({"results": []})); + // A service read from the internet (the app's record of its capabilities) whose + // GetFeatureInfo points into the local network isn't asked, and says so; the same service + // read on the local network, at the same public-looking kind of name, is asked there. Each + // case its own names: the record is process-wide. + for (host, web) in [("maps-web.example.com", true), ("maps-intranet.example.com", false)] { + let local = WMS.replace("https://maps.example.com/info?", "http://192.168.1.5/info?").replace("maps.example.com", host); + let url = format!("https://{host}/wms"); + if web { + crate::render::rustgis_tiles::cache::restrict_to_public(&rustgis_data::ogc::capabilities_url(&url, None)); + } + let mut s = Session::new(Project::default()); + s.run("service.add", &json!({"url": url, "layer": "roads", "text": local})).unwrap(); + s.run("map.goToXY", &json!({"lon": 8.5, "lat": 47.4, "scale": 10000})).unwrap(); + let before = s.notice_mark(); + let v = s.run("identify", &json!({"lon": 8.5, "lat": 47.4, "mode": "visible"})).unwrap(); + let told: Vec<_> = s.notices_since(before).iter().map(|n| n.text.clone()).collect(); + let r = s.run("identify.featureInfo", &json!({"layer": "Roads", "lon": 8.5, "lat": 47.4, "request": true})); + if web { + assert!(v.is_null(), "{v}"); + assert!( + told.len() == 1 + && told[0].starts_with("Roads wasn't asked what is here: http://192.168.1.5/info") + && told[0].contains("local network"), + "{told:?}" + ); + let e = r.unwrap_err(); + assert!(e.starts_with("Roads: http://192.168.1.5/info") && e.contains("local network"), "{e}"); + } else { + assert!(v["featureInfo"][0]["url"].as_str().is_some_and(|u| u.starts_with("http://192.168.1.5/info?")), "{v}"); + assert!(v["featureInfo"][0].get("public").is_none(), "{v}"); + assert!(told.is_empty(), "{told:?}"); + assert!(r.unwrap()["url"].as_str().is_some_and(|u| u.starts_with("http://192.168.1.5/info?"))); + } + } } /// A tile layer picked in Layers (`map.selectTiles`, view state like `layer.select`) is the one @@ -25285,12 +25310,15 @@ fn services_list_and_add_layers() { let r = s.run("service.add", &json!({"url": api, "layer": "lakes", "text": collections})).unwrap(); assert_eq!(r["features"], 1); assert!(s.map().layer_by_name("Lakes").is_some()); - // A document on the web can't send RustGIS into the local network. + // A document read from the internet (the app's record of it) can't send RustGIS into the + // local network; its own address on its own record, as the record is process-wide. let inward = WMS.replace("https://maps.example.com/wms?", "http://127.0.0.1:8080/wms?"); - let v = s.run("service.layers", &json!({"url": url, "text": inward})).unwrap(); + let web = "https://maps-web-inward.example.com/wms"; + crate::render::rustgis_tiles::cache::restrict_to_public(&rustgis_data::ogc::capabilities_url(web, None)); + let v = s.run("service.layers", &json!({"url": web, "text": inward})).unwrap(); assert_eq!(v["count"], 0); assert!(v["notes"].as_array().unwrap().iter().any(|n| n.as_str().is_some_and(|n| n.contains("won't fetch"))), "{v}"); - assert!(s.run("service.add", &json!({"url": url, "layer": "roads", "text": inward})).is_err()); + assert!(s.run("service.add", &json!({"url": web, "layer": "roads", "text": inward})).is_err()); // A service's answer with latitude first (it misses the collection's extent, and fits it // turned round) is turned round, and a page of a larger collection is pointed out. const LAT_FIRST: &[u8] = br#"{"type": "FeatureCollection", "numberMatched": 9, "numberReturned": 1, "features": [{"type": "Feature", "properties": {}, "geometry": {"type": "Point", "coordinates": [50, 10]}}], "crs": {"type": "name", "properties": {"name": "urn:ogc:def:crs:EPSG::4326"}}}"#; @@ -25313,8 +25341,12 @@ fn services_list_and_add_layers() { ) .unwrap(); assert!(s.map().tiles.iter().any(|t| t.url == "https://x.org/relief/map/tiles/smerc/{z}/{y}/{x}.png"), "{r}"); + // (Its document read from the internet, the app's record of it, on its own name as the record + // is process-wide: a template into the local network is refused.) + let web = "https://x-web-templates.example/collections"; + crate::render::rustgis_tiles::cache::restrict_to_public(web); for bad in ["https://x.org/relief.png", "http://169.254.169.254/{z}/{x}/{y}", "http://127.0.0.1/{z}/{x}/{y}"] { - assert!(s.run("service.add", &json!({"url": api, "layer": "relief (map tiles)", "text": tiled, "tiles": bad})).is_err(), "{bad}"); + assert!(s.run("service.add", &json!({"url": web, "layer": "relief (map tiles)", "text": tiled, "tiles": bad})).is_err(), "{bad}"); } } @@ -26358,11 +26390,15 @@ fn wcs_coverages_and_catalogue_records() { Forests https://geo.example.org/wmshttp://192.168.1.2/wfs "#; - let v = s.run("catalog.search", &json!({"url": "https://cat.example.org/csw", "query": "forest", "text": records})).unwrap(); + // Its answer read from the internet (the app's record of it): a link into the local network + // is left out, and the one kept is marked as from a document read from there. + let p = json!({"url": "https://cat-web.example.org/csw", "query": "forest", "text": records}); + crate::render::rustgis_tiles::cache::restrict_to_public(&crate::cmd::service::records_request(&s, &p).unwrap()); + let v = s.run("catalog.search", &p).unwrap(); assert_eq!((v["matched"].as_u64(), v["count"].as_u64(), v["next"].as_u64()), (Some(3), Some(1), Some(2)), "{v}"); assert_eq!( v["records"][0]["links"], - json!([{"url": "https://geo.example.org/wms", "kind": "wms", "name": null, "protocol": "OGC:WMS"}]) + json!([{"url": "https://geo.example.org/wms", "kind": "wms", "name": null, "protocol": "OGC:WMS", "fromDocument": true}]) ); assert!(v["notes"][0].as_str().is_some_and(|n| n.contains("1 links")), "{v}"); assert!(v["request"].as_str().is_some_and(|r| r.contains("AnyText%20LIKE%20%27%25forest%25%27")), "{v}"); @@ -39373,7 +39409,10 @@ fn ogc_landing_keeps_map_tiles_and_collection_provenance() { fn ogc_landing_discovery_is_bounded_and_checks_addresses() { let mut session = Session::new(Project::default()); let link = |url: &str| json!({"links":[{"rel":"data","type":"application/json","href":url}]}).to_string(); - let root = "https://example.org/ogc/root"; + // The root read from the internet (the app's record of it): it may not link into the local + // network. Its own address on its own record, as the record is process-wide. + let root = "https://landing-web.example.org/ogc/root"; + crate::render::rustgis_tiles::cache::restrict_to_public(root); for target in ["http://127.0.0.1/catalog", "http://169.254.169.254/catalog", "file:///etc/passwd"] { let result = session.run("service.layers", &json!({"url":root,"text":link(target)})); assert!(result.is_err(), "{target}"); diff --git a/crates/engine/src/tests/ogc_dataset.rs b/crates/engine/src/tests/ogc_dataset.rs index d04dfc9f65..d159a28dd4 100644 --- a/crates/engine/src/tests/ogc_dataset.rs +++ b/crates/engine/src/tests/ogc_dataset.rs @@ -383,8 +383,11 @@ fn ogc_dataset_styles_use_advertised_projection_and_native_web_parity() { #[test] fn ogc_dataset_styles_require_templates_allowed_from_the_tileset_document() { + // The first read from the internet (the app's record of its root), on its own name as the + // record is process-wide; the last on the local network. + crate::render::rustgis_tiles::cache::restrict_to_public("https://maps-web-templates.example.org/dataset"); for (origin, template, allowed) in [ - ("https://maps.example.org", "http://127.0.0.1/{z}/{y}/{x}.pbf", false), + ("https://maps-web-templates.example.org", "http://127.0.0.1/{z}/{y}/{x}.pbf", false), ("https://maps.example.org", "https://tiles.example.org/{z}/{y}/{x}.pbf", true), ("http://127.0.0.1", "http://127.0.0.1/{z}/{y}/{x}.pbf", true), ] { @@ -645,14 +648,17 @@ fn ogc_dataset_style_discovery_is_bounded_and_checks_source_addresses() { assert_eq!(listing["count"], 16, "{listing}"); assert!(listing["notes"].as_array().unwrap().iter().any(|n| n.as_str().unwrap().contains("16-style discovery limit"))); assert_eq!(server.requests().len(), 19); - let root = "https://maps.example.org/dataset"; + // The root read from the internet (the app's record of it), on its own name as the record is + // process-wide. + let root = "https://maps-web-styles.example.org/dataset"; + crate::render::rustgis_tiles::cache::restrict_to_public(root); let mut docs = documents(); docs[2].1["styles"].as_array_mut().unwrap().truncate(1); docs[3].1["sources"]["basemap"] = json!({"type":"vector","url":"http://127.0.0.1/private"}); let params = json!({"url":root,"type":"ogcapi","text":docs[0].1.to_string(),"documents":[ - {"url":"https://maps.example.org/tiles?f=json","text":docs[1].1.to_string()}, - {"url":"https://maps.example.org/styles?f=json","text":docs[2].1.to_string()}, - {"url":"https://maps.example.org/good?f=mapbox","text":docs[3].1.to_string()} + {"url":"https://maps-web-styles.example.org/tiles?f=json","text":docs[1].1.to_string()}, + {"url":"https://maps-web-styles.example.org/styles?f=json","text":docs[2].1.to_string()}, + {"url":"https://maps-web-styles.example.org/good?f=mapbox","text":docs[3].1.to_string()} ]}); let mut params = params; params["documents"][1]["text"] = json!( @@ -662,7 +668,7 @@ fn ogc_dataset_style_discovery_is_bounded_and_checks_source_addresses() { ]}) .to_string() ); - params["documents"].as_array_mut().unwrap().push(json!({"url":"https://maps.example.org/public","text":good.to_string()})); + params["documents"].as_array_mut().unwrap().push(json!({"url":"https://maps-web-styles.example.org/public","text":good.to_string()})); let listing = session.run("service.layers", ¶ms).unwrap(); assert_eq!(listing["count"], 1, "{listing}"); assert_eq!(listing["layers"][0]["name"], "public"); diff --git a/crates/tiles/src/address.rs b/crates/tiles/src/address.rs index b1b1b99e17..283e73637d 100644 --- a/crates/tiles/src/address.rs +++ b/crates/tiles/src/address.rs @@ -20,7 +20,8 @@ use std::net::{IpAddr, Ipv4Addr, Ipv6Addr}; pub enum Reach { /// The internet. Public, - /// This computer or the local network (loopback, private and unique-local addresses). + /// This computer or the local network (loopback, private, unique-local and site-local + /// addresses). Local, /// Never fetched: link-local and unspecified addresses, cloud metadata hosts. Forbidden, @@ -152,10 +153,15 @@ pub fn ip_reach(ip: IpAddr) -> Reach { [0x2002, hi, lo, ..] => return v4_reach(Ipv4Addr::from((u32::from(hi) << 16) | u32::from(lo))), _ => {} } + // Teredo (`2001:0::/32`, RFC 4380) embeds an IPv4 address too, but obfuscated (the + // client's is XORed) and only reached through a relay, never routed to directly, so it + // keeps the public arm. let seg0 = v6.segments().first().copied().unwrap_or(0); if v6.is_unspecified() || (seg0 & 0xffc0) == 0xfe80 { Reach::Forbidden - } else if v6 == Ipv6Addr::LOCALHOST || (seg0 & 0xfe00) == 0xfc00 { + } else if v6 == Ipv6Addr::LOCALHOST || (seg0 & 0xfe00) == 0xfc00 || (seg0 & 0xffc0) == 0xfec0 { + // Unique-local `fc00::/7` and the deprecated site-local `fec0::/10` (RFC 3879), + // which older networks still route inside a site. Reach::Local } else { Reach::Public @@ -418,6 +424,23 @@ mod tests { } } + /// Site-local addresses (`fec0::/10`, deprecated but still routed inside some sites) are + /// local: a document on the web can't point at them, and a peer there is observed local. + /// Teredo addresses stay public: what they embed is obfuscated and reached through a relay. + #[test] + fn site_local_addresses_are_local_and_teredo_stays_public() { + for ip in ["fec0::1", "fefe:1::2", "feff:ffff::1"] { + let url = format!("http://[{ip}]/tiles"); + assert_eq!(reach(&url), Reach::Local, "{url}"); + assert!(check(&url, None).is_ok(), "{url}"); + assert!(check(&url, Some("https://public.example/style.json")).is_err(), "{url}"); + assert_eq!(Origin::connected("https://looks-public.example/", ip.parse().unwrap()).unwrap().reach, Reach::Local, "{ip}"); + } + // Link-local, just below, stays forbidden. + assert_eq!(reach("http://[febf::1]/"), Reach::Forbidden); + assert_eq!(reach("http://[2001:0:4136:e378:8000:63bf:3fff:fdd2]/"), Reach::Public); + } + #[test] fn checks_where_addresses_come_from() { // The user's own choice may be local; a web document's may not. diff --git a/crates/tiles/src/portal.rs b/crates/tiles/src/portal.rs index 5fe023541f..80f5a818cd 100644 --- a/crates/tiles/src/portal.rs +++ b/crates/tiles/src/portal.rs @@ -8,6 +8,7 @@ //! REST); a Hugging Face dataset lists its files in a second request ([`Dataset::listing`]). //! Requests are built and answers read here; the fetching is the caller's. +use crate::address::Reach; use serde_json::Value; /// The portals searched when none is named. @@ -454,10 +455,10 @@ impl Portal { } } - /// The datasets in a search's answer (`from`: the search's address, which the resources' own - /// addresses are judged against), with the resources RustGIS can add; datasets without one are - /// left out, as are those outside `bbox` when they say where they are. - pub fn parse(&self, from: &str, bytes: &[u8], bbox: Option<[f64; 4]>, query: &str) -> Result, String> { + /// The datasets in a search's answer (read within `reach`, as its fetch observed it, which the + /// resources' own addresses are judged by), with the resources RustGIS can add; datasets + /// without one are left out, as are those outside `bbox` when they say where they are. + pub fn parse(&self, reach: Reach, bytes: &[u8], bbox: Option<[f64; 4]>, query: &str) -> Result, String> { let v: Value = serde_json::from_slice(bytes).map_err(|_| format!("{}: the answer isn't JSON", self.label()))?; // The words a portal whose search takes none is kept to here: every one in the title, // description or provider. @@ -535,11 +536,12 @@ impl Portal { } }; for d in &mut out { - // The portal's answer is hostile input: an address it gives may not reach into the - // local network (unless the portal is there) or a forbidden address. - d.resources.retain(|r| crate::address::check(&r.url, Some(from)).is_ok()); + // The portal's answer is hostile input: an address it gives may not reach past where + // the answer was read (into the local network, unless the portal is there) or a + // forbidden address, however the portal's own address is spelled. + d.resources.retain(|r| crate::address::check_reach(&r.url, reach).is_ok()); // So may its pictures', fetched as results are shown. - d.thumbnail = d.thumbnail.take().filter(|u| crate::address::check(u, Some(from)).is_ok()); + d.thumbnail = d.thumbnail.take().filter(|u| crate::address::check_reach(u, reach).is_ok()); d.resources.sort_by_key(|r| rank(&r.format)); d.resources.truncate(MAX_RESOURCES); } @@ -838,9 +840,9 @@ fn arcgis_words(q: &str) -> String { /// A web map's layers (its operational layers, those in groups too) RustGIS adds: ArcGIS services, /// named by their titles. -fn web_map_layers(v: &Value, from: &str) -> Result, String> { +fn web_map_layers(v: &Value, reach: Reach) -> Result, String> { // A layer in a group is named after the group too (groups often repeat their layers' titles). - fn walk(layers: &Value, depth: usize, group: &str, out: &mut Vec, from: &str) { + fn walk(layers: &Value, depth: usize, group: &str, out: &mut Vec, reach: Reach) { for l in layers.as_array().into_iter().flatten().take(500) { if out.len() >= MAX_FILES { return; @@ -854,10 +856,10 @@ fn web_map_layers(v: &Value, from: &str) -> Result, String> { if depth < 6 && let Some(inner) = l.get("layers") { - walk(inner, depth + 1, &named, out, from); + walk(inner, depth + 1, &named, out, reach); } let url = text(l, "url", 2048); - if let Some(mut r) = classify("ArcGIS REST", "", &url).filter(|r| crate::address::check(&r.url, Some(from)).is_ok()) { + if let Some(mut r) = classify("ArcGIS REST", "", &url).filter(|r| crate::address::check_reach(&r.url, reach).is_ok()) { if !named.is_empty() { r.format = named; } @@ -867,7 +869,7 @@ fn web_map_layers(v: &Value, from: &str) -> Result, String> { } let ops = v.get("operationalLayers").ok_or("not an ArcGIS web map (it has no operational layers)")?; let mut out = Vec::new(); - walk(ops, 0, "", &mut out, from); + walk(ops, 0, "", &mut out, reach); Ok(out) } @@ -1232,12 +1234,13 @@ impl Portal { } } - /// The files a dataset's listing ([`Dataset::listing`], fetched from `from`) offers: those - /// RustGIS adds, named by their path in the dataset. - pub fn parse_listing(&self, from: &str, bytes: &[u8]) -> Result, String> { + /// The files a dataset's listing ([`Dataset::listing`], fetched from `from` and read within + /// `reach`, which the files' addresses are judged by) offers: those RustGIS adds, named by + /// their path in the dataset. + pub fn parse_listing(&self, from: &str, reach: Reach, bytes: &[u8]) -> Result, String> { let v: Value = serde_json::from_slice(bytes).map_err(|_| format!("{}: the listing isn't JSON", self.label()))?; if self.kind == Kind::ArcGis { - return web_map_layers(&v, from); + return web_map_layers(&v, reach); } let entries = v.as_array().ok_or_else(|| format!("{}: not a listing of files", self.label()))?; // `…/api/datasets/{owner}/{name}/tree/…`: the dataset. @@ -1280,7 +1283,7 @@ impl Portal { .any(|x| lower.ends_with(x)); addable.then_some(Resource { format: path, url, using: Use::File }) }) - .filter(|r| crate::address::check(&r.url, Some(from)).is_ok()) + .filter(|r| crate::address::check_reach(&r.url, reach).is_ok()) .take(MAX_FILES) .collect(); out.sort_by(|a, b| a.format.cmp(&b.format)); @@ -1352,10 +1355,9 @@ mod tests { #[test] fn answers() { - let from = "https://catalog.data.gov/search?q=parks"; let dg = br#"{"results":[{"slug":"parks","title":"Parks","description":"Parks of a city","organization":{"name":"City"},"spatial_shape":{"type":"Polygon","coordinates":[[[-122.5,47.5],[-122.2,47.5],[-122.2,47.7],[-122.5,47.5]]]},"dcat":{"distribution":[{"downloadURL":"https://x.org/p.csv","mediaType":"text/csv"},{"downloadURL":"https://x.org/p.geojson","mediaType":"application/geo+json"},{"accessURL":"http://127.0.0.1/p.geojson","format":"GeoJSON"},{"downloadURL":"https://x.org/p.html","format":"HTML"}]}},{"slug":"report","title":"A report","dcat":{"distribution":[{"downloadURL":"https://x.org/r.pdf"}]}}],"sort":"relevance"}"#; let p = Portal::new(None, None).unwrap(); - let ds = p.parse(from, dg, None, "").unwrap(); + let ds = p.parse(Reach::Public, dg, None, "").unwrap(); assert_eq!(ds.len(), 1, "a dataset with nothing to add is left out"); let d = &ds[0]; assert_eq!((d.title.as_str(), d.organization.as_str()), ("Parks", "City")); @@ -1363,30 +1365,38 @@ mod tests { assert_eq!(d.bbox, Some([-122.5, 47.5, -122.2, 47.7])); // GeoJSON first, the local-network address left out, the page not a resource. assert_eq!(d.resources.iter().map(|r| r.format.as_str()).collect::>(), vec!["GeoJSON", "CSV"]); + // An answer read on the local network (a portal there, whatever its name) keeps it: the + // addresses are judged by where the answer was read. + let local = p.parse(Reach::Local, dg, None, "").unwrap(); + assert!(local[0].resources.iter().any(|r| r.url == "http://127.0.0.1/p.geojson"), "{:?}", local[0].resources); // Kept to a box: a dataset elsewhere goes. - assert!(p.parse(from, dg, Some([0.0, 0.0, 1.0, 1.0]), "").unwrap().is_empty()); - assert_eq!(p.parse(from, dg, Some([-123.0, 47.0, -122.0, 48.0]), "").unwrap().len(), 1); - assert!(p.parse(from, b"", None, "").is_err() && p.parse(from, b"{}", None, "").is_err()); + assert!(p.parse(Reach::Public, dg, Some([0.0, 0.0, 1.0, 1.0]), "").unwrap().is_empty()); + assert_eq!(p.parse(Reach::Public, dg, Some([-123.0, 47.0, -122.0, 48.0]), "").unwrap().len(), 1); + assert!(p.parse(Reach::Public, b"", None, "").is_err() && p.parse(Reach::Public, b"{}", None, "").is_err()); let soc = br#"{"results":[{"resource":{"id":"enfh-gkve","name":"Parks Properties","type":"dataset","columns_datatype":["Text","MultiPolygon"]},"metadata":{"domain":"data.cityofnewyork.us"},"permalink":"https://data.cityofnewyork.us/d/enfh-gkve"},{"resource":{"id":"nc67-uf89","name":"Violations","type":"dataset","columns_datatype":["Text"]},"metadata":{"domain":"data.cityofnewyork.us"}},{"resource":{"id":"bad","name":"x","type":"dataset","columns_datatype":["Point"]},"metadata":{"domain":"evil host"}}]}"#; let s = Portal::new(Some("socrata"), None).unwrap(); - let ds = s.parse("https://api.us.socrata.com/api/catalog/v1?q=parks", soc, None, "").unwrap(); + let ds = s.parse(Reach::Public, soc, None, "").unwrap(); assert_eq!(ds.len(), 1); assert_eq!(ds[0].resources[0].url, "https://data.cityofnewyork.us/resource/enfh-gkve.geojson?%24limit=50000"); let hub = br#"{"type":"FeatureCollection","features":[{"id":"c5ef","properties":{"id":"c5ef","title":"parks","type":"Feature Service","owner":"nyc","url":"https://services1.arcgis.com/S/arcgis/rest/services/parks/FeatureServer","extent":{"type":"Polygon","coordinates":[[[-73.9,40.76],[-73.87,40.76],[-73.87,40.74],[-73.9,40.76]]]}}},{"properties":{"title":"no url"}}]}"#; let h = Portal::new(Some("arcgis-hub"), None).unwrap(); - let ds = h.parse("https://hub.arcgis.com/api/search/v1/collections/dataset/items?q=parks", hub, None, "").unwrap(); + let ds = h.parse(Reach::Public, hub, None, "").unwrap(); assert_eq!(ds.len(), 1); assert_eq!(ds[0].resources[0].using, Use::Service { kind: "arcgis", layer: None }); assert_eq!(ds[0].bbox, Some([-73.9, 40.74, -73.87, 40.76])); let ckan = br#"{"success":true,"result":{"count":1,"results":[{"name":"lakes","title":"Lakes","notes":"All lakes","organization":{"title":"NRCan"},"extras":[{"key":"spatial","value":"{\"type\":\"Polygon\",\"coordinates\":[[[-80,43],[-79,43],[-79,44],[-80,43]]]}"}],"resources":[{"format":"WMS","url":"https://maps.example.ca/wms?service=WMS"},{"format":"SHP","url":"https://x.ca/lakes.zip"}]}]}}"#; let c = Portal::new(Some("ckan"), Some("https://open.canada.ca/data")).unwrap(); - let ds = c.parse("https://open.canada.ca/data/api/3/action/package_search?q=lakes", ckan, None, "").unwrap(); + let ds = c.parse(Reach::Public, ckan, None, "").unwrap(); assert_eq!(ds[0].page.as_deref(), Some("https://open.canada.ca/data/dataset/lakes")); assert_eq!(ds[0].resources.iter().map(|r| r.format.as_str()).collect::>(), vec!["Shapefile", "WMS"]); - assert!(c.parse("x", br#"{"success":false,"error":{"message":"Bad request"}}"#, None, "").unwrap_err().contains("Bad request")); + assert!( + c.parse(Reach::Public, br#"{"success":false,"error":{"message":"Bad request"}}"#, None, "") + .unwrap_err() + .contains("Bad request") + ); } #[test] @@ -1435,33 +1445,36 @@ mod tests { #[test] fn web_service_answers() { let agol = Portal::new(Some("arcgis-portal"), None).unwrap(); - let from = "https://www.arcgis.com/sharing/rest/search?q=parks"; let a = br#"{"total":3,"results":[{"id":"abc123","type":"Feature Service","title":"Parks","owner":"city","snippet":"City parks","url":"https://services.arcgis.com/x/arcgis/rest/services/Parks/FeatureServer/0","extent":[[-122.5,47.5],[-122.2,47.7]]},{"id":"def456","type":"GeoJson","title":"Trails"},{"id":"bad id","type":"Map Service","url":"https://x.org/arcgis/rest/services/a/MapServer"},{"id":"ghi789","type":"Image Service","title":"Imagery","url":"https://x.org/arcgis/rest/services/i/ImageServer"}]}"#; - let ds = agol.parse(from, a, None, "").unwrap(); + let ds = agol.parse(Reach::Public, a, None, "").unwrap(); assert_eq!(ds.len(), 3, "the item with a bad id is left out"); assert_eq!(ds[0].resources[0].using, Use::Service { kind: "arcgis", layer: Some("0".into()) }); assert_eq!(ds[0].bbox, Some([-122.5, 47.5, -122.2, 47.7])); assert_eq!(ds[0].page.as_deref(), Some("https://www.arcgis.com/home/item.html?id=abc123")); assert_eq!(ds[1].resources[0].url, "https://www.arcgis.com/sharing/rest/content/items/def456/data"); assert_eq!(ds[2].resources[0].url, "https://x.org/arcgis/rest/services/i/ImageServer"); - assert!(agol.parse(from, br#"{"error":{"code":400,"message":"Invalid query"}}"#, None, "").unwrap_err().contains("Invalid query")); + assert!( + agol.parse(Reach::Public, br#"{"error":{"code":400,"message":"Invalid query"}}"#, None, "") + .unwrap_err() + .contains("Invalid query") + ); let oam = Portal::new(Some("openaerialmap"), None).unwrap(); let o = br#"{"meta":{"found":2},"results":[{"_id":"1","uuid":"https://oin.s3.amazonaws.com/a/b.tif","title":"Village","provider":"HOT","platform":"uav","gsd":0.05,"acquisition_end":"2026-09-20T06:00:00Z","bbox":[-77.3,4.85,-77.2,4.86]},{"_id":"2","uuid":"https://oin.s3.amazonaws.com/a/c.tif","title":"Coast","bbox":[1,2,3]}]}"#; - let ds = oam.parse("https://api.openaerialmap.org/meta", o, Some([-80.0, 0.0, -70.0, 10.0]), "").unwrap(); + let ds = oam.parse(Reach::Public, o, Some([-80.0, 0.0, -70.0, 10.0]), "").unwrap(); assert_eq!(ds.len(), 2, "an image whose box isn't one is kept"); assert_eq!((ds[0].kind.as_str(), ds[0].date.as_str()), ("uav · 5 cm per pixel", "2026-09-20")); - assert_eq!(oam.parse("https://api.openaerialmap.org/meta", o, None, "coast").unwrap()[0].title, "Coast"); + assert_eq!(oam.parse(Reach::Public, o, None, "coast").unwrap()[0].title, "Coast"); let dem = Portal::new(Some("usgs-dem"), None).unwrap(); let d = br#"{"total":3,"items":[{"title":"USGS 1/3 Arc Second n47w123 20121001","downloadURL":"https://prd-tnm.s3.amazonaws.com/x/historical/n47w123/a.tif","publicationDate":"2012-10-01","boundingBox":{"minX":-123,"minY":46,"maxX":-122,"maxY":47}},{"title":"USGS 1/3 Arc Second n47w123 20240101","downloadURL":"https://prd-tnm.s3.amazonaws.com/x/current/n47w123/b.tif","publicationDate":"2024-01-01"},{"title":"USGS 1/3 Arc Second n47w123 20250813","downloadURL":"https://prd-tnm.s3.amazonaws.com/x/historical/n47w123/c.tif","publicationDate":"2025-08-13"}]}"#; - let ds = dem.parse("https://tnmaccess.nationalmap.gov/api/v1/products", d, None, "").unwrap(); + let ds = dem.parse(Reach::Public, d, None, "").unwrap(); assert_eq!(ds.len(), 1, "one per tile"); assert!(ds[0].resources[0].url.ends_with("/current/n47w123/b.tif"), "the current edition"); let ign = Portal::new(Some("ign-lidar"), None).unwrap(); let i = br#"{"features":[{"id":"metadata.1","geometry":{"type":"Polygon","coordinates":[[[2.3,48.8],[2.31,48.8],[2.31,48.81],[2.3,48.8]]]},"properties":{"coordonnees_nw":"0650-6858","nombre_points":17455527,"date_fin_acquisition":"2023-03-01Z","url_npl":"https://data.geopf.fr/telechargement/download/x/LHD_FXX_0650_6858_PTS_LAMB93_IGN69.copc.laz"}},{"id":"metadata.2","properties":{"url_npl":"http://x.org/a.laz"}}]}"#; - let ds = ign.parse("https://data.geopf.fr/wfs?x", i, None, "").unwrap(); + let ds = ign.parse(Reach::Public, i, None, "").unwrap(); assert_eq!(ds.len(), 1); assert_eq!( (ds[0].title.as_str(), ds[0].kind.as_str(), ds[0].date.as_str()), @@ -1470,30 +1483,30 @@ mod tests { let gl = Portal::new(Some("geolens"), None).unwrap(); let g = br#"{"type":"FeatureCollection","features":[{"id":"8c26-1","properties":{"title":"Tracks","record_type":"vector_dataset","geometry_type":"MULTILINESTRING","feature_count":12}},{"id":"r1","properties":{"title":"DEM","record_type":"raster_dataset","band_count":1}},{"id":"../x","properties":{"title":"Bad"}}]}"#; - let ds = gl.parse("https://datasets.geolibre.app/api/search/datasets/?q=", g, None, "").unwrap(); + let ds = gl.parse(Reach::Public, g, None, "").unwrap(); assert_eq!(ds.len(), 1); assert_eq!(ds[0].resources[0].url, "https://datasets.geolibre.app/api/collections/8c26-1/items?limit=1000"); assert_eq!(ds[0].resources[0].using, Use::Features, "read page by page"); let hf = Portal::new(Some("huggingface"), None).unwrap(); let h = br#"[{"id":"giswqs/geospatial","downloads":10,"gated":false,"private":false,"tags":["license:mit","region:us"]},{"id":"a/gated","gated":"manual"},{"id":"noslash"}]"#; - let ds = hf.parse("https://huggingface.co/api/datasets?search=x", h, None, "").unwrap(); + let ds = hf.parse(Reach::Public, h, None, "").unwrap(); assert_eq!(ds.len(), 1); assert_eq!((ds[0].kind.as_str(), ds[0].description.as_str(), ds[0].resources.len()), ("Dataset · 10 downloads", "license: mit", 0)); let listing = ds[0].listing.clone().unwrap(); assert_eq!(Some(listing.clone()), hf.listing_of("giswqs/geospatial")); let files = br#"[{"type":"directory","path":"naip"},{"type":"file","path":"naip/a b.tif"},{"type":"file","path":"README.md"},{"type":"file","path":"x/../../etc.geojson"},{"type":"file","path":"z.pmtiles"}]"#; - let r = hf.parse_listing(&listing, files).unwrap(); + let r = hf.parse_listing(&listing, Reach::Public, files).unwrap(); assert_eq!(r.iter().map(|r| r.format.as_str()).collect::>(), vec!["naip/a b.tif", "z.pmtiles"]); assert_eq!(r[0].url, "https://huggingface.co/datasets/giswqs/geospatial/resolve/main/naip/a%20b.tif"); - assert!(hf.parse_listing("https://huggingface.co/api/datasets/../tree/main", files).is_err()); - assert!(hf.parse_listing(&listing, b"{}").is_err()); + assert!(hf.parse_listing("https://huggingface.co/api/datasets/../tree/main", Reach::Public, files).is_err()); + assert!(hf.parse_listing(&listing, Reach::Public, b"{}").is_err()); let odp = Portal::new(Some("ocean-data"), None).unwrap(); let o = br#"{"features":[{"id":"cd48-1","bbox":[-64.6,17.7,-64.5,17.8],"properties":{"title":"Published - Coral sites","description":"Reef survey"}},{"id":"x2","bbox":[10,50,11,51],"properties":{"title":"Kelp"}}]}"#; - let ds = odp.parse("https://api.hubocean.earth/api/stac/search?limit=1000", o, None, "coral").unwrap(); + let ds = odp.parse(Reach::Public, o, None, "coral").unwrap(); assert_eq!((ds.len(), ds[0].title.as_str()), (1, "Coral sites")); - assert_eq!(odp.parse("https://api.hubocean.earth/api/stac/search", o, Some([9.0, 49.0, 12.0, 52.0]), "").unwrap()[0].title, "Kelp"); + assert_eq!(odp.parse(Reach::Public, o, Some([9.0, 49.0, 12.0, 52.0]), "").unwrap()[0].title, "Kelp"); // Hostile answers: never a panic, an error or nothing. for k in ["arcgis-portal", "openaerialmap", "usgs-dem", "ign-lidar", "geolens", "huggingface", "ocean-data"] { @@ -1506,8 +1519,8 @@ mod tests { b"{\"features\":[{\"properties\":7}]}", b"{\"items\":\"x\"}", ] { - let _ = p.parse("https://x.org/", junk, Some([0.0, 0.0, 1.0, 1.0]), "a"); - let _ = p.parse_listing("https://huggingface.co/api/datasets/a/b/tree/main", junk); + let _ = p.parse(Reach::Public, junk, Some([0.0, 0.0, 1.0, 1.0]), "a"); + let _ = p.parse_listing("https://huggingface.co/api/datasets/a/b/tree/main", Reach::Public, junk); } } } @@ -1533,7 +1546,7 @@ mod tests { assert_eq!(oam.paging(&ou, b"junk"), (None, None)); // A web map's item, its kind, date and picture, and its layers. let a = br#"{"results":[{"id":"w1","type":"Web Map","title":"Isaias","owner":"patrick_rea","modified":1792108800000,"thumbnail":"thumbnail/t.png"}]}"#; - let ds = p.parse("https://gis.earthdata.nasa.gov/portal/sharing/rest/search", a, None, "").unwrap(); + let ds = p.parse(Reach::Public, a, None, "").unwrap(); let d = &ds[0]; assert_eq!((d.kind.as_str(), d.date.as_str()), ("Web map", "2026-10-16")); assert_eq!( @@ -1543,10 +1556,10 @@ mod tests { let listing = d.listing.clone().unwrap(); assert_eq!(Some(listing.clone()), p.listing_of("w1")); let wm = br#"{"operationalLayers":[{"title":"Optical","url":"https://gis.earthdata.nasa.gov/portal/rest/services/a/ImageServer"},{"layerType":"GroupLayer","title":"Sept","layers":[{"title":"Flood","url":"https://gis.earthdata.nasa.gov/portal/rest/services/b/MapServer/2"}]},{"title":"Notes"},{"title":"Local","url":"http://169.254.169.254/rest/services/c/FeatureServer/0"}]}"#; - let layers = p.parse_listing(&listing, wm).unwrap(); + let layers = p.parse_listing(&listing, Reach::Public, wm).unwrap(); assert_eq!(layers.iter().map(|r| r.format.as_str()).collect::>(), vec!["Optical", "Sept › Flood"]); assert_eq!(layers[1].using, Use::Service { kind: "arcgis", layer: Some("2".into()) }); - assert!(p.parse_listing(&listing, b"{}").is_err()); + assert!(p.parse_listing(&listing, Reach::Public, b"{}").is_err()); assert_eq!(day_of_ms(0.0), "1970-01-01"); assert_eq!(day_of_ms(951_782_400_000.0), "2000-02-29"); assert_eq!(day_of_ms(f64::NAN), ""); @@ -1559,7 +1572,7 @@ mod tests { assert!(!p.needs_query() && !p.needs_place()); assert_eq!(p.search_url("", None, 20), "https://stac.dynamical.org/catalog.json"); let c = br#"{"links":[{"rel":"root","href":"https://stac.dynamical.org/catalog.json"},{"rel":"child","href":"https://stac.dynamical.org/noaa-gfs-forecast/collection.json","title":"NOAA GFS forecast"},{"rel":"child","href":"https://stac.dynamical.org/noaa-gfs-forecast-virtual/collection.json","title":"virtual"},{"rel":"child","href":"https://stac.dynamical.org/ecmwf-ifs-ens-forecast-15-day-0-25-degree/collection.json"},{"rel":"child","href":"https://stac.dynamical.org/odd/collection.json"}]}"#; - let ds = p.parse("https://stac.dynamical.org/catalog.json", c, None, "").unwrap(); + let ds = p.parse(Reach::Public, c, None, "").unwrap(); assert_eq!( ds.iter().map(|d| d.resources[0].url.as_str()).collect::>(), vec![ @@ -1569,7 +1582,7 @@ mod tests { ); assert_eq!((ds[0].title.as_str(), ds[0].organization.as_str(), ds[0].kind.as_str()), ("NOAA GFS forecast", "NOAA", "Forecast")); assert_eq!(ds[0].resources[0].using, Use::Zarr); - assert_eq!(p.parse("https://stac.dynamical.org/catalog.json", c, None, "ecmwf").unwrap().len(), 1); + assert_eq!(p.parse(Reach::Public, c, None, "ecmwf").unwrap().len(), 1); } #[test] diff --git a/crates/ui-egui/src/connectiontree.rs b/crates/ui-egui/src/connectiontree.rs index 462e73cd07..6f6e27346a 100644 --- a/crates/ui-egui/src/connectiontree.rs +++ b/crates/ui-egui/src/connectiontree.rs @@ -10,7 +10,10 @@ use std::sync::Arc; use egui::collapsing_header::CollapsingState; use egui::{Label, RichText, Sense, Ui}; use rustgis_engine::connections::{Connection, DATABASE_KINDS}; -use rustgis_engine::render::rustgis_tiles::{address::Origin, cache, stac}; +use rustgis_engine::render::rustgis_tiles::{ + address::{Origin, Reach}, + cache, stac, +}; use rustgis_engine::sources::Source; use serde_json::{Value, json}; @@ -212,6 +215,12 @@ fn listing(v: &Value, first: Option, documents: Vec) -> Listing { /// An answer arrived: asks again with it (and what came before). A service's discovery may need /// further documents, which are fetched in turn. fn advance(app: &mut RustGisApp, id: &str, mut f: Fetch, fetched: cache::Fetched) -> Entry { + // A document read from the internet is recorded so, as Add From Service's fetch records it: + // the service's discovery, which reads the answer by its address, then holds what it links to + // and the layers it lists there. + if fetched.origin.reach() == Reach::Public { + cache::restrict_to_public(&f.pending); + } let Ok(text) = crate::service_text(fetched.bytes) else { return Entry::Failed(tl!("The answer isn't UTF-8 text").to_string()); }; @@ -1127,6 +1136,48 @@ mod tests { assert!(rustgis_engine::render::rustgis_tiles::logins::apply(&address).unwrap().is_none()); } + /// A service connection's documents are recorded where they were read: one at a public-looking + /// name read from the internet has its link into the local network refused, naming it; read on + /// the local network, the link is followed. + #[test] + fn a_service_connections_documents_hold_their_links_where_they_were_read() { + for (n, observed) in [(1, Reach::Public), (2, Reach::Local)] { + let _turn = crate::fetching::turn(); + let linked = format!("http://10.0.{n}.5/collections"); + let landing = json!({"links":[{"rel":"data","type":"application/json","href":linked}]}).to_string(); + let collections = json!({"collections":[]}).to_string(); + let asked = std::sync::Arc::new(std::sync::Mutex::new(Vec::new())); + let log = asked.clone(); + cache::set_fetcher_with_origin(move |url, ceiling, done, _| { + let clean = cache::split_download_limit(&url).0.to_string(); + log.lock().unwrap().push((clean.clone(), ceiling)); + let body = if clean.contains("10.0.") { &collections } else { &landing }; + let origin = Origin::with_observed_reach(&clean, observed.min(ceiling)).unwrap(); + done(Ok(cache::Fetched { bytes: body.clone().into_bytes(), origin })); + }); + let mut app = RustGisApp::new(rustgis_engine::Session::new(rustgis_engine::Project::default())); + let address = format!("https://tree-{n}.corp-looks-public.example/ogc"); + let saved = app.run("connection.new", json!({"kind": "ogcapi", "address": address})).unwrap(); + let c = app.session.connections.connections.iter().find(|c| c.id == saved["id"].as_str().unwrap()).unwrap().clone(); + start(&mut app, &c, ""); + for _ in 0..3 { + poll(&mut app, &egui::Context::default()); + } + let asked = asked.lock().unwrap().clone(); + let entry = app.ui.connection_tree.entries.get(&(c.id.clone(), String::new())); + if observed == Reach::Local { + assert!(asked.iter().any(|(u, r)| u.starts_with(&linked) && *r == Reach::Local), "{asked:?}"); + assert!(matches!(entry, Some(Entry::Ready(_))), "the level was read"); + } else { + assert!(!asked.iter().any(|(u, _)| u.starts_with(&linked)), "the link is not fetched: {asked:?}"); + assert!( + matches!(entry, Some(Entry::Failed(e)) if e.contains(&linked) && e.contains("local network")), + "the refusal is said" + ); + } + } + } + #[test] fn a_tileset_step_names_its_layer_and_a_refused_one_is_not_recorded() { let _turn = crate::fetching::turn(); @@ -1134,6 +1185,9 @@ mod tests { let api = "https://x.org/collections"; let tiled = r#"{"collections": [{"id": "relief", "links": [{"rel": "tilesets-map", "href": "https://x.org/relief/map/tiles"}]}]}"#; let opened = h.state().session.opened; + // The service's document was read from the internet (the dialog's fetch records it): a + // template into the local network is refused. + cache::restrict_to_public(api); let step = |fallback: &str, origin: Option<&str>| { let slot = Slot::default(); *slot.lock().unwrap() = Some(Err("unreachable".to_string())); diff --git a/crates/ui-egui/src/cswui.rs b/crates/ui-egui/src/cswui.rs index 0a722f70ca..5fa0b60d5d 100644 --- a/crates/ui-egui/src/cswui.rs +++ b/crates/ui-egui/src/cswui.rs @@ -80,7 +80,8 @@ pub fn search(app: &mut RustGisApp, start: u64) { st.next = None; st.asked = asked; } - st.waiting = Some((p, crate::fetch_into(&request))); + // Recorded if read from the internet, so `catalog.search` holds the links it lists there. + st.waiting = Some((p, crate::fetch_document_into(&request))); } Err(e) => app.ui.csw.error = Some(e), } @@ -210,7 +211,8 @@ fn records(app: &mut RustGisApp, ui: &mut egui::Ui) { let what: String = what.chars().take(28).collect(); let text = if what.is_empty() { tl!(*label).to_string() } else { format!("{} · {what}", tl!(*label)) }; if ui.small_button(text).on_hover_text(url).clicked() { - follow = Some((kind.to_string(), url.to_string(), title.to_string())); + let public = l.get("fromDocument").and_then(Value::as_bool) == Some(true); + follow = Some((kind.to_string(), url.to_string(), title.to_string(), public)); } } if !any { @@ -230,10 +232,11 @@ fn records(app: &mut RustGisApp, ui: &mut egui::Ui) { if let Some(b) = zoom { let _ = app.run("map.zoomToExtent", json!({"extent": b})); } - if let Some((kind, url, title)) = follow { + if let Some((kind, url, title, public)) = follow { app.dialogs.error = None; + // A link from a catalogue read from the internet leads only there (`fromDocument`). let r = if kind == "download" { - app.run("ui.addUrl", json!({"url": url, "name": title})).map(|_| ()) + app.run("ui.addUrl", json!({"url": url, "name": title, "fromDocument": public})).map(|_| ()) } else { // A service: connected to in this dialog, its type picked (the catalogue's results // stay for Catalogue). @@ -245,7 +248,7 @@ fn records(app: &mut RustGisApp, ui: &mut egui::Ui) { "ogcapi" => "ogcapi", _ => "arcgis", }; - app.run("ui.addService", json!({"url": url, "type": app.dialogs.mode})).map(|_| ()) + app.run("ui.addService", json!({"url": url, "type": app.dialogs.mode, "fromDocument": public})).map(|_| ()) }; if let Err(e) = r { app.ui.csw.error = Some(e); @@ -258,3 +261,56 @@ fn records(app: &mut RustGisApp, ui: &mut egui::Ui) { } } } + +#[cfg(test)] +mod tests { + use super::*; + use rustgis_engine::render::rustgis_tiles::{ + address::{Origin, Reach}, + cache, + }; + + /// A catalogue's answer read from the internet holds the services its records link to there: + /// clicking a record's service reads its capabilities only from the internet. Read on the local + /// network, at a public-looking name, its records keep a service on a private address, and + /// clicking it reads that service as the user's own. + #[test] + fn a_catalogues_services_are_read_within_the_reach_of_its_answer() { + use egui_kittest::kittest::Queryable; + for (n, observed) in [(1, Reach::Public), (2, Reach::Local)] { + let _turn = crate::fetching::turn(); + let csw = format!("https://csw-{n}.corp-looks-public.example/csw"); + let service = + if observed == Reach::Public { format!("https://csw-service-{n}.example/wms") } else { format!("http://10.0.{n}.4/wms") }; + let answer = format!( + r#"aRoads{service}"# + ); + let asked = std::sync::Arc::new(std::sync::Mutex::new(Vec::new())); + let log = asked.clone(); + cache::set_fetcher_with_origin(move |url, ceiling, done, _| { + let clean = cache::split_download_limit(&url).0.to_string(); + log.lock().unwrap().push((clean.clone(), ceiling)); + let origin = Origin::with_observed_reach(&clean, observed.min(ceiling)).unwrap(); + done(Ok(cache::Fetched { bytes: answer.clone().into_bytes(), origin })); + }); + let app = RustGisApp::new(rustgis_engine::Session::new(rustgis_engine::Project::default())); + let mut h = egui_kittest::Harness::builder().with_size(egui::vec2(1400.0, 900.0)).with_max_steps(16).build_ui_state( + |ui, app: &mut RustGisApp| { + let ctx = ui.ctx().clone(); + app.logic(&ctx); + app.ui(ui); + }, + app, + ); + h.state_mut().run("ui.addService", json!({"url": csw, "type": "csw"})).unwrap(); + h.run_steps(3); + assert_eq!(h.state().ui.csw.records.len(), 1, "{:?}", h.state().ui.csw.error); + h.get_by_label("WMS · wms").click(); + h.run_steps(2); + let caps = rustgis_engine::data::ogc::capabilities_url(&service, Some("wms")); + let asked = asked.lock().unwrap().clone(); + assert!(asked.contains(&(caps.clone(), observed)), "the service, its catalogue read {observed:?}: {asked:?}"); + assert_eq!(cache::ceiling_for(&caps), observed); + } + } +} diff --git a/crates/ui-egui/src/earthaccessui.rs b/crates/ui-egui/src/earthaccessui.rs index b0f10a3155..38f47f62cb 100644 --- a/crates/ui-egui/src/earthaccessui.rs +++ b/crates/ui-egui/src/earthaccessui.rs @@ -5,13 +5,14 @@ //! this computer (`earthdata.login` with `remember`). Requests go off the frame through the tile //! cache's downloads, and the remembered token is read off the frame too. -use rustgis_engine::render::rustgis_tiles::cache; use rustgis_engine::render::rustgis_tiles::earthdata::{self, Collection, Granule}; +use rustgis_engine::render::rustgis_tiles::{address::Reach, cache}; use serde_json::{Value, json}; use crate::{RustGisApp, Slot}; -type Answer = Slot, String>>; +/// An answer, with the reach it was read at. +type Answer = Slot, Reach), String>>; /// Granules asked for a page. const PAGE: usize = 25; @@ -49,6 +50,9 @@ pub struct State { pub start: String, pub end: String, pub granules: Vec, + /// Where the granules listed were read (the narrowest of their pages): their files and + /// pictures are fetched within it. + granules_reach: Reach, searched: bool, page: usize, more: bool, @@ -94,6 +98,7 @@ impl Default for State { restoring: false, was_remembered: false, thumbs: Default::default(), + granules_reach: Reach::Public, waiting: None, error: None, info: None, @@ -101,11 +106,9 @@ impl Default for State { } } +/// Fetches a search RustGIS names off the frame, landing with the reach it was read at. fn fetch(url: &str) -> Answer { - let slot: Answer = Slot::default(); - let land = slot.clone(); - cache::download(url, Box::new(move |r| *land.lock().unwrap_or_else(|e| e.into_inner()) = Some(r))); - slot + crate::fetch_within(url, cache::MAX_DOWNLOAD, None, Reach::Local) } /// Lands the preview pictures fetched, as small textures. @@ -118,7 +121,7 @@ fn poll_thumbs(app: &mut RustGisApp, ctx: &egui::Context) { continue; }; // Browse images are up to 1000 px: kept at a card's size. - *thumb = match r.and_then(|b| image::load_from_memory(&b).map_err(|e| e.to_string())) { + *thumb = match r.and_then(|(b, _)| image::load_from_memory(&b).map_err(|e| e.to_string())) { Ok(img) => { let small = img.thumbnail(160, 160).to_rgba8(); let size = [small.width() as usize, small.height() as usize]; @@ -142,6 +145,8 @@ pub fn poll(app: &mut RustGisApp, ctx: &egui::Context) { return; }; let Some((asked, _)) = app.ui.earthaccess.waiting.take() else { return }; + let reach = r.as_ref().map_or(Reach::Public, |(_, reach)| *reach); + let r = r.map(|(bytes, _)| bytes); let done = match asked { Asked::Collections { more, page } => r.and_then(|b| earthdata::parse_collections(&b)).map(|found| { let st = &mut app.ui.earthaccess; @@ -167,7 +172,10 @@ pub fn poll(app: &mut RustGisApp, ctx: &egui::Context) { st.searched = true; if !more { st.granules.clear(); + st.granules_reach = reach; } + // The granules' links came in this answer: they reach no further than it was read. + st.granules_reach = st.granules_reach.min(reach); st.granules.extend(found); draw_footprints(app) }), @@ -630,9 +638,7 @@ fn granules(app: &mut RustGisApp, ui: &mut egui::Ui, t: &crate::theme::Tokens, w if st.thumbs.len() >= MAX_THUMBS { break; } - let slot: Answer = Slot::default(); - let land = slot.clone(); - cache::download_limited(&u, MAX_THUMB_BYTES, Box::new(move |r| *land.lock().unwrap_or_else(|e| e.into_inner()) = Some(r))); + let slot = crate::fetch_within(&u, MAX_THUMB_BYTES, None, st.granules_reach); st.thumbs.insert(u, Thumb::Loading(slot)); } if let Some(b) = zoom { @@ -646,7 +652,9 @@ fn granules(app: &mut RustGisApp, ui: &mut egui::Ui, t: &crate::theme::Tokens, w Some(tl!("Add an Earthdata Login token (Earthdata Login, above) to put NASA GeoTIFFs on the map.").to_string()); return; } - match app.run("ui.addUrl", json!({"url": url, "name": name, "zoom": true})) { + // A link CMR's answer gave, read from the internet, leads only there (`fromDocument`). + let public = app.ui.earthaccess.granules_reach == Reach::Public; + match app.run("ui.addUrl", json!({"url": url, "name": name, "zoom": true, "fromDocument": public})) { Ok(_) => app.ui.earthaccess.added.push(url), Err(e) => app.ui.earthaccess.error = Some(e), } @@ -686,6 +694,55 @@ mod tests { earthdata::set_secret_store(None); } + /// A granule's GeoTIFF that CMR's answer, read from the internet, links to is added only from + /// there; from an answer read on the local network (a mirror at CMR's name), one on a private + /// address is added as the user's own would be. + #[test] + fn granules_are_added_within_the_reach_of_the_answer_listing_them() { + use egui_kittest::kittest::Queryable; + use rustgis_engine::render::rustgis_tiles::address::Origin; + for (n, observed) in [(1, Reach::Public), (2, Reach::Local)] { + let _turn = crate::fetching::turn(); + let tif = if observed == Reach::Public { + format!("https://granules-{n}.example/a.B04.tif") + } else { + format!("http://10.0.{n}.6/a.B04.tif") + }; + let answer = json!({"feed":{"entry":[{"id":"G1","title":"Scene","links":[{"rel":"http://esipfed.org/ns/fedsearch/1.1/data#","href":tif}]}]}}).to_string(); + let asked = std::sync::Arc::new(std::sync::Mutex::new(Vec::new())); + let log = asked.clone(); + cache::set_fetcher_with_origin(move |url, ceiling, done, _| { + let clean = cache::split_download_limit(&url).0.to_string(); + log.lock().unwrap().push((clean.clone(), ceiling)); + let origin = Origin::with_observed_reach(&clean, observed.min(ceiling)).unwrap(); + let body = if clean.contains(".tif") { b"not a tiff".to_vec() } else { answer.clone().into_bytes() }; + done(Ok(cache::Fetched { bytes: body, origin })); + }); + let mut app = RustGisApp::new(rustgis_engine::Session::new(rustgis_engine::Project::default())); + app.ui.earthaccess.collection = Some(Collection { id: "C1-TEST".into(), short_name: "TEST".into(), ..Collection::default() }); + search_granules(&mut app, false); + let mut h = egui_kittest::Harness::builder().with_size(egui::vec2(900.0, 900.0)).with_max_steps(16).build_ui_state( + |ui, app: &mut RustGisApp| { + let ctx = ui.ctx().clone(); + app.logic(&ctx); + pane(app, ui); + }, + app, + ); + h.run_steps(2); + assert_eq!(h.state().ui.earthaccess.granules.len(), 1, "{:?}", h.state().ui.earthaccess.error); + assert_eq!(h.state().ui.earthaccess.granules_reach, observed); + h.get_by_label("Add").click(); + h.run_steps(2); + let asked = asked.lock().unwrap().clone(); + assert_eq!(asked.first().map(|(_, c)| *c), Some(Reach::Local), "CMR, which RustGIS names: {asked:?}"); + assert!( + asked.iter().any(|(u, c)| u.starts_with(&tif) && *c == observed), + "the GeoTIFF, its answer read {observed:?}: {asked:?}" + ); + } + } + #[test] fn bounds_and_names() { let g = json!({"type": "MultiPolygon", "coordinates": [[[[1.0, 2.0], [3.0, -4.0], [0.5, 9.0]]]]}); diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index ade5aebcfe..b591f6d654 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -733,6 +733,29 @@ fn fetch_document_as(url: &str, told: fn(Failure) -> E) -> Sl slot } +/// Fetches an address off the frame, connecting no wider than `ceiling`: the reach of the +/// document that named it, as that document's fetch observed it (`Reach::Local` for the user's own +/// address). It lands with the bytes and the reach it was read at, which the addresses it names in +/// turn are fetched within. Nothing is recorded for its address, so a long chain of reads (a +/// service's feature pages, a catalogue's results) adds nothing to the restricted addresses +/// ([`cache::restrict_to_public`]). Native downloads end at `timeout`, if it has one (the usual +/// download's otherwise); the browser's late answer is discarded by the polling read. +pub(crate) fn fetch_within( + url: &str, + max: usize, + timeout: Option, + ceiling: Reach, +) -> Slot, Reach), String>> { + let slot: Slot, Reach), String>> = Slot::default(); + let land = slot.clone(); + let done: cache::FetchedDone = Box::new(move |r| { + let r = r.map(|fetched| (fetched.bytes, fetched.origin.reach())); + *land.lock().unwrap_or_else(|e| e.into_inner()) = Some(r); + }); + cache::download_limited_reaching_with_origin(url, max, timeout, ceiling, done); + slot +} + pub(crate) fn fetch_into_limited(url: &str, max: usize) -> Slot, String>> { let slot: Slot, String>> = Slot::default(); let land = slot.clone(); @@ -4464,6 +4487,16 @@ impl RustGisApp { let resolved_connection = bound.get("connection").and_then(Value::as_str).map(str::to_string); let url = bound.get("url").and_then(Value::as_str).unwrap_or(url); let caps = rustgis_engine::data::ogc::capabilities_url(url, (kind != "auto").then_some(kind)); + // An address a document read from the internet named (a catalogue's or a portal's + // entry, `fromDocument`) leads only there: its capabilities, the documents they + // link to and the layers they list (`service.layers` reads the address's record). + // It can only narrow what the address may reach. + if p.get("fromDocument").and_then(Value::as_bool) == Some(true) { + rustgis_engine::render::rustgis_tiles::address::check_reach(url, Reach::Public) + .map_err(|e| connectionui::translated(&e))?; + cache::restrict_to_public(url); + cache::restrict_to_public(&caps); + } // A refusal is told with what the server said (#509). let slot = fetch_detailed_into(&caps); // The dialog shows the address connected to, however the connection was asked for. @@ -6506,7 +6539,9 @@ impl RustGisApp { resolve.read += 1; // The resolver already carried the current document's binding, or // its absence. A saved connection must not restore it after a hop. - match rustgis_engine::render::rustgis_tiles::address::check(&next, Some(&resolve.doc)) { + // Judged by where the list was read (its record), not by how its + // address is spelled: a public-looking name may connect on the local network. + match rustgis_engine::render::rustgis_tiles::address::check_reach(&next, cache::ceiling_for(&resolve.doc)) { Ok(()) => { resolve.crossed_origin |= rustgis_engine::render::rustgis_tiles::logins::origin(&resolve.doc) != rustgis_engine::render::rustgis_tiles::logins::origin(&next); @@ -8571,6 +8606,8 @@ mod download_service_tests { for (query, count) in [("collections=roads", 0), ("token=RGSYNTH_ui_refused&collections=roads", 1)] { let mut app = RustGisApp::new(rustgis_engine::Session::new(rustgis_engine::Project::default())); let list = format!("https://h.invalid/svc/tiles?{query}"); + // The list was read from the internet (the dialog's fetch records it). + rustgis_engine::render::rustgis_tiles::cache::restrict_to_public(&list); let body = json!({"tilesets":[{"tileMatrixSetId":"WebMercatorQuad", "links":[{"rel":"self", "href":"http://127.0.0.1/tiles"}]}]}) .to_string() diff --git a/crates/ui-egui/src/mapview.rs b/crates/ui-egui/src/mapview.rs index 74c3666fe0..cf040ea335 100644 --- a/crates/ui-egui/src/mapview.rs +++ b/crates/ui-egui/src/mapview.rs @@ -15,6 +15,7 @@ use rustgis_engine::map::layout::TextAlign; use rustgis_engine::map::projection::Flat; use rustgis_engine::map::{Camera, Globe, Projection}; use rustgis_engine::render::rustgis_tiles::Unfinished; +use rustgis_engine::render::rustgis_tiles::{address::Reach, cache}; use rustgis_engine::render::{PlacedLabel, Rendered, View}; use serde_json::{Value, json}; @@ -109,7 +110,15 @@ pub struct Ask { /// The GetFeatureInfo request asked (none for capabilities): its answer format tells what to /// ask next after the service's error. request: Option, - slot: crate::Slot, String>>, + /// The answer, with the reach it was read at. + slot: crate::Slot, Reach), String>>, +} + +/// Asks for a request identify listed, within the layer's reach (`"public"`: a document read from +/// the internet listed the layer, or its capabilities were read from there). +fn ask_within(a: &Value, url: &str) -> crate::Slot, Reach), String>> { + let ceiling = if a["public"] == true { Reach::Public } else { Reach::Local }; + crate::fetch_within(url, rustgis_engine::data::ogc::MAX_INFO_BYTES, None, ceiling) } impl Popup { @@ -134,7 +143,7 @@ impl Popup { if capabilities { fetched.push((url.to_string(), asks.len())); } - let slot = crate::fetch_into_limited(url, rustgis_engine::data::ogc::MAX_INFO_BYTES); + let slot = ask_within(a, url); let request = (!capabilities).then(|| url.to_string()); asks.push(Ask { layer, also: Vec::new(), capabilities, request, slot }); } @@ -4128,7 +4137,18 @@ fn follow_asks(app: &mut RustGisApp, ctx: &egui::Context) { let also: Vec = group.collect(); // The fetch's failure, or an answer that isn't text, is told here; the command tells its // own errors (naming the layer). - let text = match r.and_then(|bytes| rustgis_engine::data::ogc::answer_text(&bytes).map(std::borrow::Cow::into_owned)) { + let text = match r.and_then(|(bytes, reach)| { + // Capabilities read from the internet hold the requests they name there, as identify's + // own read does (the layer then lists them with `"public"`). + if capabilities + && reach == Reach::Public + && let Some((caps, _)) = + app.session.map().tiles.iter().find(|t| t.name == layer).and_then(|t| rustgis_engine::data::ogc::wms_layer_of(&t.url)) + { + cache::restrict_to_public(&caps); + } + rustgis_engine::data::ogc::answer_text(&bytes).map(std::borrow::Cow::into_owned) + }) { Ok(text) => text, Err(e) => { app.session.notify(crate::i18n::fmt("{layer}: {e}", &[("layer", &layer), ("e", &e)]), true); @@ -4156,7 +4176,7 @@ fn follow_asks(app: &mut RustGisApp, ctx: &egui::Context) { for (layer, r) in replies { let Ok(v) = r else { continue }; if let Some(url) = v["url"].as_str() { - let slot = crate::fetch_into_limited(url, rustgis_engine::data::ogc::MAX_INFO_BYTES); + let slot = ask_within(&v, url); next.push(Ask { layer, also: Vec::new(), capabilities: false, request: Some(url.to_string()), slot }); } found.extend(v["results"].as_array().cloned().unwrap_or_default()); @@ -5545,6 +5565,48 @@ mod tests { } } + /// The WMS requests identify lists are fetched within the layer's reach (`"public"`: only the + /// internet), and capabilities read from the internet are recorded so the requests they name + /// are held there; read on the local network, neither. + #[test] + fn identify_requests_are_fetched_within_the_layers_reach() { + use rustgis_engine::render::rustgis_tiles::address::Origin; + for observed in [Reach::Public, Reach::Local] { + let _turn = crate::fetching::turn(); + let host = if observed == Reach::Public { "identify-web.example" } else { "identify-intranet.example" }; + let asked = std::sync::Arc::new(std::sync::Mutex::new(Vec::new())); + let log = asked.clone(); + cache::set_fetcher_with_origin(move |url, ceiling, done, _| { + let clean = cache::split_download_limit(&url).0.to_string(); + log.lock().unwrap().push((clean.clone(), ceiling)); + let origin = Origin::with_observed_reach(&clean, observed.min(ceiling)).unwrap(); + done(Ok(cache::Fetched { bytes: b"".to_vec(), origin })); + }); + let mut s = rustgis_engine::Session::new(rustgis_engine::Project::default()); + let template = format!( + "https://{host}/wms?SERVICE=WMS&VERSION=1.3.0&REQUEST=GetMap&LAYERS=over&STYLES=&CRS=EPSG:3857&BBOX={{bbox-epsg-3857}}&WIDTH=256&HEIGHT=256&FORMAT=image%2Fpng" + ); + s.run("map.addTiles", &json!({"url": template, "name": "Over", "overlay": true})).unwrap(); + let caps = rustgis_engine::data::ogc::wms_layer_of(&template).unwrap().0; + let (map, opened) = (s.project.active_map, s.opened); + let mut app = RustGisApp::new(s); + let request = format!("https://{host}/info?REQUEST=GetFeatureInfo"); + let info = json!({"featureInfo": [ + {"tileLayer": "Over", "url": request, "public": observed == Reach::Public}, + {"tileLayer": "Over", "capabilities": caps}, + ]}); + app.map.popup = Some(Popup::new(info, Coord::new(8.6, 46.65), map, opened)); + { + let asked = asked.lock().unwrap(); + assert_eq!(asked.len(), 2, "{asked:?}"); + assert_eq!(asked[0], (request.clone(), observed), "the request, listed within {observed:?}"); + assert_eq!(asked[1], (caps.clone(), Reach::Local), "the capabilities of the user's own layer"); + } + follow_asks(&mut app, &egui::Context::default()); + assert_eq!(cache::ceiling_for(&caps), observed, "capabilities observed {observed:?}"); + } + } + /// Answers that land while the pop-up waits open it on the top result, with its feature /// selected: drawn over Countries, Over's feature comes first, and Switzerland, selected by the /// click, no longer is. @@ -5564,7 +5626,7 @@ mod tests { let mut app = RustGisApp::new(s); let mut pp = Popup::new(info, Coord::new(8.6, 46.65), map, opened); let answer = br#"{"type":"FeatureCollection","features":[{"type":"Feature","properties":{"name":"Bern"},"geometry":null}]}"#; - let slot = std::sync::Arc::new(std::sync::Mutex::new(Some(Ok(answer.to_vec())))); + let slot = std::sync::Arc::new(std::sync::Mutex::new(Some(Ok((answer.to_vec(), Reach::Local))))); pp.asks.push(Ask { layer: "Over".into(), also: Vec::new(), capabilities: false, request: None, slot }); app.map.popup = Some(pp); follow_asks(&mut app, &egui::Context::default()); diff --git a/crates/ui-egui/src/opendataui.rs b/crates/ui-egui/src/opendataui.rs index 80486e7337..efebf412ac 100644 --- a/crates/ui-egui/src/opendataui.rs +++ b/crates/ui-egui/src/opendataui.rs @@ -7,14 +7,16 @@ //! service opens Add From Service connected to it. use egui::vec2; -use rustgis_engine::render::rustgis_tiles::cache; use rustgis_engine::render::rustgis_tiles::portal::{DEM_DATASETS, Dataset, Portal, Use}; use rustgis_engine::render::rustgis_tiles::usgis::{self, Search, Set}; +use rustgis_engine::render::rustgis_tiles::{address::Reach, cache}; use serde_json::json; use crate::{RustGisApp, Slot}; -type Answer = Slot, String>>; +/// An answer with the reach it was read at, which the addresses it gives are judged by and +/// fetched within. +type Read = Slot, Reach), String>>; /// The portals Search Open Data offers: the kind, its name, and what its address field takes. const PORTALS: [(&str, &str, &str); 3] = [ @@ -75,12 +77,12 @@ struct Pending { query: String, source: String, more: bool, - slot: Answer, + slot: Read, } /// A result's picture: being fetched, ready, or not to be had. enum Thumb { - Loading(Answer), + Loading(Read), Ready(egui::TextureHandle), Failed, } @@ -111,16 +113,20 @@ pub struct State { waiting: Option, /// A dataset's files or layers being listed: the dataset (its place in `found`), the portal, /// the listing's address. - listing: Option<(usize, Portal, String, Answer)>, + listing: Option<(usize, Portal, String, Read)>, pub found: Vec, - /// How many the search found in all, when the portal says, and its next page's address. + /// Where each of `found` was read (its page's answer, as the fetch observed it): what it + /// names (its pictures, its listing, its files and services) is fetched within it. + reaches: Vec, + /// How many the search found in all, when the portal says, and its next page's address + /// with the reach of the page that named it. total: Option, - next: Option<(Portal, String, Option<[f64; 4]>, String, String)>, + next: Option<(Portal, String, Option<[f64; 4]>, String, String, Reach)>, /// The results whose details are shown. open: std::collections::HashSet, thumbs: std::collections::HashMap, /// The Zarr stores being checked (by their result's place), which some datasets lack. - probes: Vec<(usize, Answer)>, + probes: Vec<(usize, Read)>, /// The result whose Zarr store is open in the pane, to pick its variable and steps. zarr_open: Option, pub error: Option, @@ -142,6 +148,7 @@ impl Default for State { waiting: None, listing: None, found: Vec::new(), + reaches: Vec::new(), total: None, next: None, open: Default::default(), @@ -172,12 +179,10 @@ impl State { } } -/// Starts fetching `url` off the frame. -fn fetch(url: &str) -> Answer { - let slot: Answer = Slot::default(); - let land = slot.clone(); - cache::download(url, Box::new(move |r| *land.lock().unwrap_or_else(|e| e.into_inner()) = Some(r))); - slot +/// Starts fetching `url` off the frame, within `ceiling`: the reach of the answer that named it +/// (`Reach::Local` for the portal the user picked). +fn fetch(url: &str, ceiling: Reach) -> Read { + crate::fetch_within(url, cache::MAX_DOWNLOAD, None, ceiling) } /// Lands the search's answer, a dataset's listing and the results' pictures. @@ -193,12 +198,14 @@ pub fn poll(app: &mut RustGisApp, ctx: &egui::Context) { let Some(w) = app.ui.opendata.waiting.take() else { return }; let replaced = !w.more && app.ui.opendata.zarr_open.is_some(); let st = &mut app.ui.opendata; - match r.and_then(|b| w.portal.parse(&w.url, &b, w.area, &w.query).map(|found| (found, w.portal.paging(&w.url, &b)))) { - Ok((found, (total, next))) => { + match r.and_then(|(b, reach)| w.portal.parse(reach, &b, w.area, &w.query).map(|found| (found, w.portal.paging(&w.url, &b), reach))) { + Ok((found, (total, next), reach)) => { let first = if w.more { st.found.len() } else { 0 }; if w.more { + st.reaches.extend(std::iter::repeat_n(reach, found.len())); st.found.extend(found); } else { + st.reaches = vec![reach; found.len()]; st.found = found; st.zarr_open = None; // The earlier list's checks would land on these results' places. @@ -207,11 +214,11 @@ pub fn poll(app: &mut RustGisApp, ctx: &egui::Context) { // A dynamical.org store (Zarr 3) is checked before it is offered. for (i, d) in st.found.iter().enumerate().skip(first) { if let Some(r) = d.resources.iter().find(|r| r.using == Use::Zarr && r.url.starts_with("https://data.dynamical.org/")) { - st.probes.push((i, fetch(&format!("{}/zarr.json", r.url)))); + st.probes.push((i, fetch(&format!("{}/zarr.json", r.url), reach))); } } st.total = total; - st.next = next.map(|n| (w.portal.clone(), n, w.area, w.query.clone(), w.source.clone())); + st.next = next.map(|n| (w.portal.clone(), n, w.area, w.query.clone(), w.source.clone(), reach)); let shown = st.found.len().to_string(); st.info = Some(match total { _ if st.found.is_empty() => tl!("No datasets with data RustGIS can add").to_string(), @@ -238,8 +245,12 @@ fn poll_listing(app: &mut RustGisApp, ctx: &egui::Context) { }; let Some((i, portal, url, _)) = app.ui.opendata.listing.take() else { return }; let st = &mut app.ui.opendata; - match r.and_then(|b| portal.parse_listing(&url, &b)) { - Ok(files) => { + match r.and_then(|(b, reach)| portal.parse_listing(&url, reach, &b).map(|files| (files, reach))) { + Ok((files, reach)) => { + // The files came in the listing: they reach no further than it was read. + if let Some(r) = st.reaches.get_mut(i) { + *r = (*r).min(reach); + } if files.is_empty() { st.info = Some(tl!("The dataset has nothing RustGIS can add").to_string()); } @@ -286,7 +297,7 @@ fn poll_thumbs(app: &mut RustGisApp, ctx: &egui::Context) { waiting = true; continue; }; - *thumb = match r.and_then(|b| cache::decode_image(&b)) { + *thumb = match r.and_then(|(b, _)| cache::decode_image(&b)) { Ok(pm) => { let img = egui::ColorImage::from_rgba_premultiplied([pm.width() as usize, pm.height() as usize], pm.data()); Thumb::Ready(ctx.load_texture(format!("webdata_thumb_{url}"), img, egui::TextureOptions::LINEAR)) @@ -380,8 +391,8 @@ fn params(st: &State) -> serde_json::Value { /// Starts a search for the pane's choices, or (`more`) its next page. fn search(app: &mut RustGisApp, more: bool) { if more { - let Some((portal, url, area, query, source)) = app.ui.opendata.next.take() else { return }; - let slot = fetch(&url); + let Some((portal, url, area, query, source, reach)) = app.ui.opendata.next.take() else { return }; + let slot = fetch(&url, reach); app.ui.opendata.waiting = Some(Pending { portal, url, area, query, source, more, slot }); return; } @@ -389,9 +400,10 @@ fn search(app: &mut RustGisApp, more: bool) { match rustgis_engine::cmd::portals::portal_query(&app.session, &p) { Ok((portal, query, area, limit)) => { let url = portal.search_url(&query, area, limit); - let slot = fetch(&url); + let slot = fetch(&url, Reach::Local); let st = &mut app.ui.opendata; st.found.clear(); + st.reaches.clear(); st.open.clear(); st.probes.clear(); // Pictures of the earlier results go (and their textures). @@ -410,9 +422,11 @@ fn search(app: &mut RustGisApp, more: bool) { fn list_files(app: &mut RustGisApp, i: usize) { let st = &app.ui.opendata; let Some(url) = st.found.get(i).and_then(|d| d.listing.clone()) else { return }; + // The listing's address came from the search's answer: it reaches no further. + let reach = st.reaches.get(i).copied().unwrap_or(Reach::Public); match Portal::new(Some(st.portal), None) { Ok(portal) => { - let slot = fetch(&url); + let slot = fetch(&url, reach); app.ui.opendata.listing = Some((i, portal, url, slot)); } Err(e) => app.ui.opendata.error = Some(e), @@ -608,17 +622,20 @@ pub fn dialog(app: &mut RustGisApp, ui: &mut egui::Ui) { let mut act = None; let mut wanted = Vec::new(); for (i, d) in st.found.iter().enumerate() { + // What a result names reaches no further than the answer it came in (one not recorded, + // which can't happen, only the internet). + let reach = st.reaches.get(i).copied().unwrap_or(Reach::Public); let thumb = d.thumbnail.as_ref().and_then(|u| match st.thumbs.get(u) { Some(Thumb::Ready(tex)) => Some(tex.clone()), None => { - wanted.push(u.clone()); + wanted.push((u.clone(), reach)); None } _ => None, }); ui.push_id(i, |ui| { if let Some(a) = card(ui, &t, d, thumb, st.open.contains(&i), i, busy || listing) { - act = Some(a); + act = Some((a, reach)); } }); } @@ -628,52 +645,53 @@ pub fn dialog(app: &mut RustGisApp, ui: &mut egui::Ui) { } // Pictures of the results shown, fetched once each. let st = &mut app.ui.opendata; - for u in wanted { + for (u, reach) in wanted { if st.thumbs.len() >= MAX_THUMBS { break; } - let slot = fetch(&u); + let slot = fetch(&u, reach); st.thumbs.insert(u, Thumb::Loading(slot)); } match act { - Some(Act::Details(i)) if !st.open.remove(&i) => { + Some((Act::Details(i), _)) if !st.open.remove(&i) => { st.open.insert(i); } - Some(Act::Zoom(b)) => { + Some((Act::Zoom(b), _)) => { if let Err(e) = app.run("map.zoomToExtent", json!({"extent": b})) { app.ui.opendata.error = Some(e); } } - Some(Act::List(i)) => { + Some((Act::List(i), _)) => { app.ui.opendata.error = None; list_files(app, i); } - Some(Act::Add(url, Use::Zarr, title)) => { + Some((Act::Add(url, Use::Zarr, title), reach)) => { // Its variable and steps are picked in the pane. app.ui.zarr.title = Some(title.clone()); app.ui.opendata.zarr_open = Some(title); app.ui.zarr.address = url; - crate::zarrui::connect(app); + crate::zarrui::connect_within(app, reach == Reach::Public); } - Some(Act::Add(url, using, title)) => { + Some((Act::Add(url, using, title), reach)) => { app.ui.opendata.error = None; - if let Err(e) = add(app, &url, &using, &title) { + if let Err(e) = add(app, &url, &using, &title, reach == Reach::Public) { app.ui.opendata.error = Some(e); } } - None | Some(Act::Details(_)) => {} + None | Some((Act::Details(_), _)) => {} } } /// Adds a result's resource: a file by its address, a service's features page by page, or a -/// service through Add From Service, connected, to pick its layer. -fn add(app: &mut RustGisApp, url: &str, using: &Use, title: &str) -> Result<(), String> { +/// service through Add From Service, connected, to pick its layer. With `public` (the result came +/// in an answer read from the internet), what it adds is fetched only from there (`fromDocument`). +fn add(app: &mut RustGisApp, url: &str, using: &Use, title: &str, public: bool) -> Result<(), String> { match using { - Use::File | Use::Zarr => app.run("ui.addUrl", json!({"url": url, "name": title})).map(|_| ()), - Use::Features => app.run("ui.addUrl", json!({"url": url, "name": title, "service": true})).map(|_| ()), + Use::File | Use::Zarr => app.run("ui.addUrl", json!({"url": url, "name": title, "fromDocument": public})).map(|_| ()), + Use::Features => app.run("ui.addUrl", json!({"url": url, "name": title, "service": true, "fromDocument": public})).map(|_| ()), Use::Service { kind, .. } => app .run("ui.dialog", json!({"name": "addService"})) - .and_then(|_| app.run("ui.addService", json!({"url": url, "type": kind}))) + .and_then(|_| app.run("ui.addService", json!({"url": url, "type": kind, "fromDocument": public}))) .map(|_| ()), } } @@ -855,6 +873,52 @@ mod tests { base } + /// A search's answer is read within its reach and what its results name inherits it: a + /// result's file is added only from the internet when the answer came from there; from an + /// answer read on the local network, a file on a private address is kept and added as the + /// user's own would be. + #[test] + fn search_results_are_added_within_the_reach_of_the_answer_naming_them() { + use egui_kittest::kittest::Queryable; + use rustgis_engine::render::rustgis_tiles::address::Origin; + for (n, observed) in [(1, Reach::Public), (2, Reach::Local)] { + let _turn = crate::fetching::turn(); + let file = if observed == Reach::Public { + format!("https://open-data-{n}.example/p.geojson") + } else { + format!("http://10.0.{n}.3/p.geojson") + }; + let answer = json!({"results":[{"slug":"parks","title":"Parks","organization":{"name":"City"},"dcat":{"distribution":[{"downloadURL":file,"mediaType":"application/geo+json"}]}}]}).to_string(); + let asked = std::sync::Arc::new(std::sync::Mutex::new(Vec::new())); + let log = asked.clone(); + cache::set_fetcher_with_origin(move |url, ceiling, done, _| { + let clean = cache::split_download_limit(&url).0.to_string(); + log.lock().unwrap().push((clean.clone(), ceiling)); + let origin = Origin::with_observed_reach(&clean, observed.min(ceiling)).unwrap(); + let body = + if clean.ends_with(".geojson") { r#"{"type":"FeatureCollection","features":[]}"#.to_string() } else { answer.clone() }; + done(Ok(cache::Fetched { bytes: body.into_bytes(), origin })); + }); + let mut h = egui_kittest::Harness::builder().with_size(egui::vec2(1400.0, 900.0)).with_max_steps(16).build_ui_state( + |ui, app: &mut RustGisApp| { + let ctx = ui.ctx().clone(); + app.logic(&ctx); + app.ui(ui); + }, + RustGisApp::new(rustgis_engine::Session::new(rustgis_engine::Project::default())), + ); + h.state_mut().run("ui.searchOpenData", json!({"query": "parks"})).unwrap(); + h.run_steps(3); + assert_eq!(h.state().ui.opendata.found.len(), 1, "{:?}", h.state().ui.opendata.error); + assert_eq!(h.state().ui.opendata.reaches, [observed]); + h.get_by_label("Add").click(); + h.run_steps(3); + let asked = asked.lock().unwrap().clone(); + assert_eq!(asked.first().map(|(_, c)| *c), Some(Reach::Local), "the search RustGIS names: {asked:?}"); + assert!(asked.iter().any(|(u, c)| u.starts_with(&file) && *c == observed), "the file, its answer read {observed:?}: {asked:?}"); + } + } + /// Web Data's Add reads a GeoLens dataset's every page, not only the server's first 1,000. #[test] fn a_geolens_dataset_is_added_page_by_page() { @@ -870,7 +934,7 @@ mod tests { RustGisApp::with_sample(), ); let url = format!("{base}/api/collections/trees/items?limit=1000"); - add(h.state_mut(), &url, &Use::Features, "Street Trees").unwrap(); + add(h.state_mut(), &url, &Use::Features, "Street Trees", false).unwrap(); let deadline = std::time::Instant::now() + std::time::Duration::from_secs(20); while h.state().session.map().layer_by_name("Street Trees").is_none() { assert!(std::time::Instant::now() < deadline, "timed out waiting"); diff --git a/crates/ui-egui/src/portalsui.rs b/crates/ui-egui/src/portalsui.rs index 62c9151f86..780bc04713 100644 --- a/crates/ui-egui/src/portalsui.rs +++ b/crates/ui-egui/src/portalsui.rs @@ -4,12 +4,13 @@ //! `boundaries.add`, so the layers are added like any command's. use egui::vec2; -use rustgis_engine::render::rustgis_tiles::{boundaries, cache, overpass}; +use rustgis_engine::render::rustgis_tiles::{address::Reach, boundaries, cache, overpass}; use serde_json::{Value, json}; use crate::{RustGisApp, Slot}; -type Answer = Slot, String>>; +/// An answer, with the reach it was read at. +type Answer = Slot, Reach), String>>; /// What is being fetched, with the parameters its answer is added with. enum Asked { @@ -56,11 +57,10 @@ impl Default for State { } } -fn fetch(url: &str) -> Answer { - let slot: Answer = Slot::default(); - let land = slot.clone(); - cache::download(url, Box::new(move |r| *land.lock().unwrap_or_else(|e| e.into_inner()) = Some(r))); - slot +/// Fetches `url` off the frame within `ceiling`: the reach of the answer that named it +/// (`Reach::Local` for a service the user or RustGIS names). +fn fetch(url: &str, ceiling: Reach) -> Answer { + crate::fetch_within(url, cache::MAX_DOWNLOAD, None, ceiling) } /// Lands the answers. @@ -71,6 +71,8 @@ pub fn poll(app: &mut RustGisApp, ctx: &egui::Context) { return; }; let Some((asked, _)) = app.ui.portals.waiting.take() else { return }; + let reach = r.as_ref().map_or(Reach::Public, |(_, reach)| *reach); + let r = r.map(|(bytes, _)| bytes); app.ui.portals.error = None; app.ui.portals.info = None; let text = |b: Vec| String::from_utf8(b).map_err(|_| "the answer isn't UTF-8 text".to_string()); @@ -100,7 +102,8 @@ pub fn poll(app: &mut RustGisApp, ctx: &egui::Context) { } Asked::Meta(mut p) => r.and_then(|b| boundaries::parse_meta(&b)).map(|m| { p["name"] = json!(format!("{} {}", m.name, m.level)); - app.ui.portals.waiting = Some((Asked::Boundary(p), fetch(&m.geojson))); + // The description names where the boundaries are: they are read no further than it was. + app.ui.portals.waiting = Some((Asked::Boundary(p), fetch(&m.geojson, reach))); }), Asked::Boundary(mut p) => r.and_then(text).and_then(|t| { p["text"] = json!(t); @@ -174,7 +177,7 @@ pub fn osm(app: &mut RustGisApp, ui: &mut egui::Ui) { match url { Ok(url) => { app.ui.portals.error = None; - app.ui.portals.waiting = Some((Asked::Osm(p), fetch(&url))); + app.ui.portals.waiting = Some((Asked::Osm(p), fetch(&url, Reach::Local))); } Err(e) => app.ui.portals.error = Some(e), } @@ -189,7 +192,7 @@ pub fn boundaries(app: &mut RustGisApp, ui: &mut egui::Ui) { // The country list, asked for once. if !app.ui.portals.countries_asked && !busy { app.ui.portals.countries_asked = true; - app.ui.portals.waiting = Some((Asked::Countries, fetch(&boundaries::countries_url()))); + app.ui.portals.waiting = Some((Asked::Countries, fetch(&boundaries::countries_url(), Reach::Local))); } if let Some(e) = &app.ui.portals.countries_error { ui.label(egui::RichText::new(e).small().weak()); @@ -245,10 +248,49 @@ pub fn boundaries(app: &mut RustGisApp, ui: &mut egui::Ui) { Ok((c, l)) => { let url = boundaries::meta_url(&c, &l); app.ui.portals.error = None; - app.ui.portals.waiting = Some((Asked::Meta(json!({"country": c, "level": l})), fetch(&url))); + app.ui.portals.waiting = Some((Asked::Meta(json!({"country": c, "level": l})), fetch(&url, Reach::Local))); } Err(e) => app.ui.portals.error = Some(e), } } status(app, ui); } + +#[cfg(test)] +mod tests { + use super::*; + use rustgis_engine::render::rustgis_tiles::address::Origin; + + /// The boundaries geoBoundaries' description names are read within the reach the description + /// was read at: only from the internet when it came from there; from a description read on the + /// local network (a mirror at its name), from a private address too. + #[test] + fn boundaries_are_read_within_the_reach_of_their_description() { + for (n, observed) in [(1, Reach::Public), (2, Reach::Local)] { + let _turn = crate::fetching::turn(); + let geojson = if observed == Reach::Public { + format!("https://boundaries-{n}.example/che.geojson") + } else { + format!("http://10.0.{n}.2/che.geojson") + }; + let meta = + json!({"boundaryISO": "CHE", "boundaryName": "Switzerland", "boundaryType": "ADM1", "gjDownloadURL": geojson}).to_string(); + let asked = std::sync::Arc::new(std::sync::Mutex::new(Vec::new())); + let log = asked.clone(); + cache::set_fetcher_with_origin(move |url, ceiling, done, _| { + let clean = cache::split_download_limit(&url).0.to_string(); + log.lock().unwrap().push((clean.clone(), ceiling)); + let origin = Origin::with_observed_reach(&clean, observed.min(ceiling)).unwrap(); + let body = + if clean.ends_with(".geojson") { r#"{"type":"FeatureCollection","features":[]}"#.to_string() } else { meta.clone() }; + done(Ok(cache::Fetched { bytes: body.into_bytes(), origin })); + }); + let mut app = RustGisApp::new(rustgis_engine::Session::new(rustgis_engine::Project::default())); + let url = boundaries::meta_url("CHE", "ADM1"); + app.ui.portals.waiting = Some((Asked::Meta(json!({"country": "CHE", "level": "ADM1"})), fetch(&url, Reach::Local))); + poll(&mut app, &egui::Context::default()); + let asked = asked.lock().unwrap().clone(); + assert_eq!(asked, [(url, Reach::Local), (geojson.clone(), observed)], "observed {observed:?}"); + } + } +} diff --git a/crates/ui-egui/src/serviceui.rs b/crates/ui-egui/src/serviceui.rs index abf43843ef..acc2def3b7 100644 --- a/crates/ui-egui/src/serviceui.rs +++ b/crates/ui-egui/src/serviceui.rs @@ -382,8 +382,12 @@ impl Import { } let base = self.params.get("url").and_then(Value::as_str).unwrap_or_default(); // The plan already resolved this exact destination and its login (or absence). - // Re-selecting from the original saved connection would undo a foreign hop. - rustgis_engine::render::rustgis_tiles::address::check(url, Some(base)).map_err(|e| crate::connectionui::translated(&e))?; + // Re-selecting from the original saved connection would undo a foreign hop. The plan + // judged it by where the document naming it was read, and recorded one read from the + // internet, so it is checked within that record, never by how the service's address is + // spelled (a public-looking name may connect on the local network). + let ceiling = cache::ceiling_for(base).min(cache::ceiling_for(url)); + rustgis_engine::render::rustgis_tiles::address::check_reach(url, ceiling).map_err(|e| crate::connectionui::translated(&e))?; Ok(url.to_string()) } @@ -569,22 +573,6 @@ fn drawn(app: &mut RustGisApp, landed: &mut Landed, step: &mut Step) { } } -/// A bounded description or feature page fetched off the frame. Native downloads end at the -/// timeout, if it has one; the browser's late answer is discarded by the polling read. It connects -/// no wider than `ceiling`, and lands with the reach it was read at, which the next page is -/// fetched within ([`go_on`]). Nothing is recorded for a page's address, so a long read adds -/// nothing to the restricted addresses ([`cache::restrict_to_public`]). -fn fetch_page(url: &str, max: usize, timeout: Option, ceiling: Reach) -> Slot, Reach), String>> { - let slot: Slot, Reach), String>> = Slot::default(); - let land = slot.clone(); - let done: cache::FetchedDone = Box::new(move |r| { - let r = r.map(|fetched| (fetched.bytes, fetched.origin.reach())); - *land.lock().unwrap_or_else(|e| e.into_inner()) = Some(r); - }); - cache::download_limited_reaching_with_origin(url, max, timeout, ceiling, done); - slot -} - /// Hands each page that landed to its read, and adds the layers whose features are all read. A /// read whose project was closed meanwhile is dropped. pub fn poll_pages(app: &mut RustGisApp, ctx: &egui::Context) { @@ -671,9 +659,9 @@ pub(crate) fn go_on(app: &mut RustGisApp, mut landed: Landed, left: usize, reach let slot = match next { // A layer's description: small, and soon given up on. Ok(url) if pages.describing() => { - fetch_page(&url, left.min(ogc::DESCRIPTION_MAX), Some(ogc::DESCRIPTION_TIMEOUT), reach) + crate::fetch_within(&url, left.min(ogc::DESCRIPTION_MAX), Some(ogc::DESCRIPTION_TIMEOUT), reach) } - Ok(url) => fetch_page(&url, left, pages.page_timeout(), reach), + Ok(url) => crate::fetch_within(&url, left, pages.page_timeout(), reach), Err(e) => Slot::new(std::sync::Mutex::new(Some(Err(e)))), }; app.ui.service_pages.push(PageRead { landed, pages, left, reach, slot, asked: web_time::Instant::now() }); @@ -917,6 +905,125 @@ mod tests { } } + /// A tile set list at a public-looking name read on the local network leads to the tile set it + /// names on a private address: it is judged by where the list was read, not by how its name is + /// spelled. The same list read from the internet has that tile set refused, naming it and why, + /// and nothing more is fetched. + #[test] + fn a_tile_set_list_read_on_the_local_network_leads_to_its_local_tile_set() { + use rustgis_engine::render::rustgis_tiles::address::{Origin, Reach}; + for (n, observed) in [(1, Reach::Local), (2, Reach::Public)] { + let _turn = crate::fetching::turn(); + let root = format!("https://tileset-root-{n}.example/ogc"); + let list = format!("https://tileset-list-{n}.corp-looks-public.example/collections/relief/map/tiles"); + let tileset = format!("http://10.0.{n}.7/tiles/WebMercatorQuad"); + let template = format!("http://10.0.{n}.7/relief/{{tileMatrix}}/{{tileRow}}/{{tileCol}}.png"); + let collections = json!({"collections":[{"id":"relief","title":"Relief","links":[{"rel":"tilesets-map","href":list}]}]}); + let asked = std::sync::Arc::new(std::sync::Mutex::new(Vec::new())); + let log = asked.clone(); + let (list_at, tileset_body) = (list.clone(), json!({"links":[{"rel":"item","type":"image/png","href":template}]})); + let list_body = json!({"tilesets":[{"tileMatrixSetId":"WebMercatorQuad","links":[{"rel":"self","href":tileset}]}]}); + cache::set_fetcher_with_origin(move |url, ceiling, done, _| { + let clean = cache::split_download_limit(&url).0.to_string(); + log.lock().unwrap().push((clean.clone(), ceiling)); + let body = if clean.starts_with(&list_at) { &list_body } else { &tileset_body }; + let origin = Origin::with_observed_reach(&clean, observed.min(ceiling)).unwrap(); + done(Ok(cache::Fetched { bytes: body.to_string().into_bytes(), origin })); + }); + let mut app = RustGisApp::new(rustgis_engine::Session::new(rustgis_engine::Project::default())); + let text = collections.to_string(); + let listing = app.session.run("service.layers", &json!({"url": root, "type": "ogcapi", "text": text})).unwrap(); + let layer = listing["layers"].as_array().and_then(|l| l.iter().find(|l| l.get("tilesets").is_some())).unwrap().clone(); + let src = ServiceSource { url: root.clone(), kind: "ogcapi", text, documents: Vec::new() }; + add_layer_from(&mut app, &src, &layer, "", None, false, None, None).unwrap(); + app.poll_service_steps(); + app.poll_service_steps(); + let asked = asked.lock().unwrap().clone(); + if observed == Reach::Local { + assert_eq!(asked.len(), 2, "{asked:?}"); + assert_eq!(asked[1], (format!("{tileset}?f=json"), Reach::Local), "{asked:?}"); + let added = app.session.map().tiles.last().map(|t| t.url.clone()).unwrap_or_default(); + assert!(added.starts_with(&format!("http://10.0.{n}.7/relief/")), "{added} {:?}", app.dialogs.error); + } else { + assert_eq!(asked.len(), 1, "the tile set is not fetched: {asked:?}"); + let told: Vec<_> = app.session.notices_since(0).iter().map(|n| n.text.clone()).collect(); + assert!(told.iter().any(|t| t.contains(&tileset) && t.contains("local network")), "{told:?}"); + } + } + } + + /// A grouped import's next document is judged by the plan's record of where the document + /// naming it was read, not by how the service's address is spelled: under a service at a + /// public-looking name read on the local network, a document on a private address is asked + /// for; under one recorded as read from the internet, it is refused, naming it and why. + #[test] + fn a_grouped_import_judges_its_next_document_by_where_the_service_was_read() { + use rustgis_engine::render::rustgis_tiles::address::Reach; + for (n, observed) in [(3, Reach::Local), (4, Reach::Public)] { + let _turn = crate::fetching::turn(); + let base = format!("https://import-{n}.corp-looks-public.example/ogc"); + let next = format!("http://10.0.{n}.8/collections"); + if observed == Reach::Public { + cache::restrict_to_public(&base); + } + let task = Import { + params: json!({"url": base}), + refresh: false, + connection: None, + token: 0, + map: (0, String::new()), + slot: Slot::default(), + document: None, + current: None, + remaining: VecDeque::new(), + responses: Vec::new(), + bytes: 0, + }; + match task.request(&next) { + Ok(asked) => { + assert_eq!(observed, Reach::Local); + assert_eq!(asked, next); + } + Err(e) => { + assert_eq!(observed, Reach::Public, "{e}"); + assert!(e.contains(&next) && e.contains("local network"), "{e}"); + } + } + } + } + + /// A service a document read from the internet named (`fromDocument`: a catalogue's or a + /// portal's entry) is read only from there: its capabilities and what they list. One whose + /// address points into the local network is refused, naming it and why. Without it the + /// address is the user's, as before. + #[test] + fn a_service_a_document_named_is_read_only_from_the_internet() { + use rustgis_engine::render::rustgis_tiles::address::{Origin, Reach}; + for public in [true, false] { + let _turn = crate::fetching::turn(); + let url = format!("https://named-{public}.example/wms"); + let asked = std::sync::Arc::new(std::sync::Mutex::new(Vec::new())); + let log = asked.clone(); + cache::set_fetcher_with_origin(move |url, ceiling, done, _| { + let clean = cache::split_download_limit(&url).0.to_string(); + log.lock().unwrap().push((clean.clone(), ceiling)); + let origin = Origin::with_observed_reach(&clean, ceiling).unwrap(); + done(Ok(cache::Fetched { bytes: b"".to_vec(), origin })); + }); + let mut app = RustGisApp::new(rustgis_engine::Session::new(rustgis_engine::Project::default())); + app.run("ui.addService", json!({"url": url, "type": "wms", "fromDocument": public})).unwrap(); + let caps = rustgis_engine::data::ogc::capabilities_url(&url, Some("wms")); + let want = if public { Reach::Public } else { Reach::Local }; + assert_eq!(asked.lock().unwrap().clone(), [(caps.clone(), want)]); + assert_eq!(cache::ceiling_for(&caps), want); + if public { + let e = app.run("ui.addService", json!({"url": "http://10.0.5.9/wms", "type": "wms", "fromDocument": true})).unwrap_err(); + assert!(e.contains("10.0.5.9") && e.contains("local network"), "{e}"); + assert_eq!(asked.lock().unwrap().len(), 1, "a refused service is not asked"); + } + } + } + /// Discovery's anonymous provenance survives both deferred protocols and their final params. #[test] fn anonymous_service_offers_keep_descriptions_and_tiles_unbound() { diff --git a/crates/ui-egui/src/zarrui.rs b/crates/ui-egui/src/zarrui.rs index 135b589e46..89a5a1d06d 100644 --- a/crates/ui-egui/src/zarrui.rs +++ b/crates/ui-egui/src/zarrui.rs @@ -41,6 +41,9 @@ pub struct State { /// The store's root: a web address or a folder, as connected. root: String, web: bool, + /// The store's address came from a document read from the internet (a Search Open Data + /// result): its files are fetched only from there ([`connect_within`]). + public: bool, store: Option, /// `raster.zarrInfo`'s answer: variables, dimensions and their labels. info: Option, @@ -114,7 +117,13 @@ pub fn poll(app: &mut RustGisApp, ctx: &egui::Context) { { let slot: Answer = Slot::default(); let land = slot.clone(); - cache::download(&format!("{}/{k}", st.root), Box::new(move |r| *land.lock().unwrap_or_else(|e| e.into_inner()) = Some(r))); + let url = format!("{}/{k}", st.root); + let done: cache::Done = Box::new(move |r| *land.lock().unwrap_or_else(|e| e.into_inner()) = Some(r)); + if st.public { + cache::download_public(&url, done) + } else { + cache::download(&url, done) + } st.waiting.push((k, slot)); } if !st.waiting.is_empty() || !st.queue.is_empty() { @@ -204,8 +213,17 @@ pub fn poll(app: &mut RustGisApp, ctx: &egui::Context) { } } +/// Connects to the store at the dialog's address, the user's own: its files are fetched wherever +/// its name points. pub(crate) fn connect(app: &mut RustGisApp) { + connect_within(app, false); +} + +/// [`connect`], to a store a document read from the internet named when `public`: its files are +/// fetched only from there, however its name resolves. +pub(crate) fn connect_within(app: &mut RustGisApp, public: bool) { let st = &mut app.ui.zarr; + st.public = public; let a = st.address.trim().trim_end_matches('/').to_string(); st.error = None; st.info = None; @@ -442,6 +460,33 @@ mod tests { use super::*; use rustgis_engine::{Project, Session}; + /// A store a document read from the internet named (a Search Open Data result) has its files + /// fetched only from there; one the user names, wherever its name points. + #[test] + fn a_store_a_document_named_is_read_only_from_the_internet() { + use rustgis_engine::render::rustgis_tiles::{ + address::{Origin, Reach}, + cache, + }; + for public in [true, false] { + let _turn = crate::fetching::turn(); + let asked = std::sync::Arc::new(std::sync::Mutex::new(Vec::new())); + let log = asked.clone(); + cache::set_fetcher_with_origin(move |url, ceiling, done, _| { + log.lock().unwrap().push(ceiling); + let origin = Origin::with_observed_reach(cache::split_download_limit(&url).0, ceiling).unwrap(); + done(Ok(cache::Fetched { bytes: b"{}".to_vec(), origin })); + }); + let mut app = RustGisApp::new(Session::new(Project::default())); + app.ui.zarr.address = format!("https://store-{public}.example/data.zarr"); + connect_within(&mut app, public); + poll(&mut app, &egui::Context::default()); + let asked = asked.lock().unwrap().clone(); + let want = if public { Reach::Public } else { Reach::Local }; + assert!(!asked.is_empty() && asked.iter().all(|c| *c == want), "{asked:?}"); + } + } + /// A slice keeps its geographic system through its GeoTIFF handoff: another body's (an ESRI PE /// citation in the keys), and the Earth's other datums, retain their datum through `ran`. #[test] From c517c225f0ee38b02ba3c67e028e95ba91a62b0f Mon Sep 17 00:00:00 2001 From: mavrick Date: Mon, 23 Nov 2026 03:04:33 -0600 Subject: [PATCH 02/10] fix(services): take documents supplied by anything but the app as read from the internet A document, catalogue answer or WMS capabilities handed to a command by the Assistant, MCP or a plugin says nothing trustworthy about where it was read, so what it names reaches only the internet; the app's own are recorded by its fetch. Add From Service refuses a catalogue's local link before opening the dialog, and the grouped import test records what the plan records. --- crates/engine/src/cmd/select_info.rs | 54 +++++++++++++++++++++++++ crates/engine/src/cmd/service.rs | 59 +++++++++++++++++++++++++++- crates/ui-egui/src/lib.rs | 11 ++++-- crates/ui-egui/src/mapview.rs | 34 ++++++++++++++++ crates/ui-egui/src/serviceui.rs | 5 ++- 5 files changed, 157 insertions(+), 6 deletions(-) diff --git a/crates/engine/src/cmd/select_info.rs b/crates/engine/src/cmd/select_info.rs index d283a385cd..d9f9249868 100644 --- a/crates/engine/src/cmd/select_info.rs +++ b/crates/engine/src/cmd/select_info.rs @@ -217,6 +217,13 @@ fn feature_info(s: &mut Session, p: &Value) -> CmdResult { return Err(named(format!("the capabilities are larger than {} MB", MAX_TEXT >> 20))); } learn(s, index, caps.as_bytes()).map_err(named)?; + // Capabilities supplied by anything but the app say nothing trustworthy about where they + // were read: the requests they name are asked only on the internet. + if !s.policy_user() + && let Some((caps_url, _)) = s.map().tiles.get(index).and_then(|t| ogc::wms_layer_of(&t.url)) + { + cache::restrict_to_public(&caps_url); + } } if let Some(text) = ps(p, "text") { if text.len() > MAX_TEXT { @@ -329,3 +336,50 @@ fn answered(s: &mut Session, index: usize, request: &str) { t.feature_info = Some(next); } } + +#[cfg(all(test, not(target_arch = "wasm32")))] +mod tests { + use super::*; + + /// Capabilities supplied by anything but the app (the Assistant, MCP, a plugin) say nothing + /// trustworthy about where they were read: the GetFeatureInfo request they name on the local + /// network is refused, naming it. The app's own are asked there, as read where it read them. + #[test] + fn capabilities_supplied_by_anything_but_the_app_hold_their_requests_to_the_internet() { + use crate::policy::{Effects, Revocation, Scope}; + struct Live; + impl Revocation for Live { + fn allows(&self, _: Effects) -> bool { + true + } + } + for (n, app) in [(1, true), (2, false)] { + let host = format!("identify-supplied-{n}.example"); + let caps = format!( + r#" +Test WMS +image/png +application/geo+json +RootEPSG:3857roadsRoads"# + ); + let mut s = Session::new(crate::Project::default()); + let template = format!( + "https://{host}/wms?SERVICE=WMS&VERSION=1.3.0&REQUEST=GetMap&LAYERS=roads&STYLES=&CRS=EPSG:3857&BBOX={{bbox-epsg-3857}}&WIDTH=256&HEIGHT=256&FORMAT=image/png" + ); + s.run("map.addTiles", &json!({"url": template, "name": "Roads"})).unwrap(); + s.run("map.goToXY", &json!({"lon": 8.5, "lat": 47.4, "scale": 10000})).unwrap(); + let p = json!({"layer": "Roads", "lon": 8.5, "lat": 47.4, "capabilities": caps, "request": true}); + let r = if app { + feature_info(&mut s, &p) + } else { + s.with_scope(Scope::assistant(4_201_303, std::sync::Arc::new(Live)), |s| feature_info(s, &p)).unwrap() + }; + if app { + assert!(r.unwrap()["url"].as_str().is_some_and(|u| u.starts_with(&format!("http://192.168.{n}.5/info?")))); + } else { + let e = r.unwrap_err(); + assert!(e.contains(&format!("http://192.168.{n}.5/info")) && e.contains("local network"), "{e}"); + } + } + } +} diff --git a/crates/engine/src/cmd/service.rs b/crates/engine/src/cmd/service.rs index 2f393c4108..188184835f 100644 --- a/crates/engine/src/cmd/service.rs +++ b/crates/engine/src/cmd/service.rs @@ -294,9 +294,12 @@ fn read_documents_with( // one inherits its document's reach (a document not recorded, which can't happen, reaches // only the internet). Either is judged by that reach, never by how the document's address // is spelled: a public-looking name may connect on the local network, and its local links - // are then the service's own. + // are then the service's own. A document the app supplies was recorded by its fetch if it + // came from the internet; one supplied by anything else (the Assistant, MCP, a plugin) says + // nothing trustworthy about where it was read, so it is taken as read from the internet. let inherited = if seen.is_empty() { - cache::ceiling_for(original) + let untrusted = supplied.is_some() && !s.policy_user(); + cache::ceiling_for(original).min(if untrusted { Reach::Public } else { Reach::Local }) } else { reaches.get(crate::render::rustgis_tiles::logins::inner(&parent)).copied().unwrap_or(Reach::Public) }; @@ -1817,6 +1820,8 @@ pub(super) fn catalog_search(s: &mut Session, p: &Value) -> CmdResult { // fetch recorded of it ([`cache::ceiling_for`]). The catalogue's own address is the user's // choice, unless a document read from the internet named it. let within = cache::ceiling_for(url).min(cache::ceiling_for(&request)); + // An answer supplied by anything but the app says nothing trustworthy about where it was read. + let within = if ps(p, "text").is_some() && !s.policy_user() { within.min(Reach::Public) } else { within }; let (page, reach) = match ps(p, "text") { Some(text) => ( rustgis_data::ogc::parse_records(&request, text.as_bytes()).map_err(|e| crate::sources::message_with_address(url, &e))?, @@ -2241,6 +2246,56 @@ mod tests { } } + /// A document the app supplies without a record of an internet read was read where the app's + /// fetch connected, so its local links are followed; one supplied by the Assistant (or MCP, or a + /// plugin) says nothing trustworthy about where it was read and is taken as read from the + /// internet: its link into the local network is refused, naming it and why. + #[test] + fn a_document_supplied_by_anything_but_the_app_is_taken_as_read_from_the_internet() { + use crate::policy::{Effects, Revocation, Scope}; + struct Live; + impl Revocation for Live { + fn allows(&self, _: Effects) -> bool { + true + } + } + for (n, app) in [(13, true), (14, false)] { + let linked = format!("http://10.0.{n}.5/collections"); + let landing = json!({"links":[{"rel":"data","type":"application/json","href":linked}]}).to_string(); + let p = json!({"url": format!("https://gis-{n}.corp-looks-public.example/ogc"), "type": "ogcapi", "text": landing}); + let mut s = Session::new(crate::Project::default()); + let mut never = |_: &str, _: Reach| -> Result { Err("nothing is fetched".into()) }; + let found = if app { + read_documents_with(&mut s, &p, false, None, &mut never) + } else { + s.with_scope(Scope::assistant(4_201_301, std::sync::Arc::new(Live)), |s| { + read_documents_with(s, &p, false, None, &mut never) + }) + .unwrap() + }; + if app { + let next = found.unwrap().next.unwrap_or_default(); + assert!(next.starts_with(&linked), "the app's document leads on: {next}"); + } else { + let e = found.err().unwrap_or_default(); + assert!(e.contains(&linked) && e.contains("local network"), "{e}"); + } + // A catalogue's answer the same way: its link into the local network is kept for the + // app, left out for the Assistant. + let record = format!( + r#"aAhttp://10.0.{n}.4/wms"# + ); + let p = json!({"url": format!("https://csw-{n}.corp-looks-public.example/csw"), "text": record}); + let out = if app { + catalog_search(&mut s, &p).unwrap() + } else { + s.with_scope(Scope::assistant(4_201_302, std::sync::Arc::new(Live)), |s| catalog_search(s, &p)).unwrap().unwrap() + }; + let links = out["records"][0]["links"].as_array().map_or(0, Vec::len); + assert_eq!(links, usize::from(app), "{out}"); + } + } + /// The layers a service's document lists are judged by where the document was read: a /// collections document at a public-looking name read on the local network keeps a features /// layer on a private address; read from the internet, the layer is left out, as said. diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index b591f6d654..ea3ae56ed0 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -4442,6 +4442,13 @@ impl RustGisApp { let Some(url) = p.get("url").and_then(Value::as_str).map(str::trim).filter(|u| !u.is_empty()) else { return self.run("ui.dialog", json!({"name": "addService"})); }; + // An address a document read from the internet named (`fromDocument`, below) may not + // point into the local network: refused before anything opens. + let from_document = p.get("fromDocument").and_then(Value::as_bool) == Some(true); + if from_document { + rustgis_engine::render::rustgis_tiles::address::check_reach(url, Reach::Public) + .map_err(|e| connectionui::translated(&e))?; + } let connection = p .get("connection") .and_then(Value::as_str) @@ -4491,9 +4498,7 @@ impl RustGisApp { // entry, `fromDocument`) leads only there: its capabilities, the documents they // link to and the layers they list (`service.layers` reads the address's record). // It can only narrow what the address may reach. - if p.get("fromDocument").and_then(Value::as_bool) == Some(true) { - rustgis_engine::render::rustgis_tiles::address::check_reach(url, Reach::Public) - .map_err(|e| connectionui::translated(&e))?; + if from_document { cache::restrict_to_public(url); cache::restrict_to_public(&caps); } diff --git a/crates/ui-egui/src/mapview.rs b/crates/ui-egui/src/mapview.rs index cf040ea335..a18d36c227 100644 --- a/crates/ui-egui/src/mapview.rs +++ b/crates/ui-egui/src/mapview.rs @@ -4174,6 +4174,8 @@ fn follow_asks(app: &mut RustGisApp, ctx: &egui::Context) { replies.push((layer.clone(), app.session.run("identify.featureInfo", &p))); } for (layer, r) in replies { + // A failure (a request refused because it reaches past the layer, too) was told by the + // command, as every command's error is. let Ok(v) = r else { continue }; if let Some(url) = v["url"].as_str() { let slot = ask_within(&v, url); @@ -5607,6 +5609,38 @@ mod tests { } } + /// A layer held to the internet whose capabilities name a GetFeatureInfo request on the local + /// network isn't asked there, and the pop-up says so, naming the request. + #[test] + fn a_refused_identify_request_is_said() { + use rustgis_engine::render::rustgis_tiles::address::Origin; + let _turn = crate::fetching::turn(); + const CAPS: &str = r#" +Test WMS +image/png +application/geo+json +RootEPSG:3857overOver"#; + cache::set_fetcher_with_origin(move |url, ceiling, done, _| { + let origin = Origin::with_observed_reach(cache::split_download_limit(&url).0, ceiling).unwrap(); + done(Ok(cache::Fetched { bytes: CAPS.as_bytes().to_vec(), origin })); + }); + let mut s = rustgis_engine::Session::new(rustgis_engine::Project::default()); + let template = "https://identify-refused.example/wms?SERVICE=WMS&VERSION=1.3.0&REQUEST=GetMap&LAYERS=over&STYLES=&CRS=EPSG:3857&BBOX={bbox-epsg-3857}&WIDTH=256&HEIGHT=256&FORMAT=image%2Fpng"; + s.run("map.addTiles", &json!({"url": template, "name": "Over", "overlay": true})).unwrap(); + // Listed by a document read from the internet. + cache::restrict_to_public(template); + s.run("map.goToXY", &json!({"lon": 8.6, "lat": 46.65, "scale": 10000})).unwrap(); + let caps = rustgis_engine::data::ogc::wms_layer_of(template).unwrap().0; + let (map, opened) = (s.project.active_map, s.opened); + let mut app = RustGisApp::new(s); + let info = json!({"featureInfo": [{"tileLayer": "Over", "capabilities": caps, "public": true}]}); + app.map.popup = Some(Popup::new(info, Coord::new(8.6, 46.65), map, opened)); + let mark = app.session.notice_mark(); + follow_asks(&mut app, &egui::Context::default()); + let told: Vec<_> = app.session.notices_since(mark).iter().map(|n| n.text.clone()).collect(); + assert!(told.iter().any(|t| t.contains("http://192.168.7.5/info") && t.contains("local network")), "{told:?}"); + } + /// Answers that land while the pop-up waits open it on the top result, with its feature /// selected: drawn over Countries, Over's feature comes first, and Switzerland, selected by the /// click, no longer is. diff --git a/crates/ui-egui/src/serviceui.rs b/crates/ui-egui/src/serviceui.rs index acc2def3b7..c7beed5de7 100644 --- a/crates/ui-egui/src/serviceui.rs +++ b/crates/ui-egui/src/serviceui.rs @@ -963,8 +963,9 @@ mod tests { let _turn = crate::fetching::turn(); let base = format!("https://import-{n}.corp-looks-public.example/ogc"); let next = format!("http://10.0.{n}.8/collections"); + // The plan records a document it names after one read from the internet. if observed == Reach::Public { - cache::restrict_to_public(&base); + cache::restrict_to_public(&next); } let task = Import { params: json!({"url": base}), @@ -1017,9 +1018,11 @@ mod tests { assert_eq!(asked.lock().unwrap().clone(), [(caps.clone(), want)]); assert_eq!(cache::ceiling_for(&caps), want); if public { + app.dialogs.open = None; let e = app.run("ui.addService", json!({"url": "http://10.0.5.9/wms", "type": "wms", "fromDocument": true})).unwrap_err(); assert!(e.contains("10.0.5.9") && e.contains("local network"), "{e}"); assert_eq!(asked.lock().unwrap().len(), 1, "a refused service is not asked"); + assert_eq!(app.dialogs.open, None, "nothing opens for a refused service"); } } } From cc26c096734e1084f24608726ac0b67430701c05 Mon Sep 17 00:00:00 2001 From: mavrick Date: Mon, 23 Nov 2026 05:22:11 -0600 Subject: [PATCH 03/10] fix(services): review round: carry each read's reach through steps, listings and catalogues The Add From Service tile set and coverage steps keep the reach their document was read at, so a later change to the address's record can't widen what it names. Catalogue search under fromDocument, the folders a service lists in Data Sources, a catalogue the engine itself read, a template given with a list read from the internet and a stylesheet a TileJSON completes keep the reach they were read at. Identify says a refused WMS layer whichever layer it reports; the pop-up's capabilities answer only the service they were asked of; a Zarr connect that starts nothing leaves a batch under way as it was. Portal answers say how many addresses they left out, and a full record of browsed nodes no longer fails a listing. --- crates/engine/src/cmd/connection_browse.rs | 120 +++++++++++++++++++-- crates/engine/src/cmd/portals.rs | 26 ++++- crates/engine/src/cmd/select.rs | 6 +- crates/engine/src/cmd/select_info.rs | 40 ++++--- crates/engine/src/cmd/service.rs | 116 ++++++++++++++++++-- crates/engine/src/tests.rs | 26 +++++ crates/tiles/src/portal.rs | 102 +++++++++++------- crates/ui-egui/src/cswui.rs | 30 +++++- crates/ui-egui/src/lib.rs | 99 +++++++++++++---- crates/ui-egui/src/mapview.rs | 61 +++++++++-- crates/ui-egui/src/opendataui.rs | 34 +++++- crates/ui-egui/src/serviceui.rs | 10 +- crates/ui-egui/src/zarrui.rs | 31 +++++- 13 files changed, 584 insertions(+), 117 deletions(-) diff --git a/crates/engine/src/cmd/connection_browse.rs b/crates/engine/src/cmd/connection_browse.rs index 525b761c7b..82d2367bb4 100644 --- a/crates/engine/src/cmd/connection_browse.rs +++ b/crates/engine/src/cmd/connection_browse.rs @@ -91,9 +91,10 @@ fn level(c: &Connection, node: &str, observed: Option<&address::Origin>) -> Resu return Err(not_a_node()); } let (t, url) = rest.split_once(':').filter(|(t, _)| SERVICE_TYPES.contains(t)).ok_or_else(not_a_node)?; - // Judged by where the document listing it was read (a catalogue's records, recorded when - // they were browsed), not by how the connection's address is spelled; one not recorded, - // conservatively, as a document at that address would be. + // Judged by where the document listing it was read (a catalogue's records or a service's + // listing, recorded when they were browsed), not by how the connection's address is + // spelled. A node not recorded (one this session's browsing didn't list, or past the + // session's record) is still judged by the connection's address, as before. let origin = observed.cloned().unwrap_or_else(|| address::Origin::named(&c.address)); origin.check(url)?; return Ok(Level::Service { url: url.to_string(), kind: (t != "auto").then(|| t.to_string()), reach: origin.reach() }); @@ -276,7 +277,7 @@ pub(super) fn browse(s: &mut Session, p: &Value) -> CmdResult { Level::Database => database_schemas(s, &c, &mut out)?, Level::DatabaseSchema { schema } => database_schema(s, &c, schema, &mut out)?, Level::DatabaseDataset { dataset } => database_dataset(s, &c, dataset, &mut out)?, - Level::Service { url, kind, .. } => service(s, p, &mut out, &c, url, kind.as_deref())?, + Level::Service { url, kind, reach } => service(s, p, &mut out, &c, url, kind.as_deref(), *reach)?, Level::S3Root if url.is_none() => { buckets(c.options.get("buckets").map(String::as_str).unwrap_or("").split(',').map(str::to_string)) } @@ -608,7 +609,18 @@ fn schema_tables(tables: &[Value], schema: &str, address: &str) -> Found { } /// A service's layers (capabilities read here, or the app's `answer` and `documents`). -fn service(s: &mut Session, p: &Value, out: &mut Value, c: &Connection, url: &str, kind: Option<&str>) -> Result { +/// A service's layers, and the folders and services it lists as nodes, each recorded with the +/// reach the listing was read at (`reach`, narrowed by its document's record), so opening one +/// judges it by that. +fn service( + s: &mut Session, + p: &Value, + out: &mut Value, + c: &Connection, + url: &str, + kind: Option<&str>, + reach: address::Reach, +) -> Result { let mut q = json!({"url": crate::service_logins::request(s, Some(&c.id), url)?, "connection": c.id}); if let Some(k) = kind { q["type"] = json!(k); @@ -678,22 +690,46 @@ fn service(s: &mut Session, p: &Value, out: &mut Value, c: &Connection, url: &st let listed = children.len(); let children: Vec = children.into_iter().filter(|c| !c.is_null()).collect(); let left_out = children.len() < listed; + // The folders and services listed keep where their listing was read. + let read_at = |l: &Value| { + let source = l.get("source_url").and_then(Value::as_str).unwrap_or(""); + if crate::render::rustgis_tiles::cache::ceiling_for(source) == address::Reach::Public { address::Reach::Public } else { reach } + }; + let services: Vec<(String, address::Reach)> = r + .get("layers") + .and_then(Value::as_array) + .into_iter() + .flatten() + .filter(|l| l.get("offer").and_then(|o| o.get("type")).and_then(Value::as_str) == Some("service")) + .map(|l| (format!("service:arcgis:{}", text(&l["offer"], "url")), read_at(l))) + .collect(); + for at in [address::Reach::Public, address::Reach::Local] { + let nodes: Vec = services.iter().filter(|(_, r)| *r == at).map(|(node, _)| json!({"node": node})).collect(); + if !nodes.is_empty() { + let origin = address::Origin::with_observed_reach(url, at)?; + remember_or_say(s, c, &nodes, &origin, false); + } + } let mut found = Found::new(children); found.truncated |= left_out; Ok(found) } +/// [`remember_node_origins`], saying when the session's record is full instead of failing the +/// listing: the nodes not recorded are then judged by their connection's address, as before. +fn remember_or_say(s: &mut Session, c: &Connection, children: &[Value], origin: &address::Origin, root: bool) { + if let Err(e) = remember_node_origins(s, c, children, origin, root) { + s.notify(format!("{e}; what this listing names is judged by its connection's address"), false); + } +} + /// A catalogue's records, each with the services and files it links to, read at `origin`: what /// they link to reaches no further than that, the services when they are opened ([`level`]) and /// the files when they are added (`fromDocument`). fn catalogue(s: &mut Session, c: &Connection, text: &str, origin: &address::Origin, root: bool, out: &mut Value) -> Result { let url = crate::service_logins::request(s, Some(&c.id), &c.address)?; let params = json!({"url": url, "connection": c.id, "text": text}); - // `catalog.search` judges the answer by its address's record. - if origin.reach() == address::Reach::Public { - crate::render::rustgis_tiles::cache::restrict_to_public(&super::super::service::records_request(s, ¶ms)?); - } - let r = super::super::service::catalog_search(s, ¶ms)?; + let r = super::super::service::catalog_search_read(s, ¶ms, Some(origin.reach()))?; if let Some(n) = r.get("notes") { out["notes"] = n.clone(); } @@ -754,7 +790,7 @@ fn catalogue(s: &mut Session, c: &Connection, text: &str, origin: &address::Orig // The services the records link to, opened later, keep where the records were read. let services: Vec = found.children.iter().filter_map(|r| r.get("children")).filter_map(Value::as_array).flatten().cloned().collect(); - remember_node_origins(s, c, &services, origin, root)?; + remember_or_say(s, c, &services, origin, root); Ok(found) } @@ -1129,6 +1165,68 @@ mod tests { } } + /// A catalogue connection's answer the engine itself read on the local network (the Assistant's + /// browse, which fetches it) keeps its private links: it is judged by where the fetch + /// connected, not taken as an untrusted caller's text. And with the session's record of nodes + /// full, a page still lists its records and says what it couldn't record. + #[test] + fn a_catalogue_the_engine_read_keeps_its_links_and_a_full_record_still_lists_it() { + use crate::policy::{Effects, Revocation, Scope}; + use crate::render::rustgis_tiles::address::Origin; + struct Live; + impl Revocation for Live { + fn allows(&self, _: Effects) -> bool { + true + } + } + let mut session = crate::Session::new(crate::Project::default()); + let address = "https://csw-19.corp-looks-public.example/csw"; + let saved = session.run("connection.new", &json!({"kind":"csw","address":address})).unwrap(); + let connection = session.connections.connections.iter().find(|c| c.id == saved["id"].as_str().unwrap()).unwrap().clone(); + let text = r#"aRoadshttp://10.0.19.4/wms"#; + let origin = Origin::connected(&connection.address, "10.0.0.5".parse().unwrap()).unwrap(); + let found = session + .with_scope(Scope::assistant(4_201_305, std::sync::Arc::new(Live)), |s| { + super::catalogue(s, &connection, text, &origin, true, &mut json!({})) + }) + .unwrap() + .unwrap(); + let nodes: Vec<_> = found.children[0]["children"].as_array().unwrap().iter().filter_map(|l| l["node"].as_str()).collect(); + assert_eq!(nodes, ["service:wms:http://10.0.19.4/wms"]); + // The session's record of nodes full: the page is listed, and what wasn't recorded said. + session.browse_origins = ( + session.opened, + (0..16_384).map(|i| (format!("full-{i}"), String::new(), String::new())).map(|k| (k, origin.clone())).collect(), + ); + let mark = session.notice_mark(); + let found = super::catalogue(&mut session, &connection, text, &origin, false, &mut json!({})).unwrap(); + assert_eq!(found.children.len(), 1); + let told: Vec<_> = session.notices_since(mark).iter().map(|n| n.text.clone()).collect(); + assert!(told.iter().any(|t| t.contains("judged by its connection's address")), "{told:?}"); + } + + /// The folders a service lists keep where its listing was read: a directory a catalogue read + /// on the local network listed, at a private address, has its folder opened there, though the + /// catalogue's own name looks public. + #[test] + fn the_folders_a_service_lists_keep_where_it_was_read() { + use crate::render::rustgis_tiles::address::Origin; + let mut session = crate::Session::new(crate::Project::default()); + let address = "https://csw-20.corp-looks-public.example/csw"; + let saved = session.run("connection.new", &json!({"kind":"csw","address":address})).unwrap(); + let connection = session.connections.connections.iter().find(|c| c.id == saved["id"].as_str().unwrap()).unwrap().clone(); + let directory = "http://10.0.20.5/arcgis/rest/services"; + let node = format!("service:arcgis:{directory}"); + let local = Origin::connected(&connection.address, "10.0.0.5".parse().unwrap()).unwrap(); + super::remember_node_origins(&mut session, &connection, &[json!({"node": node})], &local, false).unwrap(); + let listing = json!({"currentVersion": 11.1, "folders": ["Hydro"], "services": []}).to_string(); + let out = super::browse(&mut session, &json!({"id": connection.id, "node": node, "answer": listing})).unwrap(); + let folder = out["children"].as_array().unwrap().iter().find_map(|c| c["node"].as_str().map(str::to_string)).unwrap(); + assert!(folder.starts_with("service:arcgis:http://10.0.20.5/"), "{folder}"); + let probe = super::browse(&mut session, &json!({"id": connection.id, "node": folder, "probe": true})); + assert!(probe.is_ok(), "{probe:?}"); + } + #[test] fn admitted_intranet_nodes_keep_their_origin_and_cannot_be_granted_by_json() { use crate::render::rustgis_tiles::address::Origin; diff --git a/crates/engine/src/cmd/portals.rs b/crates/engine/src/cmd/portals.rs index 8425f47896..c6ebfb41e2 100644 --- a/crates/engine/src/cmd/portals.rs +++ b/crates/engine/src/cmd/portals.rs @@ -158,7 +158,9 @@ fn portal_search(s: &mut Session, p: &Value) -> CmdResult { let (portal, query, area, limit) = portal_query(s, p)?; let url = portal.search_url(&query, area, limit); let (bytes, reach) = fetch(&url)?; - let found = portal.parse(reach, &bytes, area, &query)?; + let mut refused = 0; + let found = portal.parse(reach, &mut refused, &bytes, area, &query)?; + say_refused(s, refused); Ok(json!({"portal": portal.label(), "count": found.len(), "datasets": found.iter().map(dataset_json).collect::>()})) } @@ -171,10 +173,12 @@ pub fn files_query(p: &Value) -> Result<(Portal, String), String> { Ok((portal, url)) } -fn portal_files(_s: &mut Session, p: &Value) -> CmdResult { +fn portal_files(s: &mut Session, p: &Value) -> CmdResult { let (portal, url) = files_query(p)?; let (bytes, reach) = fetch(&url)?; - let files = portal.parse_listing(&url, reach, &bytes)?; + let mut refused = 0; + let files = portal.parse_listing(&url, reach, &mut refused, &bytes)?; + say_refused(s, refused); let list: Vec = files .iter() .map(|r| match &r.using { @@ -254,6 +258,22 @@ fn first_layer(s: &mut Session, url: &str, kind: &str) -> Result .ok_or_else(|| crate::sources::message_with_address(url, "the service lists no layer RustGIS can add")) } +/// Says how many addresses a portal's answer gave that were left out for pointing where a +/// document read from the internet may not send RustGIS (into the local network). +pub fn refused_notice(refused: usize) -> Option { + (refused > 0).then(|| { + format!( + "{refused} addresses the portal listed point where RustGIS won't fetch for an answer read from the internet and are left out" + ) + }) +} + +fn say_refused(s: &mut Session, refused: usize) { + if let Some(notice) = refused_notice(refused) { + s.notify(notice, false); + } +} + /// A fetch the command waits for (the command line and the assistant; the app fetches off the /// frame and passes the answer), with the reach it was read at: the addresses the answer gives are /// judged by it. diff --git a/crates/engine/src/cmd/select.rs b/crates/engine/src/cmd/select.rs index 173686320c..ca1d2fe209 100644 --- a/crates/engine/src/cmd/select.rs +++ b/crates/engine/src/cmd/select.rs @@ -428,11 +428,13 @@ fn identify(s: &mut Session, p: &Value) -> CmdResult { // all the map's layers, as all were before #808, isn't asked over what they found). let over_top = |i: usize| map.tiles.get(i).is_some_and(|t| t.over.is_some()) && top.is_some_and(|top| place(rustgis_map::Drawn::Tile(i)) < top); - let (asks, refused) = if web && (!first_layer || results.is_empty() || info::topmost(s, lon, lat).is_some_and(over_top)) { + let asks = if web && (!first_layer || results.is_empty() || info::topmost(s, lon, lat).is_some_and(over_top)) { info::requests(s, lon, lat, first_layer, picked) } else { - (Vec::new(), None) + Vec::new() }; + // Said whichever layer is reported: a WMS layer whose request reaches past it is never asked. + let refused = if web { info::refused(s, lon, lat, picked) } else { None }; let out = (|| -> CmdResult { let mut out = match results.first().cloned() { Some(first) => first, diff --git a/crates/engine/src/cmd/select_info.rs b/crates/engine/src/cmd/select_info.rs index d9f9249868..fa30029335 100644 --- a/crates/engine/src/cmd/select_info.rs +++ b/crates/engine/src/cmd/select_info.rs @@ -109,26 +109,18 @@ fn fetch_value(t: &rustgis_map::tiles::TileLayer, key: &str, url: String) -> Res } /// The WMS tile layers drawn at a point to ask what is there, topmost first as drawn (a higher -/// depth priority on top, #2488; only the topmost when `first_layer`), each with what to fetch; -/// and the notice for those whose request was refused (it reaches past the layer), naming the -/// first of them, its address and why. -pub(super) fn requests(s: &Session, lon: f64, lat: f64, first_layer: bool, picked: Option) -> (Vec, Option) { - let Some((at, m_per_px)) = merc_at(s, lon, lat) else { return (Vec::new(), None) }; +/// depth priority on top, #2488; only the topmost when `first_layer`), each with what to fetch. +/// One whose request reaches past it isn't asked ([`refused`] says so). +pub(super) fn requests(s: &Session, lon: f64, lat: f64, first_layer: bool, picked: Option) -> Vec { + let Some((at, m_per_px)) = merc_at(s, lon, lat) else { return Vec::new() }; let wanted = if first_layer { 1 } else { MAX_ASKED }; let map = s.map(); - let mut refused = Vec::new(); let mut asks: Vec = map .tiles_in_draw_order() .into_iter() .filter_map(|i| Some((i, map.tiles.get(i)?))) .filter(|(i, t)| picked.is_none_or(|p| p == *i) && askable(t, picked.is_some())) - .filter_map(|(_, t)| match next_fetch(t, lon, lat, at, m_per_px)? { - Ok(ask) => Some(ask), - Err(e) => { - refused.push((t.name.clone(), e)); - None - } - }) + .filter_map(|(_, t)| next_fetch(t, lon, lat, at, m_per_px)?.ok()) .take(wanted) .collect(); if !s.policy_user() { @@ -136,11 +128,27 @@ pub(super) fn requests(s: &Session, lon: f64, lat: f64, first_layer: bool, picke crate::sources::redact_url_fields(ask); } } - let notice = refused.first().map(|(layer, e)| match refused.len() { + asks +} + +/// The notice for the WMS tile layers drawn at a point whose request reaches past the layer, so +/// they are never asked there, whichever layer identify reports: one notice, naming the first of +/// them, its address and why, with how many. +pub(super) fn refused(s: &Session, lon: f64, lat: f64, picked: Option) -> Option { + let (at, m_per_px) = merc_at(s, lon, lat)?; + let map = s.map(); + let refused: Vec<(String, String)> = map + .tiles_in_draw_order() + .into_iter() + .filter_map(|i| Some((i, map.tiles.get(i)?))) + .filter(|(i, t)| picked.is_none_or(|p| p == *i) && askable(t, picked.is_some())) + .filter_map(|(_, t)| next_fetch(t, lon, lat, at, m_per_px)?.err().map(|e| (t.name.clone(), e))) + .collect(); + let (layer, e) = refused.first()?; + Some(match refused.len() { 1 => format!("{layer} wasn't asked what is here: {e}"), n => format!("{n} WMS layers weren't asked what is here, such as {layer}: {e}"), - }); - (asks, notice) + }) } /// The index of the topmost WMS tile layer, as drawn, that can be asked what is at a point (it diff --git a/crates/engine/src/cmd/service.rs b/crates/engine/src/cmd/service.rs index 188184835f..2822ad846e 100644 --- a/crates/engine/src/cmd/service.rs +++ b/crates/engine/src/cmd/service.rs @@ -294,16 +294,18 @@ fn read_documents_with( // one inherits its document's reach (a document not recorded, which can't happen, reaches // only the internet). Either is judged by that reach, never by how the document's address // is spelled: a public-looking name may connect on the local network, and its local links - // are then the service's own. A document the app supplies was recorded by its fetch if it - // came from the internet; one supplied by anything else (the Assistant, MCP, a plugin) says - // nothing trustworthy about where it was read, so it is taken as read from the internet. + // are then the service's own. let inherited = if seen.is_empty() { - let untrusted = supplied.is_some() && !s.policy_user(); - cache::ceiling_for(original).min(if untrusted { Reach::Public } else { Reach::Local }) + cache::ceiling_for(original) } else { reaches.get(crate::render::rustgis_tiles::logins::inner(&parent)).copied().unwrap_or(Reach::Public) }; let ceiling = inherited.min(cache::ceiling_for(&address)); + // A document the app supplies was recorded by its fetch if it came from the internet; one + // supplied by anything else (the Assistant, MCP, a plugin) says nothing trustworthy about + // where it was read, so what it names is taken as named on the internet. Its address + // itself stays the caller's own choice. + let read_within = if seen.is_empty() && supplied.is_some() && !s.policy_user() { ceiling.min(Reach::Public) } else { ceiling }; let rejected = match crate::render::rustgis_tiles::address::check_reach(&address, ceiling) { Ok(()) => false, Err(_) if dataset_document => true, @@ -354,7 +356,7 @@ fn read_documents_with( result.dataset_notes(dataset.as_ref()); return Ok(result); }; - parse(text.as_bytes(), ceiling) + parse(text.as_bytes(), read_within) } else if left { let Some(read) = s.left_document(&address).map_err(|e| crate::sources::message_with_address(original, &e))? else { result.next = Some(address); @@ -377,13 +379,13 @@ fn read_documents_with( .and_then(|(bytes, reach)| parse(&bytes, reach)) }; // Natively, where the fetch connected; otherwise what the app's fetch was held to. - let reach = observed.unwrap_or(ceiling); + let reach = observed.unwrap_or(read_within); let parsed = parsed.map_err(|e| crate::sources::message_with_address(&address, &e)); let mut service = match parsed { Ok(s) => { let before = s.layers.len(); result.incomplete |= s.incomplete; - let vetted = vet(s, reach); + let vetted = vet(s, reach, dataset_document, &reaches); result.excluded_layers |= vetted.layers.len() != before; vetted } @@ -495,7 +497,11 @@ fn fetch_document(url: &str, ceiling: Reach) -> Result { /// network (unless the service itself is there) or a forbidden address. `reach` is where the /// capabilities were read, as their fetch observed it: a service at a public-looking name that /// connected on the local network keeps its local layers. -fn vet(mut svc: Service, reach: Reach) -> Service { +/// +/// In a dataset document (`completing`), a stylesheet read earlier in the same discovery (a +/// TileJSON completing it names it again) is judged by the reach it was itself read at (`read`, by +/// address without a login), not by the completing document's. +fn vet(mut svc: Service, reach: Reach, completing: bool, read: &std::collections::HashMap) -> Service { let before = svc.layers.len(); svc.layers.retain(|l| { let u = match &l.offer { @@ -503,6 +509,10 @@ fn vet(mut svc: Service, reach: Reach) -> Service { Offer::Features { url } | Offer::Style { url } | Offer::Service { url } => url, Offer::Coverage(Coverage { endpoint, .. }) => endpoint, }; + let reach = match &l.offer { + Offer::Style { url } if completing => read.get(crate::render::rustgis_tiles::logins::inner(url)).copied().unwrap_or(reach), + _ => reach, + }; crate::render::rustgis_tiles::address::check_reach(u, reach).is_ok() }); let dropped = before - svc.layers.len(); @@ -1369,7 +1379,8 @@ fn add_discovered(s: &mut Session, p: &Value, url: &str, want: &str, found: &Dis )?), crossed_origin: crosses_origin(source, list) || crosses_origin(list, t), fallback: None, - public: cache::ceiling_for(t) == Reach::Public, + // Held to the internet when the template or the list naming it was read from there. + public: cache::ceiling_for(t) == Reach::Public || cache::ceiling_for(list) == Reach::Public, }, (Some(list), None) if leaving => { match left_template(s, source, list, matches!(layer.offer, Offer::VectorTiles { .. }), withheld, public)? { @@ -1812,6 +1823,12 @@ pub(crate) fn coverage_check(name: &str, bytes: &[u8]) -> Result<(), String> { /// `catalog.search`: a page of a catalogue's (CSW) records matching words and an area, with the /// links RustGIS can follow (those pointing where a document on the web may not send it left out). pub(super) fn catalog_search(s: &mut Session, p: &Value) -> CmdResult { + catalog_search_read(s, p, None) +} + +/// [`catalog_search`], with the supplied answer read at `read` when the engine itself fetched it +/// (a connection's browse, which knows where its fetch connected) rather than a caller. +pub(super) fn catalog_search_read(s: &mut Session, p: &Value, read: Option) -> CmdResult { let bound = crate::service_logins::request_params(s, p)?; let p = bound.as_ref(); let url = url_of(p)?; @@ -1821,7 +1838,11 @@ pub(super) fn catalog_search(s: &mut Session, p: &Value) -> CmdResult { // choice, unless a document read from the internet named it. let within = cache::ceiling_for(url).min(cache::ceiling_for(&request)); // An answer supplied by anything but the app says nothing trustworthy about where it was read. - let within = if ps(p, "text").is_some() && !s.policy_user() { within.min(Reach::Public) } else { within }; + let within = match read { + Some(read) => within.min(read), + None if ps(p, "text").is_some() && !s.policy_user() => within.min(Reach::Public), + None => within, + }; let (page, reach) = match ps(p, "text") { Some(text) => ( rustgis_data::ogc::parse_records(&request, text.as_bytes()).map_err(|e| crate::sources::message_with_address(url, &e))?, @@ -2296,6 +2317,79 @@ mod tests { } } + /// The Assistant's own service address on the local network stays its choice: a document it + /// supplies for that address has what it names taken as named on the internet, but the address + /// itself isn't refused. + #[test] + fn a_callers_own_local_address_stays_its_choice_with_a_supplied_document() { + use crate::policy::{Effects, Revocation, Scope}; + struct Live; + impl Revocation for Live { + fn allows(&self, _: Effects) -> bool { + true + } + } + let own = "http://10.0.15.5/collections"; + let items = "https://public-items-15.example/collections/parcels/items"; + let collections = json!({"collections":[{"id":"parcels","title":"Parcels","links":[{"rel":"items","type":"application/geo+json","href":items}]}]}); + let p = json!({"url": own, "type": "ogcapi", "text": collections.to_string()}); + let mut s = Session::new(crate::Project::default()); + let mut never = |_: &str, _: Reach| -> Result { Err("nothing is fetched".into()) }; + let found = s + .with_scope(Scope::assistant(4_201_304, std::sync::Arc::new(Live)), |s| read_documents_with(s, &p, false, None, &mut never)) + .unwrap(); + let found = found.unwrap(); + assert_eq!(found.service.layers.len(), 1); + assert_eq!(found.sources.iter().map(|source| source.public).collect::>(), [true], "what it names is held to the internet"); + } + + /// In a dataset document, a stylesheet read earlier (a TileJSON completing it names it again) + /// is judged by where it was itself read: one read on the local network is kept under a + /// TileJSON read from the internet. Outside completion, a style is judged by its document. + #[test] + fn a_completed_stylesheet_is_judged_by_where_it_was_read() { + let style = "http://10.0.16.5/style.json"; + let service = || Service { + layers: vec![rustgis_data::ogc::ServiceLayer { + name: "s".into(), + title: "S".into(), + offer: Offer::Style { url: style.into() }, + bbox: None, + tilesets: None, + time: None, + feature_info: None, + legends: Vec::new(), + zooms: None, + }], + ..Service::default() + }; + let read = std::collections::HashMap::from([(style.to_string(), Reach::Local)]); + assert_eq!(vet(service(), Reach::Public, true, &read).layers.len(), 1, "completing: the stylesheet's own reach"); + assert_eq!(vet(service(), Reach::Public, false, &read).layers.len(), 0, "an ordinary document: its own reach"); + } + + /// A template the app read and gives `service.add` is held to the internet when the tile list + /// naming it was read from there, whatever the template's own record. + #[test] + fn a_given_template_is_held_where_its_list_was_read() { + for (n, recorded) in [(17, true), (18, false)] { + let list = format!("https://tiles-list-{n}.example/relief/map/tiles"); + let tiled = json!({"collections": [{"id": "relief", "links": [{"rel": "tilesets-map", "href": list}]}]}).to_string(); + let template = format!("https://tiles-paint-{n}.example/relief/{{z}}/{{y}}/{{x}}.png"); + let mut s = Session::new(crate::Project::default()); + let api = format!("https://tiles-api-{n}.example/collections"); + // The list as the app reads it (the layer's `tilesets`), recorded by its fetch. + let listed = s.run("service.layers", &json!({"url": api, "text": tiled})).unwrap(); + let read = listed["layers"].as_array().and_then(|l| l.iter().find_map(|l| l["tilesets"].as_str())).unwrap().to_string(); + assert!(read.starts_with(&list), "{read}"); + if recorded { + cache::restrict_to_public(&read); + } + s.run("service.add", &json!({"url": api, "layer": "relief (map tiles)", "text": tiled, "tiles": template})).unwrap(); + assert_eq!(cache::ceiling_for(&template) == Reach::Public, recorded, "{template}"); + } + } + /// The layers a service's document lists are judged by where the document was read: a /// collections document at a public-looking name read on the local network keeps a features /// layer on a private address; read from the internet, the layer is left out, as said. diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index fad980537c..3d869eee34 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -25113,6 +25113,32 @@ fn identify_asks_wms_layers() { } } +/// A WMS layer whose request reaches past it is said whichever layer identify reports: under +/// Topmost, a feature found over it is reported and the refusal said too. +#[test] +fn a_refused_wms_layer_is_said_under_topmost_too() { + let host = "maps-topmost-web.example.com"; + let caps = format!( + r#" +Test WMS +image/png +application/geo+json +RootEPSG:3857roadsRoads"# + ); + let url = format!("https://{host}/wms"); + crate::render::rustgis_tiles::cache::restrict_to_public(&rustgis_data::ogc::capabilities_url(&url, None)); + let mut s = Session::new(Project::default()); + s.run("service.add", &json!({"url": url, "layer": "roads", "text": caps})).unwrap(); + let points = r#"{"type":"FeatureCollection","features":[{"type":"Feature","properties":{"name":"Here"},"geometry":{"type":"Point","coordinates":[8.5,47.4]}}]}"#; + s.run("layer.addDataText", &json!({"fileName": "here.geojson", "text": points})).unwrap(); + s.run("map.goToXY", &json!({"lon": 8.5, "lat": 47.4, "scale": 10000})).unwrap(); + let mark = s.notice_mark(); + let v = s.run("identify", &json!({"lon": 8.5, "lat": 47.4, "mode": "topmost", "tolerancePx": 8})).unwrap(); + assert_eq!(v["attributes"]["name"], "Here", "{v}"); + let told: Vec<_> = s.notices_since(mark).iter().map(|n| n.text.clone()).collect(); + assert!(told.iter().any(|t| t.starts_with("Roads wasn't asked what is here: http://192.168.21.5/info")), "{told:?}"); +} + /// A tile layer picked in Layers (`map.selectTiles`, view state like `layer.select`) is the one /// Selected in Layers identifies, whichever it is (a basemap too, which the other modes leave /// out); it stays picked when moved, and a map layer made active ends the pick for good. diff --git a/crates/tiles/src/portal.rs b/crates/tiles/src/portal.rs index 80f5a818cd..c2d5e8e35d 100644 --- a/crates/tiles/src/portal.rs +++ b/crates/tiles/src/portal.rs @@ -458,7 +458,16 @@ impl Portal { /// The datasets in a search's answer (read within `reach`, as its fetch observed it, which the /// resources' own addresses are judged by), with the resources RustGIS can add; datasets /// without one are left out, as are those outside `bbox` when they say where they are. - pub fn parse(&self, reach: Reach, bytes: &[u8], bbox: Option<[f64; 4]>, query: &str) -> Result, String> { + /// `refused` counts the addresses (resources and pictures) left out for reaching past `reach`, + /// for the caller to say. + pub fn parse( + &self, + reach: Reach, + refused: &mut usize, + bytes: &[u8], + bbox: Option<[f64; 4]>, + query: &str, + ) -> Result, String> { let v: Value = serde_json::from_slice(bytes).map_err(|_| format!("{}: the answer isn't JSON", self.label()))?; // The words a portal whose search takes none is kept to here: every one in the title, // description or provider. @@ -539,9 +548,13 @@ impl Portal { // The portal's answer is hostile input: an address it gives may not reach past where // the answer was read (into the local network, unless the portal is there) or a // forbidden address, however the portal's own address is spelled. + let listed = d.resources.len(); d.resources.retain(|r| crate::address::check_reach(&r.url, reach).is_ok()); + *refused = refused.saturating_add(listed - d.resources.len()); // So may its pictures', fetched as results are shown. + let pictured = d.thumbnail.is_some(); d.thumbnail = d.thumbnail.take().filter(|u| crate::address::check_reach(u, reach).is_ok()); + *refused = refused.saturating_add(usize::from(pictured && d.thumbnail.is_none())); d.resources.sort_by_key(|r| rank(&r.format)); d.resources.truncate(MAX_RESOURCES); } @@ -840,9 +853,9 @@ fn arcgis_words(q: &str) -> String { /// A web map's layers (its operational layers, those in groups too) RustGIS adds: ArcGIS services, /// named by their titles. -fn web_map_layers(v: &Value, reach: Reach) -> Result, String> { +fn web_map_layers(v: &Value, reach: Reach, refused: &mut usize) -> Result, String> { // A layer in a group is named after the group too (groups often repeat their layers' titles). - fn walk(layers: &Value, depth: usize, group: &str, out: &mut Vec, reach: Reach) { + fn walk(layers: &Value, depth: usize, group: &str, out: &mut Vec, reach: Reach, refused: &mut usize) { for l in layers.as_array().into_iter().flatten().take(500) { if out.len() >= MAX_FILES { return; @@ -856,10 +869,14 @@ fn web_map_layers(v: &Value, reach: Reach) -> Result, String> { if depth < 6 && let Some(inner) = l.get("layers") { - walk(inner, depth + 1, &named, out, reach); + walk(inner, depth + 1, &named, out, reach, refused); } let url = text(l, "url", 2048); - if let Some(mut r) = classify("ArcGIS REST", "", &url).filter(|r| crate::address::check_reach(&r.url, reach).is_ok()) { + if let Some(mut r) = classify("ArcGIS REST", "", &url) { + if crate::address::check_reach(&r.url, reach).is_err() { + *refused = refused.saturating_add(1); + continue; + } if !named.is_empty() { r.format = named; } @@ -869,7 +886,7 @@ fn web_map_layers(v: &Value, reach: Reach) -> Result, String> { } let ops = v.get("operationalLayers").ok_or("not an ArcGIS web map (it has no operational layers)")?; let mut out = Vec::new(); - walk(ops, 0, "", &mut out, reach); + walk(ops, 0, "", &mut out, reach, refused); Ok(out) } @@ -1237,10 +1254,11 @@ impl Portal { /// The files a dataset's listing ([`Dataset::listing`], fetched from `from` and read within /// `reach`, which the files' addresses are judged by) offers: those RustGIS adds, named by /// their path in the dataset. - pub fn parse_listing(&self, from: &str, reach: Reach, bytes: &[u8]) -> Result, String> { + /// `refused` counts the files left out for reaching past `reach`, for the caller to say. + pub fn parse_listing(&self, from: &str, reach: Reach, refused: &mut usize, bytes: &[u8]) -> Result, String> { let v: Value = serde_json::from_slice(bytes).map_err(|_| format!("{}: the listing isn't JSON", self.label()))?; if self.kind == Kind::ArcGis { - return web_map_layers(&v, reach); + return web_map_layers(&v, reach, refused); } let entries = v.as_array().ok_or_else(|| format!("{}: not a listing of files", self.label()))?; // `…/api/datasets/{owner}/{name}/tree/…`: the dataset. @@ -1283,7 +1301,11 @@ impl Portal { .any(|x| lower.ends_with(x)); addable.then_some(Resource { format: path, url, using: Use::File }) }) - .filter(|r| crate::address::check_reach(&r.url, reach).is_ok()) + .filter(|r| { + let ok = crate::address::check_reach(&r.url, reach).is_ok(); + *refused = refused.saturating_add(usize::from(!ok)); + ok + }) .take(MAX_FILES) .collect(); out.sort_by(|a, b| a.format.cmp(&b.format)); @@ -1357,8 +1379,10 @@ mod tests { fn answers() { let dg = br#"{"results":[{"slug":"parks","title":"Parks","description":"Parks of a city","organization":{"name":"City"},"spatial_shape":{"type":"Polygon","coordinates":[[[-122.5,47.5],[-122.2,47.5],[-122.2,47.7],[-122.5,47.5]]]},"dcat":{"distribution":[{"downloadURL":"https://x.org/p.csv","mediaType":"text/csv"},{"downloadURL":"https://x.org/p.geojson","mediaType":"application/geo+json"},{"accessURL":"http://127.0.0.1/p.geojson","format":"GeoJSON"},{"downloadURL":"https://x.org/p.html","format":"HTML"}]}},{"slug":"report","title":"A report","dcat":{"distribution":[{"downloadURL":"https://x.org/r.pdf"}]}}],"sort":"relevance"}"#; let p = Portal::new(None, None).unwrap(); - let ds = p.parse(Reach::Public, dg, None, "").unwrap(); + let mut refused = 0; + let ds = p.parse(Reach::Public, &mut refused, dg, None, "").unwrap(); assert_eq!(ds.len(), 1, "a dataset with nothing to add is left out"); + assert_eq!(refused, 1, "the local-network address is counted, for the caller to say"); let d = &ds[0]; assert_eq!((d.title.as_str(), d.organization.as_str()), ("Parks", "City")); assert_eq!(d.page.as_deref(), Some("https://catalog.data.gov/dataset/parks")); @@ -1367,33 +1391,35 @@ mod tests { assert_eq!(d.resources.iter().map(|r| r.format.as_str()).collect::>(), vec!["GeoJSON", "CSV"]); // An answer read on the local network (a portal there, whatever its name) keeps it: the // addresses are judged by where the answer was read. - let local = p.parse(Reach::Local, dg, None, "").unwrap(); + let mut refused = 0; + let local = p.parse(Reach::Local, &mut refused, dg, None, "").unwrap(); + assert_eq!(refused, 0, "nothing left out of an answer read locally"); assert!(local[0].resources.iter().any(|r| r.url == "http://127.0.0.1/p.geojson"), "{:?}", local[0].resources); // Kept to a box: a dataset elsewhere goes. - assert!(p.parse(Reach::Public, dg, Some([0.0, 0.0, 1.0, 1.0]), "").unwrap().is_empty()); - assert_eq!(p.parse(Reach::Public, dg, Some([-123.0, 47.0, -122.0, 48.0]), "").unwrap().len(), 1); - assert!(p.parse(Reach::Public, b"", None, "").is_err() && p.parse(Reach::Public, b"{}", None, "").is_err()); + assert!(p.parse(Reach::Public, &mut 0, dg, Some([0.0, 0.0, 1.0, 1.0]), "").unwrap().is_empty()); + assert_eq!(p.parse(Reach::Public, &mut 0, dg, Some([-123.0, 47.0, -122.0, 48.0]), "").unwrap().len(), 1); + assert!(p.parse(Reach::Public, &mut 0, b"", None, "").is_err() && p.parse(Reach::Public, &mut 0, b"{}", None, "").is_err()); let soc = br#"{"results":[{"resource":{"id":"enfh-gkve","name":"Parks Properties","type":"dataset","columns_datatype":["Text","MultiPolygon"]},"metadata":{"domain":"data.cityofnewyork.us"},"permalink":"https://data.cityofnewyork.us/d/enfh-gkve"},{"resource":{"id":"nc67-uf89","name":"Violations","type":"dataset","columns_datatype":["Text"]},"metadata":{"domain":"data.cityofnewyork.us"}},{"resource":{"id":"bad","name":"x","type":"dataset","columns_datatype":["Point"]},"metadata":{"domain":"evil host"}}]}"#; let s = Portal::new(Some("socrata"), None).unwrap(); - let ds = s.parse(Reach::Public, soc, None, "").unwrap(); + let ds = s.parse(Reach::Public, &mut 0, soc, None, "").unwrap(); assert_eq!(ds.len(), 1); assert_eq!(ds[0].resources[0].url, "https://data.cityofnewyork.us/resource/enfh-gkve.geojson?%24limit=50000"); let hub = br#"{"type":"FeatureCollection","features":[{"id":"c5ef","properties":{"id":"c5ef","title":"parks","type":"Feature Service","owner":"nyc","url":"https://services1.arcgis.com/S/arcgis/rest/services/parks/FeatureServer","extent":{"type":"Polygon","coordinates":[[[-73.9,40.76],[-73.87,40.76],[-73.87,40.74],[-73.9,40.76]]]}}},{"properties":{"title":"no url"}}]}"#; let h = Portal::new(Some("arcgis-hub"), None).unwrap(); - let ds = h.parse(Reach::Public, hub, None, "").unwrap(); + let ds = h.parse(Reach::Public, &mut 0, hub, None, "").unwrap(); assert_eq!(ds.len(), 1); assert_eq!(ds[0].resources[0].using, Use::Service { kind: "arcgis", layer: None }); assert_eq!(ds[0].bbox, Some([-73.9, 40.74, -73.87, 40.76])); let ckan = br#"{"success":true,"result":{"count":1,"results":[{"name":"lakes","title":"Lakes","notes":"All lakes","organization":{"title":"NRCan"},"extras":[{"key":"spatial","value":"{\"type\":\"Polygon\",\"coordinates\":[[[-80,43],[-79,43],[-79,44],[-80,43]]]}"}],"resources":[{"format":"WMS","url":"https://maps.example.ca/wms?service=WMS"},{"format":"SHP","url":"https://x.ca/lakes.zip"}]}]}}"#; let c = Portal::new(Some("ckan"), Some("https://open.canada.ca/data")).unwrap(); - let ds = c.parse(Reach::Public, ckan, None, "").unwrap(); + let ds = c.parse(Reach::Public, &mut 0, ckan, None, "").unwrap(); assert_eq!(ds[0].page.as_deref(), Some("https://open.canada.ca/data/dataset/lakes")); assert_eq!(ds[0].resources.iter().map(|r| r.format.as_str()).collect::>(), vec!["Shapefile", "WMS"]); assert!( - c.parse(Reach::Public, br#"{"success":false,"error":{"message":"Bad request"}}"#, None, "") + c.parse(Reach::Public, &mut 0, br#"{"success":false,"error":{"message":"Bad request"}}"#, None, "") .unwrap_err() .contains("Bad request") ); @@ -1446,7 +1472,7 @@ mod tests { fn web_service_answers() { let agol = Portal::new(Some("arcgis-portal"), None).unwrap(); let a = br#"{"total":3,"results":[{"id":"abc123","type":"Feature Service","title":"Parks","owner":"city","snippet":"City parks","url":"https://services.arcgis.com/x/arcgis/rest/services/Parks/FeatureServer/0","extent":[[-122.5,47.5],[-122.2,47.7]]},{"id":"def456","type":"GeoJson","title":"Trails"},{"id":"bad id","type":"Map Service","url":"https://x.org/arcgis/rest/services/a/MapServer"},{"id":"ghi789","type":"Image Service","title":"Imagery","url":"https://x.org/arcgis/rest/services/i/ImageServer"}]}"#; - let ds = agol.parse(Reach::Public, a, None, "").unwrap(); + let ds = agol.parse(Reach::Public, &mut 0, a, None, "").unwrap(); assert_eq!(ds.len(), 3, "the item with a bad id is left out"); assert_eq!(ds[0].resources[0].using, Use::Service { kind: "arcgis", layer: Some("0".into()) }); assert_eq!(ds[0].bbox, Some([-122.5, 47.5, -122.2, 47.7])); @@ -1454,27 +1480,27 @@ mod tests { assert_eq!(ds[1].resources[0].url, "https://www.arcgis.com/sharing/rest/content/items/def456/data"); assert_eq!(ds[2].resources[0].url, "https://x.org/arcgis/rest/services/i/ImageServer"); assert!( - agol.parse(Reach::Public, br#"{"error":{"code":400,"message":"Invalid query"}}"#, None, "") + agol.parse(Reach::Public, &mut 0, br#"{"error":{"code":400,"message":"Invalid query"}}"#, None, "") .unwrap_err() .contains("Invalid query") ); let oam = Portal::new(Some("openaerialmap"), None).unwrap(); let o = br#"{"meta":{"found":2},"results":[{"_id":"1","uuid":"https://oin.s3.amazonaws.com/a/b.tif","title":"Village","provider":"HOT","platform":"uav","gsd":0.05,"acquisition_end":"2026-09-20T06:00:00Z","bbox":[-77.3,4.85,-77.2,4.86]},{"_id":"2","uuid":"https://oin.s3.amazonaws.com/a/c.tif","title":"Coast","bbox":[1,2,3]}]}"#; - let ds = oam.parse(Reach::Public, o, Some([-80.0, 0.0, -70.0, 10.0]), "").unwrap(); + let ds = oam.parse(Reach::Public, &mut 0, o, Some([-80.0, 0.0, -70.0, 10.0]), "").unwrap(); assert_eq!(ds.len(), 2, "an image whose box isn't one is kept"); assert_eq!((ds[0].kind.as_str(), ds[0].date.as_str()), ("uav · 5 cm per pixel", "2026-09-20")); - assert_eq!(oam.parse(Reach::Public, o, None, "coast").unwrap()[0].title, "Coast"); + assert_eq!(oam.parse(Reach::Public, &mut 0, o, None, "coast").unwrap()[0].title, "Coast"); let dem = Portal::new(Some("usgs-dem"), None).unwrap(); let d = br#"{"total":3,"items":[{"title":"USGS 1/3 Arc Second n47w123 20121001","downloadURL":"https://prd-tnm.s3.amazonaws.com/x/historical/n47w123/a.tif","publicationDate":"2012-10-01","boundingBox":{"minX":-123,"minY":46,"maxX":-122,"maxY":47}},{"title":"USGS 1/3 Arc Second n47w123 20240101","downloadURL":"https://prd-tnm.s3.amazonaws.com/x/current/n47w123/b.tif","publicationDate":"2024-01-01"},{"title":"USGS 1/3 Arc Second n47w123 20250813","downloadURL":"https://prd-tnm.s3.amazonaws.com/x/historical/n47w123/c.tif","publicationDate":"2025-08-13"}]}"#; - let ds = dem.parse(Reach::Public, d, None, "").unwrap(); + let ds = dem.parse(Reach::Public, &mut 0, d, None, "").unwrap(); assert_eq!(ds.len(), 1, "one per tile"); assert!(ds[0].resources[0].url.ends_with("/current/n47w123/b.tif"), "the current edition"); let ign = Portal::new(Some("ign-lidar"), None).unwrap(); let i = br#"{"features":[{"id":"metadata.1","geometry":{"type":"Polygon","coordinates":[[[2.3,48.8],[2.31,48.8],[2.31,48.81],[2.3,48.8]]]},"properties":{"coordonnees_nw":"0650-6858","nombre_points":17455527,"date_fin_acquisition":"2023-03-01Z","url_npl":"https://data.geopf.fr/telechargement/download/x/LHD_FXX_0650_6858_PTS_LAMB93_IGN69.copc.laz"}},{"id":"metadata.2","properties":{"url_npl":"http://x.org/a.laz"}}]}"#; - let ds = ign.parse(Reach::Public, i, None, "").unwrap(); + let ds = ign.parse(Reach::Public, &mut 0, i, None, "").unwrap(); assert_eq!(ds.len(), 1); assert_eq!( (ds[0].title.as_str(), ds[0].kind.as_str(), ds[0].date.as_str()), @@ -1483,30 +1509,30 @@ mod tests { let gl = Portal::new(Some("geolens"), None).unwrap(); let g = br#"{"type":"FeatureCollection","features":[{"id":"8c26-1","properties":{"title":"Tracks","record_type":"vector_dataset","geometry_type":"MULTILINESTRING","feature_count":12}},{"id":"r1","properties":{"title":"DEM","record_type":"raster_dataset","band_count":1}},{"id":"../x","properties":{"title":"Bad"}}]}"#; - let ds = gl.parse(Reach::Public, g, None, "").unwrap(); + let ds = gl.parse(Reach::Public, &mut 0, g, None, "").unwrap(); assert_eq!(ds.len(), 1); assert_eq!(ds[0].resources[0].url, "https://datasets.geolibre.app/api/collections/8c26-1/items?limit=1000"); assert_eq!(ds[0].resources[0].using, Use::Features, "read page by page"); let hf = Portal::new(Some("huggingface"), None).unwrap(); let h = br#"[{"id":"giswqs/geospatial","downloads":10,"gated":false,"private":false,"tags":["license:mit","region:us"]},{"id":"a/gated","gated":"manual"},{"id":"noslash"}]"#; - let ds = hf.parse(Reach::Public, h, None, "").unwrap(); + let ds = hf.parse(Reach::Public, &mut 0, h, None, "").unwrap(); assert_eq!(ds.len(), 1); assert_eq!((ds[0].kind.as_str(), ds[0].description.as_str(), ds[0].resources.len()), ("Dataset · 10 downloads", "license: mit", 0)); let listing = ds[0].listing.clone().unwrap(); assert_eq!(Some(listing.clone()), hf.listing_of("giswqs/geospatial")); let files = br#"[{"type":"directory","path":"naip"},{"type":"file","path":"naip/a b.tif"},{"type":"file","path":"README.md"},{"type":"file","path":"x/../../etc.geojson"},{"type":"file","path":"z.pmtiles"}]"#; - let r = hf.parse_listing(&listing, Reach::Public, files).unwrap(); + let r = hf.parse_listing(&listing, Reach::Public, &mut 0, files).unwrap(); assert_eq!(r.iter().map(|r| r.format.as_str()).collect::>(), vec!["naip/a b.tif", "z.pmtiles"]); assert_eq!(r[0].url, "https://huggingface.co/datasets/giswqs/geospatial/resolve/main/naip/a%20b.tif"); - assert!(hf.parse_listing("https://huggingface.co/api/datasets/../tree/main", Reach::Public, files).is_err()); - assert!(hf.parse_listing(&listing, Reach::Public, b"{}").is_err()); + assert!(hf.parse_listing("https://huggingface.co/api/datasets/../tree/main", Reach::Public, &mut 0, files).is_err()); + assert!(hf.parse_listing(&listing, Reach::Public, &mut 0, b"{}").is_err()); let odp = Portal::new(Some("ocean-data"), None).unwrap(); let o = br#"{"features":[{"id":"cd48-1","bbox":[-64.6,17.7,-64.5,17.8],"properties":{"title":"Published - Coral sites","description":"Reef survey"}},{"id":"x2","bbox":[10,50,11,51],"properties":{"title":"Kelp"}}]}"#; - let ds = odp.parse(Reach::Public, o, None, "coral").unwrap(); + let ds = odp.parse(Reach::Public, &mut 0, o, None, "coral").unwrap(); assert_eq!((ds.len(), ds[0].title.as_str()), (1, "Coral sites")); - assert_eq!(odp.parse(Reach::Public, o, Some([9.0, 49.0, 12.0, 52.0]), "").unwrap()[0].title, "Kelp"); + assert_eq!(odp.parse(Reach::Public, &mut 0, o, Some([9.0, 49.0, 12.0, 52.0]), "").unwrap()[0].title, "Kelp"); // Hostile answers: never a panic, an error or nothing. for k in ["arcgis-portal", "openaerialmap", "usgs-dem", "ign-lidar", "geolens", "huggingface", "ocean-data"] { @@ -1519,8 +1545,8 @@ mod tests { b"{\"features\":[{\"properties\":7}]}", b"{\"items\":\"x\"}", ] { - let _ = p.parse(Reach::Public, junk, Some([0.0, 0.0, 1.0, 1.0]), "a"); - let _ = p.parse_listing("https://huggingface.co/api/datasets/a/b/tree/main", Reach::Public, junk); + let _ = p.parse(Reach::Public, &mut 0, junk, Some([0.0, 0.0, 1.0, 1.0]), "a"); + let _ = p.parse_listing("https://huggingface.co/api/datasets/a/b/tree/main", Reach::Public, &mut 0, junk); } } } @@ -1546,7 +1572,7 @@ mod tests { assert_eq!(oam.paging(&ou, b"junk"), (None, None)); // A web map's item, its kind, date and picture, and its layers. let a = br#"{"results":[{"id":"w1","type":"Web Map","title":"Isaias","owner":"patrick_rea","modified":1792108800000,"thumbnail":"thumbnail/t.png"}]}"#; - let ds = p.parse(Reach::Public, a, None, "").unwrap(); + let ds = p.parse(Reach::Public, &mut 0, a, None, "").unwrap(); let d = &ds[0]; assert_eq!((d.kind.as_str(), d.date.as_str()), ("Web map", "2026-10-16")); assert_eq!( @@ -1556,10 +1582,10 @@ mod tests { let listing = d.listing.clone().unwrap(); assert_eq!(Some(listing.clone()), p.listing_of("w1")); let wm = br#"{"operationalLayers":[{"title":"Optical","url":"https://gis.earthdata.nasa.gov/portal/rest/services/a/ImageServer"},{"layerType":"GroupLayer","title":"Sept","layers":[{"title":"Flood","url":"https://gis.earthdata.nasa.gov/portal/rest/services/b/MapServer/2"}]},{"title":"Notes"},{"title":"Local","url":"http://169.254.169.254/rest/services/c/FeatureServer/0"}]}"#; - let layers = p.parse_listing(&listing, Reach::Public, wm).unwrap(); + let layers = p.parse_listing(&listing, Reach::Public, &mut 0, wm).unwrap(); assert_eq!(layers.iter().map(|r| r.format.as_str()).collect::>(), vec!["Optical", "Sept › Flood"]); assert_eq!(layers[1].using, Use::Service { kind: "arcgis", layer: Some("2".into()) }); - assert!(p.parse_listing(&listing, Reach::Public, b"{}").is_err()); + assert!(p.parse_listing(&listing, Reach::Public, &mut 0, b"{}").is_err()); assert_eq!(day_of_ms(0.0), "1970-01-01"); assert_eq!(day_of_ms(951_782_400_000.0), "2000-02-29"); assert_eq!(day_of_ms(f64::NAN), ""); @@ -1572,7 +1598,7 @@ mod tests { assert!(!p.needs_query() && !p.needs_place()); assert_eq!(p.search_url("", None, 20), "https://stac.dynamical.org/catalog.json"); let c = br#"{"links":[{"rel":"root","href":"https://stac.dynamical.org/catalog.json"},{"rel":"child","href":"https://stac.dynamical.org/noaa-gfs-forecast/collection.json","title":"NOAA GFS forecast"},{"rel":"child","href":"https://stac.dynamical.org/noaa-gfs-forecast-virtual/collection.json","title":"virtual"},{"rel":"child","href":"https://stac.dynamical.org/ecmwf-ifs-ens-forecast-15-day-0-25-degree/collection.json"},{"rel":"child","href":"https://stac.dynamical.org/odd/collection.json"}]}"#; - let ds = p.parse(Reach::Public, c, None, "").unwrap(); + let ds = p.parse(Reach::Public, &mut 0, c, None, "").unwrap(); assert_eq!( ds.iter().map(|d| d.resources[0].url.as_str()).collect::>(), vec![ @@ -1582,7 +1608,7 @@ mod tests { ); assert_eq!((ds[0].title.as_str(), ds[0].organization.as_str(), ds[0].kind.as_str()), ("NOAA GFS forecast", "NOAA", "Forecast")); assert_eq!(ds[0].resources[0].using, Use::Zarr); - assert_eq!(p.parse(Reach::Public, c, None, "ecmwf").unwrap().len(), 1); + assert_eq!(p.parse(Reach::Public, &mut 0, c, None, "ecmwf").unwrap().len(), 1); } #[test] diff --git a/crates/ui-egui/src/cswui.rs b/crates/ui-egui/src/cswui.rs index 5fa0b60d5d..6eb42f9421 100644 --- a/crates/ui-egui/src/cswui.rs +++ b/crates/ui-egui/src/cswui.rs @@ -4,6 +4,7 @@ //! off the frame; `catalog.search` reads the answers. use egui::vec2; +use rustgis_engine::render::rustgis_tiles::{address::Reach, cache}; use serde_json::{Value, json}; use crate::{RustGisApp, Slot}; @@ -80,7 +81,11 @@ pub fn search(app: &mut RustGisApp, start: u64) { st.next = None; st.asked = asked; } - // Recorded if read from the internet, so `catalog.search` holds the links it lists there. + // A catalogue held to the internet is searched only there; an answer read from the + // internet is recorded, so `catalog.search` holds the links it lists there. + if p.get("url").and_then(Value::as_str).is_some_and(|url| cache::ceiling_for(url) == Reach::Public) { + cache::restrict_to_public(&request); + } st.waiting = Some((p, crate::fetch_document_into(&request))); } Err(e) => app.ui.csw.error = Some(e), @@ -313,4 +318,27 @@ mod tests { assert_eq!(cache::ceiling_for(&caps), observed); } } + + /// A catalogue a document read from the internet named (`fromDocument`) is searched only there. + #[test] + fn a_catalogue_a_document_named_is_searched_only_on_the_internet() { + for public in [true, false] { + let _turn = crate::fetching::turn(); + let asked = std::sync::Arc::new(std::sync::Mutex::new(Vec::new())); + let log = asked.clone(); + cache::set_fetcher_with_origin(move |url, ceiling, done, _| { + log.lock().unwrap().push(ceiling); + let origin = Origin::with_observed_reach(cache::split_download_limit(&url).0, ceiling).unwrap(); + done(Ok(cache::Fetched { + bytes: b"".to_vec(), + origin, + })); + }); + let mut app = RustGisApp::new(rustgis_engine::Session::new(rustgis_engine::Project::default())); + let csw = format!("https://csw-named-{public}.example/csw"); + app.run("ui.addService", json!({"url": csw, "type": "csw", "fromDocument": public})).unwrap(); + let want = if public { Reach::Public } else { Reach::Local }; + assert_eq!(asked.lock().unwrap().clone(), [want]); + } + } } diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index ea3ae56ed0..38fa5bbccc 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -664,7 +664,9 @@ pub struct TilesResolve { pub vector: bool, /// The usual-path template, when the advertised one can't be read. pub fallback: String, - pub slot: Slot, String>>, + /// The document's answer, with the reach it was read at: what it names is judged by that, + /// whatever the address's record says by the time it lands. + pub slot: Slot, Reach), String>>, } /// A service layer waiting on a document before it is added. `dialog` tells whether the add came @@ -676,7 +678,14 @@ pub enum ServiceStep { Tiles { resolve: TilesResolve, dialog: bool, origin: Option, opened: u64 }, /// A WCS coverage whose description is being read before it is asked for: `service.coverage`'s /// parameters and the description on its way. - Coverage { params: Value, slot: Slot, String>>, dialog: bool, origin: Option, opened: u64 }, + Coverage { + params: Value, + describe: String, + slot: Slot, Reach), String>>, + dialog: bool, + origin: Option, + opened: u64, + }, } impl ServiceStep { @@ -756,6 +765,29 @@ pub(crate) fn fetch_within( slot } +/// [`fetch_document_into`], landing with the reach the document was read at (recorded too, if +/// from the internet), for a step that judges what the document names when it lands. +pub(crate) fn fetch_document_reaching(url: &str) -> Slot, Reach), String>> { + let slot: Slot, Reach), String>> = Slot::default(); + let land = slot.clone(); + let asked = url.to_string(); + cache::download_detailed_with_origin( + url, + cache::MAX_DOWNLOAD, + Box::new(move |r| { + let r = r.map_err(|failure| failure.message).map(|fetched| { + let reach = fetched.origin.reach(); + if reach == Reach::Public { + cache::restrict_to_public(&asked); + } + (fetched.bytes, reach) + }); + *land.lock().unwrap_or_else(|e| e.into_inner()) = Some(r); + }), + ); + slot +} + pub(crate) fn fetch_into_limited(url: &str, max: usize) -> Slot, String>> { let slot: Slot, String>> = Slot::default(); let land = slot.clone(); @@ -4461,6 +4493,11 @@ impl RustGisApp { } self.dialogs.mode = "csw"; self.dialogs.connection = connection; + // A catalogue a document read from the internet named is searched only there + // (its requests follow its record, `cswui::search`). + if from_document { + cache::restrict_to_public(url); + } self.ui.csw.url = url.to_string(); self.ui.csw.query = p.get("query").and_then(Value::as_str).unwrap_or("").to_string(); self.ui.csw.use_view = p.get("bbox").and_then(Value::as_str) == Some("view"); @@ -6534,7 +6571,14 @@ impl RustGisApp { self.ui.service_steps.push(ServiceStep::Tiles { resolve, dialog, origin, opened }); continue; }; - let next = r.ok().and_then(|body| resolve_tiles(&resolve.list, &resolve.doc, &body, resolve.vector)); + // Where the document was read, as its fetch observed it (one that failed: what + // it was asked within). Recorded again for one read from the internet, so + // `service.add` sees it whatever the record says by now. + let read_at = r.as_ref().map_or_else(|_| cache::ceiling_for(&resolve.doc), |(_, reach)| *reach); + if read_at == Reach::Public { + cache::restrict_to_public(&resolve.doc); + } + let next = r.ok().and_then(|(body, _)| resolve_tiles(&resolve.list, &resolve.doc, &body, resolve.vector)); let next = next.map(|resolved| { resolve.withheld_addresses = resolve.withheld_addresses.saturating_add(resolved.withheld_addresses); resolved.step @@ -6546,16 +6590,16 @@ impl RustGisApp { // its absence. A saved connection must not restore it after a hop. // Judged by where the list was read (its record), not by how its // address is spelled: a public-looking name may connect on the local network. - match rustgis_engine::render::rustgis_tiles::address::check_reach(&next, cache::ceiling_for(&resolve.doc)) { + match rustgis_engine::render::rustgis_tiles::address::check_reach(&next, read_at) { Ok(()) => { resolve.crossed_origin |= rustgis_engine::render::rustgis_tiles::logins::origin(&resolve.doc) != rustgis_engine::render::rustgis_tiles::logins::origin(&next); // A tile set document read from the internet leads only there. - if cache::ceiling_for(&resolve.doc) == Reach::Public { + if read_at == Reach::Public { cache::restrict_to_public(&next); } resolve.doc = next; - resolve.slot = fetch_document_into(&resolve.doc); + resolve.slot = fetch_document_reaching(&resolve.doc); } Err(e) => { self.notice_service_query_loss(resolve.withheld_addresses); @@ -6574,7 +6618,7 @@ impl RustGisApp { }; // After a tile set document read from the internet, the tiles come only from // there: the template it names, or the usual one in its place. - if cache::ceiling_for(&resolve.doc) == Reach::Public { + if read_at == Reach::Public { cache::restrict_to_public(&template); } resolve.crossed_origin |= rustgis_engine::render::rustgis_tiles::logins::origin(&resolve.doc) @@ -6596,7 +6640,7 @@ impl RustGisApp { self.report_step(dialog, pending.as_deref(), r); self.map.invalidate(); } - ServiceStep::Coverage { mut params, slot, dialog, origin, opened } => { + ServiceStep::Coverage { mut params, describe, slot, dialog, origin, opened } => { if !self.service_read_current( opened, params.get("url").and_then(Value::as_str).unwrap_or(""), @@ -6605,11 +6649,16 @@ impl RustGisApp { continue; } let Some(r) = slot.lock().unwrap_or_else(|e| e.into_inner()).take() else { - self.ui.service_steps.push(ServiceStep::Coverage { params, slot, dialog, origin, opened }); + self.ui.service_steps.push(ServiceStep::Coverage { params, describe, slot, dialog, origin, opened }); continue; }; let title = params["name"].as_str().unwrap_or("").to_string(); - let r = r.and_then(|bytes| { + let r = r.and_then(|(bytes, reach)| { + // Recorded again for one read from the internet, so `service.coverage` + // holds the request built from it there whatever the record says by now. + if reach == Reach::Public { + cache::restrict_to_public(&describe); + } params["describe"] = json!(String::from_utf8_lossy(&bytes)); // Not `self.run`: an error belongs where the step reports, not the notices. let c = self.session.run("service.coverage", ¶ms)?; @@ -8589,7 +8638,7 @@ mod download_service_tests { withheld_addresses: 0, vector: false, fallback: "https://h.invalid/svc/tiles/{z}/{y}/{x}".into(), - slot: std::sync::Arc::new(std::sync::Mutex::new(Some(Ok(body)))), + slot: std::sync::Arc::new(std::sync::Mutex::new(Some(Ok((body, super::Reach::Local))))), }; app.ui.service_steps.push(super::ServiceStep::Tiles { resolve, dialog: true, origin: None, opened: app.session.opened }); app.poll_service_steps(); @@ -8611,8 +8660,8 @@ mod download_service_tests { for (query, count) in [("collections=roads", 0), ("token=RGSYNTH_ui_refused&collections=roads", 1)] { let mut app = RustGisApp::new(rustgis_engine::Session::new(rustgis_engine::Project::default())); let list = format!("https://h.invalid/svc/tiles?{query}"); - // The list was read from the internet (the dialog's fetch records it). - rustgis_engine::render::rustgis_tiles::cache::restrict_to_public(&list); + // The list was read from the internet, as its fetch observed it; its record may since + // have been cleared (a direct add of the same address), which changes nothing. let body = json!({"tilesets":[{"tileMatrixSetId":"WebMercatorQuad", "links":[{"rel":"self", "href":"http://127.0.0.1/tiles"}]}]}) .to_string() @@ -8626,7 +8675,7 @@ mod download_service_tests { withheld_addresses: 0, vector: false, fallback: "https://h.invalid/svc/tiles/{z}/{y}/{x}".into(), - slot: std::sync::Arc::new(std::sync::Mutex::new(Some(Ok(body)))), + slot: std::sync::Arc::new(std::sync::Mutex::new(Some(Ok((body, super::Reach::Public))))), }; app.ui.service_steps.push(super::ServiceStep::Tiles { resolve, dialog: false, origin: None, opened: app.session.opened }); app.poll_service_steps(); @@ -8837,7 +8886,14 @@ mod download_service_tests { let params = json!({"url":"https://h.invalid/wcs", "name":"Heights"}); let slot = std::sync::Arc::new(std::sync::Mutex::new(Some(Err("the server is down".to_string())))); let opened = app.session.opened; - app.ui.service_steps.push(super::ServiceStep::Coverage { params, slot, dialog: true, origin: None, opened }); + app.ui.service_steps.push(super::ServiceStep::Coverage { + params, + describe: String::new(), + slot, + dialog: true, + origin: None, + opened, + }); app.dialogs.info = Some(if newer { "Reading the tileset of Roads" } else { "Describing Heights" }.into()); app.dialogs.open = open.then_some("addService"); app.poll_service_steps(); @@ -8864,9 +8920,16 @@ mod download_service_tests { let opened = app.session.opened; let params = json!({"url":"https://retired.invalid/service", "name":"Old read"}); let slot = std::sync::Arc::new(std::sync::Mutex::new(None)); - let step = |opened, slot: std::sync::Arc, String>>>>| { + let step = |opened, slot: std::sync::Arc, super::Reach), String>>>>| { if coverage { - super::ServiceStep::Coverage { params: params.clone(), slot, dialog: true, origin: None, opened } + super::ServiceStep::Coverage { + params: params.clone(), + describe: String::new(), + slot, + dialog: true, + origin: None, + opened, + } } else { super::ServiceStep::Tiles { resolve: super::TilesResolve { @@ -8893,7 +8956,7 @@ mod download_service_tests { app.ui.service_steps.push(step(app.session.opened, Default::default())); } app.dialogs.info = Some(if newer == 1 { "New operation" } else { pending }.into()); - *slot.lock().unwrap() = Some(Ok(b"late completion".to_vec())); + *slot.lock().unwrap() = Some(Ok((b"late completion".to_vec(), super::Reach::Local))); app.poll_service_steps(); assert_eq!(app.ui.service_steps.len(), usize::from(newer == 2)); assert!(app.session.map().tiles.is_empty() && app.session.map().layers.is_empty()); diff --git a/crates/ui-egui/src/mapview.rs b/crates/ui-egui/src/mapview.rs index a18d36c227..87609f80ff 100644 --- a/crates/ui-egui/src/mapview.rs +++ b/crates/ui-egui/src/mapview.rs @@ -107,8 +107,8 @@ pub struct Ask { /// The other layers waiting for the same capabilities: fetched and read once for all. also: Vec, capabilities: bool, - /// The GetFeatureInfo request asked (none for capabilities): its answer format tells what to - /// ask next after the service's error. + /// The GetFeatureInfo request asked, whose answer format tells what to ask next after the + /// service's error; or the capabilities asked for, which only layers of that service take. request: Option, /// The answer, with the reach it was read at. slot: crate::Slot, Reach), String>>, @@ -144,7 +144,7 @@ impl Popup { fetched.push((url.to_string(), asks.len())); } let slot = ask_within(a, url); - let request = (!capabilities).then(|| url.to_string()); + let request = Some(url.to_string()); asks.push(Ask { layer, also: Vec::new(), capabilities, request, slot }); } Popup { info, at, index: 0, map, opened, asks, since: web_time::Instant::now() } @@ -4131,8 +4131,22 @@ fn follow_asks(app: &mut RustGisApp, ctx: &egui::Context) { let exists = |app: &RustGisApp, layer: &str| app.session.map().tiles.iter().any(|t| t.name == layer && t.draws()); for (layer, also, capabilities, request, r) in landed { // Layers removed, renamed or hidden while the answer came: nothing to show, nothing to - // tell. The first of a service's layers still there takes the capabilities for the rest. - let mut group = std::iter::once(layer).chain(also).filter(|l| exists(app, l)); + // tell. The first of a service's layers still there takes the capabilities for the rest; + // capabilities go only to layers still of the service they were asked of (not another + // layer since given the same name). + let of_service = |app: &RustGisApp, l: &str| { + !capabilities + || app + .session + .map() + .tiles + .iter() + .find(|t| t.name == l) + .and_then(|t| rustgis_engine::data::ogc::wms_layer_of(&t.url)) + .map(|(c, _)| c) + == request + }; + let mut group = std::iter::once(layer).chain(also).filter(|l| exists(app, l) && of_service(app, l)); let Some(layer) = group.next() else { continue }; let also: Vec = group.collect(); // The fetch's failure, or an answer that isn't text, is told here; the command tells its @@ -4142,10 +4156,9 @@ fn follow_asks(app: &mut RustGisApp, ctx: &egui::Context) { // own read does (the layer then lists them with `"public"`). if capabilities && reach == Reach::Public - && let Some((caps, _)) = - app.session.map().tiles.iter().find(|t| t.name == layer).and_then(|t| rustgis_engine::data::ogc::wms_layer_of(&t.url)) + && let Some(caps) = &request { - cache::restrict_to_public(&caps); + cache::restrict_to_public(caps); } rustgis_engine::data::ogc::answer_text(&bytes).map(std::borrow::Cow::into_owned) }) { @@ -5641,6 +5654,38 @@ mod tests { assert!(told.iter().any(|t| t.contains("http://192.168.7.5/info") && t.contains("local network")), "{told:?}"); } + /// Capabilities answer only the service they were asked of: a layer replaced meanwhile by + /// another service's, under the same name, neither learns from them nor has its own + /// capabilities held to the internet by them. + #[test] + fn capabilities_answer_only_the_service_they_were_asked_of() { + use rustgis_engine::render::rustgis_tiles::address::Origin; + let _turn = crate::fetching::turn(); + cache::set_fetcher_with_origin(move |url, ceiling, done, _| { + let origin = Origin::with_observed_reach(cache::split_download_limit(&url).0, ceiling.min(Reach::Public)).unwrap(); + done(Ok(cache::Fetched { bytes: b"".to_vec(), origin })); + }); + let template = |host: &str| { + format!( + "https://{host}/wms?SERVICE=WMS&VERSION=1.3.0&REQUEST=GetMap&LAYERS=over&STYLES=&CRS=EPSG:3857&BBOX={{bbox-epsg-3857}}&WIDTH=256&HEIGHT=256&FORMAT=image%2Fpng" + ) + }; + let (first, second) = (template("caps-asked.example"), template("caps-replacement.example")); + let mut s = rustgis_engine::Session::new(rustgis_engine::Project::default()); + s.run("map.addTiles", &json!({"url": first, "name": "Over", "overlay": true})).unwrap(); + let (asked, replacement) = + (rustgis_engine::data::ogc::wms_layer_of(&first).unwrap().0, rustgis_engine::data::ogc::wms_layer_of(&second).unwrap().0); + let (map, opened) = (s.project.active_map, s.opened); + let mut app = RustGisApp::new(s); + app.map.popup = + Some(Popup::new(json!({"featureInfo": [{"tileLayer": "Over", "capabilities": asked}]}), Coord::new(8.6, 46.65), map, opened)); + // The layer is replaced by another service's, with the same name, while the answer comes. + app.session.map_mut().tiles[0].url = second.clone(); + follow_asks(&mut app, &egui::Context::default()); + assert_eq!(cache::ceiling_for(&replacement), Reach::Local, "the replacement's own capabilities aren't held by another's answer"); + assert!(app.session.map().tiles[0].feature_info.is_none(), "nor learned from it"); + } + /// Answers that land while the pop-up waits open it on the top result, with its feature /// selected: drawn over Countries, Over's feature comes first, and Switzerland, selected by the /// click, no longer is. diff --git a/crates/ui-egui/src/opendataui.rs b/crates/ui-egui/src/opendataui.rs index efebf412ac..3e9682e225 100644 --- a/crates/ui-egui/src/opendataui.rs +++ b/crates/ui-egui/src/opendataui.rs @@ -197,8 +197,15 @@ pub fn poll(app: &mut RustGisApp, ctx: &egui::Context) { }; let Some(w) = app.ui.opendata.waiting.take() else { return }; let replaced = !w.more && app.ui.opendata.zarr_open.is_some(); + let mut refused = 0; + let parsed = r.and_then(|(b, reach)| { + w.portal.parse(reach, &mut refused, &b, w.area, &w.query).map(|found| (found, w.portal.paging(&w.url, &b), reach)) + }); + if let Some(notice) = rustgis_engine::cmd::portals::refused_notice(refused) { + app.session.notify(notice, false); + } let st = &mut app.ui.opendata; - match r.and_then(|(b, reach)| w.portal.parse(reach, &b, w.area, &w.query).map(|found| (found, w.portal.paging(&w.url, &b), reach))) { + match parsed { Ok((found, (total, next), reach)) => { let first = if w.more { st.found.len() } else { 0 }; if w.more { @@ -244,8 +251,13 @@ fn poll_listing(app: &mut RustGisApp, ctx: &egui::Context) { return; }; let Some((i, portal, url, _)) = app.ui.opendata.listing.take() else { return }; + let mut refused = 0; + let parsed = r.and_then(|(b, reach)| portal.parse_listing(&url, reach, &mut refused, &b).map(|files| (files, reach))); + if let Some(notice) = rustgis_engine::cmd::portals::refused_notice(refused) { + app.session.notify(notice, false); + } let st = &mut app.ui.opendata; - match r.and_then(|(b, reach)| portal.parse_listing(&url, reach, &b).map(|files| (files, reach))) { + match parsed { Ok((files, reach)) => { // The files came in the listing: they reach no further than it was read. if let Some(r) = st.reaches.get_mut(i) { @@ -888,7 +900,14 @@ mod tests { } else { format!("http://10.0.{n}.3/p.geojson") }; - let answer = json!({"results":[{"slug":"parks","title":"Parks","organization":{"name":"City"},"dcat":{"distribution":[{"downloadURL":file,"mediaType":"application/geo+json"}]}}]}).to_string(); + // Read from the internet, the answer also lists a file on a private address: left out, + // and said. (Read locally, its one file is on a private address already.) + let mut files = vec![json!({"downloadURL":file,"mediaType":"application/geo+json"})]; + if observed == Reach::Public { + files.push(json!({"downloadURL":format!("http://10.0.{n}.4/q.csv"),"mediaType":"text/csv"})); + } + let answer = json!({"results":[{"slug":"parks","title":"Parks","organization":{"name":"City"},"dcat":{"distribution":files}}]}) + .to_string(); let asked = std::sync::Arc::new(std::sync::Mutex::new(Vec::new())); let log = asked.clone(); cache::set_fetcher_with_origin(move |url, ceiling, done, _| { @@ -911,6 +930,15 @@ mod tests { h.run_steps(3); assert_eq!(h.state().ui.opendata.found.len(), 1, "{:?}", h.state().ui.opendata.error); assert_eq!(h.state().ui.opendata.reaches, [observed]); + let said = h + .state() + .session + .notices + .iter() + .filter(|n| n.text.contains("addresses the portal listed point where RustGIS won't fetch")) + .count(); + assert_eq!(said, usize::from(observed == Reach::Public), "the private file left out is said once, from the internet only"); + assert_eq!(h.state().ui.opendata.found[0].resources.len(), 1); h.get_by_label("Add").click(); h.run_steps(3); let asked = asked.lock().unwrap().clone(); diff --git a/crates/ui-egui/src/serviceui.rs b/crates/ui-egui/src/serviceui.rs index c7beed5de7..54c3285207 100644 --- a/crates/ui-egui/src/serviceui.rs +++ b/crates/ui-egui/src/serviceui.rs @@ -237,8 +237,8 @@ pub(crate) fn add_layer_from( cache::restrict_to_public(&describe); } // Recorded if read from the internet: the GetCoverage request built from it goes there too. - let slot = fetch_document_into(&describe); - app.ui.service_steps.push(crate::ServiceStep::Coverage { params: p, slot, dialog, origin, opened: app.session.opened }); + let slot = crate::fetch_document_reaching(&describe); + app.ui.service_steps.push(crate::ServiceStep::Coverage { params: p, describe, slot, dialog, origin, opened: app.session.opened }); return Ok(describing(&title)); } let mut p = json!({"url": src.url, "layer": name, "text": src.text, "documents": src.documents, "source_url": l.get("source_url")}); @@ -271,7 +271,7 @@ pub(crate) fn add_layer_from( cache::restrict_to_public(&list); } // (Recording one read from the internet: what it names is fetched only from there.) - let slot = crate::fetch_document_into(&list); + let slot = crate::fetch_document_reaching(&list); let resolve = crate::TilesResolve { params: p, list: list.clone(), @@ -1072,12 +1072,12 @@ mod tests { } let params = match &app.ui.service_steps[0] { crate::ServiceStep::Coverage { params, slot, .. } => { - *slot.lock().unwrap() = Some(Ok(describe.to_vec())); + *slot.lock().unwrap() = Some(Ok((describe.to_vec(), Reach::Local))); params } crate::ServiceStep::Tiles { resolve, .. } => { assert_eq!(resolve.crossed_origin, anonymous); - *resolve.slot.lock().unwrap() = Some(Ok(br#"{"links":[{"rel":"item","type":"image/png","href":"https://anonymous-offer.invalid/{tileMatrix}/{tileRow}/{tileCol}"}]}"#.to_vec())); + *resolve.slot.lock().unwrap() = Some(Ok((br#"{"links":[{"rel":"item","type":"image/png","href":"https://anonymous-offer.invalid/{tileMatrix}/{tileRow}/{tileCol}"}]}"#.to_vec(), Reach::Local))); &resolve.params } }; diff --git a/crates/ui-egui/src/zarrui.rs b/crates/ui-egui/src/zarrui.rs index 89a5a1d06d..44f33bf6fa 100644 --- a/crates/ui-egui/src/zarrui.rs +++ b/crates/ui-egui/src/zarrui.rs @@ -223,7 +223,6 @@ pub(crate) fn connect(app: &mut RustGisApp) { /// fetched only from there, however its name resolves. pub(crate) fn connect_within(app: &mut RustGisApp, public: bool) { let st = &mut app.ui.zarr; - st.public = public; let a = st.address.trim().trim_end_matches('/').to_string(); st.error = None; st.info = None; @@ -237,6 +236,9 @@ pub(crate) fn connect_within(app: &mut RustGisApp, public: bool) { st.web = lower.starts_with("http://") || lower.starts_with("https://"); if st.web { let keys = zarr::METADATA_KEYS.iter().map(|k| k.to_string()).collect(); + // Set with the batch it is for, so a connect that starts none leaves a batch under way as + // it was. + st.public = public; st.fetch(keys, Phase::Meta); return; } @@ -487,6 +489,33 @@ mod tests { } } + /// A connect that starts no batch (a blank address) leaves the reach of a batch under way as it + /// was: a store a document named stays read only from the internet. + #[test] + fn a_connect_that_starts_nothing_leaves_a_batch_under_way_as_it_was() { + use rustgis_engine::render::rustgis_tiles::{ + address::{Origin, Reach}, + cache, + }; + let _turn = crate::fetching::turn(); + let asked = std::sync::Arc::new(std::sync::Mutex::new(Vec::new())); + let log = asked.clone(); + cache::set_fetcher_with_origin(move |url, ceiling, done, _| { + log.lock().unwrap().push(ceiling); + let origin = Origin::with_observed_reach(cache::split_download_limit(&url).0, ceiling).unwrap(); + done(Ok(cache::Fetched { bytes: b"{}".to_vec(), origin })); + }); + let mut app = RustGisApp::new(Session::new(Project::default())); + app.ui.zarr.address = "https://store-batch.example/data.zarr".into(); + connect_within(&mut app, true); + // Another connect, with nothing to connect to, before the batch is fetched. + app.ui.zarr.address = String::new(); + connect(&mut app); + poll(&mut app, &egui::Context::default()); + let asked = asked.lock().unwrap().clone(); + assert!(!asked.is_empty() && asked.iter().all(|c| *c == Reach::Public), "{asked:?}"); + } + /// A slice keeps its geographic system through its GeoTIFF handoff: another body's (an ESRI PE /// citation in the keys), and the Earth's other datums, retain their datum through `ran`. #[test] From 987b24e9ce690ef1b0c4f4d6300522e9e36130c8 Mon Sep 17 00:00:00 2001 From: mavrick Date: Mon, 23 Nov 2026 07:19:14 -0600 Subject: [PATCH 04/10] fix(services): review round 2: learned identify requests and supplied listings keep their reach A GetFeatureInfo request learned from a document read from the internet keeps that reach for the session, however the addresses' records change later. A service listing the browse didn't read itself is recorded with where the app's fetch connected, or as read from the internet when another caller supplied it. With the record of browsed nodes full, the services a listing read from the internet names are left out instead of losing their hold. The portal notice no longer says why for the forbidden addresses it also counts. --- crates/engine/src/cmd/connection_browse.rs | 78 ++++++++++++++++++++-- crates/engine/src/cmd/portals.rs | 11 ++- crates/engine/src/cmd/select_info.rs | 21 +++++- crates/engine/src/cmd/service.rs | 2 + crates/map/src/tiles.rs | 6 ++ 5 files changed, 102 insertions(+), 16 deletions(-) diff --git a/crates/engine/src/cmd/connection_browse.rs b/crates/engine/src/cmd/connection_browse.rs index 82d2367bb4..8e6c09b77b 100644 --- a/crates/engine/src/cmd/connection_browse.rs +++ b/crates/engine/src/cmd/connection_browse.rs @@ -277,7 +277,17 @@ pub(super) fn browse(s: &mut Session, p: &Value) -> CmdResult { Level::Database => database_schemas(s, &c, &mut out)?, Level::DatabaseSchema { schema } => database_schema(s, &c, schema, &mut out)?, Level::DatabaseDataset { dataset } => database_dataset(s, &c, dataset, &mut out)?, - Level::Service { url, kind, reach } => service(s, p, &mut out, &c, url, kind.as_deref(), *reach)?, + Level::Service { url, kind, reach } => { + // A listing the app read is judged by where its fetch connected; one a caller supplies + // says nothing trustworthy about where it was read, so it is taken as read from the + // internet. One read here: its documents' records say. + let read = match (ps(p, "answer"), &s.browse_response) { + (None, _) => *reach, + (Some(_), Some((id, supplied, origin))) if *id == c.id && supplied == node => (*reach).min(origin.reach()), + (Some(_), _) => address::Reach::Public, + }; + service(s, p, &mut out, &c, url, kind.as_deref(), read)? + } Level::S3Root if url.is_none() => { buckets(c.options.get("buckets").map(String::as_str).unwrap_or("").split(',').map(str::to_string)) } @@ -703,11 +713,14 @@ fn service( .filter(|l| l.get("offer").and_then(|o| o.get("type")).and_then(Value::as_str) == Some("service")) .map(|l| (format!("service:arcgis:{}", text(&l["offer"], "url")), read_at(l))) .collect(); + let mut children = children; for at in [address::Reach::Public, address::Reach::Local] { let nodes: Vec = services.iter().filter(|(_, r)| *r == at).map(|(node, _)| json!({"node": node})).collect(); if !nodes.is_empty() { let origin = address::Origin::with_observed_reach(url, at)?; - remember_or_say(s, c, &nodes, &origin, false); + if !remember_or_say(s, c, &nodes, &origin, false) { + children.retain(|child| !nodes.iter().any(|n| n["node"] == child["node"])); + } } } let mut found = Found::new(children); @@ -716,10 +729,17 @@ fn service( } /// [`remember_node_origins`], saying when the session's record is full instead of failing the -/// listing: the nodes not recorded are then judged by their connection's address, as before. -fn remember_or_say(s: &mut Session, c: &Connection, children: &[Value], origin: &address::Origin, root: bool) { - if let Err(e) = remember_node_origins(s, c, children, origin, root) { +/// listing. Nodes a listing read on the local network names are then judged by their connection's +/// address, as before; those a listing read from the internet names can't be held there without +/// the record, so the caller leaves them out (`false`). +fn remember_or_say(s: &mut Session, c: &Connection, children: &[Value], origin: &address::Origin, root: bool) -> bool { + let Err(e) = remember_node_origins(s, c, children, origin, root) else { return true }; + if origin.reach() == address::Reach::Public { + s.notify(format!("{e}: {} services this listing names are left out", children.len()), false); + false + } else { s.notify(format!("{e}; what this listing names is judged by its connection's address"), false); + true } } @@ -790,7 +810,13 @@ fn catalogue(s: &mut Session, c: &Connection, text: &str, origin: &address::Orig // The services the records link to, opened later, keep where the records were read. let services: Vec = found.children.iter().filter_map(|r| r.get("children")).filter_map(Value::as_array).flatten().cloned().collect(); - remember_or_say(s, c, &services, origin, root); + if !remember_or_say(s, c, &services, origin, root) { + for record in &mut found.children { + if let Some(links) = record.get_mut("children").and_then(Value::as_array_mut) { + links.retain(|link| link.get("node").is_none()); + } + } + } Ok(found) } @@ -1201,8 +1227,20 @@ mod tests { let mark = session.notice_mark(); let found = super::catalogue(&mut session, &connection, text, &origin, false, &mut json!({})).unwrap(); assert_eq!(found.children.len(), 1); + // Read on the local network, its services are judged by the connection's address, as + // before; read from the internet, they can't be held there without the record, so they + // are left out. + assert_eq!(found.children[0]["children"].as_array().map(Vec::len), Some(1)); let told: Vec<_> = session.notices_since(mark).iter().map(|n| n.text.clone()).collect(); assert!(told.iter().any(|t| t.contains("judged by its connection's address")), "{told:?}"); + let public = Origin::connected(&connection.address, "93.184.216.34".parse().unwrap()).unwrap(); + let web = text.replace("http://10.0.19.4/wms", "https://csw-19-wms.example/wms"); + let mark = session.notice_mark(); + let found = super::catalogue(&mut session, &connection, &web, &public, false, &mut json!({})).unwrap(); + assert_eq!(found.children.len(), 1, "the record is still listed"); + assert_eq!(found.children[0]["children"].as_array().map(Vec::len), Some(0), "its service is left out"); + let told: Vec<_> = session.notices_since(mark).iter().map(|n| n.text.clone()).collect(); + assert!(told.iter().any(|t| t.contains("1 services this listing names are left out")), "{told:?}"); } /// The folders a service lists keep where its listing was read: a directory a catalogue read @@ -1220,11 +1258,37 @@ mod tests { let local = Origin::connected(&connection.address, "10.0.0.5".parse().unwrap()).unwrap(); super::remember_node_origins(&mut session, &connection, &[json!({"node": node})], &local, false).unwrap(); let listing = json!({"currentVersion": 11.1, "folders": ["Hydro"], "services": []}).to_string(); - let out = super::browse(&mut session, &json!({"id": connection.id, "node": node, "answer": listing})).unwrap(); + // As the app hands it over: read by its fetch, which connected on the local network. + let requested = super::browse(&mut session, &json!({"id": connection.id, "node": node, "probe": true})).unwrap()["fetch"] + .as_str() + .unwrap() + .to_string(); + let read = Origin::connected(&requested, "10.0.20.5".parse().unwrap()).unwrap(); + let opened = session.opened; + let out = + session.browse_from_origin(&json!({"id": connection.id, "node": node, "answer": listing}), &requested, opened, read).unwrap(); let folder = out["children"].as_array().unwrap().iter().find_map(|c| c["node"].as_str().map(str::to_string)).unwrap(); assert!(folder.starts_with("service:arcgis:http://10.0.20.5/"), "{folder}"); let probe = super::browse(&mut session, &json!({"id": connection.id, "node": folder, "probe": true})); assert!(probe.is_ok(), "{probe:?}"); + // A listing supplied by the Assistant says nothing trustworthy about where it was read: it + // is taken as read from the internet, so the folder it lists, at a public-looking name, is + // held to the internet when it is opened. + struct Live; + impl crate::policy::Revocation for Live { + fn allows(&self, _: crate::policy::Effects) -> bool { + true + } + } + let directory = "https://dir-20.corp-looks-public.example/arcgis/rest/services"; + let node = format!("service:arcgis:{directory}"); + super::remember_node_origins(&mut session, &connection, &[json!({"node": node})], &local, false).unwrap(); + let scope = crate::policy::Scope::assistant(4_201_306, std::sync::Arc::new(Live)); + let params = json!({"id": connection.id, "node": node, "answer": listing}); + let out = session.with_scope(scope, |s| super::browse(s, ¶ms)).unwrap().unwrap(); + let folder = out["children"].as_array().unwrap().iter().find_map(|c| c["node"].as_str().map(str::to_string)).unwrap(); + let probe = super::browse(&mut session, &json!({"id": connection.id, "node": folder, "probe": true})).unwrap(); + assert_eq!(probe["fromDocument"], true, "{probe}"); } #[test] diff --git a/crates/engine/src/cmd/portals.rs b/crates/engine/src/cmd/portals.rs index c6ebfb41e2..8740f7ab55 100644 --- a/crates/engine/src/cmd/portals.rs +++ b/crates/engine/src/cmd/portals.rs @@ -258,14 +258,11 @@ fn first_layer(s: &mut Session, url: &str, kind: &str) -> Result .ok_or_else(|| crate::sources::message_with_address(url, "the service lists no layer RustGIS can add")) } -/// Says how many addresses a portal's answer gave that were left out for pointing where a -/// document read from the internet may not send RustGIS (into the local network). +/// Says how many addresses a portal's answer gave that were left out for pointing where RustGIS +/// won't fetch for it (into the local network from an answer read from the internet, or a +/// forbidden address from any answer). pub fn refused_notice(refused: usize) -> Option { - (refused > 0).then(|| { - format!( - "{refused} addresses the portal listed point where RustGIS won't fetch for an answer read from the internet and are left out" - ) - }) + (refused > 0).then(|| format!("{refused} addresses the portal listed point where RustGIS won't fetch and are left out")) } fn say_refused(s: &mut Session, refused: usize) { diff --git a/crates/engine/src/cmd/select_info.rs b/crates/engine/src/cmd/select_info.rs index fa30029335..4c33ba1d75 100644 --- a/crates/engine/src/cmd/select_info.rs +++ b/crates/engine/src/cmd/select_info.rs @@ -69,9 +69,13 @@ fn askable(t: &rustgis_map::tiles::TileLayer, picked: bool) -> bool { /// How far a WMS tile layer's identify requests may reach: only the internet when its template is /// held there (a document read from the internet listed the layer) or its capabilities were read /// from there ([`cache::ceiling_for`] records both), else as far as the user's own address. +/// +/// A request learned from a document read from the internet keeps that reach (`feature_info_public`), +/// whatever the records say by the time it is asked. fn reach_of(t: &rustgis_map::tiles::TileLayer) -> Reach { let caps = ogc::wms_layer_of(&t.url).map_or(Reach::Local, |(caps, _)| cache::ceiling_for(&caps)); - cache::ceiling_for(&t.url).min(caps) + let learned = if t.feature_info.is_some() && t.feature_info_public { Reach::Public } else { Reach::Local }; + cache::ceiling_for(&t.url).min(caps).min(learned) } /// What to fetch to ask a WMS tile layer about a point: the GetFeatureInfo request, or the @@ -189,9 +193,13 @@ fn wms_layer(s: &Session, name: &str) -> Result { /// Reads the layer's request from its service's capabilities; a layer the service doesn't list, /// or doesn't offer for identify, isn't asked again. The map's other layers from the same service /// that don't know theirs learn it too, so the capabilities are read once. +/// +/// Capabilities read from the internet (as their record says now) leave each layer's request held +/// there for good (`feature_info_public`). fn learn(s: &mut Session, index: usize, capabilities: &[u8]) -> Result<(), String> { let Some(t) = s.map().tiles.get(index) else { return Ok(()) }; let Some((caps_url, _)) = ogc::wms_layer_of(&t.url) else { return Ok(()) }; + let public = cache::ceiling_for(&caps_url) == Reach::Public; // Read as an answer is (Latin-1 from older servers), in the app and natively alike. let service = ogc::parse(&caps_url, ogc::answer_text(capabilities)?.as_bytes())?; let info_of = |layer: String| { @@ -210,6 +218,7 @@ fn learn(s: &mut Session, index: usize, capabilities: &[u8]) -> Result<(), Strin && caps == caps_url { t.feature_info = Some(info_of(layer)); + t.feature_info_public = public || cache::ceiling_for(&t.url) == Reach::Public; } } Ok(()) @@ -224,7 +233,6 @@ fn feature_info(s: &mut Session, p: &Value) -> CmdResult { if caps.len() > MAX_TEXT { return Err(named(format!("the capabilities are larger than {} MB", MAX_TEXT >> 20))); } - learn(s, index, caps.as_bytes()).map_err(named)?; // Capabilities supplied by anything but the app say nothing trustworthy about where they // were read: the requests they name are asked only on the internet. if !s.policy_user() @@ -232,6 +240,7 @@ fn feature_info(s: &mut Session, p: &Value) -> CmdResult { { cache::restrict_to_public(&caps_url); } + learn(s, index, caps.as_bytes()).map_err(named)?; } if let Some(text) = ps(p, "text") { if text.len() > MAX_TEXT { @@ -387,6 +396,14 @@ mod tests { } else { let e = r.unwrap_err(); assert!(e.contains(&format!("http://192.168.{n}.5/info")) && e.contains("local network"), "{e}"); + // The request keeps the reach it was learned at, though the user names the service + // directly afterwards (which clears the addresses' records). + let caps_url = ogc::wms_layer_of(&template).unwrap().0; + cache::allow_named(&caps_url); + cache::allow_named(&template); + let p = json!({"layer": "Roads", "lon": 8.5, "lat": 47.4, "request": true}); + let e = feature_info(&mut s, &p).unwrap_err(); + assert!(e.contains(&format!("http://192.168.{n}.5/info")) && e.contains("local network"), "{e}"); } } } diff --git a/crates/engine/src/cmd/service.rs b/crates/engine/src/cmd/service.rs index 2822ad846e..8080973c8b 100644 --- a/crates/engine/src/cmd/service.rs +++ b/crates/engine/src/cmd/service.rs @@ -1463,6 +1463,8 @@ fn add_discovered(s: &mut Session, p: &Value, url: &str, want: &str, found: &Dis let added = r["index"].as_u64().and_then(|i| usize::try_from(i).ok()); if let Some(t) = added.and_then(|i| s.map_mut().tiles.get_mut(i)) { t.feature_info = layer.feature_info.clone(); + // Learned from a document read from the internet: asked only there. + t.feature_info_public = public; if t.anonymous && let Some(info) = &mut t.feature_info { diff --git a/crates/map/src/tiles.rs b/crates/map/src/tiles.rs index 914d9f196a..47f26e899e 100644 --- a/crates/map/src/tiles.rs +++ b/crates/map/src/tiles.rs @@ -171,6 +171,10 @@ pub struct TileLayer { /// can be saved, should projects keep it. #[serde(skip)] pub feature_info: Option, + /// `feature_info` was learned from a document read from the internet: the request it makes is + /// asked only there, whatever the addresses' records say later. For the session only, as it is. + #[serde(skip)] + pub feature_info_public: bool, /// Its legend pictures (a WMS or WMTS layer's, from its service's default style, or given to /// `map.addTiles`): the Layers pane shows the one for the map's scale under it, as ArcGIS /// Pro's Contents pane does. Web addresses only, at most [`MAX_LEGENDS`](rustgis_data::ogc::MAX_LEGENDS). @@ -413,6 +417,7 @@ impl TileLayer { time_hidden: false, error: None, feature_info: None, + feature_info_public: false, legends: Vec::new(), connection: String::new(), anonymous: false, @@ -707,6 +712,7 @@ impl TileLayer { time_hidden: _, error: _, feature_info: _, + feature_info_public: _, legends, connection: _, anonymous: _, From bd2cd4468bd625cd8bb2635c7980090d5d00994a Mon Sep 17 00:00:00 2001 From: mavrick Date: Mon, 23 Nov 2026 08:15:09 -0600 Subject: [PATCH 05/10] fix(services): review round 3: supplied capabilities hold only their requests; nodes keep the narrower record Capabilities a caller supplies hold the requests learned from them to the internet without changing the record of the layer's own capabilities address. A browsed node recorded from a listing read from the internet keeps that record when a listing read locally names it again. A STAC listing with the node record full is shown and said, as catalogues and service listings are. --- crates/engine/src/cmd/connection_browse.rs | 41 ++++++++++++++++++---- crates/engine/src/cmd/select_info.rs | 24 ++++++------- 2 files changed, 47 insertions(+), 18 deletions(-) diff --git a/crates/engine/src/cmd/connection_browse.rs b/crates/engine/src/cmd/connection_browse.rs index 8e6c09b77b..16d1f1105d 100644 --- a/crates/engine/src/cmd/connection_browse.rs +++ b/crates/engine/src/cmd/connection_browse.rs @@ -307,7 +307,7 @@ pub(super) fn browse(s: &mut Session, p: &Value) -> CmdResult { } }; let bytes = text.as_bytes(); - let found = match &level { + let mut found = match &level { Level::Catalogue => catalogue(s, &c, &text, &origin, node.is_empty(), &mut out)?, Level::StacRoot { api } if stac::catalog::is_static(api) => catalogs(s, bytes, &origin)?, Level::StacRoot { .. } => collections(bytes)?, @@ -321,8 +321,10 @@ pub(super) fn browse(s: &mut Session, p: &Value) -> CmdResult { } Level::Database | Level::DatabaseSchema { .. } | Level::DatabaseDataset { .. } | Level::Service { .. } => Found::default(), }; - if matches!(&level, Level::StacCatalog { .. }) || matches!(&level, Level::StacRoot { api } if stac::catalog::is_static(api)) { - remember_node_origins(s, &c, &found.children, &origin, node.is_empty())?; + let catalog = + matches!(&level, Level::StacCatalog { .. }) || matches!(&level, Level::StacRoot { api } if stac::catalog::is_static(api)); + if catalog && !remember_or_say(s, &c, &found.children, &origin, node.is_empty()) { + found.children.clear(); } found } @@ -416,8 +418,12 @@ fn remember_node_origins(s: &mut Session, c: &Connection, children: &[Value], or if s.browse_origins.1.len().saturating_add(added) > 16_384 { return Err("too many catalog nodes are open in this session; reopen the project to browse more".into()); } + // A node a listing read from the internet named stays held there, though a listing read + // locally names it again: the narrower record is kept. for key in keys { - s.browse_origins.1.insert(key, origin.clone()); + if !s.browse_origins.1.get(&key).is_some_and(|recorded| recorded.reach() < origin.reach()) { + s.browse_origins.1.insert(key, origin.clone()); + } } Ok(()) } @@ -735,7 +741,7 @@ fn service( fn remember_or_say(s: &mut Session, c: &Connection, children: &[Value], origin: &address::Origin, root: bool) -> bool { let Err(e) = remember_node_origins(s, c, children, origin, root) else { return true }; if origin.reach() == address::Reach::Public { - s.notify(format!("{e}: {} services this listing names are left out", children.len()), false); + s.notify(format!("{e}: {} entries this listing names are left out", children.len()), false); false } else { s.notify(format!("{e}; what this listing names is judged by its connection's address"), false); @@ -1240,7 +1246,7 @@ mod tests { assert_eq!(found.children.len(), 1, "the record is still listed"); assert_eq!(found.children[0]["children"].as_array().map(Vec::len), Some(0), "its service is left out"); let told: Vec<_> = session.notices_since(mark).iter().map(|n| n.text.clone()).collect(); - assert!(told.iter().any(|t| t.contains("1 services this listing names are left out")), "{told:?}"); + assert!(told.iter().any(|t| t.contains("1 entries this listing names are left out")), "{told:?}"); } /// The folders a service lists keep where its listing was read: a directory a catalogue read @@ -1289,6 +1295,29 @@ mod tests { let folder = out["children"].as_array().unwrap().iter().find_map(|c| c["node"].as_str().map(str::to_string)).unwrap(); let probe = super::browse(&mut session, &json!({"id": connection.id, "node": folder, "probe": true})).unwrap(); assert_eq!(probe["fromDocument"], true, "{probe}"); + // And a private folder it lists is left out. + let private = "service:arcgis:http://10.0.20.5/arcgis/rest/services"; + let params = json!({"id": connection.id, "node": private, "answer": listing}); + let scope = crate::policy::Scope::assistant(4_201_307, std::sync::Arc::new(Live)); + let out = session.with_scope(scope, |s| super::browse(s, ¶ms)).unwrap().unwrap(); + assert!(out["children"].as_array().unwrap().iter().all(|c| c.get("node").is_none()), "{out}"); + } + + /// A node a listing read from the internet recorded stays held there when a listing read on + /// the local network names it again: the narrower record is kept. + #[test] + fn a_node_keeps_its_narrower_record() { + use crate::render::rustgis_tiles::address::{Origin, Reach}; + let mut session = crate::Session::new(crate::Project::default()); + let saved = session.run("connection.new", &json!({"kind":"csw","address":"https://csw-21.corp-looks-public.example/csw"})).unwrap(); + let connection = session.connections.connections.iter().find(|c| c.id == saved["id"].as_str().unwrap()).unwrap().clone(); + let node = json!({"node": "service:wms:https://csw-21-wms.example/wms"}); + let public = Origin::connected(&connection.address, "93.184.216.34".parse().unwrap()).unwrap(); + let local = Origin::connected(&connection.address, "10.0.0.5".parse().unwrap()).unwrap(); + super::remember_node_origins(&mut session, &connection, std::slice::from_ref(&node), &public, false).unwrap(); + super::remember_node_origins(&mut session, &connection, std::slice::from_ref(&node), &local, false).unwrap(); + let held = super::node_origin(&session, &connection, node["node"].as_str().unwrap()).map(|o| o.reach()); + assert_eq!(held, Some(Reach::Public)); } #[test] diff --git a/crates/engine/src/cmd/select_info.rs b/crates/engine/src/cmd/select_info.rs index 4c33ba1d75..4e00f84264 100644 --- a/crates/engine/src/cmd/select_info.rs +++ b/crates/engine/src/cmd/select_info.rs @@ -194,12 +194,13 @@ fn wms_layer(s: &Session, name: &str) -> Result { /// or doesn't offer for identify, isn't asked again. The map's other layers from the same service /// that don't know theirs learn it too, so the capabilities are read once. /// -/// Capabilities read from the internet (as their record says now) leave each layer's request held -/// there for good (`feature_info_public`). -fn learn(s: &mut Session, index: usize, capabilities: &[u8]) -> Result<(), String> { +/// Capabilities read from the internet (as their record says now), or supplied by a caller that +/// can't say where they were read (`untrusted`), leave each layer's request held there for good +/// (`feature_info_public`). The capabilities' own address keeps its record: it is the layer's. +fn learn(s: &mut Session, index: usize, capabilities: &[u8], untrusted: bool) -> Result<(), String> { let Some(t) = s.map().tiles.get(index) else { return Ok(()) }; let Some((caps_url, _)) = ogc::wms_layer_of(&t.url) else { return Ok(()) }; - let public = cache::ceiling_for(&caps_url) == Reach::Public; + let public = untrusted || cache::ceiling_for(&caps_url) == Reach::Public; // Read as an answer is (Latin-1 from older servers), in the app and natively alike. let service = ogc::parse(&caps_url, ogc::answer_text(capabilities)?.as_bytes())?; let info_of = |layer: String| { @@ -235,12 +236,8 @@ fn feature_info(s: &mut Session, p: &Value) -> CmdResult { } // Capabilities supplied by anything but the app say nothing trustworthy about where they // were read: the requests they name are asked only on the internet. - if !s.policy_user() - && let Some((caps_url, _)) = s.map().tiles.get(index).and_then(|t| ogc::wms_layer_of(&t.url)) - { - cache::restrict_to_public(&caps_url); - } - learn(s, index, caps.as_bytes()).map_err(named)?; + let untrusted = !s.policy_user(); + learn(s, index, caps.as_bytes(), untrusted).map_err(named)?; } if let Some(text) = ps(p, "text") { if text.len() > MAX_TEXT { @@ -310,7 +307,7 @@ fn feature_info(s: &mut Session, p: &Value) -> CmdResult { if fetched.origin.reach() == Reach::Public { cache::restrict_to_public(caps); } - learn(s, index, &fetched.bytes).map_err(named)?; + learn(s, index, &fetched.bytes, false).map_err(named)?; step = next(s).transpose().map_err(named)?; } // Each of the service's errors asks in a format read after the last, so this ends. @@ -396,9 +393,12 @@ mod tests { } else { let e = r.unwrap_err(); assert!(e.contains(&format!("http://192.168.{n}.5/info")) && e.contains("local network"), "{e}"); + // The layer's own capabilities address keeps its record: only the requests the + // supplied document names are held. + let caps_url = ogc::wms_layer_of(&template).unwrap().0; + assert_eq!(cache::ceiling_for(&caps_url), Reach::Local, "{caps_url}"); // The request keeps the reach it was learned at, though the user names the service // directly afterwards (which clears the addresses' records). - let caps_url = ogc::wms_layer_of(&template).unwrap().0; cache::allow_named(&caps_url); cache::allow_named(&template); let p = json!({"layer": "Roads", "lon": 8.5, "lat": 47.4, "request": true}); From b57360546c5960e43908ecc182460c11e522f21a Mon Sep 17 00:00:00 2001 From: mavrick Date: Mon, 23 Nov 2026 10:24:23 -0600 Subject: [PATCH 06/10] fix(services): review round 4: shared capabilities take the narrowest reach; full records still narrow Capabilities several WMS layers share are asked within the narrowest reach of those layers. With the record of browsed nodes full, a listing read from the internet still narrows the records it names that are already there. --- crates/engine/src/cmd/connection_browse.rs | 34 +++++++++++++++----- crates/ui-egui/src/mapview.rs | 37 ++++++++++++++++++++-- 2 files changed, 61 insertions(+), 10 deletions(-) diff --git a/crates/engine/src/cmd/connection_browse.rs b/crates/engine/src/cmd/connection_browse.rs index 16d1f1105d..943d4b4ff6 100644 --- a/crates/engine/src/cmd/connection_browse.rs +++ b/crates/engine/src/cmd/connection_browse.rs @@ -414,17 +414,21 @@ fn remember_node_origins(s: &mut Session, c: &Connection, children: &[Value], or } } } - let added = keys.iter().filter(|key| !s.browse_origins.1.contains_key(*key)).count(); - if s.browse_origins.1.len().saturating_add(added) > 16_384 { - return Err("too many catalog nodes are open in this session; reopen the project to browse more".into()); - } // A node a listing read from the internet named stays held there, though a listing read - // locally names it again: the narrower record is kept. - for key in keys { + // locally names it again: the narrower record is kept. Records already there are narrowed + // first, whatever room is left, as narrowing adds none. + let (known, new): (Vec<_>, Vec<_>) = keys.into_iter().partition(|key| s.browse_origins.1.contains_key(key)); + for key in known { if !s.browse_origins.1.get(&key).is_some_and(|recorded| recorded.reach() < origin.reach()) { s.browse_origins.1.insert(key, origin.clone()); } } + if s.browse_origins.1.len().saturating_add(new.len()) > 16_384 { + return Err("too many catalog nodes are open in this session; reopen the project to browse more".into()); + } + for key in new { + s.browse_origins.1.insert(key, origin.clone()); + } Ok(()) } @@ -741,7 +745,11 @@ fn service( fn remember_or_say(s: &mut Session, c: &Connection, children: &[Value], origin: &address::Origin, root: bool) -> bool { let Err(e) = remember_node_origins(s, c, children, origin, root) else { return true }; if origin.reach() == address::Reach::Public { - s.notify(format!("{e}: {} entries this listing names are left out", children.len()), false); + let left = match children.len() { + 1 => "1 entry".to_string(), + n => format!("{n} entries"), + }; + s.notify(format!("{e}: {left} this listing names are left out"), false); false } else { s.notify(format!("{e}; what this listing names is judged by its connection's address"), false); @@ -1246,7 +1254,7 @@ mod tests { assert_eq!(found.children.len(), 1, "the record is still listed"); assert_eq!(found.children[0]["children"].as_array().map(Vec::len), Some(0), "its service is left out"); let told: Vec<_> = session.notices_since(mark).iter().map(|n| n.text.clone()).collect(); - assert!(told.iter().any(|t| t.contains("1 entries this listing names are left out")), "{told:?}"); + assert!(told.iter().any(|t| t.contains("1 entry this listing names are left out")), "{told:?}"); } /// The folders a service lists keep where its listing was read: a directory a catalogue read @@ -1318,6 +1326,16 @@ mod tests { super::remember_node_origins(&mut session, &connection, std::slice::from_ref(&node), &local, false).unwrap(); let held = super::node_origin(&session, &connection, node["node"].as_str().unwrap()).map(|o| o.reach()); assert_eq!(held, Some(Reach::Public)); + // With the record full, a listing read from the internet still narrows the node records it + // names that are already there (it adds no entries); only its new ones can't be recorded. + let other = json!({"node": "service:wms:https://csw-21-other.example/wms"}); + super::remember_node_origins(&mut session, &connection, std::slice::from_ref(&other), &local, false).unwrap(); + let filler = (0..16_384).map(|i| ((format!("full-{i}"), String::new(), String::new()), local.clone())); + session.browse_origins.1.extend(filler); + let new = json!({"node": "service:wms:https://csw-21-new.example/wms"}); + assert!(super::remember_node_origins(&mut session, &connection, &[other.clone(), new], &public, false).is_err()); + let narrowed = super::node_origin(&session, &connection, other["node"].as_str().unwrap()).map(|o| o.reach()); + assert_eq!(narrowed, Some(Reach::Public)); } #[test] diff --git a/crates/ui-egui/src/mapview.rs b/crates/ui-egui/src/mapview.rs index 87609f80ff..d049c78f04 100644 --- a/crates/ui-egui/src/mapview.rs +++ b/crates/ui-egui/src/mapview.rs @@ -125,8 +125,17 @@ impl Popup { /// A popup for what identify found at `at`, asking the WMS layers it lists. pub fn new(info: Value, at: Coord, map: usize, opened: u64) -> Popup { let mut asks: Vec = Vec::new(); - // The capabilities each fetch is for: layers of one service share it. + // The capabilities each fetch is for: layers of one service share it, asked within the + // narrowest reach of those layers (any listed by a document read from the internet holds + // the fetch there). let mut fetched: Vec<(String, usize)> = Vec::new(); + let held: std::collections::HashSet<&str> = info["featureInfo"] + .as_array() + .into_iter() + .flatten() + .filter(|a| a["public"] == true) + .filter_map(|a| a["capabilities"].as_str()) + .collect(); for a in info["featureInfo"].as_array().into_iter().flatten() { let Some(layer) = a["tileLayer"].as_str().map(str::to_string) else { continue }; let (url, capabilities) = match (a["url"].as_str(), a["capabilities"].as_str()) { @@ -143,7 +152,7 @@ impl Popup { if capabilities { fetched.push((url.to_string(), asks.len())); } - let slot = ask_within(a, url); + let slot = if capabilities && held.contains(url) { ask_within(&json!({"public": true}), url) } else { ask_within(a, url) }; let request = Some(url.to_string()); asks.push(Ask { layer, also: Vec::new(), capabilities, request, slot }); } @@ -5654,6 +5663,30 @@ mod tests { assert!(told.iter().any(|t| t.contains("http://192.168.7.5/info") && t.contains("local network")), "{told:?}"); } + /// Layers sharing capabilities have them asked once, within the narrowest of their reaches: one + /// listed by a document read from the internet holds the fetch there, though the first layer + /// asking is the user's own. + #[test] + fn shared_capabilities_are_asked_within_the_narrowest_reach() { + use rustgis_engine::render::rustgis_tiles::address::Origin; + let _turn = crate::fetching::turn(); + let asked = std::sync::Arc::new(std::sync::Mutex::new(Vec::new())); + let log = asked.clone(); + cache::set_fetcher_with_origin(move |url, ceiling, done, _| { + log.lock().unwrap().push(ceiling); + let origin = Origin::with_observed_reach(cache::split_download_limit(&url).0, ceiling).unwrap(); + done(Ok(cache::Fetched { bytes: b"".to_vec(), origin })); + }); + let caps = "https://shared-caps.example/wms?SERVICE=WMS&REQUEST=GetCapabilities&VERSION=1.3.0"; + let info = json!({"featureInfo": [ + {"tileLayer": "Mine", "capabilities": caps}, + {"tileLayer": "Listed", "capabilities": caps, "public": true}, + ]}); + let pp = Popup::new(info, Coord::new(8.6, 46.65), 0, 0); + assert_eq!(pp.asks.len(), 1, "asked once for both"); + assert_eq!(asked.lock().unwrap().clone(), [Reach::Public]); + } + /// Capabilities answer only the service they were asked of: a layer replaced meanwhile by /// another service's, under the same name, neither learns from them nor has its own /// capabilities held to the internet by them. From bb5daf67dabf2513b4e015f4562c2ef0f4f6ad53 Mon Sep 17 00:00:00 2001 From: mavrick Date: Mon, 23 Nov 2026 13:05:39 -0600 Subject: [PATCH 07/10] fix(services): review round 5: refusals named, every layer asked, learned reach from the fetch A portal answer's notice names the first address it left out and why. The record-full notice counts only the services left out. Each of a service's WMS layers is asked whatever became of the first's request. Identify learns a request's reach from the fetch that read the capabilities, not from a record that can change in between. --- crates/engine/src/cmd/connection_browse.rs | 20 +++- crates/engine/src/cmd/portals.rs | 20 ++-- crates/engine/src/cmd/select_info.rs | 19 ++- crates/tiles/src/portal.rs | 130 +++++++++++++-------- crates/ui-egui/src/mapview.rs | 61 ++++++++-- crates/ui-egui/src/opendataui.rs | 10 +- 6 files changed, 180 insertions(+), 80 deletions(-) diff --git a/crates/engine/src/cmd/connection_browse.rs b/crates/engine/src/cmd/connection_browse.rs index 943d4b4ff6..102677ab9a 100644 --- a/crates/engine/src/cmd/connection_browse.rs +++ b/crates/engine/src/cmd/connection_browse.rs @@ -822,8 +822,16 @@ fn catalogue(s: &mut Session, c: &Connection, text: &str, origin: &address::Orig found.matched = r.get("matched").and_then(Value::as_u64); found.truncated |= dropped || r.get("next").is_some_and(|n| !n.is_null()); // The services the records link to, opened later, keep where the records were read. - let services: Vec = - found.children.iter().filter_map(|r| r.get("children")).filter_map(Value::as_array).flatten().cloned().collect(); + // The services the records name (nodes): the downloads carry their reach in their parameters. + let services: Vec = found + .children + .iter() + .filter_map(|r| r.get("children")) + .filter_map(Value::as_array) + .flatten() + .filter(|link| link.get("node").is_some()) + .cloned() + .collect(); if !remember_or_say(s, c, &services, origin, root) { for record in &mut found.children { if let Some(links) = record.get_mut("children").and_then(Value::as_array_mut) { @@ -1248,11 +1256,15 @@ mod tests { let told: Vec<_> = session.notices_since(mark).iter().map(|n| n.text.clone()).collect(); assert!(told.iter().any(|t| t.contains("judged by its connection's address")), "{told:?}"); let public = Origin::connected(&connection.address, "93.184.216.34".parse().unwrap()).unwrap(); - let web = text.replace("http://10.0.19.4/wms", "https://csw-19-wms.example/wms"); + let web = text.replace( + r#"http://10.0.19.4/wms"#, + r#"https://csw-19-wms.example/wmshttps://csw-19-files.example/a.geojson"#, + ); let mark = session.notice_mark(); let found = super::catalogue(&mut session, &connection, &web, &public, false, &mut json!({})).unwrap(); assert_eq!(found.children.len(), 1, "the record is still listed"); - assert_eq!(found.children[0]["children"].as_array().map(Vec::len), Some(0), "its service is left out"); + let kept: Vec<_> = found.children[0]["children"].as_array().unwrap().iter().map(|l| l["what"].clone()).collect(); + assert_eq!(kept, [json!("download")], "its service is left out, its download kept"); let told: Vec<_> = session.notices_since(mark).iter().map(|n| n.text.clone()).collect(); assert!(told.iter().any(|t| t.contains("1 entry this listing names are left out")), "{told:?}"); } diff --git a/crates/engine/src/cmd/portals.rs b/crates/engine/src/cmd/portals.rs index 8740f7ab55..1fac380eb0 100644 --- a/crates/engine/src/cmd/portals.rs +++ b/crates/engine/src/cmd/portals.rs @@ -158,9 +158,9 @@ fn portal_search(s: &mut Session, p: &Value) -> CmdResult { let (portal, query, area, limit) = portal_query(s, p)?; let url = portal.search_url(&query, area, limit); let (bytes, reach) = fetch(&url)?; - let mut refused = 0; + let mut refused = portal::Refused::default(); let found = portal.parse(reach, &mut refused, &bytes, area, &query)?; - say_refused(s, refused); + say_refused(s, &refused); Ok(json!({"portal": portal.label(), "count": found.len(), "datasets": found.iter().map(dataset_json).collect::>()})) } @@ -176,9 +176,9 @@ pub fn files_query(p: &Value) -> Result<(Portal, String), String> { fn portal_files(s: &mut Session, p: &Value) -> CmdResult { let (portal, url) = files_query(p)?; let (bytes, reach) = fetch(&url)?; - let mut refused = 0; + let mut refused = portal::Refused::default(); let files = portal.parse_listing(&url, reach, &mut refused, &bytes)?; - say_refused(s, refused); + say_refused(s, &refused); let list: Vec = files .iter() .map(|r| match &r.using { @@ -260,12 +260,16 @@ fn first_layer(s: &mut Session, url: &str, kind: &str) -> Result /// Says how many addresses a portal's answer gave that were left out for pointing where RustGIS /// won't fetch for it (into the local network from an answer read from the internet, or a -/// forbidden address from any answer). -pub fn refused_notice(refused: usize) -> Option { - (refused > 0).then(|| format!("{refused} addresses the portal listed point where RustGIS won't fetch and are left out")) +/// forbidden address from any answer), with the first and why. +pub fn refused_notice(refused: &portal::Refused) -> Option { + let first = refused.first.as_deref()?; + Some(match refused.count { + 1 => format!("1 address the portal listed is left out: {first}"), + n => format!("{n} addresses the portal listed are left out, such as {first}"), + }) } -fn say_refused(s: &mut Session, refused: usize) { +fn say_refused(s: &mut Session, refused: &portal::Refused) { if let Some(notice) = refused_notice(refused) { s.notify(notice, false); } diff --git a/crates/engine/src/cmd/select_info.rs b/crates/engine/src/cmd/select_info.rs index 4e00f84264..8ab3169a21 100644 --- a/crates/engine/src/cmd/select_info.rs +++ b/crates/engine/src/cmd/select_info.rs @@ -194,13 +194,14 @@ fn wms_layer(s: &Session, name: &str) -> Result { /// or doesn't offer for identify, isn't asked again. The map's other layers from the same service /// that don't know theirs learn it too, so the capabilities are read once. /// -/// Capabilities read from the internet (as their record says now), or supplied by a caller that -/// can't say where they were read (`untrusted`), leave each layer's request held there for good -/// (`feature_info_public`). The capabilities' own address keeps its record: it is the layer's. -fn learn(s: &mut Session, index: usize, capabilities: &[u8], untrusted: bool) -> Result<(), String> { +/// Capabilities read from the internet (`public`: as the fetch reading them observed it, or a +/// caller that can't say where they were read; or as their record says now) leave each layer's +/// request held there for good (`feature_info_public`). The capabilities' own address keeps its +/// record: it is the layer's. +fn learn(s: &mut Session, index: usize, capabilities: &[u8], public: bool) -> Result<(), String> { let Some(t) = s.map().tiles.get(index) else { return Ok(()) }; let Some((caps_url, _)) = ogc::wms_layer_of(&t.url) else { return Ok(()) }; - let public = untrusted || cache::ceiling_for(&caps_url) == Reach::Public; + let public = public || cache::ceiling_for(&caps_url) == Reach::Public; // Read as an answer is (Latin-1 from older servers), in the app and natively alike. let service = ogc::parse(&caps_url, ogc::answer_text(capabilities)?.as_bytes())?; let info_of = |layer: String| { @@ -307,7 +308,7 @@ fn feature_info(s: &mut Session, p: &Value) -> CmdResult { if fetched.origin.reach() == Reach::Public { cache::restrict_to_public(caps); } - learn(s, index, &fetched.bytes, false).map_err(named)?; + learn(s, index, &fetched.bytes, fetched.origin.reach() == Reach::Public).map_err(named)?; step = next(s).transpose().map_err(named)?; } // Each of the service's errors asks in a format read after the last, so this ends. @@ -390,6 +391,12 @@ mod tests { }; if app { assert!(r.unwrap()["url"].as_str().is_some_and(|u| u.starts_with(&format!("http://192.168.{n}.5/info?")))); + // Capabilities the fetch observed on the internet hold what they name there, whatever + // the capabilities address's record says by then. + learn(&mut s, 0, caps.as_bytes(), true).unwrap(); + assert!(s.map().tiles[0].feature_info_public); + let e = feature_info(&mut s, &json!({"layer": "Roads", "lon": 8.5, "lat": 47.4, "request": true})).unwrap_err(); + assert!(e.contains("local network"), "{e}"); } else { let e = r.unwrap_err(); assert!(e.contains(&format!("http://192.168.{n}.5/info")) && e.contains("local network"), "{e}"); diff --git a/crates/tiles/src/portal.rs b/crates/tiles/src/portal.rs index c2d5e8e35d..ffc056eacc 100644 --- a/crates/tiles/src/portal.rs +++ b/crates/tiles/src/portal.rs @@ -116,6 +116,29 @@ pub struct Resource { pub using: Use, } +/// The addresses a portal's answer gave that were left out (they reach past where the answer was +/// read, or are never fetched), for the caller to say: how many, and the first with why. +#[derive(Clone, Debug, Default, PartialEq)] +pub struct Refused { + pub count: usize, + /// The first left out: its address and the reason, as [`crate::address::check_reach`] says it. + pub first: Option, +} + +impl Refused { + /// Whether an address passed its check (`checked`); one that didn't is noted. + fn keep(&mut self, checked: Result<(), String>) -> bool { + match checked { + Ok(()) => true, + Err(why) => { + self.count = self.count.saturating_add(1); + self.first.get_or_insert(why); + false + } + } + } +} + /// A dataset found. #[derive(Clone, Debug, Default, PartialEq)] pub struct Dataset { @@ -458,12 +481,12 @@ impl Portal { /// The datasets in a search's answer (read within `reach`, as its fetch observed it, which the /// resources' own addresses are judged by), with the resources RustGIS can add; datasets /// without one are left out, as are those outside `bbox` when they say where they are. - /// `refused` counts the addresses (resources and pictures) left out for reaching past `reach`, + /// `refused` notes the addresses (resources and pictures) left out for reaching past `reach`, /// for the caller to say. pub fn parse( &self, reach: Reach, - refused: &mut usize, + refused: &mut Refused, bytes: &[u8], bbox: Option<[f64; 4]>, query: &str, @@ -548,13 +571,9 @@ impl Portal { // The portal's answer is hostile input: an address it gives may not reach past where // the answer was read (into the local network, unless the portal is there) or a // forbidden address, however the portal's own address is spelled. - let listed = d.resources.len(); - d.resources.retain(|r| crate::address::check_reach(&r.url, reach).is_ok()); - *refused = refused.saturating_add(listed - d.resources.len()); + d.resources.retain(|r| refused.keep(crate::address::check_reach(&r.url, reach))); // So may its pictures', fetched as results are shown. - let pictured = d.thumbnail.is_some(); - d.thumbnail = d.thumbnail.take().filter(|u| crate::address::check_reach(u, reach).is_ok()); - *refused = refused.saturating_add(usize::from(pictured && d.thumbnail.is_none())); + d.thumbnail = d.thumbnail.take().filter(|u| refused.keep(crate::address::check_reach(u, reach))); d.resources.sort_by_key(|r| rank(&r.format)); d.resources.truncate(MAX_RESOURCES); } @@ -853,9 +872,9 @@ fn arcgis_words(q: &str) -> String { /// A web map's layers (its operational layers, those in groups too) RustGIS adds: ArcGIS services, /// named by their titles. -fn web_map_layers(v: &Value, reach: Reach, refused: &mut usize) -> Result, String> { +fn web_map_layers(v: &Value, reach: Reach, refused: &mut Refused) -> Result, String> { // A layer in a group is named after the group too (groups often repeat their layers' titles). - fn walk(layers: &Value, depth: usize, group: &str, out: &mut Vec, reach: Reach, refused: &mut usize) { + fn walk(layers: &Value, depth: usize, group: &str, out: &mut Vec, reach: Reach, refused: &mut Refused) { for l in layers.as_array().into_iter().flatten().take(500) { if out.len() >= MAX_FILES { return; @@ -873,8 +892,7 @@ fn web_map_layers(v: &Value, reach: Reach, refused: &mut usize) -> Result Result, String> { + /// `refused` notes the files left out for reaching past `reach`, for the caller to say. + pub fn parse_listing(&self, from: &str, reach: Reach, refused: &mut Refused, bytes: &[u8]) -> Result, String> { let v: Value = serde_json::from_slice(bytes).map_err(|_| format!("{}: the listing isn't JSON", self.label()))?; if self.kind == Kind::ArcGis { return web_map_layers(&v, reach, refused); @@ -1301,11 +1319,7 @@ impl Portal { .any(|x| lower.ends_with(x)); addable.then_some(Resource { format: path, url, using: Use::File }) }) - .filter(|r| { - let ok = crate::address::check_reach(&r.url, reach).is_ok(); - *refused = refused.saturating_add(usize::from(!ok)); - ok - }) + .filter(|r| refused.keep(crate::address::check_reach(&r.url, reach))) .take(MAX_FILES) .collect(); out.sort_by(|a, b| a.format.cmp(&b.format)); @@ -1379,10 +1393,12 @@ mod tests { fn answers() { let dg = br#"{"results":[{"slug":"parks","title":"Parks","description":"Parks of a city","organization":{"name":"City"},"spatial_shape":{"type":"Polygon","coordinates":[[[-122.5,47.5],[-122.2,47.5],[-122.2,47.7],[-122.5,47.5]]]},"dcat":{"distribution":[{"downloadURL":"https://x.org/p.csv","mediaType":"text/csv"},{"downloadURL":"https://x.org/p.geojson","mediaType":"application/geo+json"},{"accessURL":"http://127.0.0.1/p.geojson","format":"GeoJSON"},{"downloadURL":"https://x.org/p.html","format":"HTML"}]}},{"slug":"report","title":"A report","dcat":{"distribution":[{"downloadURL":"https://x.org/r.pdf"}]}}],"sort":"relevance"}"#; let p = Portal::new(None, None).unwrap(); - let mut refused = 0; + let mut refused = Refused::default(); let ds = p.parse(Reach::Public, &mut refused, dg, None, "").unwrap(); assert_eq!(ds.len(), 1, "a dataset with nothing to add is left out"); - assert_eq!(refused, 1, "the local-network address is counted, for the caller to say"); + assert_eq!(refused.count, 1, "the local-network address is counted, for the caller to say"); + let why = refused.first.unwrap_or_default(); + assert!(why.starts_with("http://127.0.0.1/p.geojson") && why.contains("local network"), "{why}"); let d = &ds[0]; assert_eq!((d.title.as_str(), d.organization.as_str()), ("Parks", "City")); assert_eq!(d.page.as_deref(), Some("https://catalog.data.gov/dataset/parks")); @@ -1391,35 +1407,47 @@ mod tests { assert_eq!(d.resources.iter().map(|r| r.format.as_str()).collect::>(), vec!["GeoJSON", "CSV"]); // An answer read on the local network (a portal there, whatever its name) keeps it: the // addresses are judged by where the answer was read. - let mut refused = 0; + let mut refused = Refused::default(); let local = p.parse(Reach::Local, &mut refused, dg, None, "").unwrap(); - assert_eq!(refused, 0, "nothing left out of an answer read locally"); + assert_eq!(refused, Refused::default(), "nothing left out of an answer read locally"); + // A forbidden address is left out of an answer read locally too, and said why. + let metadata = std::str::from_utf8(dg).unwrap().replace("http://127.0.0.1/p.geojson", "http://169.254.169.254/p.geojson"); + let mut refused = Refused::default(); + p.parse(Reach::Local, &mut refused, metadata.as_bytes(), None, "").unwrap(); + assert_eq!(refused.count, 1); + assert!( + refused.first.as_deref().is_some_and(|why| why.contains("169.254.169.254") && why.contains("never fetched")), + "{refused:?}" + ); assert!(local[0].resources.iter().any(|r| r.url == "http://127.0.0.1/p.geojson"), "{:?}", local[0].resources); // Kept to a box: a dataset elsewhere goes. - assert!(p.parse(Reach::Public, &mut 0, dg, Some([0.0, 0.0, 1.0, 1.0]), "").unwrap().is_empty()); - assert_eq!(p.parse(Reach::Public, &mut 0, dg, Some([-123.0, 47.0, -122.0, 48.0]), "").unwrap().len(), 1); - assert!(p.parse(Reach::Public, &mut 0, b"", None, "").is_err() && p.parse(Reach::Public, &mut 0, b"{}", None, "").is_err()); + assert!(p.parse(Reach::Public, &mut Refused::default(), dg, Some([0.0, 0.0, 1.0, 1.0]), "").unwrap().is_empty()); + assert_eq!(p.parse(Reach::Public, &mut Refused::default(), dg, Some([-123.0, 47.0, -122.0, 48.0]), "").unwrap().len(), 1); + assert!( + p.parse(Reach::Public, &mut Refused::default(), b"", None, "").is_err() + && p.parse(Reach::Public, &mut Refused::default(), b"{}", None, "").is_err() + ); let soc = br#"{"results":[{"resource":{"id":"enfh-gkve","name":"Parks Properties","type":"dataset","columns_datatype":["Text","MultiPolygon"]},"metadata":{"domain":"data.cityofnewyork.us"},"permalink":"https://data.cityofnewyork.us/d/enfh-gkve"},{"resource":{"id":"nc67-uf89","name":"Violations","type":"dataset","columns_datatype":["Text"]},"metadata":{"domain":"data.cityofnewyork.us"}},{"resource":{"id":"bad","name":"x","type":"dataset","columns_datatype":["Point"]},"metadata":{"domain":"evil host"}}]}"#; let s = Portal::new(Some("socrata"), None).unwrap(); - let ds = s.parse(Reach::Public, &mut 0, soc, None, "").unwrap(); + let ds = s.parse(Reach::Public, &mut Refused::default(), soc, None, "").unwrap(); assert_eq!(ds.len(), 1); assert_eq!(ds[0].resources[0].url, "https://data.cityofnewyork.us/resource/enfh-gkve.geojson?%24limit=50000"); let hub = br#"{"type":"FeatureCollection","features":[{"id":"c5ef","properties":{"id":"c5ef","title":"parks","type":"Feature Service","owner":"nyc","url":"https://services1.arcgis.com/S/arcgis/rest/services/parks/FeatureServer","extent":{"type":"Polygon","coordinates":[[[-73.9,40.76],[-73.87,40.76],[-73.87,40.74],[-73.9,40.76]]]}}},{"properties":{"title":"no url"}}]}"#; let h = Portal::new(Some("arcgis-hub"), None).unwrap(); - let ds = h.parse(Reach::Public, &mut 0, hub, None, "").unwrap(); + let ds = h.parse(Reach::Public, &mut Refused::default(), hub, None, "").unwrap(); assert_eq!(ds.len(), 1); assert_eq!(ds[0].resources[0].using, Use::Service { kind: "arcgis", layer: None }); assert_eq!(ds[0].bbox, Some([-73.9, 40.74, -73.87, 40.76])); let ckan = br#"{"success":true,"result":{"count":1,"results":[{"name":"lakes","title":"Lakes","notes":"All lakes","organization":{"title":"NRCan"},"extras":[{"key":"spatial","value":"{\"type\":\"Polygon\",\"coordinates\":[[[-80,43],[-79,43],[-79,44],[-80,43]]]}"}],"resources":[{"format":"WMS","url":"https://maps.example.ca/wms?service=WMS"},{"format":"SHP","url":"https://x.ca/lakes.zip"}]}]}}"#; let c = Portal::new(Some("ckan"), Some("https://open.canada.ca/data")).unwrap(); - let ds = c.parse(Reach::Public, &mut 0, ckan, None, "").unwrap(); + let ds = c.parse(Reach::Public, &mut Refused::default(), ckan, None, "").unwrap(); assert_eq!(ds[0].page.as_deref(), Some("https://open.canada.ca/data/dataset/lakes")); assert_eq!(ds[0].resources.iter().map(|r| r.format.as_str()).collect::>(), vec!["Shapefile", "WMS"]); assert!( - c.parse(Reach::Public, &mut 0, br#"{"success":false,"error":{"message":"Bad request"}}"#, None, "") + c.parse(Reach::Public, &mut Refused::default(), br#"{"success":false,"error":{"message":"Bad request"}}"#, None, "") .unwrap_err() .contains("Bad request") ); @@ -1472,7 +1500,7 @@ mod tests { fn web_service_answers() { let agol = Portal::new(Some("arcgis-portal"), None).unwrap(); let a = br#"{"total":3,"results":[{"id":"abc123","type":"Feature Service","title":"Parks","owner":"city","snippet":"City parks","url":"https://services.arcgis.com/x/arcgis/rest/services/Parks/FeatureServer/0","extent":[[-122.5,47.5],[-122.2,47.7]]},{"id":"def456","type":"GeoJson","title":"Trails"},{"id":"bad id","type":"Map Service","url":"https://x.org/arcgis/rest/services/a/MapServer"},{"id":"ghi789","type":"Image Service","title":"Imagery","url":"https://x.org/arcgis/rest/services/i/ImageServer"}]}"#; - let ds = agol.parse(Reach::Public, &mut 0, a, None, "").unwrap(); + let ds = agol.parse(Reach::Public, &mut Refused::default(), a, None, "").unwrap(); assert_eq!(ds.len(), 3, "the item with a bad id is left out"); assert_eq!(ds[0].resources[0].using, Use::Service { kind: "arcgis", layer: Some("0".into()) }); assert_eq!(ds[0].bbox, Some([-122.5, 47.5, -122.2, 47.7])); @@ -1480,27 +1508,27 @@ mod tests { assert_eq!(ds[1].resources[0].url, "https://www.arcgis.com/sharing/rest/content/items/def456/data"); assert_eq!(ds[2].resources[0].url, "https://x.org/arcgis/rest/services/i/ImageServer"); assert!( - agol.parse(Reach::Public, &mut 0, br#"{"error":{"code":400,"message":"Invalid query"}}"#, None, "") + agol.parse(Reach::Public, &mut Refused::default(), br#"{"error":{"code":400,"message":"Invalid query"}}"#, None, "") .unwrap_err() .contains("Invalid query") ); let oam = Portal::new(Some("openaerialmap"), None).unwrap(); let o = br#"{"meta":{"found":2},"results":[{"_id":"1","uuid":"https://oin.s3.amazonaws.com/a/b.tif","title":"Village","provider":"HOT","platform":"uav","gsd":0.05,"acquisition_end":"2026-09-20T06:00:00Z","bbox":[-77.3,4.85,-77.2,4.86]},{"_id":"2","uuid":"https://oin.s3.amazonaws.com/a/c.tif","title":"Coast","bbox":[1,2,3]}]}"#; - let ds = oam.parse(Reach::Public, &mut 0, o, Some([-80.0, 0.0, -70.0, 10.0]), "").unwrap(); + let ds = oam.parse(Reach::Public, &mut Refused::default(), o, Some([-80.0, 0.0, -70.0, 10.0]), "").unwrap(); assert_eq!(ds.len(), 2, "an image whose box isn't one is kept"); assert_eq!((ds[0].kind.as_str(), ds[0].date.as_str()), ("uav · 5 cm per pixel", "2026-09-20")); - assert_eq!(oam.parse(Reach::Public, &mut 0, o, None, "coast").unwrap()[0].title, "Coast"); + assert_eq!(oam.parse(Reach::Public, &mut Refused::default(), o, None, "coast").unwrap()[0].title, "Coast"); let dem = Portal::new(Some("usgs-dem"), None).unwrap(); let d = br#"{"total":3,"items":[{"title":"USGS 1/3 Arc Second n47w123 20121001","downloadURL":"https://prd-tnm.s3.amazonaws.com/x/historical/n47w123/a.tif","publicationDate":"2012-10-01","boundingBox":{"minX":-123,"minY":46,"maxX":-122,"maxY":47}},{"title":"USGS 1/3 Arc Second n47w123 20240101","downloadURL":"https://prd-tnm.s3.amazonaws.com/x/current/n47w123/b.tif","publicationDate":"2024-01-01"},{"title":"USGS 1/3 Arc Second n47w123 20250813","downloadURL":"https://prd-tnm.s3.amazonaws.com/x/historical/n47w123/c.tif","publicationDate":"2025-08-13"}]}"#; - let ds = dem.parse(Reach::Public, &mut 0, d, None, "").unwrap(); + let ds = dem.parse(Reach::Public, &mut Refused::default(), d, None, "").unwrap(); assert_eq!(ds.len(), 1, "one per tile"); assert!(ds[0].resources[0].url.ends_with("/current/n47w123/b.tif"), "the current edition"); let ign = Portal::new(Some("ign-lidar"), None).unwrap(); let i = br#"{"features":[{"id":"metadata.1","geometry":{"type":"Polygon","coordinates":[[[2.3,48.8],[2.31,48.8],[2.31,48.81],[2.3,48.8]]]},"properties":{"coordonnees_nw":"0650-6858","nombre_points":17455527,"date_fin_acquisition":"2023-03-01Z","url_npl":"https://data.geopf.fr/telechargement/download/x/LHD_FXX_0650_6858_PTS_LAMB93_IGN69.copc.laz"}},{"id":"metadata.2","properties":{"url_npl":"http://x.org/a.laz"}}]}"#; - let ds = ign.parse(Reach::Public, &mut 0, i, None, "").unwrap(); + let ds = ign.parse(Reach::Public, &mut Refused::default(), i, None, "").unwrap(); assert_eq!(ds.len(), 1); assert_eq!( (ds[0].title.as_str(), ds[0].kind.as_str(), ds[0].date.as_str()), @@ -1509,30 +1537,32 @@ mod tests { let gl = Portal::new(Some("geolens"), None).unwrap(); let g = br#"{"type":"FeatureCollection","features":[{"id":"8c26-1","properties":{"title":"Tracks","record_type":"vector_dataset","geometry_type":"MULTILINESTRING","feature_count":12}},{"id":"r1","properties":{"title":"DEM","record_type":"raster_dataset","band_count":1}},{"id":"../x","properties":{"title":"Bad"}}]}"#; - let ds = gl.parse(Reach::Public, &mut 0, g, None, "").unwrap(); + let ds = gl.parse(Reach::Public, &mut Refused::default(), g, None, "").unwrap(); assert_eq!(ds.len(), 1); assert_eq!(ds[0].resources[0].url, "https://datasets.geolibre.app/api/collections/8c26-1/items?limit=1000"); assert_eq!(ds[0].resources[0].using, Use::Features, "read page by page"); let hf = Portal::new(Some("huggingface"), None).unwrap(); let h = br#"[{"id":"giswqs/geospatial","downloads":10,"gated":false,"private":false,"tags":["license:mit","region:us"]},{"id":"a/gated","gated":"manual"},{"id":"noslash"}]"#; - let ds = hf.parse(Reach::Public, &mut 0, h, None, "").unwrap(); + let ds = hf.parse(Reach::Public, &mut Refused::default(), h, None, "").unwrap(); assert_eq!(ds.len(), 1); assert_eq!((ds[0].kind.as_str(), ds[0].description.as_str(), ds[0].resources.len()), ("Dataset · 10 downloads", "license: mit", 0)); let listing = ds[0].listing.clone().unwrap(); assert_eq!(Some(listing.clone()), hf.listing_of("giswqs/geospatial")); let files = br#"[{"type":"directory","path":"naip"},{"type":"file","path":"naip/a b.tif"},{"type":"file","path":"README.md"},{"type":"file","path":"x/../../etc.geojson"},{"type":"file","path":"z.pmtiles"}]"#; - let r = hf.parse_listing(&listing, Reach::Public, &mut 0, files).unwrap(); + let r = hf.parse_listing(&listing, Reach::Public, &mut Refused::default(), files).unwrap(); assert_eq!(r.iter().map(|r| r.format.as_str()).collect::>(), vec!["naip/a b.tif", "z.pmtiles"]); assert_eq!(r[0].url, "https://huggingface.co/datasets/giswqs/geospatial/resolve/main/naip/a%20b.tif"); - assert!(hf.parse_listing("https://huggingface.co/api/datasets/../tree/main", Reach::Public, &mut 0, files).is_err()); - assert!(hf.parse_listing(&listing, Reach::Public, &mut 0, b"{}").is_err()); + assert!( + hf.parse_listing("https://huggingface.co/api/datasets/../tree/main", Reach::Public, &mut Refused::default(), files).is_err() + ); + assert!(hf.parse_listing(&listing, Reach::Public, &mut Refused::default(), b"{}").is_err()); let odp = Portal::new(Some("ocean-data"), None).unwrap(); let o = br#"{"features":[{"id":"cd48-1","bbox":[-64.6,17.7,-64.5,17.8],"properties":{"title":"Published - Coral sites","description":"Reef survey"}},{"id":"x2","bbox":[10,50,11,51],"properties":{"title":"Kelp"}}]}"#; - let ds = odp.parse(Reach::Public, &mut 0, o, None, "coral").unwrap(); + let ds = odp.parse(Reach::Public, &mut Refused::default(), o, None, "coral").unwrap(); assert_eq!((ds.len(), ds[0].title.as_str()), (1, "Coral sites")); - assert_eq!(odp.parse(Reach::Public, &mut 0, o, Some([9.0, 49.0, 12.0, 52.0]), "").unwrap()[0].title, "Kelp"); + assert_eq!(odp.parse(Reach::Public, &mut Refused::default(), o, Some([9.0, 49.0, 12.0, 52.0]), "").unwrap()[0].title, "Kelp"); // Hostile answers: never a panic, an error or nothing. for k in ["arcgis-portal", "openaerialmap", "usgs-dem", "ign-lidar", "geolens", "huggingface", "ocean-data"] { @@ -1545,8 +1575,8 @@ mod tests { b"{\"features\":[{\"properties\":7}]}", b"{\"items\":\"x\"}", ] { - let _ = p.parse(Reach::Public, &mut 0, junk, Some([0.0, 0.0, 1.0, 1.0]), "a"); - let _ = p.parse_listing("https://huggingface.co/api/datasets/a/b/tree/main", Reach::Public, &mut 0, junk); + let _ = p.parse(Reach::Public, &mut Refused::default(), junk, Some([0.0, 0.0, 1.0, 1.0]), "a"); + let _ = p.parse_listing("https://huggingface.co/api/datasets/a/b/tree/main", Reach::Public, &mut Refused::default(), junk); } } } @@ -1572,7 +1602,7 @@ mod tests { assert_eq!(oam.paging(&ou, b"junk"), (None, None)); // A web map's item, its kind, date and picture, and its layers. let a = br#"{"results":[{"id":"w1","type":"Web Map","title":"Isaias","owner":"patrick_rea","modified":1792108800000,"thumbnail":"thumbnail/t.png"}]}"#; - let ds = p.parse(Reach::Public, &mut 0, a, None, "").unwrap(); + let ds = p.parse(Reach::Public, &mut Refused::default(), a, None, "").unwrap(); let d = &ds[0]; assert_eq!((d.kind.as_str(), d.date.as_str()), ("Web map", "2026-10-16")); assert_eq!( @@ -1582,10 +1612,10 @@ mod tests { let listing = d.listing.clone().unwrap(); assert_eq!(Some(listing.clone()), p.listing_of("w1")); let wm = br#"{"operationalLayers":[{"title":"Optical","url":"https://gis.earthdata.nasa.gov/portal/rest/services/a/ImageServer"},{"layerType":"GroupLayer","title":"Sept","layers":[{"title":"Flood","url":"https://gis.earthdata.nasa.gov/portal/rest/services/b/MapServer/2"}]},{"title":"Notes"},{"title":"Local","url":"http://169.254.169.254/rest/services/c/FeatureServer/0"}]}"#; - let layers = p.parse_listing(&listing, Reach::Public, &mut 0, wm).unwrap(); + let layers = p.parse_listing(&listing, Reach::Public, &mut Refused::default(), wm).unwrap(); assert_eq!(layers.iter().map(|r| r.format.as_str()).collect::>(), vec!["Optical", "Sept › Flood"]); assert_eq!(layers[1].using, Use::Service { kind: "arcgis", layer: Some("2".into()) }); - assert!(p.parse_listing(&listing, Reach::Public, &mut 0, b"{}").is_err()); + assert!(p.parse_listing(&listing, Reach::Public, &mut Refused::default(), b"{}").is_err()); assert_eq!(day_of_ms(0.0), "1970-01-01"); assert_eq!(day_of_ms(951_782_400_000.0), "2000-02-29"); assert_eq!(day_of_ms(f64::NAN), ""); @@ -1598,7 +1628,7 @@ mod tests { assert!(!p.needs_query() && !p.needs_place()); assert_eq!(p.search_url("", None, 20), "https://stac.dynamical.org/catalog.json"); let c = br#"{"links":[{"rel":"root","href":"https://stac.dynamical.org/catalog.json"},{"rel":"child","href":"https://stac.dynamical.org/noaa-gfs-forecast/collection.json","title":"NOAA GFS forecast"},{"rel":"child","href":"https://stac.dynamical.org/noaa-gfs-forecast-virtual/collection.json","title":"virtual"},{"rel":"child","href":"https://stac.dynamical.org/ecmwf-ifs-ens-forecast-15-day-0-25-degree/collection.json"},{"rel":"child","href":"https://stac.dynamical.org/odd/collection.json"}]}"#; - let ds = p.parse(Reach::Public, &mut 0, c, None, "").unwrap(); + let ds = p.parse(Reach::Public, &mut Refused::default(), c, None, "").unwrap(); assert_eq!( ds.iter().map(|d| d.resources[0].url.as_str()).collect::>(), vec![ @@ -1608,7 +1638,7 @@ mod tests { ); assert_eq!((ds[0].title.as_str(), ds[0].organization.as_str(), ds[0].kind.as_str()), ("NOAA GFS forecast", "NOAA", "Forecast")); assert_eq!(ds[0].resources[0].using, Use::Zarr); - assert_eq!(p.parse(Reach::Public, &mut 0, c, None, "ecmwf").unwrap().len(), 1); + assert_eq!(p.parse(Reach::Public, &mut Refused::default(), c, None, "ecmwf").unwrap().len(), 1); } #[test] diff --git a/crates/ui-egui/src/mapview.rs b/crates/ui-egui/src/mapview.rs index d049c78f04..b96c405305 100644 --- a/crates/ui-egui/src/mapview.rs +++ b/crates/ui-egui/src/mapview.rs @@ -4181,13 +4181,14 @@ fn follow_asks(app: &mut RustGisApp, ctx: &egui::Context) { if capabilities { let p = json!({"layer": layer, "lon": lon, "lat": lat, "capabilities": text, "request": true}); replies.push((layer, app.session.run("identify.featureInfo", &p))); - // The service's other layers learned their requests from the same capabilities. - if replies.iter().all(|(_, r)| r.is_ok()) { - for other in also { - let p = json!({"layer": other, "lon": lon, "lat": lat, "request": true}); - let r = app.session.run("identify.featureInfo", &p); - replies.push((other, r)); - } + // The service's other layers learned their requests from the same capabilities: each is + // asked whatever became of the first's (one refused, for reaching past its layer, is + // said by its own command; capabilities that couldn't be read leave the others nothing + // to ask). + for other in also { + let p = json!({"layer": other, "lon": lon, "lat": lat, "request": true}); + let r = app.session.run("identify.featureInfo", &p); + replies.push((other, r)); } } else { // With the request and the point: the service's error in one answer format asks again @@ -5687,6 +5688,52 @@ mod tests { assert_eq!(asked.lock().unwrap().clone(), [Reach::Public]); } + /// A service's other layers are asked whatever became of the first's request: one refused for + /// reaching past its layer is said, and the next layer, whose request is within its own, is + /// asked. + #[test] + fn a_services_other_layers_are_asked_when_the_first_is_refused() { + use rustgis_engine::render::rustgis_tiles::address::Origin; + let _turn = crate::fetching::turn(); + cache::set_fetcher_with_origin(move |url, ceiling, done, _| { + let origin = Origin::with_observed_reach(cache::split_download_limit(&url).0, ceiling).unwrap(); + done(Ok(cache::Fetched { bytes: b"{}".to_vec(), origin })); + }); + let host = "others-asked.example"; + let caps = format!( + r#" +Test WMS +image/png +application/geo+json +RootEPSG:3857aAbB"# + ); + let template = |layer: &str| { + format!( + "https://{host}/wms?SERVICE=WMS&VERSION=1.3.0&REQUEST=GetMap&LAYERS={layer}&STYLES=&CRS=EPSG:3857&BBOX={{bbox-epsg-3857}}&WIDTH=256&HEIGHT=256&FORMAT=image%2Fpng" + ) + }; + let mut s = rustgis_engine::Session::new(rustgis_engine::Project::default()); + s.run("map.addTiles", &json!({"url": template("a"), "name": "A", "overlay": true})).unwrap(); + s.run("map.addTiles", &json!({"url": template("b"), "name": "B", "overlay": true})).unwrap(); + // A was listed by a document read from the internet; B is the user's own. + cache::restrict_to_public(&template("a")); + s.run("map.goToXY", &json!({"lon": 8.6, "lat": 46.65, "scale": 10000})).unwrap(); + let caps_url = rustgis_engine::data::ogc::wms_layer_of(&template("a")).unwrap().0; + let (map, opened) = (s.project.active_map, s.opened); + let mut app = RustGisApp::new(s); + let info = json!({"featureInfo": [{"tileLayer": "A", "capabilities": caps_url}, {"tileLayer": "B", "capabilities": caps_url}]}); + let mut pp = Popup::new(info, Coord::new(8.6, 46.65), map, opened); + // The capabilities answer as the service gives them. + pp.asks[0].slot = std::sync::Arc::new(std::sync::Mutex::new(Some(Ok((caps.into_bytes(), Reach::Local))))); + app.map.popup = Some(pp); + let mark = app.session.notice_mark(); + follow_asks(&mut app, &egui::Context::default()); + let told: Vec<_> = app.session.notices_since(mark).iter().map(|n| n.text.clone()).collect(); + assert!(told.iter().any(|t| t.starts_with("A: ") && t.contains("local network")), "{told:?}"); + let asked: Vec<_> = app.map.popup.as_ref().map(|pp| pp.asks.iter().map(|a| a.layer.clone()).collect()).unwrap_or_default(); + assert_eq!(asked, ["B"], "B is asked"); + } + /// Capabilities answer only the service they were asked of: a layer replaced meanwhile by /// another service's, under the same name, neither learns from them nor has its own /// capabilities held to the internet by them. diff --git a/crates/ui-egui/src/opendataui.rs b/crates/ui-egui/src/opendataui.rs index 3e9682e225..cb335fcf6a 100644 --- a/crates/ui-egui/src/opendataui.rs +++ b/crates/ui-egui/src/opendataui.rs @@ -197,11 +197,11 @@ pub fn poll(app: &mut RustGisApp, ctx: &egui::Context) { }; let Some(w) = app.ui.opendata.waiting.take() else { return }; let replaced = !w.more && app.ui.opendata.zarr_open.is_some(); - let mut refused = 0; + let mut refused = rustgis_engine::render::rustgis_tiles::portal::Refused::default(); let parsed = r.and_then(|(b, reach)| { w.portal.parse(reach, &mut refused, &b, w.area, &w.query).map(|found| (found, w.portal.paging(&w.url, &b), reach)) }); - if let Some(notice) = rustgis_engine::cmd::portals::refused_notice(refused) { + if let Some(notice) = rustgis_engine::cmd::portals::refused_notice(&refused) { app.session.notify(notice, false); } let st = &mut app.ui.opendata; @@ -251,9 +251,9 @@ fn poll_listing(app: &mut RustGisApp, ctx: &egui::Context) { return; }; let Some((i, portal, url, _)) = app.ui.opendata.listing.take() else { return }; - let mut refused = 0; + let mut refused = rustgis_engine::render::rustgis_tiles::portal::Refused::default(); let parsed = r.and_then(|(b, reach)| portal.parse_listing(&url, reach, &mut refused, &b).map(|files| (files, reach))); - if let Some(notice) = rustgis_engine::cmd::portals::refused_notice(refused) { + if let Some(notice) = rustgis_engine::cmd::portals::refused_notice(&refused) { app.session.notify(notice, false); } let st = &mut app.ui.opendata; @@ -935,7 +935,7 @@ mod tests { .session .notices .iter() - .filter(|n| n.text.contains("addresses the portal listed point where RustGIS won't fetch")) + .filter(|n| n.text.contains("1 address the portal listed is left out: http://10.0.")) .count(); assert_eq!(said, usize::from(observed == Reach::Public), "the private file left out is said once, from the internet only"); assert_eq!(h.state().ui.opendata.found[0].resources.len(), 1); From 9c3e4620dbdf10976eb53166593a15d7f8966bdc Mon Sep 17 00:00:00 2001 From: mavrick Date: Mon, 23 Nov 2026 15:13:47 -0600 Subject: [PATCH 08/10] fix(services): review round 6: learned requests kept, shown nodes recorded, one notice Capabilities a caller other than the app supplies don't replace a request the app learned. A listing records only the nodes it shows and says a full record once. Search Open Data says result pictures refused for where their address reaches. --- crates/engine/src/cmd/connection_browse.rs | 129 +++++++++++++++++---- crates/engine/src/cmd/select_info.rs | 30 ++++- crates/tiles/src/address.rs | 8 ++ crates/ui-egui/src/opendataui.rs | 52 ++++++++- 4 files changed, 191 insertions(+), 28 deletions(-) diff --git a/crates/engine/src/cmd/connection_browse.rs b/crates/engine/src/cmd/connection_browse.rs index 102677ab9a..171df15bb0 100644 --- a/crates/engine/src/cmd/connection_browse.rs +++ b/crates/engine/src/cmd/connection_browse.rs @@ -715,27 +715,75 @@ fn service( let source = l.get("source_url").and_then(Value::as_str).unwrap_or(""); if crate::render::rustgis_tiles::cache::ceiling_for(source) == address::Reach::Public { address::Reach::Public } else { reach } }; - let services: Vec<(String, address::Reach)> = r - .get("layers") - .and_then(Value::as_array) - .into_iter() - .flatten() - .filter(|l| l.get("offer").and_then(|o| o.get("type")).and_then(Value::as_str) == Some("service")) - .map(|l| (format!("service:arcgis:{}", text(&l["offer"], "url")), read_at(l))) + let mut reach_of = std::collections::HashMap::new(); + for l in r.get("layers").and_then(Value::as_array).into_iter().flatten().take(MAX_CHILDREN + 1) { + if l.get("offer").and_then(|o| o.get("type")).and_then(Value::as_str) == Some("service") { + let at = read_at(l); + reach_of + .entry(format!("service:arcgis:{}", text(&l["offer"], "url"))) + .and_modify(|r: &mut address::Reach| *r = (*r).min(at)) + .or_insert(at); + } + } + // Only the nodes shown are recorded: those past the list's end never are. + let services: Vec<(String, address::Reach)> = children + .iter() + .take(MAX_CHILDREN) + .filter_map(|child| child["node"].as_str()) + .filter_map(|node| reach_of.get(node).map(|r| (node.to_string(), *r))) .collect(); let mut children = children; + remember_services(s, c, url, &services, &mut children)?; + let mut found = Found::new(children); + found.truncated |= left_out; + Ok(found) +} + +/// Records the services a listing names, each at the reach its document was read at. With the +/// session's record full, says so once: those named by a document read from the internet are left +/// out of `children`, the rest judged by their connection's address. +fn remember_services( + s: &mut Session, + c: &Connection, + url: &str, + services: &[(String, address::Reach)], + children: &mut Vec, +) -> Result<(), String> { + let (mut unrecorded, mut left, mut judged) = (None, 0, false); for at in [address::Reach::Public, address::Reach::Local] { let nodes: Vec = services.iter().filter(|(_, r)| *r == at).map(|(node, _)| json!({"node": node})).collect(); - if !nodes.is_empty() { - let origin = address::Origin::with_observed_reach(url, at)?; - if !remember_or_say(s, c, &nodes, &origin, false) { + if nodes.is_empty() { + continue; + } + let origin = address::Origin::with_observed_reach(url, at)?; + if let Err(e) = remember_node_origins(s, c, &nodes, &origin, false) { + if at == address::Reach::Public { children.retain(|child| !nodes.iter().any(|n| n["node"] == child["node"])); + left += nodes.len(); + } else { + judged = true; } + unrecorded.get_or_insert(e); } } - let mut found = Found::new(children); - found.truncated |= left_out; - Ok(found) + if let Some(e) = unrecorded { + s.notify(unrecorded_notice(&e, left, judged), false); + } + Ok(()) +} + +/// What a listing whose nodes the full record couldn't take says: how many entries are left out +/// (`left`), and whether the rest are judged by their connection's address (`judged`). +fn unrecorded_notice(e: &str, left: usize, judged: bool) -> String { + let entries = match left { + 1 => "1 entry".to_string(), + n => format!("{n} entries"), + }; + match (left > 0, judged) { + (true, true) => format!("{e}: {entries} this listing names are left out; the rest are judged by its connection's address"), + (true, false) => format!("{e}: {entries} this listing names are left out"), + _ => format!("{e}; what this listing names is judged by its connection's address"), + } } /// [`remember_node_origins`], saying when the session's record is full instead of failing the @@ -744,17 +792,9 @@ fn service( /// the record, so the caller leaves them out (`false`). fn remember_or_say(s: &mut Session, c: &Connection, children: &[Value], origin: &address::Origin, root: bool) -> bool { let Err(e) = remember_node_origins(s, c, children, origin, root) else { return true }; - if origin.reach() == address::Reach::Public { - let left = match children.len() { - 1 => "1 entry".to_string(), - n => format!("{n} entries"), - }; - s.notify(format!("{e}: {left} this listing names are left out"), false); - false - } else { - s.notify(format!("{e}; what this listing names is judged by its connection's address"), false); - true - } + let public = origin.reach() == address::Reach::Public; + s.notify(unrecorded_notice(&e, if public { children.len() } else { 0 }, !public), false); + !public } /// A catalogue's records, each with the services and files it links to, read at `origin`: what @@ -1348,6 +1388,47 @@ mod tests { assert!(super::remember_node_origins(&mut session, &connection, &[other.clone(), new], &public, false).is_err()); let narrowed = super::node_origin(&session, &connection, other["node"].as_str().unwrap()).map(|o| o.reach()); assert_eq!(narrowed, Some(Reach::Public)); + // A listing naming services read at both reaches says the full record once: those read + // from the internet left out, the rest kept. + let services = [ + ("service:arcgis:https://csw-21-web.example/arcgis/rest/services".to_string(), Reach::Public), + ("service:arcgis:http://10.0.21.5/arcgis/rest/services".to_string(), Reach::Local), + ]; + let mut children: Vec = services.iter().map(|(n, _)| json!({"node": n})).collect(); + let mark = session.notice_mark(); + super::remember_services(&mut session, &connection, "https://csw-21.corp-looks-public.example/csw", &services, &mut children) + .unwrap(); + let said: Vec<&str> = session.notices_since(mark).iter().map(|n| n.text.as_str()).collect(); + assert_eq!(said.len(), 1, "{said:?}"); + assert!(said[0].contains("1 entry") && said[0].contains("the rest are judged"), "{said:?}"); + assert_eq!(children, [json!({"node": services[1].0})]); + } + + /// A directory listing more services than are shown records only those shown. + #[test] + fn only_the_services_a_listing_shows_are_recorded() { + use crate::render::rustgis_tiles::address::Origin; + let mut session = crate::Session::new(crate::Project::default()); + let address = "https://csw-22.corp-looks-public.example/csw"; + let saved = session.run("connection.new", &json!({"kind":"csw","address":address})).unwrap(); + let connection = session.connections.connections.iter().find(|c| c.id == saved["id"].as_str().unwrap()).unwrap().clone(); + let node = "service:arcgis:http://10.0.22.5/arcgis/rest/services".to_string(); + let local = Origin::connected(&connection.address, "10.0.0.5".parse().unwrap()).unwrap(); + super::remember_node_origins(&mut session, &connection, &[json!({"node": node})], &local, false).unwrap(); + let folders: Vec = (0..super::MAX_CHILDREN + 100).map(|i| format!("F{i}")).collect(); + let listing = json!({"currentVersion": 11.1, "folders": folders, "services": []}).to_string(); + let requested = super::browse(&mut session, &json!({"id": connection.id, "node": node, "probe": true})).unwrap()["fetch"] + .as_str() + .unwrap() + .to_string(); + let read = Origin::connected(&requested, "10.0.22.5".parse().unwrap()).unwrap(); + let before = session.browse_origins.1.len(); + let opened = session.opened; + let out = + session.browse_from_origin(&json!({"id": connection.id, "node": node, "answer": listing}), &requested, opened, read).unwrap(); + let shown = out["children"].as_array().unwrap().iter().filter(|c| c.get("node").is_some()).count(); + assert!(shown > 0 && shown <= super::MAX_CHILDREN + 1, "{shown}"); + assert_eq!(session.browse_origins.1.len() - before, shown); } #[test] diff --git a/crates/engine/src/cmd/select_info.rs b/crates/engine/src/cmd/select_info.rs index 8ab3169a21..b51917005e 100644 --- a/crates/engine/src/cmd/select_info.rs +++ b/crates/engine/src/cmd/select_info.rs @@ -236,9 +236,12 @@ fn feature_info(s: &mut Session, p: &Value) -> CmdResult { return Err(named(format!("the capabilities are larger than {} MB", MAX_TEXT >> 20))); } // Capabilities supplied by anything but the app say nothing trustworthy about where they - // were read: the requests they name are asked only on the internet. + // were read: the requests they name are asked only on the internet. Nor do they replace + // a request the layer already knows, or its reach. let untrusted = !s.policy_user(); - learn(s, index, caps.as_bytes(), untrusted).map_err(named)?; + if !(untrusted && s.map().tiles.get(index).is_some_and(|t| t.feature_info.is_some())) { + learn(s, index, caps.as_bytes(), untrusted).map_err(named)?; + } } if let Some(text) = ps(p, "text") { if text.len() > MAX_TEXT { @@ -413,5 +416,28 @@ mod tests { assert!(e.contains(&format!("http://192.168.{n}.5/info")) && e.contains("local network"), "{e}"); } } + // A layer whose request the app learned keeps it, and its reach, when the Assistant + // supplies capabilities for it afterwards. + let host = "identify-supplied-3.example"; + let caps = format!( + r#" +Test WMS +image/png +application/geo+json +RootEPSG:3857roadsRoads"# + ); + let mut s = Session::new(crate::Project::default()); + let template = format!( + "https://{host}/wms?SERVICE=WMS&VERSION=1.3.0&REQUEST=GetMap&LAYERS=roads&STYLES=&CRS=EPSG:3857&BBOX={{bbox-epsg-3857}}&WIDTH=256&HEIGHT=256&FORMAT=image/png" + ); + s.run("map.addTiles", &json!({"url": template, "name": "Mine"})).unwrap(); + s.run("map.goToXY", &json!({"lon": 8.5, "lat": 47.4, "scale": 10000})).unwrap(); + let p = json!({"layer": "Mine", "lon": 8.5, "lat": 47.4, "capabilities": caps, "request": true}); + feature_info(&mut s, &p).unwrap(); + let scope = Scope::assistant(4_201_308, std::sync::Arc::new(Live)); + let _ = s.with_scope(scope, |s| feature_info(s, &p)).unwrap(); + assert!(!s.map().tiles[0].feature_info_public); + let asked = feature_info(&mut s, &json!({"layer": "Mine", "lon": 8.5, "lat": 47.4, "request": true})).unwrap(); + assert!(asked["url"].as_str().is_some_and(|u| u.starts_with("http://192.168.3.5/info?")), "{asked}"); } } diff --git a/crates/tiles/src/address.rs b/crates/tiles/src/address.rs index 283e73637d..12fe47a84c 100644 --- a/crates/tiles/src/address.rs +++ b/crates/tiles/src/address.rs @@ -301,6 +301,14 @@ pub fn check_reach(url: &str, ceiling: Reach) -> Result<(), String> { } } +/// Whether a fetch's error is a refusal for where its address reaches ([`check_reach`], or where +/// the address resolved when it was fetched), not a failure of the service. +pub fn is_refusal(error: &str) -> bool { + ["can't point into the local network", "that address is never fetched", "resolves to this computer or the local network"] + .iter() + .any(|m| error.contains(m)) +} + #[cfg(test)] mod tests { use super::*; diff --git a/crates/ui-egui/src/opendataui.rs b/crates/ui-egui/src/opendataui.rs index cb335fcf6a..f720590595 100644 --- a/crates/ui-egui/src/opendataui.rs +++ b/crates/ui-egui/src/opendataui.rs @@ -125,6 +125,9 @@ pub struct State { /// The results whose details are shown. open: std::collections::HashSet, thumbs: std::collections::HashMap, + /// Pictures refused for where their address reaches, said once those being fetched have + /// landed: how many, and the first refusal. + thumbs_refused: (usize, Option), /// The Zarr stores being checked (by their result's place), which some datasets lack. probes: Vec<(usize, Read)>, /// The result whose Zarr store is open in the pane, to pick its variable and steps. @@ -153,6 +156,7 @@ impl Default for State { next: None, open: Default::default(), thumbs: Default::default(), + thumbs_refused: (0, None), probes: Vec::new(), zarr_open: None, error: None, @@ -302,8 +306,9 @@ fn poll_probes(app: &mut RustGisApp, ctx: &egui::Context) { /// Lands the pictures fetched, as textures. fn poll_thumbs(app: &mut RustGisApp, ctx: &egui::Context) { + let st = &mut app.ui.opendata; let mut waiting = false; - for (url, thumb) in app.ui.opendata.thumbs.iter_mut() { + for (url, thumb) in st.thumbs.iter_mut() { let Thumb::Loading(slot) = thumb else { continue }; let Some(r) = slot.lock().unwrap_or_else(|e| e.into_inner()).take() else { waiting = true; @@ -314,11 +319,28 @@ fn poll_thumbs(app: &mut RustGisApp, ctx: &egui::Context) { let img = egui::ColorImage::from_rgba_premultiplied([pm.width() as usize, pm.height() as usize], pm.data()); Thumb::Ready(ctx.load_texture(format!("webdata_thumb_{url}"), img, egui::TextureOptions::LINEAR)) } - Err(_) => Thumb::Failed, + // A picture the answer naming it can't reach is said; one the service hasn't is not. + Err(e) => { + if rustgis_engine::render::rustgis_tiles::address::is_refusal(&e) { + st.thumbs_refused.0 += 1; + st.thumbs_refused.1.get_or_insert(e); + } + Thumb::Failed + } }; } if waiting { ctx.request_repaint_after(std::time::Duration::from_millis(150)); + return; + } + let (n, first) = std::mem::take(&mut st.thumbs_refused); + if let Some(first) = first { + let notice = if n == 1 { + crate::i18n::fmt("A picture of the results is left out: {first}", &[("first", &first)]) + } else { + crate::i18n::fmt("{n} pictures of the results are left out, such as {first}", &[("n", &n.to_string()), ("first", &first)]) + }; + app.session.notify(notice, false); } } @@ -947,6 +969,32 @@ mod tests { } } + /// A result's picture refused for where its address reaches is said, once for those fetched + /// together; one the service just hasn't isn't, and one fetched is shown. + #[test] + fn pictures_refused_for_their_reach_are_said_once() { + let mut app = RustGisApp::new(rustgis_engine::Session::new(rustgis_engine::Project::default())); + let landed = |r: Result<(Vec, Reach), String>| { + let slot: crate::Slot, Reach), String>> = Default::default(); + *slot.lock().unwrap() = Some(r); + Thumb::Loading(slot) + }; + let refused = |u: &str| rustgis_engine::render::rustgis_tiles::address::check_reach(u, Reach::Public).unwrap_err(); + let png = rustgis_engine::render::Pixmap::new(1, 1).unwrap().encode_png().unwrap(); + let st = &mut app.ui.opendata; + st.thumbs.insert("a".into(), landed(Err(refused("http://10.0.30.1/a.png")))); + st.thumbs.insert("b".into(), landed(Err(refused("http://10.0.30.2/b.png")))); + st.thumbs.insert("c".into(), landed(Err("HTTP 404".into()))); + st.thumbs.insert("d".into(), landed(Ok((png, Reach::Public)))); + let mark = app.session.notice_mark(); + poll_thumbs(&mut app, &egui::Context::default()); + let said: Vec<&str> = app.session.notices_since(mark).iter().map(|n| n.text.as_str()).collect(); + assert_eq!(said.len(), 1, "{said:?}"); + assert!(said[0].starts_with("2 pictures of the results are left out, such as http://10.0.30."), "{said:?}"); + assert!(matches!(app.ui.opendata.thumbs.get("d"), Some(Thumb::Ready(_)))); + assert!(matches!(app.ui.opendata.thumbs.get("c"), Some(Thumb::Failed))); + } + /// Web Data's Add reads a GeoLens dataset's every page, not only the server's first 1,000. #[test] fn a_geolens_dataset_is_added_page_by_page() { From d617a895c3e7a98df5553f0d6c981739b9d5f087 Mon Sep 17 00:00:00 2001 From: mavrick Date: Mon, 23 Nov 2026 16:26:05 -0600 Subject: [PATCH 09/10] fix(services): review round 7: cut a listing before recording it; keep the picture count across services A listing is cut to what is shown before its nodes are recorded and those a full record refuses are left out, so no node past the end is shown unrecorded. Search Open Data keeps the count of refused pictures when it moves to another service. --- crates/engine/src/cmd/connection_browse.rs | 28 ++++++++++++++++------ crates/ui-egui/src/opendataui.rs | 18 ++++++++++++-- 2 files changed, 37 insertions(+), 9 deletions(-) diff --git a/crates/engine/src/cmd/connection_browse.rs b/crates/engine/src/cmd/connection_browse.rs index 171df15bb0..a3a71030aa 100644 --- a/crates/engine/src/cmd/connection_browse.rs +++ b/crates/engine/src/cmd/connection_browse.rs @@ -725,17 +725,17 @@ fn service( .or_insert(at); } } - // Only the nodes shown are recorded: those past the list's end never are. - let services: Vec<(String, address::Reach)> = children + // The list is cut to what is shown first, so only the nodes shown are recorded, and none past + // its end comes up unrecorded when those the full record refuses are left out. + let mut found = Found::new(children); + found.truncated |= left_out; + let services: Vec<(String, address::Reach)> = found + .children .iter() - .take(MAX_CHILDREN) .filter_map(|child| child["node"].as_str()) .filter_map(|node| reach_of.get(node).map(|r| (node.to_string(), *r))) .collect(); - let mut children = children; - remember_services(s, c, url, &services, &mut children)?; - let mut found = Found::new(children); - found.truncated |= left_out; + remember_services(s, c, url, &services, &mut found.children)?; Ok(found) } @@ -1429,6 +1429,20 @@ mod tests { let shown = out["children"].as_array().unwrap().iter().filter(|c| c.get("node").is_some()).count(); assert!(shown > 0 && shown <= super::MAX_CHILDREN + 1, "{shown}"); assert_eq!(session.browse_origins.1.len() - before, shown); + // With the record full, a listing read from the internet has every node it shows left + // out, and none past the shown end takes their place unrecorded. + let node = "service:arcgis:https://dir-22.corp-looks-public.example/arcgis/rest/services".to_string(); + super::remember_node_origins(&mut session, &connection, &[json!({"node": node})], &local, false).unwrap(); + let requested = super::browse(&mut session, &json!({"id": connection.id, "node": node, "probe": true})).unwrap()["fetch"] + .as_str() + .unwrap() + .to_string(); + session.browse_origins.1.extend((0..16_384).map(|i| ((format!("full-{i}"), String::new(), String::new()), local.clone()))); + let read = Origin::connected(&requested, "93.184.216.34".parse().unwrap()).unwrap(); + let out = + session.browse_from_origin(&json!({"id": connection.id, "node": node, "answer": listing}), &requested, opened, read).unwrap(); + let nodes: Vec<&Value> = out["children"].as_array().unwrap().iter().filter(|c| c.get("node").is_some()).collect(); + assert!(nodes.is_empty(), "{nodes:?}"); } #[test] diff --git a/crates/ui-egui/src/opendataui.rs b/crates/ui-egui/src/opendataui.rs index f720590595..6e1b2bbdad 100644 --- a/crates/ui-egui/src/opendataui.rs +++ b/crates/ui-egui/src/opendataui.rs @@ -353,8 +353,9 @@ pub fn start(app: &mut RustGisApp, p: &serde_json::Value) { let st = &mut app.ui.opendata; let fresh = st.service != svc.map(|s| s.id); if fresh { - // Another service: its own choices. - *st = State { service: svc.map(|s| s.id), ..State::default() }; + // Another service: its own choices. Pictures refused so far are still said. + let refused = std::mem::take(&mut st.thumbs_refused); + *st = State { service: svc.map(|s| s.id), thumbs_refused: refused, ..State::default() }; if let Some(s) = svc { st.portal = s.portal; // A search by place is where the map is. @@ -993,6 +994,19 @@ mod tests { assert!(said[0].starts_with("2 pictures of the results are left out, such as http://10.0.30."), "{said:?}"); assert!(matches!(app.ui.opendata.thumbs.get("d"), Some(Thumb::Ready(_)))); assert!(matches!(app.ui.opendata.thumbs.get("c"), Some(Thumb::Failed))); + // One refused while another is still being fetched, and the pane moves to another + // service: still said. + let st = &mut app.ui.opendata; + st.service = Some("dynamical"); + st.thumbs.insert("e".into(), landed(Err(refused("http://10.0.30.5/e.png")))); + st.thumbs.insert("f".into(), Thumb::Loading(Default::default())); + let mark = app.session.notice_mark(); + poll_thumbs(&mut app, &egui::Context::default()); + assert_eq!(app.session.notices_since(mark).len(), 0, "one is still being fetched"); + start(&mut app, &json!({})); + poll_thumbs(&mut app, &egui::Context::default()); + let said: Vec<&str> = app.session.notices_since(mark).iter().map(|n| n.text.as_str()).collect(); + assert!(said.len() == 1 && said[0].starts_with("A picture of the results is left out: http://10.0.30.5/"), "{said:?}"); } /// Web Data's Add reads a GeoLens dataset's every page, not only the server's first 1,000. From cf79fbf5acfa1608dda175499a2dd5670655fb1a Mon Sep 17 00:00:00 2001 From: mavrick Date: Mon, 23 Nov 2026 17:19:42 -0600 Subject: [PATCH 10/10] fix(services): review round 8: a node named twice takes one place; peer refusals said A page naming a node twice no longer counts it twice against the record's room. A picture refused at a forbidden peer is recognised as a refusal and said, with a test over each refusal the address module gives. --- crates/engine/src/cmd/connection_browse.rs | 24 ++++++++++++++++++++- crates/tiles/src/address.rs | 25 +++++++++++++++++++--- 2 files changed, 45 insertions(+), 4 deletions(-) diff --git a/crates/engine/src/cmd/connection_browse.rs b/crates/engine/src/cmd/connection_browse.rs index a3a71030aa..f574a99726 100644 --- a/crates/engine/src/cmd/connection_browse.rs +++ b/crates/engine/src/cmd/connection_browse.rs @@ -417,7 +417,10 @@ fn remember_node_origins(s: &mut Session, c: &Connection, children: &[Value], or // A node a listing read from the internet named stays held there, though a listing read // locally names it again: the narrower record is kept. Records already there are narrowed // first, whatever room is left, as narrowing adds none. - let (known, new): (Vec<_>, Vec<_>) = keys.into_iter().partition(|key| s.browse_origins.1.contains_key(key)); + let (known, mut new): (Vec<_>, Vec<_>) = keys.into_iter().partition(|key| s.browse_origins.1.contains_key(key)); + // A node named twice (records often link the same service) takes one place. + let mut unique = std::collections::HashSet::new(); + new.retain(|key| unique.insert(key.clone())); for key in known { if !s.browse_origins.1.get(&key).is_some_and(|recorded| recorded.reach() < origin.reach()) { s.browse_origins.1.insert(key, origin.clone()); @@ -1404,6 +1407,25 @@ mod tests { assert_eq!(children, [json!({"node": services[1].0})]); } + /// A node a listing names twice takes one place in the record, so a page that fits isn't + /// refused as too many. + #[test] + fn a_node_named_twice_takes_one_place_in_the_record() { + use crate::render::rustgis_tiles::address::Origin; + let mut session = crate::Session::new(crate::Project::default()); + let saved = session.run("connection.new", &json!({"kind":"csw","address":"https://csw-23.corp-looks-public.example/csw"})).unwrap(); + let connection = session.connections.connections.iter().find(|c| c.id == saved["id"].as_str().unwrap()).unwrap().clone(); + let local = Origin::connected(&connection.address, "10.0.0.5".parse().unwrap()).unwrap(); + let first = json!({"node": "service:wms:https://csw-23-first.example/wms"}); + super::remember_node_origins(&mut session, &connection, &[first], &local, false).unwrap(); + let room = 16_384 - session.browse_origins.1.len() - 1; + session.browse_origins.1.extend((0..room).map(|i| ((format!("full-{i}"), String::new(), String::new()), local.clone()))); + let node = json!({"node": "service:wms:https://csw-23-wms.example/wms"}); + let twice = super::remember_node_origins(&mut session, &connection, &[node.clone(), node], &local, false); + assert!(twice.is_ok(), "{twice:?}"); + assert_eq!(session.browse_origins.1.len(), 16_384); + } + /// A directory listing more services than are shown records only those shown. #[test] fn only_the_services_a_listing_shows_are_recorded() { diff --git a/crates/tiles/src/address.rs b/crates/tiles/src/address.rs index 12fe47a84c..8e9dad4ba5 100644 --- a/crates/tiles/src/address.rs +++ b/crates/tiles/src/address.rs @@ -304,9 +304,14 @@ pub fn check_reach(url: &str, ceiling: Reach) -> Result<(), String> { /// Whether a fetch's error is a refusal for where its address reaches ([`check_reach`], or where /// the address resolved when it was fetched), not a failure of the service. pub fn is_refusal(error: &str) -> bool { - ["can't point into the local network", "that address is never fetched", "resolves to this computer or the local network"] - .iter() - .any(|m| error.contains(m)) + [ + "can't point into the local network", + "that address is never fetched", + "that peer address is never fetched", + "resolves to this computer or the local network", + ] + .iter() + .any(|m| error.contains(m)) } #[cfg(test)] @@ -432,6 +437,20 @@ mod tests { } } + /// Every refusal for where an address reaches is told from a service's failure. + #[test] + fn refusals_are_told_from_other_failures() { + let refused = [ + check_reach("http://10.0.40.1/a.png", Reach::Public).unwrap_err(), + check_reach("http://169.254.169.254/latest", Reach::Local).unwrap_err(), + Origin::connected("https://refused-peer.example/a.png", "169.254.169.254".parse().unwrap()).unwrap_err(), + ]; + for e in &refused { + assert!(is_refusal(e), "{e}"); + } + assert!(!is_refusal("HTTP 404")); + } + /// Site-local addresses (`fec0::/10`, deprecated but still routed inside some sites) are /// local: a document on the web can't point at them, and a peer there is observed local. /// Teredo addresses stay public: what they embed is obfuscated and reached through a relay.