Skip to main content

adk_tool/mcp/
auth.rs

1// MCP Authentication Support
2//
3// Provides authentication mechanisms for remote MCP servers.
4// Integrates with adk-auth for SSO/OAuth support.
5
6use std::collections::HashMap;
7use std::sync::Arc;
8use tokio::sync::RwLock;
9
10/// Authentication configuration for MCP connections
11#[derive(Clone, Default)]
12pub enum McpAuth {
13    /// No authentication required
14    #[default]
15    None,
16    /// Static bearer token
17    Bearer(String),
18    /// API key in header
19    ApiKey {
20        /// HTTP header name for the API key.
21        header: String,
22        /// The API key value.
23        key: String,
24    },
25    /// OAuth2 with automatic token refresh
26    OAuth2(Arc<OAuth2Config>),
27}
28
29impl std::fmt::Debug for McpAuth {
30    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
31        match self {
32            McpAuth::None => write!(f, "McpAuth::None"),
33            McpAuth::Bearer(_) => write!(f, "McpAuth::Bearer([REDACTED])"),
34            McpAuth::ApiKey { header, .. } => write!(f, "McpAuth::ApiKey {{ header: {} }}", header),
35            McpAuth::OAuth2(_) => write!(f, "McpAuth::OAuth2([CONFIG])"),
36        }
37    }
38}
39
40impl McpAuth {
41    /// Create bearer token auth
42    pub fn bearer(token: impl Into<String>) -> Self {
43        McpAuth::Bearer(token.into())
44    }
45
46    /// Create API key auth
47    pub fn api_key(header: impl Into<String>, key: impl Into<String>) -> Self {
48        McpAuth::ApiKey { header: header.into(), key: key.into() }
49    }
50
51    /// Create OAuth2 auth
52    pub fn oauth2(config: OAuth2Config) -> Self {
53        McpAuth::OAuth2(Arc::new(config))
54    }
55
56    /// Get authorization headers for a request
57    pub async fn get_headers(&self) -> Result<HashMap<String, String>, AuthError> {
58        let mut headers = HashMap::new();
59
60        match self {
61            McpAuth::None => {}
62            McpAuth::Bearer(token) => {
63                headers.insert("Authorization".to_string(), format!("Bearer {}", token));
64            }
65            McpAuth::ApiKey { header, key } => {
66                headers.insert(header.clone(), key.clone());
67            }
68            McpAuth::OAuth2(config) => {
69                let token = config.get_or_refresh_token().await?;
70                headers.insert("Authorization".to_string(), format!("Bearer {}", token));
71            }
72        }
73
74        Ok(headers)
75    }
76
77    /// Check if authentication is configured
78    pub fn is_configured(&self) -> bool {
79        !matches!(self, McpAuth::None)
80    }
81}
82
83/// OAuth2 configuration for MCP authentication
84pub struct OAuth2Config {
85    /// OAuth2 client ID
86    pub client_id: String,
87    /// OAuth2 client secret (optional for public clients)
88    pub client_secret: Option<String>,
89    /// Token endpoint URL. Must use `https`, except for a loopback host.
90    pub token_url: String,
91    /// Requested scopes
92    pub scopes: Vec<String>,
93    /// Timeout applied to OAuth token requests.
94    pub timeout: std::time::Duration,
95    /// Cached token with expiry
96    token_cache: RwLock<Option<CachedToken>>,
97}
98
99impl OAuth2Config {
100    /// Create a new OAuth2 config
101    pub fn new(client_id: impl Into<String>, token_url: impl Into<String>) -> Self {
102        Self {
103            client_id: client_id.into(),
104            client_secret: None,
105            token_url: token_url.into(),
106            scopes: Vec::new(),
107            timeout: std::time::Duration::from_secs(30),
108            token_cache: RwLock::new(None),
109        }
110    }
111
112    /// Set client secret
113    pub fn with_secret(mut self, secret: impl Into<String>) -> Self {
114        self.client_secret = Some(secret.into());
115        self
116    }
117
118    /// Add scopes
119    pub fn with_scopes(mut self, scopes: Vec<String>) -> Self {
120        self.scopes = scopes;
121        self
122    }
123
124    /// Set a bounded timeout for OAuth token requests.
125    pub fn with_timeout(mut self, timeout: std::time::Duration) -> Self {
126        self.timeout = timeout;
127        self
128    }
129
130    /// Return the cached access token, fetching a new one when none is cached
131    /// or the cached one is due for refresh.
132    ///
133    /// A token is refreshed one minute before the `expires_in` its token
134    /// response declared, or halfway through its lifetime when that is under
135    /// two minutes. A token response without `expires_in` is cached until
136    /// [`clear_cache`](Self::clear_cache) is called or a server rejects it.
137    ///
138    /// # Errors
139    ///
140    /// Returns [`AuthError`] when the token endpoint cannot be reached or
141    /// rejects the client credentials.
142    pub async fn get_or_refresh_token(&self) -> Result<String, AuthError> {
143        if let Some(cached) =
144            self.token_cache.read().await.as_ref().filter(|cached| !cached.is_expired())
145        {
146            return Ok(cached.access_token.clone());
147        }
148
149        // One caller fetches while the rest wait for its token, rather than
150        // every concurrent request asking the token endpoint for its own.
151        let mut cache = self.token_cache.write().await;
152        if let Some(cached) = cache.as_ref().filter(|cached| !cached.is_expired()) {
153            return Ok(cached.access_token.clone());
154        }
155        let token = self.fetch_token().await?;
156        let access_token = token.access_token.clone();
157        *cache = Some(token);
158        Ok(access_token)
159    }
160
161    /// Drop the cached token if it is `rejected`, so the next request fetches
162    /// a new one. A token another request already replaced is kept.
163    #[cfg(feature = "http-transport")]
164    pub(crate) async fn discard_token(&self, rejected: &str) {
165        let mut cache = self.token_cache.write().await;
166        if cache.as_ref().is_some_and(|cached| cached.access_token == rejected) {
167            *cache = None;
168        }
169    }
170
171    /// Fetch a new token from the token endpoint
172    async fn fetch_token(&self) -> Result<CachedToken, AuthError> {
173        // Build request body
174        let mut params = vec![
175            ("grant_type", "client_credentials".to_string()),
176            ("client_id", self.client_id.clone()),
177        ];
178
179        if let Some(ref secret) = self.client_secret {
180            params.push(("client_secret", secret.clone()));
181        }
182
183        if !self.scopes.is_empty() {
184            params.push(("scope", self.scopes.join(" ")));
185        }
186
187        // Make request (using reqwest if available)
188        #[cfg(feature = "http-transport")]
189        {
190            // Client credentials and the issued token travel in this request, so
191            // plain HTTP is accepted only for a loopback token endpoint.
192            let url = reqwest::Url::parse(&self.token_url).map_err(|e| {
193                AuthError::TokenFetch(format!("invalid token URL '{}': {e}", self.token_url))
194            })?;
195            let host =
196                url.host_str().unwrap_or_default().trim_start_matches('[').trim_end_matches(']');
197            let loopback = host.eq_ignore_ascii_case("localhost")
198                || host.parse::<std::net::IpAddr>().is_ok_and(|ip| ip.is_loopback());
199            if url.scheme() != "https" && !(url.scheme() == "http" && loopback) {
200                return Err(AuthError::TokenFetch(format!(
201                    "token URL '{}' must use https; plain http is accepted only for localhost",
202                    self.token_url
203                )));
204            }
205            let client = reqwest::Client::builder()
206                .timeout(self.timeout)
207                .build()
208                .map_err(|e| AuthError::TokenFetch(e.to_string()))?;
209            let response = client
210                .post(&self.token_url)
211                .form(&params)
212                .send()
213                .await
214                .map_err(|e| AuthError::TokenFetch(e.to_string()))?;
215
216            if !response.status().is_success() {
217                let status = response.status();
218                let mut body = response.text().await.unwrap_or_default();
219                if let Some(secret) = &self.client_secret
220                    && !secret.is_empty()
221                {
222                    body = body.replace(secret, "[REDACTED]");
223                }
224                let body = body.chars().take(512).collect::<String>();
225                return Err(AuthError::TokenFetch(format!(
226                    "Token request failed: {} - {}",
227                    status, body
228                )));
229            }
230
231            let token_response: TokenResponse =
232                response.json().await.map_err(|e| AuthError::TokenParse(e.to_string()))?;
233
234            Ok(CachedToken::from_response(token_response))
235        }
236
237        #[cfg(not(feature = "http-transport"))]
238        {
239            Err(AuthError::NotSupported("OAuth2 requires the 'http-transport' feature".to_string()))
240        }
241    }
242
243    /// Clear the token cache (force refresh on next request)
244    pub async fn clear_cache(&self) {
245        let mut cache = self.token_cache.write().await;
246        *cache = None;
247    }
248}
249
250/// Cached OAuth2 token
251#[derive(Clone)]
252#[allow(dead_code)] // Used when http-transport feature is enabled
253struct CachedToken {
254    access_token: String,
255    expires_at: Option<std::time::Instant>,
256    refresh_token: Option<String>,
257}
258
259#[allow(dead_code)] // Used when http-transport feature is enabled
260impl CachedToken {
261    fn from_response(response: TokenResponse) -> Self {
262        let expires_at = response.expires_in.map(|secs| {
263            // A fixed one-minute margin would treat every token shorter than a
264            // minute as already expired and fetch a new one for each request.
265            let lifetime = secs.saturating_sub(60.min(secs / 2));
266            std::time::Instant::now() + std::time::Duration::from_secs(lifetime)
267        });
268
269        Self {
270            access_token: response.access_token,
271            expires_at,
272            refresh_token: response.refresh_token,
273        }
274    }
275
276    fn is_expired(&self) -> bool {
277        match self.expires_at {
278            Some(expires_at) => std::time::Instant::now() >= expires_at,
279            None => false, // No expiry = never expires
280        }
281    }
282}
283
284/// OAuth2 token response
285#[derive(serde::Deserialize)]
286#[allow(dead_code)] // Used when http-transport feature is enabled
287struct TokenResponse {
288    access_token: String,
289    #[serde(default)]
290    expires_in: Option<u64>,
291    #[serde(default)]
292    refresh_token: Option<String>,
293    #[serde(default)]
294    token_type: Option<String>,
295}
296
297/// Authentication errors
298#[derive(Debug, Clone)]
299pub enum AuthError {
300    /// Failed to fetch token
301    TokenFetch(String),
302    /// Failed to parse token response
303    TokenParse(String),
304    /// Token expired and refresh failed
305    TokenExpired(String),
306    /// Feature not supported
307    NotSupported(String),
308}
309
310impl std::fmt::Display for AuthError {
311    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
312        match self {
313            AuthError::TokenFetch(msg) => write!(f, "Token fetch failed: {}", msg),
314            AuthError::TokenParse(msg) => write!(f, "Token parse failed: {}", msg),
315            AuthError::TokenExpired(msg) => write!(f, "Token expired: {}", msg),
316            AuthError::NotSupported(msg) => write!(f, "Not supported: {}", msg),
317        }
318    }
319}
320
321impl std::error::Error for AuthError {}
322
323#[cfg(test)]
324mod tests {
325    use super::*;
326
327    #[test]
328    fn test_mcp_auth_none() {
329        let auth = McpAuth::None;
330        assert!(!auth.is_configured());
331    }
332
333    #[test]
334    fn test_mcp_auth_bearer() {
335        let auth = McpAuth::bearer("test-token");
336        assert!(auth.is_configured());
337    }
338
339    #[test]
340    fn test_mcp_auth_api_key() {
341        let auth = McpAuth::api_key("X-API-Key", "secret-key");
342        assert!(auth.is_configured());
343    }
344
345    #[tokio::test]
346    async fn test_bearer_headers() {
347        let auth = McpAuth::bearer("my-token");
348        let headers = auth.get_headers().await.unwrap();
349        assert_eq!(headers.get("Authorization"), Some(&"Bearer my-token".to_string()));
350    }
351
352    #[tokio::test]
353    async fn test_api_key_headers() {
354        let auth = McpAuth::api_key("X-API-Key", "secret");
355        let headers = auth.get_headers().await.unwrap();
356        assert_eq!(headers.get("X-API-Key"), Some(&"secret".to_string()));
357    }
358
359    #[test]
360    fn test_oauth2_config() {
361        let config = OAuth2Config::new("client-id", "https://auth.example.com/token")
362            .with_secret("client-secret")
363            .with_scopes(vec!["read".to_string(), "write".to_string()]);
364
365        assert_eq!(config.client_id, "client-id");
366        assert_eq!(config.client_secret, Some("client-secret".to_string()));
367        assert_eq!(config.scopes, vec!["read", "write"]);
368    }
369
370    #[cfg(feature = "http-transport")]
371    #[tokio::test]
372    async fn plain_http_token_url_is_refused_unless_loopback() {
373        let config =
374            OAuth2Config::new("client-id", "http://auth.example.com/token").with_secret("s3cret");
375        let err = config.get_or_refresh_token().await.unwrap_err();
376        assert!(err.to_string().contains("must use https"), "got {err}");
377
378        for url in ["http://localhost:1/token", "http://127.0.0.1:1/token", "http://[::1]:1/token"]
379        {
380            let err = OAuth2Config::new("client-id", url).get_or_refresh_token().await.unwrap_err();
381            assert!(!err.to_string().contains("must use https"), "{url} was refused: {err}");
382        }
383    }
384}