use std::fs;
use std::io;
use std::path::{Path, PathBuf};
use super::{
ChainError, ChainOptions, ChainOutcome, RotationAttestation, decode_pubkey, verify_chain,
};
pub const HUMAN_IDENTITY_DIR: &str = "identity";
pub const HUMAN_KEY_DIR: &str = ".human";
pub const KEYS_DIR: &str = "keys";
pub fn human_identity_dir(mur_home: &Path) -> PathBuf {
mur_home.join(HUMAN_IDENTITY_DIR)
}
pub fn human_key_dir(mur_home: &Path) -> PathBuf {
mur_home.join(KEYS_DIR).join(HUMAN_KEY_DIR)
}
pub const HUMAN_PUBKEY_FILE: &str = "identity.pub";
pub const HUMAN_ROTATIONS_FILE: &str = "rotations.jsonl";
pub const HUMAN_PRIVATE_KEY_FILE: &str = "identity.key";
#[derive(Debug, thiserror::Error)]
pub enum HumanIdentityError {
#[error("no human identity enrolled ({path} is absent)")]
NotEnrolled { path: PathBuf },
#[error("human identity at {path} exists but is not readable: {source}")]
Unreadable {
path: PathBuf,
#[source]
source: io::Error,
},
#[error("human identity at {path} is invalid: {detail}")]
Invalid { path: PathBuf, detail: String },
}
#[derive(Debug, Clone)]
pub struct RotationChain {
entries: Vec<RotationAttestation>,
head: ChainOutcome,
head_pubkey: [u8; 32],
}
impl RotationChain {
pub fn entries(&self) -> &[RotationAttestation] {
&self.entries
}
pub fn head_pubkey(&self) -> [u8; 32] {
self.head_pubkey
}
pub fn head_key_version(&self) -> u32 {
self.head.head_key_version
}
}
pub fn human_pubkey_path(mur_home: &Path) -> PathBuf {
human_identity_dir(mur_home).join(HUMAN_PUBKEY_FILE)
}
pub fn human_rotations_path(mur_home: &Path) -> PathBuf {
human_identity_dir(mur_home).join(HUMAN_ROTATIONS_FILE)
}
pub fn human_private_key_path(mur_home: &Path) -> PathBuf {
human_key_dir(mur_home).join(HUMAN_PRIVATE_KEY_FILE)
}
fn read_public(path: &Path) -> Result<String, HumanIdentityError> {
let unreadable = |source| HumanIdentityError::Unreadable {
path: path.to_path_buf(),
source,
};
match fs::metadata(path) {
Ok(_) => {}
Err(e) if e.kind() == io::ErrorKind::NotFound => {
return Err(HumanIdentityError::NotEnrolled {
path: path.to_path_buf(),
});
}
Err(e) => return Err(unreadable(e)),
}
fs::read_to_string(path).map_err(unreadable)
}
fn invalid(path: &Path, detail: impl ToString) -> HumanIdentityError {
HumanIdentityError::Invalid {
path: path.to_path_buf(),
detail: detail.to_string(),
}
}
pub fn load_pubkey(mur_home: &Path) -> Result<[u8; 32], HumanIdentityError> {
let path = human_pubkey_path(mur_home);
let text = read_public(&path)?;
decode_pubkey(text.trim()).map_err(|e| invalid(&path, e))
}
pub fn rotation_chain(mur_home: &Path) -> Result<RotationChain, HumanIdentityError> {
let path = human_rotations_path(mur_home);
let text = read_public(&path)?;
let entries = text
.lines()
.filter(|l| !l.trim().is_empty())
.map(serde_json::from_str::<RotationAttestation>)
.collect::<Result<Vec<_>, _>>()
.map_err(|e| invalid(&path, e))?;
let head = verify_chain(
&entries,
ChainOptions {
allow_emergency: false,
},
)
.map_err(|e: ChainError| invalid(&path, e))?;
let head_pubkey = decode_pubkey(&head.head_pubkey).map_err(|e| invalid(&path, e))?;
let current = load_pubkey(mur_home)?;
if current != head_pubkey {
return Err(invalid(
&path,
format!(
"chain head (key_version {}) is not the key in {HUMAN_PUBKEY_FILE}",
head.head_key_version
),
));
}
Ok(RotationChain {
entries,
head,
head_pubkey,
})
}
#[cfg(test)]
#[path = "human_tests.rs"]
mod human_tests;
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn the_key_dir_name_is_not_a_valid_agent_name() {
assert!(crate::agent_name::validate_agent_name(HUMAN_KEY_DIR).is_err());
}
#[test]
fn the_two_halves_never_share_a_directory() {
let home = Path::new("/m");
let public = human_identity_dir(home);
let private = human_key_dir(home);
assert!(!private.starts_with(&public) && !public.starts_with(&private));
}
}