Skip to content
107 changes: 106 additions & 1 deletion apps/rustgis-web/src/arcgis.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,8 @@
use std::cell::Cell;

use rustgis_ui_egui::Slot;
use rustgis_ui_egui::rustgis_engine::render::rustgis_tiles::{arcgis_auth, cache};
use rustgis_ui_egui::rustgis_engine::data::secrets::Secret;
use rustgis_ui_egui::rustgis_engine::render::rustgis_tiles::{arcgis_auth, arcgis_token, cache};
use wasm_bindgen::JsCast as _;

/// How long a request to the portal may take before it is given up.
Expand Down Expand Up @@ -208,3 +209,107 @@ pub async fn renew_if_due(url: &str, still: Option<cache::Still>) {
}
arcgis_auth::renewal_done(&r, answer.as_deref().map_err(String::clone));
}

/// How often a token request looks at its cancellation predicate and its deadline.
const TOKEN_WATCH_MS: i32 = 50;

/// Asks an ArcGIS Server for a token (see `rustgis_tiles::arcgis_token`): the form is POSTed to
/// `endpoint` once. The request is never redirected and carries no cookies, referrer or other
/// login; its answer is read in chunks up to the limit; every failure is a fixed sentence, never
/// the browser's own text. It is given up, and the fetch aborted, when `still` turns false
/// (checked every 50 ms) or at the deadline. `done` is called exactly once, whatever happens.
pub fn generate_token(endpoint: String, body: Secret, still: cache::Still, done: arcgis_token::Done) {
wasm_bindgen_futures::spawn_local(async move {
let result = token_request(&endpoint, &body, &still).await;
done(result);
});
}

async fn token_request(endpoint: &str, body: &Secret, still: &cache::Still) -> Result<arcgis_token::Credential, String> {
use std::{cell::Cell, rc::Rc};
let held = Some(still.clone());
let stopped = |_: String| arcgis_token::CANCELLED.to_string();
cache::check_still(&held).map_err(stopped)?;
let window = web_sys::window().ok_or(arcgis_token::FAILED)?;
let failed = |_: wasm_bindgen::JsValue| arcgis_token::FAILED.to_string();
let abort = web_sys::AbortController::new().map_err(failed)?;
let init = web_sys::RequestInit::new();
init.set_method("POST");
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(failed)?;
headers.set("Content-Type", "application/x-www-form-urlencoded").map_err(failed)?;
headers.set("Accept", "application/json").map_err(failed)?;
init.set_headers(&headers);
init.set_body(&wasm_bindgen::JsValue::from_str(body.expose()));
init.set_signal(Some(&abort.signal()));
// The watchdog aborts the fetch the moment the request is cancelled or out of time, saying why.
let why: Rc<Cell<Option<&'static str>>> = Rc::default();
let began = web_time::Instant::now();
let watch = {
let (abort, still, why) = (abort.clone(), still.clone(), why.clone());
wasm_bindgen::closure::Closure::<dyn FnMut()>::new(move || {
if !still() {
why.set(Some(arcgis_token::CANCELLED));
abort.abort();
} else if began.elapsed() >= std::time::Duration::from_secs(arcgis_token::DEADLINE_SECS) {
why.set(Some(arcgis_token::TIMED_OUT));
abort.abort();
}
})
};
let timer =
window.set_interval_with_callback_and_timeout_and_arguments_0(watch.as_ref().unchecked_ref(), TOKEN_WATCH_MS).map_err(failed)?;
let read = async {
// The last look before the request leaves.
cache::check_still(&held).map_err(stopped)?;
let response: web_sys::Response = wasm_bindgen_futures::JsFuture::from(window.fetch_with_str_and_init(endpoint, &init))
.await
.map_err(failed)?
.dyn_into()
.map_err(failed)?;
let status = response.status();
if response
.headers()
.get("content-length")
.ok()
.flatten()
.and_then(|l| l.parse::<usize>().ok())
.is_some_and(|n| n > arcgis_token::MAX_ANSWER)
{
return Err(arcgis_token::TOO_LARGE.to_string());
}
let mut bytes: Vec<u8> = Vec::new();
if let Some(stream) = response.body() {
let reader: web_sys::ReadableStreamDefaultReader =
stream.get_reader().dyn_into().map_err(|_| arcgis_token::FAILED.to_string())?;
loop {
let chunk = wasm_bindgen_futures::JsFuture::from(reader.read()).await.map_err(failed)?;
if js_sys::Reflect::get(&chunk, &"done".into()).ok().and_then(|d| d.as_bool()).unwrap_or(true) {
break;
}
let value = js_sys::Uint8Array::new(&js_sys::Reflect::get(&chunk, &"value".into()).map_err(failed)?);
if bytes.len() + value.length() as usize > arcgis_token::MAX_ANSWER {
let _ = reader.cancel();
return Err(arcgis_token::TOO_LARGE.to_string());
}
let at = bytes.len();
bytes.resize(at + value.length() as usize, 0);
value.copy_to(bytes.get_mut(at..).unwrap_or_default());
}
}
// An answer that arrives after a cancel, or past the deadline a throttled timer missed, is discarded.
cache::check_still(&held).map_err(stopped)?;
if began.elapsed() >= std::time::Duration::from_secs(arcgis_token::DEADLINE_SECS) {
return Err(arcgis_token::TIMED_OUT.to_string());
}
arcgis_token::from_answer(status, &bytes, arcgis_token::now_millis())
};
let result = read.await;
window.clear_interval_with_handle(timer);
abort.abort();
drop(watch);
// An abort reads as the browser's failure: what the watchdog saw is why.
result.map_err(|e| why.get().map(str::to_string).unwrap_or(e))
}
20 changes: 15 additions & 5 deletions apps/rustgis-web/src/web.rs
Original file line number Diff line number Diff line change
Expand Up @@ -686,18 +686,26 @@ async fn fetch_reached(
let prepared = cache::prepare_get(url)?;
let url = prepared.url.as_str();
let destination = check_destination(url, ceiling)?;
// A connection's own ArcGIS token (already in the login's address) outranks the portal
// sign-in: with one applied, the sign-in's token is neither renewed nor added.
let target = logins::inherit(bound, url);
let mut login = if prepared.signed { None } else { logins::apply(&target).map_err(str::to_string)? };
let explicit = login.as_ref().is_some_and(|applied| applied.arcgis);
// An ArcGIS sign-in's token, for the portal and the servers it covers, renewed first when it
// is about to expire. It goes as the request's `token` parameter, not a header: ArcGIS's
// query endpoints answer the header's CORS preflight with an error.
if !prepared.signed {
if !prepared.signed && !explicit {
crate::arcgis::renew_if_due(url, still.clone()).await;
cache::check_still(&still)?;
// The renewal suspended this request: its login is looked at once more.
login = logins::apply(&target).map_err(str::to_string)?;
}
let target = logins::inherit(bound, url);
let login = if prepared.signed { None } else { logins::apply(&target).map_err(str::to_string)? };
let login_url = login.as_ref().map_or(url, |applied| applied.url.as_str());
let arcgis =
if prepared.signed { None } else { rustgis_ui_egui::rustgis_engine::render::rustgis_tiles::arcgis_auth::with_token(login_url) };
let arcgis = if prepared.signed || explicit {
None
} else {
rustgis_ui_egui::rustgis_engine::render::rustgis_tiles::arcgis_auth::with_token(login_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 @@ -1163,6 +1171,8 @@ fn services(inbox: Inbox, font_inbox: Inbox, notes: Notes, ctx: egui::Context, e
done,
));
});
// So are the token requests of ArcGIS connections made from a user and password.
rustgis_ui_egui::rustgis_engine::render::rustgis_tiles::arcgis_token::set_generator(crate::arcgis::generate_token);
let open_inbox = inbox.clone();
let font_ctx = ctx.clone();
let (gl_list_ctx, gl_run_ctx) = (ctx.clone(), ctx.clone());
Expand Down
59 changes: 59 additions & 0 deletions crates/engine/src/cmd/connection_token.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
//! `connection.generateToken`, `connection.tokenStatus` and `connection.cancelToken`: making an
//! ArcGIS token for a saved connection from its user and a password, in the background.
//!
//! All three are session operations: they change no project, make no undo step, and take no
//! response, token or completion from their caller. The work, its ownership and its landing are
//! [`crate::service_tokens`]'s.

use serde_json::{Value, json};

use super::{Reopened, activate_token, finished_login, found, remember_flag};
use crate::service_logins as web;
use crate::service_tokens::{self as tokens, Polled, Ready};
use crate::{CmdResult, Session};

/// A required text parameter, as it was given.
fn text<'a>(p: &'a Value, key: &str) -> Result<&'a str, String> {
match p.get(key) {
Some(Value::String(t)) if !t.is_empty() => Ok(t),
None | Some(Value::Null | Value::String(_)) => Err(format!("{key} is required")),
Some(_) => Err(format!("{key} is text")),
}
}

pub(super) fn generate(s: &mut Session, p: &Value) -> CmdResult {
let c = found(s, p)?.clone();
if !web::is_service(&c) {
return Err(format!("{} connections don't log in with a token: only web-service connections do", c.kind));
}
if c.auth != "arcgis" {
return Err("this connection doesn't log in with an ArcGIS token: set auth to arcgis (connection.edit) first".into());
}
let endpoint = text(p, "tokenEndpoint")?.trim();
let password = text(p, "password")?;
let remember = remember_flag(p)?;
tokens::start(s, &c, endpoint, password, remember)?;
Ok(json!({"id": c.id, "pending": true}))
}

pub(super) fn status(s: &mut Session, p: &Value) -> CmdResult {
let c = found(s, p)?.clone();
match tokens::poll(s, &c)? {
Polled::Idle => Ok(json!({"id": c.id, "pending": false, "loggedIn": web::logged_in(s, &c)})),
Polled::Pending => Ok(json!({"id": c.id, "pending": true})),
Polled::Ready(Ready { credential, remember, owner }) => {
// Logging in is the user's answer to a request waiting at this origin (the login ends it).
let answers = web::answers(s, &c);
// Landed under the authority that started it, never the poller's own.
let landed: Result<Reopened, String> = s.resume(&owner, |s| activate_token(s, &c, &credential, false, remember))?;
let mut out = finished_login(s, c, answers, landed?)?;
out["pending"] = json!(false);
Ok(out)
}
}
}

pub(super) fn cancel(s: &mut Session, p: &Value) -> CmdResult {
let c = found(s, p)?.clone();
Ok(json!({"id": c.id, "cancelled": tokens::cancel(s, &c.id)?}))
}
Loading
Loading