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,
};
#[derive(clap::Args)]
pub struct TokenArgs {
#[command(subcommand)]
command: TokenCommand,
#[arg(long, global = true)]
ca_cert: Option<PathBuf>,
}
#[derive(clap::Subcommand)]
enum TokenCommand {
Create {
#[arg(long, default_value_t = 1)]
uses: u32,
#[arg(long, default_value = "1h", value_parser = parse_duration)]
expires: u64,
},
Ls,
Revoke {
id: String,
},
}
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,
}
}
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"))?;
crate::approve::remember(&*secret, expires)?;
let request = AccountRequest::TokenCreate {
login: saved.token.clone(),
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(())
}
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(())
}
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));
};
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));
};
Ok((tokens, if now > 0 { now } else { self::now() }))
}
fn short(id: &str) -> &str {
id.get(..12).unwrap_or(id)
}
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)
}
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:?}");
}
}
}