Skip to main content

orch/github/
token.rs

1//! Centralized GitHub token resolution from env vars, config, and the gh CLI.
2//!
3//! Out of the box, `TokenResolver::default()` works with just `gh auth login`, no extra config needed.
4//! Resolution order:
5//! 1. `GH_TOKEN` environment variable
6//! 2. `GITHUB_TOKEN` environment variable
7//! 3. `gh.auth.token` config value, as written, `${NAME}` or `passbox:<name>`
8//! 4. `gh auth token` CLI (via `allow_gh_fallback = true`)
9
10use std::env;
11use std::process::Command;
12#[cfg(test)]
13use std::sync::Mutex;
14use std::sync::{Arc, OnceLock};
15use tokio::sync::RwLock;
16
17use crate::config;
18use crate::security::secret_ref;
19
20/// Centralized token resolver for GitHub authentication.
21///
22/// ## Default setup
23///
24/// ```rust,ignore
25/// let resolver = TokenResolver::default(); // uses gh auth token if no env var set
26/// let token = resolver.get_token().await?;
27/// ```
28#[derive(Debug, Clone)]
29pub struct TokenResolver {
30    /// Whether to fall back to `gh auth token` CLI when env vars and config are unset.
31    ///
32    /// Defaults to `true` — just run `gh auth login` and everything works.
33    allow_gh_fallback: bool,
34    /// Cached token, kept until `clear_cache` drops it.
35    cached: Arc<RwLock<Option<String>>>,
36}
37
38impl TokenResolver {
39    /// Create a default TokenResolver using environment variables with gh CLI fallback.
40    pub fn default_env() -> Self {
41        Self {
42            allow_gh_fallback: true,
43            cached: Arc::new(RwLock::new(None)),
44        }
45    }
46
47    /// Enable or disable `gh auth token` CLI fallback.
48    #[cfg(test)]
49    #[must_use]
50    pub fn with_gh_fallback(mut self, enabled: bool) -> Self {
51        self.allow_gh_fallback = enabled;
52        self
53    }
54
55    /// Resolve the GitHub token asynchronously.
56    ///
57    /// Returns `Ok(Some(token))` if a token is available,
58    /// `Ok(None)` if no token could be resolved,
59    /// or `Err` if an error occurred during resolution.
60    pub async fn get_token(&self) -> anyhow::Result<Option<String>> {
61        if let Some(ref t) = *self.cached.read().await {
62            return Ok(Some(t.clone()));
63        }
64
65        let token = self.resolve_fresh().await?;
66        if let Some(ref t) = token {
67            *self.cached.write().await = Some(t.clone());
68        }
69
70        Ok(token)
71    }
72
73    /// Clear the cached token (useful when token is known to be invalid).
74    pub async fn clear_cache(&self) {
75        let mut cached = self.cached.write().await;
76        *cached = None;
77    }
78
79    /// Resolve a fresh token: env vars and config first, then the gh CLI.
80    async fn resolve_fresh(&self) -> anyhow::Result<Option<String>> {
81        if let Some(t) = Self::resolve_env_token() {
82            return Ok(Some(t));
83        }
84        if let Some(t) = Self::resolve_config_token().await? {
85            return Ok(Some(t));
86        }
87
88        // gh CLI fallback — the default when nothing else is configured
89        if self.allow_gh_fallback {
90            tracing::debug!("No token in env/config — trying gh auth token CLI");
91            return Self::resolve_gh_cli_token();
92        }
93
94        Ok(None)
95    }
96
97    /// Resolve token from the `GH_TOKEN` and `GITHUB_TOKEN` environment variables, in that order.
98    fn resolve_env_token() -> Option<String> {
99        if let Ok(t) = env::var("GH_TOKEN")
100            && !t.is_empty()
101        {
102            // Info, not debug: when a token turns out bad, the source is the first thing to check
103            tracing::info!("Resolved GitHub token from GH_TOKEN environment variable");
104            return Some(t);
105        }
106        if let Ok(t) = env::var("GITHUB_TOKEN")
107            && !t.is_empty()
108        {
109            tracing::info!("Resolved GitHub token from GITHUB_TOKEN environment variable");
110            return Some(t);
111        }
112        None
113    }
114
115    /// Resolve `gh.auth.token`, which holds the token, `${NAME}` or `passbox:<name>`.
116    async fn resolve_config_token() -> anyhow::Result<Option<String>> {
117        // A missing or empty key falls through to the gh CLI, a configured reference that fails must not
118        if config::get_global("gh.auth.token").is_ok_and(|v| !v.is_empty()) {
119            let t = secret_ref::config_secret("gh.auth.token").await?;
120            tracing::info!("Resolved GitHub token from gh.auth.token config");
121            return Ok(Some(t));
122        }
123        Ok(None)
124    }
125
126    /// Resolve token using `gh auth token` CLI.
127    fn resolve_gh_cli_token() -> anyhow::Result<Option<String>> {
128        tracing::debug!("Attempting to resolve GitHub token via gh CLI");
129
130        // Try gh in PATH first
131        if let Some(token) = Self::try_gh_command("gh")? {
132            return Ok(Some(token));
133        }
134
135        // Try common gh install paths for launchd/Homebrew environments
136        for path in &["/opt/homebrew/bin/gh", "/usr/local/bin/gh"] {
137            if let Some(token) = Self::try_gh_command(path)? {
138                return Ok(Some(token));
139            }
140        }
141
142        Ok(None)
143    }
144
145    /// Try to get token from a specific gh binary path.
146    ///
147    /// # Why `std::process::Command` (blocking) is intentional here
148    ///
149    /// This looks like a "blocking call in async context" antipattern, but it is not a problem:
150    /// - `resolve_fresh()` is only called from `get_token()` on a cache miss
151    /// - The result is cached until a 401 clears it, so this runs once at startup
152    ///   and again after each 401
153    /// - A one-time ~100ms call does not meaningfully block the Tokio runtime
154    ///
155    /// DO NOT replace this with `spawn_blocking` or `tokio::process::Command` —
156    /// the added complexity is not justified and previous attempts to "fix" this
157    /// broke the auth flow. See issues #418 and #421 (closed as invalid).
158    #[expect(
159        clippy::unnecessary_wraps,
160        reason = "the gh fallback is settled code, see issues 418 and 421"
161    )]
162    fn try_gh_command(gh_path: &str) -> anyhow::Result<Option<String>> {
163        match Command::new(gh_path).args(["auth", "token"]).output() {
164            Ok(out) if out.status.success() => {
165                let token = String::from_utf8_lossy(&out.stdout).trim().to_string();
166                if !token.is_empty() {
167                    tracing::info!(gh_path, "Resolved GitHub token via gh CLI (keychain)");
168                    return Ok(Some(token));
169                }
170            }
171            Ok(out) => {
172                let stderr = String::from_utf8_lossy(&out.stderr);
173                tracing::debug!(gh_path, %stderr, "gh auth token failed");
174            }
175            Err(e) => {
176                tracing::debug!(gh_path, error = %e, "Failed to execute gh command");
177            }
178        }
179        Ok(None)
180    }
181}
182
183/// Process-wide shared [`TokenResolver`].
184///
185/// Initialized once on first call. All callers (GhHttp, agent runner, etc.)
186/// share the same instance so the token is resolved once — via GH_TOKEN,
187/// GITHUB_TOKEN, or `gh auth token` CLI — and cached for the life of the process.
188static SHARED_RESOLVER: OnceLock<Arc<TokenResolver>> = OnceLock::new();
189
190/// Get the process-wide shared token resolver.
191pub fn shared() -> Arc<TokenResolver> {
192    Arc::clone(SHARED_RESOLVER.get_or_init(|| Arc::new(TokenResolver::default_env())))
193}
194
195impl Default for TokenResolver {
196    fn default() -> Self {
197        Self::default_env()
198    }
199}
200
201/// Serializes tests that mutate `GH_TOKEN`/`GITHUB_TOKEN`, shared with http.rs tests
202#[cfg(test)]
203pub(crate) static ENV_LOCK: Mutex<()> = Mutex::new(());
204
205#[cfg(test)]
206mod tests {
207    use std::fs;
208
209    use super::*;
210
211    #[test]
212    fn token_resolver_gh_fallback_enabled_by_default() {
213        let resolver = TokenResolver::default_env();
214        assert!(resolver.allow_gh_fallback);
215    }
216
217    #[test]
218    fn token_resolver_with_gh_fallback() {
219        let resolver = TokenResolver::default_env().with_gh_fallback(false);
220        assert!(!resolver.allow_gh_fallback);
221    }
222
223    #[expect(
224        clippy::await_holding_lock,
225        reason = "the guard keeps env var tests serial across awaits"
226    )]
227    #[tokio::test(flavor = "current_thread")]
228    async fn get_token_returns_none_when_no_env_set() {
229        let _guard = ENV_LOCK.lock().unwrap();
230        // SAFETY: nextest runs each test in its own process, so no other test touches the environment
231        unsafe { env::remove_var("GH_TOKEN") };
232        // SAFETY: nextest runs each test in its own process, so no other test touches the environment
233        unsafe { env::remove_var("GITHUB_TOKEN") };
234        // Disable gh fallback so we don't actually call gh CLI in tests
235        let resolver = TokenResolver::default_env().with_gh_fallback(false);
236        resolver.clear_cache().await;
237
238        let token = resolver.get_token().await.unwrap();
239        assert!(token.is_none());
240    }
241
242    #[expect(
243        clippy::await_holding_lock,
244        reason = "the guard keeps env var tests serial across awaits"
245    )]
246    #[tokio::test(flavor = "current_thread")]
247    async fn get_token_prefers_gh_token() {
248        let _guard = ENV_LOCK.lock().unwrap();
249        // SAFETY: nextest runs each test in its own process, so no other test touches the environment
250        unsafe { env::remove_var("GH_TOKEN") };
251        // SAFETY: nextest runs each test in its own process, so no other test touches the environment
252        unsafe { env::remove_var("GITHUB_TOKEN") };
253        let resolver = TokenResolver::default_env().with_gh_fallback(false);
254        resolver.clear_cache().await;
255
256        // SAFETY: nextest runs each test in its own process, so no other test touches the environment
257        unsafe { env::set_var("GH_TOKEN", "gh_token_value") };
258        // SAFETY: nextest runs each test in its own process, so no other test touches the environment
259        unsafe { env::remove_var("GITHUB_TOKEN") };
260
261        let resolver = TokenResolver::default_env().with_gh_fallback(false);
262        let token = resolver.get_token().await.unwrap();
263        assert_eq!(token, Some("gh_token_value".to_string()));
264
265        // SAFETY: nextest runs each test in its own process, so no other test touches the environment
266        unsafe { env::remove_var("GH_TOKEN") };
267    }
268
269    #[expect(
270        clippy::await_holding_lock,
271        reason = "the guard keeps env var tests serial across awaits"
272    )]
273    #[tokio::test(flavor = "current_thread")]
274    async fn get_token_falls_back_to_github_token() {
275        let _guard = ENV_LOCK.lock().unwrap();
276        // SAFETY: nextest runs each test in its own process, so no other test touches the environment
277        unsafe { env::remove_var("GH_TOKEN") };
278        // SAFETY: nextest runs each test in its own process, so no other test touches the environment
279        unsafe { env::remove_var("GITHUB_TOKEN") };
280        let resolver = TokenResolver::default_env().with_gh_fallback(false);
281        resolver.clear_cache().await;
282
283        // SAFETY: nextest runs each test in its own process, so no other test touches the environment
284        unsafe { env::set_var("GITHUB_TOKEN", "github_token_value") };
285
286        let token = resolver.get_token().await.unwrap();
287        assert_eq!(token, Some("github_token_value".to_string()));
288
289        // SAFETY: nextest runs each test in its own process, so no other test touches the environment
290        unsafe { env::remove_var("GITHUB_TOKEN") };
291    }
292
293    #[expect(
294        clippy::await_holding_lock,
295        reason = "the guard keeps env var tests serial across awaits"
296    )]
297    #[tokio::test(flavor = "current_thread")]
298    async fn get_token_prefers_gh_token_over_github_token() {
299        let _guard = ENV_LOCK.lock().unwrap();
300        // SAFETY: nextest runs each test in its own process, so no other test touches the environment
301        unsafe { env::remove_var("GH_TOKEN") };
302        // SAFETY: nextest runs each test in its own process, so no other test touches the environment
303        unsafe { env::remove_var("GITHUB_TOKEN") };
304        let resolver = TokenResolver::default_env().with_gh_fallback(false);
305        resolver.clear_cache().await;
306
307        // SAFETY: nextest runs each test in its own process, so no other test touches the environment
308        unsafe { env::set_var("GH_TOKEN", "gh_token_value") };
309        // SAFETY: nextest runs each test in its own process, so no other test touches the environment
310        unsafe { env::set_var("GITHUB_TOKEN", "github_token_value") };
311
312        let token = resolver.get_token().await.unwrap();
313        // GH_TOKEN should be preferred
314        assert_eq!(token, Some("gh_token_value".to_string()));
315
316        // SAFETY: nextest runs each test in its own process, so no other test touches the environment
317        unsafe { env::remove_var("GH_TOKEN") };
318        // SAFETY: nextest runs each test in its own process, so no other test touches the environment
319        unsafe { env::remove_var("GITHUB_TOKEN") };
320    }
321
322    #[expect(
323        clippy::await_holding_lock,
324        reason = "the guard keeps env var tests serial across awaits"
325    )]
326    #[tokio::test(flavor = "current_thread")]
327    async fn get_token_ignores_empty_env_vars() {
328        let _guard = ENV_LOCK.lock().unwrap();
329        // SAFETY: nextest runs each test in its own process, so no other test touches the environment
330        unsafe { env::remove_var("GH_TOKEN") };
331        // SAFETY: nextest runs each test in its own process, so no other test touches the environment
332        unsafe { env::remove_var("GITHUB_TOKEN") };
333        let resolver = TokenResolver::default_env().with_gh_fallback(false);
334        resolver.clear_cache().await;
335
336        // SAFETY: nextest runs each test in its own process, so no other test touches the environment
337        unsafe { env::set_var("GH_TOKEN", "") };
338        // SAFETY: nextest runs each test in its own process, so no other test touches the environment
339        unsafe { env::set_var("GITHUB_TOKEN", "") };
340
341        let token = resolver.get_token().await.unwrap();
342        assert!(token.is_none());
343
344        // SAFETY: nextest runs each test in its own process, so no other test touches the environment
345        unsafe { env::remove_var("GH_TOKEN") };
346        // SAFETY: nextest runs each test in its own process, so no other test touches the environment
347        unsafe { env::remove_var("GITHUB_TOKEN") };
348    }
349
350    #[expect(
351        clippy::await_holding_lock,
352        reason = "the guard keeps env var tests serial across awaits"
353    )]
354    #[tokio::test(flavor = "current_thread")]
355    async fn clear_cache_clears_token() {
356        let _guard = ENV_LOCK.lock().unwrap();
357        // SAFETY: nextest runs each test in its own process, so no other test touches the environment
358        unsafe { env::remove_var("GH_TOKEN") };
359        // SAFETY: nextest runs each test in its own process, so no other test touches the environment
360        unsafe { env::remove_var("GITHUB_TOKEN") };
361        let resolver = TokenResolver::default_env().with_gh_fallback(false);
362        resolver.clear_cache().await;
363
364        // SAFETY: nextest runs each test in its own process, so no other test touches the environment
365        unsafe { env::set_var("GH_TOKEN", "cached_token") };
366
367        // First call should cache the token
368        let token1 = resolver.get_token().await.unwrap();
369        assert_eq!(token1, Some("cached_token".to_string()));
370
371        // Clear cache
372        resolver.clear_cache().await;
373
374        // Token should still resolve (fresh lookup)
375        let token2 = resolver.get_token().await.unwrap();
376        assert_eq!(token2, Some("cached_token".to_string()));
377
378        // SAFETY: nextest runs each test in its own process, so no other test touches the environment
379        unsafe { env::remove_var("GH_TOKEN") };
380    }
381
382    /// Points ORCH_HOME at a temp config holding `yaml`, so the operator's config is never read
383    fn config_home(yaml: &str) -> tempfile::TempDir {
384        let home = tempfile::tempdir().unwrap();
385        fs::write(home.path().join("config.yml"), yaml).unwrap();
386        // SAFETY: nextest runs each test in its own process, so no other test touches the environment
387        unsafe { env::set_var("ORCH_HOME", home.path()) };
388        home
389    }
390
391    #[tokio::test(flavor = "current_thread")]
392    async fn config_token_is_used_as_written() {
393        let _home = config_home("gh:\n  auth:\n    token: plain-token\n");
394        let token = TokenResolver::resolve_config_token().await.unwrap();
395        assert_eq!(token, Some("plain-token".to_string()));
396    }
397
398    #[tokio::test(flavor = "current_thread")]
399    async fn config_token_expands_an_env_reference() {
400        // SAFETY: nextest runs each test in its own process, so no other test touches the environment
401        unsafe { env::set_var("ORCH_GH_TOKEN_TEST_SET", "from-env") };
402        let _home = config_home("gh:\n  auth:\n    token: \"${ORCH_GH_TOKEN_TEST_SET}\"\n");
403        let token = TokenResolver::resolve_config_token().await.unwrap();
404        assert_eq!(token, Some("from-env".to_string()));
405    }
406
407    #[tokio::test(flavor = "current_thread")]
408    async fn config_token_missing_key_falls_through() {
409        let _home = config_home("gh:\n  repo: owner/repo\n");
410        let token = TokenResolver::resolve_config_token().await.unwrap();
411        assert!(token.is_none());
412    }
413
414    #[expect(
415        clippy::await_holding_lock,
416        reason = "the guard keeps env var tests serial across awaits"
417    )]
418    #[tokio::test(flavor = "current_thread")]
419    async fn a_failed_config_reference_does_not_fall_through_to_the_gh_cli() {
420        let _guard = ENV_LOCK.lock().unwrap();
421        // SAFETY: nextest runs each test in its own process, so no other test touches the environment
422        unsafe { env::remove_var("GH_TOKEN") };
423        // SAFETY: nextest runs each test in its own process, so no other test touches the environment
424        unsafe { env::remove_var("GITHUB_TOKEN") };
425        // SAFETY: nextest runs each test in its own process, so no other test touches the environment
426        unsafe { env::remove_var("ORCH_GH_TOKEN_TEST_UNSET") };
427        let _home = config_home("gh:\n  auth:\n    token: \"${ORCH_GH_TOKEN_TEST_UNSET}\"\n");
428
429        // The gh fallback is on, so a fall-through would return a token or Ok(None), never an error
430        let resolver = TokenResolver::default_env();
431        let err = resolver.get_token().await.unwrap_err().to_string();
432        assert!(err.contains("ORCH_GH_TOKEN_TEST_UNSET"), "{err}");
433    }
434
435    #[test]
436    fn resolve_env_token_returns_none_when_unset() {
437        let _guard = ENV_LOCK.lock().unwrap();
438        // SAFETY: nextest runs each test in its own process, so no other test touches the environment
439        unsafe { env::remove_var("GH_TOKEN") };
440        // SAFETY: nextest runs each test in its own process, so no other test touches the environment
441        unsafe { env::remove_var("GITHUB_TOKEN") };
442
443        let token = TokenResolver::resolve_env_token();
444        assert!(token.is_none());
445    }
446
447    #[test]
448    fn resolve_env_token_prefers_gh_token() {
449        let _guard = ENV_LOCK.lock().unwrap();
450        // SAFETY: nextest runs each test in its own process, so no other test touches the environment
451        unsafe { env::set_var("GH_TOKEN", "gh_pref") };
452        // SAFETY: nextest runs each test in its own process, so no other test touches the environment
453        unsafe { env::set_var("GITHUB_TOKEN", "github_pref") };
454
455        let token = TokenResolver::resolve_env_token();
456        assert_eq!(token, Some("gh_pref".to_string()));
457
458        // SAFETY: nextest runs each test in its own process, so no other test touches the environment
459        unsafe { env::remove_var("GH_TOKEN") };
460        // SAFETY: nextest runs each test in its own process, so no other test touches the environment
461        unsafe { env::remove_var("GITHUB_TOKEN") };
462    }
463}