teter 26.11.5

teter: persistent terminal sessions on your machines, reachable through a relay that cannot read them
//! The account's approval of its machines (#133). The device that made a
//! registration token keeps its secret until it expires; a machine that
//! registered with it left a proof on the relay (an HMAC under a key derived
//! from the secret, which the relay never saw), so this device approves it
//! by signing its ID, key and sealed name with the account's key. Devices
//! trust only approved machines, their names and their signed records. A
//! machine registered before, or with a token another device made, is
//! approved by hand against the fingerprint it shows (`teter machine
//! fingerprint` on it).

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;

/// A token this device made and has not seen expire.
#[derive(Serialize, Deserialize)]
struct Pending {
    /// Its secret, hex.
    secret: String,
    /// When it stops working (Unix seconds).
    expires: i64,
}

/// The file of the tokens this device made: beside the account, 0600.
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)
        })
}

/// The tokens this device made that still work.
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(()),
        };
    }
    // A name of its own: two commands writing at once do not share one.
    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)
}

/// Keeps the secret of a token this device just made, until it expires.
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)
}

/// Forgets the secret of the token whose relay ID is `id` (revoked: it must
/// approve nothing any more).
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)
}

/// Forgets every token's secret (logged out, or another account now).
pub fn forget_all() -> std::io::Result<()> {
    write_pending(&[])
}

/// Whether this device holds a token's secret it could approve with.
pub fn has_pending() -> bool {
    !pending().is_empty()
}

/// Whether `machine` carries the account's approval.
pub fn approved(keys: &AccountKeys, machine: &MachineInfo) -> bool {
    account::cert_holds(
        &keys.public_keys(),
        &machine.id,
        &machine.public_key,
        &machine.sealed_name,
        &machine.cert,
    )
}

/// Signs and sends the account's approval of `machine`.
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",
        ))
    }
}

/// Approves each machine in `machines` not approved yet whose proof one of
/// this device's tokens holds; how many.
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 {
            // A failure here (the machine removed meanwhile, say) must not
            // stop what the user asked for.
            match approve(saved, keys, ca_cert, machine).await {
                Ok(()) => done += 1,
                Err(e) => eprintln!("teter: could not approve machine {}: {e}", machine.id),
            }
        }
    }
    // Nothing written back: a command running meanwhile (a revoke, a
    // logout, a new token) changes the file; expired ones are skipped when
    // read, and go with the next change.
    Ok(done)
}

/// Approves `machine` by hand, if its key's fingerprint is `fingerprint`.
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
}