Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions apps/rustgis-python/python/rustgis/_embed.py
Original file line number Diff line number Diff line change
Expand Up @@ -289,9 +289,14 @@ def _app_src(url: Optional[str], lang: Optional[str]) -> str:
Args:
url: The web app's address, or None for ``RUSTGIS_WEB_URL`` or the default.
lang: The interface language code, or None.

Raises:
ValueError: When the address is not an ``http://`` or ``https://`` URL with a host.
"""
base = url or os.environ.get("RUSTGIS_WEB_URL") or DEFAULT_URL
parts = urlsplit(base)
if parts.scheme.lower() not in ("http", "https") or not parts.netloc or not parts.hostname:
raise ValueError(f"web app url must be an http:// or https:// address with a host, got {base!r}")
kept = [q for q in parts.query.split("&") if q]
if lang:
# The app reads the first `lang`: an explicit one replaces any the address holds.
Expand Down
8 changes: 6 additions & 2 deletions apps/rustgis-python/python/rustgis/_widget.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,13 @@

function render({ model, el }) {
const src = model.get("_src");
const origin = new URL(src, window.location.href).origin;
const parsed = new URL(src, window.location.href);
if (parsed.protocol !== "http:" && parsed.protocol !== "https:") {
throw new Error(`Refusing non-HTTP(S) RustGIS app URL: ${parsed.protocol}`);
}
const origin = parsed.origin;
const iframe = document.createElement("iframe");
iframe.src = src;
iframe.src = parsed.href;
iframe.style.width = "100%";
iframe.style.height = model.get("height") || "800px";
iframe.style.border = "0";
Expand Down
61 changes: 61 additions & 0 deletions apps/rustgis-python/tests/test_embed.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
"""URL construction and validation for the embedded web app widgets."""

import shutil
import subprocess

import pytest

from rustgis._embed import WIDGET_JS, _app_src


@pytest.mark.parametrize(
"bad_url",
[
"javascript:alert(1)",
"JAVASCRIPT:alert(1)",
"data:text/html,<h1>x</h1>",
"file:///etc/passwd",
"https://",
"http://",
"https://:443",
"/relative/path",
"ftp://example.org/app",
],
)
def test_app_src_rejects_non_http_or_hostless_urls(bad_url):
with pytest.raises(ValueError):
_app_src(bad_url, None)


def test_widget_js_refuses_non_http_and_frames_https(tmp_path):
node = shutil.which("node")
if node is None:
pytest.skip("node not installed")
mjs = tmp_path / "_widget.mjs"
mjs.write_text(WIDGET_JS.read_text(encoding="utf-8"), encoding="utf-8")
script = f"""
import widget from {mjs.as_uri()!r};
globalThis.window = {{ location: {{ href: "https://notebook.example/" }}, addEventListener() {{}}, removeEventListener() {{}} }};
globalThis.document = {{ createElement() {{ return {{ style: {{}} }}; }} }};
const model = (src) => ({{ get: (k) => (k === "_src" ? src : ""), on() {{}}, off() {{}} }});
const el = {{ appended: 0, appendChild() {{ this.appended += 1; }} }};
// The guard refuses a javascript: address with its own message, not some other failure.
let message = null;
try {{
widget.render({{ model: model("javascript:alert(1)"), el }});
}} catch (e) {{
Comment thread
giswqs marked this conversation as resolved.
Resolved
message = String(e && e.message);
}}
if (!message || !message.includes("Refusing non-HTTP(S) RustGIS app URL")) {{
console.error(`expected the scheme guard to refuse javascript:, got ${{message}}`);
process.exit(1);
}}
// The same harness frames an https: address.
const cleanup = widget.render({{ model: model("https://web.rustgis.app/?embed"), el }});
if (el.appended !== 1 || typeof cleanup !== "function") {{
console.error("expected an https: address to be framed");
process.exit(1);
}}
"""
proc = subprocess.run([node, "--input-type=module", "-e", script], capture_output=True, text=True)
assert proc.returncode == 0, proc.stderr
19 changes: 14 additions & 5 deletions crates/analysis/src/kriging.rs
Original file line number Diff line number Diff line change
Expand Up @@ -368,6 +368,7 @@ fn kriging_on(
let scratch = || (Vec::<(f64, f64, Coord)>::with_capacity(points.len()), KrigingBuffers::new(), crate::control::Pace::default());
let (mut pred_data, mut var_data) = (crate::rasterops::new_band(w, h, NODATA)?, crate::rasterops::new_band(w, h, NODATA)?);
let rows = pred_data.chunks_mut(w).zip(var_data.chunks_mut(w));
let (past_pred, past_var) = (std::sync::atomic::AtomicUsize::new(0), std::sync::atomic::AtomicUsize::new(0));
crate::control::begin(h);
crate::parallel::for_each_row(rows, threads, scratch, |(near, buffers, pace), row, (pred, var): (&mut [f32], &mut [f32])| {
// East-west degrees shrink with latitude; a projected system's units don't.
Expand All @@ -387,19 +388,27 @@ fn kriging_on(
}));

if k < near.len() {
near.select_nth_unstable_by(k - 1, |a, b| a.0.partial_cmp(&b.0).unwrap_or(std::cmp::Ordering::Equal));
near.select_nth_unstable_by(k - 1, |a, b| a.0.total_cmp(&b.0));
near.truncate(k);
}

let (val, var_est) = ordinary_kriging_point(c, near, params, kx, buffers);
*pred = if val.is_finite() { val as f32 } else { NODATA };
*var = if var_est.is_finite() { var_est as f32 } else { NODATA };
// Each band counted on its own, so its note says which output lost the values.
*pred = crate::rasterops::stored_counting(val, &past_pred);
*var = crate::rasterops::stored_counting(var_est, &past_var);
}
})?;

let gt = GeoTransform { origin_x: extent.min_x, origin_y: extent.max_y, pixel_width: cell, pixel_height: -cell };
Raster::new(name, w as u32, h as u32, vec![pred_data, var_data], gt, crs, Some(NODATA as f64), ColorHint::Gray, "Float32")
.map_err(|e| e.to_string())
let mut r = Raster::new(name, w as u32, h as u32, vec![pred_data, var_data], gt, crs, Some(NODATA as f64), ColorHint::Gray, "Float32")
.map_err(|e| e.to_string())?;
// Named as the tool names its two outputs: the prediction, and `{name}_variance`.
for (band, past) in [(name.to_string(), past_pred), (format!("{name}_variance"), past_var)] {
if let Some(note) = crate::rasterops::past_f32_note(past.into_inner()) {
r.lost.push(rustgis_data::loss::Note::loss(rustgis_data::loss::LossCode::DroppedValue, format!("{band}: {note}")));
}
}
Ok(r)
}

#[cfg(test)]
Expand Down
6 changes: 3 additions & 3 deletions crates/analysis/src/network.rs
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ impl PartialOrd for State {
}
impl Ord for State {
fn cmp(&self, o: &Self) -> std::cmp::Ordering {
o.0.partial_cmp(&self.0).unwrap_or(std::cmp::Ordering::Equal)
o.0.total_cmp(&self.0)
}
}

Expand Down Expand Up @@ -1061,7 +1061,7 @@ pub fn similar(ds: &Dataset, row: usize, fields: &[usize], n: usize) -> Result<S
}
}
control::check()?;
out.sort_by(|a, b| a.1.partial_cmp(&b.1).unwrap_or(std::cmp::Ordering::Equal));
out.sort_by(|a, b| a.1.total_cmp(&b.1));
control::check()?;
out.truncate(n);
control::finish();
Expand Down Expand Up @@ -1216,7 +1216,7 @@ pub fn within_report(ds: &Dataset, rows: &[usize], at: Coord, radius_m: f64) ->
(d.is_finite() && d <= radius_m).then_some((*r, d))
})
.collect();
out.sort_by(|a, b| a.1.partial_cmp(&b.1).unwrap_or(std::cmp::Ordering::Equal));
out.sort_by(|a, b| a.1.total_cmp(&b.1));
WithinReport { rows: out, bounded, invalid_latitudes, missing_coordinates }
}

Expand Down
Loading
Loading