Vendor Codex and land Phase 1 Epiphany state slice
This commit is contained in:
parent
130e074c69
commit
2042687e30
3959 changed files with 953751 additions and 7 deletions
337
vendor/codex/codex-rs/execpolicy/src/amend.rs
vendored
Normal file
337
vendor/codex/codex-rs/execpolicy/src/amend.rs
vendored
Normal file
|
|
@ -0,0 +1,337 @@
|
|||
use std::fs::OpenOptions;
|
||||
use std::io::Read;
|
||||
use std::io::Seek;
|
||||
use std::io::SeekFrom;
|
||||
use std::io::Write;
|
||||
use std::path::Path;
|
||||
use std::path::PathBuf;
|
||||
|
||||
use crate::decision::Decision;
|
||||
use crate::rule::NetworkRuleProtocol;
|
||||
use crate::rule::normalize_network_rule_host;
|
||||
use thiserror::Error;
|
||||
|
||||
#[derive(Debug, Error)]
|
||||
pub enum AmendError {
|
||||
#[error("prefix rule requires at least one token")]
|
||||
EmptyPrefix,
|
||||
#[error("invalid network rule: {0}")]
|
||||
InvalidNetworkRule(String),
|
||||
#[error("policy path has no parent: {path}")]
|
||||
MissingParent { path: PathBuf },
|
||||
#[error("failed to create policy directory {dir}: {source}")]
|
||||
CreatePolicyDir {
|
||||
dir: PathBuf,
|
||||
source: std::io::Error,
|
||||
},
|
||||
#[error("failed to format prefix tokens: {source}")]
|
||||
SerializePrefix { source: serde_json::Error },
|
||||
#[error("failed to serialize network rule field: {source}")]
|
||||
SerializeNetworkRule { source: serde_json::Error },
|
||||
#[error("failed to open policy file {path}: {source}")]
|
||||
OpenPolicyFile {
|
||||
path: PathBuf,
|
||||
source: std::io::Error,
|
||||
},
|
||||
#[error("failed to write to policy file {path}: {source}")]
|
||||
WritePolicyFile {
|
||||
path: PathBuf,
|
||||
source: std::io::Error,
|
||||
},
|
||||
#[error("failed to lock policy file {path}: {source}")]
|
||||
LockPolicyFile {
|
||||
path: PathBuf,
|
||||
source: std::io::Error,
|
||||
},
|
||||
#[error("failed to seek policy file {path}: {source}")]
|
||||
SeekPolicyFile {
|
||||
path: PathBuf,
|
||||
source: std::io::Error,
|
||||
},
|
||||
#[error("failed to read policy file {path}: {source}")]
|
||||
ReadPolicyFile {
|
||||
path: PathBuf,
|
||||
source: std::io::Error,
|
||||
},
|
||||
#[error("failed to read metadata for policy file {path}: {source}")]
|
||||
PolicyMetadata {
|
||||
path: PathBuf,
|
||||
source: std::io::Error,
|
||||
},
|
||||
}
|
||||
|
||||
/// Note this thread uses advisory file locking and performs blocking I/O, so it should be used with
|
||||
/// [`tokio::task::spawn_blocking`] when called from an async context.
|
||||
pub fn blocking_append_allow_prefix_rule(
|
||||
policy_path: &Path,
|
||||
prefix: &[String],
|
||||
) -> Result<(), AmendError> {
|
||||
if prefix.is_empty() {
|
||||
return Err(AmendError::EmptyPrefix);
|
||||
}
|
||||
|
||||
let tokens = prefix
|
||||
.iter()
|
||||
.map(serde_json::to_string)
|
||||
.collect::<Result<Vec<_>, _>>()
|
||||
.map_err(|source| AmendError::SerializePrefix { source })?;
|
||||
let pattern = format!("[{}]", tokens.join(", "));
|
||||
let rule = format!(r#"prefix_rule(pattern={pattern}, decision="allow")"#);
|
||||
append_rule_line(policy_path, &rule)
|
||||
}
|
||||
|
||||
/// Note this function uses advisory file locking and performs blocking I/O, so it should be used
|
||||
/// with [`tokio::task::spawn_blocking`] when called from an async context.
|
||||
pub fn blocking_append_network_rule(
|
||||
policy_path: &Path,
|
||||
host: &str,
|
||||
protocol: NetworkRuleProtocol,
|
||||
decision: Decision,
|
||||
justification: Option<&str>,
|
||||
) -> Result<(), AmendError> {
|
||||
let host = normalize_network_rule_host(host)
|
||||
.map_err(|err| AmendError::InvalidNetworkRule(err.to_string()))?;
|
||||
if let Some(raw) = justification
|
||||
&& raw.trim().is_empty()
|
||||
{
|
||||
return Err(AmendError::InvalidNetworkRule(
|
||||
"justification cannot be empty".to_string(),
|
||||
));
|
||||
}
|
||||
|
||||
let host = serde_json::to_string(&host)
|
||||
.map_err(|source| AmendError::SerializeNetworkRule { source })?;
|
||||
let protocol = serde_json::to_string(protocol.as_policy_string())
|
||||
.map_err(|source| AmendError::SerializeNetworkRule { source })?;
|
||||
let decision = serde_json::to_string(match decision {
|
||||
Decision::Allow => "allow",
|
||||
Decision::Prompt => "prompt",
|
||||
Decision::Forbidden => "deny",
|
||||
})
|
||||
.map_err(|source| AmendError::SerializeNetworkRule { source })?;
|
||||
|
||||
let mut args = vec![
|
||||
format!("host={host}"),
|
||||
format!("protocol={protocol}"),
|
||||
format!("decision={decision}"),
|
||||
];
|
||||
if let Some(justification) = justification {
|
||||
let justification = serde_json::to_string(justification)
|
||||
.map_err(|source| AmendError::SerializeNetworkRule { source })?;
|
||||
args.push(format!("justification={justification}"));
|
||||
}
|
||||
let rule = format!("network_rule({})", args.join(", "));
|
||||
append_rule_line(policy_path, &rule)
|
||||
}
|
||||
|
||||
fn append_rule_line(policy_path: &Path, rule: &str) -> Result<(), AmendError> {
|
||||
let dir = policy_path
|
||||
.parent()
|
||||
.ok_or_else(|| AmendError::MissingParent {
|
||||
path: policy_path.to_path_buf(),
|
||||
})?;
|
||||
match std::fs::create_dir(dir) {
|
||||
Ok(()) => {}
|
||||
Err(ref source) if source.kind() == std::io::ErrorKind::AlreadyExists => {}
|
||||
Err(source) => {
|
||||
return Err(AmendError::CreatePolicyDir {
|
||||
dir: dir.to_path_buf(),
|
||||
source,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
append_locked_line(policy_path, rule)
|
||||
}
|
||||
|
||||
fn append_locked_line(policy_path: &Path, line: &str) -> Result<(), AmendError> {
|
||||
let mut file = OpenOptions::new()
|
||||
.create(true)
|
||||
.read(true)
|
||||
.append(true)
|
||||
.open(policy_path)
|
||||
.map_err(|source| AmendError::OpenPolicyFile {
|
||||
path: policy_path.to_path_buf(),
|
||||
source,
|
||||
})?;
|
||||
file.lock().map_err(|source| AmendError::LockPolicyFile {
|
||||
path: policy_path.to_path_buf(),
|
||||
source,
|
||||
})?;
|
||||
|
||||
file.seek(SeekFrom::Start(0))
|
||||
.map_err(|source| AmendError::SeekPolicyFile {
|
||||
path: policy_path.to_path_buf(),
|
||||
source,
|
||||
})?;
|
||||
let mut contents = String::new();
|
||||
file.read_to_string(&mut contents)
|
||||
.map_err(|source| AmendError::ReadPolicyFile {
|
||||
path: policy_path.to_path_buf(),
|
||||
source,
|
||||
})?;
|
||||
|
||||
if contents.lines().any(|existing| existing == line) {
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
if !contents.is_empty() && !contents.ends_with('\n') {
|
||||
file.write_all(b"\n")
|
||||
.map_err(|source| AmendError::WritePolicyFile {
|
||||
path: policy_path.to_path_buf(),
|
||||
source,
|
||||
})?;
|
||||
}
|
||||
|
||||
file.write_all(format!("{line}\n").as_bytes())
|
||||
.map_err(|source| AmendError::WritePolicyFile {
|
||||
path: policy_path.to_path_buf(),
|
||||
source,
|
||||
})?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use pretty_assertions::assert_eq;
|
||||
use tempfile::tempdir;
|
||||
|
||||
#[test]
|
||||
fn appends_rule_and_creates_directories() {
|
||||
let tmp = tempdir().expect("create temp dir");
|
||||
let policy_path = tmp.path().join("rules").join("default.rules");
|
||||
|
||||
blocking_append_allow_prefix_rule(
|
||||
&policy_path,
|
||||
&[String::from("echo"), String::from("Hello, world!")],
|
||||
)
|
||||
.expect("append rule");
|
||||
|
||||
let contents = std::fs::read_to_string(&policy_path).expect("default.rules should exist");
|
||||
assert_eq!(
|
||||
contents,
|
||||
r#"prefix_rule(pattern=["echo", "Hello, world!"], decision="allow")
|
||||
"#
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn appends_rule_without_duplicate_newline() {
|
||||
let tmp = tempdir().expect("create temp dir");
|
||||
let policy_path = tmp.path().join("rules").join("default.rules");
|
||||
std::fs::create_dir_all(policy_path.parent().unwrap()).expect("create policy dir");
|
||||
std::fs::write(
|
||||
&policy_path,
|
||||
r#"prefix_rule(pattern=["ls"], decision="allow")
|
||||
"#,
|
||||
)
|
||||
.expect("write seed rule");
|
||||
|
||||
blocking_append_allow_prefix_rule(
|
||||
&policy_path,
|
||||
&[String::from("echo"), String::from("Hello, world!")],
|
||||
)
|
||||
.expect("append rule");
|
||||
|
||||
let contents = std::fs::read_to_string(&policy_path).expect("read policy");
|
||||
assert_eq!(
|
||||
contents,
|
||||
r#"prefix_rule(pattern=["ls"], decision="allow")
|
||||
prefix_rule(pattern=["echo", "Hello, world!"], decision="allow")
|
||||
"#
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn inserts_newline_when_missing_before_append() {
|
||||
let tmp = tempdir().expect("create temp dir");
|
||||
let policy_path = tmp.path().join("rules").join("default.rules");
|
||||
std::fs::create_dir_all(policy_path.parent().unwrap()).expect("create policy dir");
|
||||
std::fs::write(
|
||||
&policy_path,
|
||||
r#"prefix_rule(pattern=["ls"], decision="allow")"#,
|
||||
)
|
||||
.expect("write seed rule without newline");
|
||||
|
||||
blocking_append_allow_prefix_rule(
|
||||
&policy_path,
|
||||
&[String::from("echo"), String::from("Hello, world!")],
|
||||
)
|
||||
.expect("append rule");
|
||||
|
||||
let contents = std::fs::read_to_string(&policy_path).expect("read policy");
|
||||
assert_eq!(
|
||||
contents,
|
||||
r#"prefix_rule(pattern=["ls"], decision="allow")
|
||||
prefix_rule(pattern=["echo", "Hello, world!"], decision="allow")
|
||||
"#
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn appends_network_rule() {
|
||||
let tmp = tempdir().expect("create temp dir");
|
||||
let policy_path = tmp.path().join("rules").join("default.rules");
|
||||
|
||||
blocking_append_network_rule(
|
||||
&policy_path,
|
||||
"Api.GitHub.com",
|
||||
NetworkRuleProtocol::Https,
|
||||
Decision::Allow,
|
||||
Some("Allow https_connect access to api.github.com"),
|
||||
)
|
||||
.expect("append network rule");
|
||||
|
||||
let contents = std::fs::read_to_string(&policy_path).expect("read policy");
|
||||
assert_eq!(
|
||||
contents,
|
||||
r#"network_rule(host="api.github.com", protocol="https", decision="allow", justification="Allow https_connect access to api.github.com")
|
||||
"#
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn appends_prefix_and_network_rules() {
|
||||
let tmp = tempdir().expect("create temp dir");
|
||||
let policy_path = tmp.path().join("rules").join("default.rules");
|
||||
|
||||
blocking_append_allow_prefix_rule(&policy_path, &[String::from("curl")])
|
||||
.expect("append prefix rule");
|
||||
blocking_append_network_rule(
|
||||
&policy_path,
|
||||
"api.github.com",
|
||||
NetworkRuleProtocol::Https,
|
||||
Decision::Allow,
|
||||
Some("Allow https_connect access to api.github.com"),
|
||||
)
|
||||
.expect("append network rule");
|
||||
|
||||
let contents = std::fs::read_to_string(&policy_path).expect("read policy");
|
||||
assert_eq!(
|
||||
contents,
|
||||
r#"prefix_rule(pattern=["curl"], decision="allow")
|
||||
network_rule(host="api.github.com", protocol="https", decision="allow", justification="Allow https_connect access to api.github.com")
|
||||
"#
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_wildcard_network_rule_host() {
|
||||
let tmp = tempdir().expect("create temp dir");
|
||||
let policy_path = tmp.path().join("rules").join("default.rules");
|
||||
let err = blocking_append_network_rule(
|
||||
&policy_path,
|
||||
"*.example.com",
|
||||
NetworkRuleProtocol::Https,
|
||||
Decision::Allow,
|
||||
/*justification*/ None,
|
||||
)
|
||||
.expect_err("wildcards should be rejected");
|
||||
assert_eq!(
|
||||
err.to_string(),
|
||||
"invalid network rule: invalid rule: network_rule host must be a specific host; wildcards are not allowed"
|
||||
);
|
||||
}
|
||||
}
|
||||
27
vendor/codex/codex-rs/execpolicy/src/decision.rs
vendored
Normal file
27
vendor/codex/codex-rs/execpolicy/src/decision.rs
vendored
Normal file
|
|
@ -0,0 +1,27 @@
|
|||
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 explicit user approval; rejected outright when running with `approval_policy="never"`.
|
||||
Prompt,
|
||||
/// 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())),
|
||||
}
|
||||
}
|
||||
}
|
||||
101
vendor/codex/codex-rs/execpolicy/src/error.rs
vendored
Normal file
101
vendor/codex/codex-rs/execpolicy/src/error.rs
vendored
Normal file
|
|
@ -0,0 +1,101 @@
|
|||
use starlark::Error as StarlarkError;
|
||||
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,
|
||||
}
|
||||
|
||||
#[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),
|
||||
}
|
||||
|
||||
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,
|
||||
}
|
||||
}
|
||||
|
||||
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,
|
||||
}
|
||||
}
|
||||
}
|
||||
95
vendor/codex/codex-rs/execpolicy/src/execpolicycheck.rs
vendored
Normal file
95
vendor/codex/codex-rs/execpolicy/src/execpolicycheck.rs
vendored
Normal file
|
|
@ -0,0 +1,95 @@
|
|||
use std::fs;
|
||||
use std::path::PathBuf;
|
||||
|
||||
use anyhow::Context;
|
||||
use anyhow::Result;
|
||||
use clap::Parser;
|
||||
use serde::Serialize;
|
||||
|
||||
use crate::Decision;
|
||||
use crate::MatchOptions;
|
||||
use crate::Policy;
|
||||
use crate::PolicyParser;
|
||||
use crate::RuleMatch;
|
||||
|
||||
/// Arguments for evaluating a command against one or more execpolicy files.
|
||||
#[derive(Debug, Parser, Clone)]
|
||||
pub struct ExecPolicyCheckCommand {
|
||||
/// Paths to execpolicy rule files to evaluate (repeatable).
|
||||
#[arg(short = 'r', long = "rules", value_name = "PATH", required = true)]
|
||||
pub rules: Vec<PathBuf>,
|
||||
|
||||
/// Pretty-print the JSON output.
|
||||
#[arg(long)]
|
||||
pub pretty: bool,
|
||||
|
||||
/// Resolve absolute program paths against basename rules, gated by any
|
||||
/// `host_executable()` definitions in the loaded policy files.
|
||||
#[arg(long)]
|
||||
pub resolve_host_executables: bool,
|
||||
|
||||
/// Command tokens to check against the policy.
|
||||
#[arg(
|
||||
value_name = "COMMAND",
|
||||
required = true,
|
||||
trailing_var_arg = true,
|
||||
allow_hyphen_values = true
|
||||
)]
|
||||
pub command: Vec<String>,
|
||||
}
|
||||
|
||||
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.rules)?;
|
||||
let matched_rules = policy.matches_for_command_with_options(
|
||||
&self.command,
|
||||
/*heuristics_fallback*/ None,
|
||||
&MatchOptions {
|
||||
resolve_host_executables: self.resolve_host_executables,
|
||||
},
|
||||
);
|
||||
|
||||
let json = format_matches_json(&matched_rules, self.pretty)?;
|
||||
println!("{json}");
|
||||
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
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(&output).map_err(Into::into)
|
||||
} else {
|
||||
serde_json::to_string(&output).map_err(Into::into)
|
||||
}
|
||||
}
|
||||
|
||||
pub fn load_policies(policy_paths: &[PathBuf]) -> Result<Policy> {
|
||||
let mut parser = PolicyParser::new();
|
||||
|
||||
for policy_path in policy_paths {
|
||||
let policy_file_contents = fs::read_to_string(policy_path)
|
||||
.with_context(|| format!("failed to read policy at {}", policy_path.display()))?;
|
||||
let policy_identifier = policy_path.to_string_lossy().to_string();
|
||||
parser
|
||||
.parse(&policy_identifier, &policy_file_contents)
|
||||
.with_context(|| format!("failed to parse policy at {}", policy_path.display()))?;
|
||||
}
|
||||
|
||||
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>,
|
||||
}
|
||||
29
vendor/codex/codex-rs/execpolicy/src/executable_name.rs
vendored
Normal file
29
vendor/codex/codex-rs/execpolicy/src/executable_name.rs
vendored
Normal file
|
|
@ -0,0 +1,29 @@
|
|||
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)
|
||||
}
|
||||
30
vendor/codex/codex-rs/execpolicy/src/lib.rs
vendored
Normal file
30
vendor/codex/codex-rs/execpolicy/src/lib.rs
vendored
Normal file
|
|
@ -0,0 +1,30 @@
|
|||
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;
|
||||
|
||||
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 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 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;
|
||||
18
vendor/codex/codex-rs/execpolicy/src/main.rs
vendored
Normal file
18
vendor/codex/codex-rs/execpolicy/src/main.rs
vendored
Normal file
|
|
@ -0,0 +1,18 @@
|
|||
use anyhow::Result;
|
||||
use clap::Parser;
|
||||
use codex_execpolicy::ExecPolicyCheckCommand;
|
||||
|
||||
/// CLI for evaluating exec policies
|
||||
#[derive(Parser)]
|
||||
#[command(name = "codex-execpolicy")]
|
||||
enum Cli {
|
||||
/// Evaluate a command against a policy.
|
||||
Check(ExecPolicyCheckCommand),
|
||||
}
|
||||
|
||||
fn main() -> Result<()> {
|
||||
let cli = Cli::parse();
|
||||
match cli {
|
||||
Cli::Check(cmd) => cmd.run(),
|
||||
}
|
||||
}
|
||||
472
vendor/codex/codex-rs/execpolicy/src/parser.rs
vendored
Normal file
472
vendor/codex/codex-rs/execpolicy/src/parser.rs
vendored
Normal file
|
|
@ -0,0 +1,472 @@
|
|||
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;
|
||||
use starlark::starlark_module;
|
||||
use starlark::syntax::AstModule;
|
||||
use starlark::syntax::Dialect;
|
||||
use starlark::values::Value;
|
||||
use starlark::values::list::ListRef;
|
||||
use starlark::values::list::UnpackList;
|
||||
use starlark::values::none::NoneType;
|
||||
use std::cell::RefCell;
|
||||
use std::cell::RefMut;
|
||||
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::rule::NetworkRule;
|
||||
use crate::rule::NetworkRuleProtocol;
|
||||
use crate::rule::PatternToken;
|
||||
use crate::rule::PrefixPattern;
|
||||
use crate::rule::PrefixRule;
|
||||
use crate::rule::RuleRef;
|
||||
use crate::rule::validate_match_examples;
|
||||
use crate::rule::validate_not_match_examples;
|
||||
|
||||
pub struct PolicyParser {
|
||||
builder: RefCell<PolicyBuilder>,
|
||||
}
|
||||
|
||||
impl Default for PolicyParser {
|
||||
fn default() -> Self {
|
||||
Self::new()
|
||||
}
|
||||
}
|
||||
|
||||
impl PolicyParser {
|
||||
pub fn new() -> Self {
|
||||
Self {
|
||||
builder: RefCell::new(PolicyBuilder::new()),
|
||||
}
|
||||
}
|
||||
|
||||
/// 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<()> {
|
||||
let pending_validation_count = self.builder.borrow().pending_example_validations.len();
|
||||
let mut dialect = Dialect::Extended.clone();
|
||||
dialect.enable_f_strings = true;
|
||||
let ast = AstModule::parse(
|
||||
policy_identifier,
|
||||
policy_file_contents.to_string(),
|
||||
&dialect,
|
||||
)
|
||||
.map_err(Error::Starlark)?;
|
||||
let globals = GlobalsBuilder::standard().with(policy_builtins).build();
|
||||
let module = Module::new();
|
||||
{
|
||||
let mut eval = Evaluator::new(&module);
|
||||
eval.extra = Some(&self.builder);
|
||||
eval.eval_module(ast, &globals).map_err(Error::Starlark)?;
|
||||
}
|
||||
self.builder
|
||||
.borrow()
|
||||
.validate_pending_examples_from(pending_validation_count)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn build(self) -> crate::policy::Policy {
|
||||
self.builder.into_inner().build()
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, ProvidesStaticType)]
|
||||
struct PolicyBuilder {
|
||||
rules_by_program: MultiMap<String, RuleRef>,
|
||||
network_rules: Vec<NetworkRule>,
|
||||
host_executables_by_name: HashMap<String, Arc<[AbsolutePathBuf]>>,
|
||||
pending_example_validations: Vec<PendingExampleValidation>,
|
||||
}
|
||||
|
||||
impl PolicyBuilder {
|
||||
fn new() -> Self {
|
||||
Self {
|
||||
rules_by_program: MultiMap::new(),
|
||||
network_rules: Vec::new(),
|
||||
host_executables_by_name: HashMap::new(),
|
||||
pending_example_validations: Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
fn add_rule(&mut self, rule: RuleRef) {
|
||||
self.rules_by_program
|
||||
.insert(rule.program().to_string(), rule);
|
||||
}
|
||||
|
||||
fn add_network_rule(&mut self, rule: NetworkRule) {
|
||||
self.network_rules.push(rule);
|
||||
}
|
||||
|
||||
fn add_host_executable(&mut self, name: String, paths: Vec<AbsolutePathBuf>) {
|
||||
self.host_executables_by_name.insert(name, paths.into());
|
||||
}
|
||||
|
||||
fn add_pending_example_validation(
|
||||
&mut self,
|
||||
rules: Vec<RuleRef>,
|
||||
matches: Vec<Vec<String>>,
|
||||
not_matches: Vec<Vec<String>>,
|
||||
location: Option<ErrorLocation>,
|
||||
) {
|
||||
self.pending_example_validations
|
||||
.push(PendingExampleValidation {
|
||||
rules,
|
||||
matches,
|
||||
not_matches,
|
||||
location,
|
||||
});
|
||||
}
|
||||
|
||||
fn validate_pending_examples_from(&self, start: usize) -> Result<()> {
|
||||
for validation in &self.pending_example_validations[start..] {
|
||||
let mut rules_by_program = MultiMap::new();
|
||||
for rule in &validation.rules {
|
||||
rules_by_program.insert(rule.program().to_string(), rule.clone());
|
||||
}
|
||||
|
||||
let policy = crate::policy::Policy::from_parts(
|
||||
rules_by_program,
|
||||
Vec::new(),
|
||||
self.host_executables_by_name.clone(),
|
||||
);
|
||||
validate_not_match_examples(&policy, &validation.rules, &validation.not_matches)
|
||||
.map_err(|error| attach_validation_location(error, validation.location.clone()))?;
|
||||
validate_match_examples(&policy, &validation.rules, &validation.matches)
|
||||
.map_err(|error| attach_validation_location(error, validation.location.clone()))?;
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn build(self) -> crate::policy::Policy {
|
||||
crate::policy::Policy::from_parts(
|
||||
self.rules_by_program,
|
||||
self.network_rules,
|
||||
self.host_executables_by_name,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
struct PendingExampleValidation {
|
||||
rules: Vec<RuleRef>,
|
||||
matches: Vec<Vec<String>>,
|
||||
not_matches: Vec<Vec<String>>,
|
||||
location: Option<ErrorLocation>,
|
||||
}
|
||||
|
||||
fn parse_pattern<'v>(pattern: UnpackList<Value<'v>>) -> Result<Vec<PatternToken>> {
|
||||
let tokens: Vec<PatternToken> = pattern
|
||||
.items
|
||||
.into_iter()
|
||||
.map(parse_pattern_token)
|
||||
.collect::<Result<_>>()?;
|
||||
if tokens.is_empty() {
|
||||
Err(Error::InvalidPattern("pattern cannot be empty".to_string()))
|
||||
} else {
|
||||
Ok(tokens)
|
||||
}
|
||||
}
|
||||
|
||||
fn parse_pattern_token<'v>(value: Value<'v>) -> Result<PatternToken> {
|
||||
if let Some(s) = value.unpack_str() {
|
||||
Ok(PatternToken::Single(s.to_string()))
|
||||
} else if let Some(list) = ListRef::from_value(value) {
|
||||
let tokens: Vec<String> = list
|
||||
.content()
|
||||
.iter()
|
||||
.map(|value| {
|
||||
value
|
||||
.unpack_str()
|
||||
.ok_or_else(|| {
|
||||
Error::InvalidPattern(format!(
|
||||
"pattern alternative must be a string (got {})",
|
||||
value.get_type()
|
||||
))
|
||||
})
|
||||
.map(str::to_string)
|
||||
})
|
||||
.collect::<Result<_>>()?;
|
||||
|
||||
match tokens.as_slice() {
|
||||
[] => Err(Error::InvalidPattern(
|
||||
"pattern alternatives cannot be empty".to_string(),
|
||||
)),
|
||||
[single] => Ok(PatternToken::Single(single.clone())),
|
||||
_ => Ok(PatternToken::Alts(tokens)),
|
||||
}
|
||||
} else {
|
||||
Err(Error::InvalidPattern(format!(
|
||||
"pattern element must be a string or list of strings (got {})",
|
||||
value.get_type()
|
||||
)))
|
||||
}
|
||||
}
|
||||
|
||||
fn parse_examples<'v>(examples: UnpackList<Value<'v>>) -> Result<Vec<Vec<String>>> {
|
||||
examples.items.into_iter().map(parse_example).collect()
|
||||
}
|
||||
|
||||
fn parse_literal_absolute_path(raw: &str) -> Result<AbsolutePathBuf> {
|
||||
if !Path::new(raw).is_absolute() {
|
||||
return Err(Error::InvalidRule(format!(
|
||||
"host_executable paths must be absolute (got {raw})"
|
||||
)));
|
||||
}
|
||||
|
||||
AbsolutePathBuf::try_from(raw.to_string())
|
||||
.map_err(|error| Error::InvalidRule(format!("invalid absolute path `{raw}`: {error}")))
|
||||
}
|
||||
|
||||
fn validate_host_executable_name(name: &str) -> Result<()> {
|
||||
if name.is_empty() {
|
||||
return Err(Error::InvalidRule(
|
||||
"host_executable name cannot be empty".to_string(),
|
||||
));
|
||||
}
|
||||
|
||||
let path = Path::new(name);
|
||||
if path.components().count() != 1
|
||||
|| path.file_name().and_then(|value| value.to_str()) != Some(name)
|
||||
{
|
||||
return Err(Error::InvalidRule(format!(
|
||||
"host_executable name must be a bare executable name (got {name})"
|
||||
)));
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn parse_network_rule_decision(raw: &str) -> Result<Decision> {
|
||||
match raw {
|
||||
"deny" => Ok(Decision::Forbidden),
|
||||
other => Decision::parse(other),
|
||||
}
|
||||
}
|
||||
|
||||
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),
|
||||
None => error,
|
||||
}
|
||||
}
|
||||
|
||||
fn parse_example<'v>(value: Value<'v>) -> Result<Vec<String>> {
|
||||
if let Some(raw) = value.unpack_str() {
|
||||
parse_string_example(raw)
|
||||
} else if let Some(list) = ListRef::from_value(value) {
|
||||
parse_list_example(list)
|
||||
} else {
|
||||
Err(Error::InvalidExample(format!(
|
||||
"example must be a string or list of strings (got {})",
|
||||
value.get_type()
|
||||
)))
|
||||
}
|
||||
}
|
||||
|
||||
fn parse_string_example(raw: &str) -> Result<Vec<String>> {
|
||||
let tokens = shlex::split(raw).ok_or_else(|| {
|
||||
Error::InvalidExample("example string has invalid shell syntax".to_string())
|
||||
})?;
|
||||
|
||||
if tokens.is_empty() {
|
||||
Err(Error::InvalidExample(
|
||||
"example cannot be an empty string".to_string(),
|
||||
))
|
||||
} else {
|
||||
Ok(tokens)
|
||||
}
|
||||
}
|
||||
|
||||
fn parse_list_example(list: &ListRef) -> Result<Vec<String>> {
|
||||
let tokens: Vec<String> = list
|
||||
.content()
|
||||
.iter()
|
||||
.map(|value| {
|
||||
value
|
||||
.unpack_str()
|
||||
.ok_or_else(|| {
|
||||
Error::InvalidExample(format!(
|
||||
"example tokens must be strings (got {})",
|
||||
value.get_type()
|
||||
))
|
||||
})
|
||||
.map(str::to_string)
|
||||
})
|
||||
.collect::<Result<_>>()?;
|
||||
|
||||
if tokens.is_empty() {
|
||||
Err(Error::InvalidExample(
|
||||
"example cannot be an empty list".to_string(),
|
||||
))
|
||||
} else {
|
||||
Ok(tokens)
|
||||
}
|
||||
}
|
||||
|
||||
fn policy_builder<'v, 'a>(eval: &Evaluator<'v, 'a, '_>) -> RefMut<'a, PolicyBuilder> {
|
||||
#[expect(clippy::expect_used)]
|
||||
eval.extra
|
||||
.as_ref()
|
||||
.expect("policy_builder requires Evaluator.extra to be populated")
|
||||
.downcast_ref::<RefCell<PolicyBuilder>>()
|
||||
.expect("Evaluator.extra must contain a PolicyBuilder")
|
||||
.borrow_mut()
|
||||
}
|
||||
|
||||
#[starlark_module]
|
||||
fn policy_builtins(builder: &mut GlobalsBuilder) {
|
||||
fn prefix_rule<'v>(
|
||||
pattern: UnpackList<Value<'v>>,
|
||||
decision: Option<&'v str>,
|
||||
r#match: Option<UnpackList<Value<'v>>>,
|
||||
not_match: Option<UnpackList<Value<'v>>>,
|
||||
justification: Option<&'v str>,
|
||||
eval: &mut Evaluator<'v, '_, '_>,
|
||||
) -> anyhow::Result<NoneType> {
|
||||
let decision = match decision {
|
||||
Some(raw) => Decision::parse(raw)?,
|
||||
None => Decision::Allow,
|
||||
};
|
||||
|
||||
let justification = match justification {
|
||||
Some(raw) if raw.trim().is_empty() => {
|
||||
return Err(Error::InvalidRule("justification cannot be empty".to_string()).into());
|
||||
}
|
||||
Some(raw) => Some(raw.to_string()),
|
||||
None => None,
|
||||
};
|
||||
|
||||
let pattern_tokens = parse_pattern(pattern)?;
|
||||
|
||||
let matches: Vec<Vec<String>> =
|
||||
r#match.map(parse_examples).transpose()?.unwrap_or_default();
|
||||
let not_matches: Vec<Vec<String>> = not_match
|
||||
.map(parse_examples)
|
||||
.transpose()?
|
||||
.unwrap_or_default();
|
||||
let location = eval
|
||||
.call_stack_top_location()
|
||||
.map(error_location_from_file_span);
|
||||
|
||||
let mut builder = policy_builder(eval);
|
||||
|
||||
let (first_token, remaining_tokens) = pattern_tokens
|
||||
.split_first()
|
||||
.ok_or_else(|| Error::InvalidPattern("pattern cannot be empty".to_string()))?;
|
||||
|
||||
let rest: Arc<[PatternToken]> = remaining_tokens.to_vec().into();
|
||||
|
||||
let rules: Vec<RuleRef> = first_token
|
||||
.alternatives()
|
||||
.iter()
|
||||
.map(|head| {
|
||||
Arc::new(PrefixRule {
|
||||
pattern: PrefixPattern {
|
||||
first: Arc::from(head.as_str()),
|
||||
rest: rest.clone(),
|
||||
},
|
||||
decision,
|
||||
justification: justification.clone(),
|
||||
}) as RuleRef
|
||||
})
|
||||
.collect();
|
||||
|
||||
builder.add_pending_example_validation(rules.clone(), matches, not_matches, location);
|
||||
rules.into_iter().for_each(|rule| builder.add_rule(rule));
|
||||
Ok(NoneType)
|
||||
}
|
||||
|
||||
fn network_rule<'v>(
|
||||
host: &'v str,
|
||||
protocol: &'v str,
|
||||
decision: &'v str,
|
||||
justification: Option<&'v str>,
|
||||
eval: &mut Evaluator<'v, '_, '_>,
|
||||
) -> anyhow::Result<NoneType> {
|
||||
let protocol = NetworkRuleProtocol::parse(protocol)?;
|
||||
let decision = parse_network_rule_decision(decision)?;
|
||||
let justification = match justification {
|
||||
Some(raw) if raw.trim().is_empty() => {
|
||||
return Err(Error::InvalidRule("justification cannot be empty".to_string()).into());
|
||||
}
|
||||
Some(raw) => Some(raw.to_string()),
|
||||
None => None,
|
||||
};
|
||||
|
||||
let mut builder = policy_builder(eval);
|
||||
builder.add_network_rule(NetworkRule {
|
||||
host: crate::rule::normalize_network_rule_host(host)?,
|
||||
protocol,
|
||||
decision,
|
||||
justification,
|
||||
});
|
||||
Ok(NoneType)
|
||||
}
|
||||
|
||||
fn host_executable<'v>(
|
||||
name: &'v str,
|
||||
paths: UnpackList<Value<'v>>,
|
||||
eval: &mut Evaluator<'v, '_, '_>,
|
||||
) -> anyhow::Result<NoneType> {
|
||||
validate_host_executable_name(name)?;
|
||||
|
||||
let mut parsed_paths = Vec::new();
|
||||
for value in paths.items {
|
||||
let raw = value.unpack_str().ok_or_else(|| {
|
||||
Error::InvalidRule(format!(
|
||||
"host_executable paths must be strings (got {})",
|
||||
value.get_type()
|
||||
))
|
||||
})?;
|
||||
let path = parse_literal_absolute_path(raw)?;
|
||||
let Some(path_name) = executable_path_lookup_key(path.as_path()) else {
|
||||
return Err(Error::InvalidRule(format!(
|
||||
"host_executable path `{raw}` must have basename `{name}`"
|
||||
))
|
||||
.into());
|
||||
};
|
||||
if path_name != executable_lookup_key(name) {
|
||||
return Err(Error::InvalidRule(format!(
|
||||
"host_executable path `{raw}` must have basename `{name}`"
|
||||
))
|
||||
.into());
|
||||
}
|
||||
if !parsed_paths.iter().any(|existing| existing == &path) {
|
||||
parsed_paths.push(path);
|
||||
}
|
||||
}
|
||||
|
||||
policy_builder(eval).add_host_executable(executable_lookup_key(name), parsed_paths);
|
||||
Ok(NoneType)
|
||||
}
|
||||
}
|
||||
375
vendor/codex/codex-rs/execpolicy/src/policy.rs
vendored
Normal file
375
vendor/codex/codex-rs/execpolicy/src/policy.rs
vendored
Normal file
|
|
@ -0,0 +1,375 @@
|
|||
use crate::decision::Decision;
|
||||
use crate::error::Error;
|
||||
use crate::error::Result;
|
||||
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::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 {
|
||||
rules_by_program: MultiMap<String, RuleRef>,
|
||||
network_rules: Vec<NetworkRule>,
|
||||
host_executables_by_name: HashMap<String, Arc<[AbsolutePathBuf]>>,
|
||||
}
|
||||
|
||||
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 {
|
||||
Self {
|
||||
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 {
|
||||
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());
|
||||
}
|
||||
|
||||
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 => {}
|
||||
}
|
||||
}
|
||||
|
||||
(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.rules_by_program
|
||||
.get_vec(first)
|
||||
.map(|rules| rules.iter().filter_map(|rule| rule.matches(cmd)).collect())
|
||||
.unwrap_or_default(),
|
||||
)
|
||||
}
|
||||
|
||||
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) = executable_path_lookup_key(program.as_path()) else {
|
||||
return Vec::new();
|
||||
};
|
||||
let Some(rules) = self.rules_by_program.get_vec(&basename) else {
|
||||
return Vec::new();
|
||||
};
|
||||
if let Some(paths) = self.host_executables_by_name.get(&basename)
|
||||
&& !paths.iter().any(|path| path == &program)
|
||||
{
|
||||
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 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,
|
||||
}
|
||||
}
|
||||
}
|
||||
306
vendor/codex/codex-rs/execpolicy/src/rule.rs
vendored
Normal file
306
vendor/codex/codex-rs/execpolicy/src/rule.rs
vendored
Normal file
|
|
@ -0,0 +1,306 @@
|
|||
use crate::decision::Decision;
|
||||
use crate::error::Error;
|
||||
use crate::error::Result;
|
||||
use crate::policy::MatchOptions;
|
||||
use crate::policy::Policy;
|
||||
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;
|
||||
|
||||
/// 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 {
|
||||
fn matches(&self, token: &str) -> bool {
|
||||
match self {
|
||||
Self::Single(expected) => expected == token,
|
||||
Self::Alts(alternatives) => alternatives.iter().any(|alt| alt == token),
|
||||
}
|
||||
}
|
||||
|
||||
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 first: Arc<str>,
|
||||
pub rest: Arc<[PatternToken]>,
|
||||
}
|
||||
|
||||
impl PrefixPattern {
|
||||
pub fn matches_prefix(&self, cmd: &[String]) -> Option<Vec<String>> {
|
||||
let pattern_length = self.rest.len() + 1;
|
||||
if cmd.len() < pattern_length || cmd[0] != self.first.as_ref() {
|
||||
return None;
|
||||
}
|
||||
|
||||
for (pattern_token, cmd_token) in self.rest.iter().zip(&cmd[1..pattern_length]) {
|
||||
if !pattern_token.matches(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(())
|
||||
}
|
||||
Reference in a new issue