Watch
0
0
Fork
You've already forked hyperhive
0

agent ssh connections: declare per agent, render into the agent's ssh config

This commit is contained in:
atlas 2026-11-20 01:38:49 +01:00
commit 934da6f31f
16 changed files with 1420 additions and 12 deletions

View file

@ -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 - It signs ed25519 user keys only, and the certificate allows a terminal
(`permit-pty`) and nothing else. (`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 ## Revoking access
- **One agent from one machine:** remove its principal (the `authorizedPrincipals` - **One agent from one machine:** remove its principal (the `authorizedPrincipals`

View file

@ -119,6 +119,46 @@ and attaches it to the agent's cert-auth role `hive-agent-<name>` as a second
NixOS then writes `/etc/ssh/authorized_principals.d/<user>` and sets NixOS then writes `/etc/ssh/authorized_principals.d/<user>` and sets
`AuthorizedPrincipalsFile` to it. `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/<agent>/ssh-connections
PUT /api/agents/<agent>/ssh-connections/<name> {"user":"root","host":"muede-pc2","port":2222}
DELETE /api/agents/<agent>/ssh-connections/<name>
```
`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 ## Not covered
Egress. The default `egress.forward = "log"` lets a direct connection from an Egress. The default `egress.forward = "log"` lets a direct connection from an

View file

@ -31,6 +31,7 @@ mod reminders;
mod router_todos; mod router_todos;
mod schedule_timer; mod schedule_timer;
mod serve_common; mod serve_common;
mod ssh_connections;
mod state_entry_watch; mod state_entry_watch;
mod subagent_role_watch; mod subagent_role_watch;
mod swarm_agent_commands; mod swarm_agent_commands;

View file

@ -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<String>,
failed: Option<String>,
}
/// 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<String> {
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}"
);
}
}

View file

@ -11,6 +11,9 @@
//! ([`BEFORE_FIRST_READ`]), so a queue that is down at start never leaves it //! ([`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 //! 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. //! 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::sync::{PoisonError, RwLock};
use std::time::Duration; use std::time::Duration;
@ -68,8 +71,16 @@ pub async fn run() {
%agent, %agent,
"permissions: holding none (no bash) until the first read of this agent's key succeeds" "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 { loop {
let read = read_once(&client, &agent).await; 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 mut current = CURRENT.write().unwrap_or_else(PoisonError::into_inner);
let next = settle(current.clone(), read); let next = settle(current.clone(), read);

View file

@ -64,6 +64,12 @@ let
# In the state dir, which is bound from the host, so a pin survives a restart. # In the state dir, which is bound from the host, so a pin survives a restart.
knownHostsFile = "/agents/${agentName}/state/ssh_known_hosts"; 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}"; signPath = "${ca.mountPath}/sign/${ca.roleName}";
# A certificate with less than this left is signed again by `ssh`. The timer # 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) { config = lib.mkIf (baoCfg.addr != null) {
# Every host: the certificate, and the pins in the state dir, which outlives # 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 # 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, # runs its command while it reads the config, before it loads any identity,
# and the answer is not used. # and the answer is not used.
programs.ssh.extraConfig = '' programs.ssh.extraConfig = ''
Include ${connectionsFile}
Match exec "HIVE_SSH_CERT_ENSURE=1 ${helper} </dev/null" Match exec "HIVE_SSH_CERT_ENSURE=1 ${helper} </dev/null"
Host * Host *
IdentityFile ${keyFile} IdentityFile ${keyFile}
@ -105,6 +116,14 @@ in
UserKnownHostsFile ${knownHostsFile} UserKnownHostsFile ${knownHostsFile}
''; '';
# The directory and an empty file in it, so that the `Include` above finds
# a file before the harness has read the agent's record. `f` leaves an
# existing file's content alone.
systemd.tmpfiles.rules = [
"d ${connectionsDir} 0755 ${agentName} ${agentName} - -"
"f ${connectionsFile} 0600 ${agentName} ${agentName} - -"
];
systemd.services.${unitName} = { systemd.services.${unitName} = {
description = "sign this agent's SSH key with the swarm's SSH CA"; description = "sign this agent's SSH key with the swarm's SSH CA";
after = [ after = [

View file

@ -598,6 +598,30 @@ let
&& !(lib.hasInfix "StrictHostKeyChecking no" conf) && !(lib.hasInfix "StrictHostKeyChecking no" conf)
&& !(lib.hasInfix "hive-agent-ssh-cert" agentForgeNoBao.environment.etc."ssh/ssh_config".text); && !(lib.hasInfix "hive-agent-ssh-cert" agentForgeNoBao.environment.etc."ssh/ssh_config".text);
} }
{
# The named connections reach `ssh` through an `Include` that comes
# before everything else in the system config: an include below `Host *`
# would sit inside that block, and ssh takes the first value it finds. The
# directory and an empty file exist before the harness writes anything,
# owned by the agent. An agent with no store has neither. Mutant: moving
# the `Include` below `Host *`, or dropping the `f` rule, turns this red.
name = "the ssh config includes the named connections first, and their file exists empty and agent-owned";
ok =
let
conf = agentForgeBao.environment.etc."ssh/ssh_config".text;
noBao = agentForgeNoBao.environment.etc."ssh/ssh_config".text;
include = "Include /run/hive-agent-ssh-connections/config";
rules = agentForgeBao.systemd.tmpfiles.rules;
in
lib.hasInfix include conf
&& !(lib.hasInfix "Host" (lib.head (lib.splitString include conf)))
&& !(lib.hasInfix "Match" (lib.head (lib.splitString include conf)))
&& lib.hasInfix "Match exec" (lib.last (lib.splitString include conf))
&& lib.elem "d /run/hive-agent-ssh-connections 0755 a1 a1 - -" rules
&& lib.elem "f /run/hive-agent-ssh-connections/config 0600 a1 a1 - -" rules
&& !(lib.hasInfix "hive-agent-ssh-connections" noBao)
&& !(lib.any (lib.hasInfix "hive-agent-ssh-connections") agentForgeNoBao.systemd.tmpfiles.rules);
}
{ {
# `ssh` runs the helper before it loads an identity, so the first `ssh` # `ssh` runs the helper before it loads an identity, so the first `ssh`
# after the operator's switch has a certificate. The line comes before the # after the operator's switch has a certificate. The line comes before the

View file

@ -14,3 +14,4 @@ pub mod messages;
pub mod permissions; pub mod permissions;
pub mod schedules; pub mod schedules;
pub mod ssh; pub mod ssh;
pub mod ssh_connections;

View file

@ -0,0 +1,77 @@
//! `/api/agents/{name}/ssh-connections`: the named SSH connections declared for
//! one agent. The agent's ssh config gets one `Host` block for each while its
//! `ssh` switch is on.
use serde::{Deserialize, Serialize};
/// One named connection: `ssh <name>` 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<SshConnection>,
}
#[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::<PutSshConnection>(wire).unwrap(), put);
assert!(
serde_json::from_str::<PutSshConnection>(
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":[]}"#
);
}
}

View file

@ -43,7 +43,8 @@ const MAX_ATTEMPTS: usize = 5;
/// The permissions to store for `req`, whose list is already checked. The list /// The permissions to store for `req`, whose list is already checked. The list
/// replaces the stored one; `unrestricted_internet`, `max_repos` and `ssh` left /// 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_internet` without it turns it off: an agent that moves to
/// unrestricted and back to restricted does not come back logging. /// unrestricted and back to restricted does not come back logging.
fn into_stored(req: Permissions, current: &AgentPermissions) -> AgentPermissions { fn into_stored(req: Permissions, current: &AgentPermissions) -> AgentPermissions {
@ -58,6 +59,7 @@ fn into_stored(req: Permissions, current: &AgentPermissions) -> AgentPermissions
internet_log, internet_log,
max_repos: req.max_repos.or(current.max_repos), max_repos: req.max_repos.or(current.max_repos),
ssh: req.ssh.or(current.ssh), 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<String, (StatusCode, String)> { pub(crate) fn agent_name(name: &str) -> Result<String, (StatusCode, String)> {
hive_types::Ident::parse(name) hive_types::Ident::parse(name)
.map(hive_types::Ident::into_string) .map(hive_types::Ident::into_string)
.map_err(|reason| (StatusCode::BAD_REQUEST, reason.to_owned())) .map_err(|reason| (StatusCode::BAD_REQUEST, reason.to_owned()))
@ -136,7 +138,7 @@ fn agent_name(name: &str) -> Result<String, (StatusCode, String)> {
/// Log a refused `op` on `agent` at `warn` and pass the problem on. The /// Log a refused `op` on `agent` at `warn` and pass the problem on. The
/// handlers have no caller identity; `detail` is the response's. /// 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!( tracing::warn!(
op, op,
agent, agent,
@ -198,12 +200,12 @@ fn hive_names(state: &AppState) -> Vec<String> {
state.hives.iter().map(|h| h.name.clone()).collect() 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"); tracing::warn!(error = %format!("{e:#}"), "agent permissions: queue failure");
error_problem(wanted_error_status(e), &format!("{e:#}")) error_problem(wanted_error_status(e), &format!("{e:#}"))
} }
async fn open_or_create( pub(crate) async fn open_or_create(
client: &async_nats::Client, client: &async_nats::Client,
) -> Result<async_nats::jetstream::kv::Store, ProblemDetails> { ) -> Result<async_nats::jetstream::kv::Store, ProblemDetails> {
agent_permissions::open_or_create(client) agent_permissions::open_or_create(client)
@ -386,16 +388,17 @@ async fn delete_with(
let (current, revision, _) = read_or_default::<AgentPermissions>(&store, &agent) let (current, revision, _) = read_or_default::<AgentPermissions>(&store, &agent)
.await .await
.map_err(|e| queue_problem(&e))?; .map_err(|e| queue_problem(&e))?;
// Only the flags and the repository limit outlive a clear: dropping // Only the flags, the repository limit and the ssh connections outlive a
// `unrestricted_internet` would turn an agent created with `false` on, // clear: dropping `unrestricted_internet` would turn an agent created with
// dropping `internet_log` would turn a logging agent into an enforced // `false` on, dropping `internet_log` would turn a logging agent into an
// one, and a limit is an operator's decision about repositories, not // enforced one, and a limit or a connection is an operator's decision
// part of the permission list. // with its own route, not part of the permission list.
let kept = AgentPermissions { let kept = AgentPermissions {
unrestricted_internet: current.unrestricted_internet, unrestricted_internet: current.unrestricted_internet,
internet_log: current.internet_log, internet_log: current.internet_log,
max_repos: current.max_repos, max_repos: current.max_repos,
ssh: current.ssh, ssh: current.ssh,
ssh_connections: current.ssh_connections.clone(),
..AgentPermissions::default() ..AgentPermissions::default()
}; };
mirror(leaves, &agent, &held(&current), &held(&kept)) mirror(leaves, &agent, &held(&current), &held(&kept))
@ -497,6 +500,7 @@ pub(crate) fn at_create(
internet_log: None, internet_log: None,
max_repos: None, max_repos: None,
ssh: None, ssh: None,
ssh_connections: Vec::new(),
}) })
} }
@ -528,6 +532,7 @@ fn merged_at_create(
}, },
max_repos: value.max_repos.or(current.max_repos), max_repos: value.max_repos.or(current.max_repos),
ssh: value.ssh.or(current.ssh), ssh: value.ssh.or(current.ssh),
ssh_connections: current.ssh_connections.clone(),
} }
} }

View file

@ -88,6 +88,7 @@ mod request_reviewer;
mod review_classifier; mod review_classifier;
mod routes; mod routes;
mod schedules; mod schedules;
mod ssh_connections;
mod startup; mod startup;
mod status; mod status;
mod store; mod store;

View file

@ -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<Stored>) -> 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<AppState>,
Path(name): Path<String>,
) -> Result<Json<SshConnections>, 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::<AgentPermissions>(&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<AppState>,
Path((name, conn)): Path<(String, String)>,
req: Result<Json<PutSshConnection>, JsonRejection>,
) -> Result<Json<SshConnections>, 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::<AgentPermissions>(&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<AppState>,
Path((name, conn)): Path<(String, String)>,
) -> Result<StatusCode, ProblemDetails> {
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::<AgentPermissions>(&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<SshConnections, ProblemDetails> {
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);
}
}

View file

@ -32,7 +32,8 @@ use crate::{
claude_login, config_drift, config_pr, egress_allow, egress_deny, forge, forge_account, claude_login, config_drift, config_pr, egress_allow, egress_deny, forge, forge_account,
github_account, gitlab_account, inference, issue_report, linked_accounts, matrix_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, 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`. /// Where the daemon binds, overridable via `SWARM_CONTROLLER_SOCKET`.
@ -633,6 +634,11 @@ fn permission_routes(router: OpenApiRouter<AppState>) -> OpenApiRouter<AppState>
)) ))
.routes(routes!(agent_permissions::get_permission_catalogue)) .routes(routes!(agent_permissions::get_permission_catalogue))
.routes(routes!(agent_ssh::get_ssh_ca)) .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 /// The routes that write, delete and list an agent's linked accounts and

View file

@ -102,6 +102,13 @@ pub struct AgentPermissions {
/// to the agent's store login role while this is `true`. /// to the agent's store login role while this is `true`.
#[serde(default, skip_serializing_if = "Option::is_none")] #[serde(default, skip_serializing_if = "Option::is_none")]
pub ssh: Option<bool>, pub ssh: Option<bool>,
/// 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<crate::ssh_connection::SshConnection>,
} }
/// What an agent whose record has no `max_repos` may create: no repositories. /// 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); 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<bool>,
}
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::<AgentPermissions>(wire).unwrap(), one);
assert_eq!(serde_json::from_str::<Old>(wire).unwrap().ssh, Some(true));
}
/// The repository limit is left out when unset, so a record that never /// The repository limit is left out when unset, so a record that never
/// named it encodes as before; a negative number (Forgejo's "unlimited") /// named it encodes as before; a negative number (Forgejo's "unlimited")
/// does not decode. /// does not decode.

View file

@ -31,6 +31,7 @@ pub mod review_classifier;
pub mod router_api; pub mod router_api;
pub mod router_sink; pub mod router_sink;
pub mod router_todo; pub mod router_todo;
pub mod ssh_connection;
pub mod stt; pub mod stt;
pub mod subagent_status; pub mod subagent_status;
pub mod subagent_term; pub mod subagent_term;

View file

@ -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 <name>` runs `ssh -p <port> <user>@<host>`.
#[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<Self, String> {
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<String, String> {
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::<Ipv4Addr>() {
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::<SshConnection>(
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"
);
}
}