use std::collections::BTreeMap;
use std::path::PathBuf;
use super::{Module, tunnelled, vm_named};
use crate::Result;
use crate::ssh::Login;
const VIA_OUTPUT: &str = "ip";
pub(crate) const JUMP_VAR: &str = "ssh_jump";
pub(crate) const JUMP_KNOWN_HOSTS_VAR: &str = "ssh_jump_known_hosts_file";
#[derive(Debug, Clone, PartialEq, Eq)]
pub(super) struct Route {
pub(super) hops: Vec<Login>,
pub(super) to: Login,
pub(super) key: PathBuf,
pub(super) jump_known_hosts: Option<PathBuf>,
}
impl Route {
pub(super) fn first(&self) -> &Login {
self.hops.first().unwrap_or(&self.to)
}
pub(super) async fn options(&self, module: &Module<'_, '_>) -> Result<Vec<String>> {
let cx = module.cx;
let first = crate::ssh::First::given(self.jump_known_hosts.as_deref());
crate::ssh::ready(cx.processes, cx.state_dir, &self.first().host, first).await?;
crate::ssh::options_through(&self.key, cx.state_dir, &self.hops, first)
}
}
pub(super) async fn to(module: &Module<'_, '_>, machine: &str, user: Option<&str>) -> Result<std::result::Result<Route, String>> {
let cx = module.cx;
let state = module.state()?;
let held = module.shown(state).await?;
let vm = vm_named(cx, &held, machine)?;
if vm.vm.windows {
return Ok(Err("it runs Windows: its screen is its Remote Desktop".to_owned()));
}
let out = tunnelled::outputs(module, state).await?;
let jump = cx.var(JUMP_VAR);
let jump_known_hosts = jump.as_ref().and(cx.var(JUMP_KNOWN_HOSTS_VAR)).map(PathBuf::from);
Ok(route(&out, vm.vm.address.as_deref(), machine, user, jump.as_deref()).map(|(hops, to)| Route {
hops,
to,
key: cx.var(tunnelled::KEY_VAR).map_or_else(|| cx.ssh_key.to_path_buf(), PathBuf::from),
jump_known_hosts,
}))
}
fn route(
out: &BTreeMap<String, String>,
stated: Option<&str>,
machine: &str,
user: Option<&str>,
jump: Option<&str>,
) -> std::result::Result<(Vec<Login>, Login), String> {
let (address, behind) = match (out.get(&format!("address_{machine}")), tunnelled::named_address(out, machine)) {
(Some(address), _) => (address.clone(), false),
(None, Some(address)) => (address, true),
(None, None) => (
stated
.map(str::to_owned)
.ok_or_else(|| format!("neither its state nor the module's outputs (`address_{machine}`, `machines`) give it an address"))?,
false,
),
};
let mut hops = Vec::new();
if let Some(jump) = jump {
let (jump_user, jump_host) = jump
.split_once('@')
.ok_or_else(|| format!("the run's `{JUMP_VAR}` value `{}` isn't `user@host`", jump.escape_debug()))?;
hops.push(Login::new(jump_user, jump_host).ok_or_else(|| format!("the run's `{JUMP_VAR}` value `{}` isn't an SSH login", jump.escape_debug()))?);
}
if behind {
let via = out
.get(VIA_OUTPUT)
.ok_or_else(|| format!("the module names no machine to reach {address} through (its `{VIA_OUTPUT}` output)"))?;
if *via != address {
let login = tunnelled::user_at(out, via)
.and_then(|u| Login::new(&u, via))
.ok_or_else(|| format!("the module names no SSH user on {via}, the machine {address} is reached through (`ssh_user`)"))?;
hops.push(login);
}
}
let user = user
.map(str::to_owned)
.or_else(|| out.get(&format!("ssh_user_{machine}")).cloned())
.or_else(|| tunnelled::user_at(out, &address))
.ok_or_else(|| format!("the module names no SSH user for it (`ssh_user_{machine}`, `ssh_user`)"))?;
let to = Login::new(&user, &address).ok_or_else(|| format!("`{}@{}` isn't an SSH login", user.escape_debug(), address.escape_debug()))?;
Ok((hops, to))
}
#[cfg(test)]
mod tests {
use super::*;
fn outputs(pairs: &[(&str, &str)]) -> BTreeMap<String, String> {
pairs.iter().map(|(k, v)| ((*k).to_owned(), (*v).to_owned())).collect()
}
fn targets(route: &(Vec<Login>, Login)) -> Vec<String> {
route.0.iter().chain(std::iter::once(&route.1)).map(Login::target).collect()
}
fn behind_a_router() -> BTreeMap<String, String> {
outputs(&[
("ip", "192.0.2.10"),
("ssh_user", "ops"),
("machines", r#"{"web":"10.60.0.10","cache":"10.60.0.20"}"#),
])
}
#[test]
fn a_machine_on_the_modules_networks_is_reached_through_its_router_and_the_runs_jump_first() {
let out = behind_a_router();
assert_eq!(
targets(&route(&out, None, "web", None, None).expect("a route")),
["ops@192.0.2.10", "ops@10.60.0.10"]
);
assert_eq!(
targets(&route(&out, None, "web", Some("admin"), Some("root@node.stack")).expect("a route")),
["root@node.stack", "ops@192.0.2.10", "admin@10.60.0.10"],
"the jump first, the router as its own user, the machine as the user asked for"
);
assert_eq!(
targets(&route(&out, Some("192.0.2.10"), "router", None, Some("root@node.stack")).expect("a route")),
["root@node.stack", "ops@192.0.2.10"]
);
}
#[test]
fn a_machine_at_an_address_of_its_own_is_reached_straight() {
let out = outputs(&[
("ip", "203.0.113.7"),
("address_web", "203.0.113.9"),
("ssh_user_web", "admin"),
("machines", r#"{"web":"203.0.113.9"}"#),
]);
assert_eq!(targets(&route(&out, None, "web", None, None).expect("a route")), ["admin@203.0.113.9"]);
let plain = outputs(&[("ssh_user", "debian")]);
assert_eq!(
targets(&route(&plain, Some("198.51.100.4"), "db", None, None).expect("a route")),
["debian@198.51.100.4"]
);
let at_ip = outputs(&[("ip", "10.60.0.10"), ("ssh_user", "ops"), ("machines", r#"{"web":"10.60.0.10"}"#)]);
assert_eq!(targets(&route(&at_ip, None, "web", None, None).expect("a route")), ["ops@10.60.0.10"]);
}
#[test]
fn a_route_that_cant_be_made_says_why() {
let out = behind_a_router();
let why = |r: std::result::Result<(Vec<Login>, Login), String>| r.expect_err("no route");
assert!(why(route(&out, None, "db", None, None)).contains("give it an address"));
assert!(why(route(&outputs(&[("machines", r#"{"web":"10.60.0.10"}"#)]), None, "web", None, None)).contains("`ip` output"));
assert!(why(route(&out, None, "web", None, Some("node.stack"))).contains("isn't `user@host`"));
assert!(why(route(&out, None, "web", None, Some("root@-oProxyCommand=x"))).contains("isn't an SSH login"));
let no_user = outputs(&[("machines", r#"{"web":"10.60.0.10"}"#), ("ip", "10.60.0.10")]);
assert!(why(route(&no_user, None, "web", None, None)).contains("no SSH user"));
}
}