diff --git a/src/commands/add.rs b/src/commands/add.rs index 31876c6..8de50bc 100644 --- a/src/commands/add.rs +++ b/src/commands/add.rs @@ -82,6 +82,7 @@ fn add_github(config: &mut Config) { email, alias: alias.clone(), host: None, + ssh_key: None, }; set_token(&username, alias.as_deref(), &token); @@ -94,6 +95,8 @@ fn add_github(config: &mut Config) { exit_raw_mode(); } +use crate::utils::scan_ssh_keys; + fn add_manual(config: &mut Config) { let Some(username) = raw_input("Username", "").filter(|u| !u.is_empty()) else { return; @@ -124,20 +127,49 @@ fn add_manual(config: &mut Config) { } } - let token = raw_password("Token/PAT (optional)").unwrap_or_default(); - let host_in = raw_input("Host", "github.com").unwrap_or_else(|| "github.com".to_string()); + let auth_types = vec!["Token/PAT".to_string(), "SSH Key".to_string()]; + let Some(auth_choice) = raw_select("Authentication Type", &auth_types, 0) else { + return; + }; - let host = if host_in == "github.com" || host_in.is_empty() { - None + let mut token = String::new(); + let mut host = None; + let mut ssh_key = None; + + if auth_choice == 0 { + // Token/PAT + token = raw_password("Token/PAT (optional)").unwrap_or_default(); + let host_in = raw_input("Host", "github.com").unwrap_or_else(|| "github.com".to_string()); + host = if host_in == "github.com" || host_in.is_empty() { + None + } else { + Some(host_in) + }; } else { - Some(host_in) - }; + // SSH Key + let (display_items, paths, default_idx) = scan_ssh_keys(&username, &email); + let Some(selection) = raw_select("Keys in ~/.ssh", &display_items, default_idx) else { + return; + }; + + if selection < paths.len() { + ssh_key = Some(paths[selection].to_string_lossy().to_string()); + } else if selection == paths.len() { + let manual = raw_input("SSH Key Path", "").unwrap_or_default(); + ssh_key = if manual.is_empty() { + None + } else { + Some(manual) + }; + } + } let account = Account { username: username.clone(), email, alias: alias.clone(), host, + ssh_key, }; if !token.is_empty() { diff --git a/src/commands/git.rs b/src/commands/git.rs index a1b1aaa..5a38758 100644 --- a/src/commands/git.rs +++ b/src/commands/git.rs @@ -20,6 +20,13 @@ pub fn run(config: &Config, account_id: Option, args: Vec) { cmd.arg("-c").arg(format!("user.name={}", account.username)); cmd.arg("-c").arg(format!("user.email={}", account.email)); + if let Some(ssh_key) = &account.ssh_key { + cmd.arg("-c").arg(format!( + "core.sshCommand={}", + crate::utils::git_ssh_command(ssh_key) + )); + } + // Inject inline credential helper if token is available match crate::models::get_token(&account.username, account.alias.as_deref()) { Some(token) if !token.is_empty() => { @@ -30,11 +37,13 @@ pub fn run(config: &Config, account_id: Option, args: Vec) { )); } _ => { - println!( - " {} No token found for {}. Git may prompt for authentication.", - "⚠".yellow(), - account.username.cyan() - ); + if account.ssh_key.is_none() || crate::utils::git_args_use_http_transport(&args) { + println!( + " {} No token found for {}. Git may prompt for authentication.", + "⚠".yellow(), + account.username.cyan() + ); + } } } diff --git a/src/commands/list.rs b/src/commands/list.rs index 039dc49..ddc493f 100644 --- a/src/commands/list.rs +++ b/src/commands/list.rs @@ -424,33 +424,37 @@ impl<'a> ListState<'a> { } fn apply_switch(&self, account: &crate::models::Account, scope: &str) -> bool { - git_config_set("user.name", &account.username, scope); - git_config_set("user.email", &account.email, scope); - - if let Some(alias) = &account.alias { - git_config_set("gitas.alias", alias, scope); - } else { - git_config_unset("gitas.alias", scope); - } - - // Enforce the correct username for the credential helper (fixes "sticky" tokens) - let host = account.host.as_deref().unwrap_or("github.com"); - let cred_key = format!("credential.https://{}.username", host); - git_config_set(&cred_key, &account.username, scope); - let mut status_lines = Vec::new(); let mut has_status_issue = false; + let host = account.host.as_deref().unwrap_or("github.com"); + let mut target_url = None; + + // Check authentication BEFORE making any git config changes if let Some(token) = crate::models::get_token(&account.username, account.alias.as_deref()) .filter(|t| !t.is_empty()) { - let host = account.host.as_deref().unwrap_or("github.com"); - let url = (scope == "local") - .then(|| git_config_get("remote.origin.url", "local")) - .flatten(); - - if scope == "local" && url.is_some() { - git_config_set("credential.useHttpPath", "true", "local"); + if scope == "local" { + let remotes = crate::utils::get_http_remotes(); + if remotes.is_empty() { + status_lines.push(format!( + " {} No HTTP remotes found. Token authentication may fail.", + "⚠".yellow() + )); + has_status_issue = true; + } else if remotes.len() == 1 { + target_url = Some(remotes[0].url.clone()); + } else { + let items: Vec = remotes + .iter() + .map(|r| format!("{} ({})", r.name, r.url)) + .collect(); + if let Some(selection) = raw_select("Select remote for token auth", &items, 0) { + target_url = Some(remotes[selection].url.clone()); + } else { + return false; + } + } } if let Some(warning) = crate::utils::check_credential_helper() { @@ -460,8 +464,25 @@ impl<'a> ListState<'a> { // Clear any potentially conflicting credentials git_credential_reject(host); - git_credential_approve(&account.username, &token, host, url.as_deref()); - } else { + if let Err(e) = + git_credential_approve(&account.username, &token, host, target_url.as_deref()) + { + status_lines.push(format!(" {} {}", "⚠".yellow(), e)); + status_lines.push(String::new()); + status_lines.push(format!( + "{} Aborted switch due to authentication failure", + "✗".red() + )); + raw_show_status(&status_lines, true); + return false; + } + + if scope == "local" && target_url.is_some() { + git_config_set("credential.useHttpPath", "true", "local"); + } + } else if account.ssh_key.is_none() + || (scope == "local" && crate::utils::has_http_remotes()) + { has_status_issue = true; status_lines.push(format!( " {} No token found for {}. Git may prompt for authentication.", @@ -470,6 +491,29 @@ impl<'a> ListState<'a> { )); } + // Apply all configuration changes now that auth has succeeded + git_config_set("user.name", &account.username, scope); + git_config_set("user.email", &account.email, scope); + + if let Some(alias) = &account.alias { + git_config_set("gitas.alias", alias, scope); + } else { + git_config_unset("gitas.alias", scope); + } + + if let Some(ssh_key) = &account.ssh_key { + git_config_set( + "core.sshCommand", + &crate::utils::git_ssh_command(ssh_key), + scope, + ); + } else if self.current_ssh_command_is_gitas_managed(scope) { + git_config_unset("core.sshCommand", scope); + } + + let cred_key = format!("credential.https://{}.username", host); + git_config_set(&cred_key, &account.username, scope); + status_lines.push(String::new()); status_lines.push(format!( "{} Switched to '{}' ({})", @@ -482,6 +526,19 @@ impl<'a> ListState<'a> { true } + fn current_ssh_command_is_gitas_managed(&self, scope: &str) -> bool { + let Some(current) = git_config_get("core.sshCommand", scope) else { + return false; + }; + + self.config + .accounts + .iter() + .filter_map(|account| account.ssh_key.as_deref()) + .map(crate::utils::git_ssh_command) + .any(|command| command == current) + } + fn handle_delete(&mut self) -> bool { if self.config.accounts.is_empty() { return false; @@ -549,6 +606,11 @@ impl<'a> ListState<'a> { "none" } ), + format!( + "{:<15} {}", + "SSH Key:".dimmed(), + temp_account.ssh_key.as_deref().unwrap_or("none") + ), "Save Changes".green().to_string(), "Cancel".dimmed().to_string(), ]; @@ -598,6 +660,29 @@ impl<'a> ListState<'a> { } } 5 => { + let (display_items, paths, default_idx) = + crate::utils::scan_ssh_keys(&temp_account.username, &temp_account.email); + if let Some(selection) = + raw_select("Keys in ~/.ssh", &display_items, default_idx) + { + if selection < paths.len() { + temp_account.ssh_key = + Some(paths[selection].to_string_lossy().to_string()); + } else if selection == paths.len() { + let manual = raw_input( + "New SSH Key Path", + temp_account.ssh_key.as_deref().unwrap_or(""), + ) + .unwrap_or_default(); + temp_account.ssh_key = if manual.is_empty() { + None + } else { + Some(manual) + }; + } + } + } + 6 => { if original_username != temp_account.username || original_alias != temp_account.alias { @@ -620,7 +705,7 @@ impl<'a> ListState<'a> { save_config(self.config); return true; } - 6 => return false, + 7 => return false, _ => {} } } diff --git a/src/models.rs b/src/models.rs index 4b3566a..25aec63 100644 --- a/src/models.rs +++ b/src/models.rs @@ -14,6 +14,8 @@ pub struct Account { pub alias: Option, #[serde(skip_serializing_if = "Option::is_none")] pub host: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub ssh_key: Option, } #[derive(Debug, Default, Serialize, Deserialize)] diff --git a/src/utils.rs b/src/utils.rs index 6eff4eb..971e9c3 100644 --- a/src/utils.rs +++ b/src/utils.rs @@ -69,6 +69,112 @@ pub fn git_toplevel() -> Option { } } +pub struct Remote { + pub name: String, + pub url: String, +} + +pub fn is_http_url(url: &str) -> bool { + url.starts_with("http://") || url.starts_with("https://") +} + +pub fn get_http_remotes() -> Vec { + let Ok(output) = Command::new("git") + .args(["config", "--get-regexp", r"remote\..*\.url"]) + .output() + else { + return Vec::new(); + }; + + if !output.status.success() { + return Vec::new(); + } + + String::from_utf8_lossy(&output.stdout) + .lines() + .filter_map(|line| { + let mut parts = line.split_whitespace(); + let key = parts.next()?; + let url = parts.next()?; + + if key.starts_with("remote.") && key.ends_with(".url") && is_http_url(url) { + let name = key + .trim_start_matches("remote.") + .trim_end_matches(".url") + .to_string(); + Some(Remote { + name, + url: url.to_string(), + }) + } else { + None + } + }) + .collect() +} + +pub fn has_http_remotes() -> bool { + !get_http_remotes().is_empty() +} + +pub fn git_args_use_http_transport(args: &[String]) -> bool { + args.iter().any(|arg| is_http_url(arg)) + || (git_args_may_use_configured_remote(args) && has_http_remotes()) +} + +pub fn git_ssh_command(ssh_key: &str) -> String { + let normalized_path = ssh_key.replace('\\', "/"); + format!("ssh -i \"{}\" -o IdentitiesOnly=yes", normalized_path) +} + +fn git_args_may_use_configured_remote(args: &[String]) -> bool { + let Some(command) = git_subcommand(args) else { + return false; + }; + + matches!( + command, + "archive" | "fetch" | "ls-remote" | "pull" | "push" | "remote" | "submodule" + ) +} + +fn git_subcommand(args: &[String]) -> Option<&str> { + let mut iter = args.iter().map(String::as_str); + + while let Some(arg) = iter.next() { + if matches!( + arg, + "-C" | "-c" | "--exec-path" | "--git-dir" | "--work-tree" + ) { + iter.next(); + continue; + } + + if matches!( + arg, + "--bare" | "--no-pager" | "--paginate" | "--literal-pathspecs" + ) { + continue; + } + + if arg.starts_with("--exec-path=") + || arg.starts_with("--git-dir=") + || arg.starts_with("--work-tree=") + || arg.starts_with("-c") + { + continue; + } + + if arg.starts_with('-') { + continue; + } + + return Some(arg); + } + + None +} + pub fn check_credential_helper() -> Option { match git_config_get("credential.helper", "effective") { Some(helper) if helper.contains("cache") => Some(format!( @@ -84,7 +190,12 @@ pub fn check_credential_helper() -> Option { } } -pub fn git_credential_approve(username: &str, token: &str, host: &str, url: Option<&str>) { +pub fn git_credential_approve( + username: &str, + token: &str, + host: &str, + url: Option<&str>, +) -> Result<(), String> { use std::io::Write; let input = if let Some(u) = url { format!("url={u}\nusername={username}\npassword={token}\n\n") @@ -94,16 +205,20 @@ pub fn git_credential_approve(username: &str, token: &str, host: &str, url: Opti let mut child = Command::new("git") .args(["credential", "approve"]) .stdin(std::process::Stdio::piped()) + .stderr(std::process::Stdio::piped()) .spawn() .expect("Failed to execute git credential approve"); if let Some(mut stdin) = child.stdin.take() { stdin.write_all(input.as_bytes()).ok(); } - let status = child - .wait() + let output = child + .wait_with_output() .expect("Failed to wait for git credential approve"); - if !status.success() { - eprintln!("{} Failed to approve git credential", "error:".red().bold()); + if !output.status.success() { + let err = String::from_utf8_lossy(&output.stderr); + Err(format!("Failed to approve git credential: {}", err.trim())) + } else { + Ok(()) } } @@ -173,3 +288,129 @@ pub fn resolve_account(config: &Config, identifier: Option, prompt: &str } } } + +pub fn scan_ssh_keys( + target_username: &str, + target_email: &str, +) -> (Vec, Vec, usize) { + let mut display_items = Vec::new(); + let mut paths = Vec::new(); + let mut default_idx = 0; + + let Some(entries) = dirs::home_dir() + .map(|h| h.join(".ssh")) + .and_then(|d| std::fs::read_dir(d).ok()) + else { + display_items.push("Enter ssh key path manually".to_string()); + return (display_items, paths, 0); + }; + + for entry in entries.flatten() { + let path = entry.path(); + if !path.is_file() { + continue; + } + + let filename = path + .file_name() + .unwrap_or_default() + .to_string_lossy() + .to_string(); + if filename.ends_with(".pub") + || filename.ends_with(".old") + || filename.ends_with(".bak") + || filename == "config" + || filename == "known_hosts" + || filename == "authorized_keys" + { + continue; + } + + let is_private_key = std::fs::File::open(&path) + .and_then(|mut f| { + let mut buffer = [0; 128]; + use std::io::Read; + let n = f.read(&mut buffer)?; + Ok(String::from_utf8_lossy(&buffer[..n]).starts_with("-----BEGIN")) + }) + .unwrap_or(false); + + if !is_private_key { + continue; + } + + let pub_path = path.with_extension("pub"); + let comment = std::fs::read_to_string(&pub_path).ok().and_then(|content| { + let parts: Vec<&str> = content.split_whitespace().collect(); + if parts.len() >= 3 { + Some(parts[2..].join(" ")) + } else { + None + } + }); + + let display_name = match &comment { + Some(c) => format!("{} ({})", filename, c), + None => filename.clone(), + }; + + let matches = comment.as_ref().is_some_and(|c| { + let c_lower = c.to_lowercase(); + let u_lower = target_username.to_lowercase(); + let e_lower = target_email.to_lowercase(); + + c_lower == e_lower + || c_lower == u_lower + || c_lower + .find('@') + .is_some_and(|idx| c_lower[..idx] == u_lower) + }); + + if matches { + default_idx = paths.len(); + } + + display_items.push(display_name); + paths.push(path); + } + + display_items.push("Enter ssh key path manually".to_string()); + if default_idx >= display_items.len() { + default_idx = display_items.len() - 1; + } + (display_items, paths, default_idx) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn detects_http_urls() { + assert!(is_http_url("https://github.com/owner/repo.git")); + assert!(is_http_url("http://github.com/owner/repo.git")); + assert!(!is_http_url("git@github.com:owner/repo.git")); + assert!(!is_http_url("ssh://git@github.com/owner/repo.git")); + } + + #[test] + fn finds_subcommand_after_global_options() { + let args = vec![ + "-C".to_string(), + "repo".to_string(), + "-c".to_string(), + "core.askpass=true".to_string(), + "fetch".to_string(), + ]; + + assert_eq!(git_subcommand(&args), Some("fetch")); + } + + #[test] + fn formats_gitas_ssh_command() { + assert_eq!( + git_ssh_command(r"C:\Users\me\.ssh\id_ed25519"), + r#"ssh -i "C:/Users/me/.ssh/id_ed25519" -o IdentitiesOnly=yes"# + ); + } +}