diff --git a/crates/grove-core/src/git.rs b/crates/grove-core/src/git.rs index dfbf984..a505009 100644 --- a/crates/grove-core/src/git.rs +++ b/crates/grove-core/src/git.rs @@ -4,7 +4,74 @@ use std::ffi::OsStr; use std::fmt; use std::io; use std::path::{Path, PathBuf}; -use std::process::Command; +use std::process::{Command, Output, Stdio}; +use std::sync::atomic::{AtomicU64, Ordering}; +use std::time::{Duration, Instant}; + +/// Wall-clock limit for one git invocation in seconds; 0 (the default) means none. +static TIMEOUT_SECS: AtomicU64 = AtomicU64::new(0); + +/// Sets a wall-clock limit for every git invocation of this process (0 disables it). Meant for +/// the daemon, whose single sync loop must never block forever on a stuck fetch, hook or helper. +pub fn set_timeout(secs: u64) { + TIMEOUT_SECS.store(secs, Ordering::Relaxed); +} + +/// Runs `cmd`, killing it (and its process group: ssh, helpers) when it outlives the limit. +fn output(cmd: Command, args: &[String]) -> Result { + output_within(cmd, args, TIMEOUT_SECS.load(Ordering::Relaxed)) +} + +fn output_within(mut cmd: Command, args: &[String], secs: u64) -> Result { + if secs == 0 { + return Ok(cmd.output()?); + } + use std::io::Read; + use std::os::unix::process::CommandExt; + cmd.stdin(Stdio::null()) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()) + .process_group(0); + let mut child = cmd.spawn()?; + let reader = |mut r: Box| { + let (tx, rx) = std::sync::mpsc::channel(); + std::thread::spawn(move || { + let mut buf = Vec::new(); + let _ = r.read_to_end(&mut buf); + let _ = tx.send(buf); + }); + rx + }; + let out_rx = reader(Box::new(child.stdout.take().expect("piped"))); + let err_rx = reader(Box::new(child.stderr.take().expect("piped"))); + let deadline = Instant::now() + Duration::from_secs(secs); + let mut nap = Duration::from_millis(1); + let status = loop { + if let Some(st) = child.try_wait()? { + break st; + } + if Instant::now() >= deadline { + let _ = Command::new("kill") + .args(["-KILL", "--", &format!("-{}", child.id())]) + .status(); + let _ = child.kill(); + let _ = child.wait(); + return Err(GitError::Other(format!( + "git {} timed out after {secs} s and was killed", + args.join(" ") + ))); + } + std::thread::sleep(nap); + nap = (nap * 2).min(Duration::from_millis(100)); + }; + // A lingering ssh master (ControlPersist) may keep the pipes open after git exits. + let grace = Duration::from_secs(2); + Ok(Output { + status, + stdout: out_rx.recv_timeout(grace).unwrap_or_default(), + stderr: err_rx.recv_timeout(grace).unwrap_or_default(), + }) +} #[derive(Debug)] pub enum GitError { @@ -37,6 +104,10 @@ impl From for GitError { } } +fn owned(args: &[&str]) -> Vec { + args.iter().map(|s| s.to_string()).collect() +} + /// A git invocation context: a working directory plus extra environment. #[derive(Debug, Clone)] pub struct Git { @@ -73,7 +144,7 @@ impl Git { /// Run git, returning trimmed stdout. Any non-zero exit is an error. pub fn run(&self, args: &[&str]) -> Result { - let out = self.command(args).output()?; + let out = output(self.command(args), &owned(args))?; if out.status.success() { Ok(String::from_utf8_lossy(&out.stdout).trim().to_string()) } else { @@ -87,7 +158,7 @@ impl Git { /// Run git; a non-zero exit yields `None` (for probes like `rev-parse --verify`). pub fn probe(&self, args: &[&str]) -> Result, GitError> { - let out = self.command(args).output()?; + let out = output(self.command(args), &owned(args))?; if out.status.success() { Ok(Some( String::from_utf8_lossy(&out.stdout).trim().to_string(), @@ -97,3 +168,58 @@ impl Git { } } } + +/// Environment that keeps unattended git from ever waiting on a person: no terminal or askpass +/// prompts (a desktop `SSH_ASKPASS` such as ksshaskpass would otherwise open a dialog and block +/// forever), and stalled HTTP transfers abort. The ssh command is left alone so a user's (or a +/// repo's) `core.sshCommand` keeps working; wall-clock limits come from [`set_timeout`]. +pub fn noninteractive_env() -> Vec<(String, String)> { + [ + ("GIT_TERMINAL_PROMPT", "0"), + ("GIT_ASKPASS", "true"), + ("SSH_ASKPASS_REQUIRE", "never"), + ("GIT_HTTP_LOW_SPEED_LIMIT", "1000"), + ("GIT_HTTP_LOW_SPEED_TIME", "60"), + ] + .into_iter() + .map(|(k, v)| (k.to_string(), v.to_string())) + .collect() +} + +/// Whether the user configured their own ssh command for git (env or `core.sshCommand`). +pub fn has_custom_ssh() -> bool { + std::env::var_os("GIT_SSH_COMMAND").is_some() + || std::env::var_os("GIT_SSH").is_some() + || std::process::Command::new("git") + .args(["config", "--get", "core.sshCommand"]) + .output() + .is_ok_and(|o| o.status.success() && !o.stdout.is_empty()) +} + +#[cfg(test)] +mod env_tests { + use super::*; + + #[test] + fn unattended_git_never_prompts_and_leaves_the_ssh_command_alone() { + let env = noninteractive_env(); + let get = |k: &str| env.iter().find(|(n, _)| n == k).map(|(_, v)| v.as_str()); + assert_eq!(get("GIT_TERMINAL_PROMPT"), Some("0")); + assert_eq!(get("SSH_ASKPASS_REQUIRE"), Some("never")); + assert_eq!(get("GIT_SSH_COMMAND"), None); + } + + #[test] + fn a_git_call_over_the_limit_is_killed() { + // A hook-like stall: `git -c alias.x='!sleep 30' x`. The global limit is not touched, so + // tests running in parallel are unaffected. + let args = owned(&["-c", "alias.zzsleep=!sleep 30", "zzsleep"]); + let t = Instant::now(); + let r = output_within(Git::new(".").command(&args), &args, 1); + assert!(r.unwrap_err().to_string().contains("timed out")); + assert!(t.elapsed() < Duration::from_secs(10)); + let v = owned(&["--version"]); + let out = output_within(Git::new(".").command(&v), &v, 5).unwrap(); + assert!(String::from_utf8_lossy(&out.stdout).starts_with("git version")); + } +} diff --git a/crates/grove-daemon/src/main.rs b/crates/grove-daemon/src/main.rs index ec08e23..8b052f6 100644 --- a/crates/grove-daemon/src/main.rs +++ b/crates/grove-daemon/src/main.rs @@ -5,6 +5,9 @@ use grove_core::config::Config; use grove_daemon::{Daemon, Settings}; use std::path::PathBuf; +/// Upper bound for one git call of the daemon (a large first fetch included). +const GIT_TIMEOUT_SECS: u64 = 900; + fn main() -> Result<()> { let mut args = std::env::args().skip(1); let mut config: Option = None; @@ -23,6 +26,13 @@ fn main() -> Result<()> { .context("cannot determine config path")?; let cfg = Config::load(&path)?; grove_core::snapshot::set_max_file_bytes(cfg.sync.max_file_mb * 1024 * 1024); + // Unattended: git/ssh must never prompt (the session's SSH_ASKPASS would open a dialog and + // block every sync), and no git call may block the sync loop forever. + for (k, v) in grove_core::git::noninteractive_env() { + // SAFETY: still single-threaded; no other thread reads the environment yet. + unsafe { std::env::set_var(k, v) }; + } + grove_core::git::set_timeout(GIT_TIMEOUT_SECS); let st = Settings::standard(); eprintln!( "groved: machine {:?}, root {}, socket {}", diff --git a/crates/grove-providers/src/token.rs b/crates/grove-providers/src/token.rs index 65b1072..d1726c9 100644 --- a/crates/grove-providers/src/token.rs +++ b/crates/grove-providers/src/token.rs @@ -31,10 +31,19 @@ pub fn get(provider_id: &str) -> Result { return Ok(t.trim().to_string()); } let e = keyring::Entry::new(SERVICE, provider_id).map_err(|e| Error::Other(e.to_string()))?; - match e.get_password() { - Ok(t) => Ok(t), - Err(keyring::Error::NoEntry) => Err(Error::NoToken(provider_id.into())), - Err(e) => Err(Error::Other(format!("secret service: {e}"))), + // A locked keyring may wait on an unlock dialog: never block the caller for longer than the + // forge CLIs get (the thread is left behind if the Secret Service never answers). + let (tx, rx) = std::sync::mpsc::channel(); + std::thread::spawn(move || { + let _ = tx.send(e.get_password()); + }); + match rx.recv_timeout(CLI_TIMEOUT) { + Ok(Ok(t)) => Ok(t), + Ok(Err(keyring::Error::NoEntry)) => Err(Error::NoToken(provider_id.into())), + Ok(Err(e)) => Err(Error::Other(format!("secret service: {e}"))), + Err(_) => Err(Error::Other( + "secret service did not answer in time (locked keyring?)".into(), + )), } } diff --git a/crates/grove/src/workflow.rs b/crates/grove/src/workflow.rs index 6836a4b..c9b47f9 100644 --- a/crates/grove/src/workflow.rs +++ b/crates/grove/src/workflow.rs @@ -95,14 +95,8 @@ pub fn connect(cfg: &Config, id: &str) -> Result { /// Git environment for SSH remotes: the user's keys/agent authenticate and nothing prompts. /// `BatchMode` is only forced when the user has no ssh command of their own. fn ssh_env() -> Vec<(String, String)> { - let mut env = vec![("GIT_TERMINAL_PROMPT".to_string(), "0".to_string())]; - let custom = std::env::var_os("GIT_SSH_COMMAND").is_some() - || std::env::var_os("GIT_SSH").is_some() - || std::process::Command::new("git") - .args(["config", "--get", "core.sshCommand"]) - .output() - .is_ok_and(|o| o.status.success() && !o.stdout.is_empty()); - if !custom { + let mut env = grove_core::git::noninteractive_env(); + if !grove_core::git::has_custom_ssh() { env.push(("GIT_SSH_COMMAND".into(), "ssh -o BatchMode=yes".into())); } env