use std::time::Instant;
use anyhow::{Context as _, Result};
use openmoat_core::{CompiledPolicy, Decision, Verdict};
use openmoat_hosts::{HookEvent, HookRequest, Host};
use crate::context;
use crate::exit::Code;
use crate::hangs::{self, Phase};
use crate::home::Home;
use crate::integrity;
use crate::taint;
pub(super) fn answer(host: Host, payload: &str, event: &HookEvent) -> Code {
let decision = host
.parse_request_as(payload, super::entry::event())
.context("parsing hook payload")
.and_then(|mut request| match std::mem::take(&mut request.event) {
HookEvent::PostToolUse { output } => kept(host, request, &output),
_ => Ok(Decision::new(Verdict::Allow)),
})
.unwrap_or_else(|error| super::kernel_error(&error));
hangs::enter(Phase::Answer);
super::respond(host, event, &decision)
}
fn kept(host: Host, request: HookRequest, output: &str) -> Result<Decision> {
let started = Instant::now();
let home = Home::locate()?;
let verified = integrity::check(&home)?;
if let Some(deny) = verified.checked.deny {
return Ok(deny);
}
if request.action.is_none() {
return Ok(Decision::new(Verdict::Allow));
}
let drifted = verified.checked.relaxed;
let home = verified.home;
let request = super::placed::placed(&home, host, request, &drifted)?;
let Some(action) = &request.action else {
return Ok(Decision::new(Verdict::Allow));
};
let cwd = request
.cwd
.as_deref()
.map(std::path::PathBuf::from)
.map_or_else(std::env::current_dir, Ok)
.context("resolving working directory")?;
hangs::enter(Phase::Context);
let ctx = context::eval_context(&home, Some(&cwd), None)?;
let policy = crate::repo::effective_policy(&home, &ctx)?;
hangs::enter(Phase::Compile);
let compiled = CompiledPolicy::compile(&policy, &ctx)?;
hangs::enter(Phase::Record);
home.require_exists()?;
let store = crate::audit_key::open_existing(&home)?;
let output = taint::injected::Output {
host,
session: &request.session_id,
action,
cwd: &ctx.cwd,
text: output,
};
taint::injected::record(&home, &store, &compiled, &output)?;
hangs::enter(Phase::Taint);
let deadline = started + super::taint_budget(host);
taint::catch_up(
&store,
host,
&request.session_id,
&compiled,
&ctx.cwd,
deadline,
);
super::shown::ran(store, host, &request, Some(action), || {
let decoys = crate::canary::Record::load(&home)?.decoys();
crate::secrets::known_with(&policy.secrets, &ctx.home, &decoys.values)
})?;
Ok(Decision::new(Verdict::Allow))
}