.botignore matches a path or any parent, with the path tried first, so !vendor/keep beats vendor/. Policy::check takes a relative path against the root and also checks the path as the file system resolves it, spelled from the root as given, so a link or a root behind a link hides nothing. session_dir: the payload's cwd if absolute, else the process directory, for both hooks; fermata check and the hook make paths absolute.
184 lines
6.6 KiB
Rust
184 lines
6.6 KiB
Rust
use crate::core::botignore::{BotignoreError, BotignoreSet};
|
|
use crate::core::decision::{Decision, Reason, Rule};
|
|
use crate::core::op::Op;
|
|
use crate::core::paths::absolute;
|
|
use crate::core::secrets::config::{PolicyConfig, SecretsConfig};
|
|
use std::path::{Path, PathBuf};
|
|
use thiserror::Error;
|
|
|
|
#[derive(Debug, Error)]
|
|
pub enum PolicyError {
|
|
#[error(transparent)]
|
|
Botignore(#[from] BotignoreError),
|
|
#[error("invalid pattern in .botsecrets: {0}")]
|
|
BadPattern(String),
|
|
}
|
|
|
|
pub struct Policy {
|
|
root: PathBuf,
|
|
botignore: BotignoreSet,
|
|
policy: PolicyConfig,
|
|
read_globs: globset::GlobSet,
|
|
write_globs: globset::GlobSet,
|
|
read_patterns: Vec<String>,
|
|
write_patterns: Vec<String>,
|
|
}
|
|
|
|
impl Policy {
|
|
pub fn load(root: &Path) -> Result<Self, PolicyError> {
|
|
let botignore = BotignoreSet::load(root)?;
|
|
|
|
// Load policy from .botsecrets (or fermata.toml fallback).
|
|
// A layer that fails costs only its own rules (fail-open).
|
|
let policy = SecretsConfig::load_or_default(root).0.policy.unwrap_or_default();
|
|
|
|
let (read_globs, read_patterns) = compile_globs(
|
|
policy.read.as_ref().map(|r| r.patterns.as_slice()).unwrap_or(&[]),
|
|
)?;
|
|
let (write_globs, write_patterns) = compile_globs(
|
|
policy.write.as_ref().map(|r| r.patterns.as_slice()).unwrap_or(&[]),
|
|
)?;
|
|
|
|
Ok(Self {
|
|
root: root.to_path_buf(),
|
|
botignore,
|
|
policy,
|
|
read_globs,
|
|
write_globs,
|
|
read_patterns,
|
|
write_patterns,
|
|
})
|
|
}
|
|
|
|
pub fn check_command(&self, command: &str) -> Result<Decision, PolicyError> {
|
|
let bash = match self.policy.bash.as_ref() {
|
|
Some(b) => b,
|
|
None => return Ok(Decision::Allow),
|
|
};
|
|
|
|
if let Some(pat) = match_command(command, &bash.deny)? {
|
|
return Ok(Decision::Deny(Reason {
|
|
message: format!("blocked by .botsecrets [policy.bash.deny]: {}", pat),
|
|
rule: Some(Rule {
|
|
source: self.root.join(".botsecrets"),
|
|
pattern: pat,
|
|
}),
|
|
}));
|
|
}
|
|
|
|
for prefix in &bash.allow_prefixes {
|
|
if command_matches_prefix(command, prefix) {
|
|
return Ok(Decision::Allow);
|
|
}
|
|
}
|
|
|
|
if let Some(pat) = match_command(command, &bash.ask)? {
|
|
return Ok(Decision::Ask(Reason {
|
|
message: format!("requires confirmation [policy.bash.ask]: {}", pat),
|
|
rule: Some(Rule {
|
|
source: self.root.join(".botsecrets"),
|
|
pattern: pat,
|
|
}),
|
|
}));
|
|
}
|
|
|
|
Ok(Decision::Allow)
|
|
}
|
|
|
|
/// A relative `path` is the project's. The path is checked as written and as the
|
|
/// file system resolves it, so a link does not hide what it points at.
|
|
pub fn check(&self, op: Op, path: &Path) -> Result<Decision, PolicyError> {
|
|
let path = absolute(path, &self.root);
|
|
let decision = self.check_rules(op, &path)?;
|
|
match self.resolved(&path) {
|
|
Some(resolved) if !decision.is_blocking() => self.check_rules(op, &resolved),
|
|
_ => Ok(decision),
|
|
}
|
|
}
|
|
|
|
/// `path` with its links resolved, or `None` if that changes nothing. A file not
|
|
/// written yet goes where the nearest existing directory above it leads. Under the
|
|
/// root it is spelled from the root as given, because the rules hold that spelling.
|
|
fn resolved(&self, path: &Path) -> Option<PathBuf> {
|
|
let real = path.ancestors().find_map(|dir| Some(absolute(path.strip_prefix(dir).ok()?, &dir.canonicalize().ok()?)))?;
|
|
let inside = self.root.canonicalize().ok().and_then(|root| Some(self.root.join(real.strip_prefix(root).ok()?)));
|
|
Some(inside.unwrap_or(real)).filter(|resolved| resolved != path)
|
|
}
|
|
|
|
fn check_rules(&self, op: Op, path: &Path) -> Result<Decision, PolicyError> {
|
|
// 1. .botignore is path-only and applies to read+write equally.
|
|
if matches!(op, Op::Read | Op::Write) {
|
|
if let Some(rule) = self.botignore.matched(path)? {
|
|
return Ok(Decision::Deny(Reason {
|
|
message: format!("blocked by .botignore: {}", rule.pattern),
|
|
rule: Some(rule),
|
|
}));
|
|
}
|
|
}
|
|
|
|
// 2. .botsecrets [policy] namespace-specific rules.
|
|
let (set, patterns) = match op {
|
|
Op::Read => (&self.read_globs, &self.read_patterns),
|
|
Op::Write => (&self.write_globs, &self.write_patterns),
|
|
Op::Execute => return Ok(Decision::Allow),
|
|
};
|
|
|
|
let rel = path.strip_prefix(&self.root).unwrap_or(path);
|
|
let matches = set.matches(rel);
|
|
if let Some(idx) = matches.first() {
|
|
let pattern = patterns[*idx].clone();
|
|
return Ok(Decision::Deny(Reason {
|
|
message: format!("blocked by .botsecrets [policy.{:?}]: {}", op, pattern),
|
|
rule: Some(Rule {
|
|
source: self.root.join(".botsecrets"),
|
|
pattern,
|
|
}),
|
|
}));
|
|
}
|
|
|
|
Ok(Decision::Allow)
|
|
}
|
|
}
|
|
|
|
/// Substring-or-glob match of `command` against `patterns`.
|
|
/// Patterns containing glob metachars (`*`, `?`, `[`) are treated as globs;
|
|
/// others are matched as literal substrings.
|
|
fn match_command(command: &str, patterns: &[String]) -> Result<Option<String>, PolicyError> {
|
|
for pat in patterns {
|
|
if is_glob(pat) {
|
|
let g = globset::Glob::new(pat)
|
|
.map_err(|e| PolicyError::BadPattern(e.to_string()))?
|
|
.compile_matcher();
|
|
if g.is_match(command) {
|
|
return Ok(Some(pat.clone()));
|
|
}
|
|
} else if command.contains(pat.as_str()) {
|
|
return Ok(Some(pat.clone()));
|
|
}
|
|
}
|
|
Ok(None)
|
|
}
|
|
|
|
fn is_glob(pat: &str) -> bool {
|
|
pat.contains('*') || pat.contains('?') || pat.contains('[')
|
|
}
|
|
|
|
/// `prefix` is `"name"` or `"name:*"`. Both treat `name` as a leading word
|
|
/// boundary in `command`. Mirrors Claude Code's `Bash(name:*)` style.
|
|
fn command_matches_prefix(command: &str, prefix: &str) -> bool {
|
|
let needle = prefix.trim_end_matches(":*");
|
|
command.trim_start().starts_with(needle)
|
|
}
|
|
|
|
fn compile_globs(patterns: &[String]) -> Result<(globset::GlobSet, Vec<String>), PolicyError> {
|
|
let mut builder = globset::GlobSetBuilder::new();
|
|
for pat in patterns {
|
|
let glob = globset::Glob::new(pat).map_err(|e| PolicyError::BadPattern(e.to_string()))?;
|
|
builder.add(glob);
|
|
}
|
|
let set = builder
|
|
.build()
|
|
.map_err(|e| PolicyError::BadPattern(e.to_string()))?;
|
|
Ok((set, patterns.to_vec()))
|
|
}
|