Skip to content
13 changes: 13 additions & 0 deletions apps/rustgis-web/src/embed.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<Msg> {
match v.get("rustgis")?.as_str()? {
Expand Down Expand Up @@ -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};
Expand Down
35 changes: 35 additions & 0 deletions apps/rustgis-web/src/request.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<String> {
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::*;
Expand Down Expand Up @@ -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: Future + ?Sized>(f: Pin<&mut F>) -> Poll<F::Output> {
f.poll(&mut Context::from_waker(Waker::noop()))
}
Expand Down
24 changes: 18 additions & 6 deletions apps/rustgis-web/src/web.rs
Original file line number Diff line number Diff line change
Expand Up @@ -298,7 +298,13 @@ pub fn start() {
match result {
Ok(()) => el.remove(),
Err(e) => {
el.set_inner_html(&format!("<p>RustGIS failed to start: {e:?}</p><p>A browser with WebGPU or WebGL2 is required.</p>"))
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);
}
}
}
}
}
Expand Down Expand Up @@ -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 {
Expand All @@ -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();
}
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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)?;
Expand Down
29 changes: 16 additions & 13 deletions crates/assistant/src/acp.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<std::path::PathBuf> {
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<std::path::PathBuf> {
fn find_program_in(program: &str, path: &std::ffi::OsStr) -> Option<std::path::PathBuf> {
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.
Expand Down Expand Up @@ -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();
Expand All @@ -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(&current, b"program").unwrap();
// Executable, so only the empty PATH entry keeps it from being found.
#[cfg(unix)]
std::fs::set_permissions(&current, 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());
}
}
33 changes: 24 additions & 9 deletions crates/data/src/raster/crs.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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(())
Expand All @@ -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 {
Expand Down Expand Up @@ -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).
Expand Down
17 changes: 14 additions & 3 deletions crates/data/src/raster/gdal.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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| {
Comment thread
giswqs marked this conversation as resolved.
Resolved
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)
Expand Down Expand Up @@ -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\"]",
Expand Down
2 changes: 2 additions & 0 deletions crates/render/src/picture/svg.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1427,6 +1427,8 @@ mod tests {
assert_eq!(read("not xml").err(), Some(Refusal::NotSvg));
let laughs = r#"<?xml version="1.0"?><!DOCTYPE svg [<!ENTITY a "aaaaaaaaaa"><!ENTITY b "&a;&a;&a;&a;&a;&a;&a;&a;&a;&a;"><!ENTITY c "&b;&b;&b;&b;&b;&b;&b;&b;&b;&b;"><!ENTITY d "&c;&c;&c;&c;&c;&c;&c;&c;&c;&c;"><!ENTITY e "&d;&d;&d;&d;&d;&d;&d;&d;&d;&d;"><!ENTITY f "&e;&e;&e;&e;&e;&e;&e;&e;&e;&e;"><!ENTITY g "&f;&f;&f;&f;&f;&f;&f;&f;&f;&f;">]><svg xmlns="http://www.w3.org/2000/svg"><desc>&g;</desc></svg>"#;
assert_eq!(read(laughs).err(), Some(Refusal::TooMuchToRead));
let plain_doctype = r#"<?xml version="1.0"?><!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd"><svg xmlns="http://www.w3.org/2000/svg"><rect width="1" height="1"/></svg>"#;
assert!(read(plain_doctype).is_ok(), "a plain DOCTYPE is a valid SVG");
Comment thread
giswqs marked this conversation as resolved.
Resolved
// The same in an attribute's value, quickly.
let started = std::time::Instant::now();
assert_eq!(read(&laughs.replace("<desc>&g;</desc>", r#"<path d="&g;"/>"#)).err(), Some(Refusal::TooMuchToRead));
Expand Down
30 changes: 28 additions & 2 deletions crates/tiles/src/arcgis_auth.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<Vec<u8>, 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<Vec<u8>, 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<Vec<u8>, String> {
Expand All @@ -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.
Expand All @@ -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`:
Expand Down Expand Up @@ -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<String> {
let mut buf = Vec::new();
Expand Down
2 changes: 2 additions & 0 deletions crates/tiles/src/arcgis_auth/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand All @@ -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}");
}
Expand Down
2 changes: 1 addition & 1 deletion crates/tiles/src/arcgis_token.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<ureq::Agent> = LazyLock::new(|| {
pub(super) static AGENT: LazyLock<ureq::Agent> = LazyLock::new(|| {
let config = ureq::Agent::config_builder()
.tls_config(rustgis_data::http::tls_config())
.http_status_as_error(false)
Expand Down
Loading
Loading