diff --git a/docs/2-handbook/external-accounts/ssh.md b/docs/2-handbook/external-accounts/ssh.md index 137eb3aa6..7c15fa710 100644 --- a/docs/2-handbook/external-accounts/ssh.md +++ b/docs/2-handbook/external-accounts/ssh.md @@ -102,6 +102,20 @@ bao read -field=public_key ssh-agents/config/ca - It signs ed25519 user keys only, and the certificate allows a terminal (`permit-pty`) and nothing else. +## Named connections + +Give a machine a short name, so the agent runs `ssh k8s-lab-vm` instead of +`ssh -p 2222 root@muede-pc2`. You declare, per agent, a name, the user, the +host and the port. For example `k8s-lab-vm`, `root`, `muede-pc2`, `2222`. + +The agent's ssh config then holds a `Host k8s-lab-vm` block with that host, +user and port, and the connection uses the same certificate as any other. The +block follows a change within ten seconds, and it's empty while the agent's SSH +switch is off, so one switch ends both the certificate and the names. A name +doesn't open the network: see the note under section 1. The routes and the +rules a connection must meet are on +[the SSH CA implementation page](../../4-implementation/swarm/ssh-ca.md#named-connections). + ## Revoking access - **One agent from one machine:** remove its principal (the `authorizedPrincipals` diff --git a/docs/4-implementation/swarm/ssh-ca.md b/docs/4-implementation/swarm/ssh-ca.md index c03e706d1..d9ac95ace 100644 --- a/docs/4-implementation/swarm/ssh-ca.md +++ b/docs/4-implementation/swarm/ssh-ca.md @@ -119,6 +119,46 @@ and attaches it to the agent's cert-auth role `hive-agent-` as a second NixOS then writes `/etc/ssh/authorized_principals.d/` and sets `AuthorizedPrincipalsFile` to it. +## Named connections + +The operator's named connections are the `ssh_connections` list of the same +record (`swarm_wire::ssh_connection::SshConnection`: `name`, `user`, `host`, +`port`). They have their own routes in +`swarm-controller/src/ssh_connections.rs`, and a write changes only that +field; a `PUT` or `DELETE` on `/permissions` keeps them: + +```text +GET /api/agents//ssh-connections +PUT /api/agents//ssh-connections/ {"user":"root","host":"muede-pc2","port":2222} +DELETE /api/agents//ssh-connections/ +``` + +`SshConnection::checked` is the one validation, run by the controller before it +stores a connection and by the agent before it renders one: + +- **Name:** lower-case letters, digits and hyphens, up to 63, not starting with + a hyphen. A name is unique per agent, and an agent has at most 32. +- **User:** letters, digits, `_`, `.` and `-`, up to 32, not starting with `-` + or `.`. +- **Host:** a DNS name (one label is fine) or an IPv4 address. The swarm refuses + IPv6 addresses, `localhost`, and loopback, link-local, multicast and reserved + addresses. +- **Port:** 1 to 65535, except 80 and 443. The hive sends those two ports to + its own proxy, so no direct connection there can exist. + +The swarm doesn't check the hive's own bridge subnet, because each hive sets its +own and an agent can move between hives. + +`hive-agent`'s `ssh_connections.rs` renders the list each time the harness reads +the record (every ten seconds) into `/run/hive-agent-ssh-connections/config`: +one `Host` block each with `HostName`, `User` and `Port`, and an empty file +while `ssh` is off. The block carries no identity lines: ssh takes the +identity from the `Host *` block below the `Include` in `ssh.nix`, which +gives the swarm CA certificate to every connection. The file belongs to the +agent user, because ssh refuses an included file that another user owns. +A controller older than the field drops the list when it next writes the +record through `PUT /permissions`. + ## Not covered Egress. The default `egress.forward = "log"` lets a direct connection from an diff --git a/hive-agent/src/main.rs b/hive-agent/src/main.rs index 7d6811fe5..367f537db 100644 --- a/hive-agent/src/main.rs +++ b/hive-agent/src/main.rs @@ -31,6 +31,7 @@ mod reminders; mod router_todos; mod schedule_timer; mod serve_common; +mod ssh_connections; mod state_entry_watch; mod subagent_role_watch; mod swarm_agent_commands; diff --git a/hive-agent/src/ssh_connections.rs b/hive-agent/src/ssh_connections.rs new file mode 100644 index 000000000..9652269b6 --- /dev/null +++ b/hive-agent/src/ssh_connections.rs @@ -0,0 +1,258 @@ +//! 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}" + ); + } +} diff --git a/hive-agent/src/swarm_permissions.rs b/hive-agent/src/swarm_permissions.rs index 17e75f5fb..cf68afedf 100644 --- a/hive-agent/src/swarm_permissions.rs +++ b/hive-agent/src/swarm_permissions.rs @@ -11,6 +11,9 @@ //! ([`BEFORE_FIRST_READ`]), so a queue that is down at start never leaves it //! wider than the swarm grants. After one, a set key wins, `[]` holds none and //! an unset key is the default. A failed read keeps the last value. +//! +//! The same read renders the ssh connections into the agent's ssh config +//! ([`crate::ssh_connections`]). use std::sync::{PoisonError, RwLock}; use std::time::Duration; @@ -68,8 +71,16 @@ pub async fn run() { %agent, "permissions: holding none (no bash) until the first read of this agent's key succeeds" ); + let mut ssh_applied = crate::ssh_connections::Applied::default(); loop { let read = read_once(&client, &agent).await; + if let Some(Read::Current(record)) = &read { + crate::ssh_connections::apply( + record, + std::path::Path::new(crate::ssh_connections::CONFIG), + &mut ssh_applied, + ); + } { let mut current = CURRENT.write().unwrap_or_else(PoisonError::into_inner); let next = settle(current.clone(), read); diff --git a/nix/agent-modules/ssh.nix b/nix/agent-modules/ssh.nix index 55587a4de..937838176 100644 --- a/nix/agent-modules/ssh.nix +++ b/nix/agent-modules/ssh.nix @@ -64,6 +64,12 @@ let # In the state dir, which is bound from the host, so a pin survives a restart. knownHostsFile = "/agents/${agentName}/state/ssh_known_hosts"; + # The file the harness writes the operator's named connections into + # (`hive-agent`'s `ssh_connections`). Owned by the agent user: ssh refuses an + # included file that another user owns, or that group or others can write. + connectionsDir = "/run/hive-agent-ssh-connections"; + connectionsFile = "${connectionsDir}/config"; + signPath = "${ca.mountPath}/sign/${ca.roleName}"; # A certificate with less than this left is signed again by `ssh`. The timer @@ -92,10 +98,15 @@ in config = lib.mkIf (baoCfg.addr != null) { # Every host: the certificate, and the pins in the state dir, which outlives # the container root. `accept-new` records a host's key at first contact and - # refuses a changed one after that. The `Match` line has no settings: ssh + # refuses a changed one after that. The `Include` is the first line: ssh + # takes the first value it finds for an option, and an include below `Host *` + # would sit inside that block. The included file holds the `Host` blocks of + # the named connections and ends its own scope, and `Host *` below still + # gives each of them the identity. The `Match` line has no settings: ssh # runs its command while it reads the config, before it loads any identity, # and the answer is not used. programs.ssh.extraConfig = '' + Include ${connectionsFile} Match exec "HIVE_SSH_CERT_ENSURE=1 ${helper} ` connects as `user` to `host` on `port`. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[cfg_attr(feature = "schema", derive(utoipa::ToSchema))] +pub struct SshConnection { + /// The alias the agent types: lower-case letters, digits and hyphens, at + /// most 63, not starting with a hyphen. + #[cfg_attr(feature = "schema", schema(example = "k8s-lab-vm"))] + pub name: String, + /// The account to log in as. + #[cfg_attr(feature = "schema", schema(example = "root"))] + pub user: String, + /// A DNS name or an IPv4 address. + #[cfg_attr(feature = "schema", schema(example = "muede-pc2"))] + pub host: String, + /// The TCP port, 1 to 65535 except 80 and 443. + #[cfg_attr(feature = "schema", schema(example = 2222))] + pub port: u16, +} + +/// The body of `PUT /api/agents/{name}/ssh-connections/{conn}`; the name is the +/// path's. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[cfg_attr(feature = "schema", derive(utoipa::ToSchema))] +#[serde(deny_unknown_fields)] +pub struct PutSshConnection { + /// The account to log in as. + #[cfg_attr(feature = "schema", schema(example = "root"))] + pub user: String, + /// A DNS name or an IPv4 address. + #[cfg_attr(feature = "schema", schema(example = "muede-pc2"))] + pub host: String, + /// The TCP port, 1 to 65535 except 80 and 443. + #[cfg_attr(feature = "schema", schema(example = 2222))] + pub port: u16, +} + +/// The answer to `GET /api/agents/{name}/ssh-connections`. +#[derive(Debug, Default, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[cfg_attr(feature = "schema", derive(utoipa::ToSchema))] +pub struct SshConnections { + /// The agent's connections, in the order they were added. + pub connections: Vec, +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn bodies_round_trip_and_the_put_refuses_other_fields() { + let put = PutSshConnection { + user: "root".to_owned(), + host: "muede-pc2".to_owned(), + port: 2222, + }; + let wire = r#"{"user":"root","host":"muede-pc2","port":2222}"#; + assert_eq!(serde_json::to_string(&put).unwrap(), wire); + assert_eq!(serde_json::from_str::(wire).unwrap(), put); + assert!( + serde_json::from_str::( + r#"{"name":"x","user":"root","host":"h","port":22}"# + ) + .is_err(), + "the name is the path's" + ); + assert_eq!( + serde_json::to_string(&SshConnections::default()).unwrap(), + r#"{"connections":[]}"# + ); + } +} diff --git a/swarm-controller/src/agent_permissions.rs b/swarm-controller/src/agent_permissions.rs index af97ba7bc..976930dad 100644 --- a/swarm-controller/src/agent_permissions.rs +++ b/swarm-controller/src/agent_permissions.rs @@ -43,7 +43,8 @@ const MAX_ATTEMPTS: usize = 5; /// The permissions to store for `req`, whose list is already checked. The list /// replaces the stored one; `unrestricted_internet`, `max_repos` and `ssh` left -/// out keep the ones in `current`. `internet_log` is stored only as `true`, and a request that sets +/// out keep the ones in `current`, and the ssh connections are always kept (they +/// have their own routes). `internet_log` is stored only as `true`, and a request that sets /// `unrestricted_internet` without it turns it off: an agent that moves to /// unrestricted and back to restricted does not come back logging. fn into_stored(req: Permissions, current: &AgentPermissions) -> AgentPermissions { @@ -58,6 +59,7 @@ fn into_stored(req: Permissions, current: &AgentPermissions) -> AgentPermissions internet_log, max_repos: req.max_repos.or(current.max_repos), ssh: req.ssh.or(current.ssh), + ssh_connections: current.ssh_connections.clone(), } } @@ -128,7 +130,7 @@ fn view(v: AgentPermissions) -> Permissions { } } -fn agent_name(name: &str) -> Result { +pub(crate) fn agent_name(name: &str) -> Result { hive_types::Ident::parse(name) .map(hive_types::Ident::into_string) .map_err(|reason| (StatusCode::BAD_REQUEST, reason.to_owned())) @@ -136,7 +138,7 @@ fn agent_name(name: &str) -> Result { /// Log a refused `op` on `agent` at `warn` and pass the problem on. The /// handlers have no caller identity; `detail` is the response's. -fn logged(op: &'static str, agent: &str, problem: ProblemDetails) -> ProblemDetails { +pub(crate) fn logged(op: &'static str, agent: &str, problem: ProblemDetails) -> ProblemDetails { tracing::warn!( op, agent, @@ -198,12 +200,12 @@ fn hive_names(state: &AppState) -> Vec { state.hives.iter().map(|h| h.name.clone()).collect() } -fn queue_problem(e: &anyhow::Error) -> ProblemDetails { +pub(crate) fn queue_problem(e: &anyhow::Error) -> ProblemDetails { tracing::warn!(error = %format!("{e:#}"), "agent permissions: queue failure"); error_problem(wanted_error_status(e), &format!("{e:#}")) } -async fn open_or_create( +pub(crate) async fn open_or_create( client: &async_nats::Client, ) -> Result { agent_permissions::open_or_create(client) @@ -386,16 +388,17 @@ async fn delete_with( let (current, revision, _) = read_or_default::(&store, &agent) .await .map_err(|e| queue_problem(&e))?; - // Only the flags and the repository limit outlive a clear: dropping - // `unrestricted_internet` would turn an agent created with `false` on, - // dropping `internet_log` would turn a logging agent into an enforced - // one, and a limit is an operator's decision about repositories, not - // part of the permission list. + // Only the flags, the repository limit and the ssh connections outlive a + // clear: dropping `unrestricted_internet` would turn an agent created with + // `false` on, dropping `internet_log` would turn a logging agent into an + // enforced one, and a limit or a connection is an operator's decision + // with its own route, not part of the permission list. let kept = AgentPermissions { unrestricted_internet: current.unrestricted_internet, internet_log: current.internet_log, max_repos: current.max_repos, ssh: current.ssh, + ssh_connections: current.ssh_connections.clone(), ..AgentPermissions::default() }; mirror(leaves, &agent, &held(¤t), &held(&kept)) @@ -497,6 +500,7 @@ pub(crate) fn at_create( internet_log: None, max_repos: None, ssh: None, + ssh_connections: Vec::new(), }) } @@ -528,6 +532,7 @@ fn merged_at_create( }, max_repos: value.max_repos.or(current.max_repos), ssh: value.ssh.or(current.ssh), + ssh_connections: current.ssh_connections.clone(), } } diff --git a/swarm-controller/src/main.rs b/swarm-controller/src/main.rs index dce44a752..6e3a4c87d 100644 --- a/swarm-controller/src/main.rs +++ b/swarm-controller/src/main.rs @@ -88,6 +88,7 @@ mod request_reviewer; mod review_classifier; mod routes; mod schedules; +mod ssh_connections; mod startup; mod status; mod store; diff --git a/swarm-controller/src/ssh_connections.rs b/swarm-controller/src/ssh_connections.rs new file mode 100644 index 000000000..f4e575d09 --- /dev/null +++ b/swarm-controller/src/ssh_connections.rs @@ -0,0 +1,471 @@ +//! `/api/agents/{name}/ssh-connections` — the named SSH connections declared +//! for one agent. +//! +//! They live in the `ssh_connections` field of the agent's `agent-permissions` +//! record, which this daemon alone writes (`crate::agent_permissions`). Every +//! write here reads the record, changes only that field and writes it back +//! against the revision it read, so it cannot undo a concurrent change to the +//! rest of the record. The agent renders the connections into its ssh config +//! while its `ssh` switch is on; nothing here depends on the switch. + +use axum::Json; +use axum::extract::rejection::JsonRejection; +use axum::extract::{Path, State}; +use axum::http::StatusCode; +use problem_details::ProblemDetails; +use swarm_controller_api::ssh_connections::{PutSshConnection, SshConnection, SshConnections}; +use swarm_wire::agent_permissions::AgentPermissions; +use swarm_wire::ssh_connection::{SshConnection as Stored, check_list}; + +use crate::agent_permissions::{agent_name, logged, open_or_create, queue_problem}; +use crate::routes::{AppState, error_problem}; +use crate::schedules::{live, queue, read_or_default, refused, write}; + +/// How many times a losing writer re-reads and re-applies, as in +/// `agent_permissions`. +const MAX_ATTEMPTS: usize = 5; + +fn view(stored: Vec) -> SshConnections { + SshConnections { + connections: stored + .into_iter() + .map(|c| SshConnection { + name: c.name, + user: c.user, + host: c.host, + port: c.port, + }) + .collect(), + } +} + +#[utoipa::path( + get, + path = "/api/agents/{name}/ssh-connections", + params(("name" = String, Path, description = "agent name")), + responses( + (status = 200, description = "the agent's named SSH connections; empty when it has \ + none", body = SshConnections), + (status = 400, description = "not an identifier (problem+json)", body = String), + (status = 503, description = "no swarm queue is configured on this host, or it is \ + not connected (problem+json)", body = String), + (status = 500, description = "the record could not be read (problem+json)", + body = String), + ), + tag = "agents" +)] +pub(crate) async fn get_ssh_connections( + State(state): State, + Path(name): Path, +) -> Result, ProblemDetails> { + let agent = agent_name(&name).map_err(refused)?; + let client = queue(&state).map_err(refused)?; + let store = open_or_create(&client).await?; + let (current, _, _) = read_or_default::(&store, &agent) + .await + .map_err(|e| queue_problem(&e))?; + Ok(Json(view(current.ssh_connections))) +} + +/// Add the connection `conn` to the agent, or replace the one of that name. +/// +/// The agent's ssh config follows within ten seconds, while its `ssh` switch +/// is on. The connection does not open the hive's network by itself. +#[utoipa::path( + put, + path = "/api/agents/{name}/ssh-connections/{conn}", + params( + ("name" = String, Path, description = "agent name"), + ("conn" = String, Path, description = "the ssh alias"), + ), + request_body = PutSshConnection, + responses( + (status = 200, description = "the agent's connections as stored", body = SshConnections), + (status = 400, description = "not an agent no hive declares, or a connection that \ + fails validation: the alias, user, host or port, or more than 32 connections \ + (problem+json)", body = String), + (status = 422, description = "an unknown field"), + (status = 503, description = "no swarm queue is configured on this host, or it is \ + not connected (problem+json)", body = String), + (status = 500, description = "the record could not be written (problem+json)", + body = String), + ), + tag = "agents" +)] +pub(crate) async fn put_ssh_connection( + State(state): State, + Path((name, conn)): Path<(String, String)>, + req: Result, JsonRejection>, +) -> Result, ProblemDetails> { + let refuse = |p| logged("put ssh connection", &name, p); + let Json(req) = + req.map_err(|rejection| refuse(error_problem(rejection.status(), &rejection.body_text())))?; + let agent = agent_name(&name).map_err(|r| refuse(refused(r)))?; + let new = Stored { + name: conn, + user: req.user, + host: req.host, + port: req.port, + } + .checked() + .map_err(|why| refuse(error_problem(StatusCode::BAD_REQUEST, &why)))?; + let client = queue(&state).map_err(|r| refuse(refused(r)))?; + if !live(&state).await.map_err(refuse)?.contains(&agent) { + return Err(refuse(error_problem( + StatusCode::BAD_REQUEST, + &format!("no hive's wanted state declares an agent {agent:?} that is not destroyed"), + ))); + } + let store = open_or_create(&client).await?; + for _ in 0..MAX_ATTEMPTS { + let (mut value, revision, _) = read_or_default::(&store, &agent) + .await + .map_err(|e| queue_problem(&e))?; + match value + .ssh_connections + .iter_mut() + .find(|c| c.name == new.name) + { + Some(slot) => *slot = new.clone(), + None => value.ssh_connections.push(new.clone()), + } + check_list(&value.ssh_connections) + .map_err(|why| refuse(error_problem(StatusCode::BAD_REQUEST, &why)))?; + if write(&store, &agent, &value, revision) + .await + .map_err(|e| queue_problem(&e))? + { + tracing::info!(%agent, connection = ?new, "set agent ssh connection"); + return Ok(Json(view(value.ssh_connections))); + } + } + Err(queue_problem(&anyhow::anyhow!( + "gave up writing the ssh connections of {agent} after {MAX_ATTEMPTS} conflicting writes" + ))) +} + +#[utoipa::path( + delete, + path = "/api/agents/{name}/ssh-connections/{conn}", + params( + ("name" = String, Path, description = "agent name"), + ("conn" = String, Path, description = "the ssh alias"), + ), + responses( + (status = 204, description = "removed, or there was none of that name"), + (status = 400, description = "not an identifier (problem+json)", body = String), + (status = 503, description = "no swarm queue is configured on this host, or it is \ + not connected (problem+json)", body = String), + (status = 500, description = "the record could not be written (problem+json)", + body = String), + ), + tag = "agents" +)] +pub(crate) async fn delete_ssh_connection( + State(state): State, + Path((name, conn)): Path<(String, String)>, +) -> Result { + let refuse = |p| logged("delete ssh connection", &name, p); + let agent = agent_name(&name).map_err(|r| refuse(refused(r)))?; + let client = queue(&state).map_err(|r| refuse(refused(r)))?; + let store = open_or_create(&client).await?; + for _ in 0..MAX_ATTEMPTS { + let (mut value, revision, _) = read_or_default::(&store, &agent) + .await + .map_err(|e| queue_problem(&e))?; + let before = value.ssh_connections.len(); + value.ssh_connections.retain(|c| c.name != conn); + if value.ssh_connections.len() == before { + return Ok(StatusCode::NO_CONTENT); + } + let written = if value == AgentPermissions::default() { + store + .delete(&agent) + .await + .map_err(|e| queue_problem(&anyhow::Error::new(e)))?; + true + } else { + write(&store, &agent, &value, revision) + .await + .map_err(|e| queue_problem(&e))? + }; + if written { + tracing::info!(%agent, connection = %conn, "removed agent ssh connection"); + return Ok(StatusCode::NO_CONTENT); + } + } + Err(queue_problem(&anyhow::anyhow!( + "gave up writing the ssh connections of {agent} after {MAX_ATTEMPTS} conflicting writes" + ))) +} + +#[cfg(test)] +mod tests { + use super::{delete_ssh_connection, get_ssh_connections, put_ssh_connection}; + use crate::agent_permissions::{delete_agent_permissions, put_agent_permissions}; + use crate::routes::AppState; + use crate::test_nats::TestNats; + use axum::Json; + use axum::extract::{Path, State}; + use axum::http::StatusCode; + use problem_details::ProblemDetails; + use swarm_controller_api::permissions::Permissions; + use swarm_controller_api::ssh_connections::{PutSshConnection, SshConnections}; + + fn body(user: &str, host: &str, port: u16) -> PutSshConnection { + PutSshConnection { + user: user.to_owned(), + host: host.to_owned(), + port, + } + } + + async fn put( + state: &AppState, + agent: &str, + name: &str, + req: PutSshConnection, + ) -> Result { + put_ssh_connection( + State(state.clone()), + Path((agent.to_owned(), name.to_owned())), + Ok(Json(req)), + ) + .await + .map(|Json(v)| v) + } + + async fn get(state: &AppState, agent: &str) -> SshConnections { + get_ssh_connections(State(state.clone()), Path(agent.to_owned())) + .await + .expect("read") + .0 + } + + async fn remove(state: &AppState, agent: &str, name: &str) -> StatusCode { + delete_ssh_connection( + State(state.clone()), + Path((agent.to_owned(), name.to_owned())), + ) + .await + .expect("delete") + } + + async fn stored( + client: &async_nats::Client, + agent: &str, + ) -> swarm_wire::agent_permissions::AgentPermissions { + match swarm_queue_client::agent_permissions::read(client, agent) + .await + .expect("read the record") + { + swarm_queue_client::agent_permissions::Read::Current(record) => record, + swarm_queue_client::agent_permissions::Read::NoBucket => panic!("no bucket"), + } + } + + fn names(v: &SshConnections) -> Vec<&str> { + v.connections.iter().map(|c| c.name.as_str()).collect() + } + + /// A connection is added, listed, replaced under its own name and removed; + /// another agent's list is not touched. + #[tokio::test] + async fn connections_are_added_replaced_and_removed_per_agent() { + use crate::wanted::WantedWriter; + use swarm_wire::wanted::AgentState; + + let nats = TestNats::start(); + let client = nats.client().await; + let state = crate::agent_limits::tests::declared(&client).await; + WantedWriter::new(client.clone()) + .set("pr1ma", "iris", AgentState::Up) + .await + .expect("declare iris"); + + assert!(get(&state, "atlas").await.connections.is_empty()); + let one = put( + &state, + "atlas", + "k8s-lab-vm", + body("root", "muede-pc2", 2222), + ) + .await + .expect("added"); + assert_eq!(names(&one), ["k8s-lab-vm"]); + assert_eq!(one.connections[0].host, "muede-pc2"); + let two = put(&state, "atlas", "db", body("deploy", "Db.Example.org", 22)) + .await + .expect("added"); + assert_eq!(names(&two), ["k8s-lab-vm", "db"]); + assert_eq!( + two.connections[1].host, "db.example.org", + "stored lower-case" + ); + + let replaced = put( + &state, + "atlas", + "k8s-lab-vm", + body("admin", "10.1.2.3", 2200), + ) + .await + .expect("replaced"); + assert_eq!(names(&replaced), ["k8s-lab-vm", "db"], "replaced in place"); + assert_eq!(replaced.connections[0].user, "admin"); + assert_eq!(get(&state, "atlas").await, replaced); + assert!( + get(&state, "iris").await.connections.is_empty(), + "another agent's list is not changed" + ); + + assert_eq!( + remove(&state, "atlas", "k8s-lab-vm").await, + StatusCode::NO_CONTENT + ); + assert_eq!(names(&get(&state, "atlas").await), ["db"]); + assert_eq!( + remove(&state, "atlas", "k8s-lab-vm").await, + StatusCode::NO_CONTENT, + "removing again is not an error" + ); + assert_eq!(names(&get(&state, "atlas").await), ["db"]); + } + + /// The list rides in the permissions record: a `PUT` or `DELETE` of the + /// permissions keeps it, and a change of connections keeps the switch. + #[tokio::test] + async fn the_list_and_the_rest_of_the_record_survive_each_others_writes() { + let nats = TestNats::start(); + let client = nats.client().await; + let state = crate::agent_limits::tests::declared(&client).await; + let permissions = |ssh| Permissions { + ssh, + ..Permissions::default() + }; + let _ = put_agent_permissions( + State(state.clone()), + Path("atlas".to_owned()), + Ok(Json(permissions(Some(true)))), + ) + .await + .expect("switch on"); + let _ = put(&state, "atlas", "lab", body("root", "muede-pc2", 2222)) + .await + .expect("added"); + + let _ = put_agent_permissions( + State(state.clone()), + Path("atlas".to_owned()), + Ok(Json(Permissions { + max_repos: Some(3), + ..Permissions::default() + })), + ) + .await + .expect("limit"); + assert_eq!( + names(&get(&state, "atlas").await), + ["lab"], + "PUT /permissions keeps it" + ); + delete_agent_permissions(State(state.clone()), Path("atlas".to_owned())) + .await + .expect("cleared"); + assert_eq!( + names(&get(&state, "atlas").await), + ["lab"], + "DELETE /permissions keeps it" + ); + + let _ = put(&state, "atlas", "other", body("root", "h", 22)) + .await + .expect("added"); + let record = stored(&client, "atlas").await; + assert_eq!( + record.ssh, + Some(true), + "a connection write keeps the switch" + ); + assert_eq!(record.max_repos, Some(3)); + + // Control: the permissions record the field left out of is still read. + remove(&state, "atlas", "lab").await; + remove(&state, "atlas", "other").await; + let record = stored(&client, "atlas").await; + assert_eq!(record.ssh, Some(true)); + assert!(record.ssh_connections.is_empty()); + } + + /// Each refusal is a 400 and writes nothing; the control is the same + /// request with the one field fixed. + #[tokio::test] + async fn an_invalid_connection_is_refused_and_nothing_is_written() { + let nats = TestNats::start(); + let client = nats.client().await; + let state = crate::agent_limits::tests::declared(&client).await; + + for (why, agent, name, req) in [ + ("alias", "atlas", "Bad Name", body("root", "h", 22)), + ("user", "atlas", "a", body("-oProxyCommand=x", "h", 22)), + ("loopback", "atlas", "a", body("root", "127.0.0.1", 22)), + ("host", "atlas", "a", body("root", "h\nHost *", 22)), + ("port 80", "atlas", "a", body("root", "h", 80)), + ("port 443", "atlas", "a", body("root", "h", 443)), + ("port 0", "atlas", "a", body("root", "h", 0)), + ("undeclared agent", "ghost", "a", body("root", "h", 22)), + ("agent name", "Not An Ident", "a", body("root", "h", 22)), + ] { + let err = put(&state, agent, name, req).await.expect_err(why); + assert_eq!(err.status, Some(StatusCode::BAD_REQUEST), "{why}: {err:?}"); + } + assert!( + get(&state, "atlas").await.connections.is_empty(), + "nothing was written" + ); + let _ = put(&state, "atlas", "a", body("root", "h", 22)) + .await + .expect("control: the valid one is stored"); + } + + /// The 33rd connection is refused; replacing one at the bound is not. + #[tokio::test] + async fn an_agent_has_at_most_the_bound() { + let nats = TestNats::start(); + let client = nats.client().await; + let state = crate::agent_limits::tests::declared(&client).await; + for i in 0..swarm_wire::ssh_connection::MAX_CONNECTIONS { + let _ = put(&state, "atlas", &format!("c{i}"), body("root", "h", 22)) + .await + .expect("within the bound"); + } + let err = put(&state, "atlas", "one-more", body("root", "h", 22)) + .await + .expect_err("over the bound"); + assert_eq!(err.status, Some(StatusCode::BAD_REQUEST)); + let _ = put(&state, "atlas", "c0", body("root", "h", 2222)) + .await + .expect("control: a replacement at the bound"); + } + + /// A record written before the field existed takes a connection and keeps + /// its other fields. + #[tokio::test] + async fn a_record_from_before_the_field_takes_a_connection() { + let nats = TestNats::start(); + let client = nats.client().await; + let state = crate::agent_limits::tests::declared(&client).await; + swarm_queue_client::agent_permissions::open_or_create(&client) + .await + .expect("bucket") + .put("atlas", br#"{"ssh":true,"max_repos":2}"#.to_vec().into()) + .await + .expect("old record"); + let _ = put(&state, "atlas", "lab", body("root", "muede-pc2", 2222)) + .await + .expect("added"); + let record = stored(&client, "atlas").await; + assert_eq!((record.ssh, record.max_repos), (Some(true), Some(2))); + assert_eq!(record.ssh_connections.len(), 1); + } +} diff --git a/swarm-controller/src/startup.rs b/swarm-controller/src/startup.rs index 86171d7db..04c626625 100644 --- a/swarm-controller/src/startup.rs +++ b/swarm-controller/src/startup.rs @@ -32,7 +32,8 @@ use crate::{ claude_login, config_drift, config_pr, egress_allow, egress_deny, forge, forge_account, github_account, gitlab_account, inference, issue_report, linked_accounts, matrix_account, message_stream, notify_flows, notify_router_api, pause_hold, pr_report, pulls, queue_identity, - review_classifier, schedules, status, subagent_term, term_stream, wanted, webhook, + review_classifier, schedules, ssh_connections, status, subagent_term, term_stream, wanted, + webhook, }; /// Where the daemon binds, overridable via `SWARM_CONTROLLER_SOCKET`. @@ -633,6 +634,11 @@ fn permission_routes(router: OpenApiRouter) -> OpenApiRouter )) .routes(routes!(agent_permissions::get_permission_catalogue)) .routes(routes!(agent_ssh::get_ssh_ca)) + .routes(routes!(ssh_connections::get_ssh_connections)) + .routes(routes!( + ssh_connections::put_ssh_connection, + ssh_connections::delete_ssh_connection + )) } /// The routes that write, delete and list an agent's linked accounts and diff --git a/swarm-wire/src/agent_permissions.rs b/swarm-wire/src/agent_permissions.rs index 37a98721b..16acd4dbe 100644 --- a/swarm-wire/src/agent_permissions.rs +++ b/swarm-wire/src/agent_permissions.rs @@ -102,6 +102,13 @@ pub struct AgentPermissions { /// to the agent's store login role while this is `true`. #[serde(default, skip_serializing_if = "Option::is_none")] pub ssh: Option, + /// The named SSH connections the operator declared for the agent. The + /// agent renders them into its ssh config while `ssh` is on. Each passes + /// [`crate::ssh_connection::SshConnection::checked`] before it is stored, + /// and names are unique. A controller built before this field decodes the + /// record without it and stores it back without it. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub ssh_connections: Vec, } /// What an agent whose record has no `max_repos` may create: no repositories. @@ -237,6 +244,41 @@ mod tests { assert_eq!(before.internet_log, None); } + /// The connections are left out when empty, so a record that never named + /// them encodes as before, and an older reader keeps the fields it knows. + #[test] + fn ssh_connections_are_left_out_when_empty_and_old_readers_skip_them() { + use crate::ssh_connection::SshConnection; + // A reader built before the field existed. + #[derive(serde::Deserialize)] + struct Old { + ssh: Option, + } + let none = AgentPermissions { + ssh: Some(true), + ..AgentPermissions::default() + }; + assert_eq!(serde_json::to_string(&none).unwrap(), r#"{"ssh":true}"#); + let before: AgentPermissions = serde_json::from_str(r#"{"ssh":true}"#).unwrap(); + assert!(before.ssh_connections.is_empty()); + assert_eq!(before, none); + + let one = AgentPermissions { + ssh: Some(true), + ssh_connections: vec![SshConnection { + name: "k8s-lab-vm".to_owned(), + user: "root".to_owned(), + host: "muede-pc2".to_owned(), + port: 2222, + }], + ..AgentPermissions::default() + }; + let wire = r#"{"ssh":true,"ssh_connections":[{"name":"k8s-lab-vm","user":"root","host":"muede-pc2","port":2222}]}"#; + assert_eq!(serde_json::to_string(&one).unwrap(), wire); + assert_eq!(serde_json::from_str::(wire).unwrap(), one); + assert_eq!(serde_json::from_str::(wire).unwrap().ssh, Some(true)); + } + /// The repository limit is left out when unset, so a record that never /// named it encodes as before; a negative number (Forgejo's "unlimited") /// does not decode. diff --git a/swarm-wire/src/lib.rs b/swarm-wire/src/lib.rs index a61c70cf7..3a3a63059 100644 --- a/swarm-wire/src/lib.rs +++ b/swarm-wire/src/lib.rs @@ -31,6 +31,7 @@ pub mod review_classifier; pub mod router_api; pub mod router_sink; pub mod router_todo; +pub mod ssh_connection; pub mod stt; pub mod subagent_status; pub mod subagent_term; diff --git a/swarm-wire/src/ssh_connection.rs b/swarm-wire/src/ssh_connection.rs new file mode 100644 index 000000000..5009738a7 --- /dev/null +++ b/swarm-wire/src/ssh_connection.rs @@ -0,0 +1,437 @@ +//! A named SSH connection an operator declares for one agent: the alias the +//! agent types, and the user, host and port it stands for. +//! +//! Stored in [`crate::agent_permissions::AgentPermissions::ssh_connections`]. +//! [`SshConnection::checked`] is the one gate both ends use: the controller +//! runs it before it stores a connection, and the agent runs it again before it +//! writes one into its ssh config, so a record edited by hand cannot put +//! whitespace, a newline or an ssh option into that file. + +use std::net::Ipv4Addr; + +/// The most connections one agent may have. +pub const MAX_CONNECTIONS: usize = 32; + +/// The longest `name` an alias may have, the DNS label limit. +const MAX_NAME: usize = 63; + +/// The longest `user`, the `LOGIN_NAME_MAX` of POSIX. +const MAX_USER: usize = 32; + +/// Ports the hive's intercept chain redirects before its forward chain sees +/// them, so no allowance on the forward chain can ever match. +pub const INTERCEPTED_PORTS: [u16; 2] = [80, 443]; + +/// One named connection: `ssh ` runs `ssh -p @`. +#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)] +pub struct SshConnection { + /// The ssh `Host` alias: lower-case letters, digits and hyphens, starting + /// with a letter or digit, at most 63 characters. Unique per agent. + pub name: String, + /// The account to log in as: a POSIX portable user name, at most 32 + /// characters. + pub user: String, + /// A DNS name (a single label is fine) or an IPv4 address. + pub host: String, + /// The TCP port, 1 to 65535 except [`INTERCEPTED_PORTS`]. + pub port: u16, +} + +impl SshConnection { + /// `self` as it is stored and rendered: the host lower-cased, every field + /// checked. + /// + /// # Errors + /// A caller-ready message naming the field and the rule it breaks. + pub fn checked(mut self) -> Result { + check_name(&self.name)?; + check_user(&self.user)?; + self.host = normalize_host(&self.host)?; + check_port(self.port)?; + Ok(self) + } +} + +/// Refuse a list that is too long or names a connection twice. +/// +/// # Errors +/// A caller-ready message. +pub fn check_list(connections: &[SshConnection]) -> Result<(), String> { + if connections.len() > MAX_CONNECTIONS { + return Err(format!( + "an agent may have at most {MAX_CONNECTIONS} ssh connections" + )); + } + let mut seen = std::collections::HashSet::new(); + for c in connections { + if !seen.insert(c.name.as_str()) { + return Err(format!("ssh connection {:?} is listed twice", c.name)); + } + } + Ok(()) +} + +fn check_name(name: &str) -> Result<(), String> { + let ok = (1..=MAX_NAME).contains(&name.len()) + && name + .bytes() + .all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'-') + && !name.starts_with('-'); + if ok { + Ok(()) + } else { + Err(format!( + "name {name:?} is not an ssh alias: 1 to {MAX_NAME} lower-case letters, digits or \ + hyphens, not starting with a hyphen" + )) + } +} + +fn check_user(user: &str) -> Result<(), String> { + let ok = (1..=MAX_USER).contains(&user.len()) + && user + .bytes() + .all(|b| b.is_ascii_alphanumeric() || matches!(b, b'_' | b'.' | b'-')) + && !user.starts_with(['-', '.']); + if ok { + Ok(()) + } else { + Err(format!( + "user {user:?} is not a user name: 1 to {MAX_USER} letters, digits, `_`, `.` or `-`, \ + not starting with `-` or `.`" + )) + } +} + +fn check_port(port: u16) -> Result<(), String> { + if port == 0 { + return Err("port 0 is not a port".to_owned()); + } + if INTERCEPTED_PORTS.contains(&port) { + return Err(format!( + "port {port} is refused: the hive redirects it to its own proxy, so a direct \ + connection there cannot be allowed" + )); + } + Ok(()) +} + +/// `raw` as the host stored and rendered, or why it is refused. +/// +/// An IPv4 address in dotted-quad form, or a DNS name, lower-cased: labels of +/// 1 to 63 letters, digits or hyphens that neither start nor end with a hyphen, +/// at most 253 characters in all. A single label is a name. A name whose last +/// label reads as a number (`127.1`, `0x7f.1`) is refused, as a resolver turns +/// it into an address. Refused addresses are the ones no machine of the +/// operator's can be: loopback, link-local, unspecified, multicast and +/// reserved. +fn normalize_host(raw: &str) -> Result { + let host = raw.to_ascii_lowercase(); + if host.contains(':') { + return Err(format!( + "host {raw:?} looks like an IPv6 address, which is not supported; use a name or an \ + IPv4 address" + )); + } + if let Ok(ip) = host.parse::() { + return check_address(ip).map(|()| host); + } + if host.len() > 253 { + return Err(format!("host {raw:?} is longer than 253 characters")); + } + let labels: Vec<&str> = host.split('.').collect(); + for label in &labels { + let ok = (1..=63).contains(&label.len()) + && label + .bytes() + .all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'-') + && !label.starts_with('-') + && !label.ends_with('-'); + if !ok { + return Err(format!( + "host {raw:?} is not a DNS name or an IPv4 address: labels are 1 to 63 letters, \ + digits or hyphens, not starting or ending with a hyphen" + )); + } + } + let last = labels.last().copied().unwrap_or_default(); + let numeric = last.bytes().all(|b| b.is_ascii_digit()) + || last + .strip_prefix("0x") + .is_some_and(|hex| hex.bytes().all(|b| b.is_ascii_hexdigit())); + if numeric { + return Err(format!( + "host {raw:?} is not a DNS name or an IPv4 address in dotted-quad form" + )); + } + if host == "localhost" || host.ends_with(".localhost") { + return Err(format!("host {raw:?} is this machine, not a remote one")); + } + Ok(host) +} + +fn check_address(ip: Ipv4Addr) -> Result<(), String> { + let why = if ip.is_loopback() { + "loopback" + } else if ip.is_link_local() { + "link-local" + } else if ip.octets()[0] == 0 { + "unspecified" + } else if ip.is_multicast() { + "multicast" + } else if ip.octets()[0] >= 240 { + "reserved" + } else { + return Ok(()); + }; + Err(format!("host {ip} is a {why} address")) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn conn(name: &str, user: &str, host: &str, port: u16) -> SshConnection { + SshConnection { + name: name.to_owned(), + user: user.to_owned(), + host: host.to_owned(), + port, + } + } + + fn good() -> SshConnection { + conn("k8s-lab-vm", "root", "muede-pc2", 2222) + } + + #[test] + fn the_operators_example_is_accepted_unchanged() { + assert_eq!(good().checked().unwrap(), good()); + } + + #[test] + fn a_name_is_a_safe_alias() { + for ok in ["a", "0", "k8s-lab-vm", "a-", &"a".repeat(63)] { + assert!( + SshConnection { + name: ok.to_owned(), + ..good() + } + .checked() + .is_ok(), + "{ok}" + ); + } + for bad in [ + "", + "-a", + "A", + "a b", + "a\nHost *", + "a*", + "a!b", + "a.b", + "a_b", + "é", + &"a".repeat(64), + ] { + assert!( + SshConnection { + name: bad.to_owned(), + ..good() + } + .checked() + .is_err(), + "{bad:?}" + ); + } + } + + #[test] + fn a_user_is_a_posix_portable_name() { + for ok in [ + "root", + "a", + "_svc", + "deploy-1", + "first.last", + "A1", + &"u".repeat(32), + ] { + assert!( + SshConnection { + user: ok.to_owned(), + ..good() + } + .checked() + .is_ok(), + "{ok}" + ); + } + for bad in [ + "", + "-oProxyCommand=x", + ".hidden", + "a b", + "a\nb", + "a@b", + "a%h", + "é", + &"u".repeat(33), + ] { + assert!( + SshConnection { + user: bad.to_owned(), + ..good() + } + .checked() + .is_err(), + "{bad:?}" + ); + } + } + + #[test] + fn a_host_is_a_dns_name_or_an_ipv4_address() { + for (raw, stored) in [ + ("muede-pc2", "muede-pc2"), + ("Muede-PC2", "muede-pc2"), + ("box.example.org", "box.example.org"), + ("3d-printer", "3d-printer"), + ("192.168.23.183", "192.168.23.183"), + ("8.8.8.8", "8.8.8.8"), + ] { + let c = SshConnection { + host: raw.to_owned(), + ..good() + }; + assert_eq!(c.checked().unwrap().host, stored, "{raw}"); + } + for bad in [ + "", + "-a", + "a-", + "a..b", + "a.b.", + "a b", + "a\nb", + "a_b", + "a/b", + "user@host", + "host:22", + "::1", + "2001:db8::1", + "localhost", + "x.localhost", + "127.1", + "0x7f.1", + "2130706433", + "1.2.3", + "256.1.1.1", + "é", + ] { + assert!( + SshConnection { + host: bad.to_owned(), + ..good() + } + .checked() + .is_err(), + "{bad:?}" + ); + } + let long = format!( + "{}.{}.{}.{}", + "a".repeat(63), + "b".repeat(63), + "c".repeat(63), + "d".repeat(63) + ); + assert!( + SshConnection { + host: long, + ..good() + } + .checked() + .is_err() + ); + } + + #[test] + fn an_address_no_remote_machine_has_is_refused() { + for bad in [ + "127.0.0.1", + "127.255.255.254", + "169.254.169.254", + "0.0.0.0", + "0.1.2.3", + "224.0.0.1", + "239.255.255.255", + "240.0.0.1", + "255.255.255.255", + ] { + assert!( + SshConnection { + host: bad.to_owned(), + ..good() + } + .checked() + .is_err(), + "{bad}" + ); + } + for ok in ["10.0.0.1", "172.16.0.1", "192.168.23.183", "100.64.0.1"] { + assert!( + SshConnection { + host: ok.to_owned(), + ..good() + } + .checked() + .is_ok(), + "control: {ok}" + ); + } + } + + #[test] + fn a_port_is_1_to_65535_and_not_one_the_hive_intercepts() { + for ok in [1, 22, 79, 81, 442, 444, 2222, 65535] { + assert!( + SshConnection { port: ok, ..good() }.checked().is_ok(), + "{ok}" + ); + } + for bad in [0, 80, 443] { + assert!( + SshConnection { + port: bad, + ..good() + } + .checked() + .is_err(), + "{bad}" + ); + } + assert!( + serde_json::from_str::( + r#"{"name":"a","user":"u","host":"h","port":65536}"# + ) + .is_err(), + "out of range does not decode" + ); + } + + #[test] + fn a_list_has_unique_names_and_a_bound() { + assert!(check_list(&[good(), conn("other", "root", "h", 22)]).is_ok()); + assert!(check_list(&[good(), good()]).unwrap_err().contains("twice")); + let many: Vec<_> = (0..=MAX_CONNECTIONS) + .map(|i| conn(&format!("c{i}"), "root", "h", 22)) + .collect(); + assert!(check_list(&many).is_err()); + assert!( + check_list(&many[..MAX_CONNECTIONS]).is_ok(), + "control: the bound itself" + ); + } +}