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 15d3961ba4..1cb0f9679c 100644 --- a/apps/rustgis-web/src/web.rs +++ b/apps/rustgis-web/src/web.rs @@ -298,7 +298,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); + } + } } } } @@ -381,8 +387,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 { @@ -392,7 +402,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(); } @@ -796,7 +806,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 @@ -1179,13 +1189,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 2e7af0e59e..81e876cd93 100644 --- a/crates/data/src/raster/crs.rs +++ b/crates/data/src/raster/crs.rs @@ -423,13 +423,14 @@ pub fn bare_vn2000_error(text: &str) -> 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(()) @@ -441,8 +442,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 { @@ -3460,7 +3465,17 @@ 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=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..a885cbb260 100644 --- a/crates/data/src/raster/gdal.rs +++ b/crates/data/src/raster/gdal.rs @@ -484,9 +484,13 @@ 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(|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)); !c.chars().any(char::is_control) && (code(&up) || wkt || proj || urn) @@ -749,6 +753,13 @@ 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=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/render/src/picture/svg.rs b/crates/render/src/picture/svg.rs index 378510eb4b..444786fb76 100644 --- a/crates/render/src/picture/svg.rs +++ b/crates/render/src/picture/svg.rs @@ -1427,6 +1427,8 @@ mod tests { assert_eq!(read("not xml").err(), Some(Refusal::NotSvg)); let laughs = r#"]>&g;"#; assert_eq!(read(laughs).err(), Some(Refusal::TooMuchToRead)); + let plain_doctype = r#""#; + 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::TooMuchToRead)); diff --git a/crates/tiles/src/arcgis_auth.rs b/crates/tiles/src/arcgis_auth.rs index 611babe662..023d0277ae 100644 --- a/crates/tiles/src/arcgis_auth.rs +++ b/crates/tiles/src/arcgis_auth.rs @@ -880,6 +880,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> { @@ -898,7 +913,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. @@ -919,7 +934,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`: @@ -1194,6 +1209,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 0b368ccc89..fb42ecf2ba 100644 --- a/crates/tiles/src/arcgis_auth/tests.rs +++ b/crates/tiles/src/arcgis_auth/tests.rs @@ -86,6 +86,7 @@ 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"); + 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 addresses. for bad in [ "http://gis.example.org/portal", @@ -96,6 +97,7 @@ fn portal_bases() { "https://169.254.169.254/portal", "https://100.100.100.200/portal", "https://metadata.google.internal/portal", + "https://0.0.0.0/portal", ] { assert!(portal_base(bad).is_err(), "{bad}"); } diff --git a/crates/tiles/src/arcgis_token.rs b/crates/tiles/src/arcgis_token.rs index bc296e3e7d..fbd07f555d 100644 --- a/crates/tiles/src/arcgis_token.rs +++ b/crates/tiles/src/arcgis_token.rs @@ -222,7 +222,7 @@ 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(|| { let config = ureq::Agent::config_builder() .tls_config(rustgis_data::http::tls_config()) .http_status_as_error(false) diff --git a/crates/tiles/src/arcgis_token/tests.rs b/crates/tiles/src/arcgis_token/tests.rs index d8bb952edb..5151b44f2d 100644 --- a/crates/tiles/src/arcgis_token/tests.rs +++ b/crates/tiles/src/arcgis_token/tests.rs @@ -336,5 +336,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 ffdbf75e17..8c95ec4cb4 100644 --- a/crates/tiles/src/copernicus.rs +++ b/crates/tiles/src/copernicus.rs @@ -645,6 +645,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; @@ -654,7 +655,7 @@ 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(|| { let config = ureq::Agent::config_builder() @@ -670,13 +671,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/s3.rs b/crates/tiles/src/s3.rs index 04bff65431..48ed8a0acd 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 (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(); + 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| (2..=4).contains(&a.len())) + && 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,49 @@ 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 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")?; + 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 taken == labels.len() { + return Some(AwsHost { bucket: None, region }); + } + 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. 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 +795,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 +813,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 +843,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 +1229,80 @@ 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"); + // 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()); + // 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()); } fn example() -> Credentials {