update cli with new behavior

This commit is contained in:
kevin zhao
2025-12-02 23:03:22 +00:00
parent 50257cffcc
commit eb389a9f7f
2 changed files with 22 additions and 9 deletions

View File

@@ -4,11 +4,12 @@ use std::path::PathBuf;
use anyhow::Context;
use anyhow::Result;
use clap::Parser;
use serde::Serialize;
use crate::Decision;
use crate::Evaluation;
use crate::Policy;
use crate::PolicyParser;
use crate::RuleMatch;
/// Arguments for evaluating a command against one or more execpolicy files.
#[derive(Debug, Parser, Clone)]
@@ -35,20 +36,25 @@ impl ExecPolicyCheckCommand {
/// Load the policies for this command, evaluate the command, and render JSON output.
pub fn run(&self) -> Result<()> {
let policy = load_policies(&self.policies)?;
let evaluation = policy.check(&self.command, &|_| Decision::Allow);
let matched_rules = policy.matches_for_command(&self.command, None);
let json = format_evaluation_json(&evaluation, self.pretty)?;
let json = format_matches_json(&matched_rules, self.pretty)?;
println!("{json}");
Ok(())
}
}
pub fn format_evaluation_json(evaluation: &Evaluation, pretty: bool) -> Result<String> {
pub fn format_matches_json(matched_rules: &[RuleMatch], pretty: bool) -> Result<String> {
let output = ExecPolicyCheckOutput {
matched_rules,
decision: matched_rules.iter().map(RuleMatch::decision).max(),
};
if pretty {
serde_json::to_string_pretty(evaluation).map_err(Into::into)
serde_json::to_string_pretty(&output).map_err(Into::into)
} else {
serde_json::to_string(evaluation).map_err(Into::into)
serde_json::to_string(&output).map_err(Into::into)
}
}
@@ -66,3 +72,12 @@ pub fn load_policies(policy_paths: &[PathBuf]) -> Result<Policy> {
Ok(parser.build())
}
#[derive(Serialize)]
#[serde(rename_all = "camelCase")]
struct ExecPolicyCheckOutput<'a> {
#[serde(rename = "matchedRules")]
matched_rules: &'a [RuleMatch],
#[serde(skip_serializing_if = "Option::is_none")]
decision: Option<Decision>,
}

View File

@@ -11,8 +11,6 @@ use serde::Deserialize;
use serde::Serialize;
use std::sync::Arc;
type HeuristicsFallback<'a> = Option<&'a dyn Fn(&[String]) -> Decision>;
#[derive(Clone, Debug)]
pub struct Policy {
rules_by_program: MultiMap<String, RuleRef>,
@@ -83,7 +81,7 @@ impl Policy {
pub fn matches_for_command(
&self,
cmd: &[String],
heuristics_fallback: HeuristicsFallback<'_>,
heuristics_fallback: Option<&dyn Fn(&[String]) -> Decision>,
) -> Vec<RuleMatch> {
let mut matched_rules: Vec<RuleMatch> = match cmd.first() {
Some(first) => self