Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
27 commits
Select commit Hold shift + click to select a range
43d589a
feat(net): send a web-service login only to its connection's origin
deniial00 Nov 2, 2026
7d19423
feat(connections): session-only logins for web-service connections
deniial00 Nov 2, 2026
f8896d3
feat(ui): login method, fields and http confirmation in the connectio…
deniial00 Nov 2, 2026
09afac9
docs(data): web-service logins and connections recorded in projects
deniial00 Nov 2, 2026
ea5f2b0
fix(connections): public connections never ask which to use; logging …
deniial00 Nov 2, 2026
7c65e05
test(tiles): two tests wait for cached state that other tests may clear
deniial00 Nov 2, 2026
452eacd
fix(connections): review fixes for anonymous reads, blank connections…
deniial00 Nov 2, 2026
954ea7c
docs(data): logged-in requests aren't redirected in the web app
deniial00 Nov 2, 2026
f86c123
fix(connections): second-round review fixes
deniial00 Nov 2, 2026
63ebc8b
docs(data): a kind change ends a login; one saved connection reads it…
deniial00 Nov 2, 2026
0685745
Merge remote-tracking branch 'origin/main' into feature-757-service-l…
deniial00 Nov 2, 2026
b055a5e
fix(connections): third-round review fixes
deniial00 Nov 2, 2026
d1cf078
fix(connections): fourth-round review fixes
deniial00 Nov 2, 2026
e66495d
Merge origin/main into feature-757-service-logins
deniial00 Nov 3, 2026
c9bb33d
fix(connections): fifth-round review fixes
deniial00 Nov 3, 2026
358a2ef
fix(connections): service requests list their connection parameter
deniial00 Nov 3, 2026
e8e0456
fix(ui): Search Catalogue's Keep matches and keeps the plain address
deniial00 Nov 3, 2026
193675f
Merge origin/main into feature-757-service-logins
deniial00 Nov 3, 2026
c2c8eb3
fix(connections): plugins' legends and notebook output carry no login
deniial00 Nov 3, 2026
4c5b02b
Merge origin/main into feature-757-service-logins
deniial00 Nov 3, 2026
1301b79
Merge origin/main into feature-757-service-logins
deniial00 Nov 3, 2026
c3b9899
Merge origin/main into feature-757-service-logins
deniial00 Nov 3, 2026
db5f465
fix(connections): a plugin can't leave a legend for a later login to …
deniial00 Nov 3, 2026
2e1169a
fix(connections): keep plugin layers anonymous across later logins
deniial00 Nov 4, 2026
f78872d
Merge origin/main into feature-757-service-logins
deniial00 Nov 4, 2026
04e480c
fix(connections): preserve anonymous service groups during refresh
deniial00 Nov 4, 2026
ed1b9e5
Merge main and fix necessary service-login review findings
deniial00 Nov 4, 2026
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
407 changes: 240 additions & 167 deletions apps/rustgis-web/src/web.rs

Large diffs are not rendered by default.

128 changes: 123 additions & 5 deletions crates/assistant/src/tools.rs
Original file line number Diff line number Diff line change
Expand Up @@ -278,13 +278,15 @@ pub fn run_with_budget(s: &mut Session, call: &ToolCall, tokens: usize) -> Resul
return Err(format!("unknown command '{id}'; find ids with search_commands"));
}
let (before, mark) = (layer_snap(s), s.notice_mark());
let r = s.run(&id, &params_arg(a)?).map_err(|e| error_with_notices(e, s, mark))?;
let r = s.run(&id, &params_arg(a)?).map_err(|e| public_text(error_with_notices(e, s, mark)))?;
with_notices(with_new_layers(r, s, &before), s, mark)
}
"run_tool" => {
let tool = str_arg(a, "tool").ok_or("tool is required")?;
let (before, mark) = (layer_snap(s), s.notice_mark());
let r = s.run("gp.run", &json!({"tool": tool, "params": params_arg(a)?})).map_err(|e| error_with_notices(e, s, mark))?;
let r = s
.run("gp.run", &json!({"tool": tool, "params": params_arg(a)?}))
.map_err(|e| public_text(error_with_notices(e, s, mark)))?;
with_notices(with_new_layers(r, s, &before), s, mark)
}
"read_features" => read_features(s, a)?,
Expand All @@ -310,7 +312,52 @@ pub fn run_with_budget(s: &mut Session, call: &ToolCall, tokens: usize) -> Resul
"test_panic" => panic!("a test tool panicked"),
other => return Err(format!("unknown tool '{other}'")),
};
Ok(bounded_json(&v, tokens))
Ok(public_result(s, v, tokens))
}

/// How deep a result is searched for runtime login addresses; what is deeper is withheld.
const MAX_DEPTH: usize = 16;

/// `text` with every runtime login wrapper (`rustgis-login:…`, alone or after a prefix such as
/// `pmtiles:…@`) replaced by its plain address. Commands return the bound addresses the app needs
/// to use a connection's login; the model and MCP clients get only the public ones.
fn public_text(text: String) -> String {
if text.contains(rustgis_engine::data::login_address::PREFIX) {
rustgis_engine::render::rustgis_tiles::logins::scrub(&text)
} else {
text
}
}

fn public_result(s: &mut Session, value: Value, tokens: usize) -> String {
let mut withheld = 0usize;
let mut value = public_addresses(value, 0, &mut withheld);
if withheld > 0 {
let mark = s.notice_mark();
s.notify(format!("Tool result: {withheld} subtrees at nesting depth {MAX_DEPTH} were withheld."), false);
if let Some(notices) = value.get_mut("notices").and_then(Value::as_array_mut) {
notices.extend(s.notices_since(mark).iter().map(|n| json!(n.text)));
} else {
value = with_notices(value, s, mark);
}
}
bounded_json(&value, tokens)
}

/// `v` with its strings made public ([`public_text`]), to a depth of [`MAX_DEPTH`].
fn public_addresses(v: Value, depth: usize, withheld: &mut usize) -> Value {
match v {
Value::String(s) => Value::String(public_text(s)),
Value::Array(a) if depth < MAX_DEPTH => Value::Array(a.into_iter().map(|x| public_addresses(x, depth + 1, withheld)).collect()),
Value::Object(o) if depth < MAX_DEPTH => {
Value::Object(o.into_iter().map(|(k, x)| (k, public_addresses(x, depth + 1, withheld))).collect())
}
Value::Array(_) | Value::Object(_) => {
*withheld = withheld.saturating_add(1);
json!("[too deep]")
}
other => other,
}
}

/// Serialize complete JSON. Oversized results become an explicit text preview envelope;
Expand Down Expand Up @@ -463,7 +510,7 @@ fn run_script(s: &mut Session, a: &Value, tokens: usize) -> Result<String, Strin
let added = with_new_layers(json!({}), s, &before).get("layersAdded").cloned().unwrap_or_else(|| json!([]));
let out = json!({"success": true, "result": last, "lines": ran.map_or(0, Vec::len), "layersAdded": added,
"notices": notices, "error": null, "duration_s": secs});
Ok(bounded_json(&out, tokens))
Ok(public_result(s, out, tokens))
}
Err(e) => {
// Nothing was kept, so no line ran and no layer was added.
Expand All @@ -472,7 +519,7 @@ fn run_script(s: &mut Session, a: &Value, tokens: usize) -> Result<String, Strin
let said: Vec<&&str> = notices.iter().filter(|t| **t != e && **t != told).collect();
let out = json!({"success": false, "result": null, "lines": 0, "layersAdded": [], "notices": said,
"error": clip(&e, 8000), "duration_s": secs});
Err(bounded_json(&out, tokens))
Err(public_result(s, out, tokens))
}
}
}
Expand Down Expand Up @@ -813,3 +860,74 @@ pub fn context(s: &Session) -> String {
}
out
}

#[cfg(test)]
#[allow(clippy::unwrap_used)]
mod tests {
use super::*;
use rustgis_engine::render::rustgis_tiles::logins;

#[test]
fn results_carry_plain_addresses_not_login_wrappers() {
let mut s = Session::new(rustgis_engine::Project::default());
let origin = "https://assistant-login757.example.org";
let definition = json!({"kind":"wmts", "address": format!("{origin}/tiles"), "auth":"header", "keyName":"X-Key"});
let id = s.run("connection.new", &definition).unwrap()["id"].as_str().unwrap().to_string();
s.run("connection.login", &json!({"id": id, "apiKey": "assistant-secret-757"})).unwrap();
let plain = format!("{origin}/tiles/{{z}}/{{x}}/{{y}}.png");
let tile = rustgis_engine::service_logins::request(&mut s, Some(&id), &plain).unwrap();
assert!(tile.starts_with(rustgis_engine::data::login_address::PREFIX));
// The app's command result keeps the bound address it reads through; the model's doesn't.
let call = |command: &str, params: Value| ToolCall {
id: String::new(),
name: "run_command".into(),
args: json!({"command": command, "params": params}),
};
let added = run_with_budget(&mut s, &call("map.addTiles", json!({"url": tile, "name": "T"})), DEFAULT_OUTPUT_TOKENS).unwrap();
let listed = run_with_budget(&mut s, &call("map.tiles", json!({})), DEFAULT_OUTPUT_TOKENS).unwrap();
assert!(s.map().tiles[0].url.starts_with("rustgis-login:"));
for text in [&added, &listed] {
assert!(!text.contains("rustgis-login:") && !text.contains("assistant-secret-757"), "{text}");
}
assert!(listed.contains(&plain), "the model still learns the layer's address: {listed}");
}

#[test]
fn wrappers_after_a_prefix_are_made_plain_too() {
let origin = "https://assistant-login.example";
let binding = logins::activate(origin, "assistant", logins::Method::Header("X-Key".into()), "assistant-secret", false).unwrap();
let archive = logins::bind(&binding, &format!("{origin}/a.pmtiles")).unwrap();
let result = json!({"layers": [{"next": {"request": {"url": format!("pmtiles:x@{archive}")}}}], "count": 2});
let v = public_addresses(result, 0, &mut 0);
assert_eq!(v["layers"][0]["next"]["request"]["url"], format!("pmtiles:x@{origin}/a.pmtiles"));
assert_eq!(v["count"], 2);
assert!(logins::deactivate(&binding));
}

#[test]
fn too_deep_results_report_each_withheld_subtree_without_losing_success() {
let mut s = Session::new(rustgis_engine::Project::default());
let mut deep = json!({"value": "rustgis-login:leak"});
for _ in 0..MAX_DEPTH {
deep = json!([deep]);
}
let result = json!({"success": true, "left": deep.clone(), "right": deep, "notices": ["existing warning"]});
let out: Value = serde_json::from_str(&public_result(&mut s, result, DEFAULT_OUTPUT_TOKENS)).unwrap();
assert_eq!(out["success"], true, "withholding output must not report an executed command as failed");
assert!(!out.to_string().contains("rustgis-login:"));
assert_eq!(out["notices"][0], "existing warning");
let notice = out["notices"][1].as_str().unwrap();
let counts: Vec<usize> = notice.split_whitespace().filter_map(|word| word.parse().ok()).collect();
assert_eq!(counts, [2, MAX_DEPTH], "the notice reports truncated subtrees, not an unbounded count of their contents");
assert_eq!(s.notices_since(0).len(), 1, "the app also receives one aggregate loss notice");
}

#[test]
fn clean_nested_results_need_no_withholding_notice() {
let mut s = Session::new(rustgis_engine::Project::default());
let result = json!({"result": {"nested": [{"value": "complete"}]}, "success": true});
let out: Value = serde_json::from_str(&public_result(&mut s, result.clone(), DEFAULT_OUTPUT_TOKENS)).unwrap();
assert_eq!(out, result);
assert!(s.notices_since(0).is_empty());
}
}
1 change: 1 addition & 0 deletions crates/data/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ pub mod io;
pub mod kml;
pub mod landxml;
pub mod lidar;
pub mod login_address;
pub mod mapinfo;
pub mod mbtiles;
pub mod memory;
Expand Down
188 changes: 188 additions & 0 deletions crates/data/src/login_address.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,188 @@
//! Secret-free runtime addresses bound to one web-service connection login.
//! Saved runtime tokens must be discarded and rebound by the owning session on project open.

use std::net::Ipv6Addr;

/// Canonical HTTP(S) origin: lowercase scheme and host, without a trailing host dot or
/// the scheme's default port. Paths, queries and fragments do not form part of the origin.
/// User information, whitespace, controls, backslashes and malformed authorities are refused.
fn raw_origin(url: &str) -> Option<String> {
if url.chars().any(|c| c.is_whitespace() || c.is_control() || c == '\\') {
return None;
}
let (scheme, rest) = url.split_once("://")?;
let scheme = if scheme.eq_ignore_ascii_case("https") {
"https"
} else if scheme.eq_ignore_ascii_case("http") {
"http"
} else {
return None;
};
let authority = rest.split(['/', '?', '#']).next()?;
if authority.is_empty() || authority.contains('@') {
return None;
}
let (host, port) = if let Some(ip) = authority.strip_prefix('[') {
let (ip, tail) = ip.split_once(']')?;
let host = format!("[{}]", ip.parse::<Ipv6Addr>().ok()?);
let port = if tail.is_empty() { None } else { Some(tail.strip_prefix(':')?) };
(host, port)
} else {
let (host, port) = authority.split_once(':').map_or((authority, None), |(h, p)| (h, Some(p)));
let host = host.strip_suffix('.').unwrap_or(host);
if host.is_empty() || host.contains(['[', ']', '%', '<', '>', '"', '^', '`', '{', '}', '|']) || host.split('.').any(str::is_empty) {
return None;
}
(host.to_lowercase(), port)
};
let port = match port {
Some(port) => {
if port.is_empty() || !port.bytes().all(|b| b.is_ascii_digit()) {
return None;
}
Some(port.parse::<u16>().ok()?)
}
None => None,
};
match port.filter(|p| *p != if scheme == "https" { 443 } else { 80 }) {
Some(port) => Some(format!("{scheme}://{host}:{port}")),
None => Some(format!("{scheme}://{host}")),
}
}
pub const PREFIX: &str = "rustgis-login:";
const BAD: &str = "not a bound service login address";

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct BoundLogin<'a> {
pub binding: &'a str,
pub origin: &'a str,
pub url: &'a str,
}

pub fn is_wrapper(address: &str) -> bool {
address.starts_with(PREFIX)
}

pub fn parse(address: &str) -> Result<Option<BoundLogin<'_>>, &'static str> {
let Some(rest) = address.strip_prefix(PREFIX) else { return Ok(None) };
if address.len() > 16384 || address.chars().any(char::is_control) {
return Err(BAD);
}
let (binding, rest) = rest.split_once(':').ok_or(BAD)?;
if !(16..=64).contains(&binding.len()) || !binding.bytes().all(|b| matches!(b, b'0'..=b'9' | b'a'..=b'f')) {
return Err(BAD);
}
let (len, rest) = rest.split_once(':').ok_or(BAD)?;
if len.len() > 4 || len.is_empty() || !len.bytes().all(|b| b.is_ascii_digit()) {
return Err(BAD);
}
let len: usize = len.parse().map_err(|_| BAD)?;
let origin = rest.get(..len).ok_or(BAD)?;
let url = rest.get(len..).and_then(|s| s.strip_prefix(':')).ok_or(BAD)?;
if raw_origin(origin).as_deref() != Some(origin) || raw_origin(url).as_deref() != Some(origin) {
return Err(BAD);
}
Ok(Some(BoundLogin { binding, origin, url }))
}

pub fn bind(binding: &str, origin: &str, url: &str) -> Result<String, &'static str> {
let address = format!("{PREFIX}{binding}:{}:{origin}:{url}", origin.len());
parse(&address)?;
Ok(address)
}

pub fn inner(address: &str) -> &str {
parse(address).ok().flatten().map_or(address, |b| b.url)
}

/// Canonical origin of a plain URL or a well-formed bound URL.
pub fn origin(address: &str) -> Option<String> {
raw_origin(inner(address))
}

pub fn rebound(address: &str, binding: &str) -> Option<String> {
let b = parse(address).ok().flatten()?;
bind(binding, b.origin, b.url).ok()
}

pub fn reached(address: &str) -> &str {
if is_wrapper(address) {
inner(address)
} else {
address.split_once('@').filter(|(_, a)| is_wrapper(a)).map_or(address, |(_, a)| inner(a))
}
}

/// Retains a document's binding for same-origin derived addresses only.
pub fn inherit(base: &str, url: &str) -> String {
let url = inner(url);
let Ok(Some(b)) = parse(base) else { return url.to_string() };
if origin(url).as_deref() == Some(b.origin) {
// Keep the actual derived binding even when its size exceeds the parser's bound.
// Request validation then refuses it instead of sending an anonymous request.
format!("{PREFIX}{}:{}:{}:{url}", b.binding, b.origin.len(), b.origin)
} else {
url.to_string()
}
}

type Validator = fn(&str) -> Result<(), &'static str>;
static VALIDATOR: std::sync::OnceLock<Validator> = std::sync::OnceLock::new();

/// Installs the runtime authority check supplied by the networking crate.
pub fn set_validator(validator: Validator) {
let _ = VALIDATOR.set(validator);
}

/// Bound cached data is unreadable unless its owning runtime still authorizes the binding.
pub fn check(address: &str) -> Result<(), &'static str> {
if !is_wrapper(address) {
return Ok(());
}
parse(address)?;
VALIDATOR.get().ok_or("The service login is no longer active. Sign in to this connection again.")?(address)
}

#[cfg(test)]
#[allow(clippy::unwrap_used)]
mod tests {
use super::*;

#[test]
fn binding_length_and_alphabet_are_checked() {
let wrapped = |b: &str| format!("{PREFIX}{b}:14:https://a.test:https://a.test/x");
assert!(parse(&wrapped(&"ab12".repeat(8))).unwrap().is_some());
assert!(parse(&wrapped(&"a".repeat(15))).is_err());
assert!(parse(&wrapped(&"a".repeat(65))).is_err());
assert!(parse(&wrapped(&format!("{}g", "a".repeat(31)))).is_err());
assert!(parse(&wrapped(&"A".repeat(32))).is_err());
}

#[test]
fn oversized_same_origin_inheritance_is_refused_not_anonymous() {
let base = bind("0123456789abcdef", "https://a.test", "https://a.test/collections").unwrap();
let derived = format!("https://a.test/items?filter={}", "a".repeat(17000));
let inherited = inherit(&base, &derived);
assert!(is_wrapper(&inherited));
assert!(inherited.ends_with(&derived), "keep the derived target, not the base document");
assert_eq!(parse(&inherited).unwrap_err(), BAD);
assert_eq!(check(&inherited).unwrap_err(), BAD);
let valid = inherit(&base, "https://a.test/items");
assert_eq!(parse(&valid).unwrap().unwrap().url, "https://a.test/items");
let foreign = format!("https://b.test/items?filter={}", "a".repeat(17000));
assert_eq!(inherit(&base, &foreign), foreign);
}

#[test]
fn round_trip_and_fixed_errors() {
let b = bind("0123456789abcdef", "https://a.test", "https://a.test/x?y=1").unwrap();
let p = parse(&b).unwrap().unwrap();
assert_eq!((p.binding, p.origin, p.url), ("0123456789abcdef", "https://a.test", "https://a.test/x?y=1"));
assert_eq!(inner(&b), p.url);
for bad in
["rustgis-login:secret", "rustgis-login:0123456789abcdef:1:é:https://a.test", "rustgis-login:0123456789abcdef:0::/etc/passwd"]
{
assert_eq!(parse(bad).unwrap_err(), BAD);
}
}
}
Loading
Loading