From f604ccd85dc10ede5be31025e48f18afadbc8e48 Mon Sep 17 00:00:00 2001 From: giswqs Date: Wed, 25 Nov 2026 08:59:13 -0500 Subject: [PATCH 1/7] Harden engine scope, credential, format, and sharing guards Tighten policy, credential-resolution, reach, handoff, format-version, and feature-limit checks across `rustgis-engine`: - Gate implicit bucket S3 connection matching in `s3.list` and automatic saved credential resolution (`connection_logins::resolve` and `s3_connections::resolve_project_s3`) on `policy_allows_reserved`, while keeping `Session::open_peer_text` bridge retention working for unchanged database sources. - Keep `Session::file_reach` within `Reach::Public` whenever `plugin_held()` is true (including path-based reads) and apply `held_to_public` to all commands run under a held plugin scope. - Restrict `Kind::Peer` to deny `Effect::Files`, skip identical-save secret restoration in `project.openText` for non-user scopes, and declare `ParamRole` for `text` on `project.fromTemplate`. - Require `policy_user()` before consuming internal `"ran"` handoffs in `embeddings.add`, `layer.addZarr`, `cube.trend`, and `layer.addSql`. - Report a counted notice via `Session::notify` when `share.webMap`, `share.webLayer` viewer pages, or `share.locator` omit features past `MAX_FEATURES`. - Run `project::check_format` before deserializing in `presentation.import`, `report.open`, `notebook.open` (`.rgisnb`), `bookmark.import`, and `dl.import`, and reject Jupyter `nbformat` major versions other than 4. - Fix the generated-import refusal wording in `policy/dispatch.rs` so `map.import` reports a map file rather than a GeoLibre project. - Add regression tests in `crates/engine/src/tests/engine_guards.rs`. --- crates/engine/src/cmd/connection_logins.rs | 3 + crates/engine/src/cmd/cube.rs | 3 + crates/engine/src/cmd/deeplearning.rs | 4 +- crates/engine/src/cmd/embeddings.rs | 3 + crates/engine/src/cmd/items.rs | 2 +- crates/engine/src/cmd/layer.rs | 3 + crates/engine/src/cmd/navigate.rs | 1 + crates/engine/src/cmd/notebook.rs | 20 +- crates/engine/src/cmd/presentation.rs | 1 + crates/engine/src/cmd/project.rs | 6 +- crates/engine/src/cmd/report.rs | 1 + crates/engine/src/cmd/s3.rs | 4 +- crates/engine/src/cmd/sharing.rs | 50 +- crates/engine/src/cmd/zarr.rs | 3 + crates/engine/src/peer.rs | 19 +- crates/engine/src/policy/decide.rs | 2 +- crates/engine/src/policy/dispatch.rs | 22 +- crates/engine/src/received.rs | 13 +- crates/engine/src/s3_connections.rs | 3 + crates/engine/src/tests.rs | 2 + crates/engine/src/tests/engine_guards.rs | 512 +++++++++++++++++++++ 21 files changed, 628 insertions(+), 49 deletions(-) create mode 100644 crates/engine/src/tests/engine_guards.rs diff --git a/crates/engine/src/cmd/connection_logins.rs b/crates/engine/src/cmd/connection_logins.rs index 3b778c9244..922e3deb9b 100644 --- a/crates/engine/src/cmd/connection_logins.rs +++ b/crates/engine/src/cmd/connection_logins.rs @@ -67,6 +67,9 @@ pub(crate) fn resolve_keys(s: &mut Session, keys: &[(&'static str, String)]) { #[cfg(not(target_arch = "wasm32"))] fn resolve(s: &mut Session, only: Option<&[(&'static str, String)]>) { + if !s.policy_allows_reserved() { + return; + } for ((kind, key), layers) in groups(s) { if let Some(only) = only && !only.iter().any(|(k, database)| *k == kind && *database == key) diff --git a/crates/engine/src/cmd/cube.rs b/crates/engine/src/cmd/cube.rs index 78e9b63991..40d53631fc 100644 --- a/crates/engine/src/cmd/cube.rs +++ b/crates/engine/src/cmd/cube.rs @@ -1075,6 +1075,9 @@ fn trend_cmd(s: &mut Session, p: &Value) -> CmdResult { // A run the app worked out: added if it is still kept (the last few are), never worked out // again here, which would block. if let Some(ran) = p.get("ran").filter(|v| !v.is_null()) { + if !s.policy_user() { + return Err("internal trend results are reserved for the app".into()); + } let id = ran.as_u64().ok_or("ran is the number of a run the app worked out")?; let at = s.trend_results.iter().position(|(k, ..)| *k == id).ok_or("that trend is no longer kept: run it again")?; let (_, rasters, dates) = s.trend_results.remove(at); diff --git a/crates/engine/src/cmd/deeplearning.rs b/crates/engine/src/cmd/deeplearning.rs index c73c7e4740..c374980fb5 100644 --- a/crates/engine/src/cmd/deeplearning.rs +++ b/crates/engine/src/cmd/deeplearning.rs @@ -89,7 +89,9 @@ pub fn commands() -> Vec { // Only the model is inflated, whatever else the package holds. let entries = rustgis_data::zip::read_matching(&bytes, |n| n == "model.json")?; let json = entries.first().map(|e| &e.1).ok_or("not a deep learning package (no model.json)")?; - let mut m: DlModel = serde_json::from_slice(json).map_err(|e| format!("not a deep learning package: {e}"))?; + let text = std::str::from_utf8(json).map_err(|e| format!("not a deep learning package: {e}"))?; + crate::project::check_format(text, "deep learning package")?; + let mut m: DlModel = serde_json::from_str(text).map_err(|e| format!("not a deep learning package: {e}"))?; m.model.validate()?; for c in &mut m.model.classes { *c = c.chars().take(200).collect(); diff --git a/crates/engine/src/cmd/embeddings.rs b/crates/engine/src/cmd/embeddings.rs index b6a2833073..e9c332c921 100644 --- a/crates/engine/src/cmd/embeddings.rs +++ b/crates/engine/src/cmd/embeddings.rs @@ -436,6 +436,9 @@ fn series_notes(f: &emb::SeriesFound) -> Vec { /// Bytes the app read and handed over, by their id (`ran`). fn handed(s: &mut Session, p: &Value) -> Result)>, String> { + if p.get("ran").is_some_and(|v| !v.is_null()) && !s.policy_user() { + return Err("internal read results are reserved for the app".into()); + } let Some(id) = f(p, "ran").filter(|v| *v >= 0.0 && v.fract() == 0.0).map(|v| v as u64) else { return Ok(None) }; let i = s.downloaded.iter().position(|(d, _)| *d == id).ok_or("no such read (it was dropped when another project opened)")?; Ok(Some((id, s.downloaded.remove(i).1))) diff --git a/crates/engine/src/cmd/items.rs b/crates/engine/src/cmd/items.rs index 2b8b87fdac..47872ff5e9 100644 --- a/crates/engine/src/cmd/items.rs +++ b/crates/engine/src/cmd/items.rs @@ -242,7 +242,7 @@ pub fn commands() -> Vec { super::connections::resolve_project(s); super::connections::note_waiting(s); Ok(Value::Null) - }).roles(&[]).effects(crate::policy::Effects::NONE.with(crate::policy::Effect::Replaces).with(crate::policy::Effect::Files)) + }).roles(&[crate::ParamRole { key: "text", role: crate::Role::Document(crate::Document::Project) }]).effects(crate::policy::Effects::NONE.with(crate::policy::Effect::Replaces).with(crate::policy::Effect::Files)) .view() .params(r#"{"path"?: "*.rgistemplate", "text"?: template JSON, "data"?: base64 file, "name"?: new project name}"#), // Packages. diff --git a/crates/engine/src/cmd/layer.rs b/crates/engine/src/cmd/layer.rs index 41b265a254..ca6482e370 100644 --- a/crates/engine/src/cmd/layer.rs +++ b/crates/engine/src/cmd/layer.rs @@ -4414,6 +4414,9 @@ fn add_sql(s: &mut Session, p: &Value) -> CmdResult { let full = database.as_ref().map(|d| d.label()); // A result the app ran off the frame (the SQL pane), taken only for the query and database // it came from (the layer saves them); or the query run now. + if p.get("ran").is_some_and(|v| !v.is_null()) && !s.policy_user() { + return Err("internal query results are reserved for the app".into()); + } let ran = p.get("ran").and_then(Value::as_u64); let out = match ran { Some(id) => { diff --git a/crates/engine/src/cmd/navigate.rs b/crates/engine/src/cmd/navigate.rs index 7463431b39..4836121a92 100644 --- a/crates/engine/src/cmd/navigate.rs +++ b/crates/engine/src/cmd/navigate.rs @@ -1490,6 +1490,7 @@ pub(crate) fn bookmarks_file(map: &Map) -> Result, String> { fn import_bookmarks(s: &mut Session, p: &Value) -> CmdResult { let text = super::items::read_text(p)?; + crate::project::check_format(&text, "bookmarks file")?; let v: Value = serde_json::from_str(&text).map_err(|e| format!("not a RustGIS bookmarks file: {e}"))?; let list = v.get("bookmarks").and_then(Value::as_array).ok_or("not a RustGIS bookmarks file: no bookmarks")?; let m = s.map_mut(); diff --git a/crates/engine/src/cmd/notebook.rs b/crates/engine/src/cmd/notebook.rs index 4a35c145ae..abcbc51eed 100644 --- a/crates/engine/src/cmd/notebook.rs +++ b/crates/engine/src/cmd/notebook.rs @@ -485,11 +485,20 @@ fn jupyter_outputs(outputs: &[Value]) -> (String, bool) { /// A RustGIS or Jupyter notebook. fn parse(text: &str, fallback_name: &str) -> Result { let v: Value = serde_json::from_str(text).map_err(|e| format!("not a notebook: {e}"))?; - // nbformat 3 keeps its cells in worksheets: opened as 4, they'd be lost on save. - if let Some(major) = v.get("nbformat").and_then(Value::as_u64).filter(|n| *n < 4) { - return Err(format!("this is an nbformat {major} notebook; RustGIS opens nbformat 4 notebooks (Jupyter converts older ones)")); - } - if v.get("nbformat").is_some() { + // nbformat 3 keeps its cells in worksheets; a newer major version may carry fields this + // version doesn't know: opened as 4, they'd be lost on save. + if let Some(nbformat) = v.get("nbformat") { + if nbformat.as_u64() != Some(4) { + return Err(match nbformat.as_u64() { + Some(major) if major < 4 => { + format!("this is an nbformat {major} notebook; RustGIS opens nbformat 4 notebooks (Jupyter converts older ones)") + } + Some(major) => { + format!("this is an nbformat {major} notebook; RustGIS opens nbformat 4 notebooks (update RustGIS to open newer ones)") + } + None => "this notebook's nbformat isn't a version number; RustGIS opens nbformat 4 notebooks".into(), + }); + } let meta = v.get("metadata").filter(|m| m.is_object()); let name = meta.and_then(|m| m.get("title")).and_then(Value::as_str).unwrap_or(fallback_name).to_string(); // Kept even when empty: a Jupyter notebook that doesn't say it's RustGIS isn't commands. @@ -528,6 +537,7 @@ fn parse(text: &str, fallback_name: &str) -> Result { } return Ok(nb); } + crate::project::check_format(text, "notebook")?; let cells = v.get("cells").and_then(Value::as_array).map_or(0, Vec::len); if cells > MAX_CELLS { return Err(format!("this notebook has {cells} cells; RustGIS opens notebooks of up to {MAX_CELLS}")); diff --git a/crates/engine/src/cmd/presentation.rs b/crates/engine/src/cmd/presentation.rs index 4f6baf9e88..1fef8f227c 100644 --- a/crates/engine/src/cmd/presentation.rs +++ b/crates/engine/src/cmd/presentation.rs @@ -51,6 +51,7 @@ pub fn commands() -> Vec { .params(r#"{"name"?, "title"?: the title page's text}"#), C::new("presentation.import", "Import Presentation", "Publish › Presentation", |s, p| { let text = super::items::read_text(p)?; + crate::project::check_format(&text, "presentation")?; let mut pres: Presentation = serde_json::from_str(&text).map_err(|e| format!("not a RustGIS presentation: {e}"))?; let repairs = pres.clamp(); let (name, cut) = unique_name(s, "Import Presentation", "the name from the file", &pres.name); diff --git a/crates/engine/src/cmd/project.rs b/crates/engine/src/cmd/project.rs index 2eb42d30ed..ffa5ea03ea 100644 --- a/crates/engine/src/cmd/project.rs +++ b/crates/engine/src/cmd/project.rs @@ -755,7 +755,11 @@ fn open_text(s: &mut Session, p: &Value) -> CmdResult { super::connections::clear_active(); // What it names is held within this as it is read, before anything it names is read. let reach = s.file_reach(p); - let proj = if package { Project::from_import_json_within(text, None, reach) } else { Project::from_json_within(text, reach) }; + let proj = if package || !s.policy_user() { + Project::from_import_json_within(text, None, reach) + } else { + Project::from_json_within(text, reach) + }; let (proj, named) = match proj { Ok(proj) => proj, Err(error) => { diff --git a/crates/engine/src/cmd/report.rs b/crates/engine/src/cmd/report.rs index 171886ea2d..b01f79ed6e 100644 --- a/crates/engine/src/cmd/report.rs +++ b/crates/engine/src/cmd/report.rs @@ -653,6 +653,7 @@ pub fn report_file(s: &Session, i: usize, template: bool) -> Result, Str fn open(s: &mut Session, p: &Value) -> CmdResult { let text = super::items::read_text(p)?; + crate::project::check_format(&text, "report")?; let mut r: Report = serde_json::from_str(&text).map_err(|e| format!("not a RustGIS report: {e}"))?; let repairs = r.clamp(); import_layer(s, p, &mut r)?; diff --git a/crates/engine/src/cmd/s3.rs b/crates/engine/src/cmd/s3.rs index 7150009630..d18d2e1e9c 100644 --- a/crates/engine/src/cmd/s3.rs +++ b/crates/engine/src/cmd/s3.rs @@ -267,7 +267,9 @@ pub(super) fn list(s: &mut Session, p: &Value) -> CmdResult { None => s3::grant(&c.name, &bucket), } } - let conn = named.or_else(|| s3::for_bucket(&bucket).filter(|c| !s.web_logins.is_anonymous() || c.credentials.is_none())); + let conn = named.or_else(|| { + s3::for_bucket(&bucket).filter(|c| (!s.web_logins.is_anonymous() && s.policy_allows_reserved()) || c.credentials.is_none()) + }); let (mut prefixes, mut objects, mut token, mut pages) = (Vec::new(), Vec::new(), None::, 0); loop { let url = s3::list_url(&bucket, &prefix, token.as_deref(), conn.as_ref()); diff --git a/crates/engine/src/cmd/sharing.rs b/crates/engine/src/cmd/sharing.rs index d7d0370aef..00f5c719c8 100644 --- a/crates/engine/src/cmd/sharing.rs +++ b/crates/engine/src/cmd/sharing.rs @@ -268,16 +268,27 @@ fn share_bytes_inner(s: &mut Session, kind: &str, p: &Value) -> Result<(String, let mut m = map_of(s, p)?; m.layers.iter_mut().filter(|l| shared_layer("webMap", l)).try_for_each(|l| load_whole(s, l))?; let mut unplaced = Unplaced::default(); - let html = web_map_html(&m, &m.name, &mut unplaced)?; + let mut limited = 0usize; + let html = web_map_html(&m, &m.name, &mut unplaced, &mut limited)?; unplaced.say(s, "The web map"); + if limited > 0 { + s.notify(format!("{limited} feature(s) left out of the web map: the {MAX_FEATURES} feature limit was reached"), false); + } Ok((m.name.clone(), html.into_bytes(), m.name)) } "webLayer" => { let mut l = layer_of(s, p)?; load_whole(s, &mut l)?; let mut unplaced = Unplaced::default(); - let zip = web_layer_zip(s, &l, &mut unplaced)?; + let mut limited = 0usize; + let zip = web_layer_zip(s, &l, &mut unplaced, &mut limited)?; unplaced.say(s, "The web layer"); + if limited > 0 { + s.notify( + format!("{limited} feature(s) left out of the web layer's viewer page: the {MAX_FEATURES} feature limit was reached"), + false, + ); + } Ok((l.name.clone(), zip, l.name.clone())) } "webStyle" => { @@ -290,8 +301,12 @@ fn share_bytes_inner(s: &mut Session, kind: &str, p: &Value) -> Result<(String, let fields: Option> = p.get("fields").and_then(Value::as_array).map(|a| a.iter().filter_map(Value::as_str).map(str::to_string).collect()); let mut unplaced = Unplaced::default(); - let loc = locator(&l, fields.as_deref(), &mut unplaced)?; + let mut limited = 0usize; + let loc = locator(&l, fields.as_deref(), &mut unplaced, &mut limited)?; unplaced.say(s, "The locator"); + if limited > 0 { + s.notify(format!("{limited} feature(s) left out of the locator: the {MAX_FEATURES} feature limit was reached"), false); + } Ok((l.name.clone(), serde_json::to_vec(&loc).map_err(|e| e.to_string())?, l.name.clone())) } "geodataService" => { @@ -545,8 +560,8 @@ fn css(c: Rgba) -> String { /// A layer's visible features as GeoJSON, each with its drawn style: in longitude/latitude, /// whatever system the layer holds its coordinates in. One with a place that can't be given there -/// is left out, counted in `unplaced`. -fn styled_features(l: &Layer, budget: &mut usize, unplaced: &mut Unplaced) -> Result, String> { +/// is left out, counted in `unplaced`; visible features past `budget` are counted in `limited`. +fn styled_features(l: &Layer, budget: &mut usize, unplaced: &mut Unplaced, limited: &mut usize) -> Result, String> { let rows = l.visible_rows(); let opacity = 1.0 - f64::from(l.transparency.clamp(0.0, 100.0)) / 100.0; let mut out = Vec::new(); @@ -554,13 +569,14 @@ fn styled_features(l: &Layer, budget: &mut usize, unplaced: &mut Unplaced) -> Re let styler = l.styler(None); let to = l.dataset.lonlat_conversion().map_err(|e| format!("{}: {e}", l.name))?; for (row, ft) in l.dataset.features.rows().enumerate() { - if *budget == 0 { - break; - } if rows.get(row) != Some(&true) { continue; } let Some(g) = ft.geometry() else { continue }; + if *budget == 0 { + *limited += 1; + continue; + } let Ok(g) = rustgis_data::Dataset::geometry_to_lonlat_by(&to, g) else { unplaced.add(&l.name, 1); continue; @@ -581,7 +597,7 @@ fn styled_features(l: &Layer, budget: &mut usize, unplaced: &mut Unplaced) -> Re /// A self-contained web map page: the map's layers (rasters as images) drawn on a canvas in Web /// Mercator, with pan, zoom, a layer list and pop-ups. No libraries or server. -fn web_map_html(m: &Map, title: &str, unplaced: &mut Unplaced) -> Result { +fn web_map_html(m: &Map, title: &str, unplaced: &mut Unplaced, limited: &mut usize) -> Result { let mut budget = MAX_FEATURES; let mut pictures = 0usize; let mut layers = Vec::new(); @@ -615,7 +631,7 @@ fn web_map_html(m: &Map, title: &str, unplaced: &mut Unplaced) -> Result)], unplac } /// A web layer: the layer as an OGC API Features collection, its style, and a viewer page. -fn web_layer_zip(s: &Session, l: &Layer, unplaced: &mut Unplaced) -> Result, String> { +fn web_layer_zip(s: &Session, l: &Layer, unplaced: &mut Unplaced, limited: &mut usize) -> Result, String> { let style = serde_json::to_vec_pretty(&web_style(l)).map_err(|e| e.to_string())?; // The same features as the collection's items, counted there. let geojson = serde_json::to_vec(&rustgis_data::io::to_geojson(&l.dataset.in_lonlat_leaving_out()?.0)).map_err(|e| e.to_string())?; @@ -944,7 +960,7 @@ fn web_layer_zip(s: &Session, l: &Layer, unplaced: &mut Unplaced) -> Result, } -fn locator(l: &Layer, fields: Option<&[String]>, unplaced: &mut Unplaced) -> Result { +fn locator(l: &Layer, fields: Option<&[String]>, unplaced: &mut Unplaced, limited: &mut usize) -> Result { let ds = &l.dataset; let fis: Vec = match fields { Some(fs) => { @@ -976,12 +992,17 @@ fn locator(l: &Layer, fields: Option<&[String]>, unplaced: &mut Unplaced) -> Res } let lonlat = ds.lonlat_conversion()?; let mut entries = Vec::new(); - for (row, ft) in ds.features.iter().enumerate().take(MAX_FEATURES) { + let mut taken = 0usize; + for (row, ft) in ds.features.iter().enumerate() { let Some(g) = &ft.geometry else { continue }; let e = g.extent(); if e.is_empty() { continue; } + if taken >= MAX_FEATURES { + *limited += 1; + continue; + } let c = match g { Geometry::Point(p) => *p, _ => e.center(), @@ -993,6 +1014,7 @@ fn locator(l: &Layer, fields: Option<&[String]>, unplaced: &mut Unplaced) -> Res unplaced.add(&l.name, 1); continue; }; + taken += 1; for &fi in &fis { let t = match ds.value(row, fi) { rustgis_data::Value::Null => continue, diff --git a/crates/engine/src/cmd/zarr.rs b/crates/engine/src/cmd/zarr.rs index 071596b8fe..20c189b627 100644 --- a/crates/engine/src/cmd/zarr.rs +++ b/crates/engine/src/cmd/zarr.rs @@ -503,6 +503,9 @@ pub(crate) fn add(s: &mut Session, p: &Value) -> CmdResult { Source::Dir(d) | Source::Url(d) => d.clone(), }; // A slice the app read itself (the web app, or a store by address): its GeoTIFF, handed over. + if p.get("ran").is_some_and(|v| !v.is_null()) && !s.policy_user() { + return Err("internal read results are reserved for the app".into()); + } if let Some(id) = super::f(p, "ran").filter(|v| *v >= 0.0 && v.fract() == 0.0).map(|v| v as u64) { let i = s.downloaded.iter().position(|(d, _)| *d == id).ok_or("no such read (it was dropped when another project opened)")?; let (_, tif) = s.downloaded.remove(i); diff --git a/crates/engine/src/peer.rs b/crates/engine/src/peer.rs index 951f4439f0..fe5b1b95ef 100644 --- a/crates/engine/src/peer.rs +++ b/crates/engine/src/peer.rs @@ -438,7 +438,16 @@ impl Session { /// authority. Reset advances generation, clears item trust, history, pending work and active /// connections; old approvals and continuations must bind to that generation. pub fn open_peer_text(&mut self, peer: Peer, text: &str) -> Result { - self.with_scope(crate::policy::Scope::peer(), |s| s.open_peer_text_scoped(peer, text))? + let mut report = self.with_scope(crate::policy::Scope::peer(), |s| s.open_peer_text_scoped(peer, text))??; + crate::cmd::connections::resolve_project(self); + crate::cmd::connections::note_waiting(self); + self.revision = self.revision.wrapping_add(1); + if peer == Peer::Bridge { + let (exchange, omitted) = Exchange::record(&self.project, self.opened); + self.exchange = Some(exchange); + report.not_retained = omitted; + } + Ok(report) } /// The existing raw census/reset path runs synchronously under peer provenance. fn open_peer_text_scoped(&mut self, peer: Peer, text: &str) -> Result { @@ -489,14 +498,6 @@ impl Session { report.executable_changes = durable::changed_executables(&mut self.project, &mut p)?; crate::cmd::project::reset_to(self, p); self.path = None; - crate::cmd::connections::resolve_project(self); - crate::cmd::connections::note_waiting(self); - self.revision = self.revision.wrapping_add(1); - if peer == Peer::Bridge { - let (exchange, omitted) = Exchange::record(&self.project, self.opened); - self.exchange = Some(exchange); - report.not_retained = omitted; - } Ok(report) } } diff --git a/crates/engine/src/policy/decide.rs b/crates/engine/src/policy/decide.rs index d6ec93234e..f575241da1 100644 --- a/crates/engine/src/policy/decide.rs +++ b/crates/engine/src/policy/decide.rs @@ -31,7 +31,7 @@ fn kind(s: &Session, k: &Kind, node: &Node) -> Decision { match k { Kind::User => Allow, Kind::Peer => { - if node.effects.contains(Replaces) { + if node.effects.contains(Replaces) && !node.effects.contains(Files) { Allow } else { Deny diff --git a/crates/engine/src/policy/dispatch.rs b/crates/engine/src/policy/dispatch.rs index 017159116e..e54c1a4c19 100644 --- a/crates/engine/src/policy/dispatch.rs +++ b/crates/engine/src/policy/dispatch.rs @@ -415,16 +415,19 @@ impl Session { let plan = self.plan(scope, call)?; let decision = plan.decision(self, scope)?; /// Finds imports whose operations cannot be enumerated before external content is read. - fn generated(n: &Node) -> bool { - n.generated || n.children.iter().any(generated) + fn generated(n: &Node) -> Option<&str> { + if n.generated { + return Some(n.id()); + } + n.children.iter().find_map(generated) } - if generated(&plan.root) { + if let Some(id) = generated(&plan.root) { return Err(format!( "{}; RustGIS can't show its operations before reading it; import it yourself", - if plan.root.id() == "project.importQgis" { - "it adds the files and web addresses a QGIS project names" - } else { - "it adds the files and web addresses a GeoLibre project names" + match id { + "project.importQgis" => "it adds the files and web addresses a QGIS project names", + "map.import" => "it adds the files and web addresses a map file names", + _ => "it adds the files and web addresses a GeoLibre project names", } )); } @@ -730,9 +733,8 @@ impl Session { let still = continuation.map(|c| Arc::new(move || c.check().is_ok()) as crate::render::rustgis_tiles::cache::Still); let r = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { // Plugins reach only the internet: so does every request a command one runs makes, - // the ones it derives from an address it was given (a listing, a search, a next page) - // and the ones a saved connection sends. - let held = node.effects.contains(super::Effect::Network) && self.plugin_held(); + // whether it declares Network directly or reads a file that names web addresses. + let held = self.plugin_held(); crate::render::rustgis_tiles::cache::with_optional_still(still, || { crate::render::rustgis_tiles::cache::held_to_public(held, || f(self)) }) diff --git a/crates/engine/src/received.rs b/crates/engine/src/received.rs index 7c6a69a279..894c91caea 100644 --- a/crates/engine/src/received.rs +++ b/crates/engine/src/received.rs @@ -19,14 +19,15 @@ const NAMED: usize = 3; impl Session { /// The widest reach what a file being read names may have (`p`: the command's parameters). /// A file downloaded by its web address is read within the reach it was read at - /// ([`Session::receiving`]); file text or data supplied by anything but the user (the - /// Assistant, MCP, a plugin) within the internet; a file read from a path, or given by the user, - /// within this computer and the local network, as before. That includes a path an attached - /// agent opens, even one it wrote: what the file names reaches no further than the agent's own - /// approved commands do already (its `layer.addUrl` of a local server reads from there). + /// ([`Session::receiving`]); a held plugin, or file text or data supplied by anything but the + /// user (the Assistant, MCP, a plugin), within the internet; a file read from a path, or given + /// by the user, within this computer and the local network, as before. That includes a path an + /// attached agent opens, even one it wrote: what the file names reaches no further than the + /// agent's own approved commands do already (its `layer.addUrl` of a local server reads from + /// there). pub(crate) fn file_reach(&self, p: &Value) -> Reach { let supplied = ["text", "data"].iter().any(|k| p.get(k).is_some_and(Value::is_string)); - let given = if supplied && !self.policy_user() { Reach::Public } else { Reach::Local }; + let given = if self.plugin_held() || (supplied && !self.policy_user()) { Reach::Public } else { Reach::Local }; self.received.map_or(given, |read| given.min(read.min(Reach::Local))) } diff --git a/crates/engine/src/s3_connections.rs b/crates/engine/src/s3_connections.rs index eaef1800de..24810a7d6f 100644 --- a/crates/engine/src/s3_connections.rs +++ b/crates/engine/src/s3_connections.rs @@ -164,6 +164,9 @@ impl Group { /// Settles the S3 sources of the project: see the module's text. Called when a project opens /// and when maps or layers are imported, never from a frame. pub(crate) fn resolve_project_s3(s: &mut Session) { + if !s.policy_allows_reserved() { + return; + } let mut groups: Vec = Vec::new(); for a in s.project.addresses_mut() { if let Some(u) = unresolved(a) diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index a0c70f2c78..7dd21f0386 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -86,6 +86,8 @@ mod service_logins; #[path = "tests/scopes_and_redaction.rs"] mod scopes_and_redaction; +#[path = "tests/engine_guards.rs"] +mod engine_guards; #[path = "tests/tiled_files.rs"] mod tiled_files; diff --git a/crates/engine/src/tests/engine_guards.rs b/crates/engine/src/tests/engine_guards.rs new file mode 100644 index 0000000000..f935c8e0e7 --- /dev/null +++ b/crates/engine/src/tests/engine_guards.rs @@ -0,0 +1,512 @@ +//! Regression tests for policy, credential-resolution, reach, handoff, format-version, and +//! feature-limit guards in `rustgis-engine`. + +use super::*; +use crate::policy::{AgentAccess, Call, Effects, Outcome, Pending, Revocation, Scope}; +use std::sync::{ + Arc, + atomic::{AtomicBool, AtomicUsize, Ordering}, +}; + +struct Live(AtomicBool); +impl Revocation for Live { + fn allows(&self, _: Effects) -> bool { + self.0.load(Ordering::SeqCst) + } +} + +fn assistant_scope(id: u64) -> Scope { + Scope::assistant(id, Arc::new(Live(AtomicBool::new(true)))) +} + +fn agent_scope(access: AgentAccess, label: &str) -> Scope { + Scope::agent(access, false, label, None, Arc::new(Live(AtomicBool::new(true)))) +} + +fn pending(s: &Session, scope: &Scope, call: &Call) -> Pending { + match s.review(scope, call) { + Outcome::NeedsApproval(p) => p, + Outcome::Refused(e) => panic!("refused instead of a review: {e}"), + Outcome::Allowed => panic!("expected approval requirement"), + } +} + +/// A counting secret store for verifying that non-reserved scopes never read saved credentials. +#[cfg(not(target_arch = "wasm32"))] +struct CountingSecrets { + inner: rustgis_data::secrets::MemorySecrets, + loads: AtomicUsize, +} + +#[cfg(not(target_arch = "wasm32"))] +impl CountingSecrets { + fn new() -> Self { + Self { inner: rustgis_data::secrets::MemorySecrets::new(), loads: AtomicUsize::new(0) } + } + + fn loads(&self) -> usize { + self.loads.load(Ordering::SeqCst) + } +} + +#[cfg(not(target_arch = "wasm32"))] +impl rustgis_data::secrets::SecretStore for CountingSecrets { + fn save(&self, account: &str, value: &rustgis_data::secrets::Secret) -> Result<(), rustgis_data::secrets::SecretError> { + self.inner.save(account, value) + } + + fn load(&self, account: &str) -> Result, rustgis_data::secrets::SecretError> { + self.loads.fetch_add(1, Ordering::SeqCst); + self.inner.load(account) + } + + fn delete(&self, account: &str) -> Result<(), rustgis_data::secrets::SecretError> { + self.inner.delete(account) + } +} + +/// Fix 1: `s3.list` with a `bucket` must not attach a signed session S3 connection when the active +/// scope does not allow reserved authority (Assistant or Agent). +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn s3_list_by_bucket_does_not_attach_reserved_credentials_for_agent_or_assistant() { + if isolate_process_test("tests::engine_guards::s3_list_by_bucket_does_not_attach_reserved_credentials_for_agent_or_assistant") { + return; + } + let (base, seen) = serve_s3(); + let bucket = "s3-test-bucket"; + let mut s = Session::new(Project::default()); + s.run( + "s3.connect", + &json!({ + "name": "signed-local", + "endpoint": base, + "buckets": [bucket], + "accessKeyId": "fixture-id-0001", + "secretAccessKey": "fixture-secret-0001" + }), + ) + .unwrap(); + + // Baseline: User scope attaches the signed connection and reaches the local endpoint. + let listed = s.run("s3.list", &json!({"bucket": bucket})).unwrap(); + assert_eq!(listed["bucket"], bucket); + assert!(!seen.lock().unwrap().is_empty(), "user listing should reach the signed endpoint"); + seen.lock().unwrap().clear(); + + // Agent (Allow) scope has Network but not Reserved: must not attach the signed connection. + let call = Call::command("s3.list", json!({"bucket": bucket})); + let agent = agent_scope(AgentAccess::Allow, "s3-agent"); + assert!(s.run_scoped(agent, &call).is_err(), "agent must not list through the signed session connection"); + assert!(seen.lock().unwrap().is_empty(), "agent listing must not reach the signed endpoint"); + + // Assistant approved for Network (not Reserved) must also not attach the signed connection. + let assistant = assistant_scope(29001); + let p = pending(&s, &assistant, &call); + assert!(s.run_permitted(assistant, p.allow(), &call).is_err(), "assistant must not list through the signed session connection"); + assert!(seen.lock().unwrap().is_empty(), "assistant listing must not reach the signed endpoint"); + + let _ = s.run("s3.disconnect", &json!({"name": "signed-local"})); +} + +/// Fix 2: `connection_logins::resolve` and `s3_connections::resolve_project_s3` must not resolve +/// saved keychain credentials when running under a non-reserved scope. +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn non_reserved_scopes_do_not_auto_resolve_saved_keychain_logins() { + if isolate_process_test("tests::engine_guards::non_reserved_scopes_do_not_auto_resolve_saved_keychain_logins") { + return; + } + use crate::render::rustgis_tiles::s3; + use rustgis_data::{Dataset, Field, FieldType, GeometryType}; + use rustgis_map::Layer; + use rustgis_map::source::{PostgisOrigin, SourceLayer}; + + let store = Arc::new(CountingSecrets::new()); + let mut s = Session::new(Project::default()); + s.database_logins.set_store(Some(store.clone())); + + // Set up a saved S3 connection with remembered credentials, then clear its runtime binding. + let s3_id = s + .run( + "connection.new", + &json!({ + "kind": "s3", + "name": "SavedBucketS3", + "address": "http://127.0.0.1:9", + "options": {"credentials": "keys", "buckets": "guarded-bucket", "region": "us-east-1"} + }), + ) + .unwrap()["id"] + .as_str() + .unwrap() + .to_string(); + s.run( + "connection.login", + &json!({ + "id": s3_id, + "accessKeyId": "fixture-s3-key", + "secretAccessKey": "fixture-s3-secret", + "remember": true + }), + ) + .unwrap(); + let _ = s.run("s3.disconnect", &json!({"name": "SavedBucketS3"})); + + // Set up a saved PostGIS connection with a remembered password. + let pg_addr = "postgresql://reader@127.0.0.1:1/guarded_db"; + let pg_id = s.run("connection.new", &json!({"kind": "postgres", "name": "SavedPg", "address": pg_addr})).unwrap()["id"] + .as_str() + .unwrap() + .to_string(); + s.run("connection.login", &json!({"id": pg_id, "password": "fixture-pg-pw", "remember": true})).unwrap(); + + // Open a cold session with the saved connection definitions and shared secret store so neither + // connection has an in-memory session login yet. + let definitions = s.connections.to_json(); + crate::cmd::connections::clear_active(); + let mut s = Session::new(Project::default()); + s.database_logins.set_store(Some(store.clone())); + s.connections = crate::connections::Connections::from_json(&definitions); + + // Build a layer file referencing the saved S3 bucket. + let mut s3_layer = Layer::new(1, Dataset::new("S3Guard", GeometryType::Point, vec![Field::new("id", FieldType::Integer)])); + let mut s3_src = SourceLayer::default(); + s3_src.path = Some(rustgis_data::s3_address::bind("", "http://127.0.0.1:9", "s3://guarded-bucket/data.fgb").unwrap()); + s3_layer.source = Some(s3_src); + let s3_lyr_text = serde_json::to_string(&s3_layer).unwrap(); + + // Build a layer file referencing the saved PostGIS database. + let mut pg_layer = Layer::new(2, Dataset::new("PgGuard", GeometryType::Point, vec![Field::new("id", FieldType::Integer)])); + let mut pg_src = SourceLayer::default(); + pg_src.postgis = Some(PostgisOrigin { + database: pg_addr.into(), + table: "public.parcels".into(), + crs: None, + family: Some(rustgis_data::source::Family::Points), + }); + pg_layer.source = Some(pg_src); + let pg_lyr_text = serde_json::to_string(&pg_layer).unwrap(); + + let loads_before = store.loads(); + let agent = agent_scope(AgentAccess::Allow, "import-agent"); + + s.run_scoped(agent.clone(), &Call::command("layer.addLayerFile", json!({"text": s3_lyr_text}))).unwrap(); + assert_eq!(store.loads(), loads_before, "non-reserved scope must not load saved S3 credentials"); + assert!(s.s3_binding(&s3_id).is_none(), "non-reserved scope must not bind saved S3 credentials"); + + s.run_scoped(agent, &Call::command("layer.addLayerFile", json!({"text": pg_lyr_text}))).unwrap(); + assert_eq!(store.loads(), loads_before, "non-reserved scope must not load saved DB credentials"); + let (_, pg_key) = crate::connections::database_key(pg_addr).unwrap(); + assert!(s.database_logins.activations().iter().all(|(k, _)| k != &pg_key), "DB credentials must not activate"); + + // Sanity check: User scope does consult the saved credential store on both S3 and DB resolution. + crate::s3_connections::resolve_project_s3(&mut s); + let loads_after_s3 = store.loads(); + assert!(loads_after_s3 > loads_before, "user scope should resolve saved S3 credentials"); + crate::cmd::connections::resolve_project(&mut s); + assert!(store.loads() > loads_after_s3, "user scope should resolve saved DB credentials"); + let _ = s3::disconnect("SavedBucketS3"); +} + +/// Fix 3: `Session::file_reach` returns `Reach::Public` whenever `plugin_held()` is true, even +/// when reading from a `path`, and plugin commands without `Effect::Network` remain held to public. +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn held_plugin_file_reach_stays_public_even_for_path() { + use crate::render::rustgis_tiles::{address::Reach, cache}; + use rustgis_data::{Dataset, Field, FieldType, GeometryType}; + use rustgis_map::Layer; + use rustgis_map::source::SourceLayer; + + let mut s = Session::new(Project::default()); + isolate_plugins(); + let plug_id = "eng-file-reach-held"; + plugin(plug_id, &["edit", "files"]); + + // User scope and Agent scope with a path remain Reach::Local; Agent with text is Reach::Public. + let path_p = json!({"path": "/tmp/example.rgislyr"}); + let text_p = json!({"text": "{}"}); + assert_eq!(s.file_reach(&path_p), Reach::Local); + let agent = agent_scope(AgentAccess::Allow, "reach-agent"); + assert_eq!(s.with_scope(agent.clone(), |s| s.file_reach(&path_p)).unwrap(), Reach::Local); + assert_eq!(s.with_scope(agent, |s| s.file_reach(&text_p)).unwrap(), Reach::Public); + + // Held plugin scope must return Reach::Public even when given a "path". + let loaded = rustgis_plugins::get(plug_id).unwrap(); + let plug_reach = s.as_session_plugin(loaded, |s| s.file_reach(&path_p)).unwrap(); + assert_eq!(plug_reach, Reach::Public, "held plugin file_reach must be Reach::Public for path"); + + // End-to-end: a held plugin importing a .rgislyr from disk holds its local URL to Reach::Public + // and never connects to a local listener during the Effect::Files-only command. + let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap(); + listener.set_nonblocking(true).unwrap(); + let local_url = format!("http://{}/plugin-path-guard/data.fgb", listener.local_addr().unwrap()); + cache::allow_named(&local_url); + + let mut lyr = Layer::new(1, Dataset::new("LocalFromPath", GeometryType::Point, vec![Field::new("id", FieldType::Integer)])); + let mut src = SourceLayer::default(); + src.path = Some(local_url.clone()); + lyr.source = Some(src); + + let dir = std::env::temp_dir().join(format!("rustgis-plugin-reach-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + let lyr_path = dir.join("local.rgislyr"); + std::fs::write(&lyr_path, serde_json::to_vec(&lyr).unwrap()).unwrap(); + + forward(&mut s, plug_id, "layer.addLayerFile", json!({"path": lyr_path.display().to_string()})).unwrap(); + assert_eq!(cache::ceiling_for(&local_url), Reach::Public, "URL named by plugin-opened path must be held to public"); + assert_eq!( + listener.accept().map(|_| ()).unwrap_err().kind(), + std::io::ErrorKind::WouldBlock, + "local listener must not be contacted by plugin file import" + ); + + let _ = std::fs::remove_dir_all(&dir); + rustgis_plugins::unload(plug_id); +} + +/// Fix 4: `Kind::Peer` denies `Effect::Files`, `project.openText` skips identical-save secret +/// restore for non-user scopes, and `project.fromTemplate` declares its `text` document role. +#[test] +fn peer_scope_refuses_files_and_open_text_skips_restore_for_non_user_and_template_marks_text_role() { + use rustgis_data::{Dataset, Field, FieldType, GeometryType}; + use rustgis_map::Layer; + + let mut s = Session::new(Project::default()); + + // 1. Kind::Peer denies Effect::Files commands (project.open, project.fromTemplate), + // while still permitting Effect::Replaces without Files (project.openText). + assert!(matches!(s.review(&Scope::peer(), &Call::command("project.open", json!({"path": "never.rgis"}))), Outcome::Refused(_))); + assert!(matches!( + s.review(&Scope::peer(), &Call::command("project.fromTemplate", json!({"path": "never.rgistemplate"}))), + Outcome::Refused(_) + )); + assert!(s.run_scoped(Scope::peer(), &Call::command("project.open", json!({"path": "never.rgis"}))).is_err()); + assert!(s.run_scoped(Scope::peer(), &Call::command("project.fromTemplate", json!({"path": "never.rgistemplate"}))).is_err()); + assert!(matches!(s.review(&Scope::peer(), &Call::command("project.openText", json!({"text": "{}"}))), Outcome::Allowed)); + + // 2. project.openText must never trigger durable::restore for non-user scopes. + let secret = "RGSYNTH_open_text_guard_secret"; + let mut ds = Dataset::new("SecretLayer", GeometryType::Point, vec![Field::new("id", FieldType::Integer)]); + ds.source = Some(format!("https://guard.invalid/data.geojson?token={secret}")); + let mut orig = Session::new(Project::default()); + orig.map_mut().add_layer(Layer::new(1, ds)); + let (saved, report) = orig.project.saved_text(None).unwrap(); + assert!(report.layer_addresses() > 0); + assert!(!saved.contains(secret)); + + // User scope restores from the identical-save cache. + let mut by_user = Session::new(Project::default()); + by_user.run("project.openText", &json!({"text": saved})).unwrap(); + assert!(serde_json::to_string(&by_user.project).unwrap().contains(secret), "user scope baseline should restore live secret"); + + // Non-user scopes (Agent and Peer) must never restore the live secret. + let mut by_agent = Session::new(Project::default()); + let agent = agent_scope(AgentAccess::Allow, "open-text-agent"); + by_agent.run_scoped(agent, &Call::command("project.openText", json!({"text": saved}))).unwrap(); + assert!(!serde_json::to_string(&by_agent.project).unwrap().contains(secret), "agent scope project.openText must not restore secrets"); + + let mut by_peer = Session::new(Project::default()); + by_peer.run_scoped(Scope::peer(), &Call::command("project.openText", json!({"text": saved}))).unwrap(); + assert!(!serde_json::to_string(&by_peer.project).unwrap().contains(secret), "peer scope project.openText must not restore secrets"); + + // 3. project.fromTemplate declares ParamRole for "text" as Document::Project. + let spec = s.registry.get("project.fromTemplate").unwrap(); + assert!( + spec.roles.unwrap().contains(&crate::ParamRole { key: "text", role: crate::Role::Document(crate::Document::Project) }), + "project.fromTemplate must declare text as Document::Project" + ); +} + +/// Fix 5: Non-user scopes (Agent, Plugin) cannot consume internal `"ran"` handoffs from +/// `s.downloaded`, `s.trend_results`, or `s.sql_results`, leaving pending entries intact. +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn non_user_scopes_cannot_consume_internal_ran_handoffs() { + let mut s = Session::new(Project::default()); + isolate_plugins(); + let plug_id = "eng-ran-guard"; + plugin(plug_id, &["edit", "network", "files"]); + + let geojson = br##"{"type":"FeatureCollection","features":[{"type":"Feature","geometry":{"type":"Point","coordinates":[0,0]},"properties":{"color":"#ff0000"}}]}"##.to_vec(); + let emb_id = 9101u64; + let zarr_id = 9102u64; + s.downloaded.push((emb_id, geojson)); + s.downloaded.push((zarr_id, vec![1, 2, 3, 4])); + let trend_id = crate::cmd::cube::land(&mut s, Vec::new(), 4); + let sql_id = 9103u64; + let sql_out = rustgis_data::source::duckdb::Output::default(); + s.sql_results.push((sql_id, "SELECT 1".into(), None, sql_out)); + + let agent = agent_scope(AgentAccess::Allow, "ran-agent"); + + // embeddings.add with "ran" + let emb_p = json!({"dataset": "earth-index", "ran": emb_id}); + let err = s.run_scoped(agent.clone(), &Call::command("embeddings.add", emb_p.clone())).unwrap_err(); + assert!(err.contains("reserved for the app"), "embeddings.add agent: {err}"); + let err = forward(&mut s, plug_id, "embeddings.add", emb_p).unwrap_err(); + assert!(err.contains("reserved for the app"), "embeddings.add plugin: {err}"); + assert!(s.downloaded.iter().any(|(d, _)| *d == emb_id), "embeddings downloaded entry must remain intact"); + + // layer.addZarr with "ran" + let zarr_p = json!({"path": "store.zarr", "ran": zarr_id}); + let err = s.run_scoped(agent.clone(), &Call::command("layer.addZarr", zarr_p.clone())).unwrap_err(); + assert!(err.contains("reserved for the app"), "layer.addZarr agent: {err}"); + let err = forward(&mut s, plug_id, "layer.addZarr", zarr_p).unwrap_err(); + assert!(err.contains("reserved for the app"), "layer.addZarr plugin: {err}"); + assert!(s.downloaded.iter().any(|(d, _)| *d == zarr_id), "zarr downloaded entry must remain intact"); + + // cube.trend with "ran" + let trend_p = json!({"ran": trend_id}); + let err = s.run_scoped(agent.clone(), &Call::command("cube.trend", trend_p.clone())).unwrap_err(); + assert!(err.contains("reserved for the app"), "cube.trend agent: {err}"); + let err = forward(&mut s, plug_id, "cube.trend", trend_p).unwrap_err(); + assert!(err.contains("reserved for the app"), "cube.trend plugin: {err}"); + assert!(s.trend_results.iter().any(|(k, ..)| *k == trend_id), "trend_results entry must remain intact"); + + // layer.addSql with "ran" + let sql_p = json!({"sql": "SELECT 1", "ran": sql_id}); + let err = s.run_scoped(agent, &Call::command("layer.addSql", sql_p.clone())).unwrap_err(); + assert!(err.contains("reserved for the app"), "layer.addSql agent: {err}"); + let err = forward(&mut s, plug_id, "layer.addSql", sql_p).unwrap_err(); + assert!(err.contains("reserved for the app"), "layer.addSql plugin: {err}"); + assert!(s.sql_results.iter().any(|(k, ..)| *k == sql_id), "sql_results entry must remain intact"); + + rustgis_plugins::unload(plug_id); +} + +/// Fix 6: `share.webMap` and `share.locator` emit a counted notice when features are omitted past +/// the 200,000-feature limit, and emit no limit notice for clean inputs below the limit. +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn web_map_and_locator_notify_when_feature_limit_is_reached() { + use rustgis_data::{Dataset, Feature, Field, FieldType, Geometry, GeometryType, Value as AttrValue}; + use rustgis_geom::Coord; + use rustgis_map::Layer; + + let make_session = |count: usize| -> Session { + let mut ds = Dataset::new("Places", GeometryType::Point, vec![Field::new("name", FieldType::Text)]); + ds.features.reserve(count); + for i in 0..count { + ds.features.push(Feature { + id: i as u64 + 1, + geometry: Some(Geometry::Point(Coord::new(0.0, 0.0))), + attrs: vec![AttrValue::Text("p".into())], + }); + } + let mut s = Session::new(Project::default()); + s.map_mut().add_layer(Layer::new(1, ds)); + s + }; + + let dir = std::env::temp_dir().join(format!("rustgis-share-limit-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + + // Clean input below limit: no limit notice. + let mut clean = make_session(3); + let mark = clean.notice_mark(); + clean.run("share.webMap", &json!({"path": dir.join("clean.html").display().to_string()})).unwrap(); + assert!( + clean.notices_since(mark).iter().all(|n| !n.text.contains("feature limit")), + "clean webMap must not emit limit notice: {:?}", + clean.notices_since(mark) + ); + let mark = clean.notice_mark(); + clean.run("share.locator", &json!({"layer": "Places", "path": dir.join("clean.rgisloc").display().to_string()})).unwrap(); + assert!( + clean.notices_since(mark).iter().all(|n| !n.text.contains("feature limit")), + "clean locator must not emit limit notice: {:?}", + clean.notices_since(mark) + ); + + // Input past MAX_FEATURES (200,000): emits one counted notice for each. + let mut big = make_session(200_002); + let mark = big.notice_mark(); + big.run("share.webMap", &json!({"path": dir.join("big.html").display().to_string()})).unwrap(); + let web_notices: Vec = big.notices_since(mark).iter().map(|n| n.text.clone()).collect(); + assert!( + web_notices.iter().any(|n| n.contains("2 feature(s) left out of the web map") && n.contains("200000")), + "webMap must emit counted limit notice: {web_notices:?}" + ); + + let mark = big.notice_mark(); + big.run("share.locator", &json!({"layer": "Places", "path": dir.join("big.rgisloc").display().to_string()})).unwrap(); + let loc_notices: Vec = big.notices_since(mark).iter().map(|n| n.text.clone()).collect(); + assert!( + loc_notices.iter().any(|n| n.contains("2 feature(s) left out of the locator") && n.contains("200000")), + "locator must emit counted limit notice: {loc_notices:?}" + ); + + let _ = std::fs::remove_dir_all(&dir); +} + +/// Fix 7: All five document readers refuse future `format` / unknown `requires`, and +/// `notebook.open` refuses future Jupyter `nbformat` major versions. +#[test] +fn future_format_and_nbformat_files_are_refused() { + use base64::Engine; + + let mut s = Session::new(Project::default()); + let future_format = json!({"format": 99, "requires": ["future-feature"]}).to_string(); + let future_requires = json!({"format": 1, "requires": ["future-feature"]}).to_string(); + + for payload in [&future_format, &future_requires] { + for cmd in ["presentation.import", "report.open", "notebook.open", "bookmark.import"] { + let err = s.run(cmd, &json!({"text": payload})).unwrap_err(); + assert!( + err.contains("newer RustGIS") || err.contains("future-feature"), + "{cmd} should refuse future format/requires, got: {err}" + ); + } + let dl_zip = rustgis_data::zip::write(&[("model.json".into(), payload.as_bytes().to_vec())]).unwrap(); + let dl_b64 = base64::engine::general_purpose::STANDARD.encode(dl_zip); + let err = s.run("dl.import", &json!({"data": dl_b64})).unwrap_err(); + assert!( + err.contains("newer RustGIS") || err.contains("future-feature"), + "dl.import should refuse future format/requires, got: {err}" + ); + } + + // Jupyter nbformat > 4 must be refused rather than silently downgraded to 4. + let nb5 = json!({"nbformat": 5, "cells": []}).to_string(); + let err = s.run("notebook.open", &json!({"text": nb5})).unwrap_err(); + assert!(err.contains("nbformat 5"), "notebook.open must refuse nbformat 5, got: {err}"); + + // Valid nbformat 4 still opens cleanly. + let nb4 = json!({"nbformat": 4, "cells": []}).to_string(); + s.run("notebook.open", &json!({"text": nb4})).unwrap(); +} + +/// Fix 8: Generated-import refusal for `map.import` names "a map file", not "a GeoLibre project". +#[test] +fn map_import_generated_refusal_mentions_map_file() { + let s = Session::new(Project::default()); + let assistant = assistant_scope(29008); + + match s.review(&assistant, &Call::command("map.import", json!({"path": "example.rgismap"}))) { + Outcome::Refused(msg) => { + assert!(msg.contains("a map file"), "expected map file message, got: {msg}"); + assert!(!msg.contains("GeoLibre"), "must not falsely mention GeoLibre: {msg}"); + } + other => panic!("expected Refused for map.import, got: {}", outcome_name(&other)), + } + match s.review(&assistant, &Call::command("project.importQgis", json!({"path": "example.qgs"}))) { + Outcome::Refused(msg) => assert!(msg.contains("QGIS"), "{msg}"), + other => panic!("expected Refused for project.importQgis, got: {}", outcome_name(&other)), + } + match s.review(&assistant, &Call::command("project.importGeolibre", json!({"path": "example.geolibre.json"}))) { + Outcome::Refused(msg) => assert!(msg.contains("GeoLibre"), "{msg}"), + other => panic!("expected Refused for project.importGeolibre, got: {}", outcome_name(&other)), + } +} + +fn outcome_name(o: &Outcome) -> &'static str { + match o { + Outcome::Allowed => "Allowed", + Outcome::NeedsApproval(_) => "NeedsApproval", + Outcome::Refused(_) => "Refused", + } +} From 82cb04006eb25279dd163b621a68f89a745b6376 Mon Sep 17 00:00:00 2001 From: giswqs Date: Wed, 25 Nov 2026 09:19:44 -0500 Subject: [PATCH 2/7] Address review feedback on peer resolution, S3 signing, and sharing cap - Keep `resolve_project` inside `Scope::peer()` in `open_peer_text`, gate `service_logins::resolve` on `policy_allows_reserved()`, and limit post-scope `resolve_keys` to the exact database keys retained by `Exchange::retain` for `Peer::Bridge` (never `Peer::Embedder`). - Wrap `s3.list` request URLs with `s3::anonymous` whenever no signed connection is authorized so transport preparation cannot attach an implicit bucket or endpoint signer. - Break immediately at `MAX_FEATURES` in `locator` and `styled_features` and compute the omitted feature count without further geometry work. - Add regression tests for `Peer::Embedder` credential isolation and anonymous URL wrapping on implicit AWS S3 connections. --- crates/engine/src/cmd/s3.rs | 35 +++++-- crates/engine/src/cmd/sharing.rs | 20 ++-- crates/engine/src/peer.rs | 48 ++++++---- crates/engine/src/service_logins.rs | 2 +- crates/engine/src/tests/engine_guards.rs | 116 ++++++++++++++++++++++- 5 files changed, 187 insertions(+), 34 deletions(-) diff --git a/crates/engine/src/cmd/s3.rs b/crates/engine/src/cmd/s3.rs index d18d2e1e9c..3a746a9d10 100644 --- a/crates/engine/src/cmd/s3.rs +++ b/crates/engine/src/cmd/s3.rs @@ -206,6 +206,32 @@ fn target(p: &Value) -> Result<(Option, String), String> { Ok((bucket, prefix)) } +/// Resolves the bucket listing connection and request URL for `s3.list`. When no signed +/// connection is authorized for this scope, wraps the URL with [`s3::anonymous`] so transport +/// preparation never attaches an implicit bucket or endpoint signer. +#[cfg(not(target_arch = "wasm32"))] +pub(crate) fn bucket_list_url( + s: &Session, + bucket: &str, + prefix: &str, + token: Option<&str>, + named: Option<&s3::Connection>, +) -> Result { + let allow_implicit = !s.web_logins.is_anonymous() && s.policy_allows_reserved(); + let conn = named.cloned().or_else(|| s3::for_bucket(bucket).filter(|c| allow_implicit || c.credentials.is_none())); + let url = s3::list_url(bucket, prefix, token, conn.as_ref()); + match &conn { + Some(c) if c.credentials.is_some() => match s3::binding_of(&c.name) { + Some(_) => { + let binding = owned_saved_binding(s, c).ok_or_else(|| format!("no S3 connection named '{}'", c.name))?; + s3::bound_url(&binding, &url) + } + None => Ok(url), + }, + _ => Ok(s3::anonymous(&url)), + } +} + pub(super) fn list(s: &mut Session, p: &Value) -> CmdResult { let (bucket, prefix) = target(p)?; let named = match ps(p, "connection").map(str::trim).filter(|n| !n.is_empty()) { @@ -267,16 +293,9 @@ pub(super) fn list(s: &mut Session, p: &Value) -> CmdResult { None => s3::grant(&c.name, &bucket), } } - let conn = named.or_else(|| { - s3::for_bucket(&bucket).filter(|c| (!s.web_logins.is_anonymous() && s.policy_allows_reserved()) || c.credentials.is_none()) - }); let (mut prefixes, mut objects, mut token, mut pages) = (Vec::new(), Vec::new(), None::, 0); loop { - let url = s3::list_url(&bucket, &prefix, token.as_deref(), conn.as_ref()); - let url = match &conn { - Some(c) => through(c, url)?, - None => url, - }; + let url = bucket_list_url(s, &bucket, &prefix, token.as_deref(), named.as_ref())?; let page = s3::parse_list(&fetch(&url)?)?; prefixes.extend(page.prefixes); objects.extend(page.objects); diff --git a/crates/engine/src/cmd/sharing.rs b/crates/engine/src/cmd/sharing.rs index 00f5c719c8..e08ea8770c 100644 --- a/crates/engine/src/cmd/sharing.rs +++ b/crates/engine/src/cmd/sharing.rs @@ -563,20 +563,24 @@ fn css(c: Rgba) -> String { /// is left out, counted in `unplaced`; visible features past `budget` are counted in `limited`. fn styled_features(l: &Layer, budget: &mut usize, unplaced: &mut Unplaced, limited: &mut usize) -> Result, String> { let rows = l.visible_rows(); + if *budget == 0 { + *limited += rows.iter().filter(|&&v| v).count(); + return Ok(Vec::new()); + } let opacity = 1.0 - f64::from(l.transparency.clamp(0.0, 100.0)) / 100.0; let mut out = Vec::new(); // Its symbol by expression (no map scale: the page zooms on its own). let styler = l.styler(None); let to = l.dataset.lonlat_conversion().map_err(|e| format!("{}: {e}", l.name))?; for (row, ft) in l.dataset.features.rows().enumerate() { + if *budget == 0 { + *limited += rows.get(row..).map_or(0, |tail| tail.iter().filter(|&&v| v).count()); + break; + } if rows.get(row) != Some(&true) { continue; } let Some(g) = ft.geometry() else { continue }; - if *budget == 0 { - *limited += 1; - continue; - } let Ok(g) = rustgis_data::Dataset::geometry_to_lonlat_by(&to, g) else { unplaced.add(&l.name, 1); continue; @@ -994,15 +998,15 @@ fn locator(l: &Layer, fields: Option<&[String]>, unplaced: &mut Unplaced, limite let mut entries = Vec::new(); let mut taken = 0usize; for (row, ft) in ds.features.iter().enumerate() { + if taken >= MAX_FEATURES { + *limited = ds.features.len().saturating_sub(row); + break; + } let Some(g) = &ft.geometry else { continue }; let e = g.extent(); if e.is_empty() { continue; } - if taken >= MAX_FEATURES { - *limited += 1; - continue; - } let c = match g { Geometry::Point(p) => *p, _ => e.center(), diff --git a/crates/engine/src/peer.rs b/crates/engine/src/peer.rs index fe5b1b95ef..68748d4d4a 100644 --- a/crates/engine/src/peer.rs +++ b/crates/engine/src/peer.rs @@ -311,7 +311,7 @@ impl Exchange { /// Checks last exchange, both incoming censuses, unique account and the exact current live /// value in one synchronous replacement. Public URL or incoming id alone grants nothing. - fn retain(&self, live: &Project, incoming: &mut Project, raw: &HashSet>) { + fn retain(&self, live: &Project, incoming: &mut Project, raw: &HashSet>) -> Vec<(&'static str, String)> { let current = census(live); let normalized = census(incoming); let mut records: HashMap, (usize, &Entry)> = HashMap::new(); @@ -345,27 +345,35 @@ impl Exchange { }) .collect(); drop(normalized); + let mut retained_db_keys = Vec::new(); for (at, full) in edits { if let Some(FieldMut::Text(slot)) = incoming.field_mut(&at.owners, &at.leaf) { *slot = full; } - reopen(incoming, &at); + for key in reopen(incoming, &at) { + if !retained_db_keys.contains(&key) { + retained_db_keys.push(key); + } + } } + retained_db_keys } } /// A retained address must reopen its own reader, which normalization previously opened with /// the public form. Only the exact retained owner/role is touched; S3 wrappers are excluded. -fn reopen(p: &mut Project, at: &At) { - let Some(owner) = at.owners.first() else { return }; +/// Returns the database key(s) of any retained database source so `Peer::Bridge` can re-resolve +/// only those unchanged sources. +fn reopen(p: &mut Project, at: &At) -> Vec<(&'static str, String)> { + let Some(owner) = at.owners.first() else { return Vec::new() }; let map = match owner { Owner::Map(i) => p.maps.get_mut(*i), Owner::Area(i) => p.offline_areas.get_mut(*i).map(|a| &mut a.data), _ => None, }; - let Some(map) = map else { return }; - let Leaf::Map(rustgis_map::SlotPos::Layer { layer, role }) = &at.leaf else { return }; - let Some(layer) = map.layers.get_mut(*layer) else { return }; + let Some(map) = map else { return Vec::new() }; + let Leaf::Map(rustgis_map::SlotPos::Layer { layer, role }) = &at.leaf else { return Vec::new() }; + let Some(layer) = map.layers.get_mut(*layer) else { return Vec::new() }; match role { rustgis_map::LayerRole::Streamed | rustgis_map::LayerRole::PostgisDatabase @@ -379,6 +387,7 @@ fn reopen(p: &mut Project, at: &At) { if let Err(e) = source.reopen() { source.error = Some(rustgis_data::diagnostics::Redacted::new(&e).into_string()); } + return crate::cmd::connections::layer_keys(source); } } rustgis_map::LayerRole::Raster => { @@ -390,6 +399,7 @@ fn reopen(p: &mut Project, at: &At) { } _ => {} } + Vec::new() } /// Values borrow the project, but identities include all duplicates; no normalization runs here. @@ -438,11 +448,15 @@ impl Session { /// authority. Reset advances generation, clears item trust, history, pending work and active /// connections; old approvals and continuations must bind to that generation. pub fn open_peer_text(&mut self, peer: Peer, text: &str) -> Result { - let mut report = self.with_scope(crate::policy::Scope::peer(), |s| s.open_peer_text_scoped(peer, text))??; - crate::cmd::connections::resolve_project(self); - crate::cmd::connections::note_waiting(self); - self.revision = self.revision.wrapping_add(1); + let (mut report, retained_db_keys) = self.with_scope(crate::policy::Scope::peer(), |s| s.open_peer_text_scoped(peer, text))??; if peer == Peer::Bridge { + // Only unchanged database sources explicitly retained by the Bridge exchange may + // re-acquire their remembered login; Peer::Embedder and any newly introduced or + // modified sources stay under Scope::peer() and never trigger saved login resolution. + if !retained_db_keys.is_empty() { + crate::cmd::connections::resolve_keys(self, &retained_db_keys); + crate::cmd::connections::note_waiting(self); + } let (exchange, omitted) = Exchange::record(&self.project, self.opened); self.exchange = Some(exchange); report.not_retained = omitted; @@ -450,7 +464,7 @@ impl Session { Ok(report) } /// The existing raw census/reset path runs synchronously under peer provenance. - fn open_peer_text_scoped(&mut self, peer: Peer, text: &str) -> Result { + fn open_peer_text_scoped(&mut self, peer: Peer, text: &str) -> Result<(Report, Vec<(&'static str, String)>), String> { let mut p = Project::from_peer_raw(text)?; let exchange = self.exchange.as_ref().filter(|e| peer == Peer::Bridge && e.generation == self.opened); let raw = exchange.map(|e| e.incoming(&p)); @@ -468,9 +482,8 @@ impl Session { p.read_notices.extend(repair_notices); let mut report = Report::default(); - if let (Some(exchange), Some(raw)) = (exchange, raw) { - exchange.retain(&self.project, &mut p, &raw); - } + let retained_db_keys = + if let (Some(exchange), Some(raw)) = (exchange, raw) { exchange.retain(&self.project, &mut p, &raw) } else { Vec::new() }; report.reconnect = p .maps .iter() @@ -498,7 +511,10 @@ impl Session { report.executable_changes = durable::changed_executables(&mut self.project, &mut p)?; crate::cmd::project::reset_to(self, p); self.path = None; - Ok(report) + crate::cmd::connections::resolve_project(self); + crate::cmd::connections::note_waiting(self); + self.revision = self.revision.wrapping_add(1); + Ok((report, retained_db_keys)) } } diff --git a/crates/engine/src/service_logins.rs b/crates/engine/src/service_logins.rs index 6083e74f60..2dd1b58efc 100644 --- a/crates/engine/src/service_logins.rs +++ b/crates/engine/src/service_logins.rs @@ -1008,7 +1008,7 @@ fn reads(s: &Session) -> BTreeMap<(String, String), Reads> { pub(crate) fn resolve(s: &mut Session, only: Option<&BTreeSet>) { // Imports and nested commands a plugin runs must not adopt a login before their additions // have been marked anonymous at the plugin boundary. - if s.web_logins.is_anonymous() { + if s.web_logins.is_anonymous() || !s.policy_allows_reserved() { return; } let mut pending = Vec::new(); diff --git a/crates/engine/src/tests/engine_guards.rs b/crates/engine/src/tests/engine_guards.rs index f935c8e0e7..517640b649 100644 --- a/crates/engine/src/tests/engine_guards.rs +++ b/crates/engine/src/tests/engine_guards.rs @@ -103,12 +103,126 @@ fn s3_list_by_bucket_does_not_attach_reserved_credentials_for_agent_or_assistant // Assistant approved for Network (not Reserved) must also not attach the signed connection. let assistant = assistant_scope(29001); let p = pending(&s, &assistant, &call); - assert!(s.run_permitted(assistant, p.allow(), &call).is_err(), "assistant must not list through the signed session connection"); + assert!(s.run_permitted(assistant.clone(), p.allow(), &call).is_err(), "assistant must not list through the signed session connection"); assert!(seen.lock().unwrap().is_empty(), "assistant listing must not reach the signed endpoint"); + // Implicit AWS connection (no custom endpoint): non-reserved scopes must wrap the list URL as + // anonymous so transport `s3::prepare` / `signer_for` never signs it with the implicit bucket + // credentials either. + use crate::render::rustgis_tiles::s3; + let aws_bucket = "aws-signed-guard-bucket"; + s.run( + "s3.connect", + &json!({ + "name": "signed-aws-implicit", + "buckets": [aws_bucket], + "accessKeyId": "fixture-aws-id", + "secretAccessKey": "fixture-aws-secret" + }), + ) + .unwrap(); + let user_url = crate::cmd::s3::bucket_list_url(&s, aws_bucket, "", None, None).unwrap(); + let user_prep = s3::prepare(&user_url).unwrap(); + assert!(user_prep.signed, "user scope should sign implicit AWS bucket listing"); + + let agent = agent_scope(AgentAccess::Allow, "s3-aws-agent"); + let agent_url = s.with_scope(agent, |s| crate::cmd::s3::bucket_list_url(s, aws_bucket, "", None, None)).unwrap().unwrap(); + assert!(s3::split_anonymous(&agent_url).1, "agent list URL must be marked anonymous: {agent_url}"); + let agent_prep = s3::prepare(&agent_url).unwrap(); + assert!(!agent_prep.signed && agent_prep.anonymous && agent_prep.headers.is_empty(), "agent list URL must not be signed"); + + let asst_url = s.with_scope(assistant, |s| crate::cmd::s3::bucket_list_url(s, aws_bucket, "", None, None)).unwrap().unwrap(); + assert!(s3::split_anonymous(&asst_url).1, "assistant list URL must be marked anonymous: {asst_url}"); + let asst_prep = s3::prepare(&asst_url).unwrap(); + assert!(!asst_prep.signed && asst_prep.anonymous && asst_prep.headers.is_empty(), "assistant list URL must not be signed"); + + let _ = s.run("s3.disconnect", &json!({"name": "signed-aws-implicit"})); let _ = s.run("s3.disconnect", &json!({"name": "signed-local"})); } +/// Review fix: `open_peer_text(Peer::Embedder, ...)` runs under `Scope::peer()` and must never +/// load remembered database or S3 credentials from the secret store. +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn peer_embedder_open_peer_text_never_loads_remembered_credentials() { + if isolate_process_test("tests::engine_guards::peer_embedder_open_peer_text_never_loads_remembered_credentials") { + return; + } + use rustgis_data::{Dataset, Field, FieldType, GeometryType}; + use rustgis_map::Layer; + use rustgis_map::source::{PostgisOrigin, SourceLayer}; + + let store = Arc::new(CountingSecrets::new()); + let mut setup = Session::new(Project::default()); + setup.database_logins.set_store(Some(store.clone())); + + let pg_addr = "postgresql://reader@127.0.0.1:1/embedder_db"; + let pg_id = setup.run("connection.new", &json!({"kind": "postgres", "name": "EmbedderPg", "address": pg_addr})).unwrap()["id"] + .as_str() + .unwrap() + .to_string(); + setup.run("connection.login", &json!({"id": pg_id, "password": "fixture-embedder-pw", "remember": true})).unwrap(); + + let s3_id = setup + .run( + "connection.new", + &json!({ + "kind": "s3", + "name": "EmbedderS3", + "address": "http://127.0.0.1:9", + "options": {"credentials": "keys", "buckets": "embedder-bucket", "region": "us-east-1"} + }), + ) + .unwrap()["id"] + .as_str() + .unwrap() + .to_string(); + setup + .run( + "connection.login", + &json!({ + "id": s3_id, + "accessKeyId": "fixture-embedder-key", + "secretAccessKey": "fixture-embedder-secret", + "remember": true + }), + ) + .unwrap(); + let _ = setup.run("s3.disconnect", &json!({"name": "EmbedderS3"})); + + let definitions = setup.connections.to_json(); + crate::cmd::connections::clear_active(); + let mut s = Session::new(Project::default()); + s.database_logins.set_store(Some(store.clone())); + s.connections = crate::connections::Connections::from_json(&definitions); + + let mut incoming = Project::default(); + let mut pg_layer = Layer::new(1, Dataset::new("EmbedderPgLayer", GeometryType::Point, vec![Field::new("id", FieldType::Integer)])); + let mut pg_src = SourceLayer::default(); + pg_src.postgis = Some(PostgisOrigin { + database: pg_addr.into(), + table: "public.parcels".into(), + crs: None, + family: Some(rustgis_data::source::Family::Points), + }); + pg_layer.source = Some(pg_src); + incoming.map_mut().add_layer(pg_layer); + + let mut s3_layer = Layer::new(2, Dataset::new("EmbedderS3Layer", GeometryType::Point, vec![Field::new("id", FieldType::Integer)])); + let mut s3_src = SourceLayer::default(); + s3_src.path = Some(rustgis_data::s3_address::bind("", "http://127.0.0.1:9", "s3://embedder-bucket/data.fgb").unwrap()); + s3_layer.source = Some(s3_src); + incoming.map_mut().add_layer(s3_layer); + + let incoming_json = serde_json::to_string(&incoming).unwrap(); + let loads_before = store.loads(); + let report = s.open_peer_text(crate::Peer::Embedder, &incoming_json).unwrap(); + assert_eq!(report.reconnect, 1, "incoming database layer must require reconnect"); + assert_eq!(store.loads(), loads_before, "Peer::Embedder must not load remembered credentials"); + assert!(s.database_logins.activations().is_empty(), "Peer::Embedder must not activate DB logins"); + assert!(s.s3_binding(&s3_id).is_none(), "Peer::Embedder must not bind saved S3 logins"); +} + /// Fix 2: `connection_logins::resolve` and `s3_connections::resolve_project_s3` must not resolve /// saved keychain credentials when running under a non-reserved scope. #[cfg(not(target_arch = "wasm32"))] From f1464208412689b6b3f4501105d4cad7e87cb327 Mon Sep 17 00:00:00 2001 From: giswqs Date: Sat, 28 Nov 2026 21:19:19 -0500 Subject: [PATCH 3/7] Say waiting S3 choices once, count only placeable locator rows, keep the S3 scope test offline A scope that may not bind saved logins gives one notice with the count of buckets left for the user's choice. The locator's limit notice skips rows with an empty geometry. The s3.list scope test checks the listing address instead of sending a request that could reach AWS. --- crates/engine/src/cmd/sharing.rs | 4 +-- crates/engine/src/s3_connections.rs | 21 +++++++++++---- crates/engine/src/tests/engine_guards.rs | 34 ++++++++++++------------ 3 files changed, 35 insertions(+), 24 deletions(-) diff --git a/crates/engine/src/cmd/sharing.rs b/crates/engine/src/cmd/sharing.rs index 1fdee2c985..e7dbad9977 100644 --- a/crates/engine/src/cmd/sharing.rs +++ b/crates/engine/src/cmd/sharing.rs @@ -1112,8 +1112,8 @@ fn locator(l: &Layer, fields: Option<&[String]>, unplaced: &mut Unplaced, limite let mut taken = 0usize; for (row, ft) in ds.features.iter().enumerate() { if taken >= MAX_FEATURES { - // Rows with no geometry were never going to be in the locator. - *limited = ds.features.rows().skip(row).filter(|ft| ft.geometry().is_some()).count(); + // Rows with no geometry or an empty one were never going to be in the locator. + *limited = ds.features.rows().skip(row).filter(|ft| ft.geometry().is_some_and(|g| !g.extent().is_empty())).count(); break; } let Some(g) = &ft.geometry else { continue }; diff --git a/crates/engine/src/s3_connections.rs b/crates/engine/src/s3_connections.rs index b877e303b1..13ab61e49e 100644 --- a/crates/engine/src/s3_connections.rs +++ b/crates/engine/src/s3_connections.rs @@ -176,6 +176,7 @@ pub(crate) fn resolve_project_s3(s: &mut Session) { } } let mut pending = Vec::new(); + let mut waiting = 0usize; for g in &groups { let candidates: Vec = s.connections.connections.iter().filter(|c| matches(c, &g.endpoint, &g.bucket)).map(|c| c.id.clone()).collect(); @@ -183,10 +184,20 @@ pub(crate) fn resolve_project_s3(s: &mut Session) { { pending.push(existing.clone()); } else if let Some(p) = settle(s, g, may_bind) { + // Without binding, a new pending choice is said once for them all, below. + waiting += usize::from(!may_bind); pending.push(p); } } s.s3_pending = pending; + if waiting > 0 { + s.notify( + format!( + "{waiting} S3 bucket(s) that saved connections could read came from a project you didn't open yourself: choose which connection reads each (Data Sources › Choose S3 connection…); nothing is read until you do" + ), + false, + ); + } } /// What `g`'s sources do now: bound to its one candidate, kept for a choice, or as they were. @@ -239,10 +250,8 @@ fn settle(s: &mut Session, g: &Group, may_bind: bool) -> Option { block(s, g); let source = rewrite(s, g, &endpoint, binding).into_iter().next()?; let notice = match many { - _ if !may_bind => format!( - "Saved S3 connections could read the bucket '{}'{at}, but this project wasn't opened by you: choose which one reads its sources (Data Sources › Choose S3 connection…); nothing is read until you do", - g.bucket - ), + // Said once for every such bucket by the caller. + _ if !may_bind => String::new(), [only] => format!( "The saved S3 connection '{}' could read the bucket '{}'{at}, but it does not list that bucket: confirm it under Data Sources › Choose S3 connection…; nothing is read until you do", only.name, g.bucket @@ -253,7 +262,9 @@ fn settle(s: &mut Session, g: &Group, may_bind: bool) -> Option { g.bucket ), }; - s.notify(notice, false); + if !notice.is_empty() { + s.notify(notice, false); + } Some(PendingS3 { source, endpoint: g.endpoint.clone(), diff --git a/crates/engine/src/tests/engine_guards.rs b/crates/engine/src/tests/engine_guards.rs index 2457320ded..a903ebe710 100644 --- a/crates/engine/src/tests/engine_guards.rs +++ b/crates/engine/src/tests/engine_guards.rs @@ -2,7 +2,7 @@ //! feature-limit guards in `rustgis-engine`. use super::*; -use crate::policy::{AgentAccess, Call, Effects, Outcome, Pending, Revocation, Scope}; +use crate::policy::{AgentAccess, Call, Effects, Outcome, Revocation, Scope}; use std::sync::{ Arc, atomic::{AtomicBool, AtomicUsize, Ordering}, @@ -23,14 +23,6 @@ fn agent_scope(access: AgentAccess, label: &str) -> Scope { Scope::agent(access, false, label, None, Arc::new(Live(AtomicBool::new(true)))) } -fn pending(s: &Session, scope: &Scope, call: &Call) -> Pending { - match s.review(scope, call) { - Outcome::NeedsApproval(p) => p, - Outcome::Refused(e) => panic!("refused instead of a review: {e}"), - Outcome::Allowed => panic!("expected approval requirement"), - } -} - /// A counting secret store for verifying that non-reserved scopes never read saved credentials. #[cfg(not(target_arch = "wasm32"))] struct CountingSecrets { @@ -94,17 +86,19 @@ fn s3_list_by_bucket_does_not_attach_reserved_credentials_for_agent_or_assistant assert!(!seen.lock().unwrap().is_empty(), "user listing should reach the signed endpoint"); seen.lock().unwrap().clear(); - // Agent (Allow) scope has Network but not Reserved: must not attach the signed connection. - let call = Call::command("s3.list", json!({"bucket": bucket})); + // Agent (Allow) scope has Network but not Reserved: the listing it would send is anonymous and + // never goes to the signed endpoint (checked on the address, so no request leaves the test). let agent = agent_scope(AgentAccess::Allow, "s3-agent"); - assert!(s.run_scoped(agent, &call).is_err(), "agent must not list through the signed session connection"); - assert!(seen.lock().unwrap().is_empty(), "agent listing must not reach the signed endpoint"); + let agent_url = s.with_scope(agent, |s| crate::cmd::s3::bucket_list_url(s, bucket, "", None, None)).unwrap().unwrap(); + assert!(crate::render::rustgis_tiles::s3::split_anonymous(&agent_url).1, "agent listing must be anonymous: {agent_url}"); + assert!(!agent_url.contains(base.as_str()), "agent listing must not go to the signed endpoint: {agent_url}"); // Assistant approved for Network (not Reserved) must also not attach the signed connection. let assistant = assistant_scope(29001); - let p = pending(&s, &assistant, &call); - assert!(s.run_permitted(assistant.clone(), p.allow(), &call).is_err(), "assistant must not list through the signed session connection"); - assert!(seen.lock().unwrap().is_empty(), "assistant listing must not reach the signed endpoint"); + let asst_url = s.with_scope(assistant.clone(), |s| crate::cmd::s3::bucket_list_url(s, bucket, "", None, None)).unwrap().unwrap(); + assert!(crate::render::rustgis_tiles::s3::split_anonymous(&asst_url).1, "assistant listing must be anonymous: {asst_url}"); + assert!(!asst_url.contains(base.as_str()), "assistant listing must not go to the signed endpoint: {asst_url}"); + assert!(seen.lock().unwrap().is_empty(), "no scoped listing may reach the signed endpoint"); // Implicit AWS connection (no custom endpoint): non-reserved scopes must wrap the list URL as // anonymous so transport `s3::prepare` / `signer_for` never signs it with the implicit bucket @@ -314,7 +308,7 @@ fn non_reserved_scopes_do_not_auto_resolve_saved_keychain_logins() { "non-reserved scope must leave the bucket for the user's choice: {:?}", s.s3_pending ); - assert!(s.notices_since(0).iter().any(|n| n.text.contains("guarded-bucket") && n.text.contains("Choose S3 connection"))); + assert!(s.notices_since(0).iter().any(|n| n.text.starts_with("1 S3 bucket(s)") && n.text.contains("Choose S3 connection"))); s.run_scoped(agent, &Call::command("layer.addLayerFile", json!({"text": pg_lyr_text}))).unwrap(); assert_eq!(store.loads(), loads_before, "non-reserved scope must not load saved DB credentials"); @@ -555,6 +549,12 @@ fn web_map_and_locator_notify_when_feature_limit_is_reached() { "webMap must emit counted limit notice: {web_notices:?}" ); + // Rows the locator would leave out anyway (no geometry, an empty one) aren't counted as cut by + // the limit. + let places = &mut big.map_mut().layers[0].dataset; + for (id, geometry) in [(300_001, None), (300_002, Some(Geometry::MultiPoint(Vec::new())))] { + places.features.push(Feature { id, geometry, attrs: vec![AttrValue::Text("p".into())] }); + } let mark = big.notice_mark(); big.run("share.locator", &json!({"layer": "Places", "path": dir.join("big.rgisloc").display().to_string()})).unwrap(); let loc_notices: Vec = big.notices_since(mark).iter().map(|n| n.text.clone()).collect(); From 2d0eca17a2b40f650fa53b969cc01f7ad1e24440 Mon Sep 17 00:00:00 2001 From: giswqs Date: Sat, 28 Nov 2026 21:43:35 -0500 Subject: [PATCH 4/7] Ask for service logins from peer text, guard named S3 listings, count empty rows cheaply A scope that may not use saved logins leaves a service connection with a login asking for it (a password request) instead of skipping service resolution silently. bucket_list_url refuses a named connection itself outside a reserved scope. The locator's limit count tells empty geometries by their parts instead of computing every extent. --- crates/engine/src/cmd/s3.rs | 3 +++ crates/engine/src/cmd/sharing.rs | 16 ++++++++++-- crates/engine/src/service_logins.rs | 11 ++++++++- crates/engine/src/tests/engine_guards.rs | 31 ++++++++++++++++++++++++ 4 files changed, 58 insertions(+), 3 deletions(-) diff --git a/crates/engine/src/cmd/s3.rs b/crates/engine/src/cmd/s3.rs index 3a746a9d10..6f12a741f5 100644 --- a/crates/engine/src/cmd/s3.rs +++ b/crates/engine/src/cmd/s3.rs @@ -217,6 +217,9 @@ pub(crate) fn bucket_list_url( token: Option<&str>, named: Option<&s3::Connection>, ) -> Result { + if named.is_some() && !s.policy_allows_reserved() { + return Err("listing through a named S3 connection requires user authorization".into()); + } let allow_implicit = !s.web_logins.is_anonymous() && s.policy_allows_reserved(); let conn = named.cloned().or_else(|| s3::for_bucket(bucket).filter(|c| allow_implicit || c.credentials.is_none())); let url = s3::list_url(bucket, prefix, token, conn.as_ref()); diff --git a/crates/engine/src/cmd/sharing.rs b/crates/engine/src/cmd/sharing.rs index e7dbad9977..373206d6fd 100644 --- a/crates/engine/src/cmd/sharing.rs +++ b/crates/engine/src/cmd/sharing.rs @@ -1085,6 +1085,17 @@ fn web_layer_zip(s: &Session, l: &Layer, unplaced: &mut Unplaced, limited: &mut parts.zip() } +/// Whether `g` has no coordinates at all (an empty extent), found from its parts without reading +/// every vertex. +fn geometry_is_empty(g: &Geometry) -> bool { + match g { + Geometry::Point(_) => false, + Geometry::MultiPoint(points) => points.is_empty(), + Geometry::Line(parts) => parts.iter().all(Vec::is_empty), + Geometry::Polygon(polygons) => polygons.iter().all(|rings| rings.iter().all(Vec::is_empty)), + } +} + /// A locator: searchable place names and where they are. #[derive(Clone, Debug, Serialize, Deserialize)] pub struct Locator { @@ -1112,8 +1123,9 @@ fn locator(l: &Layer, fields: Option<&[String]>, unplaced: &mut Unplaced, limite let mut taken = 0usize; for (row, ft) in ds.features.iter().enumerate() { if taken >= MAX_FEATURES { - // Rows with no geometry or an empty one were never going to be in the locator. - *limited = ds.features.rows().skip(row).filter(|ft| ft.geometry().is_some_and(|g| !g.extent().is_empty())).count(); + // Rows with no geometry or an empty one were never going to be in the locator. Told + // apart by their parts, not their vertices, so this pass stays cheap. + *limited = ds.features.rows().skip(row).filter(|ft| ft.geometry().is_some_and(|g| !geometry_is_empty(g))).count(); break; } let Some(g) = &ft.geometry else { continue }; diff --git a/crates/engine/src/service_logins.rs b/crates/engine/src/service_logins.rs index 7df1cc0f09..1ff37b8e4e 100644 --- a/crates/engine/src/service_logins.rs +++ b/crates/engine/src/service_logins.rs @@ -1193,12 +1193,17 @@ fn reads(s: &Session) -> BTreeMap<(String, String), Reads> { /// layers record, the one chosen this session, or the only one. Several, a missing login, or a /// recorded connection this computer doesn't have are asked about ([`LoginRequest`]), never /// guessed. +/// +/// Under a scope that may not use saved logins by itself (a peer's text, an agent's import), a +/// connection with a login is never logged in to here: its layers ask for the login instead +/// ([`LoginReason::Password`]), which the user gives explicitly. pub(crate) fn resolve(s: &mut Session, only: Option<&BTreeSet>) { // Imports and nested commands a plugin runs must not adopt a login before their additions // have been marked anonymous at the plugin boundary. - if s.web_logins.is_anonymous() || !s.policy_allows_reserved() { + if s.web_logins.is_anonymous() { return; } + let may_login = s.policy_allows_reserved(); let mut pending = Vec::new(); let mut touched = BTreeSet::new(); let mut rebind_failures = BTreeMap::new(); @@ -1255,6 +1260,10 @@ pub(crate) fn resolve(s: &mut Session, only: Option<&BTreeSet>) { } continue; }; + if !may_login && !c.auth.is_empty() { + pending.push(request(LoginReason::Password, vec![c.id.clone()])); + continue; + } if recorded_id != c.id { record_choice(s, &origin, &recorded_id, &c); } diff --git a/crates/engine/src/tests/engine_guards.rs b/crates/engine/src/tests/engine_guards.rs index a903ebe710..fa0fa6fc44 100644 --- a/crates/engine/src/tests/engine_guards.rs +++ b/crates/engine/src/tests/engine_guards.rs @@ -633,3 +633,34 @@ fn outcome_name(o: &Outcome) -> &'static str { Outcome::Refused(_) => "Refused", } } + +/// A peer's project text never logs in to a saved service connection by itself: its layers ask +/// for the login instead, while the user's own open logs in as before. +#[test] +fn peer_text_asks_for_a_service_login_instead_of_using_it() { + let origin = "https://peer-service.example.org"; + let mut s = Session::new(Project::default()); + let id = s + .run("connection.new", &json!({"kind": "wmts", "address": format!("{origin}/wmts"), "auth": "header", "keyName": "X-Key"})) + .unwrap()["id"] + .as_str() + .unwrap() + .to_string(); + s.run("connection.login", &json!({"id": id, "apiKey": "peer-sentinel-1"})).unwrap(); + let mut p = Project::default(); + let mut t = rustgis_map::TileLayer::new("Secured", rustgis_map::TileKind::Raster, format!("{origin}/tiles/{{z}}/{{x}}/{{y}}.png")); + t.connection = id.clone(); + p.map_mut().tiles.push(t); + let text = serde_json::to_string(&p).unwrap(); + let header = |s: &Session| { + s.map().tiles.first().and_then(|t| crate::render::rustgis_tiles::logins::apply(&t.url).ok().flatten()).and_then(|a| a.header) + }; + + s.open_peer_text(crate::Peer::Embedder, &text).unwrap(); + assert!(header(&s).is_none(), "peer text must not carry the saved service login"); + let requests = s.run("connection.list", &Value::Null).unwrap()["loginRequests"].clone(); + assert_eq!(requests[0]["reason"], "password", "the layer asks for the login: {requests}"); + + s.run("project.openText", &json!({"text": text})).unwrap(); + assert_eq!(header(&s).map(|(_, v)| v).as_deref(), Some("peer-sentinel-1"), "the user's own open logs in"); +} From cbc3a400910cc069bfb2aa495f97dfb8426fc470 Mon Sep 17 00:00:00 2001 From: giswqs Date: Sun, 29 Nov 2026 16:24:31 -0500 Subject: [PATCH 5/7] Say database waiting once on Bridge open, unread S3 buckets once A Bridge open with retained database keys said which layers wait for a password twice: once inside the peer scope, before the retained login was tried, and again after. It is now said once, after the optional retained login, for every Bridge open. Buckets no saved connection reads were said with one notice each. They are now collected while settling and said in one notice with the source and bucket counts, naming the first five buckets by endpoint. --- crates/engine/src/peer.rs | 8 ++- crates/engine/src/s3_connections.rs | 71 +++++++++++++++++-- crates/engine/src/tests/engine_guards.rs | 34 +++++++++ .../src/tests/remembered_database_packets.rs | 20 ++++++ 4 files changed, 124 insertions(+), 9 deletions(-) diff --git a/crates/engine/src/peer.rs b/crates/engine/src/peer.rs index 68748d4d4a..a638b7e7b9 100644 --- a/crates/engine/src/peer.rs +++ b/crates/engine/src/peer.rs @@ -455,8 +455,9 @@ impl Session { // modified sources stay under Scope::peer() and never trigger saved login resolution. if !retained_db_keys.is_empty() { crate::cmd::connections::resolve_keys(self, &retained_db_keys); - crate::cmd::connections::note_waiting(self); } + // Said once, after any retained login, so a layer just logged in isn't listed. + crate::cmd::connections::note_waiting(self); let (exchange, omitted) = Exchange::record(&self.project, self.opened); self.exchange = Some(exchange); report.not_retained = omitted; @@ -512,7 +513,10 @@ impl Session { crate::cmd::project::reset_to(self, p); self.path = None; crate::cmd::connections::resolve_project(self); - crate::cmd::connections::note_waiting(self); + if peer != Peer::Bridge { + // Bridge says it in `open_peer_text`, after logging retained databases in. + crate::cmd::connections::note_waiting(self); + } self.revision = self.revision.wrapping_add(1); Ok((report, retained_db_keys)) } diff --git a/crates/engine/src/s3_connections.rs b/crates/engine/src/s3_connections.rs index 13ab61e49e..7ab237ca16 100644 --- a/crates/engine/src/s3_connections.rs +++ b/crates/engine/src/s3_connections.rs @@ -177,13 +177,14 @@ pub(crate) fn resolve_project_s3(s: &mut Session) { } let mut pending = Vec::new(); let mut waiting = 0usize; + let mut unread = Unread::default(); for g in &groups { let candidates: Vec = s.connections.connections.iter().filter(|c| matches(c, &g.endpoint, &g.bucket)).map(|c| c.id.clone()).collect(); if let Some(existing) = s.s3_pending.iter().find(|p| p.endpoint == g.endpoint && p.bucket == g.bucket && p.candidates == candidates) { pending.push(existing.clone()); - } else if let Some(p) = settle(s, g, may_bind) { + } else if let Some(p) = settle(s, g, may_bind, &mut unread) { // Without binding, a new pending choice is said once for them all, below. waiting += usize::from(!may_bind); pending.push(p); @@ -198,11 +199,70 @@ pub(crate) fn resolve_project_s3(s: &mut Session) { false, ); } + if unread.buckets > 0 { + s.notify( + format!( + "{} source(s) read {} S3 bucket(s) that no saved connection reads: add one under Data Sources › Connections, then open the project again. They are {}", + unread.sources, + unread.buckets, + unread.named() + ), + true, + ); + } +} + +/// The buckets no saved connection reads, said once for them all after settling. +#[derive(Default)] +struct Unread { + /// How many addresses read these buckets. + sources: usize, + /// How many buckets. + buckets: usize, + /// The first few buckets, quoted, under the endpoint they are at, in the order found. + named: Vec<(String, Vec)>, +} + +impl Unread { + /// Bucket names given in the notice; the rest are counted. + const NAMED: usize = 5; + + fn add(&mut self, endpoint: &str, bucket: &str, sources: usize) { + self.sources = self.sources.saturating_add(sources); + self.buckets = self.buckets.saturating_add(1); + if self.buckets > Self::NAMED { + return; + } + let quoted = format!("'{bucket}'"); + match self.named.iter_mut().find(|(e, _)| e == endpoint) { + Some((_, buckets)) => buckets.push(quoted), + None => self.named.push((endpoint.to_string(), vec![quoted])), + } + } + + /// The named buckets grouped by endpoint. An endpoint is never followed by punctuation, which + /// would stop it being read as an address when the notice is redacted. + fn named(&self) -> String { + let mut text = self + .named + .iter() + .map(|(endpoint, buckets)| { + let buckets = buckets.join(", "); + if endpoint.is_empty() { buckets } else { format!("{buckets} at {endpoint}") } + }) + .collect::>() + .join(" and "); + if let Some(more) = self.buckets.checked_sub(Self::NAMED).filter(|&n| n > 0) { + text.push_str(&format!(" and {more} more")); + } + text + } } /// What `g`'s sources do now: bound to its one candidate, kept for a choice, or as they were. -/// `may_bind` false keeps any candidate for the user's choice instead of binding it. -fn settle(s: &mut Session, g: &Group, may_bind: bool) -> Option { +/// `may_bind` false keeps any candidate for the user's choice instead of binding it. A bucket no +/// saved connection reads is added to `unread`, which the caller says once. +fn settle(s: &mut Session, g: &Group, may_bind: bool, unread: &mut Unread) -> Option { let candidates: Vec = s.connections.connections.iter().filter(|c| matches(c, &g.endpoint, &g.bucket)).cloned().collect(); let at = match g.endpoint.as_deref() { Some(e) if !e.is_empty() => format!(" at {e}"), @@ -217,10 +277,7 @@ fn settle(s: &mut Session, g: &Group, may_bind: bool) -> Option { reopen_where(s, |a| g.has(a)); } else { let n = block(s, g); - s.notify( - format!("{n} source(s) read the S3 bucket '{}'{at}, and no saved connection does: add one under Data Sources › Connections, then open the project again", g.bucket), - true, - ); + unread.add(g.endpoint.as_deref().unwrap_or_default(), &g.bucket, n); } None } diff --git a/crates/engine/src/tests/engine_guards.rs b/crates/engine/src/tests/engine_guards.rs index fa0fa6fc44..bf16a9cd77 100644 --- a/crates/engine/src/tests/engine_guards.rs +++ b/crates/engine/src/tests/engine_guards.rs @@ -664,3 +664,37 @@ fn peer_text_asks_for_a_service_login_instead_of_using_it() { s.run("project.openText", &json!({"text": text})).unwrap(); assert_eq!(header(&s).map(|(_, v)| v).as_deref(), Some("peer-sentinel-1"), "the user's own open logs in"); } + +/// Buckets no saved connection reads are said in one notice with their count, not one per bucket. +#[test] +fn s3_buckets_without_a_saved_connection_are_said_once() { + use rustgis_data::{Dataset, Field, FieldType, GeometryType}; + use rustgis_map::Layer; + use rustgis_map::source::SourceLayer; + + let mut s = Session::new(Project::default()); + let mark = s.notice_mark(); + crate::s3_connections::resolve_project_s3(&mut s); + assert!( + !s.notices_since(mark).iter().any(|n| n.text.contains("no saved connection reads")), + "a project without S3 sources says nothing" + ); + + let buckets = ["unread-a", "unread-a", "unread-b", "unread-c", "unread-d", "unread-e", "unread-f", "unread-g"]; + for (i, bucket) in (1u32..).zip(buckets) { + let mut layer = + Layer::new(i, Dataset::new(format!("S3Unread{i}"), GeometryType::Point, vec![Field::new("id", FieldType::Integer)])); + let mut src = SourceLayer::default(); + src.path = Some(rustgis_data::s3_address::bind("", "http://127.0.0.1:9", &format!("s3://{bucket}/data.fgb")).unwrap()); + layer.source = Some(src); + s.project.map_mut().add_layer(layer); + } + let mark = s.notice_mark(); + crate::s3_connections::resolve_project_s3(&mut s); + let said: Vec<_> = + s.notices_since(mark).iter().filter(|n| n.text.contains("no saved connection reads")).map(|n| n.text.clone()).collect(); + assert_eq!(said.len(), 1, "one notice for every unread bucket: {said:?}"); + let text = said.first().unwrap(); + assert!(text.starts_with("8 source(s) read 7 S3 bucket(s)"), "{text}"); + assert!(text.contains("at http://127.0.0.1:9 and 2 more"), "{text}"); +} diff --git a/crates/engine/src/tests/remembered_database_packets.rs b/crates/engine/src/tests/remembered_database_packets.rs index d97b89348e..3a8109bee7 100644 --- a/crates/engine/src/tests/remembered_database_packets.rs +++ b/crates/engine/src/tests/remembered_database_packets.rs @@ -977,3 +977,23 @@ fn peer_database_replacement_requires_the_exact_previously_shared_source() { } } } + +/// A Bridge round trip of a retained database source says once that its layers wait for a +/// password, after the retained login was tried, not once before it and again after. +#[test] +fn peer_bridge_retained_database_says_waiting_once() { + if isolated("peer_bridge_retained_database_says_waiting_once") { + return; + } + let server = Server::start(false); + let mut s = app(Arc::new(MemorySecrets::new()), "{}"); + remember(&mut s, "Refusing", &server.address, "RGSYNTH_refused_password"); + s.project = serde_json::from_str(&project_layers(&server.address, 1)).unwrap(); + let (text, _) = s.peer_text(crate::Peer::Bridge).unwrap(); + let mut incoming: Value = serde_json::from_str(&text).unwrap(); + incoming["maps"][0]["layers"][0]["visible"] = json!(false); + let mark = s.notice_mark(); + s.open_peer_text(crate::Peer::Bridge, &incoming.to_string()).unwrap(); + let waiting: Vec<_> = s.notices_since(mark).iter().filter(|n| n.text.contains("need its password")).map(|n| n.text.clone()).collect(); + assert_eq!(waiting.len(), 1, "one waiting notice per connection: {waiting:?}"); +} From 70733b37378e0bdfa2dbabcdbc7211e2de9b03c4 Mon Sep 17 00:00:00 2001 From: giswqs Date: Sun, 29 Nov 2026 16:51:49 -0500 Subject: [PATCH 6/7] Refuse an unplaceable layer on a web map past the feature limit The early return for a used-up feature budget ran before the layer's conversion to longitude/latitude, so a layer that can't be given there was skipped without an error once an earlier layer had used up the limit, and its features were counted under the feature-limit notice. The conversion now runs first, so that layer fails the page as before. --- crates/engine/src/cmd/sharing.rs | 7 +++-- crates/engine/src/tests/engine_guards.rs | 36 ++++++++++++++++++++++++ 2 files changed, 40 insertions(+), 3 deletions(-) diff --git a/crates/engine/src/cmd/sharing.rs b/crates/engine/src/cmd/sharing.rs index 8f77899568..83bb704c6d 100644 --- a/crates/engine/src/cmd/sharing.rs +++ b/crates/engine/src/cmd/sharing.rs @@ -661,17 +661,18 @@ fn styled_features( let left_out = |from: usize| { l.dataset.features.rows().enumerate().skip(from).filter(|(i, ft)| rows.get(*i) == Some(&true) && ft.geometry().is_some()).count() }; + // A layer that can't be given in longitude/latitude fails the page, budget left or not. + let to = l.dataset.lonlat_conversion().map_err(|e| format!("{}: {e}", l.name))?; if *budget == 0 { - *limited += left_out(0); + *limited = limited.saturating_add(left_out(0)); return Ok(()); } let opacity = 1.0 - f64::from(l.transparency.clamp(0.0, 100.0)) / 100.0; // Its symbol by expression (no map scale: the page zooms on its own). let styler = l.styler(None); - let to = l.dataset.lonlat_conversion().map_err(|e| format!("{}: {e}", l.name))?; for (row, ft) in l.dataset.features.rows().enumerate() { if *budget == 0 { - *limited += left_out(row); + *limited = limited.saturating_add(left_out(row)); break; } if rows.get(row) != Some(&true) { diff --git a/crates/engine/src/tests/engine_guards.rs b/crates/engine/src/tests/engine_guards.rs index bf16a9cd77..6fc47bbcea 100644 --- a/crates/engine/src/tests/engine_guards.rs +++ b/crates/engine/src/tests/engine_guards.rs @@ -698,3 +698,39 @@ fn s3_buckets_without_a_saved_connection_are_said_once() { assert!(text.starts_with("8 source(s) read 7 S3 bucket(s)"), "{text}"); assert!(text.contains("at http://127.0.0.1:9 and 2 more"), "{text}"); } + +/// A layer that can't be given in longitude/latitude still fails the web map once an earlier layer +/// has used up the feature limit, rather than being counted as left out by the limit. +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn web_map_past_the_feature_limit_still_refuses_a_layer_it_cannot_place() { + use rustgis_data::{Dataset, Feature, Field, FieldType, Geometry, GeometryType, Value as AttrValue}; + use rustgis_geom::Coord; + use rustgis_map::Layer; + + let point = |id: u64| Feature { id, geometry: Some(Geometry::Point(Coord::new(0.0, 0.0))), attrs: vec![AttrValue::Text("p".into())] }; + let mut big = Dataset::new("Many", GeometryType::Point, vec![Field::new("name", FieldType::Text)]); + big.features.reserve(200_001); + for id in 1..=200_001 { + big.features.push(point(id)); + } + let mut odd = Dataset::new("Unplaceable", GeometryType::Point, vec![Field::new("name", FieldType::Text)]); + odd.features.push(point(1)); + let mut saved = serde_json::to_value(&odd).unwrap(); + saved["held_in"] = json!({"Epsg": 1}); + let odd: Dataset = serde_json::from_value(saved).unwrap(); + assert!(odd.lonlat_conversion().is_err(), "the fixture's system must not convert"); + + let mut s = Session::new(Project::default()); + // The big layer comes first on the page and uses up the limit. + s.map_mut().add_layer(Layer::new(1, big)); + s.map_mut().add_layer(Layer::new(2, odd)); + let dir = std::env::temp_dir().join(format!("rustgis-share-unplaceable-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + let mark = s.notice_mark(); + let err = s.run("share.webMap", &json!({"path": dir.join("map.html").display().to_string()})).unwrap_err(); + assert!(err.contains("Unplaceable"), "{err}"); + assert!(s.notices_since(mark).iter().all(|n| !n.text.contains("feature limit")), "{:?}", s.notices_since(mark)); + let _ = std::fs::remove_dir_all(&dir); +} From 30e08b7ee860069c9791e038b0ff2394fbd5d367 Mon Sep 17 00:00:00 2001 From: giswqs Date: Sun, 29 Nov 2026 17:10:24 -0500 Subject: [PATCH 7/7] State the Bridge login boundary and the share passes' exemption open_peer_text's doc comment said no command runs with User authority, but a Bridge open resolves the saved logins of retained database sources after the peer scope returns. The comment now names Exchange::retain as the boundary there, and a test checks that Bridge text naming a database source the exchange didn't retain loads no saved login and sends no password. The counting passes past the share feature limit say they have no Cancel check, like the rest of the Share As commands, which run on the UI thread; that follow-up is noted on the audit tracking issue. --- crates/engine/src/cmd/sharing.rs | 10 +++++-- crates/engine/src/peer.rs | 7 ++++- .../src/tests/remembered_database_packets.rs | 26 +++++++++++++++++++ 3 files changed, 40 insertions(+), 3 deletions(-) diff --git a/crates/engine/src/cmd/sharing.rs b/crates/engine/src/cmd/sharing.rs index 83bb704c6d..1a6f39cfc0 100644 --- a/crates/engine/src/cmd/sharing.rs +++ b/crates/engine/src/cmd/sharing.rs @@ -657,7 +657,11 @@ fn styled_features( mut each: impl FnMut(Value) -> Result<(), String>, ) -> Result<(), String> { let rows = l.visible_rows(); - // Visible features with a geometry from `from` on: the ones the limit leaves out. + // Visible features with a geometry from `from` on: the ones the limit leaves out. Features past + // the limit are never converted, so one that couldn't be placed is counted here too: it is left + // out of the page either way. One pass over the rows, reading no coordinates and without a + // Cancel check, like the rest of this command, which runs on the UI thread (not in + // `exports::IN_BACKGROUND`). let left_out = |from: usize| { l.dataset.features.rows().enumerate().skip(from).filter(|(i, ft)| rows.get(*i) == Some(&true) && ft.geometry().is_some()).count() }; @@ -1127,7 +1131,9 @@ fn locator(l: &Layer, fields: Option<&[String]>, unplaced: &mut Unplaced, limite for (row, ft) in ds.features.iter().enumerate() { if taken >= MAX_FEATURES { // Rows with no geometry or an empty one were never going to be in the locator. Told - // apart by their parts, not their vertices, so this pass stays cheap. + // apart by their parts, not their vertices, so this pass stays cheap. It has no Cancel + // check, like the rest of `share.locator`, which runs on the UI thread (not in + // `exports::IN_BACKGROUND`). *limited = ds.features.rows().skip(row).filter(|ft| ft.geometry().is_some_and(|g| !geometry_is_empty(g))).count(); break; } diff --git a/crates/engine/src/peer.rs b/crates/engine/src/peer.rs index a638b7e7b9..4e68eaf299 100644 --- a/crates/engine/src/peer.rs +++ b/crates/engine/src/peer.rs @@ -445,7 +445,12 @@ impl Session { } /// Replaces a project synchronously with peer/import semantics. No command runs with User - /// authority. Reset advances generation, clears item trust, history, pending work and active + /// authority: the text is read and the project reset under [`Scope::peer`](crate::policy::Scope::peer). + /// The one exception is `Peer::Bridge`: after the peer scope returns, the saved logins of the + /// database sources [`Exchange::retain`] kept are resolved under the caller's authority. Retain + /// is the boundary there: it returns only sources whose address and value match the live + /// project and the last exchange exactly, so incoming text can't name a new database to log + /// in to. Reset advances generation, clears item trust, history, pending work and active /// connections; old approvals and continuations must bind to that generation. pub fn open_peer_text(&mut self, peer: Peer, text: &str) -> Result { let (mut report, retained_db_keys) = self.with_scope(crate::policy::Scope::peer(), |s| s.open_peer_text_scoped(peer, text))??; diff --git a/crates/engine/src/tests/remembered_database_packets.rs b/crates/engine/src/tests/remembered_database_packets.rs index 3a8109bee7..316d9349ac 100644 --- a/crates/engine/src/tests/remembered_database_packets.rs +++ b/crates/engine/src/tests/remembered_database_packets.rs @@ -997,3 +997,29 @@ fn peer_bridge_retained_database_says_waiting_once() { let waiting: Vec<_> = s.notices_since(mark).iter().filter(|n| n.text.contains("need its password")).map(|n| n.text.clone()).collect(); assert_eq!(waiting.len(), 1, "one waiting notice per connection: {waiting:?}"); } + +/// Bridge text that names a database source the project doesn't hold as it was shared (a new +/// table on the same database) never loads a saved login, though the Bridge resolves retained +/// sources' logins with the caller's authority. +#[test] +fn peer_bridge_text_naming_a_new_database_source_never_loads_a_saved_login() { + if isolated("peer_bridge_text_naming_a_new_database_source_never_loads_a_saved_login") { + return; + } + let server = Server::start(true); + let store = Counting::over(Arc::new(MemorySecrets::new())); + let mut s = Session::new(Project::default()); + s.database_logins.set_store(Some(store.clone())); + remember(&mut s, "Bridge", &server.address, "RGSYNTH_bridge_password"); + // Whatever the login itself sent. + while server.packets.try_recv().is_ok() {} + s.project = serde_json::from_str(&project_layers(&server.address, 1)).unwrap(); + let (text, _) = s.peer_text(crate::Peer::Bridge).unwrap(); + let mut incoming: Value = serde_json::from_str(&text).unwrap(); + incoming["maps"][0]["layers"][0]["source"]["postgis"]["table"] = json!("unapproved"); + let loads = store.loads(); + let report = s.open_peer_text(crate::Peer::Bridge, &incoming.to_string()).unwrap(); + assert_eq!(store.loads(), loads, "a source the exchange didn't retain must not load a saved login"); + server.empty(); + assert!(report.notices().iter().any(|n| n.contains("reconnect")), "{report:?}"); +}