use std::collections::BTreeMap;
use std::fmt;
use std::io::{Read, Write};
use std::net::{SocketAddr, TcpListener, TcpStream};
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::{Mutex, OnceLock};
use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
use serde::{Deserialize, Serialize};
use sha2::{Digest, Sha256};
use super::config::user_config_dir;
pub const DEFAULT_EXPIRY_MARGIN_SECS: u64 = 60;
pub const DEFAULT_OAUTH_HTTP_TIMEOUT: Duration = Duration::from_secs(30);
pub const DEFAULT_CALLBACK_TIMEOUT: Duration = Duration::from_secs(300);
#[derive(Debug)]
pub enum McpOAuthError {
Config(String),
Discovery(String),
Registration(String),
Callback(String),
StateMismatch,
AuthDenied(String),
TokenExchange(String),
RefreshFailed(String),
Timeout(String),
Io(String),
}
impl fmt::Display for McpOAuthError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
McpOAuthError::Config(msg) => write!(f, "MCP OAuth configuration error: {msg}"),
McpOAuthError::Discovery(msg) => write!(f, "MCP OAuth discovery failed: {msg}"),
McpOAuthError::Registration(msg) => {
write!(f, "MCP OAuth client registration failed: {msg}")
}
McpOAuthError::Callback(msg) => write!(f, "MCP OAuth callback error: {msg}"),
McpOAuthError::StateMismatch => {
write!(f, "MCP OAuth callback state mismatch")
}
McpOAuthError::AuthDenied(msg) => write!(f, "MCP OAuth authorization denied: {msg}"),
McpOAuthError::TokenExchange(msg) => {
write!(f, "MCP OAuth token exchange failed: {msg}")
}
McpOAuthError::RefreshFailed(msg) => {
write!(f, "MCP OAuth token refresh failed: {msg}")
}
McpOAuthError::Timeout(msg) => write!(f, "MCP OAuth timed out: {msg}"),
McpOAuthError::Io(msg) => write!(f, "MCP OAuth I/O error: {msg}"),
}
}
}
impl std::error::Error for McpOAuthError {}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Default)]
pub struct StoredServerAuth {
pub server_url: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub authorization_server: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub token_endpoint: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub client_id: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub client_secret: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub redirect_uri: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub access_token: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub refresh_token: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub token_type: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub scope: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub expires_at: Option<u64>,
}
impl StoredServerAuth {
pub fn is_expired_or_near_expiry(&self, now_secs: u64, margin_secs: u64) -> bool {
self.expires_at
.is_some_and(|exp| now_secs.saturating_add(margin_secs) >= exp)
}
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Default)]
pub struct McpAuthStore {
#[serde(default)]
pub servers: BTreeMap<String, StoredServerAuth>,
}
impl McpAuthStore {
pub fn default_path() -> Result<PathBuf, McpOAuthError> {
let dir = user_config_dir().map_err(|e| McpOAuthError::Config(e.to_string()))?;
Ok(dir.join("mcp-auth.json"))
}
pub fn load(path: &Path) -> Result<Self, McpOAuthError> {
match std::fs::read_to_string(path) {
Ok(text) => {
if text.trim().is_empty() {
return Ok(Self::default());
}
serde_json::from_str(&text).map_err(|e| {
McpOAuthError::Config(format!("invalid MCP auth store {}: {e}", path.display()))
})
}
Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(Self::default()),
Err(e) => Err(McpOAuthError::Io(format!(
"cannot read {}: {e}",
path.display()
))),
}
}
pub fn save(&self, path: &Path) -> Result<(), McpOAuthError> {
let (parent, file_name) = auth_store_path_parts(path)?;
if !parent.as_os_str().is_empty() {
std::fs::create_dir_all(parent).map_err(|e| {
McpOAuthError::Io(format!("cannot create {}: {e}", parent.display()))
})?;
set_dir_permissions_0700(parent)?;
}
let body = serde_json::to_string_pretty(self)
.map_err(|e| McpOAuthError::Config(format!("cannot serialize MCP auth store: {e}")))?;
let pid = std::process::id();
let nanos = now_unix_nanos()?;
static SAVE_SEQ: AtomicU64 = AtomicU64::new(0);
let seq = SAVE_SEQ.fetch_add(1, Ordering::Relaxed);
let tmp_name = format!(".{file_name}.tmp.{pid}.{nanos}.{seq}");
let tmp_path = parent.join(tmp_name);
write_file_0600(&tmp_path, format!("{body}\n").as_bytes())?;
if let Err(e) = std::fs::rename(&tmp_path, path) {
let _ = std::fs::remove_file(&tmp_path);
return Err(McpOAuthError::Io(format!(
"cannot persist {}: {e}",
path.display()
)));
}
set_file_permissions_0600(path)?;
Ok(())
}
pub fn modify<T, F>(path: &Path, f: F) -> Result<T, McpOAuthError>
where
F: FnOnce(&mut Self) -> Result<(bool, T), McpOAuthError>,
{
with_auth_store_lock(path, || {
let mut store = Self::load(path)?;
let (dirty, out) = f(&mut store)?;
if dirty {
store.save(path)?;
}
Ok(out)
})
}
pub fn get(&self, server_name: &str) -> Option<&StoredServerAuth> {
self.servers.get(server_name)
}
pub fn upsert(&mut self, server_name: &str, auth: StoredServerAuth) {
self.servers.insert(server_name.to_string(), auth);
}
pub fn remove(&mut self, server_name: &str) -> bool {
self.servers.remove(server_name).is_some()
}
pub fn secret_pairs(&self) -> Vec<(String, String)> {
let mut pairs = Vec::new();
for (name, auth) in &self.servers {
if let Some(ref token) = auth.access_token {
if !token.is_empty() {
pairs.push((format!("MCP_ACCESS_TOKEN_{name}"), token.clone()));
}
}
if let Some(ref token) = auth.refresh_token {
if !token.is_empty() {
pairs.push((format!("MCP_REFRESH_TOKEN_{name}"), token.clone()));
}
}
if let Some(ref secret) = auth.client_secret {
if !secret.is_empty() {
pairs.push((format!("MCP_CLIENT_SECRET_{name}"), secret.clone()));
}
}
}
pairs
}
}
fn auth_store_path_parts(path: &Path) -> Result<(&Path, &str), McpOAuthError> {
let parent = path.parent().ok_or_else(|| {
McpOAuthError::Config(format!(
"MCP auth store path '{}' has no parent directory",
path.display()
))
})?;
let file_name = path.file_name().and_then(|n| n.to_str()).ok_or_else(|| {
McpOAuthError::Config(format!(
"MCP auth store path '{}' has missing or non-UTF-8 file name",
path.display()
))
})?;
Ok((parent, file_name))
}
fn auth_store_mutex() -> &'static Mutex<()> {
static LOCK: OnceLock<Mutex<()>> = OnceLock::new();
LOCK.get_or_init(|| Mutex::new(()))
}
#[cfg(unix)]
struct AuthStoreFileLock {
file: std::fs::File,
}
#[cfg(unix)]
impl AuthStoreFileLock {
fn acquire(path: &Path) -> Result<Self, McpOAuthError> {
use std::os::unix::fs::OpenOptionsExt;
use std::os::unix::io::AsRawFd;
let (parent, file_name) = auth_store_path_parts(path)?;
if !parent.as_os_str().is_empty() {
std::fs::create_dir_all(parent).map_err(|e| {
McpOAuthError::Io(format!("cannot create {}: {e}", parent.display()))
})?;
set_dir_permissions_0700(parent)?;
}
let lock_path = parent.join(format!(".{file_name}.lock"));
let file = std::fs::OpenOptions::new()
.create(true)
.truncate(false)
.read(true)
.write(true)
.mode(0o600)
.open(&lock_path)
.map_err(|e| {
McpOAuthError::Io(format!(
"cannot open lock file {}: {e}",
lock_path.display()
))
})?;
set_file_permissions_0600(&lock_path)?;
let fd = file.as_raw_fd();
loop {
let rc = unsafe { libc::flock(fd, libc::LOCK_EX) };
if rc == 0 {
return Ok(Self { file });
}
let err = std::io::Error::last_os_error();
if err.kind() == std::io::ErrorKind::Interrupted {
continue;
}
return Err(McpOAuthError::Io(format!(
"cannot lock {}: {err}",
lock_path.display()
)));
}
}
}
#[cfg(unix)]
impl Drop for AuthStoreFileLock {
fn drop(&mut self) {
use std::os::unix::io::AsRawFd;
let _ = unsafe { libc::flock(self.file.as_raw_fd(), libc::LOCK_UN) };
}
}
fn with_auth_store_lock<T, F>(path: &Path, f: F) -> Result<T, McpOAuthError>
where
F: FnOnce() -> Result<T, McpOAuthError>,
{
let _in_process = auth_store_mutex()
.lock()
.map_err(|_| McpOAuthError::Io("MCP auth store lock is poisoned".to_string()))?;
#[cfg(unix)]
let _file_lock = AuthStoreFileLock::acquire(path)?;
#[cfg(not(unix))]
let _ = auth_store_path_parts(path)?;
f()
}
#[cfg(unix)]
fn set_dir_permissions_0700(path: &Path) -> Result<(), McpOAuthError> {
use std::os::unix::fs::PermissionsExt;
let perms = std::fs::Permissions::from_mode(0o700);
std::fs::set_permissions(path, perms)
.map_err(|e| McpOAuthError::Io(format!("cannot chmod 0700 {}: {e}", path.display())))
}
#[cfg(not(unix))]
fn set_dir_permissions_0700(_path: &Path) -> Result<(), McpOAuthError> {
Ok(())
}
#[cfg(unix)]
fn set_file_permissions_0600(path: &Path) -> Result<(), McpOAuthError> {
use std::os::unix::fs::PermissionsExt;
let perms = std::fs::Permissions::from_mode(0o600);
std::fs::set_permissions(path, perms)
.map_err(|e| McpOAuthError::Io(format!("cannot chmod 0600 {}: {e}", path.display())))
}
#[cfg(not(unix))]
fn set_file_permissions_0600(_path: &Path) -> Result<(), McpOAuthError> {
Ok(())
}
#[cfg(unix)]
fn write_file_0600(path: &Path, data: &[u8]) -> Result<(), McpOAuthError> {
use std::os::unix::fs::OpenOptionsExt;
let mut file = std::fs::OpenOptions::new()
.create(true)
.write(true)
.truncate(true)
.mode(0o600)
.open(path)
.map_err(|e| McpOAuthError::Io(format!("cannot create {}: {e}", path.display())))?;
file.write_all(data)
.map_err(|e| McpOAuthError::Io(format!("cannot write {}: {e}", path.display())))?;
file.flush()
.map_err(|e| McpOAuthError::Io(format!("cannot flush {}: {e}", path.display())))?;
set_file_permissions_0600(path)?;
Ok(())
}
#[cfg(not(unix))]
fn write_file_0600(path: &Path, data: &[u8]) -> Result<(), McpOAuthError> {
std::fs::write(path, data)
.map_err(|e| McpOAuthError::Io(format!("cannot write {}: {e}", path.display())))
}
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct ProtectedResourceMetadata {
#[serde(default)]
pub resource: Option<String>,
#[serde(default)]
pub authorization_servers: Vec<String>,
#[serde(default)]
pub scopes_supported: Option<Vec<String>>,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct AuthorizationServerMetadata {
#[serde(default)]
pub issuer: Option<String>,
pub authorization_endpoint: String,
pub token_endpoint: String,
#[serde(default)]
pub registration_endpoint: Option<String>,
#[serde(default)]
pub code_challenge_methods_supported: Option<Vec<String>>,
#[serde(default)]
pub scopes_supported: Option<Vec<String>>,
}
#[derive(Debug, Clone, Deserialize)]
struct ClientRegistrationResponse {
client_id: String,
#[serde(default)]
client_secret: Option<String>,
}
#[derive(Debug, Clone, Deserialize)]
struct TokenEndpointResponse {
access_token: String,
#[serde(default)]
token_type: Option<String>,
#[serde(default)]
expires_in: Option<u64>,
#[serde(default)]
refresh_token: Option<String>,
#[serde(default)]
scope: Option<String>,
}
#[derive(Debug, Clone, Deserialize)]
struct OAuthErrorResponse {
#[serde(default)]
error: Option<String>,
#[serde(default)]
error_description: Option<String>,
}
pub struct PendingOAuthFlow {
authorize_url: String,
redirect_uri: String,
state: String,
code_verifier: String,
client_id: String,
client_secret: Option<String>,
token_endpoint: String,
authorization_server: String,
resource: Option<String>,
server_name: String,
server_url: String,
auth_store_path: PathBuf,
listener: TcpListener,
http_timeout: Duration,
}
impl PendingOAuthFlow {
pub fn authorize_url(&self) -> &str {
&self.authorize_url
}
pub fn redirect_uri(&self) -> &str {
&self.redirect_uri
}
pub fn state(&self) -> &str {
&self.state
}
pub fn client_id(&self) -> &str {
&self.client_id
}
pub fn complete(self, callback_timeout: Duration) -> Result<StoredServerAuth, McpOAuthError> {
let callback = wait_for_loopback_callback(&self.listener, callback_timeout)?;
let mut stream = callback.stream;
if let Some(err) = callback.params.get("error") {
let desc = callback
.params
.get("error_description")
.map(|d| format!("{err}: {d}"))
.unwrap_or_else(|| err.clone());
let _ = send_html_response(
&mut stream,
"400 Bad Request",
"Authentication failed",
&format!("Authorization was denied ({}).", escape_html(&desc)),
);
return Err(McpOAuthError::AuthDenied(desc));
}
let received_state = callback.params.get("state").map(String::as_str);
if received_state != Some(self.state.as_str()) {
let _ = send_html_response(
&mut stream,
"400 Bad Request",
"Authentication failed",
"The OAuth state parameter did not match. Please restart authentication from blyte.",
);
return Err(McpOAuthError::StateMismatch);
}
let Some(code) = callback
.params
.get("code")
.filter(|c| !c.is_empty())
.cloned()
else {
let _ = send_html_response(
&mut stream,
"400 Bad Request",
"Authentication failed",
"The authorization callback did not include an authorization code.",
);
return Err(McpOAuthError::Callback(
"callback missing authorization code".to_string(),
));
};
let agent = build_http_agent(self.http_timeout);
let token_res = exchange_authorization_code(
&agent,
&self.token_endpoint,
&code,
&self.redirect_uri,
&self.client_id,
self.client_secret.as_deref(),
&self.code_verifier,
self.resource.as_deref(),
);
let token = match token_res {
Ok(t) => t,
Err(e) => {
let _ = send_html_response(
&mut stream,
"500 Internal Server Error",
"Authentication failed",
"Token exchange failed. Check blyte output for details.",
);
return Err(e);
}
};
let now = now_unix_secs()?;
let stored = StoredServerAuth {
server_url: self.server_url.clone(),
authorization_server: Some(self.authorization_server.clone()),
token_endpoint: Some(self.token_endpoint.clone()),
client_id: Some(self.client_id.clone()),
client_secret: self.client_secret.clone(),
redirect_uri: Some(self.redirect_uri.clone()),
access_token: Some(token.access_token),
refresh_token: token.refresh_token,
token_type: token.token_type.or_else(|| Some("Bearer".to_string())),
scope: token.scope,
expires_at: token.expires_in.map(|secs| now.saturating_add(secs)),
};
McpAuthStore::modify(&self.auth_store_path, |store| {
store.upsert(&self.server_name, stored.clone());
Ok((true, ()))
})?;
let _ = send_html_response(
&mut stream,
"200 OK",
"Authentication complete",
&format!(
"blyte is now authenticated with <strong>{}</strong>. You can close this tab and return to blyte.",
escape_html(&self.server_name)
),
);
Ok(stored)
}
}
pub fn prepare_oauth_flow(
auth_store_path: &Path,
server_name: &str,
server_url: &str,
www_authenticate: Option<&str>,
http_timeout: Duration,
) -> Result<PendingOAuthFlow, McpOAuthError> {
let agent = build_http_agent(http_timeout);
let (discovered_www_auth, resource_meta) =
discover_protected_resource(&agent, server_url, www_authenticate)?;
let auth_server_url = resolve_authorization_server_url(server_url, resource_meta.as_ref())?;
let auth_meta = discover_authorization_server(&agent, &auth_server_url)?;
let auth_server_id = auth_meta
.issuer
.as_deref()
.map(str::trim)
.filter(|s| !s.is_empty())
.map(str::to_string)
.ok_or_else(|| {
McpOAuthError::Discovery(format!(
"authorization server metadata for {auth_server_url} is missing required 'issuer' field"
))
})?;
let store = McpAuthStore::load(auth_store_path)?;
let cached = store
.get(server_name)
.filter(|entry| {
entry.server_url == server_url
&& entry
.authorization_server
.as_deref()
.is_none_or(|issuer| issuer == auth_server_id)
&& entry.client_id.is_some()
})
.cloned();
let (listener, redirect_uri, client_id, client_secret) =
obtain_client_and_listener(&agent, &auth_meta, cached.as_ref())?;
McpAuthStore::modify(auth_store_path, |store| {
let mut cached_entry = store
.get(server_name)
.filter(|entry| entry.server_url == server_url)
.cloned()
.unwrap_or_else(|| StoredServerAuth {
server_url: server_url.to_string(),
..StoredServerAuth::default()
});
cached_entry.server_url = server_url.to_string();
cached_entry.authorization_server = Some(auth_server_id.clone());
cached_entry.token_endpoint = Some(auth_meta.token_endpoint.clone());
cached_entry.client_id = Some(client_id.clone());
cached_entry.client_secret = client_secret.clone();
cached_entry.redirect_uri = Some(redirect_uri.clone());
store.upsert(server_name, cached_entry);
Ok((true, ()))
})?;
let code_verifier = generate_code_verifier()?;
let code_challenge = compute_code_challenge_s256(&code_verifier);
let state = generate_state()?;
let resource = resource_meta
.as_ref()
.and_then(|m| m.resource.clone())
.or_else(|| Some(server_url.to_string()));
let scope = discovered_www_auth
.as_deref()
.and_then(|h| parse_www_authenticate_param(h, "scope"))
.or_else(|| {
resource_meta
.as_ref()
.and_then(|m| m.scopes_supported.as_ref())
.filter(|s| !s.is_empty())
.map(|s| s.join(" "))
});
let mut params: Vec<(&str, &str)> = vec![
("response_type", "code"),
("client_id", &client_id),
("redirect_uri", &redirect_uri),
("code_challenge", &code_challenge),
("code_challenge_method", "S256"),
("state", &state),
];
if let Some(ref res) = resource {
params.push(("resource", res));
}
if let Some(ref sc) = scope {
params.push(("scope", sc));
}
let authorize_url = append_query_params(&auth_meta.authorization_endpoint, ¶ms);
Ok(PendingOAuthFlow {
authorize_url,
redirect_uri,
state,
code_verifier,
client_id,
client_secret,
token_endpoint: auth_meta.token_endpoint,
authorization_server: auth_server_id,
resource,
server_name: server_name.to_string(),
server_url: server_url.to_string(),
auth_store_path: auth_store_path.to_path_buf(),
listener,
http_timeout,
})
}
pub fn refresh_access_token(
auth_store_path: &Path,
server_name: &str,
server_url: &str,
www_authenticate: Option<&str>,
http_timeout: Duration,
) -> Result<StoredServerAuth, McpOAuthError> {
let store = McpAuthStore::load(auth_store_path)?;
let existing = store
.get(server_name)
.filter(|entry| entry.server_url == server_url)
.cloned()
.ok_or_else(|| {
McpOAuthError::RefreshFailed(format!(
"no stored OAuth credentials for MCP server '{server_name}'"
))
})?;
let refresh_token = existing
.refresh_token
.clone()
.filter(|t| !t.is_empty())
.ok_or_else(|| {
McpOAuthError::RefreshFailed(format!(
"no refresh token stored for MCP server '{server_name}'"
))
})?;
let agent = build_http_agent(http_timeout);
let token_endpoint = match existing.token_endpoint.clone() {
Some(ep) => ep,
None => {
let (_, resource_meta) =
discover_protected_resource(&agent, server_url, www_authenticate)?;
let auth_server_url =
resolve_authorization_server_url(server_url, resource_meta.as_ref())?;
let auth_meta = discover_authorization_server(&agent, &auth_server_url)?;
auth_meta.token_endpoint
}
};
let mut form: Vec<(&str, &str)> = vec![
("grant_type", "refresh_token"),
("refresh_token", &refresh_token),
];
if let Some(ref cid) = existing.client_id {
form.push(("client_id", cid));
}
if let Some(ref secret) = existing.client_secret {
form.push(("client_secret", secret));
}
let token = post_token_form(&agent, &token_endpoint, &form)
.map_err(|e| McpOAuthError::RefreshFailed(e.to_string()))?;
let now = now_unix_secs()?;
let updated = StoredServerAuth {
server_url: existing.server_url,
authorization_server: existing.authorization_server,
token_endpoint: Some(token_endpoint),
client_id: existing.client_id,
client_secret: existing.client_secret,
redirect_uri: existing.redirect_uri,
access_token: Some(token.access_token),
refresh_token: token.refresh_token.or(Some(refresh_token)),
token_type: token.token_type.or(existing.token_type),
scope: token.scope.or(existing.scope),
expires_at: token.expires_in.map(|secs| now.saturating_add(secs)),
};
McpAuthStore::modify(auth_store_path, |store| {
store.upsert(server_name, updated.clone());
Ok((true, ()))
})?;
Ok(updated)
}
pub fn resolve_bearer_token(
auth_store_path: &Path,
server_name: &str,
server_url: &str,
http_timeout: Duration,
) -> Result<Option<String>, McpOAuthError> {
resolve_bearer_token_at(
auth_store_path,
server_name,
server_url,
http_timeout,
now_unix_secs()?,
)
}
pub fn resolve_bearer_token_at(
auth_store_path: &Path,
server_name: &str,
server_url: &str,
http_timeout: Duration,
now_secs: u64,
) -> Result<Option<String>, McpOAuthError> {
let store = McpAuthStore::load(auth_store_path)?;
let Some(entry) = store.get(server_name) else {
return Ok(None);
};
if entry.server_url != server_url {
return Ok(None);
}
if let Some(ref token) = entry.access_token {
if !token.is_empty()
&& !entry.is_expired_or_near_expiry(now_secs, DEFAULT_EXPIRY_MARGIN_SECS)
{
return Ok(Some(token.clone()));
}
}
if entry
.refresh_token
.as_deref()
.is_some_and(|t| !t.is_empty())
{
match refresh_access_token(auth_store_path, server_name, server_url, None, http_timeout) {
Ok(refreshed) => return Ok(refreshed.access_token),
Err(_) => return Ok(None),
}
}
Ok(None)
}
pub fn logout_server(auth_store_path: &Path, server_name: &str) -> Result<bool, McpOAuthError> {
McpAuthStore::modify(auth_store_path, |store| {
let removed = store.remove(server_name);
Ok((removed, removed))
})
}
pub fn parse_www_authenticate_param(header: &str, param_name: &str) -> Option<String> {
let bytes = header.as_bytes();
let mut i = 0;
while i < bytes.len() {
while i < bytes.len()
&& (bytes[i].is_ascii_whitespace() || bytes[i] == b',' || bytes[i] == b';')
{
i += 1;
}
let key_start = i;
while i < bytes.len()
&& !bytes[i].is_ascii_whitespace()
&& bytes[i] != b'='
&& bytes[i] != b','
{
i += 1;
}
let key = &header[key_start..i];
while i < bytes.len() && bytes[i].is_ascii_whitespace() {
i += 1;
}
if i >= bytes.len() || bytes[i] != b'=' {
continue;
}
i += 1;
while i < bytes.len() && bytes[i].is_ascii_whitespace() {
i += 1;
}
let value = if i < bytes.len() && bytes[i] == b'"' {
i += 1;
let mut out = String::new();
while i < bytes.len() {
if bytes[i] == b'\\' && i + 1 < bytes.len() {
i += 1;
out.push(bytes[i] as char);
i += 1;
} else if bytes[i] == b'"' {
i += 1;
break;
} else {
let ch = header[i..].chars().next()?;
out.push(ch);
i += ch.len_utf8();
}
}
out
} else {
let val_start = i;
while i < bytes.len() && bytes[i] != b',' && !bytes[i].is_ascii_whitespace() {
i += 1;
}
header[val_start..i].to_string()
};
if key.eq_ignore_ascii_case(param_name) && !value.is_empty() {
return Some(value);
}
}
None
}
pub fn generate_code_verifier() -> Result<String, McpOAuthError> {
let bytes = generate_random_bytes(32)?;
Ok(base64url_encode(&bytes))
}
pub fn compute_code_challenge_s256(code_verifier: &str) -> String {
let digest = Sha256::digest(code_verifier.as_bytes());
base64url_encode(&digest)
}
pub fn generate_state() -> Result<String, McpOAuthError> {
let bytes = generate_random_bytes(24)?;
Ok(base64url_encode(&bytes))
}
fn generate_random_bytes(len: usize) -> Result<Vec<u8>, McpOAuthError> {
#[cfg(unix)]
{
let mut buf = vec![0u8; len];
let mut f = std::fs::File::open("/dev/urandom")
.map_err(|e| McpOAuthError::Io(format!("cannot open /dev/urandom: {e}")))?;
f.read_exact(&mut buf)
.map_err(|e| McpOAuthError::Io(format!("cannot read /dev/urandom: {e}")))?;
Ok(buf)
}
#[cfg(not(unix))]
{
use std::collections::hash_map::RandomState;
use std::hash::{BuildHasher, Hasher};
let mut out = Vec::with_capacity(len);
while out.len() < len {
let s = RandomState::new();
let mut h = s.build_hasher();
h.write_u128(now_unix_nanos()?);
out.extend_from_slice(&h.finish().to_le_bytes());
}
out.truncate(len);
Ok(out)
}
}
pub fn base64url_encode(input: &[u8]) -> String {
const TABLE: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";
let mut out = String::with_capacity(input.len().div_ceil(3) * 4);
for chunk in input.chunks(3) {
let b0 = chunk[0] as u32;
let b1 = if chunk.len() > 1 { chunk[1] as u32 } else { 0 };
let b2 = if chunk.len() > 2 { chunk[2] as u32 } else { 0 };
let triple = (b0 << 16) | (b1 << 8) | b2;
out.push(TABLE[((triple >> 18) & 0x3f) as usize] as char);
out.push(TABLE[((triple >> 12) & 0x3f) as usize] as char);
if chunk.len() > 1 {
out.push(TABLE[((triple >> 6) & 0x3f) as usize] as char);
}
if chunk.len() > 2 {
out.push(TABLE[(triple & 0x3f) as usize] as char);
}
}
out
}
fn build_http_agent(timeout: Duration) -> ureq::Agent {
ureq::AgentBuilder::new()
.timeout_connect(timeout)
.timeout_read(timeout)
.timeout_write(timeout)
.build()
}
fn discover_protected_resource(
agent: &ureq::Agent,
server_url: &str,
www_authenticate: Option<&str>,
) -> Result<(Option<String>, Option<ProtectedResourceMetadata>), McpOAuthError> {
let mut effective_www_auth = www_authenticate.map(str::to_string);
if effective_www_auth.is_none() {
if let Err(ureq::Error::Status(401, resp)) = agent
.get(server_url)
.set("Accept", "application/json, text/event-stream")
.call()
{
if let Some(hdr) = resp.header("www-authenticate") {
effective_www_auth = Some(hdr.to_string());
}
}
}
if effective_www_auth.is_none() {
if let Err(ureq::Error::Status(401, resp)) = agent
.post(server_url)
.set("Content-Type", "application/json")
.set("Accept", "application/json, text/event-stream")
.send_string("{}")
{
if let Some(hdr) = resp.header("www-authenticate") {
effective_www_auth = Some(hdr.to_string());
}
}
}
let mut candidates = Vec::new();
if let Some(ref hdr) = effective_www_auth {
if let Some(url) = parse_www_authenticate_param(hdr, "resource_metadata") {
candidates.push(url);
}
}
let (origin, path) = parse_url_parts(server_url)?;
if !path.is_empty() {
candidates.push(format!(
"{origin}/.well-known/oauth-protected-resource{path}"
));
}
candidates.push(format!("{origin}/.well-known/oauth-protected-resource"));
let mut seen = Vec::new();
for url in candidates {
if seen.contains(&url) {
continue;
}
seen.push(url.clone());
match agent.get(&url).set("Accept", "application/json").call() {
Ok(resp) if (200..300).contains(&resp.status()) => {
if let Ok(meta) = resp.into_json::<ProtectedResourceMetadata>() {
return Ok((effective_www_auth, Some(meta)));
}
}
Ok(_) | Err(ureq::Error::Status(_, _)) => continue,
Err(ureq::Error::Transport(t)) => {
return Err(McpOAuthError::Discovery(format!(
"failed to reach {url}: {t}"
)));
}
}
}
Ok((effective_www_auth, None))
}
fn discover_authorization_server(
agent: &ureq::Agent,
auth_server_url: &str,
) -> Result<AuthorizationServerMetadata, McpOAuthError> {
let (origin, path) = parse_url_parts(auth_server_url)?;
let mut candidates = Vec::new();
if !path.is_empty() {
candidates.push(format!(
"{origin}/.well-known/oauth-authorization-server{path}"
));
candidates.push(format!("{origin}/.well-known/openid-configuration{path}"));
candidates.push(format!("{origin}{path}/.well-known/openid-configuration"));
}
candidates.push(format!("{origin}/.well-known/oauth-authorization-server"));
candidates.push(format!("{origin}/.well-known/openid-configuration"));
let mut seen = Vec::new();
let mut metadata_err = None;
let mut last_err = None;
for url in candidates {
if seen.contains(&url) {
continue;
}
seen.push(url.clone());
match agent.get(&url).set("Accept", "application/json").call() {
Ok(resp) if (200..300).contains(&resp.status()) => {
match resp.into_json::<AuthorizationServerMetadata>() {
Ok(meta) => {
let issuer = meta.issuer.as_deref().map(str::trim).unwrap_or("");
if issuer.is_empty() {
if metadata_err.is_none() {
metadata_err = Some(format!(
"authorization server metadata at {url} is missing required 'issuer' field"
));
}
continue;
}
if meta.authorization_endpoint.trim().is_empty()
|| meta.token_endpoint.trim().is_empty()
{
if metadata_err.is_none() {
metadata_err = Some(format!(
"metadata at {url} missing authorization_endpoint or token_endpoint"
));
}
continue;
}
if let Some(ref methods) = meta.code_challenge_methods_supported {
if !methods.is_empty()
&& !methods.iter().any(|m| m.eq_ignore_ascii_case("S256"))
{
return Err(McpOAuthError::Discovery(
"authorization server does not advertise PKCE S256 support"
.to_string(),
));
}
}
return Ok(meta);
}
Err(e) => {
if metadata_err.is_none() {
metadata_err = Some(format!("invalid metadata JSON at {url}: {e}"));
}
}
}
}
Ok(resp) => {
last_err = Some(format!("{url} returned HTTP {}", resp.status()));
}
Err(ureq::Error::Status(code, _)) => {
last_err = Some(format!("{url} returned HTTP {code}"));
}
Err(ureq::Error::Transport(t)) => {
last_err = Some(format!("failed to reach {url}: {t}"));
}
}
}
Err(McpOAuthError::Discovery(
metadata_err.or(last_err).unwrap_or_else(|| {
format!("could not discover OAuth authorization server metadata for {auth_server_url}")
}),
))
}
fn obtain_client_and_listener(
agent: &ureq::Agent,
auth_meta: &AuthorizationServerMetadata,
cached: Option<&StoredServerAuth>,
) -> Result<(TcpListener, String, String, Option<String>), McpOAuthError> {
if let Some(entry) = cached {
if let Some(ref cid) = entry.client_id {
if let Some(ref cached_uri) = entry.redirect_uri {
if let Some(port) = extract_loopback_port(cached_uri) {
if let Ok(listener) = TcpListener::bind(("127.0.0.1", port)) {
return Ok((
listener,
cached_uri.clone(),
cid.clone(),
entry.client_secret.clone(),
));
}
}
}
if auth_meta.registration_endpoint.is_none() {
let listener = bind_loopback_ephemeral()?;
let port = listener
.local_addr()
.map_err(|e| McpOAuthError::Io(e.to_string()))?
.port();
let redirect_uri = format!("http://127.0.0.1:{port}/callback");
return Ok((
listener,
redirect_uri,
cid.clone(),
entry.client_secret.clone(),
));
}
}
}
let listener = bind_loopback_ephemeral()?;
let port = listener
.local_addr()
.map_err(|e| McpOAuthError::Io(e.to_string()))?
.port();
let redirect_uri = format!("http://127.0.0.1:{port}/callback");
let Some(ref reg_endpoint) = auth_meta.registration_endpoint else {
return Err(McpOAuthError::Registration(
"authorization server does not support Dynamic Client Registration and no client_id is cached"
.to_string(),
));
};
let reg = register_dynamic_client(agent, reg_endpoint, &redirect_uri)?;
Ok((listener, redirect_uri, reg.client_id, reg.client_secret))
}
fn bind_loopback_ephemeral() -> Result<TcpListener, McpOAuthError> {
TcpListener::bind(SocketAddr::from(([127, 0, 0, 1], 0)))
.map_err(|e| McpOAuthError::Io(format!("cannot bind loopback callback listener: {e}")))
}
fn extract_loopback_port(uri: &str) -> Option<u16> {
let rest = uri.strip_prefix("http://127.0.0.1:")?;
let port_str = rest.split('/').next()?;
port_str.parse::<u16>().ok().filter(|&p| p > 0)
}
fn register_dynamic_client(
agent: &ureq::Agent,
registration_endpoint: &str,
redirect_uri: &str,
) -> Result<ClientRegistrationResponse, McpOAuthError> {
let payload = serde_json::json!({
"client_name": "blyte",
"redirect_uris": [redirect_uri],
"grant_types": ["authorization_code", "refresh_token"],
"response_types": ["code"],
"token_endpoint_auth_method": "none",
});
match agent
.post(registration_endpoint)
.set("Accept", "application/json")
.send_json(payload)
{
Ok(resp) if (200..300).contains(&resp.status()) => {
let parsed: ClientRegistrationResponse = resp.into_json().map_err(|e| {
McpOAuthError::Registration(format!("invalid client registration response: {e}"))
})?;
if parsed.client_id.trim().is_empty() {
return Err(McpOAuthError::Registration(
"registration response returned empty client_id".to_string(),
));
}
Ok(parsed)
}
Ok(resp) => Err(McpOAuthError::Registration(format!(
"registration endpoint returned HTTP {}",
resp.status()
))),
Err(ureq::Error::Status(code, resp)) => {
let detail = extract_oauth_error_detail(resp);
Err(McpOAuthError::Registration(format!("HTTP {code}{detail}")))
}
Err(ureq::Error::Transport(t)) => Err(McpOAuthError::Registration(format!(
"cannot reach registration endpoint: {t}"
))),
}
}
#[allow(clippy::too_many_arguments)]
fn exchange_authorization_code(
agent: &ureq::Agent,
token_endpoint: &str,
code: &str,
redirect_uri: &str,
client_id: &str,
client_secret: Option<&str>,
code_verifier: &str,
resource: Option<&str>,
) -> Result<TokenEndpointResponse, McpOAuthError> {
let mut form: Vec<(&str, &str)> = vec![
("grant_type", "authorization_code"),
("code", code),
("redirect_uri", redirect_uri),
("client_id", client_id),
("code_verifier", code_verifier),
];
if let Some(res) = resource {
form.push(("resource", res));
}
if let Some(secret) = client_secret {
form.push(("client_secret", secret));
}
post_token_form(agent, token_endpoint, &form)
}
fn post_token_form(
agent: &ureq::Agent,
token_endpoint: &str,
form: &[(&str, &str)],
) -> Result<TokenEndpointResponse, McpOAuthError> {
match agent
.post(token_endpoint)
.set("Accept", "application/json")
.send_form(form)
{
Ok(resp) if (200..300).contains(&resp.status()) => {
let parsed: TokenEndpointResponse = resp.into_json().map_err(|e| {
McpOAuthError::TokenExchange(format!("invalid token response JSON: {e}"))
})?;
if parsed.access_token.is_empty() {
return Err(McpOAuthError::TokenExchange(
"token endpoint returned empty access_token".to_string(),
));
}
Ok(parsed)
}
Ok(resp) => Err(McpOAuthError::TokenExchange(format!(
"token endpoint returned HTTP {}",
resp.status()
))),
Err(ureq::Error::Status(code, resp)) => {
let detail = extract_oauth_error_detail(resp);
Err(McpOAuthError::TokenExchange(format!("HTTP {code}{detail}")))
}
Err(ureq::Error::Transport(t)) => Err(McpOAuthError::TokenExchange(format!(
"cannot reach token endpoint: {t}"
))),
}
}
fn extract_oauth_error_detail(resp: ureq::Response) -> String {
let Ok(body) = resp.into_string() else {
return String::new();
};
if let Ok(parsed) = serde_json::from_str::<OAuthErrorResponse>(&body) {
if let Some(err) = parsed.error {
if let Some(desc) = parsed.error_description {
return format!(" ({err}: {desc})");
}
return format!(" ({err})");
}
}
String::new()
}
struct LoopbackCallback {
stream: TcpStream,
params: BTreeMap<String, String>,
}
fn wait_for_loopback_callback(
listener: &TcpListener,
timeout: Duration,
) -> Result<LoopbackCallback, McpOAuthError> {
listener
.set_nonblocking(true)
.map_err(|e| McpOAuthError::Io(format!("cannot configure callback listener: {e}")))?;
let deadline = Instant::now() + timeout;
loop {
match listener.accept() {
Ok((mut stream, _)) => {
let _ = stream.set_nonblocking(false);
let _ = stream.set_read_timeout(Some(Duration::from_secs(5)));
let _ = stream.set_write_timeout(Some(Duration::from_secs(5)));
let Some((path, query)) = read_http_request_target(&mut stream) else {
continue;
};
if path != "/callback" {
let _ = send_html_response(
&mut stream,
"404 Not Found",
"Not found",
"Waiting for OAuth callback on /callback.",
);
continue;
}
let params = parse_query_params(&query);
return Ok(LoopbackCallback { stream, params });
}
Err(e) if e.kind() == std::io::ErrorKind::WouldBlock => {
if Instant::now() >= deadline {
return Err(McpOAuthError::Timeout(
"timed out waiting for OAuth browser callback".to_string(),
));
}
std::thread::sleep(Duration::from_millis(25));
}
Err(e) => {
return Err(McpOAuthError::Callback(format!(
"callback listener accept error: {e}"
)));
}
}
}
}
const MAX_CALLBACK_REQUEST_BYTES: usize = 64 * 1024;
fn read_http_request_target(stream: &mut TcpStream) -> Option<(String, String)> {
let mut buf = Vec::with_capacity(4096);
let mut chunk = [0u8; 4096];
let mut found_header_end = false;
while buf.len() < MAX_CALLBACK_REQUEST_BYTES {
let remaining = MAX_CALLBACK_REQUEST_BYTES - buf.len();
let to_read = remaining.min(chunk.len());
let n = stream.read(&mut chunk[..to_read]).ok()?;
if n == 0 {
break;
}
buf.extend_from_slice(&chunk[..n]);
if buf.windows(4).any(|w| w == b"\r\n\r\n") {
found_header_end = true;
break;
}
}
if !found_header_end {
return None;
}
let line_end = buf.windows(2).position(|w| w == b"\r\n")?;
let request_line = std::str::from_utf8(&buf[..line_end]).ok()?;
let mut parts = request_line.split_whitespace();
let method = parts.next()?;
if method != "GET" {
return None;
}
let target = parts.next()?;
match target.split_once('?') {
Some((path, query)) => Some((path.to_string(), query.to_string())),
None => Some((target.to_string(), String::new())),
}
}
fn send_html_response(
stream: &mut TcpStream,
status: &str,
title: &str,
message_html: &str,
) -> std::io::Result<()> {
let body = format!(
"<!doctype html><html lang=\"en\"><head><meta charset=\"utf-8\"><title>{title} — blyte</title><style>body{{font-family:-apple-system,BlinkMacSystemFont,sans-serif;max-width:460px;margin:12vh auto;padding:0 20px;color:#111;line-height:1.5}}h1{{font-size:1.3rem;margin-bottom:0.5rem}}</style></head><body><h1>{title}</h1><p>{message_html}</p></body></html>"
);
let response = format!(
"HTTP/1.1 {status}\r\nContent-Type: text/html; charset=utf-8\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}",
body.len()
);
stream.write_all(response.as_bytes())?;
stream.flush()
}
fn escape_html(input: &str) -> String {
let mut out = String::with_capacity(input.len());
for ch in input.chars() {
match ch {
'&' => out.push_str("&"),
'<' => out.push_str("<"),
'>' => out.push_str(">"),
'"' => out.push_str("""),
'\'' => out.push_str("'"),
_ => out.push(ch),
}
}
out
}
pub fn parse_url_parts(url: &str) -> Result<(String, String), McpOAuthError> {
let Some(scheme_end) = url.find("://") else {
return Err(McpOAuthError::Discovery(format!(
"invalid URL (missing scheme): {url}"
)));
};
let rest_start = scheme_end + 3;
let rest = &url[rest_start..];
let authority_end = rest
.find(['/', '?', '#'])
.map(|idx| rest_start + idx)
.unwrap_or(url.len());
if authority_end == rest_start {
return Err(McpOAuthError::Discovery(format!(
"invalid URL (missing host): {url}"
)));
}
let origin = url[..authority_end].to_string();
let after_origin = &url[authority_end..];
let path_raw = after_origin
.split(['?', '#'])
.next()
.unwrap_or_default()
.trim_end_matches('/');
let path = if path_raw.is_empty() || path_raw == "/" {
String::new()
} else {
path_raw.to_string()
};
Ok((origin, path))
}
fn append_query_params(base_url: &str, params: &[(&str, &str)]) -> String {
let mut out = base_url.to_string();
let mut sep = if base_url.contains('?') { '&' } else { '?' };
for (k, v) in params {
out.push(sep);
sep = '&';
out.push_str(&percent_encode(k));
out.push('=');
out.push_str(&percent_encode(v));
}
out
}
fn percent_encode(input: &str) -> String {
let mut out = String::with_capacity(input.len());
for b in input.bytes() {
if b.is_ascii_alphanumeric() || matches!(b, b'-' | b'.' | b'_' | b'~') {
out.push(b as char);
} else {
out.push_str(&format!("%{b:02X}"));
}
}
out
}
fn percent_decode(input: &str) -> String {
let bytes = input.as_bytes();
let mut out = Vec::with_capacity(bytes.len());
let mut i = 0;
while i < bytes.len() {
if bytes[i] == b'%' && i + 2 < bytes.len() {
if let Ok(hex) = std::str::from_utf8(&bytes[i + 1..i + 3]) {
if let Ok(val) = u8::from_str_radix(hex, 16) {
out.push(val);
i += 3;
continue;
}
}
}
if bytes[i] == b'+' {
out.push(b' ');
} else {
out.push(bytes[i]);
}
i += 1;
}
String::from_utf8_lossy(&out).into_owned()
}
pub fn parse_query_params(query: &str) -> BTreeMap<String, String> {
let mut map = BTreeMap::new();
for pair in query.split('&') {
if pair.is_empty() {
continue;
}
let (k, v) = match pair.split_once('=') {
Some((k, v)) => (percent_decode(k), percent_decode(v)),
None => (percent_decode(pair), String::new()),
};
map.insert(k, v);
}
map
}
fn resolve_authorization_server_url(
server_url: &str,
resource_meta: Option<&ProtectedResourceMetadata>,
) -> Result<String, McpOAuthError> {
let meta = resource_meta.ok_or_else(|| {
McpOAuthError::Discovery(format!(
"could not discover OAuth protected resource metadata for {server_url}"
))
})?;
meta.authorization_servers
.first()
.filter(|s| !s.trim().is_empty())
.cloned()
.ok_or_else(|| {
McpOAuthError::Discovery(format!(
"OAuth protected resource metadata for {server_url} is missing authorization_servers"
))
})
}
fn system_time_secs(now: SystemTime) -> Result<u64, McpOAuthError> {
now.duration_since(UNIX_EPOCH)
.map(|d| d.as_secs())
.map_err(|e| McpOAuthError::Io(format!("system clock is before UNIX_EPOCH: {e}")))
}
fn system_time_nanos(now: SystemTime) -> Result<u128, McpOAuthError> {
now.duration_since(UNIX_EPOCH)
.map(|d| d.as_nanos())
.map_err(|e| McpOAuthError::Io(format!("system clock is before UNIX_EPOCH: {e}")))
}
fn now_unix_secs() -> Result<u64, McpOAuthError> {
system_time_secs(SystemTime::now())
}
fn now_unix_nanos() -> Result<u128, McpOAuthError> {
system_time_nanos(SystemTime::now())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn system_time_before_unix_epoch_returns_error() {
let before_epoch = UNIX_EPOCH - Duration::from_secs(5);
let secs_err = system_time_secs(before_epoch).unwrap_err().to_string();
assert!(
secs_err.contains("UNIX_EPOCH"),
"expected UNIX_EPOCH in error, got: {secs_err}"
);
let nanos_err = system_time_nanos(before_epoch).unwrap_err().to_string();
assert!(
nanos_err.contains("UNIX_EPOCH"),
"expected UNIX_EPOCH in error, got: {nanos_err}"
);
}
#[test]
fn auth_store_save_rejects_missing_parent_or_invalid_file_name() {
let store = McpAuthStore::default();
let err_root = store.save(Path::new("/")).unwrap_err().to_string();
assert!(
err_root.contains("no parent directory"),
"expected missing parent directory error, got: {err_root}"
);
let err_empty = store.save(Path::new("")).unwrap_err().to_string();
assert!(
err_empty.contains("no parent directory"),
"expected missing parent directory error, got: {err_empty}"
);
let err_dotdot = store.save(Path::new("/tmp/..")).unwrap_err().to_string();
assert!(
err_dotdot.contains("missing or non-UTF-8 file name"),
"expected missing file name error, got: {err_dotdot}"
);
#[cfg(unix)]
{
use std::ffi::OsStr;
use std::os::unix::ffi::OsStrExt;
let non_utf8 = Path::new("/tmp").join(OsStr::from_bytes(b"mcp-auth-\xff.json"));
let err_utf8 = store.save(&non_utf8).unwrap_err().to_string();
assert!(
err_utf8.contains("missing or non-UTF-8 file name"),
"expected non-UTF-8 file name error, got: {err_utf8}"
);
}
}
#[test]
fn resolve_authorization_server_url_errors_when_metadata_or_servers_missing() {
let err_none = resolve_authorization_server_url("https://mcp.example.com/mcp", None)
.unwrap_err()
.to_string();
assert!(
err_none.contains("protected resource metadata"),
"expected protected resource metadata error, got: {err_none}"
);
let empty_meta = ProtectedResourceMetadata {
resource: Some("https://mcp.example.com/mcp".to_string()),
authorization_servers: Vec::new(),
scopes_supported: None,
};
let err_empty =
resolve_authorization_server_url("https://mcp.example.com/mcp", Some(&empty_meta))
.unwrap_err()
.to_string();
assert!(
err_empty.contains("authorization_servers"),
"expected authorization_servers error, got: {err_empty}"
);
}
#[test]
fn concurrent_auth_store_modifications_preserve_all_servers() {
let td = tempfile::tempdir().unwrap();
let store_path = td.path().join("mcp-auth.json");
let thread_count = 8usize;
let mut handles = Vec::new();
for idx in 0..thread_count {
let path = store_path.clone();
handles.push(std::thread::spawn(move || {
let server = format!("server-{idx}");
for round in 0..5 {
McpAuthStore::modify(&path, |store| {
store.upsert(
&server,
StoredServerAuth {
server_url: format!("https://{server}.example/mcp"),
access_token: Some(format!("tok-{idx}-{round}")),
refresh_token: Some(format!("ref-{idx}-{round}")),
..StoredServerAuth::default()
},
);
Ok((true, ()))
})
.unwrap();
}
}));
}
for h in handles {
h.join().unwrap();
}
let final_store = McpAuthStore::load(&store_path).unwrap();
assert_eq!(final_store.servers.len(), thread_count);
for idx in 0..thread_count {
let server = format!("server-{idx}");
let entry = final_store.get(&server).expect("server entry must exist");
assert_eq!(
entry.access_token.as_deref(),
Some(format!("tok-{idx}-4").as_str())
);
assert_eq!(
entry.refresh_token.as_deref(),
Some(format!("ref-{idx}-4").as_str())
);
}
}
#[test]
fn loopback_callback_reads_multipacket_headers_through_crlf_crlf_before_replying() {
let listener = TcpListener::bind("127.0.0.1:0").unwrap();
let addr = listener.local_addr().unwrap();
let server = std::thread::spawn(move || {
let mut cb = wait_for_loopback_callback(&listener, Duration::from_secs(5)).unwrap();
send_html_response(&mut cb.stream, "200 OK", "Done", "Authenticated").unwrap();
cb.params
});
let mut client = TcpStream::connect(addr).unwrap();
client.set_nodelay(true).unwrap();
client
.set_read_timeout(Some(Duration::from_millis(80)))
.unwrap();
client
.write_all(b"GET /callback?code=abc123&state=xyz789 HTTP/1.1\r\n")
.unwrap();
client.flush().unwrap();
let mut probe = [0u8; 32];
let early1 = client.read(&mut probe);
assert!(
matches!(
early1,
Err(ref e)
if e.kind() == std::io::ErrorKind::WouldBlock
|| e.kind() == std::io::ErrorKind::TimedOut
),
"server replied before end of HTTP headers after request line: {early1:?}"
);
client
.write_all(b"Host: 127.0.0.1\r\nUser-Agent: multi-packet-browser\r\n")
.unwrap();
client.flush().unwrap();
let early2 = client.read(&mut probe);
assert!(
matches!(
early2,
Err(ref e)
if e.kind() == std::io::ErrorKind::WouldBlock
|| e.kind() == std::io::ErrorKind::TimedOut
),
"server replied before trailing CRLF CRLF: {early2:?}"
);
client.write_all(b"Accept: text/html\r\n\r\n").unwrap();
client.flush().unwrap();
client
.set_read_timeout(Some(Duration::from_secs(5)))
.unwrap();
let mut response = String::new();
client.read_to_string(&mut response).unwrap();
assert!(
response.starts_with("HTTP/1.1 200 OK"),
"unexpected HTTP response: {response}"
);
assert!(response.contains("Done"));
let params = server.join().unwrap();
assert_eq!(params.get("code").map(String::as_str), Some("abc123"));
assert_eq!(params.get("state").map(String::as_str), Some("xyz789"));
}
#[test]
fn read_http_request_target_rejects_truncated_requests_on_eof() {
for truncated in [
&b"GET /callback?code=abc123&state=xyz789 HTTP/1.1"[..],
&b"GET /callback?code=abc123&state=xyz789 HTTP/1.1\r\nHost: 127.0.0.1\r\n"[..],
&b""[..],
] {
let listener = TcpListener::bind("127.0.0.1:0").unwrap();
let addr = listener.local_addr().unwrap();
let payload = truncated.to_vec();
let client_handle = std::thread::spawn(move || {
let mut client = TcpStream::connect(addr).unwrap();
client.write_all(&payload).unwrap();
client.flush().unwrap();
client.shutdown(std::net::Shutdown::Write).unwrap();
});
let (mut server_stream, _) = listener.accept().unwrap();
server_stream
.set_read_timeout(Some(Duration::from_secs(2)))
.unwrap();
assert_eq!(read_http_request_target(&mut server_stream), None);
client_handle.join().unwrap();
}
}
#[test]
fn loopback_callback_ignores_truncated_request_and_accepts_complete_request() {
let listener = TcpListener::bind("127.0.0.1:0").unwrap();
let addr = listener.local_addr().unwrap();
let server = std::thread::spawn(move || {
let mut cb = wait_for_loopback_callback(&listener, Duration::from_secs(5)).unwrap();
send_html_response(&mut cb.stream, "200 OK", "Done", "Authenticated").unwrap();
cb.params
});
{
let mut truncated = TcpStream::connect(addr).unwrap();
truncated
.set_read_timeout(Some(Duration::from_secs(2)))
.unwrap();
truncated
.write_all(b"GET /callback?code=bad&state=bad HTTP/1.1")
.unwrap();
truncated.flush().unwrap();
truncated.shutdown(std::net::Shutdown::Write).unwrap();
let mut resp = Vec::new();
truncated.read_to_end(&mut resp).unwrap();
assert!(resp.is_empty());
}
let mut valid = TcpStream::connect(addr).unwrap();
valid
.write_all(b"GET /callback?code=good&state=ok HTTP/1.1\r\nHost: 127.0.0.1\r\n\r\n")
.unwrap();
valid.flush().unwrap();
let mut response = String::new();
valid.read_to_string(&mut response).unwrap();
assert!(response.starts_with("HTTP/1.1 200 OK"));
let params = server.join().unwrap();
assert_eq!(params.get("code").map(String::as_str), Some("good"));
assert_eq!(params.get("state").map(String::as_str), Some("ok"));
}
#[test]
fn discover_authorization_server_rejects_missing_or_empty_issuer() {
for body_fn in [
|base: &str| {
serde_json::json!({
"authorization_endpoint": format!("{base}/authorize"),
"token_endpoint": format!("{base}/token"),
"code_challenge_methods_supported": ["S256"]
})
.to_string()
},
|base: &str| {
serde_json::json!({
"issuer": " ",
"authorization_endpoint": format!("{base}/authorize"),
"token_endpoint": format!("{base}/token"),
"code_challenge_methods_supported": ["S256"]
})
.to_string()
},
] {
let listener = TcpListener::bind("127.0.0.1:0").unwrap();
let addr = listener.local_addr().unwrap();
let base = format!("http://{addr}");
let payload = body_fn(&base);
let stop = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));
let stop_flag = std::sync::Arc::clone(&stop);
listener.set_nonblocking(true).unwrap();
let handle = std::thread::spawn(move || {
while !stop_flag.load(std::sync::atomic::Ordering::SeqCst) {
match listener.accept() {
Ok((mut stream, _)) => {
let _ = stream.set_read_timeout(Some(Duration::from_secs(1)));
let mut buf = [0u8; 4096];
let n = stream.read(&mut buf).unwrap_or(0);
let req = String::from_utf8_lossy(&buf[..n]);
let path = req
.lines()
.next()
.and_then(|l| l.split_whitespace().nth(1))
.unwrap_or("");
let resp = if path == "/.well-known/oauth-authorization-server" {
format!(
"HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}",
payload.len(),
payload
)
} else {
"HTTP/1.1 404 Not Found\r\nContent-Length: 0\r\nConnection: close\r\n\r\n"
.to_string()
};
let _ = stream.write_all(resp.as_bytes());
let _ = stream.flush();
}
Err(e) if e.kind() == std::io::ErrorKind::WouldBlock => {
std::thread::sleep(Duration::from_millis(5));
}
Err(_) => break,
}
}
});
let agent = build_http_agent(Duration::from_secs(2));
let err = discover_authorization_server(&agent, &base)
.expect_err("metadata missing required issuer must fail")
.to_string();
stop.store(true, std::sync::atomic::Ordering::SeqCst);
let _ = handle.join();
assert!(
err.contains("issuer"),
"expected clear error mentioning missing issuer, got: {err}"
);
}
}
}