diff --git a/CLAUDE.md b/CLAUDE.md index ccc8ad9..738bb4e 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -34,7 +34,7 @@ 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"`.** 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. +- **Hooks fail open, except under `on_parse_error = "deny"`.** A broken config layer (a parse error or an unknown field) switches only that layer's rules off, with a note beside text output. With `deny` in effect, PostToolUse answers with a refusal naming the file when the config or a secret file cannot be loaded, and PreToolUse answers `deny` when the config or the rules cannot be loaded or applied. A malformed hook payload and a missing working directory stay open: no payload means nothing to render, no directory means no setting to read. A glob in `[files]` or `[policy]` that does not compile costs only that pattern while open (`SecretsConfig::bad_patterns`, a note by name); a `[files]` list with none left leaves the built-in list; under `deny` the manifest and PreToolUse refuse, so `dirigent_server`'s filter, which forces `deny`, stays strict. `fermata check` exits 2 on a broken config or a bad glob. - **A config that cannot be read: the setting is unknown.** `SecretsConfig::denies_on_failure` reads the raw bytes of every layer: an uncommented line setting `deny` counts, broken layer or not; without one the hook stays open as for any default root; a layer whose bytes cannot be read says nothing and does not count, so an unreadable global config cannot stop every project on the machine. - **Replacing output depends on the harness.** Claude Code ignores an `updatedToolOutput` that does not match a built-in tool's output schema and then uses the original. `harness/claude.rs` therefore walks `tool_response` in any shape and masks strings in place. `SCHEMA_VALUES` lists the enum and literal values of the 87 `outputSchema` getters in Claude Code v2.1.314, as far as they have values to list (re-read it when a release adds tools): those exact values stay. Not resolved, because they exist only at run time: Workflow's `RUN_OP_STATUS` and `runOpOutputFields` and Artifact's `handlers` arms, all flag-gated, and Artifact's `reason`. Artifact's pattern fields and that `reason` are `ARTIFACT_PATTERN_FIELDS`: a secret there refuses. A secret elsewhere under those names or in a built-in's object key cannot take a mask, so `OutputEdit::Unmaskable` refuses the output under every setting. Refusals: Bash, Read and Artifact answer a minimal schema-valid output, other built-ins keep their shape, MCP gets the plain text. `tests/cli_hook_redaction.rs` checks shapes against a copy of those schemas, and `TOOL_ENUMS` there lists each tool's enums so that dropping a value fails a test; nothing here runs Claude Code. - **Read gate and write guard.** `SecretFileSet` and `unmaskable_reason` decide which listed files cannot be masked (no parser, a secret as a whole, unparseable, no value to read, tfstate by position); a Read, a Grep with a `path` and a printing command naming one is stopped under every `on_parse_error` unless `on_unparsed_read = "allow"`. `count_masks` backs the write guard: a Write, Edit or MultiEdit that adds a mask is stopped unless `on_mask_write = "allow"`. Commands meet only the session's own project rules, by verb class (`docs/security-model.md`, Layer 3). diff --git a/README.md b/README.md index 6028a0d..122d37d 100644 --- a/README.md +++ b/README.md @@ -10,17 +10,26 @@ 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. - **`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. +- **Commands are checked only for the files they name, in the forms the check reads.** These pass, with `.env` under a rule: + - a substitution that builds the name (`cat $(printf '.e%s' nv)`), and `echo "$(cat .env)"`, since a substitution inside double quotes is one word + - a script that opens the file, a printing verb that is not on the list (`python -c`, `dd`, `perl`), and a heredoc fed to a shell (`bash <... |------|---------| | 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, a config layer or a `[files]` pattern that does not load, etc.) The message names the file and line. | +| 2 | Internal error (could not load policy, bad arguments, a config layer that does not load, or a `[files]` or `[policy]` pattern that does not compile, 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. @@ -79,7 +79,7 @@ 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, 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. +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 glob that does not compile costs only that pattern, with a note naming it. 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"` (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). diff --git a/docs/configuration.md b/docs/configuration.md index b835afb..e7943f3 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -76,7 +76,7 @@ key-value pairs, and uses the values for exact-match redaction. id_rsa, id_ed25519, id_ecdsa, Secrets.toml, Secrets.*.toml, terraform.tfvars, *.auto.tfvars, terraform.tfstate, *.tfstate, *.tfstate.backup, .docker/config.json, config/master.key, -config/credentials/*.key, .aws/credentials, .netrc, .htpasswd, +config/credentials/*.key, .aws/credentials, credentials, .netrc, .htpasswd, service-account.json, service-account-key.json ``` @@ -87,14 +87,14 @@ Fermata chooses a parser from the file's name: | `.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 | +| `*.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 its armor labels are only certificates and public keys (other text in the file is not looked at). 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. +Setting `files.patterns` in a layer **replaces** the defaults entirely. A glob here or in `[policy]` that does not compile costs only that pattern, with a note naming it beside text output, and a list with no usable pattern leaves the built-in list. Under `on_parse_error = "deny"` it refuses instead, and `fermata check` exits 2. ```toml [files] @@ -342,9 +342,12 @@ 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. +a word that names an existing file, an existing path with a separator, a path with `$`, +`*` or `?` in it, or a redirect's target counts; `$(...)`, scripts and a verb off the +list that opens the file itself are not seen. The argument of `bash -c` and `eval` is +read as a command line. `[policy.write]` is not applied to commands. The forms that +pass, and the harmless commands a rule stops, are in +[Layer 3](security-model.md#layer-3-access-control-botignore--botsecrets-policy). - Blank lines and lines starting with `#` are ignored. - `*` matches anything except `/`. diff --git a/docs/security-model.md b/docs/security-model.md index 62733ef..c5758da 100644 --- a/docs/security-model.md +++ b/docs/security-model.md @@ -46,14 +46,24 @@ Its false-positive rate is higher than Layer 1's, which is why it warns: masking 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. -- **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. +- **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 redirect's target is checked. So `composer require vendor/package` and `git checkout build/fix` name nothing under a rule on `vendor/` or `build/`. The argument of `bash -c`, `sh -c`, `zsh -c` and `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. 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. 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. +**Limitations of the command check.** It sees the command's text, not what the shell makes of it. These pass: + +- A substitution that builds the file name (`cat $(printf '.e%s' nv)`), and `echo "$(cat .env)"`: a substitution inside double quotes is one word. +- A script that opens the file (`sh run.sh`, `python -c "print(open('.env').read())"`), a heredoc fed to a shell (`bash < `cat /home/user/.env`, `type C:\Users\me\secret.toml` -**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. +**Checked, by the verb.** The command is split into segments, and a word that names an existing file, an existing path with a separator or a path with `$`, `*` or `?` in it 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 diff --git a/tests/cli_hook_fail_closed.rs b/tests/cli_hook_fail_closed.rs index 742c47c..f50c546 100644 --- a/tests/cli_hook_fail_closed.rs +++ b/tests/cli_hook_fail_closed.rs @@ -405,10 +405,15 @@ fn the_gate_refuses_when_rules_cannot_be_loaded_under_deny() { assert!(deny_reason(&p.pre_read("safe.txt")).contains("rules")); assert!(deny_reason(&p.pre_bash()).contains("rules")); - // The control: the same rules with no `deny` stay open. - let p = project(&[(".botsecrets", bad_rules), ("safe.txt", "")]); + // The same rules with no `deny` stay open for what no rule names, and the bad pattern + // costs only itself: `.botignore` and the read gate still stand, and a note names it. + let p = project(&[(".botsecrets", bad_rules), (".botignore", "ignored.txt\n"), ("ignored.txt", ""), ("id_rsa", "fake key text\n"), ("safe.txt", "")]); assert_silent(&p.pre_read("safe.txt")); assert_silent(&p.pre_bash()); + assert!(deny_reason(&p.pre_read("ignored.txt")).contains(".botignore")); + assert!(deny_reason(&p.pre_read("id_rsa")).contains("id_rsa")); + let (out, _) = p.post(json!("clean")); + assert!(out["hookSpecificOutput"]["additionalContext"].as_str().unwrap().contains("a["), "{out}"); } #[test]