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
+20
View File
@@ -169,6 +169,22 @@ impl<'a> Flow<'a> {
if c.grant == Grant::AuthorizationCode && c.issuer.is_empty() && c.authorize_url.is_empty() {
problems.push("the authorization code flow needs an authorize URL or an issuer".to_string());
}
// An undefined variable leaves `{{BASE}}` in a URL; fail here with the
// reason instead of sending a request to a broken address.
for (label, v) in [
("issuer", &c.issuer),
("authorize URL", &c.authorize_url),
("token URL", &c.token_url),
("device URL", &c.device_url),
("client id", &c.client_id),
] {
if let Some(start) = v.find("{{") {
let name = v[start + 2..].split("}}").next().unwrap_or("").trim();
problems.push(format!(
"the {label} uses {{{{{name}}}}}, which is not defined. Pick the environment that defines it (Ctrl+E) or define it in the collection"
));
}
}
if c.grant == Grant::Password && c.username.is_empty() {
problems.push("username is empty".to_string());
}
@@ -823,6 +839,10 @@ pub async fn action(cfg: &OauthConfig, key: &str, hooks: &dyn FlowHooks, what: A
let mut f = Flow { cfg, hooks, http: Http::new(cfg.verify_tls), steps: Vec::new(), warnings: Vec::new(), meta: None };
if matches!(what, Action::Discovery) {
DISCOVERY.lock().unwrap().get_or_insert_with(HashMap::new).remove(&cfg.issuer);
if cfg.issuer.contains("{{") {
f.check_config();
return FlowResult { steps: f.steps, warnings: f.warnings, ..Default::default() };
}
f.discover().await;
return FlowResult { steps: f.steps, warnings: f.warnings, ..Default::default() };
}
+20
View File
@@ -214,3 +214,23 @@ async fn errors_are_explained() {
assert!(r.steps.iter().any(|s| s.id == "token" && s.summary.contains("invalid_grant") && s.status == StepStatus::Warning));
assert_eq!(r.token.as_deref(), Some("at-cc"), "{:#?}", r.steps);
}
#[tokio::test]
async fn undefined_variable_in_issuer_is_explained() {
let c = cfg(serde_json::json!({ "type": "oidc", "issuer": "{{BASE}}/realms/default/", "client_id": "knock" }));
let hooks = TestHooks::default();
let r = oauth::action(&c, &c.store_key("c", None), &hooks, oauth::Action::Discovery).await;
let failed = r.steps.iter().find(|s| s.status == StepStatus::Error).expect("error step");
assert!(failed.summary.contains("{{BASE}}"), "{}", failed.summary);
assert!(!r.steps.iter().any(|s| s.exchange.is_some()), "no request may be sent");
}
#[tokio::test]
async fn issuer_with_trailing_slash_discovers() {
let st = Arc::new(Mutex::new(Provider::default()));
let base = start_provider(st).await;
let c = cfg(serde_json::json!({ "type": "oauth2", "issuer": format!("{base}/"), "client_id": "knock" }));
let hooks = TestHooks::default();
let r = oauth::action(&c, &c.store_key("c2", None), &hooks, oauth::Action::Discovery).await;
assert!(r.steps.iter().any(|s| s.id == "discovery" && s.status == StepStatus::Ok), "{:#?}", r.steps);
}
+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>,
+89 -14
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 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 };
let res = oauth::obtain(&oc, &key, &hooks, force_refresh).await;
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 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 = lock.lock().await;
let _guard = if writes { Some(lock.lock().await) } else { None };
let hooks = Hooks { app: app.clone(), key: key.clone(), interactive: true };
let res = match what.as_str() {
"login" => {
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" => {
("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
(_, 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);
}
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())
}
+1 -1
View File
@@ -142,5 +142,5 @@ export const oauthApi = {
run: (args: OauthArgs, what: 'login' | 'test' | 'logout' | 'refresh' | 'userinfo' | 'introspect' | 'revoke' | 'discovery') =>
invoke<{ steps: import('./types').Step[]; warnings: string[]; ok: boolean }>('oauth_run', { args, what }),
callback: (url: string) => invoke<boolean>('oauth_callback', { url }),
cancel: () => invoke<void>('oauth_cancel')
cancel: (key?: string) => invoke<number>('oauth_cancel', { key: key ?? null })
};
+8 -1
View File
@@ -70,12 +70,19 @@ class Workspace {
return this.collections.find((c) => c.id === id);
}
/**
* Active environment. Until one is picked, `local` (or the first one) is
* active, so variables resolve right away. Picking "No environment" is
* remembered as an explicit null.
*/
env(col: string | null): string | null {
if (!col) return null;
const c = this.collection(col);
const chosen = this.envByCol[col];
if (chosen === null) return null;
if (chosen && c?.environments.some((e) => e.id === chosen)) return chosen;
return null;
const envs = c?.environments ?? [];
return (envs.find((e) => e.id === 'local') ?? envs[0])?.id ?? null;
}
setEnv(col: string, env: string | null) {
+10 -2
View File
@@ -114,7 +114,8 @@
function click(r: Row, e: MouseEvent) {
selected = r.key;
ws.focusCol = r.col.id;
if (!r.node) return toggleRoot(r.col);
// One click on the collection opens its settings; the chevron folds it.
if (!r.node) return ws.openSpecial('collection', r.col.id, null, r.col.name);
if (r.node.node === 'folder') {
if (e.detail === 2) ws.openSpecial('folder', r.col.id, r.node.id, r.node.name);
else toggle(r.key);
@@ -455,7 +456,14 @@
<span class="pointer-events-none absolute inset-x-2 h-0.5 bg-cyan {dropAt.where === 'before' ? 'top-0' : 'bottom-0'}"></span>
{/if}
{#if !r.node}
<Icon name={collapsedRoot(r.col) ? 'chevron-right' : 'chevron-down'} size={12} class="text-fg-subtle" />
<button
class="-ml-1 grid size-5 place-items-center rounded text-fg-subtle hover:bg-hover hover:text-fg"
aria-label={collapsedRoot(r.col) ? 'Expand collection' : 'Collapse collection'}
onclick={(e) => {
e.stopPropagation();
toggleRoot(r.col);
}}><Icon name={collapsedRoot(r.col) ? 'chevron-right' : 'chevron-down'} size={12} /></button
>
<span class="truncate font-bold text-strong">{r.col.name}</span>
{#if r.col.problems.length}
<span title="{r.col.problems.length} file(s) could not be read"><Icon name="alert" size={12} class="text-post" /></span>
+20 -4
View File
@@ -103,6 +103,13 @@
}
}
/** Stops the running flow; the login lock and the callback port are freed at once. */
async function cancel() {
await oauthApi.cancel(status?.key);
awaiting = false;
device = null;
}
async function sendPasted() {
if (!pasted.trim()) return;
await oauthApi.callback(pasted.trim());
@@ -215,7 +222,11 @@
<div class="flex min-w-0 flex-1 rounded border border-line bg-input">
<VarInput value={str('issuer')} placeholder="https://sso.example.com/realms/main" oninput={(v) => set('issuer', v)} />
</div>
<button class="rounded border border-line px-3 text-[12px] hover:border-border-strong disabled:opacity-40" disabled={!str('issuer') || !!busy} onclick={() => run('discovery')}>{busy === 'discovery' ? 'Discovering…' : 'Discover'}</button>
{#if busy === 'discovery'}
<button class="rounded border border-line px-3 text-[12px] hover:border-delete hover:text-delete" onclick={cancel}>Cancel</button>
{:else}
<button class="rounded border border-line px-3 text-[12px] hover:border-border-strong disabled:opacity-40" disabled={!str('issuer') || !!busy} onclick={() => run('discovery')}>Discover</button>
{/if}
</div>
<span class="text-[11.5px] text-fg-subtle">Endpoints, scopes and PKCE support come from /.well-known/openid-configuration. Leave empty to enter endpoints by hand.</span>
</div>
@@ -327,9 +338,14 @@
<span class="text-[12px] text-fg-subtle">none stored for this environment</span>
{/if}
<span class="flex-1"></span>
<button class="rounded bg-accent px-3 py-1 text-[12px] font-bold text-accent-fg hover:bg-accent-hover disabled:opacity-40" disabled={!!busy} onclick={() => run('login')}>
{busy === 'login' ? 'Logging in…' : status?.token ? 'Log in again' : grant === 'client_credentials' ? 'Get token' : 'Log in'}
{#if busy}
<span class="text-[12px] text-fg-muted">{busy === 'login' ? 'Logging in…' : busy === 'discovery' ? 'Discovering…' : 'Working…'}</span>
<button class="rounded border border-line px-3 py-1 text-[12px] font-bold text-strong hover:border-delete hover:text-delete" onclick={cancel}>Cancel</button>
{:else}
<button class="rounded bg-accent px-3 py-1 text-[12px] font-bold text-accent-fg hover:bg-accent-hover" onclick={() => run('login')}>
{status?.token ? 'Log in again' : grant === 'client_credentials' ? 'Get token' : 'Log in'}
</button>
{/if}
<button class="rounded border border-line px-2.5 py-1 text-[12px] hover:border-border-strong disabled:opacity-40" disabled={!!busy} onclick={() => run('test')}>Test connection</button>
</div>
{#if status?.token}
@@ -360,7 +376,7 @@
<div class="flex gap-2">
<input class="k-field mono flex-1 !border-line !bg-panel" bind:value={pasted} placeholder="https://…?code=…&state=…" onkeydown={(e) => e.key === 'Enter' && sendPasted()} />
<button class="rounded bg-accent px-3 text-[12px] font-bold text-accent-fg" onclick={sendPasted}>Continue</button>
<button class="px-2 text-[12px] text-fg-muted hover:text-fg" onclick={() => oauthApi.cancel()}>Cancel</button>
<button class="px-2 text-[12px] text-fg-muted hover:text-fg" onclick={cancel}>Cancel</button>
</div>
</div>
{/if}
+11 -3
View File
@@ -80,6 +80,7 @@
try {
ws.upsert(await api.envSave(col, id, { name: name.trim(), vars: {} }));
env = id;
ws.setEnv(col, id);
} catch (e) {
toast.error('Could not create', { description: errorText(e) });
}
@@ -156,15 +157,22 @@
</div>
</Popover>
<input class="min-w-0 flex-1 rounded bg-transparent px-1 text-[20px] font-bold text-strong outline-none hover:bg-input focus:bg-input" bind:value={() => data!.name ?? env!, (v) => (data!.name = v)} />
{#if ws.env(col) !== env}
<button class="rounded px-3 py-1.5 text-fg-muted hover:text-fg" onclick={() => ws.setEnv(col, env)}>Use</button>
{/if}
<button class="rounded px-3 py-1.5 text-fg-muted hover:text-fg" onclick={duplicateEnv}>Duplicate</button>
<button class="rounded px-3 py-1.5 text-fg-muted hover:text-delete" onclick={remove}>Delete</button>
<button class="rounded bg-accent px-4 py-1.5 font-bold text-accent-fg disabled:opacity-40" disabled={!dirty} onclick={save}>Save</button>
</div>
<div class="mono -mt-4 text-[12px] text-fg-subtle">environments/{env}.yaml</div>
{#if ws.env(col) !== env}
<div class="flex items-center gap-3 rounded border border-post/50 bg-post/10 px-4 py-2.5">
<Icon name="alert" size={14} class="text-post" />
<span class="flex-1 text-fg">
Not active. Requests use {ws.env(col) ? `"${collection?.environments.find((e) => e.id === ws.env(col))?.name}"` : 'no environment'}, so these variables do not apply yet.
</span>
<button class="rounded bg-accent px-3 py-1 text-[12px] font-bold text-accent-fg hover:bg-accent-hover" onclick={() => ws.setEnv(col, env)}>Use this environment</button>
</div>
{/if}
<div class="flex items-center gap-4 rounded border border-line px-4 py-3">
<div class="flex-1">
<div>Protected</div>