1use std::collections::HashMap;
7use std::sync::Arc;
8use tokio::sync::RwLock;
9
10#[derive(Clone, Default)]
12pub enum McpAuth {
13 #[default]
15 None,
16 Bearer(String),
18 ApiKey {
20 header: String,
22 key: String,
24 },
25 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 pub fn bearer(token: impl Into<String>) -> Self {
43 McpAuth::Bearer(token.into())
44 }
45
46 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 pub fn oauth2(config: OAuth2Config) -> Self {
53 McpAuth::OAuth2(Arc::new(config))
54 }
55
56 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 pub fn is_configured(&self) -> bool {
79 !matches!(self, McpAuth::None)
80 }
81}
82
83pub struct OAuth2Config {
85 pub client_id: String,
87 pub client_secret: Option<String>,
89 pub token_url: String,
91 pub scopes: Vec<String>,
93 pub timeout: std::time::Duration,
95 token_cache: RwLock<Option<CachedToken>>,
97}
98
99impl OAuth2Config {
100 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 pub fn with_secret(mut self, secret: impl Into<String>) -> Self {
114 self.client_secret = Some(secret.into());
115 self
116 }
117
118 pub fn with_scopes(mut self, scopes: Vec<String>) -> Self {
120 self.scopes = scopes;
121 self
122 }
123
124 pub fn with_timeout(mut self, timeout: std::time::Duration) -> Self {
126 self.timeout = timeout;
127 self
128 }
129
130 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 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 #[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 async fn fetch_token(&self) -> Result<CachedToken, AuthError> {
173 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 #[cfg(feature = "http-transport")]
189 {
190 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(¶ms)
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 pub async fn clear_cache(&self) {
245 let mut cache = self.token_cache.write().await;
246 *cache = None;
247 }
248}
249
250#[derive(Clone)]
252#[allow(dead_code)] struct CachedToken {
254 access_token: String,
255 expires_at: Option<std::time::Instant>,
256 refresh_token: Option<String>,
257}
258
259#[allow(dead_code)] impl CachedToken {
261 fn from_response(response: TokenResponse) -> Self {
262 let expires_at = response.expires_in.map(|secs| {
263 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, }
281 }
282}
283
284#[derive(serde::Deserialize)]
286#[allow(dead_code)] struct 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#[derive(Debug, Clone)]
299pub enum AuthError {
300 TokenFetch(String),
302 TokenParse(String),
304 TokenExpired(String),
306 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}