use aither_sandbox::{AnyCommandGate, CommandGate, GateDecision};
use serde::{Deserialize, Serialize};
use super::lifecycle::ExternalHooks;
use super::live::Run;
use super::runner::{HookCommand, HookRole};
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct CommandHookConfig {
pub name: String,
#[serde(flatten)]
pub command: HookCommand,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum CommandHookEvent {
BeforeCommand,
}
#[derive(Debug, Serialize)]
pub struct CommandHookInput<'a> {
pub event: CommandHookEvent,
pub role: HookRole,
pub command: &'a str,
}
#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
#[serde(tag = "decision", rename_all = "snake_case", deny_unknown_fields)]
pub enum CommandHookOutput {
Allow {},
Block {
reason: String,
},
}
impl CommandHookConfig {
fn decide(&self, answer: &Run<CommandHookOutput>, notices: &crate::AnyNotices) -> GateDecision {
let refusal = match answer {
Run::Answered(CommandHookOutput::Allow {}) | Run::Gone => return GateDecision::Allow,
Run::Answered(CommandHookOutput::Block { reason }) => {
crate::CommandHookRefusal::Blocked {
hook: &self.name,
reason,
}
}
Run::Failed(failure) => {
tracing::warn!(hook = %self.name, %failure, "command hook failed; the command is blocked");
crate::CommandHookRefusal::Failed {
hook: &self.name,
failure,
}
}
};
GateDecision::Block {
reason: notices.command_hook(&refusal),
}
}
}
impl ExternalHooks {
pub async fn check_command(&self, command: &str) -> GateDecision {
let input = CommandHookInput {
event: CommandHookEvent::BeforeCommand,
role: self.role(),
command,
};
let set = self.live().set();
let runs = set.command.iter().map(|hook| {
let input = &input;
async move {
let answer = self
.live()
.run_hook(
self.user(),
hook,
input,
|answer: Option<CommandHookOutput>| {
answer.ok_or_else(|| "it printed no answer".to_string())
},
)
.await;
hook.config.decide(&answer, self.notices())
}
});
futures::future::join_all(runs)
.await
.into_iter()
.find(|decision| matches!(decision, GateDecision::Block { .. }))
.unwrap_or(GateDecision::Allow)
}
#[must_use]
pub fn command_gate(&self) -> AnyCommandGate {
AnyCommandGate::new(self.clone())
}
}
impl CommandGate for ExternalHooks {
async fn check(&self, command: &str) -> GateDecision {
self.check_command(command).await
}
}