Skip to main content

github_mcp/auth/
auth_manager.rs

1// GitHub v3 REST API MCP server — generated by mcpify. Do not hand-edit.
2
3use 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
17/// Builds an `AuthConfig` straight from the `<PREFIX>_TOKEN`/`_API_KEY`/
18/// `_USERNAME`/`_PASSWORD` env vars documented in `.env.example`, if the
19/// vars this `auth_method` needs are actually set — closes the gap where
20/// those vars were documented but never wired into the credentials lookup,
21/// leaving a prior `setup` run (keychain/file) as the only way to
22/// authenticate. Returns `None` when the required var(s) for this
23/// deployment's `auth_method` aren't present, so callers fall back to the
24/// stored-credential lookup unchanged.
25fn 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
62/// Where `auth_method`'s credential value travels on the wire — used only
63/// by the HTTP-transport auth-gate/extractor (`http::auth_extractor`) to
64/// know which incoming header to read; stdio never calls this.
65pub 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
73/// Selects exactly one active auth strategy per deployment, chosen via the
74/// `auth_method` config value (REQ-1.2.3) — there is no runtime engine for
75/// resolving multiple simultaneously-required schemes.
76pub 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    /// Seeds in-memory credentials directly, bypassing OS-keychain/file
99    /// storage entirely — for tests (which must never touch the real OS
100    /// keychain as a side effect of running) and for callers that already
101    /// hold validated credentials from elsewhere.
102    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            // A blob with a `refresh_token` has already completed the
130            // initial code exchange at some point (it just expired) — use
131            // the cheap refresh path. A blob with neither `access_token`
132            // nor `refresh_token` is straight out of the setup wizard
133            // (raw `authorization_code`, never exchanged yet), so fall
134            // through to the full exchange instead.
135            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    /// Decorates outgoing request headers with credentials for `transport`:
175    /// on `Transport::Http`, `request_override` (extracted per-request from
176    /// the caller's own headers — see `http::auth_extractor`) is the *only*
177    /// source ever consulted, since HTTP deployments must never leak the
178    /// operator's local config/keychain secrets to a caller who didn't
179    /// supply their own; a missing override is a hard error, not a
180    /// fallback. On `Transport::Stdio`, `request_override` is ignored and
181    /// behavior is unchanged from before HTTP-transport support existed:
182    /// `self.credentials()` (config cascade + keychain).
183    ///
184    /// API-key placement (header vs. query, and the header/param name)
185    /// defaults to an `X-Api-Key` header here; a scheme declaring a
186    /// different location is one of Story R6's api-client responsibilities
187    /// to refine, not this manager's — `request_override`'s
188    /// `request_header_name`/`request_header_value` pair is the one
189    /// exception, since the HTTP path already knows the scheme's declared
190    /// header name (`RsAuthSchemeView::header_name`) at generation time.
191    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        // `method`/`url` are part of this method's fixed public signature
212        // (every active strategy's header-decoration needs them in
213        // principle), but only OAuth1's per-request signing actually
214        // consumes them — unused here since OAuth1 wasn't discovered for
215        // this deployment.
216        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            // HTTP-transport relay case: both name and value came from the
224            // caller's own incoming request (`RequestCredentials`).
225            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        // Seeded with whatever field(s) `auth_methods.0`'s own
248        // `validate_credentials` actually checks for — each strategy
249        // checks a different key (see auth/strategies/*.rs), so this has
250        // to match the specific first-discovered method, not just
251        // "oauth1 or not".
252        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        // Deliberately seed a *different* credential than the override below,
265        // so the assertion fails if HTTP transport ever falls back to it.
266        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}