From 80dbe64540189e9dad14dbef0272cbfaa74698da Mon Sep 17 00:00:00 2001 From: giswqs Date: Wed, 25 Nov 2026 09:14:41 -0500 Subject: [PATCH 1/5] Tighten hostname, path, CRS, SVG, and transport boundary validation Tighten input validation and transport boundaries across tiles, render, data, assistant, web, and CLI crates: - Parse AWS S3 hostnames from the right after stripping `.amazonaws.com` in `rustgis-tiles::s3`, accepting only valid S3 endpoint forms (`s3`, `s3.`, `s3-`, `s3.dualstack.`) with valid region and bucket names. - Reject all leading slash/backslash share combinations and drive-relative paths in local PMTiles and MBTiles path validation. - Validate normalized ArcGIS portal origins with `address::check`, bound decoded response sizes in ArcGIS and Copernicus auth helpers, and disable environment proxies on auth agents. - Disable DTD parsing (`allow_dtd: false`) in SVG picture loading. - Tokenize GDAL PROJ strings on whitespace with required `+` prefixes and refuse `model` and shift/model PROJ operations in `proj_key_refused`. - Normalize query parameter names when extracting MySQL/MariaDB passwords and redact credential query parameters from returned public addresses. - Require absolute `PATH` entries when resolving assistant ACP binaries. - Omit Copernicus tokens on bare web requests, render startup errors with DOM text nodes, reject empty or `"null"` embed origins, and sanitize disallowed assistant URLs with omitted credentials and referrer in `rustgis-web`. - Redact URL credentials in CLI `--trace` output and create trace files with mode `0o600` on Unix. --- apps/rustgis-cli/src/main.rs | 62 ++++++++-- apps/rustgis-web/src/embed.rs | 13 +++ apps/rustgis-web/src/request.rs | 35 ++++++ apps/rustgis-web/src/web.rs | 24 +++- crates/assistant/src/acp.rs | 29 ++--- crates/data/src/raster/crs.rs | 17 ++- crates/data/src/raster/gdal.rs | 14 ++- crates/data/src/source/myconn.rs | 13 ++- crates/render/src/picture/svg.rs | 8 +- crates/tiles/src/arcgis_auth.rs | 32 ++++- crates/tiles/src/arcgis_auth/tests.rs | 16 ++- crates/tiles/src/arcgis_token.rs | 3 +- crates/tiles/src/arcgis_token/tests.rs | 1 + crates/tiles/src/copernicus.rs | 16 ++- crates/tiles/src/copernicus/tests.rs | 45 ++++++++ crates/tiles/src/mbtiles.rs | 23 +++- crates/tiles/src/pmtiles.rs | 28 ++++- crates/tiles/src/s3.rs | 154 +++++++++++++++++++------ 18 files changed, 441 insertions(+), 92 deletions(-) diff --git a/apps/rustgis-cli/src/main.rs b/apps/rustgis-cli/src/main.rs index 8587a9e391..073b03fbd4 100644 --- a/apps/rustgis-cli/src/main.rs +++ b/apps/rustgis-cli/src/main.rs @@ -576,16 +576,10 @@ fn ask(s: &mut Session, args: &[String], saved: Option<&Saved>, env: &Environmen let trace = opt(args, "--trace").map(std::path::PathBuf::from); 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 { - eprintln!("rustgis-cli: {}: {e}", path.display()); - } + if let Some(path) = &trace + && let Err(e) = write_trace_entry(path, req, &r) + { + eprintln!("rustgis-cli: {}: {e}", path.display()); } r }; @@ -606,6 +600,28 @@ fn ask(s: &mut Session, args: &[String], saved: Option<&Saved>, env: &Environmen Ok(()) } +/// Appends one `--trace` exchange with URL credentials redacted and owner-only permissions on Unix. +fn write_trace_entry( + path: &std::path::Path, + req: &rustgis_assistant::HttpRequest, + r: &Result, +) -> std::io::Result<()> { + let resp = match r { + Ok(r) => format!("HTTP {}\n{}", r.status, String::from_utf8_lossy(&r.body)), + Err(e) => e.to_string(), + }; + let url = rustgis_engine::sources::address_in_message(&req.url); + let entry = format!("> {} {url}\n{}\n< {resp}\n\n", req.method, req.body.as_deref().unwrap_or("")); + let mut opts = std::fs::OpenOptions::new(); + opts.create(true).append(true); + #[cfg(unix)] + { + use std::os::unix::fs::OpenOptionsExt; + opts.mode(0o600); + } + opts.open(path).and_then(|mut f| f.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 +1325,30 @@ mod tests { } assert!(store.accounts().is_empty(), "asked for {:?}", store.accounts()); } + + #[test] + fn trace_entries_redact_url_secrets_and_set_owner_only_mode() { + let dir = std::env::temp_dir().join(format!("rustgis-cli-trace-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + let trace = dir.join("trace.log"); + let req = rustgis_assistant::HttpRequest { + method: "POST", + url: "https://generativelanguage.googleapis.com/v1beta/models/gemini:generateContent?key=secret-api-key".into(), + headers: Vec::new(), + body: Some("{}".into()), + }; + let resp = Ok(rustgis_assistant::HttpResponse { status: 200, body: b"ok".to_vec(), headers: Vec::new() }); + write_trace_entry(&trace, &req, &resp).unwrap(); + let content = std::fs::read_to_string(&trace).unwrap(); + assert!(!content.contains("secret-api-key"), "{content}"); + assert!(content.contains("generativelanguage.googleapis.com"), "{content}"); + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + let mode = std::fs::metadata(&trace).unwrap().permissions().mode() & 0o777; + assert_eq!(mode, 0o600, "expected 0600, got {mode:o}"); + } + let _ = std::fs::remove_dir_all(&dir); + } } diff --git a/apps/rustgis-web/src/embed.rs b/apps/rustgis-web/src/embed.rs index 87582004ba..40a17c1af8 100644 --- a/apps/rustgis-web/src/embed.rs +++ b/apps/rustgis-web/src/embed.rs @@ -44,6 +44,11 @@ pub enum Msg { Run { id: Value, command: String, params: Value }, } +/// Whether a `MessageEvent` origin identifies a real embedding page (never empty or opaque `"null"`). +pub fn valid_origin(origin: &str) -> bool { + !origin.is_empty() && origin != "null" +} + /// Reads a message from the page; anything else (another script's messages) is `None`. pub fn parse(v: &Value) -> Option { match v.get("rustgis")?.as_str()? { @@ -472,6 +477,14 @@ mod tests { assert_eq!(load_again("assistant_model_openai"), None); } + #[test] + fn valid_origin_rejects_empty_and_opaque_null() { + assert!(!valid_origin("")); + assert!(!valid_origin("null")); + assert!(valid_origin("https://example.org")); + assert!(valid_origin("http://127.0.0.1:8888")); + } + #[test] fn embedded_preferences_stay_in_memory_without_reading_or_writing_storage() { use std::sync::{Arc, Mutex}; diff --git a/apps/rustgis-web/src/request.rs b/apps/rustgis-web/src/request.rs index 0909c3c631..0383d0662a 100644 --- a/apps/rustgis-web/src/request.rs +++ b/apps/rustgis-web/src/request.rs @@ -55,6 +55,20 @@ pub(crate) fn destination( Ok(normalized) } +/// Returns the Copernicus Data Space authorization header only when the request is neither +/// bare (signed S3 or explicitly anonymous) nor already carrying a service login. +pub(crate) fn copernicus_authorization(bare: bool, has_login: bool, url: &str) -> Option { + if bare || has_login { None } else { rustgis_ui_egui::rustgis_engine::render::rustgis_tiles::copernicus::authorization(url) } +} + +/// Formats a disallowed AI provider URL error with any address credentials redacted. +pub(crate) fn disallowed_assistant_url_error(url: &str) -> String { + rustgis_ui_egui::rustgis_engine::data::diagnostics::message_with_address( + url, + "only HTTPS addresses, or plain HTTP on this computer or network, are allowed", + ) +} + #[cfg(test)] mod tests { use super::*; @@ -102,6 +116,27 @@ mod tests { assert!(cache::http_status(&error).is_none()); } + #[test] + fn copernicus_authorization_omits_bare_and_login_requests() { + use rustgis_ui_egui::rustgis_engine::render::rustgis_tiles::copernicus; + copernicus::logout(); + let sent = copernicus::sending(); + let body = br#"{"access_token":"synthetic-web-tok","expires_in":1800,"refresh_token":"ref"}"#; + copernicus::login_answer(&sent, "user@example.invalid", 200, body).unwrap(); + let data = "https://download.dataspace.copernicus.eu/odata/v1/Products(abc)/$value"; + assert_eq!(copernicus_authorization(false, false, data).as_deref(), Some("Bearer synthetic-web-tok")); + assert_eq!(copernicus_authorization(true, false, data), None); + assert_eq!(copernicus_authorization(false, true, data), None); + copernicus::logout(); + } + + #[test] + fn disallowed_assistant_url_error_redacts_secrets() { + let err = disallowed_assistant_url_error("http://example.org/v1/models?key=super-secret-key"); + assert!(!err.contains("super-secret-key"), "{err}"); + assert!(err.contains("only HTTPS addresses"), "{err}"); + } + fn poll(f: Pin<&mut F>) -> Poll { f.poll(&mut Context::from_waker(Waker::noop())) } diff --git a/apps/rustgis-web/src/web.rs b/apps/rustgis-web/src/web.rs index e0c7628e58..f8e0e36392 100644 --- a/apps/rustgis-web/src/web.rs +++ b/apps/rustgis-web/src/web.rs @@ -292,7 +292,13 @@ pub fn start() { match result { Ok(()) => el.remove(), Err(e) => { - el.set_inner_html(&format!("

RustGIS failed to start: {e:?}

A browser with WebGPU or WebGL2 is required.

")) + el.set_text_content(None); + for line in [format!("RustGIS failed to start: {e:?}"), "A browser with WebGPU or WebGL2 is required.".into()] { + if let Ok(p) = document.create_element("p") { + p.set_text_content(Some(&line)); + let _ = el.append_child(&p); + } + } } } } @@ -374,8 +380,12 @@ impl Embed { if !e.source().is_some_and(|s| js_sys::Object::is(&s, &from)) { return; } + let sender = e.origin(); + if !crate::embed::valid_origin(&sender) { + return; + } let mut origin = o.borrow_mut(); - if origin.as_deref().is_some_and(|known| known != e.origin()) { + if origin.as_deref().is_some_and(|known| known != sender) { return; } let Some(text) = js_sys::JSON::stringify(&e.data()).ok().and_then(|t| t.as_string()) else { @@ -385,7 +395,7 @@ impl Embed { return; }; if crate::embed::parse(&value).is_some() { - origin.get_or_insert_with(|| e.origin()); + origin.get_or_insert(sender); q.borrow_mut().push(value); ctx.request_repaint(); } @@ -778,7 +788,7 @@ async fn fetch_reached( }; // A Copernicus Data Space sign-in's token goes to its data hosts only, as on the // desktop; the request then refuses any redirect, so it never leaves them. - let copernicus = if prepared.signed || login.is_some() { None } else { copernicus::authorization(url) }; + let copernicus = crate::request::copernicus_authorization(bare, login.is_some(), url); // Only the request carries credentials: messages and cache keys keep the original address. let request = arcgis.as_deref().unwrap_or(login_url); // URL parsing in a browser can normalize a numeric or escaped hostname. Judge @@ -1161,13 +1171,15 @@ async fn http( let limit = reply_limit(&req); let err = |e: wasm_bindgen::JsValue| format!("{e:?}"); if !allowed_url(&req.url) { - return Err(format!("{}: only HTTPS addresses, or plain HTTP on this computer or network, are allowed", req.url).into()); + return Err(crate::request::disallowed_assistant_url_error(&req.url).into()); } let window = web_sys::window().ok_or("no window")?; let init = web_sys::RequestInit::new(); init.set_method(req.method); - // The API key is never carried on to another address. + // The API key is never carried on to another address; no cookies or referrer leave with it. init.set_redirect(web_sys::RequestRedirect::Error); + init.set_credentials(web_sys::RequestCredentials::Omit); + init.set_referrer_policy(web_sys::ReferrerPolicy::NoReferrer); let headers = web_sys::Headers::new().map_err(err)?; for (k, v) in &req.headers { headers.set(k, v).map_err(err)?; diff --git a/crates/assistant/src/acp.rs b/crates/assistant/src/acp.rs index 5d0f27e555..4a137c388f 100644 --- a/crates/assistant/src/acp.rs +++ b/crates/assistant/src/acp.rs @@ -749,16 +749,16 @@ impl Session { /// Where a program is on the PATH (with Windows' extensions: `.exe`, `.cmd`, `.bat`), if anywhere. #[cfg(not(target_arch = "wasm32"))] pub fn find_program(program: &str) -> Option { - find_program_in(program, &std::env::var_os("PATH")?, &std::env::current_dir().ok()?) + find_program_in(program, &std::env::var_os("PATH")?) } #[cfg(not(target_arch = "wasm32"))] -fn find_program_in(program: &str, path: &std::ffi::OsStr, cwd: &std::path::Path) -> Option { +fn find_program_in(program: &str, path: &std::ffi::OsStr) -> Option { let exts: &[&str] = if cfg!(windows) { &[".exe", ".cmd", ".bat"] } else { &[""] }; - std::env::split_paths(path).filter(|p| !p.as_os_str().is_empty()).find_map(|dir| { - let dir = if dir.is_absolute() { dir } else { cwd.join(dir) }; - exts.iter().map(|e| dir.join(format!("{program}{e}"))).find(|p| p.is_absolute() && runnable(p)) - }) + // Absolute entries only: an empty or relative one would resolve against the current folder. + std::env::split_paths(path) + .filter(|p| p.is_absolute()) + .find_map(|dir| exts.iter().map(|e| dir.join(format!("{program}{e}"))).find(|p| p.is_absolute() && runnable(p))) } /// A file the shell would run: on Unix, one with an execute bit. @@ -838,7 +838,7 @@ mod mode_tests { #[cfg(all(test, not(target_arch = "wasm32")))] mod lookup_tests { #[test] - fn relative_path_entries_are_resolved_before_the_agents_work_directory_changes() { + fn relative_and_empty_path_entries_are_ignored() { let root = tempfile::tempdir().unwrap(); let tools = root.path().join("tools"); std::fs::create_dir_all(&tools).unwrap(); @@ -850,19 +850,22 @@ mod lookup_tests { // Not executable: not found, as the shell wouldn't run it. std::fs::set_permissions(&file, PermissionsExt::from_mode(0o644)).unwrap(); let path = std::env::join_paths([tools.as_path()]).unwrap(); - assert!(super::find_program_in("test-agent", &path, root.path()).is_none()); + assert!(super::find_program_in("test-agent", &path).is_none()); std::fs::set_permissions(&file, PermissionsExt::from_mode(0o755)).unwrap(); } - let path = std::env::join_paths([std::path::Path::new(""), std::path::Path::new("tools")]).unwrap(); - let found = super::find_program_in("test-agent", &path, root.path()).unwrap(); + // Absolute PATH entries are found. + let abs_path = std::env::join_paths([tools.as_path()]).unwrap(); + let found = super::find_program_in("test-agent", &abs_path).unwrap(); assert!(found.is_absolute()); - assert_eq!(std::fs::canonicalize(&found).unwrap(), std::fs::canonicalize(file).unwrap()); + assert_eq!(std::fs::canonicalize(&found).unwrap(), std::fs::canonicalize(&file).unwrap()); + // Empty and relative PATH entries are ignored, even if they point to an executable. + let rel_path = std::env::join_paths([std::path::Path::new(""), std::path::Path::new("."), std::path::Path::new("tools")]).unwrap(); + assert!(super::find_program_in("test-agent", &rel_path).is_none()); let empty = std::env::join_paths([std::path::Path::new("")]).unwrap(); let current = root.path().join(if cfg!(windows) { "dot-only.exe" } else { "dot-only" }); std::fs::write(¤t, b"program").unwrap(); - // Executable, so only the empty PATH entry keeps it from being found. #[cfg(unix)] std::fs::set_permissions(¤t, std::os::unix::fs::PermissionsExt::from_mode(0o755)).unwrap(); - assert!(super::find_program_in("dot-only", &empty, root.path()).is_none()); + assert!(super::find_program_in("dot-only", &empty).is_none()); } } diff --git a/crates/data/src/raster/crs.rs b/crates/data/src/raster/crs.rs index 9a53e37034..020b77d762 100644 --- a/crates/data/src/raster/crs.rs +++ b/crates/data/src/raster/crs.rs @@ -440,8 +440,12 @@ fn validate_proj_string(proj4: &str) -> Result<(), String> { pub(crate) fn proj_key_refused(key: &str, val: &str) -> bool { let key = key.trim().to_ascii_lowercase(); key.contains("grid") - || ["init", "file", "catalog", "step"].contains(&key.as_str()) - || (key == "proj" && val.trim().eq_ignore_ascii_case("pipeline")) + || ["init", "file", "catalog", "step", "model"].contains(&key.as_str()) + || (key == "proj" + && matches!( + val.trim().to_ascii_lowercase().as_str(), + "pipeline" | "defmodel" | "tinshift" | "gridshift" | "hgridshift" | "vgridshift" | "xyzgridshift" + )) } impl Crs { @@ -3453,7 +3457,16 @@ mod tests { "+proj=utm +zone=33 +gridlist=x", "+proj=pipeline +step +proj=utm +zone=33", "+PROJ=Pipeline +step +proj=utm +zone=33", + "+proj=merc nadgrids=foo.gsb", + "+proj=defmodel +model=foo.json", + "+proj=tinshift", + "+proj=hgridshift", + "+proj=vgridshift", + "+proj=xyzgridshift", + "+proj=gridshift", + "+proj=utm +zone=33 +model=foo.json", ] { + assert!(validate_proj_string(bad).is_err(), "{bad}"); assert!(Crs::parse(bad).is_err(), "{bad}"); } // A file's own definition may carry `+nadgrids=@null` (Web Mercator as GDAL writes it). diff --git a/crates/data/src/raster/gdal.rs b/crates/data/src/raster/gdal.rs index e3da8bfa0c..f14b74e58d 100644 --- a/crates/data/src/raster/gdal.rs +++ b/crates/data/src/raster/gdal.rs @@ -484,9 +484,11 @@ fn valid_crs(c: &str) -> bool { // pipeline, are refused (the same check as for typed definitions). let proj = c.starts_with("+proj=") && c.chars().all(|ch| ch.is_ascii_alphanumeric() || " +=_.,-".contains(ch)) - && !c.split('+').any(|kv| { - let (k, v) = kv.split_once('=').unwrap_or((kv, "")); - super::crs::proj_key_refused(k, v) + && c.split_whitespace().all(|token| { + token.strip_prefix('+').is_some_and(|kv| { + let (k, v) = kv.split_once('=').unwrap_or((kv, "")); + !k.is_empty() && !super::crs::proj_key_refused(k, v) + }) }); let urn = up.starts_with("URN:OGC:DEF:CRS:") && c.chars().all(|ch| ch.is_ascii_alphanumeric() || ":._-".contains(ch)); !c.chars().any(char::is_control) && (code(&up) || wkt || proj || urn) @@ -749,6 +751,12 @@ mod tests { "+proj=pipeline +step +proj=hgridshift +grids=ntv2.gsb", "+proj=utm +zone=33 +vgrids=egm96_15.gtx", "+proj=deformation +xy_grids=a.tif", + "+proj=merc nadgrids=foo.gsb", + "+proj=defmodel +model=foo.json", + "+proj=tinshift +file=foo.json", + "+proj=hgridshift", + "GEOGCS[\"WGS 84\",EXTENSION[\"PROJ4\",\"+proj=defmodel +model=foo.json\"]]", + "GEOGCS[\"WGS 84\",EXTENSION[\"PROJ4\",\"+proj=merc nadgrids=foo.gsb\"]]", "GEOGCS[\"WGS 84\",EXTENSION[\"PROJ4\",\"+proj=longlat +nadgrids=/tmp/grid.gsb\"]]", "GEOGCS[\"WGS 84\",extension[\"proj4_grids\",\"ntv2_0.gsb\"]]", "PROJCS[\"x\",GEOGCS[\"y\"],\"+geoidgrids=egm96.gtx\"]", diff --git a/crates/data/src/source/myconn.rs b/crates/data/src/source/myconn.rs index 6b2aac79fd..4056a44428 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)?; + crate::address::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 crate::address::normalized_name(k).is_some_and(|n| n == "password" || n == "pass") { password = Some(super::pgconn::percent_decode(v)); } else { kept.push(kv); @@ -108,6 +110,13 @@ mod tests { assert_eq!(s("mysql://h/gis?ssl-ca=/a@b.pem"), ("mysql://h/gis?ssl-ca=/a@b.pem".into(), None)); assert_eq!(s("mysql://me:p#w?x@h:3306/gis#f"), ("mysql://me@h:3306/gis".into(), Some("p#w?x".into()))); assert_eq!(s("mysql://me@h/gis?pass=a%26b&ssl-mode=DISABLED"), ("mysql://me@h/gis?ssl-mode=DISABLED".into(), Some("a&b".into()))); + assert_eq!( + s("mysql://me@h/gis?pass%77ord=secret&ssl-mode=REQUIRED"), + ("mysql://me@h/gis?ssl-mode=REQUIRED".into(), Some("secret".into())) + ); + assert_eq!(s("mysql://me@h/gis?pa%73s=secret"), ("mysql://me@h/gis".into(), Some("secret".into()))); + assert_eq!(s("mysql://me@h/gis?token=secret&ssl-mode=REQUIRED"), ("mysql://me@h/gis?ssl-mode=REQUIRED".into(), None)); + assert_eq!(s("mysql://me@h/gis?pwd=secret&ssl-mode=REQUIRED"), ("mysql://me@h/gis?ssl-mode=REQUIRED".into(), None)); assert!(split_password("postgres:host=h").is_none()); assert_eq!(database_name("mysql://me@h:3306/my%20db?x=1").as_deref(), Some("my db")); assert_eq!(database_name("mysql://h"), None); diff --git a/crates/render/src/picture/svg.rs b/crates/render/src/picture/svg.rs index 2dc44450bf..2ba629cd8b 100644 --- a/crates/render/src/picture/svg.rs +++ b/crates/render/src/picture/svg.rs @@ -86,7 +86,7 @@ const STOPS_PER_UNIT: u64 = 16; /// run ([`Refusal::PastRun`]) when below [`CSS_STEPS`]; `matched` is set to the steps it took, /// refused or not, which its length doesn't bound, for the run to be charged them. pub(super) fn read(text: &str, cap: u64, matched: &mut u64) -> Result { - let xml = roxmltree::ParsingOptions { allow_dtd: true, nodes_limit: XML_NODES, ..Default::default() }; + let xml = roxmltree::ParsingOptions { allow_dtd: false, nodes_limit: XML_NODES, ..Default::default() }; let doc = roxmltree::Document::parse_with_options(text, xml).map_err(|e| match e { roxmltree::Error::NodesLimitReached => Refusal::TooNested, _ => Refusal::NotSvg, @@ -1120,6 +1120,12 @@ mod tests { assert_eq!(read("not xml").err(), Some(Refusal::NotSvg)); let laughs = r#"]>&g;"#; assert_eq!(read(laughs).err(), Some(Refusal::NotSvg)); + // Any internal DTD entity subset is refused outright (allow_dtd: false). + let entity = r#"]>"#; + assert_eq!(read(entity).err(), Some(Refusal::NotSvg)); + // Plain DOCTYPE without an internal subset behaves cleanly without panicking. + let plain_doctype = r#""#; + let _ = read(plain_doctype); // The same in an attribute's value, quickly. let started = std::time::Instant::now(); assert_eq!(read(&laughs.replace("&g;", r#""#)).err(), Some(Refusal::NotSvg)); diff --git a/crates/tiles/src/arcgis_auth.rs b/crates/tiles/src/arcgis_auth.rs index dd001e4145..eb0094ab15 100644 --- a/crates/tiles/src/arcgis_auth.rs +++ b/crates/tiles/src/arcgis_auth.rs @@ -93,6 +93,7 @@ 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"))?; + crate::address::check(&origin, None)?; if origin == "https://arcgis.com" { return Ok(ONLINE.to_string()); } @@ -863,6 +864,7 @@ mod native { // A token request is never redirected: a redirect would replay the code or the refresh token. ureq::Agent::config_builder() .tls_config(rustgis_data::http::tls_config()) + .proxy(None) .http_status_as_error(!forms) .timeout_global(Some(REQUEST_TIMEOUT)) .user_agent(concat!("RustGIS/", env!("CARGO_PKG_VERSION"), " (+https://rustgis.app)")) @@ -873,6 +875,21 @@ mod native { }) } + /// Reads at most `max` decoded bytes from `reader`, refusing larger payloads. + fn read_limited(reader: impl Read, max: usize) -> Result, String> { + let mut buf = Vec::new(); + reader.take(max as u64 + 1).read_to_end(&mut buf).map_err(|e| e.to_string())?; + if buf.len() > max { + return Err(format!("larger than {max} bytes")); + } + Ok(buf) + } + + /// Bounds both wire and decoded bytes (when gzip expands them) to `max`. + fn read_bounded(mut body: ureq::Body, max: usize) -> Result, String> { + read_limited(body.with_config().limit(max as u64 + 2).reader(), max) + } + /// POSTs a form; a refusal's answer (an OAuth `error`, often with HTTP 400) is returned for /// the caller to read, while a server error (5xx) counts as the portal not being reached. fn post_form(url: &str, body: &str) -> Result, String> { @@ -891,7 +908,7 @@ mod native { if status >= 500 { return Err(format!("the portal answered HTTP {status}")); } - resp.into_body().with_config().limit(1 << 20).read_to_vec().map_err(|e| e.to_string()) + read_bounded(resp.into_body(), 1 << 20) } /// Request preparation (including TLS setup) can wait; the final send has its own check. @@ -912,7 +929,7 @@ mod native { .header("Accept", "application/json") .call() .map_err(|e| e.to_string())?; - resp.into_body().with_config().limit(4 << 20).read_to_vec().map_err(|e| e.to_string()) + read_bounded(resp.into_body(), 4 << 20) } /// Starts signing in to `portal` (blank: ArcGIS Online) with an OAuth app's `client_id`: @@ -1178,6 +1195,17 @@ mod native { assert!(revoke_all_with(refuse, Vec::new()).is_ok()); } + #[cfg(test)] + #[test] + fn bounded_body_reader_and_proxy_configuration() { + assert!(agent(true).config().proxy().is_none()); + assert!(agent(false).config().proxy().is_none()); + assert_eq!(read_limited(std::io::Cursor::new(vec![b'a'; 16]), 16).unwrap().len(), 16); + assert!(read_limited(std::io::Cursor::new(vec![b'a'; 17]), 16).unwrap_err().contains("larger than 16")); + // An unbounded stream stops at max + 1 bytes instead of allocating indefinitely. + assert!(read_limited(std::io::repeat(b'x'), 64).unwrap_err().contains("larger than 64")); + } + /// The request line's target of an HTTP request. fn request_target(stream: &mut TcpStream) -> Option { let mut buf = Vec::new(); diff --git a/crates/tiles/src/arcgis_auth/tests.rs b/crates/tiles/src/arcgis_auth/tests.rs index 1dbba61735..1636f67b18 100644 --- a/crates/tiles/src/arcgis_auth/tests.rs +++ b/crates/tiles/src/arcgis_auth/tests.rs @@ -86,9 +86,19 @@ 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"] - { + assert_eq!(portal_base("https://127.0.0.1:7443/portal").unwrap(), "https://127.0.0.1:7443/portal"); + // Tokens travel to the portal: never over plain HTTP, never with user info, never to forbidden hosts. + 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://metadata.google.internal/portal", + "https://0.0.0.0/portal", + "https://100.100.100.200/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")); diff --git a/crates/tiles/src/arcgis_token.rs b/crates/tiles/src/arcgis_token.rs index 61a8607b74..838a863da5 100644 --- a/crates/tiles/src/arcgis_token.rs +++ b/crates/tiles/src/arcgis_token.rs @@ -221,9 +221,10 @@ 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(|| { + pub(super) static AGENT: LazyLock = LazyLock::new(|| { ureq::Agent::config_builder() .tls_config(rustgis_data::http::tls_config()) + .proxy(None) .http_status_as_error(false) .timeout_global(Some(Duration::from_secs(DEADLINE_SECS))) .user_agent(concat!("RustGIS/", env!("CARGO_PKG_VERSION"), " (+https://rustgis.app)")) diff --git a/crates/tiles/src/arcgis_token/tests.rs b/crates/tiles/src/arcgis_token/tests.rs index c6d46f880c..b4051afe13 100644 --- a/crates/tiles/src/arcgis_token/tests.rs +++ b/crates/tiles/src/arcgis_token/tests.rs @@ -328,5 +328,6 @@ mod native { super::super::native::finish(&slot, Err("again".into())); assert_eq!(received.recv().unwrap(), Ok(("test-token".to_string(), Some(FUTURE)))); assert!(received.try_recv().is_err(), "done is called once"); + assert!(super::super::native::AGENT.config().proxy().is_none()); } } diff --git a/crates/tiles/src/copernicus.rs b/crates/tiles/src/copernicus.rs index a59403384a..07876ba656 100644 --- a/crates/tiles/src/copernicus.rs +++ b/crates/tiles/src/copernicus.rs @@ -632,6 +632,7 @@ pub use native::{Restored, authorization_fresh, login, restore}; #[cfg(not(target_arch = "wasm32"))] mod native { + use std::io::Read; use std::sync::{Mutex, OnceLock}; use std::time::Duration; @@ -641,11 +642,12 @@ mod native { /// The agent for token requests: never redirected (a redirect would replay the password or /// the refresh token), an error status answered for the caller to read. - fn agent() -> &'static ureq::Agent { + pub(crate) fn agent() -> &'static ureq::Agent { static A: OnceLock = OnceLock::new(); A.get_or_init(|| { ureq::Agent::config_builder() .tls_config(rustgis_data::http::tls_config()) + .proxy(None) .http_status_as_error(false) .timeout_global(Some(REQUEST_TIMEOUT)) .user_agent(concat!("RustGIS/", env!("CARGO_PKG_VERSION"), " (+https://rustgis.app)")) @@ -656,13 +658,23 @@ mod native { }) } + /// Reads at most `max` decoded bytes from a response body, bounding compressed expansion too. + fn read_bounded(mut body: ureq::Body, max: usize) -> Result, String> { + let mut buf = Vec::new(); + body.with_config().limit(max as u64 + 2).reader().take(max as u64 + 1).read_to_end(&mut buf).map_err(|e| e.to_string())?; + if buf.len() > max { + return Err(format!("larger than {max} bytes")); + } + Ok(buf) + } + /// POSTs a form; its status and answer. The error never quotes the form. fn post_form(url: &str, body: &str, still: &Option) -> Result<(u16, Vec), String> { let req = agent().post(url).header("Content-Type", "application/x-www-form-urlencoded").header("Accept", "application/json"); crate::cache::check_still(still)?; let resp = req.send(body).map_err(|e| format!("couldn't reach Copernicus Data Space's sign-in: {e}"))?; let status = resp.status().as_u16(); - let bytes = resp.into_body().with_config().limit(1 << 20).read_to_vec().map_err(|e| e.to_string())?; + let bytes = read_bounded(resp.into_body(), 1 << 20)?; Ok((status, bytes)) } diff --git a/crates/tiles/src/copernicus/tests.rs b/crates/tiles/src/copernicus/tests.rs index 2ef81e4e0a..752c5e0d10 100644 --- a/crates/tiles/src/copernicus/tests.rs +++ b/crates/tiles/src/copernicus/tests.rs @@ -154,6 +154,51 @@ fn a_refused_sign_in_says_why_without_the_password_and_keeps_the_one_before() { logout(); } +fn gzip_bytes(data: &[u8]) -> Vec { + let mut crc = 0xffff_ffffu32; + for &b in data { + crc ^= u32::from(b); + for _ in 0..8 { + crc = if crc & 1 != 0 { (crc >> 1) ^ 0xedb8_8320 } else { crc >> 1 }; + } + } + let crc = !crc; + let mut out = vec![0x1f, 0x8b, 8, 0, 0, 0, 0, 0, 0, 0xff]; + out.extend(miniz_oxide::deflate::compress_to_vec(data, 6)); + out.extend_from_slice(&crc.to_le_bytes()); + out.extend_from_slice(&(data.len() as u32).to_le_bytes()); + out +} + +#[test] +fn token_responses_bound_decompressed_size_and_bypass_proxies() { + let _turn = crate::cache::turn(); + logout(); + assert!(native::agent().config().proxy().is_none()); + // A small gzipped JSON response whose decompressed payload exceeds the 1 MiB limit is rejected. + let pad = "a".repeat((1 << 20) + 1024); + let big = format!(r#"{{"access_token":"tok","expires_in":1800,"refresh_token":"ref","pad":"{pad}"}}"#); + let gz = gzip_bytes(big.as_bytes()); + assert!(gz.len() < 16 << 10, "compressed payload stays small: {}", gz.len()); + let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap(); + let addr = listener.local_addr().unwrap(); + let server = std::thread::spawn(move || { + if let Ok((mut stream, _)) = listener.accept() { + let _ = read_request(&mut stream); + let head = format!( + "HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Encoding: gzip\r\nContent-Length: {}\r\nConnection: close\r\n\r\n", + gz.len() + ); + let _ = stream.write_all(head.as_bytes()); + let _ = stream.write_all(&gz); + } + }); + let err = login_at(&format!("http://{addr}/token"), USER, PASSWORD, None).unwrap_err(); + let _ = server.join(); + assert!(err.contains("larger than"), "{err}"); + assert_eq!(authorization(DATA), None); +} + /// The web app sends the sign-in itself and lands its answer: kept as a sign-in made here is, /// renewed at CDSE's token endpoint, and a refusal or a server error leaves the one before. #[test] diff --git a/crates/tiles/src/mbtiles.rs b/crates/tiles/src/mbtiles.rs index 6ae5b87539..a4c58003cf 100644 --- a/crates/tiles/src/mbtiles.rs +++ b/crates/tiles/src/mbtiles.rs @@ -60,8 +60,10 @@ pub fn check(archive: &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); - let share = p.starts_with("\\\\") || p.starts_with("//") || (archive.starts_with("file://") && !p.starts_with('/')); + let drive = p.as_bytes().get(1) == Some(&b':') + && p.as_bytes().first().is_some_and(u8::is_ascii_alphabetic) + && matches!(p.as_bytes().get(2), Some(b'/' | b'\\')); + let share = matches!(p.as_bytes(), [b'/' | b'\\', b'/' | b'\\', ..]) || (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")); } @@ -606,10 +608,21 @@ 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("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/x.mbtiles", + "\\/server/share/x.mbtiles", + "file:///\\server/share/x.mbtiles", + "C:relative.mbtiles", + "file://server/a.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..f0775bd6fd 100644 --- a/crates/tiles/src/pmtiles.rs +++ b/crates/tiles/src/pmtiles.rs @@ -204,10 +204,12 @@ pub fn check_local(archive: &str) -> Result<(), String> { /// 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('/')); + let drive = p.as_bytes().get(1) == Some(&b':') + && p.as_bytes().first().is_some_and(u8::is_ascii_alphabetic) + && matches!(p.as_bytes().get(2), Some(b'/' | b'\\')); + // A path on this computer: not a network share (\\server\share, mixed /\ or \/, or + // file://server/…), which a project could use to make Windows connect to another machine. + let share = matches!(p.as_bytes(), [b'/' | b'\\', b'/' | b'\\', ..]) || (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")); } @@ -1896,6 +1898,24 @@ pub(crate) mod tests { rx.recv_timeout(std::time::Duration::from_secs(10)).map_err(|e| e.to_string())? } + #[test] + fn check_local_rejects_mixed_shares_and_drive_relative_paths() { + for good in ["/data/a.pmtiles", "C:\\data\\a.pmtiles", "C:/data/a.pmtiles", "file:///data/a.pmtiles"] { + assert!(check_local(good).is_ok(), "{good}"); + } + for bad in [ + "/\\server/share/x.pmtiles", + "\\/server/share/x.pmtiles", + "\\\\server\\share\\x.pmtiles", + "//server/share/x.pmtiles", + "file:///\\server/share/x.pmtiles", + "C:relative.pmtiles", + "relative/x.pmtiles", + ] { + assert!(check_local(bad).is_err(), "{bad}"); + } + } + #[test] fn written_archives_read_back() { let _turn = crate::cache::turn(); diff --git a/crates/tiles/src/s3.rs b/crates/tiles/src/s3.rs index 04bff65431..1561d4cb0a 100644 --- a/crates/tiles/src/s3.rs +++ b/crates/tiles/src/s3.rs @@ -461,6 +461,20 @@ pub fn public_url(url: &str, region: Option<&str>) -> Result { Ok(object_url(&bucket, &key, at.as_ref())) } +/// Whether `r` has the form of an AWS region code (two-letter area, lowercase words, and a +/// 1-2 digit number, such as `us-east-1`, `ap-southeast-2`, or `us-gov-west-1`). +fn valid_aws_region(r: &str) -> bool { + let parts: Vec<&str> = r.split('-').collect(); + let Some((number, words)) = parts.split_last() else { return false }; + let word = |w: &&str| !w.is_empty() && w.bytes().all(|b| b.is_ascii_lowercase()); + r.len() <= 30 + && words.len() >= 2 + && words.first().is_some_and(|a| a.len() == 2) + && words.iter().all(word) + && (1..=2).contains(&number.len()) + && number.bytes().all(|b| b.is_ascii_digit()) +} + /// The region an S3 refusal says a bucket is in, when it was asked at the wrong endpoint: a bucket /// in a region AWS opts in (af-south-1, Digital Earth Africa's) asked at the global endpoint /// ("The af-south-1 location constraint is incompatible…"), or an endpoint named in a redirect @@ -470,16 +484,7 @@ pub fn public_url(url: &str, region: Option<&str>) -> Result { pub fn region_in(text: &str) -> Option { let region = |r: &str| { let r = r.trim_matches(|c: char| !c.is_ascii_alphanumeric()); - let parts: Vec<&str> = r.split('-').collect(); - let (number, words) = parts.split_last()?; - let word = |w: &&str| !w.is_empty() && w.bytes().all(|b| b.is_ascii_lowercase()); - (r.len() <= 30 - && words.len() >= 2 - && words.first().is_some_and(|a| a.len() == 2) - && words.iter().all(word) - && (1..=2).contains(&number.len()) - && number.bytes().all(|b| b.is_ascii_digit())) - .then(|| r.to_string()) + valid_aws_region(r).then(|| r.to_string()) }; let constraint = text.split_once(" location constraint").and_then(|(before, _)| before.rsplit(' ').next()).and_then(region); constraint.or_else(|| text.split(".s3.").skip(1).find_map(|after| after.split_once(".amazonaws.com").and_then(|(r, _)| region(r)))) @@ -584,7 +589,7 @@ fn bound_target(address: &str) -> Result<(String, Connection), String> { } else { rest.split_once('/').map(|(_, p)| p).unwrap_or("").split(['?', '#']).next().unwrap_or("").is_empty() }; - let root_region = host.strip_prefix("s3.").and_then(|r| r.strip_suffix(".amazonaws.com")); + let root_region = parse_aws_host(host).filter(|p| p.bucket.is_none()).and_then(|p| p.region); let (c, granted) = snapshot(bucket.as_deref())?; let allowed = match bucket.as_deref() { Some(bucket) => c.buckets.iter().any(|b| b == bucket) || granted, @@ -739,12 +744,53 @@ fn canonical_path(path: &str) -> String { path.split('/').map(|part| encode(&rustgis_data::address::percent_decode(part), true)).collect::>().join("/") } +/// A parsed AWS S3 hostname (`*.amazonaws.com`), split from the right. +struct AwsHost<'a> { + bucket: Option<&'a str>, + region: Option<&'a str>, +} + +/// Parses a lower-case AWS S3 hostname from the right after stripping `.amazonaws.com`. +/// Accepts only valid S3 endpoint forms: `s3`, `s3.`, `s3-`, and +/// `s3.dualstack.`, each optionally preceded by `.` passing [`valid_bucket`]. +fn parse_aws_host(host: &str) -> Option> { + let prefix = host.strip_suffix(".amazonaws.com")?; + if prefix.is_empty() { + return None; + } + if prefix == "s3" { + return Some(AwsHost { bucket: None, region: None }); + } + if let Some(bucket) = prefix.strip_suffix(".s3") { + return valid_bucket(bucket).then_some(AwsHost { bucket: Some(bucket), region: None }); + } + let (rest, last) = match prefix.rsplit_once('.') { + Some((r, l)) => (Some(r), l), + None => (None, prefix), + }; + if let Some(region) = last.strip_prefix("s3-") { + if !valid_aws_region(region) { + return None; + } + return match rest { + None => Some(AwsHost { bucket: None, region: Some(region) }), + Some(bucket) => valid_bucket(bucket).then_some(AwsHost { bucket: Some(bucket), region: Some(region) }), + }; + } + if !valid_aws_region(last) { + return None; + } + let before = rest?; + if before == "s3" || before == "s3.dualstack" { + return Some(AwsHost { bucket: None, region: Some(last) }); + } + let bucket = before.strip_suffix(".s3.dualstack").or_else(|| before.strip_suffix(".s3"))?; + valid_bucket(bucket).then_some(AwsHost { bucket: Some(bucket), region: Some(last) }) +} + /// Whether an address (its scheme, its origin and its host, all lower-case) is at AWS S3. fn aws_host(scheme: &str, here: &str, host: &str) -> bool { - scheme == "https" - && here == format!("https://{host}") - && host.ends_with(".amazonaws.com") - && (host.starts_with("s3.") || host.contains(".s3.") || host.starts_with("s3-") || host.contains(".s3-")) + scheme == "https" && here == format!("https://{host}") && parse_aws_host(host).is_some() } /// The region an address at AWS S3 names (`s3..amazonaws.com`), else `default`. The @@ -753,17 +799,7 @@ fn aws_region(url: &str, default: &str) -> String { let rest = url.split_once("://").map(|(_, r)| r).unwrap_or(url); let authority = rest.split(['/', '?', '#']).next().unwrap_or(""); let host = authority.split(':').next().unwrap_or(authority); - let after = host - .rsplit_once(".s3.") - .map(|(_, a)| a) - .or_else(|| host.strip_prefix("s3.")) - .or_else(|| host.rsplit_once(".s3-").map(|(_, a)| a)) - .or_else(|| host.strip_prefix("s3-")); - after - .and_then(|a| a.split('.').next()) - .filter(|r| !r.is_empty() && *r != "amazonaws" && *r != "dualstack") - .map(str::to_string) - .unwrap_or_else(|| default.to_string()) + parse_aws_host(host).and_then(|p| p.region).unwrap_or(default).to_string() } /// The connection whose credentials sign a request to `url`, and the region it is signed for: @@ -781,7 +817,7 @@ fn signer_for(url: &str) -> Result, String> { let host = authority.split(':').next().unwrap_or(authority); let aws = aws_host(scheme, &here, host); let bucket = aws_bucket(host, rest); - let list_region = host.strip_prefix("s3.").and_then(|r| r.strip_suffix(".amazonaws.com")); + let list_region = parse_aws_host(host).filter(|p| p.bucket.is_none()).and_then(|p| p.region); let path = rest.split_once('/').map(|(_, p)| p).unwrap_or(""); let list_root = path.split(['?', '#']).next().unwrap_or("").is_empty(); // Parse before locking; only selected connections are cloned while the registry is held. @@ -811,18 +847,12 @@ fn signer_for(url: &str) -> Result, String> { })) } -/// The bucket an AWS S3 address names: its host's first label (virtual-hosted) or its path's -/// first part (path-style at `s3..amazonaws.com`). +/// The bucket an AWS S3 address names: its virtual-hosted prefix or its path's first segment +/// (path-style at an AWS S3 endpoint). fn aws_bucket(host: &str, rest: &str) -> Option { - // Virtual-hosted: bucket.s3.amazonaws.com, bucket.s3..amazonaws.com, or the legacy - // bucket.s3-.amazonaws.com. - if let Some(b) = host - .split_once(".s3.") - .map(|(b, _)| b) - .or_else(|| host.strip_suffix(".s3.amazonaws.com")) - .or_else(|| host.split_once(".s3-").map(|(b, _)| b)) - { - return Some(b.to_string()); + let parsed = parse_aws_host(host)?; + if let Some(bucket) = parsed.bucket { + return Some(bucket.to_string()); } let path = rest.split_once('/').map(|(_, p)| p).unwrap_or(""); path.split(['/', '?', '#']).next().filter(|b| valid_bucket(b)).map(str::to_string) @@ -1203,6 +1233,54 @@ mod tests { // Path style: the first path segment. assert_eq!(b("s3-us-west-2.amazonaws.com", "s3-us-west-2.amazonaws.com/data/a.tif").as_deref(), Some("data")); assert_eq!(b("s3.amazonaws.com", "s3.amazonaws.com/data/a.tif").as_deref(), Some("data")); + // Dualstack virtual-hosted and path-style endpoints. + assert_eq!( + b("data.s3.dualstack.eu-west-1.amazonaws.com", "data.s3.dualstack.eu-west-1.amazonaws.com/a.tif").as_deref(), + Some("data") + ); + assert_eq!(b("s3.dualstack.eu-west-1.amazonaws.com", "s3.dualstack.eu-west-1.amazonaws.com/data/a.tif").as_deref(), Some("data")); + } + + #[test] + fn aws_host_and_bucket_parsing_rejects_non_s3_and_ambiguous_hosts() { + // Non-S3 *.amazonaws.com hosts must be rejected by both aws_host and aws_bucket. + for bad in [ + "s3-foo.us-east-1.elb.amazonaws.com", + "bucket.s3.us-east-1.elb.amazonaws.com", + "bucket.s3.notaregion.amazonaws.com", + "bucket.s3-notaregion.amazonaws.com", + "s3.notaregion.amazonaws.com", + "s3-foo.amazonaws.com", + "ab.s3.amazonaws.com", + "s3.s3.amazonaws.com", + "my.s3.amazonaws.com.evil.example", + "ec2-1-2-3-4.compute-1.amazonaws.com", + ] { + let origin = format!("https://{bad}"); + assert!(!aws_host("https", &origin, bad), "{bad}"); + assert_eq!(aws_bucket(bad, &format!("{bad}/data/a.tif")), None, "{bad}"); + assert_eq!(bucket_of("", &format!("https://{bad}/data/a.tif")), None, "{bad}"); + } + // Valid S3 endpoints parse from the right: a bucket containing `.s3.` is not truncated + // at the leftmost `.s3.`, so a connection for `mine` will not match `mine.s3.other`. + assert!(aws_host("https", "https://mine.s3.other.s3.us-west-2.amazonaws.com", "mine.s3.other.s3.us-west-2.amazonaws.com")); + assert_eq!( + aws_bucket("mine.s3.other.s3.us-west-2.amazonaws.com", "mine.s3.other.s3.us-west-2.amazonaws.com/k").as_deref(), + Some("mine.s3.other") + ); + assert_eq!(aws_region("https://mine.s3.other.s3.us-west-2.amazonaws.com/k", "us-east-1"), "us-west-2"); + assert_eq!( + aws_bucket("mine.s3.us-east-1.s3.amazonaws.com", "mine.s3.us-east-1.s3.amazonaws.com/k").as_deref(), + Some("mine.s3.us-east-1") + ); + assert_eq!(aws_region("https://mine.s3.us-east-1.s3.amazonaws.com/k", "eu-west-1"), "eu-west-1"); + assert_eq!( + aws_bucket("mine.s3.dualstack.ap-southeast-2.amazonaws.com", "mine.s3.dualstack.ap-southeast-2.amazonaws.com/k").as_deref(), + Some("mine") + ); + assert_eq!(aws_region("https://mine.s3.dualstack.ap-southeast-2.amazonaws.com/k", "us-east-1"), "ap-southeast-2"); + assert_eq!(aws_region("https://s3.dualstack.ap-southeast-2.amazonaws.com/mine/k", "us-east-1"), "ap-southeast-2"); + assert_eq!(aws_region("https://mine.s3-eu-west-1.amazonaws.com/k", "us-east-1"), "eu-west-1"); } fn example() -> Credentials { From 9dd3fcf6142e954441ab6ebf00a6de1e7aaac7e0 Mon Sep 17 00:00:00 2001 From: giswqs Date: Wed, 25 Nov 2026 09:34:29 -0500 Subject: [PATCH 2/5] Allow plain SVG DOCTYPEs and split interior PROJ '+' tokens - Keep `allow_dtd: true` in `rustgis-render::picture::svg::read` so plain `` declarations remain valid, while rejecting any input containing an ASCII case-insensitive ` String { /// `xy_grids`, `z_grids`, `gridlist`…), so a grid key PROJ adds later is refused too. fn validate_proj_string(proj4: &str) -> Result<(), String> { for token in proj4.split_whitespace() { - let t = token.trim_start_matches('+'); - let (key, val) = t.split_once('=').unwrap_or((t, "")); - if proj_key_refused(key, val) { - return Err(format!("parameter '+{t}' is not allowed in coordinate system definition")); - } - if val.contains("..") || val.contains('/') || val.contains('\\') { - return Err("file path in parameter is not allowed in coordinate system definition".into()); + for part in token.trim_start_matches('+').split('+') { + let (key, val) = part.split_once('=').unwrap_or((part, "")); + if proj_key_refused(key, val) { + return Err(format!("parameter '+{part}' is not allowed in coordinate system definition")); + } + if val.contains("..") || val.contains('/') || val.contains('\\') { + return Err("file path in parameter is not allowed in coordinate system definition".into()); + } } } Ok(()) @@ -3458,6 +3459,7 @@ mod tests { "+proj=pipeline +step +proj=utm +zone=33", "+PROJ=Pipeline +step +proj=utm +zone=33", "+proj=merc nadgrids=foo.gsb", + "+proj=merc+nadgrids=foo.gsb", "+proj=defmodel +model=foo.json", "+proj=tinshift", "+proj=hgridshift", diff --git a/crates/data/src/raster/gdal.rs b/crates/data/src/raster/gdal.rs index f14b74e58d..a885cbb260 100644 --- a/crates/data/src/raster/gdal.rs +++ b/crates/data/src/raster/gdal.rs @@ -485,9 +485,11 @@ fn valid_crs(c: &str) -> bool { let proj = c.starts_with("+proj=") && c.chars().all(|ch| ch.is_ascii_alphanumeric() || " +=_.,-".contains(ch)) && c.split_whitespace().all(|token| { - token.strip_prefix('+').is_some_and(|kv| { - let (k, v) = kv.split_once('=').unwrap_or((kv, "")); - !k.is_empty() && !super::crs::proj_key_refused(k, v) + token.strip_prefix('+').is_some_and(|rest| { + rest.split('+').all(|kv| { + let (k, v) = kv.split_once('=').unwrap_or((kv, "")); + !k.is_empty() && !super::crs::proj_key_refused(k, v) + }) }) }); let urn = up.starts_with("URN:OGC:DEF:CRS:") && c.chars().all(|ch| ch.is_ascii_alphanumeric() || ":._-".contains(ch)); @@ -752,6 +754,7 @@ mod tests { "+proj=utm +zone=33 +vgrids=egm96_15.gtx", "+proj=deformation +xy_grids=a.tif", "+proj=merc nadgrids=foo.gsb", + "+proj=merc+nadgrids=foo.gsb", "+proj=defmodel +model=foo.json", "+proj=tinshift +file=foo.json", "+proj=hgridshift", diff --git a/crates/render/src/picture/svg.rs b/crates/render/src/picture/svg.rs index 2ba629cd8b..38e16c9b8d 100644 --- a/crates/render/src/picture/svg.rs +++ b/crates/render/src/picture/svg.rs @@ -86,7 +86,12 @@ const STOPS_PER_UNIT: u64 = 16; /// run ([`Refusal::PastRun`]) when below [`CSS_STEPS`]; `matched` is set to the steps it took, /// refused or not, which its length doesn't bound, for the run to be charged them. pub(super) fn read(text: &str, cap: u64, matched: &mut u64) -> Result { - let xml = roxmltree::ParsingOptions { allow_dtd: false, nodes_limit: XML_NODES, ..Default::default() }; + // Plain `` declarations (such as from Inkscape or Illustrator) are kept, + // while DTD entity declarations are refused outright before XML parsing. + if text.as_bytes().windows(8).any(|w| w.eq_ignore_ascii_case(b" Refusal::TooNested, _ => Refusal::NotSvg, @@ -1120,12 +1125,12 @@ mod tests { assert_eq!(read("not xml").err(), Some(Refusal::NotSvg)); let laughs = r#"]>&g;"#; assert_eq!(read(laughs).err(), Some(Refusal::NotSvg)); - // Any internal DTD entity subset is refused outright (allow_dtd: false). + // Any internal DTD entity declaration is refused outright, while a plain DOCTYPE without entities parses. let entity = r#"]>"#; assert_eq!(read(entity).err(), Some(Refusal::NotSvg)); - // Plain DOCTYPE without an internal subset behaves cleanly without panicking. + assert_eq!(read(&entity.replace(""#; - let _ = read(plain_doctype); + assert!(read(plain_doctype).is_ok(), "a plain DOCTYPE is a valid SVG"); // The same in an attribute's value, quickly. let started = std::time::Instant::now(); assert_eq!(read(&laughs.replace("&g;", r#""#)).err(), Some(Refusal::NotSvg)); From 05d5cfecc3d6270619963616f58f528210fe2faf Mon Sep 17 00:00:00 2001 From: giswqs Date: Sat, 28 Nov 2026 19:38:34 -0500 Subject: [PATCH 3/5] fix(tiles): keep FIPS, accelerate and us-east-1 S3 hosts as AWS Parse the endpoint labels from the right so `s3-fips.`, `s3-fips.dualstack.`, `s3-accelerate[.dualstack]` and the legacy `s3-external-1` stay AWS S3 hosts, as they were before the stricter parser. Drops the dotted `s3.dualstack` literal the command id scan took for a command. --- crates/tiles/src/s3.rs | 75 +++++++++++++++++++++++++----------------- 1 file changed, 44 insertions(+), 31 deletions(-) diff --git a/crates/tiles/src/s3.rs b/crates/tiles/src/s3.rs index 1561d4cb0a..a9a379cc26 100644 --- a/crates/tiles/src/s3.rs +++ b/crates/tiles/src/s3.rs @@ -751,41 +751,37 @@ struct AwsHost<'a> { } /// Parses a lower-case AWS S3 hostname from the right after stripping `.amazonaws.com`. -/// Accepts only valid S3 endpoint forms: `s3`, `s3.`, `s3-`, and -/// `s3.dualstack.`, each optionally preceded by `.` passing [`valid_bucket`]. +/// Accepts only S3 endpoint forms: `s3`, `s3.`, `s3-`, `s3.dualstack.`, +/// `s3-fips.`, `s3-fips.dualstack.`, `s3-accelerate`, `s3-accelerate.dualstack` +/// and the legacy `s3-external-1` (us-east-1), each optionally preceded by `.` passing +/// [`valid_bucket`]. Any other `*.amazonaws.com` host is not S3. fn parse_aws_host(host: &str) -> Option> { let prefix = host.strip_suffix(".amazonaws.com")?; - if prefix.is_empty() { - return None; - } - if prefix == "s3" { - return Some(AwsHost { bucket: None, region: None }); - } - if let Some(bucket) = prefix.strip_suffix(".s3") { - return valid_bucket(bucket).then_some(AwsHost { bucket: Some(bucket), region: None }); - } - let (rest, last) = match prefix.rsplit_once('.') { - Some((r, l)) => (Some(r), l), - None => (None, prefix), + let labels: Vec<&str> = prefix.split('.').collect(); + // The label `back` places from the right (1 is the last). + let at = |back: usize| labels.len().checked_sub(back).and_then(|i| labels.get(i)).copied(); + let last = at(1)?; + // How many labels the endpoint takes, and the region it names. + let (taken, region) = match last { + "s3" | "s3-accelerate" => (1, None), + "s3-external-1" => (1, Some("us-east-1")), + "dualstack" if at(2) == Some("s3-accelerate") => (2, None), + _ => match last.strip_prefix("s3-") { + Some(region) if valid_aws_region(region) => (1, Some(region)), + Some(_) => return None, + None if !valid_aws_region(last) => return None, + None => match (at(3), at(2)) { + (_, Some("s3" | "s3-fips")) => (2, Some(last)), + (Some("s3" | "s3-fips"), Some("dualstack")) => (3, Some(last)), + _ => return None, + }, + }, }; - if let Some(region) = last.strip_prefix("s3-") { - if !valid_aws_region(region) { - return None; - } - return match rest { - None => Some(AwsHost { bucket: None, region: Some(region) }), - Some(bucket) => valid_bucket(bucket).then_some(AwsHost { bucket: Some(bucket), region: Some(region) }), - }; - } - if !valid_aws_region(last) { - return None; - } - let before = rest?; - if before == "s3" || before == "s3.dualstack" { - return Some(AwsHost { bucket: None, region: Some(last) }); + if taken == labels.len() { + return Some(AwsHost { bucket: None, region }); } - let bucket = before.strip_suffix(".s3.dualstack").or_else(|| before.strip_suffix(".s3"))?; - valid_bucket(bucket).then_some(AwsHost { bucket: Some(bucket), region: Some(last) }) + let bucket = prefix.rsplitn(taken + 1, '.').nth(taken)?; + valid_bucket(bucket).then_some(AwsHost { bucket: Some(bucket), region }) } /// Whether an address (its scheme, its origin and its host, all lower-case) is at AWS S3. @@ -1281,6 +1277,23 @@ mod tests { assert_eq!(aws_region("https://mine.s3.dualstack.ap-southeast-2.amazonaws.com/k", "us-east-1"), "ap-southeast-2"); assert_eq!(aws_region("https://s3.dualstack.ap-southeast-2.amazonaws.com/mine/k", "us-east-1"), "ap-southeast-2"); assert_eq!(aws_region("https://mine.s3-eu-west-1.amazonaws.com/k", "us-east-1"), "eu-west-1"); + // FIPS, Transfer Acceleration and the legacy us-east-1 endpoint are S3 too. + for (host, bucket, region) in [ + ("mine.s3-fips.us-gov-west-1.amazonaws.com", Some("mine"), "us-gov-west-1"), + ("mine.s3-fips.dualstack.us-east-1.amazonaws.com", Some("mine"), "us-east-1"), + ("mine.s3-accelerate.amazonaws.com", Some("mine"), "eu-west-1"), + ("mine.s3-accelerate.dualstack.amazonaws.com", Some("mine"), "eu-west-1"), + ("s3-external-1.amazonaws.com", None, "us-east-1"), + ("mine.s3-external-1.amazonaws.com", Some("mine"), "us-east-1"), + ] { + assert!(aws_host("https", &format!("https://{host}"), host), "{host}"); + let rest = format!("{host}/mine/k"); + assert_eq!(aws_bucket(host, &rest).as_deref(), Some("mine"), "{host}"); + assert_eq!(parse_aws_host(host).and_then(|p| p.bucket), bucket, "{host}"); + assert_eq!(aws_region(&format!("https://{host}/k"), "eu-west-1"), region, "{host}"); + } + assert!(parse_aws_host("dualstack.amazonaws.com").is_none()); + assert!(parse_aws_host("mine.s3-fips.amazonaws.com").is_none()); } fn example() -> Credentials { From 972cb668e96c86737087d87f31b8548b7040f98b Mon Sep 17 00:00:00 2001 From: giswqs Date: Sat, 28 Nov 2026 20:34:31 -0500 Subject: [PATCH 4/5] fix(tiles): take an AWS region whose first word has up to four letters The European Sovereign Cloud's eusc-de-east-1 has a four-letter first word, so the stricter S3 host parser no longer took it for AWS. --- crates/tiles/src/s3.rs | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/crates/tiles/src/s3.rs b/crates/tiles/src/s3.rs index a9a379cc26..8909e30027 100644 --- a/crates/tiles/src/s3.rs +++ b/crates/tiles/src/s3.rs @@ -461,7 +461,7 @@ pub fn public_url(url: &str, region: Option<&str>) -> Result { Ok(object_url(&bucket, &key, at.as_ref())) } -/// Whether `r` has the form of an AWS region code (two-letter area, lowercase words, and a +/// Whether `r` has the form of an AWS region code (a two- to four-letter area such as `eusc`, lowercase words, and a /// 1-2 digit number, such as `us-east-1`, `ap-southeast-2`, or `us-gov-west-1`). fn valid_aws_region(r: &str) -> bool { let parts: Vec<&str> = r.split('-').collect(); @@ -469,7 +469,7 @@ fn valid_aws_region(r: &str) -> bool { let word = |w: &&str| !w.is_empty() && w.bytes().all(|b| b.is_ascii_lowercase()); r.len() <= 30 && words.len() >= 2 - && words.first().is_some_and(|a| a.len() == 2) + && words.first().is_some_and(|a| (2..=4).contains(&a.len())) && words.iter().all(word) && (1..=2).contains(&number.len()) && number.bytes().all(|b| b.is_ascii_digit()) @@ -1293,6 +1293,10 @@ mod tests { assert_eq!(aws_region(&format!("https://{host}/k"), "eu-west-1"), region, "{host}"); } assert!(parse_aws_host("dualstack.amazonaws.com").is_none()); + // A region whose first word is longer than two letters (the European Sovereign Cloud's). + let esc = "mine.s3.eusc-de-east-1.amazonaws.com"; + assert!(aws_host("https", &format!("https://{esc}"), esc)); + assert_eq!(aws_region(&format!("https://{esc}/k"), "us-east-1"), "eusc-de-east-1"); assert!(parse_aws_host("mine.s3-fips.amazonaws.com").is_none()); } From 663c99531c5bf23a0f0e20b637eb14f669e3c1df Mon Sep 17 00:00:00 2001 From: giswqs Date: Sat, 28 Nov 2026 21:07:43 -0500 Subject: [PATCH 5/5] test(tiles): pin S3 website and amazonaws.eu hosts as not AWS S3 The European Sovereign Cloud is served at amazonaws.eu, which the S3 host parser never took; check the region's form directly instead of a .com host that doesn't exist, and pin that website endpoints, which take no signed request, are not AWS S3. --- crates/tiles/src/s3.rs | 13 +++++++++---- 1 file changed, 9 insertions(+), 4 deletions(-) diff --git a/crates/tiles/src/s3.rs b/crates/tiles/src/s3.rs index 8909e30027..48ed8a0acd 100644 --- a/crates/tiles/src/s3.rs +++ b/crates/tiles/src/s3.rs @@ -1293,10 +1293,15 @@ mod tests { assert_eq!(aws_region(&format!("https://{host}/k"), "eu-west-1"), region, "{host}"); } assert!(parse_aws_host("dualstack.amazonaws.com").is_none()); - // A region whose first word is longer than two letters (the European Sovereign Cloud's). - let esc = "mine.s3.eusc-de-east-1.amazonaws.com"; - assert!(aws_host("https", &format!("https://{esc}"), esc)); - assert_eq!(aws_region(&format!("https://{esc}/k"), "us-east-1"), "eusc-de-east-1"); + // A region code whose first word has up to four letters, such as `eusc-de-east-1`, has a + // region's form. (That region is served at amazonaws.eu, which isn't AWS S3 here, as before.) + assert!(valid_aws_region("eusc-de-east-1") && !valid_aws_region("abcde-de-east-1")); + assert!(parse_aws_host("mine.s3.eusc-de-east-1.amazonaws.eu").is_none()); + // Website endpoints serve public objects only and take no signed request: never AWS S3. + for website in ["mine.s3-website-us-east-1.amazonaws.com", "mine.s3-website.eu-west-1.amazonaws.com"] { + assert!(!aws_host("https", &format!("https://{website}"), website), "{website}"); + assert_eq!(aws_bucket(website, &format!("{website}/k")), None, "{website}"); + } assert!(parse_aws_host("mine.s3-fips.amazonaws.com").is_none()); }