mirror of
https://github.com/JoshiCodes/knock.git
synced 2026-12-04 15:29:40 +01:00
Auth types and OAuth 2.0 / OpenID Connect (M3, M4)
- 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
This commit is contained in:
@@ -309,7 +309,7 @@ pub struct ScopeArgs {
|
||||
pub env: Option<String>,
|
||||
}
|
||||
|
||||
pub fn build_context(state: &AppState, a: &ScopeArgs) -> anyhow::Result<RequestContext> {
|
||||
pub fn build_context(app: &AppHandle, state: &AppState, a: &ScopeArgs) -> anyhow::Result<RequestContext> {
|
||||
let globals = db::globals_load(&state.db.lock().unwrap()).unwrap_or_default();
|
||||
match &a.col {
|
||||
Some(col) => {
|
||||
@@ -325,7 +325,7 @@ pub fn build_context(state: &AppState, a: &ScopeArgs) -> anyhow::Result<RequestC
|
||||
runtime: state.runtime_vars(col),
|
||||
globals,
|
||||
secrets: Arc::new(store),
|
||||
oauth: Some(Arc::new(crate::oauth::TokenLookup::new(state, &c, a.env.as_deref()))),
|
||||
oauth: Some(Arc::new(crate::oauth::TokenLookup::new(app, &c, a.env.as_deref()))),
|
||||
})
|
||||
}
|
||||
None => {
|
||||
@@ -352,8 +352,8 @@ pub struct VarsView {
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub fn vars_list(state: State<'_, AppState>, args: ScopeArgs) -> Res<VarsView> {
|
||||
let ctx = build_context(&state, &args).map_err(errx)?;
|
||||
pub fn vars_list(app: AppHandle, state: State<'_, AppState>, args: ScopeArgs) -> Res<VarsView> {
|
||||
let ctx = build_context(&app, &state, &args).map_err(errx)?;
|
||||
Ok(VarsView {
|
||||
vars: ctx.resolver.names(),
|
||||
dynamic: DYNAMIC_VARS.iter().map(|(a, b)| (a.to_string(), b.to_string())).collect(),
|
||||
@@ -410,7 +410,7 @@ pub struct SendResult {
|
||||
#[tauri::command]
|
||||
pub async fn request_send(app: AppHandle, args: SendArgs) -> Res<SendResult> {
|
||||
let state = app.state::<AppState>();
|
||||
let ctx = build_context(&state, &args.scope).map_err(errx)?;
|
||||
let ctx = build_context(&app, &state, &args.scope).map_err(errx)?;
|
||||
let engine = state.engine.clone();
|
||||
let req = args.scope.request.clone();
|
||||
let host = crate::oauth::Host::new(app.clone(), args.scope.col.clone(), args.scope.env.clone());
|
||||
@@ -522,7 +522,7 @@ pub struct Preview {
|
||||
#[tauri::command]
|
||||
pub async fn request_preview(app: AppHandle, args: ScopeArgs) -> Res<Preview> {
|
||||
let state = app.state::<AppState>();
|
||||
let ctx = build_context(&state, &args).map_err(errx)?;
|
||||
let ctx = build_context(&app, &state, &args).map_err(errx)?;
|
||||
let mut p = match knock_core::prepare::prepare(&args.request, &ctx) {
|
||||
Ok(p) => p,
|
||||
Err(e) => {
|
||||
@@ -530,7 +530,7 @@ pub async fn request_preview(app: AppHandle, args: ScopeArgs) -> Res<Preview> {
|
||||
}
|
||||
};
|
||||
let host = crate::oauth::Host::preview(app.clone(), args.col.clone(), args.env.clone());
|
||||
let auth = knock_core::auth::apply(&ctx.auth, &mut p, &ctx.resolver, Some(&host), false).await;
|
||||
let auth = knock_core::auth::apply(&ctx.auth, &mut p, &ctx.resolver, Some(&host), false, &ctx.root).await;
|
||||
Ok(Preview {
|
||||
request: Some(knock_core::run::SentRequest {
|
||||
method: p.method.clone(),
|
||||
|
||||
@@ -21,6 +21,7 @@ pub fn run() {
|
||||
.setup(|app| {
|
||||
let dir = app.path().app_data_dir()?;
|
||||
app.manage(state::AppState::new(dir)?);
|
||||
app.manage(oauth::OauthState::default());
|
||||
Ok(())
|
||||
})
|
||||
.invoke_handler(tauri::generate_handler![
|
||||
@@ -66,6 +67,11 @@ pub fn run() {
|
||||
commands::setting_set,
|
||||
commands::path_params,
|
||||
commands::app_version,
|
||||
oauth::oauth_status,
|
||||
oauth::oauth_run,
|
||||
oauth::oauth_callback,
|
||||
oauth::oauth_deep_link,
|
||||
oauth::oauth_cancel,
|
||||
])
|
||||
.run(tauri::generate_context!())
|
||||
.expect("error while running knock");
|
||||
|
||||
+302
-21
@@ -1,21 +1,182 @@
|
||||
//! OAuth glue between the core flow code and the app (browser, keyring,
|
||||
//! flow log). Filled in with the OAuth milestone.
|
||||
//! 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 tauri::AppHandle;
|
||||
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 {
|
||||
#[allow(dead_code)]
|
||||
app: AppHandle,
|
||||
#[allow(dead_code)]
|
||||
col: Option<String>,
|
||||
#[allow(dead_code)]
|
||||
env: Option<String>,
|
||||
#[allow(dead_code)]
|
||||
interactive: bool,
|
||||
}
|
||||
|
||||
@@ -29,31 +190,151 @@ impl Host {
|
||||
}
|
||||
|
||||
impl AuthHost for Host {
|
||||
fn oauth2_token(
|
||||
&self,
|
||||
_cfg: &AuthConfig,
|
||||
_resolver: &Resolver,
|
||||
_force_refresh: bool,
|
||||
) -> futures_util::future::BoxFuture<'_, OauthResult> {
|
||||
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 {
|
||||
OauthResult {
|
||||
steps: vec![Step::new("token", "Get token", StepStatus::Error, "OAuth 2.0 is not wired up yet")],
|
||||
..Default::default()
|
||||
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 }
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
pub struct TokenLookup;
|
||||
/// `{{oauth.<name>.access_token}}` and friends.
|
||||
pub struct TokenLookup {
|
||||
app: AppHandle,
|
||||
col: String,
|
||||
env: Option<String>,
|
||||
}
|
||||
|
||||
impl TokenLookup {
|
||||
pub fn new(_state: &AppState, _c: &Collection, _env: Option<&str>) -> Self {
|
||||
Self
|
||||
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> {
|
||||
None
|
||||
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();
|
||||
}
|
||||
|
||||
@@ -14,7 +14,6 @@ pub struct StoredBody {
|
||||
}
|
||||
|
||||
pub struct AppState {
|
||||
pub data_dir: PathBuf,
|
||||
pub collections: RwLock<HashMap<String, Collection>>,
|
||||
pub engine: Arc<Engine>,
|
||||
pub db: Mutex<Connection>,
|
||||
@@ -33,7 +32,6 @@ impl AppState {
|
||||
let db = db::open(&data_dir.join("knock.db"))?;
|
||||
Ok(Self {
|
||||
engine: Arc::new(Engine::new(data_dir.join("responses"))),
|
||||
data_dir,
|
||||
collections: RwLock::default(),
|
||||
db: Mutex::new(db),
|
||||
runtime: Mutex::default(),
|
||||
|
||||
Reference in New Issue
Block a user