From a14b533f01aa59e770e364f6faab4d1c6b688322 Mon Sep 17 00:00:00 2001 From: giswqs Date: Wed, 25 Nov 2026 09:17:37 -0500 Subject: [PATCH 01/20] fix(engine): harden plugin isolation, command effects, and credential scrubbing Enforce anonymous outbound fetches under anonymous session scopes across S3, Zarr, URL, service, STAC, and Earthdata reads, and strip S3 wrapper prefixes in anonymous request normalization. Declare network reach when map.setTiles attaches legend URLs, include legend URLs in no-network plugin verification with snapshot-based rollback instead of removing modified tile layers, and scan nested arrays and objects with a node bound in plugin address checks. Scrub structured legend parameters and MySQL, MariaDB, and SQL Server addresses on durable save, scrub active logins and S3 capability wrappers in project logs and MCP audit logs, guard earthdata.status keychain restoration by scope and opt-in, mark mutating layout.arrangement calls as reserved, and exclude direct database and SQL commands from plugins. --- crates/assistant/src/audit.rs | 46 +- crates/engine/src/cmd/cube.rs | 4 +- crates/engine/src/cmd/earthdata.rs | 37 +- crates/engine/src/cmd/layer.rs | 41 +- crates/engine/src/cmd/plugin_fetch.rs | 38 +- crates/engine/src/cmd/plugins.rs | 38 +- crates/engine/src/cmd/s3.rs | 10 +- crates/engine/src/cmd/service.rs | 35 +- crates/engine/src/cmd/stac.rs | 22 +- crates/engine/src/cmd/tiles.rs | 24 +- crates/engine/src/cmd/zarr.rs | 205 +++++---- crates/engine/src/policy/decide.rs | 23 + crates/engine/src/policy/effects.rs | 7 + crates/engine/src/project_log.rs | 25 +- crates/engine/src/roles.rs | 77 +++- crates/engine/src/service_logins.rs | 23 +- .../engine/src/tests/scopes_and_redaction.rs | 401 ++++++++++++++++++ 17 files changed, 865 insertions(+), 191 deletions(-) diff --git a/crates/assistant/src/audit.rs b/crates/assistant/src/audit.rs index e1ff9f9d3e..3a704c1d57 100644 --- a/crates/assistant/src/audit.rs +++ b/crates/assistant/src/audit.rs @@ -164,8 +164,15 @@ fn normalized_args(tool: &str, arguments: &Value) -> Value { /// A string argument without its secrets: an address (one word with a scheme, or a database /// connection string) loses its password, keys and tokens; `password=…` in a keyword connection -/// string is withheld. Other text is kept as it is, not cut at a `?` or `#`. +/// string is withheld; active web logins and `rustgis-s3:` capability wrappers are scrubbed. Other +/// text is kept as it is, not cut at a `?` or `#`. fn redact_string(s: &str) -> String { + let s = rustgis_engine::sources::scrub_s3_wrappers(&rustgis_engine::render::rustgis_tiles::logins::scrub(s)); + let out = redact_string_inner(&s); + rustgis_engine::sources::scrub_s3_wrappers(&rustgis_engine::render::rustgis_tiles::logins::scrub(&out)) +} + +fn redact_string_inner(s: &str) -> String { let t = s.trim(); let lower = t.to_ascii_lowercase(); // A password given as `password=…` or `password: …` (a keyword connection string, quoted or @@ -508,4 +515,41 @@ mod tests { assert!(output.starts_with("# [1 further script line(s) not recorded]\n")); assert!(!output.contains("RGSYNTH_omitted_line")); } + + /// Active web-service logins and `rustgis-s3:` capability wrappers are scrubbed from both + /// string arguments and tool error replies in the MCP audit log. + #[test] + fn audit_scrubs_active_logins_and_s3_wrappers() { + let mut s = rustgis_engine::Session::new(rustgis_engine::Project::default()); + s.database_logins.set_store(None); + let conn = s + .run( + "connection.new", + &json!({"kind": "wms", "address": "https://audit-active.example.org/wms", "auth": "header", "keyName": "X-Key"}), + ) + .unwrap(); + let active_secret = "RGSYNTH_active_audit_login_9921"; + s.run("connection.login", &json!({"id": conn["id"], "apiKey": active_secret})).unwrap(); + + let wrapped = "rustgis-s3:0123456789abcdef:22:https://s3.example.org:https://s3.example.org/b/k?token=RGSYNTH_s3_tok_9921"; + let scrubbed_login = redact_string(&format!("upstream rejected {active_secret}")); + assert!(!scrubbed_login.contains(active_secret), "{scrubbed_login}"); + let scrubbed_s3 = redact_string(&format!("could not read {wrapped}")); + assert!(!scrubbed_s3.contains("rustgis-s3:") && !scrubbed_s3.contains("RGSYNTH_s3_tok_9921"), "{scrubbed_s3}"); + + let call = json!({"jsonrpc": "2.0", "id": 1, "method": "tools/call", "params": {"name": "list_layers", "arguments": {}}}); + let err = json!({ + "jsonrpc": "2.0", + "id": 1, + "result": { + "isError": true, + "content": [{"type": "text", "text": format!("failed on {wrapped} with {active_secret}")}] + } + }); + let lines = entries("mcp", &call.to_string(), Some(&err.to_string()), Duration::ZERO, 0); + let error_text = lines[0]["error"].as_str().unwrap_or(""); + assert!(!error_text.contains(active_secret), "{error_text}"); + assert!(!error_text.contains("rustgis-s3:"), "{error_text}"); + assert!(!error_text.contains("RGSYNTH_s3_tok_9921"), "{error_text}"); + } } diff --git a/crates/engine/src/cmd/cube.rs b/crates/engine/src/cmd/cube.rs index 78e9b63991..3ec0d67793 100644 --- a/crates/engine/src/cmd/cube.rs +++ b/crates/engine/src/cmd/cube.rs @@ -184,9 +184,9 @@ impl TimeCube for ZarrCube { // many dates doesn't push out the slices a layer following the slider holds. A step // never written is `None`: no value that date, as the Zarr summary takes it. let zt = &self.0.zt; - let r = match super::zarr::kept_slice(&super::zarr::slice_key(zt, i)) { + let r = match super::zarr::kept_slice(&super::zarr::slice_key_for(zt, i, self.0.anonymous)) { Some(r) => r, - None => match super::zarr::read_slice(zt, i)? { + None => match super::zarr::read_slice_with(zt, i, self.0.anonymous)? { Some(r) => Arc::new(r), None => return Ok(None), }, diff --git a/crates/engine/src/cmd/earthdata.rs b/crates/engine/src/cmd/earthdata.rs index 7dc062692e..fd7309b69c 100644 --- a/crates/engine/src/cmd/earthdata.rs +++ b/crates/engine/src/cmd/earthdata.rs @@ -24,10 +24,17 @@ pub fn commands() -> Vec { C::new("earthdata.logout", "Forget Earthdata Login Token", "Home › Add › Web Data › NASA Earthaccess", logout).roles(&[]).effects(crate::policy::Effects::NONE.with(crate::policy::Effect::Reserved)) .view() .params("{} — forgets the token for the session, deletes the one remembered on this computer and empties the download cache (what was read with it)"), - C::new("earthdata.status", "Earthdata Login Status", "Home › Add › Web Data › NASA Earthaccess", |_s, _p| { - // Asked for: the token remembered on this computer is read, if it wasn't. - earthdata::restore(); - earthdata::forget_if_expired(); + C::new("earthdata.status", "Earthdata Login Status", "Home › Add › Web Data › NASA Earthaccess", |s, _p| { + // Only a native user session may restore from the keychain (when saved secrets are + // enabled) or mutate process-wide expiry state; other scopes get a read-only status. + if s.policy_user() { + if s.saved_secrets_opted_in { + earthdata::restore(); + } + if s.saved_secrets_opted_in || !earthdata::is_remembered() { + earthdata::forget_if_expired(); + } + } Ok(status()) }).roles(&[]).effects(crate::policy::Effects::NONE) .view() @@ -92,17 +99,17 @@ pub fn collections_query(p: &Value) -> Result { Ok(earthdata::collections_url(keyword, short, b(p, "cloudHosted").unwrap_or(false), limit, page)) } -fn collections(_s: &mut Session, p: &Value) -> CmdResult { +fn collections(s: &mut Session, p: &Value) -> CmdResult { let url = collections_query(p)?; - let bytes = answer_or_fetch(p, &url)?; + let bytes = answer_or_fetch(p, &url, s.web_logins.is_anonymous())?; let found = earthdata::parse_collections(&bytes)?; Ok(json!({"count": found.len(), "collections": found.iter().map(earthdata::collection_json).collect::>()})) } /// The collection a short name means: its cloud-hosted, newest version. -fn resolve(short: &str) -> Result { +fn resolve(short: &str, anonymous: bool) -> Result { let url = earthdata::collections_url("", Some(short), false, 50, 1); - let found = earthdata::parse_collections(&fetch(&url)?)?; + let found = earthdata::parse_collections(&fetch(&url, anonymous)?)?; earthdata::best(&found, short).cloned().ok_or_else(|| format!("NASA's CMR has no collection named {short}")) } @@ -111,7 +118,7 @@ pub fn granules_query(s: &Session, p: &Value) -> Result { let collection = ps(p, "collection").map(str::trim).filter(|c| !c.is_empty()); let collection = match (collection, ps(p, "shortName").map(str::trim).filter(|c| !c.is_empty())) { (Some(c), _) => c.to_string(), - (None, Some(short)) => resolve(short)?.id, + (None, Some(short)) => resolve(short, s.web_logins.is_anonymous())?.id, (None, None) => return Err("give collection (a concept id earthdata.collections lists) or shortName".into()), }; // Where the map is, unless asked for everywhere. @@ -122,7 +129,7 @@ pub fn granules_query(s: &Session, p: &Value) -> Result { fn granules(s: &mut Session, p: &Value) -> CmdResult { let url = granules_query(s, p)?; - let bytes = answer_or_fetch(p, &url)?; + let bytes = answer_or_fetch(p, &url, s.web_logins.is_anonymous())?; let found = earthdata::parse_granules(&bytes)?; let mut out = json!({"count": found.len(), "granules": found.iter().map(earthdata::granule_json).collect::>()}); if b(p, "footprints").unwrap_or(true) { @@ -138,19 +145,19 @@ fn granules(s: &mut Session, p: &Value) -> CmdResult { } /// The answer the app fetched, or the one fetched now. -fn answer_or_fetch(p: &Value, url: &str) -> Result, String> { +fn answer_or_fetch(p: &Value, url: &str, anonymous: bool) -> Result, String> { match ps(p, "answer") { Some(a) => Ok(a.as_bytes().to_vec()), - None => fetch(url), + None => fetch(url, anonymous), } } #[cfg(not(target_arch = "wasm32"))] -fn fetch(url: &str) -> Result, String> { - crate::render::rustgis_tiles::cache::download_blocking(url) +fn fetch(url: &str, anonymous: bool) -> Result, String> { + crate::render::rustgis_tiles::cache::download_blocking(&crate::service_logins::fetch_url(anonymous, url)) } #[cfg(target_arch = "wasm32")] -fn fetch(_url: &str) -> Result, String> { +fn fetch(_url: &str, _anonymous: bool) -> Result, String> { Err("in the web app, search NASA Earthdata with Home › Add › Web Data › NASA Earthaccess".into()) } diff --git a/crates/engine/src/cmd/layer.rs b/crates/engine/src/cmd/layer.rs index 41b265a254..1ded279290 100644 --- a/crates/engine/src/cmd/layer.rs +++ b/crates/engine/src/cmd/layer.rs @@ -5288,8 +5288,10 @@ fn add_url_as_given(s: &mut Session, p: &Value) -> CmdResult { // A byte range of a GRIB file (`"bytes"`, #2428): only that range is downloaded, and read as // the file. The browser refuses it ([`byte_range`]). #[cfg(not(target_arch = "wasm32"))] + let anonymous = s.web_logins.is_anonymous() || b(p, "anonymous") == Some(true); + #[cfg(not(target_arch = "wasm32"))] if let Some(range) = byte_range(p, url)? { - return add_url_range(s, p, url, range, public); + return add_url_range(s, p, url, range, public, anonymous); } #[cfg(target_arch = "wasm32")] byte_range(p, url)?; @@ -5376,7 +5378,7 @@ fn add_url_as_given(s: &mut Session, p: &Value) -> CmdResult { #[cfg(target_arch = "wasm32")] let opened = rustgis_data::source::open_url_now(url); #[cfg(not(target_arch = "wasm32"))] - let opened = rustgis_data::source::open_url_blocking(url); + let opened = rustgis_data::source::open_url_blocking(&crate::service_logins::fetch_url(anonymous, url)); match opened { Ok(src) => return add_remote(s, p, url, src), Err(e) if e.to_string().contains(rustgis_data::source::remote::READ_WHOLE) => {} @@ -5425,11 +5427,12 @@ fn add_url_as_given(s: &mut Session, p: &Value) -> CmdResult { } return Ok(r); } + let fetch_url = crate::service_logins::fetch_url(anonymous, url); // An address without a file name may be a GeoTIFF too: its first bytes are read to see, // and anything that doesn't answer as one is downloaded whole, as before. let unnamed = !tiff && is_unnamed_url(url); if (tiff || unnamed) && !scan && !super::b(p, "whole").unwrap_or(false) { - let cog = match crate::render::rustgis_tiles::cog::probe_blocking(url) { + let cog = match crate::render::rustgis_tiles::cog::probe_blocking(&fetch_url) { Ok(cog) => cog, Err(_) if unnamed => false, Err(e) => return Err(named(e)), @@ -5439,17 +5442,17 @@ fn add_url_as_given(s: &mut Session, p: &Value) -> CmdResult { } } let bytes = if rustgis_data::io::shapefile_part_urls(url).is_some() { - download_shapefile_blocking_with(url, public)? + download_shapefile_blocking_with(url, public, anonymous)? } else if public { crate::render::rustgis_tiles::cache::download_public_within( - url, + &fetch_url, crate::render::rustgis_tiles::cache::MAX_DOWNLOAD, crate::render::rustgis_tiles::cache::BLOCKING_TIMEOUT, ) .map_err(crate::render::rustgis_tiles::cache::large_file_hint) .map_err(named)? } else { - crate::render::rustgis_tiles::cache::download_blocking(url).map_err(named)? + crate::render::rustgis_tiles::cache::download_blocking(&fetch_url).map_err(named)? }; let name = url_file_name(url, &bytes).map_err(named)?; let left_out = parts_left_out(url, &bytes, p); @@ -5567,7 +5570,7 @@ pub fn range_failed(url: &str, e: String) -> String { /// /// [`cache::NO_RANGES`]: crate::render::rustgis_tiles::cache::NO_RANGES #[cfg(not(target_arch = "wasm32"))] -fn add_url_range(s: &mut Session, p: &Value, url: &str, range: (u64, u64), public: bool) -> CmdResult { +fn add_url_range(s: &mut Session, p: &Value, url: &str, range: (u64, u64), public: bool, anonymous: bool) -> CmdResult { use crate::render::rustgis_tiles::cache; if s.leave_downloads { let mut asked = p.clone(); @@ -5576,12 +5579,13 @@ fn add_url_range(s: &mut Session, p: &Value, url: &str, range: (u64, u64), publi } let named = |e: String| crate::sources::message_with_address(url, &e); let ranged = ranged_address(url, range); + let fetch_ranged = crate::service_logins::fetch_url(anonymous, &ranged); let len = usize::try_from(range.1 - range.0 + 1).unwrap_or(usize::MAX); let public = public || cache::ceiling_for(url) == crate::render::rustgis_tiles::address::Reach::Public; let bytes = if public { - cache::download_public_within(&ranged, len, cache::BLOCKING_TIMEOUT) + cache::download_public_within(&fetch_ranged, len, cache::BLOCKING_TIMEOUT) } else { - cache::download_blocking_within(&ranged, len, cache::BLOCKING_TIMEOUT) + cache::download_blocking_within(&fetch_ranged, len, cache::BLOCKING_TIMEOUT) }; // Without `large_file_hint`: a range timing out isn't helped by downloading the whole file. let bytes = bytes.map_err(|e| range_failed(&ranged, e)).map_err(named)?; @@ -5716,7 +5720,7 @@ fn parts_left_out(url: &str, bytes: &[u8], p: &Value) -> Option { /// `.prj` and `.cpg` beside it (each but the `.dbf` only when it is there), zipped, within one /// download's budget together. #[cfg(not(target_arch = "wasm32"))] -fn download_shapefile_blocking_with(url: &str, public: bool) -> Result, String> { +fn download_shapefile_blocking_with(url: &str, public: bool, anonymous: bool) -> Result, String> { use crate::render::rustgis_tiles::cache; let parts = rustgis_data::io::shapefile_part_urls(url).unwrap_or_default(); if public { @@ -5728,10 +5732,13 @@ fn download_shapefile_blocking_with(url: &str, public: bool) -> Result, let until = std::time::Instant::now() + cache::BLOCKING_TIMEOUT; // Past it, a part isn't asked for at all (a zero timeout may mean none), and a timeout says // where a large file goes instead. - let within = |u: &str, max: usize, omit: &'static [u16]| match until.saturating_duration_since(std::time::Instant::now()) { - w if w.is_zero() => Err(cache::large_file_hint("timed out".into())), - w if public => cache::download_public_omitting_within(u, max, w, omit).map_err(cache::large_file_hint), - w => cache::download_blocking_omitting_within(u, max, w, omit).map_err(cache::large_file_hint), + let within = |u: &str, max: usize, omit: &'static [u16]| { + let fetch_u = crate::service_logins::fetch_url(anonymous, u); + match until.saturating_duration_since(std::time::Instant::now()) { + w if w.is_zero() => Err(cache::large_file_hint("timed out".into())), + w if public => cache::download_public_omitting_within(&fetch_u, max, w, omit).map_err(cache::large_file_hint), + w => cache::download_blocking_omitting_within(&fetch_u, max, w, omit).map_err(cache::large_file_hint), + } }; let shp = within(url, cache::MAX_DOWNLOAD, &[]).map_err(|e| part_failed(url, e))?; // Already zipped (a server answering the address with its parts): read as it is. @@ -6348,7 +6355,11 @@ pub fn window_asked_in(s: &Session, p: &Value, seen: Option<[f64; 4]>) -> Result /// `layer.addUrl` with `"bbox"`, for those that wait: read here and added. #[cfg(not(target_arch = "wasm32"))] fn add_cog_window(s: &mut Session, p: &Value, url: &str) -> CmdResult { - let read = read_cog_window(&window_settled(s, p, url, None)?)?; + let mut asked = window_settled(s, p, url, None)?; + if s.web_logins.is_anonymous() || b(p, "anonymous") == Some(true) { + asked.url = crate::service_logins::fetch_url(true, &asked.url); + } + let read = read_cog_window(&asked)?; add_window(s, p, read) } diff --git a/crates/engine/src/cmd/plugin_fetch.rs b/crates/engine/src/cmd/plugin_fetch.rs index 261aec087f..1c7297f155 100644 --- a/crates/engine/src/cmd/plugin_fetch.rs +++ b/crates/engine/src/cmd/plugin_fetch.rs @@ -219,7 +219,7 @@ impl Session { if !self.plugin_held() { return Ok(()); } - let named = web_addresses(params); + let named = web_addresses(params)?; for url in &named { // An address wrong some other way (spaces in it) is the command's to judge; it is // held to the internet below all the same. @@ -236,15 +236,35 @@ impl Session { } } +/// The most JSON nodes inspected when scanning a plugin command's parameters for web addresses. +const MAX_ADDRESS_SCAN_NODES: usize = 4096; + /// The web addresses among a command's own parameters, not inside the contents of a file it -/// gives (`data`, `text`). -fn web_addresses(params: &Value) -> Vec<&str> { - let Some(o) = params.as_object() else { return Vec::new() }; - o.iter() - .filter(|(key, _)| !matches!(key.as_str(), "data" | "text")) - .filter_map(|(_, v)| v.as_str().map(str::trim)) - .filter(|v| is_web_address(v)) - .collect() +/// gives (`data`, `text`). Walks nested arrays and objects iteratively up to +/// [`MAX_ADDRESS_SCAN_NODES`] nodes; overly complex parameters are refused rather than skipped. +fn web_addresses(params: &Value) -> Result, String> { + let Some(o) = params.as_object() else { return Ok(Vec::new()) }; + let mut stack: Vec<&Value> = o.iter().filter(|(key, _)| !matches!(key.as_str(), "data" | "text")).map(|(_, v)| v).collect(); + let mut out = Vec::new(); + let mut visited = 0usize; + while let Some(v) = stack.pop() { + visited += 1; + if visited > MAX_ADDRESS_SCAN_NODES { + return Err("command parameters are too complex for a plugin network check".into()); + } + match v { + Value::String(s) => { + let s = s.trim(); + if is_web_address(s) { + out.push(s); + } + } + Value::Array(a) => stack.extend(a.iter()), + Value::Object(m) => stack.extend(m.values()), + _ => {} + } + } + Ok(out) } /// Whether `v` is a web address the app fetches (`http://`, `https://` or `s3://`), as given or diff --git a/crates/engine/src/cmd/plugins.rs b/crates/engine/src/cmd/plugins.rs index ad5be9231d..66c94bb4e2 100644 --- a/crates/engine/src/cmd/plugins.rs +++ b/crates/engine/src/cmd/plugins.rs @@ -726,14 +726,22 @@ impl Bridge<'_> { return Err(format!("{label}: {why}")); } // Without `network`, no command may bring in a tile address (a map file read from text - // carries its tile layers), or change where an existing layer fetches from: any such - // layer is taken out again. Where a layer fetches from is decided by its address, kind, - // subdomains and row order. Its name, attribution and opacity never reach a server, and - // its tile size reaches one only as `{width}`/`{height}` (256 or 512). - let fetched = |t: &rustgis_map::TileLayer| (t.url.clone(), t.kind, t.subdomains.clone(), t.tms); + // carries its tile layers), or change where an existing layer or its legends fetch from: + // on violation, each pre-existing map's tiles are restored from its snapshot rather than + // dropping modified layers. Where a layer fetches from is decided by its address, kind, + // subdomains, row order and legend addresses. Its name, attribution and opacity never + // reach a server, and its tile size reaches one only as `{width}`/`{height}` (256 or 512). + let fetched = |t: &rustgis_map::TileLayer| { + (t.url.clone(), t.kind, t.subdomains.clone(), t.tms, t.legends.iter().map(|l| l.url.clone()).collect::>()) + }; let tile_sources = |s: &Session| -> std::collections::HashSet<_> { s.project.maps.iter().flat_map(|m| &m.tiles).map(fetched).collect() }; - let before = (!self.plugin.manifest.has(Permission::Network)).then(|| tile_sources(self.s)); + let before = (!self.plugin.manifest.has(Permission::Network)).then(|| { + let sources = tile_sources(self.s); + let snapshots: std::collections::HashMap> = + self.s.project.maps.iter().map(|m| (m.instance_id(), m.tiles.clone())).collect(); + (sources, snapshots) + }); // The plugin command took the undo snapshot: the commands it runs are part of it, and say // what they did in its account ([`Session::shared_step`]). let mut res = crate::service_logins::anonymously(self.s, true, |s| { @@ -741,14 +749,16 @@ impl Bridge<'_> { super::workflows::steps_of(s, |s| s.invoke(op, crate::policy::Txn::Shared)) }) .unwrap_or_else(|_| Err(format!("{label} failed unexpectedly"))); - if let Some(before) = before { - let mut dropped = false; - for m in &mut self.s.project.maps { - let n = m.tiles.len(); - m.tiles.retain(|t| before.contains(&fetched(t))); - dropped |= m.tiles.len() != n; - } - if dropped { + if let Some((sources, mut snapshots)) = before { + let violated = self.s.project.maps.iter().flat_map(|m| &m.tiles).any(|t| !sources.contains(&fetched(t))); + if violated { + for m in &mut self.s.project.maps { + if let Some(saved) = snapshots.remove(&m.instance_id()) { + m.tiles = saved; + } else { + m.tiles.retain(|t| sources.contains(&fetched(t))); + } + } res = Err(format!("{} needs the 'network' permission to add tile layers", self.plugin.manifest.name)); } } diff --git a/crates/engine/src/cmd/s3.rs b/crates/engine/src/cmd/s3.rs index 7150009630..3e827ec6f8 100644 --- a/crates/engine/src/cmd/s3.rs +++ b/crates/engine/src/cmd/s3.rs @@ -267,13 +267,17 @@ 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 anonymous = s.web_logins.is_anonymous(); + let conn = named.or_else(|| s3::for_bucket(&bucket).filter(|c| !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, + Some(c) => { + let url = through(c, url)?; + crate::service_logins::fetch_url(anonymous && c.credentials.is_none(), &url) + } + None => crate::service_logins::fetch_url(anonymous, &url), }; let page = s3::parse_list(&fetch(&url)?)?; prefixes.extend(page.prefixes); diff --git a/crates/engine/src/cmd/service.rs b/crates/engine/src/cmd/service.rs index d16cf33337..ba805f2015 100644 --- a/crates/engine/src/cmd/service.rs +++ b/crates/engine/src/cmd/service.rs @@ -246,7 +246,14 @@ type FetchDocument<'a> = &'a mut dyn FnMut(&str, Reach) -> Result)>) -> Result { - read_documents_with(s, p, left, explicit_map, &mut fetch_document) + #[cfg_attr(target_arch = "wasm32", expect(unused_variables, reason = "blocking fetches are desktop only"))] + let anonymous = s.web_logins.is_anonymous() || super::b(p, "anonymous") == Some(true); + let mut fetch = |url: &str, ceiling: Reach| { + #[cfg(not(target_arch = "wasm32"))] + let url = crate::service_logins::fetch_url(anonymous, url); + fetch_document(&url, ceiling) + }; + read_documents_with(s, p, left, explicit_map, &mut fetch) } /// [`read_documents`] with its fetch given, so the reach each document is fetched within can be @@ -637,10 +644,12 @@ pub(crate) fn add_service_layer( zoom: Option, file: impl FnOnce(&[u8]) -> Result, ) -> CmdResult { + let anonymous = s.web_logins.is_anonymous() || super::b(p, "anonymous") == Some(true); let fetch = |s: &mut Session, url: &str| { download_layer_with(s, name, url, cache::MAX_DOWNLOAD, true, |url, max, timeout, ceiling| { let ceiling = if public { ceiling.min(Reach::Public) } else { ceiling }; - cache::download_blocking_with_origin_within(url, max, timeout, &[], ceiling) + let fetch_url = crate::service_logins::fetch_url(anonymous, url); + cache::download_blocking_with_origin_within(&fetch_url, max, timeout, &[], ceiling) }) }; let first = fetch(s, url); @@ -1609,7 +1618,8 @@ fn add_discovered(s: &mut Session, p: &Value, url: &str, want: &str, found: &Dis } return super::layer::add_url(s, &q); } - let bytes = crate::render::rustgis_tiles::cache::download_blocking(&get).map_err(|e| format!("{name}: {e}"))?; + let fetch_get = crate::service_logins::fetch_url(anonymous, &get); + let bytes = crate::render::rustgis_tiles::cache::download_blocking(&fetch_get).map_err(|e| format!("{name}: {e}"))?; coverage_check(&name, &bytes)?; let r = super::raster::add_coverage_bytes(s, &json!({"name": name}), format!("{name}.tif"), bytes, asked)?; mark_service_source(s, &r, &get); @@ -1750,7 +1760,7 @@ fn coverage_request( } let info = match ps(p, "describe") { Some(text) => rustgis_data::ogc::parse_describe(c, text.as_bytes())?, - None => fetch_describe(c, &describe)?, + None => fetch_describe(c, &describe, anonymous)?, }; // A description read from the internet (here, or by the app, which records it) holds the // GetCoverage request built from it there too, however the endpoint's name resolves then. @@ -1796,9 +1806,10 @@ fn coverage_request_from( /// Reads a coverage's description, recording one that came from the internet /// ([`cache::restrict_to_public`]) so the GetCoverage request built from it goes only there. #[cfg(not(target_arch = "wasm32"))] -fn fetch_describe(c: &Coverage, describe: &str) -> Result { +fn fetch_describe(c: &Coverage, describe: &str, anonymous: bool) -> Result { + let fetch_url = crate::service_logins::fetch_url(anonymous, describe); let fetched = cache::download_blocking_with_origin_within( - describe, + &fetch_url, cache::MAX_DOWNLOAD, cache::BLOCKING_TIMEOUT, &[], @@ -1813,7 +1824,7 @@ fn fetch_describe(c: &Coverage, describe: &str) -> Result Result { +fn fetch_describe(c: &Coverage, _: &str, _: bool) -> Result { Err(format!("{}: in the web app, the description is read first (give it as \"describe\")", c.id)) } @@ -1905,12 +1916,13 @@ pub(super) fn catalog_search_read(s: &mut Session, p: &Value, read: Option within.min(Reach::Public), None => within, }; + let anonymous = s.web_logins.is_anonymous() || super::b(p, "anonymous") == Some(true); let (page, reach) = match ps(p, "text") { Some(text) => ( rustgis_data::ogc::parse_records(&request, text.as_bytes()).map_err(|e| crate::sources::message_with_address(url, &e))?, within, ), - None => fetch_records(url, &request, within)?, + None => fetch_records(url, &request, within, anonymous)?, }; let mut dropped = 0usize; let records: Vec = page @@ -1952,8 +1964,9 @@ pub(super) fn catalog_search_read(s: &mut Session, p: &Value, read: Option Result<(rustgis_data::ogc::RecordPage, Reach), String> { - let fetched = cache::download_blocking_with_origin_within(request, cache::MAX_DOWNLOAD, cache::BLOCKING_TIMEOUT, &[], ceiling) +fn fetch_records(url: &str, request: &str, ceiling: Reach, anonymous: bool) -> Result<(rustgis_data::ogc::RecordPage, Reach), String> { + let fetch_url = crate::service_logins::fetch_url(anonymous, request); + let fetched = cache::download_blocking_with_origin_within(&fetch_url, cache::MAX_DOWNLOAD, cache::BLOCKING_TIMEOUT, &[], ceiling) .map_err(cache::large_file_hint) .map_err(|e| crate::sources::message_with_address(url, &e))?; let page = rustgis_data::ogc::parse_records(request, &fetched.bytes).map_err(|e| crate::sources::message_with_address(url, &e))?; @@ -1961,7 +1974,7 @@ fn fetch_records(url: &str, request: &str, ceiling: Reach) -> Result<(rustgis_da } #[cfg(target_arch = "wasm32")] -fn fetch_records(url: &str, _: &str, _: Reach) -> Result<(rustgis_data::ogc::RecordPage, Reach), String> { +fn fetch_records(url: &str, _: &str, _: Reach, _: bool) -> Result<(rustgis_data::ogc::RecordPage, Reach), String> { Err(crate::sources::message_with_address(url, "in the web app, use Home › Add › Add Data › From Service › Search Catalogue")) } diff --git a/crates/engine/src/cmd/stac.rs b/crates/engine/src/cmd/stac.rs index 78efa23cca..d590ea56c4 100644 --- a/crates/engine/src/cmd/stac.rs +++ b/crates/engine/src/cmd/stac.rs @@ -129,7 +129,8 @@ pub(super) fn collections(s: &mut Session, p: &Value) -> CmdResult { } else { stac::collections_url(&api) }; - let fetched = crate::render::rustgis_tiles::cache::download_blocking_with_origin(&url)?; + let fetch_url = crate::service_logins::fetch_url(s.web_logins.is_anonymous() || b(p, "anonymous") == Some(true), &url); + let fetched = crate::render::rustgis_tiles::cache::download_blocking_with_origin(&fetch_url)?; collections_json_from_origin(s, &api, &fetched.bytes, &fetched.origin) } } @@ -209,20 +210,21 @@ fn search(s: &mut Session, p: &Value) -> CmdResult { } #[cfg(not(target_arch = "wasm32"))] { + let anonymous = s.web_logins.is_anonymous() || b(p, "anonymous") == Some(true); // A shape goes in the body of a POST, which has no limit that matters; a server that // refuses it is asked again in the query, when the shape is short enough for one. let (fetched, posted) = if search.intersects.is_some() { - let post = stac::search_post_url(&api); + let post = crate::service_logins::fetch_url(anonymous, &stac::search_post_url(&api)); let body = stac::search_body(&search)?.to_string(); match crate::render::rustgis_tiles::cache::post_json_named_blocking_with_origin(&post, &body) { Ok(fetched) => (fetched, true), Err(e) => { - let url = stac::search_url(&api, &search).map_err(|_| e.clone())?; + let url = crate::service_logins::fetch_url(anonymous, &stac::search_url(&api, &search).map_err(|_| e.clone())?); (crate::render::rustgis_tiles::cache::download_blocking_with_origin(&url).map_err(|_| e)?, false) } } } else { - let url = stac::search_url(&api, &search)?; + let url = crate::service_logins::fetch_url(anonymous, &stac::search_url(&api, &search)?); (crate::render::rustgis_tiles::cache::download_blocking_with_origin(&url)?, false) }; let bytes = fetched.bytes; @@ -349,7 +351,7 @@ fn search_static(s: &mut Session, p: &Value, root: &str) -> CmdResult { } /// The item a command names: given whole, or by its address. -fn item(p: &Value) -> Result { +fn item(p: &Value, anonymous: bool) -> Result { if let Some(v) = p.get("item").filter(|v| v.is_object()) { // Given whole (by the assistant or a plugin, maybe from another answer): it came from no // address, so its assets may only be public web addresses. @@ -358,12 +360,13 @@ fn item(p: &Value) -> Result { let url = ps(p, "url").map(str::trim).filter(|u| !u.is_empty()).ok_or("give item (a STAC item) or url (an item's address)")?; #[cfg(target_arch = "wasm32")] { - let _ = url; + let _ = (url, anonymous); Err("in the web app, add STAC assets with Home › Add › Web Data › STAC Search".into()) } #[cfg(not(target_arch = "wasm32"))] { - item_downloaded(crate::render::rustgis_tiles::cache::download_blocking_fetched(url)?, url) + let fetch_url = crate::service_logins::fetch_url(anonymous, url); + item_downloaded(crate::render::rustgis_tiles::cache::download_blocking_fetched(&fetch_url)?, url) } } @@ -378,7 +381,7 @@ fn item_downloaded(fetched: crate::render::rustgis_tiles::cache::Fetched, reques fn add_asset(s: &mut Session, p: &Value) -> CmdResult { let bound = crate::service_logins::request_params(s, p)?; let p = bound.as_ref(); - let i = item(p)?; + let i = item(p, s.web_logins.is_anonymous() || b(p, "anonymous") == Some(true))?; let (key, href) = i.asset_href(ps(p, "asset"))?; // Codes for a failed retrieval (JAXA Earth's `dn.error`), which a data cube skips but a // single file draws as values: of the asset `asset_href` picked, by the same selector. @@ -560,7 +563,8 @@ pub fn cube_files(s: &mut Session, p: &Value, max_items: usize, mask: Option<&st if read.len() >= MAX_CUBE_PAGES { return Err(format!("more than {MAX_CUBE_PAGES} pages of results: take a shorter period or a smaller area")); } - let bytes = crate::render::rustgis_tiles::cache::download_blocking(&url)?; + let fetch_url = crate::service_logins::fetch_url(s.web_logins.is_anonymous() || b(p, "anonymous") == Some(true), &url); + let bytes = crate::render::rustgis_tiles::cache::download_blocking(&fetch_url)?; let (page, more) = stac::parse_items(&bytes, &url)?; read.push(url); if page.is_empty() { diff --git a/crates/engine/src/cmd/tiles.rs b/crates/engine/src/cmd/tiles.rs index 4539de577a..8bd1c99efa 100644 --- a/crates/engine/src/cmd/tiles.rs +++ b/crates/engine/src/cmd/tiles.rs @@ -10,15 +10,18 @@ use serde_json::{Value, json}; use super::{b, f, ps}; use crate::{CmdResult, CommandSpec as C, Session}; +/// Durable-output parameter roles for tile commands: `legend` holds structured URL configuration. +const TILE_ROLES: &[crate::ParamRole] = &[crate::ParamRole { key: "legend", role: crate::Role::Configuration }]; + /// Registers commands for tile-layer sources, drawing properties, coverage and celestial bodies. pub fn commands() -> Vec { vec![ - C::new("map.addTiles", "Add Tile Layer", "Home › Add", add).roles(&[]).effects(crate::policy::Effects::NONE.with(crate::policy::Effect::Network)).params( + C::new("map.addTiles", "Add Tile Layer", "Home › Add", add).roles(TILE_ROLES).effects(crate::policy::Effects::NONE.with(crate::policy::Effect::Network)).params( r#"{"url": "https://…/{z}/{x}/{y}.png" | vector tiles ".pbf" or TileJSON | MapLibre style.json | a PMTiles archive (web address or file path) | an MBTiles file path, "kind"?: "raster"|"vector"|"style"|"pmtiles"|"mbtiles" (guessed from the url), "name"?: text, "bounds"?: [west, south, east, north] (longitude/latitude coverage, when known), "attribution"?: text, "minZoom"?: number, "maxZoom"?: number, "tileSize"?: 256|512 (1024 too for a WMS or map service asked for in Web Mercator by its tiles' box: their pictures are asked for that size), "singleImage"?: bool (a WMS or map service: one picture of the view instead of tiles, so symbols and labels aren't cut at tile edges; tiles on the globe, a tilted map or a projection the service doesn't offer; by default on for one, unless tileSize is given), "tms"?: bool, "subdomains"?: [text], "layers"?: [vector tile layer names, drawn in colours of their own], "styleLayers"?: [MapLibre style layers drawing vector tiles instead (their source is the tiles')], "opacity"?: 0–1, "blend"?: "normal"|"multiply"|"screen"|"overlay"|"darken"|"lighten"|"difference" (how it combines with what is beneath), "resampling"?: "nearest"|"bilinear" (picture tiles drawn at a size other than their own: each pixel a block, or blended, the default), "overlay"?: bool (on top of the map's layers, as every new layer goes; without it a basemap, under them; one with the same address and role is replaced when it has the same name or the same look), "top"?: bool (on top of the map's layers, as a layer added as data goes; by default an overlay's place), "replace"?: bool (removes the other tile basemaps, not overlays), "id"?: catalog id, "view"?: bool (a MapLibre style: go to the place, zoom, bearing and pitch its root properties give, once it loads), "start"?, "end"?: dates a url with date placeholders ({date:YYYY-MM-DD}, {YYYY}) spans, turning the time slider on (or, when it is on, setting its span), "unit"?, "interval"?, "dates"?: its steps (as in time.set), "legend"?: "the web address of its legend picture (PNG or JPEG)" | [address | {"url": address, "minScale"?: scale denominator, "maxScale"?: one (the scales it is for, from minScale up to below maxScale)}] (at most 16; the Layers pane shows the one for the map's scale under the layer; service.add gives a WMS or WMTS layer its service's), "connection"?: "the id of the saved web-service connection it comes from (as service.add): the tile layer records it, and its tiles are read with its login"}"#, ), C::new("map.removeTiles", "Remove Tile Layer", "Home › Add", remove).roles(&[]).effects(crate::policy::Effects::NONE) .params(r#"{"name"?: text, "index"?: number, "id"?: catalog id} (removes every tile layer when none is given)"#), - C::new("map.setTiles", "Tile Layer Properties", "Home › Add", set).inputs(set_inputs).roles(&[]).effects(crate::policy::Effects::NONE).params( + C::new("map.setTiles", "Tile Layer Properties", "Home › Add", set).inputs(set_inputs).roles(TILE_ROLES).effects(crate::policy::Effects::NONE).params( r#"{"name"?: text | "index"?: number (0 = top) | "id"?: catalog id, "visible"?: bool, "opacity"?: 0–1, "blend"?: "normal"|"multiply"|"screen"|"overlay"|"darken"|"lighten"|"difference", "resampling"?: "nearest"|"bilinear" (how picture tiles are drawn at a size other than their own: each pixel a block, or blended, the default), "move"?: "up"|"down"|"top"|"bottom" (past the next layer in the drawing order of all the map's layers, a feature or raster layer too), "to"?: number (its place in that order among the other layers, 0 = top; the Layers pane lists it), "rename"?: text, "bands"?: [red, green, blue] | [band] (a cloud-optimised GeoTIFF's bands shown, from 1; [] for its own), "range"?: [low, high] (the values shown from black to full colour; null: each band's 2nd–98th percentile), "dequantize"?: "aef" (AlphaEarth's quantised embeddings) | "none", "legend"?: as map.addTiles's, or null for none, "hiddenLayers"?: [source layer name] (vector tiles' source layers not drawn or identified, as map.tiles's sourceLayers names them; replaces the list, [] or null for none), "singleImage"?: bool (as map.addTiles's), "tileSize"?: 256|512|1024 (a WMS or map service asked for in Web Mercator: its tiles' size)}"#, ), C::new("map.tiles", "Tile Layers", "Home › Add", |s, _| Ok(list(s, !s.policy_user()))).inputs(listing_inputs).roles(&[]).effects(crate::policy::Effects::NONE).view(), @@ -607,9 +610,24 @@ pub(crate) fn listing_reach(map: &rustgis_map::Map) -> crate::policy::Effects { .fold(crate::policy::Effects::NONE, |reach, tile| reach.union(tile_source_reach(tile))) } -/// Setting a COG look checks its header; the command's returned list also reads archive names. +/// Whether `map.setTiles` attaches or replaces legend URLs (as opposed to leaving them alone or +/// clearing them with `null`, `""` or `[]`). +pub(crate) fn sets_legend(p: &Value) -> bool { + match p.get("legend") { + None | Some(Value::Null) => false, + Some(Value::String(s)) => !s.trim().is_empty(), + Some(Value::Array(a)) => !a.is_empty(), + Some(_) => true, + } +} + +/// Setting a COG look checks its header, setting a legend adds network URLs, and the command's +/// returned list also reads archive names. pub(crate) fn set_reach(input: &super::InputContext<'_>, p: &Value) -> crate::policy::Effects { let mut reach = listing_reach(input.map()); + if sets_legend(p) { + reach = reach.with(crate::policy::Effect::Network); + } if matches!(cog_look(p), Ok(Some(_))) && let Some(tile) = find(input, p).ok().flatten().and_then(|i| input.map().tiles.get(i)) && tile.kind == TileKind::Cog diff --git a/crates/engine/src/cmd/zarr.rs b/crates/engine/src/cmd/zarr.rs index 071596b8fe..fc86f9b53e 100644 --- a/crates/engine/src/cmd/zarr.rs +++ b/crates/engine/src/cmd/zarr.rs @@ -83,13 +83,13 @@ pub fn is_absent(error: &str) -> bool { /// is left out. Also says how many were refused with 403, so a store that refuses everything /// (access denied) isn't taken for an empty one. #[cfg(not(target_arch = "wasm32"))] -fn fetch(root: &str, keys: &[String]) -> Result<(HashMap>, usize), String> { - fetch_items(root, &keys.iter().map(|k| (k.clone(), k.clone())).collect::>()) +fn fetch(root: &str, keys: &[String], anonymous: bool) -> Result<(HashMap>, usize), String> { + fetch_items(root, &keys.iter().map(|k| (k.clone(), k.clone())).collect::>(), anonymous) } /// Fetches bytes of a store's files ([`zarr::Part`]s, by range), each kept by its id, as [`fetch`]. #[cfg(not(target_arch = "wasm32"))] -fn fetch_parts(root: &str, parts: &[zarr::Part]) -> Result<(HashMap>, usize), String> { +fn fetch_parts(root: &str, parts: &[zarr::Part], anonymous: bool) -> Result<(HashMap>, usize), String> { use crate::render::rustgis_tiles::cache::{RANGE, TAIL}; let items: Vec<(String, String)> = parts .iter() @@ -101,18 +101,18 @@ fn fetch_parts(root: &str, parts: &[zarr::Part]) -> Result<(HashMap Result<(HashMap>, usize), String> { - let (mut got, mut forbidden) = fetch(root, &plan.keys)?; - let (parts, f) = fetch_parts(root, &plan.parts)?; +fn fetch_plan(root: &str, store: &zarr::Store, plan: &zarr::Plan, anonymous: bool) -> Result<(HashMap>, usize), String> { + let (mut got, mut forbidden) = fetch(root, &plan.keys, anonymous)?; + let (parts, f) = fetch_parts(root, &plan.parts, anonymous)?; got.extend(parts); let inner = zarr::inner_parts(store, plan, &got).map_err(|e| crate::sources::message_with_address(root, &e.to_string()))?; - let (chunks, g) = fetch_parts(root, &inner)?; + let (chunks, g) = fetch_parts(root, &inner, anonymous)?; got.extend(chunks); forbidden += f + g; Ok((got, forbidden)) @@ -120,7 +120,7 @@ fn fetch_plan(root: &str, store: &zarr::Store, plan: &zarr::Plan) -> Result<(Has /// [`fetch`] of `(id, file)` pairs: each file (a key, with a byte range's mark) kept by its id. #[cfg(not(target_arch = "wasm32"))] -fn fetch_items(root: &str, keys: &[(String, String)]) -> Result<(HashMap>, usize), String> { +fn fetch_items(root: &str, keys: &[(String, String)], anonymous: bool) -> Result<(HashMap>, usize), String> { use std::sync::Mutex; let out = Mutex::new(HashMap::new()); let forbidden = std::sync::atomic::AtomicUsize::new(0); @@ -149,7 +149,8 @@ fn fetch_items(root: &str, keys: &[(String, String)]) -> Result<(HashMap { let len = b.len() as u64; @@ -229,7 +230,7 @@ mod transport_tests { } flag.load(SeqCst) }); - let worker = std::thread::spawn(move || cache::with_still(still, || super::fetch(&root, &["a/0.0".into()]))); + let worker = std::thread::spawn(move || cache::with_still(still, || super::fetch(&root, &["a/0.0".into()], false))); let held = entry.recv_timeout(Duration::from_secs(10)).is_ok(); live.store(false, SeqCst); let _ = release.send(()); @@ -258,7 +259,7 @@ mod transport_tests { listener.set_nonblocking(true).unwrap(); let root = format!("http://{}/held.zarr", listener.local_addr().unwrap()); cache::restrict_to_public(&root); - let result = super::fetch(&root, &["zarr.json".into()]); + let result = super::fetch(&root, &["zarr.json".into()], false); assert_eq!(listener.accept().map(|_| ()).unwrap_err().kind(), std::io::ErrorKind::WouldBlock, "a file of the store was asked for"); assert!(result.is_err(), "{result:?}"); } @@ -271,8 +272,8 @@ const MEMBER_ROUNDS: usize = 3; /// A store's metadata from its web address ([`read_store`]). #[cfg(not(target_arch = "wasm32"))] -fn store_at(url: &str, variable: &str) -> Result { - read_store(url, variable).map(|(store, _)| store) +fn store_at(url: &str, variable: &str, anonymous: bool) -> Result { + read_store(url, variable, anonymous).map(|(store, _)| store) } /// A store's metadata from its web address, and whether it holds only what was found from @@ -280,9 +281,9 @@ fn store_at(url: &str, variable: &str) -> Result { /// [`zarr::lists_no_arrays`]) has them found by name from `variable` ([`zarr::member_keys`]), in up /// to [`MEMBER_ROUNDS`] rounds; with no `variable`, that is refused. #[cfg(not(target_arch = "wasm32"))] -fn read_store(url: &str, variable: &str) -> Result<(zarr::Store, bool), String> { +fn read_store(url: &str, variable: &str, anonymous: bool) -> Result<(zarr::Store, bool), String> { let keys: Vec = zarr::METADATA_KEYS.iter().map(|k| k.to_string()).collect(); - let (got, forbidden) = fetch(url, &keys)?; + let (got, forbidden) = fetch(url, &keys, anonymous)?; // Every metadata file refused: access is denied, not a store without metadata. if got.is_empty() && forbidden > 0 { return Err(crate::sources::message_with_address(url, "access denied (HTTP 403)")); @@ -302,7 +303,7 @@ fn read_store(url: &str, variable: &str) -> Result<(zarr::Store, bool), String> if next.is_empty() { break; } - let (found, refused) = fetch(url, &next)?; + let (found, refused) = fetch(url, &next, anonymous)?; // The variable's own files refused: access is denied. Later rounds' coordinates may // just not exist, which S3 answers with 403 too (`is_absent`). if round == 0 && refused > 0 && found.is_empty() { @@ -335,15 +336,16 @@ fn read_store(url: &str, variable: &str) -> Result<(zarr::Store, bool), String> /// as Float64), each file a download of at most 60 s. A store whose root lists no arrays is read /// in up to [`MEMBER_ROUNDS`] more rounds of metadata files ([`store_at`]), each at most /// `zarr::member_keys`' 163 names (one or two files each), fetched several at a time. -fn info(_s: &mut Session, p: &Value) -> CmdResult { +fn info(s: &mut Session, p: &Value) -> CmdResult { #[cfg(target_arch = "wasm32")] { - let _ = p; + let _ = (s, p); Err("in the web app, open Zarr stores with Home › Add › Add Data › Zarr…".into()) } #[cfg(not(target_arch = "wasm32"))] { - let (root, store, mut v) = info_of(p)?; + let anonymous = s.web_logins.is_anonymous(); + let (root, store, mut v) = info_of(p, anonymous)?; // A bbox: the window of cells it is in a variable's grid, for layer.addZarr's cells. if let Some(asked) = asked_window(p)? { // Cells are given to layer.addZarr, which checks them against the grid; here only a @@ -353,7 +355,7 @@ fn info(_s: &mut Session, p: &Value) -> CmdResult { } let mut sel = zarr::Selection { variable: ps(p, "variable").map(str::trim).unwrap_or("").to_string(), ..Default::default() }; pick_variable(&store, &mut sel)?; - let cut = place_window(&root, &store, &mut sel, Some(asked))?; + let cut = place_window(&root, &store, &mut sel, Some(asked), anonymous)?; let w = sel.window.unwrap_or_default(); v["window"] = serde_json::json!({"variable": sel.variable, "cells": [w.x0, w.y0, w.x1, w.y1], "notes": cut}); } @@ -363,7 +365,7 @@ fn info(_s: &mut Session, p: &Value) -> CmdResult { /// [`info`] of the store a command names: its root, metadata and what it holds. #[cfg(not(target_arch = "wasm32"))] -fn info_of(p: &Value) -> Result<(String, zarr::Store, Value), String> { +fn info_of(p: &Value, anonymous: bool) -> Result<(String, zarr::Store, Value), String> { match source(p)? { Source::Dir(d) => { let store = zarr::read_metadata(Path::new(&d)).map_err(|e| format!("{d}: {e}"))?; @@ -388,8 +390,8 @@ fn info_of(p: &Value) -> Result<(String, zarr::Store, Value), String> { Ok((d, store, v)) } Source::Url(u) => { - let store = store_at(&u, ps(p, "variable").unwrap_or(""))?; - let (chunks, _) = fetch(&u, &zarr::info_keys(&store))?; + let store = store_at(&u, ps(p, "variable").unwrap_or(""), anonymous)?; + let (chunks, _) = fetch(&u, &zarr::info_keys(&store), anonymous)?; let v = zarr::info(&store, &chunks); Ok((u, store, v)) } @@ -456,7 +458,13 @@ fn asked_window(p: &Value) -> Result, String> { /// store at `root`). What is said of it: a box reaching past the grid, read only within it; a box /// within one cell along an axis, read as two there. #[cfg(not(target_arch = "wasm32"))] -fn place_window(root: &str, store: &zarr::Store, sel: &mut zarr::Selection, asked: Option) -> Result, String> { +fn place_window( + root: &str, + store: &zarr::Store, + sel: &mut zarr::Selection, + asked: Option, + anonymous: bool, +) -> Result, String> { let at = |e: rustgis_data::DataError| crate::sources::message_with_address(root, &e.to_string()); match asked { None => Ok(Vec::new()), @@ -465,7 +473,7 @@ fn place_window(root: &str, store: &zarr::Store, sel: &mut zarr::Selection, aske Ok(Vec::new()) } Some(Asked::Bbox(bbox)) => { - let coords = store_files(root, &zarr::window_keys(store, &sel.variable).map_err(at)?)?; + let coords = store_files(root, &zarr::window_keys(store, &sel.variable).map_err(at)?, anonymous)?; let (w, cut, widened) = zarr::window_of(store, &sel.variable, &coords, bbox).map_err(at)?; sel.window = Some(w); // A window's ends are exclusive; the text gives the last column and row read. @@ -531,7 +539,7 @@ pub(crate) fn add(s: &mut Session, p: &Value) -> CmdResult { Source::Dir(d) => { let store = zarr::read_metadata(Path::new(&d)).map_err(|e| format!("{d}: {e}"))?; pick_variable(&store, &mut sel)?; - let cut = place_window(&d, &store, &mut sel, asked)?; + let cut = place_window(&d, &store, &mut sel, asked, false)?; let mut r = zarr::read_dir_in(&store, Path::new(&d), &sel.label(), crs).map_err(|e| format!("{d}: {e}"))?; r.lost.extend(cut); crs_lost(&mut r, crs, &store, &sel.variable); @@ -558,11 +566,12 @@ pub(crate) fn add(s: &mut Session, p: &Value) -> CmdResult { super::raster::add_raster(s, &name, layer) } Source::Url(u) => { - let store = store_at(&u, &sel.variable)?; + let anonymous = s.web_logins.is_anonymous(); + let store = store_at(&u, &sel.variable, anonymous)?; pick_variable(&store, &mut sel)?; - let cut = place_window(&u, &store, &mut sel, asked)?; + let cut = place_window(&u, &store, &mut sel, asked, anonymous)?; let plan = zarr::plan(&store, &sel).map_err(|e| crate::sources::message_with_address(&u, &e.to_string()))?; - let (chunks, forbidden) = fetch_plan(&u, &store, &plan)?; + let (chunks, forbidden) = fetch_plan(&u, &store, &plan, anonymous)?; if forbidden > 0 { return Err(crate::sources::message_with_address( &u, @@ -617,25 +626,27 @@ fn is_web(store: &str) -> bool { } /// A web store kept by [`cached_store`]: its address, the variable its arrays were found from (for -/// a store whose root lists no arrays; `None` for one that lists them all), and its metadata. +/// a store whose root lists no arrays; `None` for one that lists them all), whether it was read +/// anonymously, and its metadata. #[cfg(not(target_arch = "wasm32"))] -type CachedStore = (String, Option, std::sync::Arc); +type CachedStore = (String, Option, bool, std::sync::Arc); /// A web store's metadata, from the run's cache when it was read before. A store whose root lists /// no arrays holds only those found from the variable it was read for, so it is taken from the /// cache only for that same variable, and each variable read of it is kept beside the others /// (among the last four kept): a nested `g/v` read first doesn't stand in for the root's `v`. #[cfg(not(target_arch = "wasm32"))] -fn cached_store(url: &str, variable: &str) -> Result, String> { +fn cached_store(url: &str, variable: &str, anonymous: bool) -> Result, String> { let wanted = variable.trim().trim_matches('/'); - let fits = |(u, found_from, _): &&CachedStore| u == url && found_from.as_deref().is_none_or(|v| v == wanted); - if let Some((_, _, st)) = stores().lock().ok().and_then(|c| c.iter().find(fits).cloned()) { + let fits = + |(u, found_from, anon, _): &&CachedStore| u == url && *anon == anonymous && found_from.as_deref().is_none_or(|v| v == wanted); + if let Some((_, _, _, st)) = stores().lock().ok().and_then(|c| c.iter().find(fits).cloned()) { return Ok(st); } - let (st, partial) = read_store(url, variable)?; + let (st, partial) = read_store(url, variable, anonymous)?; let st = std::sync::Arc::new(st); if let Ok(mut c) = stores().lock() { - c.push((url.to_string(), partial.then(|| wanted.to_string()), st.clone())); + c.push((url.to_string(), partial.then(|| wanted.to_string()), anonymous, st.clone())); let excess = c.len().saturating_sub(4); c.drain(..excess); } @@ -665,6 +676,13 @@ pub(crate) fn slice_key(zt: &ZarrTime, i: usize) -> String { format!("{}\u{0}{}\u{0}{}\u{0}{changed}\u{0}{}", zt.store, zt.selection(i), zt.crs.as_deref().unwrap_or(""), zt.read_generation) } +/// The cache key of a slice, separating anonymous reads from authenticated ones. +#[cfg(not(target_arch = "wasm32"))] +pub(crate) fn slice_key_for(zt: &ZarrTime, i: usize, anonymous: bool) -> String { + let key = slice_key(zt, i); + if anonymous { format!("{key}\u{0}anon") } else { key } +} + #[cfg(not(target_arch = "wasm32"))] fn is_kept(key: &str) -> bool { slices().lock().is_ok_and(|c| c.iter().any(|(k, _)| k == key)) @@ -688,11 +706,11 @@ static READ_AHEAD_THREADS: std::sync::atomic::AtomicUsize = std::sync::atomic::A /// Reads the two steps after `i` in the background, those neither kept nor already being read, /// on at most [`MAX_READ_AHEAD`] threads: a thread more is skipped (the next step starts one). #[cfg(not(target_arch = "wasm32"))] -fn read_ahead(zt: ZarrTime, i: usize) { +fn read_ahead(zt: ZarrTime, i: usize, anonymous: bool) { use std::sync::atomic::Ordering; let keys: Vec<(usize, String)> = (i + 1..zt.dates.len()) .take(2) - .map(|j| (j, slice_key(&zt, j))) + .map(|j| (j, slice_key_for(&zt, j, anonymous))) .filter(|(_, k)| !is_kept(k) && !ahead_failed(k) && reading_ahead().lock().is_ok_and(|mut r| r.insert(k.clone()))) .collect(); if keys.is_empty() { @@ -734,7 +752,7 @@ fn read_ahead(zt: ZarrTime, i: usize) { let _diagnostic_scope = capture.enter(); let _done = Done(keys.iter().map(|(_, k)| k.clone()).collect()); for (n, (j, k)) in keys.iter().enumerate() { - let ok = read_step(&zt, *j, k.clone()).is_ok(); + let ok = read_step_with(&zt, *j, k.clone(), anonymous).is_ok(); // Not read ahead again (each follow would): the slider reaching it reads it off the // frame, and says why it fails. if !ok && let Ok(mut f) = failed_ahead().lock() { @@ -782,17 +800,23 @@ fn wait_for_read_ahead(key: &str) { /// Step `i`, once a read ahead of it has finished, so it isn't fetched twice. #[cfg(not(target_arch = "wasm32"))] -fn read_waiting(zt: &ZarrTime, i: usize) -> Result, String> { +fn read_waiting(zt: &ZarrTime, i: usize, anonymous: bool) -> Result, String> { // One key for the wait and the read: a store rewritten between them is read once. - let key = slice_key(zt, i); + let key = slice_key_for(zt, i, anonymous); wait_for_read_ahead(&key); - read_step(zt, i, key) + read_step_with(zt, i, key, anonymous) } /// Step `i` of a following layer's variable, kept as `key` (its [`slice_key`]), from the kept /// slices or read now. #[cfg(not(target_arch = "wasm32"))] +#[cfg_attr(not(test), expect(dead_code, reason = "unit tests call read_step directly"))] pub(crate) fn read_step(zt: &ZarrTime, i: usize, key: String) -> Result, String> { + read_step_with(zt, i, key, false) +} + +#[cfg(not(target_arch = "wasm32"))] +fn read_step_with(zt: &ZarrTime, i: usize, key: String, anonymous: bool) -> Result, String> { use crate::render::rustgis_tiles::cache; let still = cache::current_still(); cache::check_still(&still)?; @@ -801,7 +825,8 @@ pub(crate) fn read_step(zt: &ZarrTime, i: usize, key: String) -> Result Option> { /// Step `i` of a following layer's variable, read from its store (no slice kept). #[cfg(not(target_arch = "wasm32"))] -pub(crate) fn read_slice(zt: &ZarrTime, i: usize) -> Result, String> { +pub(crate) fn read_slice_with(zt: &ZarrTime, i: usize, anonymous: bool) -> Result, String> { if rustgis_map::paths::is_project_relative(&zt.store) { return Err(rustgis_map::paths::unknown_folder(&zt.store)); } let sel = zt.selection(i); let crs = zt.crs.as_deref().map(str::trim).filter(|c| !c.is_empty()); let (read, st) = if is_web(&zt.store) { - let st = cached_store(&zt.store, &zt.variable)?; + let st = cached_store(&zt.store, &zt.variable, anonymous)?; let plan = zarr::plan(&st, &zarr::Selection::parse(&sel)).map_err(|e| e.to_string())?; // A window's coordinates and, in shards, only its chunks, by range. - let (chunks, forbidden) = fetch_plan(&zt.store, &st, &plan)?; + let (chunks, forbidden) = fetch_plan(&zt.store, &st, &plan, anonymous)?; // A chunk refused (HTTP 403) isn't one never written: it's said, not read as fill. if forbidden > 0 { return Err(crate::sources::message_with_address( @@ -874,7 +899,7 @@ pub(crate) fn relink_following( if !store.variables().iter().any(|v| v.path == zt.variable) { return Err(format!("{full} has no variable '{}': choose the store the layer was added from", zt.variable)); } - let coords = store_files(full, &zarr::coordinate_keys(&store, &zt.variable))?; + let coords = store_files(full, &zarr::coordinate_keys(&store, &zt.variable), false)?; let (dim, dates) = zarr::time_axis(&store, &zt.variable, &coords).ok_or_else(|| format!("{full}: {} no longer has a time axis", zt.variable))?; if dim != zt.dim || !dates.iter().all(|d| d.is_finite()) || !dates.windows(2).all(|w| w[0] < w[1]) { @@ -931,7 +956,7 @@ pub(crate) fn relink_following( let window = slider.map(rustgis_map::time::TimeSlider::window); let want = zt.step_for(window); let i = want.unwrap_or(0); - let r = read_step(&zt, i, slice_key(&zt, i))?; + let r = read_step_with(&zt, i, slice_key(&zt, i), false)?; rl.validate_replacement(&r, full)?; zt.shown = want; let mut new = rl.clone(); @@ -951,16 +976,17 @@ const FAILED_KEPT: usize = 16; #[derive(Default)] pub(crate) struct ReadWaits { layers: HashMap<(u64, u64), std::sync::Arc>, - shared: HashMap<(String, String, Option), std::sync::Weak>, + shared: HashMap<(String, String, Option, bool), std::sync::Weak>, } #[cfg(not(target_arch = "wasm32"))] impl ReadWaits { /// Retains a move's owner while queued; layers on the same owned slice share its completion. - fn for_layer(&mut self, owner: (u64, u64), zt: &ZarrTime, i: usize) -> std::sync::Arc { + fn for_layer(&mut self, owner: (u64, u64), zt: &ZarrTime, i: usize, anonymous: bool) -> std::sync::Arc { use std::sync::Arc; if let Some(read) = self.layers.get(&owner) && read.step == i + && read.anonymous == anonymous && read.zt.store == zt.store && read.zt.crs == zt.crs && read.zt.selection(i) == zt.selection(i) @@ -968,7 +994,7 @@ impl ReadWaits { { return read.clone(); } - let selection = (zt.store.clone(), zt.selection(i), zt.crs.clone()); + let selection = (zt.store.clone(), zt.selection(i), zt.crs.clone(), anonymous); let still = crate::render::rustgis_tiles::cache::current_still(); let read = self .shared @@ -979,7 +1005,7 @@ impl ReadWaits { (None, None) => true, _ => false, }) - .unwrap_or_else(|| Arc::new(PendingRead::new(zt, i, still))); + .unwrap_or_else(|| Arc::new(PendingRead::new(zt, i, still, anonymous))); self.shared.insert(selection, Arc::downgrade(&read)); self.layers.insert(owner, read.clone()); read @@ -1007,6 +1033,7 @@ struct PendingRead { zt: ZarrTime, step: usize, key: String, + anonymous: bool, still: Option, capture: rustgis_data::diagnostics::Capture, started: std::sync::atomic::AtomicBool, @@ -1016,11 +1043,12 @@ struct PendingRead { #[cfg(not(target_arch = "wasm32"))] impl PendingRead { /// Captures at the initial move, even when all worker slots are occupied. - fn new(zt: &ZarrTime, step: usize, still: Option) -> Self { + fn new(zt: &ZarrTime, step: usize, still: Option, anonymous: bool) -> Self { Self { zt: zt.clone(), step, - key: slice_key(zt, step), + key: slice_key_for(zt, step, anonymous), + anonymous, still, capture: rustgis_data::diagnostics::Capture::current(), started: std::sync::atomic::AtomicBool::new(false), @@ -1050,7 +1078,7 @@ impl PendingRead { fn read(&self) -> Result, String> { crate::render::rustgis_tiles::cache::with_optional_still(self.still.clone(), || { let _diagnostic_scope = self.capture.enter(); - std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| read_step(&self.zt, self.step, self.key.clone()))) + std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| read_step_with(&self.zt, self.step, self.key.clone(), self.anonymous))) .unwrap_or_else(|_| Err(format!("{}: reading step {} failed unexpectedly", self.zt.store, self.step))) }) } @@ -1174,6 +1202,7 @@ pub(crate) fn follow_time_now(s: &mut Session) { fn follow(s: &mut Session, wait: bool) { #[cfg(not(target_arch = "wasm32"))] { + let anonymous = s.web_logins.is_anonymous(); let mut errors = Vec::new(); let mut ahead = Vec::new(); let mut waiting = std::collections::HashSet::new(); @@ -1201,7 +1230,7 @@ fn follow(s: &mut Session, wait: bool) { } // Consume this layer's original completion, including its lifetime at landing. Some(i) if !wait => { - let read = s.zarr_reads.for_layer(owner, zt, i); + let read = s.zarr_reads.for_layer(owner, zt, i, anonymous); let result = observed.entry(std::sync::Arc::as_ptr(&read)).or_insert_with(|| read.poll()).clone(); // The shared observation does not replace the lifetime check at delivery. let result = result.map(|r| crate::render::rustgis_tiles::cache::check_still(&read.still).and(r)); @@ -1226,7 +1255,7 @@ fn follow(s: &mut Session, wait: bool) { } } } - Some(i) => match read_waiting(zt, i) { + Some(i) => match read_waiting(zt, i, anonymous) { Ok(r) => { rl.data = Some(r); zt.shown = Some(i); @@ -1262,7 +1291,7 @@ fn follow(s: &mut Session, wait: bool) { s.notify(text, true); } for (zt, i, still) in ahead { - crate::render::rustgis_tiles::cache::with_optional_still(still, || read_ahead(zt, i)); + crate::render::rustgis_tiles::cache::with_optional_still(still, || read_ahead(zt, i, anonymous)); } } #[cfg(target_arch = "wasm32")] @@ -1289,6 +1318,7 @@ fn add_following(s: &mut Session, p: &Value, asked: Option) -> CmdResult if let Some(c) = &crs { Crs::parse(c)?; } + let anonymous = s.web_logins.is_anonymous(); let (root, store, chunks) = match src { Source::Dir(d) => { let store = zarr::read_metadata(Path::new(&d)).map_err(|e| format!("{d}: {e}"))?; @@ -1314,15 +1344,18 @@ fn add_following(s: &mut Session, p: &Value, asked: Option) -> CmdResult (full, std::sync::Arc::new(store), chunks) } Source::Url(u) => { - let store = cached_store(&u, &sel.variable)?; + let store = cached_store(&u, &sel.variable, anonymous)?; (u, store, HashMap::new()) } }; pick_variable(&store, &mut sel)?; // A window: every step reads only its cells (and in shards only their chunks it needs). - let window_notes = place_window(&root, &store, &mut sel, asked)?; - let chunks = - if chunks.is_empty() && is_web(&root) { fetch(&root, &zarr::coordinate_keys(&store, &sel.variable))?.0 } else { chunks }; + let window_notes = place_window(&root, &store, &mut sel, asked, anonymous)?; + let chunks = if chunks.is_empty() && is_web(&root) { + fetch(&root, &zarr::coordinate_keys(&store, &sel.variable), anonymous)?.0 + } else { + chunks + }; let (dim, dates) = zarr::time_axis(&store, &sel.variable, &chunks).ok_or_else(|| { format!( "{} has no time dimension (a coordinate with CF units, such as \"days since 2001-01-01\", or of whole years, such as 2017)", @@ -1387,7 +1420,8 @@ fn add_following(s: &mut Session, p: &Value, asked: Option) -> CmdResult zt.repair(); // The first step read before the slider is touched, so a store that can't be read leaves // the map as it was. - let first = read_step(&zt, 0, slice_key(&zt, 0)).map_err(|e| crate::sources::message_with_address(&root, &e))?; + let first = read_step_with(&zt, 0, slice_key_for(&zt, 0, anonymous), anonymous) + .map_err(|e| crate::sources::message_with_address(&root, &e))?; // The slider, on over the variable's dates when it is off. if s.map().time.is_none() { let dates: Vec = zt.dates.iter().map(|d| serde_json::json!(d)).collect(); @@ -1397,7 +1431,8 @@ fn add_following(s: &mut Session, p: &Value, asked: Option) -> CmdResult let want = zt.step_for(window); // The first slice the layer shows sets its style; with no step in the window, the first step's. let r = match want { - Some(i) if i != 0 => read_step(&zt, i, slice_key(&zt, i)).map_err(|e| crate::sources::message_with_address(&root, &e))?, + Some(i) if i != 0 => read_step_with(&zt, i, slice_key_for(&zt, i, anonymous), anonymous) + .map_err(|e| crate::sources::message_with_address(&root, &e))?, _ => first, }; let mut layer = RasterLayer::from_path((*r).clone(), root.clone()); @@ -1499,8 +1534,8 @@ fn series_source(s: &Session, p: &Value) -> Result { /// A store's metadata, and its files `keys`: a folder's read (files only, bounded), a web /// store's fetched. #[cfg(not(target_arch = "wasm32"))] -fn store_files(root: &str, keys: &[String]) -> Result>, String> { - store_files_by(root, keys, &mut |_| Ok(())) +fn store_files(root: &str, keys: &[String], anonymous: bool) -> Result>, String> { + store_files_by(root, keys, anonymous, &mut |_| Ok(())) } /// The files of a store read in batches of up to [`SERIES_BATCH`] files, as [`store_files`] reads @@ -1510,6 +1545,7 @@ fn store_files(root: &str, keys: &[String]) -> Result>, fn store_files_by( root: &str, keys: &[String], + anonymous: bool, before: &mut dyn FnMut(usize) -> Result<(), String>, ) -> Result>, String> { if is_web(root) { @@ -1519,7 +1555,7 @@ fn store_files_by( let mut total = 0u64; for batch in keys.chunks(SERIES_BATCH) { before(batch.len())?; - let (got, forbidden) = fetch(root, batch)?; + let (got, forbidden) = fetch(root, batch, anonymous)?; // A file refused (HTTP 403) isn't one never written: said, not read as missing. if forbidden > 0 { return Err(crate::sources::message_with_address(root, &format!("access denied (HTTP 403) to {forbidden} of its files"))); @@ -1565,6 +1601,7 @@ fn store_files_by( fn store_parts( root: &str, parts: &[zarr::Part], + anonymous: bool, before: &mut dyn FnMut(usize) -> Result<(), String>, ) -> Result>, String> { let mut out = HashMap::new(); @@ -1572,7 +1609,7 @@ fn store_parts( for batch in parts.chunks(SERIES_BATCH) { before(batch.len())?; if is_web(root) { - let (got, forbidden) = fetch_parts(root, batch)?; + let (got, forbidden) = fetch_parts(root, batch, anonymous)?; if forbidden > 0 { return Err(crate::sources::message_with_address(root, &format!("access denied (HTTP 403) to {forbidden} of its files"))); } @@ -1629,6 +1666,7 @@ pub struct SeriesRun { src: SeriesSource, start: Option, end: Option, + anonymous: bool, } /// The steps a series has read, for its progress: the reads made of those it plans (the chunks, @@ -1677,7 +1715,7 @@ impl SeriesRun { let check = &mut |_: usize| rustgis_data::progress::check().map_err(|_| "cancelled".to_string()); check(0)?; let store = if is_web(&src.root) { - cached_store(&src.root, &src.sel.variable)? + cached_store(&src.root, &src.sel.variable, self.anonymous)? } else { std::sync::Arc::new(zarr::read_metadata(Path::new(&src.root)).map_err(|e| format!("{}: {e}", src.root))?) }; @@ -1685,7 +1723,7 @@ impl SeriesRun { let var = src.sel.variable.clone(); let mut keys = zarr::coordinate_keys(&store, &var); keys.extend(zarr::map_coordinate_keys(&store, &var)); - let coords = store_files_by(&src.root, &keys, check)?; + let coords = store_files_by(&src.root, &keys, self.anonymous, check)?; let (dim, dates) = zarr::time_axis(&store, &var, &coords) .ok_or_else(|| format!("{var} has no time dimension (a coordinate with CF units, such as \"days since 2001-01-01\", or of whole years, such as 2017)"))?; // A period is found along the axis in order, as following the slider takes it. @@ -1746,13 +1784,13 @@ impl SeriesRun { rustgis_data::progress::begin(count); let mut tally = SeriesTally { steps: count, reads: plan.keys.len() + 2 * plan.parts.len(), done: 0, flight: 0, shown: 0 }; let mut before = |n: usize| tally.before(n); - let mut chunks = store_files_by(&src.root, &plan.keys, &mut before)?; + let mut chunks = store_files_by(&src.root, &plan.keys, self.anonymous, &mut before)?; // A sharded variable: the shards' indexes, then the chunk holding the cell in each. if !plan.parts.is_empty() { - chunks.extend(store_parts(&src.root, &plan.parts, &mut before)?); + chunks.extend(store_parts(&src.root, &plan.parts, self.anonymous, &mut before)?); let inner = zarr::series_inner_parts(&store, &plan, &chunks) .map_err(|e| crate::sources::message_with_address(&src.root, &e.to_string()))?; - chunks.extend(store_parts(&src.root, &inner, &mut before)?); + chunks.extend(store_parts(&src.root, &inner, self.anonymous, &mut before)?); } // The last batch counted as read once it is, before decoding; cancelled during it, nothing // is decoded, so no part of a series is given. @@ -1791,7 +1829,7 @@ pub fn series_start(s: &Session, p: &Value) -> Result { } }; let (start, end) = (date("start")?, date("end")?); - Ok(SeriesRun { lon, lat, src, start, end }) + Ok(SeriesRun { lon, lat, src, start, end, anonymous: s.web_logins.is_anonymous() }) } // --- A summary over time (opengeos/RustGIS#556) ---------------------------------------------------- @@ -1810,6 +1848,7 @@ pub struct ReduceRun { steps: Vec, stat: Stat, min_valid: f64, + anonymous: bool, /// The layer's name, and the store and variable to hand the result over with. pub name: String, pub root: String, @@ -1842,9 +1881,9 @@ impl ReduceRun { } // A slice already kept is used; the others are read without being kept, so a long // summary doesn't push out the slices a layer following the slider holds. - let r = match kept_slice(&slice_key(&self.zt, i)) { + let r = match kept_slice(&slice_key_for(&self.zt, i, self.anonymous)) { Some(r) => r, - None => match read_slice(&self.zt, i)? { + None => match read_slice_with(&self.zt, i, self.anonymous)? { Some(r) => std::sync::Arc::new(r), // A step never written is its fill value: no value for any cell, so it only // lowers the counts (and the step after it still sets the grid). @@ -1925,7 +1964,7 @@ pub fn reduce_start(s: &Session, p: &Value) -> Result { let min_valid = super::cube::min_share(p)?; // The name given, checked before the store is read. let given = super::name_given(p, "the output's name", 200)?; - let ZarrCube { zt, period } = zarr_cube(s, p)?; + let ZarrCube { zt, period, anonymous } = zarr_cube(s, p)?; let steps = super::cube::steps(&zt.dates, period, p)?; let months = super::cube::months(p)?; let (var, dates) = (zt.variable.clone(), &zt.dates); @@ -1945,7 +1984,7 @@ pub fn reduce_start(s: &Session, p: &Value) -> Result { } let name = given.unwrap_or(label); let root = zt.store.clone(); - Ok(ReduceRun { zt, steps, stat, min_valid, name, root, variable: var }) + Ok(ReduceRun { zt, steps, stat, min_valid, anonymous, name, root, variable: var }) } /// A Zarr variable's time axis as a data cube (#579): the store and variable to read, all its @@ -1954,11 +1993,13 @@ pub fn reduce_start(s: &Session, p: &Value) -> Result { pub struct ZarrCube { pub zt: ZarrTime, pub period: (usize, usize), + pub anonymous: bool, } /// The cube of a Zarr layer, or of the store and variable the parameters name. #[cfg(not(target_arch = "wasm32"))] pub fn zarr_cube(s: &Session, p: &Value) -> Result { + let anonymous = s.web_logins.is_anonymous(); let mut src = series_source(s, p)?; // A layer that is a window of its variable: its steps over time would be read whole. if src.sel.window.is_some() { @@ -1968,13 +2009,13 @@ pub fn zarr_cube(s: &Session, p: &Value) -> Result { )); } let store = if is_web(&src.root) { - cached_store(&src.root, &src.sel.variable)? + cached_store(&src.root, &src.sel.variable, anonymous)? } else { std::sync::Arc::new(zarr::read_metadata(Path::new(&src.root)).map_err(|e| format!("{}: {e}", src.root))?) }; pick_variable(&store, &mut src.sel)?; let var = src.sel.variable.clone(); - let coords = store_files(&src.root, &zarr::coordinate_keys(&store, &var))?; + let coords = store_files(&src.root, &zarr::coordinate_keys(&store, &var), anonymous)?; let (dim, dates) = zarr::time_axis(&store, &var, &coords).ok_or_else(|| { format!( "{var} has no time dimension (a coordinate with CF units, such as \"days since 2001-01-01\", or of whole years, such as 2017)" @@ -2004,7 +2045,7 @@ pub fn zarr_cube(s: &Session, p: &Value) -> Result { shown: None, read_generation: src.read_generation, }; - Ok(ZarrCube { zt, period }) + Ok(ZarrCube { zt, period, anonymous }) } /// The most cells a summary keeps running totals for (12 to 20 bytes each): 32 million, at most diff --git a/crates/engine/src/policy/decide.rs b/crates/engine/src/policy/decide.rs index d6ec93234e..c532ceb1e7 100644 --- a/crates/engine/src/policy/decide.rs +++ b/crates/engine/src/policy/decide.rs @@ -90,6 +90,9 @@ fn kind(s: &Session, k: &Kind, node: &Node) -> Decision { if own { Deny } else { kind(s, within, node) } } Kind::Plugin { pin, within } => { + if is_plugin_blocked_database_command(node.id()) { + return Deny; + } let m = &pin.0.manifest; let own = node.effects.iter().all(|e| match e { Edits => m.has(Permission::Edit), @@ -148,6 +151,9 @@ fn refusal(s: &Session, k: &Kind, n: &Node) -> String { ), Kind::Plugin { pin, .. } => { let m = &pin.0.manifest; + if is_plugin_blocked_database_command(n.id()) { + return format!("{} cannot run '{}' (plugins can't access databases or run SQL)", m.name, n.id()); + } if let Op::Tool(tool) = &n.op && tool.plugin().is_some_and(|p| p.0.manifest.id != m.id) { @@ -186,3 +192,20 @@ fn refusal(s: &Session, k: &Kind, n: &Node) -> String { ), } } + +/// Direct database and SQL commands are excluded from plugins even when a plugin holds `files` +/// and `network` permissions: they can use the user's live PostGIS session, reach local database +/// hosts outside HTTP address checks, or run DuckDB SQL. +fn is_plugin_blocked_database_command(id: &str) -> bool { + matches!( + id, + "pg.tables" + | "pg.addLayer" + | "pg.discardEdits" + | "info.databaseTables" + | "layer.addDatabase" + | "sql.query" + | "sql.schema" + | "layer.addSql" + ) +} diff --git a/crates/engine/src/policy/effects.rs b/crates/engine/src/policy/effects.rs index 669e702315..b8f2725ae0 100644 --- a/crates/engine/src/policy/effects.rs +++ b/crates/engine/src/policy/effects.rs @@ -64,9 +64,16 @@ pub(super) fn declared(spec: &CommandSpec, params: &Value) -> Effects { if spec.id == "layout.publication" && params.get("coverage").is_some_and(|v| !v.is_null()) { effects = effects.with(Effect::Files); } + // Changing the favourite or saved publication-layout arrangements mutates app-wide preferences. + if spec.id == "layout.arrangement" && ["save", "remove", "favourite"].iter().any(|k| params.get(*k).is_some_and(|v| !v.is_null())) { + effects = effects.with(Effect::Reserved); + } if spec.id == "map.addTiles" { effects = effects.union(crate::cmd::tiles::add_reach(params)); } + if spec.id == "map.setTiles" && crate::cmd::tiles::sets_legend(params) { + effects = effects.with(Effect::Network); + } if spec.id == "layer.addDataBytes" && crate::cmd::raster::bytes_is_jpeg2000(params) { effects = effects.with(Effect::Files); } diff --git a/crates/engine/src/project_log.rs b/crates/engine/src/project_log.rs index a05d4aded1..fdc2a5a8ad 100644 --- a/crates/engine/src/project_log.rs +++ b/crates/engine/src/project_log.rs @@ -133,7 +133,9 @@ fn kept_error(e: &str) -> String { } else { e.to_string() }; - crate::cmd::history::redacted_text(&sql_secrets_removed(&e)) + let e = crate::sources::scrub_s3_wrappers(&e); + let e = crate::cmd::history::redacted_text(&sql_secrets_removed(&e)); + crate::sources::scrub_s3_wrappers(&crate::render::rustgis_tiles::logins::scrub(&e)) } /// `v` without secrets: as History's Copy as code takes them out (`history::redacted`), and, @@ -199,7 +201,24 @@ fn review_value(v: &Value, depth: usize) -> Result { } fn redacted(v: &Value) -> Value { - crate::cmd::history::redacted(&embedded_redacted(v, 0)) + scrub_log_value(crate::cmd::history::redacted(&embedded_redacted(v, 0)), 0) +} + +/// Removes active login values and runtime capability wrappers from every string and object key +/// retained in log parameters. +fn scrub_log_text(t: &str) -> String { + crate::sources::scrub_s3_wrappers(&crate::render::rustgis_tiles::logins::scrub(t)) +} + +fn scrub_log_value(v: Value, depth: usize) -> Value { + match v { + Value::String(t) => Value::String(scrub_log_text(&t)), + Value::Array(a) if depth < 8 => Value::Array(a.into_iter().map(|x| scrub_log_value(x, depth + 1)).collect()), + Value::Object(o) if depth < 8 => { + Value::Object(o.into_iter().map(|(k, x)| (scrub_log_text(&k), scrub_log_value(x, depth + 1))).collect()) + } + other => other, + } } /// A bounded log-only context check for a short key beside nested connection settings. @@ -241,7 +260,7 @@ fn embedded_redacted(v: &Value, depth: usize) -> Value { match v { Value::String(t) => { let t = if t.contains('{') { json_in_text_redacted(t) } else { t.clone() }; - Value::String(sql_secrets_removed(&t)) + Value::String(crate::sources::scrub_s3_wrappers(&sql_secrets_removed(&t))) } Value::Array(a) if depth < 8 => Value::Array(a.iter().map(|x| embedded_redacted(x, depth + 1)).collect()), Value::Object(o) if depth < 8 => { diff --git a/crates/engine/src/roles.rs b/crates/engine/src/roles.rs index d8d1798f41..f50dabe36e 100644 --- a/crates/engine/src/roles.rs +++ b/crates/engine/src/roles.rs @@ -197,31 +197,31 @@ fn object(id: &str, value: &Value, depth: usize, config_depth: usize, registered let clean = sql_secrets_removed(s); (clean != s).then_some(Value::String(clean)) }) + } else if registered && (role == Some(Role::Configuration) || CONFIG.contains(&k.as_str())) && (v.is_object() || v.is_array()) { + match v { + Value::Object(_) => object("", v, depth, config_depth + 1, true, report), + Value::Array(a) => config_array(a, depth, config_depth + 1, report), + _ => None, + } } else if ADDRESS.contains(&k.as_str()) || address_like(v) { - if v.is_object() && registered && (role == Some(Role::Configuration) || CONFIG.contains(&k.as_str())) { - object("", v, depth, config_depth + 1, true, report) - } else { - // String leaves are cleaned below; opaque shapes keep their meaning. - unchecked |= match v { - Value::Object(_) => suspicious(v), - Value::Array(a) => a.iter().any(|v| !v.is_string() && suspicious(v)), - _ => false, - }; - match query_name - .zip(v.as_str()) - .map(|(name, s)| crate::render::rustgis_tiles::logins::without_query_parameter(s, name)) - .filter(|stripped| Some(stripped.as_str()) != v.as_str()) - { - // The same object names its login parameter, registered or not. - Some(stripped) => { - report.withheld = report.withheld.saturating_add(1); - Some(address(&Value::String(stripped.clone()), report).unwrap_or(Value::String(stripped))) - } - None => address(v, report), + // String leaves are cleaned below; opaque shapes keep their meaning. + unchecked |= match v { + Value::Object(_) => suspicious(v), + Value::Array(a) => a.iter().any(|v| !v.is_string() && suspicious(v)), + _ => false, + }; + match query_name + .zip(v.as_str()) + .map(|(name, s)| crate::render::rustgis_tiles::logins::without_query_parameter(s, name)) + .filter(|stripped| Some(stripped.as_str()) != v.as_str()) + { + // The same object names its login parameter, registered or not. + Some(stripped) => { + report.withheld = report.withheld.saturating_add(1); + Some(address(&Value::String(stripped.clone()), report).unwrap_or(Value::String(stripped))) } + None => address(v, report), } - } else if registered && (role == Some(Role::Configuration) || CONFIG.contains(&k.as_str())) && v.is_object() { - object("", v, depth, config_depth + 1, true, report) } else { unchecked |= suspicious(v); None @@ -239,6 +239,36 @@ fn object(id: &str, value: &Value, depth: usize, config_depth: usize, registered replacement.map(Value::Object) } +/// Cleans a structured configuration array (for example `legend` entries of strings and objects) +/// within the shared configuration depth bound. +fn config_array(a: &[Value], depth: usize, config_depth: usize, report: &mut Report) -> Option { + if config_depth >= 8 { + return invalid(&Value::Array(a.to_vec()), report); + } + let mut changed = None; + let mut unchecked = false; + for (i, item) in a.iter().enumerate() { + let clean = match item { + Value::Object(_) => object("", item, depth, config_depth + 1, true, report), + Value::String(_) if address_like(item) => address(item, report), + Value::Array(inner) => config_array(inner, depth, config_depth + 1, report), + _ => { + unchecked |= suspicious(item); + None + } + }; + if let Some(clean) = clean.filter(|clean| clean != item) + && let Some(slot) = changed.get_or_insert_with(|| a.to_vec()).get_mut(i) + { + *slot = clean; + } + } + if unchecked { + report.unchecked = report.unchecked.saturating_add(1); + } + changed.map(Value::Array) +} + /// Recognition precedes parsing, including malformed wrappers and differently cased prefixes. fn address_like(v: &Value) -> bool { match v { @@ -256,6 +286,9 @@ fn address_like(v: &Value) -> bool { "postgres:", "postgresql:", "pg:", + "mysql:", + "mariadb:", + "mssql:", ] .iter() .any(|p| s.get(..p.len()).is_some_and(|s| s.eq_ignore_ascii_case(p))) diff --git a/crates/engine/src/service_logins.rs b/crates/engine/src/service_logins.rs index 6083e74f60..60cb49a223 100644 --- a/crates/engine/src/service_logins.rs +++ b/crates/engine/src/service_logins.rs @@ -751,6 +751,18 @@ pub fn open_connection(s: &mut Session, c: &Connection) -> Result<(), String> { Ok(()) } +/// Marks an outbound fetch address anonymous when `anonymous` is set, preventing implicit S3 +/// signing and Earthdata/Copernicus/ArcGIS sign-in tokens on that request without altering the +/// plain URL kept in layers or parameters. +#[cfg_attr(target_arch = "wasm32", expect(dead_code, reason = "blocking fetches are desktop only"))] +pub(crate) fn fetch_url(anonymous: bool, url: &str) -> String { + if anonymous && !crate::render::rustgis_tiles::s3::split_anonymous(url).1 { + crate::render::rustgis_tiles::s3::anonymous(url) + } else { + url.to_string() + } +} + pub fn request_params<'a>(s: &mut Session, p: &'a Value) -> Result, String> { let Some(url) = p.get("url").and_then(Value::as_str) else { return Ok(std::borrow::Cow::Borrowed(p)) }; let id = match p.get("connection") { @@ -760,8 +772,15 @@ pub fn request_params<'a>(s: &mut Session, p: &'a Value) -> Result return Err(CONNECTION_TEXT.into()), }; if id.is_none() && (s.web_logins.anonymous || p.get("anonymous").and_then(Value::as_bool) == Some(true)) { - // An address bound to a login is no authority for it here either. - let plain = logins::inner(url); + // An address bound to a web login or saved S3 connection is no authority for it here either. + let mut plain = url; + for _ in 0..8 { + let next = rustgis_data::s3_address::inner(logins::inner(plain)); + if next == plain { + break; + } + plain = next; + } if plain == url { return Ok(std::borrow::Cow::Borrowed(p)); } diff --git a/crates/engine/src/tests/scopes_and_redaction.rs b/crates/engine/src/tests/scopes_and_redaction.rs index ce9d9ea921..6c370a2b66 100644 --- a/crates/engine/src/tests/scopes_and_redaction.rs +++ b/crates/engine/src/tests/scopes_and_redaction.rs @@ -806,3 +806,404 @@ fn an_agent_url_request_cannot_clear_a_document_restriction() { assert!(s.run_scoped(scope, &call).is_err()); assert_eq!(cache::ceiling_for(url), Reach::Public); } + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn anonymous_reads_suppress_implicit_s3_and_sign_in_credentials() { + if isolate_process_test("tests::scopes_and_redaction::anonymous_reads_suppress_implicit_s3_and_sign_in_credentials") { + return; + } + use std::io::{Read, Write}; + use std::net::TcpListener; + use std::sync::Mutex; + + let listener = TcpListener::bind("127.0.0.1:0").unwrap(); + let addr = listener.local_addr().unwrap(); + let base = format!("http://{addr}"); + let seen: Arc>> = Arc::new(Mutex::new(Vec::new())); + let stop = Arc::new(AtomicBool::new(false)); + let seen_srv = seen.clone(); + let stop_srv = stop.clone(); + let server = std::thread::spawn(move || { + while let Ok((mut stream, _)) = listener.accept() { + if stop_srv.load(Ordering::SeqCst) { + break; + } + let _ = stream.set_read_timeout(Some(std::time::Duration::from_secs(5))); + let mut buf = [0u8; 4096]; + let n = stream.read(&mut buf).unwrap_or(0); + let req = String::from_utf8_lossy(&buf[..n]).into_owned(); + let first = req.lines().next().unwrap_or(""); + if first.contains("/__stop") { + let _ = stream.write_all(b"HTTP/1.1 200 OK\r\nContent-Length: 0\r\nConnection: close\r\n\r\n"); + break; + } + seen_srv.lock().unwrap_or_else(|e| e.into_inner()).push(req.clone()); + let (status, body) = if first.contains("list-type=2") { + ("200 OK", "false") + } else if first.contains(".geojson") { + ("200 OK", r#"{"type":"FeatureCollection","features":[]}"#) + } else { + ("404 Not Found", "") + }; + let resp = format!("HTTP/1.1 {status}\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}", body.len()); + let _ = stream.write_all(resp.as_bytes()); + } + }); + + let mut s = Session::new(Project::default()); + s.run( + "s3.connect", + &json!({ + "name": "priv-anon-test", + "endpoint": base, + "buckets": ["priv-bkt-anon"], + "accessKeyId": "AKIA_SYNTH_ANON", + "secretAccessKey": "SECRET_SYNTH_ANON" + }), + ) + .unwrap(); + s.run( + "s3.connect", + &json!({ + "name": "pub-anon-test", + "endpoint": base, + "buckets": ["pub-bkt-anon"], + "anonymous": true + }), + ) + .unwrap(); + + // Baseline: non-anonymous fetch to the endpoint signs with the active S3 connection's keys. + s.run("layer.addUrl", &json!({"url": format!("{base}/priv-bkt-anon/baseline.geojson")})).unwrap(); + let baseline = std::mem::take(&mut *seen.lock().unwrap_or_else(|e| e.into_inner())); + assert!(baseline.iter().any(|r| r.contains("AKIA_SYNTH_ANON")), "baseline request should be signed: {baseline:?}"); + + // 1. s3.list under anonymous session must not sign even when another connection shares the endpoint. + crate::service_logins::anonymously(&mut s, true, |s| { + s.run("s3.list", &json!({"bucket": "pub-bkt-anon"})).unwrap(); + }) + .unwrap(); + let s3_reqs = std::mem::take(&mut *seen.lock().unwrap_or_else(|e| e.into_inner())); + assert!(!s3_reqs.is_empty()); + for r in &s3_reqs { + assert!(!r.contains("AKIA_SYNTH_ANON") && !r.to_ascii_lowercase().contains("authorization:"), "s3.list signed anonymously: {r}"); + } + + // 2. Zarr metadata fetches under anonymous session must not carry S3 signing headers. + crate::service_logins::anonymously(&mut s, true, |s| { + let _ = s.run("raster.zarrInfo", &json!({"url": format!("{base}/priv-bkt-anon/store.zarr")})); + }) + .unwrap(); + let zarr_reqs = std::mem::take(&mut *seen.lock().unwrap_or_else(|e| e.into_inner())); + assert!(!zarr_reqs.is_empty()); + for r in &zarr_reqs { + assert!(!r.contains("AKIA_SYNTH_ANON") && !r.to_ascii_lowercase().contains("authorization:"), "zarr signed anonymously: {r}"); + } + + // 3. layer.addUrl under anonymous session must not carry S3 signing headers. + crate::service_logins::anonymously(&mut s, true, |s| { + s.run("layer.addUrl", &json!({"url": format!("{base}/priv-bkt-anon/points.geojson")})).unwrap(); + }) + .unwrap(); + let url_reqs = std::mem::take(&mut *seen.lock().unwrap_or_else(|e| e.into_inner())); + assert!(!url_reqs.is_empty()); + for r in &url_reqs { + assert!( + !r.contains("AKIA_SYNTH_ANON") && !r.to_ascii_lowercase().contains("authorization:"), + "layer.addUrl signed anonymously: {r}" + ); + } + + // 4. request_params strips rustgis-s3: capability wrappers under anonymous mode. + let wrapped = rustgis_data::s3_address::bind("0123456789abcdef", "https://s3.example.org", "s3://priv-bkt-anon/key.geojson").unwrap(); + let p = json!({"url": wrapped}); + let stripped = + crate::service_logins::anonymously(&mut s, true, |s| crate::service_logins::request_params(s, &p).unwrap().into_owned()).unwrap(); + assert_eq!(stripped["url"], "s3://priv-bkt-anon/key.geojson"); + + stop.store(true, Ordering::SeqCst); + let _ = std::net::TcpStream::connect(addr); + let _ = server.join(); + let _ = s.run("s3.disconnect", &json!({"name": "priv-anon-test"})); + let _ = s.run("s3.disconnect", &json!({"name": "pub-anon-test"})); +} + +#[test] +fn map_set_tiles_legend_requires_network_and_preserves_existing_tile_layers() { + let mut s = Session::new(Project::default()); + let spec = s.registry.get("map.setTiles").unwrap(); + for legend in [ + json!("https://tiles.example.org/legend.png"), + json!(["https://tiles.example.org/legend.png"]), + json!([{"url": "https://tiles.example.org/legend.png"}]), + ] { + let effects = command_effects(spec, &json!({"name": "Base", "legend": legend})); + assert!(effects.contains(Effect::Network), "map.setTiles with legend must declare Network: {legend}"); + } + for clearing in [json!(null), json!(""), json!([])] { + let effects = command_effects(spec, &json!({"name": "Base", "legend": clearing})); + assert!(!effects.contains(Effect::Network), "clearing legend must not require Network: {clearing}"); + } + + s.run("map.addTiles", &json!({"url": "https://tiles.example.org/{z}/{x}/{y}.png", "name": "Base"})).unwrap(); + isolate_plugins(); + plugin("plug-no-net-legend", &["edit"]); + let err = + forward(&mut s, "plug-no-net-legend", "map.setTiles", json!({"name": "Base", "legend": "https://tiles.example.org/legend.png"})) + .unwrap_err(); + assert!(err.contains("network"), "{err}"); + assert_eq!(s.map().tiles.len(), 1, "existing tile layer must be preserved"); + assert_eq!(s.map().tiles[0].name, "Base"); + assert!(s.map().tiles[0].legends.is_empty()); + + // Clearing legends remains allowed for an edit-only plugin. + forward(&mut s, "plug-no-net-legend", "map.setTiles", json!({"name": "Base", "legend": null})).unwrap(); + rustgis_plugins::unload("plug-no-net-legend"); +} + +#[test] +fn plugin_address_hold_scans_nested_legend_urls_and_bounds_work() { + use crate::render::rustgis_tiles::{address::Reach, cache}; + let mut s = Session::new(Project::default()); + s.run("map.addTiles", &json!({"url": "https://tiles.example.org/{z}/{x}/{y}.png", "name": "Base"})).unwrap(); + isolate_plugins(); + plugin("plug-net-nested", &["edit", "network"]); + + for legend in [ + json!(["http://127.0.0.1:8080/secret.png"]), + json!([{"url": "http://127.0.0.1:8080/secret.png"}]), + json!({"url": "http://127.0.0.1:8080/secret.png"}), + ] { + let err = forward( + &mut s, + "plug-net-nested", + "map.addTiles", + json!({"url": "https://tiles.example.org/{z}/{x}/{y}.png", "name": "New", "legend": legend}), + ) + .unwrap_err(); + assert!(err.contains("this computer or the local network"), "{err}"); + + let err = forward(&mut s, "plug-net-nested", "map.setTiles", json!({"name": "Base", "legend": legend})).unwrap_err(); + assert!(err.contains("this computer or the local network"), "{err}"); + } + + // Public nested legend is accepted and restricted to public reach. + let public_legend = "https://nested-legend-check.example.org/l.png"; + forward(&mut s, "plug-net-nested", "map.setTiles", json!({"name": "Base", "legend": [{"url": public_legend}]})).unwrap(); + assert_eq!(cache::ceiling_for(public_legend), Reach::Public); + + // Overly large nested payloads fail closed rather than bypassing the address scan. + let mut pad: Vec = (0..4100).map(|i| json!(i)).collect(); + pad.push(json!("http://127.0.0.1:8080/hidden.png")); + let err = forward(&mut s, "plug-net-nested", "map.addTiles", json!({"url": "https://tiles.example.org/{z}/{x}/{y}.png", "extra": pad})) + .unwrap_err(); + assert!(err.contains("too complex"), "{err}"); + + rustgis_plugins::unload("plug-net-nested"); +} + +#[test] +fn durable_save_scrubs_structured_tile_legends_and_mysql_mssql_addresses() { + use crate::project::{Task, TaskStep}; + + let leg1 = fixture_marker("leg1"); + let leg2 = fixture_marker("leg2"); + let leg3 = fixture_marker("leg3"); + let leg4 = fixture_marker("leg4"); + let my_pw = fixture_marker("mypw"); + let ma_pw = fixture_marker("mapw"); + let ms_pw = fixture_marker("mspw"); + + let mut s = Session::new(Project::default()); + s.project.tasks.push(Task { + name: "TileAndDb".into(), + description: String::new(), + steps: vec![ + TaskStep { + title: "Add tiles".into(), + instructions: String::new(), + command: "map.addTiles".into(), + params: json!({ + "url": "https://tiles.example.org/{z}/{x}/{y}.png", + "legend": [ + {"url": format!("https://user:{leg1}@tiles.example.org/l1.png?token={leg2}"), "minScale": 1000}, + format!("https://tiles.example.org/l2.png?api_key={leg3}") + ] + }), + }, + TaskStep { + title: "Set legend".into(), + instructions: String::new(), + command: "map.setTiles".into(), + params: json!({ + "name": "Base", + "legend": {"url": format!("https://tiles.example.org/l3.png?token={leg4}")} + }), + }, + TaskStep { + title: "Db links".into(), + instructions: String::new(), + command: "info.databaseTables".into(), + params: json!({ + "target": format!("mysql://ann:{my_pw}@db.example.org:3306/gis"), + "secondary": format!("mariadb://ann:{ma_pw}@db.example.org:3306/gis"), + "archive": format!("mssql://ann:{ms_pw}@db.example.org:1433/gis") + }), + }, + ], + }); + + let (saved, _) = s.project.saved_text(None).unwrap(); + for secret in [&leg1, &leg2, &leg3, &leg4, &my_pw, &ma_pw, &ms_pw] { + assert!(!saved.contains(secret.as_str()), "saved project leaked {secret}: {saved}"); + } +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn project_log_scrubs_active_logins_and_s3_wrappers() { + if isolate_process_test("tests::scopes_and_redaction::project_log_scrubs_active_logins_and_s3_wrappers") { + return; + } + let active_secret = fixture_marker("projlog_active"); + let s3_tok = fixture_marker("projlog_s3tok"); + let mut s = Session::new(Project::default()); + s.database_logins.set_store(None); + let conn = s + .run( + "connection.new", + &json!({"kind": "wms", "address": "https://log-scrub.example.org/wms", "auth": "header", "keyName": "X-Key"}), + ) + .unwrap(); + s.run("connection.login", &json!({"id": conn["id"], "apiKey": active_secret})).unwrap(); + + let wrapped = format!("rustgis-s3:0123456789abcdef:22:https://s3.example.org:https://s3.example.org/b/k?token={s3_tok}"); + let logged = crate::log_params(&json!({ + "note": format!("server rejected {active_secret}"), + "url": wrapped, + })) + .into_log_value() + .to_string(); + assert!(!logged.contains(&active_secret), "log_params leaked active login: {logged}"); + assert!(!logged.contains("rustgis-s3:"), "log_params leaked s3 wrapper: {logged}"); + assert!(!logged.contains(&s3_tok), "log_params leaked wrapped query token: {logged}"); + + // Failed command errors recorded in the session log must also scrub active logins and wrappers. + let _ = s.run("layer.rename", &json!({"layer": format!("missing {active_secret} {wrapped}")})); + let entry = s.log.entries().last().unwrap(); + let err = entry.error.as_deref().unwrap_or(""); + assert!(!err.contains(&active_secret), "session log error leaked active login: {err}"); + assert!(!err.contains("rustgis-s3:"), "session log error leaked s3 wrapper: {err}"); + assert!(!err.contains(&s3_tok), "session log error leaked wrapped token: {err}"); +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn earthdata_status_guards_keychain_restore_by_scope_and_opt_in() { + if isolate_process_test("tests::scopes_and_redaction::earthdata_status_guards_keychain_restore_by_scope_and_opt_in") { + return; + } + use crate::render::rustgis_tiles::earthdata; + use rustgis_data::secrets::{MemorySecrets, Secret, SecretStore}; + + let store = Arc::new(MemorySecrets::new()); + store.save(earthdata::ACCOUNT, &Secret::new("synthetic-earthdata-keychain-token")).unwrap(); + earthdata::set_token(None).unwrap(); + earthdata::set_secret_store(Some(store)); + assert!(!earthdata::has_token()); + + let mut s = Session::new(Project::default()); + assert!(!s.saved_secrets_opted_in); + + // Non-opted-in native user session must not restore from keychain. + let st = s.run("earthdata.status", &json!({})).unwrap(); + assert_eq!(st["token"], json!(false)); + assert!(!earthdata::has_token()); + + // Plugin, agent, and assistant scopes must never restore from keychain even if opted in. + s.saved_secrets_opted_in = true; + isolate_plugins(); + plugin("plug-earthdata-ro", &["edit", "network", "files"]); + let st = forward(&mut s, "plug-earthdata-ro", "earthdata.status", json!({})).unwrap(); + assert_eq!(st["token"], json!(false)); + assert!(!earthdata::has_token()); + rustgis_plugins::unload("plug-earthdata-ro"); + + let st = s.run_scoped(agent_scope(AgentAccess::Allow, "ed-ro"), &Call::command("earthdata.status", json!({}))).unwrap(); + assert_eq!(st["token"], json!(false)); + assert!(!earthdata::has_token()); + + let (asst, _) = assistant_scope(7711); + let st = s.run_scoped(asst, &Call::command("earthdata.status", json!({}))).unwrap(); + assert_eq!(st["token"], json!(false)); + assert!(!earthdata::has_token()); + + // Opted-in native user session DOES restore from keychain. + let st = s.run("earthdata.status", &json!({})).unwrap(); + assert_eq!(st["token"], json!(true)); + assert!(earthdata::has_token()); + + let _ = earthdata::logout(); + earthdata::set_secret_store(None); +} + +#[test] +fn layout_arrangement_mutations_require_reserved_while_listing_is_read_only() { + let mut s = Session::new(Project::default()); + let spec = s.registry.get("layout.arrangement").unwrap(); + assert!(!command_effects(spec, &json!({})).contains(Effect::Reserved)); + for mutation in [json!({"save": "Atlas", "arrangement": "classic"}), json!({"remove": "Atlas"}), json!({"favourite": "mirrored"})] { + assert!(command_effects(spec, &mutation).contains(Effect::Reserved), "expected Reserved for {mutation}"); + } + + isolate_plugins(); + plugin("plug-layout-arr", &["edit", "files", "network"]); + // Listing stays allowed. + forward(&mut s, "plug-layout-arr", "layout.arrangement", json!({})).unwrap(); + // Mutating global preferences is denied for plugins. + for mutation in [json!({"save": "Atlas", "arrangement": "classic"}), json!({"remove": "Atlas"}), json!({"favourite": "mirrored"})] { + assert!(forward(&mut s, "plug-layout-arr", "layout.arrangement", mutation.clone()).is_err(), "{mutation}"); + assert!( + s.run_scoped(agent_scope(AgentAccess::Allow, "arr-agent"), &Call::command("layout.arrangement", mutation.clone())).is_err() + ); + let (asst, _) = assistant_scope(7712); + assert!(matches!(s.review(&asst, &Call::command("layout.arrangement", mutation)), Outcome::NeedsApproval(_))); + } + let (asst, _) = assistant_scope(7713); + assert!(matches!(s.review(&asst, &Call::command("layout.arrangement", json!({}))), Outcome::Allowed)); + rustgis_plugins::unload("plug-layout-arr"); +} + +#[test] +fn plugins_cannot_run_database_or_sql_commands() { + let mut s = Session::new(Project::default()); + isolate_plugins(); + plugin("plug-db-blocked", &["edit", "files", "network"]); + // Commands without a pre-condition reach policy::decide directly through Bridge::command. + for (cmd, params) in [ + ("pg.discardEdits", json!({})), + ("info.databaseTables", json!({"database": "/tmp/a.duckdb"})), + ("layer.addDatabase", json!({"database": "/tmp/a.duckdb"})), + ("sql.query", json!({"sql": "SELECT 1"})), + ("sql.schema", json!({"database": "/tmp/a.duckdb"})), + ("layer.addSql", json!({"sql": "SELECT ST_Point(0, 0) AS g"})), + ] { + let err = forward(&mut s, "plug-db-blocked", cmd, params).unwrap_err(); + assert!(err.contains("databases or run SQL"), "{cmd}: unexpected error: {err}"); + } + // Commands with `.when(need_connection)` are also explicitly denied by policy authorization for plugins. + #[cfg(not(target_arch = "wasm32"))] + { + let pkg = + rustgis_plugins::Package::from_zip(&rustgis_plugins::testing::package("plug-db-blocked-auth", &["edit", "files", "network"])) + .unwrap(); + let loaded = rustgis_plugins::load(pkg, "test").unwrap(); + for (cmd, params) in [("pg.tables", json!({})), ("pg.addLayer", json!({"table": "public.roads"}))] { + let err = s.as_session_plugin(loaded.clone(), |s| s.authorize(cmd, ¶ms)).unwrap().err().expect("expected refusal"); + assert!(err.contains("databases or run SQL"), "{cmd}: unexpected refusal: {err}"); + } + rustgis_plugins::unload("plug-db-blocked-auth"); + } + rustgis_plugins::unload("plug-db-blocked"); +} From 6964f0777a05862c0ce8e47dc5320ebffe9f8f49 Mon Sep 17 00:00:00 2001 From: giswqs Date: Wed, 25 Nov 2026 10:04:05 -0500 Subject: [PATCH 02/20] Address review feedback - Propagate anonymous fetch wrapping into COG overview/info/dated probe reads, OGC tileset template discovery, static STAC catalog walks, and STAC dated cube searches. - Respect explicit anonymous flags on Zarr and Earthdata entrypoints, preserve per-layer anonymous mode in Zarr time-following and layer-backed series/cube reads, and forward anonymous flags from stac.addAsset and PMTiles/COG tile additions. - Allow edit-only plugins without network permission to clear existing tile legends while still blocking and rolling back newly introduced legend URLs. - Scrub active web logins and S3 wrappers before clipping in project_log and MCP audit redaction, and scrub object keys in MCP audit arguments. - Loop HTTP header reads until CRLFCRLF in the mock server test and expand regression coverage for anonymous Zarr, legend clearing, and boundary-spanning log redaction. --- crates/assistant/src/audit.rs | 48 +++++++-- crates/engine/src/cmd/earthdata.rs | 11 +- crates/engine/src/cmd/layer.rs | 41 +++++-- crates/engine/src/cmd/plugins.rs | 28 ++--- crates/engine/src/cmd/service.rs | 11 +- crates/engine/src/cmd/stac.rs | 9 +- crates/engine/src/cmd/zarr.rs | 53 ++++++--- crates/engine/src/project_log.rs | 19 ++-- .../engine/src/tests/scopes_and_redaction.rs | 101 ++++++++++++++++-- crates/tiles/src/stac/catalog.rs | 9 +- crates/tiles/src/stac/dated.rs | 10 +- 11 files changed, 264 insertions(+), 76 deletions(-) diff --git a/crates/assistant/src/audit.rs b/crates/assistant/src/audit.rs index 3a704c1d57..57aec1792f 100644 --- a/crates/assistant/src/audit.rs +++ b/crates/assistant/src/audit.rs @@ -167,9 +167,8 @@ fn normalized_args(tool: &str, arguments: &Value) -> Value { /// string is withheld; active web logins and `rustgis-s3:` capability wrappers are scrubbed. Other /// text is kept as it is, not cut at a `?` or `#`. fn redact_string(s: &str) -> String { - let s = rustgis_engine::sources::scrub_s3_wrappers(&rustgis_engine::render::rustgis_tiles::logins::scrub(s)); - let out = redact_string_inner(&s); - rustgis_engine::sources::scrub_s3_wrappers(&rustgis_engine::render::rustgis_tiles::logins::scrub(&out)) + let s = rustgis_engine::render::rustgis_tiles::logins::scrub(&rustgis_engine::sources::scrub_s3_wrappers(s)); + redact_string_inner(&s) } fn redact_string_inner(s: &str) -> String { @@ -266,17 +265,30 @@ fn redact_script(script: &str) -> String { /// secret, the passwords, keys and tokens in addresses ([`rustgis_engine::sources::redact`]), /// and the same inside a script's lines. fn redact(v: Value, depth: usize) -> Value { + let redact_bounded = |s: &str| { + if s.len() > MAX_ARGS { + // Scrub wrappers and active logins before clipping so a secret crossing MAX_ARGS + // cannot leave a recognizable prefix behind. + let scrubbed = rustgis_engine::render::rustgis_tiles::logins::scrub(&rustgis_engine::sources::scrub_s3_wrappers(s)); + redact_string_inner(&crate::tools::clip(&scrubbed, MAX_ARGS)) + } else { + redact_string(s) + } + }; match v { - // A long value (inline GeoJSON) is cut before it's searched, not after. - Value::String(s) if s.len() > MAX_ARGS => Value::String(redact_string(&crate::tools::clip(&s, MAX_ARGS))), - Value::String(s) => Value::String(redact_string(&s)), + Value::String(s) => Value::String(redact_bounded(&s)), Value::Array(a) if depth < 16 => Value::Array(a.into_iter().map(|x| redact(x, depth + 1)).collect()), Value::Object(o) if depth < 16 => Value::Object( o.into_iter() - .map(|(k, x)| match (rustgis_engine::data::address::log_sensitive(&k), k.as_str(), x) { - (true, _, _) => (k, json!("[redacted]")), - (false, "script", Value::String(s)) => (k, json!(redact_script(&s))), - (false, _, x) => (k, redact(x, depth + 1)), + .map(|(k, x)| { + let sensitive = rustgis_engine::data::address::log_sensitive(&k); + let is_script = k.as_str() == "script"; + let safe_k = redact_bounded(&k); + match (sensitive, is_script, x) { + (true, _, _) => (safe_k, json!("[redacted]")), + (false, true, Value::String(s)) => (safe_k, json!(redact_script(&s))), + (false, _, x) => (safe_k, redact(x, depth + 1)), + } }) .collect(), ), @@ -551,5 +563,21 @@ mod tests { assert!(!error_text.contains(active_secret), "{error_text}"); assert!(!error_text.contains("rustgis-s3:"), "{error_text}"); assert!(!error_text.contains("RGSYNTH_s3_tok_9921"), "{error_text}"); + + // Object keys and strings spanning MAX_ARGS also scrub active logins and wrappers. + let prefix = "x".repeat(MAX_ARGS - 8); + let spanning = format!("{prefix}{active_secret}tail"); + let redacted = redact( + json!({ + format!("key-{active_secret}-{wrapped}"): "val", + "long": spanning, + }), + 0, + ) + .to_string(); + assert!(!redacted.contains(active_secret), "redacted leaked active login: {redacted}"); + assert!(!redacted.contains(&active_secret[..8]), "redacted leaked active login prefix: {redacted}"); + assert!(!redacted.contains("rustgis-s3:"), "redacted leaked s3 wrapper in key: {redacted}"); + assert!(!redacted.contains("RGSYNTH_s3_tok_9921"), "redacted leaked wrapped token in key: {redacted}"); } } diff --git a/crates/engine/src/cmd/earthdata.rs b/crates/engine/src/cmd/earthdata.rs index fd7309b69c..74bbc9cb97 100644 --- a/crates/engine/src/cmd/earthdata.rs +++ b/crates/engine/src/cmd/earthdata.rs @@ -27,6 +27,8 @@ pub fn commands() -> Vec { C::new("earthdata.status", "Earthdata Login Status", "Home › Add › Web Data › NASA Earthaccess", |s, _p| { // Only a native user session may restore from the keychain (when saved secrets are // enabled) or mutate process-wide expiry state; other scopes get a read-only status. + // Without opt-in, skip expiry cleanup when the token is remembered in the keychain so + // an unopted session does not delete a keychain entry. if s.policy_user() { if s.saved_secrets_opted_in { earthdata::restore(); @@ -101,7 +103,8 @@ pub fn collections_query(p: &Value) -> Result { fn collections(s: &mut Session, p: &Value) -> CmdResult { let url = collections_query(p)?; - let bytes = answer_or_fetch(p, &url, s.web_logins.is_anonymous())?; + let anonymous = s.web_logins.is_anonymous() || b(p, "anonymous") == Some(true); + let bytes = answer_or_fetch(p, &url, anonymous)?; let found = earthdata::parse_collections(&bytes)?; Ok(json!({"count": found.len(), "collections": found.iter().map(earthdata::collection_json).collect::>()})) } @@ -116,9 +119,10 @@ fn resolve(short: &str, anonymous: bool) -> Result { /// The granule search a command names: its address and the collection's concept id. pub fn granules_query(s: &Session, p: &Value) -> Result { let collection = ps(p, "collection").map(str::trim).filter(|c| !c.is_empty()); + let anonymous = s.web_logins.is_anonymous() || b(p, "anonymous") == Some(true); let collection = match (collection, ps(p, "shortName").map(str::trim).filter(|c| !c.is_empty())) { (Some(c), _) => c.to_string(), - (None, Some(short)) => resolve(short, s.web_logins.is_anonymous())?.id, + (None, Some(short)) => resolve(short, anonymous)?.id, (None, None) => return Err("give collection (a concept id earthdata.collections lists) or shortName".into()), }; // Where the map is, unless asked for everywhere. @@ -129,7 +133,8 @@ pub fn granules_query(s: &Session, p: &Value) -> Result { fn granules(s: &mut Session, p: &Value) -> CmdResult { let url = granules_query(s, p)?; - let bytes = answer_or_fetch(p, &url, s.web_logins.is_anonymous())?; + let anonymous = s.web_logins.is_anonymous() || b(p, "anonymous") == Some(true); + let bytes = answer_or_fetch(p, &url, anonymous)?; let found = earthdata::parse_granules(&bytes)?; let mut out = json!({"count": found.len(), "granules": found.iter().map(earthdata::granule_json).collect::>()}); if b(p, "footprints").unwrap_or(true) { diff --git a/crates/engine/src/cmd/layer.rs b/crates/engine/src/cmd/layer.rs index 1ded279290..3e1c6c660d 100644 --- a/crates/engine/src/cmd/layer.rs +++ b/crates/engine/src/cmd/layer.rs @@ -5331,6 +5331,9 @@ fn add_url_as_given(s: &mut Session, p: &Value) -> CmdResult { if let Some(connection) = p.get("connection") { q["connection"] = connection.clone(); } + if b(p, "anonymous") == Some(true) { + q["anonymous"] = json!(true); + } return super::tiles::add(s, &q); } // A dated address (one file per date, `{date:YYYY}`) is read in place, following the time @@ -5943,16 +5946,17 @@ pub(crate) fn add_cog_with(s: &mut Session, p: &Value, url: &str, strict: bool, let (file, mut look) = crate::render::rustgis_tiles::cog::split(url); // A key given as `null` (a script's unused one) asks for nothing. let given = |k: &str| p.get(k).filter(|v| !v.is_null()); + let anonymous = s.web_logins.is_anonymous() || b(p, "anonymous") == Some(true); // A data cube's file stays a tile layer, its project opened again too: its address says so. look.cube |= b(p, "cube") == Some(true); let dated = rustgis_data::time::is_template(file) || ["start", "end", "unit", "interval", "dates"].iter().any(|k| given(k).is_some()); if !dated && !look.aef && !look.cube { - return add_in_place(s, name, file, &look, strict, b(p, "zoom"), probed); + return add_in_place(s, name, file, &look, strict, b(p, "zoom"), probed, anonymous); } let url = crate::render::rustgis_tiles::cog::with_look(url, &look); let mut q = json!({"url": url, "kind": "cog", "name": name, "top": true}); // A dated address's span and steps (see map.addTiles). - for k in ["start", "end", "unit", "interval", "dates", "connection"] { + for k in ["start", "end", "unit", "interval", "dates", "connection", "anonymous"] { if let Some(v) = given(k) { q[k] = v.clone(); } @@ -5968,18 +5972,29 @@ pub(crate) fn add_cog_with(s: &mut Session, p: &Value, url: &str, strict: bool, let dated = s.map().tiles.get(index).ok_or("added GeoTIFF tile is missing")?.url.clone(); // Its header read now (natively) as an undated address's is before it is added. #[cfg(not(target_arch = "wasm32"))] - let probe = if s.leave_downloads { Ok(false) } else { crate::render::rustgis_tiles::cog::probe_blocking(&dated) }; + let probe = if s.leave_downloads { + Ok(false) + } else { + let fetch_dated = crate::service_logins::fetch_url(anonymous, &dated); + crate::render::rustgis_tiles::cog::probe_blocking(&fetch_dated) + }; #[cfg(target_arch = "wasm32")] - let probe: Result = Ok(false); + let probe: Result = { + let _ = anonymous; + Ok(false) + }; (dated, probe == Ok(true), probe.err()) } else { (url.to_string(), probed, None) }; #[cfg(not(target_arch = "wasm32"))] - let info = if probed { - crate::render::rustgis_tiles::cog::info_blocking(&url).map(Some) - } else { - crate::render::rustgis_tiles::cog::info(&url) + let info = { + let fetch_url = crate::service_logins::fetch_url(anonymous, &url); + if probed { + crate::render::rustgis_tiles::cog::info_blocking(&fetch_url).map(Some) + } else { + crate::render::rustgis_tiles::cog::info(&fetch_url) + } }; #[cfg(target_arch = "wasm32")] let info = crate::render::rustgis_tiles::cog::info(&url); @@ -6071,6 +6086,7 @@ pub(crate) fn cog_tile_losses(info: &crate::render::rustgis_tiles::cog::Info) -> /// `zoom` is the adding command's `"zoom"`: /// `Some(true)` frames it, `Some(false)` keeps the view, `None` frames it only as the first content /// on an empty map. `probed` is [`add_cog`]'s. +#[expect(clippy::too_many_arguments, reason = "in-place COG helper mirrors add_cog_with options")] fn add_in_place( s: &mut Session, name: &str, @@ -6079,6 +6095,7 @@ fn add_in_place( strict: bool, zoom: Option, probed: bool, + anonymous: bool, ) -> CmdResult { use crate::render::rustgis_tiles::cog; // Judged as an address a project keeps is (a host, no spaces, not too long) before it is read. @@ -6089,8 +6106,10 @@ fn add_in_place( // doesn't hold the window. Otherwise read with the other layers added with it (see // `project::read_in_place`); in the browser, landing later. #[cfg(not(target_arch = "wasm32"))] + let fetch_file = crate::service_logins::fetch_url(anonymous, file); + #[cfg(not(target_arch = "wasm32"))] let layer = if strict && s.in_place_wait { - rustgis_map::raster::RasterLayer::in_place(cog::raster::overview_blocking(file)?, file) + rustgis_map::raster::RasterLayer::in_place(cog::raster::overview_blocking(&fetch_file)?, file) } else if strict { rustgis_map::raster::RasterLayer::opening_in_place(file) } else { @@ -6098,7 +6117,7 @@ fn add_in_place( }; #[cfg(target_arch = "wasm32")] let layer = { - let _ = strict; + let _ = (strict, anonymous); rustgis_map::raster::RasterLayer::opening_in_place(file) }; let layer = layer.with_look(super::tiles::address_look(look)); @@ -6108,7 +6127,7 @@ fn add_in_place( // login ended): the layer would go unframed. A plugin's command in the app doesn't wait (it // runs on the frame), as in the browser. #[cfg(not(target_arch = "wasm32"))] - let info = if probed && !s.leave_downloads { cog::info_blocking(file).map(Some) } else { cog::info(file) }; + let info = if probed && !s.leave_downloads { cog::info_blocking(&fetch_file).map(Some) } else { cog::info(&fetch_file) }; #[cfg(target_arch = "wasm32")] let info = { let _ = probed; diff --git a/crates/engine/src/cmd/plugins.rs b/crates/engine/src/cmd/plugins.rs index 66c94bb4e2..d4ee720e3b 100644 --- a/crates/engine/src/cmd/plugins.rs +++ b/crates/engine/src/cmd/plugins.rs @@ -726,16 +726,19 @@ impl Bridge<'_> { return Err(format!("{label}: {why}")); } // Without `network`, no command may bring in a tile address (a map file read from text - // carries its tile layers), or change where an existing layer or its legends fetch from: - // on violation, each pre-existing map's tiles are restored from its snapshot rather than - // dropping modified layers. Where a layer fetches from is decided by its address, kind, - // subdomains, row order and legend addresses. Its name, attribution and opacity never - // reach a server, and its tile size reaches one only as `{width}`/`{height}` (256 or 512). - let fetched = |t: &rustgis_map::TileLayer| { - (t.url.clone(), t.kind, t.subdomains.clone(), t.tms, t.legends.iter().map(|l| l.url.clone()).collect::>()) + // carries its tile layers), or introduce a new legend address on an existing tile layer + // (clearing or removing legends requires no network). On violation, each pre-existing map's + // tiles are restored from its snapshot rather than dropping modified layers. Where a layer + // fetches from is decided by its address, kind, subdomains, row order and legend addresses. + // Its name, attribution and opacity never reach a server, and its tile size reaches one + // only as `{width}`/`{height}` (256 or 512). + let tile_base = |t: &rustgis_map::TileLayer| (t.url.clone(), t.kind, t.subdomains.clone(), t.tms); + let tile_sources = |s: &Session| { + let bases: std::collections::HashSet<_> = s.project.maps.iter().flat_map(|m| &m.tiles).map(tile_base).collect(); + let legends: std::collections::HashSet = + s.project.maps.iter().flat_map(|m| &m.tiles).flat_map(|t| t.legends.iter().map(|l| l.url.clone())).collect(); + (bases, legends) }; - let tile_sources = - |s: &Session| -> std::collections::HashSet<_> { s.project.maps.iter().flat_map(|m| &m.tiles).map(fetched).collect() }; let before = (!self.plugin.manifest.has(Permission::Network)).then(|| { let sources = tile_sources(self.s); let snapshots: std::collections::HashMap> = @@ -749,14 +752,15 @@ impl Bridge<'_> { super::workflows::steps_of(s, |s| s.invoke(op, crate::policy::Txn::Shared)) }) .unwrap_or_else(|_| Err(format!("{label} failed unexpectedly"))); - if let Some((sources, mut snapshots)) = before { - let violated = self.s.project.maps.iter().flat_map(|m| &m.tiles).any(|t| !sources.contains(&fetched(t))); + if let Some(((bases, legends), mut snapshots)) = before { + let allowed = |t: &rustgis_map::TileLayer| bases.contains(&tile_base(t)) && t.legends.iter().all(|l| legends.contains(&l.url)); + let violated = self.s.project.maps.iter().flat_map(|m| &m.tiles).any(|t| !allowed(t)); if violated { for m in &mut self.s.project.maps { if let Some(saved) = snapshots.remove(&m.instance_id()) { m.tiles = saved; } else { - m.tiles.retain(|t| sources.contains(&fetched(t))); + m.tiles.retain(allowed); } } res = Err(format!("{} needs the 'network' permission to add tile layers", self.plugin.manifest.name)); diff --git a/crates/engine/src/cmd/service.rs b/crates/engine/src/cmd/service.rs index ba805f2015..21fdf881d4 100644 --- a/crates/engine/src/cmd/service.rs +++ b/crates/engine/src/cmd/service.rs @@ -852,10 +852,11 @@ fn crosses_origin(from: &str, to: &str) -> bool { /// fetched within the reach of the one before it, the service's document first (`public`: it was /// read from the internet), as their fetches observed it. #[cfg(not(target_arch = "wasm32"))] -fn advertised_template(source: &str, list: &str, vector: bool, withheld: &mut u32, public: bool) -> AdvertisedTemplate { +fn advertised_template(source: &str, list: &str, vector: bool, withheld: &mut u32, public: bool, anonymous: bool) -> AdvertisedTemplate { let reach = if public { Reach::Public } else { Reach::Local }; advertised_template_with(source, list, vector, withheld, reach, |doc, reach| { - let fetched = cache::download_blocking_with_origin_within(doc, cache::MAX_DOWNLOAD, cache::BLOCKING_TIMEOUT, &[], reach) + let fetch_doc = crate::service_logins::fetch_url(anonymous, doc); + let fetched = cache::download_blocking_with_origin_within(&fetch_doc, cache::MAX_DOWNLOAD, cache::BLOCKING_TIMEOUT, &[], reach) .map_err(cache::large_file_hint)?; Ok((fetched.bytes, fetched.origin.reach())) }) @@ -1004,7 +1005,7 @@ fn left_template( /// In the browser nothing waits: the app reads the template itself and passes it as `"tiles"`. #[cfg(target_arch = "wasm32")] -fn advertised_template(source: &str, list: &str, _: bool, _: &mut u32, _: bool) -> AdvertisedTemplate { +fn advertised_template(source: &str, list: &str, _: bool, _: &mut u32, _: bool, _: bool) -> AdvertisedTemplate { AdvertisedTemplate { template: None, crossed_origin: crosses_origin(source, list), fallback: None, public: false } } @@ -1441,7 +1442,9 @@ fn add_discovered(s: &mut Session, p: &Value, url: &str, want: &str, found: &Dis } } (Some(list), None) => { - let advertised = advertised_template(source, list, matches!(layer.offer, Offer::VectorTiles { .. }), withheld, public); + let anonymous = s.web_logins.is_anonymous() || super::b(p, "anonymous") == Some(true); + let advertised = + advertised_template(source, list, matches!(layer.offer, Offer::VectorTiles { .. }), withheld, public, anonymous); if let Some(note) = &advertised.fallback { s.notify(note.clone(), false); } diff --git a/crates/engine/src/cmd/stac.rs b/crates/engine/src/cmd/stac.rs index d590ea56c4..6d7f620af5 100644 --- a/crates/engine/src/cmd/stac.rs +++ b/crates/engine/src/cmd/stac.rs @@ -321,7 +321,8 @@ fn search_static(s: &mut Session, p: &Value, root: &str) -> CmdResult { } #[cfg(not(target_arch = "wasm32"))] { - let walk = stac::catalog::walk_blocking(root, filter, search.limit); + let anonymous = s.web_logins.is_anonymous() || b(p, "anonymous") == Some(true); + let walk = stac::catalog::walk_blocking_with(root, filter, search.limit, anonymous); let complete = walk.complete(); let (read, failed) = (walk.reads, walk.failed); let (refused, skipped) = (walk.refused(), walk.skipped()); @@ -398,6 +399,9 @@ fn add_asset(s: &mut Session, p: &Value) -> CmdResult { if let Some(connection) = p.get("connection") { add["connection"] = connection.clone(); } + if b(p, "anonymous") == Some(true) { + add["anonymous"] = json!(true); + } let added = super::layer::add_url(s, &add)?; match codes { (_, true) => s.warn(format!( @@ -524,7 +528,8 @@ pub fn cube_files(s: &mut Session, p: &Value, max_items: usize, mask: Option<&st // A static collection has no search: read by its layout, and no pages follow. crate::render::rustgis_tiles::address::check(&api, None)?; let filter = stac::catalog::Filter::from_search(&search, None)?; - let found = stac::dated::search_blocking(&api, &filter, (&day(start), &day(end)), max_items)?; + let anonymous = s.web_logins.is_anonymous() || b(p, "anonymous") == Some(true); + let found = stac::dated::search_blocking_with(&api, &filter, (&day(start), &day(end)), max_items, anonymous)?; // Its items say which collection it is; another name given is a mistake. if let Some(other) = found.items.iter().map(|i| i.collection.as_str()).find(|c| !c.is_empty() && *c != collection) { return Err(format!("{api} holds {other}, not {collection}")); diff --git a/crates/engine/src/cmd/zarr.rs b/crates/engine/src/cmd/zarr.rs index fc86f9b53e..c486491b06 100644 --- a/crates/engine/src/cmd/zarr.rs +++ b/crates/engine/src/cmd/zarr.rs @@ -344,7 +344,7 @@ fn info(s: &mut Session, p: &Value) -> CmdResult { } #[cfg(not(target_arch = "wasm32"))] { - let anonymous = s.web_logins.is_anonymous(); + let anonymous = s.web_logins.is_anonymous() || b(p, "anonymous") == Some(true); let (root, store, mut v) = info_of(p, anonymous)?; // A bbox: the window of cells it is in a variable's grid, for layer.addZarr's cells. if let Some(asked) = asked_window(p)? { @@ -566,7 +566,7 @@ pub(crate) fn add(s: &mut Session, p: &Value) -> CmdResult { super::raster::add_raster(s, &name, layer) } Source::Url(u) => { - let anonymous = s.web_logins.is_anonymous(); + let anonymous = s.web_logins.is_anonymous() || b(p, "anonymous") == Some(true); let store = store_at(&u, &sel.variable, anonymous)?; pick_variable(&store, &mut sel)?; let cut = place_window(&u, &store, &mut sel, asked, anonymous)?; @@ -593,7 +593,14 @@ pub(crate) fn add(s: &mut Session, p: &Value) -> CmdResult { // The coordinate system given for a store that doesn't say, kept as a folder's slice // keeps it, so a time series read from the layer finds it. layer.crs = crs.map(str::to_string); - super::raster::add_raster(s, &name, layer) + let out = super::raster::add_raster(s, &name, layer)?; + if anonymous + && let Some(id) = s.active_layer + && let Some(l) = s.map_mut().layer_mut(id) + { + l.anonymous = true; + } + Ok(out) } } } @@ -1215,6 +1222,7 @@ fn follow(s: &mut Session, wait: bool) { for l in &mut m.layers { let owner = (map, l.instance_id()); let name = l.name.clone(); + let layer_anonymous = anonymous || l.anonymous; let Some(rl) = l.raster.as_mut() else { continue }; let Some(zt) = rl.time_zarr.as_mut() else { continue }; let want = zt.step_for(window); @@ -1230,7 +1238,7 @@ fn follow(s: &mut Session, wait: bool) { } // Consume this layer's original completion, including its lifetime at landing. Some(i) if !wait => { - let read = s.zarr_reads.for_layer(owner, zt, i, anonymous); + let read = s.zarr_reads.for_layer(owner, zt, i, layer_anonymous); let result = observed.entry(std::sync::Arc::as_ptr(&read)).or_insert_with(|| read.poll()).clone(); // The shared observation does not replace the lifetime check at delivery. let result = result.map(|r| crate::render::rustgis_tiles::cache::check_still(&read.still).and(r)); @@ -1239,7 +1247,7 @@ fn follow(s: &mut Session, wait: bool) { rl.data = Some(r); zt.shown = Some(i); if is_web(&zt.store) { - ahead.push((zt.clone(), i, read.still.clone())); + ahead.push((zt.clone(), i, read.still.clone(), layer_anonymous)); } } Some(Err(e)) => { @@ -1250,17 +1258,17 @@ fn follow(s: &mut Session, wait: bool) { None => { waiting.insert(owner); if is_web(&zt.store) { - ahead.push((zt.clone(), i, read.still.clone())); + ahead.push((zt.clone(), i, read.still.clone(), layer_anonymous)); } } } } - Some(i) => match read_waiting(zt, i, anonymous) { + Some(i) => match read_waiting(zt, i, layer_anonymous) { Ok(r) => { rl.data = Some(r); zt.shown = Some(i); if is_web(&zt.store) { - ahead.push((zt.clone(), i, crate::render::rustgis_tiles::cache::current_still())); + ahead.push((zt.clone(), i, crate::render::rustgis_tiles::cache::current_still(), layer_anonymous)); } } Err(e) => { @@ -1290,8 +1298,8 @@ fn follow(s: &mut Session, wait: bool) { }; s.notify(text, true); } - for (zt, i, still) in ahead { - crate::render::rustgis_tiles::cache::with_optional_still(still, || read_ahead(zt, i, anonymous)); + for (zt, i, still, layer_anonymous) in ahead { + crate::render::rustgis_tiles::cache::with_optional_still(still, || read_ahead(zt, i, layer_anonymous)); } } #[cfg(target_arch = "wasm32")] @@ -1318,7 +1326,7 @@ fn add_following(s: &mut Session, p: &Value, asked: Option) -> CmdResult if let Some(c) = &crs { Crs::parse(c)?; } - let anonymous = s.web_logins.is_anonymous(); + let anonymous = s.web_logins.is_anonymous() || b(p, "anonymous") == Some(true); let (root, store, chunks) = match src { Source::Dir(d) => { let store = zarr::read_metadata(Path::new(&d)).map_err(|e| format!("{d}: {e}"))?; @@ -1467,6 +1475,12 @@ fn add_following(s: &mut Session, p: &Value, asked: Option) -> CmdResult }); layer.time_zarr = Some(zt); let mut out = super::raster::add_raster(s, &name, layer)?; + if anonymous + && let Some(id) = s.active_layer + && let Some(l) = s.map_mut().layer_mut(id) + { + l.anonymous = true; + } let said: Vec = window_notes.into_iter().chain(part).collect(); for w in &said { s.warn(w.clone()); @@ -1491,6 +1505,7 @@ struct SeriesSource { period: Option<(u64, usize)>, crs: Option, read_generation: u64, + anonymous: bool, } #[cfg(not(target_arch = "wasm32"))] @@ -1507,6 +1522,7 @@ fn series_source(s: &Session, p: &Value) -> Result { period: Some((zt.offset, zt.dates.len())), crs: zt.crs.clone(), read_generation: zt.read_generation, + anonymous: l.anonymous, }); } // A slice: its store is its folder, or the address it was read from. @@ -1522,13 +1538,21 @@ fn series_source(s: &Session, p: &Value) -> Result { period: None, crs: rl.crs.clone(), read_generation: rustgis_map::raster::next_read_generation(), + anonymous: l.anonymous, }); } let root = match source(p)? { Source::Dir(d) | Source::Url(d) => d, }; let crs = ps(p, "crs").map(str::trim).filter(|c| !c.is_empty()).map(str::to_string); - Ok(SeriesSource { root, sel: selection(p), period: None, crs, read_generation: rustgis_map::raster::next_read_generation() }) + Ok(SeriesSource { + root, + sel: selection(p), + period: None, + crs, + read_generation: rustgis_map::raster::next_read_generation(), + anonymous: false, + }) } /// A store's metadata, and its files `keys`: a folder's read (files only, bounded), a web @@ -1829,7 +1853,8 @@ pub fn series_start(s: &Session, p: &Value) -> Result { } }; let (start, end) = (date("start")?, date("end")?); - Ok(SeriesRun { lon, lat, src, start, end, anonymous: s.web_logins.is_anonymous() }) + let anonymous = s.web_logins.is_anonymous() || b(p, "anonymous") == Some(true) || src.anonymous; + Ok(SeriesRun { lon, lat, src, start, end, anonymous }) } // --- A summary over time (opengeos/RustGIS#556) ---------------------------------------------------- @@ -1999,8 +2024,8 @@ pub struct ZarrCube { /// The cube of a Zarr layer, or of the store and variable the parameters name. #[cfg(not(target_arch = "wasm32"))] pub fn zarr_cube(s: &Session, p: &Value) -> Result { - let anonymous = s.web_logins.is_anonymous(); let mut src = series_source(s, p)?; + let anonymous = s.web_logins.is_anonymous() || b(p, "anonymous") == Some(true) || src.anonymous; // A layer that is a window of its variable: its steps over time would be read whole. if src.sel.window.is_some() { return Err(format!( diff --git a/crates/engine/src/project_log.rs b/crates/engine/src/project_log.rs index fdc2a5a8ad..1d7bcfd4b1 100644 --- a/crates/engine/src/project_log.rs +++ b/crates/engine/src/project_log.rs @@ -125,17 +125,14 @@ pub(crate) fn kept_params(params: &Value) -> Value { } } -/// An error as the log keeps it: clipped to [`LOG_ERROR_CHARS`] before its secrets are taken out, -/// so a long one costs little (a secret cut short still follows its name). +/// An error as the log keeps it: active logins and `rustgis-s3:` wrappers are scrubbed before +/// clipping to [`LOG_ERROR_CHARS`] so a secret spanning the clip boundary cannot leave a prefix +/// behind, then other secrets are removed. fn kept_error(e: &str) -> String { - let e = if e.chars().nth(LOG_ERROR_CHARS).is_some() { - format!("{}…", e.chars().take(LOG_ERROR_CHARS).collect::()) - } else { - e.to_string() - }; - let e = crate::sources::scrub_s3_wrappers(&e); - let e = crate::cmd::history::redacted_text(&sql_secrets_removed(&e)); - crate::sources::scrub_s3_wrappers(&crate::render::rustgis_tiles::logins::scrub(&e)) + let e = scrub_log_text(e); + let e = + if e.chars().nth(LOG_ERROR_CHARS).is_some() { format!("{}…", e.chars().take(LOG_ERROR_CHARS).collect::()) } else { e }; + crate::cmd::history::redacted_text(&sql_secrets_removed(&e)) } /// `v` without secrets: as History's Copy as code takes them out (`history::redacted`), and, @@ -207,7 +204,7 @@ fn redacted(v: &Value) -> Value { /// Removes active login values and runtime capability wrappers from every string and object key /// retained in log parameters. fn scrub_log_text(t: &str) -> String { - crate::sources::scrub_s3_wrappers(&crate::render::rustgis_tiles::logins::scrub(t)) + crate::render::rustgis_tiles::logins::scrub(&crate::sources::scrub_s3_wrappers(t)) } fn scrub_log_value(v: Value, depth: usize) -> Value { diff --git a/crates/engine/src/tests/scopes_and_redaction.rs b/crates/engine/src/tests/scopes_and_redaction.rs index 6c370a2b66..4311669678 100644 --- a/crates/engine/src/tests/scopes_and_redaction.rs +++ b/crates/engine/src/tests/scopes_and_redaction.rs @@ -821,18 +821,51 @@ fn anonymous_reads_suppress_implicit_s3_and_sign_in_credentials() { let addr = listener.local_addr().unwrap(); let base = format!("http://{addr}"); let seen: Arc>> = Arc::new(Mutex::new(Vec::new())); + let read_errors: Arc>> = Arc::new(Mutex::new(Vec::new())); let stop = Arc::new(AtomicBool::new(false)); let seen_srv = seen.clone(); + let errs_srv = read_errors.clone(); let stop_srv = stop.clone(); let server = std::thread::spawn(move || { + const MAX_HEADER_BYTES: usize = 16 * 1024; while let Ok((mut stream, _)) = listener.accept() { if stop_srv.load(Ordering::SeqCst) { break; } let _ = stream.set_read_timeout(Some(std::time::Duration::from_secs(5))); - let mut buf = [0u8; 4096]; - let n = stream.read(&mut buf).unwrap_or(0); - let req = String::from_utf8_lossy(&buf[..n]).into_owned(); + let mut buf = Vec::new(); + let mut chunk = [0u8; 1024]; + let mut complete = false; + loop { + match stream.read(&mut chunk) { + Ok(0) => break, + Ok(n) => { + buf.extend_from_slice(&chunk[..n]); + if buf.windows(4).any(|w| w == b"\r\n\r\n") { + complete = true; + break; + } + if buf.len() > MAX_HEADER_BYTES { + errs_srv + .lock() + .unwrap_or_else(|e| e.into_inner()) + .push(format!("oversized request headers ({} bytes)", buf.len())); + break; + } + } + Err(e) => { + errs_srv.lock().unwrap_or_else(|e| e.into_inner()).push(format!("header read failed: {e}")); + break; + } + } + } + if !complete { + if !stop_srv.load(Ordering::SeqCst) && errs_srv.lock().unwrap_or_else(|e| e.into_inner()).is_empty() { + errs_srv.lock().unwrap_or_else(|e| e.into_inner()).push(format!("incomplete request headers ({} bytes)", buf.len())); + } + continue; + } + let req = String::from_utf8_lossy(&buf).into_owned(); let first = req.lines().next().unwrap_or(""); if first.contains("/__stop") { let _ = stream.write_all(b"HTTP/1.1 200 OK\r\nContent-Length: 0\r\nConnection: close\r\n\r\n"); @@ -890,7 +923,7 @@ fn anonymous_reads_suppress_implicit_s3_and_sign_in_credentials() { assert!(!r.contains("AKIA_SYNTH_ANON") && !r.to_ascii_lowercase().contains("authorization:"), "s3.list signed anonymously: {r}"); } - // 2. Zarr metadata fetches under anonymous session must not carry S3 signing headers. + // 2. Zarr metadata fetches under anonymous session or explicit anonymous param must not sign. crate::service_logins::anonymously(&mut s, true, |s| { let _ = s.run("raster.zarrInfo", &json!({"url": format!("{base}/priv-bkt-anon/store.zarr")})); }) @@ -900,6 +933,43 @@ fn anonymous_reads_suppress_implicit_s3_and_sign_in_credentials() { for r in &zarr_reqs { assert!(!r.contains("AKIA_SYNTH_ANON") && !r.to_ascii_lowercase().contains("authorization:"), "zarr signed anonymously: {r}"); } + let _ = s.run("raster.zarrInfo", &json!({"url": format!("{base}/priv-bkt-anon/explicit-anon.zarr"), "anonymous": true})); + let explicit_zarr_reqs = std::mem::take(&mut *seen.lock().unwrap_or_else(|e| e.into_inner())); + assert!(!explicit_zarr_reqs.is_empty()); + for r in &explicit_zarr_reqs { + assert!( + !r.contains("AKIA_SYNTH_ANON") && !r.to_ascii_lowercase().contains("authorization:"), + "zarr explicit anonymous signed: {r}" + ); + } + + // 2b. Time-following Zarr layers tagged anonymous stay anonymous outside an anonymous scope. + { + let mut rl = rustgis_map::raster::RasterLayer::unread_in_place(format!("{base}/priv-bkt-anon/follow.zarr")); + rl.time_zarr = Some(rustgis_map::raster::ZarrTime { + store: format!("{base}/priv-bkt-anon/follow.zarr"), + variable: "v".into(), + index: vec![], + dim: "t".into(), + offset: 0, + dates: vec![0.0, 86_400_000.0], + crs: None, + window: None, + shown: None, + read_generation: rustgis_map::raster::next_read_generation(), + }); + let id = s.map_mut().add_raster("AnonZarr", rl); + s.map_mut().layer_mut(id).unwrap().anonymous = true; + crate::cmd::zarr::follow_time_now(&mut s); + let follow_reqs = std::mem::take(&mut *seen.lock().unwrap_or_else(|e| e.into_inner())); + assert!(!follow_reqs.is_empty()); + for r in &follow_reqs { + assert!( + !r.contains("AKIA_SYNTH_ANON") && !r.to_ascii_lowercase().contains("authorization:"), + "follow_time signed an anonymous Zarr layer: {r}" + ); + } + } // 3. layer.addUrl under anonymous session must not carry S3 signing headers. crate::service_logins::anonymously(&mut s, true, |s| { @@ -925,6 +995,8 @@ fn anonymous_reads_suppress_implicit_s3_and_sign_in_credentials() { stop.store(true, Ordering::SeqCst); let _ = std::net::TcpStream::connect(addr); let _ = server.join(); + let errs = read_errors.lock().unwrap_or_else(|e| e.into_inner()); + assert!(errs.is_empty(), "mock HTTP server saw incomplete or failed header reads: {errs:?}"); let _ = s.run("s3.disconnect", &json!({"name": "priv-anon-test"})); let _ = s.run("s3.disconnect", &json!({"name": "pub-anon-test"})); } @@ -946,7 +1018,11 @@ fn map_set_tiles_legend_requires_network_and_preserves_existing_tile_layers() { assert!(!effects.contains(Effect::Network), "clearing legend must not require Network: {clearing}"); } - s.run("map.addTiles", &json!({"url": "https://tiles.example.org/{z}/{x}/{y}.png", "name": "Base"})).unwrap(); + s.run( + "map.addTiles", + &json!({"url": "https://tiles.example.org/{z}/{x}/{y}.png", "name": "Base", "legend": "https://tiles.example.org/orig.png"}), + ) + .unwrap(); isolate_plugins(); plugin("plug-no-net-legend", &["edit"]); let err = @@ -955,10 +1031,13 @@ fn map_set_tiles_legend_requires_network_and_preserves_existing_tile_layers() { assert!(err.contains("network"), "{err}"); assert_eq!(s.map().tiles.len(), 1, "existing tile layer must be preserved"); assert_eq!(s.map().tiles[0].name, "Base"); - assert!(s.map().tiles[0].legends.is_empty()); + assert_eq!(s.map().tiles[0].legends.len(), 1); + assert_eq!(s.map().tiles[0].legends[0].url, "https://tiles.example.org/orig.png"); - // Clearing legends remains allowed for an edit-only plugin. + // Clearing an existing legend remains allowed for an edit-only plugin. forward(&mut s, "plug-no-net-legend", "map.setTiles", json!({"name": "Base", "legend": null})).unwrap(); + assert_eq!(s.map().tiles.len(), 1); + assert!(s.map().tiles[0].legends.is_empty()); rustgis_plugins::unload("plug-no-net-legend"); } @@ -1096,6 +1175,14 @@ fn project_log_scrubs_active_logins_and_s3_wrappers() { assert!(!err.contains(&active_secret), "session log error leaked active login: {err}"); assert!(!err.contains("rustgis-s3:"), "session log error leaked s3 wrapper: {err}"); assert!(!err.contains(&s3_tok), "session log error leaked wrapped token: {err}"); + + // An active login spanning the error clip boundary must be scrubbed before truncation. + let pad = "a".repeat(1985); + let _ = s.run("layer.rename", &json!({"layer": format!("{pad}{active_secret}tail")})); + let entry = s.log.entries().last().unwrap(); + let clipped_err = entry.error.as_deref().unwrap_or(""); + assert!(!clipped_err.contains(&active_secret), "clipped error leaked active login: {clipped_err}"); + assert!(!clipped_err.contains(&active_secret[..8]), "clipped error leaked active login prefix: {clipped_err}"); } #[cfg(not(target_arch = "wasm32"))] diff --git a/crates/tiles/src/stac/catalog.rs b/crates/tiles/src/stac/catalog.rs index adc8e8ffac..facfff9ce9 100644 --- a/crates/tiles/src/stac/catalog.rs +++ b/crates/tiles/src/stac/catalog.rs @@ -543,6 +543,12 @@ fn collection_item(v: &Value, from: &str) -> Option { /// them off the frame): the walk, finished. #[cfg(not(target_arch = "wasm32"))] pub fn walk_blocking(root: &str, filter: Filter, limit: usize) -> Walk { + walk_blocking_with(root, filter, limit, false) +} + +/// [`walk_blocking`], suppressing implicit S3 and web-service credentials when `anonymous` is true. +#[cfg(not(target_arch = "wasm32"))] +pub fn walk_blocking_with(root: &str, filter: Filter, limit: usize, anonymous: bool) -> Walk { let mut w = Walk::new(root, filter, limit); loop { // A few documents at a time, each on its own thread. @@ -552,8 +558,9 @@ pub fn walk_blocking(root: &str, filter: Filter, limit: usize) -> Walk { } let read = |u: String, public: bool| { let ceiling = if public { crate::address::Reach::Public } else { crate::address::Reach::Local }; + let fetch_u = if anonymous { crate::s3::anonymous(&u) } else { u.clone() }; let r = crate::cache::download_blocking_with_origin_within( - &u, + &fetch_u, crate::cache::MAX_DOWNLOAD, std::time::Duration::from_secs(60), &[], diff --git a/crates/tiles/src/stac/dated.rs b/crates/tiles/src/stac/dated.rs index 2a89f59230..4ea18d80b9 100644 --- a/crates/tiles/src/stac/dated.rs +++ b/crates/tiles/src/stac/dated.rs @@ -318,7 +318,15 @@ pub fn search(root: &str, filter: &Filter, period: (&str, &str), max_items: usiz /// [`search`], waiting for each document (the command line, and the app's `stac.addCube`). pub fn search_blocking(root: &str, filter: &Filter, period: (&str, &str), max_items: usize) -> Result { - search(root, filter, period, max_items, &|u| crate::cache::download_blocking(u)) + search_blocking_with(root, filter, period, max_items, false) +} + +/// [`search_blocking`], suppressing implicit S3 and web-service credentials when `anonymous` is true. +pub fn search_blocking_with(root: &str, filter: &Filter, period: (&str, &str), max_items: usize, anonymous: bool) -> Result { + search(root, filter, period, max_items, &|u| { + let fetch_u = if anonymous { crate::s3::anonymous(u) } else { u.to_string() }; + crate::cache::download_blocking(&fetch_u) + }) } #[cfg(test)] From 33e2658ec647e7b6123648dff1cb26666e884ad8 Mon Sep 17 00:00:00 2001 From: giswqs Date: Wed, 25 Nov 2026 10:25:42 -0500 Subject: [PATCH 03/20] Address CodeRabbit review feedback - Honor explicit anonymous flags on same-origin coverage and feature requests in service.add. - Forward anonymous mode from stac.addCube into sample_range COG reads and layer.addUrl. --- crates/engine/src/cmd/service.rs | 7 +++++-- crates/engine/src/cmd/stac.rs | 15 +++++++++++---- 2 files changed, 16 insertions(+), 6 deletions(-) diff --git a/crates/engine/src/cmd/service.rs b/crates/engine/src/cmd/service.rs index 21fdf881d4..8471040f44 100644 --- a/crates/engine/src/cmd/service.rs +++ b/crates/engine/src/cmd/service.rs @@ -1581,7 +1581,10 @@ fn add_discovered(s: &mut Session, p: &Value, url: &str, want: &str, found: &Dis ), )), Offer::Coverage(c) => { - let anonymous = capability_crossed || crosses_origin(source, &c.endpoint) || s.web_logins.is_anonymous(); + let anonymous = capability_crossed + || crosses_origin(source, &c.endpoint) + || s.web_logins.is_anonymous() + || super::b(p, "anonymous") == Some(true); let (get, _, _, asked) = match ps(p, "describe") { // A plugin's command: its description read off the frame, as its documents are. None if leaving => { @@ -1654,7 +1657,7 @@ fn add_discovered(s: &mut Session, p: &Value, url: &str, want: &str, found: &Dis let from = asked.as_deref().unwrap_or(items); let crossed = capability_crossed || crosses_origin(source, from); let from = if crossed { crate::render::rustgis_tiles::logins::inner(from) } else { from }; - let anonymous = crossed || s.web_logins.is_anonymous(); + let anonymous = crossed || s.web_logins.is_anonymous() || super::b(p, "anonymous") == Some(true); crate::service_logins::anonymously(s, anonymous, |s| { // An area request keeps the view until the requested box is applied below. let keep_view = asked.is_some().then_some(false); diff --git a/crates/engine/src/cmd/stac.rs b/crates/engine/src/cmd/stac.rs index 6d7f620af5..877acadb48 100644 --- a/crates/engine/src/cmd/stac.rs +++ b/crates/engine/src/cmd/stac.rs @@ -1443,6 +1443,7 @@ fn add_cube(s: &mut Session, p: &Value) -> CmdResult { )); } } + let anonymous = s.web_logins.is_anonymous() || b(p, "anonymous") == Some(true); // A range from the files themselves: one for every date and tile, as a range given is. let mut sampled = None; let range = if !auto { @@ -1458,7 +1459,7 @@ fn add_cube(s: &mut Session, p: &Value) -> CmdResult { )); None } else { - match sample_range(&tiles, &scales, scale, &nodata) { + match sample_range(&tiles, &scales, scale, &nodata, anonymous) { Ok(Sample::Range(r)) => { sampled = Some(r); Some((r[0], r[1])) @@ -1519,7 +1520,11 @@ fn add_cube(s: &mut Session, p: &Value) -> CmdResult { let urls: Vec<(f64, String)> = by_day.iter().map(|(d, u)| (*d as f64 * 86_400_000.0, format!("{u}{look}"))).collect(); let Some((_, first)) = urls.first() else { continue }; let name = if many { format!("{base} {tile}") } else { base.clone() }; - let r = match super::layer::add_url(s, &json!({"url": first, "name": name, "cube": true, "connection": p.get("connection")})) { + let mut add = json!({"url": first, "name": name, "cube": true, "connection": p.get("connection")}); + if anonymous { + add["anonymous"] = json!(true); + } + let r = match super::layer::add_url(s, &add) { Ok(r) => r, Err(e) => { undo(s); @@ -1663,6 +1668,7 @@ fn sample_range( scales: &std::collections::HashMap, scale: Option<(f64, f64)>, nodata: &std::collections::HashMap>, + anonymous: bool, ) -> Result { use crate::render::rustgis_tiles::{cog, cubes}; let newest: Vec<&String> = tiles.values().filter_map(|by_day| by_day.values().next_back()).collect(); @@ -1670,7 +1676,8 @@ fn sample_range( let picked: Vec<&String> = (0..n.min(SAMPLE_FILES)).filter_map(|i| newest.get(i * n / n.min(SAMPLE_FILES))).copied().collect(); let mut values = Vec::new(); for href in picked { - let info = cog::info_blocking(href)?; + let fetch_href = crate::service_logins::fetch_url(anonymous, href); + let info = cog::info_blocking(&fetch_href)?; let l = &info.layout; if l.palette.is_some() { return Ok(Sample::Classes); @@ -1681,7 +1688,7 @@ fn sample_range( }; let (w, h) = (lv.width.min(SAMPLE_SIDE), lv.height.min(SAMPLE_SIDE)); let (c0, r0) = ((lv.width - w) / 2, (lv.height - h) / 2); - let read = cog::read_values_blocking(&info, href, level, 0, (c0, c0 + w), (r0, r0 + h))?; + let read = cog::read_values_blocking(&info, &fetch_href, level, 0, (c0, c0 + w), (r0, r0 + h))?; let (k, o) = scales.get(href).copied().or(scale).unwrap_or((1.0, 0.0)); let fill: Vec = nodata.get(href).map(|f| f.iter().map(|v| *v as f32).collect()).unwrap_or_default(); values.extend(read.into_iter().filter(|v| v.is_finite() && !fill.contains(v)).map(|v| f64::from(v) * k + o)); From 1f03e62ee39c63de54c408f91e21a9aaea1e7112 Mon Sep 17 00:00:00 2001 From: giswqs Date: Wed, 25 Nov 2026 10:36:50 -0500 Subject: [PATCH 04/20] Address Claude review feedback - Stringify and scrub deeply nested containers (depth >= 8) in project_log::scrub_log_value so active logins and S3 wrappers cannot bypass scrubbing. - Skip primitive JSON values (numbers, booleans, nulls) when counting nodes in plugin_fetch::web_addresses so large coordinate or numeric arrays do not trip the scan limit. - Expand regression tests for deep log scrubbing and large numeric vs string arrays. --- crates/engine/src/cmd/plugin_fetch.rs | 11 ++++++--- crates/engine/src/project_log.rs | 1 + .../engine/src/tests/scopes_and_redaction.rs | 24 +++++++++++++++++-- 3 files changed, 31 insertions(+), 5 deletions(-) diff --git a/crates/engine/src/cmd/plugin_fetch.rs b/crates/engine/src/cmd/plugin_fetch.rs index 1c7297f155..25ad995eec 100644 --- a/crates/engine/src/cmd/plugin_fetch.rs +++ b/crates/engine/src/cmd/plugin_fetch.rs @@ -244,10 +244,15 @@ const MAX_ADDRESS_SCAN_NODES: usize = 4096; /// [`MAX_ADDRESS_SCAN_NODES`] nodes; overly complex parameters are refused rather than skipped. fn web_addresses(params: &Value) -> Result, String> { let Some(o) = params.as_object() else { return Ok(Vec::new()) }; - let mut stack: Vec<&Value> = o.iter().filter(|(key, _)| !matches!(key.as_str(), "data" | "text")).map(|(_, v)| v).collect(); + let is_primitive = |v: &Value| matches!(v, Value::Number(_) | Value::Bool(_) | Value::Null); + let mut stack: Vec<&Value> = + o.iter().filter(|(key, v)| !matches!(key.as_str(), "data" | "text") && !is_primitive(v)).map(|(_, v)| v).collect(); let mut out = Vec::new(); let mut visited = 0usize; while let Some(v) = stack.pop() { + if is_primitive(v) { + continue; + } visited += 1; if visited > MAX_ADDRESS_SCAN_NODES { return Err("command parameters are too complex for a plugin network check".into()); @@ -259,8 +264,8 @@ fn web_addresses(params: &Value) -> Result, String> { out.push(s); } } - Value::Array(a) => stack.extend(a.iter()), - Value::Object(m) => stack.extend(m.values()), + Value::Array(a) => stack.extend(a.iter().filter(|x| !is_primitive(x))), + Value::Object(m) => stack.extend(m.values().filter(|x| !is_primitive(x))), _ => {} } } diff --git a/crates/engine/src/project_log.rs b/crates/engine/src/project_log.rs index 1d7bcfd4b1..1f73cffa6c 100644 --- a/crates/engine/src/project_log.rs +++ b/crates/engine/src/project_log.rs @@ -214,6 +214,7 @@ fn scrub_log_value(v: Value, depth: usize) -> Value { Value::Object(o) if depth < 8 => { Value::Object(o.into_iter().map(|(k, x)| (scrub_log_text(&k), scrub_log_value(x, depth + 1))).collect()) } + container @ (Value::Array(_) | Value::Object(_)) => Value::String(scrub_log_text(&container.to_string())), other => other, } } diff --git a/crates/engine/src/tests/scopes_and_redaction.rs b/crates/engine/src/tests/scopes_and_redaction.rs index 4311669678..ac77f2d6db 100644 --- a/crates/engine/src/tests/scopes_and_redaction.rs +++ b/crates/engine/src/tests/scopes_and_redaction.rs @@ -1072,8 +1072,18 @@ fn plugin_address_hold_scans_nested_legend_urls_and_bounds_work() { forward(&mut s, "plug-net-nested", "map.setTiles", json!({"name": "Base", "legend": [{"url": public_legend}]})).unwrap(); assert_eq!(cache::ceiling_for(public_legend), Reach::Public); - // Overly large nested payloads fail closed rather than bypassing the address scan. - let mut pad: Vec = (0..4100).map(|i| json!(i)).collect(); + // Large numeric arrays do not trip the node limit, while still scanning any strings inside. + let mut nums: Vec = (0..4100).map(|i| json!(i)).collect(); + forward(&mut s, "plug-net-nested", "map.setTiles", json!({"name": "Base", "legend": [{"url": public_legend}], "extra": nums.clone()})) + .unwrap(); + nums.push(json!("http://127.0.0.1:8080/hidden.png")); + let err = + forward(&mut s, "plug-net-nested", "map.addTiles", json!({"url": "https://tiles.example.org/{z}/{x}/{y}.png", "extra": nums})) + .unwrap_err(); + assert!(err.contains("this computer or the local network"), "{err}"); + + // Overly large nested string/container payloads fail closed rather than bypassing the scan. + let mut pad: Vec = (0..4100).map(|i| json!(format!("item-{i}"))).collect(); pad.push(json!("http://127.0.0.1:8080/hidden.png")); let err = forward(&mut s, "plug-net-nested", "map.addTiles", json!({"url": "https://tiles.example.org/{z}/{x}/{y}.png", "extra": pad})) .unwrap_err(); @@ -1168,6 +1178,16 @@ fn project_log_scrubs_active_logins_and_s3_wrappers() { assert!(!logged.contains("rustgis-s3:"), "log_params leaked s3 wrapper: {logged}"); assert!(!logged.contains(&s3_tok), "log_params leaked wrapped query token: {logged}"); + // Deeply nested containers (depth >= 8) must still scrub active logins and S3 wrappers. + let mut deep = json!({ format!("k-{active_secret}"): format!("{active_secret} {wrapped}") }); + for _ in 0..10 { + deep = json!({"nested": [deep]}); + } + let deep_logged = crate::log_params(&deep).into_log_value().to_string(); + assert!(!deep_logged.contains(&active_secret), "deep log_params leaked active login: {deep_logged}"); + assert!(!deep_logged.contains("rustgis-s3:"), "deep log_params leaked s3 wrapper: {deep_logged}"); + assert!(!deep_logged.contains(&s3_tok), "deep log_params leaked wrapped token: {deep_logged}"); + // Failed command errors recorded in the session log must also scrub active logins and wrappers. let _ = s.run("layer.rename", &json!({"layer": format!("missing {active_secret} {wrapped}")})); let entry = s.log.entries().last().unwrap(); From e942b9ddaf528ece1b36e26f5aa997de14f797da Mon Sep 17 00:00:00 2001 From: giswqs Date: Wed, 25 Nov 2026 10:56:21 -0500 Subject: [PATCH 05/20] Address CodeRabbit review feedback - Omit deeply nested containers (depth >= 8) in project_log::scrub_log_value instead of stringifying them, so JSON escaping cannot disguise active credentials and parameters are marked partial. - Add regression test for active credentials containing quotes and backslashes inside deeply nested containers. --- crates/engine/src/project_log.rs | 7 ++++--- .../engine/src/tests/scopes_and_redaction.rs | 20 +++++++++++++++++-- 2 files changed, 22 insertions(+), 5 deletions(-) diff --git a/crates/engine/src/project_log.rs b/crates/engine/src/project_log.rs index 1f73cffa6c..7c8745e8a3 100644 --- a/crates/engine/src/project_log.rs +++ b/crates/engine/src/project_log.rs @@ -201,8 +201,9 @@ fn redacted(v: &Value) -> Value { scrub_log_value(crate::cmd::history::redacted(&embedded_redacted(v, 0)), 0) } -/// Removes active login values and runtime capability wrappers from every string and object key -/// retained in log parameters. +/// Removes active login values and runtime capability wrappers from strings and object keys +/// retained in log parameters. Containers nested to depth 8 or deeper are omitted rather than +/// serialized so JSON escaping cannot disguise an active credential. fn scrub_log_text(t: &str) -> String { crate::render::rustgis_tiles::logins::scrub(&crate::sources::scrub_s3_wrappers(t)) } @@ -214,7 +215,7 @@ fn scrub_log_value(v: Value, depth: usize) -> Value { Value::Object(o) if depth < 8 => { Value::Object(o.into_iter().map(|(k, x)| (scrub_log_text(&k), scrub_log_value(x, depth + 1))).collect()) } - container @ (Value::Array(_) | Value::Object(_)) => Value::String(scrub_log_text(&container.to_string())), + Value::Array(_) | Value::Object(_) => Value::String("[omitted: nested too deeply]".into()), other => other, } } diff --git a/crates/engine/src/tests/scopes_and_redaction.rs b/crates/engine/src/tests/scopes_and_redaction.rs index ac77f2d6db..89d29031d0 100644 --- a/crates/engine/src/tests/scopes_and_redaction.rs +++ b/crates/engine/src/tests/scopes_and_redaction.rs @@ -1178,15 +1178,31 @@ fn project_log_scrubs_active_logins_and_s3_wrappers() { assert!(!logged.contains("rustgis-s3:"), "log_params leaked s3 wrapper: {logged}"); assert!(!logged.contains(&s3_tok), "log_params leaked wrapped query token: {logged}"); - // Deeply nested containers (depth >= 8) must still scrub active logins and S3 wrappers. - let mut deep = json!({ format!("k-{active_secret}"): format!("{active_secret} {wrapped}") }); + // Deeply nested containers (depth >= 8) must omit contents so active logins (including ones + // with quotes or backslashes that JSON escaping would alter) and S3 wrappers cannot survive. + let quoted_secret = format!("pa\"ss\\word_{}", fixture_marker("deep_quoted")); + let conn2 = s + .run( + "connection.new", + &json!({"kind": "wms", "address": "https://log-scrub-quoted.example.org/wms", "auth": "header", "keyName": "X-Key"}), + ) + .unwrap(); + s.run("connection.login", &json!({"id": conn2["id"], "apiKey": quoted_secret})).unwrap(); + + let mut deep = json!({ format!("k-{active_secret}"): format!("{active_secret} {quoted_secret} {wrapped}") }); for _ in 0..10 { deep = json!({"nested": [deep]}); } let deep_logged = crate::log_params(&deep).into_log_value().to_string(); + let escaped_quoted = serde_json::to_string("ed_secret).unwrap(); + let escaped_inner = &escaped_quoted[1..escaped_quoted.len() - 1]; assert!(!deep_logged.contains(&active_secret), "deep log_params leaked active login: {deep_logged}"); + assert!(!deep_logged.contains("ed_secret), "deep log_params leaked quoted login: {deep_logged}"); + assert!(!deep_logged.contains(escaped_inner), "deep log_params leaked JSON-escaped quoted login: {deep_logged}"); assert!(!deep_logged.contains("rustgis-s3:"), "deep log_params leaked s3 wrapper: {deep_logged}"); assert!(!deep_logged.contains(&s3_tok), "deep log_params leaked wrapped token: {deep_logged}"); + let (kept_deep, partial) = crate::project_log::kept_and_partial(&deep); + assert!(partial, "deeply nested omitted container must mark params partial: {kept_deep}"); // Failed command errors recorded in the session log must also scrub active logins and wrappers. let _ = s.run("layer.rename", &json!({"layer": format!("missing {active_secret} {wrapped}")})); From 593a754e45f060bed09e6a114b905a80c708eb25 Mon Sep 17 00:00:00 2001 From: giswqs Date: Wed, 25 Nov 2026 11:30:32 -0500 Subject: [PATCH 06/20] Address Claude review feedback - Preserve anonymous mode across deferred and lazy in-place COG reads (overview, map drawing, raster export, project open, retry, and S3 reopen) while keeping stored layer paths plain. - Skip pure-primitive arrays such as [x, y] coordinate pairs from MAX_ADDRESS_SCAN_NODES in plugin_fetch::web_addresses while bounding total scanned elements at MAX_ADDRESS_SCAN_ELEMENTS. - Assert layer.rename failure in project_log_scrubs_active_logins_and_s3_wrappers and add regression tests for deferred anonymous COGs and 5,000 coordinate pairs. --- crates/engine/src/cmd/layer.rs | 20 ++++++--- crates/engine/src/cmd/plugin_fetch.rs | 23 ++++++++-- crates/engine/src/cmd/tiles.rs | 2 +- crates/engine/src/lib.rs | 2 + crates/engine/src/project.rs | 2 + crates/engine/src/s3_connections.rs | 5 ++- .../engine/src/tests/scopes_and_redaction.rs | 42 +++++++++++++++---- crates/map/src/raster.rs | 30 ++++++++++++- crates/render/src/lib.rs | 10 ++++- crates/render/src/raster_export.rs | 4 +- 10 files changed, 117 insertions(+), 23 deletions(-) diff --git a/crates/engine/src/cmd/layer.rs b/crates/engine/src/cmd/layer.rs index 3e1c6c660d..f666a9405c 100644 --- a/crates/engine/src/cmd/layer.rs +++ b/crates/engine/src/cmd/layer.rs @@ -6109,20 +6109,30 @@ fn add_in_place( let fetch_file = crate::service_logins::fetch_url(anonymous, file); #[cfg(not(target_arch = "wasm32"))] let layer = if strict && s.in_place_wait { - rustgis_map::raster::RasterLayer::in_place(cog::raster::overview_blocking(&fetch_file)?, file) + rustgis_map::raster::RasterLayer::in_place(cog::raster::overview_blocking(&fetch_file)?, file).with_anonymous(anonymous) } else if strict { - rustgis_map::raster::RasterLayer::opening_in_place(file) + let mut layer = rustgis_map::raster::RasterLayer::unread_in_place(file).with_anonymous(anonymous); + let _ = layer.begin_reload(); + layer } else { - rustgis_map::raster::RasterLayer::unread_in_place(file) + rustgis_map::raster::RasterLayer::unread_in_place(file).with_anonymous(anonymous) }; #[cfg(target_arch = "wasm32")] let layer = { - let _ = (strict, anonymous); - rustgis_map::raster::RasterLayer::opening_in_place(file) + let _ = strict; + let mut layer = rustgis_map::raster::RasterLayer::unread_in_place(file).with_anonymous(anonymous); + let _ = layer.begin_reload(); + layer }; let layer = layer.with_look(super::tiles::address_look(look)); let landed = layer.data.is_some(); let mut r = super::raster::add_raster_after(s, name, layer, zoom)?; + if anonymous + && let Some(id) = s.active_layer + && let Some(l) = s.map_mut().layer_mut(id) + { + l.anonymous = true; + } // A header just read (natively) is waited for if something emptied the tile cache since (a // login ended): the layer would go unframed. A plugin's command in the app doesn't wait (it // runs on the frame), as in the browser. diff --git a/crates/engine/src/cmd/plugin_fetch.rs b/crates/engine/src/cmd/plugin_fetch.rs index 25ad995eec..79bdbf7612 100644 --- a/crates/engine/src/cmd/plugin_fetch.rs +++ b/crates/engine/src/cmd/plugin_fetch.rs @@ -236,12 +236,19 @@ impl Session { } } -/// The most JSON nodes inspected when scanning a plugin command's parameters for web addresses. +/// The most string, object, and non-primitive array nodes inspected when scanning a plugin +/// command's parameters for web addresses. const MAX_ADDRESS_SCAN_NODES: usize = 4096; +/// The most total array elements scanned across nested arrays (including pure-primitive coordinate +/// lists) so hostile gigantic payloads still fail closed. +const MAX_ADDRESS_SCAN_ELEMENTS: usize = 1_000_000; + /// The web addresses among a command's own parameters, not inside the contents of a file it -/// gives (`data`, `text`). Walks nested arrays and objects iteratively up to -/// [`MAX_ADDRESS_SCAN_NODES`] nodes; overly complex parameters are refused rather than skipped. +/// gives (`data`, `text`). Walks nested arrays and objects iteratively, skipping primitive leaves +/// and pure-primitive arrays (such as `[x, y]` coordinate pairs) from the +/// [`MAX_ADDRESS_SCAN_NODES`] count while bounding total scanned array elements at +/// [`MAX_ADDRESS_SCAN_ELEMENTS`]; overly complex parameters are refused rather than skipped. fn web_addresses(params: &Value) -> Result, String> { let Some(o) = params.as_object() else { return Ok(Vec::new()) }; let is_primitive = |v: &Value| matches!(v, Value::Number(_) | Value::Bool(_) | Value::Null); @@ -249,10 +256,20 @@ fn web_addresses(params: &Value) -> Result, String> { o.iter().filter(|(key, v)| !matches!(key.as_str(), "data" | "text") && !is_primitive(v)).map(|(_, v)| v).collect(); let mut out = Vec::new(); let mut visited = 0usize; + let mut elements = 0usize; while let Some(v) = stack.pop() { if is_primitive(v) { continue; } + if let Value::Array(a) = v { + elements = elements.saturating_add(a.len()); + if elements > MAX_ADDRESS_SCAN_ELEMENTS { + return Err("command parameters are too complex for a plugin network check".into()); + } + if a.iter().all(is_primitive) { + continue; + } + } visited += 1; if visited > MAX_ADDRESS_SCAN_NODES { return Err("command parameters are too complex for a plugin network check".into()); diff --git a/crates/engine/src/cmd/tiles.rs b/crates/engine/src/cmd/tiles.rs index 8bd1c99efa..f662aff4f1 100644 --- a/crates/engine/src/cmd/tiles.rs +++ b/crates/engine/src/cmd/tiles.rs @@ -767,7 +767,7 @@ pub(crate) fn cog_tiles_to_rasters(m: &mut rustgis_map::Map) { } // Read with the project's other rasters read in place (see `project::read_in_place`), in // its look once it lands. - let rl = RasterLayer::unread_in_place(file).with_look(address_look(&look)).from_tiles_dropping(dropped); + let rl = RasterLayer::unread_in_place(file).with_anonymous(t.anonymous).with_look(address_look(&look)).from_tiles_dropping(dropped); // A name another layer has: numbered, as a layer added is. let mut name = t.name.clone(); let mut nth = 1; diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 6d01ab221f..0c1fdded64 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -3062,7 +3062,9 @@ impl Session { let mut started = false; for m in &mut self.project.maps { for l in &mut m.layers { + let anon = l.anonymous; let Some(rl) = &mut l.raster else { continue }; + rl.anonymous |= anon; let Some((e, at, failures)) = rl.read_failure() else { continue }; let wait = cache::backoff(cache::retry_wait(e, cache::RETRY), failures); if at.elapsed() < wait { diff --git a/crates/engine/src/project.rs b/crates/engine/src/project.rs index 2233e4d49f..e23e0f5fcb 100644 --- a/crates/engine/src/project.rs +++ b/crates/engine/src/project.rs @@ -2164,7 +2164,9 @@ pub(crate) fn read_in_place(m: &mut Map) { .iter_mut() .filter_map(|l| { let name = l.name.clone(); + let anon = l.anonymous; let rl = l.raster.as_mut()?; + rl.anonymous |= anon; (rl.in_place && rl.error.is_none() && !rl.path.as_deref().is_some_and(crate::s3_connections::is_s3_backed)) .then_some((name, rl)) }) diff --git a/crates/engine/src/s3_connections.rs b/crates/engine/src/s3_connections.rs index eaef1800de..d4e5382381 100644 --- a/crates/engine/src/s3_connections.rs +++ b/crates/engine/src/s3_connections.rs @@ -312,7 +312,10 @@ fn reopen_where(s: &mut Session, which: impl Fn(&str) -> bool) -> Counts { } } let mut in_place = Vec::new(); - for raster in s.project.maps.iter_mut().flat_map(|m| m.layers.iter_mut()).filter_map(|l| l.raster.as_mut()) { + for l in s.project.maps.iter_mut().flat_map(|m| m.layers.iter_mut()) { + let anon = l.anonymous; + let Some(raster) = l.raster.as_mut() else { continue }; + raster.anonymous |= anon; if raster.data.is_none() && raster.time_zarr.is_none() && raster.path.as_deref().is_some_and(&which) { if raster.in_place { in_place.push(raster); diff --git a/crates/engine/src/tests/scopes_and_redaction.rs b/crates/engine/src/tests/scopes_and_redaction.rs index 89d29031d0..7dfc4f236f 100644 --- a/crates/engine/src/tests/scopes_and_redaction.rs +++ b/crates/engine/src/tests/scopes_and_redaction.rs @@ -985,6 +985,21 @@ fn anonymous_reads_suppress_implicit_s3_and_sign_in_credentials() { ); } + // 3b. Deferred in-place COG reads marked anonymous must not carry S3 signing headers. + { + let mut rl = + rustgis_map::raster::RasterLayer::unread_in_place(format!("{base}/priv-bkt-anon/deferred-cog.tif")).with_anonymous(true); + let _ = rustgis_map::raster::read_together(&mut [&mut rl], true); + let cog_reqs = std::mem::take(&mut *seen.lock().unwrap_or_else(|e| e.into_inner())); + assert!(!cog_reqs.is_empty(), "deferred in-place COG should issue an HTTP request"); + for r in &cog_reqs { + assert!( + !r.contains("AKIA_SYNTH_ANON") && !r.to_ascii_lowercase().contains("authorization:"), + "deferred anonymous COG signed with S3 credentials: {r}" + ); + } + } + // 4. request_params strips rustgis-s3: capability wrappers under anonymous mode. let wrapped = rustgis_data::s3_address::bind("0123456789abcdef", "https://s3.example.org", "s3://priv-bkt-anon/key.geojson").unwrap(); let p = json!({"url": wrapped}); @@ -1072,13 +1087,18 @@ fn plugin_address_hold_scans_nested_legend_urls_and_bounds_work() { forward(&mut s, "plug-net-nested", "map.setTiles", json!({"name": "Base", "legend": [{"url": public_legend}]})).unwrap(); assert_eq!(cache::ceiling_for(public_legend), Reach::Public); - // Large numeric arrays do not trip the node limit, while still scanning any strings inside. - let mut nums: Vec = (0..4100).map(|i| json!(i)).collect(); - forward(&mut s, "plug-net-nested", "map.setTiles", json!({"name": "Base", "legend": [{"url": public_legend}], "extra": nums.clone()})) - .unwrap(); - nums.push(json!("http://127.0.0.1:8080/hidden.png")); + // Large numeric and coordinate-pair arrays do not trip the node limit, while still scanning strings inside. + let mut coords: Vec = (0..5000).map(|i| json!([f64::from(i) * 0.01, f64::from(i) * -0.01])).collect(); + forward( + &mut s, + "plug-net-nested", + "map.setTiles", + json!({"name": "Base", "legend": [{"url": public_legend}], "extra": coords.clone()}), + ) + .unwrap(); + coords.push(json!([0.0, "http://127.0.0.1:8080/hidden.png"])); let err = - forward(&mut s, "plug-net-nested", "map.addTiles", json!({"url": "https://tiles.example.org/{z}/{x}/{y}.png", "extra": nums})) + forward(&mut s, "plug-net-nested", "map.addTiles", json!({"url": "https://tiles.example.org/{z}/{x}/{y}.png", "extra": coords})) .unwrap_err(); assert!(err.contains("this computer or the local network"), "{err}"); @@ -1205,7 +1225,10 @@ fn project_log_scrubs_active_logins_and_s3_wrappers() { assert!(partial, "deeply nested omitted container must mark params partial: {kept_deep}"); // Failed command errors recorded in the session log must also scrub active logins and wrappers. - let _ = s.run("layer.rename", &json!({"layer": format!("missing {active_secret} {wrapped}")})); + assert!( + s.run("layer.rename", &json!({"layer": format!("missing {active_secret} {wrapped}")})).is_err(), + "renaming a missing layer must fail to exercise error logging" + ); let entry = s.log.entries().last().unwrap(); let err = entry.error.as_deref().unwrap_or(""); assert!(!err.contains(&active_secret), "session log error leaked active login: {err}"); @@ -1214,7 +1237,10 @@ fn project_log_scrubs_active_logins_and_s3_wrappers() { // An active login spanning the error clip boundary must be scrubbed before truncation. let pad = "a".repeat(1985); - let _ = s.run("layer.rename", &json!({"layer": format!("{pad}{active_secret}tail")})); + assert!( + s.run("layer.rename", &json!({"layer": format!("{pad}{active_secret}tail")})).is_err(), + "renaming a missing padded layer must fail to exercise clipped error logging" + ); let entry = s.log.entries().last().unwrap(); let clipped_err = entry.error.as_deref().unwrap_or(""); assert!(!clipped_err.contains(&active_secret), "clipped error leaked active login: {clipped_err}"); diff --git a/crates/map/src/raster.rs b/crates/map/src/raster.rs index 5df1209661..e1d6e72fbe 100644 --- a/crates/map/src/raster.rs +++ b/crates/map/src/raster.rs @@ -110,6 +110,10 @@ pub struct RasterLayer { /// [`RasterLayer::dropped_unsaid`]). #[serde(skip)] dropped: Vec<&'static str>, + /// Runtime flag mirroring [`crate::Layer::anonymous`]: in-place COG overview and tile reads + /// suppress implicit S3 and web-service credentials when true. + #[serde(skip)] + pub anonymous: bool, } /// Called once with a cloud-optimised GeoTIFF's overview, or why it couldn't be read. @@ -333,6 +337,7 @@ impl RasterLayer { lost_said: false, look_lost: None, dropped: Vec::new(), + anonymous: false, }) } @@ -383,6 +388,7 @@ impl RasterLayer { lost_said: false, look_lost: None, dropped: Vec::new(), + anonymous: false, } } @@ -421,6 +427,7 @@ impl RasterLayer { lost_said: false, look_lost: None, dropped: Vec::new(), + anonymous: false, } } @@ -465,6 +472,24 @@ impl RasterLayer { lost_said: false, look_lost: None, dropped: Vec::new(), + anonymous: false, + } + } + + /// Marks the raster layer as read without implicit S3 or saved web-service credentials. + pub fn with_anonymous(mut self, anonymous: bool) -> RasterLayer { + self.anonymous = anonymous; + self + } + + /// The address passed to the COG reader: wrapped with `rustgis-anonymous:` when `self.anonymous` + /// is set so lazy overview and tile reads do not sign with an active S3 or web-service login. + pub fn fetch_address(&self) -> Option> { + let path = self.path.as_deref()?; + if self.anonymous && !path.starts_with("rustgis-anonymous:") { + Some(std::borrow::Cow::Owned(format!("rustgis-anonymous:{path}"))) + } else { + Some(std::borrow::Cow::Borrowed(path)) } } @@ -523,8 +548,9 @@ impl RasterLayer { let land = slot.clone(); self.opening = Some(slot); self.read_still = still.clone(); + let fetch = self.fetch_address().unwrap_or(std::borrow::Cow::Borrowed(&address)); reader( - &address, + &fetch, Box::new(move |result| { *land.lock().unwrap_or_else(|e| e.into_inner()) = Some(remote::check_still(&still).and(result.map(Arc::new))); crate::source::wake(); @@ -896,6 +922,7 @@ impl RasterLayer { lost_said: _, look_lost: _, dropped: _, + anonymous: _, } = self; if *in_place || *tiled || opening.is_some() || read_still.is_some() || self.casts_shadows() { return None; @@ -2602,6 +2629,7 @@ impl RasterLayer { lost_said: _, look_lost: _, dropped: _, + anonymous: _, } = self; let mut out = Vec::new(); if let Some(p) = path { diff --git a/crates/render/src/lib.rs b/crates/render/src/lib.rs index 3744c7b871..5668d65db8 100644 --- a/crates/render/src/lib.rs +++ b/crates/render/src/lib.rs @@ -5196,8 +5196,14 @@ fn render_frame( water: lake_light.as_deref(), }; // Read in place: the part in view, at the level the view needs. - let address = rl.path.as_deref().filter(|_| rl.reads_in_place()); - let mut draw_it = |pm: &mut Pixmap, opacity: f32| match address { + let address = rl.path.as_deref().filter(|_| rl.reads_in_place()).map(|a| { + if layer.anonymous || rl.anonymous { + std::borrow::Cow::Owned(rustgis_tiles::s3::anonymous(a)) + } else { + std::borrow::Cow::Borrowed(a) + } + }); + let mut draw_it = |pm: &mut Pixmap, opacity: f32| match address.as_deref() { // Drawn from less than the view needs (a coarser level, tiles that couldn't be // read): shown, and said with the tile errors. Some(a) => match raster::draw_in_place(pm, a, data, &rl.style, stats, view, opacity, full_res_rasters, place, light) { diff --git a/crates/render/src/raster_export.rs b/crates/render/src/raster_export.rs index 32c586e2a2..80d9c2778d 100644 --- a/crates/render/src/raster_export.rs +++ b/crates/render/src/raster_export.rs @@ -91,7 +91,7 @@ pub fn export(layer: &RasterLayer, min_zoom: u8, max_zoom: u8, opacity: f32) -> let place = raster::Place::Flat(&Flat::Mercator, "EPSG:3857"); let stats = stats.as_deref().map(Vec::as_slice); let mut image = Pixmap::new(TILE_SIZE, TILE_SIZE).ok_or("couldn't allocate a raster tile")?; - match layer.path.as_deref().filter(|_| layer.reads_in_place()) { + match layer.fetch_address().filter(|_| layer.reads_in_place()) { // Read in place: at the tile's level, once its parts have arrived (natively; // the browser draws what has). Some(address) => { @@ -102,7 +102,7 @@ pub fn export(layer: &RasterLayer, min_zoom: u8, max_zoom: u8, opacity: f32) -> return Err(rustgis_data::DataError::Cancelled.to_string()); } let drawn_at = crate::rustgis_tiles::cache::generation(); - match raster::draw_in_place(&mut image, address, r, &layer.style, stats, &view, opacity, true, place, light) { + match raster::draw_in_place(&mut image, &address, r, &layer.style, stats, &view, opacity, true, place, light) { Ok(false) => break, Ok(true) => {} // Drawn from less than the tile needs: not written in its place. From 0bf20e024ca5c09dbb587eeedd77425675b659fe Mon Sep 17 00:00:00 2001 From: giswqs Date: Wed, 25 Nov 2026 12:11:36 -0500 Subject: [PATCH 07/20] Address Claude review feedback - Scrub active logins and S3 wrappers in project_log::kept_params before clipping so credentials spanning LOG_PARAMS_BYTES cannot leave a prefix behind. - Pass fetch_address() into remote::fetch_whole during whole-file RasterLayer::reload while keeping the wrapper/scheme check on the plain path. - Propagate parent Layer::anonymous into raster_export::export_with_anonymous and mirror Layer::anonymous onto RasterLayer::anonymous in service_logins, service, and zarr. - Bound plugin_fetch::web_addresses by total scanned values (1,000,000) and discovered web address strings (4,096) so large inline feature collections and ID lists pass while every string is still scanned. --- crates/engine/src/cmd/gp.rs | 2 +- crates/engine/src/cmd/plugin_fetch.rs | 86 +++++++++++++------ crates/engine/src/cmd/service.rs | 3 + crates/engine/src/cmd/zarr.rs | 6 ++ crates/engine/src/project_log.rs | 4 +- crates/engine/src/service_logins.rs | 3 + .../engine/src/tests/scopes_and_redaction.rs | 51 ++++++++++- crates/map/src/raster.rs | 15 +++- crates/render/src/raster_export.rs | 17 +++- 9 files changed, 151 insertions(+), 36 deletions(-) diff --git a/crates/engine/src/cmd/gp.rs b/crates/engine/src/cmd/gp.rs index 857c8a2894..78aedded01 100644 --- a/crates/engine/src/cmd/gp.rs +++ b/crates/engine/src/cmd/gp.rs @@ -2418,7 +2418,7 @@ impl Inputs for MapInputs<'_> { let layer = map.layer_by_name(layer).ok_or_else(|| format!("no raster layer named '{layer}'"))?; let raster = layer.raster.as_ref().ok_or_else(|| format!("no raster layer named '{}'", layer.name))?; let opacity = map.layer_opacity(layer); - crate::render::raster_export::export(raster, min_zoom, max_zoom, opacity) + crate::render::raster_export::export_with_anonymous(raster, layer.anonymous, min_zoom, max_zoom, opacity) } fn dataset(&self, layer: &str) -> Option<&Dataset> { // (A standalone table converted for the run is had by its number, [`table_key`].) diff --git a/crates/engine/src/cmd/plugin_fetch.rs b/crates/engine/src/cmd/plugin_fetch.rs index 79bdbf7612..bc3edd66a1 100644 --- a/crates/engine/src/cmd/plugin_fetch.rs +++ b/crates/engine/src/cmd/plugin_fetch.rs @@ -236,53 +236,68 @@ impl Session { } } -/// The most string, object, and non-primitive array nodes inspected when scanning a plugin -/// command's parameters for web addresses. -const MAX_ADDRESS_SCAN_NODES: usize = 4096; +/// The most web address strings accepted in one plugin command's parameters. +const MAX_ADDRESS_SCAN_ADDRESSES: usize = 4096; -/// The most total array elements scanned across nested arrays (including pure-primitive coordinate -/// lists) so hostile gigantic payloads still fail closed. +/// The most total JSON values scanned across nested arrays and objects when searching a plugin +/// command's parameters for web addresses so hostile gigantic payloads still fail closed. const MAX_ADDRESS_SCAN_ELEMENTS: usize = 1_000_000; /// The web addresses among a command's own parameters, not inside the contents of a file it -/// gives (`data`, `text`). Walks nested arrays and objects iteratively, skipping primitive leaves -/// and pure-primitive arrays (such as `[x, y]` coordinate pairs) from the -/// [`MAX_ADDRESS_SCAN_NODES`] count while bounding total scanned array elements at -/// [`MAX_ADDRESS_SCAN_ELEMENTS`]; overly complex parameters are refused rather than skipped. +/// gives (`data`, `text`). Walks nested arrays and objects iteratively, bounding total scanned +/// JSON values at [`MAX_ADDRESS_SCAN_ELEMENTS`] (1,000,000) and discovered web address strings at +/// [`MAX_ADDRESS_SCAN_ADDRESSES`] (4,096); payloads past either limit are refused rather than +/// skipped so large non-address inputs (inline geometries, feature collections, ID lists) pass +/// while every string inside them is still inspected. fn web_addresses(params: &Value) -> Result, String> { + web_addresses_within(params, MAX_ADDRESS_SCAN_ELEMENTS, MAX_ADDRESS_SCAN_ADDRESSES) +} + +fn web_addresses_within(params: &Value, max_elements: usize, max_addresses: usize) -> Result, String> { let Some(o) = params.as_object() else { return Ok(Vec::new()) }; let is_primitive = |v: &Value| matches!(v, Value::Number(_) | Value::Bool(_) | Value::Null); - let mut stack: Vec<&Value> = - o.iter().filter(|(key, v)| !matches!(key.as_str(), "data" | "text") && !is_primitive(v)).map(|(_, v)| v).collect(); - let mut out = Vec::new(); - let mut visited = 0usize; + let mut stack: Vec<&Value> = Vec::new(); let mut elements = 0usize; - while let Some(v) = stack.pop() { - if is_primitive(v) { + for (key, v) in o { + if matches!(key.as_str(), "data" | "text") { continue; } - if let Value::Array(a) = v { - elements = elements.saturating_add(a.len()); - if elements > MAX_ADDRESS_SCAN_ELEMENTS { - return Err("command parameters are too complex for a plugin network check".into()); - } - if a.iter().all(is_primitive) { - continue; - } + elements = elements.saturating_add(1); + if elements > max_elements { + return Err(format!("command parameters are too complex for a plugin network check (over {max_elements} values)")); } - visited += 1; - if visited > MAX_ADDRESS_SCAN_NODES { - return Err("command parameters are too complex for a plugin network check".into()); + if !is_primitive(v) { + stack.push(v); } + } + let mut out = Vec::new(); + while let Some(v) = stack.pop() { match v { Value::String(s) => { let s = s.trim(); if is_web_address(s) { + if out.len() >= max_addresses { + return Err(format!( + "command parameters are too complex for a plugin network check (over {max_addresses} web addresses)" + )); + } out.push(s); } } - Value::Array(a) => stack.extend(a.iter().filter(|x| !is_primitive(x))), - Value::Object(m) => stack.extend(m.values().filter(|x| !is_primitive(x))), + Value::Array(a) => { + elements = elements.saturating_add(a.len()); + if elements > max_elements { + return Err(format!("command parameters are too complex for a plugin network check (over {max_elements} values)")); + } + stack.extend(a.iter().filter(|x| !is_primitive(x))); + } + Value::Object(m) => { + elements = elements.saturating_add(m.len()); + if elements > max_elements { + return Err(format!("command parameters are too complex for a plugin network check (over {max_elements} values)")); + } + stack.extend(m.values().filter(|x| !is_primitive(x))); + } _ => {} } } @@ -1769,4 +1784,19 @@ mod tests { assert!(c.entries.iter().map(|e| e.size).sum::() <= CACHE_BYTES); assert!(c.get("https://cache.test/big39").is_some()); } + + #[test] + fn web_addresses_within_bounds_elements_and_addresses() { + let ok_params = json!({"ids": ["a", "b", "c"], "url": "https://example.org/a.png"}); + let ok = web_addresses_within(&ok_params, 10, 2).unwrap(); + assert_eq!(ok, vec!["https://example.org/a.png"]); + + let many_elements = json!({"ids": [1, 2, 3, 4, 5, 6]}); + let too_many_elements = web_addresses_within(&many_elements, 5, 10).unwrap_err(); + assert!(too_many_elements.contains("over 5 values"), "{too_many_elements}"); + + let many_urls = json!({"urls": ["https://a.example/1", "https://a.example/2", "https://a.example/3"]}); + let too_many_urls = web_addresses_within(&many_urls, 50, 2).unwrap_err(); + assert!(too_many_urls.contains("over 2 web addresses"), "{too_many_urls}"); + } } diff --git a/crates/engine/src/cmd/service.rs b/crates/engine/src/cmd/service.rs index 8471040f44..e2a2f9ab1c 100644 --- a/crates/engine/src/cmd/service.rs +++ b/crates/engine/src/cmd/service.rs @@ -559,6 +559,9 @@ pub(crate) fn mark_service_source(s: &mut Session, r: &Value, url: &str) { l.dataset.source = Some(url.to_string()); if anonymous { l.anonymous = true; + if let Some(rl) = l.raster.as_mut() { + rl.anonymous = true; + } l.connection.clear(); } } diff --git a/crates/engine/src/cmd/zarr.rs b/crates/engine/src/cmd/zarr.rs index c486491b06..deadbf0bb2 100644 --- a/crates/engine/src/cmd/zarr.rs +++ b/crates/engine/src/cmd/zarr.rs @@ -599,6 +599,9 @@ pub(crate) fn add(s: &mut Session, p: &Value) -> CmdResult { && let Some(l) = s.map_mut().layer_mut(id) { l.anonymous = true; + if let Some(rl) = l.raster.as_mut() { + rl.anonymous = true; + } } Ok(out) } @@ -1480,6 +1483,9 @@ fn add_following(s: &mut Session, p: &Value, asked: Option) -> CmdResult && let Some(l) = s.map_mut().layer_mut(id) { l.anonymous = true; + if let Some(rl) = l.raster.as_mut() { + rl.anonymous = true; + } } let said: Vec = window_notes.into_iter().chain(part).collect(); for w in &said { diff --git a/crates/engine/src/project_log.rs b/crates/engine/src/project_log.rs index 7c8745e8a3..c5a55d1975 100644 --- a/crates/engine/src/project_log.rs +++ b/crates/engine/src/project_log.rs @@ -75,7 +75,9 @@ pub(crate) fn is_logged(s: &Session, id: &str, params: &Value) -> bool { /// each giving up more: texts at that bound and lists at their first [`LOG_LIST_ITEMS`]; then /// texts at 512 characters; then the first keys with their short values only. pub(crate) fn kept_params(params: &Value) -> Value { - let v = redacted(&clip(params, LOG_PARAMS_BYTES, LOG_LIST_ITEMS, 0, true)); + // Scrub active logins and S3 wrappers before clipping so a secret spanning LOG_PARAMS_BYTES + // cannot leave a recognizable prefix behind. + let v = redacted(&clip(&scrub_log_value(params.clone(), 0), LOG_PARAMS_BYTES, LOG_LIST_ITEMS, 0, true)); if serde_json::to_vec(&v).map_or(0, |b| b.len()) <= LOG_PARAMS_BYTES { return v; } diff --git a/crates/engine/src/service_logins.rs b/crates/engine/src/service_logins.rs index 60cb49a223..90276bcc83 100644 --- a/crates/engine/src/service_logins.rs +++ b/crates/engine/src/service_logins.rs @@ -1318,6 +1318,9 @@ pub(crate) fn tag(s: &mut Session, params: &Value, before: Before, out: &Value) added.insert(l.id); if anonymous || l.anonymous { l.anonymous = true; + if let Some(rl) = l.raster.as_mut() { + rl.anonymous = true; + } l.connection.clear(); continue; } diff --git a/crates/engine/src/tests/scopes_and_redaction.rs b/crates/engine/src/tests/scopes_and_redaction.rs index 7dfc4f236f..454a7c9229 100644 --- a/crates/engine/src/tests/scopes_and_redaction.rs +++ b/crates/engine/src/tests/scopes_and_redaction.rs @@ -1000,6 +1000,24 @@ fn anonymous_reads_suppress_implicit_s3_and_sign_in_credentials() { } } + // 3c. Non-in-place anonymous S3 raster reload must pass rustgis-anonymous: to fetch_whole + // so s3::prepare never signs with an active S3 connection. + { + let captured: Arc>> = Arc::new(Mutex::new(Vec::new())); + let cap_cb = captured.clone(); + rustgis_data::source::remote::set_fetcher(move |url, _want, done| { + cap_cb.lock().unwrap_or_else(|e| e.into_inner()).push(url.to_string()); + done(Err(rustgis_data::source::remote::Failed::Other("captured".into()))); + }); + let mut rl = rustgis_map::raster::RasterLayer::unread_in_place("s3://priv-bkt-anon/whole-reload.tif").with_anonymous(true); + rl.in_place = false; + rl.reload().unwrap(); + let urls = captured.lock().unwrap_or_else(|e| e.into_inner()); + assert_eq!(urls.as_slice(), ["rustgis-anonymous:s3://priv-bkt-anon/whole-reload.tif"]); + let prep = crate::render::rustgis_tiles::s3::prepare(&urls[0]).unwrap(); + assert!(!prep.signed && prep.anonymous && prep.headers.is_empty(), "{prep:?}"); + } + // 4. request_params strips rustgis-s3: capability wrappers under anonymous mode. let wrapped = rustgis_data::s3_address::bind("0123456789abcdef", "https://s3.example.org", "s3://priv-bkt-anon/key.geojson").unwrap(); let p = json!({"url": wrapped}); @@ -1087,7 +1105,7 @@ fn plugin_address_hold_scans_nested_legend_urls_and_bounds_work() { forward(&mut s, "plug-net-nested", "map.setTiles", json!({"name": "Base", "legend": [{"url": public_legend}]})).unwrap(); assert_eq!(cache::ceiling_for(public_legend), Reach::Public); - // Large numeric and coordinate-pair arrays do not trip the node limit, while still scanning strings inside. + // Large numeric, coordinate-pair, and non-address object/ID arrays pass while still scanning strings inside. let mut coords: Vec = (0..5000).map(|i| json!([f64::from(i) * 0.01, f64::from(i) * -0.01])).collect(); forward( &mut s, @@ -1096,14 +1114,31 @@ fn plugin_address_hold_scans_nested_legend_urls_and_bounds_work() { json!({"name": "Base", "legend": [{"url": public_legend}], "extra": coords.clone()}), ) .unwrap(); + let mut features: Vec = (0..5000).map(|i| json!({"id": format!("feat-{i}"), "name": "parcel"})).collect(); + forward( + &mut s, + "plug-net-nested", + "map.setTiles", + json!({"name": "Base", "legend": [{"url": public_legend}], "features": features.clone()}), + ) + .unwrap(); coords.push(json!([0.0, "http://127.0.0.1:8080/hidden.png"])); let err = forward(&mut s, "plug-net-nested", "map.addTiles", json!({"url": "https://tiles.example.org/{z}/{x}/{y}.png", "extra": coords})) .unwrap_err(); assert!(err.contains("this computer or the local network"), "{err}"); + features.push(json!({"id": "hidden", "href": "http://127.0.0.1:8080/hidden-feat.png"})); + let err = forward( + &mut s, + "plug-net-nested", + "map.addTiles", + json!({"url": "https://tiles.example.org/{z}/{x}/{y}.png", "features": features}), + ) + .unwrap_err(); + assert!(err.contains("this computer or the local network"), "{err}"); - // Overly large nested string/container payloads fail closed rather than bypassing the scan. - let mut pad: Vec = (0..4100).map(|i| json!(format!("item-{i}"))).collect(); + // Exceeding the web-address cap fails closed rather than skipping remaining addresses. + let mut pad: Vec = (0..4100).map(|i| json!(format!("https://tiles.example.org/{i}.png"))).collect(); pad.push(json!("http://127.0.0.1:8080/hidden.png")); let err = forward(&mut s, "plug-net-nested", "map.addTiles", json!({"url": "https://tiles.example.org/{z}/{x}/{y}.png", "extra": pad})) .unwrap_err(); @@ -1198,6 +1233,16 @@ fn project_log_scrubs_active_logins_and_s3_wrappers() { assert!(!logged.contains("rustgis-s3:"), "log_params leaked s3 wrapper: {logged}"); assert!(!logged.contains(&s3_tok), "log_params leaked wrapped query token: {logged}"); + // An active login spanning LOG_PARAMS_BYTES (4096) in params must be scrubbed before clipping. + let param_pad = "p".repeat(crate::project_log::LOG_PARAMS_BYTES - 8); + let clipped_param = crate::log_params(&json!({ + "note": format!("{param_pad}{active_secret}tail"), + })) + .into_log_value() + .to_string(); + assert!(!clipped_param.contains(&active_secret), "clipped log_params leaked active login: {clipped_param}"); + assert!(!clipped_param.contains(&active_secret[..8]), "clipped log_params leaked active login prefix: {clipped_param}"); + // Deeply nested containers (depth >= 8) must omit contents so active logins (including ones // with quotes or backslashes that JSON escaping would alter) and S3 wrappers cannot survive. let quoted_secret = format!("pa\"ss\\word_{}", fixture_marker("deep_quoted")); diff --git a/crates/map/src/raster.rs b/crates/map/src/raster.rs index e1d6e72fbe..882c857fe7 100644 --- a/crates/map/src/raster.rs +++ b/crates/map/src/raster.rs @@ -676,6 +676,7 @@ impl RasterLayer { .next() .unwrap_or("raster.tif") .to_string(); + let fetch_path = self.fetch_address().unwrap_or(std::borrow::Cow::Borrowed(path)).into_owned(); let placement = self.placement; // A PDF's page, read again from the download. let page = self.subdataset.clone(); @@ -685,7 +686,7 @@ impl RasterLayer { self.data = None; self.opening = Some(slot); rustgis_data::source::remote::fetch_whole( - path, + &fetch_path, Box::new(move |result| { let result = remote::check_still(&still) .and(result.map_err(|e| match e { @@ -3616,4 +3617,16 @@ mod tests { let CastShadows::Unavailable(why) = rl.sky_view(true, (0, 1), || {}) else { panic!("said") }; assert!(why.contains("sky visibility") && why.contains("read in place"), "{why}"); } + + #[test] + fn anonymous_fetch_address_wraps_plain_and_is_idempotent() { + let plain = RasterLayer::unread_in_place("s3://bucket/scene.tif"); + assert_eq!(plain.fetch_address().as_deref(), Some("s3://bucket/scene.tif")); + + let anon = RasterLayer::unread_in_place("s3://bucket/scene.tif").with_anonymous(true); + assert_eq!(anon.fetch_address().as_deref(), Some("rustgis-anonymous:s3://bucket/scene.tif")); + + let already = RasterLayer::unread_in_place("rustgis-anonymous:s3://bucket/scene.tif").with_anonymous(true); + assert_eq!(already.fetch_address().as_deref(), Some("rustgis-anonymous:s3://bucket/scene.tif")); + } } diff --git a/crates/render/src/raster_export.rs b/crates/render/src/raster_export.rs index 80d9c2778d..e2e1303312 100644 --- a/crates/render/src/raster_export.rs +++ b/crates/render/src/raster_export.rs @@ -25,6 +25,12 @@ fn tile_range(start: f64, end: f64, n: u32) -> (u32, u32) { /// Raster pixels are rendered with the same style and resampling as the map. pub fn export(layer: &RasterLayer, min_zoom: u8, max_zoom: u8, opacity: f32) -> Result, String> { + export_with_anonymous(layer, layer.anonymous, min_zoom, max_zoom, opacity) +} + +/// [`export`], also honoring the parent [`rustgis_map::Layer::anonymous`] flag so in-place COG +/// reads match the map render path even when only the layer flag is set. +pub fn export_with_anonymous(layer: &RasterLayer, anonymous: bool, min_zoom: u8, max_zoom: u8, opacity: f32) -> Result, String> { if min_zoom > max_zoom || max_zoom > 16 { return Err("zoom range must satisfy 0 <= minZoom <= maxZoom <= 16".into()); } @@ -91,7 +97,14 @@ pub fn export(layer: &RasterLayer, min_zoom: u8, max_zoom: u8, opacity: f32) -> let place = raster::Place::Flat(&Flat::Mercator, "EPSG:3857"); let stats = stats.as_deref().map(Vec::as_slice); let mut image = Pixmap::new(TILE_SIZE, TILE_SIZE).ok_or("couldn't allocate a raster tile")?; - match layer.fetch_address().filter(|_| layer.reads_in_place()) { + let address = layer.path.as_deref().filter(|_| layer.reads_in_place()).map(|a| { + if anonymous || layer.anonymous { + std::borrow::Cow::Owned(crate::rustgis_tiles::s3::anonymous(a)) + } else { + std::borrow::Cow::Borrowed(a) + } + }); + match address.as_deref() { // Read in place: at the tile's level, once its parts have arrived (natively; // the browser draws what has). Some(address) => { @@ -102,7 +115,7 @@ pub fn export(layer: &RasterLayer, min_zoom: u8, max_zoom: u8, opacity: f32) -> return Err(rustgis_data::DataError::Cancelled.to_string()); } let drawn_at = crate::rustgis_tiles::cache::generation(); - match raster::draw_in_place(&mut image, &address, r, &layer.style, stats, &view, opacity, true, place, light) { + match raster::draw_in_place(&mut image, address, r, &layer.style, stats, &view, opacity, true, place, light) { Ok(false) => break, Ok(true) => {} // Drawn from less than the tile needs: not written in its place. From acf81bdb849cecd0d2f8789c2b2e53b967430285 Mon Sep 17 00:00:00 2001 From: giswqs Date: Sat, 28 Nov 2026 18:07:51 -0500 Subject: [PATCH 08/20] Read a GRIB record's rows anonymously when asked; wrap addresses once layer.addUrl with "bytes" and "bbox" computed the anonymous flag after add_url_rows returned, so the rows read signed with an implicit S3 connection or login. RowsAsked now carries the flag, and each range is fetched through service_logins::fetch_url. A request-header test covers the default, an anonymous session and an explicit "anonymous": true. Add s3::anonymous_once and use it at the STAC walker, dated search and render call sites so an already wrapped address isn't wrapped again. --- crates/engine/src/cmd/layer.rs | 11 ++++++-- crates/engine/src/service_logins.rs | 4 +-- .../engine/src/tests/scopes_and_redaction.rs | 28 +++++++++++++++++++ crates/render/src/lib.rs | 2 +- crates/render/src/raster_export.rs | 2 +- crates/tiles/src/s3.rs | 16 +++++++++++ crates/tiles/src/stac/catalog.rs | 2 +- crates/tiles/src/stac/dated.rs | 2 +- 8 files changed, 58 insertions(+), 9 deletions(-) diff --git a/crates/engine/src/cmd/layer.rs b/crates/engine/src/cmd/layer.rs index 68ff39cedd..bd714e38e8 100644 --- a/crates/engine/src/cmd/layer.rs +++ b/crates/engine/src/cmd/layer.rs @@ -5710,7 +5710,9 @@ fn rows_settled(s: &Session, p: &Value, url: &str, seen: Option<[f64; 4]>, publi let bbox = window_box(s, p, seen)?; let name = ps(p, "name").map(str::trim).filter(|n| !n.is_empty()).map(String::from); let public = public || cache::ceiling_for(url) == Reach::Public; - Ok(WindowAsked { url: url.to_string(), bbox, cell: None, name, bands: None, auto_cell: false, rows: Some(RowsAsked { range, public }) }) + let anonymous = s.web_logins.is_anonymous() || b(p, "anonymous") == Some(true); + let rows = Some(RowsAsked { range, public, anonymous }); + Ok(WindowAsked { url: url.to_string(), bbox, cell: None, name, bands: None, auto_cell: false, rows }) } /// Reads the rows of a box of a GRIB record ([`rows_settled`]): the record's first octets @@ -5736,11 +5738,12 @@ fn read_grib_rows_until(asked: &WindowAsked, rows: &RowsAsked, stop: &std::sync: return Err(named(cog::STOPPED.to_string())); } let ranged = ranged_address(url, (first, last)); + let fetch_ranged = crate::service_logins::fetch_url(rows.anonymous, &ranged); let len = usize::try_from(last - first + 1).unwrap_or(usize::MAX); let bytes = if rows.public { - cache::download_public_within(&ranged, len, cache::BLOCKING_TIMEOUT) + cache::download_public_within(&fetch_ranged, len, cache::BLOCKING_TIMEOUT) } else { - cache::download_blocking_within(&ranged, len, cache::BLOCKING_TIMEOUT) + cache::download_blocking_within(&fetch_ranged, len, cache::BLOCKING_TIMEOUT) }; // A transfer cut short by Cancel is said as stopped, whatever its own error. if bytes.is_err() && stop.load(std::sync::atomic::Ordering::Relaxed) { @@ -6519,6 +6522,8 @@ struct RowsAsked { range: (u64, u64), /// Whether its requests may reach only the internet (a plugin's). public: bool, + /// Whether its requests go without any saved login or implicit credentials. + anonymous: bool, } #[cfg(not(target_arch = "wasm32"))] diff --git a/crates/engine/src/service_logins.rs b/crates/engine/src/service_logins.rs index 7e3295e3c7..152ae2f07c 100644 --- a/crates/engine/src/service_logins.rs +++ b/crates/engine/src/service_logins.rs @@ -944,8 +944,8 @@ pub fn open_connection(s: &mut Session, c: &Connection) -> Result<(), String> { /// plain URL kept in layers or parameters. #[cfg_attr(target_arch = "wasm32", expect(dead_code, reason = "blocking fetches are desktop only"))] pub(crate) fn fetch_url(anonymous: bool, url: &str) -> String { - if anonymous && !crate::render::rustgis_tiles::s3::split_anonymous(url).1 { - crate::render::rustgis_tiles::s3::anonymous(url) + if anonymous { + crate::render::rustgis_tiles::s3::anonymous_once(url) } else { url.to_string() } diff --git a/crates/engine/src/tests/scopes_and_redaction.rs b/crates/engine/src/tests/scopes_and_redaction.rs index 454a7c9229..e28b0b1a07 100644 --- a/crates/engine/src/tests/scopes_and_redaction.rs +++ b/crates/engine/src/tests/scopes_and_redaction.rs @@ -1000,6 +1000,34 @@ fn anonymous_reads_suppress_implicit_s3_and_sign_in_credentials() { } } + // 3b2. The rows of a box of a GRIB record (`"bytes"` with `"bbox"`): signed by default, and not + // under an anonymous session or with an explicit `"anonymous": true`. + { + let grib = |anonymous: Option| { + let mut p = json!({"url": format!("{base}/priv-bkt-anon/rec.grib2"), "bytes": [0, 99], "bbox": [0.0, 0.0, 1.0, 1.0]}); + if let Some(a) = anonymous { + p["anonymous"] = json!(a); + } + p + }; + let _ = s.run("layer.addUrl", &grib(None)); + let signed = std::mem::take(&mut *seen.lock().unwrap_or_else(|e| e.into_inner())); + assert!(signed.iter().any(|r| r.contains("AKIA_SYNTH_ANON")), "a GRIB rows read should be signed by default: {signed:?}"); + crate::service_logins::anonymously(&mut s, true, |s| { + let _ = s.run("layer.addUrl", &grib(None)); + }) + .unwrap(); + let _ = s.run("layer.addUrl", &grib(Some(true))); + let grib_reqs = std::mem::take(&mut *seen.lock().unwrap_or_else(|e| e.into_inner())); + assert!(grib_reqs.len() >= 2, "both anonymous GRIB rows reads should issue a request: {grib_reqs:?}"); + for r in &grib_reqs { + assert!( + !r.contains("AKIA_SYNTH_ANON") && !r.to_ascii_lowercase().contains("authorization:"), + "an anonymous GRIB rows read signed with S3 credentials: {r}" + ); + } + } + // 3c. Non-in-place anonymous S3 raster reload must pass rustgis-anonymous: to fetch_whole // so s3::prepare never signs with an active S3 connection. { diff --git a/crates/render/src/lib.rs b/crates/render/src/lib.rs index 12748f2f99..9169dd9fa8 100644 --- a/crates/render/src/lib.rs +++ b/crates/render/src/lib.rs @@ -5338,7 +5338,7 @@ fn render_frame( // Read in place: the part in view, at the level the view needs. let address = rl.path.as_deref().filter(|_| rl.reads_in_place()).map(|a| { if layer.anonymous || rl.anonymous { - std::borrow::Cow::Owned(rustgis_tiles::s3::anonymous(a)) + std::borrow::Cow::Owned(rustgis_tiles::s3::anonymous_once(a)) } else { std::borrow::Cow::Borrowed(a) } diff --git a/crates/render/src/raster_export.rs b/crates/render/src/raster_export.rs index 898c028646..f36bb7ead6 100644 --- a/crates/render/src/raster_export.rs +++ b/crates/render/src/raster_export.rs @@ -99,7 +99,7 @@ pub fn export_with_anonymous(layer: &RasterLayer, anonymous: bool, min_zoom: u8, let mut image = Pixmap::new(TILE_SIZE, TILE_SIZE).ok_or("couldn't allocate a raster tile")?; let address = layer.path.as_deref().filter(|_| layer.reads_in_place()).map(|a| { if anonymous || layer.anonymous { - std::borrow::Cow::Owned(crate::rustgis_tiles::s3::anonymous(a)) + std::borrow::Cow::Owned(crate::rustgis_tiles::s3::anonymous_once(a)) } else { std::borrow::Cow::Borrowed(a) } diff --git a/crates/tiles/src/s3.rs b/crates/tiles/src/s3.rs index 04bff65431..b4e3ab6351 100644 --- a/crates/tiles/src/s3.rs +++ b/crates/tiles/src/s3.rs @@ -417,6 +417,12 @@ pub fn anonymous(url: &str) -> String { format!("{ANONYMOUS}{url}") } +/// `url` read anonymously, wrapped in [`ANONYMOUS`] once: an address already wrapped is kept as +/// it is. +pub fn anonymous_once(url: &str) -> String { + if split_anonymous(url).1 { url.to_string() } else { anonymous(url) } +} + /// Splits off [`ANONYMOUS`]: the address, and whether it is read anonymously. pub fn split_anonymous(url: &str) -> (&str, bool) { match url.strip_prefix(ANONYMOUS) { @@ -1134,6 +1140,16 @@ pub fn profile(credentials_ini: &str, config_ini: &str, name: &str) -> Profile { mod tests { use super::*; + /// An address is wrapped for an anonymous read once, however often it is asked. + #[test] + fn anonymous_once_wraps_once() { + let url = "https://bucket.example/a.tif"; + let once = anonymous_once(url); + assert_eq!(once, anonymous(url)); + assert_eq!(anonymous_once(&once), once); + assert_eq!(split_anonymous(&anonymous_once(&once)), (url, true)); + } + /// A public `s3://` address from a catalog: read anonymously at AWS's global endpoint, or at /// the region its refusal names (Digital Earth Africa's af-south-1); a bucket refusing anonymous /// reads is refused by name. diff --git a/crates/tiles/src/stac/catalog.rs b/crates/tiles/src/stac/catalog.rs index facfff9ce9..7e432d0ad7 100644 --- a/crates/tiles/src/stac/catalog.rs +++ b/crates/tiles/src/stac/catalog.rs @@ -558,7 +558,7 @@ pub fn walk_blocking_with(root: &str, filter: Filter, limit: usize, anonymous: b } let read = |u: String, public: bool| { let ceiling = if public { crate::address::Reach::Public } else { crate::address::Reach::Local }; - let fetch_u = if anonymous { crate::s3::anonymous(&u) } else { u.clone() }; + let fetch_u = if anonymous { crate::s3::anonymous_once(&u) } else { u.clone() }; let r = crate::cache::download_blocking_with_origin_within( &fetch_u, crate::cache::MAX_DOWNLOAD, diff --git a/crates/tiles/src/stac/dated.rs b/crates/tiles/src/stac/dated.rs index 4ea18d80b9..8b92b1f78f 100644 --- a/crates/tiles/src/stac/dated.rs +++ b/crates/tiles/src/stac/dated.rs @@ -324,7 +324,7 @@ pub fn search_blocking(root: &str, filter: &Filter, period: (&str, &str), max_it /// [`search_blocking`], suppressing implicit S3 and web-service credentials when `anonymous` is true. pub fn search_blocking_with(root: &str, filter: &Filter, period: (&str, &str), max_items: usize, anonymous: bool) -> Result { search(root, filter, period, max_items, &|u| { - let fetch_u = if anonymous { crate::s3::anonymous(u) } else { u.to_string() }; + let fetch_u = if anonymous { crate::s3::anonymous_once(u) } else { u.to_string() }; crate::cache::download_blocking(&fetch_u) }) } From 7b11f4a206457eff541b894ab67ee7b78a5bb658 Mon Sep 17 00:00:00 2001 From: giswqs Date: Sat, 28 Nov 2026 18:14:53 -0500 Subject: [PATCH 09/20] Format service_logins::fetch_url --- crates/engine/src/service_logins.rs | 6 +----- 1 file changed, 1 insertion(+), 5 deletions(-) diff --git a/crates/engine/src/service_logins.rs b/crates/engine/src/service_logins.rs index 152ae2f07c..455292851c 100644 --- a/crates/engine/src/service_logins.rs +++ b/crates/engine/src/service_logins.rs @@ -944,11 +944,7 @@ pub fn open_connection(s: &mut Session, c: &Connection) -> Result<(), String> { /// plain URL kept in layers or parameters. #[cfg_attr(target_arch = "wasm32", expect(dead_code, reason = "blocking fetches are desktop only"))] pub(crate) fn fetch_url(anonymous: bool, url: &str) -> String { - if anonymous { - crate::render::rustgis_tiles::s3::anonymous_once(url) - } else { - url.to_string() - } + if anonymous { crate::render::rustgis_tiles::s3::anonymous_once(url) } else { url.to_string() } } pub fn request_params<'a>(s: &mut Session, p: &'a Value) -> Result, String> { From e6b3f993d3d0dd003f854e4e5a472c9c0e2c296e Mon Sep 17 00:00:00 2001 From: giswqs Date: Sat, 28 Nov 2026 19:37:29 -0500 Subject: [PATCH 10/20] Read a queued COG window anonymously when asked window_settled now wraps the address with service_logins::fetch_url when the session is anonymous or the request says "anonymous": true, so a plugin's window the app reads off the frame (window_asked_in) is as anonymous as one read while the command runs. Names and messages keep the plain address. A request-header test covers both. Say in is_plugin_blocked_database_command's doc that a DuckDB or GeoPackage file added with layer.addData stays a file read under files. --- crates/engine/src/cmd/layer.rs | 25 +++++++++++-------- crates/engine/src/policy/decide.rs | 4 ++- .../engine/src/tests/scopes_and_redaction.rs | 21 ++++++++++++++++ 3 files changed, 39 insertions(+), 11 deletions(-) diff --git a/crates/engine/src/cmd/layer.rs b/crates/engine/src/cmd/layer.rs index bd714e38e8..cdb10f45df 100644 --- a/crates/engine/src/cmd/layer.rs +++ b/crates/engine/src/cmd/layer.rs @@ -6573,7 +6573,12 @@ fn window_settled(s: &Session, p: &Value, url: &str, seen: Option<[f64; 4]>) -> Some(v) => Some(v.as_f64().filter(|c| c.is_finite() && *c > 0.0).ok_or_else(|| named("cellSize is a size above 0".into()))?), }; let name = ps(p, "name").map(str::trim).filter(|n| !n.is_empty()).map(String::from); - Ok(WindowAsked { url: url.to_string(), bbox, cell, name, bands: None, auto_cell: false, rows: None }) + // Read without a saved login or implicit credentials when asked: here, so a window the app + // reads off the frame (a plugin's, queued with `"anonymous": true`) is as anonymous as one read + // while the command runs. + let anonymous = s.web_logins.is_anonymous() || b(p, "anonymous") == Some(true); + let url = crate::service_logins::fetch_url(anonymous, url); + Ok(WindowAsked { url, bbox, cell, name, bands: None, auto_cell: false, rows: None }) } /// A window the app reads off the frame: `p`, a `layer.addUrl` with `"bbox"` and its address bound @@ -6603,10 +6608,7 @@ pub fn window_asked_in(s: &Session, p: &Value, seen: Option<[f64; 4]>) -> Result /// `layer.addUrl` with `"bbox"`, for those that wait: read here and added. #[cfg(not(target_arch = "wasm32"))] fn add_cog_window(s: &mut Session, p: &Value, url: &str) -> CmdResult { - let mut asked = window_settled(s, p, url, None)?; - if s.web_logins.is_anonymous() || b(p, "anonymous") == Some(true) { - asked.url = crate::service_logins::fetch_url(true, &asked.url); - } + let asked = window_settled(s, p, url, None)?; let read = read_cog_window(&asked)?; add_window(s, p, read) } @@ -6641,13 +6643,15 @@ pub(crate) fn finer_than_file(cell: Option, fits: bool, auto: bool) -> Opti pub(crate) fn read_window_raster(asked: &WindowAsked, stop: &std::sync::atomic::AtomicBool) -> Result { use crate::render::rustgis_tiles::cog; use rustgis_data::raster::cog::Level; - let url = asked.url.as_str(); + // The address fetched (wrapped when read anonymously, [`window_settled`]) and the one said. + let fetch = asked.url.as_str(); + let url = crate::render::rustgis_tiles::s3::split_anonymous(fetch).0; let named = |e: String| crate::sources::message_with_address(url, &e); let [west, south, east, north] = asked.bbox; let cell = asked.cell; // The five minutes count from the header's read. let started = std::time::Instant::now(); - let info = cog::info_until(url, stop).map_err(named)?; + let info = cog::info_until(fetch, stop).map_err(named)?; let layout = &info.layout; let (pw, ph) = (layout.transform.pixel_width, layout.transform.pixel_height); if !(pw.is_finite() && ph.is_finite() && pw != 0.0 && ph != 0.0) { @@ -6817,7 +6821,7 @@ pub(crate) fn read_window_raster(asked: &WindowAsked, stop: &std::sync::atomic:: band_in_time(batch.first().copied().unwrap_or(0), count, started.elapsed(), WINDOW_WAIT).map_err(named)?; let wait = batch_wait(batch.len(), started.elapsed()); for (values, changed, past) in - cog::read_bands_counted_blocking(&info, url, level, batch, (c0, c1), (r0, r1), wait, stop).map_err(named)? + cog::read_bands_counted_blocking(&info, fetch, level, batch, (c0, c1), (r0, r1), wait, stop).map_err(named)? { bands.push(values); rounded.push(changed); @@ -6896,9 +6900,10 @@ pub fn read_cog_window_until(asked: &WindowAsked, stop: &std::sync::atomic::Atom if let Some(rows) = &asked.rows { return read_grib_rows_until(asked, rows, stop); } - let named = |e: String| crate::sources::message_with_address(&asked.url, &e); + let shown = crate::render::rustgis_tiles::s3::split_anonymous(&asked.url).0; + let named = |e: String| crate::sources::message_with_address(shown, &e); let WindowRaster { raster: r, read, finer, edges, columns, rows, level, cell_size } = read_window_raster(asked, stop)?; - let name = asked.name.clone().unwrap_or_else(|| cog_name(&asked.url)); + let name = asked.name.clone().unwrap_or_else(|| cog_name(shown)); // Kept in the project as a GeoTIFF of the window: a cloud-optimised one, which keeps a colour // table; one it can't write (a palette with no index left for no-data) is kept plain, and said so. // Neither writes more bands than colour (or grey and alpha) takes: the others are said. diff --git a/crates/engine/src/policy/decide.rs b/crates/engine/src/policy/decide.rs index c532ceb1e7..dca4214e2a 100644 --- a/crates/engine/src/policy/decide.rs +++ b/crates/engine/src/policy/decide.rs @@ -195,7 +195,9 @@ fn refusal(s: &Session, k: &Kind, n: &Node) -> String { /// Direct database and SQL commands are excluded from plugins even when a plugin holds `files` /// and `network` permissions: they can use the user's live PostGIS session, reach local database -/// hosts outside HTTP address checks, or run DuckDB SQL. +/// hosts outside HTTP address checks, or run DuckDB SQL. A DuckDB or GeoPackage file's tables +/// added with `layer.addData` stay a file read under `files`: that path runs no SQL the caller +/// writes, reaches no host and uses no saved session. fn is_plugin_blocked_database_command(id: &str) -> bool { matches!( id, diff --git a/crates/engine/src/tests/scopes_and_redaction.rs b/crates/engine/src/tests/scopes_and_redaction.rs index e28b0b1a07..4ec0198769 100644 --- a/crates/engine/src/tests/scopes_and_redaction.rs +++ b/crates/engine/src/tests/scopes_and_redaction.rs @@ -1028,6 +1028,27 @@ fn anonymous_reads_suppress_implicit_s3_and_sign_in_credentials() { } } + // 3b3. A cloud-optimised GeoTIFF's window the app reads off the frame (a plugin's command, + // queued with `"anonymous": true`): signed without the flag, not with it. + { + let window = |anonymous: bool| { + let p = json!({"url": format!("{base}/priv-bkt-anon/window-{anonymous}.tif"), "bbox": [0.0, 0.0, 1.0, 1.0], "anonymous": anonymous}); + let asked = crate::cmd::layer::window_asked(&s, &p).unwrap(); + let _ = crate::cmd::layer::read_cog_window(&asked); + std::mem::take(&mut *seen.lock().unwrap_or_else(|e| e.into_inner())) + }; + let signed = window(false); + assert!(signed.iter().any(|r| r.contains("AKIA_SYNTH_ANON")), "a window read should be signed by default: {signed:?}"); + let queued = window(true); + assert!(!queued.is_empty(), "the anonymous window read should issue a request"); + for r in &queued { + assert!( + !r.contains("AKIA_SYNTH_ANON") && !r.to_ascii_lowercase().contains("authorization:"), + "a queued anonymous window read signed with S3 credentials: {r}" + ); + } + } + // 3c. Non-in-place anonymous S3 raster reload must pass rustgis-anonymous: to fetch_whole // so s3::prepare never signs with an active S3 connection. { From f5263dc8e7f51a39d6f1f411286d6b75ceb8c0c8 Mon Sep 17 00:00:00 2001 From: giswqs Date: Sat, 28 Nov 2026 20:35:05 -0500 Subject: [PATCH 11/20] Keep local files unwrapped; read STAC bands and AlphaEarth anonymously - anonymous_once and RasterLayer::fetch_address leave a file on this computer as it is: the in-place readers don't see through the rustgis-anonymous: wrapper, and no login reaches a local file. - stac.addBands, stac.addIndex and the embeddings commands take the session's anonymity when they run and read their windows through service_logins::fetch_url, as window_settled does. - The project log scrubs a document found in text after the clip; only a document passed as a parameter itself is left whole for its size. --- crates/engine/src/cmd/embeddings.rs | 19 ++++++++++---- crates/engine/src/cmd/stac_bands.rs | 26 ++++++++++++++----- crates/engine/src/project_log.rs | 15 ++++++----- .../engine/src/tests/scopes_and_redaction.rs | 7 +++++ crates/map/src/raster.rs | 9 ++++++- crates/tiles/src/s3.rs | 17 ++++++++++-- 6 files changed, 72 insertions(+), 21 deletions(-) diff --git a/crates/engine/src/cmd/embeddings.rs b/crates/engine/src/cmd/embeddings.rs index 4dcf466b7d..e7f74c291e 100644 --- a/crates/engine/src/cmd/embeddings.rs +++ b/crates/engine/src/cmd/embeddings.rs @@ -820,6 +820,10 @@ pub(crate) fn similarity_work(s: &Session, p: &Value) -> Result Result = searched.into_iter().map(Note::plain).collect(); let file = files.first().ok_or("AlphaEarth has no file there")?; - let w = read_window(file, area, cell)?; + let w = read_window(file, area, cell, anonymous)?; notes.extend(w.notes()); let r = &w.raster; // A reference with no embedding fails with what its layer said. @@ -860,14 +864,18 @@ pub(crate) fn change_work(s: &Session, p: &Value) -> Result = searched.into_iter().map(Note::plain).collect(); let (Some(a), Some(b)) = (files.first(), files.get(1)) else { return Err("AlphaEarth has no files there".into()) }; - let a = read_window(a, area, cell)?; - let b = read_window(b, area, cell)?; + let a = read_window(a, area, cell, anonymous)?; + let b = read_window(b, area, cell, anonymous)?; notes.extend(two_years_notes(&a, &b, (from, to))); let band = change_band(&a.raster, &b.raster)?; let name = name.unwrap_or_else(|| format!("AlphaEarth change {from}–{to}")); @@ -997,9 +1005,10 @@ fn missed_points(missed: usize, of: usize) -> Option { /// this one looks at the run's Cancel and stops the read once it is set. A thread the system /// refuses costs only that: the read runs here, Cancel looked at once it is in. #[cfg(not(target_arch = "wasm32"))] -fn read_window(url: &str, area: [f64; 4], cell: Option) -> Result { +/// `anonymous`: read without any saved login or implicit credentials (a plugin's command). +fn read_window(url: &str, area: [f64; 4], cell: Option, anonymous: bool) -> Result { use std::sync::atomic::{AtomicBool, Ordering}; - let asked = super::layer::WindowAsked::of(url, area, cell, AEF_BANDS); + let asked = super::layer::WindowAsked::of(&crate::service_logins::fetch_url(anonymous, url), area, cell, AEF_BANDS); let stop = AtomicBool::new(false); // The reader carries the request context on (a plugin's command reaches only the internet). let still = crate::render::rustgis_tiles::cache::current_still(); diff --git a/crates/engine/src/cmd/stac_bands.rs b/crates/engine/src/cmd/stac_bands.rs index 97bce98d47..07bef59a4e 100644 --- a/crates/engine/src/cmd/stac_bands.rs +++ b/crates/engine/src/cmd/stac_bands.rs @@ -166,9 +166,12 @@ mod desktop { None => format!("{} {label}", item.id), }; let channels = [wanted[0].clone(), wanted[1].clone(), wanted[2].clone()]; + // Taken now: the files are read later, off the session, without its saved logins when + // it runs anonymously (a plugin's command). + let anonymous = s.web_logins.is_anonymous(); Ok(Box::new(move || { rustgis_data::progress::check().map_err(|e| e.to_string())?; - let (made, notes) = read_and_stack(&name, &channels, &picked, &hrefs, bbox, cell)?; + let (made, notes) = read_and_stack(&name, &channels, &picked, &hrefs, bbox, cell, anonymous)?; made_saying(made, notes, json!({"bands": channels, "bbox": bbox})) })) } @@ -207,9 +210,10 @@ mod desktop { None => format!("{} {}", item.id, ix.id.to_ascii_uppercase()), }; let id = ix.id; + let anonymous = s.web_logins.is_anonymous(); Ok(Box::new(move || { rustgis_data::progress::check().map_err(|e| e.to_string())?; - let (stacked, notes) = read_and_stack(&name, &wanted, &picked, &hrefs, bbox, cell)?; + let (stacked, notes) = read_and_stack(&name, &wanted, &picked, &hrefs, bbox, cell, anonymous)?; let band = rustgis_analysis::rasterops::band_math(&stacked, &expr)?; // An index with no value anywhere (every cell 0 / 0, say) is no result: an error, not an empty layer. if !rustgis_analysis::rasterops::has_values(&band, stacked.width as usize)? { @@ -304,7 +308,13 @@ mod desktop { /// index's two to three), each bounded by the window reader's own limit on values. An ordinary /// window (one band, about 4 million values) is far below it; files of many bands can take up to /// about that many times one window's peak, where reading them one at a time took one. - pub(super) fn read_windows(files: &[(String, usize)], bbox: [f64; 4], cell: (f64, bool)) -> Result, String> { + /// `anonymous`: the files are read without any saved login or implicit credentials. + pub(super) fn read_windows( + files: &[(String, usize)], + bbox: [f64; 4], + cell: (f64, bool), + anonymous: bool, + ) -> Result, String> { // The run's request predicate is of this thread: each reader thread is given it, as the shared // helpers give their workers, so a request whose claim has gone is not sent. let still = rustgis_data::source::remote::current_still(); @@ -317,7 +327,7 @@ mod desktop { let mut signed = Vec::with_capacity(files.len()); for (href, _) in files { rustgis_data::progress::check().map_err(|e| e.to_string())?; - let url = stac::sign_blocking(href)?; + let url = crate::service_logins::fetch_url(anonymous, &stac::sign_blocking(href)?); // The item is a document's: its files connect to public addresses only, whatever a public-looking // name resolves to. Marked (the address as given, and as signed) before any reader starts. crate::render::rustgis_tiles::cache::restrict_to_public(href); @@ -480,6 +490,7 @@ mod desktop { hrefs: &[String], bbox: [f64; 4], cell: (f64, bool), + anonymous: bool, ) -> Result<(Raster, Vec), String> { // One read for a file, whichever of its bands are wanted (the first to want it sets the count), and // every band of the file is read, so the count asked is the file's, not the band's place. @@ -493,7 +504,7 @@ mod desktop { files.push((href.clone(), band.in_file.max(band.index) as usize)); } } - let read = read_windows(&files, bbox, cell)?; + let read = read_windows(&files, bbox, cell, anonymous)?; // What each file's read said, merged into one notice for a kind (see [`merge_notes`]). let mut windows: Vec<(String, WindowRaster)> = Vec::new(); let mut said: Vec<(Vec, Vec)> = Vec::new(); @@ -967,7 +978,8 @@ mod tests { // A claim that has gone: the reads stop before any request is sent, on the reader threads too. let gone: rustgis_data::source::remote::Still = std::sync::Arc::new(|| false); let files = vec![("https://127.0.0.1:9/a.tif".to_string(), 1), ("https://127.0.0.1:9/b.tif".to_string(), 1)]; - let err = rustgis_data::source::remote::with_still(gone, || read_windows(&files, [10.0, 45.0, 10.1, 45.1], (10.0, false))).err(); + let err = + rustgis_data::source::remote::with_still(gone, || read_windows(&files, [10.0, 45.0, 10.1, 45.1], (10.0, false), false)).err(); assert!(err.is_some_and(|e| e.contains("cancelled before it was sent")), "the predicate reached the reads"); } @@ -1109,7 +1121,7 @@ mod tests { let url = "https://rustgis-public-only.example/b.tif"; assert_eq!(cache::ceiling_for(url), Reach::Local, "unmarked, a URL's ceiling is local"); let _ = rustgis_data::source::remote::with_still(gone, || { - read_windows(&[(url.to_string(), 1)], [10.0, 45.0, 10.1, 45.1], (10.0, false)) + read_windows(&[(url.to_string(), 1)], [10.0, 45.0, 10.1, 45.1], (10.0, false), false) }); assert_eq!(cache::ceiling_for(url), Reach::Public, "the read of it connects to public addresses only"); } diff --git a/crates/engine/src/project_log.rs b/crates/engine/src/project_log.rs index 6e445517fe..9e3b048d8c 100644 --- a/crates/engine/src/project_log.rs +++ b/crates/engine/src/project_log.rs @@ -77,7 +77,7 @@ pub(crate) fn is_logged(s: &Session, id: &str, params: &Value) -> bool { pub(crate) fn kept_params(params: &Value) -> Value { // Scrub active logins and S3 wrappers before clipping so a secret spanning LOG_PARAMS_BYTES // cannot leave a recognizable prefix behind. - let v = redacted(&clip(&scrub_log_value(params.clone(), 0), LOG_PARAMS_BYTES, LOG_LIST_ITEMS, 0, true)); + let v = redacted(&clip(&scrub_log_value(params.clone(), 0, true), LOG_PARAMS_BYTES, LOG_LIST_ITEMS, 0, true)); if serde_json::to_vec(&v).map_or(0, |b| b.len()) <= LOG_PARAMS_BYTES { return v; } @@ -200,7 +200,7 @@ fn review_value(v: &Value, depth: usize) -> Result { } fn redacted(v: &Value) -> Value { - scrub_log_value(crate::cmd::history::redacted(&embedded_redacted(v, 0)), 0) + scrub_log_value(crate::cmd::history::redacted(&embedded_redacted(v, 0)), 0, false) } /// Removes active login values and runtime capability wrappers from strings and object keys @@ -210,15 +210,18 @@ fn scrub_log_text(t: &str) -> String { crate::render::rustgis_tiles::logins::scrub(&crate::sources::scrub_s3_wrappers(t)) } -fn scrub_log_value(v: Value, depth: usize) -> Value { +/// `sized`: a document or a file's contents is left whole, as [`clip`] (which runs next) keeps +/// only its size, so the size said is the one passed; anywhere else (a document found in text +/// after the clip, [`redacted`]) it is scrubbed too. +fn scrub_log_value(v: Value, depth: usize, sized: bool) -> Value { match v { // A document or a file's contents is kept as its size only ([`clip`]): left whole here, so // the size given is the one passed, not that of the text scrubbed. - Value::String(t) if is_document(&t) || is_base64(&t) => Value::String(t), + Value::String(t) if sized && (is_document(&t) || is_base64(&t)) => Value::String(t), Value::String(t) => Value::String(scrub_log_text(&t)), - Value::Array(a) if depth < 8 => Value::Array(a.into_iter().map(|x| scrub_log_value(x, depth + 1)).collect()), + Value::Array(a) if depth < 8 => Value::Array(a.into_iter().map(|x| scrub_log_value(x, depth + 1, sized)).collect()), Value::Object(o) if depth < 8 => { - Value::Object(o.into_iter().map(|(k, x)| (scrub_log_text(&k), scrub_log_value(x, depth + 1))).collect()) + Value::Object(o.into_iter().map(|(k, x)| (scrub_log_text(&k), scrub_log_value(x, depth + 1, sized))).collect()) } Value::Array(_) | Value::Object(_) => Value::String("[omitted: nested too deeply]".into()), other => other, diff --git a/crates/engine/src/tests/scopes_and_redaction.rs b/crates/engine/src/tests/scopes_and_redaction.rs index 4ec0198769..62776a3f0d 100644 --- a/crates/engine/src/tests/scopes_and_redaction.rs +++ b/crates/engine/src/tests/scopes_and_redaction.rs @@ -1315,6 +1315,13 @@ fn project_log_scrubs_active_logins_and_s3_wrappers() { assert!(!deep_logged.contains(escaped_inner), "deep log_params leaked JSON-escaped quoted login: {deep_logged}"); assert!(!deep_logged.contains("rustgis-s3:"), "deep log_params leaked s3 wrapper: {deep_logged}"); assert!(!deep_logged.contains(&s3_tok), "deep log_params leaked wrapped token: {deep_logged}"); + // A document inside text (JSON in a note or script, read out after the clip) is scrubbed too: + // only a document passed as a parameter itself is left whole for its size. + let inner_doc = format!("{{\"pad\": \"{}\", \"key\": \"{quoted_secret}\"}}", "x".repeat(300)); + let outer = serde_json::to_string(&json!({"doc": inner_doc})).unwrap(); + let in_text = crate::log_params(&json!({"note": format!("ran {outer}")})).into_log_value().to_string(); + assert!(!in_text.contains("ed_secret), "a document in text leaked a login: {in_text}"); + assert!(!in_text.contains(escaped_inner), "a document in text leaked a JSON-escaped login: {in_text}"); let (kept_deep, partial) = crate::project_log::kept_and_partial(&deep); assert!(partial, "deeply nested omitted container must mark params partial: {kept_deep}"); diff --git a/crates/map/src/raster.rs b/crates/map/src/raster.rs index 87ef46f0ff..1f835432c8 100644 --- a/crates/map/src/raster.rs +++ b/crates/map/src/raster.rs @@ -524,7 +524,10 @@ impl RasterLayer { /// is set so lazy overview and tile reads do not sign with an active S3 or web-service login. pub fn fetch_address(&self) -> Option> { let path = self.path.as_deref()?; - if self.anonymous && !path.starts_with("rustgis-anonymous:") { + // A file on this computer is read as it is: no login reaches it, and its readers don't see + // through the wrapper. + let local = !path.contains("://") || path.get(..7).is_some_and(|h| h.eq_ignore_ascii_case("file://")); + if self.anonymous && !local && !path.starts_with("rustgis-anonymous:") { Some(std::borrow::Cow::Owned(format!("rustgis-anonymous:{path}"))) } else { Some(std::borrow::Cow::Borrowed(path)) @@ -3925,5 +3928,9 @@ mod tests { let already = RasterLayer::unread_in_place("rustgis-anonymous:s3://bucket/scene.tif").with_anonymous(true); assert_eq!(already.fetch_address().as_deref(), Some("rustgis-anonymous:s3://bucket/scene.tif")); + + // A file on this computer is read as it is: its in-place readers don't see through the wrapper. + let local = RasterLayer::unread_in_place("/data/big.tif").with_anonymous(true); + assert_eq!(local.fetch_address().as_deref(), Some("/data/big.tif")); } } diff --git a/crates/tiles/src/s3.rs b/crates/tiles/src/s3.rs index b4e3ab6351..6bc627dff2 100644 --- a/crates/tiles/src/s3.rs +++ b/crates/tiles/src/s3.rs @@ -418,9 +418,17 @@ pub fn anonymous(url: &str) -> String { } /// `url` read anonymously, wrapped in [`ANONYMOUS`] once: an address already wrapped is kept as -/// it is. +/// it is, and so is a file on this computer, which no login reaches and whose readers don't see +/// through the wrapper. pub fn anonymous_once(url: &str) -> String { - if split_anonymous(url).1 { url.to_string() } else { anonymous(url) } + if split_anonymous(url).1 || is_local_path(url) { url.to_string() } else { anonymous(url) } +} + +/// Whether `url` names a file on this computer: no scheme (`https://`, `s3://`, or a wrapper +/// holding one), or `file://`. +pub fn is_local_path(url: &str) -> bool { + let u = url.trim_start(); + !u.contains("://") || u.get(..7).is_some_and(|h| h.eq_ignore_ascii_case("file://")) } /// Splits off [`ANONYMOUS`]: the address, and whether it is read anonymously. @@ -1148,6 +1156,11 @@ mod tests { assert_eq!(once, anonymous(url)); assert_eq!(anonymous_once(&once), once); assert_eq!(split_anonymous(&anonymous_once(&once)), (url, true)); + // A file on this computer is read as it is. + for local in ["/data/big.tif", "C:\\data\\big.tif", "relative/big.tif", "file:///data/big.tif"] { + assert_eq!(anonymous_once(local), local); + } + assert_eq!(anonymous_once("s3://b/k.tif"), anonymous("s3://b/k.tif")); } /// A public `s3://` address from a catalog: read anonymously at AWS's global endpoint, or at From 40f2419f94fd22b101facbc5bab7d173cf2f6144 Mon Sep 17 00:00:00 2001 From: giswqs Date: Sat, 28 Nov 2026 21:31:33 -0500 Subject: [PATCH 12/20] Scrub log parameters only as far as they are kept; say coinciding keys kept_params no longer clones the parameters and scrubs every text in full before the clip. The pre-clip pass gives a document, a file's contents and a response as their sizes from the text passed, scrubs a text only to the clip's bound plus a margin longer than any secret, and stands a list's items past the first hundred as nulls to keep its count. clip loses its answers flag, which that pass now covers. An object two of whose field names come out alike once logins are taken out is replaced by a marker, in the project log and in the assistant's audit log, instead of one value overwriting the other. --- crates/assistant/src/audit.rs | 39 +++++---- crates/engine/src/project_log.rs | 83 ++++++++++++------- .../engine/src/tests/scopes_and_redaction.rs | 6 ++ 3 files changed, 85 insertions(+), 43 deletions(-) diff --git a/crates/assistant/src/audit.rs b/crates/assistant/src/audit.rs index 57aec1792f..873170d5ba 100644 --- a/crates/assistant/src/audit.rs +++ b/crates/assistant/src/audit.rs @@ -278,20 +278,26 @@ fn redact(v: Value, depth: usize) -> Value { match v { Value::String(s) => Value::String(redact_bounded(&s)), Value::Array(a) if depth < 16 => Value::Array(a.into_iter().map(|x| redact(x, depth + 1)).collect()), - Value::Object(o) if depth < 16 => Value::Object( - o.into_iter() - .map(|(k, x)| { - let sensitive = rustgis_engine::data::address::log_sensitive(&k); - let is_script = k.as_str() == "script"; - let safe_k = redact_bounded(&k); - match (sensitive, is_script, x) { - (true, _, _) => (safe_k, json!("[redacted]")), - (false, true, Value::String(s)) => (safe_k, json!(redact_script(&s))), - (false, _, x) => (safe_k, redact(x, depth + 1)), - } - }) - .collect(), - ), + Value::Object(o) if depth < 16 => { + // Two field names alike once redacted: the object is replaced by a marker as a whole, + // rather than one value silently overwriting the other. + let mut out = serde_json::Map::new(); + for (k, x) in o { + let sensitive = rustgis_engine::data::address::log_sensitive(&k); + let is_script = k.as_str() == "script"; + let safe_k = redact_bounded(&k); + let value = match (sensitive, is_script, x) { + (true, _, _) => json!("[redacted]"), + (false, true, Value::String(s)) => json!(redact_script(&s)), + (false, _, x) => redact(x, depth + 1), + }; + if out.contains_key(&safe_k) { + return json!("[redacted field names coincide]"); + } + out.insert(safe_k, value); + } + Value::Object(out) + } Value::Array(_) | Value::Object(_) => json!("[too deep]"), other => other, } @@ -549,6 +555,11 @@ mod tests { let scrubbed_s3 = redact_string(&format!("could not read {wrapped}")); assert!(!scrubbed_s3.contains("rustgis-s3:") && !scrubbed_s3.contains("RGSYNTH_s3_tok_9921"), "{scrubbed_s3}"); + // Two field names alike once the login is taken out: a marker, not one value dropped. + let placeholder = redact_string(active_secret); + let alike = json!({format!("k-{active_secret}"): 1, format!("k-{placeholder}"): 2}); + assert_eq!(redact(alike, 0), json!("[redacted field names coincide]")); + let call = json!({"jsonrpc": "2.0", "id": 1, "method": "tools/call", "params": {"name": "list_layers", "arguments": {}}}); let err = json!({ "jsonrpc": "2.0", diff --git a/crates/engine/src/project_log.rs b/crates/engine/src/project_log.rs index 9e3b048d8c..135a54cfa7 100644 --- a/crates/engine/src/project_log.rs +++ b/crates/engine/src/project_log.rs @@ -77,13 +77,13 @@ pub(crate) fn is_logged(s: &Session, id: &str, params: &Value) -> bool { pub(crate) fn kept_params(params: &Value) -> Value { // Scrub active logins and S3 wrappers before clipping so a secret spanning LOG_PARAMS_BYTES // cannot leave a recognizable prefix behind. - let v = redacted(&clip(&scrub_log_value(params.clone(), 0, true), LOG_PARAMS_BYTES, LOG_LIST_ITEMS, 0, true)); + let v = redacted(&clip(&scrub_log_value(params, 0, true), LOG_PARAMS_BYTES, LOG_LIST_ITEMS, 0)); if serde_json::to_vec(&v).map_or(0, |b| b.len()) <= LOG_PARAMS_BYTES { return v; } // Texts shorter; lists as they are (already cut, their "… N items in all" kept); responses // already given as their sizes. - let clipped = clip(&v, 512, usize::MAX, 0, false); + let clipped = clip(&v, 512, usize::MAX, 0); if serde_json::to_vec(&clipped).map_or(0, |b| b.len()) <= LOG_PARAMS_BYTES { return clipped; } @@ -200,7 +200,7 @@ fn review_value(v: &Value, depth: usize) -> Result { } fn redacted(v: &Value) -> Value { - scrub_log_value(crate::cmd::history::redacted(&embedded_redacted(v, 0)), 0, false) + scrub_log_value(&crate::cmd::history::redacted(&embedded_redacted(v, 0)), 0, false) } /// Removes active login values and runtime capability wrappers from strings and object keys @@ -210,21 +210,55 @@ fn scrub_log_text(t: &str) -> String { crate::render::rustgis_tiles::logins::scrub(&crate::sources::scrub_s3_wrappers(t)) } -/// `sized`: a document or a file's contents is left whole, as [`clip`] (which runs next) keeps -/// only its size, so the size said is the one passed; anywhere else (a document found in text -/// after the clip, [`redacted`]) it is scrubbed too. -fn scrub_log_value(v: Value, depth: usize, sized: bool) -> Value { +/// Room past a bound that a text is cut to before it is scrubbed: far longer than any secret, so +/// one that crosses the bound is still whole when it is taken out. +const SCRUB_MARGIN: usize = 256; + +/// `v` with active logins and runtime capability wrappers taken out of its texts and field names +/// ([`scrub_log_text`]). An object two of whose field names come out alike is replaced as a +/// whole by a marker, so no parameter is dropped without a word. +/// +/// `sized`, before [`clip`]: what it would keep as a size (a document, a file's contents, a +/// response) is given as that size here, from the text passed; a text is scrubbed only as far as +/// clip keeps it, plus [`SCRUB_MARGIN`]; and a list's items past [`LOG_LIST_ITEMS`] stand as +/// nulls, which keeps its count. So a large parameter is neither copied nor scanned whole. +/// Otherwise (after the clip, and for JSON read out of text, [`redacted`]) every text is scrubbed. +fn scrub_log_value(v: &Value, depth: usize, sized: bool) -> Value { match v { - // A document or a file's contents is kept as its size only ([`clip`]): left whole here, so - // the size given is the one passed, not that of the text scrubbed. - Value::String(t) if sized && (is_document(&t) || is_base64(&t)) => Value::String(t), - Value::String(t) => Value::String(scrub_log_text(&t)), - Value::Array(a) if depth < 8 => Value::Array(a.into_iter().map(|x| scrub_log_value(x, depth + 1, sized)).collect()), + Value::String(t) if sized && is_document(t) => Value::String(format!("(a document of {} characters)", t.chars().count())), + Value::String(t) if sized && is_base64(t) => Value::String(format!("(file contents of {} characters, base64)", t.len())), + Value::String(t) if sized && t.chars().nth(LOG_PARAMS_BYTES + SCRUB_MARGIN).is_some() => { + Value::String(scrub_log_text(&t.chars().take(LOG_PARAMS_BYTES + SCRUB_MARGIN).collect::())) + } + Value::String(t) => Value::String(scrub_log_text(t)), + Value::Array(a) if depth < 8 => Value::Array( + a.iter() + .enumerate() + .map(|(i, x)| if sized && i >= LOG_LIST_ITEMS { Value::Null } else { scrub_log_value(x, depth + 1, sized) }) + .collect(), + ), Value::Object(o) if depth < 8 => { - Value::Object(o.into_iter().map(|(k, x)| (scrub_log_text(&k), scrub_log_value(x, depth + 1, sized))).collect()) + let mut out = serde_json::Map::new(); + for (k, x) in o { + // A field name clip cuts (past 200 characters) is scrubbed as far as it keeps it. + let k = if sized && k.chars().nth(200 + SCRUB_MARGIN).is_some() { + scrub_log_text(&k.chars().take(200 + SCRUB_MARGIN).collect::()) + } else { + scrub_log_text(k) + }; + let x = match x.as_str() { + Some(text) if sized && k == "answer" => Value::String(format!("(a response of {} characters)", text.chars().count())), + _ => scrub_log_value(x, depth + 1, sized), + }; + if out.contains_key(&k) { + return Value::String("[omitted: field names alike once logins were taken out]".into()); + } + out.insert(k, x); + } + Value::Object(out) } Value::Array(_) | Value::Object(_) => Value::String("[omitted: nested too deeply]".into()), - other => other, + other => other.clone(), } } @@ -504,16 +538,16 @@ fn is_document(t: &str) -> bool { } /// `v` with each text cut to `chars` characters (a key to 200), a text that reads as a document -/// (JSON or XML past [`DOCUMENT_CHARS`]) or as a file's contents in base64 given as its size, a -/// response (`answer`) given as its size when `answers`, and each list cut to its first `items` -/// (and how many there were); nesting past eight levels is left out. -fn clip(v: &Value, chars: usize, items: usize, depth: usize, answers: bool) -> Value { +/// (JSON or XML past [`DOCUMENT_CHARS`]) or as a file's contents in base64 given as its size, and +/// each list cut to its first `items` (and how many there were); nesting past eight levels is left +/// out. A response (`answer`) is given as its size before this, by [`scrub_log_value`]. +fn clip(v: &Value, chars: usize, items: usize, depth: usize) -> Value { match v { Value::String(t) if is_document(t) => Value::String(format!("(a document of {} characters)", t.chars().count())), Value::String(t) if is_base64(t) => Value::String(format!("(file contents of {} characters, base64)", t.len())), Value::String(t) if t.chars().nth(chars).is_some() => Value::String(format!("{}…", t.chars().take(chars).collect::())), Value::Array(a) if depth < 8 => { - let mut out: Vec = a.iter().take(items).map(|x| clip(x, chars, items, depth + 1, answers)).collect(); + let mut out: Vec = a.iter().take(items).map(|x| clip(x, chars, items, depth + 1)).collect(); if a.len() > items { out.push(Value::String(format!("… {} items in all", a.len()))); } @@ -526,16 +560,7 @@ fn clip(v: &Value, chars: usize, items: usize, depth: usize, answers: bool) -> V let mut out = serde_json::Map::new(); for (k, x) in o { let value = || { - if k.chars().nth(200).is_some() { - Value::String("…".into()) - } else if answers - && k == "answer" - && let Some(text) = x.as_str() - { - Value::String(format!("(a response of {} characters)", text.chars().count())) - } else { - clip(x, chars, items, depth + 1, answers) - } + if k.chars().nth(200).is_some() { Value::String("…".into()) } else { clip(x, chars, items, depth + 1) } }; out.entry(k.chars().take(200).collect::()).or_insert_with(value); } diff --git a/crates/engine/src/tests/scopes_and_redaction.rs b/crates/engine/src/tests/scopes_and_redaction.rs index 62776a3f0d..1b11c6ea3f 100644 --- a/crates/engine/src/tests/scopes_and_redaction.rs +++ b/crates/engine/src/tests/scopes_and_redaction.rs @@ -1315,6 +1315,12 @@ fn project_log_scrubs_active_logins_and_s3_wrappers() { assert!(!deep_logged.contains(escaped_inner), "deep log_params leaked JSON-escaped quoted login: {deep_logged}"); assert!(!deep_logged.contains("rustgis-s3:"), "deep log_params leaked s3 wrapper: {deep_logged}"); assert!(!deep_logged.contains(&s3_tok), "deep log_params leaked wrapped token: {deep_logged}"); + // Two field names alike once the login is taken out: a marker, not one parameter dropped. + let placeholder = crate::render::rustgis_tiles::logins::scrub(&active_secret); + let alike = + crate::log_params(&json!({"opts": {format!("k-{active_secret}"): 1, format!("k-{placeholder}"): 2}})).into_log_value().to_string(); + assert!(alike.contains("field names alike"), "colliding scrubbed keys must be said: {alike}"); + // A document inside text (JSON in a note or script, read out after the clip) is scrubbed too: // only a document passed as a parameter itself is left whole for its size. let inner_doc = format!("{{\"pad\": \"{}\", \"key\": \"{quoted_secret}\"}}", "x".repeat(300)); From a020e497b62d3d5a6138e3a015498abc8b9d8aea Mon Sep 17 00:00:00 2001 From: giswqs Date: Sun, 29 Nov 2026 16:24:39 -0500 Subject: [PATCH 13/20] Keep a long login whole when a log parameter is cut before scrubbing A text or field name past the log's bound was cut to the bound plus a fixed 256 characters before active logins were taken out, so a bearer token or API key longer than that (up to 4,096 bytes) crossing the cut was only partly matched and its head could reach the log. The margin is now at least the longest active redaction (logins::longest_redaction). --- crates/engine/src/project_log.rs | 16 ++++++--- .../engine/src/tests/scopes_and_redaction.rs | 35 +++++++++++++++++++ crates/tiles/src/logins.rs | 7 ++++ 3 files changed, 54 insertions(+), 4 deletions(-) diff --git a/crates/engine/src/project_log.rs b/crates/engine/src/project_log.rs index 135a54cfa7..ec6897bbf9 100644 --- a/crates/engine/src/project_log.rs +++ b/crates/engine/src/project_log.rs @@ -210,10 +210,17 @@ fn scrub_log_text(t: &str) -> String { crate::render::rustgis_tiles::logins::scrub(&crate::sources::scrub_s3_wrappers(t)) } -/// Room past a bound that a text is cut to before it is scrubbed: far longer than any secret, so -/// one that crosses the bound is still whole when it is taken out. +/// The least room past a bound that a text is cut to before it is scrubbed, enough for a +/// capability wrapper's head; [`scrub_margin`] widens it to the longest active login. const SCRUB_MARGIN: usize = 256; +/// Room past a bound that a text is cut to before it is scrubbed: at least as long as every +/// active login (a bearer token or API key has no length cap), so one that crosses the bound is +/// still whole when it is taken out. +fn scrub_margin() -> usize { + SCRUB_MARGIN.max(crate::render::rustgis_tiles::logins::longest_redaction()) +} + /// `v` with active logins and runtime capability wrappers taken out of its texts and field names /// ([`scrub_log_text`]). An object two of whose field names come out alike is replaced as a /// whole by a marker, so no parameter is dropped without a word. @@ -228,7 +235,8 @@ fn scrub_log_value(v: &Value, depth: usize, sized: bool) -> Value { Value::String(t) if sized && is_document(t) => Value::String(format!("(a document of {} characters)", t.chars().count())), Value::String(t) if sized && is_base64(t) => Value::String(format!("(file contents of {} characters, base64)", t.len())), Value::String(t) if sized && t.chars().nth(LOG_PARAMS_BYTES + SCRUB_MARGIN).is_some() => { - Value::String(scrub_log_text(&t.chars().take(LOG_PARAMS_BYTES + SCRUB_MARGIN).collect::())) + let keep = LOG_PARAMS_BYTES.saturating_add(scrub_margin()); + Value::String(scrub_log_text(&t.chars().take(keep).collect::())) } Value::String(t) => Value::String(scrub_log_text(t)), Value::Array(a) if depth < 8 => Value::Array( @@ -242,7 +250,7 @@ fn scrub_log_value(v: &Value, depth: usize, sized: bool) -> Value { for (k, x) in o { // A field name clip cuts (past 200 characters) is scrubbed as far as it keeps it. let k = if sized && k.chars().nth(200 + SCRUB_MARGIN).is_some() { - scrub_log_text(&k.chars().take(200 + SCRUB_MARGIN).collect::()) + scrub_log_text(&k.chars().take(200usize.saturating_add(scrub_margin())).collect::()) } else { scrub_log_text(k) }; diff --git a/crates/engine/src/tests/scopes_and_redaction.rs b/crates/engine/src/tests/scopes_and_redaction.rs index 1b11c6ea3f..3b81405157 100644 --- a/crates/engine/src/tests/scopes_and_redaction.rs +++ b/crates/engine/src/tests/scopes_and_redaction.rs @@ -1354,6 +1354,41 @@ fn project_log_scrubs_active_logins_and_s3_wrappers() { assert!(!clipped_err.contains(&active_secret[..8]), "clipped error leaked active login prefix: {clipped_err}"); } +/// A login far longer than the fixed margin a parameter is cut to before it is scrubbed (a +/// bearer token or API key has no length cap) is still taken out whole where it crosses the bound +/// the log keeps, in a text and in a field name. +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn project_log_scrubs_a_long_login_across_the_clip() { + if isolate_process_test("tests::scopes_and_redaction::project_log_scrubs_a_long_login_across_the_clip") { + return; + } + let mut s = Session::new(Project::default()); + s.database_logins.set_store(None); + let conn = s + .run( + "connection.new", + &json!({"kind": "wms", "address": "https://long-login.example.org/wms", "auth": "header", "keyName": "X-Key"}), + ) + .unwrap(); + // 4,000 characters (an API key may be up to 4,096 bytes). + let long_secret: String = (0..4000).map(|i| char::from(b'A' + u8::try_from(i % 26).unwrap_or(0))).collect(); + s.run("connection.login", &json!({"id": conn["id"], "apiKey": long_secret})).unwrap(); + + // Starts at character 400, inside the 512 characters a long text keeps, and ends past + // 4,096 + 256, where a text was cut before it was scrubbed. + let pad = "word ".repeat(80); + let logged = crate::log_params(&json!({"note": format!("{pad}{long_secret}tail")})).into_log_value().to_string(); + assert!(logged.contains("word word"), "the text was not kept: {logged}"); + assert!(!logged.contains(&long_secret[..32]), "a long login crossing the clip reached the log: {logged}"); + + // A field name, cut at 200 characters, the same way. + let key = format!("{}{}", "k".repeat(150), &long_secret[..1000]); + s.run("connection.login", &json!({"id": conn["id"], "apiKey": &long_secret[..1000]})).unwrap(); + let logged = crate::log_params(&json!({ key: 1 })).into_log_value().to_string(); + assert!(!logged.contains(&long_secret[..32]), "a long login crossing a field name's cut reached the log: {logged}"); +} + #[cfg(not(target_arch = "wasm32"))] #[test] fn earthdata_status_guards_keychain_restore_by_scope_and_opt_in() { diff --git a/crates/tiles/src/logins.rs b/crates/tiles/src/logins.rs index da91e9e9eb..901547b286 100644 --- a/crates/tiles/src/logins.rs +++ b/crates/tiles/src/logins.rs @@ -498,6 +498,13 @@ pub fn scrub(text: &str) -> String { scrub_patterns(text, &patterns) } +/// The length in bytes of the longest pattern [`scrub`] takes out now (0 with no active login). +/// A caller that cuts a text before scrubbing it keeps at least this much past its bound, so a +/// credential that crosses the bound is still whole when it is matched. +pub fn longest_redaction() -> usize { + entries().values().flat_map(|entry| &entry.redactions).map(|pattern| pattern.value.expose().len()).max().unwrap_or(0) +} + /// Cleans generated error text before active values can obscure its address syntax. /// Runtime request bindings and successful data values must not use this output projection. pub fn scrub_error(text: &str) -> String { From d6c1d2863a658cb4f46c860b4d7f374abca14108 Mon Sep 17 00:00:00 2001 From: giswqs Date: Sun, 29 Nov 2026 16:54:05 -0500 Subject: [PATCH 14/20] Mirror a layer's anonymous flag onto its raster before a reopen reads it The raster's flag isn't saved, and on opening a project it was copied from the layer only in read_in_place, after rasters read whole had already been reloaded with their plain address. Copy it before that reload, and before a peer's raster is reloaded too. --- crates/engine/src/peer.rs | 4 +++ crates/engine/src/project.rs | 5 ++++ .../engine/src/tests/scopes_and_redaction.rs | 30 +++++++++++++++++++ 3 files changed, 39 insertions(+) diff --git a/crates/engine/src/peer.rs b/crates/engine/src/peer.rs index 951f4439f0..e08402696b 100644 --- a/crates/engine/src/peer.rs +++ b/crates/engine/src/peer.rs @@ -382,6 +382,10 @@ fn reopen(p: &mut Project, at: &At) { } } rustgis_map::LayerRole::Raster => { + let anonymous = layer.anonymous; + if let Some(raster) = &mut layer.raster { + raster.anonymous |= anonymous; + } if let Some(raster) = &mut layer.raster && let Err(e) = raster.reload() { diff --git a/crates/engine/src/project.rs b/crates/engine/src/project.rs index 8ac3acf2bb..00b06a4505 100644 --- a/crates/engine/src/project.rs +++ b/crates/engine/src/project.rs @@ -1806,6 +1806,11 @@ impl Project { src.error = Some(error); } } + // The raster reads as its layer does: the flag isn't saved with the raster, so it + // is mirrored before any read below, not only for those read in place. + if let Some(rl) = &mut l.raster { + rl.anonymous |= l.anonymous; + } // Read in place, read together below. if let Some(rl) = &mut l.raster && rl.data.is_none() diff --git a/crates/engine/src/tests/scopes_and_redaction.rs b/crates/engine/src/tests/scopes_and_redaction.rs index 3b81405157..ba311a60a3 100644 --- a/crates/engine/src/tests/scopes_and_redaction.rs +++ b/crates/engine/src/tests/scopes_and_redaction.rs @@ -1354,6 +1354,36 @@ fn project_log_scrubs_active_logins_and_s3_wrappers() { assert!(!clipped_err.contains(&active_secret[..8]), "clipped error leaked active login prefix: {clipped_err}"); } +/// A project's anonymous raster layer read whole again as the project is checked (not read in +/// place) is fetched anonymously: the layer's flag reaches its raster before the read, as the +/// raster doesn't save it. +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn project_repair_reloads_an_anonymous_raster_anonymously() { + if isolate_process_test("tests::scopes_and_redaction::project_repair_reloads_an_anonymous_raster_anonymously") { + return; + } + use std::sync::Mutex; + let captured: Arc>> = Arc::new(Mutex::new(Vec::new())); + let cap_cb = captured.clone(); + rustgis_data::source::remote::set_fetcher(move |url, _want, done| { + cap_cb.lock().unwrap_or_else(|e| e.into_inner()).push(url.to_string()); + done(Err(rustgis_data::source::remote::Failed::Other("captured".into()))); + }); + let address = + rustgis_data::login_address::bind("0123456789abcdef", "https://repair.example.org", "https://repair.example.org/dem.tif").unwrap(); + let mut rl = rustgis_map::raster::RasterLayer::unread_in_place(address.clone()); + rl.in_place = false; + assert!(!rl.anonymous); + let mut layer = rustgis_map::Layer::new_raster(1, "DEM", rl); + layer.anonymous = true; + let mut p = Project::default(); + p.maps[0].layers.push(layer); + let _ = p.normalize_after("while testing"); + let urls = captured.lock().unwrap_or_else(|e| e.into_inner()).clone(); + assert_eq!(urls, [format!("rustgis-anonymous:{address}")], "the reload was not anonymous"); +} + /// A login far longer than the fixed margin a parameter is cut to before it is scrubbed (a /// bearer token or API key has no length cap) is still taken out whole where it crosses the bound /// the log keeps, in a text and in a field name. From 80e21a0b5cc6ff1bd7abccb9133cb36cdc16162f Mon Sep 17 00:00:00 2001 From: giswqs Date: Sun, 29 Nov 2026 17:19:37 -0500 Subject: [PATCH 15/20] Resolve an anonymous static catalog's links against its plain address A document read anonymously came back with its origin's address still wrapped in rustgis-anonymous:, so relative child and item links didn't resolve against it and were skipped. The walk now takes the wrapper off the origin (Origin::without_anonymous); each link is wrapped again when it is read. --- crates/tiles/src/address.rs | 9 +++++++++ crates/tiles/src/stac/catalog.rs | 28 +++++++++++++++++++++++++++- 2 files changed, 36 insertions(+), 1 deletion(-) diff --git a/crates/tiles/src/address.rs b/crates/tiles/src/address.rs index c9fbdd8b07..ec62400b88 100644 --- a/crates/tiles/src/address.rs +++ b/crates/tiles/src/address.rs @@ -77,6 +77,15 @@ impl Origin { &self.url } + /// This origin without the anonymous-read wrapper on its address, its reach as observed: the + /// address a document read anonymously resolves its relative links against. + pub fn without_anonymous(mut self) -> Self { + if let (plain, true) = crate::s3::split_anonymous(&self.url) { + self.url = plain.to_owned(); + } + self + } + /// Observed network reach across all hops of this fetch. pub fn reach(&self) -> Reach { self.reach diff --git a/crates/tiles/src/stac/catalog.rs b/crates/tiles/src/stac/catalog.rs index 7e432d0ad7..e966c4ccf8 100644 --- a/crates/tiles/src/stac/catalog.rs +++ b/crates/tiles/src/stac/catalog.rs @@ -546,6 +546,16 @@ pub fn walk_blocking(root: &str, filter: Filter, limit: usize) -> Walk { walk_blocking_with(root, filter, limit, false) } +/// A document read anonymously answers with its address wrapped ([`crate::s3::anonymous`]): its +/// links resolve against the plain address, and each is wrapped again when it is read. +#[cfg(not(target_arch = "wasm32"))] +fn plain_origin(r: Result) -> Result { + r.map(|mut f| { + f.origin = f.origin.without_anonymous(); + f + }) +} + /// [`walk_blocking`], suppressing implicit S3 and web-service credentials when `anonymous` is true. #[cfg(not(target_arch = "wasm32"))] pub fn walk_blocking_with(root: &str, filter: Filter, limit: usize, anonymous: bool) -> Walk { @@ -566,7 +576,7 @@ pub fn walk_blocking_with(root: &str, filter: Filter, limit: usize, anonymous: b &[], ceiling, ); - (u, r) + (u, plain_origin(r)) }; let answers: Vec<(String, Result)> = std::thread::scope(|s| { let handles: Vec<_> = urls @@ -615,6 +625,22 @@ mod tests { "assets": {"visual": {"href": format!("./{id}.tif"), "type": "image/tiff; application=geotiff"}}}) } + /// A catalog read anonymously comes back from an address wrapped for it: its relative child + /// links still resolve, against the plain address. + #[test] + fn an_anonymous_read_resolves_relative_links() { + let root = "https://x.org/catalog.json"; + let doc = json!({"type": "Catalog", "id": "r", "links": [{"rel": "child", "href": "./b/collection.json"}]}); + let mut w = Walk::new(root, Filter::default(), 50); + let (u, _) = w.next_request().unwrap(); + assert_eq!(u, root); + let origin = crate::address::Origin::with_observed_reach(root, crate::address::Reach::Public).unwrap(); + let wrapped = crate::address::Origin { url: crate::s3::anonymous(root), ..origin }; + w.land_fetched(&u, plain_origin(Ok(crate::cache::Fetched { bytes: doc.to_string().into_bytes(), origin: wrapped }))); + assert_eq!(w.next_request().map(|(u, _)| u).as_deref(), Some("https://x.org/b/collection.json")); + assert_eq!(w.failed, 0); + } + #[test] fn static_addresses_and_children() { assert!(is_static("https://x.org/catalog.json") && is_static("https://x.org/a/collection.JSON?x=1")); From a236360695f062e0c74ac81ece90377e96e64db1 Mon Sep 17 00:00:00 2001 From: giswqs Date: Sun, 29 Nov 2026 17:59:39 -0500 Subject: [PATCH 16/20] Resolve anonymous STAC collections, searches and items at plain addresses The walk of a static catalog took the anonymous wrapper off the origin of each document it read, but stac.collections, stac.search paging and stac.addItem's item kept it, so relative links and assets in a document read anonymously didn't resolve. They now use Origin::without_anonymous too. Also test that an S3 capability wrapper cut through before a log parameter is scrubbed leaks no query token. --- crates/engine/src/cmd/stac.rs | 25 ++++++++++++++++--- .../engine/src/tests/scopes_and_redaction.rs | 16 ++++++++++++ 2 files changed, 38 insertions(+), 3 deletions(-) diff --git a/crates/engine/src/cmd/stac.rs b/crates/engine/src/cmd/stac.rs index b4ac8e123b..0f37465308 100644 --- a/crates/engine/src/cmd/stac.rs +++ b/crates/engine/src/cmd/stac.rs @@ -131,7 +131,7 @@ pub(super) fn collections(s: &mut Session, p: &Value) -> CmdResult { }; let fetch_url = crate::service_logins::fetch_url(s.web_logins.is_anonymous() || b(p, "anonymous") == Some(true), &url); let fetched = crate::render::rustgis_tiles::cache::download_blocking_with_origin(&fetch_url)?; - collections_json_from_origin(s, &api, &fetched.bytes, &fetched.origin) + collections_json_from_origin(s, &api, &fetched.bytes, &fetched.origin.without_anonymous()) } } @@ -228,7 +228,8 @@ fn search(s: &mut Session, p: &Value) -> CmdResult { (crate::render::rustgis_tiles::cache::download_blocking_with_origin(&url)?, false) }; let bytes = fetched.bytes; - let origin = fetched.origin; + // Read anonymously, its links resolve against the plain address. + let origin = fetched.origin.without_anonymous(); let (items, next) = stac::parse_items_from_origin(&bytes, &origin)?; // A POST's next link is a request with a body, which is not an address to give back. let next = if posted { @@ -374,7 +375,8 @@ fn item(p: &Value, anonymous: bool) -> Result { /// Revalidates the item at its fresh transport-observed origin, including any redirects. #[cfg(not(target_arch = "wasm32"))] fn item_downloaded(fetched: crate::render::rustgis_tiles::cache::Fetched, requested: &str) -> Result { - let mut item = stac::parse_item_from_origin(&fetched.bytes, &fetched.origin)?; + // Read anonymously, its assets resolve against the plain address. + let mut item = stac::parse_item_from_origin(&fetched.bytes, &fetched.origin.clone().without_anonymous())?; item.url.get_or_insert_with(|| requested.to_string()); Ok(item) } @@ -2131,6 +2133,23 @@ mod deferred_asset_tests { assert!(item.asset_href(Some("data")).is_err()); } + /// An item read anonymously comes back from an address wrapped for it: its relative assets + /// still resolve, against the plain address. + #[test] + fn an_anonymous_item_resolves_relative_assets() { + use crate::render::rustgis_tiles::{address::Origin, cache::Fetched, s3}; + let requested = "https://catalog.example/a/item.json"; + let bytes = json!({"type":"Feature","id":"scene","geometry":null,"properties":{}, + "assets":{"data":{"href":"./scene.tif","roles":["data"]}},"links":[]}) + .to_string() + .into_bytes(); + let origin = + Origin::connected(requested, "93.184.216.34".parse().unwrap()).unwrap().retain_binding(&s3::anonymous(requested)).unwrap(); + assert!(s3::split_anonymous(origin.url()).1, "the origin is wrapped as the transport gives it"); + let item = item_downloaded(Fetched { bytes, origin }, requested).unwrap(); + assert_eq!(item.asset_href(Some("data")).unwrap().1, "https://catalog.example/a/scene.tif"); + } + #[test] fn partial_collection_listings_report_omissions_and_duplicates_stay_quiet() { let api = "https://public.example/catalog.json"; diff --git a/crates/engine/src/tests/scopes_and_redaction.rs b/crates/engine/src/tests/scopes_and_redaction.rs index ba311a60a3..0940d261b7 100644 --- a/crates/engine/src/tests/scopes_and_redaction.rs +++ b/crates/engine/src/tests/scopes_and_redaction.rs @@ -1384,6 +1384,22 @@ fn project_repair_reloads_an_anonymous_raster_anonymously() { assert_eq!(urls, [format!("rustgis-anonymous:{address}")], "the reload was not anonymous"); } +/// An S3 capability wrapper that a long parameter is cut through before it is scrubbed leaks +/// nothing: cut in its header, the rest is redacted; cut in its address, what is kept is the plain +/// address's start, whose named query secrets are taken out after. +#[test] +fn project_log_scrubs_an_s3_wrapper_cut_before_scrubbing() { + let secret = fixture_marker("cut_wrapper_token"); + let address = format!("https://s3.example.org/b/k.tif?token={secret}&pad={}", "x".repeat(5000)); + let wrapped = rustgis_data::s3_address::bind("0123456789abcdef", "https://s3.example.org", &address).unwrap(); + for lead in [0, 4300] { + let note = format!("{}{wrapped}", "word ".repeat(lead / 5)); + let logged = crate::log_params(&json!({ "note": note })).into_log_value().to_string(); + assert!(!logged.contains(&secret), "a cut S3 wrapper's token reached the log: {logged}"); + assert!(!logged.contains("rustgis-s3:"), "a cut S3 wrapper reached the log: {logged}"); + } +} + /// A login far longer than the fixed margin a parameter is cut to before it is scrubbed (a /// bearer token or API key has no length cap) is still taken out whole where it crosses the bound /// the log keeps, in a text and in a field name. From 5e581a47384fb31fff635c31b212db03a42129e5 Mon Sep 17 00:00:00 2001 From: giswqs Date: Sun, 29 Nov 2026 18:26:42 -0500 Subject: [PATCH 17/20] Repair a time-following layer as it reads; scrub only what an error keeps relink_following read the replacement store's coordinates and step signed, and cached the step under the signed key, whatever the layer's anonymous flag; it now reads and caches as the layer does. A logged error is scrubbed only as far as its clip keeps it plus the scrub margin, so a long error page costs little. --- crates/engine/src/cmd/zarr.rs | 5 +++-- crates/engine/src/project_log.rs | 13 ++++++++++--- crates/engine/src/tests.rs | 19 +++++++++++++++++++ 3 files changed, 32 insertions(+), 5 deletions(-) diff --git a/crates/engine/src/cmd/zarr.rs b/crates/engine/src/cmd/zarr.rs index 3a2088fcb7..2be661cf5a 100644 --- a/crates/engine/src/cmd/zarr.rs +++ b/crates/engine/src/cmd/zarr.rs @@ -911,7 +911,7 @@ pub(crate) fn relink_following( if !store.variables().iter().any(|v| v.path == zt.variable) { return Err(format!("{full} has no variable '{}': choose the store the layer was added from", zt.variable)); } - let coords = store_files(full, &zarr::coordinate_keys(&store, &zt.variable), false)?; + let coords = store_files(full, &zarr::coordinate_keys(&store, &zt.variable), rl.anonymous)?; let (dim, dates) = zarr::time_axis(&store, &zt.variable, &coords).ok_or_else(|| format!("{full}: {} no longer has a time axis", zt.variable))?; if dim != zt.dim || !dates.iter().all(|d| d.is_finite()) || !dates.windows(2).all(|w| w[0] < w[1]) { @@ -968,7 +968,8 @@ pub(crate) fn relink_following( let window = slider.map(rustgis_map::time::TimeSlider::window); let want = zt.step_for(window); let i = want.unwrap_or(0); - let r = read_step_with(&zt, i, slice_key(&zt, i), false)?; + // Read as the layer reads (anonymously when it was added so), cached apart from signed reads. + let r = read_step_with(&zt, i, slice_key_for(&zt, i, rl.anonymous), rl.anonymous)?; rl.validate_replacement(&r, full)?; zt.shown = want; let mut new = rl.clone(); diff --git a/crates/engine/src/project_log.rs b/crates/engine/src/project_log.rs index ec6897bbf9..d065810510 100644 --- a/crates/engine/src/project_log.rs +++ b/crates/engine/src/project_log.rs @@ -131,9 +131,16 @@ pub(crate) fn kept_params(params: &Value) -> Value { /// clipping to [`LOG_ERROR_CHARS`] so a secret spanning the clip boundary cannot leave a prefix /// behind, then other secrets are removed. fn kept_error(e: &str) -> String { - let e = scrub_log_text(e); - let e = - if e.chars().nth(LOG_ERROR_CHARS).is_some() { format!("{}…", e.chars().take(LOG_ERROR_CHARS).collect::()) } else { e }; + // Only as much is scrubbed as the clip can keep, plus [`scrub_margin`], so a long error (a + // server's page) costs little and a secret crossing the clip is still whole when matched. + let keep = LOG_ERROR_CHARS.saturating_add(scrub_margin()); + let cut = e.chars().nth(keep).is_some(); + let e = if cut { scrub_log_text(&e.chars().take(keep).collect::()) } else { scrub_log_text(e) }; + let e = if cut || e.chars().nth(LOG_ERROR_CHARS).is_some() { + format!("{}…", e.chars().take(LOG_ERROR_CHARS).collect::()) + } else { + e + }; crate::cmd::history::redacted_text(&sql_secrets_removed(&e)) } diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 2eee97bc4a..c9aa33b124 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -38588,6 +38588,25 @@ fn a_zarr_variable_follows_the_time_slider() { let _ = std::fs::remove_dir_all(dir); } +/// A time-following layer added anonymously and repaired from a replacement store reads its step +/// as the layer reads, and caches it apart from a signed read of the same step. +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn relinking_an_anonymous_time_layer_reads_it_anonymously() { + let _cache = zarr_cache_lock(); + let (dir, path) = zarr_store_over_time("relink-anonymous"); + let mut s = Session::new(Project::default()); + let id = s.run("layer.addZarr", &json!({"path": path, "variable": "t", "time": true})).unwrap()["layer"].as_u64().unwrap() as u32; + let mut rl = s.map().layer(id).unwrap().raster.clone().unwrap(); + rl.anonymous = true; + let new = crate::cmd::zarr::relink_following(None, &rl, &path).unwrap(); + let zt = new.time_zarr.as_ref().unwrap(); + let i = zt.shown.unwrap_or(0); + assert!(crate::cmd::zarr::kept_slice(&crate::cmd::zarr::slice_key_for(zt, i, true)).is_some(), "read anonymously"); + assert!(crate::cmd::zarr::kept_slice(&crate::cmd::zarr::slice_key(zt, i)).is_none(), "not cached as a signed read"); + let _ = std::fs::remove_dir_all(dir); +} + /// Manual reload reads changed chunks even when folder metadata is unchanged, and later time /// steps cannot revive a cached pre-reload slice. #[cfg(not(target_arch = "wasm32"))] From a12b1e44b3b94885d7ca5994abc727e448231891 Mon Sep 17 00:00:00 2001 From: giswqs Date: Sun, 29 Nov 2026 19:15:31 -0500 Subject: [PATCH 18/20] Run every add command asked to read anonymously as an anonymous scope Only layer.addUrl and layer.addDownload with "anonymous": true ran in an anonymous scope, so service.add, the STAC adds and the rest read the request anonymously but tagged what they added from the session alone: a layer could take the origin's saved login as its connection and be read signed later. Every command in ADD_COMMANDS now does. --- crates/engine/src/policy/dispatch.rs | 4 +++- crates/engine/src/tests.rs | 1 + crates/engine/src/tests/service_logins.rs | 17 +++++++++++++++++ 3 files changed, 21 insertions(+), 1 deletion(-) diff --git a/crates/engine/src/policy/dispatch.rs b/crates/engine/src/policy/dispatch.rs index 5934eab835..79743d6af6 100644 --- a/crates/engine/src/policy/dispatch.rs +++ b/crates/engine/src/policy/dispatch.rs @@ -1037,8 +1037,10 @@ impl Session { } result }; + // An add command asked to read anonymously runs as an anonymous scope + // does, so what it adds is marked so too and never adopts a login. let anonymous = s.web_logins.is_anonymous() - || (matches!(spec.id, "layer.addUrl" | "layer.addDownload") + || (crate::service_logins::ADD_COMMANDS.contains(&spec.id) && params.get("anonymous").and_then(Value::as_bool) == Some(true)); let result = crate::service_logins::anonymously(s, anonymous, add) .unwrap_or_else(|payload| { diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 10568dd329..567983123e 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -28757,6 +28757,7 @@ fn wms_layers_with_time() { assert!(e.contains("no time to follow"), "{e}"); let foreign = WMS.replace("https://maps.example.com/wms?", "https://fallback-b.invalid/wms?"); service_logins::foreign_service_fallback_stays_anonymous("wms", url, "population", WMS, &foreign); + service_logins::explicit_anonymous_add_stays_unbound("wms", url, "population", WMS); } /// Identify asks a WMS layer what is at the point (GetFeatureInfo): the request from the diff --git a/crates/engine/src/tests/service_logins.rs b/crates/engine/src/tests/service_logins.rs index 847ff4519e..486eeee140 100644 --- a/crates/engine/src/tests/service_logins.rs +++ b/crates/engine/src/tests/service_logins.rs @@ -2410,6 +2410,23 @@ fn delayed_head_refusal_keeps_secrets_out_of_history_across_login_lifecycle() { } } +/// A service layer added with `"anonymous": true` outside an anonymous scope comes out unbound and +/// marked anonymous, though a login for its origin is active, now and after reopening. +pub(super) fn explicit_anonymous_add_stays_unbound(kind: &str, source: &str, layer: &str, text: &str) { + let mut s = session(None); + let a = new(&mut s, json!({"kind":kind,"address":source,"auth":"header","keyName":"X-Key"})); + s.run("connection.login", &json!({"id":a,"apiKey":"RGSYNTH_explicit_anonymous"})).unwrap(); + s.run("service.add", &json!({"url":source,"layer":layer,"text":text,"time":"default","anonymous":true})).unwrap(); + for reopened in [false, true] { + if reopened { + let saved = s.project.saved_text(None).unwrap().0; + s.run("project.openText", &json!({"text":saved})).unwrap(); + } + let tile = &s.map().tiles[0]; + assert!(tile.anonymous && tile.connection.is_empty() && header(&tile.url).is_none(), "reopened {reopened}: {}", tile.url); + } +} + /// A foreign capability fallback cannot select a destination login now or after reopening. pub(super) fn foreign_service_fallback_stays_anonymous(kind: &str, source: &str, layer: &str, clean: &str, foreign: &str) { let mut results = Vec::new(); From 850b51958fd9c667eb40132bdd5dfc3d34e08f94 Mon Sep 17 00:00:00 2001 From: giswqs Date: Sun, 29 Nov 2026 19:52:51 -0500 Subject: [PATCH 19/20] Declare map.addTiles's anonymous parameter map.addTiles is one of the add commands an "anonymous": true runs in an anonymous scope, but its parameters didn't name the key, so the Assistant, MCP and the command snapshot didn't show it. --- crates/engine/command-surface.txt | 2 +- crates/engine/src/cmd/tiles.rs | 2 +- crates/engine/src/tests/service_logins.rs | 16 ++++++++++++++++ 3 files changed, 18 insertions(+), 2 deletions(-) diff --git a/crates/engine/command-surface.txt b/crates/engine/command-surface.txt index fb50c0acfd..93d273fd1c 100644 --- a/crates/engine/command-surface.txt +++ b/crates/engine/command-surface.txt @@ -309,7 +309,7 @@ layout.seriesRefresh layout? layout.update layout? element x? y? w? h? name? visible? locked? text? size? color? bold? italic? align? letterSpacing? rotation? wrap? valign? lineSpacing? case? font? fallback? title? subtitle? allClasses? hideOther? showNoData? exclude? layerOrder? labels? classLabels? columns? textSize? showLayerNames? sizes? showCounts? orientation? ticks? tickSide? reverse? style? fill? outline? radius? width? dash? dir? head? angle? length? units? divisions? subdivisions? divisionsBeforeZero? labelPosition? unitLabel? unitLabelPosition? fit? map? scale? center? bearing? pitch? grid? extentIndicator? border? section? layer? field? label? group? statistic? order? bars? other? stack? values? decimals? barColor? classes? labelAlign? mirror? max? band? side? gap? thickness? unit? lineColor? lineWidth? min? guides? barOutline? hideLabels? rows? image? path? background? locator.find locator? text limit? zoom? map.activate name -map.addTiles url kind? name? bounds? attribution? minZoom? maxZoom? tileSize? singleImage? tms? subdomains? layers? styleLayers? opacity? blend? resampling? overlay? top? replace? id? view? start? end? unit? interval? dates? legend? connection? +map.addTiles url kind? name? bounds? attribution? minZoom? maxZoom? tileSize? singleImage? tms? subdomains? layers? styleLayers? opacity? blend? resampling? overlay? top? replace? id? view? start? end? unit? interval? dates? legend? connection? anonymous? map.basemap name keepTiles? color? map.bodies map.body name? basemap? diff --git a/crates/engine/src/cmd/tiles.rs b/crates/engine/src/cmd/tiles.rs index f662aff4f1..fef80bc372 100644 --- a/crates/engine/src/cmd/tiles.rs +++ b/crates/engine/src/cmd/tiles.rs @@ -17,7 +17,7 @@ const TILE_ROLES: &[crate::ParamRole] = &[crate::ParamRole { key: "legend", role pub fn commands() -> Vec { vec![ C::new("map.addTiles", "Add Tile Layer", "Home › Add", add).roles(TILE_ROLES).effects(crate::policy::Effects::NONE.with(crate::policy::Effect::Network)).params( - r#"{"url": "https://…/{z}/{x}/{y}.png" | vector tiles ".pbf" or TileJSON | MapLibre style.json | a PMTiles archive (web address or file path) | an MBTiles file path, "kind"?: "raster"|"vector"|"style"|"pmtiles"|"mbtiles" (guessed from the url), "name"?: text, "bounds"?: [west, south, east, north] (longitude/latitude coverage, when known), "attribution"?: text, "minZoom"?: number, "maxZoom"?: number, "tileSize"?: 256|512 (1024 too for a WMS or map service asked for in Web Mercator by its tiles' box: their pictures are asked for that size), "singleImage"?: bool (a WMS or map service: one picture of the view instead of tiles, so symbols and labels aren't cut at tile edges; tiles on the globe, a tilted map or a projection the service doesn't offer; by default on for one, unless tileSize is given), "tms"?: bool, "subdomains"?: [text], "layers"?: [vector tile layer names, drawn in colours of their own], "styleLayers"?: [MapLibre style layers drawing vector tiles instead (their source is the tiles')], "opacity"?: 0–1, "blend"?: "normal"|"multiply"|"screen"|"overlay"|"darken"|"lighten"|"difference" (how it combines with what is beneath), "resampling"?: "nearest"|"bilinear" (picture tiles drawn at a size other than their own: each pixel a block, or blended, the default), "overlay"?: bool (on top of the map's layers, as every new layer goes; without it a basemap, under them; one with the same address and role is replaced when it has the same name or the same look), "top"?: bool (on top of the map's layers, as a layer added as data goes; by default an overlay's place), "replace"?: bool (removes the other tile basemaps, not overlays), "id"?: catalog id, "view"?: bool (a MapLibre style: go to the place, zoom, bearing and pitch its root properties give, once it loads), "start"?, "end"?: dates a url with date placeholders ({date:YYYY-MM-DD}, {YYYY}) spans, turning the time slider on (or, when it is on, setting its span), "unit"?, "interval"?, "dates"?: its steps (as in time.set), "legend"?: "the web address of its legend picture (PNG or JPEG)" | [address | {"url": address, "minScale"?: scale denominator, "maxScale"?: one (the scales it is for, from minScale up to below maxScale)}] (at most 16; the Layers pane shows the one for the map's scale under the layer; service.add gives a WMS or WMTS layer its service's), "connection"?: "the id of the saved web-service connection it comes from (as service.add): the tile layer records it, and its tiles are read with its login"}"#, + r#"{"url": "https://…/{z}/{x}/{y}.png" | vector tiles ".pbf" or TileJSON | MapLibre style.json | a PMTiles archive (web address or file path) | an MBTiles file path, "kind"?: "raster"|"vector"|"style"|"pmtiles"|"mbtiles" (guessed from the url), "name"?: text, "bounds"?: [west, south, east, north] (longitude/latitude coverage, when known), "attribution"?: text, "minZoom"?: number, "maxZoom"?: number, "tileSize"?: 256|512 (1024 too for a WMS or map service asked for in Web Mercator by its tiles' box: their pictures are asked for that size), "singleImage"?: bool (a WMS or map service: one picture of the view instead of tiles, so symbols and labels aren't cut at tile edges; tiles on the globe, a tilted map or a projection the service doesn't offer; by default on for one, unless tileSize is given), "tms"?: bool, "subdomains"?: [text], "layers"?: [vector tile layer names, drawn in colours of their own], "styleLayers"?: [MapLibre style layers drawing vector tiles instead (their source is the tiles')], "opacity"?: 0–1, "blend"?: "normal"|"multiply"|"screen"|"overlay"|"darken"|"lighten"|"difference" (how it combines with what is beneath), "resampling"?: "nearest"|"bilinear" (picture tiles drawn at a size other than their own: each pixel a block, or blended, the default), "overlay"?: bool (on top of the map's layers, as every new layer goes; without it a basemap, under them; one with the same address and role is replaced when it has the same name or the same look), "top"?: bool (on top of the map's layers, as a layer added as data goes; by default an overlay's place), "replace"?: bool (removes the other tile basemaps, not overlays), "id"?: catalog id, "view"?: bool (a MapLibre style: go to the place, zoom, bearing and pitch its root properties give, once it loads), "start"?, "end"?: dates a url with date placeholders ({date:YYYY-MM-DD}, {YYYY}) spans, turning the time slider on (or, when it is on, setting its span), "unit"?, "interval"?, "dates"?: its steps (as in time.set), "legend"?: "the web address of its legend picture (PNG or JPEG)" | [address | {"url": address, "minScale"?: scale denominator, "maxScale"?: one (the scales it is for, from minScale up to below maxScale)}] (at most 16; the Layers pane shows the one for the map's scale under the layer; service.add gives a WMS or WMTS layer its service's), "connection"?: "the id of the saved web-service connection it comes from (as service.add): the tile layer records it, and its tiles are read with its login", "anonymous"?: bool (read without any saved login, S3 connection or implicit credentials: the tile layer is marked so and never takes a login)}"#, ), C::new("map.removeTiles", "Remove Tile Layer", "Home › Add", remove).roles(&[]).effects(crate::policy::Effects::NONE) .params(r#"{"name"?: text, "index"?: number, "id"?: catalog id} (removes every tile layer when none is given)"#), diff --git a/crates/engine/src/tests/service_logins.rs b/crates/engine/src/tests/service_logins.rs index 486eeee140..60220ddbf2 100644 --- a/crates/engine/src/tests/service_logins.rs +++ b/crates/engine/src/tests/service_logins.rs @@ -1432,6 +1432,22 @@ fn test_refuses_changed_endpoint_and_missing_login_instead_of_testing_anonymousl assert!(!s.database_logins.has_session_password(&id)); } +/// `map.addTiles` with `"anonymous": true` adds its tile layer unbound and marked anonymous, though +/// a login for its origin is active. +#[test] +fn map_add_tiles_asked_anonymous_takes_no_login() { + let mut s = session(None); + let a = new(&mut s, json!({"kind":"service","address":"https://anon-tiles757.example.org","auth":"header","keyName":"X-Key"})); + s.run("connection.login", &json!({"id":a,"apiKey":"RGSYNTH_anon_tiles"})).unwrap(); + s.run("map.addTiles", &json!({"url":"https://anon-tiles757.example.org/{z}/{x}/{y}.png","anonymous":true})).unwrap(); + let tile = &s.map().tiles[0]; + assert!(tile.anonymous && tile.connection.is_empty() && header(&tile.url).is_none(), "{}", tile.url); + // Without it, the tile layer takes the origin's login as before. + s.run("map.addTiles", &json!({"url":"https://anon-tiles757.example.org/b/{z}/{x}/{y}.png","name":"Signed"})).unwrap(); + let signed = s.map().tiles.iter().find(|t| t.name == "Signed").unwrap(); + assert!(!signed.anonymous && signed.connection == a, "{}", signed.url); +} + #[test] fn junk_login_parameters_never_panic() { let mut s = session(Some(Arc::new(MemorySecrets::new()))); From e77f7ebee1ec08eafc605c9179f92598db4e4be5 Mon Sep 17 00:00:00 2001 From: giswqs Date: Sun, 29 Nov 2026 20:27:46 -0500 Subject: [PATCH 20/20] Say log fields left out for alike names; state earthdata.status's limit The log's clip cut field names to 200 characters and kept the first of two that came out alike, dropping the other without a word; it now says how many were left out. earthdata.status read by another scope doesn't read back a remembered token, and its doc comment and parameters now say what that shows. --- crates/engine/src/cmd/earthdata.rs | 6 ++++- crates/engine/src/project_log.rs | 24 +++++++++++++------ .../engine/src/tests/scopes_and_redaction.rs | 12 ++++++++++ 3 files changed, 34 insertions(+), 8 deletions(-) diff --git a/crates/engine/src/cmd/earthdata.rs b/crates/engine/src/cmd/earthdata.rs index 23d9b13db0..608053e63d 100644 --- a/crates/engine/src/cmd/earthdata.rs +++ b/crates/engine/src/cmd/earthdata.rs @@ -27,6 +27,10 @@ pub fn commands() -> Vec { C::new("earthdata.status", "Earthdata Login Status", "Home › Add › Web Data › NASA Earthaccess", |s, _p| { // Only a native user session may restore from the keychain (when saved secrets are // enabled) or mutate process-wide expiry state; other scopes get a read-only status. + // That status is the session's as it stands. The desktop app reads a remembered + // token at launch; on the command line, in Python or over MCP, one not yet read back + // shows as not kept and not remembered until the user's own status or a command + // reading an Earthdata host (`plan.rs`, `bind`) reads it. // Without opt-in, skip expiry cleanup when the token is remembered in the keychain so // an unopted session does not delete a keychain entry. if s.policy_user() { @@ -40,7 +44,7 @@ pub fn commands() -> Vec { Ok(status()) }).roles(&[]).effects(crate::policy::Effects::NONE) .view() - .params("{} — whether a token is kept, its expiry, whether it is remembered on this computer, and whether an expired one was forgotten (give a new one with earthdata.login)"), + .params("{} — whether a token is kept, its expiry, whether it is remembered on this computer, and whether an expired one was forgotten (give a new one with earthdata.login); asked by the Assistant, MCP or a plugin, a remembered token not yet read back this session (the app reads it at launch) shows as not kept"), ] } diff --git a/crates/engine/src/project_log.rs b/crates/engine/src/project_log.rs index d065810510..88ebe87452 100644 --- a/crates/engine/src/project_log.rs +++ b/crates/engine/src/project_log.rs @@ -569,15 +569,25 @@ fn clip(v: &Value, chars: usize, items: usize, depth: usize) -> Value { Value::Array(out) } Value::Object(o) if depth < 8 => { - // Two keys alike in their first 200 characters: the first stays. A key cut short may - // hide a secret's name past the cut (redaction reads the names after this): its value - // goes. + // Two keys alike in their first 200 characters: the first stays, and how many were left + // out is said. A key cut short may hide a secret's name past the cut (redaction reads + // the names after this): its value goes. let mut out = serde_json::Map::new(); + let mut alike = 0usize; for (k, x) in o { - let value = || { - if k.chars().nth(200).is_some() { Value::String("…".into()) } else { clip(x, chars, items, depth + 1) } - }; - out.entry(k.chars().take(200).collect::()).or_insert_with(value); + let key: String = k.chars().take(200).collect(); + if out.contains_key(&key) { + alike = alike.saturating_add(1); + continue; + } + let value = if k.chars().nth(200).is_some() { Value::String("…".into()) } else { clip(x, chars, items, depth + 1) }; + out.insert(key, value); + } + if alike > 0 { + out.insert( + "…".into(), + Value::String(format!("{alike} field(s) left out: their names were alike in their first 200 characters")), + ); } Value::Object(out) } diff --git a/crates/engine/src/tests/scopes_and_redaction.rs b/crates/engine/src/tests/scopes_and_redaction.rs index 0940d261b7..091577cf47 100644 --- a/crates/engine/src/tests/scopes_and_redaction.rs +++ b/crates/engine/src/tests/scopes_and_redaction.rs @@ -1384,6 +1384,18 @@ fn project_repair_reloads_an_anonymous_raster_anonymously() { assert_eq!(urls, [format!("rustgis-anonymous:{address}")], "the reload was not anonymous"); } +/// Two field names alike in their first 200 characters, cut to them for the log, keep the first +/// and say how many were left out, not dropping one without a word. +#[test] +fn project_log_says_fields_left_out_whose_names_are_alike_once_cut() { + let stem = "f".repeat(200); + let logged = crate::log_params(&json!({ format!("{stem}a"): 1, format!("{stem}b"): 2, "short": 3 })).into_log_value().to_string(); + assert!(logged.contains("1 field(s) left out"), "{logged}"); + assert!(logged.contains("\"short\":3"), "{logged}"); + let clean = crate::log_params(&json!({ "a": 1, "b": 2 })).into_log_value().to_string(); + assert!(!clean.contains("left out"), "{clean}"); +} + /// An S3 capability wrapper that a long parameter is cut through before it is scrubbed leaks /// nothing: cut in its header, the rest is redacted; cut in its address, what is kept is the plain /// address's start, whose named query secrets are taken out after.