mirror of
https://github.com/JoshiCodes/knock.git
synced 2026-12-04 15:19:41 +01:00
- Digest (MD5/SHA-256, -sess, auth/auth-int) with challenge round trip, self-signed JWT, AWS SigV4 (header and presigned), OAuth 1.0a, PKCS#12 client certificates; every type explains its computation - OAuth: discovery, authorization code with PKCE over a loopback listener (knock:// and paste-by-hand as alternatives), client credentials, device code, password; tokens per issuer/client/scopes/ environment in the keyring with auto refresh and one retry after 401 - Flow log with step timeline, raw exchanges, cURL export, plain-language diagnosis of provider errors, ID token validation incl. JWKS signature - OAuth panel with redirect URI on top, token inspector, refresh, userinfo, introspection, revocation, logout and connection test
341 lines
12 KiB
Rust
341 lines
12 KiB
Rust
//! OAuth glue between the core flow code and the app: browser, callbacks,
|
|
//! keyring token store, live progress and the flow history.
|
|
|
|
use crate::commands::{build_context, ScopeArgs};
|
|
use crate::db;
|
|
use crate::state::AppState;
|
|
use futures_util::future::BoxFuture;
|
|
use knock_core::auth::{AuthHost, OauthResult, Step, StepStatus};
|
|
use knock_core::model::AuthConfig;
|
|
use knock_core::oauth::{self, config::OauthConfig, Action, FlowHooks, TokenSet};
|
|
use knock_core::secrets;
|
|
use knock_core::vars::{OauthLookup, Resolver};
|
|
use knock_core::Collection;
|
|
use serde::{Deserialize, Serialize};
|
|
use std::collections::HashMap;
|
|
use std::sync::{Arc, Mutex};
|
|
use tauri::{AppHandle, Emitter, Manager};
|
|
|
|
/// Process-wide OAuth state, managed by Tauri.
|
|
#[derive(Default)]
|
|
pub struct OauthState {
|
|
tokens: Mutex<HashMap<String, Option<TokenSet>>>,
|
|
/// One login per config at a time; parallel sends wait for it.
|
|
locks: Mutex<HashMap<String, Arc<tokio::sync::Mutex<()>>>>,
|
|
/// Waiting custom-scheme or manual callback.
|
|
pending: Mutex<Option<tokio::sync::oneshot::Sender<String>>>,
|
|
}
|
|
|
|
impl OauthState {
|
|
fn lock_for(&self, key: &str) -> Arc<tokio::sync::Mutex<()>> {
|
|
self.locks.lock().unwrap().entry(key.to_string()).or_default().clone()
|
|
}
|
|
|
|
pub fn load(&self, key: &str) -> Option<TokenSet> {
|
|
if let Some(t) = self.tokens.lock().unwrap().get(key) {
|
|
return t.clone();
|
|
}
|
|
let t = secrets::slot_get(key).and_then(|s| serde_json::from_str(&s).ok());
|
|
self.tokens.lock().unwrap().insert(key.to_string(), t.clone());
|
|
t
|
|
}
|
|
|
|
fn save(&self, key: &str, t: &TokenSet) {
|
|
self.tokens.lock().unwrap().insert(key.to_string(), Some(t.clone()));
|
|
if let Ok(s) = serde_json::to_string(t) {
|
|
if let Err(e) = secrets::slot_set(key, &s) {
|
|
tracing::warn!("keyring: {e:#}");
|
|
}
|
|
}
|
|
}
|
|
|
|
fn delete(&self, key: &str) {
|
|
self.tokens.lock().unwrap().insert(key.to_string(), None);
|
|
let _ = secrets::slot_delete(key);
|
|
}
|
|
}
|
|
|
|
#[derive(Clone, Serialize)]
|
|
struct Progress {
|
|
key: String,
|
|
step: Step,
|
|
}
|
|
|
|
#[derive(Clone, Serialize)]
|
|
struct DevicePrompt {
|
|
key: String,
|
|
uri: String,
|
|
code: String,
|
|
complete: Option<String>,
|
|
}
|
|
|
|
struct Hooks {
|
|
app: AppHandle,
|
|
key: String,
|
|
interactive: bool,
|
|
}
|
|
|
|
impl FlowHooks for Hooks {
|
|
fn interactive(&self) -> bool {
|
|
self.interactive
|
|
}
|
|
fn open_browser(&self, url: &str) -> Result<(), String> {
|
|
use tauri_plugin_opener::OpenerExt;
|
|
self.app.opener().open_url(url, None::<&str>).map_err(|e| e.to_string())
|
|
}
|
|
fn wait_external(&self) -> BoxFuture<'static, Option<String>> {
|
|
let (tx, rx) = tokio::sync::oneshot::channel();
|
|
*self.app.state::<OauthState>().pending.lock().unwrap() = Some(tx);
|
|
let _ = self.app.emit("oauth-awaiting", &self.key);
|
|
Box::pin(async move { rx.await.ok() })
|
|
}
|
|
fn progress(&self, step: &Step) {
|
|
let _ = self.app.emit("oauth-progress", Progress { key: self.key.clone(), step: step.clone() });
|
|
}
|
|
fn device_prompt(&self, uri: &str, code: &str, complete: Option<&str>) {
|
|
let _ = self.app.emit(
|
|
"oauth-device",
|
|
DevicePrompt { key: self.key.clone(), uri: uri.into(), code: code.into(), complete: complete.map(str::to_string) },
|
|
);
|
|
}
|
|
fn load_token(&self, key: &str) -> Option<TokenSet> {
|
|
self.app.state::<OauthState>().load(key)
|
|
}
|
|
fn save_token(&self, key: &str, t: &TokenSet) {
|
|
self.app.state::<OauthState>().save(key, t);
|
|
}
|
|
fn delete_token(&self, key: &str) {
|
|
self.app.state::<OauthState>().delete(key);
|
|
}
|
|
}
|
|
|
|
// ---------------------------------------------------------------- flow history
|
|
|
|
#[derive(Debug, Clone, Serialize, Deserialize)]
|
|
pub struct FlowRecord {
|
|
pub id: String,
|
|
pub at: String,
|
|
pub kind: String,
|
|
pub ok: bool,
|
|
pub steps: Vec<Step>,
|
|
pub warnings: Vec<String>,
|
|
}
|
|
|
|
const KEEP_FLOWS: usize = 20;
|
|
|
|
/// Flows are stored masked: the debugger shows live flows in clear text, but
|
|
/// nothing that lands on disk carries a token.
|
|
fn mask_steps(steps: &[Step]) -> Vec<Step> {
|
|
let re_jwt = regex_lite(r"eyJ[\w-]+\.[\w-]+\.[\w-]*");
|
|
steps
|
|
.iter()
|
|
.map(|s| {
|
|
let text = serde_json::to_string(s).unwrap_or_default();
|
|
let mut masked = re_jwt.replace_all(&text, "••••••").into_owned();
|
|
for k in ["access_token", "refresh_token", "id_token", "client_secret", "code", "code_verifier", "password", "device_code"] {
|
|
let re = regex_lite(&format!(r#"({k}\\?"?\s*[:=]\s*\\?"?)([^"&\s,}}\\]+)"#));
|
|
masked = re.replace_all(&masked, "$1••••••").into_owned();
|
|
}
|
|
serde_json::from_str(&masked).unwrap_or_else(|_| s.clone())
|
|
})
|
|
.collect()
|
|
}
|
|
|
|
fn regex_lite(p: &str) -> regex::Regex {
|
|
regex::Regex::new(p).expect("static regex")
|
|
}
|
|
|
|
fn record_flow(app: &AppHandle, key: &str, kind: &str, steps: &[Step], warnings: &[String]) -> String {
|
|
let id = uuid::Uuid::new_v4().to_string();
|
|
let rec = FlowRecord {
|
|
id: id.clone(),
|
|
at: chrono::Utc::now().to_rfc3339(),
|
|
kind: kind.into(),
|
|
ok: !steps.iter().any(|s| s.status == StepStatus::Error),
|
|
steps: mask_steps(steps),
|
|
warnings: warnings.to_vec(),
|
|
};
|
|
let state = app.state::<AppState>();
|
|
let db = state.db.lock().unwrap();
|
|
let k = format!("flows:{key}");
|
|
let mut list: Vec<FlowRecord> = db::kv_get(&db, &k).ok().flatten().and_then(|s| serde_json::from_str(&s).ok()).unwrap_or_default();
|
|
list.insert(0, rec);
|
|
list.truncate(KEEP_FLOWS);
|
|
let _ = db::kv_set(&db, &k, &serde_json::to_string(&list).unwrap_or_default());
|
|
id
|
|
}
|
|
|
|
fn remember_name(app: &AppHandle, col: &str, env: Option<&str>, name: &str, key: &str) {
|
|
let state = app.state::<AppState>();
|
|
let db = state.db.lock().unwrap();
|
|
let _ = db::kv_set(&db, &format!("oauth-name:{col}:{}:{name}", env.unwrap_or("")), key);
|
|
}
|
|
|
|
// ---------------------------------------------------------------- AuthHost
|
|
|
|
pub struct Host {
|
|
app: AppHandle,
|
|
col: Option<String>,
|
|
env: Option<String>,
|
|
interactive: bool,
|
|
}
|
|
|
|
impl Host {
|
|
pub fn new(app: AppHandle, col: Option<String>, env: Option<String>) -> Self {
|
|
Self { app, col, env, interactive: true }
|
|
}
|
|
pub fn preview(app: AppHandle, col: Option<String>, env: Option<String>) -> Self {
|
|
Self { app, col, env, interactive: false }
|
|
}
|
|
}
|
|
|
|
impl AuthHost for Host {
|
|
fn oauth2_token(&self, cfg: &AuthConfig, resolver: &Resolver, force_refresh: bool) -> BoxFuture<'_, OauthResult> {
|
|
let oc = OauthConfig::from_auth(cfg, resolver);
|
|
let col = self.col.clone().unwrap_or_default();
|
|
let key = oc.store_key(&col, self.env.as_deref());
|
|
let app = self.app.clone();
|
|
let interactive = self.interactive;
|
|
let env = self.env.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 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));
|
|
if res.tokens.is_some() {
|
|
remember_name(&app, &col, env.as_deref(), &oc.name, &key);
|
|
}
|
|
OauthResult { token: res.token, steps: res.steps, flow_id, warnings: res.warnings }
|
|
})
|
|
}
|
|
}
|
|
|
|
/// `{{oauth.<name>.access_token}}` and friends.
|
|
pub struct TokenLookup {
|
|
app: AppHandle,
|
|
col: String,
|
|
env: Option<String>,
|
|
}
|
|
|
|
impl TokenLookup {
|
|
pub fn new(app: &AppHandle, c: &Collection, env: Option<&str>) -> Self {
|
|
Self { app: app.clone(), col: c.manifest.id.clone(), env: env.map(str::to_string) }
|
|
}
|
|
}
|
|
|
|
impl OauthLookup for TokenLookup {
|
|
fn oauth_value(&self, config: &str, field: &str) -> Option<String> {
|
|
let state = self.app.state::<AppState>();
|
|
let key = {
|
|
let db = state.db.lock().unwrap();
|
|
db::kv_get(&db, &format!("oauth-name:{}:{}:{config}", self.col, self.env.as_deref().unwrap_or(""))).ok().flatten()?
|
|
};
|
|
let t = self.app.state::<OauthState>().load(&key)?;
|
|
match field {
|
|
"access_token" => Some(t.access_token),
|
|
"id_token" => t.id_token,
|
|
"refresh_token" => t.refresh_token,
|
|
"token_type" => t.token_type,
|
|
"scope" => t.scope,
|
|
_ => None,
|
|
}
|
|
}
|
|
}
|
|
|
|
// ---------------------------------------------------------------- commands
|
|
|
|
#[derive(Deserialize)]
|
|
pub struct OauthArgs {
|
|
#[serde(flatten)]
|
|
pub scope: ScopeArgs,
|
|
pub cfg: AuthConfig,
|
|
}
|
|
|
|
#[derive(Serialize)]
|
|
pub struct OauthStatus {
|
|
pub key: String,
|
|
pub redirect_uri: String,
|
|
pub token: Option<TokenSet>,
|
|
pub flows: Vec<FlowRecord>,
|
|
pub logout_url: Option<String>,
|
|
}
|
|
|
|
fn resolve(app: &AppHandle, a: &OauthArgs) -> Result<(OauthConfig, String), String> {
|
|
let state = app.state::<AppState>();
|
|
let ctx = build_context(app, &state, &a.scope).map_err(|e| format!("{e:#}"))?;
|
|
let oc = OauthConfig::from_auth(&a.cfg, &ctx.resolver);
|
|
let key = oc.store_key(a.scope.col.as_deref().unwrap_or(""), a.scope.env.as_deref());
|
|
Ok((oc, key))
|
|
}
|
|
|
|
#[tauri::command]
|
|
pub 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 = {
|
|
let state = app.state::<AppState>();
|
|
let db = state.db.lock().unwrap();
|
|
db::kv_get(&db, &format!("flows:{key}")).ok().flatten().and_then(|s| serde_json::from_str(&s).ok()).unwrap_or_default()
|
|
};
|
|
let logout_url = oauth::logout_url(&oc, token.as_ref().and_then(|t| t.id_token.as_deref()));
|
|
Ok(OauthStatus { key, redirect_uri: oc.redirect_uri(), token, flows, logout_url })
|
|
}
|
|
|
|
#[derive(Serialize)]
|
|
pub struct FlowOutcome {
|
|
pub steps: Vec<Step>,
|
|
pub warnings: Vec<String>,
|
|
pub ok: bool,
|
|
}
|
|
|
|
#[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
|
|
}
|
|
};
|
|
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);
|
|
let ok = !res.steps.iter().any(|s| s.status == StepStatus::Error);
|
|
Ok(FlowOutcome { steps: res.steps, warnings: res.warnings, ok })
|
|
}
|
|
|
|
/// Custom-scheme callback (knock://callback?...) or a URL/code pasted by hand.
|
|
#[tauri::command]
|
|
pub fn oauth_callback(app: AppHandle, url: String) -> Result<bool, String> {
|
|
let tx = app.state::<OauthState>().pending.lock().unwrap().take();
|
|
match tx {
|
|
Some(tx) => Ok(tx.send(url).is_ok()),
|
|
None => Ok(false),
|
|
}
|
|
}
|
|
|
|
#[tauri::command]
|
|
pub fn oauth_deep_link(app: AppHandle, url: String) -> Result<bool, String> {
|
|
oauth_callback(app, url)
|
|
}
|
|
|
|
#[tauri::command]
|
|
pub fn oauth_cancel(app: AppHandle) {
|
|
app.state::<OauthState>().pending.lock().unwrap().take();
|
|
}
|