All your machines, one app. For you and your AI agents: agent sessions, desktops, files, logs and GitHub across your Macs, Linux and Windows machines, with an MCP server.
Set up access: name the account, and say when a Mac doesn't accept it (#30)
Adib Hanna8063c9de5205
diff --git a/src/demo.rs b/src/demo.rsindex 1d83474..fa848be 100644--- a/src/demo.rs+++ b/src/demo.rs@@ -391,6 +391,7 @@ impl World {published: demo_containers(hw.id),route: None,kvm: hw.id == "beacon",+ refused_user: None,}}diff --git a/src/fleet/build.rs b/src/fleet/build.rsindex 85763fd..b212b2d 100644--- a/src/fleet/build.rs+++ b/src/fleet/build.rs@@ -567,6 +567,7 @@ pub fn explain_unreachable(spec: &MachineSpec, p: &ProbeResult, retrying: bool,let kind = if spec.is_local() { "error" } else { unreachable_kind(&error) };let here = if cfg!(target_os = "macos") { "this Mac" } else { "this computer" };let again = if retrying { "Reconnects when it's back." } else { "Check again when it's back." };+ let os = p.os.as_deref().or(spec.platform.as_deref()).or(device.map(|d| d.os.as_str())).unwrap_or("").to_ascii_lowercase();let (title, detail, hint) = match kind {"offline" => (format!("{name} is offline"), format!("Shut down, asleep, or off the network. {again}"), None),// ssh got to the machine it goes through (ProxyJump), and nothing@@ -575,7 +576,6 @@ pub fn explain_unreachable(spec: &MachineSpec, p: &ProbeResult, retrying: bool,(format!("{name} isn't answering"), format!("The machine it's reached through is up, but nothing answers behind it: {name} is off, or its ssh server isn't running."), None)}"refused" => {- let os = p.os.as_deref().or(spec.platform.as_deref()).unwrap_or("").to_ascii_lowercase();let ssh = if os.starts_with("darwin") || os.starts_with("macos") {"Remote Login (ssh) is off"} else if os.starts_with("windows") {@@ -587,21 +587,31 @@ pub fn explain_unreachable(spec: &MachineSpec, p: &ProbeResult, retrying: bool,};(format!("{name} isn't accepting connections"), format!("Starting up, or {ssh}."), None)}+ // The account ssh guessed isn't one the machine lets in: a key can't+ // fix that, the right account name can.+ "auth" if p.refused_user.is_some() => {+ let user = p.refused_user.as_deref().unwrap_or_default();+ let again = format!("Add this machine again as name@{host}, with your account's name there.");+ let sharing = "System Settings › General › Sharing › Remote Login › ⓘ";+ let detail = if os.starts_with("darwin") || os.starts_with("macos") {+ format!("There's no account {user} there, or Remote Login doesn't allow it. {again} If {user} is there, allow it in {sharing}.")+ } else if os.is_empty() {+ format!("There's no account {user} there, or ssh doesn't allow it. {again} On a Mac, allowed users are in {sharing}.")+ } else {+ format!("There's no account {user} there, or its ssh server doesn't allow it. {again}")+ };+ (format!("{name} doesn't accept {user}"), detail, None)+ }"auth" => {- // "[email protected]: Permission denied (...)": who ssh signed in as.- let user = error- .lines()- .find_map(|l| l.split_once(": Permission denied"))- .and_then(|(who, _)| who.rsplit_once('@'))- .map(|(u, _)| u.trim().to_string())- .filter(|u| !u.is_empty() && !u.contains(' '));+ let user = crate::probe::ssh_user(spec, Some(p));+ let key = crate::probe::default_ssh_key().unwrap_or_else(|| "~/.ssh/id_ed25519.pub".into());(format!("{name} doesn't know {here} yet"),- match user {+ match &user {Some(u) => format!("Set up access once with your password for {u} there."),None => "Set up access once with your password there.".to_string(),},- Some(format!("ssh-copy-id -i {} {host}", crate::probe::default_ssh_key().unwrap_or_else(|| "~/.ssh/id_ed25519.pub".into()))),+ Some(crate::probe::copy_id_command(spec, user.as_deref(), Some(&key))),)}"unknown-host" => (format!("Can't find {name}"), format!("Check \"{host}\", or join its network or VPN."), None),@@ -1420,14 +1430,70 @@ mod tests {let u = explain_unreachable(&inv.machines[0], &p, true, None, None);assert_eq!(u.kind, "auth");assert!(u.detail.contains("password for adib"), "{}", u.detail);- assert!(u.hint.unwrap().starts_with("ssh-copy-id -i "));+ // The account goes in the command, so ssh-copy-id doesn't guess another.+ let hint = u.hint.unwrap();+ assert!(hint.starts_with("ssh-copy-id -i "), "{hint}");+ assert!(hint.ends_with(" [email protected]"), "{hint}");+ }++ #[test]+ fn copy_id_hint_signs_in_as_sshs_account() {+ use crate::probe::SshRoute;+ let denied = |error: &str, user: Option<&str>| ProbeResult {+ ok: false,+ error: Some(error.into()),+ route: Some(SshRoute { hostname: "box.local".into(), port: 22, user: user.map(Into::into), ..Default::default() }),+ ..Default::default()+ };+ // ssh's config (or this computer's login name) says who, even when the error doesn't.+ let inv = inventory("[[machine]]\nname = \"Box\"\nhost = \"box.local\"\nport = 2222\n");+ let u = explain_unreachable(&inv.machines[0], &denied("Permission denied (publickey).", Some("adib")), true, None, None);+ assert!(u.detail.contains("password for adib"), "{}", u.detail);+ let hint = u.hint.unwrap();+ assert!(hint.ends_with(" -p 2222 [email protected]"), "{hint}");++ // A host that names its account keeps it.+ let inv = inventory("[[machine]]\nname = \"Box\"\nhost = \"[email protected]\"\n");+ let u = explain_unreachable(&inv.machines[0], &denied("[email protected]: Permission denied (publickey).", Some("ahanna")), true, None, None);+ assert!(u.hint.unwrap().ends_with(" [email protected]"));+ assert!(u.detail.contains("password for ahanna"), "{}", u.detail);+ }++ #[test]+ fn says_when_the_account_is_the_problem() {+ let inv = inventory("[[machine]]\nname = \"Mac-Webtech-025\"\nhost = \"Mac-Webtech-025.local\"\n");+ let spec = &inv.machines[0];+ let refused = |os: Option<&str>| ProbeResult {+ ok: false,+ error: Some("[email protected]: Permission denied (publickey,password,keyboard-interactive).".into()),+ os: os.map(Into::into),+ refused_user: Some("adibhanna".into()),+ ..Default::default()+ };+ // Never reached, so it may be a Mac.+ let u = explain_unreachable(spec, &refused(None), true, None, None);+ assert_eq!(u.kind, "auth");+ assert_eq!(u.title, "Mac-Webtech-025 doesn't accept adibhanna");+ assert!(u.detail.starts_with("There's no account adibhanna there, or ssh doesn't allow it."), "{}", u.detail);+ assert!(u.detail.contains("Add this machine again as [email protected], with your account's name there."), "{}", u.detail);+ assert!(u.detail.contains("On a Mac, allowed users are in System Settings › General › Sharing › Remote Login › ⓘ."), "{}", u.detail);+ // ssh-copy-id would fail the same way: no command, and no Set up access.+ assert_eq!(u.hint, None);++ let u = explain_unreachable(spec, &refused(Some("darwin")), true, None, None);+ assert!(u.detail.starts_with("There's no account adibhanna there, or Remote Login doesn't allow it."), "{}", u.detail);+ assert!(u.detail.ends_with("If adibhanna is there, allow it in System Settings › General › Sharing › Remote Login › ⓘ."), "{}", u.detail);++ let u = explain_unreachable(spec, &refused(Some("linux")), true, None, None);+ assert!(u.detail.contains("its ssh server doesn't allow it"), "{}", u.detail);+ assert!(!u.detail.contains("Remote Login"), "{}", u.detail);}#[test]fn knows_a_vm_runs_on_another_machine() {use crate::probe::{PublishedContainer, PublishedPort, SshRoute};let inv = inventory("[[machine]]\nname = \"Beelink\"\nhost = \"beelink\"\n\n[[machine]]\nname = \"Win11\"\nhost = \"win11\"\n\n[[machine]]\nname = \"Inner\"\nhost = \"inner\"\n");- let route = |jump: Option<&str>, hostname: &str, port: u16| Some(SshRoute { jump: jump.map(Into::into), hostname: hostname.into(), port });+ let route = |jump: Option<&str>, hostname: &str, port: u16| Some(SshRoute { jump: jump.map(Into::into), hostname: hostname.into(), port, user: None });let zn = |state: &str| PublishedContainer {name: "zn-win11".into(),state: state.into(),diff --git a/src/probe/mod.rs b/src/probe/mod.rsindex 0b29c04..a30da72 100644--- a/src/probe/mod.rs+++ b/src/probe/mod.rs@@ -87,6 +87,11 @@ pub struct ProbeResult {/// Linux: it has /dev/kvm, so it can run VMs (Windows in Docker, say).#[serde(default)]pub kvm: bool,+ /// The account the machine turned away before asking for its password,+ /// after the key wasn't accepted for one ssh guessed: there's no such+ /// account there, or ssh there doesn't let it in.+ #[serde(default)]+ pub refused_user: Option<String>,}/// A Docker container that publishes ports on its machine.@@ -111,13 +116,15 @@ pub struct PublishedPort {}/// Where ssh goes for a machine: through a jump host (`ProxyJump`, its last-/// hop), and the address and port at the end.+/// hop), and the address and port at the end. And as whom: the account it+/// signs in as there (its config's User, else this computer's login name).#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]#[serde(rename_all = "camelCase", default)]pub struct SshRoute {pub jump: Option<String>,pub hostname: String,pub port: u16,+ pub user: Option<String>,}impl ProbeResult {@@ -213,10 +220,142 @@ pub async fn probe(spec: &MachineSpec, remembered: Option<Shell>) -> ProbeResultlet mut r = check(spec, remembered).await;if spec.is_checkable() && !spec.is_local() {r.route = ssh_route(spec).await;+ r.refused_user = refused_user(spec, &r).await;}r}+/// The account a machine turns away, when its key wasn't accepted for one+/// ssh guessed (the host names none). Asked once, after that failure, and+/// only of a machine that offers keyboard-interactive sign-in: see `turns_away`.+async fn refused_user(spec: &MachineSpec, r: &ProbeResult) -> Option<String> {+ let error = r.error.as_deref()?;+ if names_user(spec) || crate::fleet::build::unreachable_kind(error) != "auth" || !error.contains("keyboard-interactive") {+ return None;+ }+ let user = ssh_user(spec, Some(r))?;+ turns_away(spec).await.then_some(user)+}++/// Whether the machine's host or settings say which account to sign in as.+fn names_user(spec: &MachineSpec) -> bool {+ spec.host.contains('@') || spec.user.as_deref().is_some_and(|u| !u.is_empty())+}++/// The account ssh signs in to a machine as: the one its host or settings+/// name, else ssh's config's (from the last check), else the one its error+/// names, else this computer's login name.+pub fn ssh_user(spec: &MachineSpec, p: Option<&ProbeResult>) -> Option<String> {+ let named = spec.host.trim().rsplit_once('@').map(|(u, _)| u.to_string()).or_else(|| spec.user.clone());+ named+ .or_else(|| p.and_then(|p| p.route.as_ref()?.user.clone()))+ .or_else(|| p.and_then(|p| signed_in_as(p.error.as_deref()?)))+ .or_else(|| std::env::var("USER").or_else(|_| std::env::var("LOGNAME")).ok())+ .filter(|u| !u.is_empty())+}++/// Who ssh signed in as, from its "[email protected]: Permission denied (...)"+/// (after a known-hosts warning, say: a check's error is one line).+fn signed_in_as(error: &str) -> Option<String> {+ error+ .lines()+ .find_map(|l| l.split_once(": Permission denied"))+ .and_then(|(who, _)| who.split_whitespace().last()?.rsplit_once('@'))+ .map(|(u, _)| u.to_string())+ .filter(|u| !u.is_empty())+}++/// The command that gives a machine this computer's public key (like+/// "~/.ssh/id_ed25519.pub"; ssh-copy-id's own pick without one), signed in as+/// `user` when the host names no one: ssh-copy-id alone guesses this+/// computer's login name, which may not be an account there.+pub fn copy_id_command(spec: &MachineSpec, user: Option<&str>, key: Option<&str>) -> String {+ let host = spec.host.trim();+ let key = key.map(|k| format!(" -i {k}")).unwrap_or_default();+ let port = spec.port.map(|p| format!(" -p {p}")).unwrap_or_default();+ let target = match user.filter(|u| !u.is_empty()) {+ Some(u) if !host.contains('@') => format!("{u}@{host}"),+ _ => host.to_string(),+ };+ format!("ssh-copy-id{key}{port} {target}")+}++/// Whether the machine closes the connection for ssh's account before it+/// asks for a password: it has no such account, or doesn't let it in (a Mac's+/// Remote Login can allow only some users). A password sign-in can't tell:+/// servers ask for one even for accounts they don't have. Keyboard-interactive+/// on a Mac says no first. ssh is stopped at the prompt when there is one, so+/// nothing is ever typed or sent.+#[cfg(unix)]+async fn turns_away(spec: &MachineSpec) -> bool {+ let Some(askpass) = askpass_stop() else { return false };+ let mut cmd = Command::new("ssh");+ // ssh keeps the first value it's given for an option: these go before+ // ssh_args' BatchMode=yes, which turns keyboard-interactive off.+ cmd.args([+ "-o", "BatchMode=no",+ "-o", "PreferredAuthentications=keyboard-interactive",+ "-o", "KbdInteractiveAuthentication=yes",+ "-o", "PubkeyAuthentication=no",+ "-o", "NumberOfPasswordPrompts=1",+ "-o", "ControlPath=none",+ ]);+ cmd.args(ssh_args(spec)).arg("true");+ cmd.env("SSH_ASKPASS", askpass).env("SSH_ASKPASS_REQUIRE", "force");+ cmd.stdin(Stdio::null()).stdout(Stdio::null()).stderr(Stdio::piped()).kill_on_drop(true);+ // Without the terminal Muxin may have been started from: an older ssh+ // would ask there instead of through SSH_ASKPASS.+ unsafe {+ cmd.pre_exec(|| {+ libc::setsid();+ Ok(())+ });+ }+ match tokio::time::timeout(Duration::from_secs(15), cmd.output()).await {+ Ok(Ok(out)) => closed_before_asking(&String::from_utf8_lossy(&out.stderr)),+ _ => false,+ }+}++#[cfg(not(unix))]+async fn turns_away(_spec: &MachineSpec) -> bool {+ false+}++/// What `turns_away` gives ssh as SSH_ASKPASS: it says ssh asked (ASKED, on+/// ssh's stderr) and ends ssh, its parent, before an answer goes out. An+/// askpass that only fails would have ssh send an empty one.+#[cfg(unix)]+const ASKPASS_STOP: &str = "#!/bin/sh\necho \"muxin: asked: $1\" >&2\nkill -TERM \"$PPID\"\nexit 1\n";+#[cfg_attr(not(unix), allow(dead_code))]+const ASKED: &str = "muxin: asked:";++/// ASKPASS_STOP as a file to run, in this user's cache folder.+#[cfg(unix)]+fn askpass_stop() -> Option<std::path::PathBuf> {+ static PATH: std::sync::OnceLock<Option<std::path::PathBuf>> = std::sync::OnceLock::new();+ PATH.get_or_init(|| {+ use std::os::unix::fs::PermissionsExt;+ let dir = dirs::cache_dir()?.join("muxen");+ std::fs::create_dir_all(&dir).ok()?;+ let path = dir.join("askpass-stop");+ let tmp = dir.join(format!("askpass-stop.{}", std::process::id()));+ std::fs::write(&tmp, ASKPASS_STOP).ok()?;+ std::fs::set_permissions(&tmp, std::fs::Permissions::from_mode(0o700)).ok()?;+ std::fs::rename(&tmp, &path).ok()?;+ Some(path)+ })+ .clone()+}++/// From ssh's stderr in `turns_away`: the machine closed the connection+/// ("Connection closed by fe80::1%en0 port 22"), and nothing asked for a+/// password first.+#[cfg_attr(not(unix), allow(dead_code))]+fn closed_before_asking(stderr: &str) -> bool {+ !stderr.contains(ASKED) && stderr.lines().any(|l| l.trim().starts_with("Connection closed by ") && l.contains(" port "))+}+/// Where ssh goes for the machine (its config resolved by `ssh -G`).pub async fn ssh_route(spec: &MachineSpec) -> Option<SshRoute> {let out = tokio::time::timeout(Duration::from_secs(3), Command::new("ssh").arg("-G").args(ssh_args(spec)).output()).await.ok()?.ok()?;@@ -229,6 +368,7 @@ pub fn parse_route(text: &str) -> Option<SshRoute> {let get = |key: &str| text.lines().find_map(|l| l.strip_prefix(key).map(|v| v.trim().to_string()));let hostname = get("hostname ").filter(|h| !h.is_empty())?;let port = get("port ").and_then(|p| p.parse().ok()).unwrap_or(22);+ let user = get("user ").filter(|u| !u.is_empty());let jump = get("proxyjump ").filter(|j| !j.is_empty() && j != "none").and_then(|j| {let hop = j.rsplit(',').next()?.trim().trim_start_matches("ssh://");let hop = hop.rsplit_once('@').map(|(_, h)| h).unwrap_or(hop);@@ -238,7 +378,7 @@ pub fn parse_route(text: &str) -> Option<SshRoute> {};(!host.is_empty()).then(|| host.to_string())});- Some(SshRoute { jump, hostname, port })+ Some(SshRoute { jump, hostname, port, user })}async fn check(spec: &MachineSpec, remembered: Option<Shell>) -> ProbeResult {@@ -720,13 +860,48 @@ r1.listener=#[test]fn reads_where_ssh_goes() {let r = parse_route("user adib\nhostname 127.0.0.1\nport 2222\nproxyjump beelink\n").unwrap();- assert_eq!(r, SshRoute { jump: Some("beelink".into()), hostname: "127.0.0.1".into(), port: 2222 });+ assert_eq!(r, SshRoute { jump: Some("beelink".into()), hostname: "127.0.0.1".into(), port: 2222, user: Some("adib".into()) });let r = parse_route("hostname 10.0.0.5\nport 22\nproxyjump a@bastion:2200,ssh://me@[fd00::1]:22\n").unwrap();assert_eq!(r.jump.as_deref(), Some("fd00::1"));let r = parse_route("hostname adib-ser\nport 22\n").unwrap();assert_eq!(r.jump, None);}+ #[test]+ fn knows_which_account_ssh_signs_in_as() {+ let inv = crate::config::Inventory::parse("[[machine]]\nname = \"A\"\nhost = \"[email protected]\"\n\n[[machine]]\nname = \"B\"\nhost = \"b.local\"\nuser = \"bee\"\n\n[[machine]]\nname = \"C\"\nhost = \"c.local\"\n").unwrap();+ let (a, b, c) = (&inv.machines[0], &inv.machines[1], &inv.machines[2]);+ let route = |user: &str| ProbeResult { route: Some(SshRoute { hostname: "c.local".into(), port: 22, user: Some(user.into()), ..Default::default() }), ..Default::default() };+ assert_eq!(ssh_user(a, Some(&route("adib"))).as_deref(), Some("ahanna"));+ assert_eq!(ssh_user(b, Some(&route("adib"))).as_deref(), Some("bee"));+ assert_eq!(ssh_user(c, Some(&route("adib"))).as_deref(), Some("adib"));+ let denied = ProbeResult { error: Some("[email protected]: Permission denied (publickey).".into()), ..Default::default() };+ assert_eq!(ssh_user(c, Some(&denied)).as_deref(), Some("cee"));+ // A check's error is ssh's last lines, joined.+ let error = "Warning: Permanently added 'c.local' (ED25519) to the list of known hosts. [email protected]: Permission denied (publickey,password,keyboard-interactive).";+ assert_eq!(signed_in_as(error).as_deref(), Some("cee"));+ assert_eq!(signed_in_as("Permission denied, please try again."), None);+ assert!(names_user(a) && names_user(b) && !names_user(c));++ assert_eq!(copy_id_command(c, Some("adib"), Some("~/.ssh/id_ed25519.pub")), "ssh-copy-id -i ~/.ssh/id_ed25519.pub [email protected]");+ assert_eq!(copy_id_command(a, Some("adib"), None), "ssh-copy-id [email protected]");+ assert_eq!(copy_id_command(c, None, None), "ssh-copy-id c.local");+ }++ #[test]+ fn tells_a_turned_away_account_from_a_password_prompt() {+ // macOS: no such account, or Remote Login doesn't allow it.+ assert!(closed_before_asking("Connection closed by fe80::1c2b:3d4e:5f60:7a8b%en0 port 22\n"));+ assert!(closed_before_asking("Connection closed by 192.168.1.20 port 22\r\n"));+ // It asked: the account is there.+ assert!(!closed_before_asking("muxin: asked: ([email protected]) Password:\n"));+ assert!(!closed_before_asking("muxin: asked: (ahanna@host) Password:\nConnection closed by 10.0.0.2 port 22\n"));+ // It doesn't offer keyboard-interactive, or never got that far: can't tell.+ assert!(!closed_before_asking("adib@box: Permission denied (publickey,password).\n"));+ assert!(!closed_before_asking("kex_exchange_identification: Connection closed by remote host\n"));+ assert!(!closed_before_asking("ssh: connect to host box port 22: Operation timed out\n"));+ }+#[test]fn parses_docker_and_runner_containers() {let out = "\diff --git a/src/ui/detail.rs b/src/ui/detail.rsindex b0cf741..2a1d4f5 100644--- a/src/ui/detail.rs+++ b/src/ui/detail.rs@@ -890,7 +890,8 @@ impl Root {)}),)- .when(u.kind == "auth", |d| {+ // Not for an account the machine turns away (no hint): a key can't fix that.+ .when(u.kind == "auth" && u.hint.is_some(), |d| {let mid = m.id.clone();d.child(Button::new("m-offline-access", "Set up access")diff --git a/src/ui/sessions.rs b/src/ui/sessions.rsindex 0b23d76..0f34215 100644--- a/src/ui/sessions.rs+++ b/src/ui/sessions.rs@@ -1446,9 +1446,11 @@ impl Root {/// `ssh-copy-id` typed in (making a key first if there's none), for the/// user to run and type their password for that machine once.pub(super) fn setup_ssh_access(&mut self, machine_id: &str, window: &mut Window, cx: &mut Context<Self>) {- let Some((spec, _)) = self.engine.machine(machine_id) else { return };+ let Some((spec, probe)) = self.engine.machine(machine_id) else { return };+ // The account to sign in as, so ssh-copy-id doesn't guess another one.+ let user = crate::probe::ssh_user(&spec, probe.as_ref());let Some(local) = self.snapshot.machines.iter().find(|m| m.local).map(|m| m.id.clone()) else {- let cmd = format!("ssh-copy-id {}", spec.host.trim());+ let cmd = crate::probe::copy_id_command(&spec, user.as_deref(), None);cx.write_to_clipboard(ClipboardItem::new_string(cmd));self.notify_user("Copied. Run it in Terminal, then check again.", false, cx);return;@@ -1459,10 +1461,12 @@ impl Root {});let task = cx.spawn_in(window, async move |this, cx| {let key = job.await.ok().flatten();- let host = spec.host.trim().to_string();let typed = match key {- Some(k) => format!("ssh-copy-id -i {k} {host}"),- None => format!("ssh-keygen -t ed25519 -f ~/.ssh/id_ed25519 -N '' && ssh-copy-id -i ~/.ssh/id_ed25519.pub {host}"),+ Some(k) => crate::probe::copy_id_command(&spec, user.as_deref(), Some(&k)),+ None => format!(+ "ssh-keygen -t ed25519 -f ~/.ssh/id_ed25519 -N '' && {}",+ crate::probe::copy_id_command(&spec, user.as_deref(), Some("~/.ssh/id_ed25519.pub"))+ ),};let _ = this.update_in(cx, |this, window, cx| {let req = StartSession {@@ -1473,7 +1477,10 @@ impl Root {typed: Some(typed),..Default::default()};- let then = format!("Press Enter and type your password for {}, then check again.", spec.name);+ let then = match &user {+ Some(u) => format!("Press Enter and type your password for {u} on {}, then check again.", spec.name),+ None => format!("Press Enter and type your password for {}, then check again.", spec.name),+ };this.start_session_then(req, Some(then), window, cx);});});