use globset::{Glob, GlobMatcher};
use serde::{Deserialize, Serialize};
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum RuleDecision {
Allow,
Ask,
Deny,
}
impl RuleDecision {
pub fn parse(word: &str) -> Option<Self> {
match word {
"allow" => Some(Self::Allow),
"ask" => Some(Self::Ask),
"deny" => Some(Self::Deny),
_ => None,
}
}
pub fn as_str(self) -> &'static str {
match self {
Self::Allow => "allow",
Self::Ask => "ask",
Self::Deny => "deny",
}
}
pub fn rank(self) -> u8 {
match self {
Self::Allow => 0,
Self::Ask => 1,
Self::Deny => 2,
}
}
}
#[derive(Debug, Clone)]
pub struct CompiledGlob {
pattern: String,
matcher: GlobMatcher,
literal_prefix_len: usize,
}
impl CompiledGlob {
pub fn compile(pattern: &str) -> Result<Self, String> {
let glob = Glob::new(pattern).map_err(|e| e.to_string())?;
Ok(Self {
pattern: pattern.to_string(),
matcher: glob.compile_matcher(),
literal_prefix_len: literal_prefix_len(pattern),
})
}
pub fn pattern(&self) -> &str {
&self.pattern
}
pub fn is_match(&self, candidate: &str) -> bool {
self.matcher.is_match(candidate)
}
pub fn literal_prefix_len(&self) -> usize {
self.literal_prefix_len
}
}
fn literal_prefix_len(pattern: &str) -> usize {
pattern
.chars()
.take_while(|c| !matches!(c, '*' | '?' | '[' | '{'))
.count()
}
#[derive(Debug, Clone)]
pub enum RuleBody {
Tool(RuleDecision),
Args(Vec<ArgRule>),
}
#[derive(Debug, Clone)]
pub struct ArgRule {
pub glob: CompiledGlob,
pub decision: RuleDecision,
}
#[derive(Debug, Clone)]
pub struct ToolRule {
pub glob: CompiledGlob,
pub body: RuleBody,
}
#[derive(Debug, Clone, Default)]
pub struct PermissionMap {
pub(crate) rules: Vec<ToolRule>,
}
impl PermissionMap {
pub fn len(&self) -> usize {
self.rules.len()
}
pub fn is_empty(&self) -> bool {
self.rules.is_empty()
}
}
#[derive(Debug, thiserror::Error)]
pub enum PermissionConfigError {
#[error(
"{source_label}: `permissions:` must be a mapping of tool globs to decisions, got {found}"
)]
NotAMapping {
source_label: String,
found: &'static str,
},
#[error(
"{source_label}: `permissions: {key}` has unknown decision `{value}` — expected one of allow, ask, deny"
)]
UnknownDecision {
source_label: String,
key: String,
value: String,
},
#[error("{source_label}: `permissions: {key}` is not a valid glob pattern: {reason}")]
BadGlob {
source_label: String,
key: String,
reason: String,
},
#[error(
"{source_label}: `permissions: {key}` must be a decision string or a table of argument globs, got {found}"
)]
BadValue {
source_label: String,
key: String,
found: &'static str,
},
#[error("{source_label}: `permissions:` block is not valid YAML: {reason}")]
Yaml {
source_label: String,
reason: String,
},
}
pub fn parse_permissions(
source_label: &str,
document: &str,
) -> Result<Option<PermissionMap>, PermissionConfigError> {
let Some(block) = extract_permissions_block(document) else {
return Ok(None);
};
let value: serde_yaml::Value =
serde_yaml::from_str(&block).map_err(|e| PermissionConfigError::Yaml {
source_label: source_label.to_string(),
reason: e.to_string(),
})?;
let body = value
.get("permissions")
.cloned()
.unwrap_or(serde_yaml::Value::Null);
compile_map(source_label, &body).map(Some)
}
fn extract_permissions_block(document: &str) -> Option<String> {
let mut lines = document.lines();
match lines.next() {
Some(first) if first.trim() == "---" => {}
_ => return None,
}
let mut collected: Vec<String> = Vec::new();
let mut key_indent = 0usize;
for line in lines {
if line.trim() == "---" {
break;
}
let indent = line.len() - line.trim_start().len();
if collected.is_empty() {
let rest = line.trim_start();
if rest.starts_with("permissions:") {
key_indent = indent;
collected.push(rest.to_string());
}
continue;
}
if line.trim().is_empty() {
collected.push(String::new());
continue;
}
if indent <= key_indent {
break;
}
collected.push(line[key_indent..].to_string());
}
(!collected.is_empty()).then(|| collected.join("\n"))
}
fn compile_map(
source_label: &str,
body: &serde_yaml::Value,
) -> Result<PermissionMap, PermissionConfigError> {
let mapping = match body {
serde_yaml::Value::Null => return Ok(PermissionMap::default()),
serde_yaml::Value::Mapping(m) => m,
other => {
return Err(PermissionConfigError::NotAMapping {
source_label: source_label.to_string(),
found: yaml_kind(other),
});
}
};
let mut rules = Vec::with_capacity(mapping.len());
for (key, value) in mapping {
let key = scalar_key(key).ok_or_else(|| PermissionConfigError::BadValue {
source_label: source_label.to_string(),
key: "<non-scalar key>".to_string(),
found: yaml_kind(key),
})?;
let glob = compile_glob(source_label, &key, &key)?;
let body = compile_body(source_label, &key, value)?;
rules.push(ToolRule { glob, body });
}
Ok(PermissionMap { rules })
}
fn compile_body(
source_label: &str,
key: &str,
value: &serde_yaml::Value,
) -> Result<RuleBody, PermissionConfigError> {
let bad_value = |key: String, found: &'static str| PermissionConfigError::BadValue {
source_label: source_label.to_string(),
key,
found,
};
match value {
serde_yaml::Value::String(word) => {
Ok(RuleBody::Tool(decision_word(source_label, key, word)?))
}
serde_yaml::Value::Mapping(args) => {
let mut compiled = Vec::with_capacity(args.len());
for (arg_key, arg_value) in args {
let arg_pattern = scalar_key(arg_key)
.ok_or_else(|| bad_value(key.to_string(), yaml_kind(arg_key)))?;
let label = format!("{key}: {arg_pattern}");
let word = arg_value
.as_str()
.ok_or_else(|| bad_value(label.clone(), yaml_kind(arg_value)))?;
compiled.push(ArgRule {
glob: compile_glob(source_label, &label, &arg_pattern)?,
decision: decision_word(source_label, &label, word)?,
});
}
Ok(RuleBody::Args(compiled))
}
other => Err(bad_value(key.to_string(), yaml_kind(other))),
}
}
fn decision_word(
source_label: &str,
key: &str,
word: &str,
) -> Result<RuleDecision, PermissionConfigError> {
RuleDecision::parse(word).ok_or_else(|| PermissionConfigError::UnknownDecision {
source_label: source_label.to_string(),
key: key.to_string(),
value: word.to_string(),
})
}
fn compile_glob(
source_label: &str,
key: &str,
pattern: &str,
) -> Result<CompiledGlob, PermissionConfigError> {
CompiledGlob::compile(pattern).map_err(|reason| PermissionConfigError::BadGlob {
source_label: source_label.to_string(),
key: key.to_string(),
reason,
})
}
fn scalar_key(value: &serde_yaml::Value) -> Option<String> {
match value {
serde_yaml::Value::String(s) => Some(s.clone()),
serde_yaml::Value::Bool(b) => Some(b.to_string()),
serde_yaml::Value::Number(n) => Some(n.to_string()),
_ => None,
}
}
fn yaml_kind(value: &serde_yaml::Value) -> &'static str {
match value {
serde_yaml::Value::Null => "null",
serde_yaml::Value::Bool(_) => "a boolean",
serde_yaml::Value::Number(_) => "a number",
serde_yaml::Value::String(_) => "a string",
serde_yaml::Value::Sequence(_) => "a list",
serde_yaml::Value::Mapping(_) => "a table",
serde_yaml::Value::Tagged(_) => "a tagged value",
}
}