diff --git a/CLAUDE.md b/CLAUDE.md deleted file mode 100644 index 403e070..0000000 --- a/CLAUDE.md +++ /dev/null @@ -1,55 +0,0 @@ -# Package: dirigent_fermata - -Harness-agnostic secret redaction engine and policy gate for AI coding agents. - -## Quick Facts -- **Type**: Library + binary (`fermata`) -- **Main Entry**: `src/lib.rs`, `src/bin/fermata.rs` -- **Dependencies**: `ignore`, `toml`, `regex`, `globset`, `serde`, `clap` (cli feature), `aho-corasick`, `serde_yaml` -- **Status**: v0.2 — secret redaction + policy gate (`.botsecrets` now includes `[policy]` section) - -## Layering - -Three concentric layers; nothing inner imports from anything outer. - -- **`core/`** — harness-unaware, transport-unaware, sync. Types (`Op`, `Decision`), `.botignore` walker, `Policy::check` / `check_command` / `check_command_paths`, `paths.rs` (command segments, verb classes, the named files). `.botsecrets` contains a `[policy]` section for access control rules (`fermata.toml` is accepted as an alias for `.botsecrets`). Sync, no tokio. - - **`core/secrets/`** — the secret filtering engine: - - `config.rs` — `.botsecrets` TOML parser (`SecretsConfig`, `PolicyConfig`) and hierarchical resolution (user, project, local override). Every config struct has `deny_unknown_fields`; `[enforcement]` holds `on_parse_error` (default `allow`), `on_unparsed_read` and `on_mask_write` (default `deny`), and nothing else. - - `manifest.rs` — discovers secret-containing files from `.botsecrets` patterns and loads their content for redaction. One entry per spelling of a value: file text, decoded, escaped forms, each line of a multi-line value from 8 characters (`MIN_LINE_LEN`). - - `parser.rs` — multi-format secret file parser (`.env`, TOML, YAML per document, JSON, Python, properties, opaque key files). Extracts key-value pairs where the value is a secret, numbers from 6 characters, and a value's text as the file spells it as a second entry of the key. - - `value_class.rs` — `is_plain_setting`: booleans, short numbers, durations and setting-word keys make no entry. - - `patterns.rs` — built-in key name patterns (~30 universal patterns like `*_KEY`, `*_SECRET`, `*_PASSWORD`) and gitleaks-derived regex patterns for heuristic scanning. - - `redactor.rs` — `Redactor` builds an Aho-Corasick automaton from known secret values and replaces them in arbitrary text; overlapping matches become one mask under the longest. Sub-millisecond performance. - - `scanner.rs` — `Scanner` applies heuristic regex patterns to detect secrets not covered by the known-value manifest (entropy-based and format-based detection). -- **`harness/`** — `HarnessAdapter` trait over a normalized `ToolCall` (PreToolUse) and `PostToolUsePayload` (PostToolUse). Each adapter (Claude, future Codex, etc.) lives in its own submodule, feature-gated. PostToolUse enables output redaction via `updatedToolOutput` before content enters the LLM context. -- **`bin/fermata.rs`** — only place where `clap`, stdio, and exit codes appear. - -## Release Model - -Developed in this monorepo; planned to be exported as a standalone repo in the future for advertising / external distribution. Development stays here. See `docs/tools/fermata.md`. - -## Dependency Direction - -`dirigent_tools` depends on `dirigent_fermata`, never the reverse. Fermata must remain usable as a standalone hook/MCP without dragging in the in-process ACP tool runtime. - -## Failure behaviour and known limits - -- **Hooks fail open, except under `on_parse_error = "deny"`.** A broken config layer (a parse error or an unknown field) switches only that layer's rules off, with a note beside text output. With `deny` in effect, PostToolUse answers with a refusal naming the file when the config or a secret file cannot be loaded, and PreToolUse answers `deny` when the config or the rules cannot be loaded or applied. A malformed hook payload and a missing working directory stay open: no payload means nothing to render, no directory means no setting to read. A glob in `[files]` or `[policy]` that does not compile costs only that pattern while open (`SecretsConfig::bad_patterns`, a note naming pattern, section and layer by `bad_pattern_sources`); a `[files]` list with none left leaves the built-in list; under `deny` the manifest and PreToolUse refuse, so `dirigent_server`'s filter, which forces `deny`, stays strict. `fermata check` exits 2 on a broken config or a bad glob. -- **A config that cannot be read: the setting is unknown.** `SecretsConfig::denies_on_failure` reads the raw bytes of every layer: an uncommented line setting `deny` counts, broken layer or not; without one the hook stays open as for any default root; a layer whose bytes cannot be read says nothing and does not count, so an unreadable global config cannot stop every project on the machine. -- **Replacing output depends on the harness.** Claude Code ignores an `updatedToolOutput` that does not match a built-in tool's output schema and then uses the original. `harness/claude.rs` therefore walks `tool_response` in any shape and masks strings in place. `SCHEMA_VALUES` lists the enum and literal values of the 87 `outputSchema` getters in Claude Code v2.1.314, as far as they have values to list (re-read it when a release adds tools): those exact values stay. Not resolved, because they exist only at run time: Workflow's `RUN_OP_STATUS` and `runOpOutputFields` and Artifact's `handlers` arms, all flag-gated, and Artifact's `reason`. Artifact's pattern fields and that `reason` are `ARTIFACT_PATTERN_FIELDS`: a secret there refuses. A secret elsewhere under those names or in a built-in's object key cannot take a mask, so `OutputEdit::Unmaskable` refuses the output under every setting. Refusals: Bash, Read and Artifact answer a minimal schema-valid output, other built-ins keep their shape, MCP gets the plain text. `tests/cli_hook_redaction.rs` checks shapes against a copy of those schemas, and `TOOL_ENUMS` there lists each tool's enums so that dropping a value fails a test; nothing here runs Claude Code. -- **Read gate and write guard.** `SecretFileSet` and `unmaskable_reason` decide which listed files cannot be masked (no parser, a secret as a whole, unparseable, no value to read, tfstate by position); a Read, a Grep with a `path` and a printing command naming one is stopped under every `on_parse_error` unless `on_unparsed_read = "allow"`. `count_masks` backs the write guard: a Write, Edit or MultiEdit that adds a mask is stopped unless `on_mask_write = "allow"`. Commands meet only the session's own project rules, by verb class (`docs/security-model.md`, Layer 3). What a command writes (`Verb::Writes`) meets `.botignore`, `[policy.write]` and `[policy.read]`, also for a file not there yet, and not the read gate; a printing verb's write stays `Prints` too. -- **The gate approves nothing.** `render_decision` answers `{}` for `Decision::Allow`, never `permissionDecision: "allow"`, which would skip Claude Code's permission prompt. `allow_prefixes` only skips fermata's own `ask` rules. `[policy.bash]` reaches Bash, PowerShell and Monitor. -- **Redaction limits.** The largest: a failed tool (`PostToolUseFailure`, including a Bash non-zero exit) cannot be rewritten by any hook and is not hooked, so `cat .env; false` reaches the model. Only a `[policy.bash] deny` pattern stops that, and only for the spelling it names. Also out of reach: Monitor's output and changed-file attachments. Values split across strings, encoded values, JSON numbers in a response and binary fields are not masked. `tests/known_limits.rs` pins each limit that the binary can show: when one starts to fail, a limit was fixed and `docs/known-failures.md` must change with it (`tests/docs_known_failures.rs` keeps the two in step and keeps the failure list out of the README). `tests/docs_toml_examples.rs` loads every TOML example of `docs/configuration.md` under `deny_unknown_fields`. Heuristics warn in `additionalContext` and do not mask. Full list: `docs/known-failures.md`. -- **Errors never quote a file.** `ParseError::Format` and `SecretsConfigError::Parse` keep the format and line number and drop the parser's text, because it can quote the failing line. Patterns (`.botignore`, `[policy]`, `[files]`) can appear in messages: they are not values, and a deny reason names them too. -- **Editor files never refuse.** A discovered vim swap file (`*.sw[a-p]`, `*.swx`), Kate's `*.kate-swp` or a `*~` that cannot be read or parsed is passed over silently under every `on_parse_error`, in the hooks and in Dirigent's channel filter (which forces `deny`). If it can be parsed its values stay known and are redacted, as before. `.bak`, `.orig` and `.env.gpg` keep today's rule, since a hand-made copy can hold live values. A `[[file]]` override is meant, whatever its name, and keeps the rule too. Files with no parser format (`secrets.toml~`, `#secrets.toml#`, `secrets.toml.bak`) were and are opaque: no refusal, not redacted (they are not on the secret list, so the read gate does not meet them either). - -## Out of scope (v0.2) - -Codex / Gemini hook adapters, MCP server mode, `readonly_only` Bash mode, audit log, filesystem watcher, context taint tracking. Each is a future task with its own plan. - -## See also - -- `docs/tools/fermata.md` — Dirigent integration plan -- `docs/workpad/brainstorm/fermata.md` — canonical product spec -- `docs/architecture/fermata-security-philosophy.md` — security philosophy and the reveal triangle -- `.botsecrets` format: `core/secrets/config.rs` — unified config for secret redaction and policy (`fermata.toml` accepted as alias) diff --git a/Cargo.toml b/Cargo.toml index 1a716cc..d3effb0 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -40,6 +40,3 @@ predicates = "3.1" default = ["cli", "harness-claude"] cli = ["dep:clap"] harness-claude = [] - -[lints] -workspace = true diff --git a/README.md b/README.md index 914fee8..ab90c30 100644 --- a/README.md +++ b/README.md @@ -1,61 +1,63 @@ -# fermata +# 𝄐 fermata **Do not use this software.** > [!CAUTION] > This is an experiment. It does not protect your secrets. Secrets can and do reach the model while it is installed. Do not rely on it. Do not install it on a real project. +--- + Where it is known to fail: [docs/known-failures.md](docs/known-failures.md). +--- + ## What it tries to do -AI coding agents read files and run commands, and what they read enters the model's context. The experiment asks whether a tool's output could be filtered before the model sees it, so that an agent could see which keys `.env` holds without seeing their values. +AI coding agents read files and run commands. When an agent reads `.env`, the values enter the model's context, and from there they can end up in commits or API calls. The experiment asks whether the output of a tool could be filtered before the model sees it, so that the agent could see which keys exist without seeing their values. -fermata runs in hooks around an agent's tool calls: +fermata is a program that runs in hooks around an agent's tool calls. -``` -Agent wants to run a tool - | - PreToolUse ── .botsecrets [policy] / .botignore, read gate, write guard - | a rule matches? → deny or ask - | otherwise → no answer: Claude Code's permissions decide - | - Tool executes - | - PostToolUse ── .botsecrets [files] + [keys] + [heuristic] - | values it parsed? → masked - | known formats? → a warning, the value stays - | - Output enters LLM context, with whatever was missed -``` +

+ Where the two hooks sit around a tool call, and what each one tries to do +

-| Part | Mechanism | What it does | -|------|-----------|--------------| -| Known-value masking | `.botsecrets` names secret files; fermata parses those it has a parser for and builds an Aho-Corasick automaton | Masks a value from the manifest in a string of a successful tool's output | -| Heuristic scan | Regex patterns from gitleaks (AWS keys, JWTs, GitHub PATs, database URLs) | Warns beside the output and masks nothing | -| Rules | `.botsecrets [policy]` / `.botignore` | Stops the Read, Write and Edit tools on matching paths, commands whose text matches, and commands that name a matching file. No rules, nothing stopped | -| Read gate and write guard | built in; `[enforcement]` | Stops a Read of a listed secret file it cannot mask, and a Write or Edit that adds a mask to a file | +**Before the tool runs (PreToolUse).** fermata compares the call, and the files a command names, with the rules in `.botsecrets [policy]` and `.botignore`, and stops it when a rule matches. It also stops a Read of a listed secret file it cannot mask, and a Write or Edit that adds a mask to a file. When no rule matches it answers nothing, so Claude Code's own permission prompts stay. It has no rules unless you write them. -Each call parses the secret files again. In a release build that took 5 to 9 ms for a small `.env` and 0.13 s for a 2.3 MB JSON file of 35000 keys. +**After the tool runs (PostToolUse).** fermata finds the secret files named in `.botsecrets`, parses them, keeps the values under keys that look secret, and replaces those values in every string of the output with `*****`, using an Aho-Corasick automaton. A second scan with regular expressions looks for known formats such as AWS keys and JWTs. It only adds a warning and masks nothing. Each call parses the secret files again: in a release build that took 5 to 9 ms for a small `.env` and 0.13 s for a 2.3 MB JSON file of 35000 keys. -fermata is no sandbox: see [docs/threat-model.md](docs/threat-model.md). +So in the cases it handles, `source .env && echo $DB_PASSWORD` comes back masked although no read was stopped. [docs/known-failures.md](docs/known-failures.md) shows how many cases it does not handle. + +fermata is no sandbox. See [docs/threat-model.md](docs/threat-model.md). + +--- + +## How it is configured + +**`.botsecrets`** is a TOML file. It names the secret files (`[files]`), extra key names (`[keys]`), the mask style (`[redaction]`), the heuristic scan (`[heuristic]`) and the rules for the gate (`[policy.write]`, `[policy.bash]`, `[policy.read]`). `fermata.toml` is accepted as another name for it, and `.botsecrets` wins when both exist. + +**`.botignore`** uses gitignore syntax and stops the Read, Write and Edit tools on paths that match. It is optional. + +The reference is [docs/configuration.md](docs/configuration.md), and the CLI is in [docs/commands.md](docs/commands.md). + +--- ## Trying the experiment -Use a throwaway project and fake secrets. +Use a throwaway project and fake secrets. Nothing here makes a real project safer. + +Install, with a working [Rust toolchain](https://rustup.rs): ```bash -cargo install --path . --features cli +cargo install --git https://git.g4b.org/dirigence/fermata --features cli ``` +Create a `.botsecrets` in the throwaway project: + ```toml # .botsecrets [files] patterns = [".env", ".env.*", "secrets.*"] -[keys] -include = ["STRIPE_*", "MY_APP_SIGNING_*"] - [policy.write] patterns = [".claude/**", "vendor/**", "*.lock"] @@ -63,7 +65,7 @@ patterns = [".claude/**", "vendor/**", "*.lock"] deny = ["rm -rf /", "curl * | sh"] ``` -`fermata.toml` is accepted as another name for `.botsecrets`, which wins when both exist. An optional `.botignore` uses gitignore syntax for the Read, Write and Edit tools. See [docs/configuration.md](docs/configuration.md). +Setting `patterns` replaces the default list of files. Built-in key patterns such as `*_KEY`, `*SECRET*`, `*PASSWORD*`, `*TOKEN*` and `DATABASE_URL` decide which values count. Add both hooks to `.claude/settings.json`: @@ -88,59 +90,40 @@ Add both hooks to `.claude/settings.json`: } ``` -PreToolUse is no permission approver: when no rule stops a call it answers nothing, and Claude Code's own prompts stay. - Leave out `matcher`: a matcher that omits a tool leaves that tool's output unfiltered. -`"onFailure": "block"` (Claude Code v2.1.295 or later; older versions ignore it) stops a tool call when the hook cannot run. Without it Claude Code carries out the call and the output passes unfiltered. On PostToolUse it can hold nothing back, because the tool has already run. With it, a teammate without `fermata` on `PATH` is blocked at every tool by a committed `.claude/settings.json`, so per-user installs belong in `.claude/settings.local.json`. To recover, edit the settings by hand or set `"continue"`. +`"onFailure": "block"` (Claude Code v2.1.295 or later) stops a tool call when the hook cannot run. Without it, Claude Code carries out the call and the output passes unfiltered. On PostToolUse it can hold nothing back, because the tool has already run. -## Commands - -```bash -# Check a path against the rules -fermata check --op read /path/to/.env # exit 1 = a rule denies it -fermata check --op write /path/to/src/main.rs # exit 0 = no rule denies it - -# Run as a hook (reads harness JSON from stdin) -fermata hook --harness claude -fermata hook --harness claude --event post-tool-use -``` - -See [docs/commands.md](docs/commands.md). - -## Library API - -```rust -use std::path::Path; -use dirigent_fermata::core::secrets::{Manifest, Redactor, Scanner, SecretsConfig}; - -let root = Path::new("/path/to/project"); -let config = SecretsConfig::load(root)?; -let manifest = Manifest::build(&config, root)?; - -let redactor = Redactor::new(&manifest, config.redaction.style); -let clean = redactor.redact("DB_PASSWORD=fake-db-pass-1"); -// clean.text holds the masked text, if that value made it into the manifest - -let scanner = Scanner::new(&config.heuristic)?; -let findings = scanner.scan("Found key: AKIA1234567890ABCDEF"); -``` +--- ## Harness support | Harness | Status | Mechanism | |---------|--------|-----------| | Claude Code | Exists, and fails often | PreToolUse and PostToolUse hooks | -| Codex CLI | Not built | Pre-exec hook adapter | +| Any tool that can call a program | Exists | Exit codes of `fermata check` | +| Codex CLI | Not built | Hook adapter | | Gemini CLI | Not built | MCP server mode | | Any MCP agent | Not built | MCP proxy | +--- + ## Background - [docs/security-model.md](docs/security-model.md): the idea of "reveal", as distinct from read and write, and the design - [docs/known-failures.md](docs/known-failures.md): where it is known to fail - [docs/threat-model.md](docs/threat-model.md): what fermata tries to catch and where it stops +- [docs/commands.md](docs/commands.md): the CLI + +fermata is developed in the [Dirigent](https://git.g4b.org/dirigence/dirigent) monorepo and exported here. It needs no other Dirigent component. + +--- ## License -Licensed under either of [Apache License, Version 2.0](LICENSE-APACHE) or [MIT License](LICENSE-MIT) at your option. +Licensed under either of + +- Apache License, Version 2.0 ([LICENSE-APACHE](LICENSE-APACHE)) +- MIT License ([LICENSE-MIT](LICENSE-MIT)) + +at your option. diff --git a/interception-flow.svg b/interception-flow.svg new file mode 100644 index 0000000..afe77dd --- /dev/null +++ b/interception-flow.svg @@ -0,0 +1,72 @@ + + + How fermata tries to intercept. It fails often: see docs/known-failures.md. + + + Agent requests a tool call + + + + + + PreToolUse: rule check + .botignore, [policy]: only rules you wrote + A match stops the call. + + + + + DENIED + + + + allowed + + + Tool runs (Read, Bash, Edit, Write) + + + + + + PostToolUse: tries to mask + values it parsed → ***** + Heuristic patterns → warning only + Aho-Corasick automaton + + + + + + Output enters LLM context, with what it missed + + WHAT IT TRIES TO DO + + + PreToolUse + Read .env → stopped if a rule names it + rm -rf / → stopped if a rule names it + cat .env → stopped if a rule names it + + + PostToolUse + DB_PASSWORD=fake-db-pass → DB_PASSWORD=***** + AKIA1234567890ABCDEF → warning, value stays + docker-compose config → values it knows masked + + + Beyond fermata: + network exfil, kernel access → sandbox + + + Speed + Parses secret files each call: 0.13 s at 2.3 MB. + + + It fails often + Secrets reach the model while it is installed. See docs/known-failures.md. + + + Wiring: + Hook script (Claude Code only) · Library API · Other harnesses and MCP proxy: not built +