use std::io::{IsTerminal as _, Read, Write as _};
use anyhow::{Context as _, bail};
use zeroize::Zeroizing;
const MAX_PASSWORD_BYTES: usize = nitr::stdlib::MAX_PASSWORD_BYTES;
pub(crate) async fn hash_password() -> anyhow::Result<()> {
let stdin = std::io::stdin();
let password = if stdin.is_terminal() {
let password = prompt("Password")?;
confirm(&password, |_| prompt("Confirm password"))?;
password
} else {
read_stdin_password(stdin.lock())?
};
if password.is_empty() {
bail!(
"refusing to hash an empty password: pipe the password in \
(`printf %s \"$PW\" | nitr hash-password`) or run this on a \
terminal to be prompted"
);
}
println!("{}", argon2id(&password).await?);
Ok(())
}
const CONFIRM_ATTEMPTS: u32 = 3;
fn confirm(
password: &str,
mut ask: impl FnMut(u32) -> anyhow::Result<Zeroizing<String>>,
) -> anyhow::Result<()> {
for attempt in 1..=CONFIRM_ATTEMPTS {
let again = ask(attempt)?;
if again.as_str() == password {
return Ok(());
}
if attempt < CONFIRM_ATTEMPTS {
eprintln!(
"the passwords do not match (attempt {attempt} of {CONFIRM_ATTEMPTS}); try again"
);
}
}
bail!("the passwords did not match in {CONFIRM_ATTEMPTS} attempts; nothing was hashed")
}
fn read_stdin_password(reader: impl Read) -> anyhow::Result<Zeroizing<String>> {
let cap = MAX_PASSWORD_BYTES + 2;
let mut raw = Zeroizing::new(String::new());
reader
.take(cap as u64 + 1)
.read_to_string(&mut raw)
.context("cannot read the password from stdin")?;
if raw.len() > cap {
bail!(
"the password from stdin is longer than the {MAX_PASSWORD_BYTES}-byte limit \
the server enforces: a hash of it could never verify"
);
}
let stripped = strip_eol(std::mem::take(&mut *raw));
if stripped.len() > MAX_PASSWORD_BYTES {
bail!(
"the password from stdin is longer than the {MAX_PASSWORD_BYTES}-byte limit \
the server enforces: a hash of it could never verify"
);
}
Ok(Zeroizing::new(stripped))
}
fn strip_eol(mut raw: String) -> String {
if raw.ends_with('\n') {
raw.pop();
if raw.ends_with('\r') {
raw.pop();
}
}
raw
}
fn prompt(label: &str) -> anyhow::Result<Zeroizing<String>> {
let echo = EchoOff::new();
eprint!("{label}: ");
if echo.is_visible() {
eprint!("(warning: this terminal is echoing) ");
}
std::io::stderr().flush().ok();
let mut line = Zeroizing::new(String::new());
let read = std::io::stdin().read_line(&mut line);
let visible = echo.is_visible();
drop(echo);
if !visible {
eprintln!();
}
read.context("cannot read the password from the terminal")?;
Ok(Zeroizing::new(strip_eol(std::mem::take(&mut *line))))
}
struct EchoOff {
disabled: bool,
}
impl EchoOff {
fn new() -> Self {
Self {
disabled: set_echo(false),
}
}
fn is_visible(&self) -> bool {
!self.disabled
}
}
impl Drop for EchoOff {
fn drop(&mut self) {
if self.disabled {
set_echo(true);
}
}
}
#[cfg(unix)]
fn set_echo(on: bool) -> bool {
std::process::Command::new("stty")
.arg(if on { "echo" } else { "-echo" })
.stdin(std::process::Stdio::inherit())
.status()
.is_ok_and(|status| status.success())
}
#[cfg(not(unix))]
fn set_echo(_on: bool) -> bool {
false
}
async fn argon2id(password: &str) -> anyhow::Result<String> {
let lua = mlua::Lua::new();
nitr::stdlib::register_builtins(&lua, nitr::Builtins::CRYPTO, &nitr::BuiltinsEnv::default())
.context("`nitr hash-password` needs argon2, which this build does not have")?;
let crypto: mlua::Table = lua
.globals()
.get::<mlua::Table>("nitr")
.context("the nitr namespace")?
.get("crypto")
.context("the nitr.crypto table")?;
let hash: mlua::Function = crypto.get("password_hash").context("password_hash")?;
let password = lua.create_string(password)?;
Ok(hash.call_async::<String>(password).await?)
}
#[cfg(test)]
mod tests {
use super::{MAX_PASSWORD_BYTES, read_stdin_password, strip_eol};
#[test]
fn confirmation_retries_then_refuses() {
let answers = |list: &'static [&'static str]| {
let mut it = list.iter();
move |_attempt: u32| {
Ok(zeroize::Zeroizing::new(
it.next().expect("more answers than attempts").to_string(),
))
}
};
super::confirm("secret", answers(&["secret"])).expect("first try");
super::confirm("secret", answers(&["typo", "secret"])).expect("second try");
super::confirm("secret", answers(&["typo", "typo", "secret"])).expect("third try");
let err = super::confirm("secret", answers(&["a", "b", "c", "secret"]))
.expect_err("three mismatches must refuse");
assert!(err.to_string().contains("3 attempts"), "got: {err}");
let err =
super::confirm("secret", |_| anyhow::bail!("terminal closed")).expect_err("read error");
assert!(err.to_string().contains("terminal closed"));
}
#[test]
fn only_the_shells_line_ending_is_removed() {
assert_eq!(strip_eol("hunter2\n".into()), "hunter2");
assert_eq!(strip_eol("hunter2\r\n".into()), "hunter2");
assert_eq!(strip_eol("hunter2".into()), "hunter2");
assert_eq!(strip_eol("hunter2 \n".into()), "hunter2 ");
assert_eq!(strip_eol("hunter2\t".into()), "hunter2\t");
assert_eq!(strip_eol("a\nb\n".into()), "a\nb");
assert_eq!(strip_eol("\n".into()), "");
assert_eq!(strip_eol(String::new()), "");
}
#[test]
fn stdin_reads_are_capped_at_the_servers_password_limit() {
let max = "x".repeat(MAX_PASSWORD_BYTES);
let got = read_stdin_password(max.as_bytes()).expect("at the limit");
assert_eq!(got.len(), MAX_PASSWORD_BYTES);
let with_eol = format!("{max}\r\n");
let got = read_stdin_password(with_eol.as_bytes()).expect("limit + crlf");
assert_eq!(got.len(), MAX_PASSWORD_BYTES);
let got = read_stdin_password(b"hunter2 \n".as_slice()).expect("trailing space");
assert_eq!(&*got, "hunter2 ");
let over = "x".repeat(MAX_PASSWORD_BYTES + 1);
let err = read_stdin_password(over.as_bytes()).expect_err("one over");
assert!(err.to_string().contains("1024"), "got: {err}");
assert!(!err.to_string().contains(" "), "got: {err}");
let endless = std::io::repeat(b'z');
let err = read_stdin_password(endless).expect_err("an endless stream");
assert!(err.to_string().contains("1024"), "got: {err}");
}
}