mirror of
https://github.com/JoshiCodes/knock.git
synced 2026-12-04 15:09: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
217 lines
10 KiB
Rust
217 lines
10 KiB
Rust
//! End-to-end OAuth flows against a tiny in-process provider.
|
|
|
|
use futures_util::future::BoxFuture;
|
|
use knock_core::auth::{Step, StepStatus};
|
|
use knock_core::model::AuthConfig;
|
|
use knock_core::oauth::{self, config::OauthConfig, FlowHooks, TokenSet};
|
|
use knock_core::vars::Resolver;
|
|
use std::collections::HashMap;
|
|
use std::sync::{Arc, Mutex};
|
|
use tokio::io::{AsyncReadExt, AsyncWriteExt};
|
|
use tokio::net::TcpListener;
|
|
|
|
#[derive(Default)]
|
|
struct Provider {
|
|
codes: HashMap<String, (String, Option<String>)>, // code -> (redirect_uri, code_challenge)
|
|
refreshes: u32,
|
|
reject_refresh: bool,
|
|
}
|
|
|
|
async fn start_provider(state: Arc<Mutex<Provider>>) -> String {
|
|
let l = TcpListener::bind("127.0.0.1:0").await.unwrap();
|
|
let base = format!("http://{}", l.local_addr().unwrap());
|
|
let base2 = base.clone();
|
|
tokio::spawn(async move {
|
|
loop {
|
|
let (mut s, _) = l.accept().await.unwrap();
|
|
let state = state.clone();
|
|
let base = base2.clone();
|
|
tokio::spawn(async move {
|
|
let mut buf = vec![0u8; 65536];
|
|
let n = s.read(&mut buf).await.unwrap_or(0);
|
|
let req = String::from_utf8_lossy(&buf[..n]).to_string();
|
|
let first = req.lines().next().unwrap_or("").to_string();
|
|
let target = first.split_whitespace().nth(1).unwrap_or("/").to_string();
|
|
let body = req.split("\r\n\r\n").nth(1).unwrap_or("").to_string();
|
|
let form: HashMap<String, String> = url::form_urlencoded::parse(body.as_bytes()).into_owned().collect();
|
|
let (status, extra_headers, payload) = route(&base, &target, &req, &form, &state);
|
|
let resp = format!(
|
|
"HTTP/1.1 {status}\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n{extra_headers}\r\n{payload}",
|
|
payload.len()
|
|
);
|
|
let _ = s.write_all(resp.as_bytes()).await;
|
|
});
|
|
}
|
|
});
|
|
base
|
|
}
|
|
|
|
fn route(base: &str, target: &str, raw: &str, form: &HashMap<String, String>, st: &Arc<Mutex<Provider>>) -> (String, String, String) {
|
|
let path = target.split('?').next().unwrap();
|
|
match path {
|
|
"/.well-known/openid-configuration" => (
|
|
"200 OK".into(),
|
|
String::new(),
|
|
serde_json::json!({
|
|
"issuer": base,
|
|
"authorization_endpoint": format!("{base}/authorize"),
|
|
"token_endpoint": format!("{base}/token"),
|
|
"scopes_supported": ["openid", "profile", "api"],
|
|
"code_challenge_methods_supported": ["S256"],
|
|
"token_endpoint_auth_methods_supported": ["client_secret_basic", "client_secret_post"]
|
|
})
|
|
.to_string(),
|
|
),
|
|
"/authorize" => {
|
|
let q: HashMap<String, String> = url::form_urlencoded::parse(target.split('?').nth(1).unwrap_or("").as_bytes()).into_owned().collect();
|
|
let code = format!("code-{}", q["state"].len());
|
|
st.lock().unwrap().codes.insert(code.clone(), (q["redirect_uri"].clone(), q.get("code_challenge").cloned()));
|
|
let loc = format!("{}?code={code}&state={}", q["redirect_uri"], q["state"]);
|
|
("302 Found".into(), format!("Location: {loc}\r\n"), String::new())
|
|
}
|
|
"/token" => {
|
|
let basic_ok = raw.contains("Authorization: Basic ") || raw.to_lowercase().contains("authorization: basic ");
|
|
if !basic_ok && form.get("client_secret").map(String::as_str) != Some("s3cret") {
|
|
return ("401 Unauthorized".into(), String::new(), r#"{"error":"invalid_client","error_description":"bad secret"}"#.into());
|
|
}
|
|
let ok = |extra: &str| {
|
|
(
|
|
"200 OK".to_string(),
|
|
String::new(),
|
|
format!(r#"{{"access_token":"at-{extra}","token_type":"Bearer","expires_in":3600,"refresh_token":"rt-1","scope":"api"}}"#),
|
|
)
|
|
};
|
|
match form.get("grant_type").map(String::as_str) {
|
|
Some("client_credentials") => ok("cc"),
|
|
Some("authorization_code") => {
|
|
let mut s = st.lock().unwrap();
|
|
let Some((redirect, challenge)) = s.codes.remove(&form["code"]) else {
|
|
return ("400 Bad Request".into(), String::new(), r#"{"error":"invalid_grant"}"#.into());
|
|
};
|
|
if redirect != form["redirect_uri"] {
|
|
return ("400 Bad Request".into(), String::new(), r#"{"error":"invalid_grant","error_description":"redirect_uri"}"#.into());
|
|
}
|
|
use base64::Engine;
|
|
use sha2::Digest;
|
|
let v = form.get("code_verifier").cloned().unwrap_or_default();
|
|
let calc = base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(sha2::Sha256::digest(v.as_bytes()));
|
|
if challenge.as_deref() != Some(calc.as_str()) {
|
|
return ("400 Bad Request".into(), String::new(), r#"{"error":"invalid_grant","error_description":"PKCE verification failed"}"#.into());
|
|
}
|
|
ok("code")
|
|
}
|
|
Some("refresh_token") => {
|
|
let mut s = st.lock().unwrap();
|
|
if s.reject_refresh {
|
|
return ("400 Bad Request".into(), String::new(), r#"{"error":"invalid_grant","error_description":"Token is not active"}"#.into());
|
|
}
|
|
s.refreshes += 1;
|
|
ok("refreshed")
|
|
}
|
|
_ => ("400 Bad Request".into(), String::new(), r#"{"error":"unsupported_grant_type"}"#.into()),
|
|
}
|
|
}
|
|
_ => ("404 Not Found".into(), String::new(), "{}".into()),
|
|
}
|
|
}
|
|
|
|
#[derive(Default)]
|
|
struct TestHooks {
|
|
store: Mutex<HashMap<String, TokenSet>>,
|
|
}
|
|
|
|
impl FlowHooks for TestHooks {
|
|
fn interactive(&self) -> bool {
|
|
true
|
|
}
|
|
fn open_browser(&self, url: &str) -> Result<(), String> {
|
|
// The "browser": follow the provider's redirect to the loopback listener.
|
|
let url = url.to_string();
|
|
tokio::spawn(async move {
|
|
let c = reqwest::Client::builder().redirect(reqwest::redirect::Policy::limited(3)).build().unwrap();
|
|
let _ = c.get(url).send().await;
|
|
});
|
|
Ok(())
|
|
}
|
|
fn wait_external(&self) -> BoxFuture<'static, Option<String>> {
|
|
Box::pin(async { None })
|
|
}
|
|
fn progress(&self, _: &Step) {}
|
|
fn device_prompt(&self, _: &str, _: &str, _: Option<&str>) {}
|
|
fn load_token(&self, key: &str) -> Option<TokenSet> {
|
|
self.store.lock().unwrap().get(key).cloned()
|
|
}
|
|
fn save_token(&self, key: &str, t: &TokenSet) {
|
|
self.store.lock().unwrap().insert(key.into(), t.clone());
|
|
}
|
|
fn delete_token(&self, key: &str) {
|
|
self.store.lock().unwrap().remove(key);
|
|
}
|
|
}
|
|
|
|
fn cfg(json: serde_json::Value) -> OauthConfig {
|
|
let a: AuthConfig = serde_json::from_value(json).unwrap();
|
|
OauthConfig::from_auth(&a, &Resolver::default())
|
|
}
|
|
|
|
#[tokio::test]
|
|
async fn client_credentials_then_cached_then_refresh() {
|
|
let st = Arc::new(Mutex::new(Provider::default()));
|
|
let base = start_provider(st.clone()).await;
|
|
let c = cfg(serde_json::json!({ "type": "oauth2", "grant": "client_credentials", "issuer": base, "client_id": "knock", "client_secret": "s3cret", "scopes": "api" }));
|
|
let hooks = TestHooks::default();
|
|
let key = c.store_key("col", Some("local"));
|
|
|
|
let r = oauth::obtain(&c, &key, &hooks, false).await;
|
|
assert_eq!(r.token.as_deref(), Some("at-cc"), "{:#?}", r.steps);
|
|
assert!(r.steps.iter().any(|s| s.id == "discovery" && s.status == StepStatus::Ok));
|
|
|
|
let r = oauth::obtain(&c, &key, &hooks, false).await;
|
|
assert_eq!(r.token.as_deref(), Some("at-cc"));
|
|
assert!(r.steps.iter().any(|s| s.id == "stored" && s.status == StepStatus::Ok));
|
|
|
|
// After a 401 the token is refreshed.
|
|
let r = oauth::obtain(&c, &key, &hooks, true).await;
|
|
assert_eq!(r.token.as_deref(), Some("at-refreshed"), "{:#?}", r.steps);
|
|
assert_eq!(st.lock().unwrap().refreshes, 1);
|
|
}
|
|
|
|
#[tokio::test]
|
|
async fn authorization_code_with_pkce_over_loopback() {
|
|
let st = Arc::new(Mutex::new(Provider::default()));
|
|
let base = start_provider(st.clone()).await;
|
|
let c = cfg(serde_json::json!({ "type": "oauth2", "issuer": base, "client_id": "knock", "client_secret": "s3cret", "scopes": "api", "redirect_port": 53199 }));
|
|
let hooks = TestHooks::default();
|
|
let key = c.store_key("col", None);
|
|
let r = oauth::obtain(&c, &key, &hooks, false).await;
|
|
assert_eq!(r.token.as_deref(), Some("at-code"), "{:#?}", r.steps);
|
|
let ids: Vec<&str> = r.steps.iter().map(|s| s.id.as_str()).collect();
|
|
for want in ["config", "discovery", "authorize", "browser", "callback", "received", "state", "token", "parse", "save"] {
|
|
assert!(ids.contains(&want), "missing step {want}: {ids:?}");
|
|
}
|
|
}
|
|
|
|
#[tokio::test]
|
|
async fn errors_are_explained() {
|
|
let st = Arc::new(Mutex::new(Provider::default()));
|
|
let base = start_provider(st.clone()).await;
|
|
let c = cfg(serde_json::json!({ "type": "oauth2", "grant": "client_credentials", "issuer": base, "client_id": "knock", "client_auth": "post", "client_secret": "wrong" }));
|
|
let hooks = TestHooks::default();
|
|
let r = oauth::obtain(&c, &c.store_key("c", None), &hooks, false).await;
|
|
assert!(r.token.is_none());
|
|
let failed = r.steps.iter().find(|s| s.status == StepStatus::Error).expect("an error step");
|
|
assert!(failed.summary.contains("invalid_client"), "{}", failed.summary);
|
|
let hint = failed.hint.clone().unwrap_or_default();
|
|
assert!(hint.contains("client_secret_basic"), "{hint}");
|
|
assert!(failed.exchange.as_ref().unwrap().curl.starts_with("curl -X POST"));
|
|
|
|
// A dead refresh token falls back to a new login (here: client credentials).
|
|
st.lock().unwrap().reject_refresh = true;
|
|
let c = cfg(serde_json::json!({ "type": "oauth2", "grant": "client_credentials", "issuer": base, "client_id": "knock", "client_secret": "s3cret" }));
|
|
let key = c.store_key("c", None);
|
|
hooks.save_token(&key, &TokenSet { access_token: "old".into(), refresh_token: Some("rt-dead".into()), expires_at: Some(0), obtained_at: 0, ..Default::default() });
|
|
let r = oauth::obtain(&c, &key, &hooks, false).await;
|
|
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);
|
|
}
|