Files
fermata/docs/security-model.md
T
g4borg 709f0cf1bc docs(fermata): the failure list moves out of the READMEs into docs/known-failures.md
One list, merged from both READMEs and security-model.md "Known limits", each entry with
its test. Entries fixed on this branch are gone. Both READMEs keep the warning and point at
the page. tests/docs_known_failures.rs keeps the page and known_limits.rs in step, and
test_crate_export.py checks that the public README's links resolve in the exported tree.
2026-11-07 09:07:19 +01:00

142 lines
18 KiB
Markdown

# fermata Security Model
> **Do not use this software.** fermata is an experiment. It does not protect your secrets, and secrets can and do reach the model while it is installed. This document describes what fermata tries to do. See [Known failures](known-failures.md) for where it fails.
## The Problem
AI coding agents see secrets. Not because they try to -- because secrets are everywhere in a working codebase, and agents read files, run commands, and inspect output as part of their normal workflow.
When an agent reads `.env`, the secret values get tokenized into the LLM's context window. Once there, they can leak into commits, PR descriptions, log messages, or API calls the agent makes. The secret is irrecoverably revealed.
Blocking a file before the read leaves other paths to the same data open. This experiment looks at filtering the output instead.
## The Reveal Triangle
Most security models think about secrets in terms of *files*: can the agent read this file? Can it write to it? This experiment looks at a third dimension.
**Read** -- Can the agent open a file? Handled by policy rules and file access controls. A blunt instrument: blocking `.env` also blocks legitimate tooling that needs configuration values. In fermata's model, read access to secret-containing files is *allowed by default* -- the agent needs to see file structure and key names to reason about configuration.
**Write** -- Can the agent modify a file? Less concerning than it appears, because version control provides full recovery. Write restrictions matter primarily for anti-jailbreak (preventing the agent from modifying its own hooks or policy files).
**Reveal** -- Do secret *values* enter the LLM context? A file read that configures a database is not a security event. The same file read that feeds credentials to an LLM *is*.
These three dimensions are independent. In theory an agent could have read access to `.env` without the secret values being revealed, if the output were masked before it reached the model. The agent would see file structure and key names and not the values. fermata tries this and does not achieve it reliably: see [Known failures](known-failures.md).
The key insight is that Read and Write operate on file identity (*which file*). Reveal operates on data content (*which values*). File identity alone does not answer the reveal question.
## Layers
The design has four layers. Layers 1 and 2 operate on data content (the actual secret values). Layers 3 and 4 operate on file and system identity.
### Layer 1: Known-Value Redaction (.botsecrets + Aho-Corasick)
Parse secret-containing files at startup, extract actual secret values, build an Aho-Corasick automaton. Scan all tool output for those exact byte strings and replace them with redaction markers.
This layer looks at values, not at how they reached the output: file reads, shell command output, log files. If a value such as `fake-db-pass-1` (the `DB_PASSWORD` of a parsed `.env`) made it into the manifest, every occurrence in a string of a successful tool's output is masked: the Aho-Corasick automaton finds all of them in a single linear pass. Many values never reach the manifest, and much output never reaches the scan: see [Known failures](known-failures.md).
### Layer 2: Heuristic Detection (Scanner + gitleaks patterns)
Regex patterns for known secret formats: AWS access keys (`AKIA...`), GitHub PATs (`ghp_...`), JWTs (`eyJ...`), database URLs with embedded passwords, and dozens more derived from industry-standard pattern sets.
This looks for secrets not covered by the manifest. It warns beside the output and does not mask, so the value still reaches the model.
Its false-positive rate is higher than Layer 1's, which is why it warns: masking every high-entropy string would corrupt the output.
### Layer 3: Access Control (.botignore / .botsecrets [policy])
Stop the tool calls your rules name, and a Read of a secret file that fermata cannot mask. With `[policy.write]` on `.claude/**`, `Write .claude/settings.json` is denied. With `[policy.bash] deny = ["rm -rf /"]`, `Bash: rm -rf /` is denied. Without rules nothing is stopped, apart from the two gates below. Path patterns apply to the Read, Write and Edit tools (and Grep with a `path`, which counts as a Read), and command patterns match the text of a command. A `~/` in a tool's path is the home directory.
- **Commands that name a file.** A command is split into segments, and each word that names an existing file, an existing path with a separator, a path with `$`, `*` or `?` in it, or a file the command writes is checked. So `composer require vendor/package` and `git checkout build/fix` name nothing under a rule on `vendor/` or `build/`. The argument of a shell's `-c` (`bash sh zsh dash ksh mksh ash yash fish csh tcsh pwsh powershell`, also PowerShell's `-Command` and `cmd /c`) and of `eval` is read as a command line of its own, and `sudo env time nohup command exec timeout nice ionice stdbuf xargs busybox` before a verb do not hide it. A wrapper counts by its file name only as a bare word or an absolute path, so `./do .env` is a script called on the file. After an absolute path (`/home/me/env .env`) the next word still counts as a path, because that may be a script too. Which check depends on the segment's verb. A printing verb (`cat head tail less more bat nl tac cut sort uniq grep egrep fgrep rg awk sed strings xxd od hexdump base64 gc type get-content select-string`) meets the path rules and the read gate. A writing verb meets `.botignore`, `[policy.write]` and `[policy.read]`, also for a file that is not there yet, and not the read gate: a redirect's target, every path of `mv rm rmdir touch mkdir tee truncate shred set-content add-content out-file new-item remove-item move-item` and of `sed -i`, the last path of `cp ln install rsync scp copy-item`, `dd of=`, and the value of `-o` or `--output` (`wget -O`). Any other verb (`source`, `python`, `chmod`) meets `.botignore` and `[policy.read]`. A metadata verb (`ls stat file test [ du which echo printf`, and `git status`, `git check-ignore`, `git ls-files`, `git commit`) given as a bare word meets nothing. So with `.env` in `.botignore`, `cat .env`, `cat ./.env; false` and `source .env` are denied, while `env`, `grep -r TOKEN .` and `git commit -m ".env loading"` pass.
- **Read gate.** A Read (or a Grep with a `path`, or a printing command that names the file) of a file on the secret list that fermata cannot mask is stopped under every `on_parse_error`. The reason names the file and the setting `[enforcement] on_unparsed_read` and says to ask the user. The files are: a file with no parser (`.netrc`, `.htpasswd`, `.p12`, `.pfx`), a key file that is a secret as a whole (`*.pem`, `*.key`, `id_rsa`, `id_ed25519`, `id_ecdsa`, unless it holds only certificates), `*.tfstate` (its secrets sit by position, not by key), and a file that cannot be parsed (a broken file, a UTF-16 or Latin-1 file, JSON with comments, text with a NUL). `on_unparsed_read = "allow"` turns the gate off.
- **Write guard.** A Write, Edit or MultiEdit that adds a mask to a file is stopped, because the mask stands for a value fermata hid and writing it back corrupts the file. `[enforcement] on_mask_write = "allow"` turns it off.
- **`.botignore` and relative paths.** A directory pattern such as `vendor/` matches the files below it, and a relative path is taken against the project root. The path is also checked as the file system resolves it, so a symlink does not hide what it points at.
Reading `.env` is allowed by default, and only Layer 1 stands between its values and the model. On the default configuration a parseable `.env` is not stopped at all, by any route.
Where the command check fails, in both directions: [Known failures](known-failures.md).
### Layer 4: Structural Containment (External)
Container-level isolation, filesystem restrictions, dropped capabilities, no-new-privileges. Prevents system modification, privilege escalation, and escape from the execution environment. This layer has no concept of secret values -- it operates on structural boundaries.
fermata does not own this layer. It would come from a container runtime, VM, or sandboxing tool.
## Design Principles
**Fail-open by default.** A parse error in a `.botsecrets` layer turns that layer's rules off, with a note beside text output that names the file and line and says so; the other layers stay in force. A field that fermata does not know (a typo, or a setting that no longer exists) is a parse error: the layer is off until the field is fixed. A glob in `[files]` or `[policy]` that does not compile costs only that pattern, with a note naming it beside text output; a `[files]` list with no usable pattern leaves the built-in list. A parse error in a secret file lets the values of that file reach the model, with a note beside text output, except that a Read of a listed file that cannot be masked is stopped (the read gate above). Two exceptions to fail-open: under `on_parse_error = "deny"` the hooks refuse instead, and under `"onFailure": "block"` on PreToolUse a `fermata` that cannot run stops every tool. `on_parse_error` is `allow` unless you set `deny`.
**Not a permission approver.** PreToolUse can stop a call or ask, and otherwise says nothing. It never answers `allow`, because Claude Code would then skip its own permission prompt, and installing a guard must not remove one. `allow_prefixes` only skips fermata's own `ask` rules.
**Every occurrence of a value in the manifest.** If a value made it into the secret manifest (loaded from files matched by `.botsecrets`), it is masked in every string of a successful tool's output, or the output is refused. [Known failures](known-failures.md) says what never reaches the manifest or the scan.
**Speed.** Hooks fire on every tool call, and each call loads the config and parses the secret files again. Measured with a release build of this branch (commit e493fb4d, `cargo build --release`, an Intel i7-12700H laptop, a throwaway project), the whole hook process, including start-up: PreToolUse 2 ms; PostToolUse with a two-line `.env` 5 to 9 ms; PostToolUse with a 2.3 MB `secrets.json` of 35000 keys 0.13 s. Before the parser used hash lookups, a 1.7 MB file of the same shape took 6.6 s in the same kind of release build, and the time grew quadratically with the size. A hook that times out lets the original output through.
**Harness adapters.** The policy engine knows no specific AI coding agent, and an adapter translates for one harness. Only the Claude Code adapter exists. There is a hook script and an in-process library, and no MCP proxy.
**Single policy file.** `.botsecrets` is the unified configuration interface. One file declares both what to redact (`[files]`, `[keys]`, `[heuristic]`) and what to restrict (`[policy]`).
## What masking covers
The PostToolUse hook redacts what Claude Code hands it and accepts back. This was read from Claude Code's documentation and the output schemas bundled in v2.1.314, and has not yet been checked in a live session.
**Covered:** a value in the manifest that appears whole in any string of a successful tool's output, for every built-in tool and MCP tool, nested at any depth. The output comes back in the same shape, with only the values masked. This is a narrow promise. Everything else, and every failure the tests show, is in [Known failures](known-failures.md).
### Spellings
A value has one manifest entry per spelling, so that a file read and a program's output both match:
- the decoded text, and the text as the file holds it (`\n` in a JSON string, a YAML block with its indentation, a TOML `\t`, a continued `.properties` line);
- its JSON-escaped form and its `\n`-escaped form, with and without the trailing line end;
- each line of a multi-line value of 8 characters or more, for a Read with a line range, a grep or a diff. PEM and base64 lines have 64 or 76 characters; below 8 sit words of ordinary text (`end`, `prod`), and a line matches everywhere. PEM armor (`-----BEGIN ...`) and lines with no letter or digit are left out, since scripts and docs hold them too. So the last line of a key shorter than 8 characters passes when read away from the rest of it;
- the text of a number in a JSON, TOML or YAML secret file, from 6 characters. Shorter numbers under a matching key are mostly settings (`CACHE_KEY_TTL = 3600`), and masking `3600` everywhere does more harm than a secret that short can suffer. A quoted value keeps the general minimum of 4.
**Plain settings make no entry.** Before an entry is made, a value is dropped when it is a boolean or null word (`true false yes no on off null none nil enabled disabled`, any case, quoted or not), a number or a duration under 6 characters (`3600`, `0.5`, `30s`, `15m`, `2d`). This holds for a `.env` too, and also for a key named in `keys.include` or a `[[file]]` override. Without such a naming, a value is also dropped when the key's last word (split at `.`, `_` or `-`) is a setting word: `ENABLED`, `TTL`, `TIMEOUT`, `LIMIT`, `MODE`, `PORT`, `HOST`, `POLICY`, `NAME`, `USER` and similar (the list is in `core/secrets/value_class.rs`). So `AUTH_ENABLED=true` and `API_TOKEN_TTL=604800` mask nothing, while `DB_PASSWORD=postgres` does, as it is no setting word. The built-in key pattern `*AUTH*` is three patterns (`*AUTH`, `*AUTH[!O]*`, `*AUTHORIZATION*`), so `AUTHOR`, `AUTHORITY` and `AUTHORIZED_*` no longer match; `exclude = ["*AUTH*"]` removes all three.
Overlapping matches become one mask, named after the longest. A multi-line value in a `.env` needs its closing quote at the end of a line. An opening quote without one is read as the plain value of that line, and the next assignment is still read. A closing quote that does come later swallows the assignments in between: see [Known failures](known-failures.md).
**Places a mask cannot go.** Claude Code validates a replacement for a built-in tool and, if it fails, uses the original output. So:
- A listed enum or literal value (`type: "text"`, `status: "completed"`, Bash's `gitOperation.commit.kind`) stays even if a secret equals it. It is one of the schema's fixed words and says nothing about the secret. `harness/claude.rs` holds the list.
- A secret anywhere else in such a field, or in an object key of a built-in, replaces the whole output with a refusal, under every setting. A short or common secret such as `file` can therefore refuse every output whose fields contain that word. The refusal names the secret's key, so change the value or leave its file out of `[files]`. The exception is AskUserQuestion's answers, keyed by question text: those keys are masked.
- An MCP tool's output has no schema. Its object keys are masked, and only a content block's `type` is kept.
- Fields of the Artifact tool's schema with a pattern (hashes, ids, versions, addresses) or an enum built at run time (`reason`) cannot be listed. A secret in one refuses the output.
- Two things stay unknown, and a secret inside either would make Claude Code reject the mask and use the original, which it reports as a hook error: a later Claude Code's new enum, and flag-gated fields whose values only exist at run time (`RUN_OP_STATUS` and `runOpOutputFields` of Workflow, the `handlers` arms of Artifact).
**Refusals under `on_parse_error = "deny"`.** The secrets are unknown then, so nothing can be masked. Bash, Read and Artifact answer with a minimal output holding the refusal. Other built-ins keep their shape: strings replaced, lists cut to one item, listed enum values, numbers and booleans kept, answer records emptied. Their keys and numbers pass through, since none of those schemas has other free-text keys. An MCP result becomes the refusal text.
**When the hook does not run.** `"onFailure": "block"` on PreToolUse (Claude Code v2.1.295 or later) stops the tool if `fermata` cannot start, fails or times out. Without it the call goes ahead. With it every tool stops, so the agent cannot repair this itself. A teammate without `fermata` on `PATH` is blocked 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"`. On PostToolUse a hook failure cannot hold anything back, because the tool already ran: a `fermata` that crashes only there lets that output through. So does a matcher that leaves a tool out.
**Consequences of a mask.** The agent sees `*****`, not the value. Each PostToolUse that masks something adds a note: "Values in this output are masked. Do not write them back into a file." If the agent writes what it read back anyway, the write guard stops a Write or Edit that adds a mask (`on_mask_write`), and an Edit whose `old_string` holds a mask fails. A shell command that writes is not checked. Guard secret files with `[policy.write]` as well. With `style = "absent"` a field that would come out empty reads `[fermata]`.
## The .botsecrets format
`.botsecrets` is a TOML file. It says which files to parse and which rules to apply, and nothing in it is specific to a harness. fermata reads it for Claude Code only.
A typical `.botsecrets` looks like this:
```toml
# Declare files that contain secrets.
# fermata parses them, extracts the values, and redacts those values
# from tool output, as far as it can.
[files]
patterns = [".env", ".env.*", "config/credentials.toml", "secrets/*.yaml"]
[keys]
include = ["STRIPE_*", "MY_APP_SIGNING_*"]
[heuristic]
enabled = true
# Rules for writes and commands.
# Reading secret-containing files is allowed.
[policy.write]
patterns = [".claude/**", "vendor/**", "*.lock"]
[policy.bash]
deny = ["rm -rf /", "curl * | sh"]
```
No secret values appear in `.botsecrets` itself. It points to the files that contain them. Built-in key patterns (`*PASSWORD*`, `*SECRET*`, `*API_KEY*`, `*TOKEN*`, `DATABASE_URL`, etc.) decide which values count unless `[keys]` adds more.