use openmoat_core::rule_id::{GATE_REFUSED, POLICY_CHANGE};
use openmoat_core::{Decision, Verdict};
use super::Factor;
use crate::home::Home;
pub const SESSION: &str = openmoat_audit::LEDGER_SESSION;
const DETAILS: usize = 40;
fn who() -> String {
["USER", "USERNAME", "LOGNAME"]
.iter()
.find_map(|name| std::env::var(name).ok().filter(|v| !v.is_empty()))
.unwrap_or_else(|| "unknown account".to_owned())
}
pub fn change(home: &Home, command: &str, factor: Factor, what: &str, details: &[String]) {
let mut decision = Decision::single(
Verdict::Allow,
POLICY_CHANGE,
format!(
"{what}; run by {} at a terminal; {}",
who(),
factor.describe()
),
);
decision
.reasons
.extend(details.iter().take(DETAILS).cloned());
if details.len() > DETAILS {
decision
.reasons
.push(format!("… and {} more", details.len() - DETAILS));
}
write(home, command, &decision);
}
pub fn refused(home: &Home, command: &str, why: &str) {
let decision = Decision::single(
Verdict::Deny,
GATE_REFUSED,
format!("{why}; run by {} at a terminal", who()),
);
write(home, command, &decision);
}
fn write(home: &Home, command: &str, decision: &Decision) {
if !home.audit_path().exists() {
return;
}
let written = crate::audit_key::open_existing(home).and_then(|store| {
Ok(store.record(&openmoat_audit::NewEvent {
host: openmoat_audit::LEDGER_HOST,
session_id: SESSION,
call_id: None,
cwd: None,
tool: command,
action: None,
decision,
latency_us: 0,
})?)
});
if let Err(error) = written {
eprintln!(
"openmoat: the audit log did not record `{command}` in the policy-change ledger: {error:#}"
);
}
}