1use 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#[derive(Debug, Clone)]
29pub struct TokenResolver {
30 allow_gh_fallback: bool,
34 cached: Arc<RwLock<Option<String>>>,
36}
37
38impl TokenResolver {
39 pub fn default_env() -> Self {
41 Self {
42 allow_gh_fallback: true,
43 cached: Arc::new(RwLock::new(None)),
44 }
45 }
46
47 #[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 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 pub async fn clear_cache(&self) {
75 let mut cached = self.cached.write().await;
76 *cached = None;
77 }
78
79 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 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 fn resolve_env_token() -> Option<String> {
99 if let Ok(t) = env::var("GH_TOKEN")
100 && !t.is_empty()
101 {
102 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 async fn resolve_config_token() -> anyhow::Result<Option<String>> {
117 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 fn resolve_gh_cli_token() -> anyhow::Result<Option<String>> {
128 tracing::debug!("Attempting to resolve GitHub token via gh CLI");
129
130 if let Some(token) = Self::try_gh_command("gh")? {
132 return Ok(Some(token));
133 }
134
135 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 #[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
183static SHARED_RESOLVER: OnceLock<Arc<TokenResolver>> = OnceLock::new();
189
190pub 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#[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 unsafe { env::remove_var("GH_TOKEN") };
232 unsafe { env::remove_var("GITHUB_TOKEN") };
234 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 unsafe { env::remove_var("GH_TOKEN") };
251 unsafe { env::remove_var("GITHUB_TOKEN") };
253 let resolver = TokenResolver::default_env().with_gh_fallback(false);
254 resolver.clear_cache().await;
255
256 unsafe { env::set_var("GH_TOKEN", "gh_token_value") };
258 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 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 unsafe { env::remove_var("GH_TOKEN") };
278 unsafe { env::remove_var("GITHUB_TOKEN") };
280 let resolver = TokenResolver::default_env().with_gh_fallback(false);
281 resolver.clear_cache().await;
282
283 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 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 unsafe { env::remove_var("GH_TOKEN") };
302 unsafe { env::remove_var("GITHUB_TOKEN") };
304 let resolver = TokenResolver::default_env().with_gh_fallback(false);
305 resolver.clear_cache().await;
306
307 unsafe { env::set_var("GH_TOKEN", "gh_token_value") };
309 unsafe { env::set_var("GITHUB_TOKEN", "github_token_value") };
311
312 let token = resolver.get_token().await.unwrap();
313 assert_eq!(token, Some("gh_token_value".to_string()));
315
316 unsafe { env::remove_var("GH_TOKEN") };
318 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 unsafe { env::remove_var("GH_TOKEN") };
331 unsafe { env::remove_var("GITHUB_TOKEN") };
333 let resolver = TokenResolver::default_env().with_gh_fallback(false);
334 resolver.clear_cache().await;
335
336 unsafe { env::set_var("GH_TOKEN", "") };
338 unsafe { env::set_var("GITHUB_TOKEN", "") };
340
341 let token = resolver.get_token().await.unwrap();
342 assert!(token.is_none());
343
344 unsafe { env::remove_var("GH_TOKEN") };
346 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 unsafe { env::remove_var("GH_TOKEN") };
359 unsafe { env::remove_var("GITHUB_TOKEN") };
361 let resolver = TokenResolver::default_env().with_gh_fallback(false);
362 resolver.clear_cache().await;
363
364 unsafe { env::set_var("GH_TOKEN", "cached_token") };
366
367 let token1 = resolver.get_token().await.unwrap();
369 assert_eq!(token1, Some("cached_token".to_string()));
370
371 resolver.clear_cache().await;
373
374 let token2 = resolver.get_token().await.unwrap();
376 assert_eq!(token2, Some("cached_token".to_string()));
377
378 unsafe { env::remove_var("GH_TOKEN") };
380 }
381
382 fn config_home(yaml: &str) -> tempfile::TempDir {
384 let home = tempfile::tempdir().unwrap();
385 fs::write(home.path().join("config.yml"), yaml).unwrap();
386 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 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 unsafe { env::remove_var("GH_TOKEN") };
423 unsafe { env::remove_var("GITHUB_TOKEN") };
425 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 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 unsafe { env::remove_var("GH_TOKEN") };
440 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 unsafe { env::set_var("GH_TOKEN", "gh_pref") };
452 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 unsafe { env::remove_var("GH_TOKEN") };
460 unsafe { env::remove_var("GITHUB_TOKEN") };
462 }
463}