//! The agent's named SSH connections as an ssh config file. //! //! `swarm_permissions` reads the agent's `agent-permissions` record and hands //! it to [`apply`], which writes [`CONFIG`]. The system ssh config //! (`nix/agent-modules/ssh.nix`) `Include`s that file ahead of its `Host *` //! block, so a connection's block sets `HostName`, `User` and `Port` and the //! `Host *` block still supplies the identity and the swarm CA certificate. //! //! The file always exists and is empty unless the agent's `ssh` switch is on: //! one switch ends both the certificate and the connections. ssh refuses an //! included file that group or others can write, so the file is written //! through a private temporary file and renamed into place. use std::fmt::Write as _; use std::io::Write as _; use std::path::Path; use swarm_wire::agent_permissions::AgentPermissions; /// The file the system ssh config includes. pub const CONFIG: &str = "/run/hive-agent-ssh-connections/config"; /// The ssh config text for `record`: one `Host` block for each valid /// connection while `ssh` is on, empty otherwise. A connection that fails the /// controller's own check, as a hand edit could leave one, is left out with a /// warning, so no value reaches the file that could add an ssh option. #[must_use] pub fn render(record: &AgentPermissions) -> String { if record.ssh != Some(true) { return String::new(); } let mut out = String::new(); for connection in &record.ssh_connections { match connection.clone().checked() { Ok(c) => { if !out.is_empty() { out.push('\n'); } let _ = writeln!(out, "Host {}", c.name); let _ = writeln!(out, " HostName {}", c.host); let _ = writeln!(out, " User {}", c.user); let _ = writeln!(out, " Port {}", c.port); } Err(why) => tracing::warn!( connection = %connection.name, %why, "ssh connections: left out of the ssh config" ), } } out } /// Replace `path` with `text` in one rename, so ssh never reads half a file. fn write_atomic(path: &Path, text: &str) -> std::io::Result<()> { let dir = path.parent().unwrap_or(Path::new(".")); let mut staged = tempfile::NamedTempFile::new_in(dir)?; staged.write_all(text.as_bytes())?; staged.persist(path).map_err(|e| e.error)?; Ok(()) } /// What the file holds, and the text a write last failed with. #[derive(Debug, Default)] pub struct Applied { written: Option, failed: Option, } /// Write the config `record` calls for to `path` unless `applied` says it is /// there already. A failed write is tried again at every call and logged once /// per text. pub fn apply(record: &AgentPermissions, path: &Path, applied: &mut Applied) { let text = render(record); if applied.written.as_deref() == Some(text.as_str()) { return; } match write_atomic(path, &text) { Ok(()) => { tracing::info!(path = %path.display(), bytes = text.len(), "ssh connections: config written"); applied.failed = None; applied.written = Some(text); } Err(e) => { if applied.failed.as_deref() != Some(text.as_str()) { tracing::warn!( path = %path.display(), error = %e, "ssh connections: the ssh config could not be written" ); } applied.failed = Some(text); } } } #[cfg(test)] mod tests { use super::*; fn record(json: &str) -> AgentPermissions { serde_json::from_str(json).expect("decodes") } const LAB: &str = r#"{"name":"k8s-lab-vm","user":"root","host":"muede-pc2","port":2222}"#; const DB: &str = r#"{"name":"db","user":"deploy","host":"10.1.2.3","port":22}"#; #[test] fn a_connection_is_one_host_block() { let text = render(&record(&format!( r#"{{"ssh":true,"ssh_connections":[{LAB},{DB}]}}"# ))); assert_eq!( text, "Host k8s-lab-vm\n HostName muede-pc2\n User root\n Port 2222\n\ \n\ Host db\n HostName 10.1.2.3\n User deploy\n Port 22\n" ); } #[test] fn the_file_is_empty_unless_ssh_is_on_and_a_connection_exists() { let conns = format!(r#""ssh_connections":[{LAB}]"#); for (why, json) in [ ("ssh off", format!(r#"{{"ssh":false,{conns}}}"#)), ("ssh unset", format!("{{{conns}}}")), ("no connections", r#"{"ssh":true}"#.to_owned()), ("empty record", "{}".to_owned()), ] { assert_eq!(render(&record(&json)), "", "{why}"); } assert!( !render(&record(&format!(r#"{{"ssh":true,{conns}}}"#))).is_empty(), "control: on with a connection renders" ); } #[test] fn a_connection_that_fails_the_check_is_left_out() { let evil = r#"{"name":"x","user":"root\n ProxyCommand evil","host":"h","port":22}"#; let evil_host = r#"{"name":"y","user":"root","host":"h\nHost *","port":22}"#; let evil_name = r#"{"name":"z\nHost *","user":"root","host":"h","port":22}"#; let text = render(&record(&format!( r#"{{"ssh":true,"ssh_connections":[{evil},{evil_host},{evil_name},{LAB}]}}"# ))); assert!(!text.contains("evil") && !text.contains("Host *"), "{text}"); assert!(text.starts_with("Host k8s-lab-vm\n"), "control: {text}"); } #[test] fn apply_writes_on_change_and_turns_the_file_empty_when_ssh_goes_off() { let dir = tempfile::tempdir().unwrap(); let path = dir.path().join("config"); let mut applied = Applied::default(); let on = record(&format!(r#"{{"ssh":true,"ssh_connections":[{LAB}]}}"#)); apply(&on, &path, &mut applied); assert!( std::fs::read_to_string(&path) .unwrap() .starts_with("Host k8s-lab-vm") ); let off = record(&format!(r#"{{"ssh":false,"ssh_connections":[{LAB}]}}"#)); apply(&off, &path, &mut applied); assert_eq!( std::fs::read_to_string(&path).unwrap(), "", "empty, not missing" ); } #[test] fn apply_skips_an_unchanged_text() { let dir = tempfile::tempdir().unwrap(); let path = dir.path().join("config"); let mut applied = Applied::default(); let on = record(&format!(r#"{{"ssh":true,"ssh_connections":[{LAB}]}}"#)); apply(&on, &path, &mut applied); std::fs::write(&path, "sentinel").unwrap(); apply(&on, &path, &mut applied); assert_eq!( std::fs::read_to_string(&path).unwrap(), "sentinel", "not rewritten" ); apply(&record("{}"), &path, &mut applied); assert_eq!( std::fs::read_to_string(&path).unwrap(), "", "control: a change rewrites" ); } /// ssh takes the rendered file, an empty one, and a missing one, and the /// connection's block does not leak into `Host *`. #[test] fn ssh_reads_the_file_empty_missing_and_full() { let dir = tempfile::tempdir().unwrap(); let conn = dir.path().join("config"); let main = dir.path().join("ssh_config"); let write_main = || { std::fs::write( &main, format!( "Include {}\nHost *\n IdentityFile /x/key\n IdentitiesOnly yes\n", conn.display() ), ) .unwrap(); }; write_main(); let g = |host: &str| -> Option { let out = std::process::Command::new("ssh") .args(["-F"]) .arg(&main) .args(["-G", host]) .output() .ok()?; out.status .success() .then(|| String::from_utf8_lossy(&out.stdout).into_owned()) }; if g("probe").is_none() { eprintln!("no ssh binary here; skipping"); return; } // Missing file. let missing = g("k8s-lab-vm").expect("a missing include is not an error"); assert!(missing.contains("\nport 22\n"), "{missing}"); // Empty file. std::fs::write(&conn, "").unwrap(); assert!( g("k8s-lab-vm") .expect("an empty include is not an error") .contains("\nport 22\n") ); // Rendered file. let mut applied = Applied::default(); apply( &record(&format!(r#"{{"ssh":true,"ssh_connections":[{LAB}]}}"#)), &conn, &mut applied, ); let full = g("k8s-lab-vm").expect("rendered"); for want in [ "\nhostname muede-pc2\n", "\nuser root\n", "\nport 2222\n", "\nidentityfile /x/key\n", ] { assert!(full.contains(want), "{want:?} in {full}"); } let other = g("elsewhere").expect("other host"); assert!( other.contains("\nport 22\n") && other.contains("\nidentityfile /x/key\n"), "{other}" ); } }