From d351897c967e3811a1073a10ceebba7a446c5a1d Mon Sep 17 00:00:00 2001 From: giswqs Date: Wed, 25 Nov 2026 09:14:26 -0500 Subject: [PATCH 1/9] fix(tiles,map,data,engine,cli): harden path validation, auth transport checks, and credential scrubbing Tighten local path validation for PMTiles, MBTiles, local GeoTIFFs, and QGIS picture annotations; align native auth HTTP clients and endpoint checks with the shared transport policy; and broaden query and trace credential redaction. - Reject mixed-slash double-separator prefixes and Windows drive-relative paths in local archive and COG path checks, while preserving standard Unix, Windows drive, and file:/// paths. - Share local image source validation across QGIS raster markers, picture annotations, and engine annotation import before touching the filesystem. - Disable ambient proxy use and enforce CheckedResolver and address reach checks in native ArcGIS token, ArcGIS OAuth, and Copernicus clients, and reject backslash or encoded slash separators in ArcGIS token scope matching. - Normalize percent-encoded password query keys and run query redaction for MySQL/MariaDB and SQL Server connection strings. - Redact source addresses and errors before logging tile source refresh failures, and redact CLI assistant trace entries while creating new trace files with mode 0600 on Unix. --- apps/rustgis-cli/src/main.rs | 95 ++++++++++++++++++++++++-- crates/data/src/source/msconn.rs | 4 +- crates/data/src/source/myconn.rs | 23 ++++++- crates/engine/src/cmd/qgis.rs | 95 +++++++++++++++++++++----- crates/engine/src/tests.rs | 25 +++++-- crates/map/src/qgis/annotation.rs | 9 ++- crates/map/src/qgis/mod.rs | 2 +- crates/map/src/qgis/source.rs | 34 +++++++++ crates/map/src/qgis/symbol.rs | 21 ++---- crates/map/src/qgis/tests.rs | 31 +++++++++ crates/tiles/src/arcgis_auth.rs | 26 +++++-- crates/tiles/src/arcgis_auth/tests.rs | 21 ++++-- crates/tiles/src/arcgis_token.rs | 18 +++-- crates/tiles/src/arcgis_token/tests.rs | 8 +++ crates/tiles/src/cache.rs | 7 ++ crates/tiles/src/cog.rs | 12 +++- crates/tiles/src/copernicus.rs | 15 +++- crates/tiles/src/mbtiles.rs | 30 +++++--- crates/tiles/src/pmtiles.rs | 78 ++++++++++++++++++--- crates/tiles/src/source.rs | 29 +++++++- 20 files changed, 494 insertions(+), 89 deletions(-) diff --git a/apps/rustgis-cli/src/main.rs b/apps/rustgis-cli/src/main.rs index 8587a9e391..44852a2585 100644 --- a/apps/rustgis-cli/src/main.rs +++ b/apps/rustgis-cli/src/main.rs @@ -554,6 +554,7 @@ fn ask(s: &mut Session, args: &[String], saved: Option<&Saved>, env: &Environmen let pictures = ask_pictures(args)?; eprintln!("[{} · {}]", cfg.provider, cfg.model); let yes = args.iter().any(|a| a == "--yes"); + let trace_key = cfg.key.clone(); let mut a = Agent::new(cfg, s); a.set_skills(rustgis_assistant::skills::installed()); let mut shown = 0; @@ -577,13 +578,8 @@ fn ask(s: &mut Session, args: &[String], saved: Option<&Saved>, env: &Environmen let send = |req: &rustgis_assistant::HttpRequest| { let r = transport(req); if let Some(path) = &trace { - let resp = match &r { - Ok(r) => format!("HTTP {}\n{}", r.status, String::from_utf8_lossy(&r.body)), - Err(e) => e.to_string(), - }; - let entry = format!("> {} {}\n{}\n< {resp}\n\n", req.method, req.url, req.body.as_deref().unwrap_or("")); - let written = std::fs::OpenOptions::new().create(true).append(true).open(path).and_then(|mut f| f.write_all(entry.as_bytes())); - if let Err(e) = written { + let entry = format_trace_entry(req, &r, &trace_key); + if let Err(e) = append_trace(path, &entry) { eprintln!("rustgis-cli: {}: {e}", path.display()); } } @@ -606,6 +602,41 @@ fn ask(s: &mut Session, args: &[String], saved: Option<&Saved>, env: &Environmen Ok(()) } +/// Scrubs active service login values and the assistant's own API key from trace text. +fn mask_trace_secrets(text: &str, key: &str) -> String { + let scrubbed = rustgis_engine::render::rustgis_tiles::logins::scrub(text); + if key.is_empty() { scrubbed } else { scrubbed.replace(key, "[redacted]") } +} + +/// Formats a `--trace` entry for an assistant request and its response, redacting URL +/// credentials, secret fields, active service logins, and the configured API key. +fn format_trace_entry( + req: &rustgis_assistant::HttpRequest, + resp: &Result, + key: &str, +) -> String { + let url = mask_trace_secrets(&rustgis_engine::sources::redact(&req.url), key); + let body = mask_trace_secrets(&rustgis_engine::data::diagnostics::redact_parameter(req.body.as_deref().unwrap_or("")), key); + let answer = match resp { + Ok(r) => format!( + "HTTP {}\n{}", + r.status, + mask_trace_secrets(&rustgis_engine::data::diagnostics::redact_parameter(&String::from_utf8_lossy(&r.body)), key) + ), + Err(e) => mask_trace_secrets(&rustgis_engine::data::diagnostics::redact(&e.to_string()), key), + }; + format!("> {} {url}\n{body}\n< {answer}\n\n", req.method) +} + +/// Appends `entry` to the `--trace` file, restricting new files to owner-only permissions on Unix. +fn append_trace(path: &std::path::Path, entry: &str) -> std::io::Result<()> { + let mut options = std::fs::OpenOptions::new(); + options.create(true).append(true); + #[cfg(unix)] + std::os::unix::fs::OpenOptionsExt::mode(&mut options, 0o600); + options.open(path)?.write_all(entry.as_bytes()) +} + /// `--attach [PORT]` as `mcp` takes it: the port that follows when it isn't another flag, else /// the app's default. fn attach_port(args: &[String]) -> Result, String> { @@ -1309,4 +1340,54 @@ mod tests { } assert!(store.accounts().is_empty(), "asked for {:?}", store.accounts()); } + + #[test] + fn trace_entry_scrubs_secrets_and_urls() { + let origin = "https://trace-login.example.test"; + let binding = rustgis_engine::render::rustgis_tiles::logins::activate( + origin, + "trace", + rustgis_engine::render::rustgis_tiles::logins::Method::Header("X-Key".into()), + "active-login-secret-999", + false, + ) + .unwrap(); + let req = rustgis_assistant::HttpRequest { + method: "POST", + url: "https://user:urlpw@api.example.test/v1/chat?key=sk-test-key-12345&model=m".into(), + headers: Vec::new(), + body: Some(r#"{"prompt":"check postgres://dbu:dbpw@db.example/gis and sk-test-key-12345 and active-login-secret-999"}"#.into()), + }; + let resp: Result<_, &str> = Ok(rustgis_assistant::HttpResponse { + status: 400, + headers: Vec::new(), + body: br#"{"error":"invalid key sk-test-key-12345 at https://u:respw@api.example.test?token=resptok"}"#.to_vec(), + }); + let entry = format_trace_entry(&req, &resp, "sk-test-key-12345"); + let err_entry = format_trace_entry( + &req, + &Err("failed calling https://u:errpw@api.example.test?api_key=errkey with sk-test-key-12345 and active-login-secret-999"), + "sk-test-key-12345", + ); + assert!(rustgis_engine::render::rustgis_tiles::logins::deactivate(&binding)); + for secret in ["urlpw", "sk-test-key-12345", "dbpw", "respw", "resptok", "active-login-secret-999"] { + assert!(!entry.contains(secret), "leaked {secret} in: {entry}"); + } + assert!(entry.contains("HTTP 400") && entry.contains("\"prompt\""), "{entry}"); + for secret in ["urlpw", "sk-test-key-12345", "errpw", "errkey", "active-login-secret-999"] { + assert!(!err_entry.contains(secret), "leaked {secret} in: {err_entry}"); + } + } + + #[cfg(unix)] + #[test] + fn trace_file_uses_private_permissions() { + use std::os::unix::fs::PermissionsExt; + let path = std::env::temp_dir().join(format!("rustgis-cli-trace-mode-{}.txt", std::process::id())); + let _ = std::fs::remove_file(&path); + append_trace(&path, "entry\n").unwrap(); + let mode = std::fs::metadata(&path).unwrap().permissions().mode() & 0o777; + let _ = std::fs::remove_file(&path); + assert_eq!(mode, 0o600, "expected 0600, got {mode:o}"); + } } diff --git a/crates/data/src/source/msconn.rs b/crates/data/src/source/msconn.rs index 053819c990..df3015eec8 100644 --- a/crates/data/src/source/msconn.rs +++ b/crates/data/src/source/msconn.rs @@ -17,7 +17,7 @@ pub fn split_password(s: &str) -> Option<(String, Option)> { let (_, query) = public.split_once('?')?; query.split('&').find_map(|kv| { let (key, value) = kv.split_once('=')?; - (key.eq_ignore_ascii_case("pwd") || key.eq_ignore_ascii_case("passwd")).then(|| super::pgconn::percent_decode(value)) + matches!(crate::address::normalized_name(key).as_deref(), Some("pwd" | "passwd")).then(|| super::pgconn::percent_decode(value)) }) }); super::credentials::redact_query(&mut public); @@ -59,6 +59,8 @@ mod tests { ("pwd=ignored&password=chosen", "chosen"), ("passwd=ignored&pass=chosen", "chosen"), ("pwd=&passwd=second", ""), + ("pw%64=encoded-pwd", "encoded-pwd"), + ("pass%77d=encoded-passwd", "encoded-passwd"), ] { let (public, password) = split_password(&format!("mssql://sa@h/gis?{query}&encrypt=strict")).unwrap(); assert_eq!(password.as_deref(), Some(expected), "{query}"); diff --git a/crates/data/src/source/myconn.rs b/crates/data/src/source/myconn.rs index 6b2aac79fd..70148c4c71 100644 --- a/crates/data/src/source/myconn.rs +++ b/crates/data/src/source/myconn.rs @@ -15,7 +15,9 @@ pub fn split_password(s: &str) -> Option<(String, Option)> { if !is_address(t) { return None; } - split_userinfo_password(t) + let (mut public, password) = split_userinfo_password(t)?; + super::credentials::redact_query(&mut public); + Some((public, password)) } /// Removes user-info and query passwords without restricting the address's scheme. @@ -64,7 +66,7 @@ fn query_without_password(s: &str) -> (String, Option) { let mut kept = Vec::new(); for kv in query.split('&').filter(|kv| !kv.is_empty()) { let (k, v) = kv.split_once('=').unwrap_or((kv, "")); - if k.eq_ignore_ascii_case("password") || k.eq_ignore_ascii_case("pass") { + if matches!(crate::address::normalized_name(k).as_deref(), Some("password" | "pass")) { password = Some(super::pgconn::percent_decode(v)); } else { kept.push(kv); @@ -113,4 +115,21 @@ mod tests { assert_eq!(database_name("mysql://h"), None); assert_eq!(database_name("mysql://h/"), None); } + + #[test] + fn encoded_password_and_secret_query_params_are_stripped() { + let s = |a: &str| split_password(a).unwrap_or_else(|| panic!("{a}")); + assert_eq!( + s("mysql://me@h/gis?pass%77ord=sec%26ret&ssl-mode=REQUIRED"), + ("mysql://me@h/gis?ssl-mode=REQUIRED".into(), Some("sec&ret".into())) + ); + assert_eq!( + s("mariadb://me@h/gis?pa%73s=pw123&ssl-mode=REQUIRED"), + ("mariadb://me@h/gis?ssl-mode=REQUIRED".into(), Some("pw123".into())) + ); + for key in ["token", "access_token", "client_secret", "api_key", "pwd"] { + let (public, _) = s(&format!("mysql://me@h/gis?{key}=secret&ssl-mode=REQUIRED")); + assert_eq!(public, "mysql://me@h/gis?ssl-mode=REQUIRED", "{key}"); + } + } } diff --git a/crates/engine/src/cmd/qgis.rs b/crates/engine/src/cmd/qgis.rs index 93a66af867..54a4fe8b1a 100644 --- a/crates/engine/src/cmd/qgis.rs +++ b/crates/engine/src/cmd/qgis.rs @@ -993,24 +993,29 @@ fn add_annotations( Some(Ok(b64)) if b64.len() > left => None, Some(read) => Some(read.clone()), None => { - // Its size first, from its text or its file's length (base64 is 4 bytes for 3): - // one that can't fit isn't read. - let size = match picture.strip_prefix("base64:") { - Some(b64) => Some(b64.trim().len()), - None => std::fs::metadata(picture) - .ok() - .map(|m| usize::try_from(m.len()).unwrap_or(usize::MAX).div_ceil(3).saturating_mul(4)), - }; - let read = if !has_dir && picture.strip_prefix("base64:").is_none() && qgis::is_relative(picture) { - Err(format!("{picture}, relative to the project's folder, which the import wasn't given (pass dir)")) - } else if size.is_some_and(|size| size > left) { - pictures.over.insert(picture.clone()); - over += 1; - continue; - } else if let Some(b64) = picture.strip_prefix("base64:") { - super::graphics::picture(&json!({"image": b64})) - } else { - super::graphics::picture(&json!({"path": picture})) + let read = match qgis::local_image_source(picture, if has_dir { "/" } else { "" }) { + Err(why) => Err(format!("{picture}: {why}")), + Ok(source) => { + // Its size first, from its text or its file's length (base64 is 4 bytes for 3): + // one that can't fit isn't read. + let size = match &source { + qgis::ImageSource::Base64 => Some(picture.strip_prefix("base64:").unwrap_or_default().trim().len()), + qgis::ImageSource::File(_) => std::fs::metadata(picture) + .ok() + .map(|m| usize::try_from(m.len()).unwrap_or(usize::MAX).div_ceil(3).saturating_mul(4)), + }; + if size.is_some_and(|size| size > left) { + pictures.over.insert(picture.clone()); + over += 1; + continue; + } + match source { + qgis::ImageSource::Base64 => { + super::graphics::picture(&json!({"image": picture.strip_prefix("base64:").unwrap_or_default()})) + } + qgis::ImageSource::File(_) => super::graphics::picture(&json!({"path": picture})), + } + } }; if read.as_ref().is_ok_and(|b64| b64.len() > left) { pictures.over.insert(picture.clone()); @@ -2100,3 +2105,57 @@ fn import_style(s: &mut Session, p: &Value) -> CmdResult { notify_report(s, &report); Ok(json!({"notes": report.notes.iter().map(note_json).collect::>()})) } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn add_annotations_refuses_unsafe_picture_paths_defensively() { + let mut s = Session::new(crate::Project::default()); + let rect = rustgis_data::Geometry::Polygon(vec![vec![vec![ + rustgis_geom::Coord::new(0.0, 0.0), + rustgis_geom::Coord::new(1.0, 0.0), + rustgis_geom::Coord::new(1.0, 1.0), + rustgis_geom::Coord::new(0.0, 1.0), + rustgis_geom::Coord::new(0.0, 0.0), + ]]]); + let layer = qgis::ProjectLayer { + id: "a".into(), + name: "Direct".into(), + provider: String::new(), + kind: "annotation".into(), + vector: false, + visible: true, + checked: true, + group: None, + definition_query: None, + crs: Some("EPSG:4326".into()), + source: qgis::Source::Other { provider: String::new() }, + style: qgis::Style::default(), + annotations: vec![ + qgis::Annotation { + graphic: rustgis_map::graphics::Graphic::new("picture", rect.clone()), + picture: Some(r"\\server\share\a.png".into()), + keep_aspect: false, + }, + qgis::Annotation { + graphic: rustgis_map::graphics::Graphic::new("picture", rect.clone()), + picture: Some(r"/\server\share\b.png".into()), + keep_aspect: false, + }, + qgis::Annotation { + graphic: rustgis_map::graphics::Graphic::new("picture", rect), + picture: Some("C:rel.png".into()), + keep_aspect: false, + }, + ], + }; + let mut pictures = Pictures::default(); + let mut report = Report::default(); + add_annotations(&mut s, &layer, Some("EPSG:4326"), None, true, &mut pictures, &mut report).unwrap(); + let added = s.map().layer_by_name("Direct").unwrap(); + assert!(added.dataset.features.is_empty()); + assert!(report.notes.iter().any(|n| n.text.contains("network share")), "{:?}", report.notes); + } +} diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index a0c70f2c78..2ae2941048 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -3898,17 +3898,28 @@ fn qgis_annotation_layers_import_as_graphics_layers() { // Given as text with no folder: the relative picture is noted, the rest comes in. let text = std::fs::read_to_string(&path).unwrap(); let r = s.run("project.importQgis", &json!({"text": text})).unwrap(); - assert!( - notes(&r) - .iter() - .any(|n| n.starts_with("a picture annotation's picture, which doesn't read (the first: ../data/picture.png, relative")), - "{:?}", - notes(&r) - ); + assert!(notes(&r).iter().any(|n| n.contains("relative to a folder the import wasn't given")), "{:?}", notes(&r)); let l = s.map().layer_by_name("styled annotations").unwrap(); assert!((0..l.dataset.features.len()).all(|r| rustgis_map::graphics::kind(&l.dataset, r) != "picture")); let texts = (0..l.dataset.features.len()).filter(|r| rustgis_map::graphics::label(&l.dataset, *r).is_some()).count(); assert_eq!(texts, 8, "the texts come in all the same"); + + // Unsafe picture annotation paths (network shares, drive-relative, web URLs, attachments) are skipped. + let unsafe_qgs = r#"EPSG:4326 + aUnsafe + + + + + + "#; + let r = s.run("project.importQgis", &json!({"text": unsafe_qgs, "dir": "/tmp"})).unwrap(); + let l = s.map().layer_by_name("Unsafe").unwrap(); + assert!(l.dataset.features.is_empty()); + assert!(notes(&r).iter().any(|n| n.contains("network share")), "{:?}", notes(&r)); + assert!(notes(&r).iter().any(|n| n.contains("drive's working folder")), "{:?}", notes(&r)); + assert!(notes(&r).iter().any(|n| n.contains("web address")), "{:?}", notes(&r)); + assert!(notes(&r).iter().any(|n| n.contains(".qgz project")), "{:?}", notes(&r)); } /// A QGIS style's raster image markers draw their PNG or JPEG file, read from the style's folder; diff --git a/crates/map/src/qgis/annotation.rs b/crates/map/src/qgis/annotation.rs index dfae9b1397..4dc59dcd78 100644 --- a/crates/map/src/qgis/annotation.rs +++ b/crates/map/src/qgis/annotation.rs @@ -487,10 +487,17 @@ fn boxed(item: Node, kind: &str, dir: &str, layer: &str, read: &mut Reading, rep read.no_picture += 1; return Vec::new(); } + let picture = match super::source::local_image_source(path, dir) { + Ok(super::source::ImageSource::Base64) => path.to_string(), + Ok(super::source::ImageSource::File(p)) => p, + Err(why) => { + report.skipped(layer, format!("picture annotations {why}")); + return Vec::new(); + } + }; if fixed { read.pictures_fixed += 1; } - let picture = if path.starts_with("base64:") { path.to_string() } else { super::source::absolute(path, dir) }; out.extend(background.map(wrap)); let g = Graphic::new("picture", rect()); out.push(Annotation { graphic: g, picture: Some(picture), keep_aspect: item.attribute("lockAspect") != Some("0") }); diff --git a/crates/map/src/qgis/mod.rs b/crates/map/src/qgis/mod.rs index 954983afad..115f1cb234 100644 --- a/crates/map/src/qgis/mod.rs +++ b/crates/map/src/qgis/mod.rs @@ -31,7 +31,7 @@ use crate::effects::Blend; use crate::symbology::{Labeling, LineStroke, MarkerRotation, Picture, Renderer}; pub use annotation::{Annotation, MAX_ITEMS as MAX_ANNOTATIONS}; pub use expr::{reads_measure, to_sql}; -pub use source::{MAX_MEMORY_FIELDS, Source, VirtualFrom, WebOptions, is_drive_relative, is_relative}; +pub use source::{ImageSource, MAX_MEMORY_FIELDS, Source, VirtualFrom, WebOptions, is_drive_relative, is_relative, local_image_source}; pub use structure::{MAX_BOOKMARKS, MAX_RELATIONS, ProjectBookmark, ProjectRelation, listed}; /// The most XML nodes a project or style is read with (a large project's file is some hundred diff --git a/crates/map/src/qgis/source.rs b/crates/map/src/qgis/source.rs index 6cdea893db..33d9e8983b 100644 --- a/crates/map/src/qgis/source.rs +++ b/crates/map/src/qgis/source.rs @@ -1019,6 +1019,40 @@ pub fn is_drive_relative(path: &str) -> bool { b.get(1) == Some(&b':') && b.first().is_some_and(u8::is_ascii_alphabetic) && !matches!(b.get(2), Some(b'/' | b'\\')) } +/// Where a QGIS image (a raster image marker or a picture annotation) comes from. +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum ImageSource { + /// Embedded inline (`base64:…`). + Base64, + /// A local file path, resolved from the project's folder when relative. + File(String), +} + +/// Checks a QGIS image path (`imageFile` or picture annotation `path`) against `dir` (empty when +/// the import has no project folder). Rejects `.qgz` attachments, web addresses, network shares +/// (`\\host\share`, `//host/share`, `/\host\share`, `\/host/share`), drive-relative paths +/// (`C:foo.png`), and relative paths without a folder. +pub fn local_image_source(file: &str, dir: &str) -> Result { + let file = file.trim(); + if file.starts_with("base64:") { + Ok(ImageSource::Base64) + } else if file.get(..11).is_some_and(|p| p.eq_ignore_ascii_case("attachment:")) { + Err("whose image is kept inside the .qgz project, which RustGIS doesn't read it from") + } else if file.contains("://") { + Err("whose image is at a web address, which RustGIS doesn't fetch") + } else if file.len() > 1 && file.chars().take(2).all(|c| c == '\\' || c == '/') { + // Looking a share up can sign in to the host the file names, which a style or + // project chose (as an archive on one isn't opened either). + Err("whose image is on a network share, which RustGIS doesn't open") + } else if is_drive_relative(file) { + Err("whose image file is relative to a drive's working folder, which no project folder tells") + } else if is_relative(file) && dir.is_empty() { + Err("whose image file is relative to a folder the import wasn't given") + } else { + Ok(ImageSource::File(absolute(file, dir))) + } +} + /// Whether `path` is relative to the project's folder: not absolute (`/…`, `\…`, `C:\…`), not /// on a drive (`C:…`, see [`is_drive_relative`]) and not a web address. pub fn is_relative(path: &str) -> bool { diff --git a/crates/map/src/qgis/symbol.rs b/crates/map/src/qgis/symbol.rs index f9de955686..3f1af6a28e 100644 --- a/crates/map/src/qgis/symbol.rs +++ b/crates/map/src/qgis/symbol.rs @@ -910,23 +910,10 @@ pub(super) fn read_images(root: Node, dir: &str, read: &mut ReadImage, report: & if report.images.contains_key(file) { continue; } - let source = if file.starts_with("base64:") { - Ok(None) - } else if file.starts_with("attachment:") { - Err("whose image is kept inside the .qgz project, which RustGIS doesn't read it from") - } else if file.contains("://") { - Err("whose image is at a web address, which RustGIS doesn't fetch") - } else if file.len() > 1 && file.chars().take(2).all(|c| c == '\\' || c == '/') { - // Looking a share up can sign in to the host the file names, which a style or - // project chose (as an archive on one isn't opened either). - Err("whose image is on a network share, which RustGIS doesn't open") - } else if super::is_drive_relative(file) { - Err("whose image file is relative to a drive's working folder, which no project folder tells") - } else if super::is_relative(file) && dir.is_empty() { - Err("whose image file is relative to a folder the import wasn't given") - } else { - Ok(Some(super::source::absolute(file, dir))) - }; + let source = super::source::local_image_source(file, dir).map(|s| match s { + super::source::ImageSource::Base64 => None, + super::source::ImageSource::File(path) => Some(path), + }); if let Ok(Some(path)) = &source && let Some(got) = files.get(path) { diff --git a/crates/map/src/qgis/tests.rs b/crates/map/src/qgis/tests.rs index b60cc0ef85..08ef4ab376 100644 --- a/crates/map/src/qgis/tests.rs +++ b/crates/map/src/qgis/tests.rs @@ -3347,3 +3347,34 @@ fn a_dropped_virtual_filter_is_not_noted_for_letter_case() { assert!(report.notes.iter().any(|n| n.layer == "v" && n.text.contains("too long to read together")), "{:?}", report.notes); assert_eq!(letter_case_notes(&report, "v"), 0, "{:?}", report.notes); } + +#[test] +fn picture_annotations_reject_unsafe_paths() { + let cases = [ + (r"\\server\share\a.png", "/d", "network share"), + ("//server/share/a.png", "/d", "network share"), + (r"/\server\share\a.png", "/d", "network share"), + (r"\/server/share/a.png", "/d", "network share"), + ("C:relative.png", "/d", "drive's working folder"), + ("https://example.com/a.png", "/d", "web address"), + ("file:///etc/passwd.png", "/d", "web address"), + ("attachment:a.png", "/d", ".qgz project"), + ("relative.png", "", "folder the import wasn't given"), + ]; + for (path, dir, expected_note) in cases { + let qgs = format!( + r#"EPSG:4326 + aPics + + "# + ); + let mut report = Report::default(); + let p = read_project(&qgs, dir, &mut report).unwrap(); + assert!(p.layers[0].annotations.is_empty(), "{path} (dir={dir:?}) produced {:?}", p.layers[0].annotations); + assert!( + report.notes.iter().any(|n| n.layer == "Pics" && n.kind == NoteKind::Skipped && n.text.contains(expected_note)), + "{path}: {:?}", + report.notes + ); + } +} diff --git a/crates/tiles/src/arcgis_auth.rs b/crates/tiles/src/arcgis_auth.rs index dd001e4145..611babe662 100644 --- a/crates/tiles/src/arcgis_auth.rs +++ b/crates/tiles/src/arcgis_auth.rs @@ -93,6 +93,9 @@ pub fn portal_base(input: &str) -> Result { } let (origin, path) = split(raw).ok_or_else(|| rustgis_data::diagnostics::message_with_address(raw, "a portal is given by its https:// address"))?; + if crate::address::reach(&origin) == crate::address::Reach::Forbidden { + return Err(rustgis_data::diagnostics::message_with_address(raw, "that address is never fetched")); + } if origin == "https://arcgis.com" { return Ok(ONLINE.to_string()); } @@ -255,9 +258,13 @@ impl Scope { } fn covers(&self, origin: &str, path: &str) -> bool { - // A path whose dot segments a client would resolve (`/server/../other/`) is judged by + // A path whose dot segments or encoded/backslash separators a client or server would + // resolve (`/server/../other/`, `/server/%2f../other/`, `/server\..\other`) is judged by // where it leads, so it gets no token at all. let lower = path.to_ascii_lowercase(); + if lower.contains('\\') || lower.contains("%5c") || lower.contains("%2f") { + return false; + } if lower.split('/').any(|seg| { let seg = seg.replace("%2e", "."); seg == "." || seg == ".." @@ -269,7 +276,6 @@ impl Scope { if o != origin { return false; } - let lower = path.to_ascii_lowercase(); lower.starts_with(p.as_str()) || format!("{lower}/") == *p } Scope::Org(id) => { @@ -861,15 +867,16 @@ mod native { static READS: OnceLock = OnceLock::new(); (if forms { &FORMS } else { &READS }).get_or_init(|| { // A token request is never redirected: a redirect would replay the code or the refresh token. - ureq::Agent::config_builder() + let config = ureq::Agent::config_builder() .tls_config(rustgis_data::http::tls_config()) .http_status_as_error(!forms) .timeout_global(Some(REQUEST_TIMEOUT)) .user_agent(concat!("RustGIS/", env!("CARGO_PKG_VERSION"), " (+https://rustgis.app)")) + .proxy(None) .max_redirects(0) .max_idle_connections(0) - .build() - .into() + .build(); + crate::cache::checked_local_agent(config) }) } @@ -1144,6 +1151,15 @@ mod native { assert!(!revoked(b"Bad Gateway")); } + #[cfg(test)] + #[test] + fn agent_disables_proxy() { + assert!(agent(true).config().proxy().is_none(), "forms agent must not use an ambient proxy"); + assert!(agent(false).config().proxy().is_none(), "reads agent must not use an ambient proxy"); + let err = agent(true).get("http://169.254.169.254/").call().unwrap_err(); + assert!(matches!(err, ureq::Error::Io(ref io) if io.kind() == std::io::ErrorKind::PermissionDenied), "{err:?}"); + } + /// Sends revocations off the caller's thread, on a best-effort basis. When the system refuses /// a thread, they come back unsent, for the caller to send or to say. pub fn revoke_all(revocations: Vec) -> Result<(), Vec> { diff --git a/crates/tiles/src/arcgis_auth/tests.rs b/crates/tiles/src/arcgis_auth/tests.rs index 1dbba61735..0b368ccc89 100644 --- a/crates/tiles/src/arcgis_auth/tests.rs +++ b/crates/tiles/src/arcgis_auth/tests.rs @@ -86,9 +86,17 @@ fn portal_bases() { assert_eq!(portal_base("https://gis.example.org/portal/sharing/rest?f=json").unwrap(), "https://gis.example.org/portal"); assert_eq!(portal_base("https://gis.example.org:7443/arcgis/home/").unwrap(), "https://gis.example.org:7443/arcgis"); assert_eq!(portal_base("https://gis.example.org:443/portal").unwrap(), "https://gis.example.org/portal"); - // Tokens travel to the portal: never over plain HTTP, never with user info. - for bad in ["http://gis.example.org/portal", "https://user@gis.example.org/portal", "https://", "https://gis.example.org:x/", "ftp://a"] - { + // Tokens travel to the portal: never over plain HTTP, never with user info, never to forbidden addresses. + for bad in [ + "http://gis.example.org/portal", + "https://user@gis.example.org/portal", + "https://", + "https://gis.example.org:x/", + "ftp://a", + "https://169.254.169.254/portal", + "https://100.100.100.200/portal", + "https://metadata.google.internal/portal", + ] { assert!(portal_base(bad).is_err(), "{bad}"); } assert!(is_online("https://myorg.maps.arcgis.com") && is_online(ONLINE) && !is_online("https://gis.example.org/portal")); @@ -191,9 +199,14 @@ fn a_token_in_a_service_address_reaches_its_layers() { bearer ); assert_eq!(authorization("https://tokenserver.example.org/other/rest/services"), None); - // A path leading elsewhere by its dot segments gets none. + // A path leading elsewhere by its dot segments or encoded/backslash separators gets none. assert_eq!(authorization("https://tokenserver.example.org/server/../other/rest/services"), None); assert_eq!(authorization("https://tokenserver.example.org/server/%2E%2E/other/rest/services"), None); + assert_eq!(authorization("https://tokenserver.example.org/server/..%5cother/rest/services"), None); + assert_eq!(authorization("https://tokenserver.example.org/server/..%5Cother/rest/services"), None); + assert_eq!(authorization("https://tokenserver.example.org/server/%2f../other/rest/services"), None); + assert_eq!(authorization("https://tokenserver.example.org/server/%2F../other/rest/services"), None); + assert_eq!(authorization("https://tokenserver.example.org/server\\..\\other/rest/services"), None); assert!(list().iter().any(|i| i.portal == "https://tokenserver.example.org/server" && i.token && i.expires_at.is_none())); // An address without a token is unchanged; a hostile one is refused. assert_eq!( diff --git a/crates/tiles/src/arcgis_token.rs b/crates/tiles/src/arcgis_token.rs index 61a8607b74..bc296e3e7d 100644 --- a/crates/tiles/src/arcgis_token.rs +++ b/crates/tiles/src/arcgis_token.rs @@ -132,6 +132,7 @@ pub fn check_endpoint(endpoint: &str, origin: &str) -> Result<(), &'static str> || !crate::address::is_https(endpoint) || endpoint.contains(['?', '#']) || crate::logins::origin(endpoint).as_deref() != Some(origin) + || crate::address::check(endpoint, None).is_err() { return Err(BAD_ENDPOINT); } @@ -189,7 +190,7 @@ pub fn set_generator(f: impl Fn(String, Secret, Still, Done) + Send + Sync + 'st /// but https:// again. `still` turns false when the request is cancelled: the answer is then /// discarded, and a transport stops as soon as it next looks. pub fn generate(endpoint: String, body: Secret, still: Still, done: Done) { - if !crate::address::is_https(&endpoint) { + if !crate::address::is_https(&endpoint) || crate::address::check(&endpoint, None).is_err() { done(Err(BAD_ENDPOINT.into())); return; } @@ -222,15 +223,16 @@ mod native { /// One agent, made once (its TLS setup reads the system's certificates). It never follows a /// redirect, which would replay the password; keeps no connection; has no cookie jar. static AGENT: LazyLock = LazyLock::new(|| { - ureq::Agent::config_builder() + let config = ureq::Agent::config_builder() .tls_config(rustgis_data::http::tls_config()) .http_status_as_error(false) .timeout_global(Some(Duration::from_secs(DEADLINE_SECS))) .user_agent(concat!("RustGIS/", env!("CARGO_PKG_VERSION"), " (+https://rustgis.app)")) + .proxy(None) .max_redirects(0) .max_idle_connections(0) - .build() - .into() + .build(); + crate::cache::checked_local_agent(config) }); /// Calls `done` once, whichever of the worker and a failed start gets here first. @@ -287,6 +289,14 @@ mod native { check_still(&still).map_err(cancelled)?; from_answer(status, &answer, now_millis()) } + + #[cfg(test)] + #[test] + fn agent_disables_proxy() { + assert!(AGENT.config().proxy().is_none(), "token agent must not use an ambient proxy"); + let err = AGENT.get("http://169.254.169.254/tokens").call().unwrap_err(); + assert!(matches!(err, ureq::Error::Io(ref io) if io.kind() == std::io::ErrorKind::PermissionDenied), "{err:?}"); + } } #[cfg(test)] diff --git a/crates/tiles/src/arcgis_token/tests.rs b/crates/tiles/src/arcgis_token/tests.rs index c6d46f880c..d8bb952edb 100644 --- a/crates/tiles/src/arcgis_token/tests.rs +++ b/crates/tiles/src/arcgis_token/tests.rs @@ -133,6 +133,13 @@ fn arcgis_token_endpoints_stay_on_the_connection_origin() { assert_eq!(check_endpoint(bad, origin), Err(BAD_ENDPOINT), "{bad}"); } assert_eq!(check_endpoint(&format!("https://gis.example.test/{}", "a".repeat(MAX_ENDPOINT)), origin), Err(BAD_ENDPOINT)); + for (endpoint, forbidden_origin) in [ + ("https://169.254.169.254/arcgis/tokens/generateToken", "https://169.254.169.254"), + ("https://100.100.100.200/arcgis/tokens/generateToken", "https://100.100.100.200"), + ("https://metadata.google.internal/arcgis/tokens/generateToken", "https://metadata.google.internal"), + ] { + assert_eq!(check_endpoint(endpoint, forbidden_origin), Err(BAD_ENDPOINT), "{endpoint}"); + } } #[test] @@ -159,6 +166,7 @@ mod native { ureq::Agent::config_builder() .http_status_as_error(false) .timeout_global(Some(Duration::from_secs(10))) + .proxy(None) .max_redirects(0) .max_idle_connections(0) .build() diff --git a/crates/tiles/src/cache.rs b/crates/tiles/src/cache.rs index 0eab06da51..7447f54c9f 100644 --- a/crates/tiles/src/cache.rs +++ b/crates/tiles/src/cache.rs @@ -2555,6 +2555,13 @@ fn premultiply(data: &mut [u8]) { } } +/// Builds a native agent with `config` whose DNS resolver rejects forbidden addresses (such as +/// link-local and cloud metadata endpoints) while still allowing loopback and local-network hosts. +#[cfg(not(target_arch = "wasm32"))] +pub(crate) fn checked_local_agent(config: ureq::config::Config) -> ureq::Agent { + native::checked_agent(config, ureq::unversioned::resolver::DefaultResolver::default(), false) +} + #[cfg(not(target_arch = "wasm32"))] mod native { //! Worker threads fetching with `ureq`, newest request first, a few at a time per server. diff --git a/crates/tiles/src/cog.rs b/crates/tiles/src/cog.rs index 98e788d9ca..bb53878ac6 100644 --- a/crates/tiles/src/cog.rs +++ b/crates/tiles/src/cog.rs @@ -2753,7 +2753,17 @@ mod tests { load(url.clone(), crate::address::Reach::Public, Box::new(move |r| tx.send(r.err()).unwrap())); let refused = rx.recv_timeout(Duration::from_secs(5)).unwrap().unwrap_or_default(); assert!(refused.contains("a file on this computer can't be read from here"), "{refused}"); - for not in ["local.tif", "./local.tif", "//server/share/local.tif", "https://example.com/local.tif", "file:///tmp/local.tif"] { + for not in [ + "local.tif", + "./local.tif", + "//server/share/local.tif", + "\\\\server\\share\\local.tif", + "/\\server\\share\\local.tif", + "\\/server/share/local.tif", + "C:local.tif", + "https://example.com/local.tif", + "file:///tmp/local.tif", + ] { assert!(!is_local_file(not), "{not}"); } assert!(!is_local_file(&dir.join("local.png").display().to_string())); diff --git a/crates/tiles/src/copernicus.rs b/crates/tiles/src/copernicus.rs index a59403384a..63e4086397 100644 --- a/crates/tiles/src/copernicus.rs +++ b/crates/tiles/src/copernicus.rs @@ -644,15 +644,16 @@ mod native { fn agent() -> &'static ureq::Agent { static A: OnceLock = OnceLock::new(); A.get_or_init(|| { - ureq::Agent::config_builder() + let config = ureq::Agent::config_builder() .tls_config(rustgis_data::http::tls_config()) .http_status_as_error(false) .timeout_global(Some(REQUEST_TIMEOUT)) .user_agent(concat!("RustGIS/", env!("CARGO_PKG_VERSION"), " (+https://rustgis.app)")) + .proxy(None) .max_redirects(0) .max_idle_connections(0) - .build() - .into() + .build(); + crate::cache::checked_local_agent(config) }) } @@ -827,6 +828,14 @@ mod native { } super::authorization(url) } + + #[cfg(test)] + #[test] + fn agent_disables_proxy() { + assert!(agent().config().proxy().is_none(), "copernicus agent must not use an ambient proxy"); + let err = agent().get("http://169.254.169.254/").call().unwrap_err(); + assert!(matches!(err, ureq::Error::Io(ref io) if io.kind() == std::io::ErrorKind::PermissionDenied), "{err:?}"); + } } #[cfg(all(test, not(target_arch = "wasm32")))] diff --git a/crates/tiles/src/mbtiles.rs b/crates/tiles/src/mbtiles.rs index 6ae5b87539..7287b33532 100644 --- a/crates/tiles/src/mbtiles.rs +++ b/crates/tiles/src/mbtiles.rs @@ -59,12 +59,7 @@ pub fn check(archive: &str) -> Result<(), String> { Ok(()) }; } - let p = archive.strip_prefix("file://").unwrap_or(archive); - let drive = p.as_bytes().get(1) == Some(&b':') && p.as_bytes().first().is_some_and(u8::is_ascii_alphabetic); - let share = p.starts_with("\\\\") || p.starts_with("//") || (archive.starts_with("file://") && !p.starts_with('/')); - if share || !(p.starts_with('/') || drive) || p.chars().any(char::is_control) || p.len() > 4096 { - return Err(format!("'{p}': an MBTiles file is given by its full path on this computer")); - } + let p = crate::pmtiles::check_local_prefix(archive, "an MBTiles file")?; if !p.to_ascii_lowercase().ends_with(".mbtiles") { return Err(format!("'{p}' isn't an .mbtiles file")); } @@ -606,10 +601,27 @@ mod tests { } assert!(check("/data/a.mbtiles").is_ok()); assert!(check("C:\\data\\a.MBTiles").is_ok()); + assert!(check("C:/data/a.mbtiles").is_ok()); + assert!(check("file:///data/a.mbtiles").is_ok()); + assert!(check("file:///C:/data/a.mbtiles").is_ok()); assert!(check("upload:a.mbtiles").is_ok()); - for bad in - ["a.mbtiles", "/data/a.pmtiles", "\\\\server\\share\\a.mbtiles", "file://server/a.mbtiles", "upload:", "https://x/a.mbtiles"] - { + for bad in [ + "a.mbtiles", + "/data/a.pmtiles", + "\\\\server\\share\\a.mbtiles", + "//server/share/a.mbtiles", + "/\\server\\share\\a.mbtiles", + "\\/server/share/a.mbtiles", + "file://server/a.mbtiles", + "file:////server/share/a.mbtiles", + "file:///\\\\server\\share\\a.mbtiles", + "file:///\\server\\share\\a.mbtiles", + "file://\\/server/share/a.mbtiles", + "C:map.mbtiles", + "file:///C:map.mbtiles", + "upload:", + "https://x/a.mbtiles", + ] { assert!(check(bad).is_err(), "{bad}"); } assert_eq!(template("upload:x"), "mbtiles:{z}/{x}/{y}@upload:x"); diff --git a/crates/tiles/src/pmtiles.rs b/crates/tiles/src/pmtiles.rs index f058827d3e..5533bb6b36 100644 --- a/crates/tiles/src/pmtiles.rs +++ b/crates/tiles/src/pmtiles.rs @@ -199,18 +199,50 @@ pub fn check_local(archive: &str) -> Result<(), String> { check_local_path(archive, "a PMTiles file", &["pmtiles"]) } +fn is_path_sep(b: u8) -> bool { + b == b'/' || b == b'\\' +} + +fn has_leading_double_sep(p: &str) -> bool { + let b = p.as_bytes(); + b.first().copied().is_some_and(is_path_sep) && b.get(1).copied().is_some_and(is_path_sep) +} + +fn is_drive_abs(p: &str) -> bool { + let b = p.as_bytes(); + b.first().is_some_and(u8::is_ascii_alphabetic) && b.get(1) == Some(&b':') && b.get(2).copied().is_some_and(is_path_sep) +} + +fn is_drive_rel(p: &str) -> bool { + let b = p.as_bytes(); + b.first().is_some_and(u8::is_ascii_alphabetic) && b.get(1) == Some(&b':') && !b.get(2).copied().is_some_and(is_path_sep) +} + +/// Checks that `archive` is an absolute path on this computer (not a network share, mixed-slash +/// UNC prefix, or Windows drive-relative path) and returns the path with any `file://` prefix +/// removed. `kind` names the file in the refusal. +pub(crate) fn check_local_prefix<'a>(archive: &'a str, kind: &str) -> Result<&'a str, String> { + let (is_file_url, p) = match archive.strip_prefix("file://") { + Some(p) => (true, p), + None => (false, archive), + }; + let drive = is_drive_abs(p); + // A path on this computer: not a network share (\\server\share, //server/share, /\server\share, + // \/server/share, or file://server/…), which a project could use to make Windows connect to + // another machine. + let share = has_leading_double_sep(p) + || (is_file_url && (!p.starts_with('/') || p.strip_prefix('/').is_some_and(|r| has_leading_double_sep(r) || is_drive_rel(r)))); + if share || !(p.starts_with('/') || drive) || p.chars().any(char::is_control) || p.len() > 4096 { + return Err(format!("'{p}': {kind} is given by its full path on this computer")); + } + Ok(p) +} + /// Whether a local file may be read by range: an absolute path on this computer (not a network /// share) whose extension is one of `extensions` (lowercase, without the dot). `kind` names the /// file in the refusal. pub(crate) fn check_local_path(archive: &str, kind: &str, extensions: &[&str]) -> Result<(), String> { - let p = archive.strip_prefix("file://").unwrap_or(archive); - let drive = p.as_bytes().get(1) == Some(&b':') && p.as_bytes().first().is_some_and(u8::is_ascii_alphabetic); - // A path on this computer: not a network share (\\server\share, or file://server/…), which a - // project could use to make Windows connect to another machine. - let share = p.starts_with("\\\\") || p.starts_with("//") || (archive.starts_with("file://") && !p.starts_with('/')); - if share || !(p.starts_with('/') || drive) || p.chars().any(char::is_control) || p.len() > 4096 { - return Err(format!("'{p}': {kind} is given by its full path on this computer")); - } + let p = check_local_prefix(archive, kind)?; let lower = p.to_ascii_lowercase(); if !extensions.iter().any(|e| lower.rsplit_once('.').is_some_and(|(_, ext)| ext == *e)) { let named: Vec = extensions.iter().map(|e| format!(".{e}")).collect(); @@ -2076,4 +2108,34 @@ pub(crate) mod tests { } let _ = std::fs::remove_dir_all(dir); } + + #[test] + fn check_local_path_rejects_mixed_separators_and_drive_relative() { + for good in [ + "/data/a.pmtiles", + "C:\\data\\a.pmtiles", + "C:/data/a.pmtiles", + "file:///data/a.pmtiles", + "file:///C:/data/a.pmtiles", + "file:///C:\\data\\a.pmtiles", + ] { + assert!(check_local(good).is_ok(), "{good}"); + } + for bad in [ + "\\\\server\\share\\a.pmtiles", + "//server/share/a.pmtiles", + "/\\server\\share\\a.pmtiles", + "\\/server/share/a.pmtiles", + "file://server/share/a.pmtiles", + "file:////server/share/a.pmtiles", + "file:///\\\\server\\share\\a.pmtiles", + "file:///\\server\\share\\a.pmtiles", + "file://\\/server/share/a.pmtiles", + "C:map.pmtiles", + "file:///C:map.pmtiles", + "relative.pmtiles", + ] { + assert!(check_local(bad).is_err(), "{bad}"); + } + } } diff --git a/crates/tiles/src/source.rs b/crates/tiles/src/source.rs index b68155366e..6ed80c1212 100644 --- a/crates/tiles/src/source.rs +++ b/crates/tiles/src/source.rs @@ -206,13 +206,22 @@ fn settle(anew: Resolve, cached: Option>, spec: &Spec, key: String // Or while it can't be read again: it is tried again after the next wait. Its own notice // still says what it leaves out; why it couldn't be read again goes to the log. (Resolve::Failed(e), Some(old)) => { - log::warn!("{}: drawn as it was, as it could not be read again: {e}", spec.url); + log::warn!("{}", settle_failure_log(&spec.url, &e)); Resolve::Ready(renewed(old)) } (other, _) => other, } } +/// Formats the warning logged when a cached source fails to refresh, with addresses and active +/// login credentials redacted. +fn settle_failure_log(url: &str, err: &str) -> String { + crate::logins::scrub_error(&rustgis_data::diagnostics::message_with_address( + url, + &format!("drawn as it was, as it could not be read again: {err}"), + )) +} + /// Reads `spec`'s style and resolves its sources, keeping the result under `key`. fn resolve_anew(spec: &Spec, key: String, epoch: u64) -> Resolve { let mut base = address::Origin::named(&spec.url); @@ -2075,4 +2084,22 @@ mod tests { fn plain_attribution() { assert_eq!(plain_text("© OpenStreetMap contributors & CARTO"), "© OpenStreetMap contributors & CARTO"); } + + #[test] + fn settle_failure_log_scrubs_secrets() { + let _turn = crate::cache::turn(); + let origin = "https://settle-log.example.com"; + let binding = + crate::logins::activate(origin, "settle", crate::logins::Method::Header("X-Key".into()), "active-secret-val", false).unwrap(); + let bound_url = crate::logins::bind(&binding, &format!("{origin}/style.json?token=url-tok")).unwrap(); + let msg = settle_failure_log( + &bound_url, + "failed fetching https://user:err-pw@settle-log.example.com/a?api_key=err-key with active-secret-val", + ); + assert!(crate::logins::deactivate(&binding)); + for secret in ["url-tok", "err-pw", "err-key", "active-secret-val", &binding] { + assert!(!msg.contains(secret), "leaked {secret} in: {msg}"); + } + assert!(msg.contains("drawn as it was"), "{msg}"); + } } From bf2b7f5768ddc584300363f3b4e317967d9d1a19 Mon Sep 17 00:00:00 2001 From: giswqs Date: Wed, 25 Nov 2026 09:30:27 -0500 Subject: [PATCH 2/9] Address review feedback - Pass the actual project folder into `add_annotations` and validate paths already resolved under that folder on their relative remainder, so projects opened from a UNC folder still load relative picture annotations while other shares and unsafe paths stay refused. - Use the validated, resolved path returned by `checked_annotation_picture` for both metadata sizing and `graphics::picture` loading instead of reusing the unresolved string. --- crates/engine/src/cmd/qgis.rs | 93 ++++++++++++++++++++++++++++++++--- 1 file changed, 87 insertions(+), 6 deletions(-) diff --git a/crates/engine/src/cmd/qgis.rs b/crates/engine/src/cmd/qgis.rs index 54a4fe8b1a..e6ac3c026a 100644 --- a/crates/engine/src/cmd/qgis.rs +++ b/crates/engine/src/cmd/qgis.rs @@ -230,7 +230,7 @@ fn import_project(s: &mut Session, p: &Value) -> CmdResult { // The tiles a web tile layer landed on the map as, when it is one. let mut landed_on = None; let result = if layer.kind == "annotation" { - add_annotations(s, layer, crs, canvas.as_ref(), dir.is_some(), &mut pictures, &mut report) + add_annotations(s, layer, crs, canvas.as_ref(), dir.as_deref(), &mut pictures, &mut report) .map(|(name, d)| Some((name, Some(d)))) } else { add_layer(s, layer, dir.is_some(), view, &mut landed_on, &mut connections, &mut report) @@ -922,12 +922,30 @@ fn saved_database_connection(s: &mut Session, what: &str, connection: &str, made /// `graphics::picture` reads), each read once, and at most [`qgis::MAX_ANNOTATIONS`] items a layer /// placed. Running the whole import off the window, with Cancel and progress, is for the import /// as a whole, not this layer kind. +/// Defensively validates a picture annotation path before filesystem access, returning the +/// resolved source to read. A path already resolved under the user-opened project folder `dir` +/// (including when `dir` itself is a network share) is checked on its relative remainder so +/// projects opened from a UNC folder keep loading relative pictures while other shares and unsafe +/// paths stay refused. +fn checked_annotation_picture(picture: &str, dir: Option<&str>) -> Result { + let base = dir.map(|d| d.trim_end_matches(['/', '\\'])).filter(|d| !d.is_empty()); + if let Some(base) = base + && let Some(rest) = picture.strip_prefix(base).and_then(|r| r.strip_prefix('/')) + && !rest.is_empty() + && !rest.starts_with(['/', '\\']) + { + qgis::local_image_source(rest, base) + } else { + qgis::local_image_source(picture, dir.unwrap_or("")) + } +} + fn add_annotations( s: &mut Session, layer: &qgis::ProjectLayer, project_crs: Option<&str>, canvas: Option<&rustgis_data::raster::crs::Transformer>, - has_dir: bool, + dir: Option<&str>, pictures: &mut Pictures, report: &mut Report, ) -> Result<(String, Drawn), String> { @@ -993,14 +1011,14 @@ fn add_annotations( Some(Ok(b64)) if b64.len() > left => None, Some(read) => Some(read.clone()), None => { - let read = match qgis::local_image_source(picture, if has_dir { "/" } else { "" }) { + let read = match checked_annotation_picture(picture, dir) { Err(why) => Err(format!("{picture}: {why}")), Ok(source) => { // Its size first, from its text or its file's length (base64 is 4 bytes for 3): // one that can't fit isn't read. let size = match &source { qgis::ImageSource::Base64 => Some(picture.strip_prefix("base64:").unwrap_or_default().trim().len()), - qgis::ImageSource::File(_) => std::fs::metadata(picture) + qgis::ImageSource::File(path) => std::fs::metadata(path) .ok() .map(|m| usize::try_from(m.len()).unwrap_or(usize::MAX).div_ceil(3).saturating_mul(4)), }; @@ -1013,7 +1031,7 @@ fn add_annotations( qgis::ImageSource::Base64 => { super::graphics::picture(&json!({"image": picture.strip_prefix("base64:").unwrap_or_default()})) } - qgis::ImageSource::File(_) => super::graphics::picture(&json!({"path": picture})), + qgis::ImageSource::File(path) => super::graphics::picture(&json!({"path": path})), } } }; @@ -2153,9 +2171,72 @@ mod tests { }; let mut pictures = Pictures::default(); let mut report = Report::default(); - add_annotations(&mut s, &layer, Some("EPSG:4326"), None, true, &mut pictures, &mut report).unwrap(); + add_annotations(&mut s, &layer, Some("EPSG:4326"), None, Some("/tmp"), &mut pictures, &mut report).unwrap(); let added = s.map().layer_by_name("Direct").unwrap(); assert!(added.dataset.features.is_empty()); assert!(report.notes.iter().any(|n| n.text.contains("network share")), "{:?}", report.notes); } + + #[test] + fn add_annotations_keeps_relative_pictures_under_unc_project_folder_and_uses_resolved_path() { + let unc_dir = r"\\server\share\proj"; + let qgs = r#"EPSG:4326 + aUncPics + + "#; + let mut report = Report::default(); + let project = qgis::read_project(qgs, unc_dir, &mut |_| Err("unused"), &mut report).unwrap(); + assert_eq!(project.layers[0].annotations.len(), 1); + let resolved = project.layers[0].annotations[0].picture.as_deref().unwrap(); + assert_eq!(resolved, r"\\server\share\proj/pic.png"); + assert_eq!(checked_annotation_picture(resolved, Some(unc_dir)), Ok(qgis::ImageSource::File(r"\\server\share\proj/pic.png".into()))); + // A different network share is still refused even when the project itself lives on a UNC folder. + assert!(checked_annotation_picture(r"\\other\share\pic.png", Some(unc_dir)).is_err()); + assert!(checked_annotation_picture(r"\\server\share\proj//other/pic.png", Some(unc_dir)).is_err()); + + // Round-trip through add_annotations: not rejected as a network share. + let mut s = Session::new(crate::Project::default()); + let mut pictures = Pictures::default(); + add_annotations(&mut s, &project.layers[0], Some("EPSG:4326"), None, Some(unc_dir), &mut pictures, &mut report).unwrap(); + assert!(!report.notes.iter().any(|n| n.text.contains("network share")), "{:?}", report.notes); + + // Unresolved relative picture uses the real project folder and reads the validated path. + let dir = std::env::temp_dir().join(format!("rustgis-qgis-ann-rel-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + let png = tiny_skia::Pixmap::new(2, 2).unwrap().encode_png().unwrap(); + std::fs::write(dir.join("pic.png"), &png).unwrap(); + let rect = rustgis_data::Geometry::Polygon(vec![vec![vec![ + rustgis_geom::Coord::new(0.0, 0.0), + rustgis_geom::Coord::new(1.0, 0.0), + rustgis_geom::Coord::new(1.0, 1.0), + rustgis_geom::Coord::new(0.0, 1.0), + rustgis_geom::Coord::new(0.0, 0.0), + ]]]); + let rel_layer = qgis::ProjectLayer { + id: "r".into(), + name: "RelPic".into(), + provider: String::new(), + kind: "annotation".into(), + vector: false, + visible: true, + checked: true, + group: None, + definition_query: None, + crs: Some("EPSG:4326".into()), + source: qgis::Source::Other { provider: String::new() }, + style: qgis::Style::default(), + annotations: vec![qgis::Annotation { + graphic: rustgis_map::graphics::Graphic::new("picture", rect), + picture: Some("pic.png".into()), + keep_aspect: false, + }], + }; + let mut rel_report = Report::default(); + let mut rel_pics = Pictures::default(); + add_annotations(&mut s, &rel_layer, Some("EPSG:4326"), None, Some(&dir.to_string_lossy()), &mut rel_pics, &mut rel_report).unwrap(); + let added = s.map().layer_by_name("RelPic").unwrap(); + assert_eq!(added.dataset.features.len(), 1, "{:?}", rel_report.notes); + let _ = std::fs::remove_dir_all(&dir); + } } From 655cedff91b5edb35d7e54999b4e6602b2e760ef Mon Sep 17 00:00:00 2001 From: giswqs Date: Wed, 25 Nov 2026 09:49:31 -0500 Subject: [PATCH 3/9] Address review feedback - Move `add_annotations`'s doc comment back directly above `fn add_annotations` (leaving `checked_annotation_picture` with its own doc comment) and update its `has_dir` reference to `dir`. --- crates/engine/src/cmd/qgis.rs | 22 +++++++++++----------- 1 file changed, 11 insertions(+), 11 deletions(-) diff --git a/crates/engine/src/cmd/qgis.rs b/crates/engine/src/cmd/qgis.rs index e6ac3c026a..49194f3d29 100644 --- a/crates/engine/src/cmd/qgis.rs +++ b/crates/engine/src/cmd/qgis.rs @@ -911,17 +911,6 @@ fn saved_database_connection(s: &mut Session, what: &str, connection: &str, made } } -/// Adds a QGIS annotation layer as a graphics layer: its annotations taken from its coordinate -/// system (else the project's, `project_crs`) to longitude/latitude, its pictures read from their -/// files (a relative one only with the project's folder, `has_dir`), its opacity, blending and -/// scale range from its style. What can't be placed or read is noted. -/// -/// On the thread that runs the import, as the import's other layers are: like opening a project, -/// it adds layers to the session as it goes, and no part of it runs on its own yet. Its work is -/// bounded: at most [`MAX_PICTURE_BYTES`] of pictures an import (each file at most what -/// `graphics::picture` reads), each read once, and at most [`qgis::MAX_ANNOTATIONS`] items a layer -/// placed. Running the whole import off the window, with Cancel and progress, is for the import -/// as a whole, not this layer kind. /// Defensively validates a picture annotation path before filesystem access, returning the /// resolved source to read. A path already resolved under the user-opened project folder `dir` /// (including when `dir` itself is a network share) is checked on its relative remainder so @@ -940,6 +929,17 @@ fn checked_annotation_picture(picture: &str, dir: Option<&str>) -> Result Date: Wed, 25 Nov 2026 10:26:27 -0500 Subject: [PATCH 4/9] Address review feedback - Keep background box and frame graphics when a picture annotation's path is refused in `qgis::annotation::boxed`, omitting only the picture itself while still recording the skipped note. - Lift `pwd` and `passwd` query aliases (including percent-encoded keys) as the extracted password in `myconn::split_password` (shared with `msconn::split_password`) before running `redact_query`. - Return `ImageSource::File` directly in `checked_annotation_picture` for paths already resolved under the project folder instead of reclassifying their remainder via `local_image_source`. - Decode JSON request/response bodies (and SSE `data:` payloads) and mask JSON-escaped API keys in `rustgis-cli ask --trace` so active credentials containing backslashes or quotes are scrubbed in JSON and plain text alike. --- apps/rustgis-cli/src/main.rs | 129 +++++++++++++++++++++++++++--- crates/data/src/source/msconn.rs | 8 +- crates/data/src/source/myconn.rs | 33 +++++++- crates/engine/src/cmd/qgis.rs | 18 ++++- crates/map/src/qgis/annotation.rs | 23 +++--- crates/map/src/qgis/tests.rs | 19 +++++ 6 files changed, 197 insertions(+), 33 deletions(-) diff --git a/apps/rustgis-cli/src/main.rs b/apps/rustgis-cli/src/main.rs index 44852a2585..36a335d461 100644 --- a/apps/rustgis-cli/src/main.rs +++ b/apps/rustgis-cli/src/main.rs @@ -602,10 +602,78 @@ fn ask(s: &mut Session, args: &[String], saved: Option<&Saved>, env: &Environmen Ok(()) } -/// Scrubs active service login values and the assistant's own API key from trace text. +/// Scrubs active service login values and the assistant's own API key (raw and JSON-escaped) +/// from trace text. fn mask_trace_secrets(text: &str, key: &str) -> String { - let scrubbed = rustgis_engine::render::rustgis_tiles::logins::scrub(text); - if key.is_empty() { scrubbed } else { scrubbed.replace(key, "[redacted]") } + let mut scrubbed = rustgis_engine::render::rustgis_tiles::logins::scrub(text); + if !key.is_empty() { + scrubbed = scrubbed.replace(key, "[redacted]"); + if let Ok(quoted) = serde_json::to_string(key) + && let Some(escaped) = quoted.strip_prefix('"').and_then(|s| s.strip_suffix('"')) + && escaped != key + { + scrubbed = scrubbed.replace(escaped, "[redacted]"); + } + } + scrubbed +} + +/// Recursively redacts decoded JSON string values and object keys (bounded to `depth`) so +/// JSON-escaped active credentials and API keys (for example containing `\` or `"`) match before +/// re-serialization. +fn scrub_json_value(value: &mut Value, key: &str, depth: usize) { + if depth == 0 { + *value = Value::String("[redacted]".into()); + return; + } + match value { + Value::String(s) => { + *s = mask_trace_secrets(&rustgis_engine::data::diagnostics::redact_parameter(s), key); + } + Value::Array(items) => { + for item in items { + scrub_json_value(item, key, depth - 1); + } + } + Value::Object(map) => { + let entries = std::mem::take(map); + for (k, mut v) in entries { + let k = mask_trace_secrets(&rustgis_engine::data::diagnostics::redact_parameter(&k), key); + scrub_json_value(&mut v, key, depth - 1); + map.insert(k, v); + } + } + _ => {} + } +} + +/// Scrubs a request or response body for `--trace`: decodes JSON payloads (whole bodies and SSE +/// `data:` lines) so escaped credentials match active logins and the API key, while keeping raw +/// redaction for non-JSON text. +fn scrub_trace_body(body: &str, key: &str) -> String { + const MAX_JSON_DEPTH: usize = 64; + let decoded = if let Ok(mut value) = serde_json::from_str::(body) { + scrub_json_value(&mut value, key, MAX_JSON_DEPTH); + serde_json::to_string(&value).unwrap_or_else(|_| body.to_string()) + } else if body.lines().any(|line| line.starts_with("data:")) { + body.lines() + .map(|line| { + if let Some(rest) = line.strip_prefix("data:") + && let Ok(mut value) = serde_json::from_str::(rest.trim()) + { + scrub_json_value(&mut value, key, MAX_JSON_DEPTH); + if let Ok(serialized) = serde_json::to_string(&value) { + return format!("data: {serialized}"); + } + } + line.to_string() + }) + .collect::>() + .join("\n") + } else { + body.to_string() + }; + mask_trace_secrets(&rustgis_engine::data::diagnostics::redact_parameter(&decoded), key) } /// Formats a `--trace` entry for an assistant request and its response, redacting URL @@ -616,13 +684,9 @@ fn format_trace_entry( key: &str, ) -> String { let url = mask_trace_secrets(&rustgis_engine::sources::redact(&req.url), key); - let body = mask_trace_secrets(&rustgis_engine::data::diagnostics::redact_parameter(req.body.as_deref().unwrap_or("")), key); + let body = scrub_trace_body(req.body.as_deref().unwrap_or(""), key); let answer = match resp { - Ok(r) => format!( - "HTTP {}\n{}", - r.status, - mask_trace_secrets(&rustgis_engine::data::diagnostics::redact_parameter(&String::from_utf8_lossy(&r.body)), key) - ), + Ok(r) => format!("HTTP {}\n{}", r.status, scrub_trace_body(&String::from_utf8_lossy(&r.body), key)), Err(e) => mask_trace_secrets(&rustgis_engine::data::diagnostics::redact(&e.to_string()), key), }; format!("> {} {url}\n{body}\n< {answer}\n\n", req.method) @@ -1377,6 +1441,53 @@ mod tests { for secret in ["urlpw", "sk-test-key-12345", "errpw", "errkey", "active-login-secret-999"] { assert!(!err_entry.contains(secret), "leaked {secret} in: {err_entry}"); } + + // JSON-escaped credentials containing backslashes and double quotes are redacted in JSON bodies. + let slash_secret = r"login\slash-secret-42"; + let quote_secret = r#"login"quote-secret-42"#; + let escaped_key = r#"sk\key"escape-42"#; + let b_slash = rustgis_engine::render::rustgis_tiles::logins::activate( + "https://trace-slash.example.test", + "slash", + rustgis_engine::render::rustgis_tiles::logins::Method::Header("X-Key".into()), + slash_secret, + false, + ) + .unwrap(); + let b_quote = rustgis_engine::render::rustgis_tiles::logins::activate( + "https://trace-quote.example.test", + "quote", + rustgis_engine::render::rustgis_tiles::logins::Method::Header("X-Key".into()), + quote_secret, + false, + ) + .unwrap(); + let req_json = rustgis_assistant::HttpRequest { + method: "POST", + url: "https://api.example.test/v1/chat".into(), + headers: Vec::new(), + body: Some(json!({"prompt": format!("req {slash_secret} {quote_secret} {escaped_key}")}).to_string()), + }; + let resp_json: Result<_, &str> = Ok(rustgis_assistant::HttpResponse { + status: 200, + headers: Vec::new(), + body: json!({"output": format!("resp {slash_secret} {quote_secret} {escaped_key}")}).to_string().into_bytes(), + }); + let json_entry = format_trace_entry(&req_json, &resp_json, escaped_key); + let plain_resp: Result<_, &str> = Ok(rustgis_assistant::HttpResponse { + status: 200, + headers: Vec::new(), + body: format!("plain {slash_secret} {quote_secret} {escaped_key}").into_bytes(), + }); + let plain_entry = format_trace_entry(&req_json, &plain_resp, escaped_key); + assert!(rustgis_engine::render::rustgis_tiles::logins::deactivate(&b_slash)); + assert!(rustgis_engine::render::rustgis_tiles::logins::deactivate(&b_quote)); + for leaked in + [slash_secret, r"login\\slash-secret-42", quote_secret, r#"login\"quote-secret-42"#, escaped_key, r#"sk\\key\"escape-42"#] + { + assert!(!json_entry.contains(leaked), "leaked {leaked} in JSON trace: {json_entry}"); + assert!(!plain_entry.contains(leaked), "leaked {leaked} in plain trace: {plain_entry}"); + } } #[cfg(unix)] diff --git a/crates/data/src/source/msconn.rs b/crates/data/src/source/msconn.rs index df3015eec8..60f47f5e63 100644 --- a/crates/data/src/source/msconn.rs +++ b/crates/data/src/source/msconn.rs @@ -13,13 +13,7 @@ pub fn split_password(s: &str) -> Option<(String, Option)> { return None; } let (mut public, password) = super::myconn::split_userinfo_password(s.trim())?; - let password = password.or_else(|| { - let (_, query) = public.split_once('?')?; - query.split('&').find_map(|kv| { - let (key, value) = kv.split_once('=')?; - matches!(crate::address::normalized_name(key).as_deref(), Some("pwd" | "passwd")).then(|| super::pgconn::percent_decode(value)) - }) - }); + let password = password.or_else(|| super::myconn::query_password_alias(&public)); super::credentials::redact_query(&mut public); Some((public, password)) } diff --git a/crates/data/src/source/myconn.rs b/crates/data/src/source/myconn.rs index 70148c4c71..e197515e1c 100644 --- a/crates/data/src/source/myconn.rs +++ b/crates/data/src/source/myconn.rs @@ -16,10 +16,21 @@ pub fn split_password(s: &str) -> Option<(String, Option)> { return None; } let (mut public, password) = split_userinfo_password(t)?; + let password = password.or_else(|| query_password_alias(&public)); super::credentials::redact_query(&mut public); Some((public, password)) } +/// Extracts the first `pwd` or `passwd` query alias (percent-decoded) when neither user-info nor +/// `password`/`pass` supplied a password. +pub(super) fn query_password_alias(public: &str) -> Option { + let (_, query) = public.split_once('?')?; + query.split('&').find_map(|kv| { + let (key, value) = kv.split_once('=')?; + matches!(crate::address::normalized_name(key).as_deref(), Some("pwd" | "passwd")).then(|| super::pgconn::percent_decode(value)) + }) +} + /// Removes user-info and query passwords without restricting the address's scheme. pub(super) fn split_userinfo_password(t: &str) -> Option<(String, Option)> { let (scheme, rest) = t.split_once("://")?; @@ -127,9 +138,25 @@ mod tests { s("mariadb://me@h/gis?pa%73s=pw123&ssl-mode=REQUIRED"), ("mariadb://me@h/gis?ssl-mode=REQUIRED".into(), Some("pw123".into())) ); - for key in ["token", "access_token", "client_secret", "api_key", "pwd"] { - let (public, _) = s(&format!("mysql://me@h/gis?{key}=secret&ssl-mode=REQUIRED")); - assert_eq!(public, "mysql://me@h/gis?ssl-mode=REQUIRED", "{key}"); + for (query, expected) in [ + ("pwd=sec%26ret", "sec&ret"), + ("passwd=pw123", "pw123"), + ("pw%64=enc-pwd", "enc-pwd"), + ("pass%77d=enc-passwd", "enc-passwd"), + ("pwd=ignored&password=chosen", "chosen"), + ] { + assert_eq!( + s(&format!("mysql://me@h/gis?{query}&ssl-mode=REQUIRED")), + ("mysql://me@h/gis?ssl-mode=REQUIRED".into(), Some(expected.into())), + "{query}" + ); + } + for key in ["token", "access_token", "client_secret", "api_key"] { + assert_eq!( + s(&format!("mysql://me@h/gis?{key}=secret&ssl-mode=REQUIRED")), + ("mysql://me@h/gis?ssl-mode=REQUIRED".into(), None), + "{key}" + ); } } } diff --git a/crates/engine/src/cmd/qgis.rs b/crates/engine/src/cmd/qgis.rs index 49194f3d29..ff477d7b05 100644 --- a/crates/engine/src/cmd/qgis.rs +++ b/crates/engine/src/cmd/qgis.rs @@ -913,17 +913,19 @@ fn saved_database_connection(s: &mut Session, what: &str, connection: &str, made /// Defensively validates a picture annotation path before filesystem access, returning the /// resolved source to read. A path already resolved under the user-opened project folder `dir` -/// (including when `dir` itself is a network share) is checked on its relative remainder so -/// projects opened from a UNC folder keep loading relative pictures while other shares and unsafe -/// paths stay refused. +/// (including when `dir` itself is a network share) is kept as a file source without +/// reclassifying its remainder, so filenames like `base64:logo.png` or `C:logo.png` under `dir` +/// and projects opened from a UNC folder keep working while other shares and unsafe paths stay +/// refused. fn checked_annotation_picture(picture: &str, dir: Option<&str>) -> Result { + let picture = picture.trim(); let base = dir.map(|d| d.trim_end_matches(['/', '\\'])).filter(|d| !d.is_empty()); if let Some(base) = base && let Some(rest) = picture.strip_prefix(base).and_then(|r| r.strip_prefix('/')) && !rest.is_empty() && !rest.starts_with(['/', '\\']) { - qgis::local_image_source(rest, base) + Ok(qgis::ImageSource::File(picture.to_string())) } else { qgis::local_image_source(picture, dir.unwrap_or("")) } @@ -2193,6 +2195,14 @@ mod tests { // A different network share is still refused even when the project itself lives on a UNC folder. assert!(checked_annotation_picture(r"\\other\share\pic.png", Some(unc_dir)).is_err()); assert!(checked_annotation_picture(r"\\server\share\proj//other/pic.png", Some(unc_dir)).is_err()); + assert!(checked_annotation_picture(r"\\server\share\proj/\other/pic.png", Some(unc_dir)).is_err()); + + // Resolved filenames under the project folder stay File sources even if the basename looks like a prefix. + assert_eq!( + checked_annotation_picture("/tmp/base64:logo.png", Some("/tmp")), + Ok(qgis::ImageSource::File("/tmp/base64:logo.png".into())) + ); + assert_eq!(checked_annotation_picture("/tmp/C:logo.png", Some("/tmp")), Ok(qgis::ImageSource::File("/tmp/C:logo.png".into()))); // Round-trip through add_annotations: not rejected as a network share. let mut s = Session::new(crate::Project::default()); diff --git a/crates/map/src/qgis/annotation.rs b/crates/map/src/qgis/annotation.rs index 4dc59dcd78..6703a84b2f 100644 --- a/crates/map/src/qgis/annotation.rs +++ b/crates/map/src/qgis/annotation.rs @@ -487,20 +487,23 @@ fn boxed(item: Node, kind: &str, dir: &str, layer: &str, read: &mut Reading, rep read.no_picture += 1; return Vec::new(); } - let picture = match super::source::local_image_source(path, dir) { - Ok(super::source::ImageSource::Base64) => path.to_string(), - Ok(super::source::ImageSource::File(p)) => p, + out.extend(background.map(wrap)); + match super::source::local_image_source(path, dir) { + Ok(source) => { + if fixed { + read.pictures_fixed += 1; + } + let picture = match source { + super::source::ImageSource::Base64 => path.to_string(), + super::source::ImageSource::File(p) => p, + }; + let g = Graphic::new("picture", rect()); + out.push(Annotation { graphic: g, picture: Some(picture), keep_aspect: item.attribute("lockAspect") != Some("0") }); + } Err(why) => { report.skipped(layer, format!("picture annotations {why}")); - return Vec::new(); } - }; - if fixed { - read.pictures_fixed += 1; } - out.extend(background.map(wrap)); - let g = Graphic::new("picture", rect()); - out.push(Annotation { graphic: g, picture: Some(picture), keep_aspect: item.attribute("lockAspect") != Some("0") }); out.extend(frame.map(wrap)); out } diff --git a/crates/map/src/qgis/tests.rs b/crates/map/src/qgis/tests.rs index 08ef4ab376..a3b0d3f4f9 100644 --- a/crates/map/src/qgis/tests.rs +++ b/crates/map/src/qgis/tests.rs @@ -3377,4 +3377,23 @@ fn picture_annotations_reject_unsafe_paths() { report.notes ); } + + // A refused picture still keeps its background box and frame graphics, omitting only the picture. + let qgs = r#"EPSG:4326 + aFramed + + + + + "#; + let mut report = Report::default(); + let p = read_project(qgs, "/d", &mut report).unwrap(); + let anns = &p.layers[0].annotations; + assert_eq!(anns.len(), 2, "background and frame must be kept: {anns:?}"); + assert!(anns.iter().all(|a| a.graphic.kind == "rectangle" && a.picture.is_none()), "{anns:?}"); + assert!( + report.notes.iter().any(|n| n.layer == "Framed" && n.kind == NoteKind::Skipped && n.text.contains("network share")), + "{:?}", + report.notes + ); } From b4ca0cdcbb7bb01287da0144dc9d6670e810e5a7 Mon Sep 17 00:00:00 2001 From: giswqs Date: Wed, 25 Nov 2026 10:42:57 -0500 Subject: [PATCH 5/9] Address CodeRabbit review feedback - Check `address::log_sensitive` on the original JSON object key in `scrub_json_value` before masking the key, replacing sensitive field values with `[redacted]` even when an active login value matches the field name. --- apps/rustgis-cli/src/main.rs | 33 ++++++++++++++++++++++++++++++++- 1 file changed, 32 insertions(+), 1 deletion(-) diff --git a/apps/rustgis-cli/src/main.rs b/apps/rustgis-cli/src/main.rs index 36a335d461..6bd879184f 100644 --- a/apps/rustgis-cli/src/main.rs +++ b/apps/rustgis-cli/src/main.rs @@ -638,8 +638,13 @@ fn scrub_json_value(value: &mut Value, key: &str, depth: usize) { Value::Object(map) => { let entries = std::mem::take(map); for (k, mut v) in entries { + let sensitive = rustgis_engine::data::address::log_sensitive(&k); let k = mask_trace_secrets(&rustgis_engine::data::diagnostics::redact_parameter(&k), key); - scrub_json_value(&mut v, key, depth - 1); + if sensitive { + v = Value::String("[redacted]".into()); + } else { + scrub_json_value(&mut v, key, depth - 1); + } map.insert(k, v); } } @@ -1488,6 +1493,32 @@ mod tests { assert!(!json_entry.contains(leaked), "leaked {leaked} in JSON trace: {json_entry}"); assert!(!plain_entry.contains(leaked), "leaked {leaked} in plain trace: {plain_entry}"); } + + // An active login whose value equals a sensitive field name must not bypass value redaction. + let b_field = rustgis_engine::render::rustgis_tiles::logins::activate( + "https://trace-field.example.test", + "field", + rustgis_engine::render::rustgis_tiles::logins::Method::Header("X-Key".into()), + "password", + false, + ) + .unwrap(); + let req_sensitive = rustgis_assistant::HttpRequest { + method: "POST", + url: "https://api.example.test/v1/chat".into(), + headers: Vec::new(), + body: Some(json!({"password": "my-db-secret", "prompt": "safe"}).to_string()), + }; + let resp_sensitive: Result<_, &str> = Ok(rustgis_assistant::HttpResponse { + status: 200, + headers: Vec::new(), + body: json!({"password": "my-resp-secret", "output": "ok"}).to_string().into_bytes(), + }); + let sensitive_entry = format_trace_entry(&req_sensitive, &resp_sensitive, ""); + assert!(rustgis_engine::render::rustgis_tiles::logins::deactivate(&b_field)); + assert!(!sensitive_entry.contains("my-db-secret"), "leaked request secret in: {sensitive_entry}"); + assert!(!sensitive_entry.contains("my-resp-secret"), "leaked response secret in: {sensitive_entry}"); + assert!(sensitive_entry.contains("\"prompt\":\"safe\""), "{sensitive_entry}"); } #[cfg(unix)] From 2defbed3aaba1aeeb9369385a265b6d99c308d10 Mon Sep 17 00:00:00 2001 From: giswqs Date: Wed, 25 Nov 2026 12:03:59 -0500 Subject: [PATCH 6/9] Address Claude review feedback - Accept absolute picture paths already inside the user-opened project folder `dir` (including UNC project folders, matching `/` and `\` in the UNC prefix and rejecting `..` segments that escape `dir`) before the network-share check in `qgis::local_image_source`, and delegate `checked_annotation_picture` to the same shared helper. - Add regression tests in `crates/map/src/qgis/tests.rs` covering absolute UNC picture paths inside a UNC `dir` versus other shares, sibling folders, and `..` traversal escaping `dir`. --- crates/engine/src/cmd/qgis.rs | 20 +++--------- crates/map/src/qgis/source.rs | 59 +++++++++++++++++++++++++++++++++-- crates/map/src/qgis/tests.rs | 41 ++++++++++++++++++++++++ 3 files changed, 102 insertions(+), 18 deletions(-) diff --git a/crates/engine/src/cmd/qgis.rs b/crates/engine/src/cmd/qgis.rs index ff477d7b05..40f39d0541 100644 --- a/crates/engine/src/cmd/qgis.rs +++ b/crates/engine/src/cmd/qgis.rs @@ -912,23 +912,11 @@ fn saved_database_connection(s: &mut Session, what: &str, connection: &str, made } /// Defensively validates a picture annotation path before filesystem access, returning the -/// resolved source to read. A path already resolved under the user-opened project folder `dir` -/// (including when `dir` itself is a network share) is kept as a file source without -/// reclassifying its remainder, so filenames like `base64:logo.png` or `C:logo.png` under `dir` -/// and projects opened from a UNC folder keep working while other shares and unsafe paths stay -/// refused. +/// resolved source to read. Delegates to [`qgis::local_image_source`], which keeps paths already +/// resolved inside the user-opened project folder `dir` (including UNC project folders) as file +/// sources while refusing other shares and unsafe paths. fn checked_annotation_picture(picture: &str, dir: Option<&str>) -> Result { - let picture = picture.trim(); - let base = dir.map(|d| d.trim_end_matches(['/', '\\'])).filter(|d| !d.is_empty()); - if let Some(base) = base - && let Some(rest) = picture.strip_prefix(base).and_then(|r| r.strip_prefix('/')) - && !rest.is_empty() - && !rest.starts_with(['/', '\\']) - { - Ok(qgis::ImageSource::File(picture.to_string())) - } else { - qgis::local_image_source(picture, dir.unwrap_or("")) - } + qgis::local_image_source(picture, dir.unwrap_or("")) } /// Adds a QGIS annotation layer as a graphics layer: its annotations taken from its coordinate diff --git a/crates/map/src/qgis/source.rs b/crates/map/src/qgis/source.rs index 33d9e8983b..400f96b497 100644 --- a/crates/map/src/qgis/source.rs +++ b/crates/map/src/qgis/source.rs @@ -1028,10 +1028,63 @@ pub enum ImageSource { File(String), } +/// Strips the user-opened project folder `dir` and its following separator from `file`, returning +/// the remainder. For UNC project folders, `/` and `\` are treated as equivalent in the prefix so +/// Qt's forward-slash UNC spelling matches a Windows backslash folder. +fn strip_project_dir<'a>(file: &'a str, dir: &str) -> Option<&'a str> { + let base = dir.trim_end_matches(['/', '\\']); + if base.is_empty() { + return None; + } + if let Some(rest) = file.strip_prefix(base).and_then(|r| r.strip_prefix(['/', '\\'])) { + return Some(rest); + } + if base.len() > 1 && base.chars().take(2).all(|c| c == '\\' || c == '/') { + let mut f = file.char_indices(); + for bc in base.chars() { + let (_, fc) = f.next()?; + let both_sep = matches!(bc, '/' | '\\') && matches!(fc, '/' | '\\'); + if fc != bc && !both_sep { + return None; + } + } + let (_, sep) = f.next()?; + if matches!(sep, '/' | '\\') { + return f.next().and_then(|(i, _)| file.get(i..)); + } + } + None +} + +/// Whether `file` already names a file inside `dir` (not empty, not starting with a separator, +/// and never climbing above `dir` through `..` segments). +fn is_under_project_dir(file: &str, dir: &str) -> bool { + let Some(rest) = strip_project_dir(file, dir) else { + return false; + }; + if rest.is_empty() || rest.starts_with(['/', '\\']) { + return false; + } + let mut depth = 0usize; + for seg in rest.split(['/', '\\']) { + match seg { + "" | "." => {} + ".." => { + let Some(next) = depth.checked_sub(1) else { + return false; + }; + depth = next; + } + _ => depth += 1, + } + } + depth > 0 +} + /// Checks a QGIS image path (`imageFile` or picture annotation `path`) against `dir` (empty when /// the import has no project folder). Rejects `.qgz` attachments, web addresses, network shares -/// (`\\host\share`, `//host/share`, `/\host\share`, `\/host/share`), drive-relative paths -/// (`C:foo.png`), and relative paths without a folder. +/// (`\\host\share`, `//host/share`, `/\host\share`, `\/host/share`) outside the user-opened +/// project folder `dir`, drive-relative paths (`C:foo.png`), and relative paths without a folder. pub fn local_image_source(file: &str, dir: &str) -> Result { let file = file.trim(); if file.starts_with("base64:") { @@ -1040,6 +1093,8 @@ pub fn local_image_source(file: &str, dir: &str) -> Result 1 && file.chars().take(2).all(|c| c == '\\' || c == '/') { // Looking a share up can sign in to the host the file names, which a style or // project chose (as an archive on one isn't opened either). diff --git a/crates/map/src/qgis/tests.rs b/crates/map/src/qgis/tests.rs index a3b0d3f4f9..04c825c782 100644 --- a/crates/map/src/qgis/tests.rs +++ b/crates/map/src/qgis/tests.rs @@ -3396,4 +3396,45 @@ fn picture_annotations_reject_unsafe_paths() { "{:?}", report.notes ); + + // An absolute UNC picture path inside the user-opened UNC project folder is accepted, while + // another share, sibling folder, or `..` traversal escaping `dir` stays refused. + let unc_dir = r"\\nas\gis\proj"; + for allowed in [r"\\nas\gis\proj\pic.png", r"\\nas\gis\proj\sub\pic.png", r"\\nas\gis\proj\sub\..\pic.png", "//nas/gis/proj/pic.png"] { + let qgs = format!( + r#"EPSG:4326 + aUncOk + + "# + ); + let mut report = Report::default(); + let p = read_project(&qgs, unc_dir, &mut report).unwrap(); + assert_eq!(p.layers[0].annotations.len(), 1, "{allowed}: {:?}", report.notes); + assert_eq!(p.layers[0].annotations[0].picture.as_deref(), Some(allowed)); + assert!(!report.notes.iter().any(|n| n.text.contains("network share")), "{allowed}: {:?}", report.notes); + } + for denied in [ + r"\\other\share\pic.png", + r"\\nas\other\pic.png", + r"\\nas\gis\proj2\pic.png", + r"\\nas\gis\proj\..\other\pic.png", + r"\\nas\gis\proj\sub\..\..\other\pic.png", + r"\\nas\gis\proj//other/pic.png", + r"\\nas\gis\proj/\other/pic.png", + ] { + let qgs = format!( + r#"EPSG:4326 + aUncNo + + "# + ); + let mut report = Report::default(); + let p = read_project(&qgs, unc_dir, &mut report).unwrap(); + assert!(p.layers[0].annotations.is_empty(), "{denied} produced {:?}", p.layers[0].annotations); + assert!( + report.notes.iter().any(|n| n.layer == "UncNo" && n.kind == NoteKind::Skipped && n.text.contains("network share")), + "{denied}: {:?}", + report.notes + ); + } } From 21dd2714212139ea3c99edf30088e42dbeeb49a4 Mon Sep 17 00:00:00 2001 From: giswqs Date: Wed, 25 Nov 2026 12:23:14 -0500 Subject: [PATCH 7/9] Address CodeRabbit review feedback - Restrict `is_under_project_dir` in `qgis::source::check_image_source` to non-relative paths (`!is_relative(file)`) so a relative picture path matching a relative project folder prefix still resolves against `dir`. - Add `qgis::check_resolved_image_source` and use it in `checked_annotation_picture` so already-resolved picture paths under a relative `dir` are validated without double-prefixing `dir`. --- crates/engine/src/cmd/qgis.rs | 51 ++++++++++++----------------------- crates/map/src/qgis/mod.rs | 5 +++- crates/map/src/qgis/source.rs | 28 ++++++++++++++----- crates/map/src/qgis/tests.rs | 5 ++++ 4 files changed, 47 insertions(+), 42 deletions(-) diff --git a/crates/engine/src/cmd/qgis.rs b/crates/engine/src/cmd/qgis.rs index 40f39d0541..c071bafa05 100644 --- a/crates/engine/src/cmd/qgis.rs +++ b/crates/engine/src/cmd/qgis.rs @@ -911,12 +911,13 @@ fn saved_database_connection(s: &mut Session, what: &str, connection: &str, made } } -/// Defensively validates a picture annotation path before filesystem access, returning the -/// resolved source to read. Delegates to [`qgis::local_image_source`], which keeps paths already -/// resolved inside the user-opened project folder `dir` (including UNC project folders) as file -/// sources while refusing other shares and unsafe paths. +/// Defensively validates a picture annotation path already resolved against `dir` before +/// filesystem access, without re-prefixing `dir`. Delegates to +/// [`qgis::check_resolved_image_source`], which keeps paths inside the user-opened project folder +/// `dir` (including UNC project folders) as file sources while refusing other shares and unsafe +/// paths. fn checked_annotation_picture(picture: &str, dir: Option<&str>) -> Result { - qgis::local_image_source(picture, dir.unwrap_or("")) + qgis::check_resolved_image_source(picture, dir.unwrap_or("")) } /// Adds a QGIS annotation layer as a graphics layer: its annotations taken from its coordinate @@ -2192,48 +2193,30 @@ mod tests { ); assert_eq!(checked_annotation_picture("/tmp/C:logo.png", Some("/tmp")), Ok(qgis::ImageSource::File("/tmp/C:logo.png".into()))); + // Already-resolved relative project paths are not double-prefixed with `dir`. + assert_eq!(checked_annotation_picture("data/../pic.png", Some("data")), Ok(qgis::ImageSource::File("data/../pic.png".into()))); + assert!(checked_annotation_picture("pic.png", None).is_err()); + // Round-trip through add_annotations: not rejected as a network share. let mut s = Session::new(crate::Project::default()); let mut pictures = Pictures::default(); add_annotations(&mut s, &project.layers[0], Some("EPSG:4326"), None, Some(unc_dir), &mut pictures, &mut report).unwrap(); assert!(!report.notes.iter().any(|n| n.text.contains("network share")), "{:?}", report.notes); - // Unresolved relative picture uses the real project folder and reads the validated path. + // Round-trip read_project -> add_annotations with a real file under `dir`. let dir = std::env::temp_dir().join(format!("rustgis-qgis-ann-rel-{}", std::process::id())); let _ = std::fs::remove_dir_all(&dir); std::fs::create_dir_all(&dir).unwrap(); let png = tiny_skia::Pixmap::new(2, 2).unwrap().encode_png().unwrap(); std::fs::write(dir.join("pic.png"), &png).unwrap(); - let rect = rustgis_data::Geometry::Polygon(vec![vec![vec![ - rustgis_geom::Coord::new(0.0, 0.0), - rustgis_geom::Coord::new(1.0, 0.0), - rustgis_geom::Coord::new(1.0, 1.0), - rustgis_geom::Coord::new(0.0, 1.0), - rustgis_geom::Coord::new(0.0, 0.0), - ]]]); - let rel_layer = qgis::ProjectLayer { - id: "r".into(), - name: "RelPic".into(), - provider: String::new(), - kind: "annotation".into(), - vector: false, - visible: true, - checked: true, - group: None, - definition_query: None, - crs: Some("EPSG:4326".into()), - source: qgis::Source::Other { provider: String::new() }, - style: qgis::Style::default(), - annotations: vec![qgis::Annotation { - graphic: rustgis_map::graphics::Graphic::new("picture", rect), - picture: Some("pic.png".into()), - keep_aspect: false, - }], - }; + let dir_str = dir.to_string_lossy(); let mut rel_report = Report::default(); + let rel_project = qgis::read_project(qgs, &dir_str, &mut |_| Err("unused"), &mut rel_report).unwrap(); + let mut s_rel = Session::new(crate::Project::default()); let mut rel_pics = Pictures::default(); - add_annotations(&mut s, &rel_layer, Some("EPSG:4326"), None, Some(&dir.to_string_lossy()), &mut rel_pics, &mut rel_report).unwrap(); - let added = s.map().layer_by_name("RelPic").unwrap(); + add_annotations(&mut s_rel, &rel_project.layers[0], Some("EPSG:4326"), None, Some(&dir_str), &mut rel_pics, &mut rel_report) + .unwrap(); + let added = s_rel.map().layer_by_name("UncPics").unwrap(); assert_eq!(added.dataset.features.len(), 1, "{:?}", rel_report.notes); let _ = std::fs::remove_dir_all(&dir); } diff --git a/crates/map/src/qgis/mod.rs b/crates/map/src/qgis/mod.rs index 115f1cb234..b8251ff74b 100644 --- a/crates/map/src/qgis/mod.rs +++ b/crates/map/src/qgis/mod.rs @@ -31,7 +31,10 @@ use crate::effects::Blend; use crate::symbology::{Labeling, LineStroke, MarkerRotation, Picture, Renderer}; pub use annotation::{Annotation, MAX_ITEMS as MAX_ANNOTATIONS}; pub use expr::{reads_measure, to_sql}; -pub use source::{ImageSource, MAX_MEMORY_FIELDS, Source, VirtualFrom, WebOptions, is_drive_relative, is_relative, local_image_source}; +pub use source::{ + ImageSource, MAX_MEMORY_FIELDS, Source, VirtualFrom, WebOptions, check_resolved_image_source, is_drive_relative, is_relative, + local_image_source, +}; pub use structure::{MAX_BOOKMARKS, MAX_RELATIONS, ProjectBookmark, ProjectRelation, listed}; /// The most XML nodes a project or style is read with (a large project's file is some hundred diff --git a/crates/map/src/qgis/source.rs b/crates/map/src/qgis/source.rs index 400f96b497..a2b46463fe 100644 --- a/crates/map/src/qgis/source.rs +++ b/crates/map/src/qgis/source.rs @@ -1081,11 +1081,9 @@ fn is_under_project_dir(file: &str, dir: &str) -> bool { depth > 0 } -/// Checks a QGIS image path (`imageFile` or picture annotation `path`) against `dir` (empty when -/// the import has no project folder). Rejects `.qgz` attachments, web addresses, network shares -/// (`\\host\share`, `//host/share`, `/\host\share`, `\/host/share`) outside the user-opened -/// project folder `dir`, drive-relative paths (`C:foo.png`), and relative paths without a folder. -pub fn local_image_source(file: &str, dir: &str) -> Result { +/// Shared validation for [`local_image_source`] (`resolve = true`, for raw XML paths) and +/// [`check_resolved_image_source`] (`resolve = false`, for paths already resolved against `dir`). +fn check_image_source(file: &str, dir: &str, resolve: bool) -> Result { let file = file.trim(); if file.starts_with("base64:") { Ok(ImageSource::Base64) @@ -1093,7 +1091,7 @@ pub fn local_image_source(file: &str, dir: &str) -> Result 1 && file.chars().take(2).all(|c| c == '\\' || c == '/') { // Looking a share up can sign in to the host the file names, which a style or @@ -1103,11 +1101,27 @@ pub fn local_image_source(file: &str, dir: &str) -> Result Result { + check_image_source(file, dir, true) +} + +/// Validates a picture path already resolved against `dir` without joining `dir` a second time. +/// Applies the same safety checks as [`local_image_source`]. +pub fn check_resolved_image_source(file: &str, dir: &str) -> Result { + check_image_source(file, dir, false) +} + /// Whether `path` is relative to the project's folder: not absolute (`/…`, `\…`, `C:\…`), not /// on a drive (`C:…`, see [`is_drive_relative`]) and not a web address. pub fn is_relative(path: &str) -> bool { diff --git a/crates/map/src/qgis/tests.rs b/crates/map/src/qgis/tests.rs index 04c825c782..30a8d7ed93 100644 --- a/crates/map/src/qgis/tests.rs +++ b/crates/map/src/qgis/tests.rs @@ -3437,4 +3437,9 @@ fn picture_annotations_reject_unsafe_paths() { report.notes ); } + + // A relative picture path whose first segment happens to match a relative project folder is + // still resolved relative to `dir` rather than treated as already resolved. + assert_eq!(local_image_source("maps/logo.png", "maps"), Ok(ImageSource::File("maps/maps/logo.png".into()))); + assert_eq!(check_resolved_image_source("data/../pic.png", "data"), Ok(ImageSource::File("data/../pic.png".into()))); } From 1c52d3f4d8d7b7f8d5e9a13670841b821d40400c Mon Sep 17 00:00:00 2001 From: giswqs Date: Wed, 25 Nov 2026 12:48:22 -0500 Subject: [PATCH 8/9] Check resolved UNC picture paths against project folder --- crates/map/src/qgis/source.rs | 16 +++++++++++++--- crates/map/src/qgis/tests.rs | 12 ++++++++++++ 2 files changed, 25 insertions(+), 3 deletions(-) diff --git a/crates/map/src/qgis/source.rs b/crates/map/src/qgis/source.rs index a2b46463fe..d38b167b44 100644 --- a/crates/map/src/qgis/source.rs +++ b/crates/map/src/qgis/source.rs @@ -1028,6 +1028,11 @@ pub enum ImageSource { File(String), } +/// Whether `path` starts with two path separators (`\\`, `//`, `/\`, `\/`), i.e. a UNC/network share. +fn is_unc_path(path: &str) -> bool { + path.len() > 1 && path.chars().take(2).all(|c| c == '\\' || c == '/') +} + /// Strips the user-opened project folder `dir` and its following separator from `file`, returning /// the remainder. For UNC project folders, `/` and `\` are treated as equivalent in the prefix so /// Qt's forward-slash UNC spelling matches a Windows backslash folder. @@ -1039,7 +1044,7 @@ fn strip_project_dir<'a>(file: &'a str, dir: &str) -> Option<&'a str> { if let Some(rest) = file.strip_prefix(base).and_then(|r| r.strip_prefix(['/', '\\'])) { return Some(rest); } - if base.len() > 1 && base.chars().take(2).all(|c| c == '\\' || c == '/') { + if is_unc_path(base) { let mut f = file.char_indices(); for bc in base.chars() { let (_, fc) = f.next()?; @@ -1093,7 +1098,7 @@ fn check_image_source(file: &str, dir: &str, resolve: bool) -> Result 1 && file.chars().take(2).all(|c| c == '\\' || c == '/') { + } else if is_unc_path(file) { // Looking a share up can sign in to the host the file names, which a style or // project chose (as an archive on one isn't opened either). Err("whose image is on a network share, which RustGIS doesn't open") @@ -1102,7 +1107,12 @@ fn check_image_source(file: &str, dir: &str, resolve: bool) -> Result Date: Sat, 28 Nov 2026 18:15:10 -0500 Subject: [PATCH 9/9] Share the image share rule with markers and the archive path rule A raster image or SVG marker in a project on a network share reads only the images in the project's own folder, as a picture annotation does, and matches attachment: in either case. A tile layer's archive path refuses the shares and drive-relative paths the tile reader refuses, so a layer accepted on import doesn't fail when it draws. --- crates/map/src/qgis/source.rs | 19 ++++++++++++-- crates/map/src/qgis/symbol.rs | 26 ++++++++----------- crates/map/src/qgis/tests.rs | 33 ++++++++++++++++++++++++ crates/map/src/tiles.rs | 48 ++++++++++++++++++++++++++++++----- 4 files changed, 102 insertions(+), 24 deletions(-) diff --git a/crates/map/src/qgis/source.rs b/crates/map/src/qgis/source.rs index 946a02e439..232ed83664 100644 --- a/crates/map/src/qgis/source.rs +++ b/crates/map/src/qgis/source.rs @@ -1098,6 +1098,19 @@ fn is_under_project_dir(file: &str, dir: &str) -> bool { const LEAVES_SHARED_FOLDER: &str = "whose image file leaves the project's folder on a network share, which RustGIS doesn't open outside that folder"; +/// Why an image at `path` (already joined to `dir` when relative) on a network share isn't read, +/// or `None` when it isn't on one or is inside the project's folder `dir`: the rule a raster image +/// or SVG marker's file and a picture annotation share. +pub(super) fn share_refusal(path: &str, dir: &str) -> Option<&'static str> { + if !is_unc_path(path) || is_under_project_dir(path, dir) { + None + } else if strip_project_dir(path, dir).is_some() { + Some(LEAVES_SHARED_FOLDER) + } else { + Some("whose image is on a network share, which RustGIS doesn't open") + } +} + /// Shared validation for [`local_image_source`] (`resolve = true`, for raw XML paths) and /// [`check_resolved_image_source`] (`resolve = false`, for paths already resolved against `dir`). fn check_image_source(file: &str, dir: &str, resolve: bool) -> Result { @@ -1132,8 +1145,10 @@ fn check_image_source(file: &str, dir: &str, resolve: bool) -> Result Result { diff --git a/crates/map/src/qgis/symbol.rs b/crates/map/src/qgis/symbol.rs index 97357f0f7c..d77e88d21c 100644 --- a/crates/map/src/qgis/symbol.rs +++ b/crates/map/src/qgis/symbol.rs @@ -909,13 +909,6 @@ fn rooted(path: &str) -> bool { path.starts_with(['/', '\\']) || (b.first().is_some_and(u8::is_ascii_alphabetic) && b.get(1) == Some(&b':')) } -/// Whether image path `file` names a network share (`\\host\share`, `//host/share`), which isn't -/// opened: looking one up can sign in to the host, and a project may be opened on Windows, where -/// `//` is one (as `paths::is_absolute_local` refuses it on every platform). -fn network_share(file: &str) -> bool { - file.len() > 1 && file.chars().take(2).all(|c| c == '\\' || c == '/') -} - /// Reads the images of the raster image and SVG markers under `root` (a project or a style), each /// `imageFile` or SVG `name` once, an SVG with `param(…)` values once for each set of colours its /// layers give it (a file once for each spelling of its path from the folder: a @@ -923,7 +916,8 @@ fn network_share(file: &str) -> bool { /// [`marker_image`]: a `base64:` one as it is, a file's through `read` (relative to `dir`; a /// `file:` address is the file it names). /// One at a web address isn't fetched, nor one on a network share (`\\host\share`, `//host/share`, -/// `file://host/share`), nor one kept inside a `.qgz` +/// `file://host/share`) outside the project's own folder on it (`source::share_refusal`), nor one +/// kept inside a `.qgz` /// (`attachment:`); one relative to no folder (or to a drive's working folder) isn't looked /// for, and those past the pictures a run keeps ([`MAX_PICTURES`], /// [`MAX_PICTURES_BYTES`]) aren't read. An image is kept when read, before its symbol is: one @@ -955,14 +949,17 @@ pub(super) fn read_images(root: Node, dir: &str, read: &mut ReadImage, report: & }; let source = if file.starts_with("base64:") { Ok(None) - } else if file.starts_with("attachment:") { + } else if file.get(..11).is_some_and(|p| p.eq_ignore_ascii_case("attachment:")) { Err("whose image is kept inside the .qgz project, which RustGIS doesn't read it from") } else if path.contains("://") && (!address || file.trim_start_matches("file:").trim_start_matches('/').contains("://")) { Err("whose image is at a web address, which RustGIS doesn't fetch") - } else if share || network_share(&path) { + } else if share { // Looking a share up can sign in to the host the file names, which a style or // project chose (as an archive on one isn't opened either). Err("whose image is on a network share, which RustGIS doesn't open") + } else if let Some(why) = super::source::share_refusal(&path, dir) { + // Only a project's own folder on a share is read, not the rest of the share. + Err(why) } else if address && !rooted(&path) && path.contains("://") { // `%3A%2F%2F` in a name is a name, but `absolute` would leave one from the project's folder to // the working folder. @@ -974,11 +971,10 @@ pub(super) fn read_images(root: Node, dir: &str, read: &mut ReadImage, report: & } else { let joined = super::source::absolute(&path, dir); // `.//host/share` from a project at a drive's root (`/`) is `//host/share` once joined; a project - // that is itself on a share reads its own images. - if network_share(&joined) && !network_share(dir) { - Err("whose image is on a network share, which RustGIS doesn't open") - } else { - Ok(Some(joined)) + // that is itself on a share reads the images in its own folder, not the rest of the share. + match super::source::share_refusal(&joined, dir) { + Some(why) => Err(why), + None => Ok(Some(joined)), } }; if let Ok(Some(path)) = &source diff --git a/crates/map/src/qgis/tests.rs b/crates/map/src/qgis/tests.rs index 50bb75b71e..f75d7c4e83 100644 --- a/crates/map/src/qgis/tests.rs +++ b/crates/map/src/qgis/tests.rs @@ -1857,6 +1857,39 @@ fn raster_image_markers_read_a_file_address_as_the_file_it_names() { } } +/// A raster image marker follows a picture annotation's rules: a project on a share reads the images +/// in its own folder, not the rest of the share, and a `.qgz` attachment is one in either case. +#[test] +fn raster_image_markers_on_a_share_stay_in_the_project_folder() { + let asked = std::cell::RefCell::new(Vec::new()); + let mut read = |source: &str, _: Option<&SvgColours>| { + asked.borrow_mut().push(source.to_string()); + Ok(("QUJD".to_string(), 1.0, false)) + }; + let dir = r"\\nas\gis\proj"; + for (file, refusal) in [ + (r"..\..\x.png", Some("leaves the project's folder")), + (r"\\nas\gis\proj\..\other\x.png", Some("leaves the project's folder")), + (r"\\other\share\x.png", Some("network share")), + ("ATTACHMENT:x.png", Some(".qgz project")), + ("sub/x.png", None), + (r"\\NAS\gis\proj\x.png", None), + ] { + asked.borrow_mut().clear(); + let mut report = Report::default(); + let s = super::read_style(&marker_qml("1", &raster_marker(file, "")), "Pins", dir, &mut read, &mut report).unwrap(); + let Some(Renderer::Single(sym)) = &s.renderer else { panic!("{file}") }; + match refusal { + Some(why) => { + assert_eq!(sym.marker, Marker::Circle, "{file}"); + assert!(asked.borrow().is_empty(), "{file}: {:?}", asked.borrow()); + assert!(report.notes.iter().any(|n| n.text.contains(why)), "{file}: {:?}", report.notes); + } + None => assert_eq!(asked.borrow().len(), 1, "{file}: {:?}", report.notes), + } + } +} + /// A raster image marker whose image a field or an expression gives has no image of its own to /// read; the note says that, not that it has none. #[test] diff --git a/crates/map/src/tiles.rs b/crates/map/src/tiles.rs index 5dc39d8391..d3c4b34ae7 100644 --- a/crates/map/src/tiles.rs +++ b/crates/map/src/tiles.rs @@ -634,17 +634,28 @@ pub fn is_local_archive(url: &str) -> bool { } /// Whether an archive's file path may be read: absolute, a `.` file (`pmtiles`, -/// `mbtiles`), no longer than 4096 bytes. +/// `mbtiles`), no longer than 4096 bytes. The same rules as the tile reader's +/// (`rustgis_tiles::pmtiles::check_local_prefix`, a crate this one can't depend on), so a layer +/// accepted here isn't refused when it draws. pub fn check_path(path: &str, ext: &str) -> Result<(), String> { - let p = path.strip_prefix("file://").unwrap_or(path); + let (file_url, p) = match path.strip_prefix("file://") { + Some(p) => (true, p), + None => (false, path), + }; if p.len() > 4096 || p.chars().any(char::is_control) { return Err("the path is too long or has control characters".into()); } - let windows_drive = p.as_bytes().get(1) == Some(&b':') && p.as_bytes().first().is_some_and(u8::is_ascii_alphabetic); - // Not a network share (\\server\share, or file://server/…), which a project could use to - // make Windows connect to another machine. - let share = p.starts_with("\\\\") || p.starts_with("//") || (path.starts_with("file://") && !p.starts_with('/')); - if share || !(p.starts_with('/') || windows_drive) { + let sep = |b: Option<&u8>| matches!(b, Some(b'/' | b'\\')); + let double_sep = |q: &str| sep(q.as_bytes().first()) && sep(q.as_bytes().get(1)); + let drive = |q: &str| q.as_bytes().first().is_some_and(u8::is_ascii_alphabetic) && q.as_bytes().get(1) == Some(&b':'); + let drive_abs = drive(p) && sep(p.as_bytes().get(2)); + // Not a network share (`\\server\share`, `//server/share`, `/\server\share`, `\/server/share`, + // or `file://server/…`), which a project could use to make Windows connect to another machine, + // nor a drive's working folder (`C:map.pmtiles`, `file:///C:map.pmtiles`). + let share = double_sep(p) + || (file_url + && (!p.starts_with('/') || p.strip_prefix('/').is_some_and(|r| double_sep(r) || (drive(r) && !sep(r.as_bytes().get(2)))))); + if share || !(p.starts_with('/') || drive_abs) { return Err(format!("'{p}': give the full path of the archive on this computer")); } if !p.to_ascii_lowercase().ends_with(&format!(".{ext}")) { @@ -764,6 +775,29 @@ impl TileLayer { mod tests { use super::*; + #[test] + fn archive_paths_refuse_shares_and_drive_relative_paths() { + for refused in [ + "C:map.pmtiles", + r"/\server\share\a.pmtiles", + r"\/server/share/a.pmtiles", + r"\\server\share\a.pmtiles", + "//server/share/a.pmtiles", + r"file:///\\server\share\a.pmtiles", + "file:////server/share/a.pmtiles", + "file://server/share/a.pmtiles", + "file:///C:map.pmtiles", + "relative/a.pmtiles", + ] { + assert!(check_path(refused, "pmtiles").is_err(), "{refused} was accepted"); + } + for accepted in + ["/data/a.pmtiles", r"C:\data\a.pmtiles", "C:/data/a.pmtiles", "file:///data/a.pmtiles", "file:///C:/data/a.pmtiles"] + { + assert_eq!(check_path(accepted, "pmtiles"), Ok(()), "{accepted}"); + } + } + #[test] fn invalid_secret_tile_addresses_keep_the_validation_reason() { for (url, reason) in [