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 83b46ece2d..994014ad64 100644 --- a/crates/engine/src/cmd/cube.rs +++ b/crates/engine/src/cmd/cube.rs @@ -1111,6 +1111,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/embeddings.rs b/crates/engine/src/cmd/embeddings.rs index 7a509ef68c..8868c8ecd9 100644 --- a/crates/engine/src/cmd/embeddings.rs +++ b/crates/engine/src/cmd/embeddings.rs @@ -438,6 +438,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 54ea061ad1..7993e5fdfd 100644 --- a/crates/engine/src/cmd/items.rs +++ b/crates/engine/src/cmd/items.rs @@ -256,7 +256,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 79babcf21a..9cabd4f7d4 100644 --- a/crates/engine/src/cmd/layer.rs +++ b/crates/engine/src/cmd/layer.rs @@ -4471,6 +4471,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/project.rs b/crates/engine/src/cmd/project.rs index f5e6625576..aaab639e1f 100644 --- a/crates/engine/src/cmd/project.rs +++ b/crates/engine/src/cmd/project.rs @@ -831,7 +831,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/s3.rs b/crates/engine/src/cmd/s3.rs index 7150009630..6f12a741f5 100644 --- a/crates/engine/src/cmd/s3.rs +++ b/crates/engine/src/cmd/s3.rs @@ -206,6 +206,35 @@ 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 { + 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()); + 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,14 +296,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 (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 9550412fd7..1a6f39cfc0 100644 --- a/crates/engine/src/cmd/sharing.rs +++ b/crates/engine/src/cmd/sharing.rs @@ -282,16 +282,27 @@ fn share_bytes_inner(s: &mut Session, kind: &str, p: &Value, out: Output<'_>) -> 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, out, &mut held))?; let mut unplaced = Unplaced::default(); - let html = out.file(|w| write_web_map(w, &m, &m.name, &mut unplaced))?; + let mut limited = 0usize; + let html = out.file(|w| write_web_map(w, &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, m.name)) } "webLayer" => { let mut l = layer_of(s, p)?; load_whole(s, &mut l, out, &mut held)?; let mut unplaced = Unplaced::default(); - let zip = web_layer_zip(s, &l, &mut unplaced, out)?; + let mut limited = 0usize; + let zip = web_layer_zip(s, &l, &mut unplaced, &mut limited, out)?; 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" => { @@ -304,8 +315,12 @@ fn share_bytes_inner(s: &mut Session, kind: &str, p: &Value, out: Output<'_>) -> 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, out)?; + let mut limited = 0usize; + let loc = locator(&l, fields.as_deref(), &mut unplaced, &mut limited, out)?; 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(), out.json(&loc)?, l.name.clone())) } "geodataService" => { @@ -633,20 +648,35 @@ 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`. +/// 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, 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. 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() + }; + // 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 = 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 = limited.saturating_add(left_out(row)); break; } if rows.get(row) != Some(&true) { @@ -674,7 +704,8 @@ fn styled_features( /// 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. Its layers are /// written to `page` as they are made, so a page held to a limit stops there. -fn write_web_map(page: &mut dyn std::io::Write, m: &Map, title: &str, unplaced: &mut Unplaced) -> Result<(), String> { +/// Visible features past the page's feature limit are counted in `limited`. +fn write_web_map(page: &mut dyn std::io::Write, m: &Map, title: &str, unplaced: &mut Unplaced, limited: &mut usize) -> Result<(), String> { let failed = |e: std::io::Error| e.to_string(); let mut budget = MAX_FEATURES; let mut pictures = 0usize; @@ -724,7 +755,7 @@ const L=["#, // A feature at a time, its members in the order a whole layer's value has them. write!(page, r#"{separator}{{"features":["#).map_err(failed)?; let mut between = ""; - styled_features(l, &mut budget, unplaced, |feature| { + styled_features(l, &mut budget, unplaced, limited, |feature| { write!(page, "{between}{}", script_json(&feature)).map_err(failed)?; between = ","; Ok(()) @@ -1036,7 +1067,7 @@ fn ogc_entries(parts: &mut Parts<'_>, title: &str, layers: &[&Dataset], unplaced } /// 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, out: Output<'_>) -> Result, String> { +fn web_layer_zip(s: &Session, l: &Layer, unplaced: &mut Unplaced, limited: &mut usize, out: Output<'_>) -> Result, String> { let mut parts = out.parts(); ogc_entries(&mut parts, &l.name, &[&l.dataset], unplaced)?; parts.make("style.json".into(), |w| serde_json::to_writer_pretty(w, &web_style(l)).map_err(|e| e.to_string()))?; @@ -1057,10 +1088,21 @@ fn web_layer_zip(s: &Session, l: &Layer, unplaced: &mut Unplaced, out: Output<'_ m.camera.clamp(); } // The page's features are the same, already counted by the collection. - parts.make("index.html".into(), |w| write_web_map(w, &m, &l.name, &mut Unplaced::default()))?; + parts.make("index.html".into(), |w| write_web_map(w, &m, &l.name, &mut Unplaced::default(), limited))?; 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 { @@ -1070,7 +1112,7 @@ pub struct Locator { pub entries: Vec<(String, f64, f64)>, } -fn locator(l: &Layer, fields: Option<&[String]>, unplaced: &mut Unplaced, out: Output<'_>) -> Result { +fn locator(l: &Layer, fields: Option<&[String]>, unplaced: &mut Unplaced, limited: &mut usize, out: Output<'_>) -> Result { let ds = &l.dataset; let fis: Vec = match fields { Some(fs) => { @@ -1085,7 +1127,16 @@ fn locator(l: &Layer, fields: Option<&[String]>, unplaced: &mut Unplaced, out: O let mut entries = Vec::new(); // The entries' text so far, less than the file they make comes to. let mut held = 0usize; - for (row, ft) in ds.features.iter().enumerate().take(MAX_FEATURES) { + 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. Told + // 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; + } let Some(g) = &ft.geometry else { continue }; let e = g.extent(); if e.is_empty() { @@ -1102,6 +1153,7 @@ fn locator(l: &Layer, fields: Option<&[String]>, unplaced: &mut Unplaced, out: O 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 c6ea748728..f507d5ef2f 100644 --- a/crates/engine/src/cmd/zarr.rs +++ b/crates/engine/src/cmd/zarr.rs @@ -505,6 +505,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..4e68eaf299 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. @@ -435,13 +445,32 @@ 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 { - self.with_scope(crate::policy::Scope::peer(), |s| s.open_peer_text_scoped(peer, text))? + 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); + } + // 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; + } + 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)); @@ -459,9 +488,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() @@ -490,14 +518,12 @@ impl Session { 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; + if peer != Peer::Bridge { + // Bridge says it in `open_peer_text`, after logging retained databases in. + crate::cmd::connections::note_waiting(self); } - Ok(report) + self.revision = self.revision.wrapping_add(1); + Ok((report, retained_db_keys)) } } 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 faab657112..5934eab835 100644 --- a/crates/engine/src/policy/dispatch.rs +++ b/crates/engine/src/policy/dispatch.rs @@ -445,16 +445,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", } )); } @@ -760,9 +763,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..7ab237ca16 100644 --- a/crates/engine/src/s3_connections.rs +++ b/crates/engine/src/s3_connections.rs @@ -162,8 +162,11 @@ 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. +/// and when maps or layers are imported, never from a frame. Under a scope that may not use saved +/// logins by itself (a peer's text, a plugin, an imported item), no source is bound: a bucket a +/// saved connection could read waits for the user's choice ([`PendingS3`]), with a notice. pub(crate) fn resolve_project_s3(s: &mut Session) { + let may_bind = s.policy_allows_reserved(); let mut groups: Vec = Vec::new(); for a in s.project.addresses_mut() { if let Some(u) = unresolved(a) @@ -173,21 +176,93 @@ 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) { + } 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); } } 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, + ); + } + 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. -fn settle(s: &mut Session, g: &Group) -> 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}"), @@ -202,34 +277,38 @@ fn settle(s: &mut Session, g: &Group) -> 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 } - [c] if c.options.get("buckets").is_some_and(|scope| scope.split(',').any(|b| b.trim() == g.bucket)) => match bind_group(s, g, c) { - Ok(_) => None, - Err(e) => { - // Kept blocked, naming the one connection that could read it (an older project's - // address now names its endpoint). - let endpoint = endpoint_of(c).unwrap_or_default(); - block(s, g); - let source = rewrite(s, g, &endpoint, "").into_iter().next()?; - s.notify( - format!("Log in to the saved S3 connection '{}' to open the sources that read the bucket '{}': {e}", c.name, g.bucket), - false, - ); - Some(PendingS3 { source, endpoint: Some(endpoint), bucket: g.bucket.clone(), candidates: vec![c.id.clone()] }) + [c] if may_bind && c.options.get("buckets").is_some_and(|scope| scope.split(',').any(|b| b.trim() == g.bucket)) => { + match bind_group(s, g, c) { + Ok(_) => None, + Err(e) => { + // Kept blocked, naming the one connection that could read it (an older project's + // address now names its endpoint). + let endpoint = endpoint_of(c).unwrap_or_default(); + block(s, g); + let source = rewrite(s, g, &endpoint, "").into_iter().next()?; + s.notify( + format!( + "Log in to the saved S3 connection '{}' to open the sources that read the bucket '{}': {e}", + c.name, g.bucket + ), + false, + ); + Some(PendingS3 { source, endpoint: Some(endpoint), bucket: g.bucket.clone(), candidates: vec![c.id.clone()] }) + } } - }, + } many => { let endpoint = g.endpoint.clone().unwrap_or_default(); let binding = if g.endpoint.is_none() { s3_address::LEGACY } else { "" }; block(s, g); let source = rewrite(s, g, &endpoint, binding).into_iter().next()?; let notice = match many { + // 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 @@ -240,7 +319,9 @@ fn settle(s: &mut Session, g: &Group) -> 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/service_logins.rs b/crates/engine/src/service_logins.rs index d828bc775e..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() { 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.rs b/crates/engine/src/tests.rs index f060157010..338d38c556 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -108,6 +108,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..6fc47bbcea --- /dev/null +++ b/crates/engine/src/tests/engine_guards.rs @@ -0,0 +1,736 @@ +//! 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, 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)))) +} + +/// 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: 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"); + 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 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 + // 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"))] +#[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"); + // The bucket waits for the user's choice instead, and says so. + assert!( + s.s3_pending.iter().any(|p| p.bucket == "guarded-bucket" && p.candidates == vec![s3_id.clone()]), + "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.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"); + 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 + // (as when the project opens again, with no choice pending). + s.s3_pending.clear(); + 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:?}" + ); + + // 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(); + 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", + } +} + +/// 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"); +} + +/// 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}"); +} + +/// 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); +} diff --git a/crates/engine/src/tests/remembered_database_packets.rs b/crates/engine/src/tests/remembered_database_packets.rs index d97b89348e..316d9349ac 100644 --- a/crates/engine/src/tests/remembered_database_packets.rs +++ b/crates/engine/src/tests/remembered_database_packets.rs @@ -977,3 +977,49 @@ 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:?}"); +} + +/// 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:?}"); +}