use std::io::Write as _;
use std::os::unix::fs::OpenOptionsExt as _;
use std::path::{Path, PathBuf};
use serde::{Deserialize, Serialize};
use teter_client::account::{self, AccountKeys};
use teter_common::account::{AccountReply, AccountRequest, MachineInfo, hex, unhex};
use zeroize::Zeroizing;
#[derive(Serialize, Deserialize)]
struct Pending {
secret: String,
expires: i64,
}
fn pending_file() -> std::io::Result<PathBuf> {
Ok(crate::account::account_file()?.with_file_name("pending-tokens.json"))
}
fn now() -> i64 {
std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map_or(0, |since| {
i64::try_from(since.as_secs()).unwrap_or(i64::MAX)
})
}
fn pending() -> Vec<Pending> {
let Ok(path) = pending_file() else {
return Vec::new();
};
let Ok(bytes) = std::fs::read(&path).map(Zeroizing::new) else {
return Vec::new();
};
let now = now();
serde_json::from_slice::<Vec<Pending>>(&bytes)
.unwrap_or_default()
.into_iter()
.filter(|token| token.expires > now)
.collect()
}
fn write_pending(tokens: &[Pending]) -> std::io::Result<()> {
let path = pending_file()?;
if tokens.is_empty() {
return match std::fs::remove_file(&path) {
Err(e) if e.kind() != std::io::ErrorKind::NotFound => Err(e),
_ => Ok(()),
};
}
let temporary = path.with_extension(format!("new{}", std::process::id()));
let text = Zeroizing::new(serde_json::to_vec(tokens).map_err(std::io::Error::other)?);
let mut file = std::fs::OpenOptions::new()
.create(true)
.truncate(true)
.write(true)
.mode(0o600)
.open(&temporary)?;
file.write_all(&text)?;
file.sync_all()?;
std::fs::rename(&temporary, &path)
}
pub fn remember(secret: &[u8], expires_in: u64) -> std::io::Result<()> {
let mut tokens = pending();
tokens.push(Pending {
secret: hex(secret),
expires: now().saturating_add(i64::try_from(expires_in).unwrap_or(i64::MAX)),
});
write_pending(&tokens)
}
pub fn forget(id: &str) -> std::io::Result<()> {
let tokens: Vec<Pending> = pending()
.into_iter()
.filter(|token| {
unhex(&token.secret).is_none_or(|secret| {
hex(&account::secret_hash(
account::registration_auth(&secret).as_ref(),
)) != id
})
})
.collect();
write_pending(&tokens)
}
pub fn forget_all() -> std::io::Result<()> {
write_pending(&[])
}
pub fn has_pending() -> bool {
!pending().is_empty()
}
pub fn approved(keys: &AccountKeys, machine: &MachineInfo) -> bool {
account::cert_holds(
&keys.public_keys(),
&machine.id,
&machine.public_key,
&machine.sealed_name,
&machine.cert,
)
}
async fn approve(
saved: &crate::account::Saved,
keys: &AccountKeys,
ca_cert: Option<&Path>,
machine: &MachineInfo,
) -> std::io::Result<()> {
let cert = keys.sign(&teter_common::account::cert_bytes(
&machine.id,
&machine.public_key,
&machine.sealed_name,
));
let request = AccountRequest::MachineApprove {
login: saved.token.clone(),
id: machine.id.clone(),
cert,
};
let reply = crate::account::ask(&saved.relay, ca_cert, &request).await?;
let AccountReply::MachineApproved { approved } = reply else {
return Err(crate::account::unexpected(&reply));
};
if approved {
Ok(())
} else {
Err(std::io::Error::other(
"the relay no longer has that machine",
))
}
}
pub async fn pending_machines(
saved: &crate::account::Saved,
keys: &AccountKeys,
ca_cert: Option<&Path>,
machines: &[MachineInfo],
) -> std::io::Result<usize> {
let tokens = pending();
let mut done = 0;
for machine in machines.iter().filter(|machine| !approved(keys, machine)) {
let proven = tokens.iter().any(|token| {
unhex(&token.secret)
.map(Zeroizing::new)
.is_some_and(|secret| {
!machine.binding.is_empty()
&& account::binding_proof(
&secret,
&machine.public_key,
&machine.sealed_name,
) == machine.binding
})
});
if proven {
match approve(saved, keys, ca_cert, machine).await {
Ok(()) => done += 1,
Err(e) => eprintln!("teter: could not approve machine {}: {e}", machine.id),
}
}
}
Ok(done)
}
pub async fn by_fingerprint(
saved: &crate::account::Saved,
keys: &AccountKeys,
ca_cert: Option<&Path>,
machine: &MachineInfo,
fingerprint: &str,
) -> std::io::Result<()> {
let actual = hex(&account::fingerprint(&machine.public_key));
if !actual.eq_ignore_ascii_case(fingerprint.trim()) {
return Err(std::io::Error::other(format!(
"the relay's key for that machine has fingerprint {actual}, not {fingerprint}: not \
approved (check `teter machine fingerprint` on it)"
)));
}
approve(saved, keys, ca_cert, machine).await
}