use std::collections::{BTreeMap, BTreeSet};
use std::path::{Path, PathBuf};
use anyhow::Result;
use openmoat_core::rule_id::FOREIGN_HOOK;
use openmoat_core::{Action, CompiledPolicy, Decision, ForeignHooks, Verdict};
use openmoat_hosts::Host;
use serde::{Deserialize, Serialize};
use crate::home::Home;
use crate::integrity::Lock;
mod sources;
const SHOWN_CHARS: usize = 300;
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Found {
pub id: String,
pub host: Option<Host>,
pub file: PathBuf,
pub what: String,
pub commands: Vec<String>,
pub digest: String,
}
#[derive(Debug, Default)]
pub struct Scan {
pub found: Vec<Found>,
pub scanned: BTreeSet<String>,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct HookPin {
pub host: String,
pub file: String,
pub what: String,
pub digest: String,
pub shown: String,
}
pub type Pins = BTreeMap<String, HookPin>;
impl HookPin {
fn of(found: &Found) -> Self {
Self {
host: found.host.map(|h| h.id().to_owned()).unwrap_or_default(),
file: found.file.display().to_string(),
what: found.what.clone(),
digest: found.digest.clone(),
shown: shown(&found.commands),
}
}
}
fn shown(commands: &[String]) -> String {
if commands.is_empty() {
return "(a file of code; OpenMoat cannot read what it runs)".to_owned();
}
let text = openmoat_audit::redact(&commands.join("; "));
let cut: String = text.chars().take(SHOWN_CHARS).collect();
if cut.len() < text.len() {
format!("{cut}…")
} else {
cut
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Change {
pub found: Found,
pub changed: bool,
pub verdict: Verdict,
pub rules: Vec<String>,
}
impl Change {
pub fn holds(&self, mode: ForeignHooks) -> bool {
self.verdict == Verdict::Deny || mode == ForeignHooks::Hold
}
pub fn effect(&self, mode: ForeignHooks) -> &'static str {
if self.verdict == Verdict::Deny {
"until then the agent's calls are denied"
} else if mode == ForeignHooks::Hold {
"until then the agent's calls are held for review"
} else {
"the agent's calls are not held (`hooks.foreign: hold` in your policy holds them)"
}
}
pub fn describe(&self) -> String {
let subject = self.found.host.map_or_else(
|| self.found.what.clone(),
|h| format!("{} {}", h.display_name(), self.found.what),
);
let state = if self.changed { "changed" } else { "is new" };
let rules = if self.rules.is_empty() {
String::new()
} else {
format!(" [{}]", self.rules.join(", "))
};
let text = format!(
"{subject} in {} {state} (not accepted); its command classifies as {}{rules}\n {}",
self.found.file.display(),
self.verdict.as_str(),
shown(&self.found.commands)
);
crate::render::clean_lines(&text)
}
}
pub type Classify<'a> = dyn Fn(&[String]) -> (Verdict, Vec<String>) + 'a;
#[derive(Debug, Default)]
pub struct Review {
pub recorded: bool,
pub pin_count: usize,
pub changes: Vec<Change>,
pub gone: Vec<String>,
pub mode: ForeignHooks,
}
impl Review {
pub fn holds(&self) -> bool {
self.changes.iter().any(|c| c.holds(self.mode))
}
}
pub fn compare(pins: &Pins, scan: &Scan, classify: &Classify<'_>) -> Review {
let mut changes = Vec::new();
let ids: BTreeSet<&str> = scan.found.iter().map(|f| f.id.as_str()).collect();
for found in &scan.found {
let was_pinned = match pins.get(&found.id) {
Some(pin) if pin.digest == found.digest => continue,
Some(_) => true,
None => false,
};
let (verdict, rules) = if found.commands.is_empty() {
(Verdict::Review, Vec::new())
} else {
classify(&found.commands)
};
changes.push(Change {
found: found.clone(),
changed: was_pinned,
verdict,
rules,
});
}
let gone = pins
.iter()
.filter(|(id, pin)| scan.scanned.contains(&pin.file) && !ids.contains(id.as_str()))
.map(|(id, _)| id.clone())
.collect();
Review {
recorded: true,
pin_count: pins.len(),
changes,
gone,
mode: ForeignHooks::default(),
}
}
pub fn classify(compiled: &CompiledPolicy<'_>, commands: &[String]) -> (Verdict, Vec<String>) {
let mut verdict = Verdict::Allow;
let mut rules = Vec::new();
for command in commands {
let decision = compiled.decide(&Action::Shell {
command: command.clone(),
});
if decision.verdict > verdict {
verdict = decision.verdict;
rules.clone_from(&decision.rules);
}
}
(verdict, rules)
}
pub fn review(
home: &Home,
lock: &Lock,
hosts: &[Host],
cwd: Option<&Path>,
compiled: &CompiledPolicy<'_>,
) -> Review {
reviewed(lock, &sources::scan(home, hosts, cwd), compiled)
}
fn reviewed(lock: &Lock, scan: &Scan, compiled: &CompiledPolicy<'_>) -> Review {
let empty = Pins::new();
let pins = lock.hook_ledger.as_ref().unwrap_or(&empty);
let mut found = compare(pins, scan, &|commands| classify(compiled, commands));
found.recorded = lock.hook_ledger.is_some();
found.mode = compiled.policy().foreign_hooks();
found
}
pub fn review_here(home: &Home, lock: &Lock, hosts: &[Host], cwd: Option<&Path>) -> Result<Review> {
let scan = sources::scan(home, hosts, cwd);
review_lazily(lock.hook_ledger.as_ref(), &scan, || {
let ctx = crate::context::eval_context(home, cwd, None)?;
let policy = crate::repo::effective_policy(home, &ctx)?;
let compiled = CompiledPolicy::compile(&policy, &ctx)?;
Ok(reviewed(lock, &scan, &compiled))
})
}
fn review_lazily(
ledger: Option<&Pins>,
scan: &Scan,
classified: impl FnOnce() -> Result<Review>,
) -> Result<Review> {
let empty = Pins::new();
let pins = ledger.unwrap_or(&empty);
let unaccepted = scan.found.iter().any(|found| {
pins.get(&found.id)
.is_none_or(|pin| pin.digest != found.digest)
});
if unaccepted {
return classified();
}
let mut found = compare(pins, scan, &|_| (Verdict::Review, Vec::new()));
found.recorded = ledger.is_some();
Ok(found)
}
pub fn violation(
home: &Home,
lock: &Lock,
host: Host,
cwd: Option<&Path>,
compiled: &CompiledPolicy<'_>,
) -> Option<Decision> {
lock.hook_ledger.as_ref()?;
let found = review(home, lock, &[host], cwd, compiled);
hold(&found.changes, found.mode)
}
fn hold(changes: &[Change], mode: ForeignHooks) -> Option<Decision> {
let holding: Vec<&Change> = changes.iter().filter(|c| c.holds(mode)).collect();
let verdict = holding
.iter()
.map(|c| c.verdict.max(Verdict::Review))
.max()?;
let mut decision = Decision::new(verdict);
decision.rules.push(FOREIGN_HOOK.to_owned());
decision
.reasons
.extend(holding.iter().map(|c| c.describe()));
decision.reasons.push(
"a person must review it: run `openmoat hooks accept` in a terminal (`openmoat status` \
lists them)"
.to_owned(),
);
Some(decision)
}
pub fn tightened(mut decision: Decision, hold: Option<Decision>) -> Decision {
let Some(hold) = hold else {
return decision;
};
if decision.verdict > hold.verdict {
decision.context.extend(hold.reasons);
return decision;
}
if decision.verdict < hold.verdict {
let earlier = std::mem::take(&mut decision.reasons);
decision.context.extend(earlier);
decision.rules.clear();
decision.verdict = hold.verdict;
}
for rule in hold.rules {
if !decision.rules.contains(&rule) {
decision.rules.push(rule);
}
}
decision.reasons.extend(hold.reasons);
decision
}
pub fn accept(home: &Home, changes: &[Change], gone: &[String]) -> Result<()> {
let path = home.lock_path();
let mut lock = Lock::load(&path)?;
let pins = lock.hook_ledger.get_or_insert_with(Pins::new);
for change in changes {
pins.insert(change.found.id.clone(), HookPin::of(&change.found));
}
for id in gone {
pins.remove(id);
}
lock.save(&path)
}
#[derive(Debug, Default)]
pub struct Recorded {
pub count: usize,
pub held: Vec<Change>,
pub accepted: Vec<Change>,
pub mode: ForeignHooks,
}
pub fn record_current(
home: &Home,
binary: &Path,
cwd: Option<&Path>,
no_person: bool,
) -> Result<Recorded> {
let lock = Lock::load(&home.lock_path())?;
let hosts = crate::mcp::set_up_hosts(home, binary);
let found = review_here(home, &lock, &hosts, cwd)?;
let first = !found.recorded;
let mode = found.mode;
let (held, accepted): (Vec<Change>, Vec<Change>) =
found.changes.into_iter().partition(|_| no_person && !first);
accept(home, &accepted, &found.gone)?;
let count = Lock::load(&home.lock_path())?
.hook_ledger
.map_or(0, |p| p.len());
let accepted = if first { Vec::new() } else { accepted };
Ok(Recorded {
count,
held,
accepted,
mode,
})
}
pub fn recorded(count: usize) -> String {
match count {
0 => "none besides OpenMoat's own hook".to_owned(),
n => format!("{n} besides OpenMoat's own hook, recorded"),
}
}
pub fn lines(review: &Review) -> Vec<String> {
if !review.recorded {
return vec![
"hooks the agents' other hook commands are not recorded yet: \
`openmoat hooks accept` shows them and records them, so a new or changed one is \
named"
.to_owned(),
];
}
review
.changes
.iter()
.map(|change| change.describe().replace('\n', "\n "))
.collect()
}
#[cfg(test)]
mod tests;