teter 26.11.5

teter: persistent terminal sessions on your machines, reachable through a relay that cannot read them
//! `teter signup`, `teter login` and `teter logout`: the account on this
//! device. The password never leaves it: only the auth key derived from it
//! goes to the relay. The unlocked keys and the login token are kept in
//! `$XDG_CONFIG_HOME/teter/account.json`, mode 0600 (the OS keyring is #126).

use std::io::Write as _;
use std::os::unix::fs::{DirBuilderExt, OpenOptionsExt};
use std::path::{Path, PathBuf};

use serde::{Deserialize, Serialize};
use teter_client::account::{self, AccountKeys, DEFAULT_KDF};
use teter_common::account::{AccountReply, AccountRequest};
use zeroize::Zeroizing;

/// Make an account on a relay, and log this device in to it.
#[derive(clap::Args)]
pub struct SignupArgs {
    /// The relay, such as wss://relay.example.com.
    relay: String,

    /// The account's name.
    #[arg(long)]
    name: String,

    /// The invite the relay's admin gave (`teter-relay invite`): signup is
    /// closed without one.
    #[arg(long, env = "TETER_INVITE", hide_env_values = true, default_value = "")]
    invite: String,

    /// PEM file of the CA that signed the relay's certificate, when it does
    /// not chain to the system's roots.
    #[arg(long)]
    ca_cert: Option<PathBuf>,
}

/// Log this device in to an account on a relay.
#[derive(clap::Args)]
pub struct LoginArgs {
    /// The relay, such as wss://relay.example.com.
    relay: String,

    /// The account's name.
    #[arg(long)]
    name: String,

    /// PEM file of the CA that signed the relay's certificate, when it does
    /// not chain to the system's roots.
    #[arg(long)]
    ca_cert: Option<PathBuf>,
}

/// Log this device out: the relay ends its login, and the keys kept here are
/// removed.
#[derive(clap::Args)]
pub struct LogoutArgs {
    /// PEM file of the CA that signed the relay's certificate, when it does
    /// not chain to the system's roots.
    #[arg(long)]
    ca_cert: Option<PathBuf>,
}

/// What this device keeps of its account. The private keys are unlocked:
/// the file is closed to others (mode 0600), like an SSH key.
#[derive(Serialize, Deserialize)]
pub(crate) struct Saved {
    pub(crate) relay: String,
    pub(crate) name: String,
    pub(crate) token: String,
    /// The public keys, hex.
    pub(crate) public_keys: String,
    /// The private keys, hex.
    pub(crate) private_keys: String,
    /// The CA file given at login, if any: `logout` reaches the relay with
    /// it when given none.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub(crate) ca_cert: Option<PathBuf>,
}

/// How long `logout` waits for the relay: the keys here go either way.
const LOGOUT_WAIT: std::time::Duration = std::time::Duration::from_secs(10);

/// How long a new login waits for the relay to end the one it replaces:
/// the new one works already.
const RELOGIN_WAIT: std::time::Duration = std::time::Duration::from_secs(5);

/// The account this device is logged in to.
pub(crate) fn load() -> std::io::Result<Saved> {
    let path = account_file()?;
    match std::fs::read(&path).map(Zeroizing::new) {
        Ok(bytes) => serde_json::from_slice(&bytes).map_err(std::io::Error::other),
        Err(e) if e.kind() == std::io::ErrorKind::NotFound => Err(std::io::Error::other(
            "this device is not logged in: run teter login",
        )),
        Err(e) => Err(e),
    }
}

impl Drop for Saved {
    fn drop(&mut self) {
        zeroize::Zeroize::zeroize(&mut self.private_keys);
        zeroize::Zeroize::zeroize(&mut self.token);
    }
}

/// The file this device keeps its account in.
pub(crate) fn account_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/account.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 account",
        )
    })?;
    Ok(PathBuf::from(home).join(".config/teter/account.json"))
}

/// The password: `TETER_PASSWORD` when set (for scripts), else asked on the
/// terminal without echo; at signup, asked twice.
fn password(prompt: &str, confirm: bool) -> std::io::Result<Zeroizing<String>> {
    if let Ok(password) = std::env::var("TETER_PASSWORD") {
        if password.is_empty() {
            return Err(std::io::Error::other("TETER_PASSWORD is empty"));
        }
        return Ok(Zeroizing::new(password));
    }
    let first = Zeroizing::new(rpassword::prompt_password(prompt)?);
    if confirm {
        let again = Zeroizing::new(rpassword::prompt_password("the same password again: ")?);
        if *first != *again {
            return Err(std::io::Error::other("the two passwords differ"));
        }
    }
    if first.is_empty() {
        return Err(std::io::Error::other("an empty password"));
    }
    Ok(first)
}

/// Makes the account, then logs in.
pub async fn signup(args: SignupArgs) -> std::io::Result<()> {
    let password = password(
        &format!("password for the new account {}: ", args.name),
        true,
    )?;
    let salt = account::new_salt(DEFAULT_KDF)?;
    let derived = account::derive(&password, &salt).map_err(std::io::Error::other)?;
    let keys = AccountKeys::generate()?;
    let request = AccountRequest::Signup {
        name: args.name.clone(),
        salt,
        auth_key: derived.auth_key.to_vec(),
        public_keys: keys.public_keys(),
        wrapped_keys: keys.wrap(&derived, &args.name)?,
        invite: args.invite.clone(),
    };
    let reply = ask(&args.relay, args.ca_cert.as_deref(), &request).await?;
    let AccountReply::SignedUp = reply else {
        return Err(unexpected(&reply));
    };
    log_in(&args.relay, &args.name, &password, args.ca_cert.as_deref()).await?;
    println!("made the account {} and logged in", args.name);
    Ok(())
}

/// Logs in.
pub async fn login(args: LoginArgs) -> std::io::Result<()> {
    let password = password(&format!("password for {}: ", args.name), false)?;
    log_in(&args.relay, &args.name, &password, args.ca_cert.as_deref()).await?;
    println!("logged in to {}", args.name);
    Ok(())
}

/// The salt, the keys derived from `password`, the login, and the keys
/// unwrapped and kept.
async fn log_in(
    relay: &str,
    name: &str,
    password: &str,
    ca_cert: Option<&Path>,
) -> std::io::Result<()> {
    // Absolute, before the relay makes a token: a later command may run
    // from anywhere.
    let ca_cert = ca_cert.map(std::path::absolute).transpose()?;
    let ca_cert = ca_cert.as_deref();
    let reply = ask(
        relay,
        ca_cert,
        &AccountRequest::Salt {
            name: name.to_owned(),
        },
    )
    .await?;
    let AccountReply::Salt { salt } = reply else {
        return Err(unexpected(&reply));
    };
    let derived = account::derive(password, &salt).map_err(std::io::Error::other)?;
    let request = AccountRequest::Login {
        name: name.to_owned(),
        auth_key: derived.auth_key.to_vec(),
    };
    let reply = ask(relay, ca_cert, &request).await?;
    let AccountReply::LoggedIn {
        token,
        public_keys,
        wrapped_keys,
    } = reply
    else {
        return Err(unexpected(&reply));
    };
    let keys = AccountKeys::unwrap(&derived, name, &wrapped_keys, &public_keys)
        .map_err(std::io::Error::other)?;
    // The login this one replaces is ended, not left valid on the relay.
    let before = read_saved();
    save(&Saved {
        relay: relay.to_owned(),
        name: name.to_owned(),
        token,
        public_keys: hex(&public_keys),
        private_keys: hex(keys.private_bytes().as_ref()),
        ca_cert: ca_cert.map(Path::to_path_buf),
    })?;
    if let Ok(Some(before)) = before {
        // The same relay: the CA that just worked, else the one kept with
        // it (a file from before kept none); another relay: its own.
        let same_relay =
            crate::endpoint(&before.relay, "account") == crate::endpoint(relay, "account");
        let ca = if same_relay {
            ca_cert.or(before.ca_cert.as_deref())
        } else {
            before.ca_cert.as_deref()
        };
        match end_login(&before, ca, RELOGIN_WAIT).await {
            Ok(AccountReply::LoggedOut) => {}
            Ok(other) => {
                eprintln!("teter: the relay did not end this device's login before: {other:?}")
            }
            Err(e) => eprintln!("teter: could not end this device's login before: {e}"),
        }
    }
    Ok(())
}

/// The account file's contents, `None` when there is none.
fn read_saved() -> std::io::Result<Option<Saved>> {
    match std::fs::read(account_file()?).map(Zeroizing::new) {
        Ok(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),
    }
}

/// Asks `saved`'s relay to end its login, within `wait`, with `ca_cert`,
/// else the one given at login.
async fn end_login(
    saved: &Saved,
    ca_cert: Option<&Path>,
    wait: std::time::Duration,
) -> std::io::Result<AccountReply> {
    let request = AccountRequest::Logout {
        token: saved.token.clone(),
    };
    let ca_cert = ca_cert.or(saved.ca_cert.as_deref());
    tokio::time::timeout(wait, account::request(&saved.relay, ca_cert, &request))
        .await
        .map_err(|elapsed| std::io::Error::new(std::io::ErrorKind::TimedOut, elapsed))?
        .map_err(std::io::Error::other)
}

/// Logs out: the relay ends the login (if it can be reached), and the file
/// goes.
pub async fn logout(args: LogoutArgs) -> std::io::Result<()> {
    let path = account_file()?;
    let Some(saved) = read_saved()? else {
        return Err(std::io::Error::other("this device is not logged in"));
    };
    let told = end_login(&saved, args.ca_cert.as_deref(), LOGOUT_WAIT).await;
    std::fs::remove_file(&path)?;
    // The secrets of tokens this device made go with the login (#133).
    if let Err(e) = crate::approve::forget_all() {
        eprintln!("teter: could not remove the pending token secrets: {e}");
    }
    match told {
        Ok(AccountReply::LoggedOut) => println!("logged out of {}", saved.name),
        Ok(other) => eprintln!(
            "teter: the relay did not end the login: {other:?}; the keys here are removed"
        ),
        Err(e) => {
            eprintln!("teter: the relay could not be reached ({e}); the keys here are removed")
        }
    }
    Ok(())
}

/// Writes `saved` to the account file, closed to others: a new file renamed
/// over the old one.
fn save(saved: &Saved) -> std::io::Result<()> {
    // Another account (or the same, again): tokens kept for the one before
    // approve nothing here.
    crate::approve::forget_all()?;
    let path = account_file()?;
    if let Some(dir) = path.parent() {
        std::fs::DirBuilder::new()
            .recursive(true)
            .mode(0o700)
            .create(dir)?;
    }
    // This process's own, so two logins at once never share it; a leftover
    // of the same name (a reused PID) would keep its mode: made anew.
    let temporary = path.with_extension(format!("new.{}", std::process::id()));
    match std::fs::remove_file(&temporary) {
        Err(e) if e.kind() != std::io::ErrorKind::NotFound => return Err(e),
        _ => {}
    }
    let mut file = std::fs::OpenOptions::new()
        .create_new(true)
        .write(true)
        .mode(0o600)
        .open(&temporary)?;
    let text = Zeroizing::new(serde_json::to_vec(saved).map_err(std::io::Error::other)?);
    let written = file
        .write_all(&text)
        .and_then(|()| file.sync_all())
        .and_then(|()| std::fs::rename(&temporary, &path));
    if written.is_err() {
        // Not left holding the keys.
        drop(std::fs::remove_file(&temporary));
    }
    written
}

/// The relay's reply to `request`; a refusal is an error, with its reason.
pub(crate) async fn ask(
    relay: &str,
    ca_cert: Option<&Path>,
    request: &AccountRequest,
) -> std::io::Result<AccountReply> {
    let reply = account::request(relay, ca_cert, request)
        .await
        .map_err(std::io::Error::other)?;
    if let AccountReply::Refused { reason } = reply {
        return Err(std::io::Error::other(reason));
    }
    Ok(reply)
}

pub(crate) fn unexpected(reply: &AccountReply) -> std::io::Error {
    std::io::Error::other(format!("the relay answered out of turn: {reply:?}"))
}

fn hex(bytes: &[u8]) -> String {
    bytes.iter().map(|b| format!("{b:02x}")).collect()
}