OAuth flows can be cancelled; discovery no longer waits for a pending login

- Only login, logout, refresh and revoke queue behind each other;
  discovery, test, userinfo and introspection run at once
- Cancel in the OAuth panel (and Cancel on the request) stops the flow,
  frees the callback port and the login lock
- Undefined variables in issuer, endpoints or client id are reported
  before any request is sent
- Keyring commands run off the UI thread, so a KWallet prompt cannot
  freeze the window
- One click on a collection opens its settings; the chevron folds it
- Until an environment is picked, local (or the first one) is active;
  the environment editor says when the shown one is not active
This commit is contained in:
2026-11-27 18:24:04 +01:00
parent e6913451e6
commit 5fc816a380
9 changed files with 194 additions and 40 deletions
+2 -2
View File
@@ -244,7 +244,7 @@ pub struct SecretStatus {
/// Where each secret of an environment currently comes from. Values are
/// returned so the UI can reveal them on demand; it masks by default.
#[tauri::command]
pub fn env_secrets(state: State<'_, AppState>, col: String, env: String) -> Res<Vec<SecretStatus>> {
pub async fn env_secrets(state: State<'_, AppState>, col: String, env: String) -> Res<Vec<SecretStatus>> {
let (e, file) = state
.with_collection(&col, |c| Ok((c.environment(&env)?, c.secrets_file(&env)?)))
.map_err(errx)?;
@@ -264,7 +264,7 @@ pub fn env_secrets(state: State<'_, AppState>, col: String, env: String) -> Res<
}
#[tauri::command]
pub fn secret_set(
pub async fn secret_set(
state: State<'_, AppState>,
col: String,
env: Option<String>,
+101 -26
View File
@@ -24,6 +24,8 @@ pub struct OauthState {
locks: Mutex<HashMap<String, Arc<tokio::sync::Mutex<()>>>>,
/// Waiting custom-scheme or manual callback.
pending: Mutex<Option<tokio::sync::oneshot::Sender<String>>>,
/// Running flows per config, so they can be cancelled.
running: Mutex<HashMap<String, Vec<tokio::task::AbortHandle>>>,
}
impl OauthState {
@@ -31,6 +33,21 @@ impl OauthState {
self.locks.lock().unwrap().entry(key.to_string()).or_default().clone()
}
/// Cancels every running flow of a config (all configs for None). Aborting
/// drops the loopback listener and the login lock with it.
pub fn cancel(&self, key: Option<&str>) -> usize {
self.pending.lock().unwrap().take();
let mut running = self.running.lock().unwrap();
let handles: Vec<tokio::task::AbortHandle> = match key {
Some(k) => running.remove(k).unwrap_or_default(),
None => running.drain().flat_map(|(_, v)| v).collect(),
};
for h in &handles {
h.abort();
}
handles.len()
}
pub fn load(&self, key: &str) -> Option<TokenSet> {
if let Some(t) = self.tokens.lock().unwrap().get(key) {
return t.clone();
@@ -55,6 +72,36 @@ impl OauthState {
}
}
/// Runs a flow in its own task so it can be cancelled. None when cancelled.
async fn cancellable<T: Send + 'static>(
app: &AppHandle,
key: &str,
fut: impl std::future::Future<Output = T> + Send + 'static,
) -> Option<T> {
// If the caller is dropped (the request's Cancel button aborts the send),
// the flow stops too instead of keeping the port and the login lock.
struct AbortOnDrop(tokio::task::AbortHandle);
impl Drop for AbortOnDrop {
fn drop(&mut self) {
self.0.abort();
}
}
let task = tokio::spawn(fut);
let handle = task.abort_handle();
let _guard = AbortOnDrop(handle.clone());
let state = app.state::<OauthState>();
state.running.lock().unwrap().entry(key.to_string()).or_default().push(handle.clone());
let out = task.await.ok();
if let Some(list) = state.running.lock().unwrap().get_mut(key) {
list.retain(|h| h.id() != handle.id());
}
out
}
fn cancelled_step() -> Step {
Step::new("cancel", "Cancelled", StepStatus::Error, "the flow was cancelled").hint("Start it again when you are ready.")
}
#[derive(Clone, Serialize)]
struct Progress {
key: String,
@@ -197,15 +244,24 @@ impl AuthHost for Host {
let app = self.app.clone();
let interactive = self.interactive;
let env = self.env.clone();
let (grant, name) = (oc.grant, oc.name.clone());
Box::pin(async move {
let lock = app.state::<OauthState>().lock_for(&key);
let _guard = lock.lock().await;
let hooks = Hooks { app: app.clone(), key: key.clone(), interactive };
let res = oauth::obtain(&oc, &key, &hooks, force_refresh).await;
let flow = {
let (app, key) = (app.clone(), key.clone());
async move {
let lock = app.state::<OauthState>().lock_for(&key);
let _guard = lock.lock().await;
let hooks = Hooks { app: app.clone(), key: key.clone(), interactive };
oauth::obtain(&oc, &key, &hooks, force_refresh).await
}
};
let Some(res) = cancellable(&app, &key, flow).await else {
return OauthResult { steps: vec![cancelled_step()], ..Default::default() };
};
let ran_something = res.steps.iter().any(|s| s.exchange.is_some());
let flow_id = (interactive && ran_something).then(|| record_flow(&app, &key, &format!("{:?}", oc.grant), &res.steps, &res.warnings));
let flow_id = (interactive && ran_something).then(|| record_flow(&app, &key, &format!("{:?}", grant), &res.steps, &res.warnings));
if res.tokens.is_some() {
remember_name(&app, &col, env.as_deref(), &oc.name, &key);
remember_name(&app, &col, env.as_deref(), &name, &key);
}
OauthResult { token: res.token, steps: res.steps, flow_id, warnings: res.warnings }
})
@@ -270,8 +326,9 @@ fn resolve(app: &AppHandle, a: &OauthArgs) -> Result<(OauthConfig, String), Stri
Ok((oc, key))
}
// Async so the keyring read (which can wait for a KWallet prompt) never blocks the UI thread.
#[tauri::command]
pub fn oauth_status(app: AppHandle, args: OauthArgs) -> Result<OauthStatus, String> {
pub async fn oauth_status(app: AppHandle, args: OauthArgs) -> Result<OauthStatus, String> {
let (oc, key) = resolve(&app, &args)?;
let token = app.state::<OauthState>().load(&key);
let flows = {
@@ -293,28 +350,46 @@ pub struct FlowOutcome {
#[tauri::command]
pub async fn oauth_run(app: AppHandle, args: OauthArgs, what: String) -> Result<FlowOutcome, String> {
let (oc, key) = resolve(&app, &args)?;
let lock = app.state::<OauthState>().lock_for(&key);
let _guard = lock.lock().await;
let hooks = Hooks { app: app.clone(), key: key.clone(), interactive: true };
let res = match what.as_str() {
"login" => {
hooks.delete_token(&key);
oauth::obtain(&oc, &key, &hooks, true).await
}
"test" => oauth::test_connection(&oc, &hooks).await,
"logout" => {
hooks.delete_token(&key);
oauth::FlowResult { steps: vec![Step::new("forget", "Forget token", StepStatus::Ok, "removed from the keyring")], ..Default::default() }
}
other => {
let action: Action = serde_json::from_value(serde_json::Value::String(other.into())).map_err(|_| format!("unknown action {other}"))?;
oauth::action(&oc, &key, &hooks, action).await
let action = match what.as_str() {
"login" | "test" | "logout" => None,
other => Some(
serde_json::from_value::<Action>(serde_json::Value::String(other.into())).map_err(|_| format!("unknown action {other}"))?,
),
};
let flow = {
let (app, key, oc, what) = (app.clone(), key.clone(), oc.clone(), what.clone());
async move {
// Only flows that write tokens wait for each other; discovery and
// read-only actions never queue behind a pending login.
let writes = matches!(what.as_str(), "login" | "logout") || matches!(action, Some(Action::Refresh) | Some(Action::Revoke));
let lock = app.state::<OauthState>().lock_for(&key);
let _guard = if writes { Some(lock.lock().await) } else { None };
let hooks = Hooks { app: app.clone(), key: key.clone(), interactive: true };
match (what.as_str(), action) {
("login", _) => {
hooks.delete_token(&key);
oauth::obtain(&oc, &key, &hooks, true).await
}
("test", _) => oauth::test_connection(&oc, &hooks).await,
("logout", _) => {
hooks.delete_token(&key);
oauth::FlowResult { steps: vec![Step::new("forget", "Forget token", StepStatus::Ok, "removed from the keyring")], ..Default::default() }
}
(_, Some(a)) => oauth::action(&oc, &key, &hooks, a).await,
_ => oauth::FlowResult::default(),
}
}
};
let res = match cancellable(&app, &key, flow).await {
Some(r) => r,
None => oauth::FlowResult { steps: vec![cancelled_step()], ..Default::default() },
};
if res.tokens.is_some() {
remember_name(&app, args.scope.col.as_deref().unwrap_or(""), args.scope.env.as_deref(), &oc.name, &key);
}
record_flow(&app, &key, &what, &res.steps, &res.warnings);
if what != "discovery" {
record_flow(&app, &key, &what, &res.steps, &res.warnings);
}
let ok = !res.steps.iter().any(|s| s.status == StepStatus::Error);
Ok(FlowOutcome { steps: res.steps, warnings: res.warnings, ok })
}
@@ -335,6 +410,6 @@ pub fn oauth_deep_link(app: AppHandle, url: String) -> Result<bool, String> {
}
#[tauri::command]
pub fn oauth_cancel(app: AppHandle) {
app.state::<OauthState>().pending.lock().unwrap().take();
pub fn oauth_cancel(app: AppHandle, key: Option<String>) -> usize {
app.state::<OauthState>().cancel(key.as_deref())
}