#[cfg(unix)]
mod unix;
#[cfg(all(test, unix))]
mod tests;
use std::io::{self, BufRead as _, IsTerminal as _, Write as _};
use anyhow::{Result, bail};
use zeroize::Zeroizing;
pub const MAX_SECRET: usize = 1000;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Source {
Stdin,
Terminal,
Refused,
}
fn source(assumed: bool, stdin_terminal: bool) -> Source {
if assumed {
Source::Stdin
} else if stdin_terminal {
Source::Terminal
} else {
Source::Refused
}
}
pub fn read_secret(ask: &str) -> Result<Zeroizing<String>> {
match source(super::assumed(), io::stdin().is_terminal()) {
Source::Refused => bail!(
"a secret is read only from a terminal, never from piped input; give it as a \
file instead"
),
Source::Stdin => {
eprint!("{ask}");
io::stderr().flush()?;
let mut line = Zeroizing::new(String::new());
io::stdin().lock().read_line(&mut line)?;
finish(line.as_bytes())
}
Source::Terminal => from_terminal(ask),
}
}
#[cfg(unix)]
fn from_terminal(ask: &str) -> Result<Zeroizing<String>> {
use anyhow::Context as _;
let tty = std::fs::OpenOptions::new()
.read(true)
.write(true)
.open("/dev/tty")
.context("opening the controlling terminal to read the secret")?;
eprint!("{ask}");
io::stderr().flush()?;
let line = unix::read_hidden(&tty)?;
finish(&line)
}
#[cfg(not(unix))]
fn from_terminal(_ask: &str) -> Result<Zeroizing<String>> {
bail!(
"on {} a secret cannot be typed without showing it; give it as a file instead",
std::env::consts::OS
)
}
fn finish(raw: &[u8]) -> Result<Zeroizing<String>> {
let Ok(text) = std::str::from_utf8(raw) else {
bail!("the secret is not text; nothing was saved");
};
let trimmed = text.trim();
if trimmed.is_empty() {
bail!("no secret was given; nothing was saved");
}
if trimmed.len() > MAX_SECRET {
bail!("the secret is longer than {MAX_SECRET} bytes; give it as a file instead");
}
Ok(Zeroizing::new(trimmed.to_owned()))
}