diff --git a/crates/engine/src/cmd/plugin_fetch.rs b/crates/engine/src/cmd/plugin_fetch.rs index 935d5c48a9..b15422068f 100644 --- a/crates/engine/src/cmd/plugin_fetch.rs +++ b/crates/engine/src/cmd/plugin_fetch.rs @@ -595,11 +595,12 @@ impl UrlWaits { let slot: Arc, String>>>> = Arc::default(); let land = slot.clone(); let url = asked["url"].as_str().unwrap_or("").to_string(); - crate::render::rustgis_tiles::cache::download_within( + let read = url.clone(); + crate::render::rustgis_tiles::cache::download_within_with_origin( &url, MAX_DOCUMENT, DOCUMENT_TIMEOUT, - Box::new(move |r| *land.lock().unwrap_or_else(|e| e.into_inner()) = Some(r)), + Box::new(move |r| *land.lock().unwrap_or_else(|e| e.into_inner()) = Some(document_read(&read, r))), ); self.reading.push((n, url, slot)); } @@ -662,6 +663,21 @@ impl UrlWaits { } } +/// The bytes of a service's document read off the frame from `url`. One that came from the +/// internet, wherever its name pointed, is recorded so ([`cache::restrict_to_public`]): the +/// command, run again, reads the documents it links to and adds the layers it lists only from +/// there, as it does for a document it fetches itself. +/// +/// [`cache::restrict_to_public`]: crate::render::rustgis_tiles::cache::restrict_to_public +pub(crate) fn document_read(url: &str, read: Result) -> Result, String> { + read.map(|fetched| { + if fetched.origin.reach() == address::Reach::Public { + crate::render::rustgis_tiles::cache::restrict_to_public(url); + } + fetched.bytes + }) +} + /// A download request without its number: what a command asked for. pub(crate) fn without_request(p: &Value) -> Value { let mut p = p.clone(); diff --git a/crates/engine/src/cmd/service.rs b/crates/engine/src/cmd/service.rs index 346aa6519d..a99b404048 100644 --- a/crates/engine/src/cmd/service.rs +++ b/crates/engine/src/cmd/service.rs @@ -14,6 +14,7 @@ use rustgis_data::ogc::{Coverage, Offer, Service, SliderSteps}; use serde_json::{Value, json}; use super::ps; +use crate::render::rustgis_tiles::{address::Reach, cache}; use crate::{CmdResult, CommandSpec as C, Session}; #[path = "service_group.rs"] @@ -95,6 +96,9 @@ pub(crate) fn without_token(p: &Value) -> Result, String> { struct CapabilitySource { address: std::sync::Arc, crossed_origin: bool, + /// The document was read from the internet: what it lists is fetched from there too, never + /// from this computer or the local network, whatever its names resolve to. + public: bool, } /// Capability discovery is shared by supplied-document GUI requests and native commands. @@ -230,10 +234,29 @@ fn matches_words(layer: &rustgis_data::ogc::ServiceLayer, words: &[String]) -> b words.iter().all(|w| title.contains(w.as_str()) || name.contains(w.as_str())) } +/// How discovery fetches a document while the command waits: its address and the widest network +/// reach the fetch may connect to, giving the bytes and where they actually came from. +type FetchDocument<'a> = &'a mut dyn FnMut(&str, Reach) -> Result; + /// Replays the same bounded discovery traversal for blocking, deferred and supplied documents. /// Cancel is checked between documents; parsing a single bounded JSON document cannot stop /// partway through serde's read. fn read_documents(s: &mut Session, p: &Value, left: bool, explicit_map: Option<(&str, Option<&str>)>) -> Result { + read_documents_with(s, p, left, explicit_map, &mut fetch_document) +} + +/// [`read_documents`] with its fetch given, so the reach each document is fetched within can be +/// tested. A document a service links to is fetched within the reach of the document that linked +/// it, as its fetch observed it (a name that looks public may resolve to this computer); one the +/// app supplied or reads off the frame is restricted to the internet when the document linking it +/// was read from there ([`cache::restrict_to_public`]), so the app's fetch honours it too. +fn read_documents_with( + s: &mut Session, + p: &Value, + left: bool, + explicit_map: Option<(&str, Option<&str>)>, + fetch: FetchDocument<'_>, +) -> Result { let original = url_of(p)?; let mut address = crate::render::rustgis_tiles::logins::inherit(original, &rustgis_data::ogc::capabilities_url(original, ps(p, "type"))); @@ -256,9 +279,20 @@ fn read_documents(s: &mut Session, p: &Value, left: bool, explicit_map: Option<( let mut dataset = None::; let mut dataset_document = false; let mut dataset_bytes = 0usize; + // The reach of each document read, by its address without a login: what it passes on to the + // documents it links to and the layers it lists. + let mut reaches = std::collections::HashMap::::new(); 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). + let inherited = if seen.is_empty() { + Reach::Local + } 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)) { Ok(()) => false, Err(_) if dataset_document => true, @@ -285,6 +319,12 @@ fn read_documents(s: &mut Session, p: &Value, left: bool, explicit_map: Option<( rustgis_data::ogc::parse(&address, bytes) } }; + // The app fetches a document that is supplied or read off the frame, so it is told the + // reach through the address's record. + if ceiling == Reach::Public && (supplied.is_some() || left) && !rejected && !repeated { + cache::restrict_to_public(&address); + } + let mut observed = None; let parsed = if rejected { Ok(dataset.as_mut().ok_or_else(|| "missing dataset discovery plan".to_string())?.reject_address()) } else if repeated { @@ -311,8 +351,21 @@ fn read_documents(s: &mut Session, p: &Value, left: bool, explicit_map: Option<( }; read.and_then(|bytes| parse(&bytes)) } else { - fetch_capabilities(original, &address).and_then(|bytes| parse(&bytes)) + fetch(&address, ceiling) + .map(|fetched| { + observed = Some(fetched.origin.reach()); + // The app knows a listed layer's document only by its address, so one read + // from the internet is recorded there, as one the app reads is. + if observed == Some(Reach::Public) { + cache::restrict_to_public(&address); + } + fetched.bytes + }) + .map_err(|e| crate::sources::message_with_address(original, &e)) + .and_then(|bytes| parse(&bytes)) }; + // Natively, where the fetch connected; otherwise what the app's fetch was held to. + let reach = observed.unwrap_or(ceiling); let parsed = parsed.map_err(|e| crate::sources::message_with_address(&address, &e)); let mut service = match parsed { Ok(s) => { @@ -349,7 +402,13 @@ fn read_documents(s: &mut Session, p: &Value, left: bool, explicit_map: Option<( dataset = Some(plan); } } - histories.insert(address.clone(), crossed_origin); + // A repeated dataset document is not read again: it keeps the crossed-origin record and + // the reach of its read, which the documents it links to inherit, wherever the repeat + // falls among them. + if !repeated { + histories.insert(address.clone(), crossed_origin); + reaches.insert(crate::render::rustgis_tiles::logins::inner(&address).to_string(), reach); + } seen.insert(address.clone()); if result.service.kind.is_empty() { result.service.kind = service.kind.clone(); @@ -368,9 +427,12 @@ fn read_documents(s: &mut Session, p: &Value, left: bool, explicit_map: Option<( && let Offer::Style { url } = &layer.offer && let Some(&style_crossed) = histories.get(url) { - CapabilitySource { address: url.as_str().into(), crossed_origin: style_crossed } + // Every document in `histories` has its reach recorded with it; were one missing, + // the stylesheet would be held to the internet, the narrower choice. + let public = reaches.get(crate::render::rustgis_tiles::logins::inner(url)).is_none_or(|r| *r == Reach::Public); + CapabilitySource { address: url.as_str().into(), crossed_origin: style_crossed, public } } else { - CapabilitySource { address: shared.clone(), crossed_origin } + CapabilitySource { address: shared.clone(), crossed_origin, public: reach == Reach::Public } }; result.service.layers.push(layer); result.sources.push(source); @@ -405,14 +467,15 @@ fn read_documents(s: &mut Session, p: &Value, left: bool, explicit_map: Option<( } #[cfg(target_arch = "wasm32")] -fn fetch_capabilities(url: &str, _caps: &str) -> Result, String> { - Err(crate::sources::message_with_address(url, "in the web app, use Home › Add › Add Data › From Service")) +fn fetch_document(_: &str, _: Reach) -> Result { + Err("in the web app, use Home › Add › Add Data › From Service".into()) } +/// Downloads a capabilities or dataset document within `ceiling`, keeping where it came from. #[cfg(not(target_arch = "wasm32"))] -/// Downloads bytes so ordinary capabilities and dataset documents share the same fetch path. -fn fetch_capabilities(url: &str, caps: &str) -> Result, String> { - crate::render::rustgis_tiles::cache::download_blocking(caps).map_err(|e| crate::sources::message_with_address(url, &e)) +fn fetch_document(url: &str, ceiling: Reach) -> Result { + cache::download_blocking_with_origin_within(url, cache::MAX_DOWNLOAD, cache::BLOCKING_TIMEOUT, &[], ceiling) + .map_err(cache::large_file_hint) } /// Leaves out the layers whose addresses a document on the web may not send RustGIS to: the @@ -510,13 +573,14 @@ pub(crate) fn bounds_of(v: Option<&Value>) -> Result, String> { /// [`DESCRIPTION_TIMEOUT`](rustgis_data::ogc::DESCRIPTION_TIMEOUT) and takes at most /// [`DESCRIPTION_MAX`](rustgis_data::ogc::DESCRIPTION_MAX) bytes, apart; the features /// [`BLOCKING_TIMEOUT`](crate::render::rustgis_tiles::cache::BLOCKING_TIMEOUT) in all after it -/// (75 s at most). A page is fetched only where the page before it may point. +/// (75 s at most). A page is fetched only where the page before it may point. With `public` (a +/// layer a document read from the internet lists), only internet addresses are fetched. #[cfg(not(target_arch = "wasm32"))] -pub(crate) fn download_features(s: &mut Session, name: &str, url: &str, max: usize) -> Result, String> { +pub(crate) fn download_features(s: &mut Session, name: &str, url: &str, max: usize, public: bool) -> Result, String> { // Its features alone: what they are used for (a task's input, an export) has no layer to draw // with the service's symbology, so how the description says it is drawn, or why it couldn't // be read (`.1`), is dropped. - match download_layer(s, name, url, max, false)?.0 { + match download_layer(s, name, url, max, false, public)?.0 { Downloaded::Bytes(bytes) => Ok(bytes), // Not given without protocol buffer pages. Downloaded::Read(..) => Err(crate::sources::message_with_address(url, "the pages were read as protocol buffers")), @@ -541,7 +605,6 @@ pub(crate) fn add_service_layer( zoom: Option, file: impl FnOnce(&[u8]) -> Result, ) -> CmdResult { - use crate::render::rustgis_tiles::{address::Reach, cache}; let (downloaded, drawing) = download_layer_with(s, name, url, cache::MAX_DOWNLOAD, true, |url, max, timeout, ceiling| { let ceiling = if public { ceiling.min(Reach::Public) } else { ceiling }; cache::download_blocking_with_origin_within(url, max, timeout, &[], ceiling) @@ -586,9 +649,17 @@ pub(crate) enum Downloaded { /// ArcGIS layer's description says it is drawn (its `drawingInfo`), or a note saying why it /// couldn't be read (#2152), when there is something to say. #[cfg(not(target_arch = "wasm32"))] -pub(crate) fn download_layer(s: &mut Session, name: &str, url: &str, max: usize, pbf: bool) -> Result<(Downloaded, Drawing), String> { +pub(crate) fn download_layer( + s: &mut Session, + name: &str, + url: &str, + max: usize, + pbf: bool, + public: bool, +) -> Result<(Downloaded, Drawing), String> { download_layer_with(s, name, url, max, pbf, |url, max, timeout, ceiling| { - crate::render::rustgis_tiles::cache::download_blocking_with_origin_within(url, max, timeout, &[], ceiling) + let ceiling = if public { ceiling.min(Reach::Public) } else { ceiling }; + cache::download_blocking_with_origin_within(url, max, timeout, &[], ceiling) }) } @@ -607,7 +678,7 @@ fn download_layer_with( crate::render::rustgis_tiles::address::Reach, ) -> Result, ) -> Result<(Downloaded, Drawing), String> { - use crate::render::rustgis_tiles::{address, cache}; + use crate::render::rustgis_tiles::address; use rustgis_data::ogc::{DESCRIPTION_MAX, DESCRIPTION_TIMEOUT, Step, begin, begin_with_pbf, max_paged_features}; let mut until = std::time::Instant::now() + cache::BLOCKING_TIMEOUT; let mut left = max; @@ -690,6 +761,8 @@ struct AdvertisedTemplate { /// Why the standard tile address is used instead, when a template was looked for and not /// found: the notice to give. fallback: Option, + /// A document on the way was read from the internet: the template is fetched only from there. + public: bool, } /// Compares canonical origins without treating a runtime login wrapper as part of the origin. @@ -699,10 +772,20 @@ fn crosses_origin(from: &str, to: &str) -> bool { /// The tile template an OGC API tileset list advertises (its WebMercatorQuad tileset's), read now /// (the list, then the tileset when the list doesn't carry it). Failed discovery still keeps -/// any foreign hop: a fallback must not recover the original connection either. +/// any foreign hop: a fallback must not recover the original connection either. Each document is +/// fetched within the reach of the one before it, the service's document first (`public`: it was +/// 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) -> AdvertisedTemplate { - advertised_template_with(source, list, vector, withheld, crate::render::rustgis_tiles::cache::download_blocking) +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 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 } /// Resolves at most two advertised documents while retaining every foreign hop, even on failure. @@ -733,7 +816,7 @@ fn walk_template, E>( mut read: impl FnMut(&str) -> Result, E>, ) -> Result { use rustgis_data::ogc::{TilesStep, resolve_tiles}; - let mut out = AdvertisedTemplate { template: None, crossed_origin: crosses_origin(source, list), fallback: None }; + let mut out = AdvertisedTemplate { template: None, crossed_origin: crosses_origin(source, list), fallback: None, public: false }; let mut doc = list.to_string(); for _ in 0..2 { let shown = crate::sources::address_in_message(&doc); @@ -798,18 +881,38 @@ enum LeftStop { /// [`advertised_template`] read off the frame. It keeps every foreign hop and counts the addresses /// whose query was withheld, as that does. A document that can't be asked for now (too many being /// read) fails the command, as it does for the capabilities: it wasn't read, so it doesn't fall -/// back to the standard tile address. Every fallback to that address is said. -fn left_template(s: &mut Session, source: &str, list: &str, vector: bool, withheld: &mut u32) -> Result { - let read = |doc: &str| match s.left_document(doc) { - Err(e) => Err(LeftStop::Failed(e)), - Ok(None) => Err(LeftStop::Waiting(doc.to_string())), - Ok(Some(read)) => Ok(read), - }; - match walk_template(source, list, vector, withheld, read) { +/// back to the standard tile address. Every fallback to that address is said. With `public` (the +/// service's document was read from the internet), the app reads the documents from there only; +/// so it does after a document it read from there ([`cache::ceiling_for`] records it), and the +/// template is then fetched from there too. +fn left_template( + s: &mut Session, + source: &str, + list: &str, + vector: bool, + withheld: &mut u32, + public: bool, +) -> Result { + let mut public = public; + let walked = walk_template(source, list, vector, withheld, |doc: &str| { + if 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) + } + } + }); + match walked { Ok(mut out) => { 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)), @@ -819,8 +922,8 @@ fn left_template(s: &mut Session, source: &str, list: &str, vector: bool, withhe /// In the browser nothing waits: the app reads the template itself and passes it as `"tiles"`. #[cfg(target_arch = "wasm32")] -fn advertised_template(source: &str, list: &str, _: bool, _: &mut u32) -> AdvertisedTemplate { - AdvertisedTemplate { template: None, crossed_origin: crosses_origin(source, list), fallback: None } +fn advertised_template(source: &str, list: &str, _: bool, _: &mut u32, _: bool) -> AdvertisedTemplate { + AdvertisedTemplate { template: None, crossed_origin: crosses_origin(source, list), fallback: None, public: false } } /// Adds a template resolved off the command thread through the ordinary admitted command. @@ -1147,6 +1250,8 @@ fn add_discovered(s: &mut Session, p: &Value, url: &str, want: &str, found: &Dis } })?; let capability_crossed = source.crossed_origin; + // What a document read from the internet lists is fetched only from there (#1560). + let public = source.public; let source = &*source.address; // A time-enabled layer follows the time slider, at each of its steps, unless a time is asked // for: one of its times (the layer named with it), or "default" (`false`), the service's. @@ -1232,19 +1337,21 @@ fn add_discovered(s: &mut Session, p: &Value, url: &str, want: &str, found: &Dis // An OGC API layer's tiles: the template its tileset advertises (given, or read now), else // the usual path. 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)?), crossed_origin: crosses_origin(source, list) || crosses_origin(list, t), fallback: None, + public: cache::ceiling_for(t) == Reach::Public, }, (Some(list), None) if leaving => { - match left_template(s, source, list, matches!(layer.offer, Offer::VectorTiles { .. }), withheld)? { + match left_template(s, source, list, matches!(layer.offer, Offer::VectorTiles { .. }), withheld, public)? { LeftTemplate::Read(advertised) => advertised, LeftTemplate::Waiting(doc) => return waiting_for(s, &doc), } } (Some(list), None) => { - let advertised = advertised_template(source, list, matches!(layer.offer, Offer::VectorTiles { .. }), withheld); + let advertised = advertised_template(source, list, matches!(layer.offer, Offer::VectorTiles { .. }), withheld, public); if let Some(note) = &advertised.fallback { s.notify(note.clone(), false); } @@ -1252,6 +1359,13 @@ fn add_discovered(s: &mut Session, p: &Value, url: &str, want: &str, found: &Dis } _ => AdvertisedTemplate::default(), }; + let public = public || advertised.public; + // The layer's own requests are made later, by the map: the restriction goes with them. + let restrict = |url: &str| { + if public { + cache::restrict_to_public(url); + } + }; match &layer.offer { Offer::Tiles { template } => { let template = advertised.template.as_deref().unwrap_or(template); @@ -1262,6 +1376,7 @@ fn add_discovered(s: &mut Session, p: &Value, url: &str, want: &str, found: &Dis (Some(t), None) => rustgis_data::ogc::with_time(template, t), (None, None) => template.to_string(), }; + restrict(&template); // With its legends, as its service gives them (none: no key, as before). let mut add = json!({"url": template, "kind": "raster", "name": name, "overlay": true, "bounds": layer.bbox, "connection":p.get("connection")}); // A layer its service draws on request (a WMS, an ArcGIS map service) is asked for @@ -1292,6 +1407,10 @@ fn add_discovered(s: &mut Session, p: &Value, url: &str, want: &str, found: &Dis } // Count pictures left out because their addresses fail the layer's checks. let legends = rustgis_map::tiles::checked_legends(layer.legends.iter().cloned()); + // Fetched later by the Layers pane and the print layout, each within its own record. + for legend in &legends { + restrict(&legend.url); + } let offered = layer.legends.len().min(rustgis_data::ogc::MAX_LEGENDS); s.notify_counted( Some(rustgis_data::loss::LossCode::DroppedLegend), @@ -1337,6 +1456,7 @@ fn add_discovered(s: &mut Session, p: &Value, url: &str, want: &str, found: &Dis Offer::VectorTiles { template, layers } => { let template = advertised.template.as_deref().unwrap_or(template); let crossed_origin = capability_crossed || advertised.crossed_origin || crosses_origin(source, template); + restrict(template); let r = add_tiles( s, &json!({"url": template, "kind": "vector", "name": name, "layers": layers, "overlay": true, "bounds": layer.bbox, "connection":p.get("connection")}), @@ -1349,6 +1469,7 @@ fn add_discovered(s: &mut Session, p: &Value, url: &str, want: &str, found: &Dis // and does not count as content (see `super::map_is_empty`): adding a layer after it frames // the map again. Documented in docs/user-guide/data-formats.md. Offer::Style { url: style } => { + restrict(style); let r = add_tiles( s, &json!({"url": style, "kind": "style", "name": name, "bounds": layer.bbox, "connection":p.get("connection")}), @@ -1371,15 +1492,18 @@ fn add_discovered(s: &mut Session, p: &Value, url: &str, want: &str, found: &Dis None if leaving => { let c = coverage_for(c, anonymous); let described = describe_address(&c); + restrict(&described); let Some(read) = s.left_document(&described).map_err(|e| format!("{}: {e}", c.id))? else { return waiting_for(s, &described); }; let bytes = read.map_err(|e| format!("{}: {e}", c.id))?; let info = rustgis_data::ogc::parse_describe(&c, &bytes)?; - let (get, area) = coverage_request_from(s, p, &c, &info)?; + // Recorded by the read if it came from the internet, as in `coverage_request`. + let public = public || cache::ceiling_for(&described) == Reach::Public; + let (get, area) = coverage_request_from(s, p, &c, &info, public)?; (get, area, described) } - _ => coverage_request(s, p, c, anonymous)?, + _ => coverage_request(s, p, c, anonymous, public)?, }; #[cfg(target_arch = "wasm32")] { @@ -1394,7 +1518,10 @@ fn add_discovered(s: &mut Session, p: &Value, url: &str, want: &str, found: &Dis crate::service_logins::anonymously(s, anonymous, |s| { if leaving { // (Whole: a coverage's address may end in .tif, and it is read as a raster.) - return super::layer::add_url(s, &json!({"url": get, "name": name, "coverage": true, "whole": true})); + return super::layer::add_url( + s, + &json!({"url": get, "name": name, "coverage": true, "whole": true, "fromDocument": public}), + ); } let bytes = crate::render::rustgis_tiles::cache::download_blocking(&get).map_err(|e| format!("{name}: {e}"))?; coverage_check(&name, &bytes)?; @@ -1435,7 +1562,7 @@ fn add_discovered(s: &mut Session, p: &Value, url: &str, want: &str, found: &Dis // A plugin's command: downloaded off the frame as Add From Service does, added, // and its command run again, which is answered here and goes on (#1319). let left = leaving.then(|| { - let mut q = json!({"url": from, "name": name, "service": true}); + let mut q = json!({"url": from, "name": name, "service": true, "fromDocument": public}); if let Some(bounds) = layer.bbox { q["bounds"] = json!(bounds); } @@ -1457,7 +1584,7 @@ fn add_discovered(s: &mut Session, p: &Value, url: &str, want: &str, found: &Dis r } else { let file = |_: &[u8]| Ok(format!("{name}.geojson")); - add_service_layer(s, &json!({"name": name}), &name, from, layer.bbox, false, keep_view, file) + add_service_layer(s, &json!({"name": name}), &name, from, layer.bbox, public, keep_view, file) .map_err(|e| slow_whole_layer(e, given))? }; // Over an area, the features crossing it: the view stays, or goes to a box given @@ -1519,15 +1646,23 @@ fn coverage_area(s: &Session, p: &Value, info: &rustgis_data::ogc::CoverageInfo, /// A coverage's GetCoverage address and the area it covers: its description from `"describe"`, or /// fetched (waiting for it). -fn coverage_request(s: &Session, p: &Value, c: &Coverage, anonymous: bool) -> Result<(String, [f64; 4], String), String> { +/// With `public` (a coverage a document read from the internet lists), its description and its +/// GetCoverage address are fetched only from the internet, here or by the app. +fn coverage_request(s: &Session, p: &Value, c: &Coverage, anonymous: bool, public: bool) -> Result<(String, [f64; 4], String), String> { let c = coverage_for(c, anonymous); let c = c.as_ref(); let describe = describe_address(c); + if public { + cache::restrict_to_public(&describe); + } let info = match ps(p, "describe") { Some(text) => rustgis_data::ogc::parse_describe(c, text.as_bytes())?, None => fetch_describe(c, &describe)?, }; - let (get, area) = coverage_request_from(s, p, c, &info)?; + // A description read from the internet (here, or by the app, which records it) holds the + // GetCoverage request built from it there too, however the endpoint's name resolves then. + let public = public || cache::ceiling_for(&describe) == Reach::Public; + let (get, area) = coverage_request_from(s, p, c, &info, public)?; Ok((get, area, describe)) } @@ -1553,17 +1688,34 @@ fn coverage_request_from( p: &Value, c: &Coverage, info: &rustgis_data::ogc::CoverageInfo, + public: bool, ) -> Result<(String, [f64; 4]), String> { let area = coverage_area(s, p, info, &c.id)?; let get = crate::render::rustgis_tiles::logins::inherit(&c.endpoint, &rustgis_data::ogc::get_coverage_url(c, info, area)); crate::render::rustgis_tiles::address::check(&get, Some(&c.endpoint))?; + if public { + cache::restrict_to_public(&get); + } Ok((get, area)) } +/// Reads a coverage's description, recording one that came from the internet +/// ([`cache::restrict_to_public`]) so the GetCoverage request built from it goes only there. #[cfg(not(target_arch = "wasm32"))] fn fetch_describe(c: &Coverage, describe: &str) -> Result { - let bytes = crate::render::rustgis_tiles::cache::download_blocking(describe).map_err(|e| format!("{}: {e}", c.id))?; - rustgis_data::ogc::parse_describe(c, &bytes) + let fetched = cache::download_blocking_with_origin_within( + describe, + cache::MAX_DOWNLOAD, + cache::BLOCKING_TIMEOUT, + &[], + cache::ceiling_for(describe), + ) + .map_err(cache::large_file_hint) + .map_err(|e| format!("{}: {e}", c.id))?; + if fetched.origin.reach() == Reach::Public { + cache::restrict_to_public(describe); + } + rustgis_data::ogc::parse_describe(c, &fetched.bytes) } #[cfg(target_arch = "wasm32")] @@ -1595,7 +1747,7 @@ fn coverage(s: &mut Session, p: &Value) -> CmdResult { || crosses_origin(&source.address, &c.endpoint) || s.web_logins.is_anonymous() || p.get("anonymous").and_then(Value::as_bool) == Some(true); - let (get, area, describe) = coverage_request(s, p, c, anonymous)?; + let (get, area, describe) = coverage_request(s, p, c, anonymous, source.public)?; let mut out = json!({"url": get, "name": layer.title, "bbox": area, "describe": describe}); if anonymous { out["anonymous"] = json!(true); @@ -1711,7 +1863,7 @@ mod tests { land(&mut s, list, first); let mark = s.notice_mark(); for _ in 0..3 { - match left_template(&mut s, source, list, false, &mut 0).unwrap() { + match left_template(&mut s, source, list, false, &mut 0, false).unwrap() { LeftTemplate::Read(out) => { let said: Vec = s.notices_since(mark).iter().map(|n| n.text.clone()).collect(); return (out.template, said); @@ -1734,6 +1886,60 @@ mod tests { assert!(said.is_empty(), "{said:?}"); } + /// A plugin's `service.add` reads its documents off the frame: one read from the internet, + /// as the read observed it, has what it links to read only from there, the documents its + /// listing names and the tile set documents and template of a layer alike. One read from the + /// local network leaves them as they were. + #[test] + fn documents_read_off_the_frame_hold_what_they_link_to() { + use crate::render::rustgis_tiles::address::Origin; + for observed in [Reach::Public, Reach::Local] { + let host = if observed == Reach::Public { "left-public" } else { "left-local" }; + // What the read gives the command, run again, as the app's fetch observed it. + let land = |s: &mut Session, url: &str, body: Value| { + let origin = Origin::with_observed_reach(url, observed).unwrap(); + let read = crate::cmd::plugins::fetch::document_read( + url, + Ok(cache::Fetched { bytes: serde_json::to_vec(&body).unwrap(), origin }), + ); + let asked = s.asked_for(&json!({"url": url, "document": true})); + let mut added = crate::cmd::plugins::fetch::Added::default(); + added.document = Some(read.unwrap().into()); + s.rerun_landed.push((asked, Ok(json!({})), added)); + }; + let root = format!("https://{host}.example/ogc"); + let caps = rustgis_data::ogc::capabilities_url(&root, Some("ogcapi")); + let next = format!("https://{host}-links.example/collections"); + let mut s = Session::new(crate::Project::default()); + s.call_requests = Some(Vec::new()); + land(&mut s, &caps, json!({"links":[{"rel":"data","type":"application/json","href":next}]})); + let found = read_documents(&mut s, &json!({"url": root, "type": "ogcapi"}), true, None).unwrap(); + assert_eq!(found.next.as_deref(), Some(next.as_str())); + assert_eq!(cache::ceiling_for(&next), observed, "the linked document, its landing page observed {observed:?}"); + + let (source, list) = (format!("https://{host}-api.example/collections"), format!("https://{host}-api.example/relief/tiles")); + let tileset = format!("https://{host}-api.example/relief/tiles/WebMercatorQuad"); + let mut s = Session::new(crate::Project::default()); + s.call_requests = Some(Vec::new()); + land(&mut s, &list, json!({"tilesets":[{"tileMatrixSetId":"WebMercatorQuad","links":[{"rel":"self","href":tileset}]}]})); + let LeftTemplate::Waiting(next) = left_template(&mut s, &source, &list, false, &mut 0, false).unwrap() else { + panic!("it waits for the tile set"); + }; + assert!(next.starts_with(&tileset), "{next}"); + assert_eq!(cache::ceiling_for(&next), observed, "the tile set, its list observed {observed:?}"); + land( + &mut s, + &next, + json!({"links":[{"rel":"item","type":"image/png","href":format!("https://{host}-tiles.example/{{tileMatrix}}/{{tileCol}}/{{tileRow}}.png")}]}), + ); + let LeftTemplate::Read(out) = left_template(&mut s, &source, &list, false, &mut 0, false).unwrap() else { + panic!("the template was read"); + }; + assert!(out.template.is_some_and(|t| t.starts_with(&format!("https://{host}-tiles.example/")))); + assert_eq!(out.public, observed == Reach::Public, "the template, observed {observed:?}"); + } + } + /// A tile list that can't be asked for, with as many documents being read as can be, fails /// the command: it wasn't read, so the layer doesn't go on the standard tile address (#1319). #[test] @@ -1746,7 +1952,7 @@ mod tests { let mark = s.notice_mark(); let mut withheld = 0; let list = "https://x.org/collections/a/map/tiles"; - let Err(e) = left_template(&mut s, "https://x.org/collections", list, false, &mut withheld) else { + let Err(e) = left_template(&mut s, "https://x.org/collections", list, false, &mut withheld, false) else { panic!("it went on to a template"); }; assert!(e.contains("already being read"), "{e}"); @@ -1755,7 +1961,7 @@ mod tests { let mut s = Session::new(crate::sample::world_project()); s.call_requests = Some(Vec::new()); assert!( - matches!(left_template(&mut s, "https://x.org/collections", list, false, &mut withheld), Ok(LeftTemplate::Waiting(d)) if d == list) + matches!(left_template(&mut s, "https://x.org/collections", list, false, &mut withheld, false), Ok(LeftTemplate::Waiting(d)) if d == list) ); } @@ -1913,4 +2119,257 @@ mod tests { } } } + + /// A document a service links to is fetched within the reach its linking document's fetch was + /// observed at: from a landing page on the internet, only the internet, however the links are + /// spelled; from one on this computer or the local network, wherever they point (a self-hosted + /// service linking to its own documents). Its layers carry that reach. + #[test] + fn linked_documents_are_fetched_within_the_reach_of_the_document_linking_them() { + use crate::render::rustgis_tiles::address::Origin; + for observed in [Reach::Public, Reach::Local] { + // Each case its own names: a document read from the internet is recorded as such. + let tag = if observed == Reach::Public { "public" } else { "local" }; + let linked = format!("https://looks-public-{tag}.example/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://service-{tag}.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 }; + // A fetch connects no wider than its ceiling. + let origin = Origin::with_observed_reach(url, observed.min(ceiling))?; + Ok(cache::Fetched { bytes: serde_json::to_vec(body).unwrap_or_default(), origin }) + }) + .unwrap(); + assert_eq!(asked.len(), 2, "{asked:?}"); + assert_eq!(asked[0].1, Reach::Local, "the service's own address is the user's choice"); + assert_eq!(asked[1], (linked.clone(), observed), "observed {observed:?}"); + assert_eq!(found.service.layers.len(), 1); + assert_eq!(found.sources.iter().map(|source| source.public).collect::>(), [observed == Reach::Public]); + } + } + + /// 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). + #[test] + fn documents_read_natively_from_the_internet_are_recorded() { + use crate::render::rustgis_tiles::address::Origin; + for observed in [Reach::Public, Reach::Local] { + let root = format!("https://native-read-{observed:?}.example/collections").to_ascii_lowercase(); + let items = format!("{root}/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": root, "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.sources.len(), 1); + let source = &found.sources[0]; + assert!(source.address.starts_with(&root), "{}", source.address); + assert_eq!(cache::ceiling_for(&source.address), observed, "the listed layer's document, observed {observed:?}"); + } + } + + /// A dataset document linked a second time is not read again, so it keeps the reach its read + /// observed: the documents it links to are fetched within that, whatever the reach of the + /// document that repeated the link. Here a landing on the local network lists a vector tile + /// list and a map tile list; the vector list links back to the map list, which links on to its + /// metadata. + #[test] + fn a_repeated_dataset_document_keeps_the_reach_it_was_read_at() { + use crate::render::rustgis_tiles::address::Origin; + // Where the vector list and the map list were observed; the map list's metadata is asked + // within the map list's reach either way. + for (vector_reach, map_reach) in [(Reach::Local, Reach::Public), (Reach::Public, Reach::Local)] { + // Each case its own names: a document read from the internet is recorded as such. + let tag = if map_reach == Reach::Public { "a" } else { "b" }; + let (vector, map, metadata) = ( + format!("https://vector-list-{tag}.example/tiles?f=json"), + format!("https://map-list-{tag}.example/tiles?f=json"), + format!("https://map-list-{tag}.example/metadata?f=json"), + ); + let (vector, map, metadata) = (vector.as_str(), map.as_str(), metadata.as_str()); + let landing = json!({"links":[{"rel":"tilesets-vector","href":vector},{"rel":"tilesets-map","href":map}]}); + let vector_list = json!({"tilesets":[{"tileMatrixSetId":"WebMercatorQuad","dataType":"vector","links":[ + {"rel":"self","type":"application/json","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!("https://map-list-{tag}.example/map/{{tileMatrix}}/{{tileRow}}/{{tileCol}}.png")}]}); + let mut asked = Vec::new(); + let mut s = Session::new(crate::Project::default()); + let p = json!({"url": "https://service.example/dataset", "type": "ogcapi"}); + let found = read_documents_with(&mut s, &p, false, None, &mut |url, ceiling| { + asked.push((url.to_string(), ceiling)); + let (body, observed) = match url { + u if u == vector => (&vector_list, vector_reach), + u if u == map => (&map_list, map_reach), + u if u == metadata => (&map_metadata, Reach::Local), + _ => (&landing, Reach::Local), + }; + 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 urls = asked.iter().map(|(url, _)| url.as_str()).collect::>(); + assert_eq!(urls, ["https://service.example/dataset?f=json", vector, map, metadata], "the repeat is not fetched"); + assert_eq!(asked[3].1, map_reach, "vector list {vector_reach:?}, map list {map_reach:?}"); + assert!(found.service.notes.iter().any(|n| n.contains("repeated addresses")), "{:?}", found.service.notes); + assert_eq!(found.service.layers.len(), 1, "{:?}", found.service.layers); + assert_eq!(found.sources.iter().map(|source| source.public).collect::>(), [map_reach == Reach::Public]); + } + } + + /// A repeated dataset document keeps its crossed-origin record: the documents its read linked + /// to, read after the repeat, get the saved login only when the path that read it never left + /// the service's origin, whatever path repeated it. Here a landing lists a vector tile list + /// on another origin and a map tile list; the vector list links back to the map list, which + /// links on to its metadata. + #[test] + fn a_repeated_dataset_document_keeps_its_crossed_origin_record() { + use crate::render::rustgis_tiles::address::Origin; + let vector = "https://vector-elsewhere.example/tiles?f=json"; + let metadata_json = |map: &str| { + let metadata = map.replace("/tiles?f=json", "/metadata?f=json"); + let tiles = map.replace("/tiles?f=json", "/map/{tileMatrix}/{tileRow}/{tileCol}.png"); + (metadata, json!({"tileMatrixSetId":"WebMercatorQuad","links":[{"rel":"item","type":"image/png","href":tiles}]})) + }; + // The map list on the service's own origin, read without leaving it; then on another. + for (map, crossed) in + [("https://crossed-record.example/maps/tiles?f=json", false), ("https://maps-elsewhere.example/tiles?f=json", true)] + { + let (metadata, map_metadata) = metadata_json(map); + let landing = json!({"links":[{"rel":"tilesets-vector","href":vector},{"rel":"tilesets-map","href":map}]}); + let vector_list = json!({"tilesets":[{"tileMatrixSetId":"WebMercatorQuad","dataType":"vector","links":[ + {"rel":"self","type":"application/json","href":map}]}]}); + let map_list = json!({"tilesets":[{"tileMatrixSetId":"WebMercatorQuad","dataType":"map","links":[ + {"rel":"self","type":"application/json","href":metadata}]}]}); + let mut asked = Vec::new(); + let mut s = Session::new(crate::Project::default()); + let p = json!({"url": "https://crossed-record.example/dataset", "type": "ogcapi"}); + let found = read_documents_with(&mut s, &p, false, None, &mut |url, ceiling| { + asked.push(url.to_string()); + let body = match url { + u if u == vector => &vector_list, + u if u == map => &map_list, + u if u == metadata => &map_metadata, + _ => &landing, + }; + let origin = Origin::with_observed_reach(url, Reach::Local.min(ceiling))?; + Ok(cache::Fetched { bytes: serde_json::to_vec(body).unwrap_or_default(), origin }) + }) + .unwrap(); + assert_eq!( + asked, + ["https://crossed-record.example/dataset?f=json", vector, map, metadata.as_str()], + "the repeat is not fetched" + ); + assert!(found.service.notes.iter().any(|n| n.contains("repeated addresses")), "{:?}", found.service.notes); + assert_eq!(found.service.layers.len(), 1, "{:?}", found.service.layers); + assert_eq!(found.sources.iter().map(|source| source.crossed_origin).collect::>(), [crossed], "{map}"); + } + } + + /// The legend pictures a layer from a document read from the internet lists are fetched only + /// from there, as its tiles are, whatever their names resolve to: the Layers pane and the print + /// layout fetch them later, each within its address's record. One from the local network's + /// document leaves them as they were. + #[test] + fn legends_listed_by_a_document_read_from_the_internet_are_held_there() { + for public in [true, false] { + let host = if public { "legend-public" } else { "legend-local" }; + let wms = format!("https://{host}.example/wms"); + let legend = format!("https://{host}-legend.example/legend.png"); + if public { + cache::restrict_to_public(&rustgis_data::ogc::capabilities_url(&wms, Some("wms"))); + } + let text = format!( + r#" +Test WMS +image/png +RootEPSG:3857roadsRoads + +"# + ); + let mut s = Session::new(crate::Project::default()); + s.run("service.add", &json!({"url": wms, "type": "wms", "layer": "roads", "text": text})).unwrap(); + let legends = s.map().tiles.last().map(|t| t.legends.iter().map(|l| l.url.clone()).collect::>()).unwrap_or_default(); + assert_eq!(legends, [legend.as_str()], "{host}"); + assert_eq!(cache::ceiling_for(&legend) == Reach::Public, public, "{legend}"); + } + } + + /// A coverage's GetCoverage request is built from its description: one read from the internet + /// (recorded, as the app and the native read record it) restricts the request to the internet + /// even when the capabilities listing the coverage came from the local network, so the + /// endpoint's name can't resolve locally when the request is sent. One read locally leaves it. + #[test] + fn a_coverage_description_read_from_the_internet_holds_its_request() { + let caps = r#" + Soils + socSoil carbon + 5 49.25.8 50 + "#; + let describe = r#" + 49.2 550 5.8"#; + for public in [true, false] { + let url = format!("https://coverage-described-{public}.example/wcs"); + let p = json!({"url": url, "layer": "soc", "text": caps, "describe": describe, "bbox": "full"}); + let mut s = Session::new(crate::Project::default()); + let first = s.run("service.coverage", &p).unwrap(); + assert_eq!(cache::ceiling_for(first["url"].as_str().unwrap()), Reach::Local, "the capabilities are the user's own"); + if public { + cache::restrict_to_public(first["describe"].as_str().unwrap()); + } + let c = s.run("service.coverage", &p).unwrap(); + let get = c["url"].as_str().unwrap(); + assert!(get.contains("GetCoverage"), "{get}"); + assert_eq!(cache::ceiling_for(get) == Reach::Public, public, "{get}"); + } + } + + /// The app fetches what a listing names next, and records a document it read from the + /// internet ([`cache::restrict_to_public`]): the next document is then restricted to the + /// internet for the app's fetch, and a layer the document lists is added restricted too. A + /// document the app read from the local network restricts neither. + #[test] + fn documents_the_app_read_from_the_internet_restrict_what_they_link_to() { + for public in [true, false] { + let host = if public { "recorded-public" } else { "recorded-local" }; + let root = format!("https://{host}.example/ogc"); + let next = format!("https://{host}-links.example/collections"); + let caps = rustgis_data::ogc::capabilities_url(&root, Some("ogcapi")); + if public { + cache::restrict_to_public(&caps); + } + let landing = json!({"links":[{"rel":"data","type":"application/json","href":next}]}).to_string(); + let mut s = Session::new(crate::Project::default()); + let listing = s.run("service.layers", &json!({"url": root, "type": "ogcapi", "text": landing})).unwrap(); + assert_eq!(listing["next"], json!(next)); + assert_eq!(cache::ceiling_for(&next) == Reach::Public, public, "{host}"); + + let wms = format!("https://{host}-wms.example/wms"); + let caps = rustgis_data::ogc::capabilities_url(&wms, Some("wms")); + if public { + cache::restrict_to_public(&caps); + } + let text = format!( + r#" +Test WMS +image/png +RootEPSG:3857roadsRoads"# + ); + s.run("service.add", &json!({"url": wms, "type": "wms", "layer": "roads", "text": text})).unwrap(); + let added = s.map().tiles.last().map(|t| t.url.clone()).unwrap_or_default(); + assert!(added.contains(&format!("{host}-map.example")), "{added}"); + assert_eq!(cache::ceiling_for(&added) == Reach::Public, public, "{added}"); + } + } } diff --git a/crates/engine/src/cmd/service_group.rs b/crates/engine/src/cmd/service_group.rs index facfc7634b..f8c79f6c7f 100644 --- a/crates/engine/src/cmd/service_group.rs +++ b/crates/engine/src/cmd/service_group.rs @@ -99,14 +99,16 @@ fn record_connection(s: &mut Session, layer: u32, request: &Value, anonymous: bo } fn plan(s: &mut Session, p: &Value) -> CmdResult { - let mut out = if p.get("sourceOnly").and_then(Value::as_bool) == Some(true) { request(s, p)? } else { listing(s, p)? }; + let mut out = if p.get("sourceOnly").and_then(Value::as_bool) == Some(true) { request(s, p)? } else { listing(s, p)?.0 }; if !s.policy_user() { crate::sources::redact_url_fields(&mut out); } Ok(out) } -fn listing(s: &mut Session, p: &Value) -> CmdResult { +/// The service's collections to import, and for each whether the document listing it was read +/// from the internet (its features are then fetched only from there). +fn listing(s: &mut Session, p: &Value) -> Result<(Value, Vec), String> { let q = request(s, p)?; let mut found = capabilities(s, &q)?; super::notify_withheld(s, found.service.withheld_addresses); @@ -167,6 +169,7 @@ fn listing(s: &mut Session, p: &Value) -> CmdResult { offered = pos.and_then(|i| offered.into_iter().nth(i)).into_iter().collect(); } let (selected, sources): (Vec<_>, Vec<_>) = offered.into_iter().unzip(); + let public = sources.iter().map(|source| source.public).collect(); if found.next.is_none() && child.is_some() && selected.is_empty() { return Err("the collection is no longer advertised by this service".into()); } @@ -186,21 +189,21 @@ fn listing(s: &mut Session, p: &Value) -> CmdResult { } else if let Some(connection) = q.get("connection").filter(|v| !v.is_null()) { out["request"]["connection"] = connection.clone(); } - Ok(out) + Ok((out, public)) } #[cfg(not(target_arch = "wasm32"))] -fn download(s: &mut Session, name: &str, url: &str, max: usize) -> Result, String> { - super::download_features(s, name, url, max) +fn download(s: &mut Session, name: &str, url: &str, max: usize, public: bool) -> Result, String> { + super::download_features(s, name, url, max, public) } #[cfg(target_arch = "wasm32")] -fn download(_: &mut Session, _: &str, _: &str, _: usize) -> Result, String> { +fn download(_: &mut Session, _: &str, _: &str, _: usize, _: bool) -> Result, String> { Err("the browser must supply downloaded feature responses".into()) } fn read(s: &mut Session, p: &Value) -> Result<(Value, Vec<(ServiceChild, Dataset, bool)>), String> { - let listing = listing(s, p)?; + let (listing, public) = listing(s, p)?; if listing.get("next").is_some() { return Err("complete service discovery before importing or refreshing".into()); } @@ -211,7 +214,9 @@ fn read(s: &mut Session, p: &Value) -> Result<(Value, Vec<(ServiceChild, Dataset } let mut bytes_read = 0usize; let mut reads = Vec::new(); - for layer in layers { + // `listing` returns one reach per layer it lists (`service_json` writes one entry per layer), + // so the two never differ in length. + for (layer, public) in layers.iter().zip(public) { let name = ps(layer, "title").unwrap_or("Collection"); let url = layer.get("offer").and_then(|o| ps(o, "url")).ok_or("missing features address")?; let bytes = match responses { @@ -226,7 +231,7 @@ fn read(s: &mut Session, p: &Value) -> Result<(Value, Vec<(ServiceChild, Dataset } text.as_bytes().to_vec() } - None => download(s, name, url, MAX_GROUP_BYTES.saturating_sub(bytes_read))?, + None => download(s, name, url, MAX_GROUP_BYTES.saturating_sub(bytes_read), public)?, }; bytes_read = bytes_read.saturating_add(bytes.len()); if bytes_read > MAX_GROUP_BYTES { diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 99a32d25f9..d8bfcc510c 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -25482,13 +25482,13 @@ fn arcgis_description_leaves_the_features_their_budget() { let server = Server::new(vec![Route::new(&format!("{layer}/query"), &answer), Route::new(layer, &arcgis_layer(2, false))]); let url = format!("{}{layer}/query?where=1%3D1&outFields=*&f=geojson", server.base); let mut s = Session::new(Project::default()); - let bytes = crate::cmd::service::download_features(&mut s, "Zoning", &url, answer.len()).unwrap(); + let bytes = crate::cmd::service::download_features(&mut s, "Zoning", &url, answer.len(), false).unwrap(); let read: Value = serde_json::from_slice(&bytes).unwrap(); assert_eq!(read["features"].as_array().map(Vec::len), Some(2)); let asked: Vec<_> = server.requests().iter().map(|r| r.path.trim_start_matches(layer).to_string()).collect(); assert_eq!(asked, ["", "/query"]); // A byte less and the features don't fit. - assert!(crate::cmd::service::download_features(&mut s, "Zoning", &url, answer.len() - 1).is_err()); + assert!(crate::cmd::service::download_features(&mut s, "Zoning", &url, answer.len() - 1, false).is_err()); } /// An ArcGIS layer's description larger than its cap is given up on: the layer's query is @@ -25505,7 +25505,7 @@ fn arcgis_description_past_its_cap_leaves_the_query_as_it_is() { let url = format!("{}{layer}/query?where=1%3D1&outFields=*&f=geojson", server.base); let mut s = Session::new(Project::default()); let max = crate::render::rustgis_tiles::cache::MAX_DOWNLOAD; - let bytes = crate::cmd::service::download_features(&mut s, "Zoning", &url, max).unwrap(); + let bytes = crate::cmd::service::download_features(&mut s, "Zoning", &url, max, false).unwrap(); let read: Value = serde_json::from_slice(&bytes).unwrap(); assert_eq!(read["features"].as_array().map(Vec::len), Some(2)); let asked: Vec<_> = server diff --git a/crates/tiles/src/address.rs b/crates/tiles/src/address.rs index db24c8bb39..b1b1b99e17 100644 --- a/crates/tiles/src/address.rs +++ b/crates/tiles/src/address.rs @@ -4,8 +4,8 @@ //! point at this computer or the local network: a self-hosted tile server. Addresses that come //! from somewhere else (inside a style or TileJSON document, or a redirect) may not reach into //! the local network unless the document itself came from there, so a style found on the web -//! can't make the app probe local services. Link-local addresses, where cloud metadata services -//! answer, are never fetched. +//! can't make the app probe local services. Link-local addresses and the other addresses cloud +//! metadata services answer at are never fetched. //! //! These spelling checks also run after template expansion. Native fetchers additionally //! filter the resolved IPs before connecting: a public document cannot select a local @@ -119,8 +119,19 @@ fn host(url: &str) -> Option { Some(host.trim_end_matches('.').to_ascii_lowercase()) } +/// Cloud instance metadata services at addresses outside the link-local ranges (every link-local +/// address is forbidden on its own): one unique-local IPv6 and one carrier-grade NAT address. Only +/// these two: the ranges around them stay local, for self-hosted servers there. +const METADATA: [IpAddr; 2] = + [IpAddr::V6(Ipv6Addr::new(0xfd00, 0x0ec2, 0, 0, 0, 0, 0, 0x0254)), IpAddr::V4(Ipv4Addr::new(100, 100, 100, 200))]; + /// How far an IP address reaches. pub fn ip_reach(ip: IpAddr) -> Reach { + // For the IPv6 metadata address. The IPv4 one is also checked in `v4_reach`, which every + // spelling of it reaches (mapped, NAT64, IPv4-compatible, 6to4, the `inet_aton` forms in `reach`). + if METADATA.contains(&ip) { + return Reach::Forbidden; + } match ip { IpAddr::V4(v4) => v4_reach(v4), IpAddr::V6(v6) => { @@ -132,6 +143,15 @@ pub fn ip_reach(ip: IpAddr) -> Reach { if let [0x64, 0xff9b, 0, 0, 0, 0, hi, lo] = v6.segments() { return v4_reach(Ipv4Addr::from((u32::from(hi) << 16) | u32::from(lo))); } + // IPv4-compatible (`::a.b.c.d`, RFC 4291 §2.5.5.1) and 6to4 (`2002:a.b.c.d::/48`, + // RFC 3056) addresses embed one too. `::` and `::1` keep their own arms below. + match v6.segments() { + [0, 0, 0, 0, 0, 0, hi, lo] if hi != 0 || lo > 1 => { + return v4_reach(Ipv4Addr::from((u32::from(hi) << 16) | u32::from(lo))); + } + [0x2002, hi, lo, ..] => return v4_reach(Ipv4Addr::from((u32::from(hi) << 16) | u32::from(lo))), + _ => {} + } let seg0 = v6.segments().first().copied().unwrap_or(0); if v6.is_unspecified() || (seg0 & 0xffc0) == 0xfe80 { Reach::Forbidden @@ -145,7 +165,7 @@ pub fn ip_reach(ip: IpAddr) -> Reach { } fn v4_reach(v4: Ipv4Addr) -> Reach { - if v4.is_unspecified() || v4.is_link_local() || v4.is_broadcast() { + if v4.is_unspecified() || v4.is_link_local() || v4.is_broadcast() || METADATA.contains(&IpAddr::V4(v4)) { Reach::Forbidden } else if v4.is_loopback() || v4.is_private() || (v4.octets()[0] == 100 && (v4.octets()[1] & 0xc0) == 64) { // 100.64.0.0/10 (carrier-grade NAT) counts as local too. @@ -313,6 +333,40 @@ mod tests { } } + /// IPv4-compatible (`::a.b.c.d`) and 6to4 (`2002:a.b.c.d::`) addresses keep the reach of the + /// IPv4 address they embed; `::1` stays loopback and `::` unspecified. + #[test] + fn embedded_ipv4_destinations_keep_their_reach() { + for (v4, expected) in [ + ("100.100.100.200", Reach::Forbidden), + ("169.254.169.254", Reach::Forbidden), + ("127.0.0.1", Reach::Local), + ("10.0.0.1", Reach::Local), + ("203.0.113.1", Reach::Public), + ] { + let ip: Ipv4Addr = v4.parse().unwrap(); + let [a, b, c, d] = ip.octets(); + let six_to_four = Ipv6Addr::new(0x2002, u16::from_be_bytes([a, b]), u16::from_be_bytes([c, d]), 0, 0, 0, 0, 1); + for peer in [format!("::{v4}").parse::().unwrap(), IpAddr::V6(six_to_four)] { + let url = format!("http://[{peer}]/tile"); + assert_eq!(ip_reach(peer), expected, "{peer}"); + assert_eq!(reach(&url), expected, "{url}"); + assert_eq!(check(&url, None).is_ok(), expected != Reach::Forbidden, "{url}"); + assert_eq!(check(&url, Some("https://public.example/style.json")).is_ok(), expected == Reach::Public, "{url}"); + let observed = Origin::connected("https://dns.example/tile", peer); + if expected == Reach::Forbidden { + assert!(observed.is_err(), "DNS cannot hide a forbidden embedded peer {peer}"); + } else { + assert_eq!(observed.unwrap().reach, expected, "{peer}"); + } + } + } + assert_eq!(ip_reach(Ipv6Addr::LOCALHOST.into()), Reach::Local); + assert_eq!(reach("http://[::1]/"), Reach::Local); + assert_eq!(ip_reach(Ipv6Addr::UNSPECIFIED.into()), Reach::Forbidden); + assert_eq!(reach("http://[::]/"), Reach::Forbidden); + } + #[test] fn judges_addresses() { assert_eq!(reach("https://tile.openstreetmap.org/1/0/0.png"), Reach::Public); @@ -339,6 +393,31 @@ mod tests { assert_eq!(reach("http://tiles.example.com/"), Reach::Public); } + /// The two metadata addresses outside the link-local ranges are never fetched, however they + /// are spelled; their neighbours stay local (self-hosted servers on those ranges keep working). + #[test] + fn cloud_metadata_addresses_are_forbidden_and_their_ranges_stay_local() { + for url in [ + "http://[fd00:ec2::254]/latest/meta-data/", + "http://[::ffff:100.100.100.200]/", + "http://100.100.100.200/latest/meta-data/", + "http://[64:ff9b::6464:64c8]/", + "http://[::100.100.100.200]/", + "http://[2002:6464:64c8::1]/", + "http://1684301000/", + ] { + assert_eq!(reach(url), Reach::Forbidden, "{url}"); + assert!(check(url, None).is_err(), "{url}"); + } + for peer in ["fd00:ec2::254", "100.100.100.200", "::100.100.100.200", "2002:6464:64c8::1"] { + assert!(Origin::connected("https://selected.example/", peer.parse().unwrap()).is_err(), "{peer}"); + } + for url in ["http://[fd00:ec2::253]/", "http://[fd12:3456::1]/", "http://100.100.100.201/", "http://100.64.0.1/"] { + assert_eq!(reach(url), Reach::Local, "{url}"); + assert!(check(url, None).is_ok(), "{url}"); + } + } + #[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/cache.rs b/crates/tiles/src/cache.rs index eb85437ffc..ff440849fb 100644 --- a/crates/tiles/src/cache.rs +++ b/crates/tiles/src/cache.rs @@ -1751,6 +1751,36 @@ pub fn download_detailed(url: &str, max: usize, done: DoneDetailed) { download_detailed_within(url, max, DOWNLOAD_TIMEOUT, &[], done); } +/// Like [`download_detailed`], preserving the final post-redirect [`crate::address::Origin`] and +/// observed network reach alongside the bytes: for a service's document, whose links reach only as +/// far as it did. +pub fn download_detailed_with_origin(url: &str, max: usize, done: DoneFetchedDetailed) { + download_fetched_reaching(url, max, DOWNLOAD_TIMEOUT, &[], Reaching::Any, done); +} + +/// Like [`download_within`], preserving the final post-redirect [`crate::address::Origin`] and +/// observed network reach alongside the bytes. +pub fn download_within_with_origin(url: &str, max: usize, timeout: std::time::Duration, done: FetchedDone) { + download_fetched_reaching(url, max, timeout, &[], Reaching::Any, Box::new(move |r| done(r.map_err(|f| f.message)))); +} + +/// Like [`download_limited`], connecting no wider than `ceiling` and giving up after `timeout` +/// natively (the usual download's when none), preserving the final post-redirect +/// [`crate::address::Origin`] and observed network reach alongside the bytes: a paged read's +/// next page is held to where the page before it was read, without recording its address +/// ([`restrict_to_public`]). +pub fn download_limited_reaching_with_origin( + url: &str, + max: usize, + timeout: Option, + ceiling: crate::address::Reach, + done: FetchedDone, +) { + let reaching = if ceiling == crate::address::Reach::Public { Reaching::Public } else { Reaching::Any }; + let timeout = timeout.unwrap_or(DOWNLOAD_TIMEOUT); + download_fetched_reaching(url, max, timeout, &[], reaching, Box::new(move |r| done(r.map_err(|f| f.message)))); +} + /// Like [`download`], preserving the final post-redirect [`crate::address::Origin`] and observed /// network reach alongside the downloaded bytes. pub fn download_with_origin(url: &str, done: FetchedDone) { @@ -1799,7 +1829,8 @@ enum Reaching { Public, } -type DoneFetchedDetailed = Box) + Send>; +/// Called once with a download's bytes and where they came from, or what is known of its failure. +pub type DoneFetchedDetailed = Box) + Send>; /// Like [`download_detailed`], giving up after `timeout` natively; a status in `omit` isn't /// recorded as a failure. diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index 7a3cdde196..7a144513ce 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -4,6 +4,7 @@ use egui::{Align2, vec2}; use rustgis_engine::Session; use rustgis_engine::cmd::service_added::Removal; +use rustgis_engine::render::rustgis_tiles::{address::Reach, cache}; use serde_json::{Value, json}; use std::collections::hash_map::DefaultHasher; use std::hash::{Hash, Hasher}; @@ -1877,6 +1878,12 @@ fn add_service(app: &mut RustGisApp, ui: &mut egui::Ui) -> bool { // Into a directory's folder or service, keeping the way back; or back out of it. let here = app.ui.service.as_ref().map(|c| (c.url.clone(), c.kind)); if let (Some(url), Some(here)) = (open, here) { + // A directory read from the internet lists folders and services there only. + use rustgis_engine::data::ogc::capabilities_url; + let kind_of = |kind: &'static str| (kind != "auto").then_some(kind); + if cache::ceiling_for(&capabilities_url(&here.0, kind_of(here.1))) == Reach::Public { + cache::restrict_to_public(&capabilities_url(&url, Some("arcgis"))); + } let before = app.ui.service_browse.back.clone(); let mut way = before.clone(); way.push(here); diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index de6e79c097..27948b33ee 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -140,6 +140,7 @@ mod zarrui; use rustgis_engine::cmd::service_added::Removal; use rustgis_engine::render::rustgis_tiles::failure::Failure; +use rustgis_engine::render::rustgis_tiles::{address::Reach, cache}; use rustgis_engine::{Project, Session}; use serde_json::{Value, json}; @@ -659,14 +660,36 @@ pub(crate) fn fetch_into(url: &str) -> Slot, String>> { fetch_into_limited(url, rustgis_engine::render::rustgis_tiles::cache::MAX_DOWNLOAD) } -/// Like [`fetch_into`], with what is known of a failure (#509). +/// Fetches a service's document as [`fetch_into`] does, with what is known of a failure (#509). +/// One that came from the internet, wherever its name pointed, is recorded so +/// ([`restrict_to_public`](rustgis_engine::render::rustgis_tiles::cache::restrict_to_public)): +/// the documents it links to and the layers it lists are then fetched only from there. pub(crate) fn fetch_detailed_into(url: &str) -> Slot, Failure>> { - let slot: Slot, Failure>> = Slot::default(); + fetch_document_as(url, |failure| failure) +} + +/// [`fetch_detailed_into`], with a failure's message alone. +pub(crate) fn fetch_document_into(url: &str) -> Slot, String>> { + fetch_document_as(url, |failure| failure.message) +} + +/// [`fetch_detailed_into`], its failure told as `told` gives it. +fn fetch_document_as(url: &str, told: fn(Failure) -> E) -> Slot, E>> { + let slot: Slot, E>> = Slot::default(); let land = slot.clone(); - rustgis_engine::render::rustgis_tiles::cache::download_detailed( + let asked = url.to_string(); + cache::download_detailed_with_origin( url, - rustgis_engine::render::rustgis_tiles::cache::MAX_DOWNLOAD, - Box::new(move |r| *land.lock().unwrap_or_else(|e| e.into_inner()) = Some(r)), + cache::MAX_DOWNLOAD, + Box::new(move |r| { + let r = r.map_err(told).map(|fetched| { + if fetched.origin.reach() == Reach::Public { + cache::restrict_to_public(&asked); + } + fetched.bytes + }); + *land.lock().unwrap_or_else(|e| e.into_inner()) = Some(r); + }), ); slot } @@ -6427,8 +6450,12 @@ impl RustGisApp { 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 { + cache::restrict_to_public(&next); + } resolve.doc = next; - resolve.slot = fetch_into(&resolve.doc); + resolve.slot = fetch_document_into(&resolve.doc); } Err(e) => { self.notice_service_query_loss(resolve.withheld_addresses); @@ -6445,6 +6472,11 @@ impl RustGisApp { rustgis_engine::render::rustgis_tiles::logins::inner(&resolve.fallback), ), }; + // 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 { + cache::restrict_to_public(&template); + } resolve.crossed_origin |= rustgis_engine::render::rustgis_tiles::logins::origin(&resolve.doc) != rustgis_engine::render::rustgis_tiles::logins::origin(&template); self.notice_service_query_loss(resolve.withheld_addresses); @@ -6484,6 +6516,10 @@ impl RustGisApp { let connection = params.as_object_mut().and_then(|p| p.remove("connection")); let get = c.get("url").and_then(Value::as_str).unwrap_or("").to_string(); let mut p = json!({"url": get, "name": title, "coverage": true}); + // Its service's document came from the internet: so does the coverage. + if cache::ceiling_for(&get) == Reach::Public { + p["fromDocument"] = json!(true); + } if params.get("anonymous").and_then(Value::as_bool) == Some(true) || c.get("anonymous").and_then(Value::as_bool) == Some(true) { diff --git a/crates/ui-egui/src/pluginpanel.rs b/crates/ui-egui/src/pluginpanel.rs index b7b9a1d0c1..f0eeeb084d 100644 --- a/crates/ui-egui/src/pluginpanel.rs +++ b/crates/ui-egui/src/pluginpanel.rs @@ -2187,7 +2187,8 @@ mod tests { assert_eq!(taken.len(), 1); let id = app.session.download_started_for(&taken[0]).unwrap(); let landed = crate::serviceui::Landed { id, url: url.to_string(), params: taken[0].params().clone(), origin: None }; - crate::serviceui::go_on(&mut app, landed, 0, rustgis_engine::data::ogc::Step::Failed("its second page failed".into())); + let local = rustgis_engine::render::rustgis_tiles::address::Reach::Local; + crate::serviceui::go_on(&mut app, landed, 0, local, rustgis_engine::data::ogc::Step::Failed("its second page failed".into())); let ran = app.session.poll_plugin_retries(); assert_eq!(ran.len(), 1, "{ran:?}"); assert!(ran[0].1.as_ref().is_err_and(|e| e.contains("its second page failed")), "{ran:?}"); diff --git a/crates/ui-egui/src/serviceui.rs b/crates/ui-egui/src/serviceui.rs index 3c70fc20f0..abf43843ef 100644 --- a/crates/ui-egui/src/serviceui.rs +++ b/crates/ui-egui/src/serviceui.rs @@ -2,8 +2,9 @@ //! engine commands; this state machine supplies their downloaded documents and preserves the //! saved connection or anonymous provenance through every deferred add. -use crate::{RustGisApp, Slot, fetch_into, fetch_into_limited, i18n}; +use crate::{RustGisApp, Slot, fetch_document_into, fetch_into_limited, i18n}; use rustgis_engine::data::ogc::{self, Pages, Step}; +use rustgis_engine::render::rustgis_tiles::{address::Reach, cache}; use serde_json::{Value, json}; use std::collections::VecDeque; @@ -79,7 +80,9 @@ pub struct Import { slot: Slot, String>>, document: Option, current: Option, - remaining: VecDeque, + /// The collections still to fetch, each with whether the document listing it was read from + /// the internet ([`from_public`]). + remaining: VecDeque<(String, bool)>, responses: Vec, bytes: usize, } @@ -174,6 +177,7 @@ pub(crate) fn add_layer_from( connection: Option<&str>, ) -> Result { let anonymous = l.get("anonymous").and_then(Value::as_bool) == Some(true); + let public = from_public(l); let connection = connection_for(app, connection, &src.url).filter(|_| !anonymous); let name = l.get("name").and_then(Value::as_str).unwrap_or("").to_string(); let title = l.get("title").and_then(Value::as_str).unwrap_or(&name).to_string(); @@ -206,6 +210,9 @@ pub(crate) fn add_layer_from( if asked.is_some() { params["zoom"] = json!(false); } + if public { + params["fromDocument"] = json!(true); + } return crate::connectiontree::run_add_url(app, params, origin).map(|_| downloading(&title)); } let origin = origin.map(str::to_string); @@ -226,7 +233,11 @@ pub(crate) fn add_layer_from( } else { request_from(app, connection, &src.url, &describe)? }; - let slot = crate::fetch_into(&describe); + if public { + 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 }); return Ok(describing(&title)); } @@ -256,7 +267,11 @@ pub(crate) fn add_layer_from( } else { request_from(app, connection, &src.url, list)? }; - let slot = crate::fetch_into(&list); + if public { + 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 resolve = crate::TilesResolve { params: p, list: list.clone(), @@ -283,6 +298,16 @@ pub(crate) fn add_layer_from( } } +/// Whether the document a listed layer `l` comes from (its `source_url`) was read from the +/// internet, as the app's fetch or the service's discovery recorded it: what the layer needs is +/// then fetched only from there, wherever its names point. Every layer `service.layers` lists has +/// a `source_url` (`layer_source` sets it for each one, which is the only way a listed layer +/// reaches here), so `false` for one without it is never a document's layer passed off as the +/// user's. +pub(crate) fn from_public(l: &Value) -> bool { + l.get("source_url").and_then(Value::as_str).is_some_and(|source| cache::ceiling_for(source) == Reach::Public) +} + /// Starts grouped discovery under its original request, retaining the import target and byte budget. pub fn start(app: &mut RustGisApp, p: &Value, refresh: bool) -> Result<(), String> { if !p.is_object() { @@ -341,7 +366,7 @@ pub fn start(app: &mut RustGisApp, p: &Value, refresh: bool) -> Result<(), Strin return Err(e); } }; - task.slot = fetch_into(&caps); + task.slot = fetch_document_into(&caps); task.document = Some(caps); } app.dialogs.error = None; @@ -374,7 +399,7 @@ impl Import { } if let Some(next) = listing.get("next").and_then(Value::as_str) { let next = self.request(next)?; - self.slot = fetch_into(&next); + self.slot = fetch_document_into(&next); self.document = Some(next); } else { self.remaining = listing @@ -382,7 +407,7 @@ impl Import { .and_then(Value::as_array) .into_iter() .flatten() - .filter_map(|l| l.get("offer").and_then(|o| o.get("url")).and_then(Value::as_str).map(str::to_string)) + .filter_map(|l| l.get("offer").and_then(|o| o.get("url")).and_then(Value::as_str).map(|u| (u.to_string(), from_public(l)))) .collect(); self.next()?; } @@ -391,11 +416,21 @@ impl Import { /// Fetches one exact planned collection within the remaining shared byte budget. fn next(&mut self) -> Result<(), String> { - self.current = self.remaining.pop_front(); - if let Some(url) = &self.current { - let url = self.request(url)?; - self.slot = fetch_into_limited(&url, rustgis_engine::cmd::service::MAX_GROUP_BYTES.saturating_sub(self.bytes)); - } + let Some((url, public)) = self.remaining.pop_front() else { + self.current = None; + return Ok(()); + }; + let asked = self.request(&url)?; + let max = rustgis_engine::cmd::service::MAX_GROUP_BYTES.saturating_sub(self.bytes); + self.slot = if public { + let slot = Slot::default(); + let land = slot.clone(); + cache::download_public_limited(&asked, max, Box::new(move |r| *land.lock().unwrap_or_else(|e| e.into_inner()) = Some(r))); + slot + } else { + fetch_into_limited(&asked, max) + }; + self.current = Some(url); Ok(()) } @@ -502,7 +537,10 @@ pub struct PageRead { /// The bytes the answers still to come may take (the download's budget, less the features /// read). left: usize, - slot: Slot, String>>, + /// The widest network reach the answer was asked within; once it lands, where it was read + /// ([`go_on`]). + reach: Reach, + slot: Slot, Reach), String>>, /// When the answer was asked for: a layer's description that hangs is given up on. asked: web_time::Instant, } @@ -512,7 +550,7 @@ pub struct PageRead { /// them, in pages. pub(crate) fn read_pages(app: &mut RustGisApp, landed: Landed) { let step = ogc::begin_with_pbf(&landed.url, ogc::max_paged_features()); - go_on(app, landed, rustgis_engine::render::rustgis_tiles::cache::MAX_DOWNLOAD, step); + go_on(app, landed, rustgis_engine::render::rustgis_tiles::cache::MAX_DOWNLOAD, Reach::Local, step); } /// How its ArcGIS service draws the layer being read, from its description, goes with it to be @@ -531,17 +569,19 @@ fn drawn(app: &mut RustGisApp, landed: &mut Landed, step: &mut Step) { } } -/// A bounded description or retryable feature page fetched off the frame. Native downloads -/// end at the timeout; the browser's late answer is discarded by the polling read. -fn fetch_within(url: &str, max: usize, timeout: std::time::Duration) -> Slot, String>> { - let slot: Slot, String>> = Slot::default(); +/// 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(); - rustgis_engine::render::rustgis_tiles::cache::download_within( - url, - max, - timeout, - Box::new(move |r| *land.lock().unwrap_or_else(|e| e.into_inner()) = Some(r)), - ); + 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 } @@ -571,9 +611,11 @@ pub fn poll_pages(app: &mut RustGisApp, ctx: &egui::Context) { match answer { Some(answer) => { // The description isn't the features: it leaves them the whole budget. - let left = if describing { read.left } else { read.left.saturating_sub(answer.as_ref().map_or(0, Vec::len)) }; - let step = (*read.pages).land(answer); - go_on(app, read.landed, left, step); + let left = if describing { read.left } else { read.left.saturating_sub(answer.as_ref().map_or(0, |(b, _)| b.len())) }; + // Where the answer was read; one that failed leaves the reach it was asked within. + let reach = answer.as_ref().map_or(read.reach, |(_, reach)| *reach); + let step = (*read.pages).land(answer.map(|(bytes, _)| bytes)); + go_on(app, read.landed, left, reach, step); } None => app.ui.service_pages.push(read), } @@ -583,11 +625,12 @@ pub fn poll_pages(app: &mut RustGisApp, ctx: &egui::Context) { } } -/// The address a paged read fetches next. Its login comes only from the page that led to it -/// (the referrer), so a page reached through another origin stays anonymous even when it points -/// back at the first page's origin. -fn next_request(app: &mut RustGisApp, params: &Value, pages: &Pages) -> Result { - rustgis_engine::render::rustgis_tiles::address::check(pages.next_url(), Some(pages.referrer()))?; +/// The address a paged read fetches next, judged within `reach`, where the page before it was +/// read (not by how that page's address is spelled). Its login comes only from the page that led +/// to it (the referrer), so a page reached through another origin stays anonymous even when it +/// points back at the first page's origin. +fn next_request(app: &mut RustGisApp, params: &Value, pages: &Pages, reach: Reach) -> Result { + rustgis_engine::render::rustgis_tiles::address::check_reach(pages.next_url(), reach)?; if params.get("anonymous").and_then(Value::as_bool) == Some(true) { return Ok(rustgis_engine::data::login_address::inner(pages.next_url()).to_string()); } @@ -595,8 +638,10 @@ fn next_request(app: &mut RustGisApp, params: &Value, pages: &Pages) -> Result { - let next = next_request(app, &landed.params, &pages); + let reach = reach.min(cache::ceiling_for(&landed.url)); + let next = next_request(app, &landed.params, &pages, reach); let slot = match next { // A layer's description: small, and soon given up on. - Ok(url) if pages.describing() => fetch_within(&url, left.min(ogc::DESCRIPTION_MAX), ogc::DESCRIPTION_TIMEOUT), - Ok(url) => match pages.page_timeout() { - Some(timeout) => fetch_within(&url, left, timeout), - None => fetch_into_limited(&url, left), - }, + Ok(url) if pages.describing() => { + fetch_page(&url, left.min(ogc::DESCRIPTION_MAX), Some(ogc::DESCRIPTION_TIMEOUT), reach) + } + Ok(url) => fetch_page(&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, slot, asked: web_time::Instant::now() }); + app.ui.service_pages.push(PageRead { landed, pages, left, reach, slot, asked: web_time::Instant::now() }); } Step::Done(bytes, note) => { noted(app, &landed, note); @@ -654,6 +699,224 @@ fn noted(app: &mut RustGisApp, landed: &Landed, note: Option) { mod tests { use super::*; + /// Add From Service records a document it read from the internet: the document it links to + /// is fetched only from there, and a layer listed there is added restricted to it, however + /// their names resolve. A service read from the local network links to its own documents as + /// before. + #[test] + fn documents_read_from_the_internet_hold_what_they_link_to() { + use rustgis_engine::render::rustgis_tiles::address::{Origin, Reach}; + let items = "https://dialog-links.example/collections/parcels/items"; + let landing = json!({"links":[{"rel":"data","type":"application/json","href":"https://dialog-links.example/collections"}]}); + let collections = json!({"collections":[{"id":"parcels","title":"Parcels","links":[{"rel":"items","type":"application/geo+json","href":items}]}]}); + for observed in [Reach::Public, Reach::Local] { + let _turn = crate::fetching::turn(); + let asked = std::sync::Arc::new(std::sync::Mutex::new(Vec::new())); + let log = asked.clone(); + let (landing, collections) = (landing.to_string(), collections.to_string()); + 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("dialog-links.example") { &collections } else { &landing }; + // A fetch connects no wider than its ceiling. + 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())); + app.run("ui.addService", json!({"url": "https://dialog-root.example/ogc", "type": "ogcapi"})).unwrap(); + app.poll_service(); + app.poll_service(); + let conn = app.ui.service.as_ref().unwrap(); + let listing = conn.listing.clone().expect("both documents were read"); + { + let asked = asked.lock().unwrap(); + assert_eq!(asked.len(), 2, "{asked:?}"); + assert_eq!(asked[0].1, Reach::Local, "the service's own address is the user's choice"); + assert!(asked[1].0.starts_with("https://dialog-links.example/collections"), "{asked:?}"); + assert_eq!(asked[1].1, observed, "the linked document's reach, observed {observed:?}"); + } + let layer = &listing["layers"][0]; + assert_eq!(from_public(layer), observed == Reach::Public, "{listing}"); + let src = ServiceSource { + url: conn.url.clone(), + kind: "ogcapi", + text: conn.text.clone().unwrap(), + documents: conn.documents.clone(), + }; + add_layer_from(&mut app, &src, layer, "", None, false, None, None).unwrap(); + // The features are read off the frame, page by page, within what their address records. + let asked = layer["offer"]["url"].as_str().unwrap(); + assert!(asked.starts_with(items), "{asked}"); + assert_eq!(cache::ceiling_for(asked) == Reach::Public, observed == Reach::Public, "observed {observed:?}"); + } + } + + /// The dialog reads a service's features page by page: a page read from the internet has the + /// next page it links to fetched only from there, however its name resolves, even when the + /// first page's address is the user's own. Pages read from the local network lead anywhere. + #[test] + fn feature_pages_read_from_the_internet_hold_the_next_page() { + use rustgis_engine::render::rustgis_tiles::address::{Origin, Reach}; + let first = "https://pages-first.example/collections/parcels/items"; + let next = "https://pages-next.example/collections/parcels/items?page=2"; + for observed in [Reach::Public, Reach::Local] { + 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, _| { + let clean = cache::split_download_limit(&url).0.to_string(); + log.lock().unwrap().push((clean.clone(), ceiling)); + let links = + if clean.starts_with(first) { json!([{"rel":"next","type":"application/geo+json","href":next}]) } else { json!([]) }; + let body = json!({"type":"FeatureCollection","features":[{"type":"Feature","geometry":{"type":"Point","coordinates":[0,0]},"properties":{}}],"links":links}); + // A fetch connects no wider than its ceiling. + 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())); + app.run("ui.addUrl", json!({"url": first, "name": "Parcels", "service": true})).unwrap(); + for _ in 0..4 { + poll_pages(&mut app, &egui::Context::default()); + } + let asked = asked.lock().unwrap(); + assert_eq!(asked.len(), 2, "{asked:?}"); + assert_eq!(asked[0].1, Reach::Local, "the first page is the user's own address"); + assert!(asked[1].0.starts_with("https://pages-next.example/"), "{asked:?}"); + assert_eq!(asked[1].1, observed, "the next page, the first observed {observed:?}"); + let layer = app.session.map().layers.iter().find(|l| l.name == "Parcels"); + assert_eq!(layer.map(|l| l.dataset.features.len()), Some(2), "{:?}", app.dialogs.error); + } + } + + /// The next page is judged by where the page before it was read, not by how that page's + /// address is spelled: a first page whose public-looking name connected on the local network + /// may lead to a local address; one read from the internet may not. + #[test] + fn the_next_page_is_judged_by_where_the_page_before_it_was_read() { + use rustgis_engine::render::rustgis_tiles::address::{Origin, Reach}; + let first = "https://gis-corp.example/collections/a/items"; + let next = "https://10.0.0.5/collections/a/items?page=2"; + for observed in [Reach::Local, Reach::Public] { + 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, _| { + let clean = cache::split_download_limit(&url).0.to_string(); + log.lock().unwrap().push((clean.clone(), ceiling)); + let links = + if clean.starts_with(first) { json!([{"rel":"next","type":"application/geo+json","href":next}]) } else { json!([]) }; + let body = json!({"type":"FeatureCollection","features":[{"type":"Feature","geometry":{"type":"Point","coordinates":[0,0]},"properties":{}}],"links":links}); + let reach = if clean.starts_with(first) { observed } else { Reach::Local }; + let origin = Origin::with_observed_reach(&clean, reach.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())); + app.run("ui.addUrl", json!({"url": first, "name": "Corp", "service": true})).unwrap(); + for _ in 0..4 { + poll_pages(&mut app, &egui::Context::default()); + } + let asked = asked.lock().unwrap(); + let layer = app.session.map().layers.iter().find(|l| l.name == "Corp").map(|l| l.dataset.features.len()); + if observed == Reach::Local { + assert_eq!(asked.len(), 2, "{asked:?}"); + assert_eq!(asked[1], (next.to_string(), Reach::Local), "{asked:?}"); + assert_eq!(layer, Some(2), "{:?}", app.dialogs.error); + } else { + assert_eq!(asked.len(), 1, "a page read from the internet can't lead to a local address: {asked:?}"); + assert_eq!(layer, Some(1), "the first page is kept"); + } + } + } + + /// A long paged read carries its reach from page to page instead of recording each page's + /// address: every page after one read from the internet is asked only from there, and none of + /// the pages' addresses is added to the restricted addresses, however many pages there are. + #[test] + fn feature_pages_record_none_of_their_addresses() { + use rustgis_engine::render::rustgis_tiles::address::{Origin, Reach}; + const PAGES: usize = 40; + let page = |n: usize| format!("https://pages-many.example/collections/parcels/items?page={n}"); + 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, _| { + let clean = cache::split_download_limit(&url).0.to_string(); + log.lock().unwrap().push((clean.clone(), ceiling)); + let n = clean.rsplit_once("page=").and_then(|(_, n)| n.parse::().ok()).unwrap_or(1); + let links = if n < PAGES { json!([{"rel":"next","type":"application/geo+json","href":page(n + 1)}]) } else { json!([]) }; + let body = json!({"type":"FeatureCollection","features":[{"type":"Feature","geometry":{"type":"Point","coordinates":[0,0]},"properties":{}}],"links":links}); + // Every page is on the internet; a fetch connects no wider than its ceiling. + let origin = Origin::with_observed_reach(&clean, Reach::Public.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())); + app.run("ui.addUrl", json!({"url": page(1), "name": "Many", "service": true})).unwrap(); + for _ in 0..PAGES + 4 { + poll_pages(&mut app, &egui::Context::default()); + } + let asked = asked.lock().unwrap(); + assert_eq!(asked.len(), PAGES, "{asked:?}"); + assert_eq!(asked[0].1, Reach::Local, "the first page is the user's own address"); + assert!(asked[1..].iter().all(|(_, ceiling)| *ceiling == Reach::Public), "{asked:?}"); + for n in 2..=PAGES { + assert_eq!(cache::ceiling_for(&page(n)), Reach::Local, "page {n} was recorded"); + } + let layer = app.session.map().layers.iter().find(|l| l.name == "Many"); + assert_eq!(layer.map(|l| l.dataset.features.len()), Some(PAGES), "{:?}", app.dialogs.error); + } + + /// An OGC API layer's tile set documents, read by the dialog, hold what they name to where + /// they were read from: under a listing from the local network, a tile set list read from the + /// internet has the tile set it leads to fetched only from there, and the layer's template too. + /// One read from the local network leaves both as they were. + #[test] + fn tile_set_documents_read_from_the_internet_hold_what_they_name() { + use rustgis_engine::render::rustgis_tiles::address::{Origin, Reach}; + let root = "https://tileset-root.example/ogc"; + let list = "https://tileset-list.example/collections/relief/map/tiles"; + let tileset = "https://tileset-list.example/tiles/WebMercatorQuad"; + let template = "https://tileset-tiles.example/relief/{tileMatrix}/{tileRow}/{tileCol}.png"; + let collections = json!({"collections":[{"id":"relief","title":"Relief","links":[{"rel":"tilesets-map","href":list}]}]}); + for observed in [Reach::Public, Reach::Local] { + 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, _| { + let clean = cache::split_download_limit(&url).0.to_string(); + log.lock().unwrap().push((clean.clone(), ceiling)); + let body = if clean.starts_with(list) { + json!({"tilesets":[{"tileMatrixSetId":"WebMercatorQuad","links":[{"rel":"self","href":tileset}]}]}) + } else { + json!({"links":[{"rel":"item","type":"image/png","href":template}]}) + }; + // The list is where the test says; a fetch connects no wider than its ceiling. + let reach = if clean.starts_with(list) { observed } else { Reach::Local }; + let origin = Origin::with_observed_reach(&clean, reach.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(); + assert!(!from_public(&layer), "the listing is the user's own: {listing}"); + let src = ServiceSource { url: root.into(), 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(); + assert!(app.ui.service_steps.is_empty(), "both tile set documents were read"); + { + let asked = asked.lock().unwrap(); + assert_eq!(asked.len(), 2, "{asked:?}"); + assert_eq!(asked[0].1, Reach::Local, "a document the user's listing names"); + assert!(asked[1].0.starts_with(tileset), "{asked:?}"); + assert_eq!(asked[1].1, observed, "the tile set, its list observed {observed:?}"); + } + let added = app.session.map().tiles.last().map(|t| t.url.clone()).unwrap_or_default(); + assert!(added.starts_with("https://tileset-tiles.example/relief/"), "{added} {:?}", app.dialogs.error); + assert_eq!(cache::ceiling_for(&added), observed, "the template, its list observed {observed:?}"); + } + } + /// Discovery's anonymous provenance survives both deferred protocols and their final params. #[test] fn anonymous_service_offers_keep_descriptions_and_tiles_unbound() { @@ -761,7 +1024,7 @@ mod tests { }; assert_eq!(pages.next_url(), "https://maps.example.org/items?page=3"); assert_eq!( - next_request(&mut app, &json!({"connection":connection}), &pages).as_deref(), + next_request(&mut app, &json!({"connection":connection}), &pages, Reach::Public).as_deref(), Ok("https://maps.example.org/items?page=3") ); } diff --git a/crates/ui-egui/src/webdataui.rs b/crates/ui-egui/src/webdataui.rs index b717ae7e7b..669fc473ca 100644 --- a/crates/ui-egui/src/webdataui.rs +++ b/crates/ui-egui/src/webdataui.rs @@ -76,7 +76,7 @@ fn listing(app: &mut RustGisApp, url: &str, kind: &'static str) -> Look { let state = &mut app.ui.web_services; let doc = state.docs.entry(url.to_string()).or_insert_with(|| { let caps = rustgis_engine::data::ogc::capabilities_url(url, Some(kind)); - Doc::Waiting(crate::fetch_into(&caps)) + Doc::Waiting(crate::fetch_document_into(&caps)) }); if let Doc::Waiting(slot) = doc { let landed = slot.lock().unwrap_or_else(|e| e.into_inner()).take();