agent ssh connections: declare per agent, render into the agent's ssh config
This commit is contained in:
parent
844fb0a219
commit
934da6f31f
3 changed files with 1420 additions and 12 deletions
|
|
@ -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<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.
|
||||
|
|
@ -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<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
|
||||
/// named it encodes as before; a negative number (Forgejo's "unlimited")
|
||||
/// does not decode.
|
||||
|
|
|
|||
|
|
@ -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;
|
||||
|
|
|
|||
437
swarm-wire/src/ssh_connection.rs
Normal file
437
swarm-wire/src/ssh_connection.rs
Normal 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"
|
||||
);
|
||||
}
|
||||
}
|
||||
Loading…
Reference in a new issue