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    #[serde(default)]
365    pub token_endpoint_auth_methods_supported: Option<Vec<String>>,
366}
367
368#[derive(Debug, Clone, Deserialize)]
369struct ClientRegistrationResponse {
370    client_id: String,
371    #[serde(default)]
372    client_secret: Option<String>,
373}
374
375#[derive(Debug, Clone, Deserialize)]
376struct TokenEndpointResponse {
377    access_token: String,
378    #[serde(default)]
379    token_type: Option<String>,
380    #[serde(default)]
381    expires_in: Option<u64>,
382    #[serde(default)]
383    refresh_token: Option<String>,
384    #[serde(default)]
385    scope: Option<String>,
386}
387
388#[derive(Debug, Clone, Deserialize)]
389struct OAuthErrorResponse {
390    #[serde(default)]
391    error: Option<String>,
392    #[serde(default)]
393    error_description: Option<String>,
394}
395
396pub struct PendingOAuthFlow {
397    authorize_url: String,
398    redirect_uri: String,
399    state: String,
400    code_verifier: String,
401    client_id: String,
402    client_secret: Option<String>,
403    token_endpoint: String,
404    authorization_server: String,
405    resource: Option<String>,
406    server_name: String,
407    server_url: String,
408    auth_store_path: PathBuf,
409    listener: TcpListener,
410    http_timeout: Duration,
411}
412
413impl PendingOAuthFlow {
414    pub fn authorize_url(&self) -> &str {
415        &self.authorize_url
416    }
417
418    pub fn redirect_uri(&self) -> &str {
419        &self.redirect_uri
420    }
421
422    pub fn state(&self) -> &str {
423        &self.state
424    }
425
426    pub fn client_id(&self) -> &str {
427        &self.client_id
428    }
429
430    pub fn complete(self, callback_timeout: Duration) -> Result<StoredServerAuth, McpOAuthError> {
431        let callback = wait_for_loopback_callback(&self.listener, callback_timeout)?;
432        let mut stream = callback.stream;
433        if let Some(err) = callback.params.get("error") {
434            let desc = callback
435                .params
436                .get("error_description")
437                .map(|d| format!("{err}: {d}"))
438                .unwrap_or_else(|| err.clone());
439            let _ = send_html_response(
440                &mut stream,
441                "400 Bad Request",
442                "Authentication failed",
443                &format!("Authorization was denied ({}).", escape_html(&desc)),
444            );
445            return Err(McpOAuthError::AuthDenied(desc));
446        }
447        let received_state = callback.params.get("state").map(String::as_str);
448        if received_state != Some(self.state.as_str()) {
449            let _ = send_html_response(
450                &mut stream,
451                "400 Bad Request",
452                "Authentication failed",
453                "The OAuth state parameter did not match. Please restart authentication from blyte.",
454            );
455            return Err(McpOAuthError::StateMismatch);
456        }
457        let Some(code) = callback
458            .params
459            .get("code")
460            .filter(|c| !c.is_empty())
461            .cloned()
462        else {
463            let _ = send_html_response(
464                &mut stream,
465                "400 Bad Request",
466                "Authentication failed",
467                "The authorization callback did not include an authorization code.",
468            );
469            return Err(McpOAuthError::Callback(
470                "callback missing authorization code".to_string(),
471            ));
472        };
473
474        let agent = build_http_agent(self.http_timeout);
475        let token_res = exchange_authorization_code(
476            &agent,
477            &self.token_endpoint,
478            &code,
479            &self.redirect_uri,
480            &self.client_id,
481            self.client_secret.as_deref(),
482            &self.code_verifier,
483            self.resource.as_deref(),
484        );
485        let token = match token_res {
486            Ok(t) => t,
487            Err(e) => {
488                let _ = send_html_response(
489                    &mut stream,
490                    "500 Internal Server Error",
491                    "Authentication failed",
492                    "Token exchange failed. Check blyte output for details.",
493                );
494                return Err(e);
495            }
496        };
497
498        let now = now_unix_secs()?;
499        let stored = StoredServerAuth {
500            server_url: self.server_url.clone(),
501            authorization_server: Some(self.authorization_server.clone()),
502            token_endpoint: Some(self.token_endpoint.clone()),
503            client_id: Some(self.client_id.clone()),
504            client_secret: self.client_secret.clone(),
505            redirect_uri: Some(self.redirect_uri.clone()),
506            access_token: Some(token.access_token),
507            refresh_token: token.refresh_token,
508            token_type: token.token_type.or_else(|| Some("Bearer".to_string())),
509            scope: token.scope,
510            expires_at: token.expires_in.map(|secs| now.saturating_add(secs)),
511        };
512
513        McpAuthStore::modify(&self.auth_store_path, |store| {
514            store.upsert(&self.server_name, stored.clone());
515            Ok((true, ()))
516        })?;
517
518        let _ = send_html_response(
519            &mut stream,
520            "200 OK",
521            "Authentication complete",
522            &format!(
523                "blyte is now authenticated with <strong>{}</strong>. You can close this tab and return to blyte.",
524                escape_html(&self.server_name)
525            ),
526        );
527
528        Ok(stored)
529    }
530}
531
532pub fn prepare_oauth_flow(
533    auth_store_path: &Path,
534    server_name: &str,
535    server_url: &str,
536    www_authenticate: Option<&str>,
537    http_timeout: Duration,
538) -> Result<PendingOAuthFlow, McpOAuthError> {
539    prepare_oauth_flow_with_config(
540        auth_store_path,
541        server_name,
542        server_url,
543        www_authenticate,
544        None,
545        http_timeout,
546    )
547}
548
549pub fn prepare_oauth_flow_with_config(
550    auth_store_path: &Path,
551    server_name: &str,
552    server_url: &str,
553    www_authenticate: Option<&str>,
554    oauth_config: Option<&crate::mcp::config::ResolvedOAuthClientConfig>,
555    http_timeout: Duration,
556) -> Result<PendingOAuthFlow, McpOAuthError> {
557    let agent = build_http_agent(http_timeout);
558    let (discovered_www_auth, resource_meta) =
559        discover_protected_resource(&agent, server_url, www_authenticate)?;
560
561    let auth_server_url = resolve_authorization_server_url(server_url, resource_meta.as_ref())?;
562
563    let auth_meta = discover_authorization_server(&agent, &auth_server_url)?;
564    let auth_server_id = auth_meta
565        .issuer
566        .as_deref()
567        .map(str::trim)
568        .filter(|s| !s.is_empty())
569        .map(str::to_string)
570        .ok_or_else(|| {
571            McpOAuthError::Discovery(format!(
572                "authorization server metadata for {auth_server_url} is missing required 'issuer' field"
573            ))
574        })?;
575
576    let store = McpAuthStore::load(auth_store_path)?;
577    let cached = store
578        .get(server_name)
579        .filter(|entry| {
580            entry.server_url == server_url
581                && entry
582                    .authorization_server
583                    .as_deref()
584                    .is_none_or(|issuer| issuer == auth_server_id)
585                && entry.client_id.is_some()
586        })
587        .cloned();
588
589    let (listener, redirect_uri, client_id, client_secret) =
590        obtain_client_and_listener(&agent, &auth_meta, cached.as_ref(), oauth_config)?;
591
592    McpAuthStore::modify(auth_store_path, |store| {
593        let mut cached_entry = store
594            .get(server_name)
595            .filter(|entry| entry.server_url == server_url)
596            .cloned()
597            .unwrap_or_else(|| StoredServerAuth {
598                server_url: server_url.to_string(),
599                ..StoredServerAuth::default()
600            });
601        cached_entry.server_url = server_url.to_string();
602        cached_entry.authorization_server = Some(auth_server_id.clone());
603        cached_entry.token_endpoint = Some(auth_meta.token_endpoint.clone());
604        cached_entry.client_id = Some(client_id.clone());
605        cached_entry.client_secret = client_secret.clone();
606        cached_entry.redirect_uri = Some(redirect_uri.clone());
607        store.upsert(server_name, cached_entry);
608        Ok((true, ()))
609    })?;
610
611    let code_verifier = generate_code_verifier()?;
612    let code_challenge = compute_code_challenge_s256(&code_verifier);
613    let state = generate_state()?;
614    let resource = resource_meta
615        .as_ref()
616        .and_then(|m| m.resource.clone())
617        .or_else(|| Some(server_url.to_string()));
618
619    let scope = oauth_config
620        .and_then(|cfg| cfg.scopes.as_ref())
621        .filter(|scopes| !scopes.is_empty())
622        .map(|scopes| scopes.join(" "))
623        .or_else(|| {
624            discovered_www_auth
625                .as_deref()
626                .and_then(|h| parse_www_authenticate_param(h, "scope"))
627        })
628        .or_else(|| {
629            resource_meta
630                .as_ref()
631                .and_then(|m| m.scopes_supported.as_ref())
632                .filter(|s| !s.is_empty())
633                .map(|s| s.join(" "))
634        });
635
636    let mut params: Vec<(&str, &str)> = vec![
637        ("response_type", "code"),
638        ("client_id", &client_id),
639        ("redirect_uri", &redirect_uri),
640        ("code_challenge", &code_challenge),
641        ("code_challenge_method", "S256"),
642        ("state", &state),
643    ];
644    if let Some(ref res) = resource {
645        params.push(("resource", res));
646    }
647    if let Some(ref sc) = scope {
648        params.push(("scope", sc));
649    }
650    let authorize_url = append_query_params(&auth_meta.authorization_endpoint, &params);
651
652    Ok(PendingOAuthFlow {
653        authorize_url,
654        redirect_uri,
655        state,
656        code_verifier,
657        client_id,
658        client_secret,
659        token_endpoint: auth_meta.token_endpoint,
660        authorization_server: auth_server_id,
661        resource,
662        server_name: server_name.to_string(),
663        server_url: server_url.to_string(),
664        auth_store_path: auth_store_path.to_path_buf(),
665        listener,
666        http_timeout,
667    })
668}
669
670pub fn refresh_access_token(
671    auth_store_path: &Path,
672    server_name: &str,
673    server_url: &str,
674    www_authenticate: Option<&str>,
675    http_timeout: Duration,
676) -> Result<StoredServerAuth, McpOAuthError> {
677    refresh_access_token_with_config(
678        auth_store_path,
679        server_name,
680        server_url,
681        www_authenticate,
682        None,
683        http_timeout,
684    )
685}
686
687pub fn refresh_access_token_with_config(
688    auth_store_path: &Path,
689    server_name: &str,
690    server_url: &str,
691    www_authenticate: Option<&str>,
692    oauth_config: Option<&crate::mcp::config::ResolvedOAuthClientConfig>,
693    http_timeout: Duration,
694) -> Result<StoredServerAuth, McpOAuthError> {
695    let store = McpAuthStore::load(auth_store_path)?;
696    let existing = store
697        .get(server_name)
698        .filter(|entry| entry.server_url == server_url)
699        .cloned()
700        .ok_or_else(|| {
701            McpOAuthError::RefreshFailed(format!(
702                "no stored OAuth credentials for MCP server '{server_name}'"
703            ))
704        })?;
705    let refresh_token = existing
706        .refresh_token
707        .clone()
708        .filter(|t| !t.is_empty())
709        .ok_or_else(|| {
710            McpOAuthError::RefreshFailed(format!(
711                "no refresh token stored for MCP server '{server_name}'"
712            ))
713        })?;
714
715    let agent = build_http_agent(http_timeout);
716    let token_endpoint = match existing.token_endpoint.clone() {
717        Some(ep) => ep,
718        None => {
719            let (_, resource_meta) =
720                discover_protected_resource(&agent, server_url, www_authenticate)?;
721            let auth_server_url =
722                resolve_authorization_server_url(server_url, resource_meta.as_ref())?;
723            let auth_meta = discover_authorization_server(&agent, &auth_server_url)?;
724            auth_meta.token_endpoint
725        }
726    };
727
728    let effective_client_id = oauth_config
729        .and_then(|cfg| cfg.client_id.clone())
730        .or(existing.client_id);
731    let effective_client_secret = oauth_config
732        .and_then(|cfg| cfg.client_secret.clone())
733        .or(existing.client_secret);
734
735    let mut form: Vec<(&str, &str)> = vec![
736        ("grant_type", "refresh_token"),
737        ("refresh_token", &refresh_token),
738    ];
739    if let Some(ref cid) = effective_client_id {
740        form.push(("client_id", cid));
741    }
742    if let Some(ref secret) = effective_client_secret {
743        form.push(("client_secret", secret));
744    }
745
746    let token = post_token_form(&agent, &token_endpoint, &form)
747        .map_err(|e| McpOAuthError::RefreshFailed(e.to_string()))?;
748
749    let now = now_unix_secs()?;
750    let updated = StoredServerAuth {
751        server_url: existing.server_url,
752        authorization_server: existing.authorization_server,
753        token_endpoint: Some(token_endpoint),
754        client_id: effective_client_id,
755        client_secret: effective_client_secret,
756        redirect_uri: existing.redirect_uri,
757        access_token: Some(token.access_token),
758        refresh_token: token.refresh_token.or(Some(refresh_token)),
759        token_type: token.token_type.or(existing.token_type),
760        scope: token.scope.or(existing.scope),
761        expires_at: token.expires_in.map(|secs| now.saturating_add(secs)),
762    };
763
764    McpAuthStore::modify(auth_store_path, |store| {
765        store.upsert(server_name, updated.clone());
766        Ok((true, ()))
767    })?;
768    Ok(updated)
769}
770
771pub fn resolve_bearer_token(
772    auth_store_path: &Path,
773    server_name: &str,
774    server_url: &str,
775    http_timeout: Duration,
776) -> Result<Option<String>, McpOAuthError> {
777    resolve_bearer_token_with_config(auth_store_path, server_name, server_url, None, http_timeout)
778}
779
780pub fn resolve_bearer_token_with_config(
781    auth_store_path: &Path,
782    server_name: &str,
783    server_url: &str,
784    oauth_config: Option<&crate::mcp::config::ResolvedOAuthClientConfig>,
785    http_timeout: Duration,
786) -> Result<Option<String>, McpOAuthError> {
787    resolve_bearer_token_at_with_config(
788        auth_store_path,
789        server_name,
790        server_url,
791        oauth_config,
792        http_timeout,
793        now_unix_secs()?,
794    )
795}
796
797pub fn resolve_bearer_token_at(
798    auth_store_path: &Path,
799    server_name: &str,
800    server_url: &str,
801    http_timeout: Duration,
802    now_secs: u64,
803) -> Result<Option<String>, McpOAuthError> {
804    resolve_bearer_token_at_with_config(
805        auth_store_path,
806        server_name,
807        server_url,
808        None,
809        http_timeout,
810        now_secs,
811    )
812}
813
814pub fn resolve_bearer_token_at_with_config(
815    auth_store_path: &Path,
816    server_name: &str,
817    server_url: &str,
818    oauth_config: Option<&crate::mcp::config::ResolvedOAuthClientConfig>,
819    http_timeout: Duration,
820    now_secs: u64,
821) -> Result<Option<String>, McpOAuthError> {
822    let store = McpAuthStore::load(auth_store_path)?;
823    let Some(entry) = store.get(server_name) else {
824        return Ok(None);
825    };
826    if entry.server_url != server_url {
827        return Ok(None);
828    }
829    if let Some(ref token) = entry.access_token {
830        if !token.is_empty()
831            && !entry.is_expired_or_near_expiry(now_secs, DEFAULT_EXPIRY_MARGIN_SECS)
832        {
833            return Ok(Some(token.clone()));
834        }
835    }
836    if entry
837        .refresh_token
838        .as_deref()
839        .is_some_and(|t| !t.is_empty())
840    {
841        match refresh_access_token_with_config(
842            auth_store_path,
843            server_name,
844            server_url,
845            None,
846            oauth_config,
847            http_timeout,
848        ) {
849            Ok(refreshed) => return Ok(refreshed.access_token),
850            Err(_) => return Ok(None),
851        }
852    }
853    Ok(None)
854}
855
856pub fn logout_server(auth_store_path: &Path, server_name: &str) -> Result<bool, McpOAuthError> {
857    McpAuthStore::modify(auth_store_path, |store| {
858        let removed = store.remove(server_name);
859        Ok((removed, removed))
860    })
861}
862
863pub fn parse_www_authenticate_param(header: &str, param_name: &str) -> Option<String> {
864    let bytes = header.as_bytes();
865    let mut i = 0;
866    while i < bytes.len() {
867        while i < bytes.len()
868            && (bytes[i].is_ascii_whitespace() || bytes[i] == b',' || bytes[i] == b';')
869        {
870            i += 1;
871        }
872        let key_start = i;
873        while i < bytes.len()
874            && !bytes[i].is_ascii_whitespace()
875            && bytes[i] != b'='
876            && bytes[i] != b','
877        {
878            i += 1;
879        }
880        let key = &header[key_start..i];
881        while i < bytes.len() && bytes[i].is_ascii_whitespace() {
882            i += 1;
883        }
884        if i >= bytes.len() || bytes[i] != b'=' {
885            continue;
886        }
887        i += 1;
888        while i < bytes.len() && bytes[i].is_ascii_whitespace() {
889            i += 1;
890        }
891        let value = if i < bytes.len() && bytes[i] == b'"' {
892            i += 1;
893            let mut out = String::new();
894            while i < bytes.len() {
895                if bytes[i] == b'\\' && i + 1 < bytes.len() {
896                    i += 1;
897                    out.push(bytes[i] as char);
898                    i += 1;
899                } else if bytes[i] == b'"' {
900                    i += 1;
901                    break;
902                } else {
903                    let ch = header[i..].chars().next()?;
904                    out.push(ch);
905                    i += ch.len_utf8();
906                }
907            }
908            out
909        } else {
910            let val_start = i;
911            while i < bytes.len() && bytes[i] != b',' && !bytes[i].is_ascii_whitespace() {
912                i += 1;
913            }
914            header[val_start..i].to_string()
915        };
916        if key.eq_ignore_ascii_case(param_name) && !value.is_empty() {
917            return Some(value);
918        }
919    }
920    None
921}
922
923pub fn generate_code_verifier() -> Result<String, McpOAuthError> {
924    let bytes = generate_random_bytes(32)?;
925    Ok(base64url_encode(&bytes))
926}
927
928pub fn compute_code_challenge_s256(code_verifier: &str) -> String {
929    let digest = Sha256::digest(code_verifier.as_bytes());
930    base64url_encode(&digest)
931}
932
933pub fn generate_state() -> Result<String, McpOAuthError> {
934    let bytes = generate_random_bytes(24)?;
935    Ok(base64url_encode(&bytes))
936}
937
938fn generate_random_bytes(len: usize) -> Result<Vec<u8>, McpOAuthError> {
939    #[cfg(unix)]
940    {
941        let mut buf = vec![0u8; len];
942        let mut f = std::fs::File::open("/dev/urandom")
943            .map_err(|e| McpOAuthError::Io(format!("cannot open /dev/urandom: {e}")))?;
944        f.read_exact(&mut buf)
945            .map_err(|e| McpOAuthError::Io(format!("cannot read /dev/urandom: {e}")))?;
946        Ok(buf)
947    }
948    #[cfg(not(unix))]
949    {
950        use std::collections::hash_map::RandomState;
951        use std::hash::{BuildHasher, Hasher};
952        let mut out = Vec::with_capacity(len);
953        while out.len() < len {
954            let s = RandomState::new();
955            let mut h = s.build_hasher();
956            h.write_u128(now_unix_nanos()?);
957            out.extend_from_slice(&h.finish().to_le_bytes());
958        }
959        out.truncate(len);
960        Ok(out)
961    }
962}
963
964pub fn base64url_encode(input: &[u8]) -> String {
965    const TABLE: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";
966    let mut out = String::with_capacity(input.len().div_ceil(3) * 4);
967    for chunk in input.chunks(3) {
968        let b0 = chunk[0] as u32;
969        let b1 = if chunk.len() > 1 { chunk[1] as u32 } else { 0 };
970        let b2 = if chunk.len() > 2 { chunk[2] as u32 } else { 0 };
971        let triple = (b0 << 16) | (b1 << 8) | b2;
972        out.push(TABLE[((triple >> 18) & 0x3f) as usize] as char);
973        out.push(TABLE[((triple >> 12) & 0x3f) as usize] as char);
974        if chunk.len() > 1 {
975            out.push(TABLE[((triple >> 6) & 0x3f) as usize] as char);
976        }
977        if chunk.len() > 2 {
978            out.push(TABLE[(triple & 0x3f) as usize] as char);
979        }
980    }
981    out
982}
983
984fn build_http_agent(timeout: Duration) -> ureq::Agent {
985    ureq::AgentBuilder::new()
986        .timeout_connect(timeout)
987        .timeout_read(timeout)
988        .timeout_write(timeout)
989        .build()
990}
991
992fn discover_protected_resource(
993    agent: &ureq::Agent,
994    server_url: &str,
995    www_authenticate: Option<&str>,
996) -> Result<(Option<String>, Option<ProtectedResourceMetadata>), McpOAuthError> {
997    let mut effective_www_auth = www_authenticate.map(str::to_string);
998    if effective_www_auth.is_none() {
999        if let Err(ureq::Error::Status(401, resp)) = agent
1000            .get(server_url)
1001            .set("Accept", "application/json, text/event-stream")
1002            .call()
1003        {
1004            if let Some(hdr) = resp.header("www-authenticate") {
1005                effective_www_auth = Some(hdr.to_string());
1006            }
1007        }
1008    }
1009    if effective_www_auth.is_none() {
1010        if let Err(ureq::Error::Status(401, resp)) = agent
1011            .post(server_url)
1012            .set("Content-Type", "application/json")
1013            .set("Accept", "application/json, text/event-stream")
1014            .send_string("{}")
1015        {
1016            if let Some(hdr) = resp.header("www-authenticate") {
1017                effective_www_auth = Some(hdr.to_string());
1018            }
1019        }
1020    }
1021
1022    let mut candidates = Vec::new();
1023    if let Some(ref hdr) = effective_www_auth {
1024        if let Some(url) = parse_www_authenticate_param(hdr, "resource_metadata") {
1025            candidates.push(url);
1026        }
1027    }
1028    let (origin, path) = parse_url_parts(server_url)?;
1029    if !path.is_empty() {
1030        candidates.push(format!(
1031            "{origin}/.well-known/oauth-protected-resource{path}"
1032        ));
1033    }
1034    candidates.push(format!("{origin}/.well-known/oauth-protected-resource"));
1035
1036    let mut seen = Vec::new();
1037    for url in candidates {
1038        if seen.contains(&url) {
1039            continue;
1040        }
1041        seen.push(url.clone());
1042        match agent.get(&url).set("Accept", "application/json").call() {
1043            Ok(resp) if (200..300).contains(&resp.status()) => {
1044                if let Ok(meta) = resp.into_json::<ProtectedResourceMetadata>() {
1045                    return Ok((effective_www_auth, Some(meta)));
1046                }
1047            }
1048            Ok(_) | Err(ureq::Error::Status(_, _)) => continue,
1049            Err(ureq::Error::Transport(t)) => {
1050                return Err(McpOAuthError::Discovery(format!(
1051                    "failed to reach {url}: {t}"
1052                )));
1053            }
1054        }
1055    }
1056    Ok((effective_www_auth, None))
1057}
1058
1059fn discover_authorization_server(
1060    agent: &ureq::Agent,
1061    auth_server_url: &str,
1062) -> Result<AuthorizationServerMetadata, McpOAuthError> {
1063    let (origin, path) = parse_url_parts(auth_server_url)?;
1064    let mut candidates = Vec::new();
1065    if !path.is_empty() {
1066        candidates.push(format!(
1067            "{origin}/.well-known/oauth-authorization-server{path}"
1068        ));
1069        candidates.push(format!("{origin}/.well-known/openid-configuration{path}"));
1070        candidates.push(format!("{origin}{path}/.well-known/openid-configuration"));
1071    }
1072    candidates.push(format!("{origin}/.well-known/oauth-authorization-server"));
1073    candidates.push(format!("{origin}/.well-known/openid-configuration"));
1074
1075    let mut seen = Vec::new();
1076    let mut metadata_err = None;
1077    let mut last_err = None;
1078    for url in candidates {
1079        if seen.contains(&url) {
1080            continue;
1081        }
1082        seen.push(url.clone());
1083        match agent.get(&url).set("Accept", "application/json").call() {
1084            Ok(resp) if (200..300).contains(&resp.status()) => {
1085                match resp.into_json::<AuthorizationServerMetadata>() {
1086                    Ok(meta) => {
1087                        let issuer = meta.issuer.as_deref().map(str::trim).unwrap_or("");
1088                        if issuer.is_empty() {
1089                            if metadata_err.is_none() {
1090                                metadata_err = Some(format!(
1091                                    "authorization server metadata at {url} is missing required 'issuer' field"
1092                                ));
1093                            }
1094                            continue;
1095                        }
1096                        if meta.authorization_endpoint.trim().is_empty()
1097                            || meta.token_endpoint.trim().is_empty()
1098                        {
1099                            if metadata_err.is_none() {
1100                                metadata_err = Some(format!(
1101                                    "metadata at {url} missing authorization_endpoint or token_endpoint"
1102                                ));
1103                            }
1104                            continue;
1105                        }
1106                        if let Some(ref methods) = meta.code_challenge_methods_supported {
1107                            if !methods.is_empty()
1108                                && !methods.iter().any(|m| m.eq_ignore_ascii_case("S256"))
1109                            {
1110                                return Err(McpOAuthError::Discovery(
1111                                    "authorization server does not advertise PKCE S256 support"
1112                                        .to_string(),
1113                                ));
1114                            }
1115                        }
1116                        return Ok(meta);
1117                    }
1118                    Err(e) => {
1119                        if metadata_err.is_none() {
1120                            metadata_err = Some(format!("invalid metadata JSON at {url}: {e}"));
1121                        }
1122                    }
1123                }
1124            }
1125            Ok(resp) => {
1126                last_err = Some(format!("{url} returned HTTP {}", resp.status()));
1127            }
1128            Err(ureq::Error::Status(code, _)) => {
1129                last_err = Some(format!("{url} returned HTTP {code}"));
1130            }
1131            Err(ureq::Error::Transport(t)) => {
1132                last_err = Some(format!("failed to reach {url}: {t}"));
1133            }
1134        }
1135    }
1136    Err(McpOAuthError::Discovery(
1137        metadata_err.or(last_err).unwrap_or_else(|| {
1138            format!("could not discover OAuth authorization server metadata for {auth_server_url}")
1139        }),
1140    ))
1141}
1142
1143fn obtain_client_and_listener(
1144    agent: &ureq::Agent,
1145    auth_meta: &AuthorizationServerMetadata,
1146    cached: Option<&StoredServerAuth>,
1147    oauth_config: Option<&crate::mcp::config::ResolvedOAuthClientConfig>,
1148) -> Result<(TcpListener, String, String, Option<String>), McpOAuthError> {
1149    let configured_port = oauth_config.and_then(|cfg| cfg.callback_port);
1150
1151    if let Some(configured_client_id) = oauth_config.and_then(|cfg| cfg.client_id.as_deref()) {
1152        let configured_secret = oauth_config.and_then(|cfg| cfg.client_secret.clone());
1153        let (listener, redirect_uri) = if let Some(port) = configured_port {
1154            bind_loopback_port(port)?
1155        } else if let Some((listener, uri)) = cached
1156            .filter(|entry| entry.client_id.as_deref() == Some(configured_client_id))
1157            .and_then(|entry| entry.redirect_uri.as_deref())
1158            .and_then(|uri| {
1159                let port = extract_loopback_port(uri)?;
1160                TcpListener::bind(("127.0.0.1", port))
1161                    .ok()
1162                    .map(|l| (l, uri.to_string()))
1163            })
1164        {
1165            (listener, uri)
1166        } else {
1167            bind_loopback_ephemeral_with_uri()?
1168        };
1169        return Ok((
1170            listener,
1171            redirect_uri,
1172            configured_client_id.to_string(),
1173            configured_secret,
1174        ));
1175    }
1176
1177    if let Some(port) = configured_port {
1178        let (listener, redirect_uri) = bind_loopback_port(port)?;
1179        if let Some(entry) = cached {
1180            if let Some(ref cid) = entry.client_id {
1181                if entry.redirect_uri.as_deref() == Some(redirect_uri.as_str())
1182                    || auth_meta.registration_endpoint.is_none()
1183                {
1184                    return Ok((
1185                        listener,
1186                        redirect_uri,
1187                        cid.clone(),
1188                        entry.client_secret.clone(),
1189                    ));
1190                }
1191            }
1192        }
1193        let Some(ref reg_endpoint) = auth_meta.registration_endpoint else {
1194            return Err(missing_dcr_error());
1195        };
1196        let reg = register_dynamic_client(agent, reg_endpoint, &redirect_uri)?;
1197        return Ok((listener, redirect_uri, reg.client_id, reg.client_secret));
1198    }
1199
1200    if let Some(entry) = cached {
1201        if let Some(ref cid) = entry.client_id {
1202            if let Some(ref cached_uri) = entry.redirect_uri {
1203                if let Some(port) = extract_loopback_port(cached_uri) {
1204                    if let Ok(listener) = TcpListener::bind(("127.0.0.1", port)) {
1205                        return Ok((
1206                            listener,
1207                            cached_uri.clone(),
1208                            cid.clone(),
1209                            entry.client_secret.clone(),
1210                        ));
1211                    }
1212                }
1213            }
1214            if auth_meta.registration_endpoint.is_none() {
1215                let (listener, redirect_uri) = bind_loopback_ephemeral_with_uri()?;
1216                return Ok((
1217                    listener,
1218                    redirect_uri,
1219                    cid.clone(),
1220                    entry.client_secret.clone(),
1221                ));
1222            }
1223        }
1224    }
1225
1226    let (listener, redirect_uri) = bind_loopback_ephemeral_with_uri()?;
1227
1228    let Some(ref reg_endpoint) = auth_meta.registration_endpoint else {
1229        return Err(missing_dcr_error());
1230    };
1231
1232    let reg = register_dynamic_client(agent, reg_endpoint, &redirect_uri)?;
1233    Ok((listener, redirect_uri, reg.client_id, reg.client_secret))
1234}
1235
1236fn missing_dcr_error() -> McpOAuthError {
1237    McpOAuthError::Registration(
1238        "authorization server does not support Dynamic Client Registration and no OAuth client_id is configured; configure client_id (and client_secret / callback_port) or use a Bearer token Authorization header"
1239            .to_string(),
1240    )
1241}
1242
1243fn bind_loopback_port(port: u16) -> Result<(TcpListener, String), McpOAuthError> {
1244    if port == 0 {
1245        return Err(McpOAuthError::Config(
1246            "OAuth callback_port must be between 1 and 65535".to_string(),
1247        ));
1248    }
1249    let listener = TcpListener::bind(SocketAddr::from(([127, 0, 0, 1], port))).map_err(|e| {
1250        McpOAuthError::Io(format!(
1251            "cannot bind OAuth callback listener on 127.0.0.1:{port} (port may already be in use): {e}"
1252        ))
1253    })?;
1254    Ok((listener, format!("http://127.0.0.1:{port}/callback")))
1255}
1256
1257fn bind_loopback_ephemeral_with_uri() -> Result<(TcpListener, String), McpOAuthError> {
1258    let listener = bind_loopback_ephemeral()?;
1259    let port = listener
1260        .local_addr()
1261        .map_err(|e| McpOAuthError::Io(e.to_string()))?
1262        .port();
1263    Ok((listener, format!("http://127.0.0.1:{port}/callback")))
1264}
1265
1266fn bind_loopback_ephemeral() -> Result<TcpListener, McpOAuthError> {
1267    TcpListener::bind(SocketAddr::from(([127, 0, 0, 1], 0)))
1268        .map_err(|e| McpOAuthError::Io(format!("cannot bind loopback callback listener: {e}")))
1269}
1270
1271fn extract_loopback_port(uri: &str) -> Option<u16> {
1272    let rest = uri.strip_prefix("http://127.0.0.1:")?;
1273    let port_str = rest.split('/').next()?;
1274    port_str.parse::<u16>().ok().filter(|&p| p > 0)
1275}
1276
1277fn register_dynamic_client(
1278    agent: &ureq::Agent,
1279    registration_endpoint: &str,
1280    redirect_uri: &str,
1281) -> Result<ClientRegistrationResponse, McpOAuthError> {
1282    let payload = serde_json::json!({
1283        "client_name": "blyte",
1284        "redirect_uris": [redirect_uri],
1285        "grant_types": ["authorization_code", "refresh_token"],
1286        "response_types": ["code"],
1287        "token_endpoint_auth_method": "none",
1288    });
1289    match agent
1290        .post(registration_endpoint)
1291        .set("Accept", "application/json")
1292        .send_json(payload)
1293    {
1294        Ok(resp) if (200..300).contains(&resp.status()) => {
1295            let parsed: ClientRegistrationResponse = resp.into_json().map_err(|e| {
1296                McpOAuthError::Registration(format!("invalid client registration response: {e}"))
1297            })?;
1298            if parsed.client_id.trim().is_empty() {
1299                return Err(McpOAuthError::Registration(
1300                    "registration response returned empty client_id".to_string(),
1301                ));
1302            }
1303            Ok(parsed)
1304        }
1305        Ok(resp) => Err(McpOAuthError::Registration(format!(
1306            "registration endpoint returned HTTP {}",
1307            resp.status()
1308        ))),
1309        Err(ureq::Error::Status(code, resp)) => {
1310            let detail = extract_oauth_error_detail(resp);
1311            Err(McpOAuthError::Registration(format!("HTTP {code}{detail}")))
1312        }
1313        Err(ureq::Error::Transport(t)) => Err(McpOAuthError::Registration(format!(
1314            "cannot reach registration endpoint: {t}"
1315        ))),
1316    }
1317}
1318
1319#[allow(clippy::too_many_arguments)]
1320fn exchange_authorization_code(
1321    agent: &ureq::Agent,
1322    token_endpoint: &str,
1323    code: &str,
1324    redirect_uri: &str,
1325    client_id: &str,
1326    client_secret: Option<&str>,
1327    code_verifier: &str,
1328    resource: Option<&str>,
1329) -> Result<TokenEndpointResponse, McpOAuthError> {
1330    let mut form: Vec<(&str, &str)> = vec![
1331        ("grant_type", "authorization_code"),
1332        ("code", code),
1333        ("redirect_uri", redirect_uri),
1334        ("client_id", client_id),
1335        ("code_verifier", code_verifier),
1336    ];
1337    if let Some(res) = resource {
1338        form.push(("resource", res));
1339    }
1340    if let Some(secret) = client_secret {
1341        form.push(("client_secret", secret));
1342    }
1343    post_token_form(agent, token_endpoint, &form)
1344}
1345
1346fn post_token_form(
1347    agent: &ureq::Agent,
1348    token_endpoint: &str,
1349    form: &[(&str, &str)],
1350) -> Result<TokenEndpointResponse, McpOAuthError> {
1351    match agent
1352        .post(token_endpoint)
1353        .set("Accept", "application/json")
1354        .send_form(form)
1355    {
1356        Ok(resp) if (200..300).contains(&resp.status()) => {
1357            let value: serde_json::Value = resp.into_json().map_err(|e| {
1358                McpOAuthError::TokenExchange(format!("invalid token response JSON: {e}"))
1359            })?;
1360            parse_token_response_value(&value)
1361        }
1362        Ok(resp) => Err(McpOAuthError::TokenExchange(format!(
1363            "token endpoint returned HTTP {}",
1364            resp.status()
1365        ))),
1366        Err(ureq::Error::Status(code, resp)) => {
1367            let detail = extract_oauth_error_detail(resp);
1368            Err(McpOAuthError::TokenExchange(format!("HTTP {code}{detail}")))
1369        }
1370        Err(ureq::Error::Transport(t)) => Err(McpOAuthError::TokenExchange(format!(
1371            "cannot reach token endpoint: {t}"
1372        ))),
1373    }
1374}
1375
1376fn parse_token_response_value(
1377    value: &serde_json::Value,
1378) -> Result<TokenEndpointResponse, McpOAuthError> {
1379    let obj = value.as_object().ok_or_else(|| {
1380        McpOAuthError::TokenExchange("invalid token response JSON: expected object".to_string())
1381    })?;
1382
1383    if obj.get("ok").and_then(|v| v.as_bool()) == Some(false) {
1384        let err = obj
1385            .get("error")
1386            .and_then(|v| v.as_str())
1387            .filter(|s| !s.is_empty())
1388            .unwrap_or("unknown_error");
1389        let desc = obj
1390            .get("error_description")
1391            .and_then(|v| v.as_str())
1392            .filter(|s| !s.is_empty());
1393        let detail = match desc {
1394            Some(d) => format!("{err}: {d}"),
1395            None => err.to_string(),
1396        };
1397        return Err(McpOAuthError::TokenExchange(format!(
1398            "token endpoint returned error ({detail})"
1399        )));
1400    }
1401
1402    let authed_user = obj.get("authed_user").and_then(|v| v.as_object());
1403    let source = if authed_user
1404        .and_then(|au| au.get("access_token"))
1405        .and_then(|v| v.as_str())
1406        .is_some_and(|s| !s.is_empty())
1407    {
1408        authed_user.unwrap()
1409    } else {
1410        obj
1411    };
1412
1413    let access_token = source
1414        .get("access_token")
1415        .and_then(|v| v.as_str())
1416        .unwrap_or("")
1417        .to_string();
1418    if access_token.is_empty() {
1419        return Err(McpOAuthError::TokenExchange(
1420            "token endpoint returned empty access_token".to_string(),
1421        ));
1422    }
1423
1424    let token_type = source
1425        .get("token_type")
1426        .or_else(|| obj.get("token_type"))
1427        .and_then(|v| v.as_str())
1428        .map(str::to_string);
1429    let expires_in = source
1430        .get("expires_in")
1431        .or_else(|| obj.get("expires_in"))
1432        .and_then(|v| v.as_u64());
1433    let refresh_token = source
1434        .get("refresh_token")
1435        .or_else(|| obj.get("refresh_token"))
1436        .and_then(|v| v.as_str())
1437        .filter(|s| !s.is_empty())
1438        .map(str::to_string);
1439    let scope = source
1440        .get("scope")
1441        .or_else(|| obj.get("scope"))
1442        .and_then(|v| v.as_str())
1443        .map(str::to_string);
1444
1445    Ok(TokenEndpointResponse {
1446        access_token,
1447        token_type,
1448        expires_in,
1449        refresh_token,
1450        scope,
1451    })
1452}
1453
1454fn extract_oauth_error_detail(resp: ureq::Response) -> String {
1455    let Ok(body) = resp.into_string() else {
1456        return String::new();
1457    };
1458    if let Ok(parsed) = serde_json::from_str::<OAuthErrorResponse>(&body) {
1459        if let Some(err) = parsed.error {
1460            if let Some(desc) = parsed.error_description {
1461                return format!(" ({err}: {desc})");
1462            }
1463            return format!(" ({err})");
1464        }
1465    }
1466    String::new()
1467}
1468
1469struct LoopbackCallback {
1470    stream: TcpStream,
1471    params: BTreeMap<String, String>,
1472}
1473
1474fn wait_for_loopback_callback(
1475    listener: &TcpListener,
1476    timeout: Duration,
1477) -> Result<LoopbackCallback, McpOAuthError> {
1478    listener
1479        .set_nonblocking(true)
1480        .map_err(|e| McpOAuthError::Io(format!("cannot configure callback listener: {e}")))?;
1481    let deadline = Instant::now() + timeout;
1482    loop {
1483        match listener.accept() {
1484            Ok((mut stream, _)) => {
1485                let _ = stream.set_nonblocking(false);
1486                let _ = stream.set_read_timeout(Some(Duration::from_secs(5)));
1487                let _ = stream.set_write_timeout(Some(Duration::from_secs(5)));
1488                let Some((path, query)) = read_http_request_target(&mut stream) else {
1489                    continue;
1490                };
1491                if path != "/callback" {
1492                    let _ = send_html_response(
1493                        &mut stream,
1494                        "404 Not Found",
1495                        "Not found",
1496                        "Waiting for OAuth callback on /callback.",
1497                    );
1498                    continue;
1499                }
1500                let params = parse_query_params(&query);
1501                return Ok(LoopbackCallback { stream, params });
1502            }
1503            Err(e) if e.kind() == std::io::ErrorKind::WouldBlock => {
1504                if Instant::now() >= deadline {
1505                    return Err(McpOAuthError::Timeout(
1506                        "timed out waiting for OAuth browser callback".to_string(),
1507                    ));
1508                }
1509                std::thread::sleep(Duration::from_millis(25));
1510            }
1511            Err(e) => {
1512                return Err(McpOAuthError::Callback(format!(
1513                    "callback listener accept error: {e}"
1514                )));
1515            }
1516        }
1517    }
1518}
1519
1520const MAX_CALLBACK_REQUEST_BYTES: usize = 64 * 1024;
1521
1522fn read_http_request_target(stream: &mut TcpStream) -> Option<(String, String)> {
1523    let mut buf = Vec::with_capacity(4096);
1524    let mut chunk = [0u8; 4096];
1525    let mut found_header_end = false;
1526    while buf.len() < MAX_CALLBACK_REQUEST_BYTES {
1527        let remaining = MAX_CALLBACK_REQUEST_BYTES - buf.len();
1528        let to_read = remaining.min(chunk.len());
1529        let n = stream.read(&mut chunk[..to_read]).ok()?;
1530        if n == 0 {
1531            break;
1532        }
1533        buf.extend_from_slice(&chunk[..n]);
1534        if buf.windows(4).any(|w| w == b"\r\n\r\n") {
1535            found_header_end = true;
1536            break;
1537        }
1538    }
1539    if !found_header_end {
1540        return None;
1541    }
1542    let line_end = buf.windows(2).position(|w| w == b"\r\n")?;
1543    let request_line = std::str::from_utf8(&buf[..line_end]).ok()?;
1544    let mut parts = request_line.split_whitespace();
1545    let method = parts.next()?;
1546    if method != "GET" {
1547        return None;
1548    }
1549    let target = parts.next()?;
1550    match target.split_once('?') {
1551        Some((path, query)) => Some((path.to_string(), query.to_string())),
1552        None => Some((target.to_string(), String::new())),
1553    }
1554}
1555
1556fn send_html_response(
1557    stream: &mut TcpStream,
1558    status: &str,
1559    title: &str,
1560    message_html: &str,
1561) -> std::io::Result<()> {
1562    let body = format!(
1563        "<!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>"
1564    );
1565    let response = format!(
1566        "HTTP/1.1 {status}\r\nContent-Type: text/html; charset=utf-8\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}",
1567        body.len()
1568    );
1569    stream.write_all(response.as_bytes())?;
1570    stream.flush()
1571}
1572
1573fn escape_html(input: &str) -> String {
1574    let mut out = String::with_capacity(input.len());
1575    for ch in input.chars() {
1576        match ch {
1577            '&' => out.push_str("&amp;"),
1578            '<' => out.push_str("&lt;"),
1579            '>' => out.push_str("&gt;"),
1580            '"' => out.push_str("&quot;"),
1581            '\'' => out.push_str("&#39;"),
1582            _ => out.push(ch),
1583        }
1584    }
1585    out
1586}
1587
1588pub fn parse_url_parts(url: &str) -> Result<(String, String), McpOAuthError> {
1589    let Some(scheme_end) = url.find("://") else {
1590        return Err(McpOAuthError::Discovery(format!(
1591            "invalid URL (missing scheme): {url}"
1592        )));
1593    };
1594    let rest_start = scheme_end + 3;
1595    let rest = &url[rest_start..];
1596    let authority_end = rest
1597        .find(['/', '?', '#'])
1598        .map(|idx| rest_start + idx)
1599        .unwrap_or(url.len());
1600    if authority_end == rest_start {
1601        return Err(McpOAuthError::Discovery(format!(
1602            "invalid URL (missing host): {url}"
1603        )));
1604    }
1605    let origin = url[..authority_end].to_string();
1606    let after_origin = &url[authority_end..];
1607    let path_raw = after_origin
1608        .split(['?', '#'])
1609        .next()
1610        .unwrap_or_default()
1611        .trim_end_matches('/');
1612    let path = if path_raw.is_empty() || path_raw == "/" {
1613        String::new()
1614    } else {
1615        path_raw.to_string()
1616    };
1617    Ok((origin, path))
1618}
1619
1620fn append_query_params(base_url: &str, params: &[(&str, &str)]) -> String {
1621    let mut out = base_url.to_string();
1622    let mut sep = if base_url.contains('?') { '&' } else { '?' };
1623    for (k, v) in params {
1624        out.push(sep);
1625        sep = '&';
1626        out.push_str(&percent_encode(k));
1627        out.push('=');
1628        out.push_str(&percent_encode(v));
1629    }
1630    out
1631}
1632
1633fn percent_encode(input: &str) -> String {
1634    let mut out = String::with_capacity(input.len());
1635    for b in input.bytes() {
1636        if b.is_ascii_alphanumeric() || matches!(b, b'-' | b'.' | b'_' | b'~') {
1637            out.push(b as char);
1638        } else {
1639            out.push_str(&format!("%{b:02X}"));
1640        }
1641    }
1642    out
1643}
1644
1645fn percent_decode(input: &str) -> String {
1646    let bytes = input.as_bytes();
1647    let mut out = Vec::with_capacity(bytes.len());
1648    let mut i = 0;
1649    while i < bytes.len() {
1650        if bytes[i] == b'%' && i + 2 < bytes.len() {
1651            if let Ok(hex) = std::str::from_utf8(&bytes[i + 1..i + 3]) {
1652                if let Ok(val) = u8::from_str_radix(hex, 16) {
1653                    out.push(val);
1654                    i += 3;
1655                    continue;
1656                }
1657            }
1658        }
1659        if bytes[i] == b'+' {
1660            out.push(b' ');
1661        } else {
1662            out.push(bytes[i]);
1663        }
1664        i += 1;
1665    }
1666    String::from_utf8_lossy(&out).into_owned()
1667}
1668
1669pub fn parse_query_params(query: &str) -> BTreeMap<String, String> {
1670    let mut map = BTreeMap::new();
1671    for pair in query.split('&') {
1672        if pair.is_empty() {
1673            continue;
1674        }
1675        let (k, v) = match pair.split_once('=') {
1676            Some((k, v)) => (percent_decode(k), percent_decode(v)),
1677            None => (percent_decode(pair), String::new()),
1678        };
1679        map.insert(k, v);
1680    }
1681    map
1682}
1683
1684fn resolve_authorization_server_url(
1685    server_url: &str,
1686    resource_meta: Option<&ProtectedResourceMetadata>,
1687) -> Result<String, McpOAuthError> {
1688    let meta = resource_meta.ok_or_else(|| {
1689        McpOAuthError::Discovery(format!(
1690            "could not discover OAuth protected resource metadata for {server_url}"
1691        ))
1692    })?;
1693    meta.authorization_servers
1694        .first()
1695        .filter(|s| !s.trim().is_empty())
1696        .cloned()
1697        .ok_or_else(|| {
1698            McpOAuthError::Discovery(format!(
1699                "OAuth protected resource metadata for {server_url} is missing authorization_servers"
1700            ))
1701        })
1702}
1703
1704fn system_time_secs(now: SystemTime) -> Result<u64, McpOAuthError> {
1705    now.duration_since(UNIX_EPOCH)
1706        .map(|d| d.as_secs())
1707        .map_err(|e| McpOAuthError::Io(format!("system clock is before UNIX_EPOCH: {e}")))
1708}
1709
1710fn system_time_nanos(now: SystemTime) -> Result<u128, McpOAuthError> {
1711    now.duration_since(UNIX_EPOCH)
1712        .map(|d| d.as_nanos())
1713        .map_err(|e| McpOAuthError::Io(format!("system clock is before UNIX_EPOCH: {e}")))
1714}
1715
1716fn now_unix_secs() -> Result<u64, McpOAuthError> {
1717    system_time_secs(SystemTime::now())
1718}
1719
1720fn now_unix_nanos() -> Result<u128, McpOAuthError> {
1721    system_time_nanos(SystemTime::now())
1722}
1723
1724#[cfg(test)]
1725mod tests {
1726    use super::*;
1727
1728    #[test]
1729    fn system_time_before_unix_epoch_returns_error() {
1730        let before_epoch = UNIX_EPOCH - Duration::from_secs(5);
1731        let secs_err = system_time_secs(before_epoch).unwrap_err().to_string();
1732        assert!(
1733            secs_err.contains("UNIX_EPOCH"),
1734            "expected UNIX_EPOCH in error, got: {secs_err}"
1735        );
1736        let nanos_err = system_time_nanos(before_epoch).unwrap_err().to_string();
1737        assert!(
1738            nanos_err.contains("UNIX_EPOCH"),
1739            "expected UNIX_EPOCH in error, got: {nanos_err}"
1740        );
1741    }
1742
1743    #[test]
1744    fn auth_store_save_rejects_missing_parent_or_invalid_file_name() {
1745        let store = McpAuthStore::default();
1746        let err_root = store.save(Path::new("/")).unwrap_err().to_string();
1747        assert!(
1748            err_root.contains("no parent directory"),
1749            "expected missing parent directory error, got: {err_root}"
1750        );
1751        let err_empty = store.save(Path::new("")).unwrap_err().to_string();
1752        assert!(
1753            err_empty.contains("no parent directory"),
1754            "expected missing parent directory error, got: {err_empty}"
1755        );
1756        let err_dotdot = store.save(Path::new("/tmp/..")).unwrap_err().to_string();
1757        assert!(
1758            err_dotdot.contains("missing or non-UTF-8 file name"),
1759            "expected missing file name error, got: {err_dotdot}"
1760        );
1761
1762        #[cfg(unix)]
1763        {
1764            use std::ffi::OsStr;
1765            use std::os::unix::ffi::OsStrExt;
1766            let non_utf8 = Path::new("/tmp").join(OsStr::from_bytes(b"mcp-auth-\xff.json"));
1767            let err_utf8 = store.save(&non_utf8).unwrap_err().to_string();
1768            assert!(
1769                err_utf8.contains("missing or non-UTF-8 file name"),
1770                "expected non-UTF-8 file name error, got: {err_utf8}"
1771            );
1772        }
1773    }
1774
1775    #[test]
1776    fn resolve_authorization_server_url_errors_when_metadata_or_servers_missing() {
1777        let err_none = resolve_authorization_server_url("https://mcp.example.com/mcp", None)
1778            .unwrap_err()
1779            .to_string();
1780        assert!(
1781            err_none.contains("protected resource metadata"),
1782            "expected protected resource metadata error, got: {err_none}"
1783        );
1784
1785        let empty_meta = ProtectedResourceMetadata {
1786            resource: Some("https://mcp.example.com/mcp".to_string()),
1787            authorization_servers: Vec::new(),
1788            scopes_supported: None,
1789        };
1790        let err_empty =
1791            resolve_authorization_server_url("https://mcp.example.com/mcp", Some(&empty_meta))
1792                .unwrap_err()
1793                .to_string();
1794        assert!(
1795            err_empty.contains("authorization_servers"),
1796            "expected authorization_servers error, got: {err_empty}"
1797        );
1798    }
1799
1800    #[test]
1801    fn concurrent_auth_store_modifications_preserve_all_servers() {
1802        let td = tempfile::tempdir().unwrap();
1803        let store_path = td.path().join("mcp-auth.json");
1804        let thread_count = 8usize;
1805        let mut handles = Vec::new();
1806        for idx in 0..thread_count {
1807            let path = store_path.clone();
1808            handles.push(std::thread::spawn(move || {
1809                let server = format!("server-{idx}");
1810                for round in 0..5 {
1811                    McpAuthStore::modify(&path, |store| {
1812                        store.upsert(
1813                            &server,
1814                            StoredServerAuth {
1815                                server_url: format!("https://{server}.example/mcp"),
1816                                access_token: Some(format!("tok-{idx}-{round}")),
1817                                refresh_token: Some(format!("ref-{idx}-{round}")),
1818                                ..StoredServerAuth::default()
1819                            },
1820                        );
1821                        Ok((true, ()))
1822                    })
1823                    .unwrap();
1824                }
1825            }));
1826        }
1827        for h in handles {
1828            h.join().unwrap();
1829        }
1830        let final_store = McpAuthStore::load(&store_path).unwrap();
1831        assert_eq!(final_store.servers.len(), thread_count);
1832        for idx in 0..thread_count {
1833            let server = format!("server-{idx}");
1834            let entry = final_store.get(&server).expect("server entry must exist");
1835            assert_eq!(
1836                entry.access_token.as_deref(),
1837                Some(format!("tok-{idx}-4").as_str())
1838            );
1839            assert_eq!(
1840                entry.refresh_token.as_deref(),
1841                Some(format!("ref-{idx}-4").as_str())
1842            );
1843        }
1844    }
1845
1846    #[test]
1847    fn loopback_callback_reads_multipacket_headers_through_crlf_crlf_before_replying() {
1848        let listener = TcpListener::bind("127.0.0.1:0").unwrap();
1849        let addr = listener.local_addr().unwrap();
1850
1851        let server = std::thread::spawn(move || {
1852            let mut cb = wait_for_loopback_callback(&listener, Duration::from_secs(5)).unwrap();
1853            send_html_response(&mut cb.stream, "200 OK", "Done", "Authenticated").unwrap();
1854            cb.params
1855        });
1856
1857        let mut client = TcpStream::connect(addr).unwrap();
1858        client.set_nodelay(true).unwrap();
1859        client
1860            .set_read_timeout(Some(Duration::from_millis(80)))
1861            .unwrap();
1862
1863        client
1864            .write_all(b"GET /callback?code=abc123&state=xyz789 HTTP/1.1\r\n")
1865            .unwrap();
1866        client.flush().unwrap();
1867        let mut probe = [0u8; 32];
1868        let early1 = client.read(&mut probe);
1869        assert!(
1870            matches!(
1871                early1,
1872                Err(ref e)
1873                    if e.kind() == std::io::ErrorKind::WouldBlock
1874                        || e.kind() == std::io::ErrorKind::TimedOut
1875            ),
1876            "server replied before end of HTTP headers after request line: {early1:?}"
1877        );
1878
1879        client
1880            .write_all(b"Host: 127.0.0.1\r\nUser-Agent: multi-packet-browser\r\n")
1881            .unwrap();
1882        client.flush().unwrap();
1883        let early2 = client.read(&mut probe);
1884        assert!(
1885            matches!(
1886                early2,
1887                Err(ref e)
1888                    if e.kind() == std::io::ErrorKind::WouldBlock
1889                        || e.kind() == std::io::ErrorKind::TimedOut
1890            ),
1891            "server replied before trailing CRLF CRLF: {early2:?}"
1892        );
1893
1894        client.write_all(b"Accept: text/html\r\n\r\n").unwrap();
1895        client.flush().unwrap();
1896
1897        client
1898            .set_read_timeout(Some(Duration::from_secs(5)))
1899            .unwrap();
1900        let mut response = String::new();
1901        client.read_to_string(&mut response).unwrap();
1902        assert!(
1903            response.starts_with("HTTP/1.1 200 OK"),
1904            "unexpected HTTP response: {response}"
1905        );
1906        assert!(response.contains("Done"));
1907
1908        let params = server.join().unwrap();
1909        assert_eq!(params.get("code").map(String::as_str), Some("abc123"));
1910        assert_eq!(params.get("state").map(String::as_str), Some("xyz789"));
1911    }
1912
1913    #[test]
1914    fn read_http_request_target_rejects_truncated_requests_on_eof() {
1915        for truncated in [
1916            &b"GET /callback?code=abc123&state=xyz789 HTTP/1.1"[..],
1917            &b"GET /callback?code=abc123&state=xyz789 HTTP/1.1\r\nHost: 127.0.0.1\r\n"[..],
1918            &b""[..],
1919        ] {
1920            let listener = TcpListener::bind("127.0.0.1:0").unwrap();
1921            let addr = listener.local_addr().unwrap();
1922            let payload = truncated.to_vec();
1923
1924            let client_handle = std::thread::spawn(move || {
1925                let mut client = TcpStream::connect(addr).unwrap();
1926                client.write_all(&payload).unwrap();
1927                client.flush().unwrap();
1928                client.shutdown(std::net::Shutdown::Write).unwrap();
1929            });
1930
1931            let (mut server_stream, _) = listener.accept().unwrap();
1932            server_stream
1933                .set_read_timeout(Some(Duration::from_secs(2)))
1934                .unwrap();
1935            assert_eq!(read_http_request_target(&mut server_stream), None);
1936            client_handle.join().unwrap();
1937        }
1938    }
1939
1940    #[test]
1941    fn loopback_callback_ignores_truncated_request_and_accepts_complete_request() {
1942        let listener = TcpListener::bind("127.0.0.1:0").unwrap();
1943        let addr = listener.local_addr().unwrap();
1944
1945        let server = std::thread::spawn(move || {
1946            let mut cb = wait_for_loopback_callback(&listener, Duration::from_secs(5)).unwrap();
1947            send_html_response(&mut cb.stream, "200 OK", "Done", "Authenticated").unwrap();
1948            cb.params
1949        });
1950
1951        {
1952            let mut truncated = TcpStream::connect(addr).unwrap();
1953            truncated
1954                .set_read_timeout(Some(Duration::from_secs(2)))
1955                .unwrap();
1956            truncated
1957                .write_all(b"GET /callback?code=bad&state=bad HTTP/1.1")
1958                .unwrap();
1959            truncated.flush().unwrap();
1960            truncated.shutdown(std::net::Shutdown::Write).unwrap();
1961            let mut resp = Vec::new();
1962            truncated.read_to_end(&mut resp).unwrap();
1963            assert!(resp.is_empty());
1964        }
1965
1966        let mut valid = TcpStream::connect(addr).unwrap();
1967        valid
1968            .write_all(b"GET /callback?code=good&state=ok HTTP/1.1\r\nHost: 127.0.0.1\r\n\r\n")
1969            .unwrap();
1970        valid.flush().unwrap();
1971
1972        let mut response = String::new();
1973        valid.read_to_string(&mut response).unwrap();
1974        assert!(response.starts_with("HTTP/1.1 200 OK"));
1975
1976        let params = server.join().unwrap();
1977        assert_eq!(params.get("code").map(String::as_str), Some("good"));
1978        assert_eq!(params.get("state").map(String::as_str), Some("ok"));
1979    }
1980
1981    #[test]
1982    fn discover_authorization_server_rejects_missing_or_empty_issuer() {
1983        for body_fn in [
1984            |base: &str| {
1985                serde_json::json!({
1986                    "authorization_endpoint": format!("{base}/authorize"),
1987                    "token_endpoint": format!("{base}/token"),
1988                    "code_challenge_methods_supported": ["S256"]
1989                })
1990                .to_string()
1991            },
1992            |base: &str| {
1993                serde_json::json!({
1994                    "issuer": "   ",
1995                    "authorization_endpoint": format!("{base}/authorize"),
1996                    "token_endpoint": format!("{base}/token"),
1997                    "code_challenge_methods_supported": ["S256"]
1998                })
1999                .to_string()
2000            },
2001        ] {
2002            let listener = TcpListener::bind("127.0.0.1:0").unwrap();
2003            let addr = listener.local_addr().unwrap();
2004            let base = format!("http://{addr}");
2005            let payload = body_fn(&base);
2006            let stop = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));
2007            let stop_flag = std::sync::Arc::clone(&stop);
2008            listener.set_nonblocking(true).unwrap();
2009
2010            let handle = std::thread::spawn(move || {
2011                while !stop_flag.load(std::sync::atomic::Ordering::SeqCst) {
2012                    match listener.accept() {
2013                        Ok((mut stream, _)) => {
2014                            let _ = stream.set_nonblocking(false);
2015                            let _ = stream.set_read_timeout(Some(Duration::from_secs(1)));
2016                            let mut buf = [0u8; 4096];
2017                            let n = stream.read(&mut buf).unwrap_or(0);
2018                            let req = String::from_utf8_lossy(&buf[..n]);
2019                            let path = req
2020                                .lines()
2021                                .next()
2022                                .and_then(|l| l.split_whitespace().nth(1))
2023                                .unwrap_or("");
2024                            let resp = if path == "/.well-known/oauth-authorization-server" {
2025                                format!(
2026                                    "HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}",
2027                                    payload.len(),
2028                                    payload
2029                                )
2030                            } else {
2031                                "HTTP/1.1 404 Not Found\r\nContent-Length: 0\r\nConnection: close\r\n\r\n"
2032                                    .to_string()
2033                            };
2034                            let _ = stream.write_all(resp.as_bytes());
2035                            let _ = stream.flush();
2036                        }
2037                        Err(e) if e.kind() == std::io::ErrorKind::WouldBlock => {
2038                            std::thread::sleep(Duration::from_millis(5));
2039                        }
2040                        Err(_) => break,
2041                    }
2042                }
2043            });
2044
2045            let agent = build_http_agent(Duration::from_secs(2));
2046            let err = discover_authorization_server(&agent, &base)
2047                .expect_err("metadata missing required issuer must fail")
2048                .to_string();
2049            stop.store(true, std::sync::atomic::Ordering::SeqCst);
2050            let _ = handle.join();
2051
2052            assert!(
2053                err.contains("issuer"),
2054                "expected clear error mentioning missing issuer, got: {err}"
2055            );
2056        }
2057    }
2058}