diff --git a/apps/rustgis-cli/src/main.rs b/apps/rustgis-cli/src/main.rs index bb09ef7a9f..e3fc54e4bb 100644 --- a/apps/rustgis-cli/src/main.rs +++ b/apps/rustgis-cli/src/main.rs @@ -655,6 +655,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; @@ -678,13 +679,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()); } } @@ -707,6 +703,110 @@ 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 (raw and JSON-escaped) +/// from trace text. +fn mask_trace_secrets(text: &str, key: &str) -> String { + 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 sensitive = rustgis_engine::data::address::log_sensitive(&k); + let k = mask_trace_secrets(&rustgis_engine::data::diagnostics::redact_parameter(&k), key); + if sensitive { + v = Value::String("[redacted]".into()); + } else { + 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 +/// 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 = scrub_trace_body(req.body.as_deref().unwrap_or(""), key); + let answer = match resp { + 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) +} + +/// 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> { @@ -1483,4 +1583,127 @@ 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}"); + } + + // 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}"); + } + + // 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)] + #[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..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('=')?; - (key.eq_ignore_ascii_case("pwd") || key.eq_ignore_ascii_case("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)) } @@ -59,6 +53,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..e197515e1c 100644 --- a/crates/data/src/source/myconn.rs +++ b/crates/data/src/source/myconn.rs @@ -15,7 +15,20 @@ 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)?; + 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. @@ -64,7 +77,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 +126,37 @@ 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 (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 bbaa734809..354c51f54c 100644 --- a/crates/engine/src/cmd/qgis.rs +++ b/crates/engine/src/cmd/qgis.rs @@ -290,7 +290,7 @@ fn import_project(s: &mut Session, p: &Value) -> CmdResult { let mut landed_on = None; let result = rustgis_data::progress::without_counting(|| { 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) @@ -1005,9 +1005,18 @@ fn saved_database_connection(s: &mut Session, what: &str, connection: &str, made } } +/// 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::check_resolved_image_source(picture, dir.unwrap_or("")) +} + /// 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 +/// files (a relative one only with the project's folder, `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, @@ -1021,7 +1030,7 @@ fn add_annotations( 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> { @@ -1087,24 +1096,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 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(path) => std::fs::metadata(path) + .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(path) => super::graphics::picture(&json!({"path": path})), + } + } }; if read.as_ref().is_ok_and(|b64| b64.len() > left) { pictures.over.insert(picture.clone()); @@ -2484,3 +2498,127 @@ 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, 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", false)), &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()); + 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()))); + + // 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); + + // A relative picture climbing out of the project's folder on the share is refused, read + // and checked again in `add_annotations`, with a note that says it leaves the folder. + let up = qgs.replace(r#"path="pic.png""#, r#"path="../img/x.png""#); + let mut up_report = Report::default(); + let up_project = qgis::read_project(&up, unc_dir, &mut |_, _| Err(("unused", false)), &mut up_report).unwrap(); + assert!(up_project.layers[0].annotations.is_empty()); + assert!(up_report.notes.iter().any(|n| n.text.contains("leaves the project's folder")), "{:?}", up_report.notes); + let mut escaping = project.layers[0].clone(); + if let Some(a) = escaping.annotations.first_mut() { + a.picture = Some(r"\\server\share\proj/../img/x.png".into()); + } + let mut s_up = Session::new(crate::Project::default()); + let mut up_pics = Pictures::default(); + let mut up_report = Report::default(); + add_annotations(&mut s_up, &escaping, Some("EPSG:4326"), None, Some(unc_dir), &mut up_pics, &mut up_report).unwrap(); + assert!(up_report.notes.iter().any(|n| n.text.contains("leaves the project's folder")), "{:?}", up_report.notes); + + // 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 dir_str = dir.to_string_lossy(); + let mut rel_report = Report::default(); + let rel_project = qgis::read_project(qgs, &dir_str, &mut |_, _| Err(("unused", false)), &mut rel_report).unwrap(); + let mut s_rel = Session::new(crate::Project::default()); + let mut rel_pics = Pictures::default(); + 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/engine/src/tests.rs b/crates/engine/src/tests.rs index 0cf477dd2f..b87ed28fca 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -4173,17 +4173,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..6703a84b2f 100644 --- a/crates/map/src/qgis/annotation.rs +++ b/crates/map/src/qgis/annotation.rs @@ -487,13 +487,23 @@ fn boxed(item: Node, kind: &str, dir: &str, layer: &str, read: &mut Reading, rep read.no_picture += 1; 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") }); + 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}")); + } + } out.extend(frame.map(wrap)); out } diff --git a/crates/map/src/qgis/mod.rs b/crates/map/src/qgis/mod.rs index 012a2137fe..012d58a81d 100644 --- a/crates/map/src/qgis/mod.rs +++ b/crates/map/src/qgis/mod.rs @@ -32,7 +32,10 @@ use crate::symbology::{Labeling, LineStroke, MarkerRotation, Renderer}; pub use annotation::{Annotation, MAX_ITEMS as MAX_ANNOTATIONS}; pub use expr::{reads_measure, to_sql}; use rustgis_data::loss::LossCode; -pub use source::{MAX_MEMORY_FIELDS, Source, VirtualFrom, WebOptions, is_drive_relative, is_relative}; +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 03e7ce4d57..232ed83664 100644 --- a/crates/map/src/qgis/source.rs +++ b/crates/map/src/qgis/source.rs @@ -1025,6 +1025,142 @@ 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), +} + +/// 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, and letters match in either +/// case, as Windows matches server, share and folder names. +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 is_unc_path(base) { + let mut f = file.char_indices(); + for bc in base.chars() { + let (_, fc) = f.next()?; + let both_sep = matches!(bc, '/' | '\\') && matches!(fc, '/' | '\\'); + if !fc.eq_ignore_ascii_case(&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 +} + +/// Why an image path that starts in a project folder on a network share but leaves it (`..`, an +/// empty segment) isn't read: only the folder the user opened is, not the rest of the share. +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 { + 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 !is_relative(file) && is_under_project_dir(file, dir) { + Ok(ImageSource::File(file.to_string())) + } else if is_unc_path(file) && strip_project_dir(file, dir).is_some() { + Err(LEAVES_SHARED_FOLDER) + } 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") + } 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 if resolve { + let resolved = absolute(file, dir); + if is_unc_path(&resolved) && !is_under_project_dir(&resolved, dir) { + Err(LEAVES_SHARED_FOLDER) + } else { + Ok(ImageSource::File(resolved)) + } + } else { + Ok(ImageSource::File(file.to_string())) + } +} + +/// Checks a QGIS picture annotation's `path` against `dir` (empty when the import has no project +/// folder). A raster image or SVG marker's file goes through `symbol::read_images`, which also +/// reads `file:` addresses but refuses shares through the same [`share_refusal`] and attachments +/// in either case, as here. 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 { + 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/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 f856355493..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] @@ -3795,6 +3828,127 @@ fn a_dropped_virtual_filter_is_not_noted_for_letter_case() { 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 + ); + } + + // 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 + ); + + // 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 + ); + } + + // 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()))); + + // A relative picture path inside a UNC project folder stays allowed when it remains under + // `dir`, but is refused when `..` climbs outside the opened share folder. + assert_eq!(local_image_source("sub/../pic.png", unc_dir), Ok(ImageSource::File(format!("{unc_dir}/sub/../pic.png")))); + for escaping in ["../other/pic.png", "sub/../../other/pic.png", "../../../other/share/pic.png"] { + assert!( + local_image_source(escaping, unc_dir).is_err_and(|e| e.contains("network share")), + "{escaping} under {unc_dir} should be refused" + ); + } + // A relative picture climbing out of a project folder on a share says it leaves that folder, + // read from the project and checked again once resolved. + let qgs = r#"EPSG:4326 + aUp + + "#; + let mut report = Report::default(); + let p = read_project(qgs, unc_dir, &mut report).unwrap(); + assert!(p.layers[0].annotations.is_empty(), "{:?}", p.layers[0].annotations); + assert!(report.notes.iter().any(|n| n.layer == "Up" && n.text.contains("leaves the project's folder")), "{:?}", report.notes); + assert!(check_resolved_image_source(r"\\nas\gis\proj/../img/x.png", unc_dir).is_err_and(|e| e.contains("leaves the project's folder"))); + // The share's server and share names (and folders) match in either case, as on Windows. + assert_eq!(local_image_source(r"\\NAS\Gis\proj\pic.png", unc_dir), Ok(ImageSource::File(r"\\NAS\Gis\proj\pic.png".into()))); + // Local sibling assets remain allowed when the project folder is local. + assert_eq!(local_image_source("../other/pic.png", "/d/proj"), Ok(ImageSource::File("/d/proj/../other/pic.png".into()))); +} + /// Layers past the most an import reads are a data loss only when one of them holds data: a /// group or annotation layer holds 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 [ 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 e59970d5b0..dcf99af21f 100644 --- a/crates/tiles/src/cache.rs +++ b/crates/tiles/src/cache.rs @@ -2563,6 +2563,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 103599af5e..604e7042dc 100644 --- a/crates/tiles/src/cog.rs +++ b/crates/tiles/src/cog.rs @@ -2812,7 +2812,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 149250aea2..ffdbf75e17 100644 --- a/crates/tiles/src/copernicus.rs +++ b/crates/tiles/src/copernicus.rs @@ -657,15 +657,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) }) } @@ -840,6 +841,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}"); + } }