Skip to main content

blyte_cli/mcp/
oauth.rs

1use std::collections::BTreeMap;
2use std::fmt;
3use std::io::{Read, Write};
4use std::net::{SocketAddr, TcpListener, TcpStream};
5use std::path::{Path, PathBuf};
6use std::sync::atomic::{AtomicU64, Ordering};
7use std::sync::{Mutex, OnceLock};
8use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
9
10use serde::{Deserialize, Serialize};
11use sha2::{Digest, Sha256};
12
13use super::config::user_config_dir;
14
15pub const DEFAULT_EXPIRY_MARGIN_SECS: u64 = 60;
16pub const DEFAULT_OAUTH_HTTP_TIMEOUT: Duration = Duration::from_secs(30);
17pub const DEFAULT_CALLBACK_TIMEOUT: Duration = Duration::from_secs(300);
18
19#[derive(Debug)]
20pub enum McpOAuthError {
21    Config(String),
22    Discovery(String),
23    Registration(String),
24    Callback(String),
25    StateMismatch,
26    AuthDenied(String),
27    TokenExchange(String),
28    RefreshFailed(String),
29    Timeout(String),
30    Io(String),
31}
32
33impl fmt::Display for McpOAuthError {
34    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
35        match self {
36            McpOAuthError::Config(msg) => write!(f, "MCP OAuth configuration error: {msg}"),
37            McpOAuthError::Discovery(msg) => write!(f, "MCP OAuth discovery failed: {msg}"),
38            McpOAuthError::Registration(msg) => {
39                write!(f, "MCP OAuth client registration failed: {msg}")
40            }
41            McpOAuthError::Callback(msg) => write!(f, "MCP OAuth callback error: {msg}"),
42            McpOAuthError::StateMismatch => {
43                write!(f, "MCP OAuth callback state mismatch")
44            }
45            McpOAuthError::AuthDenied(msg) => write!(f, "MCP OAuth authorization denied: {msg}"),
46            McpOAuthError::TokenExchange(msg) => {
47                write!(f, "MCP OAuth token exchange failed: {msg}")
48            }
49            McpOAuthError::RefreshFailed(msg) => {
50                write!(f, "MCP OAuth token refresh failed: {msg}")
51            }
52            McpOAuthError::Timeout(msg) => write!(f, "MCP OAuth timed out: {msg}"),
53            McpOAuthError::Io(msg) => write!(f, "MCP OAuth I/O error: {msg}"),
54        }
55    }
56}
57
58impl std::error::Error for McpOAuthError {}
59
60#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Default)]
61pub struct StoredServerAuth {
62    pub server_url: String,
63    #[serde(default, skip_serializing_if = "Option::is_none")]
64    pub authorization_server: Option<String>,
65    #[serde(default, skip_serializing_if = "Option::is_none")]
66    pub token_endpoint: Option<String>,
67    #[serde(default, skip_serializing_if = "Option::is_none")]
68    pub client_id: Option<String>,
69    #[serde(default, skip_serializing_if = "Option::is_none")]
70    pub client_secret: Option<String>,
71    #[serde(default, skip_serializing_if = "Option::is_none")]
72    pub redirect_uri: Option<String>,
73    #[serde(default, skip_serializing_if = "Option::is_none")]
74    pub access_token: Option<String>,
75    #[serde(default, skip_serializing_if = "Option::is_none")]
76    pub refresh_token: Option<String>,
77    #[serde(default, skip_serializing_if = "Option::is_none")]
78    pub token_type: Option<String>,
79    #[serde(default, skip_serializing_if = "Option::is_none")]
80    pub scope: Option<String>,
81    #[serde(default, skip_serializing_if = "Option::is_none")]
82    pub expires_at: Option<u64>,
83}
84
85impl StoredServerAuth {
86    pub fn is_expired_or_near_expiry(&self, now_secs: u64, margin_secs: u64) -> bool {
87        self.expires_at
88            .is_some_and(|exp| now_secs.saturating_add(margin_secs) >= exp)
89    }
90}
91
92#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Default)]
93pub struct McpAuthStore {
94    #[serde(default)]
95    pub servers: BTreeMap<String, StoredServerAuth>,
96}
97
98impl McpAuthStore {
99    pub fn default_path() -> Result<PathBuf, McpOAuthError> {
100        let dir = user_config_dir().map_err(|e| McpOAuthError::Config(e.to_string()))?;
101        Ok(dir.join("mcp-auth.json"))
102    }
103
104    pub fn load(path: &Path) -> Result<Self, McpOAuthError> {
105        match std::fs::read_to_string(path) {
106            Ok(text) => {
107                if text.trim().is_empty() {
108                    return Ok(Self::default());
109                }
110                serde_json::from_str(&text).map_err(|e| {
111                    McpOAuthError::Config(format!("invalid MCP auth store {}: {e}", path.display()))
112                })
113            }
114            Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(Self::default()),
115            Err(e) => Err(McpOAuthError::Io(format!(
116                "cannot read {}: {e}",
117                path.display()
118            ))),
119        }
120    }
121
122    pub fn save(&self, path: &Path) -> Result<(), McpOAuthError> {
123        let (parent, file_name) = auth_store_path_parts(path)?;
124        if !parent.as_os_str().is_empty() {
125            std::fs::create_dir_all(parent).map_err(|e| {
126                McpOAuthError::Io(format!("cannot create {}: {e}", parent.display()))
127            })?;
128            set_dir_permissions_0700(parent)?;
129        }
130        let body = serde_json::to_string_pretty(self)
131            .map_err(|e| McpOAuthError::Config(format!("cannot serialize MCP auth store: {e}")))?;
132        let pid = std::process::id();
133        let nanos = now_unix_nanos()?;
134        static SAVE_SEQ: AtomicU64 = AtomicU64::new(0);
135        let seq = SAVE_SEQ.fetch_add(1, Ordering::Relaxed);
136        let tmp_name = format!(".{file_name}.tmp.{pid}.{nanos}.{seq}");
137        let tmp_path = parent.join(tmp_name);
138        write_file_0600(&tmp_path, format!("{body}\n").as_bytes())?;
139        if let Err(e) = std::fs::rename(&tmp_path, path) {
140            let _ = std::fs::remove_file(&tmp_path);
141            return Err(McpOAuthError::Io(format!(
142                "cannot persist {}: {e}",
143                path.display()
144            )));
145        }
146        set_file_permissions_0600(path)?;
147        Ok(())
148    }
149
150    pub fn modify<T, F>(path: &Path, f: F) -> Result<T, McpOAuthError>
151    where
152        F: FnOnce(&mut Self) -> Result<(bool, T), McpOAuthError>,
153    {
154        with_auth_store_lock(path, || {
155            let mut store = Self::load(path)?;
156            let (dirty, out) = f(&mut store)?;
157            if dirty {
158                store.save(path)?;
159            }
160            Ok(out)
161        })
162    }
163
164    pub fn get(&self, server_name: &str) -> Option<&StoredServerAuth> {
165        self.servers.get(server_name)
166    }
167
168    pub fn upsert(&mut self, server_name: &str, auth: StoredServerAuth) {
169        self.servers.insert(server_name.to_string(), auth);
170    }
171
172    pub fn remove(&mut self, server_name: &str) -> bool {
173        self.servers.remove(server_name).is_some()
174    }
175
176    pub fn secret_pairs(&self) -> Vec<(String, String)> {
177        let mut pairs = Vec::new();
178        for (name, auth) in &self.servers {
179            if let Some(ref token) = auth.access_token {
180                if !token.is_empty() {
181                    pairs.push((format!("MCP_ACCESS_TOKEN_{name}"), token.clone()));
182                }
183            }
184            if let Some(ref token) = auth.refresh_token {
185                if !token.is_empty() {
186                    pairs.push((format!("MCP_REFRESH_TOKEN_{name}"), token.clone()));
187                }
188            }
189            if let Some(ref secret) = auth.client_secret {
190                if !secret.is_empty() {
191                    pairs.push((format!("MCP_CLIENT_SECRET_{name}"), secret.clone()));
192                }
193            }
194        }
195        pairs
196    }
197}
198
199fn auth_store_path_parts(path: &Path) -> Result<(&Path, &str), McpOAuthError> {
200    let parent = path.parent().ok_or_else(|| {
201        McpOAuthError::Config(format!(
202            "MCP auth store path '{}' has no parent directory",
203            path.display()
204        ))
205    })?;
206    let file_name = path.file_name().and_then(|n| n.to_str()).ok_or_else(|| {
207        McpOAuthError::Config(format!(
208            "MCP auth store path '{}' has missing or non-UTF-8 file name",
209            path.display()
210        ))
211    })?;
212    Ok((parent, file_name))
213}
214
215fn auth_store_mutex() -> &'static Mutex<()> {
216    static LOCK: OnceLock<Mutex<()>> = OnceLock::new();
217    LOCK.get_or_init(|| Mutex::new(()))
218}
219
220#[cfg(unix)]
221struct AuthStoreFileLock {
222    file: std::fs::File,
223}
224
225#[cfg(unix)]
226impl AuthStoreFileLock {
227    fn acquire(path: &Path) -> Result<Self, McpOAuthError> {
228        use std::os::unix::fs::OpenOptionsExt;
229        use std::os::unix::io::AsRawFd;
230        let (parent, file_name) = auth_store_path_parts(path)?;
231        if !parent.as_os_str().is_empty() {
232            std::fs::create_dir_all(parent).map_err(|e| {
233                McpOAuthError::Io(format!("cannot create {}: {e}", parent.display()))
234            })?;
235            set_dir_permissions_0700(parent)?;
236        }
237        let lock_path = parent.join(format!(".{file_name}.lock"));
238        let file = std::fs::OpenOptions::new()
239            .create(true)
240            .truncate(false)
241            .read(true)
242            .write(true)
243            .mode(0o600)
244            .open(&lock_path)
245            .map_err(|e| {
246                McpOAuthError::Io(format!(
247                    "cannot open lock file {}: {e}",
248                    lock_path.display()
249                ))
250            })?;
251        set_file_permissions_0600(&lock_path)?;
252        let fd = file.as_raw_fd();
253        loop {
254            let rc = unsafe { libc::flock(fd, libc::LOCK_EX) };
255            if rc == 0 {
256                return Ok(Self { file });
257            }
258            let err = std::io::Error::last_os_error();
259            if err.kind() == std::io::ErrorKind::Interrupted {
260                continue;
261            }
262            return Err(McpOAuthError::Io(format!(
263                "cannot lock {}: {err}",
264                lock_path.display()
265            )));
266        }
267    }
268}
269
270#[cfg(unix)]
271impl Drop for AuthStoreFileLock {
272    fn drop(&mut self) {
273        use std::os::unix::io::AsRawFd;
274        let _ = unsafe { libc::flock(self.file.as_raw_fd(), libc::LOCK_UN) };
275    }
276}
277
278fn with_auth_store_lock<T, F>(path: &Path, f: F) -> Result<T, McpOAuthError>
279where
280    F: FnOnce() -> Result<T, McpOAuthError>,
281{
282    let _in_process = auth_store_mutex()
283        .lock()
284        .map_err(|_| McpOAuthError::Io("MCP auth store lock is poisoned".to_string()))?;
285    #[cfg(unix)]
286    let _file_lock = AuthStoreFileLock::acquire(path)?;
287    #[cfg(not(unix))]
288    let _ = auth_store_path_parts(path)?;
289    f()
290}
291
292#[cfg(unix)]
293fn set_dir_permissions_0700(path: &Path) -> Result<(), McpOAuthError> {
294    use std::os::unix::fs::PermissionsExt;
295    let perms = std::fs::Permissions::from_mode(0o700);
296    std::fs::set_permissions(path, perms)
297        .map_err(|e| McpOAuthError::Io(format!("cannot chmod 0700 {}: {e}", path.display())))
298}
299
300#[cfg(not(unix))]
301fn set_dir_permissions_0700(_path: &Path) -> Result<(), McpOAuthError> {
302    Ok(())
303}
304
305#[cfg(unix)]
306fn set_file_permissions_0600(path: &Path) -> Result<(), McpOAuthError> {
307    use std::os::unix::fs::PermissionsExt;
308    let perms = std::fs::Permissions::from_mode(0o600);
309    std::fs::set_permissions(path, perms)
310        .map_err(|e| McpOAuthError::Io(format!("cannot chmod 0600 {}: {e}", path.display())))
311}
312
313#[cfg(not(unix))]
314fn set_file_permissions_0600(_path: &Path) -> Result<(), McpOAuthError> {
315    Ok(())
316}
317
318#[cfg(unix)]
319fn write_file_0600(path: &Path, data: &[u8]) -> Result<(), McpOAuthError> {
320    use std::os::unix::fs::OpenOptionsExt;
321    let mut file = std::fs::OpenOptions::new()
322        .create(true)
323        .write(true)
324        .truncate(true)
325        .mode(0o600)
326        .open(path)
327        .map_err(|e| McpOAuthError::Io(format!("cannot create {}: {e}", path.display())))?;
328    file.write_all(data)
329        .map_err(|e| McpOAuthError::Io(format!("cannot write {}: {e}", path.display())))?;
330    file.flush()
331        .map_err(|e| McpOAuthError::Io(format!("cannot flush {}: {e}", path.display())))?;
332    set_file_permissions_0600(path)?;
333    Ok(())
334}
335
336#[cfg(not(unix))]
337fn write_file_0600(path: &Path, data: &[u8]) -> Result<(), McpOAuthError> {
338    std::fs::write(path, data)
339        .map_err(|e| McpOAuthError::Io(format!("cannot write {}: {e}", path.display())))
340}
341
342#[derive(Debug, Clone, Deserialize, Serialize)]
343pub struct ProtectedResourceMetadata {
344    #[serde(default)]
345    pub resource: Option<String>,
346    #[serde(default)]
347    pub authorization_servers: Vec<String>,
348    #[serde(default)]
349    pub scopes_supported: Option<Vec<String>>,
350}
351
352#[derive(Debug, Clone, Deserialize, Serialize)]
353pub struct AuthorizationServerMetadata {
354    #[serde(default)]
355    pub issuer: Option<String>,
356    pub authorization_endpoint: String,
357    pub token_endpoint: String,
358    #[serde(default)]
359    pub registration_endpoint: Option<String>,
360    #[serde(default)]
361    pub code_challenge_methods_supported: Option<Vec<String>>,
362    #[serde(default)]
363    pub scopes_supported: Option<Vec<String>>,
364}
365
366#[derive(Debug, Clone, Deserialize)]
367struct ClientRegistrationResponse {
368    client_id: String,
369    #[serde(default)]
370    client_secret: Option<String>,
371}
372
373#[derive(Debug, Clone, Deserialize)]
374struct TokenEndpointResponse {
375    access_token: String,
376    #[serde(default)]
377    token_type: Option<String>,
378    #[serde(default)]
379    expires_in: Option<u64>,
380    #[serde(default)]
381    refresh_token: Option<String>,
382    #[serde(default)]
383    scope: Option<String>,
384}
385
386#[derive(Debug, Clone, Deserialize)]
387struct OAuthErrorResponse {
388    #[serde(default)]
389    error: Option<String>,
390    #[serde(default)]
391    error_description: Option<String>,
392}
393
394pub struct PendingOAuthFlow {
395    authorize_url: String,
396    redirect_uri: String,
397    state: String,
398    code_verifier: String,
399    client_id: String,
400    client_secret: Option<String>,
401    token_endpoint: String,
402    authorization_server: String,
403    resource: Option<String>,
404    server_name: String,
405    server_url: String,
406    auth_store_path: PathBuf,
407    listener: TcpListener,
408    http_timeout: Duration,
409}
410
411impl PendingOAuthFlow {
412    pub fn authorize_url(&self) -> &str {
413        &self.authorize_url
414    }
415
416    pub fn redirect_uri(&self) -> &str {
417        &self.redirect_uri
418    }
419
420    pub fn state(&self) -> &str {
421        &self.state
422    }
423
424    pub fn client_id(&self) -> &str {
425        &self.client_id
426    }
427
428    pub fn complete(self, callback_timeout: Duration) -> Result<StoredServerAuth, McpOAuthError> {
429        let callback = wait_for_loopback_callback(&self.listener, callback_timeout)?;
430        let mut stream = callback.stream;
431        if let Some(err) = callback.params.get("error") {
432            let desc = callback
433                .params
434                .get("error_description")
435                .map(|d| format!("{err}: {d}"))
436                .unwrap_or_else(|| err.clone());
437            let _ = send_html_response(
438                &mut stream,
439                "400 Bad Request",
440                "Authentication failed",
441                &format!("Authorization was denied ({}).", escape_html(&desc)),
442            );
443            return Err(McpOAuthError::AuthDenied(desc));
444        }
445        let received_state = callback.params.get("state").map(String::as_str);
446        if received_state != Some(self.state.as_str()) {
447            let _ = send_html_response(
448                &mut stream,
449                "400 Bad Request",
450                "Authentication failed",
451                "The OAuth state parameter did not match. Please restart authentication from blyte.",
452            );
453            return Err(McpOAuthError::StateMismatch);
454        }
455        let Some(code) = callback
456            .params
457            .get("code")
458            .filter(|c| !c.is_empty())
459            .cloned()
460        else {
461            let _ = send_html_response(
462                &mut stream,
463                "400 Bad Request",
464                "Authentication failed",
465                "The authorization callback did not include an authorization code.",
466            );
467            return Err(McpOAuthError::Callback(
468                "callback missing authorization code".to_string(),
469            ));
470        };
471
472        let agent = build_http_agent(self.http_timeout);
473        let token_res = exchange_authorization_code(
474            &agent,
475            &self.token_endpoint,
476            &code,
477            &self.redirect_uri,
478            &self.client_id,
479            self.client_secret.as_deref(),
480            &self.code_verifier,
481            self.resource.as_deref(),
482        );
483        let token = match token_res {
484            Ok(t) => t,
485            Err(e) => {
486                let _ = send_html_response(
487                    &mut stream,
488                    "500 Internal Server Error",
489                    "Authentication failed",
490                    "Token exchange failed. Check blyte output for details.",
491                );
492                return Err(e);
493            }
494        };
495
496        let now = now_unix_secs()?;
497        let stored = StoredServerAuth {
498            server_url: self.server_url.clone(),
499            authorization_server: Some(self.authorization_server.clone()),
500            token_endpoint: Some(self.token_endpoint.clone()),
501            client_id: Some(self.client_id.clone()),
502            client_secret: self.client_secret.clone(),
503            redirect_uri: Some(self.redirect_uri.clone()),
504            access_token: Some(token.access_token),
505            refresh_token: token.refresh_token,
506            token_type: token.token_type.or_else(|| Some("Bearer".to_string())),
507            scope: token.scope,
508            expires_at: token.expires_in.map(|secs| now.saturating_add(secs)),
509        };
510
511        McpAuthStore::modify(&self.auth_store_path, |store| {
512            store.upsert(&self.server_name, stored.clone());
513            Ok((true, ()))
514        })?;
515
516        let _ = send_html_response(
517            &mut stream,
518            "200 OK",
519            "Authentication complete",
520            &format!(
521                "blyte is now authenticated with <strong>{}</strong>. You can close this tab and return to blyte.",
522                escape_html(&self.server_name)
523            ),
524        );
525
526        Ok(stored)
527    }
528}
529
530pub fn prepare_oauth_flow(
531    auth_store_path: &Path,
532    server_name: &str,
533    server_url: &str,
534    www_authenticate: Option<&str>,
535    http_timeout: Duration,
536) -> Result<PendingOAuthFlow, McpOAuthError> {
537    let agent = build_http_agent(http_timeout);
538    let (discovered_www_auth, resource_meta) =
539        discover_protected_resource(&agent, server_url, www_authenticate)?;
540
541    let auth_server_url = resolve_authorization_server_url(server_url, resource_meta.as_ref())?;
542
543    let auth_meta = discover_authorization_server(&agent, &auth_server_url)?;
544    let auth_server_id = auth_meta
545        .issuer
546        .as_deref()
547        .map(str::trim)
548        .filter(|s| !s.is_empty())
549        .map(str::to_string)
550        .ok_or_else(|| {
551            McpOAuthError::Discovery(format!(
552                "authorization server metadata for {auth_server_url} is missing required 'issuer' field"
553            ))
554        })?;
555
556    let store = McpAuthStore::load(auth_store_path)?;
557    let cached = store
558        .get(server_name)
559        .filter(|entry| {
560            entry.server_url == server_url
561                && entry
562                    .authorization_server
563                    .as_deref()
564                    .is_none_or(|issuer| issuer == auth_server_id)
565                && entry.client_id.is_some()
566        })
567        .cloned();
568
569    let (listener, redirect_uri, client_id, client_secret) =
570        obtain_client_and_listener(&agent, &auth_meta, cached.as_ref())?;
571
572    McpAuthStore::modify(auth_store_path, |store| {
573        let mut cached_entry = store
574            .get(server_name)
575            .filter(|entry| entry.server_url == server_url)
576            .cloned()
577            .unwrap_or_else(|| StoredServerAuth {
578                server_url: server_url.to_string(),
579                ..StoredServerAuth::default()
580            });
581        cached_entry.server_url = server_url.to_string();
582        cached_entry.authorization_server = Some(auth_server_id.clone());
583        cached_entry.token_endpoint = Some(auth_meta.token_endpoint.clone());
584        cached_entry.client_id = Some(client_id.clone());
585        cached_entry.client_secret = client_secret.clone();
586        cached_entry.redirect_uri = Some(redirect_uri.clone());
587        store.upsert(server_name, cached_entry);
588        Ok((true, ()))
589    })?;
590
591    let code_verifier = generate_code_verifier()?;
592    let code_challenge = compute_code_challenge_s256(&code_verifier);
593    let state = generate_state()?;
594    let resource = resource_meta
595        .as_ref()
596        .and_then(|m| m.resource.clone())
597        .or_else(|| Some(server_url.to_string()));
598
599    let scope = discovered_www_auth
600        .as_deref()
601        .and_then(|h| parse_www_authenticate_param(h, "scope"))
602        .or_else(|| {
603            resource_meta
604                .as_ref()
605                .and_then(|m| m.scopes_supported.as_ref())
606                .filter(|s| !s.is_empty())
607                .map(|s| s.join(" "))
608        });
609
610    let mut params: Vec<(&str, &str)> = vec![
611        ("response_type", "code"),
612        ("client_id", &client_id),
613        ("redirect_uri", &redirect_uri),
614        ("code_challenge", &code_challenge),
615        ("code_challenge_method", "S256"),
616        ("state", &state),
617    ];
618    if let Some(ref res) = resource {
619        params.push(("resource", res));
620    }
621    if let Some(ref sc) = scope {
622        params.push(("scope", sc));
623    }
624    let authorize_url = append_query_params(&auth_meta.authorization_endpoint, &params);
625
626    Ok(PendingOAuthFlow {
627        authorize_url,
628        redirect_uri,
629        state,
630        code_verifier,
631        client_id,
632        client_secret,
633        token_endpoint: auth_meta.token_endpoint,
634        authorization_server: auth_server_id,
635        resource,
636        server_name: server_name.to_string(),
637        server_url: server_url.to_string(),
638        auth_store_path: auth_store_path.to_path_buf(),
639        listener,
640        http_timeout,
641    })
642}
643
644pub fn refresh_access_token(
645    auth_store_path: &Path,
646    server_name: &str,
647    server_url: &str,
648    www_authenticate: Option<&str>,
649    http_timeout: Duration,
650) -> Result<StoredServerAuth, McpOAuthError> {
651    let store = McpAuthStore::load(auth_store_path)?;
652    let existing = store
653        .get(server_name)
654        .filter(|entry| entry.server_url == server_url)
655        .cloned()
656        .ok_or_else(|| {
657            McpOAuthError::RefreshFailed(format!(
658                "no stored OAuth credentials for MCP server '{server_name}'"
659            ))
660        })?;
661    let refresh_token = existing
662        .refresh_token
663        .clone()
664        .filter(|t| !t.is_empty())
665        .ok_or_else(|| {
666            McpOAuthError::RefreshFailed(format!(
667                "no refresh token stored for MCP server '{server_name}'"
668            ))
669        })?;
670
671    let agent = build_http_agent(http_timeout);
672    let token_endpoint = match existing.token_endpoint.clone() {
673        Some(ep) => ep,
674        None => {
675            let (_, resource_meta) =
676                discover_protected_resource(&agent, server_url, www_authenticate)?;
677            let auth_server_url =
678                resolve_authorization_server_url(server_url, resource_meta.as_ref())?;
679            let auth_meta = discover_authorization_server(&agent, &auth_server_url)?;
680            auth_meta.token_endpoint
681        }
682    };
683
684    let mut form: Vec<(&str, &str)> = vec![
685        ("grant_type", "refresh_token"),
686        ("refresh_token", &refresh_token),
687    ];
688    if let Some(ref cid) = existing.client_id {
689        form.push(("client_id", cid));
690    }
691    if let Some(ref secret) = existing.client_secret {
692        form.push(("client_secret", secret));
693    }
694
695    let token = post_token_form(&agent, &token_endpoint, &form)
696        .map_err(|e| McpOAuthError::RefreshFailed(e.to_string()))?;
697
698    let now = now_unix_secs()?;
699    let updated = StoredServerAuth {
700        server_url: existing.server_url,
701        authorization_server: existing.authorization_server,
702        token_endpoint: Some(token_endpoint),
703        client_id: existing.client_id,
704        client_secret: existing.client_secret,
705        redirect_uri: existing.redirect_uri,
706        access_token: Some(token.access_token),
707        refresh_token: token.refresh_token.or(Some(refresh_token)),
708        token_type: token.token_type.or(existing.token_type),
709        scope: token.scope.or(existing.scope),
710        expires_at: token.expires_in.map(|secs| now.saturating_add(secs)),
711    };
712
713    McpAuthStore::modify(auth_store_path, |store| {
714        store.upsert(server_name, updated.clone());
715        Ok((true, ()))
716    })?;
717    Ok(updated)
718}
719
720pub fn resolve_bearer_token(
721    auth_store_path: &Path,
722    server_name: &str,
723    server_url: &str,
724    http_timeout: Duration,
725) -> Result<Option<String>, McpOAuthError> {
726    resolve_bearer_token_at(
727        auth_store_path,
728        server_name,
729        server_url,
730        http_timeout,
731        now_unix_secs()?,
732    )
733}
734
735pub fn resolve_bearer_token_at(
736    auth_store_path: &Path,
737    server_name: &str,
738    server_url: &str,
739    http_timeout: Duration,
740    now_secs: u64,
741) -> Result<Option<String>, McpOAuthError> {
742    let store = McpAuthStore::load(auth_store_path)?;
743    let Some(entry) = store.get(server_name) else {
744        return Ok(None);
745    };
746    if entry.server_url != server_url {
747        return Ok(None);
748    }
749    if let Some(ref token) = entry.access_token {
750        if !token.is_empty()
751            && !entry.is_expired_or_near_expiry(now_secs, DEFAULT_EXPIRY_MARGIN_SECS)
752        {
753            return Ok(Some(token.clone()));
754        }
755    }
756    if entry
757        .refresh_token
758        .as_deref()
759        .is_some_and(|t| !t.is_empty())
760    {
761        match refresh_access_token(auth_store_path, server_name, server_url, None, http_timeout) {
762            Ok(refreshed) => return Ok(refreshed.access_token),
763            Err(_) => return Ok(None),
764        }
765    }
766    Ok(None)
767}
768
769pub fn logout_server(auth_store_path: &Path, server_name: &str) -> Result<bool, McpOAuthError> {
770    McpAuthStore::modify(auth_store_path, |store| {
771        let removed = store.remove(server_name);
772        Ok((removed, removed))
773    })
774}
775
776pub fn parse_www_authenticate_param(header: &str, param_name: &str) -> Option<String> {
777    let bytes = header.as_bytes();
778    let mut i = 0;
779    while i < bytes.len() {
780        while i < bytes.len()
781            && (bytes[i].is_ascii_whitespace() || bytes[i] == b',' || bytes[i] == b';')
782        {
783            i += 1;
784        }
785        let key_start = i;
786        while i < bytes.len()
787            && !bytes[i].is_ascii_whitespace()
788            && bytes[i] != b'='
789            && bytes[i] != b','
790        {
791            i += 1;
792        }
793        let key = &header[key_start..i];
794        while i < bytes.len() && bytes[i].is_ascii_whitespace() {
795            i += 1;
796        }
797        if i >= bytes.len() || bytes[i] != b'=' {
798            continue;
799        }
800        i += 1;
801        while i < bytes.len() && bytes[i].is_ascii_whitespace() {
802            i += 1;
803        }
804        let value = if i < bytes.len() && bytes[i] == b'"' {
805            i += 1;
806            let mut out = String::new();
807            while i < bytes.len() {
808                if bytes[i] == b'\\' && i + 1 < bytes.len() {
809                    i += 1;
810                    out.push(bytes[i] as char);
811                    i += 1;
812                } else if bytes[i] == b'"' {
813                    i += 1;
814                    break;
815                } else {
816                    let ch = header[i..].chars().next()?;
817                    out.push(ch);
818                    i += ch.len_utf8();
819                }
820            }
821            out
822        } else {
823            let val_start = i;
824            while i < bytes.len() && bytes[i] != b',' && !bytes[i].is_ascii_whitespace() {
825                i += 1;
826            }
827            header[val_start..i].to_string()
828        };
829        if key.eq_ignore_ascii_case(param_name) && !value.is_empty() {
830            return Some(value);
831        }
832    }
833    None
834}
835
836pub fn generate_code_verifier() -> Result<String, McpOAuthError> {
837    let bytes = generate_random_bytes(32)?;
838    Ok(base64url_encode(&bytes))
839}
840
841pub fn compute_code_challenge_s256(code_verifier: &str) -> String {
842    let digest = Sha256::digest(code_verifier.as_bytes());
843    base64url_encode(&digest)
844}
845
846pub fn generate_state() -> Result<String, McpOAuthError> {
847    let bytes = generate_random_bytes(24)?;
848    Ok(base64url_encode(&bytes))
849}
850
851fn generate_random_bytes(len: usize) -> Result<Vec<u8>, McpOAuthError> {
852    #[cfg(unix)]
853    {
854        let mut buf = vec![0u8; len];
855        let mut f = std::fs::File::open("/dev/urandom")
856            .map_err(|e| McpOAuthError::Io(format!("cannot open /dev/urandom: {e}")))?;
857        f.read_exact(&mut buf)
858            .map_err(|e| McpOAuthError::Io(format!("cannot read /dev/urandom: {e}")))?;
859        Ok(buf)
860    }
861    #[cfg(not(unix))]
862    {
863        use std::collections::hash_map::RandomState;
864        use std::hash::{BuildHasher, Hasher};
865        let mut out = Vec::with_capacity(len);
866        while out.len() < len {
867            let s = RandomState::new();
868            let mut h = s.build_hasher();
869            h.write_u128(now_unix_nanos()?);
870            out.extend_from_slice(&h.finish().to_le_bytes());
871        }
872        out.truncate(len);
873        Ok(out)
874    }
875}
876
877pub fn base64url_encode(input: &[u8]) -> String {
878    const TABLE: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";
879    let mut out = String::with_capacity(input.len().div_ceil(3) * 4);
880    for chunk in input.chunks(3) {
881        let b0 = chunk[0] as u32;
882        let b1 = if chunk.len() > 1 { chunk[1] as u32 } else { 0 };
883        let b2 = if chunk.len() > 2 { chunk[2] as u32 } else { 0 };
884        let triple = (b0 << 16) | (b1 << 8) | b2;
885        out.push(TABLE[((triple >> 18) & 0x3f) as usize] as char);
886        out.push(TABLE[((triple >> 12) & 0x3f) as usize] as char);
887        if chunk.len() > 1 {
888            out.push(TABLE[((triple >> 6) & 0x3f) as usize] as char);
889        }
890        if chunk.len() > 2 {
891            out.push(TABLE[(triple & 0x3f) as usize] as char);
892        }
893    }
894    out
895}
896
897fn build_http_agent(timeout: Duration) -> ureq::Agent {
898    ureq::AgentBuilder::new()
899        .timeout_connect(timeout)
900        .timeout_read(timeout)
901        .timeout_write(timeout)
902        .build()
903}
904
905fn discover_protected_resource(
906    agent: &ureq::Agent,
907    server_url: &str,
908    www_authenticate: Option<&str>,
909) -> Result<(Option<String>, Option<ProtectedResourceMetadata>), McpOAuthError> {
910    let mut effective_www_auth = www_authenticate.map(str::to_string);
911    if effective_www_auth.is_none() {
912        if let Err(ureq::Error::Status(401, resp)) = agent
913            .get(server_url)
914            .set("Accept", "application/json, text/event-stream")
915            .call()
916        {
917            if let Some(hdr) = resp.header("www-authenticate") {
918                effective_www_auth = Some(hdr.to_string());
919            }
920        }
921    }
922    if effective_www_auth.is_none() {
923        if let Err(ureq::Error::Status(401, resp)) = agent
924            .post(server_url)
925            .set("Content-Type", "application/json")
926            .set("Accept", "application/json, text/event-stream")
927            .send_string("{}")
928        {
929            if let Some(hdr) = resp.header("www-authenticate") {
930                effective_www_auth = Some(hdr.to_string());
931            }
932        }
933    }
934
935    let mut candidates = Vec::new();
936    if let Some(ref hdr) = effective_www_auth {
937        if let Some(url) = parse_www_authenticate_param(hdr, "resource_metadata") {
938            candidates.push(url);
939        }
940    }
941    let (origin, path) = parse_url_parts(server_url)?;
942    if !path.is_empty() {
943        candidates.push(format!(
944            "{origin}/.well-known/oauth-protected-resource{path}"
945        ));
946    }
947    candidates.push(format!("{origin}/.well-known/oauth-protected-resource"));
948
949    let mut seen = Vec::new();
950    for url in candidates {
951        if seen.contains(&url) {
952            continue;
953        }
954        seen.push(url.clone());
955        match agent.get(&url).set("Accept", "application/json").call() {
956            Ok(resp) if (200..300).contains(&resp.status()) => {
957                if let Ok(meta) = resp.into_json::<ProtectedResourceMetadata>() {
958                    return Ok((effective_www_auth, Some(meta)));
959                }
960            }
961            Ok(_) | Err(ureq::Error::Status(_, _)) => continue,
962            Err(ureq::Error::Transport(t)) => {
963                return Err(McpOAuthError::Discovery(format!(
964                    "failed to reach {url}: {t}"
965                )));
966            }
967        }
968    }
969    Ok((effective_www_auth, None))
970}
971
972fn discover_authorization_server(
973    agent: &ureq::Agent,
974    auth_server_url: &str,
975) -> Result<AuthorizationServerMetadata, McpOAuthError> {
976    let (origin, path) = parse_url_parts(auth_server_url)?;
977    let mut candidates = Vec::new();
978    if !path.is_empty() {
979        candidates.push(format!(
980            "{origin}/.well-known/oauth-authorization-server{path}"
981        ));
982        candidates.push(format!("{origin}/.well-known/openid-configuration{path}"));
983        candidates.push(format!("{origin}{path}/.well-known/openid-configuration"));
984    }
985    candidates.push(format!("{origin}/.well-known/oauth-authorization-server"));
986    candidates.push(format!("{origin}/.well-known/openid-configuration"));
987
988    let mut seen = Vec::new();
989    let mut metadata_err = None;
990    let mut last_err = None;
991    for url in candidates {
992        if seen.contains(&url) {
993            continue;
994        }
995        seen.push(url.clone());
996        match agent.get(&url).set("Accept", "application/json").call() {
997            Ok(resp) if (200..300).contains(&resp.status()) => {
998                match resp.into_json::<AuthorizationServerMetadata>() {
999                    Ok(meta) => {
1000                        let issuer = meta.issuer.as_deref().map(str::trim).unwrap_or("");
1001                        if issuer.is_empty() {
1002                            if metadata_err.is_none() {
1003                                metadata_err = Some(format!(
1004                                    "authorization server metadata at {url} is missing required 'issuer' field"
1005                                ));
1006                            }
1007                            continue;
1008                        }
1009                        if meta.authorization_endpoint.trim().is_empty()
1010                            || meta.token_endpoint.trim().is_empty()
1011                        {
1012                            if metadata_err.is_none() {
1013                                metadata_err = Some(format!(
1014                                    "metadata at {url} missing authorization_endpoint or token_endpoint"
1015                                ));
1016                            }
1017                            continue;
1018                        }
1019                        if let Some(ref methods) = meta.code_challenge_methods_supported {
1020                            if !methods.is_empty()
1021                                && !methods.iter().any(|m| m.eq_ignore_ascii_case("S256"))
1022                            {
1023                                return Err(McpOAuthError::Discovery(
1024                                    "authorization server does not advertise PKCE S256 support"
1025                                        .to_string(),
1026                                ));
1027                            }
1028                        }
1029                        return Ok(meta);
1030                    }
1031                    Err(e) => {
1032                        if metadata_err.is_none() {
1033                            metadata_err = Some(format!("invalid metadata JSON at {url}: {e}"));
1034                        }
1035                    }
1036                }
1037            }
1038            Ok(resp) => {
1039                last_err = Some(format!("{url} returned HTTP {}", resp.status()));
1040            }
1041            Err(ureq::Error::Status(code, _)) => {
1042                last_err = Some(format!("{url} returned HTTP {code}"));
1043            }
1044            Err(ureq::Error::Transport(t)) => {
1045                last_err = Some(format!("failed to reach {url}: {t}"));
1046            }
1047        }
1048    }
1049    Err(McpOAuthError::Discovery(
1050        metadata_err.or(last_err).unwrap_or_else(|| {
1051            format!("could not discover OAuth authorization server metadata for {auth_server_url}")
1052        }),
1053    ))
1054}
1055
1056fn obtain_client_and_listener(
1057    agent: &ureq::Agent,
1058    auth_meta: &AuthorizationServerMetadata,
1059    cached: Option<&StoredServerAuth>,
1060) -> Result<(TcpListener, String, String, Option<String>), McpOAuthError> {
1061    if let Some(entry) = cached {
1062        if let Some(ref cid) = entry.client_id {
1063            if let Some(ref cached_uri) = entry.redirect_uri {
1064                if let Some(port) = extract_loopback_port(cached_uri) {
1065                    if let Ok(listener) = TcpListener::bind(("127.0.0.1", port)) {
1066                        return Ok((
1067                            listener,
1068                            cached_uri.clone(),
1069                            cid.clone(),
1070                            entry.client_secret.clone(),
1071                        ));
1072                    }
1073                }
1074            }
1075            if auth_meta.registration_endpoint.is_none() {
1076                let listener = bind_loopback_ephemeral()?;
1077                let port = listener
1078                    .local_addr()
1079                    .map_err(|e| McpOAuthError::Io(e.to_string()))?
1080                    .port();
1081                let redirect_uri = format!("http://127.0.0.1:{port}/callback");
1082                return Ok((
1083                    listener,
1084                    redirect_uri,
1085                    cid.clone(),
1086                    entry.client_secret.clone(),
1087                ));
1088            }
1089        }
1090    }
1091
1092    let listener = bind_loopback_ephemeral()?;
1093    let port = listener
1094        .local_addr()
1095        .map_err(|e| McpOAuthError::Io(e.to_string()))?
1096        .port();
1097    let redirect_uri = format!("http://127.0.0.1:{port}/callback");
1098
1099    let Some(ref reg_endpoint) = auth_meta.registration_endpoint else {
1100        return Err(McpOAuthError::Registration(
1101            "authorization server does not support Dynamic Client Registration and no client_id is cached"
1102                .to_string(),
1103        ));
1104    };
1105
1106    let reg = register_dynamic_client(agent, reg_endpoint, &redirect_uri)?;
1107    Ok((listener, redirect_uri, reg.client_id, reg.client_secret))
1108}
1109
1110fn bind_loopback_ephemeral() -> Result<TcpListener, McpOAuthError> {
1111    TcpListener::bind(SocketAddr::from(([127, 0, 0, 1], 0)))
1112        .map_err(|e| McpOAuthError::Io(format!("cannot bind loopback callback listener: {e}")))
1113}
1114
1115fn extract_loopback_port(uri: &str) -> Option<u16> {
1116    let rest = uri.strip_prefix("http://127.0.0.1:")?;
1117    let port_str = rest.split('/').next()?;
1118    port_str.parse::<u16>().ok().filter(|&p| p > 0)
1119}
1120
1121fn register_dynamic_client(
1122    agent: &ureq::Agent,
1123    registration_endpoint: &str,
1124    redirect_uri: &str,
1125) -> Result<ClientRegistrationResponse, McpOAuthError> {
1126    let payload = serde_json::json!({
1127        "client_name": "blyte",
1128        "redirect_uris": [redirect_uri],
1129        "grant_types": ["authorization_code", "refresh_token"],
1130        "response_types": ["code"],
1131        "token_endpoint_auth_method": "none",
1132    });
1133    match agent
1134        .post(registration_endpoint)
1135        .set("Accept", "application/json")
1136        .send_json(payload)
1137    {
1138        Ok(resp) if (200..300).contains(&resp.status()) => {
1139            let parsed: ClientRegistrationResponse = resp.into_json().map_err(|e| {
1140                McpOAuthError::Registration(format!("invalid client registration response: {e}"))
1141            })?;
1142            if parsed.client_id.trim().is_empty() {
1143                return Err(McpOAuthError::Registration(
1144                    "registration response returned empty client_id".to_string(),
1145                ));
1146            }
1147            Ok(parsed)
1148        }
1149        Ok(resp) => Err(McpOAuthError::Registration(format!(
1150            "registration endpoint returned HTTP {}",
1151            resp.status()
1152        ))),
1153        Err(ureq::Error::Status(code, resp)) => {
1154            let detail = extract_oauth_error_detail(resp);
1155            Err(McpOAuthError::Registration(format!("HTTP {code}{detail}")))
1156        }
1157        Err(ureq::Error::Transport(t)) => Err(McpOAuthError::Registration(format!(
1158            "cannot reach registration endpoint: {t}"
1159        ))),
1160    }
1161}
1162
1163#[allow(clippy::too_many_arguments)]
1164fn exchange_authorization_code(
1165    agent: &ureq::Agent,
1166    token_endpoint: &str,
1167    code: &str,
1168    redirect_uri: &str,
1169    client_id: &str,
1170    client_secret: Option<&str>,
1171    code_verifier: &str,
1172    resource: Option<&str>,
1173) -> Result<TokenEndpointResponse, McpOAuthError> {
1174    let mut form: Vec<(&str, &str)> = vec![
1175        ("grant_type", "authorization_code"),
1176        ("code", code),
1177        ("redirect_uri", redirect_uri),
1178        ("client_id", client_id),
1179        ("code_verifier", code_verifier),
1180    ];
1181    if let Some(res) = resource {
1182        form.push(("resource", res));
1183    }
1184    if let Some(secret) = client_secret {
1185        form.push(("client_secret", secret));
1186    }
1187    post_token_form(agent, token_endpoint, &form)
1188}
1189
1190fn post_token_form(
1191    agent: &ureq::Agent,
1192    token_endpoint: &str,
1193    form: &[(&str, &str)],
1194) -> Result<TokenEndpointResponse, McpOAuthError> {
1195    match agent
1196        .post(token_endpoint)
1197        .set("Accept", "application/json")
1198        .send_form(form)
1199    {
1200        Ok(resp) if (200..300).contains(&resp.status()) => {
1201            let parsed: TokenEndpointResponse = resp.into_json().map_err(|e| {
1202                McpOAuthError::TokenExchange(format!("invalid token response JSON: {e}"))
1203            })?;
1204            if parsed.access_token.is_empty() {
1205                return Err(McpOAuthError::TokenExchange(
1206                    "token endpoint returned empty access_token".to_string(),
1207                ));
1208            }
1209            Ok(parsed)
1210        }
1211        Ok(resp) => Err(McpOAuthError::TokenExchange(format!(
1212            "token endpoint returned HTTP {}",
1213            resp.status()
1214        ))),
1215        Err(ureq::Error::Status(code, resp)) => {
1216            let detail = extract_oauth_error_detail(resp);
1217            Err(McpOAuthError::TokenExchange(format!("HTTP {code}{detail}")))
1218        }
1219        Err(ureq::Error::Transport(t)) => Err(McpOAuthError::TokenExchange(format!(
1220            "cannot reach token endpoint: {t}"
1221        ))),
1222    }
1223}
1224
1225fn extract_oauth_error_detail(resp: ureq::Response) -> String {
1226    let Ok(body) = resp.into_string() else {
1227        return String::new();
1228    };
1229    if let Ok(parsed) = serde_json::from_str::<OAuthErrorResponse>(&body) {
1230        if let Some(err) = parsed.error {
1231            if let Some(desc) = parsed.error_description {
1232                return format!(" ({err}: {desc})");
1233            }
1234            return format!(" ({err})");
1235        }
1236    }
1237    String::new()
1238}
1239
1240struct LoopbackCallback {
1241    stream: TcpStream,
1242    params: BTreeMap<String, String>,
1243}
1244
1245fn wait_for_loopback_callback(
1246    listener: &TcpListener,
1247    timeout: Duration,
1248) -> Result<LoopbackCallback, McpOAuthError> {
1249    listener
1250        .set_nonblocking(true)
1251        .map_err(|e| McpOAuthError::Io(format!("cannot configure callback listener: {e}")))?;
1252    let deadline = Instant::now() + timeout;
1253    loop {
1254        match listener.accept() {
1255            Ok((mut stream, _)) => {
1256                let _ = stream.set_nonblocking(false);
1257                let _ = stream.set_read_timeout(Some(Duration::from_secs(5)));
1258                let _ = stream.set_write_timeout(Some(Duration::from_secs(5)));
1259                let Some((path, query)) = read_http_request_target(&mut stream) else {
1260                    continue;
1261                };
1262                if path != "/callback" {
1263                    let _ = send_html_response(
1264                        &mut stream,
1265                        "404 Not Found",
1266                        "Not found",
1267                        "Waiting for OAuth callback on /callback.",
1268                    );
1269                    continue;
1270                }
1271                let params = parse_query_params(&query);
1272                return Ok(LoopbackCallback { stream, params });
1273            }
1274            Err(e) if e.kind() == std::io::ErrorKind::WouldBlock => {
1275                if Instant::now() >= deadline {
1276                    return Err(McpOAuthError::Timeout(
1277                        "timed out waiting for OAuth browser callback".to_string(),
1278                    ));
1279                }
1280                std::thread::sleep(Duration::from_millis(25));
1281            }
1282            Err(e) => {
1283                return Err(McpOAuthError::Callback(format!(
1284                    "callback listener accept error: {e}"
1285                )));
1286            }
1287        }
1288    }
1289}
1290
1291const MAX_CALLBACK_REQUEST_BYTES: usize = 64 * 1024;
1292
1293fn read_http_request_target(stream: &mut TcpStream) -> Option<(String, String)> {
1294    let mut buf = Vec::with_capacity(4096);
1295    let mut chunk = [0u8; 4096];
1296    let mut found_header_end = false;
1297    while buf.len() < MAX_CALLBACK_REQUEST_BYTES {
1298        let remaining = MAX_CALLBACK_REQUEST_BYTES - buf.len();
1299        let to_read = remaining.min(chunk.len());
1300        let n = stream.read(&mut chunk[..to_read]).ok()?;
1301        if n == 0 {
1302            break;
1303        }
1304        buf.extend_from_slice(&chunk[..n]);
1305        if buf.windows(4).any(|w| w == b"\r\n\r\n") {
1306            found_header_end = true;
1307            break;
1308        }
1309    }
1310    if !found_header_end {
1311        return None;
1312    }
1313    let line_end = buf.windows(2).position(|w| w == b"\r\n")?;
1314    let request_line = std::str::from_utf8(&buf[..line_end]).ok()?;
1315    let mut parts = request_line.split_whitespace();
1316    let method = parts.next()?;
1317    if method != "GET" {
1318        return None;
1319    }
1320    let target = parts.next()?;
1321    match target.split_once('?') {
1322        Some((path, query)) => Some((path.to_string(), query.to_string())),
1323        None => Some((target.to_string(), String::new())),
1324    }
1325}
1326
1327fn send_html_response(
1328    stream: &mut TcpStream,
1329    status: &str,
1330    title: &str,
1331    message_html: &str,
1332) -> std::io::Result<()> {
1333    let body = format!(
1334        "<!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>"
1335    );
1336    let response = format!(
1337        "HTTP/1.1 {status}\r\nContent-Type: text/html; charset=utf-8\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}",
1338        body.len()
1339    );
1340    stream.write_all(response.as_bytes())?;
1341    stream.flush()
1342}
1343
1344fn escape_html(input: &str) -> String {
1345    let mut out = String::with_capacity(input.len());
1346    for ch in input.chars() {
1347        match ch {
1348            '&' => out.push_str("&amp;"),
1349            '<' => out.push_str("&lt;"),
1350            '>' => out.push_str("&gt;"),
1351            '"' => out.push_str("&quot;"),
1352            '\'' => out.push_str("&#39;"),
1353            _ => out.push(ch),
1354        }
1355    }
1356    out
1357}
1358
1359pub fn parse_url_parts(url: &str) -> Result<(String, String), McpOAuthError> {
1360    let Some(scheme_end) = url.find("://") else {
1361        return Err(McpOAuthError::Discovery(format!(
1362            "invalid URL (missing scheme): {url}"
1363        )));
1364    };
1365    let rest_start = scheme_end + 3;
1366    let rest = &url[rest_start..];
1367    let authority_end = rest
1368        .find(['/', '?', '#'])
1369        .map(|idx| rest_start + idx)
1370        .unwrap_or(url.len());
1371    if authority_end == rest_start {
1372        return Err(McpOAuthError::Discovery(format!(
1373            "invalid URL (missing host): {url}"
1374        )));
1375    }
1376    let origin = url[..authority_end].to_string();
1377    let after_origin = &url[authority_end..];
1378    let path_raw = after_origin
1379        .split(['?', '#'])
1380        .next()
1381        .unwrap_or_default()
1382        .trim_end_matches('/');
1383    let path = if path_raw.is_empty() || path_raw == "/" {
1384        String::new()
1385    } else {
1386        path_raw.to_string()
1387    };
1388    Ok((origin, path))
1389}
1390
1391fn append_query_params(base_url: &str, params: &[(&str, &str)]) -> String {
1392    let mut out = base_url.to_string();
1393    let mut sep = if base_url.contains('?') { '&' } else { '?' };
1394    for (k, v) in params {
1395        out.push(sep);
1396        sep = '&';
1397        out.push_str(&percent_encode(k));
1398        out.push('=');
1399        out.push_str(&percent_encode(v));
1400    }
1401    out
1402}
1403
1404fn percent_encode(input: &str) -> String {
1405    let mut out = String::with_capacity(input.len());
1406    for b in input.bytes() {
1407        if b.is_ascii_alphanumeric() || matches!(b, b'-' | b'.' | b'_' | b'~') {
1408            out.push(b as char);
1409        } else {
1410            out.push_str(&format!("%{b:02X}"));
1411        }
1412    }
1413    out
1414}
1415
1416fn percent_decode(input: &str) -> String {
1417    let bytes = input.as_bytes();
1418    let mut out = Vec::with_capacity(bytes.len());
1419    let mut i = 0;
1420    while i < bytes.len() {
1421        if bytes[i] == b'%' && i + 2 < bytes.len() {
1422            if let Ok(hex) = std::str::from_utf8(&bytes[i + 1..i + 3]) {
1423                if let Ok(val) = u8::from_str_radix(hex, 16) {
1424                    out.push(val);
1425                    i += 3;
1426                    continue;
1427                }
1428            }
1429        }
1430        if bytes[i] == b'+' {
1431            out.push(b' ');
1432        } else {
1433            out.push(bytes[i]);
1434        }
1435        i += 1;
1436    }
1437    String::from_utf8_lossy(&out).into_owned()
1438}
1439
1440pub fn parse_query_params(query: &str) -> BTreeMap<String, String> {
1441    let mut map = BTreeMap::new();
1442    for pair in query.split('&') {
1443        if pair.is_empty() {
1444            continue;
1445        }
1446        let (k, v) = match pair.split_once('=') {
1447            Some((k, v)) => (percent_decode(k), percent_decode(v)),
1448            None => (percent_decode(pair), String::new()),
1449        };
1450        map.insert(k, v);
1451    }
1452    map
1453}
1454
1455fn resolve_authorization_server_url(
1456    server_url: &str,
1457    resource_meta: Option<&ProtectedResourceMetadata>,
1458) -> Result<String, McpOAuthError> {
1459    let meta = resource_meta.ok_or_else(|| {
1460        McpOAuthError::Discovery(format!(
1461            "could not discover OAuth protected resource metadata for {server_url}"
1462        ))
1463    })?;
1464    meta.authorization_servers
1465        .first()
1466        .filter(|s| !s.trim().is_empty())
1467        .cloned()
1468        .ok_or_else(|| {
1469            McpOAuthError::Discovery(format!(
1470                "OAuth protected resource metadata for {server_url} is missing authorization_servers"
1471            ))
1472        })
1473}
1474
1475fn system_time_secs(now: SystemTime) -> Result<u64, McpOAuthError> {
1476    now.duration_since(UNIX_EPOCH)
1477        .map(|d| d.as_secs())
1478        .map_err(|e| McpOAuthError::Io(format!("system clock is before UNIX_EPOCH: {e}")))
1479}
1480
1481fn system_time_nanos(now: SystemTime) -> Result<u128, McpOAuthError> {
1482    now.duration_since(UNIX_EPOCH)
1483        .map(|d| d.as_nanos())
1484        .map_err(|e| McpOAuthError::Io(format!("system clock is before UNIX_EPOCH: {e}")))
1485}
1486
1487fn now_unix_secs() -> Result<u64, McpOAuthError> {
1488    system_time_secs(SystemTime::now())
1489}
1490
1491fn now_unix_nanos() -> Result<u128, McpOAuthError> {
1492    system_time_nanos(SystemTime::now())
1493}
1494
1495#[cfg(test)]
1496mod tests {
1497    use super::*;
1498
1499    #[test]
1500    fn system_time_before_unix_epoch_returns_error() {
1501        let before_epoch = UNIX_EPOCH - Duration::from_secs(5);
1502        let secs_err = system_time_secs(before_epoch).unwrap_err().to_string();
1503        assert!(
1504            secs_err.contains("UNIX_EPOCH"),
1505            "expected UNIX_EPOCH in error, got: {secs_err}"
1506        );
1507        let nanos_err = system_time_nanos(before_epoch).unwrap_err().to_string();
1508        assert!(
1509            nanos_err.contains("UNIX_EPOCH"),
1510            "expected UNIX_EPOCH in error, got: {nanos_err}"
1511        );
1512    }
1513
1514    #[test]
1515    fn auth_store_save_rejects_missing_parent_or_invalid_file_name() {
1516        let store = McpAuthStore::default();
1517        let err_root = store.save(Path::new("/")).unwrap_err().to_string();
1518        assert!(
1519            err_root.contains("no parent directory"),
1520            "expected missing parent directory error, got: {err_root}"
1521        );
1522        let err_empty = store.save(Path::new("")).unwrap_err().to_string();
1523        assert!(
1524            err_empty.contains("no parent directory"),
1525            "expected missing parent directory error, got: {err_empty}"
1526        );
1527        let err_dotdot = store.save(Path::new("/tmp/..")).unwrap_err().to_string();
1528        assert!(
1529            err_dotdot.contains("missing or non-UTF-8 file name"),
1530            "expected missing file name error, got: {err_dotdot}"
1531        );
1532
1533        #[cfg(unix)]
1534        {
1535            use std::ffi::OsStr;
1536            use std::os::unix::ffi::OsStrExt;
1537            let non_utf8 = Path::new("/tmp").join(OsStr::from_bytes(b"mcp-auth-\xff.json"));
1538            let err_utf8 = store.save(&non_utf8).unwrap_err().to_string();
1539            assert!(
1540                err_utf8.contains("missing or non-UTF-8 file name"),
1541                "expected non-UTF-8 file name error, got: {err_utf8}"
1542            );
1543        }
1544    }
1545
1546    #[test]
1547    fn resolve_authorization_server_url_errors_when_metadata_or_servers_missing() {
1548        let err_none = resolve_authorization_server_url("https://mcp.example.com/mcp", None)
1549            .unwrap_err()
1550            .to_string();
1551        assert!(
1552            err_none.contains("protected resource metadata"),
1553            "expected protected resource metadata error, got: {err_none}"
1554        );
1555
1556        let empty_meta = ProtectedResourceMetadata {
1557            resource: Some("https://mcp.example.com/mcp".to_string()),
1558            authorization_servers: Vec::new(),
1559            scopes_supported: None,
1560        };
1561        let err_empty =
1562            resolve_authorization_server_url("https://mcp.example.com/mcp", Some(&empty_meta))
1563                .unwrap_err()
1564                .to_string();
1565        assert!(
1566            err_empty.contains("authorization_servers"),
1567            "expected authorization_servers error, got: {err_empty}"
1568        );
1569    }
1570
1571    #[test]
1572    fn concurrent_auth_store_modifications_preserve_all_servers() {
1573        let td = tempfile::tempdir().unwrap();
1574        let store_path = td.path().join("mcp-auth.json");
1575        let thread_count = 8usize;
1576        let mut handles = Vec::new();
1577        for idx in 0..thread_count {
1578            let path = store_path.clone();
1579            handles.push(std::thread::spawn(move || {
1580                let server = format!("server-{idx}");
1581                for round in 0..5 {
1582                    McpAuthStore::modify(&path, |store| {
1583                        store.upsert(
1584                            &server,
1585                            StoredServerAuth {
1586                                server_url: format!("https://{server}.example/mcp"),
1587                                access_token: Some(format!("tok-{idx}-{round}")),
1588                                refresh_token: Some(format!("ref-{idx}-{round}")),
1589                                ..StoredServerAuth::default()
1590                            },
1591                        );
1592                        Ok((true, ()))
1593                    })
1594                    .unwrap();
1595                }
1596            }));
1597        }
1598        for h in handles {
1599            h.join().unwrap();
1600        }
1601        let final_store = McpAuthStore::load(&store_path).unwrap();
1602        assert_eq!(final_store.servers.len(), thread_count);
1603        for idx in 0..thread_count {
1604            let server = format!("server-{idx}");
1605            let entry = final_store.get(&server).expect("server entry must exist");
1606            assert_eq!(
1607                entry.access_token.as_deref(),
1608                Some(format!("tok-{idx}-4").as_str())
1609            );
1610            assert_eq!(
1611                entry.refresh_token.as_deref(),
1612                Some(format!("ref-{idx}-4").as_str())
1613            );
1614        }
1615    }
1616
1617    #[test]
1618    fn loopback_callback_reads_multipacket_headers_through_crlf_crlf_before_replying() {
1619        let listener = TcpListener::bind("127.0.0.1:0").unwrap();
1620        let addr = listener.local_addr().unwrap();
1621
1622        let server = std::thread::spawn(move || {
1623            let mut cb = wait_for_loopback_callback(&listener, Duration::from_secs(5)).unwrap();
1624            send_html_response(&mut cb.stream, "200 OK", "Done", "Authenticated").unwrap();
1625            cb.params
1626        });
1627
1628        let mut client = TcpStream::connect(addr).unwrap();
1629        client.set_nodelay(true).unwrap();
1630        client
1631            .set_read_timeout(Some(Duration::from_millis(80)))
1632            .unwrap();
1633
1634        client
1635            .write_all(b"GET /callback?code=abc123&state=xyz789 HTTP/1.1\r\n")
1636            .unwrap();
1637        client.flush().unwrap();
1638        let mut probe = [0u8; 32];
1639        let early1 = client.read(&mut probe);
1640        assert!(
1641            matches!(
1642                early1,
1643                Err(ref e)
1644                    if e.kind() == std::io::ErrorKind::WouldBlock
1645                        || e.kind() == std::io::ErrorKind::TimedOut
1646            ),
1647            "server replied before end of HTTP headers after request line: {early1:?}"
1648        );
1649
1650        client
1651            .write_all(b"Host: 127.0.0.1\r\nUser-Agent: multi-packet-browser\r\n")
1652            .unwrap();
1653        client.flush().unwrap();
1654        let early2 = client.read(&mut probe);
1655        assert!(
1656            matches!(
1657                early2,
1658                Err(ref e)
1659                    if e.kind() == std::io::ErrorKind::WouldBlock
1660                        || e.kind() == std::io::ErrorKind::TimedOut
1661            ),
1662            "server replied before trailing CRLF CRLF: {early2:?}"
1663        );
1664
1665        client.write_all(b"Accept: text/html\r\n\r\n").unwrap();
1666        client.flush().unwrap();
1667
1668        client
1669            .set_read_timeout(Some(Duration::from_secs(5)))
1670            .unwrap();
1671        let mut response = String::new();
1672        client.read_to_string(&mut response).unwrap();
1673        assert!(
1674            response.starts_with("HTTP/1.1 200 OK"),
1675            "unexpected HTTP response: {response}"
1676        );
1677        assert!(response.contains("Done"));
1678
1679        let params = server.join().unwrap();
1680        assert_eq!(params.get("code").map(String::as_str), Some("abc123"));
1681        assert_eq!(params.get("state").map(String::as_str), Some("xyz789"));
1682    }
1683
1684    #[test]
1685    fn read_http_request_target_rejects_truncated_requests_on_eof() {
1686        for truncated in [
1687            &b"GET /callback?code=abc123&state=xyz789 HTTP/1.1"[..],
1688            &b"GET /callback?code=abc123&state=xyz789 HTTP/1.1\r\nHost: 127.0.0.1\r\n"[..],
1689            &b""[..],
1690        ] {
1691            let listener = TcpListener::bind("127.0.0.1:0").unwrap();
1692            let addr = listener.local_addr().unwrap();
1693            let payload = truncated.to_vec();
1694
1695            let client_handle = std::thread::spawn(move || {
1696                let mut client = TcpStream::connect(addr).unwrap();
1697                client.write_all(&payload).unwrap();
1698                client.flush().unwrap();
1699                client.shutdown(std::net::Shutdown::Write).unwrap();
1700            });
1701
1702            let (mut server_stream, _) = listener.accept().unwrap();
1703            server_stream
1704                .set_read_timeout(Some(Duration::from_secs(2)))
1705                .unwrap();
1706            assert_eq!(read_http_request_target(&mut server_stream), None);
1707            client_handle.join().unwrap();
1708        }
1709    }
1710
1711    #[test]
1712    fn loopback_callback_ignores_truncated_request_and_accepts_complete_request() {
1713        let listener = TcpListener::bind("127.0.0.1:0").unwrap();
1714        let addr = listener.local_addr().unwrap();
1715
1716        let server = std::thread::spawn(move || {
1717            let mut cb = wait_for_loopback_callback(&listener, Duration::from_secs(5)).unwrap();
1718            send_html_response(&mut cb.stream, "200 OK", "Done", "Authenticated").unwrap();
1719            cb.params
1720        });
1721
1722        {
1723            let mut truncated = TcpStream::connect(addr).unwrap();
1724            truncated
1725                .set_read_timeout(Some(Duration::from_secs(2)))
1726                .unwrap();
1727            truncated
1728                .write_all(b"GET /callback?code=bad&state=bad HTTP/1.1")
1729                .unwrap();
1730            truncated.flush().unwrap();
1731            truncated.shutdown(std::net::Shutdown::Write).unwrap();
1732            let mut resp = Vec::new();
1733            truncated.read_to_end(&mut resp).unwrap();
1734            assert!(resp.is_empty());
1735        }
1736
1737        let mut valid = TcpStream::connect(addr).unwrap();
1738        valid
1739            .write_all(b"GET /callback?code=good&state=ok HTTP/1.1\r\nHost: 127.0.0.1\r\n\r\n")
1740            .unwrap();
1741        valid.flush().unwrap();
1742
1743        let mut response = String::new();
1744        valid.read_to_string(&mut response).unwrap();
1745        assert!(response.starts_with("HTTP/1.1 200 OK"));
1746
1747        let params = server.join().unwrap();
1748        assert_eq!(params.get("code").map(String::as_str), Some("good"));
1749        assert_eq!(params.get("state").map(String::as_str), Some("ok"));
1750    }
1751
1752    #[test]
1753    fn discover_authorization_server_rejects_missing_or_empty_issuer() {
1754        for body_fn in [
1755            |base: &str| {
1756                serde_json::json!({
1757                    "authorization_endpoint": format!("{base}/authorize"),
1758                    "token_endpoint": format!("{base}/token"),
1759                    "code_challenge_methods_supported": ["S256"]
1760                })
1761                .to_string()
1762            },
1763            |base: &str| {
1764                serde_json::json!({
1765                    "issuer": "   ",
1766                    "authorization_endpoint": format!("{base}/authorize"),
1767                    "token_endpoint": format!("{base}/token"),
1768                    "code_challenge_methods_supported": ["S256"]
1769                })
1770                .to_string()
1771            },
1772        ] {
1773            let listener = TcpListener::bind("127.0.0.1:0").unwrap();
1774            let addr = listener.local_addr().unwrap();
1775            let base = format!("http://{addr}");
1776            let payload = body_fn(&base);
1777            let stop = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));
1778            let stop_flag = std::sync::Arc::clone(&stop);
1779            listener.set_nonblocking(true).unwrap();
1780
1781            let handle = std::thread::spawn(move || {
1782                while !stop_flag.load(std::sync::atomic::Ordering::SeqCst) {
1783                    match listener.accept() {
1784                        Ok((mut stream, _)) => {
1785                            let _ = stream.set_read_timeout(Some(Duration::from_secs(1)));
1786                            let mut buf = [0u8; 4096];
1787                            let n = stream.read(&mut buf).unwrap_or(0);
1788                            let req = String::from_utf8_lossy(&buf[..n]);
1789                            let path = req
1790                                .lines()
1791                                .next()
1792                                .and_then(|l| l.split_whitespace().nth(1))
1793                                .unwrap_or("");
1794                            let resp = if path == "/.well-known/oauth-authorization-server" {
1795                                format!(
1796                                    "HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}",
1797                                    payload.len(),
1798                                    payload
1799                                )
1800                            } else {
1801                                "HTTP/1.1 404 Not Found\r\nContent-Length: 0\r\nConnection: close\r\n\r\n"
1802                                    .to_string()
1803                            };
1804                            let _ = stream.write_all(resp.as_bytes());
1805                            let _ = stream.flush();
1806                        }
1807                        Err(e) if e.kind() == std::io::ErrorKind::WouldBlock => {
1808                            std::thread::sleep(Duration::from_millis(5));
1809                        }
1810                        Err(_) => break,
1811                    }
1812                }
1813            });
1814
1815            let agent = build_http_agent(Duration::from_secs(2));
1816            let err = discover_authorization_server(&agent, &base)
1817                .expect_err("metadata missing required issuer must fail")
1818                .to_string();
1819            stop.store(true, std::sync::atomic::Ordering::SeqCst);
1820            let _ = handle.join();
1821
1822            assert!(
1823                err.contains("issuer"),
1824                "expected clear error mentioning missing issuer, got: {err}"
1825            );
1826        }
1827    }
1828}