use std::collections::HashMap;
use std::path::Path;
use anyhow::Result;
use second_brain_core::keys::{
DeviceRecord, DeviceRoute, LegacyRoute, valid_login, valid_machine_id,
};
use second_brain_core::sqlite_store::SqliteStore;
use crate::mdns::{self, Found};
use crate::peers::{self, Peer};
const SSH_PORT: u16 = 22;
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Route {
Device {
machine_id: String,
login: String,
address: String,
port: u16,
},
Line(Peer),
}
impl Route {
pub fn describe(&self) -> String {
match self {
Route::Device {
login,
address,
port,
..
} if *port != SSH_PORT => format!("{login}@{address}:{port}"),
Route::Device { login, address, .. } => format!("{login}@{address}"),
Route::Line(peer) => peer.host.clone(),
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Dial {
pub key: String,
pub label: String,
pub machine_id: Option<String>,
pub routes: Vec<Route>,
}
pub fn dials(store: &SqliteStore, data_dir: &Path) -> Result<Vec<Dial>> {
let mut out = device_dials(store)?;
out.extend(line_dials(store, data_dir)?);
Ok(out)
}
pub fn device_dials(store: &SqliteStore) -> Result<Vec<Dial>> {
let routes: HashMap<String, _> = store
.device_routes()?
.into_iter()
.map(|route| (route.machine_id.clone(), route))
.collect();
let legacy: Vec<(String, LegacyRoute)> = store.legacy_routes()?;
let mut out = Vec::new();
for record in &peer_records(store)? {
let route = routes.get(&record.machine_id);
let login = login_for(record, route, None);
let port = port_for(record, route, None);
let mut tried = Vec::new();
if let (Some(login), Some(route)) = (login, route) {
tried.extend(route.addresses.iter().map(|address| Route::Device {
machine_id: record.machine_id.clone(),
login: login.clone(),
address: address.clone(),
port,
}));
}
tried.extend(
legacy
.iter()
.filter(|(id, _)| *id == record.machine_id)
.map(|(_, line)| {
Route::Line(Peer {
host: line.host.clone(),
sb: line.sb.clone(),
})
}),
);
if tried.is_empty() {
continue;
}
out.push(Dial {
key: record.machine_id.clone(),
label: label(record),
machine_id: Some(record.machine_id.clone()),
routes: tried,
});
}
let labels: Vec<String> = out.iter().map(|dial| dial.label.clone()).collect();
for dial in &mut out {
if labels.iter().filter(|label| **label == dial.label).count() > 1 {
dial.label = format!("{} ({})", dial.label, dial.key);
}
}
Ok(out)
}
pub fn found_dials(store: &SqliteStore, found: &[Found]) -> Result<Vec<Dial>> {
let routes: HashMap<String, DeviceRoute> = store
.device_routes()?
.into_iter()
.map(|route| (route.machine_id.clone(), route))
.collect();
let mut out = Vec::new();
for record in peer_records(store)? {
let route = routes.get(&record.machine_id);
let mut tried: Vec<Route> = Vec::new();
for answer in found
.iter()
.filter(|answer| answer.get(mdns::TXT_ID) == Some(record.machine_id.as_str()))
{
let Some(login) = login_for(&record, route, Some(answer)) else {
continue;
};
let port = port_for(&record, route, Some(answer));
let found_route = Route::Device {
machine_id: record.machine_id.clone(),
login,
address: answer.address.to_string(),
port,
};
if !tried.contains(&found_route) {
tried.push(found_route);
}
}
if !tried.is_empty() {
out.push(Dial {
key: record.machine_id.clone(),
label: label(&record),
machine_id: Some(record.machine_id.clone()),
routes: tried,
});
}
}
Ok(out)
}
pub fn undialled(store: &SqliteStore, dials: &[Dial]) -> Result<bool> {
Ok(peer_records(store)?
.iter()
.any(|record| !dials.iter().any(|dial| dial.key == record.machine_id)))
}
pub fn record_answered(store: &SqliteStore, route: &Route) -> Result<bool> {
let Route::Device {
machine_id,
login,
address,
port,
} = route
else {
return Ok(false);
};
let held = store.device_route(machine_id)?.unwrap_or_default();
if held.addresses.contains(address) {
return Ok(false);
}
let mut addresses = vec![address.clone()];
addresses.extend(held.addresses);
store.set_device_route(DeviceRoute {
machine_id: machine_id.clone(),
addresses,
ssh_login: Some(login.clone()),
ssh_port: Some(*port),
})?;
Ok(true)
}
fn peer_records(store: &SqliteStore) -> Result<Vec<DeviceRecord>> {
let own = store.machine_id().to_string();
let rows = store.device_records()?;
let identity = rows
.iter()
.find(|row| row.current.record.machine_id == own)
.map(|row| row.current.record.identity_tag.clone());
Ok(rows
.into_iter()
.filter(|row| {
let record = &row.current.record;
!row.revoked
&& valid_machine_id(&record.machine_id)
&& record.machine_id != own
&& Some(&record.identity_tag) == identity.as_ref()
})
.map(|row| row.current.record)
.collect())
}
fn login_for(
record: &DeviceRecord,
route: Option<&DeviceRoute>,
answer: Option<&Found>,
) -> Option<String> {
record
.ssh_login
.clone()
.filter(|login| valid_login(login))
.or_else(|| route.and_then(|r| r.ssh_login.clone()))
.or_else(|| {
answer
.and_then(|a| a.get(mdns::TXT_LOGIN))
.filter(|login| valid_login(login))
.map(str::to_string)
})
}
fn port_for(record: &DeviceRecord, route: Option<&DeviceRoute>, answer: Option<&Found>) -> u16 {
record
.ssh_port
.filter(|port| *port != 0)
.or_else(|| route.and_then(|r| r.ssh_port))
.or_else(|| answer.map(|a| a.port).filter(|port| *port != 0))
.unwrap_or(SSH_PORT)
}
fn label(record: &DeviceRecord) -> String {
if record.name.is_empty() {
record.machine_id.clone()
} else {
record.name.clone()
}
}
pub fn line_dials(store: &SqliteStore, data_dir: &Path) -> Result<Vec<Dial>> {
if store.sync_peers_migrated()? {
return Ok(Vec::new());
}
let lines = unmatched_lines(data_dir, &store.legacy_routes()?)?;
if lines.is_empty() {
store.mark_sync_peers_migrated()?;
}
Ok(lines
.into_iter()
.map(|peer| Dial {
key: peer.host.clone(),
label: peer.host.clone(),
machine_id: None,
routes: vec![Route::Line(peer)],
})
.collect())
}
pub fn sync_partners(store: &SqliteStore, data_dir: &Path) -> Result<usize> {
let devices = peer_records(store)?.len();
let lines = if store.sync_peers_migrated()? {
0
} else {
unmatched_lines(data_dir, &store.legacy_routes()?)?.len()
};
Ok(devices + lines)
}
fn unmatched_lines(data_dir: &Path, legacy: &[(String, LegacyRoute)]) -> Result<Vec<Peer>> {
let mut seen = Vec::new();
let mut lines = Vec::new();
for line in peers::configured_peers(data_dir)?.unwrap_or_default() {
let peer = Peer::parse(&line);
if seen.contains(&peer.host) {
continue;
}
seen.push(peer.host.clone());
if !legacy.iter().any(|(_, route)| route.host == peer.host) {
lines.push(peer);
}
}
Ok(lines)
}
pub fn line_answered(store: &SqliteStore, peer: &Peer, machine_id: &str) -> Result<()> {
if store.device_record(machine_id)?.is_none() {
return Ok(());
}
store.set_legacy_route(
machine_id,
&LegacyRoute {
host: peer.host.clone(),
sb: peer.sb.clone(),
},
)
}
pub fn refuse_answer(store: &SqliteStore, dial: &Dial, answered: &str) -> Result<()> {
if let Some(expected) = &dial.machine_id
&& expected != answered
{
anyhow::bail!(
"{} answered as {answered}, not as {expected}; skipping that route",
dial.label
);
}
if store
.device_record(answered)?
.is_some_and(|row| row.revoked)
{
anyhow::bail!(
"{} answered as {answered}, a revoked device; it is not synced with",
dial.label
);
}
Ok(())
}
#[cfg(test)]
mod tests {
use std::collections::BTreeSet;
use second_brain_core::keys::{
DeviceKeys, DeviceRecord, DeviceRoute, admit_device, ensure_device_keys, found_identity,
load_device_keys,
};
use super::*;
use crate::keyring::Keyring;
struct Fixture {
store: SqliteStore,
dir: tempfile::TempDir,
}
impl Fixture {
fn new(others: &[(&str, Option<&str>)]) -> Self {
let named: Vec<(&str, String, Option<&str>)> = others
.iter()
.map(|(id, login)| (*id, format!("{id}-name"), *login))
.collect();
Self::named(&named)
}
fn named(others: &[(&str, String, Option<&str>)]) -> Self {
let dir = tempfile::tempdir().unwrap();
let store = SqliteStore::in_memory("self".to_string()).unwrap();
ensure_device_keys(&store, dir.path()).unwrap();
let device = load_device_keys(dir.path()).unwrap().unwrap();
let founded = found_identity(&store, &device, "self", &[], 1).unwrap();
for (id, name, login) in others {
let keys = DeviceKeys::generate().unwrap();
let record = DeviceRecord {
machine_id: id.to_string(),
identity_tag: founded.tag.as_str().to_string(),
version: 1,
name: name.clone(),
age_recipient: keys.age_recipient().to_string(),
ssh_public_key: keys.ssh_public_key(),
signing_public_key: keys.verifying_key().to_bytes(),
recovery_fingerprints: Vec::new(),
ssh_login: login.map(str::to_string),
ssh_port: login.map(|_| 2222),
ssh_host_key: None,
};
admit_device(&store, &device, record).unwrap();
}
Self { store, dir }
}
fn route(&self, id: &str, addresses: &[&str]) {
self.store
.set_device_route(DeviceRoute {
machine_id: id.to_string(),
addresses: addresses.iter().map(|a| a.to_string()).collect(),
ssh_login: None,
ssh_port: None,
})
.unwrap();
}
fn lines(&self, text: &str) {
std::fs::write(self.dir.path().join(peers::PEERS_FILE), text).unwrap();
}
fn dials(&self) -> Vec<Dial> {
dials(&self.store, self.dir.path()).unwrap()
}
fn revoke(&self, id: &str) {
Keyring::load(&self.store, self.dir.path())
.unwrap()
.remove_device(id, &BTreeSet::new(), 10)
.unwrap();
}
}
fn line(host: &str) -> Route {
Route::Line(Peer {
host: host.to_string(),
sb: "sb".to_string(),
})
}
#[test]
fn an_active_device_is_dialled_at_each_known_address_through_its_signed_login() {
let f = Fixture::new(&[("a", Some("me")), ("b", None)]);
f.route("a", &["192.0.2.1", "a.local"]);
f.route("b", &["192.0.2.2"]);
let dials = f.dials();
assert_eq!(dials.len(), 1, "b has no sshd login and no line: {dials:?}");
assert_eq!(dials[0].key, "a");
assert_eq!(dials[0].label, "a-name");
assert_eq!(
dials[0]
.routes
.iter()
.map(Route::describe)
.collect::<Vec<_>>(),
vec!["me@192.0.2.1:2222", "me@a.local:2222"]
);
}
#[test]
fn a_signed_login_that_ssh_could_misread_is_never_dialled() {
let f = Fixture::new(&[("a", Some("-oProxyCommand=x")), ("b", Some("me"))]);
f.route("a", &["192.0.2.1"]);
f.store
.set_device_route(DeviceRoute {
machine_id: "b".to_string(),
addresses: vec!["192.0.2.2".to_string()],
ssh_login: Some("-oProxyCommand=y".to_string()),
ssh_port: None,
})
.unwrap();
let dials = f.dials();
assert_eq!(
dials.iter().map(|d| d.key.as_str()).collect::<Vec<_>>(),
vec!["b"],
"{dials:?}"
);
assert_eq!(dials[0].routes[0].describe(), "me@192.0.2.2:2222");
}
#[test]
fn devices_with_one_name_get_labels_that_tell_them_apart() {
let f = Fixture::named(&[
("a", "laptop".to_string(), Some("me")),
("b", "laptop".to_string(), Some("me")),
("c", "pi".to_string(), Some("me")),
]);
for id in ["a", "b", "c"] {
f.route(id, &["192.0.2.1"]);
}
assert_eq!(
f.dials()
.iter()
.map(|d| d.label.as_str())
.collect::<Vec<_>>(),
vec!["laptop (a)", "laptop (b)", "pi"]
);
}
#[test]
fn partners_count_every_active_device_and_unmatched_line_without_marking() {
let f = Fixture::new(&[("a", Some("me")), ("b", None), ("c", None)]);
f.revoke("c");
f.lines("me@pi\n");
assert_eq!(sync_partners(&f.store, f.dir.path()).unwrap(), 3);
f.lines("");
assert_eq!(sync_partners(&f.store, f.dir.path()).unwrap(), 2);
assert!(!f.store.sync_peers_migrated().unwrap());
}
#[test]
fn a_signed_row_with_an_unsafe_machine_id_is_neither_dialled_nor_counted() {
let f = Fixture::new(&[("a", Some("me"))]);
f.route("a", &["192.0.2.1"]);
let device = load_device_keys(f.dir.path()).unwrap().unwrap();
let tag = f
.store
.device_record("self")
.unwrap()
.unwrap()
.current
.record
.identity_tag;
let keys = DeviceKeys::generate().unwrap();
for id in ["x\n@cert-authority *", "x\0"] {
let record = DeviceRecord {
machine_id: id.to_string(),
identity_tag: tag.clone(),
version: 1,
name: "planted".to_string(),
age_recipient: keys.age_recipient().to_string(),
ssh_public_key: keys.ssh_public_key(),
signing_public_key: keys.verifying_key().to_bytes(),
recovery_fingerprints: Vec::new(),
ssh_login: Some("me".to_string()),
ssh_port: None,
ssh_host_key: None,
};
f.store
.insert_first_device_record(
&record.sign("self", device.signing_key()),
"self",
&device.verifying_key(),
)
.unwrap();
f.route(id, &["192.0.2.9"]);
}
assert_eq!(
f.dials().iter().map(|d| d.key.as_str()).collect::<Vec<_>>(),
vec!["a"]
);
assert_eq!(sync_partners(&f.store, f.dir.path()).unwrap(), 1);
}
#[test]
fn an_unreadable_sync_peers_leaves_devices_dialled() {
let f = Fixture::new(&[("a", Some("me"))]);
f.route("a", &["192.0.2.1"]);
std::fs::create_dir(f.dir.path().join(peers::PEERS_FILE)).unwrap();
assert!(dials(&f.store, f.dir.path()).is_err());
assert!(line_dials(&f.store, f.dir.path()).is_err());
assert_eq!(
device_dials(&f.store)
.unwrap()
.iter()
.map(|d| d.key.as_str())
.collect::<Vec<_>>(),
vec!["a"]
);
}
#[test]
fn a_revoked_device_is_not_dialled_by_any_route() {
let f = Fixture::new(&[("a", Some("me")), ("b", Some("me"))]);
f.route("a", &["192.0.2.1"]);
f.route("b", &["192.0.2.2"]);
f.lines("me@pi\n");
line_answered(&f.store, &Peer::parse("me@pi"), "b").unwrap();
f.revoke("b");
let dials = f.dials();
assert_eq!(
dials.iter().map(|d| d.key.as_str()).collect::<Vec<_>>(),
vec!["a"]
);
}
#[test]
fn sync_peers_lines_are_dialled_until_each_names_a_device_then_never_read_again() {
let f = Fixture::new(&[("a", None)]);
f.lines("me@pi /opt/sb\nme@mac\nme@pi\n");
let before = f.dials();
assert_eq!(
before.iter().map(|d| d.key.as_str()).collect::<Vec<_>>(),
vec!["me@pi", "me@mac"]
);
assert_eq!(before[0].machine_id, None);
line_answered(&f.store, &Peer::parse("me@pi /opt/sb"), "a").unwrap();
line_answered(&f.store, &Peer::parse("me@mac"), "unknown").unwrap();
let after = f.dials();
assert_eq!(after[0].key, "a");
assert_eq!(
after[0].routes,
vec![Route::Line(Peer::parse("me@pi /opt/sb"))]
);
assert_eq!(after[1].routes, vec![line("me@mac")]);
assert!(!f.store.sync_peers_migrated().unwrap());
f.lines("me@pi\n");
f.dials();
assert!(f.store.sync_peers_migrated().unwrap());
f.lines("me@new\n");
assert_eq!(
f.dials().iter().map(|d| d.key.as_str()).collect::<Vec<_>>(),
vec!["a"]
);
}
#[test]
fn an_answer_from_another_or_a_revoked_device_is_refused() {
let f = Fixture::new(&[("a", Some("me")), ("b", Some("me"))]);
f.route("a", &["192.0.2.1"]);
let dial = f.dials().remove(0);
assert!(refuse_answer(&f.store, &dial, "a").is_ok());
assert!(refuse_answer(&f.store, &dial, "b").is_err());
f.revoke("b");
let unmatched = Dial {
key: "me@old".to_string(),
label: "me@old".to_string(),
machine_id: None,
routes: vec![line("me@old")],
};
assert!(refuse_answer(&f.store, &unmatched, "b").is_err());
assert!(refuse_answer(&f.store, &unmatched, "x").is_ok());
}
fn answer(id: &str, address: &str, login: Option<&str>, port: u16) -> Found {
let mut txt = std::collections::BTreeMap::new();
txt.insert(mdns::TXT_ID.to_string(), id.to_string());
if let Some(login) = login {
txt.insert(mdns::TXT_LOGIN.to_string(), login.to_string());
}
Found {
instance: id.to_string(),
address: address.parse().unwrap(),
port,
txt,
}
}
fn described(dials: &[Dial]) -> Vec<(String, Vec<String>)> {
dials
.iter()
.map(|d| {
(
d.key.clone(),
d.routes.iter().map(Route::describe).collect(),
)
})
.collect()
}
#[test]
fn a_lookup_dials_only_active_devices_of_this_identity_by_their_pinned_id() {
let f = Fixture::new(&[("a", None), ("b", Some("signed")), ("c", None)]);
f.revoke("c");
let found = [
answer("a", "192.0.2.1", Some("me"), 22),
answer("a", "192.0.2.1", Some("me"), 22),
answer("b", "192.0.2.2", Some("advertised"), 2200),
answer("c", "192.0.2.3", Some("me"), 22),
answer("stranger", "192.0.2.4", Some("me"), 22),
answer("self", "192.0.2.5", Some("me"), 22),
answer("a", "192.0.2.6", None, 22),
answer("a", "192.0.2.7", Some("-oProxyCommand=x"), 22),
answer("a", "192.0.2.8", Some("me"), 0),
];
assert_eq!(
described(&found_dials(&f.store, &found).unwrap()),
vec![
(
"a".to_string(),
vec!["me@192.0.2.1".to_string(), "me@192.0.2.8".to_string()]
),
("b".to_string(), vec!["signed@192.0.2.2:2222".to_string()]),
]
);
}
#[test]
fn a_held_login_and_port_win_over_the_adverts() {
let f = Fixture::new(&[("a", None)]);
f.store
.set_device_route(DeviceRoute {
machine_id: "a".to_string(),
addresses: vec!["192.0.2.1".to_string()],
ssh_login: Some("held".to_string()),
ssh_port: Some(2022),
})
.unwrap();
assert_eq!(
described(
&found_dials(
&f.store,
&[answer("a", "192.0.2.9", Some("advertised"), 2200)]
)
.unwrap()
),
vec![("a".to_string(), vec!["held@192.0.2.9:2022".to_string()])]
);
}
#[test]
fn an_address_that_answered_goes_first_once() {
let f = Fixture::new(&[("a", None)]);
f.route("a", &["192.0.2.1"]);
let found = Route::Device {
machine_id: "a".to_string(),
login: "me".to_string(),
address: "192.0.2.9".to_string(),
port: 2200,
};
assert!(record_answered(&f.store, &found).unwrap());
assert_eq!(
f.store.device_route("a").unwrap().unwrap(),
DeviceRoute {
machine_id: "a".to_string(),
addresses: vec!["192.0.2.9".to_string(), "192.0.2.1".to_string()],
ssh_login: Some("me".to_string()),
ssh_port: Some(2200),
}
);
assert!(!record_answered(&f.store, &found).unwrap());
assert!(!record_answered(&f.store, &line("me@pi")).unwrap());
assert_eq!(
described(&device_dials(&f.store).unwrap()),
vec![(
"a".to_string(),
vec![
"me@192.0.2.9:2200".to_string(),
"me@192.0.2.1:2200".to_string()
]
)]
);
}
#[test]
fn an_active_device_without_a_dial_is_undialled() {
let f = Fixture::new(&[("a", Some("me")), ("b", None), ("c", None)]);
f.revoke("c");
f.route("a", &["192.0.2.1"]);
let dials = device_dials(&f.store).unwrap();
assert!(undialled(&f.store, &dials).unwrap(), "b has no route");
f.route("b", &["192.0.2.2"]);
record_answered(
&f.store,
&Route::Device {
machine_id: "b".to_string(),
login: "me".to_string(),
address: "192.0.2.3".to_string(),
port: 22,
},
)
.unwrap();
let dials = device_dials(&f.store).unwrap();
assert!(!undialled(&f.store, &dials).unwrap(), "{dials:?}");
}
}