teter 26.11.7

teter: persistent terminal sessions on your machines, reachable through a relay that cannot read them
//! `teter token create`, `ls` and `revoke`: registration tokens, made by the
//! logged-in account and used once on a machine to register it (#86), like a
//! GitLab runner's. The relay keeps only the hash of a token's secret.

use std::path::PathBuf;
use std::time::{SystemTime, UNIX_EPOCH};

use teter_client::account;
use teter_common::account::{
    AccountReply, AccountRequest, MAX_TOKEN_LIFETIME, Registration, TokenInfo, unhex,
};

/// Registration tokens, to register machines with the account.
#[derive(clap::Args)]
pub struct TokenArgs {
    #[command(subcommand)]
    command: TokenCommand,

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

#[derive(clap::Subcommand)]
enum TokenCommand {
    /// Make a registration token, and print it (once: the relay keeps only
    /// its hash).
    Create {
        /// How many machines it registers.
        #[arg(long, default_value_t = 1)]
        uses: u32,
        /// How long it works: seconds, or a number and s, m, h or d.
        #[arg(long, default_value = "1h", value_parser = parse_duration)]
        expires: u64,
    },
    /// List the account's registration tokens.
    Ls,
    /// Revoke a registration token, by its ID (or the start of it).
    Revoke {
        /// The token's ID, as `teter token ls` shows it.
        id: String,
    },
}

/// Runs the token command.
pub async fn token(args: TokenArgs) -> std::io::Result<()> {
    let saved = crate::account::load().await?;
    let ca_cert = args.ca_cert.as_deref();
    match args.command {
        TokenCommand::Create { uses, expires } => create(&saved, ca_cert, uses, expires).await,
        TokenCommand::Ls => ls(&saved, ca_cert).await,
        TokenCommand::Revoke { id } => revoke(&saved, ca_cert, &id).await,
    }
}

/// Makes a token and prints it.
async fn create(
    saved: &crate::account::Saved,
    ca_cert: Option<&std::path::Path>,
    uses: u32,
    expires: u64,
) -> std::io::Result<()> {
    let mut secret = zeroize::Zeroizing::new([0_u8; 32]);
    getrandom::fill(secret.as_mut()).map_err(std::io::Error::other)?;
    let public_keys = unhex(&saved.public_keys)
        .ok_or_else(|| std::io::Error::other("the saved account is damaged: log in again"))?;
    // Kept before the relay makes the token: a token it made that this
    // device could not keep would be live and never shown.
    crate::approve::remember(&*secret, expires)?;
    let request = AccountRequest::TokenCreate {
        login: saved.token.clone(),
        // A key derived from the secret goes to the relay; the secret stays
        // here, to approve the machine that registers with it (#133).
        secret_hash: account::secret_hash(account::registration_auth(&*secret).as_ref()),
        expires_in: expires,
        uses,
    };
    let reply = crate::account::ask_as(saved, ca_cert, &request).await?;
    let AccountReply::TokenCreated = reply else {
        return Err(crate::account::unexpected(&reply));
    };
    let registration = Registration {
        relay: saved.relay.clone(),
        secret: *secret,
        fingerprint: account::fingerprint(&public_keys),
    };
    println!("{}", *zeroize::Zeroizing::new(registration.to_text()));
    eprintln!(
        "registers {uses} machine{} within {}: on the machine, run \
         teter register --token <the token above>",
        if uses == 1 { "" } else { "s" },
        shown_duration(expires)
    );
    Ok(())
}

/// Lists the tokens.
async fn ls(
    saved: &crate::account::Saved,
    ca_cert: Option<&std::path::Path>,
) -> std::io::Result<()> {
    let (tokens, now) = list(saved, ca_cert).await?;
    if tokens.is_empty() {
        println!("no registration tokens");
    }
    for token in tokens {
        let state = if token.expires <= now {
            "expired".to_owned()
        } else if token.uses_left <= 0 {
            "used up".to_owned()
        } else {
            format!(
                "{} use{} left, expires in {}",
                token.uses_left,
                if token.uses_left == 1 { "" } else { "s" },
                shown_duration(u64::try_from(token.expires - now).unwrap_or(0))
            )
        };
        println!("{}  {state}", short(&token.id));
    }
    Ok(())
}

/// Revokes the one token whose ID starts with `id`.
async fn revoke(
    saved: &crate::account::Saved,
    ca_cert: Option<&std::path::Path>,
    id: &str,
) -> std::io::Result<()> {
    let id = id.to_ascii_lowercase();
    if id.is_empty() || !id.bytes().all(|b| b.is_ascii_hexdigit()) {
        return Err(std::io::Error::other(
            "give the token's ID, or the start of it, as teter token ls shows it",
        ));
    }
    let (tokens, _) = list(saved, ca_cert).await?;
    let matching: Vec<&TokenInfo> = tokens
        .iter()
        .filter(|token| token.id.starts_with(&id))
        .collect();
    let [token] = matching[..] else {
        return Err(std::io::Error::other(if matching.is_empty() {
            format!("no registration token starts with {id}")
        } else {
            format!("more than one registration token starts with {id}: give more of it")
        }));
    };
    let request = AccountRequest::TokenRevoke {
        login: saved.token.clone(),
        id: token.id.clone(),
    };
    let reply = crate::account::ask_as(saved, ca_cert, &request).await?;
    let AccountReply::TokenRevoked { revoked } = reply else {
        return Err(crate::account::unexpected(&reply));
    };
    // Revoked, it approves nothing either (#133): a machine that registered
    // with it and is not approved yet (a leaked token's, say) is approved
    // only by hand, against its fingerprint.
    crate::approve::forget(&token.id)?;
    if revoked {
        println!("revoked {}", short(&token.id));
    } else {
        println!("{} was already gone", short(&token.id));
    }
    Ok(())
}

async fn list(
    saved: &crate::account::Saved,
    ca_cert: Option<&std::path::Path>,
) -> std::io::Result<(Vec<TokenInfo>, i64)> {
    let request = AccountRequest::TokenList {
        login: saved.token.clone(),
    };
    let reply = crate::account::ask_as(saved, ca_cert, &request).await?;
    let AccountReply::Tokens { tokens, now } = reply else {
        return Err(crate::account::unexpected(&reply));
    };
    // The expiries are on the relay's clock: this device's only when the
    // relay does not say.
    Ok((tokens, if now > 0 { now } else { self::now() }))
}

/// A token's ID, short enough to read and long enough to tell apart.
fn short(id: &str) -> &str {
    id.get(..12).unwrap_or(id)
}

/// `text` (seconds, or a number and s, m, h or d) in seconds, within what a
/// token may last.
fn parse_duration(text: &str) -> Result<u64, String> {
    let (number, unit) = match text.char_indices().find(|(_, c)| !c.is_ascii_digit()) {
        Some((at, _)) => text.split_at(at),
        None => (text, "s"),
    };
    let number: u64 = number
        .parse()
        .map_err(|_bad| format!("{text:?} is not a duration such as 30m, 1h or 7d"))?;
    let unit = match unit {
        "s" => 1,
        "m" => 60,
        "h" => 3600,
        "d" => 86_400,
        _ => return Err(format!("{text:?} is not a duration such as 30m, 1h or 7d")),
    };
    let seconds = number.saturating_mul(unit);
    if !(1..=MAX_TOKEN_LIFETIME).contains(&seconds) {
        return Err(format!(
            "a registration token lasts 1 second to {} days",
            MAX_TOKEN_LIFETIME / 86_400
        ));
    }
    Ok(seconds)
}

/// `seconds`, in the largest whole unit.
fn shown_duration(seconds: u64) -> String {
    match seconds {
        s if s >= 86_400 => format!("{}d", s / 86_400),
        s if s >= 3600 => format!("{}h", s / 3600),
        s if s >= 60 => format!("{}m", s / 60),
        s => format!("{s}s"),
    }
}

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::parse_duration;

    #[test]
    fn durations_read_with_or_without_a_unit() {
        assert_eq!(parse_duration("90"), Ok(90));
        assert_eq!(parse_duration("30m"), Ok(1800));
        assert_eq!(parse_duration("1h"), Ok(3600));
        assert_eq!(parse_duration("7d"), Ok(7 * 86_400));
        for bad in ["", "h", "1w", "0", "31d", "-1h"] {
            assert!(parse_duration(bad).is_err(), "{bad:?}");
        }
    }
}