- A glob in [files] or [policy] that does not compile costs only that pattern while open, with a note by name beside text output. A [files] list with none left leaves the built-in list. Under deny the refusal stays, and the channel filter stays strict. - A file named `credentials` is on the default list, at any depth. - A word with a separator counts only if the path is there, the shell may expand it, or a redirect names it: packages, branches and hosts' paths are not denied. - timeout, nice, ionice, stdbuf, xargs and busybox are prefixes; `2>&1` stays in its segment. - `bash|sh|zsh -c` and `eval` arguments are read as command lines. - A `<<` with no closing line is no heredoc. A commented line's own comment is dropped. Text holding NUL fails to parse. The unknown-field message says so. Durations are bound to under 6 characters. More source extensions pass the gate. - Removed: HarnessAdapter::post_tool_op (dead since 3C was dropped), tool_op back inline.
252 lines
10 KiB
Rust
252 lines
10 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, command_paths, Dialect, Verb};
|
|
use crate::core::secrets::config::{GuardAction, PolicyConfig, SecretsConfig};
|
|
use crate::core::secrets::{unmaskable_reason, FileFormat, SecretFileSet};
|
|
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>,
|
|
/// The secret list, if `on_unparsed_read` is `deny`.
|
|
read_gate: Option<SecretFileSet>,
|
|
/// What `[[file]]` overrides declare a file's format to be.
|
|
declared_formats: Vec<(PathBuf, FileFormat)>,
|
|
}
|
|
|
|
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 config = SecretsConfig::load_or_default(root).0;
|
|
// A pattern that does not compile costs only itself: `bad_patterns` names it for the hooks.
|
|
let usable = |patterns: &[String]| patterns.iter().filter(|p| globset::Glob::new(p).is_ok()).cloned().collect::<Vec<_>>();
|
|
let read_gate = SecretFileSet::compile(&config.usable_file_patterns()).ok().filter(|_| config.enforcement.on_unparsed_read == GuardAction::Deny);
|
|
let declared_formats = config
|
|
.file_overrides
|
|
.iter()
|
|
.filter_map(|file| Some((absolute(Path::new(&file.path), root), FileFormat::from_hint(file.format.as_deref()?)?)))
|
|
.collect();
|
|
let policy = config.policy.unwrap_or_default();
|
|
|
|
let (read_globs, read_patterns) = compile_globs(
|
|
&usable(policy.read.as_ref().map(|r| r.patterns.as_slice()).unwrap_or(&[])),
|
|
)?;
|
|
let (write_globs, write_patterns) = compile_globs(
|
|
&usable(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,
|
|
read_gate,
|
|
declared_formats,
|
|
})
|
|
}
|
|
|
|
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)
|
|
}
|
|
|
|
/// What the paths `command` names meet, by verb class: nothing for a verb that only
|
|
/// names them, the read rules for any other, and the read gate for one that prints them.
|
|
/// `[policy.write]` does not reach commands.
|
|
pub fn check_command_paths(&self, command: &str, dialect: Dialect, cwd: &Path) -> Result<Decision, PolicyError> {
|
|
let home = std::env::var_os("HOME").or_else(|| std::env::var_os("USERPROFILE")).map(PathBuf::from);
|
|
for named in command_paths(command, dialect, cwd, home.as_deref()) {
|
|
let decision = match named.verb {
|
|
Verb::Prints => self.check(Op::Read, &named.path)?,
|
|
Verb::Other => self.check_path_rules(Op::Read, &named.path)?,
|
|
Verb::Metadata => Decision::Allow,
|
|
};
|
|
if decision.is_blocking() {
|
|
return Ok(decision);
|
|
}
|
|
}
|
|
Ok(Decision::Allow)
|
|
}
|
|
|
|
/// The path rules and, for a Read, the read gate.
|
|
pub fn check(&self, op: Op, path: &Path) -> Result<Decision, PolicyError> {
|
|
let decision = self.check_path_rules(op, path)?;
|
|
if op == Op::Read && !decision.is_blocking() {
|
|
return Ok(self.check_read_gate(path));
|
|
}
|
|
Ok(decision)
|
|
}
|
|
|
|
/// Stops a Read of an existing file on the secret list that fermata cannot mask.
|
|
/// The reason names the file and quotes nothing of it, and it sends the agent to the
|
|
/// user, not to the setting: `.botsecrets` is writable by default.
|
|
pub fn check_read_gate(&self, path: &Path) -> Decision {
|
|
let path = absolute(path, &self.root);
|
|
let Some(files) = self.read_gate.as_ref().filter(|_| path.is_file()) else {
|
|
return Decision::Allow;
|
|
};
|
|
let listed = std::iter::once(path.clone()).chain(self.resolved(&path)).find(|p| files.matches(p, &self.root));
|
|
let Some(file) = listed else {
|
|
return Decision::Allow;
|
|
};
|
|
let declared = self.declared_formats.iter().find(|(declared, _)| *declared == file).map(|(_, format)| *format);
|
|
match unmaskable_reason(&file, declared) {
|
|
None => Decision::Allow,
|
|
Some(why) => Decision::Deny(Reason {
|
|
message: format!(
|
|
"[fermata] Read stopped: {} is on the secret list and {}, so its values would reach the model. To read it, ask the user: the setting is [enforcement] on_unparsed_read.",
|
|
file.strip_prefix(&self.root).unwrap_or(&file).display(),
|
|
why,
|
|
),
|
|
rule: None,
|
|
}),
|
|
}
|
|
}
|
|
|
|
/// `.botignore` and `[policy]`. 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_path_rules(&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) {
|
|
// A bad pattern costs only itself: see `SecretsConfig::bad_patterns`.
|
|
let Ok(glob) = globset::Glob::new(pat) else { continue };
|
|
if glob.compile_matcher().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()))
|
|
}
|