use std::io::Write as _;
use std::os::unix::fs::{DirBuilderExt, OpenOptionsExt};
use std::path::{Path, PathBuf};
use std::time::{SystemTime, UNIX_EPOCH};
use serde::{Deserialize, Serialize};
use teter_client::account::{self, AccountKeys, MachineKey};
use teter_common::account::{
AccountReply, AccountRequest, MachineInfo, Registration, hex, unhex, unregister_message,
};
use zeroize::Zeroizing;
pub(crate) const NAME_INFO: &[u8] = teter_common::account::MACHINE_NAME_INFO;
#[derive(clap::Args)]
pub struct RegisterArgs {
#[arg(long, env = "TETER_REGISTRATION", hide_env_values = true)]
token: String,
#[arg(long)]
name: Option<String>,
#[arg(long)]
ca_cert: Option<PathBuf>,
}
#[derive(clap::Args)]
pub struct UnregisterArgs {
#[arg(long)]
ca_cert: Option<PathBuf>,
}
#[derive(clap::Args)]
pub struct MachineArgs {
#[command(subcommand)]
command: MachineCommand,
#[arg(long, global = true)]
ca_cert: Option<PathBuf>,
}
#[derive(clap::Subcommand)]
enum MachineCommand {
Ls,
Fingerprint,
Approve {
name: String,
#[arg(long)]
fingerprint: String,
},
Rm {
id: String,
},
}
#[derive(Serialize, Deserialize)]
pub(crate) struct Host {
pub(crate) relay: String,
pub(crate) machine: String,
pub(crate) machine_key: String,
pub(crate) account_keys: String,
}
impl Drop for Host {
fn drop(&mut self) {
zeroize::Zeroize::zeroize(&mut self.machine_key);
}
}
impl Host {
pub(crate) fn key(&self) -> std::io::Result<MachineKey> {
unhex(&self.machine_key)
.map(Zeroizing::new)
.and_then(|seed| MachineKey::from_seed(&seed))
.ok_or_else(|| std::io::Error::other("host.json is damaged: register again"))
}
}
pub(crate) fn host_file() -> std::io::Result<PathBuf> {
let var = |name| std::env::var_os(name).filter(|value| !value.is_empty());
if let Some(config) = var("XDG_CONFIG_HOME") {
return Ok(PathBuf::from(config).join("teter/host.json"));
}
let home = var("HOME").ok_or_else(|| {
std::io::Error::new(
std::io::ErrorKind::NotFound,
"neither XDG_CONFIG_HOME nor HOME is set: no place for the machine's identity",
)
})?;
Ok(PathBuf::from(home).join(".config/teter/host.json"))
}
pub(crate) fn load_host() -> std::io::Result<Option<Host>> {
match std::fs::read(host_file()?) {
Ok(bytes) => {
let bytes = Zeroizing::new(bytes);
serde_json::from_slice(&bytes)
.map(Some)
.map_err(std::io::Error::other)
}
Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(None),
Err(e) => Err(e),
}
}
pub async fn register(args: RegisterArgs) -> std::io::Result<()> {
let path = host_file()?;
if path.exists() {
return Err(std::io::Error::other(
"this machine is registered already: teter unregister first",
));
}
let registration = Registration::parse(&args.token)
.ok_or_else(|| std::io::Error::other("this is not a registration token"))?;
let ca_cert = args.ca_cert.as_deref();
let relay = registration.relay.clone();
let public_keys = checked_account_keys(&relay, ca_cert, ®istration).await?;
let name = match args.name {
Some(name) => name,
None => host_name(),
};
let key = MachineKey::generate()?;
let mut host = Host {
relay: relay.clone(),
machine: String::new(),
machine_key: hex(key.seed().as_ref()),
account_keys: hex(&public_keys),
};
save_host(&path, &host, true)?;
let sealed_name = account::seal_to(&public_keys, NAME_INFO, name.as_bytes())?;
let request = AccountRequest::Register {
secret: account::registration_auth(®istration.secret).to_vec(),
machine_key: key.public_key(),
binding: account::binding_proof(®istration.secret, &key.public_key(), &sealed_name),
sealed_name,
};
let registered = match crate::account::ask(&relay, ca_cert, &request).await {
Ok(AccountReply::Registered { machine }) => Ok(machine),
Ok(reply) => Err(crate::account::unexpected(&reply)),
Err(e) => Err(e),
};
let machine = match registered {
Ok(machine) => machine,
Err(e) => {
drop(std::fs::remove_file(&path));
return Err(e);
}
};
host.machine.clone_from(&machine);
save_host(&path, &host, false).map_err(|e| {
std::io::Error::other(format!(
"registered as {machine}, but could not keep it ({e}): remove it with teter machine \
rm {machine} on a logged-in device, and register again"
))
})?;
announce_registered(&path, &name, &machine, &key.public_key());
Ok(())
}
fn announce_registered(path: &Path, name: &str, machine: &str, public_key: &[u8]) {
let next = start_link_service(path).map_or_else(
|| "run teter link to serve it".to_owned(),
|service| format!("started its link ({service})"),
);
println!("registered this machine as {name} ({machine}); {next}");
println!(
"its key's fingerprint: {} (the device that made the token approves it on its own; \
another approves it with teter machine approve {name} --fingerprint <it>)",
hex(&account::fingerprint(public_key))
);
}
fn start_link_service(registered: &Path) -> Option<String> {
let home = std::env::var_os("HOME").filter(|home| !home.is_empty())?;
if registered != Path::new(&home).join(".config/teter/host.json") {
return None;
}
let run = |program: &str, args: &[&str]| {
std::process::Command::new(program)
.args(args)
.stdin(std::process::Stdio::null())
.stdout(std::process::Stdio::null())
.stderr(std::process::Stdio::null())
.status()
.is_ok_and(|status| status.success())
};
if cfg!(target_os = "macos") {
let domain = format!("gui/{}", rustix::process::getuid().as_raw());
[
"br.tec.ars.teter-link",
"sh.brew.teter",
"homebrew.mxcl.teter",
]
.into_iter()
.map(|label| format!("{domain}/{label}"))
.find(|target| {
run("launchctl", &["print", target]) && run("launchctl", &["kickstart", target])
})
.map(|target| format!("launchctl kickstart {target}"))
} else {
["teter-link", "homebrew.teter"]
.into_iter()
.find(|unit| {
run("systemctl", &["--user", "is-enabled", "--quiet", unit])
&& run("systemctl", &["--user", "start", unit])
})
.map(|unit| format!("systemctl --user start {unit}"))
}
}
async fn checked_account_keys(
relay: &str,
ca_cert: Option<&Path>,
registration: &Registration,
) -> std::io::Result<Vec<u8>> {
let request = AccountRequest::TokenKeys {
secret: account::registration_auth(®istration.secret).to_vec(),
};
let reply = crate::account::ask(relay, ca_cert, &request).await?;
let AccountReply::AccountKeys { public_keys } = reply else {
return Err(crate::account::unexpected(&reply));
};
if account::fingerprint(&public_keys) != registration.fingerprint {
return Err(std::io::Error::other(
"the relay gave account keys that do not match the token's fingerprint: refusing to \
register (the relay, or something between, may be swapping the account's keys)",
));
}
Ok(public_keys)
}
pub async fn unregister(args: UnregisterArgs) -> std::io::Result<()> {
let host =
load_host()?.ok_or_else(|| std::io::Error::other("this machine is not registered"))?;
let at = now();
let request = AccountRequest::Unregister {
machine: host.machine.clone(),
at,
signature: host.key()?.sign(&unregister_message(&host.machine, at)),
};
let reply = crate::account::ask(&host.relay, args.ca_cert.as_deref(), &request).await?;
let AccountReply::MachineRemoved { removed } = reply else {
return Err(crate::account::unexpected(&reply));
};
std::fs::remove_file(host_file()?)?;
if removed {
println!("unregistered this machine");
} else {
println!("the relay had forgotten this machine already; its identity here is removed");
}
Ok(())
}
pub async fn machine(args: MachineArgs) -> std::io::Result<()> {
if matches!(args.command, MachineCommand::Fingerprint) {
let host = load_host()?
.filter(|host| !host.machine.is_empty())
.ok_or_else(|| std::io::Error::other("this machine is not registered"))?;
println!("{}", hex(&account::fingerprint(&host.key()?.public_key())));
return Ok(());
}
let saved = crate::account::load().await?;
let ca_cert = args.ca_cert.as_deref();
let keys = unhex(&saved.private_keys)
.map(Zeroizing::new)
.and_then(|private| AccountKeys::from_private_bytes(&private))
.ok_or_else(|| std::io::Error::other("the saved account is damaged: log in again"))?;
let mut machines = list(&saved, ca_cert).await?;
if crate::approve::pending_machines(&saved, &keys, ca_cert, &machines).await? > 0 {
machines = list(&saved, ca_cert).await?;
}
let name_of = |machine: &MachineInfo| {
keys.open_sealed(NAME_INFO, &machine.sealed_name)
.ok()
.and_then(|name| String::from_utf8(name.to_vec()).ok())
};
match args.command {
MachineCommand::Fingerprint => Ok(()),
MachineCommand::Approve { name, fingerprint } => {
let matching: Vec<&MachineInfo> = machines
.iter()
.filter(|machine| name_of(machine).as_deref() == Some(name.as_str()))
.collect();
approve_named(&saved, &keys, ca_cert, &name, &matching, &fingerprint).await
}
MachineCommand::Ls => {
ls(&keys, &machines);
Ok(())
}
MachineCommand::Rm { id } => rm(&saved, ca_cert, &machines, &id).await,
}
}
async fn rm(
saved: &crate::account::Saved,
ca_cert: Option<&Path>,
machines: &[MachineInfo],
id: &str,
) -> std::io::Result<()> {
let id = id.to_ascii_lowercase();
let matching: Vec<&MachineInfo> = machines
.iter()
.filter(|machine| !id.is_empty() && machine.id.starts_with(&id))
.collect();
let [machine] = matching[..] else {
return Err(std::io::Error::other(if matching.is_empty() {
format!("no machine's ID starts with {id:?}")
} else {
format!("more than one machine's ID starts with {id}: give more of it")
}));
};
let request = AccountRequest::MachineRemove {
login: saved.token.clone(),
id: machine.id.clone(),
};
let reply = crate::account::ask_as(saved, ca_cert, &request).await?;
let AccountReply::MachineRemoved { removed } = reply else {
return Err(crate::account::unexpected(&reply));
};
println!(
"{} {}",
if removed { "removed" } else { "already gone:" },
short(&machine.id)
);
Ok(())
}
async fn approve_named(
saved: &crate::account::Saved,
keys: &AccountKeys,
ca_cert: Option<&Path>,
name: &str,
matching: &[&MachineInfo],
fingerprint: &str,
) -> std::io::Result<()> {
let Some(first) = matching.first() else {
return Err(std::io::Error::other(format!(
"no machine named {name:?} in this account"
)));
};
let machine = matching
.iter()
.find(|machine| {
teter_common::account::hex(&account::fingerprint(&machine.public_key))
.eq_ignore_ascii_case(fingerprint.trim())
})
.unwrap_or(first);
crate::approve::by_fingerprint(saved, keys, ca_cert, machine, fingerprint).await?;
println!("approved {name}");
Ok(())
}
fn ls(keys: &AccountKeys, machines: &[MachineInfo]) {
if machines.is_empty() {
println!("no machines");
}
for machine in machines {
let name = keys
.open_sealed(NAME_INFO, &machine.sealed_name)
.ok()
.and_then(|name| String::from_utf8(name.to_vec()).ok())
.unwrap_or_else(|| "(a name that does not open)".to_owned());
let seen = match machine.last_seen {
Some(at) => format!("last connected {}s ago", now().saturating_sub(at).max(0)),
None => "never connected".to_owned(),
};
let approval = if crate::approve::approved(keys, machine) {
""
} else {
" (not approved: teter machine approve)"
};
println!("{} {name} {seen}{approval}", short(&machine.id));
}
}
async fn list(
saved: &crate::account::Saved,
ca_cert: Option<&Path>,
) -> std::io::Result<Vec<MachineInfo>> {
let request = AccountRequest::MachineList {
login: saved.token.clone(),
};
let reply = crate::account::ask_as(saved, ca_cert, &request).await?;
let AccountReply::Machines { machines } = reply else {
return Err(crate::account::unexpected(&reply));
};
Ok(machines)
}
pub(crate) fn save_account_keys(keys: &[u8]) -> std::io::Result<()> {
let path = host_file()?;
let mut host = load_host()?
.ok_or_else(|| std::io::Error::other("this machine is not registered any more"))?;
host.account_keys = hex(keys);
save_host(&path, &host, false)
}
fn save_host(path: &Path, host: &Host, new: bool) -> std::io::Result<()> {
if let Some(dir) = path.parent() {
std::fs::DirBuilder::new()
.recursive(true)
.mode(0o700)
.create(dir)?;
}
let target = if new {
path.to_owned()
} else {
let temporary = path.with_extension("new");
drop(std::fs::remove_file(&temporary));
temporary
};
let mut file = std::fs::OpenOptions::new()
.create_new(true)
.write(true)
.mode(0o600)
.open(&target)?;
let text = Zeroizing::new(serde_json::to_vec(host).map_err(std::io::Error::other)?);
file.write_all(&text)?;
file.sync_all()?;
if new {
Ok(())
} else {
std::fs::rename(&target, path)
}
}
fn host_name() -> String {
std::fs::read_to_string("/etc/hostname")
.ok()
.map(|name| name.trim().to_owned())
.filter(|name| !name.is_empty())
.or_else(|| std::env::var("HOSTNAME").ok())
.unwrap_or_else(|| "machine".to_owned())
}
fn short(id: &str) -> &str {
id.get(..12).unwrap_or(id)
}
fn now() -> i64 {
SystemTime::now()
.duration_since(UNIX_EPOCH)
.map_or(0, |since| {
i64::try_from(since.as_secs()).unwrap_or(i64::MAX)
})
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn an_identity_the_services_do_not_read_starts_no_service() {
assert_eq!(
start_link_service(Path::new("/elsewhere/teter/host.json")),
None
);
}
}