diff --git a/crates/assistant/src/audit.rs b/crates/assistant/src/audit.rs index e1ff9f9d3e..873170d5ba 100644 --- a/crates/assistant/src/audit.rs +++ b/crates/assistant/src/audit.rs @@ -164,8 +164,14 @@ 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::render::rustgis_tiles::logins::scrub(&rustgis_engine::sources::scrub_s3_wrappers(s)); + redact_string_inner(&s) +} + +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 @@ -259,20 +265,39 @@ 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)), - }) - .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, } @@ -508,4 +533,62 @@ 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}"); + + // 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", + "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}"); + + // 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/command-surface.txt b/crates/engine/command-surface.txt index fc5ae35e85..93d273fd1c 100644 --- a/crates/engine/command-surface.txt +++ b/crates/engine/command-surface.txt @@ -29,7 +29,7 @@ cache.cancel cache.empty cache.emptyIndexes cache.fill -catalog.search url query? bbox? start? bboxCrs? text? connection? +catalog.search url query? bbox? start? bboxCrs? text? connection? anonymous? connection.browse id node? probe? answer? documents? connection.cancelToken id connection.duplicate id name? @@ -52,8 +52,8 @@ copernicus.logout copernicus.status cube.catalog theme? bbox? query? cube.open id bbox? start? end? maxCloud? range? name? -cube.reduce cube? layers? layer? path? url? collection variable? index? crs? asset? assets? mask? bbox? maxCloud? cellSize? resampling? band? dates? stat order? above? classes? by? start? end? months? minValid? name? -cube.trend cube? layers? layer? collection url? asset? mask? bbox? maxCloud? cellSize? resampling? band? dates? start? end? months? test? seasons? alpha? minValid? per? name? ran? +cube.reduce cube? layers? layer? path? url? collection variable? index? crs? asset? assets? mask? bbox? maxCloud? cellSize? resampling? band? dates? stat order? above? classes? by? start? end? months? minValid? name? anonymous? +cube.trend cube? layers? layer? collection url? asset? mask? bbox? maxCloud? cellSize? resampling? band? dates? start? end? months? test? seasons? alpha? minValid? per? name? ran? anonymous? data.archive layer? on? data.archiveHistory layer? data.archiveRestore layer? time @@ -72,8 +72,8 @@ dl.import path? data? dl.package model? path dl.remove model dl.train layer training classField bands? hidden? epochs? model? -earthdata.collections keyword? shortName? cloudHosted? limit? page? answer? -earthdata.granules collection? shortName? bbox? view? start? end? limit? page? footprints? name? answer? +earthdata.collections keyword? shortName? cloudHosted? limit? page? answer? anonymous? +earthdata.granules collection? shortName? bbox? view? start? end? limit? page? footprints? name? answer? anonymous? earthdata.login token remember? earthdata.logout earthdata.status @@ -224,7 +224,7 @@ layer.addPhotos paths? folder? name? layer.addSample name layer.addSql sql name? database? password? crs? stream? ran? layer.addUrl url bytes? format? name? layer? zoom? x? y? wkt? crs? delimiter? paperSpace? blocks? stream? as? whole? cog? bbox? cellSize? cube? start? end? unit? interval? dates? connection? service? bounds? from? fromDocument? anonymous? coverage? coverageCrs? request? -layer.addZarr path url variable? index? cells? bbox? crs? name? time? start? end? ran? summary? +layer.addZarr path url variable? index? cells? bbox? crs? name? time? start? end? ran? summary? anonymous? layer.aggregation layer? shape size? layer.blend layer? mode layer.classStyle layer? value? index? other? color? outline? label? @@ -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? @@ -489,7 +489,7 @@ raster.setDefaultStyle fromLayer? layer? ramp? invert? stretch? low? high? n? re raster.spectral layer lon? lat? points? zone? raster.stretch layer? type low? high? n? min? max? like? raster.symbology layer? type band? ramp? invert? classes? method? azimuth? altitude? zFactor? shadow? sky? fill? ambient? balanced? shadowSoftness? aerial? terrain? flats? rock? grey? -raster.zarrInfo path url bbox? variable? +raster.zarrInfo path url bbox? variable? anonymous? report.activate report report.attachments report? field report.autofill report? @@ -527,12 +527,12 @@ select.layerFromSelection layer? select.rows layer? rows mode? select.switch layer? select.zoomTo -service.add url type? layer name? time? text? documents? source_url? describe? tiles? bbox? full where? connection? +service.add url type? layer name? time? text? documents? source_url? describe? tiles? bbox? full where? connection? anonymous? service.coverage url type? layer text? documents? source_url? describe? bbox? connection? anonymous? service.group group? layer? name? expanded? visible? remove? service.groupPlan url? type? name? group? layer? sourceOnly? text? documents? connection? anonymous? service.import url type? name? text? documents? responses? connection? anonymous? -service.layers url type? text? documents? connection? filter? +service.layers url type? text? documents? connection? filter? anonymous? service.refresh group? layer? text? documents? responses? connection? anonymous? share.dataStore name? path? remove? share.export3d layer? path heightField? height? zScale? @@ -564,14 +564,14 @@ sources.remove list kind address sources.save kind address name? extra? sql.query sql database? password? limit? sql.schema database password? -stac.addAsset item url asset? name? connection? +stac.addAsset item url asset? name? connection? anonymous? stac.addBands item combination? red? green? blue? bbox? cellSize? name? ran? -stac.addCube url? collection asset bbox? start end maxCloud? range? name? attribution? connection? +stac.addCube url? collection asset bbox? start end maxCloud? range? name? attribution? connection? anonymous? stac.addFootprints footprints name? stac.addIndex item index bbox? cellSize? name? ran? stac.area path? layer? buffer? unit? -stac.collections url? connection? -stac.search url? collections? bbox? intersects? layer? buffer? unit? datetime? limit? maxCloud? sortby? phase? properties? footprints? connection? +stac.collections url? connection? anonymous? +stac.search url? collections? bbox? intersects? layer? buffer? unit? datetime? limit? maxCloud? sortby? phase? properties? footprints? connection? anonymous? style.add path? text? data? style.apply layer? name style.import path? text? data? @@ -604,5 +604,5 @@ tool.set tool topology.rules add? remove? clear? topology.validate toleranceM? view.linkViews on? -zarr.reduce layer? path url variable? index? stat above? start? end? months? minValid? name? crs? -zarr.series lon lat layer? path url variable? index? start? end? crs? +zarr.reduce layer? path url variable? index? stat above? start? end? months? minValid? name? crs? anonymous? +zarr.series lon lat layer? path url variable? index? start? end? crs? anonymous? diff --git a/crates/engine/src/cmd/cube.rs b/crates/engine/src/cmd/cube.rs index 994014ad64..f317fa8793 100644 --- a/crates/engine/src/cmd/cube.rs +++ b/crates/engine/src/cmd/cube.rs @@ -26,10 +26,10 @@ use crate::{CmdResult, CommandSpec as C, Session}; pub fn commands() -> Vec { vec![C::new("cube.trend", "Trend Analysis", "Analyze › Workflows", trend_cmd).inputs(cube_inputs).roles(&[]).effects(crate::policy::Effects::NONE.with(crate::policy::Effect::Network).with(crate::policy::Effect::Files)).params( - r#"{"cube"?: an entry of cube.catalog (its STAC API, collection, band, cell size and cloud cap, or its Zarr store and variable) | "layers"?: [raster layers, a date each; one on another grid is resampled (nearest) onto the first's] | "layer"?: a Zarr layer (or "path" | "url", "variable", "index", "crs" as for zarr.reduce) or a raster of several bands, a date each (default: the active layer) | "collection": a STAC collection (desktop; read in place over an area, in pieces when large; with url, asset, bbox, maxCloud, cellSize and resampling below, and "start", "end"), "url"?: the collection's STAC API (as for stac.addCube), "asset"?: the collection's band, such as NDVI ("assets", several bands, is cube.reduce's: a trend refuses it), "mask"?: a collection's quality band (as for cube.reduce), "bbox"?: [w, s, e, n] | "view" (the collection's area), "maxCloud"?: a collection's cloud cover cap, "cellSize"?: a collection's cell size in the files' units (the overview level nearest it is read; a GeoTIFF in strips without one near it takes it with "resampling": "average"), "resampling"?: "nearest" (default: that overview's pixels as stored) | "average" (each cell the mean of the full images' pixels in it, which reads them), "band"?: 1-based (a stack's band), "dates"?: [dates] (a stack's or the bands' dates, in their order; default: read from the layers' names or files, or the bands' names), "start"?, "end"?: dates (a whole number from 1000 to 9999 is a year; an end given as a year or a month takes all of it), "months"?: [1–12] (one season across years), "test"?: "hamedRao" (default) | "yueWang" | "seasonal" | "original", "seasons"?: parts of a year for the seasonal test (default 12), "alpha"?: 0.05 (above 0, below 0.5), "minValid"?: dates a cell needs (default: half of them, at least 4; the seasonal test also needs 4 in seasons of two or more), "per"?: "year" (default) | "decade", "name"?: text, "ran"?: (internal: a trend the app has worked out)} → four raster layers: Sen's slope, the test's Z and p-value, and the slope where p < alpha"#, + r#"{"cube"?: an entry of cube.catalog (its STAC API, collection, band, cell size and cloud cap, or its Zarr store and variable) | "layers"?: [raster layers, a date each; one on another grid is resampled (nearest) onto the first's] | "layer"?: a Zarr layer (or "path" | "url", "variable", "index", "crs" as for zarr.reduce) or a raster of several bands, a date each (default: the active layer) | "collection": a STAC collection (desktop; read in place over an area, in pieces when large; with url, asset, bbox, maxCloud, cellSize and resampling below, and "start", "end"), "url"?: the collection's STAC API (as for stac.addCube), "asset"?: the collection's band, such as NDVI ("assets", several bands, is cube.reduce's: a trend refuses it), "mask"?: a collection's quality band (as for cube.reduce), "bbox"?: [w, s, e, n] | "view" (the collection's area), "maxCloud"?: a collection's cloud cover cap, "cellSize"?: a collection's cell size in the files' units (the overview level nearest it is read; a GeoTIFF in strips without one near it takes it with "resampling": "average"), "resampling"?: "nearest" (default: that overview's pixels as stored) | "average" (each cell the mean of the full images' pixels in it, which reads them), "band"?: 1-based (a stack's band), "dates"?: [dates] (a stack's or the bands' dates, in their order; default: read from the layers' names or files, or the bands' names), "start"?, "end"?: dates (a whole number from 1000 to 9999 is a year; an end given as a year or a month takes all of it), "months"?: [1–12] (one season across years), "test"?: "hamedRao" (default) | "yueWang" | "seasonal" | "original", "seasons"?: parts of a year for the seasonal test (default 12), "alpha"?: 0.05 (above 0, below 0.5), "minValid"?: dates a cell needs (default: half of them, at least 4; the seasonal test also needs 4 in seasons of two or more), "per"?: "year" (default) | "decade", "name"?: text, "ran"?: (internal: a trend the app has worked out), "anonymous"?: bool (read without any saved login, S3 connection or implicit credentials)} → four raster layers: Sen's slope, the test's Z and p-value, and the slope where p < alpha"#, ), C::new("cube.reduce", "Summarise a Data Cube over Time", "Analyze › Workflows", reduce_cmd).inputs(cube_inputs).roles(&[]).effects(crate::policy::Effects::NONE.with(crate::policy::Effect::Network).with(crate::policy::Effect::Files)).params( - r#"{"cube"?: an entry of cube.catalog (as for cube.trend) | "layers"?: [raster layers, a date each; one on another grid is resampled (nearest) onto the first's] | "layer"?: a Zarr layer or a raster of several bands, a date each (default: the active layer) | "path"?: a Zarr store's folder | "url"?: a Zarr store's address, or a STAC collection's API (as for stac.addCube) | "collection": a STAC collection (desktop; read in place over an area, in pieces when large; with url, asset, bbox, maxCloud, cellSize and resampling below, and "start", "end"), "variable"?, "index"?, "crs"?: a Zarr variable's (as for zarr.reduce), "asset"?: the collection's band, such as NDVI, "assets"?: [2–16 of the collection's bands, such as ["B04", "B03", "B02"]] (instead of asset, for mean, median, first or firstDate: one layer a group with a band for each, drawn as RGB when three (firstDate: one band, the date all of them were taken at); a cell goes in at a date only with a value in every band, and median takes each cell's bands from one date, the one whose bands' sum is the middle (the lower of two); items without all of them are left out), "mask"?: {"asset": the items' quality band, such as SCL, Fmask, qa_pixel or CMASK, and one of "keep": [classes] | "drop": [classes] | "bits": {"set"?: [bits on], "unset"?: [bits off]} (bits 0–63)} (a collection's: a cell is taken at a date only where the same item's quality band lets it through, read onto the band's grid by nearest neighbour; items without it are left out), "bbox"?: [w, s, e, n] | "view" (the collection's area), "maxCloud"?: a collection's cloud cover cap, "cellSize"?: a collection's cell size in the files' units (the overview level nearest it is read; a GeoTIFF in strips without one near it takes it with "resampling": "average"), "resampling"?: "nearest" (default) | "average" (as for cube.trend), "band"?: 1-based (a stack's band), "dates"?: [dates] (a stack's or the bands' dates, in their order; default: read from the layers' names or files, or the bands' names), "stat": "mean"|"median"|"min"|"max"|"sum"|"std" (the population standard deviation, n)|"count"|"countAbove"|"first" (the value at the cell's first date with one, in "order": the best pixel)|"firstDate" (the date of the value first takes, as days since 1970-01-01, its legend the dates)|"mode" or "majority" (a categorical cube's most frequent class; the least of those tied)|"modeCount" (how many dates had the mode)|"variety" (how many classes)|"changes" (how many times the class changed from one valued date to the next)|"longestRun" (the class of the longest run of dates in one class; the least of those tied)|"longestRunLength" (how many dates that run lasted)|"frequency" (a layer for each class met: its count of dates)|"countIn" (how many dates in the classes given), "order"?: first's and firstDate's order of the dates: "clear" (the default with a mask: by the share of the area the mask lets through, the clearest first) | "date" (the default without one: the earliest first) | "-date" (the latest first), "above"?: number (countAbove's threshold), "classes"?: [whole numbers 0–255, at most 256] (countIn's classes), "by"?: "all" (default: one layer) | "year" (a layer for each calendar year) | "month" (a layer for each month of the year, across years), "start"?, "end"?: dates (as for cube.trend), "months"?: [1–12] (a season across years), "minValid"?: 0–1 (a cell with a smaller share of its group's dates is left empty; default 0), "name"?: text} → raster layers of the statistic, one for each group (frequency: one for each class of each group)"#, + r#"{"cube"?: an entry of cube.catalog (as for cube.trend) | "layers"?: [raster layers, a date each; one on another grid is resampled (nearest) onto the first's] | "layer"?: a Zarr layer or a raster of several bands, a date each (default: the active layer) | "path"?: a Zarr store's folder | "url"?: a Zarr store's address, or a STAC collection's API (as for stac.addCube) | "collection": a STAC collection (desktop; read in place over an area, in pieces when large; with url, asset, bbox, maxCloud, cellSize and resampling below, and "start", "end"), "variable"?, "index"?, "crs"?: a Zarr variable's (as for zarr.reduce), "asset"?: the collection's band, such as NDVI, "assets"?: [2–16 of the collection's bands, such as ["B04", "B03", "B02"]] (instead of asset, for mean, median, first or firstDate: one layer a group with a band for each, drawn as RGB when three (firstDate: one band, the date all of them were taken at); a cell goes in at a date only with a value in every band, and median takes each cell's bands from one date, the one whose bands' sum is the middle (the lower of two); items without all of them are left out), "mask"?: {"asset": the items' quality band, such as SCL, Fmask, qa_pixel or CMASK, and one of "keep": [classes] | "drop": [classes] | "bits": {"set"?: [bits on], "unset"?: [bits off]} (bits 0–63)} (a collection's: a cell is taken at a date only where the same item's quality band lets it through, read onto the band's grid by nearest neighbour; items without it are left out), "bbox"?: [w, s, e, n] | "view" (the collection's area), "maxCloud"?: a collection's cloud cover cap, "cellSize"?: a collection's cell size in the files' units (the overview level nearest it is read; a GeoTIFF in strips without one near it takes it with "resampling": "average"), "resampling"?: "nearest" (default) | "average" (as for cube.trend), "band"?: 1-based (a stack's band), "dates"?: [dates] (a stack's or the bands' dates, in their order; default: read from the layers' names or files, or the bands' names), "stat": "mean"|"median"|"min"|"max"|"sum"|"std" (the population standard deviation, n)|"count"|"countAbove"|"first" (the value at the cell's first date with one, in "order": the best pixel)|"firstDate" (the date of the value first takes, as days since 1970-01-01, its legend the dates)|"mode" or "majority" (a categorical cube's most frequent class; the least of those tied)|"modeCount" (how many dates had the mode)|"variety" (how many classes)|"changes" (how many times the class changed from one valued date to the next)|"longestRun" (the class of the longest run of dates in one class; the least of those tied)|"longestRunLength" (how many dates that run lasted)|"frequency" (a layer for each class met: its count of dates)|"countIn" (how many dates in the classes given), "order"?: first's and firstDate's order of the dates: "clear" (the default with a mask: by the share of the area the mask lets through, the clearest first) | "date" (the default without one: the earliest first) | "-date" (the latest first), "above"?: number (countAbove's threshold), "classes"?: [whole numbers 0–255, at most 256] (countIn's classes), "by"?: "all" (default: one layer) | "year" (a layer for each calendar year) | "month" (a layer for each month of the year, across years), "start"?, "end"?: dates (as for cube.trend), "months"?: [1–12] (a season across years), "minValid"?: 0–1 (a cell with a smaller share of its group's dates is left empty; default 0), "name"?: text, "anonymous"?: bool (read without any saved login, S3 connection or implicit credentials)} → raster layers of the statistic, one for each group (frequency: one for each class of each group)"#, )] } @@ -203,9 +203,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..608053e63d 100644 --- a/crates/engine/src/cmd/earthdata.rs +++ b/crates/engine/src/cmd/earthdata.rs @@ -14,9 +14,9 @@ pub fn commands() -> Vec { vec![ C::new("earthdata.collections", "Search NASA Earthdata Collections", "Home › Add › Web Data › NASA Earthaccess", collections).roles(&[]).effects(crate::policy::Effects::NONE.with(crate::policy::Effect::Network)) .view() - .params(r#"{"keyword"?: text (free text: "sea surface temperature"), "shortName"?: "a collection's short name (HLSL30, ATL08, GEDI02_A…)", "cloudHosted"?: bool (only collections in NASA's cloud), "limit"?: 1–100 (20), "page"?: number (1), "answer"?: "CMR's JSON answer, when already fetched (the app's background request)"} — keyword or shortName is needed; searching needs no Earthdata Login"#), + .params(r#"{"keyword"?: text (free text: "sea surface temperature"), "shortName"?: "a collection's short name (HLSL30, ATL08, GEDI02_A…)", "cloudHosted"?: bool (only collections in NASA's cloud), "limit"?: 1–100 (20), "page"?: number (1), "answer"?: "CMR's JSON answer, when already fetched (the app's background request)", "anonymous"?: bool (read without any saved login, S3 connection or implicit credentials)} — keyword or shortName is needed; searching needs no Earthdata Login"#), C::new("earthdata.granules", "Search NASA Earthdata Granules", "Home › Add › Web Data › NASA Earthaccess", granules).roles(&[]).effects(crate::policy::Effects::NONE.with(crate::policy::Effect::Network)).params( - r#"{"collection"?: "a collection's concept id (C…-PROVIDER, as earthdata.collections lists it)", "shortName"?: "or a short name: its cloud-hosted, newest version", "bbox"?: [west, south, east, north] | "view" (the map's extent, the default), "view"?: bool (false: everywhere), "start"?: "YYYY-MM-DD", "end"?: "YYYY-MM-DD", "limit"?: 1–100 (25), "page"?: number (1), "footprints"?: bool (adds the granules' footprints as a layer, default true), "name"?: text (the footprints layer's), "answer"?: "CMR's JSON answer, when already fetched"} — each granule lists its data files; add a GeoTIFF with layer.addUrl (files need an Earthdata Login token: earthdata.login)"#, + r#"{"collection"?: "a collection's concept id (C…-PROVIDER, as earthdata.collections lists it)", "shortName"?: "or a short name: its cloud-hosted, newest version", "bbox"?: [west, south, east, north] | "view" (the map's extent, the default), "view"?: bool (false: everywhere), "start"?: "YYYY-MM-DD", "end"?: "YYYY-MM-DD", "limit"?: 1–100 (25), "page"?: number (1), "footprints"?: bool (adds the granules' footprints as a layer, default true), "name"?: text (the footprints layer's), "answer"?: "CMR's JSON answer, when already fetched", "anonymous"?: bool (read without any saved login, S3 connection or implicit credentials)} — each granule lists its data files; add a GeoTIFF with layer.addUrl (files need an Earthdata Login token: earthdata.login)"#, ), C::new("earthdata.login", "Earthdata Login Token", "Home › Add › Web Data › NASA Earthaccess", login).roles(&[]).effects(crate::policy::Effects::NONE.with(crate::policy::Effect::Reserved)).view().params( r#"{"token": "an Earthdata Login token (Earthdata Login › Generate Token)", "remember"?: bool (false: kept for the session only; true: also remembered on this computer, in the system's credential store, and read back when next needed; without it a token remembered before is deleted)} — never in the project; sent only to NASA's Earthdata data hosts (https://*.earthdatacloud.nasa.gov, *.earthdata.nasa.gov) when their files are read; an expired token is forgotten"#, @@ -24,14 +24,27 @@ 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. + // 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() { + 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() - .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"), ] } @@ -92,26 +105,28 @@ 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 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::>()})) } /// 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}")) } /// 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)?.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. @@ -122,7 +137,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)?; + 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) { @@ -138,19 +154,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/embeddings.rs b/crates/engine/src/cmd/embeddings.rs index 8868c8ecd9..d90b386715 100644 --- a/crates/engine/src/cmd/embeddings.rs +++ b/crates/engine/src/cmd/embeddings.rs @@ -824,6 +824,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. @@ -864,14 +868,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}")); @@ -1001,9 +1009,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/gp.rs b/crates/engine/src/cmd/gp.rs index 474c845b60..3d5181bc1a 100644 --- a/crates/engine/src/cmd/gp.rs +++ b/crates/engine/src/cmd/gp.rs @@ -2470,7 +2470,9 @@ 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); - self.file_within(file_name, |limit| crate::render::raster_export::export_within(raster, min_zoom, max_zoom, opacity, limit)) + self.file_within(file_name, |limit| { + crate::render::raster_export::export_within(raster, layer.anonymous, min_zoom, max_zoom, opacity, limit) + }) } 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/layer.rs b/crates/engine/src/cmd/layer.rs index 325d2fd627..c5b908de2d 100644 --- a/crates/engine/src/cmd/layer.rs +++ b/crates/engine/src/cmd/layer.rs @@ -5375,8 +5375,10 @@ fn add_url_as_given(s: &mut Session, p: &Value) -> CmdResult { return add_url_rows(s, p, url, public); } #[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)?; @@ -5417,6 +5419,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 @@ -5464,7 +5469,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) => {} @@ -5513,6 +5518,7 @@ 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); @@ -5522,7 +5528,7 @@ fn add_url_as_given(s: &mut Session, p: &Value) -> CmdResult { let (_, mut look) = crate::render::rustgis_tiles::cog::split(url); look.cube |= super::b(p, "cube") == Some(true); let asked = crate::render::rustgis_tiles::cog::with_look(url, &look); - let cog = match crate::render::rustgis_tiles::cog::probe_blocking(&asked) { + let cog = match crate::render::rustgis_tiles::cog::probe_blocking(&crate::service_logins::fetch_url(anonymous, &asked)) { Ok(cog) => cog, Err(_) if unnamed => false, Err(e) => return Err(named(e)), @@ -5532,17 +5538,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); @@ -5669,7 +5675,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(); @@ -5678,12 +5684,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)?; @@ -5733,7 +5740,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 @@ -5759,11 +5768,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) { @@ -5936,7 +5946,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 { @@ -5948,10 +5958,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. @@ -6161,16 +6174,17 @@ pub(crate) fn add_cog_with(s: &mut Session, p: &Value, url: &str, strict: bool, } // 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(); } @@ -6192,19 +6206,26 @@ pub(crate) fn add_cog_with(s: &mut Session, p: &Value, url: &str, strict: bool, crate::render::rustgis_tiles::cog::forget_dropped(&dated); Ok(false) } else { - crate::render::rustgis_tiles::cog::probe_blocking(&dated) + 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); @@ -6298,6 +6319,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, @@ -6306,6 +6328,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. @@ -6316,26 +6339,38 @@ 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).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; - 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 }; 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. #[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; @@ -6517,6 +6552,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"))] @@ -6566,7 +6603,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 @@ -6596,7 +6638,8 @@ 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 asked = window_settled(s, p, url, None)?; + let read = read_cog_window(&asked)?; add_window(s, p, read) } @@ -6630,14 +6673,16 @@ 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(); // A file in strips too (#2592): a strip is a tile as wide as the image. - let info = cog::window_info_until(url, stop).map_err(named)?; + let info = cog::window_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) { @@ -6822,7 +6867,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_stepped_blocking(&info, url, level, batch, (c0, c1), (r0, r1), step, wait, stop).map_err(named)? + cog::read_bands_stepped_blocking(&info, fetch, level, batch, (c0, c1), (r0, r1), step, wait, stop).map_err(named)? { bands.push(values); rounded.push(changed); @@ -6904,9 +6949,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/cmd/plugin_fetch.rs b/crates/engine/src/cmd/plugin_fetch.rs index 6fa0d45784..8f12728d39 100644 --- a/crates/engine/src/cmd/plugin_fetch.rs +++ b/crates/engine/src/cmd/plugin_fetch.rs @@ -221,7 +221,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. @@ -238,15 +238,72 @@ impl Session { } } +/// The most web address strings accepted in one plugin command's parameters. +const MAX_ADDRESS_SCAN_ADDRESSES: usize = 4096; + +/// 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`). -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, 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> = Vec::new(); + let mut elements = 0usize; + for (key, v) in o { + if matches!(key.as_str(), "data" | "text") { + 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)")); + } + 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) => { + 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))); + } + _ => {} + } + } + Ok(out) } /// Whether `v` is a web address the app fetches (`http://`, `https://` or `s3://`), as given or @@ -1825,4 +1882,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/plugins.rs b/crates/engine/src/cmd/plugins.rs index e140bc4ccd..40a6089860 100644 --- a/crates/engine/src/cmd/plugins.rs +++ b/crates/engine/src/cmd/plugins.rs @@ -730,14 +730,25 @@ 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); - 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)); + // 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 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| { @@ -749,14 +760,17 @@ impl Bridge<'_> { let incident = rustgis_data::incident::caught(payload.as_ref()); Err(rustgis_data::incident::message(label, false, &incident.id)) }); - 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(((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(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 0095db6dc1..51f02109c2 100644 --- a/crates/engine/src/cmd/service.rs +++ b/crates/engine/src/cmd/service.rs @@ -32,16 +32,16 @@ const DOCUMENT_ROLES: &[crate::ParamRole] = &[ pub fn commands() -> Vec { let mut commands = vec![ C::new("service.layers", "Service Layers", "Home › Add", layers).roles(&[]).effects(crate::policy::Effects::NONE.with(crate::policy::Effect::Network)).view().params( - r#"{"url": "a WMS, WMTS or WFS address (GetCapabilities is added), an OGC API collections address or landing page (its dataset tiles, supported styles and linked collections), or an ArcGIS FeatureServer, MapServer, ImageServer or VectorTileServer, or an ArcGIS services directory or folder (its folders and services, each listed by its own url)", "type"?: "wms"|"wmts"|"wfs"|"ogcapi"|"arcgis" (guessed from the address), "text"?: "the capabilities document, when already fetched", "documents"?: [{"url": "a discovered document address", "text": "its fetched JSON"}], "connection"?: "the saved web-service connection id whose login the requests use", "filter"?: "words a layer's title or name must all contain, in any case: every layer read is searched, not only those a listing shows, and the first 2000 that match are listed; what a listing says in a notice, a search says only in its notes"} → layers with source_url (with filter, total: the layers read, and matched: how many match), and next when supplied documents need another fetch"#, + r#"{"url": "a WMS, WMTS or WFS address (GetCapabilities is added), an OGC API collections address or landing page (its dataset tiles, supported styles and linked collections), or an ArcGIS FeatureServer, MapServer, ImageServer or VectorTileServer, or an ArcGIS services directory or folder (its folders and services, each listed by its own url)", "type"?: "wms"|"wmts"|"wfs"|"ogcapi"|"arcgis" (guessed from the address), "text"?: "the capabilities document, when already fetched", "documents"?: [{"url": "a discovered document address", "text": "its fetched JSON"}], "connection"?: "the saved web-service connection id whose login the requests use", "filter"?: "words a layer's title or name must all contain, in any case: every layer read is searched, not only those a listing shows, and the first 2000 that match are listed; what a listing says in a notice, a search says only in its notes", "anonymous"?: bool (read without any saved login, S3 connection or implicit credentials)} → layers with source_url (with filter, total: the layers read, and matched: how many match), and next when supplied documents need another fetch"#, ), C::new("service.add", "Add Service Layer", "Home › Add", add).roles(&[]).effects(crate::policy::Effects::NONE.with(crate::policy::Effect::Network)).params( - r#"{"url": "as service.layers", "type"?, "layer": "the layer's name (service.layers lists them)", "name"?: text, "time"?: "a time-enabled WMS or WMTS layer: by default (or \"slider\", true) it follows the time slider, turned on with the layer's times when it is off; or one of its dates (2024-06-01), or \"default\" (false): its service's default", "text"?: "the capabilities document, when already fetched", "documents"?: "additional fetched documents, as service.layers", "source_url"?: "the listed layer's source_url", "describe"?: "a WCS coverage's DescribeCoverage document, when already fetched", "tiles"?: "an OGC API layer's tile template, when already read from its tileset (the app's)", "bbox"?: [west, south, east, north] | "view" | "full": a WCS coverage's area (the view by default); for a WFS, OGC API or ArcGIS feature layer, only the features that cross it (the whole layer, "full", by default), "where"?: "an ArcGIS feature layer's SQL where clause (1=1 when absent); combined with bbox and kept by every page; rejected clauses give an error", "connection"?: "the id of the saved web-service connection it comes from (connection.browse gives it): the layer records it, and is read with its login"}"#, + r#"{"url": "as service.layers", "type"?, "layer": "the layer's name (service.layers lists them)", "name"?: text, "time"?: "a time-enabled WMS or WMTS layer: by default (or \"slider\", true) it follows the time slider, turned on with the layer's times when it is off; or one of its dates (2024-06-01), or \"default\" (false): its service's default", "text"?: "the capabilities document, when already fetched", "documents"?: "additional fetched documents, as service.layers", "source_url"?: "the listed layer's source_url", "describe"?: "a WCS coverage's DescribeCoverage document, when already fetched", "tiles"?: "an OGC API layer's tile template, when already read from its tileset (the app's)", "bbox"?: [west, south, east, north] | "view" | "full": a WCS coverage's area (the view by default); for a WFS, OGC API or ArcGIS feature layer, only the features that cross it (the whole layer, "full", by default), "where"?: "an ArcGIS feature layer's SQL where clause (1=1 when absent); combined with bbox and kept by every page; rejected clauses give an error", "connection"?: "the id of the saved web-service connection it comes from (connection.browse gives it): the layer records it, and is read with its login", "anonymous"?: bool (read without any saved login, S3 connection or implicit credentials)}"#, ), C::new("service.coverage", "WCS Coverage Request", "Home › Add", coverage).roles(&[]).effects(crate::policy::Effects::NONE.with(crate::policy::Effect::Network)).view().params( r#"{"url": "a WCS address", "type"?: "wcs", "layer": "the coverage's name", "text"?: "the capabilities document, when already fetched", "documents"?: "additional fetched documents, as service.layers", "source_url"?: "the listed coverage's source_url", "describe"?: "its DescribeCoverage answer, when already fetched", "bbox"?: [west, south, east, north] | "view" (the default) | "full", "connection"?: "the saved web-service connection id whose login the request uses", "anonymous"?: boolean (never use a saved login for the coverage or its description)} → the GetCoverage address of a GeoTIFF (layer.addUrl adds it), its area in longitude/latitude, and "coverageCrs": the coverage's own system when it is asked in it (as layer.addUrl takes it, for an answer that doesn't say its system)"#, ), C::new("catalog.search", "Search Catalogue", "Home › Add", catalog_search).roles(&[]).effects(crate::policy::Effects::NONE.with(crate::policy::Effect::Network)).view().params( - r#"{"url": "a catalogue's CSW address", "query"?: "words anywhere in the records", "bbox"?: [west, south, east, north] | "view" (none by default; one across the antimeridian isn't asked for, which a note says), "start"?: "the first record's position (a page's next)", "bboxCrs"?: "CRS84" | "none" (how the area's coordinate system is named to the catalogue; by default CRS84, and none when the catalogue answers that with an exception to a request RustGIS makes (a supplied text isn't asked again); the answer's bboxCrs says which was read, to give with its next page), "text"?: "the GetRecords answer, when already fetched", "connection"?: "as service.layers"} → records with their service and download links (service.add or layer.addUrl add them; a link with "fromDocument": true came from a catalogue read from the internet: give layer.addUrl that too)"#, + r#"{"url": "a catalogue's CSW address", "query"?: "words anywhere in the records", "bbox"?: [west, south, east, north] | "view" (none by default; one across the antimeridian isn't asked for, which a note says), "start"?: "the first record's position (a page's next)", "bboxCrs"?: "CRS84" | "none" (how the area's coordinate system is named to the catalogue; by default CRS84, and none when the catalogue answers that with an exception to a request RustGIS makes (a supplied text isn't asked again); the answer's bboxCrs says which was read, to give with its next page), "text"?: "the GetRecords answer, when already fetched", "connection"?: "as service.layers", "anonymous"?: bool (read without any saved login, S3 connection or implicit credentials)} → records with their service and download links (service.add or layer.addUrl add them; a link with "fromDocument": true came from a catalogue read from the internet: give layer.addUrl that too)"#, ), ]; commands.extend(group::commands()); @@ -245,7 +245,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 @@ -551,6 +558,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(); } } @@ -637,10 +647,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); @@ -845,10 +857,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())) }) @@ -997,7 +1010,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 } } @@ -1434,7 +1447,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); } @@ -1573,7 +1588,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 => { @@ -1613,7 +1631,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); @@ -1645,7 +1664,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); @@ -1754,7 +1773,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. @@ -1800,9 +1819,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, &[], @@ -1817,7 +1837,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)) } @@ -1972,6 +1992,7 @@ 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 mut named = area_named(p)?.unwrap_or(true); let mut notes = Vec::new(); let parse = |request: &str, bytes: &[u8]| { @@ -1983,7 +2004,7 @@ pub(super) fn catalog_search_read(s: &mut Session, p: &Value, read: Option { - let (bytes, reach) = fetch_records(url, &request, within)?; + let (bytes, reach) = fetch_records(url, &request, within, anonymous)?; match records_again(s, p, &bytes) { None => { let page = parse(&request, &bytes)?; @@ -1992,7 +2013,7 @@ pub(super) fn catalog_search_read(s: &mut Session, p: &Value, read: Option { let request = records_request(s, &again)?; let within = within.min(cache::ceiling_for(&request)); - let (page, reach) = fetch_records(url, &request, within) + let (page, reach) = fetch_records(url, &request, within, anonymous) .and_then(|(bytes, reach)| Ok((parse(&request, &bytes)?, reach))) .map_err(|second| refused_again(&refused, &second))?; named = false; @@ -2052,8 +2073,9 @@ pub(super) fn catalog_search_read(s: &mut Session, p: &Value, read: Option Result<(Vec, 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<(Vec, 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 reach = fetched.origin.reach(); @@ -2061,7 +2083,7 @@ fn fetch_records(url: &str, request: &str, ceiling: Reach) -> Result<(Vec, R } #[cfg(target_arch = "wasm32")] -fn fetch_records(url: &str, _: &str, _: Reach) -> Result<(Vec, Reach), String> { +fn fetch_records(url: &str, _: &str, _: Reach, _: bool) -> Result<(Vec, 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 5a60a50b3d..0f37465308 100644 --- a/crates/engine/src/cmd/stac.rs +++ b/crates/engine/src/cmd/stac.rs @@ -13,17 +13,17 @@ pub fn commands() -> Vec { vec![ C::new("stac.collections", "List STAC Collections", "Home › Add › Web Data › STAC Search", collections).roles(&[]).effects(crate::policy::Effects::NONE.with(crate::policy::Effect::Network)) .view() - .params(r#"{"url"?: "a STAC API (default: Earth Search, https://earth-search.aws.element84.com/v1; Planetary Computer: https://planetarycomputer.microsoft.com/api/stac/v1), or a static catalog's catalog.json or collection.json (its child catalogs and collections are listed)", "connection"?: "as service.add: the saved web-service connection whose login the request uses"}"#), + .params(r#"{"url"?: "a STAC API (default: Earth Search, https://earth-search.aws.element84.com/v1; Planetary Computer: https://planetarycomputer.microsoft.com/api/stac/v1), or a static catalog's catalog.json or collection.json (its child catalogs and collections are listed)", "connection"?: "as service.add: the saved web-service connection whose login the request uses", "anonymous"?: bool (read without any saved login, S3 connection or implicit credentials)}"#), C::new("stac.search", "STAC Search", "Home › Add › Web Data › STAC Search", search).roles(&[]).effects(crate::policy::Effects::NONE.with(crate::policy::Effect::Network)).params( - r#"{"url"?: "a STAC API (default: Earth Search), or a static catalog's catalog.json or collection.json (walked from there, at most 400 documents)", "collections"?: id | [ids] (APIs), "bbox"?: [west, south, east, north] | "view" (the map's extent), "intersects"?: GeoJSON (a geometry, a feature or a collection of features, as stac.area returns) | "selection" (the selected features of "layer"): the search area, which replaces bbox; only the highest dimension present is kept (polygons, then lines, then points) and what is left out is reported, "layer"?: the layer (name or id) whose selection "selection" uses (default the active layer), "buffer"?: the distance to widen an intersects point or line into a polygon (default 0), "unit"?: "Meters" | "Feet" | "Kilometers" | "Miles" (the buffer's unit, default Meters), "datetime"?: "2024-06-01" | "2024-06-01/2024-06-30", "limit"?: 1–200 (default 10), "maxCloud"?: percent, "sortby"?: "eo:cloud_cover" | "-datetime" (APIs that sort), "phase"?: "pre" | "post" (static catalogs of events), "properties"?: bool (every property of each item, not only its date and cloud cover; default false), "footprints"?: bool (adds the items' footprints as a layer, default true), "connection"?: "as service.add: the saved web-service connection whose login the request uses"}"#, + r#"{"url"?: "a STAC API (default: Earth Search), or a static catalog's catalog.json or collection.json (walked from there, at most 400 documents)", "collections"?: id | [ids] (APIs), "bbox"?: [west, south, east, north] | "view" (the map's extent), "intersects"?: GeoJSON (a geometry, a feature or a collection of features, as stac.area returns) | "selection" (the selected features of "layer"): the search area, which replaces bbox; only the highest dimension present is kept (polygons, then lines, then points) and what is left out is reported, "layer"?: the layer (name or id) whose selection "selection" uses (default the active layer), "buffer"?: the distance to widen an intersects point or line into a polygon (default 0), "unit"?: "Meters" | "Feet" | "Kilometers" | "Miles" (the buffer's unit, default Meters), "datetime"?: "2024-06-01" | "2024-06-01/2024-06-30", "limit"?: 1–200 (default 10), "maxCloud"?: percent, "sortby"?: "eo:cloud_cover" | "-datetime" (APIs that sort), "phase"?: "pre" | "post" (static catalogs of events), "properties"?: bool (every property of each item, not only its date and cloud cover; default false), "footprints"?: bool (adds the items' footprints as a layer, default true), "connection"?: "as service.add: the saved web-service connection whose login the request uses", "anonymous"?: bool (read without any saved login, S3 connection or implicit credentials)}"#, ), C::new("stac.addFootprints", "Add STAC Footprints", "Home › Add › Web Data › STAC Search", add_footprints_cmd).roles(&[]).effects(crate::policy::Effects::NONE) .params(r#"{"footprints": GeoJSON FeatureCollection (items' footprints, as STAC Search finds them), "name"?: text}"#), C::new("stac.addCube", "Add STAC Data Cube", "Home › Add › Web Data › STAC Search", add_cube).roles(&[]).effects(crate::policy::Effects::NONE.with(crate::policy::Effect::Network)).params( - r#"{"url"?: a STAC API (default: Earth Search), or the collection.json of a static collection laid out by date (JAXA Earth's), "collection": id, "asset": key (a band, such as NDVI), "bbox"?: [west, south, east, north] | "view" (default: the map's extent), "start", "end": dates, "maxCloud"?: percent, "range"?: [low, high] (the values shown from black to white, in the asset's own units after its raster:bands scale and offset, the same for every date and tile; default: each file's 2nd–98th percentile) | "auto" (one range for every date and tile, the 2nd–98th percentiles of a sample: the newest file of up to four tiles, read at an overview), "name"?: text, "attribution"?: text, at most 500 characters (the credit its tile layers show, as in tiles.add), "connection"?: "as service.add: the saved web-service connection whose login the request uses"} → a tile layer per tile of the grid the items cover, each a file per date following the time slider, which turns on over their dates when it is off (desktop)"#, + r#"{"url"?: a STAC API (default: Earth Search), or the collection.json of a static collection laid out by date (JAXA Earth's), "collection": id, "asset": key (a band, such as NDVI), "bbox"?: [west, south, east, north] | "view" (default: the map's extent), "start", "end": dates, "maxCloud"?: percent, "range"?: [low, high] (the values shown from black to white, in the asset's own units after its raster:bands scale and offset, the same for every date and tile; default: each file's 2nd–98th percentile) | "auto" (one range for every date and tile, the 2nd–98th percentiles of a sample: the newest file of up to four tiles, read at an overview), "name"?: text, "attribution"?: text, at most 500 characters (the credit its tile layers show, as in tiles.add), "connection"?: "as service.add: the saved web-service connection whose login the request uses", "anonymous"?: bool (read without any saved login, S3 connection or implicit credentials)} → a tile layer per tile of the grid the items cover, each a file per date following the time slider, which turns on over their dates when it is off (desktop)"#, ), C::new("stac.addAsset", "Add STAC Asset", "Home › Add › Web Data › STAC Search", add_asset).roles(&[]).effects(crate::policy::Effects::NONE.with(crate::policy::Effect::Network)).params( - r#"{"item": a STAC item (as stac.search returns it) | "url": an item's address (Planetary Computer assets are signed), "asset"?: key (default: visual, else the first GeoTIFF, else the first data asset), "name"?: text, "connection"?: "as service.add"}"#, + r#"{"item": a STAC item (as stac.search returns it) | "url": an item's address (Planetary Computer assets are signed), "asset"?: key (default: visual, else the first GeoTIFF, else the first data asset), "name"?: text, "connection"?: "as service.add", "anonymous"?: bool (read without any saved login, S3 connection or implicit credentials)}"#, ), ] } @@ -129,8 +129,9 @@ 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)?; - collections_json_from_origin(s, &api, &fetched.bytes, &fetched.origin) + 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.without_anonymous()) } } @@ -209,24 +210,26 @@ 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; - 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 { @@ -319,7 +322,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()); @@ -349,7 +353,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,19 +362,21 @@ 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) } } /// 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) } @@ -378,7 +384,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. @@ -395,6 +401,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!( @@ -531,7 +540,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}")); @@ -570,7 +580,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() { @@ -1708,6 +1719,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 { @@ -1723,7 +1735,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])) @@ -1794,7 +1806,11 @@ fn add_cube(s: &mut Session, p: &Value) -> CmdResult { .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); @@ -1938,6 +1954,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(); @@ -1945,7 +1962,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 = values_header(href)?; + let fetch_href = crate::service_logins::fetch_url(anonymous, href); + let info = values_header(&fetch_href)?; let l = &info.layout; if l.palette.is_some() { return Ok(Sample::Classes); @@ -1956,7 +1974,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)); @@ -2115,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/cmd/stac_bands.rs b/crates/engine/src/cmd/stac_bands.rs index e086a1a199..057654b661 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, mut notes) = read_and_stack(&name, &wanted, &picked, &hrefs, bbox, cell)?; + let (stacked, mut notes) = read_and_stack(&name, &wanted, &picked, &hrefs, bbox, cell, anonymous)?; let (band, past) = rustgis_analysis::rasterops::band_math_reported(&stacked, &expr)?; notes.extend(rustgis_analysis::rasterops::past_f32_note(past).map(|note| Note::loss(LossCode::DroppedValue, note))); // An index with no value anywhere (every cell 0 / 0, say) is no result: an error, not an empty layer. @@ -305,7 +309,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(); @@ -318,7 +328,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); @@ -481,6 +491,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. @@ -494,7 +505,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(); @@ -968,7 +979,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"); } @@ -1110,7 +1122,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/cmd/tiles.rs b/crates/engine/src/cmd/tiles.rs index 4539de577a..fef80bc372 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( - 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.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", "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)"#), - 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 @@ -749,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/cmd/zarr.rs b/crates/engine/src/cmd/zarr.rs index f507d5ef2f..9bd827b1a2 100644 --- a/crates/engine/src/cmd/zarr.rs +++ b/crates/engine/src/cmd/zarr.rs @@ -22,15 +22,15 @@ pub fn commands() -> Vec { vec![ C::new("raster.zarrInfo", "Zarr Variables", "Home › Add › Add Data › Zarr", info).roles(&[]).effects(crate::policy::Effects::NONE.with(crate::policy::Effect::Network).with(crate::policy::Effect::Files)) .view() - .params(r#"{"path": "a Zarr store's folder" | "url": "https://… a store (one with no consolidated metadata needs variable)", "bbox"?: [west, south, east, north] (in the grid's coordinates: the window of cells it is in a variable's grid, for layer.addZarr's cells), "variable"?: (its path in the store: with bbox, or for a store with no consolidated metadata; default the first)} → variables with their dimensions, chunks and shards' chunks (innerChunks)"#), + .params(r#"{"path": "a Zarr store's folder" | "url": "https://… a store (one with no consolidated metadata needs variable)", "bbox"?: [west, south, east, north] (in the grid's coordinates: the window of cells it is in a variable's grid, for layer.addZarr's cells), "variable"?: (its path in the store: with bbox, or for a store with no consolidated metadata; default the first), "anonymous"?: bool (read without any saved login, S3 connection or implicit credentials)} → variables with their dimensions, chunks and shards' chunks (innerChunks)"#), C::new("zarr.series", "Time Series at a Point", "View › Time Series", series).roles(&[]).effects(crate::policy::Effects::NONE.with(crate::policy::Effect::Network).with(crate::policy::Effect::Files)).view().params( - r#"{"lon", "lat", "layer"? (a Zarr layer: its store, variable and steps; default the active layer) | "path": folder | "url": "https://…", "variable"?, "index"?: {"level": 0} (the other dimensions' steps), "start"?, "end"?: dates (default: the layer's period, else the whole axis), "crs"?: for a projected store that doesn't say} → dates, values (null for no data) and labels along the variable's time dimension at the cell holding the point (desktop)"#, + r#"{"lon", "lat", "layer"? (a Zarr layer: its store, variable and steps; default the active layer) | "path": folder | "url": "https://…", "variable"?, "index"?: {"level": 0} (the other dimensions' steps), "start"?, "end"?: dates (default: the layer's period, else the whole axis), "crs"?: for a projected store that doesn't say, "anonymous"?: bool (read without any saved login, S3 connection or implicit credentials)} → dates, values (null for no data) and labels along the variable's time dimension at the cell holding the point (desktop)"#, ), C::new("zarr.reduce", "Summarise Zarr Over Time", "View › Time Series", reduce).roles(&[]).effects(crate::policy::Effects::NONE.with(crate::policy::Effect::Network).with(crate::policy::Effect::Files)).params( - r#"{"layer"? (a Zarr layer: its store, variable and steps; default the active layer) | "path": folder | "url": "https://…", "variable"?, "index"?, "stat": "mean"|"min"|"max"|"sum"|"std" (the population standard deviation, n)|"count"|"countAbove", "above"?: number (countAbove's threshold), "start"?, "end"?: dates (default: the layer's period, else the whole axis), "months"?: [1–12] (a season across years: [12, 1, 2]), "minValid"?: 0–1 (a cell with a smaller share of values is left empty; default 0), "name"?: text, "crs"?} → a raster layer of the statistic (desktop)"#, + r#"{"layer"? (a Zarr layer: its store, variable and steps; default the active layer) | "path": folder | "url": "https://…", "variable"?, "index"?, "stat": "mean"|"min"|"max"|"sum"|"std" (the population standard deviation, n)|"count"|"countAbove", "above"?: number (countAbove's threshold), "start"?, "end"?: dates (default: the layer's period, else the whole axis), "months"?: [1–12] (a season across years: [12, 1, 2]), "minValid"?: 0–1 (a cell with a smaller share of values is left empty; default 0), "name"?: text, "crs"?, "anonymous"?: bool (read without any saved login, S3 connection or implicit credentials)} → a raster layer of the statistic (desktop)"#, ), C::new("layer.addZarr", "Add Zarr Variable", "Home › Add › Add Data", add).roles(&[]).effects(crate::policy::Effects::NONE.with(crate::policy::Effect::Network).with(crate::policy::Effect::Files)).params( - r#"{"path": folder | "url": "https://…", "variable"?: "its path in the store (default: the first)", "index"?: {"time": 3, "level": 0} (other dimensions' steps, default 0), "cells"?: [first column, first row, end column, end row] (a window of the map's cells as stored, the ends not included, at least 2 × 2: only the chunks it touches are read, and in shards only their chunks it needs, by range) | "bbox"?: [west, south, east, north] (a window by the grid's coordinates: degrees for a longitude/latitude grid; its coordinates are read to place it), "crs"?: "EPSG:… for a store that doesn't say", "name"?: text, "time"?: bool (follow the time slider: the layer shows the step the slider is at, and turns the slider on over the variable's dates when it is off; with cells or bbox, each step reads only that window; desktop), "start"?, "end"?: dates (with time: the period to take, for an axis longer than the slider's 20,000 steps), "ran"?: (internal: a slice the app has read), "summary"?: bool (internal: with ran, a summary over time rather than a slice)}"#, + r#"{"path": folder | "url": "https://…", "variable"?: "its path in the store (default: the first)", "index"?: {"time": 3, "level": 0} (other dimensions' steps, default 0), "cells"?: [first column, first row, end column, end row] (a window of the map's cells as stored, the ends not included, at least 2 × 2: only the chunks it touches are read, and in shards only their chunks it needs, by range) | "bbox"?: [west, south, east, north] (a window by the grid's coordinates: degrees for a longitude/latitude grid; its coordinates are read to place it), "crs"?: "EPSG:… for a store that doesn't say", "name"?: text, "time"?: bool (follow the time slider: the layer shows the step the slider is at, and turns the slider on over the variable's dates when it is off; with cells or bbox, each step reads only that window; desktop), "start"?, "end"?: dates (with time: the period to take, for an axis longer than the slider's 20,000 steps), "ran"?: (internal: a slice the app has read), "summary"?: bool (internal: with ran, a summary over time rather than a slice), "anonymous"?: bool (read without any saved login, S3 connection or implicit credentials)}"#, ), ] } @@ -85,13 +85,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() @@ -103,18 +103,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)) @@ -122,7 +122,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); @@ -151,7 +151,8 @@ fn fetch_items(root: &str, keys: &[(String, String)]) -> Result<(HashMap { let len = b.len() as u64; @@ -231,7 +232,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(()); @@ -260,7 +261,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:?}"); } @@ -273,8 +274,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 @@ -282,9 +283,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)")); @@ -304,7 +305,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() { @@ -337,15 +338,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() || 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)? { // Cells are given to layer.addZarr, which checks them against the grid; here only a @@ -355,7 +357,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}); } @@ -365,7 +367,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}"))?; @@ -390,8 +392,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)) } @@ -458,7 +460,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()), @@ -467,7 +475,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. @@ -536,7 +544,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); @@ -563,11 +571,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() || 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)?; + 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, @@ -589,7 +598,17 @@ 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; + if let Some(rl) = l.raster.as_mut() { + rl.anonymous = true; + } + } + Ok(out) } } } @@ -622,25 +641,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); } @@ -670,6 +691,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)) @@ -693,11 +721,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() { @@ -739,7 +767,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() { @@ -787,17 +815,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)?; @@ -806,7 +840,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( @@ -879,7 +914,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), 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]) { @@ -936,7 +971,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(&zt, i, slice_key(&zt, i))?; + // 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(); @@ -956,16 +992,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) @@ -973,7 +1010,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 @@ -984,7 +1021,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 @@ -1012,6 +1049,7 @@ struct PendingRead { zt: ZarrTime, step: usize, key: String, + anonymous: bool, still: Option, capture: rustgis_data::diagnostics::Capture, started: std::sync::atomic::AtomicBool, @@ -1021,11 +1059,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), @@ -1055,7 +1094,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(|payload| Err(crate::bug(&format!("{}: reading step {}", self.zt.store, self.step), payload.as_ref()))) }) } @@ -1179,6 +1218,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(); @@ -1191,6 +1231,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); @@ -1206,7 +1247,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, 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)); @@ -1215,7 +1256,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)) => { @@ -1226,17 +1267,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) { + 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) => { @@ -1266,8 +1307,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)); + 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")] @@ -1294,6 +1335,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() || 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}"))?; @@ -1319,15 +1361,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)", @@ -1392,7 +1437,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(); @@ -1402,7 +1448,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()); @@ -1437,6 +1484,15 @@ 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; + 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 { s.warn(w.clone()); @@ -1461,6 +1517,7 @@ struct SeriesSource { period: Option<(u64, usize)>, crs: Option, read_generation: u64, + anonymous: bool, } #[cfg(not(target_arch = "wasm32"))] @@ -1477,6 +1534,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. @@ -1492,20 +1550,28 @@ 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 /// 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 @@ -1515,6 +1581,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) { @@ -1524,7 +1591,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"))); @@ -1570,6 +1637,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(); @@ -1577,7 +1645,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"))); } @@ -1634,6 +1702,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, @@ -1682,7 +1751,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))?) }; @@ -1690,7 +1759,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. @@ -1757,13 +1826,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. @@ -1802,7 +1871,8 @@ pub fn series_start(s: &Session, p: &Value) -> Result { } }; let (start, end) = (date("start")?, date("end")?); - Ok(SeriesRun { lon, lat, src, start, end }) + 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) ---------------------------------------------------- @@ -1821,6 +1891,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, @@ -1853,9 +1924,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). @@ -1936,7 +2007,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); @@ -1956,7 +2027,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 @@ -1965,12 +2036,14 @@ 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 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!( @@ -1979,13 +2052,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)" @@ -2015,7 +2088,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/lib.rs b/crates/engine/src/lib.rs index 18464859e9..6e3542cb10 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -3290,7 +3290,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/peer.rs b/crates/engine/src/peer.rs index 4e68eaf299..d223173f14 100644 --- a/crates/engine/src/peer.rs +++ b/crates/engine/src/peer.rs @@ -391,6 +391,10 @@ fn reopen(p: &mut Project, at: &At) -> Vec<(&'static str, String)> { } } 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/policy/decide.rs b/crates/engine/src/policy/decide.rs index f575241da1..c63aa22148 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,22 @@ 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. 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, + "pg.tables" + | "pg.addLayer" + | "pg.discardEdits" + | "info.databaseTables" + | "layer.addDatabase" + | "sql.query" + | "sql.schema" + | "layer.addSql" + ) +} 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/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.rs b/crates/engine/src/project.rs index 19fb1676ab..4672136783 100644 --- a/crates/engine/src/project.rs +++ b/crates/engine/src/project.rs @@ -1807,6 +1807,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() @@ -2206,7 +2211,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/project_log.rs b/crates/engine/src/project_log.rs index 837c6779d3..88ebe87452 100644 --- a/crates/engine/src/project_log.rs +++ b/crates/engine/src/project_log.rs @@ -75,13 +75,15 @@ 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, 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; } @@ -125,13 +127,19 @@ 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() { + // 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.to_string() + e }; crate::cmd::history::redacted_text(&sql_secrets_removed(&e)) } @@ -199,7 +207,74 @@ 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, false) +} + +/// 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)) +} + +/// 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. +/// +/// `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 { + 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() => { + 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( + 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 => { + 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(200usize.saturating_add(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.clone(), + } } /// A bounded log-only context check for a short key beside nested connection settings. @@ -241,7 +316,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 => { @@ -471,46 +546,48 @@ fn is_base64(t: &str) -> bool { && body.bytes().all(|b| b.is_ascii_alphanumeric() || matches!(b, b'+' | b'/' | b'=' | b'-' | b'_' | b'\n' | b'\r')) } +/// Whether `t` is a document given as text (a map, a project, GeoJSON), which [`clip`] keeps as +/// its size only. A byte-order mark before it is still a document's start. +fn is_document(t: &str) -> bool { + t.trim_start_matches('\u{feff}').trim_start().starts_with(['{', '[', '<']) && t.chars().nth(DOCUMENT_CHARS).is_some() +} + /// `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 { - // A byte-order mark before it is still a document's start. - Value::String(t) - if t.trim_start_matches('\u{feff}').trim_start().starts_with(['{', '[', '<']) && t.chars().nth(DOCUMENT_CHARS).is_some() => - { - Value::String(format!("(a document of {} characters)", t.chars().count())) - } + 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()))); } 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 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) - } - }; - 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/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/s3_connections.rs b/crates/engine/src/s3_connections.rs index 7ab237ca16..11cf926ecc 100644 --- a/crates/engine/src/s3_connections.rs +++ b/crates/engine/src/s3_connections.rs @@ -393,7 +393,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/service_logins.rs b/crates/engine/src/service_logins.rs index 1ff37b8e4e..f3f2f83621 100644 --- a/crates/engine/src/service_logins.rs +++ b/crates/engine/src/service_logins.rs @@ -939,6 +939,14 @@ 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::anonymous_once(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") { @@ -948,8 +956,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)); } @@ -1496,6 +1511,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.rs b/crates/engine/src/tests.rs index f2d5e5152e..3ee2ef6070 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -28784,6 +28784,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 @@ -38617,6 +38618,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"))] diff --git a/crates/engine/src/tests/engine_guards.rs b/crates/engine/src/tests/engine_guards.rs index 6fc47bbcea..d440b56ca4 100644 --- a/crates/engine/src/tests/engine_guards.rs +++ b/crates/engine/src/tests/engine_guards.rs @@ -487,8 +487,9 @@ fn non_user_scopes_cannot_consume_internal_ran_handoffs() { let sql_p = json!({"sql": "SELECT 1", "ran": sql_id}); let err = s.run_scoped(agent, &Call::command("layer.addSql", sql_p.clone())).unwrap_err(); assert!(err.contains("reserved for the app"), "layer.addSql agent: {err}"); + // A plugin is refused SQL before the handoff is looked at. let err = forward(&mut s, plug_id, "layer.addSql", sql_p).unwrap_err(); - assert!(err.contains("reserved for the app"), "layer.addSql plugin: {err}"); + assert!(err.contains("plugins can't access databases or run SQL"), "layer.addSql plugin: {err}"); assert!(s.sql_results.iter().any(|(k, ..)| *k == sql_id), "sql_results entry must remain intact"); rustgis_plugins::unload(plug_id); diff --git a/crates/engine/src/tests/scopes_and_redaction.rs b/crates/engine/src/tests/scopes_and_redaction.rs index ce9d9ea921..091577cf47 100644 --- a/crates/engine/src/tests/scopes_and_redaction.rs +++ b/crates/engine/src/tests/scopes_and_redaction.rs @@ -806,3 +806,753 @@ 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 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 = 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"); + 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 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")})); + }) + .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}"); + } + 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| { + 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}" + ); + } + + // 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}" + ); + } + } + + // 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}" + ); + } + } + + // 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. + { + 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}); + 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 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"})); +} + +#[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", "legend": "https://tiles.example.org/orig.png"}), + ) + .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_eq!(s.map().tiles[0].legends.len(), 1); + assert_eq!(s.map().tiles[0].legends[0].url, "https://tiles.example.org/orig.png"); + + // 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"); +} + +#[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); + + // 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, + "plug-net-nested", + "map.setTiles", + 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}"); + + // 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(); + 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}"); + + // 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")); + 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}"); + // 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)); + 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}"); + + // Failed command errors recorded in the session log must also scrub active logins and wrappers. + 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}"); + 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); + 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}"); + 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"); +} + +/// 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. +#[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. +#[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() { + 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"); +} diff --git a/crates/engine/src/tests/service_logins.rs b/crates/engine/src/tests/service_logins.rs index 847ff4519e..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()))); @@ -2410,6 +2426,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(); diff --git a/crates/map/src/raster.rs b/crates/map/src/raster.rs index c7965e30b9..824b173953 100644 --- a/crates/map/src/raster.rs +++ b/crates/map/src/raster.rs @@ -115,6 +115,10 @@ pub struct RasterLayer { /// a new allocation, breaks the pairing. #[serde(skip)] written: Option<(Weak, Weak>)>, + /// 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. @@ -350,6 +354,7 @@ impl RasterLayer { look_lost: None, dropped: Vec::new(), written: None, + anonymous: false, }) } @@ -401,6 +406,7 @@ impl RasterLayer { look_lost: None, dropped: Vec::new(), written: None, + anonymous: false, } } @@ -458,6 +464,7 @@ impl RasterLayer { look_lost: None, dropped: Vec::new(), written: None, + anonymous: false, } } @@ -503,6 +510,27 @@ impl RasterLayer { look_lost: None, dropped: Vec::new(), written: None, + 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()?; + // 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)) } } @@ -561,8 +589,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(); @@ -688,6 +717,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(); @@ -697,7 +727,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 { @@ -935,6 +965,7 @@ impl RasterLayer { look_lost: _, dropped: _, written: _, + anonymous: _, } = self; if *in_place || *tiled || opening.is_some() || read_still.is_some() || self.casts_shadows() { return None; @@ -2793,6 +2824,7 @@ impl RasterLayer { look_lost: _, dropped: _, written: _, + anonymous: _, } = self; let mut out = Vec::new(); if let Some(p) = path { @@ -4084,4 +4116,20 @@ 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")); + + // 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/render/src/lib.rs b/crates/render/src/lib.rs index 17d6fb1eac..8fd38fabc5 100644 --- a/crates/render/src/lib.rs +++ b/crates/render/src/lib.rs @@ -5442,8 +5442,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_once(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 a60cf2fcd0..a9f2c8eea1 100644 --- a/crates/render/src/raster_export.rs +++ b/crates/render/src/raster_export.rs @@ -26,12 +26,21 @@ 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_within(layer, min_zoom, max_zoom, opacity, &Limit::none()) + export_within(layer, layer.anonymous, min_zoom, max_zoom, opacity, &Limit::none()) } /// [`export`] with the archive held to `limit`: no tile is drawn after the one that passes it -/// ([`Limit::passed`] then says so). -pub fn export_within(layer: &RasterLayer, min_zoom: u8, max_zoom: u8, opacity: f32, limit: &Limit) -> Result, String> { +/// ([`Limit::passed`] then says so). `anonymous` also honors 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_within( + layer: &RasterLayer, + anonymous: bool, + min_zoom: u8, + max_zoom: u8, + opacity: f32, + limit: &Limit, +) -> Result, String> { if min_zoom > max_zoom || max_zoom > 16 { return Err("zoom range must satisfy 0 <= minZoom <= maxZoom <= 16".into()); } @@ -101,7 +110,14 @@ pub fn export_within(layer: &RasterLayer, min_zoom: u8, max_zoom: u8, opacity: f 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()) { + 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_once(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) => { 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/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 { diff --git a/crates/tiles/src/s3.rs b/crates/tiles/src/s3.rs index 48ed8a0acd..801788096c 100644 --- a/crates/tiles/src/s3.rs +++ b/crates/tiles/src/s3.rs @@ -417,6 +417,20 @@ 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, 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 || 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. pub fn split_anonymous(url: &str) -> (&str, bool) { match url.strip_prefix(ANONYMOUS) { @@ -1160,6 +1174,21 @@ 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 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 /// 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 adc8e8ffac..e966c4ccf8 100644 --- a/crates/tiles/src/stac/catalog.rs +++ b/crates/tiles/src/stac/catalog.rs @@ -543,6 +543,22 @@ 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) +} + +/// 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 { let mut w = Walk::new(root, filter, limit); loop { // A few documents at a time, each on its own thread. @@ -552,14 +568,15 @@ 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_once(&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), &[], ceiling, ); - (u, r) + (u, plain_origin(r)) }; let answers: Vec<(String, Result)> = std::thread::scope(|s| { let handles: Vec<_> = urls @@ -608,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")); diff --git a/crates/tiles/src/stac/dated.rs b/crates/tiles/src/stac/dated.rs index 2a89f59230..8b92b1f78f 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_once(u) } else { u.to_string() }; + crate::cache::download_blocking(&fetch_u) + }) } #[cfg(test)]