Split in-memory execution policy rules into a separate crate (#62615)

## Why

Configuration, protocol, and prompt code use in-memory policies and
previously pulled in the Starlark parser through `codex-execpolicy`.

## What changed

Move policy construction, rule validation, and evaluation into
`codex-execpolicy-rules` and use it directly from those crates. Keep
Starlark policy loading and file updates in `codex-execpolicy`, which
re-exports the shared rule types and wraps rule validation errors while
preserving their source locations.

GitOrigin-RevId: 5bc70d3cd387b43a3ad1fcc56af96ad169ac8b13
This commit is contained in:
Charlie Marsh
2026-11-19 22:32:56 +00:00
committed by copyberry
parent db263d4f54
commit 5bdb5e8b3c
26 changed files with 261 additions and 171 deletions
+1 -1
View File
@@ -6,7 +6,7 @@ use std::io::Write;
use std::path::Path;
use std::path::PathBuf;
use crate::decision::Decision;
use crate::Decision;
use crate::rule::NetworkRuleProtocol;
use crate::rule::normalize_network_rule_host;
use thiserror::Error;
-30
View File
@@ -1,30 +0,0 @@
use serde::Deserialize;
use serde::Serialize;
use crate::error::Error;
use crate::error::Result;
#[derive(Clone, Copy, Debug, Eq, PartialEq, Ord, PartialOrd, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub enum Decision {
/// Command may run without further approval.
Allow,
/// Request approval from the configured reviewer; rejected with `approval_policy="never"`.
Prompt,
/// Requires a fresh human decision, independent of the configured reviewer.
#[serde(rename = "prompt-user")]
PromptUser,
/// Command is blocked without further consideration.
Forbidden,
}
impl Decision {
pub fn parse(raw: &str) -> Result<Self> {
match raw {
"allow" => Ok(Self::Allow),
"prompt" => Ok(Self::Prompt),
"forbidden" => Ok(Self::Forbidden),
other => Err(Error::InvalidDecision(other.to_string())),
}
}
}
+32 -86
View File
@@ -1,101 +1,47 @@
use starlark::Error as StarlarkError;
//! Diagnostics for loading and validating a Starlark policy file.
use crate::ErrorLocation;
use crate::RuleError;
use codex_execpolicy_rules::TextPosition;
use codex_execpolicy_rules::TextRange;
use starlark::codemap::FileSpan;
use thiserror::Error;
pub type Result<T> = std::result::Result<T, Error>;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct TextPosition {
pub line: usize,
pub column: usize,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct TextRange {
pub start: TextPosition,
pub end: TextPosition,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ErrorLocation {
pub path: String,
pub range: TextRange,
}
/// A failure to evaluate a policy file or validate its rules.
#[derive(Debug, Error)]
pub enum Error {
#[error("invalid decision: {0}")]
InvalidDecision(String),
#[error("invalid pattern element: {0}")]
InvalidPattern(String),
#[error("invalid example: {0}")]
InvalidExample(String),
#[error("invalid rule: {0}")]
InvalidRule(String),
#[error(
"expected every example to match at least one rule. rules: {rules:?}; unmatched examples: \
{examples:?}"
)]
ExampleDidNotMatch {
rules: Vec<String>,
examples: Vec<String>,
location: Option<ErrorLocation>,
},
#[error("expected example to not match rule `{rule}`: {example}")]
ExampleDidMatch {
rule: String,
example: String,
location: Option<ErrorLocation>,
},
#[error("starlark error: {0}")]
Starlark(StarlarkError),
Starlark(starlark::Error),
#[error(transparent)]
Rule(#[from] RuleError),
}
impl Error {
pub fn with_location(self, location: ErrorLocation) -> Self {
match self {
Error::ExampleDidNotMatch {
rules,
examples,
location: None,
} => Error::ExampleDidNotMatch {
rules,
examples,
location: Some(location),
},
Error::ExampleDidMatch {
rule,
example,
location: None,
} => Error::ExampleDidMatch {
rule,
example,
location: Some(location),
},
other => other,
}
}
/// Return the one-based source range when the failure has a span.
pub fn location(&self) -> Option<ErrorLocation> {
match self {
Error::ExampleDidNotMatch { location, .. }
| Error::ExampleDidMatch { location, .. } => location.clone(),
Error::Starlark(err) => err.span().map(|span| {
let resolved = span.resolve_span();
ErrorLocation {
path: span.filename().to_string(),
range: TextRange {
start: TextPosition {
line: resolved.begin.line + 1,
column: resolved.begin.column + 1,
},
end: TextPosition {
line: resolved.end.line + 1,
column: resolved.end.column + 1,
},
},
}
}),
_ => None,
Error::Starlark(error) => error.span().map(error_location_from_file_span),
Error::Rule(error) => error.location(),
}
}
}
/// Convert a parser span to the one-based coordinates used for policy diagnostics.
pub(crate) fn error_location_from_file_span(span: &FileSpan) -> ErrorLocation {
let resolved = span.resolve_span();
ErrorLocation {
path: span.filename().to_string(),
range: TextRange {
start: TextPosition {
line: resolved.begin.line + 1,
column: resolved.begin.column + 1,
},
end: TextPosition {
line: resolved.end.line + 1,
column: resolved.end.column + 1,
},
},
}
}
@@ -1,29 +0,0 @@
use std::path::Path;
#[cfg(windows)]
const WINDOWS_EXECUTABLE_SUFFIXES: [&str; 4] = [".exe", ".cmd", ".bat", ".com"];
pub(crate) fn executable_lookup_key(raw: &str) -> String {
#[cfg(windows)]
{
let raw = raw.to_ascii_lowercase();
for suffix in WINDOWS_EXECUTABLE_SUFFIXES {
if raw.ends_with(suffix) {
let stripped_len = raw.len() - suffix.len();
return raw[..stripped_len].to_string();
}
}
raw
}
#[cfg(not(windows))]
{
raw.to_string()
}
}
pub(crate) fn executable_path_lookup_key(path: &Path) -> Option<String> {
path.file_name()
.and_then(|name| name.to_str())
.map(executable_lookup_key)
}
+17 -19
View File
@@ -1,33 +1,31 @@
pub(crate) mod amend;
pub(crate) mod decision;
pub(crate) mod error;
pub(crate) mod execpolicycheck;
mod executable_name;
pub(crate) mod parser;
pub(crate) mod policy;
pub mod rule;
mod sandbox_migration;
pub use amend::AmendError;
pub use amend::blocking_append_allow_prefix_rule;
pub use amend::blocking_append_network_rule;
pub use decision::Decision;
pub use codex_execpolicy_rules::Decision;
pub use codex_execpolicy_rules::Error as RuleError;
pub use codex_execpolicy_rules::ErrorLocation;
pub use codex_execpolicy_rules::Evaluation;
pub use codex_execpolicy_rules::MatchOptions;
pub use codex_execpolicy_rules::NetworkRuleProtocol;
pub use codex_execpolicy_rules::PatternToken;
pub use codex_execpolicy_rules::Policy;
pub use codex_execpolicy_rules::PrefixPattern;
pub use codex_execpolicy_rules::PrefixRule;
pub use codex_execpolicy_rules::RequirementsExecPolicy;
pub use codex_execpolicy_rules::Rule;
pub use codex_execpolicy_rules::RuleMatch;
pub use codex_execpolicy_rules::RuleRef;
pub use codex_execpolicy_rules::TextPosition;
pub use codex_execpolicy_rules::TextRange;
pub use codex_execpolicy_rules::rule;
pub use error::Error;
pub use error::ErrorLocation;
pub use error::Result;
pub use error::TextPosition;
pub use error::TextRange;
pub use execpolicycheck::ExecPolicyCheckCommand;
pub use parser::PolicyParser;
pub use policy::Evaluation;
pub use policy::MatchOptions;
pub use policy::Policy;
pub use policy::RequirementsExecPolicy;
pub use rule::NetworkRuleProtocol;
pub use rule::PatternToken;
pub use rule::PrefixPattern;
pub use rule::PrefixRule;
pub use rule::Rule;
pub use rule::RuleMatch;
pub use rule::RuleRef;
pub use sandbox_migration::prefix_rule_migration;
+19 -33
View File
@@ -1,7 +1,7 @@
use crate::error::error_location_from_file_span;
use codex_utils_absolute_path::AbsolutePathBuf;
use multimap::MultiMap;
use starlark::any::ProvidesStaticType;
use starlark::codemap::FileSpan;
use starlark::environment::GlobalsBuilder;
use starlark::environment::Module;
use starlark::eval::Evaluator;
@@ -18,14 +18,7 @@ use std::collections::HashMap;
use std::path::Path;
use std::sync::Arc;
use crate::decision::Decision;
use crate::error::Error;
use crate::error::ErrorLocation;
use crate::error::Result;
use crate::error::TextPosition;
use crate::error::TextRange;
use crate::executable_name::executable_lookup_key;
use crate::executable_name::executable_path_lookup_key;
use crate::Decision;
use crate::rule::NetworkRule;
use crate::rule::NetworkRuleProtocol;
use crate::rule::PatternToken;
@@ -34,6 +27,11 @@ use crate::rule::PrefixRule;
use crate::rule::RuleRef;
use crate::rule::validate_match_examples;
use crate::rule::validate_not_match_examples;
use codex_execpolicy_rules::Error;
use codex_execpolicy_rules::ErrorLocation;
use codex_execpolicy_rules::Result;
use codex_execpolicy_rules::executable_lookup_key;
use codex_execpolicy_rules::executable_path_lookup_key;
pub struct PolicyParser {
builder: RefCell<PolicyBuilder>,
@@ -54,7 +52,11 @@ impl PolicyParser {
/// Parses a policy, tagging parser errors with `policy_identifier` so failures include the
/// identifier alongside line numbers.
pub fn parse(&mut self, policy_identifier: &str, policy_file_contents: &str) -> Result<()> {
pub fn parse(
&mut self,
policy_identifier: &str,
policy_file_contents: &str,
) -> crate::Result<()> {
let pending_validation_count = self.builder.borrow().pending_example_validations.len();
let mut dialect = Dialect::Extended.clone();
dialect.enable_f_strings = true;
@@ -63,14 +65,14 @@ impl PolicyParser {
policy_file_contents.to_string(),
&dialect,
)
.map_err(Error::Starlark)?;
.map_err(crate::Error::Starlark)?;
let globals = GlobalsBuilder::standard().with(policy_builtins).build();
Module::with_temp_heap(|module| {
let mut eval = Evaluator::new(&module);
eval.extra = Some(&self.builder);
eval.eval_module(ast, &globals)
.map(|_| ())
.map_err(Error::Starlark)
.map_err(crate::Error::Starlark)
})?;
self.builder
.borrow()
@@ -78,7 +80,7 @@ impl PolicyParser {
Ok(())
}
pub fn build(self) -> crate::policy::Policy {
pub fn build(self) -> crate::Policy {
self.builder.into_inner().build()
}
}
@@ -137,7 +139,7 @@ impl PolicyBuilder {
rules_by_program.insert(rule.program().to_string(), rule.clone());
}
let policy = crate::policy::Policy::from_parts(
let policy = crate::Policy::from_parts(
rules_by_program,
Vec::new(),
self.host_executables_by_name.clone(),
@@ -151,8 +153,8 @@ impl PolicyBuilder {
Ok(())
}
fn build(self) -> crate::policy::Policy {
crate::policy::Policy::from_parts(
fn build(self) -> crate::Policy {
crate::Policy::from_parts(
self.rules_by_program,
self.network_rules,
self.host_executables_by_name,
@@ -257,23 +259,6 @@ fn parse_network_rule_decision(raw: &str) -> Result<Decision> {
}
}
fn error_location_from_file_span(span: FileSpan) -> ErrorLocation {
let resolved = span.resolve_span();
ErrorLocation {
path: span.filename().to_string(),
range: TextRange {
start: TextPosition {
line: resolved.begin.line + 1,
column: resolved.begin.column + 1,
},
end: TextPosition {
line: resolved.end.line + 1,
column: resolved.end.column + 1,
},
},
}
}
fn attach_validation_location(error: Error, location: Option<ErrorLocation>) -> Error {
match location {
Some(location) => error.with_location(location),
@@ -378,6 +363,7 @@ fn policy_builtins(builder: &mut GlobalsBuilder) {
.unwrap_or_default();
let location = eval
.call_stack_top_location()
.as_ref()
.map(error_location_from_file_span);
let mut builder = policy_builder(eval);
-595
View File
@@ -1,595 +0,0 @@
use crate::decision::Decision;
use crate::error::Error;
use crate::error::Result;
use crate::executable_name::executable_lookup_key;
use crate::executable_name::executable_path_lookup_key;
use crate::rule::NetworkRule;
use crate::rule::NetworkRuleProtocol;
use crate::rule::PatternToken;
use crate::rule::PrefixPattern;
use crate::rule::PrefixRule;
use crate::rule::RuleMatch;
use crate::rule::RuleRef;
use crate::rule::canonical_key;
use crate::rule::normalize_network_rule_host;
use codex_utils_absolute_path::AbsolutePathBuf;
use multimap::MultiMap;
use serde::Deserialize;
use serde::Serialize;
use std::collections::HashMap;
use std::sync::Arc;
type HeuristicsFallback<'a> = Option<&'a dyn Fn(&[String]) -> Decision>;
#[derive(Clone, Debug, Default, Eq, PartialEq)]
pub struct MatchOptions {
pub resolve_host_executables: bool,
}
#[derive(Clone, Debug)]
pub struct Policy {
insensitive_rules: MultiMap<String, RuleRef>,
rules_by_program: MultiMap<String, RuleRef>,
network_rules: Vec<NetworkRule>,
host_executables_by_name: HashMap<String, Arc<[AbsolutePathBuf]>>,
}
/// A requirements-owned execution policy with order-independent equality.
#[derive(Debug, Clone)]
pub struct RequirementsExecPolicy {
policy: Policy,
}
impl RequirementsExecPolicy {
pub fn new(policy: Policy) -> Self {
Self { policy }
}
pub fn fingerprint(&self) -> Vec<String> {
let mut entries = Vec::new();
for (program, rules) in self.policy.rules().iter_all() {
for rule in rules {
entries.push(format!("{program}:{rule:?}"));
}
}
entries.sort();
entries
}
}
impl PartialEq for RequirementsExecPolicy {
fn eq(&self, other: &Self) -> bool {
self.fingerprint() == other.fingerprint()
}
}
impl Eq for RequirementsExecPolicy {}
impl AsRef<Policy> for RequirementsExecPolicy {
fn as_ref(&self) -> &Policy {
&self.policy
}
}
impl Policy {
pub fn new(rules_by_program: MultiMap<String, RuleRef>) -> Self {
Self::from_parts(rules_by_program, Vec::new(), HashMap::new())
}
pub fn from_parts(
rules_by_program: MultiMap<String, RuleRef>,
network_rules: Vec<NetworkRule>,
host_executables_by_name: HashMap<String, Arc<[AbsolutePathBuf]>>,
) -> Self {
let insensitive_rules = rules_by_program
.iter_all()
.flat_map(|(program, rules)| {
rules
.iter()
.filter(|rule| {
rule.as_any()
.downcast_ref::<PrefixRule>()
.is_some_and(|rule| rule.pattern.canonical_matching)
})
.map(|rule| (canonical_key(program).collect::<String>(), rule.clone()))
})
.collect();
Self {
insensitive_rules,
rules_by_program,
network_rules,
host_executables_by_name,
}
}
pub fn empty() -> Self {
Self::new(MultiMap::new())
}
pub fn rules(&self) -> &MultiMap<String, RuleRef> {
&self.rules_by_program
}
pub fn network_rules(&self) -> &[NetworkRule] {
&self.network_rules
}
pub fn host_executables(&self) -> &HashMap<String, Arc<[AbsolutePathBuf]>> {
&self.host_executables_by_name
}
pub fn get_allowed_prefixes(&self) -> Vec<Vec<String>> {
let mut prefixes = Vec::new();
for (_program, rules) in self.rules_by_program.iter_all() {
for rule in rules {
let Some(prefix_rule) = rule.as_any().downcast_ref::<PrefixRule>() else {
continue;
};
if prefix_rule.decision != Decision::Allow {
continue;
}
let mut prefix = Vec::with_capacity(prefix_rule.pattern.rest.len() + 1);
prefix.push(prefix_rule.pattern.first.as_ref().to_string());
prefix.extend(prefix_rule.pattern.rest.iter().map(render_pattern_token));
prefixes.push(prefix);
}
}
prefixes.sort();
prefixes.dedup();
prefixes
}
pub fn add_prefix_rule(&mut self, prefix: &[String], decision: Decision) -> Result<()> {
let (first_token, rest) = prefix
.split_first()
.ok_or_else(|| Error::InvalidPattern("prefix cannot be empty".to_string()))?;
let rule: RuleRef = Arc::new(PrefixRule {
pattern: PrefixPattern {
canonical_matching: false,
first: Arc::from(first_token.as_str()),
rest: rest
.iter()
.map(|token| PatternToken::Single(token.clone()))
.collect::<Vec<_>>()
.into(),
},
decision,
justification: None,
});
self.rules_by_program.insert(first_token.clone(), rule);
Ok(())
}
pub fn add_network_rule(
&mut self,
host: &str,
protocol: NetworkRuleProtocol,
decision: Decision,
justification: Option<String>,
) -> Result<()> {
let host = normalize_network_rule_host(host)?;
if let Some(raw) = justification.as_deref()
&& raw.trim().is_empty()
{
return Err(Error::InvalidRule(
"justification cannot be empty".to_string(),
));
}
self.network_rules.push(NetworkRule {
host,
protocol,
decision,
justification,
});
Ok(())
}
pub fn set_host_executable_paths(&mut self, name: String, paths: Vec<AbsolutePathBuf>) {
self.host_executables_by_name.insert(name, paths.into());
}
/// Check that a transported snapshot still enforces the destination's managed rules.
/// Exact path matches can suppress basename matching, and a later network grant can
/// override a managed denial for the same host.
pub fn preserves_managed_requirements(&self, requirements: &RequirementsExecPolicy) -> bool {
let managed = requirements.as_ref();
if self.host_executables() != managed.host_executables() {
return false;
}
for (program, rules) in managed.rules().iter_all() {
if rules
.iter()
.any(|rule| !self.contains_prefix_rule(program, rule))
{
return false;
}
}
for (program, rules) in self.rules().iter_all() {
let Ok(path) = AbsolutePathBuf::try_from(program.as_str()) else {
continue;
};
// A differently cased path can shadow a managed basename at that spelling.
if rules.iter().any(|rule| {
rule.as_any()
.downcast_ref::<PrefixRule>()
.is_some_and(|rule| rule.pattern.canonical_matching)
}) && let Some(name) = executable_path_lookup_key(path.as_path())
&& managed.rules().iter_all().any(|(program, fallbacks)| {
canonical_key(program).eq(canonical_key(&name))
&& rules
.iter()
.filter(|rule| {
rule.as_any()
.downcast_ref::<PrefixRule>()
.is_some_and(|prefix| prefix.pattern.canonical_matching)
&& !managed.contains_prefix_rule(rule.program(), rule)
})
.any(|rule| {
fallbacks
.iter()
.any(|fallback| can_weaken_fallback(rule, fallback, rules))
})
})
{
return false;
}
if let Some((_, fallback_rules)) = managed.host_executable_rules(&path)
&& rules.iter().any(|rule| {
!managed.contains_prefix_rule(program, rule)
&& fallback_rules
.iter()
.any(|fallback| can_weaken_fallback(rule, fallback, rules))
})
{
return false;
}
}
let (_, required_denials) = managed.compiled_network_domains();
let (_, snapshot_denials) = self.compiled_network_domains();
required_denials
.iter()
.all(|host| snapshot_denials.contains(host))
}
fn contains_prefix_rule(&self, program: &str, rule: &RuleRef) -> bool {
let Some(prefix) = rule.as_any().downcast_ref::<PrefixRule>() else {
return false;
};
self.rules().get_vec(program).is_some_and(|rules| {
rules
.iter()
.any(|candidate| candidate.as_any().downcast_ref::<PrefixRule>() == Some(prefix))
})
}
pub fn merge_overlay(&self, overlay: &Policy) -> Policy {
let mut combined_rules = self.rules_by_program.clone();
for (program, rules) in overlay.rules_by_program.iter_all() {
for rule in rules {
combined_rules.insert(program.clone(), rule.clone());
}
}
let mut combined_network_rules = self.network_rules.clone();
combined_network_rules.extend(overlay.network_rules.iter().cloned());
let mut host_executables_by_name = self.host_executables_by_name.clone();
host_executables_by_name.extend(
overlay
.host_executables_by_name
.iter()
.map(|(name, paths)| (name.clone(), paths.clone())),
);
Policy::from_parts(
combined_rules,
combined_network_rules,
host_executables_by_name,
)
}
pub fn compiled_network_domains(&self) -> (Vec<String>, Vec<String>) {
let mut allowed = Vec::new();
let mut denied = Vec::new();
for rule in &self.network_rules {
match rule.decision {
Decision::Allow => {
denied.retain(|entry| entry != &rule.host);
upsert_domain(&mut allowed, &rule.host);
}
Decision::Forbidden => {
allowed.retain(|entry| entry != &rule.host);
upsert_domain(&mut denied, &rule.host);
}
Decision::Prompt | Decision::PromptUser => {}
}
}
(allowed, denied)
}
pub fn check<F>(&self, cmd: &[String], heuristics_fallback: &F) -> Evaluation
where
F: Fn(&[String]) -> Decision,
{
let matched_rules = self.matches_for_command_with_options(
cmd,
Some(heuristics_fallback),
&MatchOptions::default(),
);
Evaluation::from_matches(matched_rules)
}
pub fn check_with_options<F>(
&self,
cmd: &[String],
heuristics_fallback: &F,
options: &MatchOptions,
) -> Evaluation
where
F: Fn(&[String]) -> Decision,
{
let matched_rules =
self.matches_for_command_with_options(cmd, Some(heuristics_fallback), options);
Evaluation::from_matches(matched_rules)
}
/// Checks multiple commands and aggregates the results.
pub fn check_multiple<Commands, F>(
&self,
commands: Commands,
heuristics_fallback: &F,
) -> Evaluation
where
Commands: IntoIterator,
Commands::Item: AsRef<[String]>,
F: Fn(&[String]) -> Decision,
{
self.check_multiple_with_options(commands, heuristics_fallback, &MatchOptions::default())
}
pub fn check_multiple_with_options<Commands, F>(
&self,
commands: Commands,
heuristics_fallback: &F,
options: &MatchOptions,
) -> Evaluation
where
Commands: IntoIterator,
Commands::Item: AsRef<[String]>,
F: Fn(&[String]) -> Decision,
{
let matched_rules: Vec<RuleMatch> = commands
.into_iter()
.flat_map(|command| {
self.matches_for_command_with_options(
command.as_ref(),
Some(heuristics_fallback),
options,
)
})
.collect();
Evaluation::from_matches(matched_rules)
}
/// Returns matching rules for the given command. If no rules match and
/// `heuristics_fallback` is provided, returns a single
/// `HeuristicsRuleMatch` with the decision rendered by
/// `heuristics_fallback`.
///
/// If `heuristics_fallback.is_some()`, then the returned vector is
/// guaranteed to be non-empty.
pub fn matches_for_command(
&self,
cmd: &[String],
heuristics_fallback: HeuristicsFallback<'_>,
) -> Vec<RuleMatch> {
self.matches_for_command_with_options(cmd, heuristics_fallback, &MatchOptions::default())
}
pub fn matches_for_command_with_options(
&self,
cmd: &[String],
heuristics_fallback: HeuristicsFallback<'_>,
options: &MatchOptions,
) -> Vec<RuleMatch> {
let matched_rules = self
.match_exact_rules(cmd)
.filter(|matched_rules| !matched_rules.is_empty())
.or_else(|| {
options
.resolve_host_executables
.then(|| self.match_host_executable_rules(cmd))
.filter(|matched_rules| !matched_rules.is_empty())
})
.unwrap_or_default();
if matched_rules.is_empty()
&& let Some(heuristics_fallback) = heuristics_fallback
{
vec![RuleMatch::HeuristicsRuleMatch {
command: cmd.to_vec(),
decision: heuristics_fallback(cmd),
}]
} else {
matched_rules
}
}
fn match_exact_rules(&self, cmd: &[String]) -> Option<Vec<RuleMatch>> {
let first = cmd.first()?;
Some(
self.candidates(first)
.into_iter()
.filter_map(|rule| rule.matches(cmd))
.collect(),
)
}
fn candidates(&self, program: &str) -> Vec<&RuleRef> {
let mut candidates: Vec<_> = self
.rules_by_program
.get_vec(program)
.into_iter()
.flatten()
.collect();
if !self.insensitive_rules.is_empty() {
candidates.extend(
self.insensitive_rules
.get_vec(&canonical_key(program).collect::<String>())
.into_iter()
.flatten()
.filter(|rule| rule.program() != program),
);
}
candidates
}
fn match_host_executable_rules(&self, cmd: &[String]) -> Vec<RuleMatch> {
let Some(first) = cmd.first() else {
return Vec::new();
};
let Ok(program) = AbsolutePathBuf::try_from(first.clone()) else {
return Vec::new();
};
let Some((basename, rules)) = self.host_executable_rules(&program) else {
return Vec::new();
};
let basename_command = std::iter::once(basename)
.chain(cmd.iter().skip(1).cloned())
.collect::<Vec<_>>();
rules
.iter()
.filter_map(|rule| rule.matches(&basename_command))
.map(|rule_match| rule_match.with_resolved_program(&program))
.collect()
}
fn host_executable_rules(&self, path: &AbsolutePathBuf) -> Option<(String, Vec<&RuleRef>)> {
let basename = executable_path_lookup_key(path.as_path())?;
if let Some(paths) = self.host_executables_by_name.get(&basename)
&& !paths.contains(path)
{
return None;
}
let mut rules = self.candidates(&basename);
// Canonical rules can use a different name, whose declaration also restricts the path.
rules.retain(|rule| {
rule.program() == basename.as_str()
|| self
.host_executables_by_name
.get(&executable_lookup_key(rule.program()))
.is_none_or(|paths| paths.contains(path))
});
Some((basename, rules))
}
}
fn can_weaken_fallback(exact: &RuleRef, fallback: &RuleRef, path_rules: &[RuleRef]) -> bool {
let (Some(exact), Some(fallback)) = (
exact.as_any().downcast_ref::<PrefixRule>(),
fallback.as_any().downcast_ref::<PrefixRule>(),
) else {
return true;
};
if exact.decision >= fallback.decision {
return false;
}
let fallback_decision = fallback.decision;
let exact = &exact.pattern;
let fallback = &fallback.pattern;
let length = exact.rest.len().max(fallback.rest.len());
// Where both rules constrain an argument, use the case-sensitive spellings
// if available. A missing token leaves the other rule's alternatives unrestricted.
let overlap_at = |i: usize| {
let (source, filter) = if i >= exact.rest.len()
|| (i < fallback.rest.len() && exact.canonical_matching && !fallback.canonical_matching)
{
(fallback, exact)
} else {
(exact, fallback)
};
source.rest[i].alternatives().iter().filter_map(move |arg| {
let matches = filter.rest.get(i).is_none_or(|token| {
token
.alternatives()
.iter()
.any(|alt| filter.tokens_equal(alt, arg))
});
matches.then_some((arg, source.canonical_matching))
})
};
if (0..length).any(|i| overlap_at(i).next().is_none()) {
return false;
}
// A protecting exact rule must cover every spelling in the overlap.
!path_rules.iter().any(|rule| {
let Some(rule) = rule.as_any().downcast_ref::<PrefixRule>() else {
return false;
};
rule.decision >= fallback_decision
&& (!exact.canonical_matching || rule.pattern.canonical_matching)
&& rule.pattern.rest.len() <= length
&& rule.pattern.rest.iter().enumerate().all(|(i, token)| {
overlap_at(i).all(|(arg, insensitive)| {
// For a folded overlap, an exact spelling alone proves coverage
// only for ASCII tokens without letters.
let needs_fold = insensitive
&& (!arg.is_ascii() || arg.bytes().any(|b| b.is_ascii_alphabetic()));
(!needs_fold || rule.pattern.canonical_matching)
&& token
.alternatives()
.iter()
.any(|alt| rule.pattern.tokens_equal(alt, arg))
})
})
})
}
fn upsert_domain(entries: &mut Vec<String>, host: &str) {
entries.retain(|entry| entry != host);
entries.push(host.to_string());
}
fn render_pattern_token(token: &PatternToken) -> String {
match token {
PatternToken::Single(value) => value.clone(),
PatternToken::Alts(alternatives) => format!("[{}]", alternatives.join("|")),
}
}
#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Evaluation {
pub decision: Decision,
#[serde(rename = "matchedRules")]
pub matched_rules: Vec<RuleMatch>,
}
impl Evaluation {
pub fn is_match(&self) -> bool {
self.matched_rules
.iter()
.any(|rule_match| !matches!(rule_match, RuleMatch::HeuristicsRuleMatch { .. }))
}
/// Caller is responsible for ensuring that `matched_rules` is non-empty.
fn from_matches(matched_rules: Vec<RuleMatch>) -> Self {
let decision = matched_rules.iter().map(RuleMatch::decision).max();
#[expect(clippy::expect_used)]
let decision = decision.expect("invariant failed: matched_rules must be non-empty");
Self {
decision,
matched_rules,
}
}
}
-319
View File
@@ -1,319 +0,0 @@
use crate::decision::Decision;
use crate::error::Error;
use crate::error::Result;
use crate::policy::MatchOptions;
use crate::policy::Policy;
use caseless::Caseless;
use codex_utils_absolute_path::AbsolutePathBuf;
use serde::Deserialize;
use serde::Serialize;
use shlex::try_join;
use std::any::Any;
use std::fmt::Debug;
use std::sync::Arc;
use unicode_normalization::UnicodeNormalization;
/// Unicode canonical caseless comparison key: NFD, full case folding, then NFD.
pub(crate) fn canonical_key(token: &str) -> impl Iterator<Item = char> + '_ {
token.nfd().default_case_fold().nfd()
}
/// Matches a single command token, either a fixed string or one of several allowed alternatives.
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum PatternToken {
Single(String),
Alts(Vec<String>),
}
impl PatternToken {
pub fn alternatives(&self) -> &[String] {
match self {
Self::Single(expected) => std::slice::from_ref(expected),
Self::Alts(alternatives) => alternatives,
}
}
}
/// Prefix matcher for commands with support for alternative match tokens.
/// First token is fixed since we key by the first token in policy.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct PrefixPattern {
pub canonical_matching: bool,
pub first: Arc<str>,
pub rest: Arc<[PatternToken]>,
}
impl PrefixPattern {
pub(crate) fn tokens_equal(&self, a: &str, b: &str) -> bool {
if self.canonical_matching {
canonical_key(a).eq(canonical_key(b))
} else {
a == b
}
}
pub fn matches_prefix(&self, cmd: &[String]) -> Option<Vec<String>> {
let pattern_length = self.rest.len() + 1;
if cmd.len() < pattern_length || !self.tokens_equal(&cmd[0], &self.first) {
return None;
}
for (pattern_token, cmd_token) in self.rest.iter().zip(&cmd[1..pattern_length]) {
if !pattern_token
.alternatives()
.iter()
.any(|alt| self.tokens_equal(alt, cmd_token))
{
return None;
}
}
Some(cmd[..pattern_length].to_vec())
}
}
#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub enum RuleMatch {
PrefixRuleMatch {
#[serde(rename = "matchedPrefix")]
matched_prefix: Vec<String>,
decision: Decision,
#[serde(rename = "resolvedProgram", skip_serializing_if = "Option::is_none")]
resolved_program: Option<AbsolutePathBuf>,
/// Optional rationale for why this rule exists.
///
/// This can be supplied for any decision and may be surfaced in different contexts
/// (e.g., prompt reasons or rejection messages).
#[serde(skip_serializing_if = "Option::is_none")]
justification: Option<String>,
},
HeuristicsRuleMatch {
command: Vec<String>,
decision: Decision,
},
}
impl RuleMatch {
pub fn decision(&self) -> Decision {
match self {
Self::PrefixRuleMatch { decision, .. } => *decision,
Self::HeuristicsRuleMatch { decision, .. } => *decision,
}
}
pub fn with_resolved_program(self, resolved_program: &AbsolutePathBuf) -> Self {
match self {
Self::PrefixRuleMatch {
matched_prefix,
decision,
justification,
..
} => Self::PrefixRuleMatch {
matched_prefix,
decision,
resolved_program: Some(resolved_program.clone()),
justification,
},
other => other,
}
}
}
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct PrefixRule {
pub pattern: PrefixPattern,
pub decision: Decision,
pub justification: Option<String>,
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum NetworkRuleProtocol {
Http,
Https,
Socks5Tcp,
Socks5Udp,
}
impl NetworkRuleProtocol {
pub fn parse(raw: &str) -> Result<Self> {
match raw {
"http" => Ok(Self::Http),
"https" | "https_connect" | "http-connect" => Ok(Self::Https),
"socks5_tcp" => Ok(Self::Socks5Tcp),
"socks5_udp" => Ok(Self::Socks5Udp),
other => Err(Error::InvalidRule(format!(
"network_rule protocol must be one of http, https, socks5_tcp, socks5_udp (got {other})"
))),
}
}
pub fn as_policy_string(self) -> &'static str {
match self {
Self::Http => "http",
Self::Https => "https",
Self::Socks5Tcp => "socks5_tcp",
Self::Socks5Udp => "socks5_udp",
}
}
}
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct NetworkRule {
pub host: String,
pub protocol: NetworkRuleProtocol,
pub decision: Decision,
pub justification: Option<String>,
}
pub(crate) fn normalize_network_rule_host(raw: &str) -> Result<String> {
let mut host = raw.trim();
if host.is_empty() {
return Err(Error::InvalidRule(
"network_rule host cannot be empty".to_string(),
));
}
if host.contains("://") || host.contains('/') || host.contains('?') || host.contains('#') {
return Err(Error::InvalidRule(
"network_rule host must be a hostname or IP literal (without scheme or path)"
.to_string(),
));
}
if let Some(stripped) = host.strip_prefix('[') {
let Some((inside, rest)) = stripped.split_once(']') else {
return Err(Error::InvalidRule(
"network_rule host has an invalid bracketed IPv6 literal".to_string(),
));
};
let port_ok = rest
.strip_prefix(':')
.is_some_and(|port| !port.is_empty() && port.chars().all(|c| c.is_ascii_digit()));
if !rest.is_empty() && !port_ok {
return Err(Error::InvalidRule(format!(
"network_rule host contains an unsupported suffix: {raw}"
)));
}
host = inside;
} else if host.matches(':').count() == 1
&& let Some((candidate, port)) = host.rsplit_once(':')
&& !candidate.is_empty()
&& !port.is_empty()
&& port.chars().all(|c| c.is_ascii_digit())
{
host = candidate;
}
let normalized = host.trim_end_matches('.').trim().to_ascii_lowercase();
if normalized.is_empty() {
return Err(Error::InvalidRule(
"network_rule host cannot be empty".to_string(),
));
}
if normalized.contains('*') {
return Err(Error::InvalidRule(
"network_rule host must be a specific host; wildcards are not allowed".to_string(),
));
}
if normalized.chars().any(char::is_whitespace) {
return Err(Error::InvalidRule(
"network_rule host cannot contain whitespace".to_string(),
));
}
Ok(normalized)
}
pub trait Rule: Any + Debug + Send + Sync {
fn program(&self) -> &str;
fn matches(&self, cmd: &[String]) -> Option<RuleMatch>;
fn as_any(&self) -> &dyn Any;
}
pub type RuleRef = Arc<dyn Rule>;
impl Rule for PrefixRule {
fn program(&self) -> &str {
self.pattern.first.as_ref()
}
fn matches(&self, cmd: &[String]) -> Option<RuleMatch> {
self.pattern
.matches_prefix(cmd)
.map(|matched_prefix| RuleMatch::PrefixRuleMatch {
matched_prefix,
decision: self.decision,
resolved_program: None,
justification: self.justification.clone(),
})
}
fn as_any(&self) -> &dyn Any {
self
}
}
/// Count how many rules match each provided example and error if any example is unmatched.
pub(crate) fn validate_match_examples(
policy: &Policy,
rules: &[RuleRef],
matches: &[Vec<String>],
) -> Result<()> {
let mut unmatched_examples = Vec::new();
let options = MatchOptions {
resolve_host_executables: true,
};
for example in matches {
if !policy
.matches_for_command_with_options(example, /*heuristics_fallback*/ None, &options)
.is_empty()
{
continue;
}
unmatched_examples.push(
try_join(example.iter().map(String::as_str))
.unwrap_or_else(|_| "unable to render example".to_string()),
);
}
if unmatched_examples.is_empty() {
Ok(())
} else {
Err(Error::ExampleDidNotMatch {
rules: rules.iter().map(|rule| format!("{rule:?}")).collect(),
examples: unmatched_examples,
location: None,
})
}
}
/// Ensure that no rule matches any provided negative example.
pub(crate) fn validate_not_match_examples(
policy: &Policy,
_rules: &[RuleRef],
not_matches: &[Vec<String>],
) -> Result<()> {
let options = MatchOptions {
resolve_host_executables: true,
};
for example in not_matches {
if let Some(rule) = policy
.matches_for_command_with_options(example, /*heuristics_fallback*/ None, &options)
.first()
{
return Err(Error::ExampleDidMatch {
rule: format!("{rule:?}"),
example: try_join(example.iter().map(String::as_str))
.unwrap_or_else(|_| "unable to render example".to_string()),
location: None,
});
}
}
Ok(())
}