Classify every comment as tautology, stale, excuse or decision record. Tautology/stale/excuse comments are deleted (excuses filed as issues #196-#236), decisions moved to docs/adr/0001-0034. - scripts/lint-comments.sh + .comment-baseline: per-file comment count may only go down; wired into tests/all.sh - .claude/skills/delete-comment: repeatable audit workflow - cargo fmt applied to touched crates Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
373 lines
11 KiB
Rust
373 lines
11 KiB
Rust
use crate::client::chain;
|
|
use crate::config::Server;
|
|
use hx_ai::auth::{await_redirect, now_ms, parse_code, pkce, urlenc};
|
|
use reqwest::Url;
|
|
use serde::{Deserialize, Serialize};
|
|
use serde_json::{Value, json};
|
|
use std::collections::BTreeMap;
|
|
use std::path::{Path, PathBuf};
|
|
|
|
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
|
|
pub struct Entry {
|
|
pub client_id: String,
|
|
#[serde(default, skip_serializing_if = "Option::is_none")]
|
|
pub client_secret: Option<String>,
|
|
pub token_endpoint: String,
|
|
pub access: String,
|
|
#[serde(default)]
|
|
pub refresh: Option<String>,
|
|
pub expires: u64,
|
|
}
|
|
|
|
type Store = BTreeMap<String, Entry>;
|
|
|
|
pub fn store_path() -> PathBuf {
|
|
hx_core::context::hx_home().join("mcp-auth.json")
|
|
}
|
|
|
|
fn path_of(s: &Server) -> PathBuf {
|
|
s.oauth.store.clone().unwrap_or_else(store_path)
|
|
}
|
|
|
|
fn read(p: &Path) -> Store {
|
|
std::fs::read(p)
|
|
.ok()
|
|
.and_then(|b| serde_json::from_slice(&b).ok())
|
|
.unwrap_or_default()
|
|
}
|
|
|
|
fn write(p: &Path, url: &str, e: Option<Entry>) -> Result<(), String> {
|
|
let mut s = read(p);
|
|
match e {
|
|
Some(e) => s.insert(url.into(), e),
|
|
None => s.remove(url),
|
|
};
|
|
let io = |e: std::io::Error| format!("{}: {e}", p.display());
|
|
std::fs::create_dir_all(p.parent().unwrap_or(p)).map_err(io)?;
|
|
let tmp = p.with_extension("tmp");
|
|
std::fs::write(&tmp, serde_json::to_vec_pretty(&s).unwrap_or_default()).map_err(io)?;
|
|
#[cfg(unix)]
|
|
{
|
|
use std::os::unix::fs::PermissionsExt;
|
|
std::fs::set_permissions(&tmp, std::fs::Permissions::from_mode(0o600)).map_err(io)?;
|
|
}
|
|
std::fs::rename(&tmp, p).map_err(io)
|
|
}
|
|
|
|
pub fn logout(s: &Server) -> Result<(), String> {
|
|
write(
|
|
&path_of(s),
|
|
s.url.as_deref().ok_or("not an HTTP server")?,
|
|
None,
|
|
)
|
|
}
|
|
|
|
pub fn logged_in(s: &Server) -> bool {
|
|
s.url
|
|
.as_deref()
|
|
.is_some_and(|u| read(&path_of(s)).contains_key(u))
|
|
}
|
|
|
|
pub fn resource_metadata(h: &str) -> Option<String> {
|
|
let i = h.find("resource_metadata=")? + "resource_metadata=".len();
|
|
let r = &h[i..];
|
|
Some(match r.strip_prefix('"') {
|
|
Some(q) => q.split('"').next()?.to_string(),
|
|
None => r.split([',', ' ']).next()?.to_string(),
|
|
})
|
|
.filter(|s| !s.is_empty())
|
|
}
|
|
|
|
pub fn as_metadata_urls(issuer: &str) -> Vec<String> {
|
|
let Ok(u) = Url::parse(issuer) else {
|
|
return vec![];
|
|
};
|
|
let origin = u.origin().ascii_serialization();
|
|
let p = u.path().trim_matches('/');
|
|
if p.is_empty() {
|
|
vec![
|
|
format!("{origin}/.well-known/oauth-authorization-server"),
|
|
format!("{origin}/.well-known/openid-configuration"),
|
|
]
|
|
} else {
|
|
vec![
|
|
format!("{origin}/.well-known/oauth-authorization-server/{p}"),
|
|
format!("{origin}/.well-known/openid-configuration/{p}"),
|
|
format!("{origin}/{p}/.well-known/openid-configuration"),
|
|
]
|
|
}
|
|
}
|
|
|
|
async fn get_json(h: &reqwest::Client, url: &str) -> Option<Value> {
|
|
let r = h.get(url).send().await.ok()?;
|
|
r.status().is_success().then_some(())?;
|
|
r.json().await.ok()
|
|
}
|
|
|
|
#[derive(Deserialize)]
|
|
struct TokenResp {
|
|
access_token: String,
|
|
refresh_token: Option<String>,
|
|
expires_in: Option<u64>,
|
|
}
|
|
|
|
async fn token_req(
|
|
h: &reqwest::Client,
|
|
endpoint: &str,
|
|
form: &[(&str, &str)],
|
|
) -> Result<TokenResp, String> {
|
|
let r = h
|
|
.post(endpoint)
|
|
.header("accept", "application/json")
|
|
.form(form)
|
|
.send()
|
|
.await
|
|
.map_err(|e| chain(&e))?;
|
|
let st = r.status();
|
|
let body = r.text().await.map_err(|e| chain(&e))?;
|
|
if !st.is_success() {
|
|
return Err(format!(
|
|
"token endpoint HTTP {st}: {}",
|
|
body.chars().take(300).collect::<String>()
|
|
));
|
|
}
|
|
serde_json::from_str(&body).map_err(|e| format!("bad token response: {e}"))
|
|
}
|
|
|
|
fn expiry(t: &TokenResp) -> u64 {
|
|
now_ms()
|
|
+ t.expires_in
|
|
.unwrap_or(3600)
|
|
.saturating_mul(1000)
|
|
.saturating_sub(60_000)
|
|
}
|
|
|
|
pub async fn login(s: &Server, announce: impl Fn(&str)) -> Result<(), String> {
|
|
let url = s.url.as_deref().ok_or("not an HTTP server")?;
|
|
let h = reqwest::Client::builder()
|
|
.timeout(std::time::Duration::from_secs(30))
|
|
.build()
|
|
.map_err(|e| chain(&e))?;
|
|
let probe = h
|
|
.post(url)
|
|
.header("accept", "application/json, text/event-stream")
|
|
.json(
|
|
&json!({"jsonrpc":"2.0","id":0,"method":"initialize","params":{
|
|
"protocolVersion": crate::client::PROTOCOL, "capabilities": {},
|
|
"clientInfo": {"name":"hx","version":env!("CARGO_PKG_VERSION")}}}),
|
|
)
|
|
.send()
|
|
.await
|
|
.map_err(|e| chain(&e))?;
|
|
if probe.status().as_u16() != 401 {
|
|
return Err(format!(
|
|
"server did not ask for auth (HTTP {})",
|
|
probe.status()
|
|
));
|
|
}
|
|
let origin = Url::parse(url)
|
|
.map_err(|e| chain(&e))?
|
|
.origin()
|
|
.ascii_serialization();
|
|
let hdr = probe
|
|
.headers()
|
|
.get("www-authenticate")
|
|
.and_then(|v| v.to_str().ok())
|
|
.unwrap_or_default();
|
|
let prm_url = resource_metadata(hdr)
|
|
.unwrap_or_else(|| format!("{origin}/.well-known/oauth-protected-resource"));
|
|
let issuer = get_json(&h, &prm_url)
|
|
.await
|
|
.and_then(|m| m["authorization_servers"][0].as_str().map(String::from))
|
|
.unwrap_or(origin);
|
|
let mut meta = None;
|
|
for u in as_metadata_urls(&issuer) {
|
|
if let Some(m) = get_json(&h, &u).await {
|
|
meta = Some(m);
|
|
break;
|
|
}
|
|
}
|
|
let meta = meta.ok_or_else(|| format!("no OAuth metadata found for {issuer}"))?;
|
|
let ep = |k: &str| {
|
|
meta[k]
|
|
.as_str()
|
|
.map(String::from)
|
|
.ok_or_else(|| format!("auth server metadata lacks {k}"))
|
|
};
|
|
let (authorize, token) = (ep("authorization_endpoint")?, ep("token_endpoint")?);
|
|
let listener = tokio::net::TcpListener::bind(("127.0.0.1", s.oauth.callback_port.unwrap_or(0)))
|
|
.await
|
|
.map_err(|e| format!("bind callback port: {e}"))?;
|
|
let redirect = format!(
|
|
"http://127.0.0.1:{}/callback",
|
|
listener.local_addr().map_err(|e| chain(&e))?.port()
|
|
);
|
|
let (client_id, client_secret) = match &s.oauth.client_id {
|
|
Some(id) => (id.clone(), s.oauth.client_secret.clone()),
|
|
None => {
|
|
let reg = meta["registration_endpoint"].as_str().ok_or(
|
|
"server has no dynamic client registration: set `oauth.clientId` in the mcp.json entry",
|
|
)?;
|
|
let r = h
|
|
.post(reg)
|
|
.json(&json!({
|
|
"client_name": "hx", "redirect_uris": [redirect],
|
|
"grant_types": ["authorization_code", "refresh_token"],
|
|
"response_types": ["code"], "token_endpoint_auth_method": "none"}))
|
|
.send()
|
|
.await
|
|
.map_err(|e| chain(&e))?;
|
|
let st = r.status();
|
|
let b: Value = r
|
|
.json()
|
|
.await
|
|
.map_err(|e| format!("bad registration reply: {e}"))?;
|
|
if !st.is_success() {
|
|
return Err(format!("client registration HTTP {st}: {b}"));
|
|
}
|
|
let id = b["client_id"]
|
|
.as_str()
|
|
.ok_or("registration: no client_id")?;
|
|
(id.into(), b["client_secret"].as_str().map(String::from))
|
|
}
|
|
};
|
|
let (verifier, challenge) = pkce();
|
|
let state = pkce().0;
|
|
let mut q = vec![
|
|
("response_type", "code"),
|
|
("client_id", &client_id),
|
|
("redirect_uri", &redirect),
|
|
("code_challenge", &challenge),
|
|
("code_challenge_method", "S256"),
|
|
("state", &state),
|
|
("resource", url),
|
|
];
|
|
if let Some(sc) = &s.oauth.scope {
|
|
q.push(("scope", sc));
|
|
}
|
|
let qs: Vec<String> = q
|
|
.iter()
|
|
.map(|(k, v)| format!("{k}={}", urlenc(v)))
|
|
.collect();
|
|
let sep = if authorize.contains('?') { '&' } else { '?' };
|
|
announce(&format!("{authorize}{sep}{}", qs.join("&")));
|
|
let (code, got) = parse_code(
|
|
&await_redirect(Some(listener), "/callback")
|
|
.await
|
|
.map_err(|e| chain(&e))?,
|
|
);
|
|
if got.as_deref().is_some_and(|g| g != state) {
|
|
return Err("OAuth state mismatch".into());
|
|
}
|
|
let code = code.ok_or("missing authorization code")?;
|
|
let mut form = vec![
|
|
("grant_type", "authorization_code"),
|
|
("code", code.as_str()),
|
|
("redirect_uri", redirect.as_str()),
|
|
("client_id", client_id.as_str()),
|
|
("code_verifier", verifier.as_str()),
|
|
("resource", url),
|
|
];
|
|
if let Some(sec) = &client_secret {
|
|
form.push(("client_secret", sec));
|
|
}
|
|
let t = token_req(&h, &token, &form).await?;
|
|
write(
|
|
&path_of(s),
|
|
url,
|
|
Some(Entry {
|
|
client_id,
|
|
client_secret,
|
|
token_endpoint: token,
|
|
expires: expiry(&t),
|
|
access: t.access_token,
|
|
refresh: t.refresh_token,
|
|
}),
|
|
)
|
|
}
|
|
|
|
pub async fn access(s: &Server, force: bool) -> Option<String> {
|
|
let url = s.url.as_deref()?;
|
|
let p = path_of(s);
|
|
let e = read(&p).remove(url)?;
|
|
if !force && e.expires > now_ms() {
|
|
return Some(e.access);
|
|
}
|
|
let rt = e.refresh.clone()?;
|
|
let mut form = vec![
|
|
("grant_type", "refresh_token"),
|
|
("refresh_token", rt.as_str()),
|
|
("client_id", e.client_id.as_str()),
|
|
("resource", url),
|
|
];
|
|
if let Some(sec) = &e.client_secret {
|
|
form.push(("client_secret", sec));
|
|
}
|
|
let t = token_req(&reqwest::Client::new(), &e.token_endpoint, &form)
|
|
.await
|
|
.ok()?;
|
|
let n = Entry {
|
|
expires: expiry(&t),
|
|
access: t.access_token.clone(),
|
|
refresh: t.refresh_token.or(Some(rt)),
|
|
..e
|
|
};
|
|
write(&p, url, Some(n)).ok()?;
|
|
Some(t.access_token)
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod t {
|
|
use super::*;
|
|
|
|
#[test]
|
|
fn www_authenticate() {
|
|
assert_eq!(
|
|
resource_metadata(r#"Bearer realm="x", resource_metadata="https://a/b""#).as_deref(),
|
|
Some("https://a/b")
|
|
);
|
|
assert_eq!(resource_metadata("Bearer realm=x"), None);
|
|
}
|
|
|
|
#[test]
|
|
fn metadata_candidates() {
|
|
assert_eq!(
|
|
as_metadata_urls("https://a.com"),
|
|
[
|
|
"https://a.com/.well-known/oauth-authorization-server",
|
|
"https://a.com/.well-known/openid-configuration"
|
|
]
|
|
);
|
|
assert_eq!(
|
|
as_metadata_urls("https://a.com/t1")[0],
|
|
"https://a.com/.well-known/oauth-authorization-server/t1"
|
|
);
|
|
}
|
|
|
|
#[test]
|
|
fn store_roundtrip_0600() {
|
|
let d = tempfile::tempdir().unwrap();
|
|
let p = d.path().join("x/mcp-auth.json");
|
|
let e = Entry {
|
|
client_id: "c".into(),
|
|
client_secret: None,
|
|
token_endpoint: "t".into(),
|
|
access: "a".into(),
|
|
refresh: Some("r".into()),
|
|
expires: 1,
|
|
};
|
|
write(&p, "https://u", Some(e.clone())).unwrap();
|
|
assert_eq!(read(&p)["https://u"], e);
|
|
#[cfg(unix)]
|
|
{
|
|
use std::os::unix::fs::PermissionsExt;
|
|
assert_eq!(
|
|
std::fs::metadata(&p).unwrap().permissions().mode() & 0o777,
|
|
0o600
|
|
);
|
|
}
|
|
write(&p, "https://u", None).unwrap();
|
|
assert!(read(&p).is_empty());
|
|
}
|
|
}
|