use std::path::{Path, PathBuf};
use std::time::{Duration, Instant};
use anyhow::{Context as _, Result, bail};
use openmoat_audit::{ChainKey, Store};
use zeroize::Zeroizing;
use crate::home::Home;
pub const KEY_FILE: &str = "audit.key";
const UPGRADE_WAIT: Duration = Duration::from_millis(500);
pub fn path(home: &Home) -> PathBuf {
home.root().join(KEY_FILE)
}
pub fn read(home: &Home) -> Result<Option<ChainKey>> {
read_at(&path(home))
}
fn read_at(path: &Path) -> Result<Option<ChainKey>> {
match std::fs::symlink_metadata(path) {
Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(None),
_ => {}
}
let text = crate::key_file::read(path)?;
let key = ChainKey::parse(&text).with_context(|| format!("reading {}", path.display()))?;
Ok(Some(key))
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Writer {
Person,
Process,
}
fn for_writing(home: &Home, store: &Store, writer: Writer) -> Result<ChainKey> {
if let Some(key) = read(home)? {
return Ok(key);
}
let path = path(home);
let empty = store.latest_id()?.is_none();
let may_make = empty
|| store.upgraded_to_keyed()
|| (writer == Writer::Person && !store.has_keyed_events()?);
if !may_make {
if writer == Writer::Process
&& let Some(key) = wait_for_key(home)?
{
return Ok(key);
}
bail!(
"the audit key {} is missing and this audit log already holds events, so \
OpenMoat records nothing more: only an upgrade or a person's `openmoat init` makes \
a key for a log with events. Put the key back from a backup, or move the audit log \
aside as evidence and run `openmoat init` to start a new log with a new key",
path.display()
);
}
let (after, after_hash) = store.key_start()?;
let mut raw = Zeroizing::new([0u8; 32]);
getrandom::fill(raw.as_mut_slice())
.map_err(|e| anyhow::Error::msg(e.to_string()))
.context("reading random bytes for the audit key")?;
let made = ChainKey::new(&raw, after, after_hash.as_deref());
crate::home::write_private_new(&path, made.encode().as_bytes())?;
read(home)?.with_context(|| format!("{} is gone just after it was made", path.display()))
}
fn wait_for_key(home: &Home) -> Result<Option<ChainKey>> {
let deadline = Instant::now() + UPGRADE_WAIT;
while Instant::now() < deadline {
std::thread::sleep(Duration::from_millis(25));
if let Some(key) = read(home)? {
return Ok(Some(key));
}
}
Ok(None)
}
pub fn open(home: &Home) -> Result<Option<PathBuf>> {
let new = !home.audit_path().exists();
let store = Store::open(&home.audit_path())?;
let mut kept = None;
let old = path(home);
let replace = new
|| (store.latest_id()?.is_none()
&& read(home).map_or(true, |key| key.is_some_and(|k| k.after().0 > 0)));
if replace && std::fs::symlink_metadata(&old).is_ok() {
let to = home
.root()
.join(format!("{KEY_FILE}.{}.old", crate::time::now_ms()));
crate::home::keep_private(&old, &to)?;
kept = Some(to);
}
for_writing(home, &store, Writer::Person)?;
Ok(kept)
}
pub fn open_existing(home: &Home) -> Result<Store> {
let path = home.audit_path();
let store =
Store::open_existing(&path).with_context(|| format!("opening {}", path.display()))?;
let key = for_writing(home, &store, Writer::Process)?;
Ok(store.with_chain_key(key))
}
pub fn missing_over_events(home: &Home) -> bool {
!path(home).exists()
&& home
.open_audit()
.and_then(|store| Ok(store.keys_events() && store.latest_id()?.is_some()))
.unwrap_or(false)
}
#[cfg(test)]
mod tests;