返回 CodeWhale
oauth.rs
根目录 / crates / engine / src / mcp / oauth.rs
1 use super::http_client::McpHttpClient;
2 use crate::mcp::McpServerConfigExt;
3 use codewhale_net::network_policy::NetworkPolicyDecider;
4 use codewhale_runtime::credentials::AuthContext;
5 use std::collections::HashMap;
6 use std::sync::Arc;
7 use std::time::{Duration, SystemTime, UNIX_EPOCH};
8
9 use anyhow::{Context, Result, anyhow, bail};
10 use base64::Engine as _;
11 use base64::engine::general_purpose::URL_SAFE_NO_PAD;
12 use oauth2::TokenResponse;
13 use reqwest::Url;
14 use reqwest::header::{CONTENT_TYPE, HeaderMap, HeaderName, HeaderValue};
15 use rmcp::transport::AuthorizationManager;
16 use rmcp::transport::AuthorizationSession;
17 use rmcp::transport::auth::{
18 AuthError, AuthorizationRequest, CredentialStore, InMemoryCredentialStore, InMemoryStateStore,
19 OAuthHttpClient, OAuthHttpClientError, OAuthHttpClientFuture, OAuthHttpRedirectPolicy,
20 OAuthHttpRequest, OAuthState, OAuthTokenResponse, StateStore, StoredCredentials,
21 };
22 use serde::{Deserialize, Serialize};
23 use sha2::{Digest, Sha256};
24 use tokio::io::{AsyncReadExt, AsyncWriteExt};
25 use tokio::net::TcpListener;
26 use tokio::sync::{Mutex, oneshot};
27 use tokio::time::timeout;
28 use tokio_util::sync::CancellationToken;
29
30 use super::McpServerConfig;
31
32 const REFRESH_SKEW_MILLIS: u64 = 30_000;
33
34 #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
35 #[serde(rename_all = "snake_case")]
36 pub enum McpAuthStatus {
37 Unsupported,
38 NotLoggedIn,
39 BearerToken,
40 OAuth,
41 }
42
43 impl std::fmt::Display for McpAuthStatus {
44 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
45 let text = match self {
46 Self::Unsupported => "Unsupported",
47 Self::NotLoggedIn => "Not logged in",
48 Self::BearerToken => "Bearer token",
49 Self::OAuth => "OAuth",
50 };
51 f.write_str(text)
52 }
53 }
54
55 /// Context for a failed token refresh. An auth-required failure already
56 /// flips the server to `◆ auth required` and offers the login tool; any
57 /// other failure (a token endpoint answering something the client could
58 /// not parse, a transport error) names the same remedy in words, because
59 /// the operator otherwise sees only the provider's parse error (#5926).
60 /// When the token endpoint did answer, its receipt (status line,
61 /// content-type, masked excerpt) rides along so a provider outage — an HTML
62 /// 502 page — reads differently from a parser defect on JSON it should
63 /// have accepted.
64 fn refresh_failure_context(
65 server_name: &str,
66 names_remedy: bool,
67 receipt: Option<&TokenEndpointReceipt>,
68 ) -> String {
69 if names_remedy {
70 let answered =
71 receipt.map_or_else(String::new, |receipt| format!(" (it answered {receipt})"));
72 format!(
73 "refreshing MCP OAuth token for server {server_name}: the token endpoint did not answer the way the client expects{answered}; \
74 if this persists, run `codewhale mcp login {server_name}` (or `/mcp login {server_name}`) to re-authorize"
75 )
76 } else {
77 format!("refreshing MCP OAuth token for server {server_name}")
78 }
79 }
80
81 /// Longest excerpt of a token-endpoint body a refresh failure keeps.
82 const TOKEN_RECEIPT_EXCERPT_BYTES: usize = 200;
83
84 /// rmcp's own cap on an OAuth response body, mirrored so the recording
85 /// client refuses the same oversized answers the stock one does.
86 const MAX_OAUTH_HTTP_RESPONSE_BODY_BYTES: usize = 1024 * 1024;
87
88 /// Response fields whose values are credentials. Their values are masked
89 /// before any body excerpt is kept; the field names themselves are not
90 /// secrets and stay so the operator can see which fields the answer had.
91 const OAUTH_SECRET_FIELDS: &[&str] = &[
92 "access_token",
93 "refresh_token",
94 "client_secret",
95 "id_token",
96 "authorization",
97 ];
98
99 /// What the token endpoint actually answered. rmcp collapses an
100 /// unparseable answer to `Failed to parse server response` and drops the
101 /// body; this is the receipt it drops, with every credential-shaped value
102 /// masked and the body cut to its first [`TOKEN_RECEIPT_EXCERPT_BYTES`].
103 #[derive(Debug, Clone, PartialEq, Eq)]
104 pub struct TokenEndpointReceipt {
105 status: u16,
106 reason: Option<&'static str>,
107 content_type: Option<String>,
108 excerpt: String,
109 }
110
111 impl TokenEndpointReceipt {
112 fn from_response(status: reqwest::StatusCode, headers: &HeaderMap, body: &[u8]) -> Self {
113 let content_type = headers
114 .get(CONTENT_TYPE)
115 .and_then(|value| value.to_str().ok())
116 .map(str::trim)
117 .filter(|value| !value.is_empty())
118 .map(str::to_string);
119 Self {
120 status: status.as_u16(),
121 reason: status.canonical_reason(),
122 content_type,
123 excerpt: token_response_excerpt(body),
124 }
125 }
126 }
127
128 impl std::fmt::Display for TokenEndpointReceipt {
129 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
130 write!(f, "HTTP {}", self.status)?;
131 if let Some(reason) = self.reason {
132 write!(f, " {reason}")?;
133 }
134 match self.content_type.as_deref() {
135 Some(content_type) => write!(f, " ({content_type})")?,
136 None => f.write_str(" (no content-type)")?,
137 }
138 if self.excerpt.is_empty() {
139 f.write_str(" with an empty body")
140 } else {
141 write!(f, ": {}", self.excerpt)
142 }
143 }
144 }
145
146 /// Masked, whitespace-collapsed, byte-capped excerpt of a token-endpoint
147 /// body. Masking runs before the cut so a truncated credential never leaks
148 /// its prefix.
149 fn token_response_excerpt(body: &[u8]) -> String {
150 let masked = mask_oauth_secrets(&String::from_utf8_lossy(body));
151 let collapsed = masked.split_whitespace().collect::<Vec<_>>().join(" ");
152 if collapsed.len() <= TOKEN_RECEIPT_EXCERPT_BYTES {
153 return collapsed;
154 }
155 let mut end = TOKEN_RECEIPT_EXCERPT_BYTES;
156 while !collapsed.is_char_boundary(end) {
157 end -= 1;
158 }
159 format!("{}…", &collapsed[..end])
160 }
161
162 fn is_word_byte(byte: u8) -> bool {
163 byte.is_ascii_alphanumeric() || byte == b'_'
164 }
165
166 /// Replace every credential-shaped value in `text` with `***`: JSON
167 /// members (`"access_token": "…"`), form/query pairs (`refresh_token=…`),
168 /// and bearer schemes (`Bearer …`). Field names, separators and everything
169 /// else survive so the shape of the answer stays readable.
170 pub fn mask_oauth_secrets(text: &str) -> String {
171 let lower = text.to_ascii_lowercase();
172 let bytes = text.as_bytes();
173 let mut out = String::with_capacity(text.len());
174 let mut index = 0;
175 while index < text.len() {
176 let at_word_start = index == 0 || !is_word_byte(bytes[index - 1]);
177 if at_word_start
178 && let Some((value_start, value_end)) = secret_value_span(text, &lower, index)
179 {
180 out.push_str(&text[index..value_start]);
181 out.push_str("***");
182 index = value_end;
183 continue;
184 }
185 let ch = text[index..]
186 .chars()
187 .next()
188 .expect("index sits on a char boundary");
189 out.push(ch);
190 index += ch.len_utf8();
191 }
192 out
193 }
194
195 /// The byte span of the secret value that starts at `start`, if a secret
196 /// field or bearer scheme begins there. Every scan step consumes ASCII
197 /// bytes only, so both ends land on char boundaries.
198 fn secret_value_span(text: &str, lower: &str, start: usize) -> Option<(usize, usize)> {
199 let bytes = text.as_bytes();
200 let skip_spaces = |mut cursor: usize| {
201 while bytes
202 .get(cursor)
203 .is_some_and(|byte| *byte == b' ' || *byte == b'\t')
204 {
205 cursor += 1;
206 }
207 cursor
208 };
209 let unquoted_end = |mut cursor: usize| {
210 while bytes.get(cursor).is_some_and(|byte| {
211 !matches!(byte, b'&' | b',' | b';' | b'}' | b'"' | b'\'') && !byte.is_ascii_whitespace()
212 }) {
213 cursor += 1;
214 }
215 cursor
216 };
217 if lower[start..].starts_with("bearer ") {
218 let value_start = skip_spaces(start + "bearer".len());
219 let value_end = unquoted_end(value_start);
220 return (value_end > value_start).then_some((value_start, value_end));
221 }
222 for field in OAUTH_SECRET_FIELDS {
223 if !lower[start..].starts_with(field) {
224 continue;
225 }
226 let mut cursor = start + field.len();
227 if bytes.get(cursor).is_some_and(|byte| is_word_byte(*byte)) {
228 continue;
229 }
230 if bytes.get(cursor) == Some(&b'"') {
231 cursor += 1;
232 }
233 cursor = skip_spaces(cursor);
234 match bytes.get(cursor) {
235 Some(b':' | b'=') => cursor += 1,
236 _ => continue,
237 }
238 cursor = skip_spaces(cursor);
239 if bytes.get(cursor) == Some(&b'"') {
240 let value_start = cursor + 1;
241 let mut value_end = value_start;
242 while let Some(byte) = bytes.get(value_end) {
243 match byte {
244 b'\\' => value_end += 2,
245 b'"' => break,
246 _ => value_end += 1,
247 }
248 }
249 return Some((value_start, value_end.min(text.len())));
250 }
251 // An unquoted `Authorization: Bearer <token>` carries its scheme in
252 // front of the credential; the whole value is the secret.
253 let value_start = cursor;
254 let mut value_end = unquoted_end(cursor);
255 if matches!(lower[value_start..value_end].as_ref(), "bearer" | "basic")
256 && bytes.get(value_end) == Some(&b' ')
257 {
258 value_end = unquoted_end(skip_spaces(value_end));
259 }
260 return Some((value_start, value_end));
261 }
262 None
263 }
264
265 /// Shared guarded HTTP client for discovery, login and stored credentials.
266 /// It honors each OAuth operation's redirect policy, caps response bodies and keeps
267 /// the receipt of the latest token-endpoint answer (every token request is
268 /// a POST; discovery is GET) so a failed refresh can say what came back.
269 pub struct RecordingOAuthHttpClient {
270 client: McpHttpClient,
271 last_token_response: std::sync::Mutex<Option<TokenEndpointReceipt>>,
272 }
273
274 impl RecordingOAuthHttpClient {
275 fn new(client: McpHttpClient) -> Self {
276 Self {
277 client,
278 last_token_response: std::sync::Mutex::new(None),
279 }
280 }
281
282 fn take_token_endpoint_receipt(&self) -> Option<TokenEndpointReceipt> {
283 self.last_token_response
284 .lock()
285 .unwrap_or_else(std::sync::PoisonError::into_inner)
286 .take()
287 }
288 }
289
290 impl OAuthHttpClient for RecordingOAuthHttpClient {
291 fn execute(&self, request: OAuthHttpRequest) -> OAuthHttpClientFuture<'_> {
292 Box::pin(async move {
293 let OAuthHttpRequest {
294 request,
295 timeout,
296 redirect_policy,
297 ..
298 } = request;
299 let is_token_request = request.method() == reqwest::Method::POST;
300 let mut request = reqwest::Request::try_from(request)
301 .map_err(|error| Box::new(error) as OAuthHttpClientError)?;
302 if let Some(timeout) = timeout {
303 *request.timeout_mut() = Some(timeout);
304 }
305 let mut response = self
306 .client
307 .execute(
308 request,
309 matches!(redirect_policy, OAuthHttpRedirectPolicy::Follow),
310 )
311 .await
312 .map_err(|error| -> OAuthHttpClientError { error.into() })?;
313 let status = response.status();
314 let version = response.version();
315 let headers = response.headers().clone();
316 let mut body = Vec::new();
317 while let Some(chunk) = response
318 .chunk()
319 .await
320 .map_err(|error| Box::new(error) as OAuthHttpClientError)?
321 {
322 if chunk.len() > MAX_OAUTH_HTTP_RESPONSE_BODY_BYTES - body.len() {
323 return Err(anyhow!(
324 "OAuth HTTP response body exceeds {MAX_OAUTH_HTTP_RESPONSE_BODY_BYTES} bytes"
325 )
326 .into());
327 }
328 body.extend_from_slice(&chunk);
329 }
330 if is_token_request {
331 *self
332 .last_token_response
333 .lock()
334 .unwrap_or_else(std::sync::PoisonError::into_inner) =
335 Some(TokenEndpointReceipt::from_response(status, &headers, &body));
336 }
337 let mut builder = oauth2::http::Response::builder()
338 .status(status)
339 .version(version);
340 for (name, value) in &headers {
341 builder = builder.header(name, value);
342 }
343 builder
344 .body(body)
345 .map_err(|error| Box::new(error) as OAuthHttpClientError)
346 })
347 }
348 }
349
350 pub fn error_looks_auth_required(error: &anyhow::Error) -> bool {
351 error
352 .downcast_ref::<super::McpCredentialConfigurationError>()
353 .is_none()
354 && error_text_looks_auth_required(&format!("{error:#}"))
355 }
356
357 /// Whether the error chain carries the OAuth `invalid_grant` code: the
358 /// authorization server definitively rejected the presented grant (typically
359 /// a stale or already-rotated refresh token).
360 fn error_is_invalid_grant(error: &anyhow::Error) -> bool {
361 format!("{error:#}")
362 .to_ascii_lowercase()
363 .contains("invalid_grant")
364 }
365
366 /// The one auth-required classifier every surface consults: the pool's
367 /// `◆ auth required` state, the session-boot row, the `/mcp` manager
368 /// recovery verb, and the synthetic `mcp_<server>_authenticate` tool all
369 /// derive from this predicate so a failure is never "needs login" on one
370 /// surface and "failed" on another. `invalid_grant` belongs here because the
371 /// authorization server has definitively rejected the stored grant — only a
372 /// fresh login recovers it.
373 pub fn error_text_looks_auth_required(text: &str) -> bool {
374 let text = text.to_ascii_lowercase();
375 if text.contains(&super::MCP_CREDENTIAL_CONFIGURATION_ERROR_PREFIX.to_ascii_lowercase()) {
376 return false;
377 }
378 let status_401 = text_names_http_status(&text, "401");
379 // `auth required` and `requires oauth` are anchored to the shapes this
380 // product and the Codex-compatible managers actually emit (`◆ auth
381 // required`, `requires OAuth login/authentication/reauthentication`) —
382 // bare substrings would misclassify incidental server errors like
383 // "auth required parameter is missing".
384 status_401
385 || text.contains("unauthorized")
386 || text.contains("authentication_required")
387 || text.contains("invalid_grant")
388 // rmcp 3.2 collapsed several unrecoverable refresh outcomes onto
389 // `AuthError::AuthorizationRequired` (Display: "OAuth authorization
390 // required") — a stored credential with no usable refresh grant, and
391 // every refresh the server definitively rejected. In 2.2 those
392 // arrived as `TokenRefreshFailed("No refresh token available")`, which
393 // no surface recognised. The full phrase is matched so it stays
394 // anchored to rmcp's own wording.
395 || text.contains("oauth authorization required")
396 || text.contains("◆ auth required")
397 || text.contains("requires oauth login")
398 || text.contains("requires oauth authentication")
399 || text.contains("requires oauth reauthentication")
400 || text.contains("not logged in")
401 || text.contains("not-logged-in")
402 || text.contains("re-authorize")
403 || text.contains("/mcp login")
404 || text.contains("mcp login")
405 }
406
407 /// Whether error text names an HTTP status as a status, not as digits inside
408 /// an address or a larger number. Transport errors carry the URL they failed
409 /// on, so a bare substring match read the reset on
410 /// `http://127.0.0.1:50401/mcp` as a 401 and put a healthy server into
411 /// `◆ auth required` — whenever the ephemeral port happened to contain it.
412 pub fn text_names_http_status(text: &str, status: &str) -> bool {
413 text.split_whitespace()
414 .filter(|token| !token.contains("://"))
415 .any(|token| {
416 token
417 .split(|c: char| !c.is_ascii_digit())
418 .any(|digits| digits == status)
419 })
420 }
421
422 pub fn auth_required_login_hint(server_name: &str) -> String {
423 format!(
424 "MCP server '{server_name}' requires OAuth authentication. Run `codewhale mcp login {server_name}` to authenticate."
425 )
426 }
427
428 /// The one recovery sentence for a server in the `◆ auth required` state,
429 /// chosen by how that server is allowed to authenticate. OAuth-servable
430 /// servers get the login command; plugin-contributed servers (OAuth is
431 /// disabled for them by review policy) and servers with a manual
432 /// Authorization configuration are told which environment-backed
433 /// credential to supply instead, so `/mcp login` is never named for a
434 /// server it would refuse. Environment variable *names* are not secrets;
435 /// their values never appear here.
436 pub fn auth_required_recovery_hint(server_name: &str, server: &McpServerConfig) -> String {
437 let mut env_vars: Vec<&str> = server
438 .env_headers
439 .values()
440 .map(String::as_str)
441 .chain(server.bearer_token_env_var.as_deref())
442 .collect();
443 env_vars.sort_unstable();
444 env_vars.dedup();
445 let credential_source = if env_vars.is_empty() {
446 "its configured Authorization header".to_string()
447 } else {
448 format!(
449 "the environment variable{} {}",
450 if env_vars.len() == 1 { "" } else { "s" },
451 env_vars.join(", ")
452 )
453 };
454 if let Some(source) = server.reviewed_plugin_source() {
455 return format!(
456 "MCP server '{server_name}' is contributed by plugin '{}' and its credential comes from {credential_source} (OAuth login is disabled for plugin-contributed servers). Set the credential, then run `/mcp reload`.",
457 source.authority.plugin_name
458 );
459 }
460 if server_has_manual_authorization(server) {
461 return format!(
462 "MCP server '{server_name}' authenticates with {credential_source}; the server rejected that credential. Correct it, then run `/mcp reload`."
463 );
464 }
465 auth_required_login_hint(server_name)
466 }
467
468 /// TUI recovery for a stale Streamable HTTP OAuth session. `/mcp auth` is not a
469 /// command; login is `/mcp login <name>` (CLI: `codewhale mcp login <name>`).
470 pub fn tui_reauth_hint() -> &'static str {
471 "Re-authorize this server (/mcp login <name>) to continue."
472 }
473
474 pub fn tui_reauth_refresh_failed_hint() -> &'static str {
475 "Re-authorize this server (/mcp login <name>) or configure a fresh bearer token."
476 }
477
478 #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
479 pub struct McpOAuthBinding {
480 pub issuer: String,
481 pub resource: String,
482 }
483
484 #[derive(Debug, Clone, Serialize, Deserialize)]
485 pub struct StoredMcpOAuthTokens {
486 pub server_name: String,
487 pub url: String,
488 pub client_id: String,
489 #[serde(default)]
490 pub binding: Option<McpOAuthBinding>,
491 pub token_response: WrappedOAuthTokenResponse,
492 #[serde(default)]
493 pub expires_at: Option<u64>,
494 }
495
496 impl PartialEq for StoredMcpOAuthTokens {
497 fn eq(&self, other: &Self) -> bool {
498 if self.server_name != other.server_name
499 || self.url != other.url
500 || self.client_id != other.client_id
501 || self.binding != other.binding
502 || self.expires_at != other.expires_at
503 {
504 return false;
505 }
506 if self.expires_at.is_none() {
507 return self.token_response == other.token_response;
508 }
509 // Loading a credential derives a decreasing expires_in from the
510 // durable expires_at. That countdown is not a peer token rotation:
511 // comparing it would adopt the same rejected grant after one second
512 // instead of invalidating it. Preserve every other response field.
513 let mut left = self.token_response.clone();
514 let mut right = other.token_response.clone();
515 left.0.set_expires_in(None);
516 right.0.set_expires_in(None);
517 left == right
518 }
519 }
520
521 #[derive(Debug, Clone, Serialize, Deserialize)]
522 pub struct WrappedOAuthTokenResponse(pub OAuthTokenResponse);
523
524 impl PartialEq for WrappedOAuthTokenResponse {
525 fn eq(&self, other: &Self) -> bool {
526 match (serde_json::to_string(self), serde_json::to_string(other)) {
527 (Ok(left), Ok(right)) => left == right,
528 _ => false,
529 }
530 }
531 }
532
533 #[derive(Clone)]
534 pub struct McpOAuthRuntime {
535 inner: Arc<McpOAuthRuntimeInner>,
536 }
537
538 struct McpOAuthRuntimeInner {
539 server_name: String,
540 url: String,
541 binding: McpOAuthBinding,
542 configured_client_id: Option<String>,
543 manager: Arc<Mutex<AuthorizationManager>>,
544 last_tokens: Mutex<Option<StoredMcpOAuthTokens>>,
545 /// Why the held credential was invalidated (the provider's error code,
546 /// e.g. `invalid_grant`, or `logged_out` when a refresh found the stored
547 /// entry removed), so every later failure names the cause even though
548 /// the rejected grant is never replayed. `None` while a credential is
549 /// held.
550 rejection: Mutex<Option<String>>,
551 /// The HTTP client the runtime was built with, shared with the manager
552 /// so an adopted on-disk rotation rebuilds it with identical HTTP shape
553 /// and a failed refresh can read the token endpoint's receipt.
554 http_client: Arc<RecordingOAuthHttpClient>,
555 }
556
557 #[derive(Debug, Clone, PartialEq, Eq)]
558 pub struct McpOAuthDiscovery {
559 pub scopes_supported: Option<Vec<String>>,
560 }
561
562 #[derive(Debug, Clone, PartialEq, Eq)]
563 pub struct ResolvedMcpOAuthScopes {
564 pub scopes: Vec<String>,
565 pub source: McpOAuthScopesSource,
566 }
567
568 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
569 pub enum McpOAuthScopesSource {
570 Explicit,
571 Configured,
572 Discovered,
573 Empty,
574 }
575
576 #[derive(Debug, Clone, PartialEq, Eq)]
577 pub struct OAuthProviderError {
578 error: Option<String>,
579 error_description: Option<String>,
580 }
581
582 impl OAuthProviderError {
583 fn new(error: Option<String>, error_description: Option<String>) -> Self {
584 Self {
585 error,
586 error_description,
587 }
588 }
589 }
590
591 impl std::fmt::Display for OAuthProviderError {
592 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
593 match (self.error.as_deref(), self.error_description.as_deref()) {
594 (Some(error), Some(description)) => {
595 write!(f, "OAuth provider returned `{error}`: {description}")
596 }
597 (Some(error), None) => write!(f, "OAuth provider returned `{error}`"),
598 (None, Some(description)) => write!(f, "OAuth error: {description}"),
599 (None, None) => write!(f, "OAuth provider returned an error"),
600 }
601 }
602 }
603
604 impl std::error::Error for OAuthProviderError {}
605
606 /// Build an `AuthorizationManager` preloaded with stored credentials, the
607 /// shared construction step for initial load and for adopting a credential
608 /// that another process rotated on disk.
609 async fn manager_from_stored_tokens(
610 url: &str,
611 tokens: &StoredMcpOAuthTokens,
612 http_client: &Arc<RecordingOAuthHttpClient>,
613 ) -> Result<AuthorizationManager> {
614 let binding = tokens.binding.as_ref().ok_or_else(|| anyhow!(
615 "Stored MCP credential requires OAuth reauthentication: issuer/resource binding is absent; run /mcp login. The old credential was preserved."
616 ))?;
617 anyhow::ensure!(
618 tokens.url == url,
619 "Stored MCP credential requires OAuth reauthentication: server URL changed"
620 );
621 let (mut manager, discovered) = prepare_authorization_manager(url, http_client).await?;
622 anyhow::ensure!(
623 *binding == discovered,
624 "Stored MCP credential requires OAuth reauthentication: authorization issuer or resource changed. The old credential was preserved."
625 );
626 let store = InMemoryCredentialStore::new();
627 store
628 .save(
629 StoredCredentials::new(
630 tokens.client_id.clone(),
631 Some(tokens.token_response.0.clone()),
632 tokens
633 .token_response
634 .0
635 .scopes()
636 .map(|scopes| {
637 scopes
638 .iter()
639 .map(|scope| scope.as_str().to_owned())
640 .collect()
641 })
642 .unwrap_or_default(),
643 Some(
644 SystemTime::now()
645 .duration_since(UNIX_EPOCH)
646 .unwrap_or_default()
647 .as_secs(),
648 ),
649 )
650 .with_issuer(Some(binding.issuer.clone())),
651 )
652 .await?;
653 manager.set_credential_store(store);
654 anyhow::ensure!(
655 manager.initialize_from_store().await?,
656 "Stored MCP credential requires OAuth reauthentication"
657 );
658 Ok(manager)
659 }
660
661 async fn prepare_authorization_manager(
662 url: &str,
663 http_client: &Arc<RecordingOAuthHttpClient>,
664 ) -> Result<(AuthorizationManager, McpOAuthBinding)> {
665 let client = Arc::clone(http_client) as Arc<dyn OAuthHttpClient>;
666 let mut manager = AuthorizationManager::new_with_oauth_http_client(url, client).await?;
667 let resolution = manager.resolve_metadata().await?;
668 anyhow::ensure!(
669 resolution.source.is_discovered(),
670 "MCP OAuth requires published authorization server metadata"
671 );
672 let issuer = resolution
673 .metadata
674 .issuer
675 .clone()
676 .filter(|issuer| !issuer.is_empty())
677 .ok_or_else(|| anyhow!("MCP OAuth metadata omitted its validated issuer"))?;
678 manager.set_metadata(resolution.metadata);
679 manager.configure_client_id("codewhale-binding-preparation")?;
680 let probe_url = manager.get_authorization_url(&[]).await?;
681 let resource = authorization_request_parameter(&probe_url, "resource")?;
682 manager.set_state_store(InMemoryStateStore::new());
683 Ok((manager, McpOAuthBinding { issuer, resource }))
684 }
685
686 fn authorization_request_parameter(url: &str, key: &str) -> Result<String> {
687 let parsed = Url::parse(url).context("invalid SDK OAuth authorization URL")?;
688 let mut values = parsed.query_pairs().filter(|(name, _)| name == key);
689 let value = values
690 .next()
691 .map(|(_, value)| value.into_owned())
692 .filter(|value| !value.is_empty())
693 .ok_or_else(|| anyhow!("SDK OAuth authorization URL omitted {key}"))?;
694 anyhow::ensure!(
695 values.next().is_none(),
696 "SDK OAuth authorization URL duplicated {key}"
697 );
698 Ok(value)
699 }
700
701 impl McpOAuthRuntime {
702 #[cfg(test)]
703 pub(super) async fn from_server_config(
704 server_name: &str,
705 server: &McpServerConfig,
706 default_headers: HeaderMap,
707 ) -> Result<Option<Self>> {
708 if server.reviewed_plugin.is_some() || server_has_manual_authorization(server) {
709 return Ok(None);
710 }
711 let Some(url) = server.url.as_deref() else {
712 return Ok(None);
713 };
714 let client = oauth_http_client(server, url, None)?;
715 Self::from_server_config_with_client(server_name, server, default_headers, client).await
716 }
717
718 pub(super) async fn from_server_config_with_client(
719 server_name: &str,
720 server: &McpServerConfig,
721 default_headers: HeaderMap,
722 client: McpHttpClient,
723 ) -> Result<Option<Self>> {
724 if server.reviewed_plugin.is_some() {
725 return Ok(None);
726 }
727 let Some(url) = server.url.as_deref() else {
728 return Ok(None);
729 };
730 if server_has_manual_authorization(server) {
731 return Ok(None);
732 }
733 let Some(tokens) = load_oauth_tokens(server_name, url)? else {
734 return Ok(None);
735 };
736 anyhow::ensure!(
737 tokens.server_name == server_name,
738 "Stored MCP credential requires OAuth reauthentication: server identity changed"
739 );
740 if let Some(binding) = tokens.binding.as_ref() {
741 if let Some(issuer) = server
742 .oauth
743 .as_ref()
744 .and_then(|oauth| oauth.issuer.as_deref())
745 {
746 anyhow::ensure!(
747 issuer == binding.issuer,
748 "Configured MCP OAuth issuer changed; requires OAuth reauthentication"
749 );
750 }
751 if let Some(resource) = server.oauth_resource.as_deref() {
752 anyhow::ensure!(
753 resource == binding.resource,
754 "Configured MCP OAuth resource changed; requires OAuth reauthentication"
755 );
756 }
757 }
758 if let Some(client_id) = server.oauth_client_id() {
759 anyhow::ensure!(
760 client_id == tokens.client_id,
761 "Configured MCP OAuth client changed; requires OAuth reauthentication"
762 );
763 }
764 Self::from_stored_tokens(
765 server_name,
766 url,
767 tokens,
768 server.oauth_client_id(),
769 client.with_default_headers(default_headers),
770 )
771 .await
772 .map(Some)
773 }
774
775 async fn from_stored_tokens(
776 server_name: &str,
777 url: &str,
778 mut tokens: StoredMcpOAuthTokens,
779 configured_client_id: Option<&str>,
780 client: McpHttpClient,
781 ) -> Result<Self> {
782 refresh_expires_in_from_timestamp(&mut tokens);
783 let client = client.with_credential_transport()?;
784 let http_client = Arc::new(RecordingOAuthHttpClient::new(client));
785 let manager = manager_from_stored_tokens(url, &tokens, &http_client).await?;
786 let binding = tokens
787 .binding
788 .clone()
789 .ok_or_else(|| anyhow!("MCP OAuth credential binding is absent"))?;
790
791 Ok(Self {
792 inner: Arc::new(McpOAuthRuntimeInner {
793 server_name: server_name.to_string(),
794 url: url.to_string(),
795 binding,
796 configured_client_id: configured_client_id.map(str::to_owned),
797 manager: Arc::new(Mutex::new(manager)),
798 last_tokens: Mutex::new(Some(tokens)),
799 rejection: Mutex::new(None),
800 http_client,
801 }),
802 })
803 }
804
805 pub async fn authorization_header(&self) -> Result<Option<String>> {
806 self.refresh_if_needed().await?;
807 // Never send a credential the provider already rejected; the request
808 // goes out unauthenticated and the server's 401 drives the reactive
809 // refresh, which adopts a peer's login or reports auth-required.
810 if self.is_invalidated().await {
811 return Ok(None);
812 }
813 let credentials = {
814 let guard = self.inner.manager.lock().await;
815 let (_client_id, credentials) = guard
816 .get_credentials()
817 .await
818 .context("reading MCP OAuth credentials")?;
819 credentials
820 };
821 let Some(credentials) = credentials else {
822 return Ok(None);
823 };
824 let token = credentials.access_token().secret().trim();
825 if token.is_empty() {
826 Ok(None)
827 } else {
828 Ok(Some(format!("Bearer {token}")))
829 }
830 }
831
832 async fn refresh_if_needed(&self) -> Result<()> {
833 let expires_at = {
834 let guard = self.inner.last_tokens.lock().await;
835 guard.as_ref().and_then(|tokens| tokens.expires_at)
836 };
837 if !token_needs_refresh(expires_at) {
838 return Ok(());
839 }
840 self.refresh_and_persist().await
841 }
842
843 /// Force a token refresh regardless of the local expiry clock (T4): a
844 /// 401/403 means the server no longer accepts the token — clock skew,
845 /// server-side revocation, or rotation — so the expiry-based gate must
846 /// not decide alone.
847 pub async fn force_refresh(&self) -> Result<()> {
848 self.refresh_and_persist().await
849 }
850
851 /// Whether this runtime's credential was invalidated: definitively
852 /// rejected by the provider, or removed from the store (a logout) before
853 /// a refresh could persist. `last_tokens` is `Some` from construction and
854 /// after every persisted refresh; [`Self::clear_stored_tokens`] and a
855 /// refresh that returns no credential or finds the stored entry removed
856 /// empty it.
857 async fn is_invalidated(&self) -> bool {
858 self.inner.last_tokens.lock().await.is_none()
859 }
860
861 async fn refresh_and_persist(&self) -> Result<()> {
862 // A credential the provider definitively rejected is never replayed:
863 // the `AuthorizationManager` still holds it, but every later refresh
864 // with that grant is a guaranteed `invalid_grant`. The only way back
865 // is a credential another process stored since (a completed login),
866 // so adopt that when present and otherwise report auth-required
867 // without touching the token endpoint.
868 if self.is_invalidated().await {
869 if !self.adopt_rotated_on_disk_tokens().await? {
870 let reason = self
871 .inner
872 .rejection
873 .lock()
874 .await
875 .clone()
876 .unwrap_or_else(|| "unauthorized".to_string());
877 if reason == "logged_out" {
878 bail!(
879 "stored MCP OAuth credential for server {} was removed by a logout; the server requires OAuth login again",
880 self.inner.server_name
881 );
882 }
883 bail!(
884 "stored MCP OAuth credential for server {} was rejected by the provider ({reason}) and removed; the server requires OAuth login again",
885 self.inner.server_name
886 );
887 }
888 let adopted_needs_refresh = {
889 let last = self.inner.last_tokens.lock().await;
890 token_needs_refresh(last.as_ref().and_then(|tokens| tokens.expires_at))
891 };
892 if !adopted_needs_refresh {
893 return Ok(());
894 }
895 }
896 // Only this refresh's answer may explain this refresh's failure.
897 self.inner.http_client.take_token_endpoint_receipt();
898 let mut err = match self.try_refresh_and_persist().await {
899 Ok(()) => return Ok(()),
900 Err(err) => err,
901 };
902 // Refresh-race tolerance: another codewhale process sharing this token
903 // store (a concurrent `mcp login`, or a peer session's refresh) may
904 // have rotated the credential after this runtime loaded its copy, and
905 // single-use refresh tokens then fail here with `invalid_grant`.
906 // Re-read the store once; when the on-disk credential changed, adopt
907 // it — using it directly while fresh, or retrying the refresh exactly
908 // once with the rotated grant — before surfacing failure. When the
909 // store is unchanged the grant is simply dead: the auth-required
910 // branch below invalidates it so the server flips to `◆ auth
911 // required` and the self-serve login tool appears, instead of every
912 // later connect replaying the same rejected refresh.
913 if error_is_invalid_grant(&err) && self.adopt_rotated_on_disk_tokens().await? {
914 let adopted_needs_refresh = {
915 let last = self.inner.last_tokens.lock().await;
916 token_needs_refresh(last.as_ref().and_then(|tokens| tokens.expires_at))
917 };
918 if !adopted_needs_refresh {
919 return Ok(());
920 }
921 match self.try_refresh_and_persist().await {
922 Ok(()) => return Ok(()),
923 Err(retry_err) => err = retry_err,
924 }
925 }
926 if error_looks_auth_required(&err) {
927 let reason = if error_is_invalid_grant(&err) {
928 "invalid_grant"
929 } else {
930 "unauthorized"
931 };
932 self.clear_stored_tokens(reason).await?;
933 }
934 let server_name = self.inner.server_name.clone();
935 let names_remedy = !error_looks_auth_required(&err);
936 let receipt = self.inner.http_client.take_token_endpoint_receipt();
937 Err(err)
938 .with_context(|| refresh_failure_context(&server_name, names_remedy, receipt.as_ref()))
939 }
940
941 async fn try_refresh_and_persist(&self) -> Result<()> {
942 let refresh_result = {
943 let guard = self.inner.manager.lock().await;
944 guard.refresh_token().await
945 };
946 refresh_result.map_err(|err| anyhow!(err))?;
947 self.persist_if_needed().await
948 }
949
950 /// Re-read the on-disk credential after an `invalid_grant` refresh
951 /// failure and, when another process rotated it, rebuild the manager
952 /// around the rotated token exactly like initial construction. Returns
953 /// `true` only when the stored credential actually changed; an unchanged
954 /// store means the failure is ours to report.
955 async fn adopt_rotated_on_disk_tokens(&self) -> Result<bool> {
956 let Some(stored) = load_oauth_tokens(&self.inner.server_name, &self.inner.url)? else {
957 return Ok(false);
958 };
959 let changed = {
960 let last = self.inner.last_tokens.lock().await;
961 last.as_ref() != Some(&stored)
962 };
963 if !changed {
964 return Ok(false);
965 }
966 self.adopt_stored_tokens(stored).await?;
967 Ok(true)
968 }
969
970 async fn adopt_stored_tokens(&self, stored: StoredMcpOAuthTokens) -> Result<()> {
971 anyhow::ensure!(
972 stored.server_name == self.inner.server_name
973 && stored.binding.as_ref() == Some(&self.inner.binding),
974 "Stored MCP credential requires OAuth reauthentication: server, issuer or resource changed"
975 );
976 if let Some(client_id) = self.inner.configured_client_id.as_deref() {
977 anyhow::ensure!(
978 stored.client_id == client_id,
979 "Stored MCP credential requires OAuth reauthentication: configured client changed"
980 );
981 }
982 let manager =
983 manager_from_stored_tokens(&self.inner.url, &stored, &self.inner.http_client).await?;
984 *self.inner.manager.lock().await = manager;
985 *self.inner.last_tokens.lock().await = Some(stored);
986 *self.inner.rejection.lock().await = None;
987 Ok(())
988 }
989
990 /// Invalidate the credential this runtime holds after the provider
991 /// definitively rejected it. Never deletes a newer durable winner: when
992 /// the on-disk credential no longer matches the one we hold, another
993 /// process rotated it after our copy loaded, and that credential — not
994 /// ours — is the one the next connect must try. The manager is rebuilt
995 /// around that winner exactly like initial construction; remembering
996 /// the rotated token while keeping our dead grant would make the next
997 /// `invalid_grant` compare an "unchanged" store and delete the newer
998 /// valid credential.
999 ///
1000 /// The comparison and the delete are one step under the secret store's
1001 /// entry lock (the same lock every save takes), so a login that lands
1002 /// between them is never the credential that gets deleted.
1003 async fn clear_stored_tokens(&self, reason: &str) -> Result<()> {
1004 let held = { self.inner.last_tokens.lock().await.take() };
1005 let Some(held) = held else {
1006 return Ok(());
1007 };
1008 match delete_oauth_tokens_if_held(&self.inner.server_name, &self.inner.url, &held)? {
1009 Some(stored) => {
1010 tracing::debug!(
1011 target: "mcp",
1012 server = %self.inner.server_name,
1013 "MCP OAuth credential was rotated by another process; keeping the on-disk winner"
1014 );
1015 self.adopt_stored_tokens(stored).await?;
1016 }
1017 None => {
1018 *self.inner.rejection.lock().await = Some(reason.to_string());
1019 }
1020 }
1021 Ok(())
1022 }
1023
1024 async fn persist_if_needed(&self) -> Result<()> {
1025 let (client_id, credentials) = {
1026 let guard = self.inner.manager.lock().await;
1027 guard
1028 .get_credentials()
1029 .await
1030 .context("reading refreshed MCP OAuth credentials")?
1031 };
1032 let Some(credentials) = credentials else {
1033 let mut last = self.inner.last_tokens.lock().await;
1034 if let Some(previous) = last.take() {
1035 // Only our own credential goes; a newer login stays.
1036 delete_oauth_tokens_if_held(&self.inner.server_name, &self.inner.url, &previous)?;
1037 }
1038 return Ok(());
1039 };
1040
1041 let new_response = WrappedOAuthTokenResponse(credentials.clone());
1042 let mut last = self.inner.last_tokens.lock().await;
1043 let same_token = last
1044 .as_ref()
1045 .map(|previous| previous.token_response == new_response)
1046 .unwrap_or(false);
1047 let expires_at = if same_token {
1048 last.as_ref().and_then(|previous| previous.expires_at)
1049 } else {
1050 compute_expires_at_millis(&credentials)
1051 };
1052 let stored = StoredMcpOAuthTokens {
1053 server_name: self.inner.server_name.clone(),
1054 url: self.inner.url.clone(),
1055 client_id,
1056 binding: Some(self.inner.binding.clone()),
1057 token_response: new_response,
1058 expires_at,
1059 };
1060 let Some(held) = last.as_ref().filter(|held| **held != stored) else {
1061 return Ok(());
1062 };
1063 match save_oauth_tokens_if_held(held, &stored)? {
1064 HeldTokenSave::Saved => *last = Some(stored),
1065 HeldTokenSave::Removed => {
1066 *last = None;
1067 drop(last);
1068 *self.inner.rejection.lock().await = Some("logged_out".to_string());
1069 }
1070 HeldTokenSave::Replaced(current) => {
1071 drop(last);
1072 self.adopt_stored_tokens(*current).await?;
1073 }
1074 }
1075 Ok(())
1076 }
1077 }
1078
1079 pub async fn auth_status_for_server(
1080 name: &str,
1081 server: &McpServerConfig,
1082 network_policy: Option<&NetworkPolicyDecider>,
1083 ) -> McpAuthStatus {
1084 auth_status_for_server_with_auth_context(
1085 name,
1086 server,
1087 network_policy,
1088 super::process_mcp_auth_context(),
1089 )
1090 .await
1091 }
1092
1093 pub async fn auth_status_for_server_with_auth_context(
1094 name: &str,
1095 server: &McpServerConfig,
1096 network_policy: Option<&NetworkPolicyDecider>,
1097 auth_context: Arc<dyn AuthContext>,
1098 ) -> McpAuthStatus {
1099 if server.reviewed_plugin.is_some() || !server.is_enabled() || server.url.is_none() {
1100 return McpAuthStatus::Unsupported;
1101 }
1102 if server_has_manual_authorization(server) {
1103 return McpAuthStatus::BearerToken;
1104 }
1105 let Some(url) = server.url.as_deref() else {
1106 return McpAuthStatus::Unsupported;
1107 };
1108 match load_oauth_tokens(name, url) {
1109 Ok(Some(tokens)) if oauth_tokens_are_usable(&tokens) => return McpAuthStatus::OAuth,
1110 Ok(Some(_)) => return McpAuthStatus::NotLoggedIn,
1111 Ok(None) => {}
1112 Err(err) => {
1113 tracing::warn!(target: "mcp", server = %name, error = %err, "failed to read MCP OAuth tokens");
1114 }
1115 }
1116
1117 let headers = match build_default_headers_with_auth_context(server, auth_context.as_ref()) {
1118 Ok(headers) => headers,
1119 Err(err) => {
1120 tracing::warn!(target: "mcp", server = %name, error = %err, "failed to build MCP OAuth discovery headers");
1121 return McpAuthStatus::Unsupported;
1122 }
1123 };
1124 match discover_streamable_http_oauth_for_server(server, url, headers, network_policy).await {
1125 Ok(Some(_)) => McpAuthStatus::NotLoggedIn,
1126 Ok(None) => McpAuthStatus::Unsupported,
1127 Err(err) => {
1128 tracing::debug!(target: "mcp", server = %name, error = %err, "MCP OAuth discovery failed");
1129 McpAuthStatus::Unsupported
1130 }
1131 }
1132 }
1133
1134 pub async fn oauth_login_support(
1135 server: &McpServerConfig,
1136 network_policy: Option<&NetworkPolicyDecider>,
1137 ) -> Result<Option<McpOAuthDiscovery>> {
1138 oauth_login_support_with_auth_context(server, network_policy, super::process_mcp_auth_context())
1139 .await
1140 }
1141
1142 pub async fn oauth_login_support_with_auth_context(
1143 server: &McpServerConfig,
1144 network_policy: Option<&NetworkPolicyDecider>,
1145 auth_context: Arc<dyn AuthContext>,
1146 ) -> Result<Option<McpOAuthDiscovery>> {
1147 if server.reviewed_plugin.is_some() {
1148 return Ok(None);
1149 }
1150 let Some(url) = server.url.as_deref() else {
1151 return Ok(None);
1152 };
1153 if server_has_manual_authorization(server) {
1154 return Ok(None);
1155 }
1156 let headers = build_default_headers_with_auth_context(server, auth_context.as_ref())?;
1157 discover_streamable_http_oauth_for_server(server, url, headers, network_policy).await
1158 }
1159
1160 fn oauth_http_client(
1161 server: &McpServerConfig,
1162 url: &str,
1163 network_policy: Option<&NetworkPolicyDecider>,
1164 ) -> Result<McpHttpClient> {
1165 let timeouts = super::McpTimeouts::default();
1166 McpHttpClient::new(
1167 url,
1168 server.runtime_added,
1169 server.reviewed_plugin.is_some(),
1170 server.allow_private_network,
1171 network_policy,
1172 Duration::from_secs(server.effective_connect_timeout(&timeouts)),
1173 Duration::from_secs(server.effective_read_timeout(&timeouts)),
1174 )
1175 .and_then(McpHttpClient::with_credential_transport)
1176 }
1177
1178 fn oauth_login_client(
1179 server: &McpServerConfig,
1180 url: &str,
1181 network_policy: Option<&NetworkPolicyDecider>,
1182 auth_context: &dyn AuthContext,
1183 ) -> Result<McpHttpClient> {
1184 let headers = build_default_headers_with_auth_context(server, auth_context)?;
1185 Ok(oauth_http_client(server, url, network_policy)?.with_default_headers(headers))
1186 }
1187
1188 async fn discover_streamable_http_oauth_for_server(
1189 server: &McpServerConfig,
1190 url: &str,
1191 default_headers: HeaderMap,
1192 network_policy: Option<&NetworkPolicyDecider>,
1193 ) -> Result<Option<McpOAuthDiscovery>> {
1194 let client =
1195 oauth_http_client(server, url, network_policy)?.with_default_headers(default_headers);
1196 discover_streamable_http_oauth_with_client(url, client).await
1197 }
1198
1199 async fn discover_streamable_http_oauth_with_client(
1200 url: &str,
1201 client: McpHttpClient,
1202 ) -> Result<Option<McpOAuthDiscovery>> {
1203 let client = Arc::new(RecordingOAuthHttpClient::new(client));
1204 let manager = AuthorizationManager::new_with_oauth_http_client(url, client).await?;
1205 match tokio::time::timeout(Duration::from_secs(5), manager.resolve_metadata()).await? {
1206 Ok(resolution) if resolution.source.is_discovered() => Ok(Some(McpOAuthDiscovery {
1207 scopes_supported: normalize_scopes(resolution.metadata.scopes_supported),
1208 })),
1209 Ok(_) | Err(AuthError::NoAuthorizationSupport) => Ok(None),
1210 Err(err) => Err(err.into()),
1211 }
1212 }
1213
1214 pub fn resolve_oauth_scopes(
1215 explicit_scopes: Option<Vec<String>>,
1216 configured_scopes: Vec<String>,
1217 discovered_scopes: Option<Vec<String>>,
1218 ) -> ResolvedMcpOAuthScopes {
1219 if let Some(scopes) = explicit_scopes {
1220 return ResolvedMcpOAuthScopes {
1221 scopes,
1222 source: McpOAuthScopesSource::Explicit,
1223 };
1224 }
1225 if !configured_scopes.is_empty() {
1226 return ResolvedMcpOAuthScopes {
1227 scopes: configured_scopes,
1228 source: McpOAuthScopesSource::Configured,
1229 };
1230 }
1231 if let Some(scopes) = discovered_scopes
1232 && !scopes.is_empty()
1233 {
1234 return ResolvedMcpOAuthScopes {
1235 scopes,
1236 source: McpOAuthScopesSource::Discovered,
1237 };
1238 }
1239 ResolvedMcpOAuthScopes {
1240 scopes: Vec::new(),
1241 source: McpOAuthScopesSource::Empty,
1242 }
1243 }
1244
1245 pub async fn perform_oauth_login_for_server(
1246 name: &str,
1247 server: &McpServerConfig,
1248 explicit_scopes: Option<Vec<String>>,
1249 callback_port: Option<u16>,
1250 callback_url: Option<&str>,
1251 network_policy: Option<&NetworkPolicyDecider>,
1252 ) -> Result<()> {
1253 perform_oauth_login_for_server_with_auth_context(
1254 name,
1255 server,
1256 explicit_scopes,
1257 callback_port,
1258 callback_url,
1259 network_policy,
1260 super::process_mcp_auth_context(),
1261 )
1262 .await
1263 }
1264
1265 pub async fn perform_oauth_login_for_server_with_auth_context(
1266 name: &str,
1267 server: &McpServerConfig,
1268 explicit_scopes: Option<Vec<String>>,
1269 callback_port: Option<u16>,
1270 callback_url: Option<&str>,
1271 network_policy: Option<&NetworkPolicyDecider>,
1272 auth_context: Arc<dyn AuthContext>,
1273 ) -> Result<()> {
1274 if server.reviewed_plugin.is_some() {
1275 bail!(
1276 "OAuth is disabled for plugin-contributed MCP servers; use a reviewed environment-backed header or bearer token"
1277 );
1278 }
1279 perform_oauth_login_for_server_inner(
1280 name,
1281 server,
1282 explicit_scopes,
1283 callback_port,
1284 callback_url,
1285 network_policy,
1286 auth_context,
1287 )
1288 .await
1289 }
1290
1291 /// Run an MCP OAuth login that can be stopped by the caller.
1292 ///
1293 /// Cancellation drops the in-flight OAuth future before this function returns,
1294 /// which also closes its callback listener. A caller that replaces one login
1295 /// with another should await the cancelled call before starting the replacement.
1296 pub async fn perform_oauth_login_for_server_with_cancel(
1297 name: &str,
1298 server: &McpServerConfig,
1299 explicit_scopes: Option<Vec<String>>,
1300 callback_port: Option<u16>,
1301 callback_url: Option<&str>,
1302 cancellation_token: CancellationToken,
1303 network_policy: Option<&NetworkPolicyDecider>,
1304 ) -> Result<()> {
1305 if server.reviewed_plugin.is_some() {
1306 bail!(
1307 "OAuth is disabled for plugin-contributed MCP servers; use a reviewed environment-backed header or bearer token"
1308 );
1309 }
1310 run_cancellable_oauth(
1311 &cancellation_token,
1312 perform_oauth_login_for_server_with_auth_context(
1313 name,
1314 server,
1315 explicit_scopes,
1316 callback_port,
1317 callback_url,
1318 network_policy,
1319 super::process_mcp_auth_context(),
1320 ),
1321 )
1322 .await
1323 }
1324
1325 async fn run_cancellable_oauth<F, T>(cancellation_token: &CancellationToken, future: F) -> Result<T>
1326 where
1327 F: std::future::Future<Output = Result<T>>,
1328 {
1329 tokio::select! {
1330 biased;
1331 _ = cancellation_token.cancelled() => bail!("OAuth login was cancelled"),
1332 result = future => result,
1333 }
1334 }
1335
1336 /// Shared gate + scope resolution for `/mcp login` and the model-driven
1337 /// authenticate tool: URL-based servers only, no manual Authorization config,
1338 /// scopes from explicit argument, config, or discovery (in that order).
1339 async fn resolve_oauth_login(
1340 name: &str,
1341 server: &McpServerConfig,
1342 explicit_scopes: Option<Vec<String>>,
1343 network_policy: Option<&NetworkPolicyDecider>,
1344 auth_context: Arc<dyn AuthContext>,
1345 ) -> Result<(String, ResolvedMcpOAuthScopes)> {
1346 let Some(url) = server.url.as_deref() else {
1347 bail!("OAuth login is only supported for URL-based MCP servers");
1348 };
1349 if server_has_manual_authorization(server) {
1350 bail!("MCP server '{name}' already has bearer/static Authorization configured");
1351 }
1352
1353 let discovery = if explicit_scopes.is_none() && server.scopes.is_empty() {
1354 oauth_login_support_with_auth_context(server, network_policy, Arc::clone(&auth_context))
1355 .await?
1356 } else {
1357 None
1358 };
1359 let resolved_scopes = resolve_oauth_scopes(
1360 explicit_scopes,
1361 server.scopes.clone(),
1362 discovery.and_then(|discovery| discovery.scopes_supported),
1363 );
1364 Ok((url.to_string(), resolved_scopes))
1365 }
1366
1367 async fn perform_oauth_login_for_server_inner(
1368 name: &str,
1369 server: &McpServerConfig,
1370 explicit_scopes: Option<Vec<String>>,
1371 callback_port: Option<u16>,
1372 callback_url: Option<&str>,
1373 network_policy: Option<&NetworkPolicyDecider>,
1374 auth_context: Arc<dyn AuthContext>,
1375 ) -> Result<()> {
1376 let (url, resolved_scopes) = resolve_oauth_login(
1377 name,
1378 server,
1379 explicit_scopes,
1380 network_policy,
1381 Arc::clone(&auth_context),
1382 )
1383 .await?;
1384
1385 match perform_oauth_login(
1386 name,
1387 &url,
1388 oauth_login_client(server, &url, network_policy, auth_context.as_ref())?,
1389 &resolved_scopes.scopes,
1390 server.oauth.as_ref(),
1391 server.oauth_resource.as_deref(),
1392 callback_port,
1393 callback_url,
1394 )
1395 .await
1396 {
1397 Ok(()) => Ok(()),
1398 Err(err)
1399 if resolved_scopes.source == McpOAuthScopesSource::Discovered
1400 && err
1401 .downcast_ref::<OAuthProviderError>()
1402 .is_some_and(|error| error.error.as_deref() == Some("invalid_scope")) =>
1403 {
1404 println!("OAuth provider rejected discovered scopes. Retrying without scopes...");
1405 perform_oauth_login(
1406 name,
1407 &url,
1408 oauth_login_client(server, &url, network_policy, auth_context.as_ref())?,
1409 &[],
1410 server.oauth.as_ref(),
1411 server.oauth_resource.as_deref(),
1412 callback_port,
1413 callback_url,
1414 )
1415 .await
1416 }
1417 Err(err) => Err(err),
1418 }
1419 }
1420
1421 #[allow(clippy::too_many_arguments)]
1422 async fn perform_oauth_login(
1423 server_name: &str,
1424 server_url: &str,
1425 client: McpHttpClient,
1426 scopes: &[String],
1427 oauth: Option<&super::McpServerOAuthConfig>,
1428 oauth_resource: Option<&str>,
1429 callback_port: Option<u16>,
1430 callback_url: Option<&str>,
1431 ) -> Result<()> {
1432 OauthLoginFlow::new(
1433 server_name,
1434 server_url,
1435 client,
1436 scopes,
1437 oauth,
1438 oauth_resource,
1439 callback_port,
1440 callback_url,
1441 )
1442 .await?
1443 .finish()
1444 .await
1445 }
1446
1447 /// How an OAuth login announces its authorization URL.
1448 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
1449 enum OAuthLoginAnnounce {
1450 /// `/mcp login` in a terminal: print the URL and open a browser.
1451 Terminal,
1452 /// Model-driven `mcp_<server>_authenticate` tool: never write to stdout
1453 /// (a tool call inside a running session is not a terminal); the result
1454 /// carries the URL for the model to relay to the user verbatim.
1455 Tool { open_browser: bool },
1456 }
1457
1458 /// An in-flight OAuth login started by the model-driven authenticate tool.
1459 ///
1460 /// The authorization URL is available immediately so the model can relay it
1461 /// to the user verbatim; [`McpOAuthToolLogin::finish`] then blocks on the
1462 /// loopback callback (up to 15 minutes, same as `/mcp login`) and persists
1463 /// the issued tokens to the shared store on success.
1464 pub struct McpOAuthToolLogin {
1465 server_name: String,
1466 server: McpServerConfig,
1467 scopes_source: McpOAuthScopesSource,
1468 auth_context: Arc<dyn AuthContext>,
1469 network_policy: Option<NetworkPolicyDecider>,
1470 flow: OauthLoginFlow,
1471 open_browser: bool,
1472 }
1473
1474 impl McpOAuthToolLogin {
1475 /// The exact authorization URL the user must visit. Treat it as
1476 /// sensitive: never modify it or strip query parameters.
1477 #[must_use]
1478 pub fn authorization_url(&self) -> &str {
1479 &self.flow.auth_url
1480 }
1481
1482 /// Block on the browser callback and persist the issued tokens. Mirrors
1483 /// the `/mcp login` retry: when the provider rejects scopes that came
1484 /// from discovery (rather than explicit config), restart once without
1485 /// scopes.
1486 pub async fn finish(self) -> Result<()> {
1487 let announce = OAuthLoginAnnounce::Tool {
1488 open_browser: self.open_browser,
1489 };
1490 let retry_without_scopes = self.scopes_source == McpOAuthScopesSource::Discovered;
1491 match self.flow.finish_with_announce(announce).await {
1492 Ok(()) => Ok(()),
1493 Err(err)
1494 if retry_without_scopes
1495 && err
1496 .downcast_ref::<OAuthProviderError>()
1497 .is_some_and(|error| error.error.as_deref() == Some("invalid_scope")) =>
1498 {
1499 let server = &self.server;
1500 let url = server
1501 .url
1502 .as_deref()
1503 .expect("tool login is gated to URL-based servers at begin");
1504 OauthLoginFlow::new(
1505 &self.server_name,
1506 url,
1507 oauth_login_client(
1508 server,
1509 url,
1510 self.network_policy.as_ref(),
1511 self.auth_context.as_ref(),
1512 )?,
1513 &[],
1514 server.oauth.as_ref(),
1515 server.oauth_resource.as_deref(),
1516 None,
1517 None,
1518 )
1519 .await?
1520 .finish_with_announce(announce)
1521 .await
1522 }
1523 Err(err) => Err(err),
1524 }
1525 }
1526 }
1527
1528 /// Begin the same OAuth login flow `/mcp login` runs, for the model-driven
1529 /// `mcp_<server>_authenticate` tool. The callback listener binds an
1530 /// ephemeral loopback port; callers needing a pre-registered redirect URI
1531 /// keep the terminal `/mcp login <name>` path, which honors the configured
1532 /// callback overrides.
1533 pub async fn begin_oauth_login_for_server_tool(
1534 name: &str,
1535 server: &McpServerConfig,
1536 explicit_scopes: Option<Vec<String>>,
1537 callback_port: Option<u16>,
1538 callback_url: Option<&str>,
1539 network_policy: Option<&NetworkPolicyDecider>,
1540 ) -> Result<McpOAuthToolLogin> {
1541 begin_oauth_login_for_server_tool_with_auth_context(
1542 name,
1543 server,
1544 explicit_scopes,
1545 callback_port,
1546 callback_url,
1547 network_policy,
1548 super::process_mcp_auth_context(),
1549 )
1550 .await
1551 }
1552
1553 pub async fn begin_oauth_login_for_server_tool_with_auth_context(
1554 name: &str,
1555 server: &McpServerConfig,
1556 explicit_scopes: Option<Vec<String>>,
1557 callback_port: Option<u16>,
1558 callback_url: Option<&str>,
1559 network_policy: Option<&NetworkPolicyDecider>,
1560 auth_context: Arc<dyn AuthContext>,
1561 ) -> Result<McpOAuthToolLogin> {
1562 if server.reviewed_plugin.is_some() {
1563 bail!(
1564 "OAuth is disabled for plugin-contributed MCP servers; use a reviewed environment-backed header or bearer token"
1565 );
1566 }
1567 let (url, resolved_scopes) = resolve_oauth_login(
1568 name,
1569 server,
1570 explicit_scopes,
1571 network_policy,
1572 Arc::clone(&auth_context),
1573 )
1574 .await?;
1575 let flow = OauthLoginFlow::new(
1576 name,
1577 &url,
1578 oauth_login_client(server, &url, network_policy, auth_context.as_ref())?,
1579 &resolved_scopes.scopes,
1580 server.oauth.as_ref(),
1581 server.oauth_resource.as_deref(),
1582 callback_port,
1583 callback_url,
1584 )
1585 .await?;
1586 Ok(McpOAuthToolLogin {
1587 server_name: name.to_string(),
1588 server: server.clone(),
1589 scopes_source: resolved_scopes.source,
1590 auth_context,
1591 network_policy: network_policy.cloned(),
1592 flow,
1593 // The test build drives the loopback callback itself; a real browser
1594 // launch from a unit test would hijack the developer's desktop.
1595 open_browser: !cfg!(any(test, feature = "test-support")),
1596 })
1597 }
1598
1599 /// Whether the self-serve OAuth login flow can run for this server at all:
1600 /// URL-based, not plugin-contributed (plugin servers authenticate through
1601 /// reviewed environment-backed headers, and OAuth storage is disabled for
1602 /// them), and without a manual Authorization configuration that an OAuth
1603 /// login would conflict with.
1604 pub fn server_supports_oauth_login(server: &McpServerConfig) -> bool {
1605 server.reviewed_plugin.is_none()
1606 && server.url.is_some()
1607 && !server_has_manual_authorization(server)
1608 }
1609
1610 pub async fn has_usable_stored_tokens_with_auth_context(
1611 name: &str,
1612 server: &McpServerConfig,
1613 network_policy: Option<&NetworkPolicyDecider>,
1614 auth_context: Arc<dyn AuthContext>,
1615 ) -> Result<bool> {
1616 let Some(url) = server.url.as_deref() else {
1617 return Ok(false);
1618 };
1619 if !server_supports_oauth_login(server)
1620 || !load_oauth_tokens(name, url)?.is_some_and(|tokens| oauth_tokens_are_usable(&tokens))
1621 {
1622 return Ok(false);
1623 }
1624 match McpOAuthRuntime::from_server_config_with_client(
1625 name,
1626 server,
1627 build_default_headers_with_auth_context(server, auth_context.as_ref())?,
1628 oauth_login_client(server, url, network_policy, auth_context.as_ref())?,
1629 )
1630 .await
1631 {
1632 Ok(runtime) => Ok(runtime.is_some()),
1633 Err(error) if error_looks_auth_required(&error) => Ok(false),
1634 Err(error) => Err(error),
1635 }
1636 }
1637
1638 /// Model-facing description for the synthetic `mcp_<server>_authenticate`
1639 /// tool. The coaching contract (show the URL verbatim, the call blocks, real
1640 /// tools replace this one on success) is pinned by tests.
1641 pub fn authenticate_tool_description(server_name: &str) -> String {
1642 format!(
1643 "Authenticate with MCP server \"{server_name}\" via OAuth.\n\n\
1644 This server requires an OAuth login that has not yet been completed, so its \
1645 real tools are currently unavailable. Calling this tool starts the \
1646 authorization flow:\n\n\
1647 1. A browser window is opened for the user to sign in and approve the \
1648 Codewhale client, and the exact authorization URL is shown to the user in \
1649 the session status while this call waits. The same URL is returned in this \
1650 call's result; if the user reports the browser did not open, show that URL \
1651 to the user verbatim and ask them to complete the sign-in there.\n\
1652 2. The call blocks (up to 15 minutes) until the browser flow completes on the \
1653 local callback listener, is declined, or times out. Do not assume success \
1654 before the call returns.\n\
1655 3. On success the server reconnects and its real MCP tools replace this \
1656 synthetic authenticate tool, becoming callable from the next model request \
1657 in this session.\n\n\
1658 Treat the URL as sensitive — do not modify it or strip query parameters. If \
1659 the flow is declined, cancelled, or times out, the call returns an error; \
1660 relay it truthfully and suggest `/mcp login {server_name}` in the TUI or \
1661 `codewhale mcp login {server_name}` from a terminal."
1662 )
1663 }
1664
1665 pub fn delete_oauth_tokens_for_server(name: &str, server: &McpServerConfig) -> Result<bool> {
1666 if server.reviewed_plugin.is_some() {
1667 bail!("OAuth storage is disabled for plugin-contributed MCP servers");
1668 }
1669 let Some(url) = server.url.as_deref() else {
1670 bail!("OAuth logout is only supported for URL-based MCP servers");
1671 };
1672 delete_oauth_tokens(name, url)
1673 }
1674
1675 pub fn server_has_manual_authorization(server: &McpServerConfig) -> bool {
1676 server.bearer_token_env_var.is_some()
1677 || contains_authorization_header(&server.headers)
1678 || contains_authorization_header(&server.env_headers)
1679 }
1680
1681 pub(super) fn build_default_headers_with_auth_context(
1682 server: &McpServerConfig,
1683 auth_context: &dyn AuthContext,
1684 ) -> Result<HeaderMap> {
1685 let mut headers = HeaderMap::new();
1686 for (name, value) in &server.headers {
1687 insert_header(&mut headers, name, value)?;
1688 }
1689 for (name, env_var) in &server.env_headers {
1690 let value =
1691 super::required_mcp_secret_var(server.reviewed_plugin_source(), env_var, auth_context)?;
1692 insert_header(&mut headers, name, &value)?;
1693 }
1694 Ok(headers)
1695 }
1696
1697 pub(super) fn insert_header(headers: &mut HeaderMap, name: &str, value: &str) -> Result<()> {
1698 if !super::headers::is_safe_custom_header(name, value) {
1699 bail!("unsafe MCP HTTP header '{name}'");
1700 }
1701 let name = HeaderName::from_bytes(name.as_bytes())
1702 .with_context(|| format!("invalid MCP HTTP header name '{name}'"))?;
1703 let value = HeaderValue::from_str(value).with_context(|| "invalid MCP HTTP header value")?;
1704 headers.insert(name, value);
1705 Ok(())
1706 }
1707
1708 fn contains_authorization_header(headers: &HashMap<String, String>) -> bool {
1709 headers
1710 .keys()
1711 .any(|key| key.trim().eq_ignore_ascii_case("authorization"))
1712 }
1713
1714 fn normalize_scopes(scopes_supported: Option<Vec<String>>) -> Option<Vec<String>> {
1715 let scopes_supported = scopes_supported?;
1716 let mut normalized = Vec::new();
1717 for scope in scopes_supported {
1718 let scope = scope.trim();
1719 if scope.is_empty() {
1720 continue;
1721 }
1722 let scope = scope.to_string();
1723 if !normalized.contains(&scope) {
1724 normalized.push(scope);
1725 }
1726 }
1727 (!normalized.is_empty()).then_some(normalized)
1728 }
1729
1730 pub fn load_oauth_tokens(server_name: &str, url: &str) -> Result<Option<StoredMcpOAuthTokens>> {
1731 let secrets = codewhale_secrets::Secrets::auto_detect();
1732 let key = store_key(server_name, url);
1733 let Some(serialized) = secrets
1734 .get(&key)
1735 .with_context(|| format!("reading MCP OAuth token for '{server_name}'"))?
1736 else {
1737 return Ok(None);
1738 };
1739 decode_stored_oauth_tokens(&serialized, server_name).map(Some)
1740 }
1741
1742 fn decode_stored_oauth_tokens(serialized: &str, server_name: &str) -> Result<StoredMcpOAuthTokens> {
1743 let mut tokens = parse_stored_oauth_tokens(serialized, server_name)?;
1744 refresh_expires_in_from_timestamp(&mut tokens);
1745 Ok(tokens)
1746 }
1747
1748 /// Delete the stored credential only while it is still exactly `held`,
1749 /// comparing and deleting under the store's entry lock. Returns the different
1750 /// credential found in its place (left untouched), or `None` when the entry
1751 /// was `held` and is now gone, or was already absent. An unreadable entry is
1752 /// an error and is left in place, as a plain load would report it.
1753 fn delete_oauth_tokens_if_held(
1754 server_name: &str,
1755 url: &str,
1756 held: &StoredMcpOAuthTokens,
1757 ) -> Result<Option<StoredMcpOAuthTokens>> {
1758 let secrets = codewhale_secrets::Secrets::auto_detect();
1759 let key = store_key(server_name, url);
1760 secrets
1761 .with_entry_transaction(&key, |current| {
1762 let Some(serialized) = current.as_deref() else {
1763 return Ok(Ok(None));
1764 };
1765 Ok(match decode_stored_oauth_tokens(serialized, server_name) {
1766 Ok(stored) if stored == *held => {
1767 *current = None;
1768 Ok(None)
1769 }
1770 Ok(stored) => Ok(Some(stored)),
1771 Err(error) => Err(error),
1772 })
1773 })
1774 .with_context(|| format!("clearing the MCP OAuth token for '{server_name}'"))?
1775 }
1776
1777 enum HeldTokenSave {
1778 Saved,
1779 Removed,
1780 Replaced(Box<StoredMcpOAuthTokens>),
1781 }
1782
1783 fn save_oauth_tokens_if_held(
1784 held: &StoredMcpOAuthTokens,
1785 tokens: &StoredMcpOAuthTokens,
1786 ) -> Result<HeldTokenSave> {
1787 let secrets = codewhale_secrets::Secrets::auto_detect();
1788 let key = store_key(&tokens.server_name, &tokens.url);
1789 let replacement = serde_json::to_string(tokens).context("serializing MCP OAuth token")?;
1790 secrets
1791 .with_entry_transaction(&key, |current| {
1792 let Some(serialized) = current.as_deref() else {
1793 return Ok(Ok(HeldTokenSave::Removed));
1794 };
1795 Ok(
1796 match decode_stored_oauth_tokens(serialized, &tokens.server_name) {
1797 Ok(stored) if stored == *held => {
1798 *current = Some(replacement);
1799 Ok(HeldTokenSave::Saved)
1800 }
1801 Ok(stored) => Ok(HeldTokenSave::Replaced(Box::new(stored))),
1802 Err(error) => Err(error),
1803 },
1804 )
1805 })
1806 .with_context(|| format!("saving MCP OAuth token for '{}'", tokens.server_name))?
1807 }
1808
1809 static DYNAMIC_REGISTRATION_UNAVAILABLE: std::sync::LazyLock<
1810 std::sync::Mutex<std::collections::HashSet<(String, String)>>,
1811 > = std::sync::LazyLock::new(|| std::sync::Mutex::new(std::collections::HashSet::new()));
1812
1813 fn note_dynamic_registration(server_name: &str, url: &str, available: bool) {
1814 let mut unavailable = DYNAMIC_REGISTRATION_UNAVAILABLE
1815 .lock()
1816 .unwrap_or_else(std::sync::PoisonError::into_inner);
1817 let key = (server_name.to_string(), url.to_string());
1818 if available {
1819 unavailable.remove(&key);
1820 } else {
1821 unavailable.insert(key);
1822 }
1823 }
1824
1825 pub fn dynamic_registration_unavailable(server_name: &str, url: &str) -> bool {
1826 DYNAMIC_REGISTRATION_UNAVAILABLE
1827 .lock()
1828 .unwrap_or_else(std::sync::PoisonError::into_inner)
1829 .contains(&(server_name.to_string(), url.to_string()))
1830 }
1831
1832 const MAX_REGISTRATION_DETAIL_CHARS: usize = 400;
1833
1834 fn registration_status_rejection(message: &str) -> Option<String> {
1835 let trimmed = message.trim();
1836 let status = trimmed.strip_prefix("HTTP ")?.split_whitespace().next()?;
1837 let code = status.parse::<u16>().ok()?;
1838 if !(400..500).contains(&code) {
1839 return None;
1840 }
1841 let mut detail: String = trimmed
1842 .chars()
1843 .take(MAX_REGISTRATION_DETAIL_CHARS)
1844 .collect();
1845 if detail.chars().count() < trimmed.chars().count() {
1846 detail.push('\u{2026}');
1847 }
1848 Some(detail)
1849 }
1850
1851 fn error_is_dynamic_registration_unsupported(error: &anyhow::Error) -> bool {
1852 matches!(
1853 error.downcast_ref::<AuthError>(),
1854 Some(AuthError::RegistrationFailed(message))
1855 if message.contains("Dynamic client registration not supported")
1856 || registration_status_rejection(message).is_some()
1857 )
1858 }
1859
1860 fn dynamic_registration_failure(error: &anyhow::Error) -> String {
1861 error
1862 .downcast_ref::<AuthError>()
1863 .and_then(|err| match err {
1864 AuthError::RegistrationFailed(message) => Some(message.as_str()),
1865 _ => None,
1866 })
1867 .map_or_else(
1868 || "client registration is unavailable".to_string(),
1869 |message| registration_status_rejection(message).unwrap_or_else(|| message.to_string()),
1870 )
1871 }
1872
1873 fn dynamic_registration_guidance() -> &'static str {
1874 "Configure `oauth.client_metadata_url` for a hosted client document, or `oauth.client_id` with its exact `oauth.issuer`, then log in again. Alternatively set `bearer_token_env_var` to an environment variable holding a least-privilege personal access token and run `/mcp reload`"
1875 }
1876
1877 pub fn dynamic_registration_unavailable_hint(server_name: &str) -> String {
1878 format!(
1879 "MCP server '{server_name}' cannot complete an OAuth login: its authorization server offers no usable client registration. {}",
1880 dynamic_registration_guidance()
1881 )
1882 }
1883
1884 fn parse_stored_oauth_tokens(serialized: &str, server_name: &str) -> Result<StoredMcpOAuthTokens> {
1885 serde_json::from_str(serialized).map_err(|_| {
1886 anyhow!(
1887 "stored MCP OAuth token for '{server_name}' is not valid credential JSON; contents were omitted"
1888 )
1889 })
1890 }
1891
1892 pub fn save_oauth_tokens(tokens: &StoredMcpOAuthTokens) -> Result<()> {
1893 let secrets = codewhale_secrets::Secrets::auto_detect();
1894 let key = store_key(&tokens.server_name, &tokens.url);
1895 let serialized = serde_json::to_string(tokens).context("serializing MCP OAuth token")?;
1896 secrets
1897 .set(&key, &serialized)
1898 .with_context(|| format!("saving MCP OAuth token for '{}'", tokens.server_name))
1899 }
1900
1901 fn delete_oauth_tokens(server_name: &str, url: &str) -> Result<bool> {
1902 let secrets = codewhale_secrets::Secrets::auto_detect();
1903 let key = store_key(server_name, url);
1904 let existed = secrets
1905 .get(&key)
1906 .with_context(|| format!("reading MCP OAuth token for '{server_name}'"))?
1907 .is_some();
1908 secrets
1909 .delete(&key)
1910 .with_context(|| format!("deleting MCP OAuth token for '{server_name}'"))?;
1911 Ok(existed)
1912 }
1913
1914 fn store_key(server_name: &str, url: &str) -> String {
1915 let mut payload = Vec::with_capacity(server_name.len() + url.len() + 1);
1916 payload.extend_from_slice(server_name.as_bytes());
1917 payload.push(0);
1918 payload.extend_from_slice(url.as_bytes());
1919 let digest = Sha256::digest(&payload);
1920 format!("mcp_oauth_{}", URL_SAFE_NO_PAD.encode(digest))
1921 }
1922
1923 fn oauth_tokens_are_usable(tokens: &StoredMcpOAuthTokens) -> bool {
1924 if tokens.client_id.trim().is_empty()
1925 || tokens
1926 .binding
1927 .as_ref()
1928 .is_none_or(|binding| binding.issuer.is_empty() || binding.resource.is_empty())
1929 {
1930 return false;
1931 }
1932 let response = &tokens.token_response.0;
1933 if token_needs_refresh(tokens.expires_at) {
1934 return response
1935 .refresh_token()
1936 .is_some_and(|token| !token.secret().trim().is_empty());
1937 }
1938 !response.access_token().secret().trim().is_empty()
1939 }
1940
1941 fn refresh_expires_in_from_timestamp(tokens: &mut StoredMcpOAuthTokens) {
1942 let Some(expires_at) = tokens.expires_at else {
1943 return;
1944 };
1945 match expires_in_from_timestamp(expires_at) {
1946 Some(seconds) => {
1947 let duration = Duration::from_secs(seconds);
1948 tokens.token_response.0.set_expires_in(Some(&duration));
1949 }
1950 None => {
1951 tokens
1952 .token_response
1953 .0
1954 .set_expires_in(Some(&Duration::ZERO));
1955 }
1956 }
1957 }
1958
1959 fn compute_expires_at_millis(response: &OAuthTokenResponse) -> Option<u64> {
1960 let expires = response.expires_in()?;
1961 let now = SystemTime::now()
1962 .duration_since(UNIX_EPOCH)
1963 .ok()?
1964 .as_millis() as u64;
1965 Some(now.saturating_add(expires.as_millis() as u64))
1966 }
1967
1968 fn expires_in_from_timestamp(expires_at: u64) -> Option<u64> {
1969 let now = SystemTime::now()
1970 .duration_since(UNIX_EPOCH)
1971 .ok()?
1972 .as_millis() as u64;
1973 if expires_at <= now {
1974 return None;
1975 }
1976 Some((expires_at - now) / 1000)
1977 }
1978
1979 fn token_needs_refresh(expires_at: Option<u64>) -> bool {
1980 let Some(expires_at) = expires_at else {
1981 return false;
1982 };
1983 let now = SystemTime::now()
1984 .duration_since(UNIX_EPOCH)
1985 .map(|duration| duration.as_millis() as u64)
1986 .unwrap_or(0);
1987 now.saturating_add(REFRESH_SKEW_MILLIS) >= expires_at
1988 }
1989
1990 struct CallbackServerGuard {
1991 accept_task: tokio::task::JoinHandle<()>,
1992 }
1993
1994 impl Drop for CallbackServerGuard {
1995 fn drop(&mut self) {
1996 // Aborting drops the accept future and its owned listener instead of
1997 // leaving a detached task holding a fixed callback port indefinitely.
1998 self.accept_task.abort();
1999 }
2000 }
2001
2002 struct OauthLoginFlow {
2003 auth_url: String,
2004 oauth_state: OAuthState,
2005 rx: oneshot::Receiver<CallbackResult>,
2006 guard: CallbackServerGuard,
2007 server_name: String,
2008 server_url: String,
2009 binding: McpOAuthBinding,
2010 }
2011
2012 impl OauthLoginFlow {
2013 #[allow(clippy::too_many_arguments)]
2014 async fn new(
2015 server_name: &str,
2016 server_url: &str,
2017 client: McpHttpClient,
2018 scopes: &[String],
2019 oauth: Option<&super::McpServerOAuthConfig>,
2020 oauth_resource: Option<&str>,
2021 callback_port: Option<u16>,
2022 callback_url: Option<&str>,
2023 ) -> Result<Self> {
2024 let bind_host = callback_bind_host(callback_url);
2025 let bind_addr = match callback_port {
2026 Some(0) => bail!("invalid MCP OAuth callback port 0"),
2027 Some(port) => format!("{bind_host}:{port}"),
2028 None => format!("{bind_host}:0"),
2029 };
2030 let listener = TcpListener::bind(&bind_addr)
2031 .await
2032 .map_err(|err| anyhow!(err))?;
2033 let redirect_uri = resolve_redirect_uri(&listener, callback_url)?;
2034 let callback_id = callback_id_from_server_url(server_url)?;
2035 let redirect_uri = append_callback_id_to_redirect_uri(&redirect_uri, &callback_id)?;
2036 let callback_path = callback_path_from_redirect_uri(&redirect_uri)?;
2037
2038 let scope_refs: Vec<&str> = scopes.iter().map(String::as_str).collect();
2039 let (oauth_state, binding, callback_states) = match start_authorization(
2040 server_url,
2041 client,
2042 &scope_refs,
2043 &redirect_uri,
2044 oauth,
2045 oauth_resource,
2046 )
2047 .await
2048 {
2049 Ok(prepared) => {
2050 note_dynamic_registration(server_name, server_url, true);
2051 prepared
2052 }
2053 Err(error) if error_is_dynamic_registration_unsupported(&error) => {
2054 note_dynamic_registration(server_name, server_url, false);
2055 return Err(anyhow!(
2056 "MCP server '{server_name}' cannot complete an OAuth login: {}. {}",
2057 dynamic_registration_failure(&error),
2058 dynamic_registration_guidance()
2059 ));
2060 }
2061 Err(error) => return Err(error),
2062 };
2063 let auth_url = oauth_state.get_authorization_url().await?;
2064 anyhow::ensure!(
2065 authorization_request_parameter(&auth_url, "resource")? == binding.resource,
2066 "MCP OAuth authorization resource changed during preparation"
2067 );
2068 let (tx, rx) = oneshot::channel();
2069 let guard = CallbackServerGuard {
2070 accept_task: spawn_callback_server(listener, tx, callback_path, callback_states),
2071 };
2072 // #6040: logout clears this machine's token only — the provider keeps
2073 // its standing grant. Without a forced prompt the next login silently
2074 // re-grants it (same account/workspace, no picker ever shown), so an
2075 // explicit login could never change the authorized workspace.
2076 let auth_url = append_query_param(&auth_url, "prompt", Some("consent"));
2077
2078 Ok(Self {
2079 auth_url,
2080 oauth_state,
2081 rx,
2082 guard,
2083 server_name: server_name.to_string(),
2084 server_url: server_url.to_string(),
2085 binding,
2086 })
2087 }
2088
2089 async fn finish(self) -> Result<()> {
2090 self.finish_with_announce(OAuthLoginAnnounce::Terminal)
2091 .await
2092 }
2093
2094 async fn finish_with_announce(mut self, announce: OAuthLoginAnnounce) -> Result<()> {
2095 match announce {
2096 OAuthLoginAnnounce::Terminal => {
2097 println!(
2098 "Authorize `{}` by opening this URL in your browser:\n{}\n",
2099 self.server_name, self.auth_url
2100 );
2101 if webbrowser::open(&self.auth_url).is_err() {
2102 eprintln!("Browser launch failed; copy the URL above manually.");
2103 }
2104 println!(
2105 "Waiting for browser authorization for MCP server '{}'...",
2106 self.server_name
2107 );
2108 }
2109 OAuthLoginAnnounce::Tool { open_browser } => {
2110 // A tool call is not a terminal: nothing goes to stdout. The
2111 // tool result carries the URL for the model to relay; the
2112 // browser open is a best-effort convenience on top.
2113 if open_browser {
2114 let _ = webbrowser::open(&self.auth_url);
2115 }
2116 }
2117 }
2118
2119 let result = async {
2120 // Allow time for the user to finish browser authentication and 2FA.
2121 let callback = timeout(Duration::from_secs(900), &mut self.rx)
2122 .await
2123 .with_context(|| {
2124 let retry_hint = match announce {
2125 OAuthLoginAnnounce::Terminal => "Retry from a terminal, or use a background shell (background=true) if an agent is running the login flow.".to_string(),
2126 OAuthLoginAnnounce::Tool { .. } => format!(
2127 "The user can complete the sign-in directly via `/mcp login {}` or `codewhale mcp login {}`, then this tool can be called again.",
2128 self.server_name, self.server_name
2129 ),
2130 };
2131 format!(
2132 "timed out waiting for OAuth callback for MCP server '{}'. {retry_hint}",
2133 self.server_name
2134 )
2135 })?
2136 .context("OAuth callback was cancelled")?;
2137 let OauthCallbackResult {
2138 code,
2139 state,
2140 issuer,
2141 } = match callback {
2142 CallbackResult::Success(callback) => callback,
2143 CallbackResult::Error(error) => return Err(anyhow!(error)),
2144 };
2145
2146 // RFC 9207: servers that advertise
2147 // `authorization_response_iss_parameter_supported` send `iss` on the
2148 // redirect and rmcp requires it back; forward it so the callback binds
2149 // to the discovered issuer instead of failing as "missing".
2150 self.oauth_state
2151 .handle_callback_with_issuer(&code, &state, issuer.as_deref())
2152 .await
2153 .context("handling MCP OAuth callback")?;
2154
2155 let (client_id, credentials) = self
2156 .oauth_state
2157 .get_credentials()
2158 .await
2159 .context("reading MCP OAuth credentials")?;
2160 let credentials =
2161 credentials.ok_or_else(|| anyhow!("OAuth provider did not return credentials"))?;
2162 let stored = StoredMcpOAuthTokens {
2163 server_name: self.server_name.clone(),
2164 url: self.server_url.clone(),
2165 client_id,
2166 binding: Some(self.binding.clone()),
2167 expires_at: compute_expires_at_millis(&credentials),
2168 token_response: WrappedOAuthTokenResponse(credentials),
2169 };
2170 save_oauth_tokens(&stored)
2171 }
2172 .await;
2173
2174 drop(self.guard);
2175 result
2176 }
2177 }
2178
2179 async fn start_authorization(
2180 server_url: &str,
2181 client: McpHttpClient,
2182 scopes: &[&str],
2183 redirect_uri: &str,
2184 oauth: Option<&super::McpServerOAuthConfig>,
2185 oauth_resource: Option<&str>,
2186 ) -> Result<(OAuthState, McpOAuthBinding, InMemoryStateStore)> {
2187 let http_client = Arc::new(RecordingOAuthHttpClient::new(client));
2188 let (mut manager, binding) = prepare_authorization_manager(server_url, &http_client).await?;
2189 if let Some(resource) = oauth_resource {
2190 anyhow::ensure!(
2191 resource == binding.resource,
2192 "Configured MCP OAuth resource differs from the discovered resource"
2193 );
2194 }
2195 let callback_states = InMemoryStateStore::new();
2196 manager.set_state_store(callback_states.clone());
2197 if let Some(issuer) = oauth.and_then(|oauth| oauth.issuer.as_deref()) {
2198 anyhow::ensure!(
2199 issuer == binding.issuer,
2200 "Configured MCP OAuth issuer does not match the discovered authorization server"
2201 );
2202 }
2203 if let Some(client_id) = oauth.and_then(|oauth| oauth.client_id.as_deref()) {
2204 anyhow::ensure!(
2205 !client_id.trim().is_empty(),
2206 "MCP OAuth client_id must not be empty"
2207 );
2208 anyhow::ensure!(
2209 oauth.and_then(|oauth| oauth.issuer.as_deref()).is_some(),
2210 "Pre-registered MCP OAuth clients require oauth.issuer matching the registration authority"
2211 );
2212 }
2213 if let Some(metadata_url) = oauth.and_then(|oauth| oauth.client_metadata_url.as_deref()) {
2214 let url = Url::parse(metadata_url).context("invalid MCP OAuth client metadata URL")?;
2215 anyhow::ensure!(
2216 url.scheme() == "https"
2217 && url.host_str().is_some()
2218 && url.path() != "/"
2219 && !url.path().is_empty()
2220 && url.fragment().is_none()
2221 && url.username().is_empty()
2222 && url.password().is_none(),
2223 "MCP OAuth client metadata URL must be an HTTPS URL with a non-root path and no credentials or fragment"
2224 );
2225 }
2226 let mut attempt_scopes: Vec<String> = scopes.iter().map(|scope| (*scope).to_string()).collect();
2227 for retried in [false, true] {
2228 let mut request = AuthorizationRequest::new(redirect_uri)
2229 .with_scopes(attempt_scopes.iter().map(String::as_str))
2230 .with_client_name("Codewhale")
2231 .with_application_type("native");
2232 if let Some(client_id) = oauth.and_then(|oauth| oauth.client_id.as_deref()) {
2233 request = request.with_preregistered_client(client_id);
2234 }
2235 if let Some(metadata_url) = oauth.and_then(|oauth| oauth.client_metadata_url.as_deref()) {
2236 request = request.with_client_metadata_url(metadata_url);
2237 }
2238 match AuthorizationSession::new(manager, request).await {
2239 Ok(session) => return Ok((OAuthState::Session(session), binding, callback_states)),
2240 Err((returned, error)) => {
2241 manager = returned;
2242 if retried || attempt_scopes.is_empty() {
2243 return Err(error.into());
2244 }
2245 let Some(narrowed) =
2246 scopes_after_registration_rejection(&attempt_scopes, &error.to_string())
2247 else {
2248 return Err(error.into());
2249 };
2250 tracing::warn!(target: "mcp::oauth", server_url,
2251 dropped = attempt_scopes.len() - narrowed.len(),
2252 "OAuth client registration rejected part of the requested scope list; retrying with the accepted scopes");
2253 attempt_scopes = narrowed;
2254 }
2255 }
2256 }
2257 unreachable!("registration retry loop returns on success or error")
2258 }
2259
2260 /// Given a registration failure message, return the scopes to retry with, or
2261 /// `None` when the failure is not about scopes. Servers that validate the
2262 /// `scope` field report positions like `scope.3: Invalid option`; those exact
2263 /// entries are dropped. A scope error without positions retries with no
2264 /// scopes at all, letting the server grant its defaults.
2265 fn scopes_after_registration_rejection(scopes: &[String], message: &str) -> Option<Vec<String>> {
2266 let lower = message.to_ascii_lowercase();
2267 if !(lower.contains("registration") && lower.contains("scope")) {
2268 return None;
2269 }
2270 let mut rejected = std::collections::BTreeSet::new();
2271 for (start, _) in message.match_indices("scope.") {
2272 let digits: String = message[start + "scope.".len()..]
2273 .chars()
2274 .take_while(char::is_ascii_digit)
2275 .collect();
2276 if let Ok(index) = digits.parse::<usize>() {
2277 rejected.insert(index);
2278 }
2279 }
2280 let narrowed: Vec<String> = scopes
2281 .iter()
2282 .enumerate()
2283 .filter(|(index, _)| !rejected.contains(index))
2284 .map(|(_, scope)| scope.clone())
2285 .collect();
2286 if narrowed.len() == scopes.len() {
2287 // The server complained about scopes without naming any position:
2288 // the only safe retry is to omit the field.
2289 return Some(Vec::new());
2290 }
2291 Some(narrowed)
2292 }
2293
2294 fn spawn_callback_server(
2295 listener: TcpListener,
2296 tx: oneshot::Sender<CallbackResult>,
2297 expected_callback_path: String,
2298 callback_states: InMemoryStateStore,
2299 ) -> tokio::task::JoinHandle<()> {
2300 tokio::spawn(async move {
2301 // The sender is wrapped in Option so we can take it on success/error
2302 let mut tx_opt = Some(tx);
2303 loop {
2304 let (mut stream, _) = match listener.accept().await {
2305 Ok(pair) => pair,
2306 Err(_) => break,
2307 };
2308 let path = match timeout(Duration::from_secs(5), read_http_path(&mut stream)).await {
2309 Ok(Some(p)) => p,
2310 _ => {
2311 let _ = write_http_response(&mut stream, 400, "Invalid OAuth callback").await;
2312 continue;
2313 }
2314 };
2315 let callback = parse_oauth_callback(&path, &expected_callback_path);
2316 let binding = match &callback {
2317 CallbackOutcome::Success(callback) => {
2318 Some((callback.state.as_str(), callback.issuer.as_deref()))
2319 }
2320 CallbackOutcome::Error { state, issuer, .. } => {
2321 Some((state.as_str(), issuer.as_deref()))
2322 }
2323 CallbackOutcome::Invalid => None,
2324 };
2325 let valid = if let Some((state, issuer)) = binding {
2326 callback_binding_is_valid(&callback_states, state, issuer).await
2327 } else {
2328 false
2329 };
2330 if !valid {
2331 let _ = write_http_response(&mut stream, 400, "Invalid OAuth callback").await;
2332 continue;
2333 }
2334 match callback {
2335 CallbackOutcome::Success(callback) => {
2336 let _ = write_http_response(
2337 &mut stream,
2338 200,
2339 "Authorization response received. Return to Codewhale to finish signing in.",
2340 )
2341 .await;
2342 if let Some(tx) = tx_opt.take() {
2343 let _ = tx.send(CallbackResult::Success(callback));
2344 }
2345 break;
2346 }
2347 CallbackOutcome::Error { error, state, .. } => {
2348 if callback_states.delete(&state).await.is_err() {
2349 let _ =
2350 write_http_response(&mut stream, 400, "Invalid OAuth callback").await;
2351 continue;
2352 }
2353 let msg = mask_oauth_secrets(&error.to_string());
2354 let _ = write_http_response(&mut stream, 400, &msg).await;
2355 if let Some(tx) = tx_opt.take() {
2356 let _ = tx.send(CallbackResult::Error(error));
2357 }
2358 break;
2359 }
2360 CallbackOutcome::Invalid => {
2361 let _ = write_http_response(&mut stream, 400, "Invalid OAuth callback").await;
2362 }
2363 }
2364 }
2365 })
2366 }
2367
2368 async fn callback_binding_is_valid(
2369 states: &InMemoryStateStore,
2370 state: &str,
2371 issuer: Option<&str>,
2372 ) -> bool {
2373 let Ok(Some(stored)) = states.load(state).await else {
2374 return false;
2375 };
2376 let Some(expected) = stored.expected_issuer.as_deref() else {
2377 return false;
2378 };
2379 issuer.map_or(!stored.require_issuer, |issuer| issuer == expected)
2380 }
2381
2382 async fn read_http_path(stream: &mut tokio::net::TcpStream) -> Option<String> {
2383 let mut buf = Vec::new();
2384 let mut tmp = [0u8; 1024];
2385 // Read until we have \r\n\r\n or exceed limit
2386 loop {
2387 match stream.read(&mut tmp).await {
2388 Ok(0) => break,
2389 Ok(n) => {
2390 buf.extend_from_slice(&tmp[..n]);
2391 if buf.len() > 8192 {
2392 return None;
2393 }
2394 if buf.windows(4).any(|w| w == b"\r\n\r\n") {
2395 break;
2396 }
2397 }
2398 Err(_) => return None,
2399 }
2400 }
2401 let request = String::from_utf8_lossy(&buf);
2402 let first_line = request.lines().next()?;
2403 // Expected: GET /callback?code=... HTTP/1.1
2404 let mut parts = first_line.split_whitespace();
2405 if parts.next()? != "GET" {
2406 return None;
2407 }
2408 let path = parts.next()?.to_string();
2409 Some(path)
2410 }
2411
2412 async fn write_http_response(
2413 stream: &mut tokio::net::TcpStream,
2414 status: u16,
2415 body: &str,
2416 ) -> std::io::Result<()> {
2417 let status_text = match status {
2418 200 => "OK",
2419 400 => "Bad Request",
2420 _ => "OK",
2421 };
2422 let response = format!(
2423 "HTTP/1.1 {status} {status_text}\r\nContent-Length: {}\r\nContent-Type: text/plain\r\nConnection: close\r\n\r\n{body}",
2424 body.len()
2425 );
2426 stream.write_all(response.as_bytes()).await?;
2427 stream.flush().await?;
2428 Ok(())
2429 }
2430
2431 #[derive(Debug, Clone, PartialEq, Eq)]
2432 struct OauthCallbackResult {
2433 code: String,
2434 state: String,
2435 /// RFC 9207 `iss` from the redirect, when the authorization server sends it.
2436 issuer: Option<String>,
2437 }
2438
2439 enum CallbackResult {
2440 Success(OauthCallbackResult),
2441 Error(OAuthProviderError),
2442 }
2443
2444 #[derive(Debug, Clone, PartialEq, Eq)]
2445 enum CallbackOutcome {
2446 Success(OauthCallbackResult),
2447 Error {
2448 error: OAuthProviderError,
2449 state: String,
2450 issuer: Option<String>,
2451 },
2452 Invalid,
2453 }
2454
2455 fn parse_oauth_callback(path: &str, expected_callback_path: &str) -> CallbackOutcome {
2456 let Some((route, query)) = path.split_once('?') else {
2457 return CallbackOutcome::Invalid;
2458 };
2459 if route != expected_callback_path {
2460 return CallbackOutcome::Invalid;
2461 }
2462
2463 let mut parameters = HashMap::new();
2464 for (key, value) in url::form_urlencoded::parse(query.as_bytes()) {
2465 if matches!(
2466 key.as_ref(),
2467 "code" | "state" | "iss" | "error" | "error_description"
2468 ) && parameters
2469 .insert(key.into_owned(), value.into_owned())
2470 .is_some()
2471 {
2472 return CallbackOutcome::Invalid;
2473 }
2474 }
2475 let Some(state) = parameters.remove("state").filter(|state| !state.is_empty()) else {
2476 return CallbackOutcome::Invalid;
2477 };
2478 let code = parameters.remove("code");
2479 let issuer = parameters.remove("iss");
2480 let error = parameters.remove("error");
2481 let error_description = parameters.remove("error_description");
2482 if code.is_some() && (error.is_some() || error_description.is_some()) {
2483 return CallbackOutcome::Invalid;
2484 }
2485 if let Some(code) = code.filter(|code| !code.is_empty()) {
2486 return CallbackOutcome::Success(OauthCallbackResult {
2487 code,
2488 state,
2489 issuer,
2490 });
2491 }
2492 if let Some(error) = error.filter(|error| !error.is_empty()) {
2493 return CallbackOutcome::Error {
2494 error: OAuthProviderError::new(Some(error), error_description),
2495 state,
2496 issuer,
2497 };
2498 }
2499 CallbackOutcome::Invalid
2500 }
2501
2502 fn local_redirect_uri(listener: &TcpListener) -> Result<String> {
2503 let addr = listener.local_addr()?;
2504 match addr {
2505 std::net::SocketAddr::V4(v4) => Ok(format!("http://{}:{}/callback", v4.ip(), v4.port())),
2506 std::net::SocketAddr::V6(v6) => Ok(format!("http://[{}]:{}/callback", v6.ip(), v6.port())),
2507 }
2508 }
2509
2510 fn resolve_redirect_uri(listener: &TcpListener, callback_url: Option<&str>) -> Result<String> {
2511 let Some(callback_url) = callback_url else {
2512 return local_redirect_uri(listener);
2513 };
2514 Url::parse(callback_url)
2515 .with_context(|| format!("invalid MCP OAuth callback URL '{callback_url}'"))?;
2516 Ok(callback_url.to_string())
2517 }
2518
2519 fn callback_bind_host(callback_url: Option<&str>) -> &'static str {
2520 let Some(callback_url) = callback_url else {
2521 return "127.0.0.1";
2522 };
2523 let Ok(parsed) = Url::parse(callback_url) else {
2524 return "127.0.0.1";
2525 };
2526 match parsed.host_str() {
2527 Some("localhost" | "127.0.0.1" | "::1") | None => "127.0.0.1",
2528 Some(_) => "0.0.0.0",
2529 }
2530 }
2531
2532 fn callback_id_from_server_url(server_url: &str) -> Result<String> {
2533 let mut parsed =
2534 Url::parse(server_url).with_context(|| format!("invalid MCP server URL '{server_url}'"))?;
2535 parsed
2536 .host_str()
2537 .ok_or_else(|| anyhow!("MCP server URL '{server_url}' must include a host"))?;
2538 parsed.set_fragment(None);
2539 let digest = Sha256::digest(parsed.as_str().as_bytes());
2540 Ok(URL_SAFE_NO_PAD.encode(&digest[..9]))
2541 }
2542
2543 fn append_callback_id_to_redirect_uri(redirect_uri: &str, callback_id: &str) -> Result<String> {
2544 let mut parsed = Url::parse(redirect_uri)
2545 .with_context(|| format!("invalid redirect URI '{redirect_uri}'"))?;
2546 let path = parsed.path();
2547 let new_path = if path.ends_with('/') {
2548 format!("{path}{callback_id}")
2549 } else {
2550 format!("{path}/{callback_id}")
2551 };
2552 parsed.set_path(&new_path);
2553 Ok(parsed.to_string())
2554 }
2555
2556 fn callback_path_from_redirect_uri(redirect_uri: &str) -> Result<String> {
2557 let parsed = Url::parse(redirect_uri)
2558 .with_context(|| format!("invalid redirect URI '{redirect_uri}'"))?;
2559 Ok(parsed.path().to_string())
2560 }
2561
2562 fn append_query_param(url: &str, key: &str, value: Option<&str>) -> String {
2563 let Some(value) = value else {
2564 return url.to_string();
2565 };
2566 let value = value.trim();
2567 if value.is_empty() {
2568 return url.to_string();
2569 }
2570 if let Ok(mut parsed) = Url::parse(url) {
2571 parsed.query_pairs_mut().append_pair(key, value);
2572 return parsed.to_string();
2573 }
2574 let separator = if url.contains('?') { "&" } else { "?" };
2575 format!("{url}{separator}{key}={}", urlencoding::encode(value))
2576 }
2577
2578 pub trait McpServerConfigOAuthExt {
2579 fn oauth_client_id(&self) -> Option<&str>;
2580 }
2581
2582 impl McpServerConfigOAuthExt for McpServerConfig {
2583 fn oauth_client_id(&self) -> Option<&str> {
2584 self.oauth
2585 .as_ref()
2586 .and_then(|oauth| oauth.client_id.as_deref())
2587 }
2588 }
2589
2590 #[cfg(test)]
2591 mod tests {
2592 #[test]
2593 fn typed_oauth_client_requires_https_or_explicit_loopback_without_header_guessing() {
2594 codewhale_release::tls::ensure_rustls_crypto_provider();
2595 let server: super::McpServerConfig = serde_json::from_value(serde_json::json!({
2596 "url": "https://example.invalid/mcp"
2597 }))
2598 .unwrap();
2599 let error = super::oauth_http_client(&server, "http://example.invalid/mcp", None)
2600 .err()
2601 .expect("OAuth form credentials must not use public HTTP");
2602 assert!(error.to_string().contains("credentials require HTTPS"));
2603 assert!(super::oauth_http_client(&server, "https://example.invalid/mcp", None).is_ok());
2604 assert!(super::oauth_http_client(&server, "http://127.0.0.1/mcp", None).is_ok());
2605 assert!(
2606 super::oauth_http_client(
2607 &server,
2608 "https://fixture-user:fixture-password@example.invalid/mcp",
2609 None
2610 )
2611 .is_err()
2612 );
2613 }
2614
2615 #[test]
2616 fn registration_rejection_drops_exactly_the_named_scopes() {
2617 let scopes: Vec<String> = ["a", "b", "c", "d"].iter().map(|s| s.to_string()).collect();
2618 let message = concat!(
2619 "Registration failed: Dynamic registration failed: HTTP 400 Bad Request: ",
2620 "{\"message\":\"scope.1: Invalid option: expected one of \\\"a\\\"|\\\"c\\\",",
2621 "scope.3: Invalid option\"}"
2622 );
2623 assert_eq!(
2624 super::scopes_after_registration_rejection(&scopes, message),
2625 Some(vec!["a".to_string(), "c".to_string()])
2626 );
2627 // A scope complaint without positions retries without scopes.
2628 assert_eq!(
2629 super::scopes_after_registration_rejection(
2630 &scopes,
2631 "Registration failed: invalid scope"
2632 ),
2633 Some(Vec::new())
2634 );
2635 // Unrelated registration failures are not retried.
2636 assert_eq!(
2637 super::scopes_after_registration_rejection(&scopes, "Registration failed: HTTP 500"),
2638 None
2639 );
2640 assert_eq!(
2641 super::scopes_after_registration_rejection(&scopes, "network unreachable"),
2642 None
2643 );
2644 }
2645
2646 #[test]
2647 fn a_refresh_parse_failure_names_the_login_remedy_and_the_server() {
2648 let text = super::refresh_failure_context("supabase", true, None);
2649 assert!(text.contains("server supabase"));
2650 assert!(text.contains("codewhale mcp login supabase"), "{text}");
2651 assert!(text.contains("/mcp login supabase"), "{text}");
2652 assert!(!text.contains("it answered"), "{text}");
2653 // An auth-required failure keeps the plain context: the typed state
2654 // and the login tool already carry the remedy.
2655 let plain = super::refresh_failure_context("supabase", false, None);
2656 assert_eq!(plain, "refreshing MCP OAuth token for server supabase");
2657 }
2658
2659 #[test]
2660 fn a_refresh_parse_failure_keeps_the_token_endpoints_receipt() {
2661 // The supabase receipt (#5926): rmcp said only "Failed to parse
2662 // server response". With the status line and a masked excerpt the
2663 // operator can tell a provider's HTML 502 from our parser.
2664 let mut headers = HeaderMap::new();
2665 headers.insert(
2666 CONTENT_TYPE,
2667 HeaderValue::from_static("text/html; charset=utf-8"),
2668 );
2669 let receipt = TokenEndpointReceipt::from_response(
2670 reqwest::StatusCode::BAD_GATEWAY,
2671 &headers,
2672 b"<html>\n <body>502 Bad Gateway</body>\n</html>",
2673 );
2674 let text = super::refresh_failure_context("supabase", true, Some(&receipt));
2675 assert!(
2676 text.contains(
2677 "it answered HTTP 502 Bad Gateway (text/html; charset=utf-8): <html> <body>502 Bad Gateway</body> </html>"
2678 ),
2679 "{text}"
2680 );
2681 assert!(text.contains("codewhale mcp login supabase"), "{text}");
2682 }
2683
2684 #[test]
2685 fn a_token_receipt_masks_credentials_before_it_cuts_the_body() {
2686 let secret = "sk-live-0123456789abcdef";
2687 let long_tail = "x".repeat(400);
2688 let body = format!(
2689 "{{\"token_type\":\"Bearer\",\"access_token\":\"{secret}\",\"refresh_token\": \"{secret}-r\",\"id_token\":\"{secret}-id\",\"expires_in\":\"soon\",\"note\":\"{long_tail}\"}}"
2690 );
2691 let mut headers = HeaderMap::new();
2692 headers.insert(CONTENT_TYPE, HeaderValue::from_static("application/json"));
2693 let receipt =
2694 TokenEndpointReceipt::from_response(reqwest::StatusCode::OK, &headers, body.as_bytes());
2695 let text = receipt.to_string();
2696 assert!(!text.contains(secret), "{text}");
2697 assert!(text.contains("\"access_token\":\"***\""), "{text}");
2698 assert!(text.contains("\"refresh_token\": \"***\""), "{text}");
2699 assert!(text.contains("\"id_token\":\"***\""), "{text}");
2700 // Non-secret members survive so the shape of the answer is readable.
2701 assert!(text.contains("\"expires_in\":\"soon\""), "{text}");
2702 assert!(text.contains("\"token_type\":\"Bearer\""), "{text}");
2703 assert!(text.ends_with('…'), "{text}");
2704 assert!(receipt.excerpt.len() <= TOKEN_RECEIPT_EXCERPT_BYTES + '…'.len_utf8());
2705 }
2706
2707 #[test]
2708 fn oauth_secret_masking_covers_form_pairs_bearer_schemes_and_case() {
2709 assert_eq!(
2710 mask_oauth_secrets("client_secret=abc123&grant_type=refresh_token&refresh_token=zzz"),
2711 "client_secret=***&grant_type=refresh_token&refresh_token=***"
2712 );
2713 assert_eq!(
2714 mask_oauth_secrets("Authorization: Bearer eyJhbGciOi.payload.sig, retry"),
2715 "Authorization: ***, retry"
2716 );
2717 assert_eq!(
2718 mask_oauth_secrets("{\"Access_Token\": \"quoted \\\" inside\", \"scope\": \"read\"}"),
2719 "{\"Access_Token\": \"***\", \"scope\": \"read\"}"
2720 );
2721 // A field name that merely contains a secret name is not a secret.
2722 assert_eq!(
2723 mask_oauth_secrets("{\"error_code\":\"invalid_request\",\"my_access_token_count\":3}"),
2724 "{\"error_code\":\"invalid_request\",\"my_access_token_count\":3}"
2725 );
2726 // Multi-byte text around a secret stays intact.
2727 assert_eq!(
2728 mask_oauth_secrets("トークン access_token=秘密 終わり"),
2729 "トークン access_token=*** 終わり"
2730 );
2731 }
2732
2733 #[test]
2734 fn a_token_receipt_names_an_empty_body_and_a_missing_content_type() {
2735 let receipt = TokenEndpointReceipt::from_response(
2736 reqwest::StatusCode::SERVICE_UNAVAILABLE,
2737 &HeaderMap::new(),
2738 b"",
2739 );
2740 assert_eq!(
2741 receipt.to_string(),
2742 "HTTP 503 Service Unavailable (no content-type) with an empty body"
2743 );
2744 }
2745
2746 use super::*;
2747 use std::sync::atomic::{AtomicBool, Ordering};
2748
2749 #[test]
2750 fn stored_credential_identity_ignores_only_a_derived_expiry_countdown() {
2751 let original = serde_json::json!({
2752 "server_name": "fixture", "url": "https://example.invalid/mcp",
2753 "client_id": "fixture-client", "expires_at": 9_999_999_999_999_u64,
2754 "binding": { "issuer": "https://example.invalid", "resource": "https://example.invalid/mcp" },
2755 "token_response": {
2756 "access_token": "fixture-access", "refresh_token": "fixture-refresh",
2757 "token_type": "Bearer", "expires_in": 3600, "scope": "read"
2758 }
2759 });
2760 let held: StoredMcpOAuthTokens = serde_json::from_value(original.clone()).unwrap();
2761 let mut aged = original.clone();
2762 aged["token_response"]["expires_in"] = serde_json::json!(3598);
2763 let loaded: StoredMcpOAuthTokens = serde_json::from_value(aged.clone()).unwrap();
2764 assert!(
2765 held == loaded,
2766 "elapsed time alone is not credential rotation"
2767 );
2768 for (field, value) in [
2769 ("access_token", "new-access"),
2770 ("refresh_token", "new-refresh"),
2771 ("scope", "read write"),
2772 ("token_type", "Mac"),
2773 ] {
2774 let mut rotated = aged.clone();
2775 rotated["token_response"][field] = serde_json::json!(value);
2776 let rotated: StoredMcpOAuthTokens = serde_json::from_value(rotated).unwrap();
2777 assert!(
2778 held != rotated,
2779 "a changed {field} remains a distinct credential"
2780 );
2781 }
2782 for (field, value) in [
2783 ("server_name", serde_json::json!("other")),
2784 ("client_id", serde_json::json!("other-client")),
2785 ("url", serde_json::json!("https://other.invalid/mcp")),
2786 (
2787 "binding",
2788 serde_json::json!({"issuer":"https://other.invalid", "resource":"https://example.invalid/mcp"}),
2789 ),
2790 (
2791 "binding",
2792 serde_json::json!({"issuer":"https://example.invalid", "resource":"https://other.invalid/mcp"}),
2793 ),
2794 ("expires_at", serde_json::json!(9_999_999_999_998_u64)),
2795 ] {
2796 let mut rotated = aged.clone();
2797 rotated[field] = value;
2798 let rotated: StoredMcpOAuthTokens = serde_json::from_value(rotated).unwrap();
2799 assert!(
2800 held != rotated,
2801 "a changed {field} remains a distinct credential"
2802 );
2803 }
2804 let mut unbound = original.clone();
2805 unbound.as_object_mut().unwrap().remove("binding");
2806 let unbound: StoredMcpOAuthTokens = serde_json::from_value(unbound).unwrap();
2807 assert!(unbound.binding.is_none());
2808 assert!(!oauth_tokens_are_usable(&unbound));
2809 assert!(oauth_tokens_are_usable(&held));
2810 let mut legacy = held.clone();
2811 legacy.expires_at = None;
2812 let mut legacy_aged = loaded;
2813 legacy_aged.expires_at = None;
2814 assert!(
2815 legacy != legacy_aged,
2816 "without a durable deadline the stored lifetime is meaningful"
2817 );
2818 }
2819
2820 #[test]
2821 fn resolve_oauth_scopes_prefers_explicit() {
2822 let resolved = resolve_oauth_scopes(
2823 Some(vec!["explicit".to_string()]),
2824 vec!["configured".to_string()],
2825 Some(vec!["discovered".to_string()]),
2826 );
2827 assert_eq!(resolved.source, McpOAuthScopesSource::Explicit);
2828 assert_eq!(resolved.scopes, vec!["explicit"]);
2829 }
2830
2831 #[test]
2832 fn parse_oauth_callback_accepts_success() {
2833 let parsed = parse_oauth_callback("/callback/id?code=abc&state=xyz", "/callback/id");
2834 assert_eq!(
2835 parsed,
2836 CallbackOutcome::Success(OauthCallbackResult {
2837 code: "abc".to_string(),
2838 state: "xyz".to_string(),
2839 issuer: None,
2840 })
2841 );
2842 }
2843
2844 #[test]
2845 fn parse_oauth_callback_keeps_rfc9207_issuer() {
2846 // Cloudflare's MCP authorization server advertises
2847 // authorization_response_iss_parameter_supported and sends `iss` back;
2848 // dropping it makes rmcp reject the callback as missing a required issuer.
2849 let parsed = parse_oauth_callback(
2850 "/callback/id?code=abc&state=xyz&iss=https%3A%2F%2Fmcp.cloudflare.com",
2851 "/callback/id",
2852 );
2853 assert_eq!(
2854 parsed,
2855 CallbackOutcome::Success(OauthCallbackResult {
2856 code: "abc".to_string(),
2857 state: "xyz".to_string(),
2858 issuer: Some("https://mcp.cloudflare.com".to_string()),
2859 })
2860 );
2861 }
2862
2863 #[test]
2864 fn parse_oauth_callback_accepts_provider_error() {
2865 let parsed = parse_oauth_callback(
2866 "/callback/id?error=invalid_scope&error_description=not+allowed&state=xyz&iss=https%3A%2F%2Fissuer.invalid",
2867 "/callback/id",
2868 );
2869 assert_eq!(
2870 parsed,
2871 CallbackOutcome::Error {
2872 error: OAuthProviderError::new(
2873 Some("invalid_scope".to_string()),
2874 Some("not allowed".to_string())
2875 ),
2876 state: "xyz".to_string(),
2877 issuer: Some("https://issuer.invalid".to_string()),
2878 }
2879 );
2880 for query in [
2881 "error=denied",
2882 "error=denied&state=",
2883 "error=denied&state=a&state=b",
2884 "code=ok&error=denied&state=a",
2885 "code=ok&state=a&iss=a&iss=b",
2886 "error_description=denied&state=a",
2887 "code=&state=a",
2888 ] {
2889 assert_eq!(
2890 parse_oauth_callback(&format!("/callback/id?{query}"), "/callback/id"),
2891 CallbackOutcome::Invalid
2892 );
2893 }
2894 }
2895
2896 #[test]
2897 fn store_key_does_not_include_raw_url_or_name() {
2898 let key = store_key("github", "https://example.com/mcp");
2899 assert!(key.starts_with("mcp_oauth_"));
2900 assert!(!key.contains("github"));
2901 assert!(!key.contains("example.com"));
2902 }
2903
2904 #[test]
2905 fn malformed_stored_oauth_diagnostic_omits_secret_contents_and_keys() {
2906 let secret = "cw-secret-mcp-oauth-4507";
2907 let serialized =
2908 format!(r#"{{"token_response":{{"access_token":"{secret}"}} trailing-junk}}"#);
2909 let error = parse_stored_oauth_tokens(&serialized, "private")
2910 .expect_err("malformed credential JSON must fail");
2911 let diagnostic = format!("{error:#}");
2912 assert!(!diagnostic.contains(secret), "{diagnostic}");
2913 assert!(!diagnostic.contains("access_token"), "{diagnostic}");
2914 assert!(diagnostic.contains("contents were omitted"), "{diagnostic}");
2915 }
2916
2917 #[test]
2918 fn auth_required_classifier_matches_http_401_shapes() {
2919 let err = anyhow!("MCP Streamable HTTP rejected status=401 Unauthorized");
2920 assert!(error_looks_auth_required(&err));
2921
2922 let err = anyhow!("authentication_required for remote server");
2923 assert!(error_looks_auth_required(&err));
2924
2925 let err = anyhow!("connection refused");
2926 assert!(!error_looks_auth_required(&err));
2927
2928 assert!(error_text_looks_auth_required("HTTP 401 from upstream"));
2929 assert!(error_text_looks_auth_required("request failed (401)"));
2930 // The failure the classifier used to misread: a reset on a loopback
2931 // server whose ephemeral port contains 401 is a transport error.
2932 let reset = "error sending request for url (http://127.0.0.1:50401/mcp): \
2933 client error (SendRequest): connection closed before message completed";
2934 assert!(!error_text_looks_auth_required(reset), "{reset}");
2935 assert!(!error_text_looks_auth_required(
2936 "read 14010 bytes before the stream reset"
2937 ));
2938 }
2939
2940 #[test]
2941 fn auth_required_classifier_treats_rejected_grants_as_auth_required() {
2942 // A definitively rejected refresh grant is recoverable only by a
2943 // fresh login, so it must classify like a 401 on every surface.
2944 let err = anyhow!("refreshing MCP OAuth token for server wiki")
2945 .context("Server returned error response: invalid_grant: stale grant");
2946 assert!(error_looks_auth_required(&err));
2947 assert!(error_text_looks_auth_required(
2948 "wiki requires OAuth — run /mcp login wiki"
2949 ));
2950 assert!(error_text_looks_auth_required("wiki: ◆ auth required"));
2951 assert!(!error_text_looks_auth_required(
2952 "invalid_request: missing parameter"
2953 ));
2954 // rmcp's own `AuthError::AuthorizationRequired` wording: a stored
2955 // credential that can no longer be refreshed is a login, not a
2956 // transport failure.
2957 assert!(error_text_looks_auth_required(
2958 "refreshing MCP OAuth token for server wiki: OAuth authorization required"
2959 ));
2960 assert!(!error_text_looks_auth_required(
2961 "authorization required for the requested file"
2962 ));
2963 }
2964
2965 #[test]
2966 fn auth_required_login_hint_names_server() {
2967 let hint = auth_required_login_hint("nordic-mcp");
2968 assert!(hint.contains("nordic-mcp"));
2969 assert!(hint.contains("codewhale mcp login nordic-mcp"));
2970 assert!(!hint.contains("/mcp auth"));
2971 }
2972
2973 #[test]
2974 fn tui_reauth_hints_name_the_login_command() {
2975 for hint in [tui_reauth_hint(), tui_reauth_refresh_failed_hint()] {
2976 assert!(
2977 hint.contains("/mcp login <name>"),
2978 "OAuth recovery must name the implemented command"
2979 );
2980 assert!(
2981 !hint.contains("/mcp auth"),
2982 "OAuth recovery must not advertise a missing /mcp auth command"
2983 );
2984 }
2985 assert!(error_text_looks_auth_required(
2986 "MCP server rejected the request with 401 Unauthorized"
2987 ));
2988 assert!(!error_text_looks_auth_required("connection refused"));
2989 }
2990
2991 #[tokio::test]
2992 async fn cancellable_oauth_drops_in_flight_flow_before_returning() {
2993 struct DropFlag(Arc<AtomicBool>);
2994 impl Drop for DropFlag {
2995 fn drop(&mut self) {
2996 self.0.store(true, Ordering::SeqCst);
2997 }
2998 }
2999
3000 let cancellation_token = CancellationToken::new();
3001 let cancel_from_task = cancellation_token.clone();
3002 let dropped = Arc::new(AtomicBool::new(false));
3003 let flow_dropped = Arc::clone(&dropped);
3004 let pending_flow = async move {
3005 let _guard = DropFlag(flow_dropped);
3006 std::future::pending::<Result<()>>().await
3007 };
3008 tokio::spawn(async move {
3009 tokio::task::yield_now().await;
3010 cancel_from_task.cancel();
3011 });
3012
3013 let error = run_cancellable_oauth(&cancellation_token, pending_flow)
3014 .await
3015 .expect_err("cancellation should stop the pending OAuth flow");
3016
3017 assert!(error.to_string().contains("OAuth login was cancelled"));
3018 assert!(
3019 dropped.load(Ordering::SeqCst),
3020 "the callback-server guard must be dropped before cancellation returns"
3021 );
3022 }
3023
3024 #[tokio::test]
3025 async fn callback_guard_aborts_accept_task_and_releases_fixed_port() -> Result<()> {
3026 let listener = TcpListener::bind(("127.0.0.1", 0)).await?;
3027 let addr = listener.local_addr()?;
3028 let (tx, _rx) = oneshot::channel();
3029 let guard = CallbackServerGuard {
3030 accept_task: spawn_callback_server(
3031 listener,
3032 tx,
3033 "/callback/test".to_string(),
3034 InMemoryStateStore::new(),
3035 ),
3036 };
3037
3038 drop(guard);
3039
3040 let rebound = timeout(Duration::from_secs(1), async {
3041 loop {
3042 match TcpListener::bind(addr).await {
3043 Ok(listener) => break Ok(listener),
3044 Err(err) if err.kind() == std::io::ErrorKind::AddrInUse => {
3045 tokio::task::yield_now().await;
3046 }
3047 Err(err) => break Err(err),
3048 }
3049 }
3050 })
3051 .await
3052 .context("callback listener did not release its fixed port")??;
3053 drop(rebound);
3054 for success in [false, true] {
3055 let states = InMemoryStateStore::new();
3056 states
3057 .save(
3058 "expected-state",
3059 serde_json::from_value(serde_json::json!({
3060 "pkce_verifier": "fixture-verifier",
3061 "csrf_token": "expected-state",
3062 "expected_issuer": "https://issuer.invalid",
3063 "require_issuer": true,
3064 "created_at": 0,
3065 "requested_scopes": []
3066 }))?,
3067 )
3068 .await?;
3069 let listener = TcpListener::bind(("127.0.0.1", 0)).await?;
3070 let addr = listener.local_addr()?;
3071 let (tx, mut rx) = oneshot::channel();
3072 let guard = CallbackServerGuard {
3073 accept_task: spawn_callback_server(
3074 listener,
3075 tx,
3076 "/callback/test".to_string(),
3077 states.clone(),
3078 ),
3079 };
3080 for query in [
3081 "error=denied&state=wrong&iss=https%3A%2F%2Fissuer.invalid",
3082 "error=denied&state=expected-state",
3083 "error=denied&state=expected-state&iss=https%3A%2F%2Fother.invalid",
3084 "code=ok&state=expected-state&iss=https%3A%2F%2Fissuer.invalid%2F",
3085 ] {
3086 let mut stream = tokio::net::TcpStream::connect(addr).await?;
3087 stream
3088 .write_all(
3089 format!("GET /callback/test?{query} HTTP/1.1\r\nHost: localhost\r\n\r\n")
3090 .as_bytes(),
3091 )
3092 .await?;
3093 let mut response = String::new();
3094 timeout(Duration::from_secs(1), stream.read_to_string(&mut response)).await??;
3095 assert!(response.starts_with("HTTP/1.1 400"));
3096 assert!(matches!(
3097 rx.try_recv(),
3098 Err(tokio::sync::oneshot::error::TryRecvError::Empty)
3099 ));
3100 assert!(states.load("expected-state").await?.is_some());
3101 }
3102 let outcome = if success { "code=ok" } else { "error=denied" };
3103 let mut stream = tokio::net::TcpStream::connect(addr).await?;
3104 stream.write_all(format!("GET /callback/test?{outcome}&state=expected-state&iss=https%3A%2F%2Fissuer.invalid HTTP/1.1\r\nHost: localhost\r\n\r\n").as_bytes()).await?;
3105 let result = timeout(Duration::from_secs(1), rx).await??;
3106 assert_eq!(matches!(result, CallbackResult::Success(_)), success);
3107 assert_eq!(states.load("expected-state").await?.is_some(), success);
3108 if success {
3109 states.delete("expected-state").await?;
3110 }
3111 assert!(
3112 !callback_binding_is_valid(
3113 &states,
3114 "expected-state",
3115 Some("https://issuer.invalid")
3116 )
3117 .await
3118 );
3119 drop(guard);
3120 }
3121 Ok(())
3122 }
3123
3124 async fn guarded_oauth_fixture(
3125 token_target: Option<String>,
3126 redirect_token: bool,
3127 ) -> (
3128 String,
3129 Arc<std::sync::atomic::AtomicUsize>,
3130 tokio::task::JoinHandle<()>,
3131 ) {
3132 use std::sync::atomic::{AtomicUsize, Ordering};
3133 let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
3134 let addr = listener.local_addr().unwrap();
3135 let captured = Arc::new(AtomicUsize::new(0));
3136 let seen = Arc::clone(&captured);
3137 let task = tokio::spawn(async move {
3138 loop {
3139 let Ok((mut socket, _)) = listener.accept().await else {
3140 break;
3141 };
3142 let mut bytes = Vec::new();
3143 let mut buffer = [0u8; 2048];
3144 loop {
3145 let n = socket.read(&mut buffer).await.unwrap();
3146 if n == 0 {
3147 break;
3148 }
3149 bytes.extend_from_slice(&buffer[..n]);
3150 if bytes.windows(4).any(|part| part == b"\r\n\r\n") {
3151 break;
3152 }
3153 }
3154 let request = String::from_utf8_lossy(&bytes);
3155 let path = request.split_whitespace().nth(1).unwrap_or("");
3156 let (status, extra, body) = if path == "/.well-known/oauth-authorization-server" {
3157 ("200 OK", String::new(), serde_json::json!({
3158 "issuer": format!("http://{addr}"),
3159 "authorization_endpoint": format!("http://{addr}/authorize"),
3160 "token_endpoint": token_target.clone().unwrap_or_else(|| format!("http://{addr}/token")),
3161 "registration_endpoint": format!("http://{addr}/register"),
3162 "response_types_supported": ["code"]
3163 }).to_string())
3164 } else if path == "/token" && redirect_token {
3165 (
3166 "307 Redirect",
3167 "Location: /capture\r\n".to_string(),
3168 String::new(),
3169 )
3170 } else if path == "/token" || path == "/capture" {
3171 seen.fetch_add(1, Ordering::SeqCst);
3172 ("200 OK", String::new(), r#"{"access_token":"new-fixture","token_type":"Bearer","refresh_token":"fixture-refresh"}"#.to_string())
3173 } else if path == "/register" {
3174 (
3175 "200 OK",
3176 String::new(),
3177 r#"{"client_id":"fixture-client","redirect_uris":[]}"#.to_string(),
3178 )
3179 } else {
3180 ("404 Not Found", String::new(), String::new())
3181 };
3182 let response = format!(
3183 "HTTP/1.1 {status}\r\n{extra}Content-Type: application/json\r\nConnection: close\r\nContent-Length: {}\r\n\r\n{body}",
3184 body.len()
3185 );
3186 let _ = socket.write_all(response.as_bytes()).await;
3187 }
3188 });
3189 (format!("http://{addr}/mcp"), captured, task)
3190 }
3191
3192 async fn guarded_oauth_state(
3193 url: &str,
3194 network_policy: Option<&NetworkPolicyDecider>,
3195 ) -> AuthorizationManager {
3196 let client = McpHttpClient::new(
3197 url,
3198 false,
3199 false,
3200 false,
3201 network_policy,
3202 Duration::from_secs(1),
3203 Duration::from_secs(3),
3204 )
3205 .unwrap();
3206 let http = Arc::new(RecordingOAuthHttpClient::new(client));
3207 let stored: StoredMcpOAuthTokens = serde_json::from_value(serde_json::json!({
3208 "server_name":"fixture", "url":url, "client_id":"fixture-client",
3209 "binding":{"issuer":Url::parse(url).unwrap().origin().ascii_serialization(), "resource":Url::parse(url).unwrap().to_string()},
3210 "token_response":{"access_token":"fixture-access", "token_type":"Bearer", "refresh_token":"fixture-refresh"}
3211 })).unwrap();
3212 let mut unbound = stored.clone();
3213 unbound.binding = None;
3214 assert!(
3215 manager_from_stored_tokens(url, &unbound, &http)
3216 .await
3217 .is_err()
3218 );
3219 let mut mismatched = stored.clone();
3220 mismatched.binding.as_mut().unwrap().issuer.push('/');
3221 assert!(
3222 manager_from_stored_tokens(url, &mismatched, &http)
3223 .await
3224 .is_err()
3225 );
3226 mismatched = stored.clone();
3227 mismatched.binding.as_mut().unwrap().resource.push('/');
3228 assert!(
3229 manager_from_stored_tokens(url, &mismatched, &http)
3230 .await
3231 .is_err()
3232 );
3233 manager_from_stored_tokens(url, &stored, &http)
3234 .await
3235 .unwrap()
3236 }
3237
3238 #[tokio::test]
3239 async fn guarded_oauth_refresh_honors_stop_and_preserves_normal_local_refresh() {
3240 use std::sync::atomic::Ordering;
3241 let _env = crate::test_support::lock_test_env();
3242 let _proxy = crate::test_support::EnvVarGuard::set("NO_PROXY", "*");
3243 for redirect in [true, false] {
3244 let (url, captured, task) = guarded_oauth_fixture(None, redirect).await;
3245 let state = guarded_oauth_state(&url, None).await;
3246 let result = state.refresh_token().await;
3247 if redirect {
3248 assert!(result.is_err(), "redirected refresh must not be followed");
3249 assert_eq!(captured.load(Ordering::SeqCst), 0);
3250 } else {
3251 result.unwrap();
3252 assert_eq!(captured.load(Ordering::SeqCst), 1);
3253 }
3254 task.abort();
3255 }
3256 }
3257
3258 #[tokio::test]
3259 async fn guarded_oauth_discovered_private_token_endpoint_never_receives_credentials() {
3260 let _env = crate::test_support::lock_test_env();
3261 let _proxy = crate::test_support::EnvVarGuard::set("NO_PROXY", "*");
3262 let destination = TcpListener::bind("127.0.0.1:0").await.unwrap();
3263 let target = format!("http://{}/token", destination.local_addr().unwrap());
3264 let (url, _, task) = guarded_oauth_fixture(Some(target), false).await;
3265 let state = guarded_oauth_state(&url, None).await;
3266 let error = tokio::time::timeout(Duration::from_secs(1), state.refresh_token())
3267 .await
3268 .expect("the destination guard rejects before attempting a network request")
3269 .unwrap_err();
3270 // rmcp intentionally wraps HTTP client failures as `Request failed`.
3271 // The observable invariant is an immediate failed refresh and no socket
3272 // at the private destination, rather than an SDK-specific error string.
3273 assert!(
3274 matches!(error, AuthError::TokenRefreshFailed(_)),
3275 "{error:#}"
3276 );
3277 assert!(
3278 tokio::time::timeout(Duration::from_millis(30), destination.accept())
3279 .await
3280 .is_err()
3281 );
3282 task.abort();
3283 }
3284
3285 #[tokio::test]
3286 async fn guarded_oauth_network_deny_applies_to_standalone_and_synthetic_login() {
3287 use crate::mcp::{AuthenticateToolStart, McpPool};
3288 use codewhale_mcp::config::McpConfig;
3289 use codewhale_net::network_policy::{DecisionToml, NetworkPolicy};
3290 let _env = crate::test_support::lock_test_env();
3291 let dir = tempfile::tempdir().unwrap();
3292 let _home = crate::test_support::EnvVarGuard::set("CODEWHALE_HOME", dir.path());
3293 let _backend = crate::test_support::EnvVarGuard::set("CODEWHALE_SECRET_BACKEND", "file");
3294 let _proxy = crate::test_support::EnvVarGuard::set("NO_PROXY", "*");
3295 let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
3296 let url = format!("http://{}/mcp", listener.local_addr().unwrap());
3297 let server: McpServerConfig =
3298 serde_json::from_value(serde_json::json!({"url":url})).unwrap();
3299 let denied = NetworkPolicyDecider::new(
3300 NetworkPolicy {
3301 default: DecisionToml::Deny,
3302 ..NetworkPolicy::default()
3303 },
3304 None,
3305 );
3306 let mut config = McpConfig::default();
3307 config
3308 .servers
3309 .insert("network-guard".to_string(), server.clone());
3310 let pool = McpPool::new(config).with_network_policy(denied.clone());
3311 let error = match pool.begin_authenticate_tool("network-guard").await {
3312 Err(error) => error,
3313 Ok(_) => panic!("a configured denied origin must not start synthetic authentication"),
3314 };
3315 assert!(error.to_string().contains("network policy"), "{error:#}");
3316 assert!(oauth_login_support(&server, Some(&denied)).await.is_err());
3317 assert_eq!(
3318 auth_status_for_server("network-guard", &server, Some(&denied)).await,
3319 McpAuthStatus::Unsupported
3320 );
3321 assert!(
3322 perform_oauth_login_for_server(
3323 "network-guard",
3324 &server,
3325 Some(vec!["explicit".to_string()]),
3326 None,
3327 None,
3328 Some(&denied)
3329 )
3330 .await
3331 .is_err()
3332 );
3333 assert!(
3334 tokio::time::timeout(Duration::from_millis(30), listener.accept())
3335 .await
3336 .is_err()
3337 );
3338
3339 let (url, _, task) = guarded_oauth_fixture(None, false).await;
3340 let server: McpServerConfig =
3341 serde_json::from_value(serde_json::json!({"url":url})).unwrap();
3342 let allowed = NetworkPolicyDecider::new(
3343 NetworkPolicy {
3344 default: DecisionToml::Allow,
3345 ..NetworkPolicy::default()
3346 },
3347 None,
3348 );
3349 let mut config = McpConfig::default();
3350 config.servers.insert("network-control".to_string(), server);
3351 let pool = McpPool::new(config).with_network_policy(allowed.clone());
3352 let AuthenticateToolStart::Login(login) = pool
3353 .begin_authenticate_tool("network-control")
3354 .await
3355 .unwrap()
3356 else {
3357 panic!("the configured local control must start a fresh login");
3358 };
3359 assert!(login.authorization_url().contains("/authorize"));
3360 // A later retry carries the same shared session ceiling.
3361 allowed.deny_session("127.0.0.1", "mcp");
3362 assert_eq!(
3363 login
3364 .network_policy
3365 .as_ref()
3366 .unwrap()
3367 .evaluate("127.0.0.1", "mcp"),
3368 codewhale_net::network_policy::Decision::Deny
3369 );
3370 drop(login);
3371 task.abort();
3372 }
3373
3374 #[tokio::test]
3375 async fn interactive_login_forces_the_consent_screen() {
3376 use crate::mcp::{AuthenticateToolStart, McpPool};
3377 use codewhale_mcp::config::McpConfig;
3378 use codewhale_net::network_policy::{DecisionToml, NetworkPolicy};
3379 let _env = crate::test_support::lock_test_env();
3380 let dir = tempfile::tempdir().unwrap();
3381 let _home = crate::test_support::EnvVarGuard::set("CODEWHALE_HOME", dir.path());
3382 let _backend = crate::test_support::EnvVarGuard::set("CODEWHALE_SECRET_BACKEND", "file");
3383 let _proxy = crate::test_support::EnvVarGuard::set("NO_PROXY", "*");
3384 let (url, _, task) = guarded_oauth_fixture(None, false).await;
3385 let server: McpServerConfig =
3386 serde_json::from_value(serde_json::json!({"url":url})).unwrap();
3387 let allowed = NetworkPolicyDecider::new(
3388 NetworkPolicy {
3389 default: DecisionToml::Allow,
3390 ..NetworkPolicy::default()
3391 },
3392 None,
3393 );
3394 let mut config = McpConfig::default();
3395 config.servers.insert("consent-probe".to_string(), server);
3396 let pool = McpPool::new(config).with_network_policy(allowed);
3397 let AuthenticateToolStart::Login(login) =
3398 pool.begin_authenticate_tool("consent-probe").await.unwrap()
3399 else {
3400 panic!("a fresh server must start an interactive login");
3401 };
3402
3403 // #6040: logout only clears this machine's token; the provider keeps
3404 // its standing grant, so the login URL must force the consent screen
3405 // or the same account/workspace is silently re-granted.
3406 // The URL carries the PKCE challenge and state, so the assertion
3407 // message reports only the fact that is being checked, never the URL.
3408 let forces_consent = login.authorization_url().contains("prompt=consent");
3409 assert!(
3410 forces_consent,
3411 "an interactive login must force consent (prompt=consent is missing from the authorization URL)"
3412 );
3413
3414 drop(login);
3415 task.abort();
3416 }
3417
3418 #[tokio::test]
3419 async fn guarded_oauth_refresh_keeps_live_session_network_denials() {
3420 use codewhale_net::network_policy::{DecisionToml, NetworkPolicy};
3421 let _env = crate::test_support::lock_test_env();
3422 let _proxy = crate::test_support::EnvVarGuard::set("NO_PROXY", "*");
3423 let (url, captured, task) = guarded_oauth_fixture(None, false).await;
3424 let policy = NetworkPolicyDecider::new(
3425 NetworkPolicy {
3426 default: DecisionToml::Allow,
3427 ..NetworkPolicy::default()
3428 },
3429 None,
3430 );
3431 let state = guarded_oauth_state(&url, Some(&policy)).await;
3432 state.refresh_token().await.unwrap();
3433 assert_eq!(captured.load(Ordering::SeqCst), 1);
3434 policy.deny_session("127.0.0.1", "mcp");
3435 assert!(state.refresh_token().await.is_err());
3436 assert_eq!(
3437 captured.load(Ordering::SeqCst),
3438 1,
3439 "no refresh request after session denial"
3440 );
3441 task.abort();
3442 }
3443 }
3444
3444 lines RUST