use std::fmt;
use std::path::Path;
use zeroize::Zeroizing;
use crate::private_file::{self, ModePolicy, PrivateFileError};
const TOKEN_HEX_LEN: usize = 64;
const TOKEN_FILE_LIMIT: usize = 256;
pub struct BootstrapToken(Zeroizing<String>);
impl BootstrapToken {
pub fn read_file(path: &Path) -> Result<Self, TokenFileError> {
let contents = private_file::read(path, TOKEN_FILE_LIMIT, ModePolicy::Any)
.map_err(TokenFileError::File)?;
let text = std::str::from_utf8(&contents).map_err(|_| TokenFileError::Malformed)?;
let line = text.strip_suffix('\n').unwrap_or(text);
Self::parse(line).ok_or(TokenFileError::Malformed)
}
pub(crate) fn parse(text: &str) -> Option<Self> {
let valid = text.len() == TOKEN_HEX_LEN
&& text.bytes().all(|b| matches!(b, b'0'..=b'9' | b'a'..=b'f'));
if !valid {
return None;
}
crate::redact::register_hex_secret(text);
Some(Self(Zeroizing::new(text.to_owned())))
}
pub(crate) fn expose(&self) -> &str {
&self.0
}
}
impl fmt::Debug for BootstrapToken {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("BootstrapToken(<redacted>)")
}
}
#[derive(Debug, thiserror::Error)]
#[non_exhaustive]
pub enum TokenFileError {
#[error(transparent)]
File(PrivateFileError),
#[error("token file does not hold a bootstrap token (64 lowercase hex digits)")]
Malformed,
}