1use std::collections::HashMap;
14use std::fs;
15use std::path::PathBuf;
16use std::sync::{Mutex, MutexGuard, PoisonError};
17use std::time::Duration;
18
19use crate::Secret;
20use crate::config::{self, Config};
21use crate::state::{self, State};
22
23mod accounts;
24mod credential;
25pub mod gh_sign_in;
26mod hosts_yml;
27mod runner;
28pub mod signed_in;
29
30pub use accounts::{AccountSource, GitHubAccounts};
31pub use credential::{Credential, Scheme, Source};
32pub use hosts_yml::is_login;
33pub use runner::{Runner, SystemRunner};
34pub use signed_in::{SignedInAccount, SignedInAccounts, StoreError};
35
36use hosts_yml::parse_hosts_yml;
37
38const GH_TIMEOUT: Duration = Duration::from_secs(15);
39
40#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
43#[error("{0}")]
44pub struct CredentialError(pub String);
45
46pub trait Environment: Send + Sync {
48 fn var(&self, name: &str) -> Option<String>;
49}
50
51pub struct ProcessEnvironment;
52
53impl Environment for ProcessEnvironment {
54 fn var(&self, name: &str) -> Option<String> {
55 std::env::var(name).ok()
56 }
57}
58
59pub const GITHUB_ACCOUNT_KEY: &str = "github.activeAccount";
61
62pub fn saved_account() -> Option<String> {
64 let saved = State::load(&state::path()?);
65 saved.get(GITHUB_ACCOUNT_KEY).map(str::to_owned)
66}
67
68pub struct Credentials {
70 environment: Box<dyn Environment>,
71 runner: Box<dyn Runner>,
72 config: Config,
73 signed_in: SignedInAccounts,
74 sign_in_offered: bool,
76 tokens: Mutex<HashMap<String, Secret>>,
77 gh: Mutex<HashMap<String, Secret>>,
78}
79
80impl Credentials {
81 pub fn from_system(config: &Config) -> Self {
84 Self::new(config, ProcessEnvironment, SystemRunner)
85 .with_signed_in(SignedInAccounts::system())
86 }
87
88 pub fn new(
90 config: &Config,
91 environment: impl Environment + 'static,
92 runner: impl Runner + 'static,
93 ) -> Self {
94 Self {
95 environment: Box::new(environment),
96 runner: Box::new(runner),
97 config: config.clone(),
98 signed_in: SignedInAccounts::memory(),
99 sign_in_offered: false,
100 tokens: Mutex::new(HashMap::new()),
101 gh: Mutex::new(HashMap::new()),
102 }
103 }
104
105 pub fn with_signed_in(mut self, accounts: SignedInAccounts) -> Self {
107 self.signed_in = accounts;
108 self
109 }
110
111 pub fn with_sign_in_offered(mut self, offered: bool) -> Self {
114 self.sign_in_offered = offered;
115 self
116 }
117
118 pub fn sign_in_offered(&self) -> bool {
119 self.sign_in_offered
120 }
121
122 fn var(&self, name: &str) -> Option<String> {
124 let value = self.environment.var(name)?;
125 let value = value.trim();
126 (!value.is_empty()).then(|| value.to_owned())
127 }
128
129 fn env_or_config(
132 &self,
133 names: &[&'static str],
134 config: &Option<Secret>,
135 key: &'static str,
136 scheme: Scheme,
137 ) -> Option<Credential> {
138 let from_env = names.iter().find_map(|&name| {
139 self.var(name)
140 .map(|value| Credential::new(Secret::new(value), scheme, Source::Environment(name)))
141 });
142 from_env.or_else(|| {
143 config
144 .clone()
145 .map(|value| Credential::new(value, scheme, Source::ConfigFile(key)))
146 })
147 }
148
149 pub fn github(&self, login: Option<&str>) -> Result<Credential, CredentialError> {
153 let token = &self.config.github.token;
154 if let Some(credential) = self.env_or_config(
155 &["GH_TOKEN", "GITHUB_TOKEN"],
156 token,
157 "github.token",
158 Scheme::Bearer,
159 ) {
160 return Ok(credential);
161 }
162 let login = match login {
163 Some(login) => login.to_owned(),
164 None => {
165 let accounts = self.github_accounts()?;
166 accounts
167 .active
168 .or_else(|| accounts.logins.into_iter().next())
169 .ok_or_else(|| no_accounts(self.sign_in_offered))?
170 }
171 };
172 self.account(&login)
173 }
174
175 pub fn account(&self, login: &str) -> Result<Credential, CredentialError> {
179 if let Some(credential) = self.signed_in_credential(login)? {
180 return Ok(credential);
181 }
182 self.gh_cli(login)
183 .map_err(|error| self.expired_guidance(login).unwrap_or(error))
184 }
185
186 fn signed_in_credential(&self, login: &str) -> Result<Option<Credential>, CredentialError> {
188 let Some(account) = self
189 .signed_in
190 .find(login)
191 .filter(|account| !account.expired)
192 else {
193 return Ok(None);
194 };
195 let key = account.login.to_ascii_lowercase();
196 let mut cached = lock(&self.tokens);
197 let value = match cached.get(&key) {
198 Some(value) => Some(value.clone()),
199 None => self
200 .signed_in
201 .token(&account.login)
202 .map_err(|error| CredentialError(error.to_string()))?,
203 };
204 Ok(value.map(|value| {
205 cached.insert(key, value.clone());
206 Credential::new(
207 value,
208 Scheme::Bearer,
209 Source::SignedIn {
210 login: account.login,
211 },
212 )
213 }))
214 }
215
216 fn expired_guidance(&self, login: &str) -> Option<CredentialError> {
219 let account = self
220 .signed_in
221 .find(login)
222 .filter(|account| account.expired)?;
223 let next = if self.sign_in_offered {
224 "Sign in with GitHub again in Settings."
225 } else {
226 "Set GH_TOKEN, or run `gh auth login`."
227 };
228 Some(CredentialError(format!(
229 "GitHub no longer accepts the sign-in for {}. {next}",
230 account.login
231 )))
232 }
233
234 pub fn sign_in(&self, login: &str, token: &Secret) -> Result<(), CredentialError> {
236 lock(&self.tokens).remove(&login.to_ascii_lowercase());
237 self.signed_in
238 .save(login, token)
239 .map_err(|error| CredentialError(error.to_string()))
240 }
241
242 pub fn sign_out(&self, login: &str) -> Result<Option<Secret>, CredentialError> {
245 lock(&self.tokens).remove(&login.to_ascii_lowercase());
246 self.signed_in
247 .remove(login)
248 .map_err(|error| CredentialError(error.to_string()))
249 }
250
251 pub fn gh_cli(&self, login: &str) -> Result<Credential, CredentialError> {
254 let login = login.to_owned();
255 let sources = token_sources(self.sign_in_offered, "the config file");
256 let failed = || {
257 CredentialError(format!(
258 "Could not get a GitHub token for {login}. {sources}"
259 ))
260 };
261 if !is_login(&login) {
262 return Err(failed());
263 }
264 let mut cached = lock(&self.gh);
265 let value = match cached.get(&login) {
266 Some(value) => value.clone(),
267 None => {
268 let args = [
270 "auth",
271 "token",
272 "--hostname",
273 "github.com",
274 "--user",
275 login.as_str(),
276 ];
277 let output = self
278 .runner
279 .run("gh", &args, &["GH_TOKEN", "GITHUB_TOKEN"], GH_TIMEOUT)
280 .map_err(|_| failed())?;
281 let value = Some(output.trim())
282 .filter(|value| !value.is_empty())
283 .ok_or_else(failed)?;
284 let value = Secret::new(value);
285 cached.insert(login.clone(), value.clone());
286 value
287 }
288 };
289 Ok(Credential {
290 value,
291 scheme: Scheme::Bearer,
292 source: Source::GhCli { login },
293 })
294 }
295
296 pub fn github_accounts(&self) -> Result<GitHubAccounts, CredentialError> {
300 GitHubAccounts::merge(self.gh_accounts(), self.signed_in.accounts())
301 .ok_or_else(|| no_accounts(self.sign_in_offered))
302 }
303
304 fn gh_accounts(&self) -> Option<GitHubAccounts> {
306 let file = self.gh_config_dir()?.join("hosts.yml");
307 let text = fs::read_to_string(file).ok()?;
308 let mut accounts = parse_hosts_yml(&text);
309 if accounts.logins.is_empty() {
310 accounts.logins.extend(accounts.active.clone());
311 }
312 Some(accounts)
313 }
314
315 fn gh_config_dir(&self) -> Option<PathBuf> {
317 if let Some(dir) = self.var("GH_CONFIG_DIR") {
318 return Some(dir.into());
319 }
320 if let Some(dir) = self.var("XDG_CONFIG_HOME") {
321 return Some(PathBuf::from(dir).join("gh"));
322 }
323 if cfg!(windows)
324 && let Some(dir) = self.var("AppData")
325 {
326 return Some(PathBuf::from(dir).join("GitHub CLI"));
327 }
328 dirs::home_dir().map(|home| home.join(".config").join("gh"))
329 }
330
331 pub fn invalidate(&self, credential: &Credential) {
335 match &credential.source {
336 Source::GhCli { login } => self.forget_gh_token(login),
337 Source::SignedIn { login } => {
338 lock(&self.tokens).remove(&login.to_ascii_lowercase());
339 let _ = self.signed_in.reject(login, &credential.value);
341 }
342 Source::Environment(_) | Source::ConfigFile(_) => {}
343 }
344 }
345
346 pub fn forget_gh_token(&self, login: &str) {
348 lock(&self.gh).remove(login);
349 }
350}
351
352fn lock<T>(mutex: &Mutex<T>) -> MutexGuard<'_, T> {
353 mutex.lock().unwrap_or_else(PoisonError::into_inner)
354}
355
356fn no_accounts(sign_in_offered: bool) -> CredentialError {
357 CredentialError(format!(
358 "No GitHub accounts found. {}",
359 token_sources(sign_in_offered, &config::place())
360 ))
361}
362
363fn token_sources(sign_in_offered: bool, config: &str) -> String {
366 let lead = if sign_in_offered {
367 "Sign in with GitHub in Settings, set"
368 } else {
369 "Set"
370 };
371 format!("{lead} GH_TOKEN, set github.token in {config}, or run `gh auth login`.")
372}
373
374#[cfg(test)]
375mod tests {
376 use std::collections::HashMap;
377 use std::fs;
378 use std::sync::{Arc, Mutex};
379 use std::time::Duration;
380
381 use super::{
382 Credential, CredentialError, Credentials, Environment, GitHubAccounts, Runner, Scheme,
383 Source, parse_hosts_yml,
384 };
385 use crate::Secret;
386
387 use crate::config::Config;
388
389 struct Env(HashMap<&'static str, String>);
390
391 impl Environment for Env {
392 fn var(&self, name: &str) -> Option<String> {
393 self.0.get(name).cloned()
394 }
395 }
396
397 fn env(pairs: &[(&'static str, &str)]) -> Env {
398 Env(pairs
399 .iter()
400 .map(|&(name, value)| (name, value.to_owned()))
401 .collect())
402 }
403
404 #[derive(Clone, Default)]
407 struct Fake {
408 answers: Arc<Mutex<Vec<Result<String, String>>>>,
409 calls: Arc<Mutex<Vec<(String, Vec<String>, Vec<String>)>>>,
410 }
411
412 impl Fake {
413 fn answering(answers: &[Result<&str, &str>]) -> Self {
414 let fake = Self::default();
415 *fake.answers.lock().unwrap() = answers
416 .iter()
417 .rev()
418 .map(|answer| answer.map(Into::into).map_err(Into::into))
419 .collect();
420 fake
421 }
422
423 fn calls(&self) -> Vec<(String, Vec<String>, Vec<String>)> {
424 self.calls.lock().unwrap().clone()
425 }
426 }
427
428 impl Runner for Fake {
429 fn run(
430 &self,
431 program: &str,
432 args: &[&str],
433 remove: &[&str],
434 _timeout: Duration,
435 ) -> Result<String, String> {
436 let strings = |items: &[&str]| items.iter().map(ToString::to_string).collect();
437 self.calls
438 .lock()
439 .unwrap()
440 .push((program.into(), strings(args), strings(remove)));
441 self.answers
442 .lock()
443 .unwrap()
444 .pop()
445 .unwrap_or(Err("no answer".into()))
446 }
447 }
448
449 fn config_with_tokens() -> Config {
450 let mut config = Config::default();
451 config.github.token = Some(Secret::new("config-gh"));
452 config
453 }
454
455 fn source(result: Result<Credential, CredentialError>) -> Source {
456 result.unwrap().source
457 }
458
459 #[test]
460 fn e01_environment_wins_over_config_and_cli() {
461 let fake = Fake::default();
462 let environment = env(&[("GITHUB_TOKEN", "env-github"), ("GH_TOKEN", "env-gh")]);
463 let credentials = Credentials::new(&config_with_tokens(), environment, fake.clone());
464
465 let github = credentials.github(None).unwrap();
466 assert_eq!(github.source, Source::Environment("GH_TOKEN"));
467 assert_eq!(github.scheme, Scheme::Bearer);
468 assert_eq!(github.value.expose(), "env-gh");
469 assert!(fake.calls().is_empty());
470 }
471
472 #[test]
473 fn e02_config_wins_over_cli_and_empty_variables_count_as_unset() {
474 let fake = Fake::default();
475 let environment = env(&[("GH_TOKEN", " "), ("GITHUB_TOKEN", "")]);
476 let credentials = Credentials::new(&config_with_tokens(), environment, fake.clone());
477
478 assert_eq!(
479 source(credentials.github(Some("octo-dev"))),
480 Source::ConfigFile("github.token")
481 );
482 assert!(fake.calls().is_empty());
483 }
484
485 const HOSTS: &str = "\
486github.com:
487 users:
488 octo-dev_shell:
489 oauth_token: gho_secret_one
490 octocat:
491 oauth_token: gho_secret_two
492 \"bad login!\":
493 git_protocol: https
494 oauth_token: gho_secret_two # active token
495 user: octo-dev_shell
496ghe.example.com:
497 users:
498 other:
499 user: other
500";
501
502 #[test]
503 fn hosts_yml_gives_logins_and_the_active_login_but_no_tokens() {
504 let accounts = parse_hosts_yml(HOSTS);
505 assert_eq!(
506 accounts,
507 GitHubAccounts {
508 logins: vec!["octo-dev_shell".into(), "octocat".into()],
509 active: Some("octo-dev_shell".into()),
510 signed_in: Vec::new(),
511 }
512 );
513 assert!(!format!("{accounts:?}").contains("gho_"));
514 }
515
516 #[test]
517 fn hosts_yml_with_only_the_active_user() {
518 let accounts = parse_hosts_yml("github.com:\n user: 'solo'\n oauth_token: x\n");
519 assert_eq!(accounts.logins, Vec::<String>::new());
520 assert_eq!(accounts.active.as_deref(), Some("solo"));
521 }
522
523 #[test]
524 fn github_uses_gh_per_account_without_the_token_variables() {
525 let dir = tempfile::tempdir().unwrap();
526 fs::write(dir.path().join("hosts.yml"), HOSTS).unwrap();
527 let fake = Fake::answering(&[Ok("gho_one\n"), Ok("gho_two\n"), Ok("gho_one_new\n")]);
528 let environment = env(&[
529 ("GH_CONFIG_DIR", dir.path().to_str().unwrap()),
530 ("GITHUB_TOKEN", ""),
531 ]);
532 let credentials = Credentials::new(&Config::default(), environment, fake.clone());
533
534 assert_eq!(credentials.github_accounts().unwrap().logins.len(), 2);
535 let active = credentials.github(None).unwrap();
536 assert_eq!(active.value.expose(), "gho_one");
537 assert_eq!(
538 active.source,
539 Source::GhCli {
540 login: "octo-dev_shell".into()
541 }
542 );
543 assert_eq!(
544 credentials.github(Some("octocat")).unwrap().value.expose(),
545 "gho_two"
546 );
547 assert_eq!(credentials.github(None).unwrap().value.expose(), "gho_one");
549 credentials.invalidate(&active);
550 assert_eq!(
551 credentials.github(None).unwrap().value.expose(),
552 "gho_one_new"
553 );
554
555 let calls = fake.calls();
556 assert_eq!(calls.len(), 3);
557 assert_eq!(calls[0].0, "gh");
558 assert_eq!(
559 calls[0].1,
560 [
561 "auth",
562 "token",
563 "--hostname",
564 "github.com",
565 "--user",
566 "octo-dev_shell"
567 ]
568 );
569 assert_eq!(calls[0].2, ["GH_TOKEN", "GITHUB_TOKEN"]);
570 }
571
572 #[test]
573 fn github_without_accounts_or_with_a_bad_login_gives_guidance() {
574 let dir = tempfile::tempdir().unwrap();
575 let environment = env(&[("GH_CONFIG_DIR", dir.path().to_str().unwrap())]);
576 let fake = Fake::default();
577 let credentials = Credentials::new(&Config::default(), environment, fake.clone());
578 assert!(
579 credentials
580 .github(None)
581 .unwrap_err()
582 .0
583 .contains("gh auth login")
584 );
585 assert!(credentials.github(Some("--help")).is_err());
586 assert!(fake.calls().is_empty());
587 }
588
589 #[test]
590 fn missing_credentials_name_their_sources() {
591 let dir = tempfile::tempdir().unwrap();
592 let environment = env(&[("GH_CONFIG_DIR", dir.path().to_str().unwrap())]);
593 let credentials = Credentials::new(&Config::default(), environment, Fake::default());
594 let place = crate::config::place();
596 let message = credentials.github(None).unwrap_err().0;
597 assert!(
598 message.contains(&format!("github.token in {place}")),
599 "{message}"
600 );
601 assert!(message.contains("GH_TOKEN"), "{message}");
602 }
603
604 #[test]
605 fn guidance_names_sign_in_with_github_only_when_the_app_offers_it() {
606 let dir = tempfile::tempdir().unwrap();
607 let credentials = |offered| {
608 let environment = env(&[("GH_CONFIG_DIR", dir.path().to_str().unwrap())]);
609 Credentials::new(&Config::default(), environment, Fake::default())
610 .with_signed_in(signed_in("octo-dev", "old"))
611 .with_sign_in_offered(offered)
612 };
613 for offered in [false, true] {
614 let credentials = credentials(offered);
615 assert_eq!(credentials.sign_in_offered(), offered);
616 let missing = credentials.gh_cli("octocat").unwrap_err().0;
617 let rejected = credentials.github(Some("octo-dev")).unwrap();
618 credentials.invalidate(&rejected);
619 let expired = credentials.github(Some("octo-dev")).unwrap_err().0;
620 for message in [missing, expired] {
621 assert_eq!(
622 message.contains("Sign in with GitHub"),
623 offered,
624 "{message}"
625 );
626 assert!(offered || message.contains("gh auth login"), "{message}");
627 }
628 }
629 let empty = Credentials::new(
630 &Config::default(),
631 env(&[("GH_CONFIG_DIR", dir.path().to_str().unwrap())]),
632 Fake::default(),
633 );
634 let message = empty.github(None).unwrap_err().0;
635 assert!(
636 message.starts_with("No GitHub accounts found. Set GH_TOKEN"),
637 "{message}"
638 );
639 }
640
641 #[test]
642 fn debug_and_errors_show_no_credential() {
643 let credential = Credential {
644 value: Secret::new("pat-value"),
645 scheme: Scheme::Bearer,
646 source: Source::Environment("GH_TOKEN"),
647 };
648 assert!(!format!("{credential:?}").contains("pat-value"));
649 let header = credential.authorization();
650 assert_eq!(format!("{header:?}"), "***");
651 assert_eq!(header.expose(), "Bearer pat-value");
652 }
653
654 fn signed_in(login: &str, token: &str) -> crate::credentials::SignedInAccounts {
655 let accounts = crate::credentials::SignedInAccounts::memory();
656 accounts.save(login, &Secret::new(token)).unwrap();
657 accounts
658 }
659
660 #[test]
661 fn precedence_is_environment_config_signed_in_then_gh() {
662 let dir = tempfile::tempdir().unwrap();
663 fs::write(dir.path().join("hosts.yml"), HOSTS).unwrap();
664 let gh_dir = dir.path().to_str().unwrap();
665 let with = |pairs: &[(&'static str, &str)], config: &Config| {
666 Credentials::new(config, env(pairs), Fake::answering(&[Ok("gho_cli")]))
667 .with_signed_in(signed_in("octocat", "signed-in-token"))
668 };
669 let environment = with(
670 &[("GH_TOKEN", "env"), ("GH_CONFIG_DIR", gh_dir)],
671 &config_with_tokens(),
672 );
673 assert_eq!(
674 source(environment.github(Some("octocat"))),
675 Source::Environment("GH_TOKEN")
676 );
677 let config = with(&[("GH_CONFIG_DIR", gh_dir)], &config_with_tokens());
678 assert_eq!(
679 source(config.github(Some("octocat"))),
680 Source::ConfigFile("github.token")
681 );
682 let accounts = with(&[("GH_CONFIG_DIR", gh_dir)], &Config::default());
683 let credential = accounts.github(Some("OCTOCAT")).unwrap();
684 assert_eq!(credential.value.expose(), "signed-in-token");
685 assert_eq!(
686 credential.source,
687 Source::SignedIn {
688 login: "octocat".into()
689 }
690 );
691 let gh = accounts.github(Some("octo-dev_shell")).unwrap();
692 assert_eq!(gh.value.expose(), "gho_cli");
693 assert!(matches!(gh.source, Source::GhCli { .. }));
694 }
695
696 #[test]
697 fn signed_in_accounts_are_listed_with_gh_and_work_without_gh() {
698 let dir = tempfile::tempdir().unwrap();
699 fs::write(dir.path().join("hosts.yml"), HOSTS).unwrap();
700 let with_gh = Credentials::new(
701 &Config::default(),
702 env(&[("GH_CONFIG_DIR", dir.path().to_str().unwrap())]),
703 Fake::default(),
704 )
705 .with_signed_in(signed_in("OctoCat", "token"));
706 let accounts = with_gh.github_accounts().unwrap();
707 assert_eq!(accounts.logins, ["OctoCat", "octo-dev_shell"]);
708 let empty = tempfile::tempdir().unwrap();
709 let without_gh = Credentials::new(
710 &Config::default(),
711 env(&[("GH_CONFIG_DIR", empty.path().to_str().unwrap())]),
712 Fake::default(),
713 )
714 .with_signed_in(signed_in("octo-dev", "token"));
715 assert_eq!(without_gh.github(None).unwrap().value.expose(), "token");
716 }
717
718 #[test]
719 fn a_rejected_signed_in_token_asks_for_sign_in_again() {
720 let empty = tempfile::tempdir().unwrap();
721 let credentials = Credentials::new(
722 &Config::default(),
723 env(&[("GH_CONFIG_DIR", empty.path().to_str().unwrap())]),
724 Fake::default(),
725 )
726 .with_signed_in(signed_in("octo-dev", "old"))
727 .with_sign_in_offered(true);
728 let rejected = credentials.github(Some("octo-dev")).unwrap();
729 credentials.invalidate(&rejected);
730 let message = credentials.github(Some("octo-dev")).unwrap_err().0;
731 assert!(message.contains("Sign in with GitHub again"), "{message}");
732 credentials
733 .sign_in("octo-dev", &Secret::new("new"))
734 .unwrap();
735 assert_eq!(credentials.github(None).unwrap().value.expose(), "new");
736 assert_eq!(
737 credentials.sign_out("octo-dev").unwrap(),
738 Some(Secret::new("new"))
739 );
740 assert!(credentials.github(None).is_err());
741 }
742}