Files
fermata/src/core/secrets/manifest.rs
T
g4borg b69fbf3ae2 fix(fermata): PostToolUse redacts any response shape, and a refusal fits each tool's schema
Built-in tools and normal MCP results send tool_response as an object or an
array, which the hook read as empty: nothing was redacted under any setting.
The hook now walks any shape, masks every string and returns the same shape.

Enum and literal values of Claude Code's output schemas (read from v2.1.314)
stay when they match exactly, because a mask there fails the schema and the
original is used. A secret that cannot take a mask refuses the output under
every setting. Refusals: Bash and Read answer a minimal schema-valid output,
others keep their shape with exact enum values only.

Also: an unreadable config layer no longer counts as deny, multi-line string
spellings of deny count, vim's other swap names and Kate's are editor files,
the heuristic warning moves to additionalContext, and PreToolUse answers
quietly for tools it has no rules for.
2026-11-06 23:36:57 +01:00

333 lines
12 KiB
Rust

//! Secret manifest loader.
//!
//! Discovers secret files per the `.botsecrets` configuration, parses them,
//! filters by key patterns, and produces the known-secrets set that the
//! Redactor will consume.
use std::path::{Path, PathBuf};
use globset::{Glob, GlobSetBuilder};
use thiserror::Error;
use walkdir::WalkDir;
use super::config::{ParseErrorAction, SecretsConfig};
use super::parser::{self, FileFormat, ParseError, SecretEntry};
// ---------------------------------------------------------------------------
// Errors
// ---------------------------------------------------------------------------
#[derive(Debug, Error)]
pub enum ManifestError {
#[error(transparent)]
Parse(#[from] ParseError),
#[error("glob pattern error: {0}")]
Glob(String),
}
impl ManifestError {
/// The secret file that failed, if a file did (a bad glob is the config's).
pub fn path(&self) -> Option<&Path> {
match self {
Self::Parse(e) => Some(e.path()),
Self::Glob(_) => None,
}
}
}
// ---------------------------------------------------------------------------
// Manifest
// ---------------------------------------------------------------------------
/// The complete set of known secrets discovered from a project.
///
/// Entries are sorted by value length descending (longest first) so the
/// redactor replaces the most specific match before shorter substrings.
#[derive(Debug, Clone)]
pub struct Manifest {
entries: Vec<SecretEntry>,
}
/// Minimum secret value length to keep. Anything shorter risks false-positive
/// redaction (e.g. `"yes"`, `"on"`, `"42"`).
const MIN_VALUE_LEN: usize = 4;
/// File name endings of the working files editors leave beside what they edit:
/// Kate's swap file and the `~` backup of vim and emacs. Vim's swap names are
/// [`is_vim_swap`].
///
/// `.bak`, `.orig` and the like are not here: nothing makes those but a person
/// copying a file by hand, and such a copy can hold live values.
const EDITOR_ARTEFACT_SUFFIXES: &[&str] = &[".kate-swp", "~"];
/// Vim's swap files: `.swp`, then `.swo`, `.swn` and on down to `.swa` when the
/// earlier names exist, and `.swx`, its write probe.
fn is_vim_swap(name: &str) -> bool {
name.rsplit_once('.')
.and_then(|(_, ext)| ext.strip_prefix("sw"))
.is_some_and(|letter| matches!(letter.as_bytes(), [b'a'..=b'p' | b'x']))
}
/// Whether `path` is an editor's working file.
///
/// Such a file comes and goes while someone edits, and a swap file is binary, so
/// failing to read one says nothing about the project's secrets and must not stop
/// anything, under any `on_parse_error`. It is still read: what can be parsed from
/// it is a copy of real values and stays known to the redactor.
///
/// Only names [`FileFormat::from_path`] gives a format reach the parser, in practice
/// `.env*`. `secrets.toml~` or emacs' `#secrets.toml#` have no format, so they are
/// opaque: never read, never a refusal, not redacted, like a `.pem`.
fn is_editor_artefact(path: &Path) -> bool {
path.file_name()
.and_then(|n| n.to_str())
.is_some_and(|name| is_vim_swap(name) || EDITOR_ARTEFACT_SUFFIXES.iter().any(|suffix| name.ends_with(suffix)))
}
/// Directories that are unconditionally skipped during file discovery.
const SKIP_DIRS: &[&str] = &[".git", "node_modules", "target", "__pycache__", ".venv"];
impl Manifest {
/// Build a manifest by discovering and parsing secret files relative to
/// `root`.
pub fn build(config: &SecretsConfig, root: &Path) -> Result<Self, ManifestError> {
let mut entries = Vec::new();
// 1. Discover files matching `config.files.patterns`.
let discovered = discover_files(&config.files.patterns, root)?;
// 2. Parse each discovered file.
for path in &discovered {
match parse_discovered_file(path) {
Ok(file_entries) => entries.extend(file_entries),
Err(_) if is_editor_artefact(path) => {}
Err(e) => match config.enforcement.on_parse_error {
ParseErrorAction::Allow => {
eprintln!(
"fermata: warning: skipping unparseable file {}: {}",
path.display(),
e
);
}
ParseErrorAction::Deny => {
return Err(e.into());
}
ParseErrorAction::MaskEntireFile => {
// We cannot extract individual secrets — the redactor
// may choose to mask the entire file content if it
// appears in output. For now we log and continue.
eprintln!(
"fermata: warning: cannot parse {}: {}",
path.display(),
e
);
}
},
}
}
// 3. Filter discovered entries by the effective key patterns.
entries = filter_by_key_patterns(entries, config);
// 4. Process explicit `[[file]]` overrides — these bypass key filtering
// because the user declared them intentionally.
for override_cfg in &config.file_overrides {
let override_path = root.join(&override_cfg.path);
if !override_path.is_file() {
continue;
}
let format = override_cfg
.format
.as_deref()
.and_then(FileFormat::from_hint);
let key_filter = if override_cfg.keys.is_empty() {
None
} else {
Some(override_cfg.keys.as_slice())
};
match parser::parse_secret_file(&override_path, format, key_filter) {
Ok(file_entries) => entries.extend(file_entries),
Err(e) if config.enforcement.on_parse_error == ParseErrorAction::Deny => {
return Err(e.into());
}
Err(e) => {
eprintln!(
"fermata: warning: cannot parse override file {}: {}",
override_path.display(),
e
);
}
}
}
// 5. Deduplicate (same key + value from different discovery paths).
entries.sort_by(|a, b| a.key.cmp(&b.key).then_with(|| a.value.cmp(&b.value)));
entries.dedup_by(|a, b| a.key == b.key && a.value == b.value);
// 6. Sort by value length descending (longest first for redaction).
entries.sort_by(|a, b| b.value.len().cmp(&a.value.len()));
// 7. Remove entries with very short values to avoid false replacements.
entries.retain(|e| e.value.len() >= MIN_VALUE_LEN);
Ok(Self { entries })
}
/// Build a manifest from a pre-built list of secret entries.
///
/// Applies the same post-processing as [`Manifest::build`]:
/// - Deduplicates entries with the same key and value.
/// - Sorts by value length descending (longest first for redaction).
/// - Removes entries with values shorter than 4 characters.
///
/// Useful for testing and for library consumers that obtain secrets
/// from sources other than filesystem discovery.
pub fn from_entries(mut entries: Vec<SecretEntry>) -> Self {
// Deduplicate (same key + value).
entries.sort_by(|a, b| a.key.cmp(&b.key).then_with(|| a.value.cmp(&b.value)));
entries.dedup_by(|a, b| a.key == b.key && a.value == b.value);
// Sort by value length descending (longest first for redaction).
entries.sort_by(|a, b| b.value.len().cmp(&a.value.len()));
// Remove entries with very short values to avoid false replacements.
entries.retain(|e| e.value.len() >= MIN_VALUE_LEN);
Self { entries }
}
/// Build an empty manifest (no secrets known).
pub fn empty() -> Self {
Self {
entries: Vec::new(),
}
}
/// Returns all discovered secret entries.
pub fn entries(&self) -> &[SecretEntry] {
&self.entries
}
/// Returns `true` if the manifest contains no secrets.
pub fn is_empty(&self) -> bool {
self.entries.is_empty()
}
/// Number of known secrets.
pub fn len(&self) -> usize {
self.entries.len()
}
}
// ---------------------------------------------------------------------------
// File discovery
// ---------------------------------------------------------------------------
/// Walk the project tree and collect files matching any of the given glob
/// patterns. Patterns are matched against paths *relative to* `root`.
fn discover_files(patterns: &[String], root: &Path) -> Result<Vec<PathBuf>, ManifestError> {
if patterns.is_empty() {
return Ok(Vec::new());
}
// Compile all patterns into a single GlobSet for efficient matching.
let mut builder = GlobSetBuilder::new();
for pat in patterns {
// `globset` patterns match against the full relative path including
// intermediate directories (e.g. `.docker/config.json`). We add
// both the literal pattern and a `**/` prefixed variant so that
// `.env` matches at the root and `subdir/.env` matches nested.
let glob = Glob::new(pat).map_err(|e| ManifestError::Glob(e.to_string()))?;
builder.add(glob);
// Also match nested occurrences: `**/<pattern>`.
if !pat.contains('/') {
let nested = format!("**/{pat}");
let nested_glob =
Glob::new(&nested).map_err(|e| ManifestError::Glob(e.to_string()))?;
builder.add(nested_glob);
}
}
let glob_set = builder.build().map_err(|e| ManifestError::Glob(e.to_string()))?;
let mut result = Vec::new();
// Common large / non-project directories are not entered at all. The root
// itself may have any name.
let walker = WalkDir::new(root).follow_links(false).into_iter().filter_entry(|entry| {
let skipped = entry.file_type().is_dir()
&& entry.file_name().to_str().is_some_and(|name| SKIP_DIRS.contains(&name));
entry.depth() == 0 || !skipped
});
for entry in walker {
let entry = match entry {
Ok(e) => e,
Err(_) => continue,
};
// Only interested in files.
if !entry.file_type().is_file() {
continue;
}
let abs_path = entry.path();
// Match relative path against the glob set.
let rel = match abs_path.strip_prefix(root) {
Ok(r) => r,
Err(_) => continue,
};
if glob_set.is_match(rel) {
result.push(abs_path.to_path_buf());
}
}
Ok(result)
}
// ---------------------------------------------------------------------------
// Single-file parsing
// ---------------------------------------------------------------------------
/// Parse a single discovered file. Auto-detects format from extension.
/// Returns an empty `Vec` if the format cannot be determined (e.g. `.key`,
/// `.pem` — opaque/binary files).
fn parse_discovered_file(path: &Path) -> Result<Vec<SecretEntry>, ParseError> {
let format = match FileFormat::from_path(path) {
Some(fmt) => fmt,
None => return Ok(Vec::new()), // opaque file — skip
};
parser::parse_secret_file(path, Some(format), None)
}
// ---------------------------------------------------------------------------
// Key-pattern filtering
// ---------------------------------------------------------------------------
/// Keep only entries whose key matches the effective key-include patterns
/// from the configuration.
fn filter_by_key_patterns(entries: Vec<SecretEntry>, config: &SecretsConfig) -> Vec<SecretEntry> {
entries
.into_iter()
.filter(|e| config.key_matches(&e.key))
.collect()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn empty_manifest() {
let m = Manifest::empty();
assert!(m.is_empty());
assert_eq!(m.len(), 0);
assert!(m.entries().is_empty());
}
}