use std::path::PathBuf;
use std::time::Duration;
use anyhow::Context;
pub const GH_PROBE_TIMEOUT: Duration = Duration::from_millis(250);
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct GhAccountStatus {
pub active: Option<String>,
pub logged_in: Vec<String>,
}
impl GhAccountStatus {
pub fn is_ambiguous(&self) -> bool {
self.logged_in.len() > 1
}
}
fn gh_config_dir() -> Option<PathBuf> {
if let Ok(dir) = std::env::var("GH_CONFIG_DIR") {
let dir = dir.trim();
if !dir.is_empty() {
return Some(PathBuf::from(dir));
}
}
if let Ok(xdg) = std::env::var("XDG_CONFIG_HOME") {
let xdg = xdg.trim();
if !xdg.is_empty() {
return Some(PathBuf::from(xdg).join("gh"));
}
}
dirs::home_dir().map(|h| h.join(".config").join("gh"))
}
fn gh_hosts_yml_path() -> Option<PathBuf> {
Some(gh_config_dir()?.join("hosts.yml"))
}
pub fn parse_active_account_from_hosts_yml(yaml: &str) -> Option<String> {
let doc: serde_yaml::Value = serde_yaml::from_str(yaml).ok()?;
let user = doc.get("github.com")?.get("user")?.as_str()?.trim();
if user.is_empty() {
None
} else {
Some(user.to_string())
}
}
pub fn parse_gh_account_status_from_hosts_yml(yaml: &str) -> Option<GhAccountStatus> {
let doc: serde_yaml::Value = serde_yaml::from_str(yaml).ok()?;
let host = doc.get("github.com")?;
let active = host
.get("user")
.and_then(|v| v.as_str())
.map(|s| s.trim().to_string())
.filter(|s| !s.is_empty());
let mut logged_in: Vec<String> = Vec::new();
if let Some(users) = host.get("users").and_then(|v| v.as_mapping()) {
for key in users.keys() {
if let Some(name) = key.as_str() {
let name = name.trim();
if !name.is_empty() && !logged_in.iter().any(|e| e == name) {
logged_in.push(name.to_string());
}
}
}
}
if logged_in.is_empty()
&& let Some(a) = &active
{
logged_in.push(a.clone());
}
if active.is_none() && logged_in.is_empty() {
return None;
}
Some(GhAccountStatus { active, logged_in })
}
pub fn parse_logged_in_accounts(auth_status: &str) -> Vec<String> {
let mut out: Vec<String> = Vec::new();
for line in auth_status.lines() {
let Some((_, rest)) = line.split_once("Logged in to") else {
continue;
};
if let Some(login) = extract_login_token(rest)
&& !out.iter().any(|e| e == &login)
{
out.push(login);
}
}
out
}
fn extract_login_token(rest: &str) -> Option<String> {
let tokens: Vec<&str> = rest.split_whitespace().collect();
for keyword in ["account", "as"] {
if let Some(pos) = tokens.iter().position(|t| *t == keyword)
&& let Some(raw) = tokens.get(pos + 1)
{
let login = raw.trim_matches(|c: char| !c.is_alphanumeric() && c != '-' && c != '_');
if !login.is_empty() {
return Some(login.to_string());
}
}
}
None
}
pub fn gh_account_status_local() -> Option<GhAccountStatus> {
let path = gh_hosts_yml_path()?;
let contents = std::fs::read_to_string(&path).ok()?;
parse_gh_account_status_from_hosts_yml(&contents)
}
fn run_bounded<T, F>(timeout: Duration, f: F) -> Option<T>
where
T: Send + 'static,
F: FnOnce() -> Option<T> + Send + 'static,
{
use std::sync::mpsc;
let (tx, rx) = mpsc::channel();
std::thread::spawn(move || {
let _ = tx.send(f());
});
rx.recv_timeout(timeout).ok().flatten()
}
pub fn active_gh_account() -> Option<String> {
if let Some(status) = gh_account_status_local()
&& let Some(active) = status.active
{
return Some(active);
}
run_bounded(GH_PROBE_TIMEOUT, || {
let out = std::process::Command::new("gh")
.args(["auth", "status", "--active"])
.output()
.ok()?;
let mut text = String::from_utf8_lossy(&out.stdout).into_owned();
text.push('\n');
text.push_str(&String::from_utf8_lossy(&out.stderr));
parse_logged_in_accounts(&text).into_iter().next()
})
}
pub fn logged_in_gh_accounts() -> Vec<String> {
run_bounded(GH_PROBE_TIMEOUT, || {
let out = std::process::Command::new("gh")
.args(["auth", "status"])
.output()
.ok()?;
let mut text = String::from_utf8_lossy(&out.stdout).into_owned();
text.push('\n');
text.push_str(&String::from_utf8_lossy(&out.stderr));
Some(parse_logged_in_accounts(&text))
})
.unwrap_or_default()
}
pub const GH_CONFIG_DIR_ENV: &str = "GH_CONFIG_DIR";
const GH_TOKEN_ENV_VARS: [&str; 2] = ["GH_TOKEN", "GITHUB_TOKEN"];
const GH_ENFORCE_TIMEOUT: Duration = Duration::from_secs(5);
fn ensure_gh_account_in_dir(
expected_user: &str,
config_dir: &std::path::Path,
) -> anyhow::Result<()> {
let dir = config_dir.to_string_lossy().to_string();
let host = crate::core::trusty_tools_config::DEFAULT_GITHUB_HOST;
let status_text = run_gh_scoped(&dir, ["auth", "status"])
.context("failed to run `gh auth status` scoped to the project's GH_CONFIG_DIR")?;
if verify_active_account(&status_text, expected_user).is_ok() {
return Ok(());
}
let switch = std::process::Command::new("gh")
.args([
"auth",
"switch",
"--hostname",
host,
"--user",
expected_user,
])
.env(GH_CONFIG_DIR_ENV, &dir)
.env_remove(GH_TOKEN_ENV_VARS[0])
.env_remove(GH_TOKEN_ENV_VARS[1])
.output()
.with_context(|| format!("failed to spawn `gh auth switch --user {expected_user}`"))?;
if !switch.status.success() {
let stderr = String::from_utf8_lossy(&switch.stderr);
anyhow::bail!(
"`gh auth switch --user {expected_user}` failed inside {dir}: {} \
(is '{expected_user}' logged in under this GH_CONFIG_DIR? run \
`GH_CONFIG_DIR={dir} gh auth login` first)",
stderr.trim()
);
}
let recheck = run_gh_scoped(&dir, ["auth", "status"])
.context("failed to re-verify `gh auth status` after switching")?;
verify_active_account(&recheck, expected_user).map_err(|msg| {
anyhow::anyhow!(
"gh account switch to '{expected_user}' did not take effect inside {dir}: {msg}"
)
})
}
fn run_gh_scoped(config_dir: &str, args: [&'static str; 2]) -> anyhow::Result<String> {
let config_dir = config_dir.to_string();
run_bounded(GH_ENFORCE_TIMEOUT, move || {
let out = std::process::Command::new("gh")
.args(args)
.env(GH_CONFIG_DIR_ENV, &config_dir)
.env_remove(GH_TOKEN_ENV_VARS[0])
.env_remove(GH_TOKEN_ENV_VARS[1])
.output()
.ok()?;
let mut text = String::from_utf8_lossy(&out.stdout).into_owned();
text.push('\n');
text.push_str(&String::from_utf8_lossy(&out.stderr));
Some(text)
})
.ok_or_else(|| anyhow::anyhow!("`gh` did not respond within {GH_ENFORCE_TIMEOUT:?}"))
}
pub(crate) fn parse_active_account_from_status(auth_status: &str) -> Option<String> {
let mut current: Option<String> = None;
for line in auth_status.lines() {
if let Some((_, rest)) = line.split_once("Logged in to") {
current = extract_login_token(rest);
continue;
}
if let Some((_, value)) = line.split_once("Active account:")
&& value.trim().eq_ignore_ascii_case("true")
{
return current.clone();
}
}
None
}
pub(crate) fn verify_active_account(status_text: &str, expected: &str) -> Result<(), String> {
let lower = status_text.to_lowercase();
if lower.contains("environment variable")
&& (lower.contains("gh_token") || lower.contains("github_token"))
{
return Err(format!(
"gh is authenticating via a GH_TOKEN/GITHUB_TOKEN environment variable override, \
so the active account inside this GH_CONFIG_DIR cannot be verified as '{expected}'"
));
}
match parse_active_account_from_status(status_text) {
Some(active) if active == expected => Ok(()),
Some(active) => Err(format!(
"active account is '{active}', expected '{expected}'"
)),
None => Err(format!(
"could not determine an active gh account (expected '{expected}')"
)),
}
}
pub fn ensure_gh_account_for_project(gh_user: &str) -> anyhow::Result<()> {
let gh_user = gh_user.trim();
anyhow::ensure!(!gh_user.is_empty(), "gh_user must not be empty");
let config_dir = std::env::var_os(GH_CONFIG_DIR_ENV)
.map(PathBuf::from)
.filter(|p| !p.as_os_str().is_empty())
.ok_or_else(|| {
anyhow::anyhow!(
"no isolated {GH_CONFIG_DIR_ENV} is set in this environment; refusing to run \
`gh auth switch` against the shared ~/.config/gh store (that would leak \
identity across concurrently-running projects). Export {GH_CONFIG_DIR_ENV} \
to a per-project gh config directory (see `github.config_dir` in \
TrustyToolsConfig, or the equivalent per-directory shell convention) before \
retrying."
)
})?;
ensure_gh_account_in_dir(gh_user, &config_dir)
}
#[cfg(test)]
mod tests {
use super::*;
const MULTI_HOSTS_YML: &str = "\
github.com:
git_protocol: https
users:
bobmatnyc:
bob-duetto:
user: bob-duetto
";
const SINGLE_HOSTS_YML: &str = "\
github.com:
git_protocol: https
user: bobmatnyc
";
const MULTI_AUTH_STATUS: &str = "\
github.com
✓ Logged in to github.com account bob-duetto (keyring)
- Active account: true
- Git operations protocol: https
- Token: gho_************************************
- Token scopes: 'admin:org', 'gist', 'project', 'repo', 'workflow'
✓ Logged in to github.com account bobmatnyc (keyring)
- Active account: false
- Git operations protocol: https
- Token: gho_************************************
- Token scopes: 'gist', 'read:org', 'repo', 'workflow'
";
const SINGLE_AUTH_STATUS: &str = "\
github.com
✓ Logged in to github.com account bobmatnyc (keyring)
- Active account: true
- Git operations protocol: https
- Token: gho_************************************
";
#[test]
fn parse_active_account_present() {
assert_eq!(
parse_active_account_from_hosts_yml(MULTI_HOSTS_YML).as_deref(),
Some("bob-duetto")
);
assert_eq!(
parse_active_account_from_hosts_yml(SINGLE_HOSTS_YML).as_deref(),
Some("bobmatnyc")
);
}
#[test]
fn parse_active_account_absent() {
assert_eq!(parse_active_account_from_hosts_yml(""), None);
assert_eq!(
parse_active_account_from_hosts_yml("other.host:\n user: x"),
None
);
assert_eq!(
parse_active_account_from_hosts_yml("github.com:\n git_protocol: https"),
None
);
assert_eq!(parse_active_account_from_hosts_yml(": : ["), None);
}
#[test]
fn parse_gh_account_status_single() {
let status = parse_gh_account_status_from_hosts_yml(SINGLE_HOSTS_YML).expect("some");
assert_eq!(status.active.as_deref(), Some("bobmatnyc"));
assert_eq!(status.logged_in, vec!["bobmatnyc".to_string()]);
assert!(!status.is_ambiguous());
}
#[test]
fn parse_gh_account_status_multi_from_users_map() {
let status = parse_gh_account_status_from_hosts_yml(MULTI_HOSTS_YML).expect("some");
assert_eq!(status.active.as_deref(), Some("bob-duetto"));
assert!(status.logged_in.contains(&"bobmatnyc".to_string()));
assert!(status.logged_in.contains(&"bob-duetto".to_string()));
assert_eq!(status.logged_in.len(), 2);
assert!(status.is_ambiguous());
}
#[test]
fn parse_gh_account_status_empty() {
assert_eq!(parse_gh_account_status_from_hosts_yml(""), None);
assert_eq!(
parse_gh_account_status_from_hosts_yml("enterprise.example.com:\n user: x"),
None
);
}
#[test]
fn parse_logged_in_single() {
assert_eq!(
parse_logged_in_accounts(SINGLE_AUTH_STATUS),
vec!["bobmatnyc".to_string()]
);
}
#[test]
fn parse_logged_in_multiple() {
assert_eq!(
parse_logged_in_accounts(MULTI_AUTH_STATUS),
vec!["bob-duetto".to_string(), "bobmatnyc".to_string()]
);
}
#[test]
fn parse_logged_in_older_as_phrasing() {
let text = "✓ Logged in to github.com as octocat (oauth_token)";
assert_eq!(parse_logged_in_accounts(text), vec!["octocat".to_string()]);
}
#[test]
fn parse_logged_in_empty() {
assert!(parse_logged_in_accounts("").is_empty());
assert!(parse_logged_in_accounts("You are not logged into any GitHub hosts.").is_empty());
}
#[test]
fn is_ambiguous_boundary() {
let none = GhAccountStatus::default();
assert!(!none.is_ambiguous());
let one = GhAccountStatus {
active: Some("a".into()),
logged_in: vec!["a".into()],
};
assert!(!one.is_ambiguous());
let two = GhAccountStatus {
active: Some("a".into()),
logged_in: vec!["a".into(), "b".into()],
};
assert!(two.is_ambiguous());
}
#[test]
fn parse_active_account_from_status_multi() {
assert_eq!(
parse_active_account_from_status(MULTI_AUTH_STATUS).as_deref(),
Some("bob-duetto")
);
}
#[test]
fn parse_active_account_from_status_single() {
assert_eq!(
parse_active_account_from_status(SINGLE_AUTH_STATUS).as_deref(),
Some("bobmatnyc")
);
}
#[test]
fn parse_active_account_from_status_none_active() {
assert_eq!(parse_active_account_from_status(""), None);
assert_eq!(
parse_active_account_from_status(
"github.com\n ✓ Logged in to github.com account x\n - Active account: false\n"
),
None
);
}
#[test]
fn verify_active_account_matches() {
assert!(verify_active_account(SINGLE_AUTH_STATUS, "bobmatnyc").is_ok());
}
#[test]
fn verify_active_account_mismatch() {
let err = verify_active_account(MULTI_AUTH_STATUS, "bobmatnyc").unwrap_err();
assert!(err.contains("bob-duetto"), "err: {err}");
assert!(err.contains("bobmatnyc"), "err: {err}");
}
#[test]
fn verify_active_account_rejects_env_token_override() {
let text = "The value of the GH_TOKEN environment variable is being used for authentication.\ngithub.com\n ✓ Logged in to github.com account bobmatnyc\n - Active account: true\n";
let err = verify_active_account(text, "bobmatnyc").unwrap_err();
assert!(err.contains("environment variable"), "err: {err}");
}
#[test]
fn ensure_gh_account_for_project_refuses_without_config_dir() {
let _g = crate::core::trusty_tools_config::env_test_lock();
let prior = std::env::var_os(GH_CONFIG_DIR_ENV);
unsafe { std::env::remove_var(GH_CONFIG_DIR_ENV) };
let err = ensure_gh_account_for_project("bobmatnyc").unwrap_err();
unsafe {
match prior {
Some(v) => std::env::set_var(GH_CONFIG_DIR_ENV, v),
None => std::env::remove_var(GH_CONFIG_DIR_ENV),
}
}
let msg = err.to_string();
assert!(msg.contains(GH_CONFIG_DIR_ENV), "msg: {msg}");
assert!(
msg.contains("shared"),
"expected the shared-store refusal rationale: {msg}"
);
}
#[test]
fn ensure_gh_account_for_project_rejects_empty_login() {
let err = ensure_gh_account_for_project(" ").unwrap_err();
assert!(err.to_string().contains("must not be empty"));
}
}