From 5fc816a38084a51faad455530a00a845d054326a Mon Sep 17 00:00:00 2001 From: JoshiCodes <55353244+JoshiCodes@users.noreply.github.com> Date: Fri, 27 Nov 2026 18:24:04 +0100 Subject: [PATCH] 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 --- crates/knock-core/src/oauth/mod.rs | 20 +++ crates/knock-core/tests/oauth_flow.rs | 20 +++ src-tauri/src/commands.rs | 4 +- src-tauri/src/oauth.rs | 127 ++++++++++++++---- src/lib/api.ts | 2 +- src/lib/state/workspace.svelte.ts | 9 +- src/lib/views/Sidebar.svelte | 12 +- src/lib/views/auth/OAuthConfig.svelte | 26 +++- src/lib/views/settings/EnvironmentView.svelte | 14 +- 9 files changed, 194 insertions(+), 40 deletions(-) diff --git a/crates/knock-core/src/oauth/mod.rs b/crates/knock-core/src/oauth/mod.rs index 0a9e4b0..2fc2cfa 100644 --- a/crates/knock-core/src/oauth/mod.rs +++ b/crates/knock-core/src/oauth/mod.rs @@ -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() }; } diff --git a/crates/knock-core/tests/oauth_flow.rs b/crates/knock-core/tests/oauth_flow.rs index 83620c2..cf07191 100644 --- a/crates/knock-core/tests/oauth_flow.rs +++ b/crates/knock-core/tests/oauth_flow.rs @@ -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); +} diff --git a/src-tauri/src/commands.rs b/src-tauri/src/commands.rs index 916e75e..e18d465 100644 --- a/src-tauri/src/commands.rs +++ b/src-tauri/src/commands.rs @@ -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> { +pub async fn env_secrets(state: State<'_, AppState>, col: String, env: String) -> Res> { 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, diff --git a/src-tauri/src/oauth.rs b/src-tauri/src/oauth.rs index d0bbb7a..d9fe5d3 100644 --- a/src-tauri/src/oauth.rs +++ b/src-tauri/src/oauth.rs @@ -24,6 +24,8 @@ pub struct OauthState { locks: Mutex>>>, /// Waiting custom-scheme or manual callback. pending: Mutex>>, + /// Running flows per config, so they can be cancelled. + running: Mutex>>, } 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 = 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 { 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( + app: &AppHandle, + key: &str, + fut: impl std::future::Future + Send + 'static, +) -> Option { + // 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::(); + 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::().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::().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 { +pub async fn oauth_status(app: AppHandle, args: OauthArgs) -> Result { let (oc, key) = resolve(&app, &args)?; let token = app.state::().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 { let (oc, key) = resolve(&app, &args)?; - let lock = app.state::().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::(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::().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 { } #[tauri::command] -pub fn oauth_cancel(app: AppHandle) { - app.state::().pending.lock().unwrap().take(); +pub fn oauth_cancel(app: AppHandle, key: Option) -> usize { + app.state::().cancel(key.as_deref()) } diff --git a/src/lib/api.ts b/src/lib/api.ts index 20f3e47..324250f 100644 --- a/src/lib/api.ts +++ b/src/lib/api.ts @@ -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('oauth_callback', { url }), - cancel: () => invoke('oauth_cancel') + cancel: (key?: string) => invoke('oauth_cancel', { key: key ?? null }) }; diff --git a/src/lib/state/workspace.svelte.ts b/src/lib/state/workspace.svelte.ts index 4816cd0..dc61e10 100644 --- a/src/lib/state/workspace.svelte.ts +++ b/src/lib/state/workspace.svelte.ts @@ -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) { diff --git a/src/lib/views/Sidebar.svelte b/src/lib/views/Sidebar.svelte index e6cd18e..3144405 100644 --- a/src/lib/views/Sidebar.svelte +++ b/src/lib/views/Sidebar.svelte @@ -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 @@ {/if} {#if !r.node} - + {r.col.name} {#if r.col.problems.length} diff --git a/src/lib/views/auth/OAuthConfig.svelte b/src/lib/views/auth/OAuthConfig.svelte index 67c6484..aa90ee2 100644 --- a/src/lib/views/auth/OAuthConfig.svelte +++ b/src/lib/views/auth/OAuthConfig.svelte @@ -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 @@
set('issuer', v)} />
- + {#if busy === 'discovery'} + + {:else} + + {/if} Endpoints, scopes and PKCE support come from /.well-known/openid-configuration. Leave empty to enter endpoints by hand. @@ -327,9 +338,14 @@ none stored for this environment {/if} - + {#if busy} + {busy === 'login' ? 'Logging in…' : busy === 'discovery' ? 'Discovering…' : 'Working…'} + + {:else} + + {/if} {#if status?.token} @@ -360,7 +376,7 @@
e.key === 'Enter' && sendPasted()} /> - +
{/if} diff --git a/src/lib/views/settings/EnvironmentView.svelte b/src/lib/views/settings/EnvironmentView.svelte index 1558420..74640c5 100644 --- a/src/lib/views/settings/EnvironmentView.svelte +++ b/src/lib/views/settings/EnvironmentView.svelte @@ -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 @@ data!.name ?? env!, (v) => (data!.name = v)} /> - {#if ws.env(col) !== env} - - {/if}
environments/{env}.yaml
+ {#if ws.env(col) !== env} +
+ + + 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. + + +
+ {/if} +
Protected