From 999ed6ba4e7e4122370372a26891ca14b5a6a389 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gabor=20K=C3=B6rber?= Date: Sat, 7 Nov 2026 01:38:19 +0100 Subject: [PATCH] docs(fermata): known limits, config reference and READMEs say what the tests show Known to fail holds only what known_limits.rs pins or Claude Code's docs state; the multi-line quoted value gets its own limit test. configuration.md follows the code (unknown fields, [enforcement] settings, marks, plain settings, verb classes) and every TOML example of it is loaded by tests/docs_toml_examples.rs. Speed numbers are measured with a release build. matrix.md notes the new refusals. --- CLAUDE.md | 14 ++-- README.md | 35 +++++---- docs/commands.md | 17 ++--- docs/configuration.md | 143 +++++++++++++++++++++++------------- docs/security-model.md | 62 ++++++++++------ docs/threat-model.md | 29 ++++---- tests/docs_toml_examples.rs | 41 +++++++++++ tests/known_limits.rs | 10 +++ 8 files changed, 236 insertions(+), 115 deletions(-) create mode 100644 tests/docs_toml_examples.rs diff --git a/CLAUDE.md b/CLAUDE.md index 8e6438f..ccc8ad9 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -12,11 +12,12 @@ Harness-agnostic secret redaction engine and policy gate for AI coding agents. Three concentric layers; nothing inner imports from anything outer. -- **`core/`** — harness-unaware, transport-unaware, sync. Types (`Op`, `Decision`), `.botignore` walker, `Policy::check` / `check_command`, path extraction. `.botsecrets` contains a `[policy]` section for access control rules (`fermata.toml` is accepted as an alias for `.botsecrets`). Sync, no tokio. +- **`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). + - `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, JSON). 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. + - `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). @@ -33,13 +34,14 @@ Developed in this monorepo; planned to be exported as a standalone repo in the f ## Failure behaviour and known limits -- **Hooks fail open, except under `on_parse_error = "deny"`.** 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. `fermata check` does not refuse on a broken config. +- **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. `fermata check` does not refuse on a broken config. - **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). - **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. Heuristics warn in `additionalContext` and do not mask. Full list: `docs/security-model.md`, "Known limits". +- **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 both READMEs and `docs/security-model.md` must change with it. `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/security-model.md`, "Known limits". - **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: not read, no refusal, not redacted. +- **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) diff --git a/README.md b/README.md index 32f1a9d..6028a0d 100644 --- a/README.md +++ b/README.md @@ -7,16 +7,24 @@ ## Known to fail -These failures were reproduced with fake values, through the fermata binary. The list is not complete. +These failures were reproduced with fake values, through the fermata binary, and each is a test that asserts the failure happens, except where it says it comes from Claude Code's documentation. The list is not complete. -- **Files on the default secret list are never read.** fermata only parses `.env`, TOML, JSON, YAML, Python and properties files. A Read of anything else on its default list reaches the model, even under `on_parse_error = "deny"`: `terraform.tfstate`, `*.tfstate`, `terraform.tfvars`, `*.auto.tfvars`, `.aws/credentials`, `.netrc`, `.htpasswd`, `*.pem`, `*.key`, `id_rsa`, `id_ed25519`, `id_ecdsa`. `*.p12` and `*.pfx` take the same path. -- **Many values never enter the list of known secrets.** A commented `.env` line, a symlinked `.env`, a multi-document YAML file, `secrets.py` with a trailing comment or a triple-quoted value, `.env` values with shell quoting inside them, the first value of a duplicate JSON key, a value swallowed by an unclosed quote, a file that cannot be parsed, a secret file outside the working project. -- **Ordinary config values get masked everywhere, and this can corrupt source.** With `AUTH_ENABLED=true` and `TOKEN_TTL=3600` in `.env`, every `true` and `3600` in every output becomes `*****`. An agent that reads the mask from a source file and writes the file back puts the mask into your code. -- **`cat .env; false` is unprotected.** According to Claude Code's documentation and bundled code, a failed tool's output goes down a path no hook can rewrite. A `[policy.bash]` deny pattern stops only the spelling it names. -- **Commands are not checked against path rules.** `.botignore` and `[policy.read]` do not stop `cat .env` in Bash. -- **A directory pattern in `.botignore` does not match the files below it.** `vendor/` lets a write to `vendor/a` through. `vendor/**` stops it. A relative path never matches `.botignore`. +- **`cat .env; false` is unprotected.** According to Claude Code's documentation and bundled code, a failed tool's output goes down a path no hook can rewrite. With `.env` in `.botignore` or `[policy.read]`, a command that names the file (`cat .env; false`, `cat ./.env; false`) is stopped, and `env; false` and a failing `npm test` that prints its environment are not. On the default configuration a parseable `.env` is not stopped at all. +- **Commands are checked only for the files they name.** A variable or substitution that builds the name, a script that opens the file, a printing verb that is not on the list (`python -c`, `dd`, `perl`) and `cd ../other && cat .env` pass. +- **A secret file fermata cannot mask is stopped when a Read names it, and by no other route.** `*.p12`, `*.pfx`, `.netrc`, `.htpasswd` and a text `*.key` pass `grep -r TOKEN .`, `tar cf x.tar .` and a script that opens them. The stop needs the PreToolUse hook: without it a Read reaches the model. A text with `{{` or `{%` that does not parse passes as a template, and a literal value in it reaches the model. +- **Many values never enter the list of known secrets.** + - a key the key filter does not match, in a parsed file; a `.tfvars` heredoc; a comment in a TOML or YAML file + - the first value of a duplicate JSON key + - a `.env` value inside a quoted value that spans several lines, when a program prints it alone + - Python triple quotes, and shell-quoted spellings such as `'a'\''b-x` and `abc"def"-x`, when a program prints the decoded value + - a number under 6 characters, and a secret number that a tool returns as a JSON number + - a UTF-16 or Latin-1 file, or JSON with comments, when no command names it + - a secret file outside the working project +- **A short password's word is masked everywhere**, in other files too, and an Edit that names such a line in source can fail. A short line of a multi-line value passes when printed alone. +- **Other routes that stay open:** Monitor's output, a changed file's attachment and a hook that times out (all from Claude Code's documentation), values split across strings, encoded values, binary fields, and any secret the heuristic scanner finds, since it only warns. +- **The write guard is narrow.** It stops a Write or Edit that adds a mask. A shell command that writes a mask, the `absent` style, and a real run of exactly five asterisks are not handled. -The fuller list: [docs/security-model.md](docs/security-model.md#known-limits). The test suite never runs Claude Code. +The fuller list: [docs/security-model.md](docs/security-model.md#known-limits). `tests/known_limits.rs` shows each limit through the binary, except what comes from Claude Code's own documentation. The test suite never runs Claude Code. ## What it tries to do @@ -27,7 +35,7 @@ fermata runs in hooks around an agent's tool calls: ``` Agent wants to run a tool | - PreToolUse ── .botsecrets [policy] / .botignore + PreToolUse ── .botsecrets [policy] / .botignore, read gate, write guard | a rule matches? → deny or ask | otherwise → no answer: Claude Code's permissions decide | @@ -44,9 +52,10 @@ Agent wants to run a tool |------|-----------|--------------| | 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, and commands whose text matches. No rules, nothing stopped | +| 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 | -Each call parses the secret files again. That takes milliseconds for a small file and about 23 s at 1.7 MB. A hook that times out lets the original output through. +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. A hook that times out lets the original output through. fermata is no sandbox: see [docs/threat-model.md](docs/threat-model.md). @@ -129,8 +138,8 @@ 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=hunter2"); -// clean.text holds the masked text, if hunter2 made it into the manifest +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"); diff --git a/docs/commands.md b/docs/commands.md index 68e8a4e..ac99655 100644 --- a/docs/commands.md +++ b/docs/commands.md @@ -29,13 +29,13 @@ fermata check [OPTIONS] ... |------|---------| | 0 | Allowed (or Ask -- the agent may prompt the user) | | 1 | Denied -- the policy blocks this operation | -| 2 | Internal error (could not load policy, bad arguments, etc.) | +| 2 | Internal error (could not load policy, bad arguments, a config layer or a `[files]` pattern that does not load, etc.) The message names the file and line. | When multiple paths are provided, fermata evaluates each one independently and returns the **worst** result. If any path is denied, the exit code is 1. **Examples** -A relative path never matches `.botignore`, so it exits 0 whatever the file says. Use absolute paths. +A relative path is taken against the project root and checked like the absolute one. ```bash # Check if the agent can read .env @@ -79,14 +79,14 @@ The hook payload is always read from **stdin** as JSON. The response is written | 0 | Success. The JSON response on stdout tells the harness what to do. | | 2 | Internal error (unknown harness, unknown event type, stdin read failure) | -Fermata follows a **fail-open** policy for hooks: if the payload cannot be parsed or the policy cannot be loaded, it writes `{}` to stdout (PreToolUse: an allow) and exits 0 so the agent can continue. A tool PreToolUse has no rules for answers `{}` without a message. Errors are reported on stderr and never quote a file. +Fermata follows a **fail-open** policy for hooks: if the payload cannot be parsed, it writes `{}` to stdout and exits 0 so the agent can continue. If a config layer cannot be loaded (including a field fermata does not know), only that layer's rules are off, and PostToolUse adds a note beside text output naming the file and line. A tool PreToolUse has no rules for answers `{}` without a message. Errors are reported on stderr and never quote a file. -The exception is `on_parse_error = "deny"`. If the config or a secret file cannot be loaded, `post-tool-use` answers with a refusal naming the file, in a form the tool's output schema accepts; if the config or the rules cannot be loaded or applied, `pre-tool-use` answers deny. See [`on_parse_error`](configuration.md) for what happens when the config itself is the broken file. Claude Code drops a replacement that its schema rejects and uses the original: see [Known limits](security-model.md#known-limits). +The exception is `on_parse_error = "deny"` (the default is `allow`). If the config or a secret file cannot be loaded, `post-tool-use` answers with a refusal naming the file, in a form the tool's output schema accepts; if the config or the rules cannot be loaded or applied, `pre-tool-use` answers deny. See [`on_parse_error`](configuration.md) for what happens when the config itself is the broken file. Claude Code drops a replacement that its schema rejects and uses the original: see [Known limits](security-model.md#known-limits). **Event types** -- **pre-tool-use** -- Runs before the tool executes. Fermata checks the requested path or command against `.botsecrets [policy]` / `.botignore` and returns an allow, deny, or ask decision to the harness. -- **post-tool-use** -- Runs after the tool executes. Fermata loads `.botsecrets`, builds a manifest of known secret values, and masks any matches in every string of the tool output, returning it in the same shape (`updatedToolOutput`), or `{}` if nothing changed. A secret where a built-in tool's schema cannot take a mask (an object key, a fixed field) refuses the whole output under every setting. A heuristic scanner (regex patterns derived from gitleaks) adds a warning beside the output (`additionalContext`) for undeclared secrets; it does not mask them. +- **pre-tool-use** -- Runs before the tool executes. Fermata checks the requested path against `.botsecrets [policy]` / `.botignore`, and the files a command names (by the verb of each segment), and returns a deny or ask decision, or nothing. It also stops a Read of a listed secret file it cannot mask (`on_unparsed_read`) and a Write or Edit that adds a mask to a file (`on_mask_write`). +- **post-tool-use** -- Runs after the tool executes. Fermata loads `.botsecrets`, builds a manifest of known secret values, and masks any matches in every string of the tool output, returning it in the same shape (`updatedToolOutput`), or `{}` if nothing changed. Each masking adds the note "Values in this output are masked. Do not write them back into a file." A secret where a built-in tool's schema cannot take a mask (an object key, a fixed field) refuses the whole output under every setting. A heuristic scanner (regex patterns derived from gitleaks) adds a warning beside the output (`additionalContext`) for undeclared secrets; it does not mask them. **Examples** @@ -109,7 +109,7 @@ Fermata does not have its own global config file. All configuration lives in you | File | Purpose | |------|---------| | `.botsecrets` | TOML file for secret redaction (`[files]`, `[heuristic]`, `[keys]`) **and** access-control policy (`[policy]` section with `[policy.read]`, `[policy.write]`, `[policy.bash]`). Unified config for most projects. `fermata.toml` is accepted as an alias (same format, `.botsecrets` takes priority). | -| `.botignore` | Gitignore-syntax patterns. Blocks both reads and writes to matched paths. | +| `.botignore` | Gitignore-syntax patterns. Blocks both reads and writes to matched paths, and commands that name a matched file. | Fermata discovers these files by walking up from the target path (or the current working directory for `hook`) until it finds a project root. @@ -138,7 +138,7 @@ patterns = [".env", ".env.*"] enabled = true ``` -The `.botignore` stops the Read, Write and Edit tools on those paths, and does not stop `cat .env` in Bash. The `.botsecrets` tries to mask the values of the files it can parse in the output of tools that succeed. +The `.botignore` stops the Read, Write and Edit tools on those paths, and a printing command such as `cat .env` that names one of them. It does not see a command that hides the name (`cat $(...)`, a script). The `.botsecrets` tries to mask the values of the files it can parse in the output of tools that succeed. ### Single-file setup with .botsecrets @@ -203,7 +203,6 @@ fermata check --op read "$PWD/src/main.rs" echo $? # Should exit 1 (denied) if .botignore blocks .env. -# Use an absolute path: a relative path never matches .botignore and exits 0. fermata check --op read "$PWD/.env" echo $? diff --git a/docs/configuration.md b/docs/configuration.md index b66b8cb..b835afb 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -2,17 +2,28 @@ > **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 limits](security-model.md#known-limits) for where it fails. -Fermata uses up to two configuration files to control what an AI coding agent -can access and what secret values it can see. `.botsecrets` is the primary -configuration file. Most projects need only this file. +Fermata reads `.botsecrets` (in up to three layers) and any number of `.botignore` +files, to control what an AI coding agent can access and what secret values it can +see. `.botsecrets` is the primary configuration file. Most projects need only this file. -| File | Purpose | Syntax | -|------|---------|--------| -| `.botsecrets` | Declare secrets, control redaction, and set policy rules | TOML | -| `.botignore` | Block agent access to matching paths (optional, gitignore syntax) | gitignore | +| File | Where | Purpose | Syntax | +|------|-------|---------|--------| +| `.botsecrets` | project root | Declare secrets, control redaction, and set policy rules | TOML | +| `.botsecrets.local` | project root, git-ignored | Developer-specific overrides of the project file | TOML | +| `.botsecrets` | `~/.config/fermata/` (Linux/macOS) or `%APPDATA%\fermata\` (Windows) | User-global defaults for every project | TOML | +| `.botignore` | any directory of the project (optional) | Block agent access to matching paths | gitignore | `fermata.toml` is accepted as an alias for `.botsecrets` (same format, `.botsecrets` takes priority when both exist). +**A field fermata does not know is an error.** Every section rejects unknown fields, +so a typo, or a setting that no longer exists (`[enforcement] mode`, +`on_parse_error = "mask-entire-file"`), makes that layer fail to load. The hooks then +switch that layer's rules off and say so beside text output (naming the file and the +line); under `on_parse_error = "deny"` they refuse instead; `fermata check` exits 2. +A stale user-global `.botsecrets` with an unknown field therefore affects every +project on the machine, and it also makes Dirigent refuse every agent-channel message +from that machine (see `docs/configuration/matrix.md` in the Dirigent repository). + Configuration is layered, with later (more specific) sources overriding earlier ones. All files are optional. Without any configuration Fermata allows all operations and performs no redaction. @@ -46,8 +57,8 @@ ones: **replaced** by the more specific layer when present. - **Key lists** (`keys.include`, `keys.exclude`): **accumulated** across layers (appended, not replaced). -- **Scalar fields** (`redaction.style`, `heuristic.enabled`, `enforcement.mode`, - etc.): the most specific value wins. +- **Scalar fields** (`redaction.style`, `heuristic.enabled`, + `enforcement.on_parse_error`, etc.): the most specific value wins. ### `[files]` -- Secret File Patterns @@ -64,18 +75,24 @@ key-value pairs, and uses the values for exact-match redaction. .env, .env.*, *.env, secrets.*, credentials.*, *.key, *.pem, *.p12, *.pfx, id_rsa, id_ed25519, id_ecdsa, Secrets.toml, Secrets.*.toml, terraform.tfvars, *.auto.tfvars, terraform.tfstate, *.tfstate, -.docker/config.json, config/master.key, config/credentials/*.key, -.aws/credentials, .netrc, .htpasswd, service-account.json, -service-account-key.json +*.tfstate.backup, .docker/config.json, config/master.key, +config/credentials/*.key, .aws/credentials, .netrc, .htpasswd, +service-account.json, service-account-key.json ``` -Fermata only parses `.env`, TOML, JSON, YAML, Python and properties files, and -`[[file]]` overrides with one of those formats. On this list, `*.key`, `*.pem`, -`*.p12`, `*.pfx`, `id_rsa`, `id_ed25519`, `id_ecdsa`, `terraform.tfvars`, -`*.auto.tfvars`, `terraform.tfstate`, `*.tfstate`, `config/master.key`, -`config/credentials/*.key`, `.aws/credentials`, `.netrc` and `.htpasswd` are -never parsed. Their contents reach the model on a Read, also under -`on_parse_error = "deny"`. +Fermata chooses a parser from the file's name: + +| Files | Format | +|-------|--------| +| `.env`, `.env.*`, `*.env`, `credentials`, `terraform.tfvars`, `*.auto.tfvars`, `.aws/credentials`, `secrets.{sh,bash,zsh,ini,conf,cfg}` | `.env` style (`KEY=value`, `[section]` lines skipped) | +| `*.toml`, `*.json`, `*.yaml`, `*.yml`, `*.py`, `*.properties` (also `secrets.*` and `credentials.*` with these extensions) | TOML, JSON, YAML (every document), Python assignments, properties | +| `*.tfstate`, `*.tfstate.backup` | JSON. Its secrets sit by position, not by key, so a Read is always stopped | +| `*.pem`, `*.key`, `id_rsa`, `id_ed25519`, `id_ecdsa`, `config/master.key`, `config/credentials/*.key` | Opaque text: a secret as a whole. A Read is stopped unless the file holds only certificates. A PEM private block's body, or a single token of 16 or more characters, becomes a manifest entry | +| `.netrc`, `.htpasswd`, `*.p12`, `*.pfx` | No parser. A Read is stopped, and nothing from them is masked | + +A `[[file]]` override can name a format. A leading UTF-8 byte order mark is read. UTF-16, Latin-1 and JSON with comments do not parse. A file named `secrets.*` or `credentials.*` takes its parser from its extension (`secrets.yaml`, `secrets.sh`). One with a source or template extension (`rs`, `ts`, `go`, `java`, `md`, `tf`, `example`, `template`, and so on) is taken for code that handles secrets, and is neither parsed nor stopped. + +**The read gate.** A Read, a Grep with a `path`, or a printing command (`cat`, `grep`, ...) naming an existing file on this list that fermata cannot mask is stopped, under every `on_parse_error`: the file has no parser, is a secret as a whole, cannot be parsed, holds lines no value can be read from, or marks its secrets by position. The setting is `[enforcement] on_unparsed_read`. Other routes (`grep -r`, a script that opens the file, a verb off the list) pass the gate, and the file's values are not masked there. A file with `{{` or `{%` that fails to parse passes as a template. See [Known limits](security-model.md#known-limits). Setting `files.patterns` in a layer **replaces** the defaults entirely. @@ -92,20 +109,33 @@ Patterns use glob syntax and are matched case-insensitively. | Field | Type | Default | Description | |-------|------|---------|-------------| | `include` | `string[]` | `[]` | Additional key name patterns to treat as secret. Accumulated across layers. | -| `exclude` | `string[]` | `[]` | Key name patterns to remove from the effective set. Exact string match against the pattern text. | +| `exclude` | `string[]` | `[]` | Key name patterns to remove from the effective set. Exact string match against the pattern text, with one alias: `*AUTH*` removes the three patterns that replaced it. | Fermata ships with ~30 built-in key patterns that are always active: ``` *PASSWORD*, *SECRET*, *API_KEY*, *APIKEY*, *TOKEN*, *ACCESS_KEY*, -*PRIVATE_KEY*, *AUTH*, *CREDENTIAL*, *CONNECTION_STRING*, DATABASE_URL, +*PRIVATE_KEY*, *AUTH, *AUTH[!O]*, *AUTHORIZATION*, *CREDENTIAL*, +*CONNECTION_STRING*, DATABASE_URL, AWS_SECRET_ACCESS_KEY, GITHUB_TOKEN, OPENAI_API_KEY, ANTHROPIC_API_KEY, JWT_SECRET, ENCRYPTION_KEY, MASTER_KEY, SECRET_KEY_BASE, ... ``` +`*AUTH*` is three patterns (`*AUTH`, `*AUTH[!O]*`, `*AUTHORIZATION*`), so that `AUTHOR`, +`AUTHORITY` and `AUTHORIZED_*` do not match. `exclude = ["*AUTH*"]` removes all three; it +does not remove `*TOKEN*`, so `AUTH_TOKEN` stays. + Use `keys.include` to add project-specific patterns. Use `keys.exclude` to suppress a built-in pattern that causes false positives. +**Plain settings make no entry.** A value that is a boolean or null word (`true`, `off`, +`none`, ...), a number under 6 characters or a duration (`30s`, `2d`) is never a secret, +even under a matching key. A key whose last word is a setting word (`TTL`, `TIMEOUT`, +`PORT`, `POLICY`, `NAME`, ...: `core/secrets/value_class.rs` has the list) makes no entry +either, unless a `keys.include` pattern matches it or a `[[file]]` override names the file. +So `AUTH_ENABLED=true` and `API_TOKEN_TTL=604800` mask nothing, and `DB_PASSWORD=postgres` +still masks `postgres` in every output. + ```toml [keys] include = ["STRIPE_*", "MY_APP_SIGNING_*"] @@ -125,9 +155,9 @@ Available styles: | Style | Output | Description | |-------|--------|-------------| | `masked` | `*****` | Replaces the value with asterisks. Default. | -| `typed` | `` | Shows the value type but not the content. | -| `named` | `` | Shows the key name but not the value. | -| `absent` | *(empty string)* | Removes the value entirely. | +| `typed` | `` | Shows the type and the value's length (`N`) but not the content. | +| `named` | `` | Shows the key name but not the value. | +| `absent` | *(empty string)* | Removes the value entirely. Where a text would come out empty it reads `[fermata]`. The write guard has nothing to count in this style. | ```toml [redaction] @@ -164,41 +194,38 @@ patterns = ["MYAPP-[A-Za-z0-9]{32}"] ### `[enforcement]` -- Enforcement Behavior -Controls how strictly Fermata enforces redaction, especially in edge cases. +Controls what fermata refuses. | Field | Type | Default | Description | |-------|------|---------|-------------| -| `mode` | `string` | `"permissive"` | Global enforcement strictness. | -| `on_parse_error` | `string` | `"mask-entire-file"` | What to do when a secret file cannot be parsed. | +| `on_parse_error` | `string` | `"allow"` | What to do when a secret file or a config layer cannot be parsed. | +| `on_unparsed_read` | `string` | `"deny"` | What to do with a Read of a listed file that fermata cannot mask. | +| `on_mask_write` | `string` | `"deny"` | What to do with a Write or Edit that adds a mask to a file. | -Enforcement modes: +There is no `mode` field: an `[enforcement] mode` line, or `on_parse_error = "mask-entire-file"`, is an unknown value and breaks the layer. -| Mode | Behavior | -|------|----------| -| `strict` | Accepted, and has no effect. | -| `permissive` | Accepted, and has no effect. Default. | -| `audit` | Accepted, and has no effect. | - -The hooks do not read `mode`. Only `on_parse_error` changes what they do. - -Parse error actions: +`on_parse_error`: | Action | Behavior | |--------|----------| -| `mask-entire-file` | Default. Warn on stderr and go on without that file's values: they are not redacted. Masking the whole file is not implemented. | -| `allow` | Skip the unparseable file (secrets may leak). | +| `allow` | Default. Go on without that file's values: they are not masked. A note beside text output names the file (or the broken config layer and its line). | | `deny` | The hooks refuse. PostToolUse answers each tool output with a refusal naming the file, until it parses. See [Known limits](security-model.md#known-limits). | +`on_unparsed_read`: `deny` stops a Read of a file on the secret list that fermata cannot mask (see the read gate above), with a reason that names the file and this setting and says to ask the user; `allow` lets it through. It applies under every `on_parse_error`. + +`on_mask_write`: `deny` stops a Write, Edit or MultiEdit whose new text holds more masks than the old text, because a mask stands for a value fermata hid and writing it back corrupts the file. `allow` turns the guard off. A shell command that writes is not checked. + Messages name the file and the line, never the line's text. -If the config itself cannot be read, the setting is unknown. Any layer with an uncommented line setting `deny` counts, even in a file that does not parse, and PreToolUse then refuses too. A layer whose bytes cannot be read says nothing, so it does not count. Otherwise the hooks stay open. +If the config itself cannot be read, the setting is unknown. Any layer with an uncommented line setting `deny` counts, even in a file that does not parse, and PreToolUse then refuses too. A layer whose bytes cannot be read says nothing, so it does not count. Otherwise the hooks stay open, with that layer's rules off. Editor files never refuse: a discovered vim swap file (`*.swp`, then `*.swo` and on down to `*.swa`, and `*.swx`), Kate's `*.kate-swp` or a `*~` that cannot be read or parsed is passed over under every setting. If it can be parsed, its values are still redacted. `.bak` and `.env.gpg` follow the setting, and so does anything named in `[[file]]`. ```toml [enforcement] -mode = "strict" on_parse_error = "deny" +on_unparsed_read = "deny" +on_mask_write = "deny" ``` ### `[[file]]` -- Per-File Overrides @@ -209,7 +236,7 @@ non-standard format or you only want to redact specific keys. | Field | Type | Required | Description | |-------|------|----------|-------------| | `path` | `string` | Yes | Path to the file (relative to project root). | -| `format` | `string` | No | Force a specific parser: `"env"`, `"toml"`, `"yaml"`, `"json"`. Auto-detected if omitted. | +| `format` | `string` | No | Force a specific parser: `"env"`, `"toml"`, `"yaml"`, `"json"`, `"python"`, `"properties"`, `"tfstate"`, `"opaque"`. Auto-detected from the name if omitted. | | `keys` | `string[]` | No | Only redact these specific keys from this file (instead of applying global key patterns). | ```toml @@ -260,8 +287,9 @@ ask = ["docker", "kubectl"] #### `[policy.read]` -- Read Restrictions (Rarely Needed) -Stops the Read tool on matching paths. A shell command that prints them is not -checked. +Stops the Read tool on matching paths, and a printing command (`cat`, `grep`, ...) +that names a matching file. A command that hides the file name (a variable, a +substitution, a script) is not checked. ```toml [policy.read] @@ -277,7 +305,8 @@ remains useful for monorepo subtree exclusion or teams that prefer gitignore syntax for simple path blocking. A `.botignore` file uses **gitignore syntax** to stop the Read, Write and Edit -tools on matching paths. A shell command is not checked. When a path matches, both reads and writes are denied. There is no +tools on matching paths, and commands that name a matching file (the verb decides: +see below). When a path matches, both reads and writes are denied. There is no distinction between operations -- if you need per-operation control, use the `[policy]` section in `.botsecrets` instead. @@ -302,9 +331,20 @@ an ignore from a shallower `.botignore`. ### Syntax -These gitignore rules apply, with two differences from git. A directory pattern -such as `vendor/` does not match the files below it, so write `vendor/**`. A -relative path never matches: the rules only meet absolute paths. +These gitignore rules apply. A directory pattern such as `vendor/` matches the +files below it, as in git (`!vendor/keep` allows one back), 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 its target. + +**Commands.** A command is checked for the files it names, by the verb of each +segment: 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 `.botignore`, `[policy.read]` and the read gate; a metadata verb (`ls stat file +test [ du which echo printf`, `git status`, `git commit`, ...) meets nothing; every other +verb (`source`, `cp`, `rm`, `python`) meets the rules but not the read gate. Only +words that name an existing file or hold a path separator count; `$VAR`, `$(...)`, +scripts and a verb off the list that opens the file itself are not seen. `[policy.write]` +is not applied to commands. - Blank lines and lines starting with `#` are ignored. - `*` matches anything except `/`. @@ -397,8 +437,9 @@ enabled = true mode = "enforce" [enforcement] -mode = "strict" -on_parse_error = "mask-entire-file" +on_parse_error = "allow" +on_unparsed_read = "deny" +on_mask_write = "deny" [policy.write] patterns = [".claude/**", "vendor/**", "*.lock", "dist/**", "migrations/**"] @@ -423,5 +464,5 @@ keys = ["api_key", "webhook_secret"] style = "masked" [enforcement] -mode = "permissive" +on_parse_error = "allow" ``` diff --git a/docs/security-model.md b/docs/security-model.md index 6ead86c..62733ef 100644 --- a/docs/security-model.md +++ b/docs/security-model.md @@ -32,7 +32,7 @@ The design has four layers. Layers 1 and 2 operate on data content (the actual s 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 the value `hunter2` 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 limits](#known-limits). +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 limits](#known-limits). ### Layer 2: Heuristic Detection (Scanner + gitleaks patterns) @@ -44,11 +44,16 @@ Its false-positive rate is higher than Layer 1's, which is why it warns: masking ### Layer 3: Access Control (.botignore / .botsecrets [policy]) -Stop the tool calls your rules name. 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. Path patterns apply to the Read, Write and Edit tools, and command patterns match the text of a command. +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. -Reading `.env` is allowed by default, and only Layer 1 stands between its values and the model. +- **Commands that name a file.** A command is split into segments, and each word that names an existing file (or holds a path separator) is checked. 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. Any other verb (`source`, `cp`, `rm`, `python`) meets the path rules only. A metadata verb (`ls stat file test [ du which echo printf`, and `git status`, `git check-ignore`, `git ls-files`, `git commit`) 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. -**Limitation**: Commands are not checked against path rules. `cat .env` and `source .env && echo $DB_PASSWORD` pass this layer, whatever `.botignore` and `[policy.read]` say. A `.botignore` directory pattern such as `vendor/` does not match the files below it; `vendor/**` does. A relative path never matches `.botignore`. +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. + +**Limitations of the command check.** It sees the command's text, not what the shell makes of it. A variable or a command substitution that builds the file name (`cat $(printf '.e%s' nv)`), `"$(cat .env)"`, a script that opens the file (`sh run.sh`, `python -c "print(open('.env').read())"`), `cd ../other && cat .env` and a printing verb that is not on the list (`dd`, `perl`, `python -c`) pass. A command run in one project is not stopped by another project's rules. A secret file outside every project has no rules at all. ### Layer 4: Structural Containment (External) @@ -58,13 +63,13 @@ fermata does not own this layer. It would come from a container runtime, VM, or ## Design Principles -**Fail-open by default.** A parse error in `.botsecrets` or in a secret file does not block the agent from working, and the values of that file then reach the model. An unrecognized file format is passed over without a word, also under `deny`. Two exceptions: under `on_parse_error = "deny"` the hooks refuse instead, and under `"onFailure": "block"` on PreToolUse a `fermata` that cannot run stops every tool. +**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 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. The [known limits](#known-limits) say 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. For a small secret file that takes milliseconds. It grows quadratically with the file: 0.6 s for an 81 KB JSON file, 23 s at 1.7 MB, over 300 s at 6.9 MB. A hook that times out lets the original output through. +**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. @@ -74,22 +79,33 @@ fermata does not own this layer. It would come from a container runtime, VM, or The PostToolUse hook redacts what Claude Code hands it and accepts back. These are the edges. They were read from Claude Code's documentation and the output schemas bundled in v2.1.314, and have 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: the list below is long and not complete. +**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: the list below is long and not complete. Each limit marked "test" is shown through the binary by `tests/known_limits.rs`, which asserts that the failure happens; the others come from Claude Code's documentation and bundled code. **Not covered:** -- **Files on the default list that are never parsed.** `terraform.tfstate`, `*.tfstate`, `terraform.tfvars`, `*.auto.tfvars`, `.aws/credentials`, `.netrc`, `.htpasswd`, `*.pem`, `*.key`, `id_rsa`, `id_ed25519`, `id_ecdsa`, `*.p12` and `*.pfx` have no parser. A Read of one reaches the model under every setting, and `deny` refuses nothing, since this is no parse failure. Some of them get a heuristic warning beside the value. -- **Values that never enter the manifest.** A commented `.env` line (`#API_TOKEN=old-prod-value`). A `.env` that is a symlink. A multi-document YAML file: by default the whole file is skipped with a line on stderr, and under `deny` every output is refused for a valid file. `secrets.py` with `SECRET_KEY = "x" # prod` or a triple-quoted value over lines. `.env` values with quoting inside them (`'a'\''b-x'`, `abc"def"-x`), when a program prints the decoded value. The first value of a duplicate JSON key. A `.env` value swallowed by an unclosed quote above it. A secret file outside the working project, such as a Read of `../other/.env`. -- **Files that cannot be parsed.** By default a BOM or a comment in JSON, or a Latin-1 or UTF-16 `.env`, skips the file with only a line on stderr. Neither the model nor the user sees more. -- **A tool that fails. This is the largest limit for values in the manifest.** Claude Code sends a failed tool's text through `PostToolUseFailure`, whose hooks can only add a note. That includes a Bash command with a non-zero exit code, whose error text holds the command's output, and an MCP error result. `cat .env; false` reaches the model unredacted, and so does a failing `npm test` that prints its environment, `curl -v -f` with a token header on a 500, or any failing `set -x` script. Fermata does not hook this event and cannot rewrite it. Only a `[policy.bash] deny` pattern stops such a command, and only for the spelling it names: a deny on `cat .env` stops `cat .env; false` but not `cat ./.env; false`, `env; false` or `grep -r TOKEN .; false`. `[policy.read]` and `.botignore` apply to the Read tool, not to what a command prints. -- **Monitor's output.** Each line of a Monitor's command goes to the model as an event, and PostToolUse only sees `{taskId, timeoutMs}`. `tail -f server.log` passes logged tokens straight through. `[policy.bash]` applies to Monitor's and PowerShell's commands, with the same spelling limit. A WebSocket Monitor (`ws`, no `command`) has no rule at all, and its frames reach the model; the hook answers `{}` quietly. -- **A changed file's attachment.** After a Read, a file that changes on disk comes back to the model as an attachment with a snippet, which no tool call and no hook handles. Read `.env`, rotate the token, and the next turn carries the new value. `@`-mentions likely take the same route; that has not been traced. -- **A value split across strings.** Each string is scanned on its own. A value divided between `stdout` and `stderr`, between two MCP content blocks, or across the lines of a diff (a multi-line value in `structuredPatch`) does not match. -- **An encoded or altered value.** Base64, URL encoding, a reversed string or a value cut short does not match. Spellings the value has in its own file are known: see [Spellings](#spellings). See the [threat model](threat-model.md). -- **Numbers and booleans in the output.** Only strings are masked. A secret number that a tool returns as a JSON number passes, as text it is masked. In a JSON, TOML or YAML secret file booleans are not treated as secrets, and neither is a number under 6 characters: see [Spellings](#spellings). In a `.env` they are: see the next item. -- **Ordinary words get masked.** A `.env` value keeps the general minimum of 4 characters, whatever it holds. With `AUTH_ENABLED=true` and `TOKEN_TTL=3600` every `true` and `3600` in every output becomes a mask, and `*AUTH*` also matches `AUTHOR`. An agent that reads `enabled: *****` from a source file and writes the file back puts the mask into the source. -- **Binary data.** `base64` in a built-in's output, `data` of 64 or more base64 characters beside `type: image`, `audio` or `base64` in a content block at the top of a result, and Bash's image `stdout` stay as they are. A mask there would break the image and the next API request, and a short value can match inside base64 by chance. -- **Undeclared secrets.** The heuristic scanner warns beside the output, and leaves the match in place. +- **A tool that fails. This is the largest limit for values in the manifest.** Claude Code sends a failed tool's text through `PostToolUseFailure`, whose hooks can only add a note. That includes a Bash command with a non-zero exit code, whose error text holds the command's output, and an MCP error result. `cat .env; false` reaches the model unredacted, and so does a failing `npm test` that prints its environment, `curl -v -f` with a token header on a 500, or any failing `set -x` script. This is from Claude Code's documentation and bundle; fermata does not hook the event (test: the event is no hook event here). Only a rule stops such a command, and only for what names the file. With `.env` in `.botignore` or `[policy.read]`, `cat .env; false`, `cat ./.env; false` and `source .env; false` are denied, while `env; false`, `grep -r TOKEN .; false`, `printenv; false` and a failing `npm test` pass. On the default configuration a parseable `.env` is not stopped at all (test). +- **Commands are checked only for the files they name.** A variable or substitution that builds the name, a script that opens the file, a printing verb that is not on the list (`python -c`, `dd`, `perl`), `cd ../other && cat .env`, and a project's rule meeting a command run from another project pass (tests). See Layer 3. +- **Secret files that cannot be masked, reached by a route that does not name them.** `.p12`, `.pfx`, `.netrc`, `.htpasswd` and a text `.key` are stopped when a Read names them, but `grep -r TOKEN .`, `ls -R` and `tar cf x.tar .` pass, and so does a printing command off the verb list (test). The read gate stands in a PreToolUse hook only: without PreToolUse wired, a Read of such a file reaches the model, and PostToolUse has nothing to mask in it (test). +- **A template that holds a literal value.** Text with `{{` or `{%` that fails to parse passes a Read as a template, with a note that the file was skipped. A literal value in it reaches the model (test). +- **Files that cannot be parsed, reached by a route that does not name them.** A UTF-16 or Latin-1 `.env`, and JSON with comments, are stopped on a Read but their values are not masked in the output of other commands (test). A UTF-8 byte order mark is read, and does not count here. +- **A secret file outside the working project.** Values in `../other/.env` are not in the manifest, and a Read, a `cat ../other/.env` and `cd ../other && cat .env` pass (test). +- **Values that never enter the manifest.** + - A key the key filter does not match, in a parsed file (test); a `.tfvars` heredoc (test); a comment in a TOML or YAML secret file (test). + - The first value of a duplicate JSON key (test). + - A `.env` value inside a quoted value that spans several lines, when a program prints it alone: with `API_TOKEN="abc` over a line `DB_PASSWORD=fake-pass` and a closing quote on a later line, `echo $DB_PASSWORD` prints the second value, which has no entry of its own (test). + - Python triple quotes, on one line or over several (test), and shell-quoted spellings such as `'a'\''b-x` and `abc"def"-x`, when a program prints the decoded value (test). + - A number under 6 characters (test), and a secret number that an MCP tool returns as a JSON number (test). + - A secret equal to a plain setting word (`true`, `3600`, a duration): it makes no entry. Values equal to a schema's fixed enum word are not masked in that field (test). +- **A short password's word is masked everywhere.** `DB_PASSWORD=postgres` masks `postgres` in every output, and an Edit that names such a line in source can fail (test). +- **Short lines of a multi-line value.** A line of fewer than 8 characters of a multi-line value passes when printed alone, by a grep or a line range (test). +- **Monitor's output.** Each line of a Monitor's command goes to the model as an event, and PostToolUse only sees `{taskId, timeoutMs}`. `tail -f server.log` passes logged tokens straight through (Claude Code's documentation). `[policy.bash]` and the path rules apply to Monitor's and PowerShell's commands, with the limits above. A WebSocket Monitor (`ws`, no `command`) has no rule and no output: the hook leaves it alone. +- **A changed file's attachment.** After a Read, a file that changes on disk comes back to the model as an attachment with a snippet, which no tool call and no hook handles. Read `.env`, rotate the token, and the next turn carries the new value (Claude Code's bundle). `@`-mentions likely take the same route; that has not been traced. +- **A hook that times out lets the output through** (Claude Code's documentation). See Speed above. +- **A value split across strings, or encoded.** Each string is scanned on its own. A value divided between `stdout` and `stderr`, between two MCP content blocks, or across the lines of a diff does not match. Base64, URL encoding, a reversed string or a value cut short does not match (test). Spellings the value has in its own file are known: see [Spellings](#spellings). See the [threat model](threat-model.md). +- **Binary data.** `base64` in a built-in's output, `data` of 64 or more base64 characters beside `type: image`, `audio` or `base64` in a content block at the top of a result, and Bash's image `stdout` stay as they are (test). A mask there would break the image and the next API request, and a short value can match inside base64 by chance. +- **Undeclared secrets.** The heuristic scanner warns beside the output and leaves the match in place (test). +- **The write guard is narrow.** A shell command that writes a mask (`sed -i`, `echo '*****' > f`) is not checked (test); with `style = "absent"` there is nothing to count (test); a real run of exactly five asterisks in a Write is stopped as if it were a mask (test). +- **Artifact, Workflow and a later Claude Code's enums.** A secret equal to a schema's fixed word stays (test); a later release's new enums are not known (Claude Code's bundle). - **A run outside a project.** With no `.botsecrets` or `.botignore` above the working directory, there is nothing to load and the output passes. ### Spellings @@ -99,9 +115,11 @@ A value has one manifest entry per spelling, so that a file read and a program's - 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 or a `.env` value keeps the general minimum of 4. +- 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. -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. +**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 under 6 characters (`3600`, `0.5`) or a duration (`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 limits. **Places a mask cannot go.** Claude Code validates a replacement for a built-in tool and, if it fails, uses the original output. So: @@ -115,7 +133,7 @@ Overlapping matches become one mask, named after the longest. A multi-line value **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. If it writes what it read back to a file, it writes the mask over the real value, and an Edit whose `old_string` holds the mask fails. Guard secret files with `[policy.write]`. +**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 diff --git a/docs/threat-model.md b/docs/threat-model.md index f245398..2bae582 100644 --- a/docs/threat-model.md +++ b/docs/threat-model.md @@ -37,11 +37,11 @@ The levels below are organised by how the agent names the path it is about to ac ### L0: Direct path arguments -The agent calls a path-typed tool (Read, Write, Edit) with an explicit file path. +The agent calls a path-typed tool (Read, Write, Edit, MultiEdit, or Grep with a `path`) with an explicit file path. > `Read({"file_path": "/home/user/.env"})` -- `.botignore` matches -- deny. -Both `.botignore` (deepest directory wins, negation patterns work as in git) and `.botsecrets [policy]` rules are evaluated against the path. This is the only level the hook checks. A `.botignore` directory pattern such as `vendor/` does not match the files below it, unlike in git; `vendor/**` does. A relative path never matches `.botignore`. +Both `.botignore` (deepest directory wins, negation patterns work as in git) and `.botsecrets [policy]` rules are evaluated against the path, relative or absolute, and against the path as the file system resolves it. A `.botignore` directory pattern such as `vendor/` matches the files below it, as in git. A Read of a listed secret file that fermata cannot mask (no parser, a secret as a whole, unparseable) is stopped too, whatever the rules say, and a Write or Edit that adds a mask to a file is stopped. ### L1: Absolute paths inside Bash commands @@ -49,7 +49,7 @@ The agent runs a shell command that mentions a full path -- one containing a dir > `cat /home/user/.env`, `type C:\Users\me\secret.toml` -**Not checked.** The library has a path extraction engine (`core::extract`) that recognises these as high-confidence candidates, and the hook does not call it. A Bash command only meets `[policy.bash]`, whose patterns match the text of the command. +**Checked, by the verb.** The command is split into segments, and a word that holds a separator or names an existing file is checked against the path rules (and, for a printing verb such as `cat`, the read gate). A metadata verb (`ls`, `echo`, `git commit`) is not checked. Only the session's own project's rules apply to a command: a rule in another project, or a secret file in no project, does not. ### L2: Bare filenames resolvable in the working directory @@ -57,7 +57,7 @@ The agent names a file without any path separator, relying on the shell's workin > `cat .env`, `cat README.md` -**Not checked**, for the same reason as L1. +**Checked**, as in L1, when the word names an existing file in the session's working directory. `cd ../other && cat .env` is not: the `cd` is not followed. ### L3: Static wildcards in commands @@ -65,7 +65,7 @@ The agent uses shell glob patterns in a command that could expand to match sensi > `cat .env*`, `grep SECRET *.toml`, `find . -name '*.pem'` -**Not checked**, for the same reason as L1. +**Checked.** A glob is matched against the entries of its one directory, and a dotfile matches only when the glob starts with `.`, as in a shell: `cat .env*` is checked and `cat *` does not reach `.env`. `find` is a verb whose `-name` pattern is read as a glob. --- @@ -75,7 +75,7 @@ The agent uses shell glob patterns in a command that could expand to match sensi Variable expansion (`cat $SECRET_FILE`), command substitution (`cat $(ls .env*)`), tool composition (`xargs cat < file_list`), and pipelines that route content through intermediate steps. -A real `bash` parser would handle the syntax, but cannot resolve runtime values. Fermata sees the command string, not the expanded result, and the hook does not look for this syntax. +A real `bash` parser would handle the syntax, but cannot resolve runtime values. Fermata sees the command string, not the expanded result. A variable assigned in the same command with the file name in it (`F=.env; cat $F`) is seen, since the name is in the text; one built apart from the name (`cat $(printf '.e%s' nv)`), `"$(cat .env)"` and a script that opens the file are not. Neither is a printing verb off the list (`python -c`, `dd`, `perl`). ### L5: Derived or out-of-band names @@ -83,7 +83,7 @@ The agent computes a path from sources fermata never sees: its own reasoning, an > The agent reads a config file, learns about `/etc/app/signing.key`, then reads it in a subsequent call. -**Important:** most derived-name scenarios collapse back to L0 at the moment of the dangerous call. If the second read is a direct path-typed tool call, a `.botignore` rule that matches stops it. If it is a shell command, nothing checks it. +**Important:** most derived-name scenarios collapse back to L0 at the moment of the dangerous call. If the second read is a direct path-typed tool call, a `.botignore` rule that matches stops it. If it is a shell command, it is checked only for the files it names. ### L6: Application-protocol exfiltration -- out of scope by design @@ -100,11 +100,11 @@ This is the network-firewall analogy: **you cannot block exfiltration over an al | Level | Description | Detection | Confidence | |-------|-------------|-----------|------------| | Secret masking | Known-value masking + heuristic warning | Aho-Corasick + regex | Only for values in the manifest, whole in a string of a successful tool. See [Known limits](security-model.md#known-limits) | -| L0 | Direct path argument | Policy check on Read, Write, Edit | Only if a rule matches | -| L1 | Absolute path in Bash | None in the hook | None | -| L2 | Bare filename in CWD | None in the hook | None | -| L3 | Wildcards in commands | None in the hook | None | -| L4 | Shell indirection | None in the hook | None | +| L0 | Direct path argument | Policy check on Read, Write, Edit, Grep with a path; read gate; write guard | Only if a rule matches, a listed file cannot be masked, or a Write adds a mask | +| L1 | Absolute path in Bash | Path rules and read gate, by the verb | Only for a path a rule or the gate covers, and a verb on the lists | +| L2 | Bare filename in CWD | The same, in the session's directory | The same; `cd` elsewhere is not followed | +| L3 | Wildcards in commands | The same, with the glob matched in its directory | The same | +| L4 | Shell indirection | None | None for a name built apart from the file | | L5 | Derived names | L0 if the final call is a path tool | Depends on final call | | L6 | Protocol exfiltration | Out of scope | N/A | @@ -119,7 +119,8 @@ Do not use fermata on a real project. If you try it anyway, this is what it atte - **Masking known secrets.** Values in the manifest are masked in the strings of successful tools' output. A failed tool's error text is out of reach, and many values never enter the manifest: see [Known limits](security-model.md#known-limits). - **Heuristic warnings.** Undeclared secrets matching common formats (AWS keys, tokens, connection strings) get a warning beside the output, and stay in it. - **Command rules.** Shell patterns you list (`rm -rf /`, `curl * | sh`) stop a command whose text matches. -- **Path rules.** `.botignore` and `.botsecrets [policy]` stop the Read, Write and Edit tools at L0. +- **Path rules.** `.botignore` and `.botsecrets [policy]` stop the Read, Write and Edit tools at L0, and commands that name a matching file at L1 to L3. +- **The read gate and the write guard.** A Read of a listed file that cannot be masked is stopped, and so is a Write that adds a mask. ### What real secrets would need instead @@ -129,6 +130,6 @@ Do not use fermata on a real project. If you try it anyway, this is what it atte ### Design constraints worth knowing -- **Latency.** Fermata fires on every tool call and parses the secret files each time, which is slow for large files: see [Speed](security-model.md#design-principles). +- **Latency.** Fermata fires on every tool call and parses the secret files each time, which grows with the size of the files: see [Speed](security-model.md#design-principles). - **No writes.** The hook reads its config and the secret files, walks the project for them, and writes no files. - **False deny vs false allow.** A false deny breaks the agent's workflow and is noticed immediately. A false allow may go undetected. diff --git a/tests/docs_toml_examples.rs b/tests/docs_toml_examples.rs new file mode 100644 index 0000000..d4c1da5 --- /dev/null +++ b/tests/docs_toml_examples.rs @@ -0,0 +1,41 @@ +//! Every fenced TOML example of `docs/configuration.md` loads as a `.botsecrets`, with +//! unknown fields refused. A doc that shows a setting the code dropped fails here. + +use dirigent_fermata::core::secrets::config::SecretsConfig; + +fn toml_examples(doc: &str) -> Vec { + let mut blocks = Vec::new(); + let mut current: Option = None; + for line in doc.lines() { + match (&mut current, line.trim_end()) { + (None, "```toml") => current = Some(String::new()), + (Some(_), "```") => blocks.extend(current.take()), + (Some(block), text) => { + block.push_str(text); + block.push('\n'); + } + _ => {} + } + } + blocks +} + +#[test] +fn every_toml_example_of_configuration_md_loads() { + let doc = include_str!("../docs/configuration.md"); + let examples = toml_examples(doc); + assert!(examples.len() >= 10, "found only {} TOML examples", examples.len()); + for example in &examples { + if let Err(error) = SecretsConfig::from_toml(example) { + panic!("this example of configuration.md does not load: {error}\n{example}"); + } + } +} + +/// The check has teeth: a removed setting is refused. +#[test] +fn a_removed_setting_does_not_load() { + for text in ["[enforcement]\nmode = \"strict\"\n", "[enforcement]\non_parse_error = \"mask-entire-file\"\n"] { + assert!(SecretsConfig::from_toml(text).is_err(), "{text}"); + } +} diff --git a/tests/known_limits.rs b/tests/known_limits.rs index 5f93171..a5da772 100644 --- a/tests/known_limits.rs +++ b/tests/known_limits.rs @@ -170,6 +170,16 @@ fn a_value_after_an_unclosed_quote_is_masked_in_every_spelling_tried() { } } +/// A closed quote that spans lines swallows the assignment inside it: the file's parser +/// reads one value, so `DB_PASSWORD` has no entry of its own, and a program that prints it +/// alone shows it. (The value stays masked while it appears inside the whole quoted text.) +#[test] +fn a_value_inside_a_quoted_value_that_spans_lines_is_not_masked_when_printed_alone() { + let p = project(&env_file("API_TOKEN=\"abc\nDB_PASSWORD=fake-swallowed-pass\nOTHER=x\"\n")); + let out = p.after_bash("fake-swallowed-pass"); + assert!(out.contains("fake-swallowed-pass"), "{out}"); +} + // --------------------------------------------------------------------------- // Files fermata does not see, and values it cannot tell // ---------------------------------------------------------------------------