github_mcp/auth/
auth_manager.rs1use crate::core::config_schema::{AuthMethod, Transport};
4use crate::core::credential_storage::{load_credential, save_credential};
5
6use super::auth_strategy::{AuthConfig, AuthStrategy, Credentials};
7use super::errors::AuthError;
8use super::request_credentials::RequestCredentials;
9use super::strategies::api_key::ApiKeyStrategy;
10use super::strategies::basic::BasicAuthStrategy;
11use super::strategies::pat::PatAuthStrategy;
12use super::strategies::stub::StubAuthStrategy;
13
14const CREDENTIAL_ACCOUNT: &str = "active-credentials";
15const ENV_PREFIX: &str = "GITHUB_MCP";
16
17fn credentials_from_env(auth_method: AuthMethod) -> Option<AuthConfig> {
26 let mut config = AuthConfig::new();
27 match auth_method {
28 AuthMethod::Pat => {
29 let token = std::env::var(format!("{ENV_PREFIX}_TOKEN"))
30 .or_else(|_| std::env::var(format!("{ENV_PREFIX}_API_KEY")))
31 .ok()?;
32 config.insert("token".to_string(), token);
33 }
34 AuthMethod::ApiKey => {
35 let api_key = std::env::var(format!("{ENV_PREFIX}_API_KEY"))
36 .or_else(|_| std::env::var(format!("{ENV_PREFIX}_TOKEN")))
37 .ok()?;
38 config.insert("api_key".to_string(), api_key);
39 }
40 AuthMethod::Basic => {
41 let username = std::env::var(format!("{ENV_PREFIX}_USERNAME")).ok()?;
42 let password = std::env::var(format!("{ENV_PREFIX}_PASSWORD")).ok()?;
43 config.insert("username".to_string(), username);
44 config.insert("password".to_string(), password);
45 }
46 #[allow(unreachable_patterns)]
47 _ => return None,
48 }
49 Some(config)
50}
51
52fn strategy_for(auth_method: AuthMethod) -> Box<dyn AuthStrategy> {
53 match auth_method {
54 AuthMethod::Basic => Box::new(BasicAuthStrategy),
55 AuthMethod::ApiKey => Box::new(ApiKeyStrategy),
56 AuthMethod::Pat => Box::new(PatAuthStrategy),
57 #[allow(unreachable_patterns)]
58 _ => Box::new(StubAuthStrategy),
59 }
60}
61
62pub fn header_location_for(auth_method: AuthMethod) -> (&'static str, &'static str) {
66 match auth_method {
67 AuthMethod::Pat => ("header", "Authorization"),
68 AuthMethod::ApiKey => ("header", "Authorization"),
69 AuthMethod::Basic => ("header", "Authorization"),
70 }
71}
72
73pub struct AuthManager {
77 auth_method: AuthMethod,
78 strategy: Box<dyn AuthStrategy>,
79 cached_credentials: Option<Credentials>,
80}
81
82impl AuthManager {
83 pub fn new(auth_method: AuthMethod) -> Self {
84 Self {
85 strategy: strategy_for(auth_method),
86 auth_method,
87 cached_credentials: None,
88 }
89 }
90
91 pub async fn login(&mut self, config: &AuthConfig) -> anyhow::Result<Credentials> {
92 let credentials = self.strategy.authenticate(config).await?;
93 self.cached_credentials = Some(credentials.clone());
94 save_credential(CREDENTIAL_ACCOUNT, &serde_json::to_string(&credentials)?)?;
95 Ok(credentials)
96 }
97
98 pub fn set_credentials(&mut self, credentials: Credentials) {
103 self.cached_credentials = Some(credentials);
104 }
105
106 pub async fn credentials(&mut self) -> anyhow::Result<Credentials> {
107 if let Some(cached) = &self.cached_credentials
108 && self.strategy.validate_credentials(cached)
109 {
110 return self.normalize_credentials(cached).await;
111 }
112
113 if let Some(env_config) = credentials_from_env(self.auth_method)
114 && let Ok(from_env) = self.strategy.authenticate(&env_config).await
115 && self.strategy.validate_credentials(&from_env)
116 {
117 self.cached_credentials = Some(from_env.clone());
118 return Ok(from_env);
119 }
120
121 if let Some(stored) = load_credential(CREDENTIAL_ACCOUNT)? {
122 let parsed: Credentials = serde_json::from_str(&stored)?;
123 if self.strategy.validate_credentials(&parsed) {
124 let normalized = self.normalize_credentials(&parsed).await?;
125 self.cached_credentials = Some(normalized.clone());
126 save_credential(CREDENTIAL_ACCOUNT, &serde_json::to_string(&normalized)?)?;
127 return Ok(normalized);
128 }
129 let exchanged = if parsed.contains_key("refresh_token") {
136 self.strategy.refresh_token(&parsed).await
137 } else {
138 self.strategy.authenticate(&parsed).await
139 };
140 if let Ok(exchanged) = exchanged {
141 let normalized = self.normalize_credentials(&exchanged).await?;
142 self.cached_credentials = Some(normalized.clone());
143 save_credential(CREDENTIAL_ACCOUNT, &serde_json::to_string(&normalized)?)?;
144 return Ok(normalized);
145 }
146 }
147
148 Err(AuthError::NoActiveCredentials(format!("{:?}", self.auth_method)).into())
149 }
150
151 async fn normalize_credentials(
152 &self,
153 credentials: &Credentials,
154 ) -> anyhow::Result<Credentials> {
155 if credentials.contains_key("authorization_header")
156 || credentials.contains_key("api_key")
157 || credentials.contains_key("request_header_name")
158 {
159 return Ok(credentials.clone());
160 }
161
162 if let Some(access_token) = credentials.get("access_token") {
163 let mut normalized = credentials.clone();
164 normalized.insert(
165 "authorization_header".to_string(),
166 format!("Bearer {access_token}"),
167 );
168 return Ok(normalized);
169 }
170
171 self.strategy.authenticate(credentials).await
172 }
173
174 pub async fn apply_auth_headers(
192 &mut self,
193 mut headers: std::collections::HashMap<String, String>,
194 method: &str,
195 url: &str,
196 transport: Transport,
197 request_override: Option<&RequestCredentials>,
198 ) -> anyhow::Result<std::collections::HashMap<String, String>> {
199 let credentials = match (transport, request_override) {
200 (Transport::Http, Some(override_credentials)) => {
201 override_credentials.clone().into_credentials_map()
202 }
203 (Transport::Http, None) => {
204 anyhow::bail!(
205 "no credentials were supplied on this HTTP request; local config/env/keychain \
206 is never used as a fallback over HTTP transport"
207 );
208 }
209 (Transport::Stdio, _) => self.credentials().await?,
210 };
211 let _ = method;
217 let _ = url;
218
219 if let (Some(name), Some(value)) = (
220 credentials.get("request_header_name"),
221 credentials.get("request_header_value"),
222 ) {
223 headers.insert(name.clone(), value.clone());
226 } else if let Some(header) = credentials.get("authorization_header") {
227 headers.insert("Authorization".to_string(), header.clone());
228 } else if let Some(api_key) = credentials.get("api_key") {
229 let header_name = credentials
230 .get("request_header_name")
231 .cloned()
232 .unwrap_or_else(|| "X-Api-Key".to_string());
233 headers.insert(header_name, api_key.clone());
234 }
235 Ok(headers)
236 }
237}
238
239#[cfg(test)]
240mod tests {
241 use super::*;
242
243 #[tokio::test]
244 async fn seeded_credentials_win_over_stored_ones() {
245 let mut manager = AuthManager::new(AuthMethod::Pat);
246 let mut credentials = Credentials::new();
247 credentials.insert("token".to_string(), "abc".to_string());
253 manager.set_credentials(credentials.clone());
254
255 let resolved = manager.credentials().await.unwrap();
256 assert_eq!(
257 resolved.get("authorization_header").map(String::as_str),
258 Some("Bearer abc")
259 );
260 }
261 #[tokio::test]
262 async fn http_transport_uses_the_request_override_not_the_config_cascade() {
263 let mut manager = AuthManager::new(AuthMethod::Pat);
264 let mut stale = Credentials::new();
267 stale.insert(
268 "request_header_name".to_string(),
269 "X-Should-Not-Be-Used".to_string(),
270 );
271 manager.set_credentials(stale);
272
273 let override_credentials = RequestCredentials {
274 header_name: "X-Api-Key".to_string(),
275 value: "from-the-request".to_string(),
276 };
277 let headers = manager
278 .apply_auth_headers(
279 std::collections::HashMap::new(),
280 "GET",
281 "https://example.com",
282 Transport::Http,
283 Some(&override_credentials),
284 )
285 .await
286 .unwrap();
287
288 assert_eq!(
289 headers.get("X-Api-Key").map(String::as_str),
290 Some("from-the-request")
291 );
292 }
293
294 #[tokio::test]
295 async fn http_transport_without_an_override_errors_instead_of_falling_back() {
296 let mut manager = AuthManager::new(AuthMethod::Pat);
297 let mut stale = Credentials::new();
298 stale.insert(
299 "request_header_name".to_string(),
300 "X-Should-Not-Be-Used".to_string(),
301 );
302 manager.set_credentials(stale);
303
304 let result = manager
305 .apply_auth_headers(
306 std::collections::HashMap::new(),
307 "GET",
308 "https://example.com",
309 Transport::Http,
310 None,
311 )
312 .await;
313
314 assert!(result.is_err());
315 }
316}