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/// Reads the `.env.example`-documented credential override env vars
18/// directly into a `Credentials` map for `auth_method`, so a deployment can
19/// supply credentials purely via environment (e.g. a container's env block)
20/// without ever running `setup` first. Returns `None` when the relevant
21/// var(s) aren't set, so callers fall back to the stored-credential lookup
22/// unchanged.
23fn credentials_from_env(auth_method: AuthMethod) -> Option<Credentials> {
24    match auth_method {
25        AuthMethod::Pat => {
26            let token = std::env::var(format!("{ENV_PREFIX}_TOKEN"))
27                .or_else(|_| std::env::var(format!("{ENV_PREFIX}_API_KEY")))
28                .ok()?;
29            let mut credentials = Credentials::new();
30            credentials.insert("token".to_string(), token);
31            Some(credentials)
32        }
33        AuthMethod::ApiKey => {
34            let api_key = std::env::var(format!("{ENV_PREFIX}_API_KEY"))
35                .or_else(|_| std::env::var(format!("{ENV_PREFIX}_TOKEN")))
36                .ok()?;
37            let mut credentials = Credentials::new();
38            credentials.insert("api_key".to_string(), api_key);
39            Some(credentials)
40        }
41        AuthMethod::Basic => {
42            let username = std::env::var(format!("{ENV_PREFIX}_USERNAME")).ok()?;
43            let password = std::env::var(format!("{ENV_PREFIX}_PASSWORD")).ok()?;
44            let mut credentials = Credentials::new();
45            credentials.insert("username".to_string(), username);
46            credentials.insert("password".to_string(), password);
47            Some(credentials)
48        }
49    }
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(from_env) = credentials_from_env(self.auth_method)
114            && self.strategy.validate_credentials(&from_env)
115        {
116            let normalized = self.normalize_credentials(&from_env).await?;
117            self.cached_credentials = Some(normalized.clone());
118            return Ok(normalized);
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            if let Ok(refreshed) = self.strategy.refresh_token(&parsed).await {
130                let normalized = self.normalize_credentials(&refreshed).await?;
131                self.cached_credentials = Some(normalized.clone());
132                save_credential(CREDENTIAL_ACCOUNT, &serde_json::to_string(&normalized)?)?;
133                return Ok(normalized);
134            }
135        }
136
137        Err(AuthError::NoActiveCredentials(format!("{:?}", self.auth_method)).into())
138    }
139
140    async fn normalize_credentials(
141        &self,
142        credentials: &Credentials,
143    ) -> anyhow::Result<Credentials> {
144        if credentials.contains_key("authorization_header")
145            || credentials.contains_key("api_key")
146            || credentials.contains_key("request_header_name")
147        {
148            return Ok(credentials.clone());
149        }
150
151        self.strategy.authenticate(credentials).await
152    }
153
154    /// Decorates outgoing request headers with credentials for `transport`:
155    /// on `Transport::Http`, `request_override` (extracted per-request from
156    /// the caller's own headers — see `http::auth_extractor`) is the *only*
157    /// source ever consulted, since HTTP deployments must never leak the
158    /// operator's local config/keychain secrets to a caller who didn't
159    /// supply their own; a missing override is a hard error, not a
160    /// fallback. On `Transport::Stdio`, `request_override` is ignored and
161    /// behavior is unchanged from before HTTP-transport support existed:
162    /// `self.credentials()` (config cascade + keychain).
163    ///
164    /// API-key placement (header vs. query, and the header/param name)
165    /// defaults to an `X-Api-Key` header here; a scheme declaring a
166    /// different location is one of Story R6's api-client responsibilities
167    /// to refine, not this manager's — `request_override`'s
168    /// `request_header_name`/`request_header_value` pair is the one
169    /// exception, since the HTTP path already knows the scheme's declared
170    /// header name (`RsAuthSchemeView::header_name`) at generation time.
171    pub async fn apply_auth_headers(
172        &mut self,
173        mut headers: std::collections::HashMap<String, String>,
174        method: &str,
175        url: &str,
176        transport: Transport,
177        request_override: Option<&RequestCredentials>,
178    ) -> anyhow::Result<std::collections::HashMap<String, String>> {
179        let credentials = match (transport, request_override) {
180            (Transport::Http, Some(override_credentials)) => {
181                override_credentials.clone().into_credentials_map()
182            }
183            (Transport::Http, None) => {
184                anyhow::bail!(
185                    "no credentials were supplied on this HTTP request; local config/env/keychain \
186                     is never used as a fallback over HTTP transport"
187                );
188            }
189            (Transport::Stdio, _) => self.credentials().await?,
190        };
191        // `method`/`url` are part of this method's fixed public signature
192        // (every active strategy's header-decoration needs them in
193        // principle), but only OAuth1's per-request signing actually
194        // consumes them — unused here since OAuth1 wasn't discovered for
195        // this deployment.
196        let _ = method;
197        let _ = url;
198
199        if let Some(name) = credentials.get("request_header_name") {
200            let value = credentials
201                .get("request_header_value")
202                .cloned()
203                .unwrap_or_default();
204            headers.insert(name.clone(), value);
205        } else if let Some(header) = credentials.get("authorization_header") {
206            headers.insert("Authorization".to_string(), header.clone());
207        } else if let Some(api_key) = credentials.get("api_key") {
208            // GitHub's discovered auth schemes (PAT, Basic) never populate
209            // "api_key"/"request_header_name" — there is no reachable path
210            // to this branch in practice since the setup wizard's ApiKey
211            // option doesn't correspond to a GitHub-supported scheme. Kept
212            // for structural parity with the other mcpify-generated Rust
213            // servers: honor the scheme's real configured header name (via
214            // "request_header_name", the same key checked above) instead of
215            // hardcoding "X-Api-Key".
216            let header_name = credentials
217                .get("request_header_name")
218                .cloned()
219                .unwrap_or_else(|| "X-Api-Key".to_string());
220            headers.insert(header_name, api_key.clone());
221        }
222        Ok(headers)
223    }
224}
225
226#[cfg(test)]
227mod tests {
228    use super::*;
229
230    #[tokio::test]
231    async fn seeded_credentials_win_over_stored_ones() {
232        let mut manager = AuthManager::new(AuthMethod::Pat);
233        let mut credentials = Credentials::new();
234        // Seeded with whatever field(s) `auth_methods.0`'s own
235        // `validate_credentials` actually checks for — each strategy
236        // checks a different key (see auth/strategies/*.rs), so this has
237        // to match the specific first-discovered method, not just
238        // "oauth1 or not".
239        credentials.insert("token".to_string(), "abc".to_string());
240        manager.set_credentials(credentials.clone());
241
242        let resolved = manager.credentials().await.unwrap();
243        assert_eq!(resolved.get("token"), credentials.get("token"));
244        assert_eq!(
245            resolved.get("authorization_header").map(String::as_str),
246            Some("Bearer abc")
247        );
248    }
249
250    #[tokio::test]
251    async fn pat_credentials_saved_by_setup_are_normalized_before_use() {
252        let mut manager = AuthManager::new(AuthMethod::Pat);
253        let mut credentials = Credentials::new();
254        credentials.insert("token".to_string(), "abc".to_string());
255        manager.set_credentials(credentials);
256
257        let headers = manager
258            .apply_auth_headers(
259                std::collections::HashMap::new(),
260                "GET",
261                "https://api.github.com/user",
262                Transport::Stdio,
263                None,
264            )
265            .await
266            .unwrap();
267
268        assert_eq!(
269            headers.get("Authorization").map(String::as_str),
270            Some("Bearer abc")
271        );
272    }
273    #[tokio::test]
274    async fn http_transport_uses_the_request_override_not_the_config_cascade() {
275        let mut manager = AuthManager::new(AuthMethod::Pat);
276        // Deliberately seed a *different* credential than the override below,
277        // so the assertion fails if HTTP transport ever falls back to it.
278        let mut stale = Credentials::new();
279        stale.insert(
280            "request_header_name".to_string(),
281            "X-Should-Not-Be-Used".to_string(),
282        );
283        manager.set_credentials(stale);
284
285        let override_credentials = RequestCredentials {
286            header_name: "X-Api-Key".to_string(),
287            value: "from-the-request".to_string(),
288        };
289        let headers = manager
290            .apply_auth_headers(
291                std::collections::HashMap::new(),
292                "GET",
293                "https://example.com",
294                Transport::Http,
295                Some(&override_credentials),
296            )
297            .await
298            .unwrap();
299
300        assert_eq!(
301            headers.get("X-Api-Key").map(String::as_str),
302            Some("from-the-request")
303        );
304    }
305
306    #[tokio::test]
307    async fn http_transport_without_an_override_errors_instead_of_falling_back() {
308        let mut manager = AuthManager::new(AuthMethod::Pat);
309        let mut stale = Credentials::new();
310        stale.insert(
311            "request_header_name".to_string(),
312            "X-Should-Not-Be-Used".to_string(),
313        );
314        manager.set_credentials(stale);
315
316        let result = manager
317            .apply_auth_headers(
318                std::collections::HashMap::new(),
319                "GET",
320                "https://example.com",
321                Transport::Http,
322                None,
323            )
324            .await;
325
326        assert!(result.is_err());
327    }
328}