diff --git a/.claude-plugin/marketplace.json b/.claude-plugin/marketplace.json index 96cc110..6f529de 100644 --- a/.claude-plugin/marketplace.json +++ b/.claude-plugin/marketplace.json @@ -11,7 +11,7 @@ { "name": "datafog", "source": "./", - "description": "Replaces personal data and credentials with reversible markers before the model sees them. Development build (0.2.0-dev)." + "description": "Replaces personal data and credentials with reversible markers before the model sees them." } ] } diff --git a/.claude-plugin/plugin.json b/.claude-plugin/plugin.json index 8f4a6ad..8018264 100644 --- a/.claude-plugin/plugin.json +++ b/.claude-plugin/plugin.json @@ -1,8 +1,8 @@ { "name": "datafog", "displayName": "DataFog", - "description": "Keeps emails, phone numbers, card and ID numbers, API keys and other credentials out of the model's context: values in files, command output and tool results are replaced by reversible markers before Claude sees them, and swapped back locally when Claude writes. Development build; see the README for what is and is not covered.", - "version": "0.2.0-dev", + "description": "Keeps emails, phone numbers, card and ID numbers, API keys and other credentials out of the model's context: values in files, command output and tool results are replaced by reversible markers before Claude sees them, and swapped back locally when Claude writes. See the README for coverage and platform limits.", + "version": "0.2.0", "author": { "name": "DataFog", "url": "https://datafog.ai" @@ -15,7 +15,7 @@ "keep_vault_on_uninstall": { "type": "boolean", "title": "Keep the vault when the plugin is uninstalled", - "description": "On: the vault (the table that turns markers back into your real values) is stored in your user data folder and survives an uninstall. Off: it is stored in the plugin's data folder, which Claude Code deletes on uninstall; markers left in your files can then never be restored.", + "description": "On: the encrypted vault (the table that turns markers back into your real values) is stored in your user data folder and survives an uninstall, and its key stays in your key store. Off: it is stored in the plugin's data folder, which Claude Code deletes on uninstall; markers left in your files can then never be restored.", "default": true }, "unscannable_file_policy": { diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 460a200..30fc304 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -21,12 +21,14 @@ jobs: with: python-version: ${{ matrix.python }} - - name: Install zsh (Linux) + # zsh for the shell tests; a D-Bus session, GNOME Keyring and secret-tool so that + # tests/test_keystore.py can run the key-store mode against a private Secret Service. + - name: Install zsh and a Secret Service (Linux) if: runner.os == 'Linux' - run: sudo apt-get update && sudo apt-get install -y zsh + run: sudo apt-get update && sudo apt-get install -y zsh dbus gnome-keyring libsecret-tools - - name: Install the engine's one dependency and the test tools - run: python -m pip install "datafog-core>=1.4.0,<1.5" "pytest>=8" "ruff>=0.6" "mypy>=1.10" + - name: Install the engine's two dependencies and the test tools + run: python -m pip install "datafog-core>=1.7.0,<1.8" "datafog-fogvault>=1.7.0,<1.8" "pytest>=8" "ruff>=0.6" "mypy>=1.10" - name: Manifests and hook config parse run: | diff --git a/.mcp.json b/.mcp.json index 1877d78..227866c 100644 --- a/.mcp.json +++ b/.mcp.json @@ -6,7 +6,8 @@ "env": { "CLAUDE_PROJECT_DIR": "${CLAUDE_PROJECT_DIR}", "DATAFOG_DATA_DIR": "${DATAFOG_DATA_DIR:-}", - "DATAFOG_VAULT_DIR": "${DATAFOG_VAULT_DIR:-}" + "DATAFOG_VAULT_DIR": "${DATAFOG_VAULT_DIR:-}", + "DATAFOG_VAULT_KEY": "${DATAFOG_VAULT_KEY:-}" } } } diff --git a/README.md b/README.md index bbcd7ba..5842f5b 100644 --- a/README.md +++ b/README.md @@ -1,36 +1,69 @@ # DataFog for Claude Code -Keeps personal data and credentials out of the model's context in Claude Code during -normal work. - -**What this is for, and what it is not.** DataFog protects against *accidental* exposure: -values that would otherwise reach the model and the model provider simply because Claude -read a file, ran a command or called a tool while doing its job. It is **not a sandbox -against a model that is actively trying to unmask values.** A model that has been -manipulated (for example by a prompt injection in a file it read) and is allowed to run -commands can recover values: by transforming them so the detector no longer recognises -them, by cutting them into pieces, or by going around the output filter with operating -system facilities. If you need protection against that, you need an OS-level sandbox and -strict permission rules; this plugin does not replace them. - -Before Claude sees the content of a file, the output of a command or the result of a -tool, DataFog replaces the values it detects with reversible markers such as -`[[EMAIL_7KQ4ZM]]`. When Claude writes a marker back to a file or a command, the -marker is swapped for the real value on your machine. The table that maps markers to -values (the vault) never leaves your machine and is never shown to the model. - -**Status: 0.2.0-dev. Not released.** The design rests on a 31-run spike against -Claude Code 2.1.299, and the engine has an automated test suite, but this build has -not yet been run in a live Claude Code session. [What is not verified yet](#not-verified-yet) -lists every such point. Read [Known gaps](#known-gaps) before you rely on it. +DataFog replaces detected personal data and credentials with markers before Claude sees +files and command output. Claude can work with `[[EMAIL_7KQ4ZM]]` instead of your email; +when it writes a marker back, the plugin restores the value on your Mac or Linux machine. +Detection is local. The encrypted vault stays on your machine, with its key in the macOS +Keychain or Linux Secret Service by default. + +It protects against accidental exposure during everyday coding. It does not stop a +malicious or manipulated agent from recovering data through commands, encodings or other +operating-system access. Use a sandbox and permission rules for that boundary. + +| Coverage group | What happens | Main limit | +| :- | :- | :- | +| Checked before Claude sees it | Readable text files, Bash stdout/stderr, submitted prompts and `@file` mentions are checked; detected values become markers, or the request is blocked. | Only recognised values are covered. Prompts cannot be rewritten automatically. | +| Filtered after a tool returns | Grep, web tools, MCP tools and subagent results have detected values replaced. The vault and detector are checked before the call. | A crash or timeout after that check can leave raw output visible to Claude. | +| Outside that protection | Free-text names, unlabelled addresses, unknown secret formats, images/PDFs and data sent directly by a command are not reliably protected. | Write/Edit and Grep/Glob marker restoration put real values in Claude Code's local transcript. | + +The default detector covers email, phone, SSN, card numbers and selected credential and +labelled account formats. **People's names are not detected. Street addresses are off by +default and require a label when enabled.** This is not a complete secret scanner. + +**Supported platforms:** macOS 11+ on Apple Silicon; Linux x86_64 with glibc 2.38+. +Linux needs a working Secret Service, or an explicit, weaker file-key setting. Intel Macs, +Linux ARM/musl/older glibc and Windows are unsupported. Unsupported machines and unavailable +key stores block tool calls. See [Supported machines](#supported-machines) for details. + +**Version 0.2.0.** See [Known gaps](#known-gaps) and +[Not verified yet](#not-verified-yet) before relying on it. ## Requirements - Claude Code **2.1.295 or later** (the plugin depends on `onFailure: "block"` for hooks). -- macOS or Linux, with `sh` and `bash` or `zsh`. Windows is not supported in this version. +- **A supported machine** (see [Supported machines](#supported-machines)): macOS on Apple + Silicon, or Linux on x86_64 with glibc 2.38 or later, each with a key store the plugin can + use. Anywhere else the plugin does not run and blocks tool calls; there is no reduced mode. +- `sh` and `bash` or `zsh`. - `uv`, or Python 3.10 or later with `pip`, and access to PyPI on first start. The plugin - builds a private Python environment in its data directory and installs one dependency, - `datafog-core>=1.4.0,<1.5`. Detection runs locally; nothing is sent anywhere. + builds a private Python environment in its data directory and installs two packages of + the DataFog core project: `datafog-core>=1.7.0,<1.8` (the detector) and + `datafog-fogvault>=1.7.0,<1.8` (the encrypted vault). Detection and storage are local; + nothing is sent anywhere. + +### Supported machines + +| Machine | Supported | Vault key is kept in | +| :- | :- | :- | +| macOS 11 or later on Apple Silicon (arm64) | yes | the login Keychain | +| Linux x86_64, glibc 2.38 or later (Ubuntu 24.04, Debian 13, Fedora 39 and later), desktop session | yes | the Secret Service (GNOME Keyring, KWallet) | +| The same Linux without a Secret Service (server, container, SSH session, CI) | only with `vault_key: file`, which is weaker; see [The vault](#the-vault) | a file beside the vault | +| macOS on Intel | **no** | | +| Linux on ARM, or with an older glibc (Ubuntu 22.04, Debian 12, RHEL 9, Amazon Linux 2023), or with musl (Alpine) | **no** | | +| Windows | **no** (the vault library exists for Windows x64; the rest of the plugin does not yet) | | + +The limit comes from the vault: `datafog-fogvault` 1.7.0 is published as compiled packages +for exactly `macosx_11_0_arm64`, `manylinux_2_38_x86_64` and `win_amd64`, and the plugin has +no other place to keep values. **On an unsupported machine it fails closed.** The installer, +the session start line, every hook, `/datafog:status` and `/datafog:doctor` give the same +message, and tool calls are blocked until you disable or uninstall the plugin: + +``` +DataFog does not support this machine. It needs macOS on Apple Silicon, or Linux on x86_64 with glibc 2.38 or later. Nothing is protected and tool calls are blocked; disable or uninstall the plugin to work without it. +``` + +The same holds when the key store cannot be used (locked, missing, access refused): the +message names the key store, and nothing runs unprotected. ## Install @@ -42,9 +75,13 @@ Start a new session. The first start installs the private environment (a few sec and prints one status line, for example: ``` -DataFog guard: on. Vault: user data folder (kept on uninstall), not encrypted at rest. Bash output: filtered. Markers in Bash commands: ask. Detecting: EMAIL, PHONE, ... +DataFog guard: on. Vault: user data folder (kept on uninstall), encrypted, key in the system key store. Bash output: filtered. Markers in Bash commands: ask. Detecting: EMAIL, PHONE, ... ``` +The first start also creates the vault and stores its key in your key store. On macOS this +adds one entry to the login Keychain (service `DataFog.ApplicationVault.v1`); macOS may ask +you to allow access, see [Not verified yet](#not-verified-yet). + If the environment cannot be installed, the status line says exactly which command to run, and every tool call is blocked until it is fixed. The plugin does not run unprotected in silence. @@ -61,18 +98,28 @@ Off by default because they are noisy in code, and can be turned on: `DATE`, Once a value is in the vault it is also recognised wherever it appears again, even where the scanner alone would miss it (for example an account number without its label). +It is matched as a whole value, whatever its case and however its parts are spaced, and +not inside a longer word or number (`000123456789` is not found inside `x000123456789y`). + +An e-mail address is replaced without the text joined in front of it: in +`user=ada&email=ada@example.com`, `1042|Ada|ada@example.com|active` or a URL query string, +the marker stands for the address only (core 1.4 took part of the surrounding text into +the value). Digits written directly onto an address with no separator +(`12345ada@example.com`) are still part of the value. **Not detected:** - **Names of people.** Free-text names are not detected at all. - **Addresses without a label**, and anything else that has no recognisable format. -- **Many credential formats.** `API_KEY` covers the formats core 1.4 knows (for example +- **Many credential formats.** `API_KEY` covers the formats core 1.7 knows (for example GitHub and Stripe keys). In our checks it did not find AWS access keys, OpenAI project keys, Slack tokens or `password=...` assignments. Do not treat this plugin as a secret scanner. - Routing numbers, NPIs and account numbers need a label next to them (`routing number 021000021`) the first time they are seen. - Anything inside images and PDFs. +- Some e-mail addresses and phone numbers in particular surroundings; see + [Known gaps](#known-gaps) 18 and 19. ## How each path is protected @@ -85,7 +132,7 @@ where the scanner alone would miss it (for example an account number without its | **Bash permissions** | The plugin decides `allow`, `ask` or `deny` from your own Claude Code rules, applied to the command as Claude wrote it. See [Bash permissions](#bash-permissions). | The command does not run. | | **Write**, **Edit**, **NotebookEdit** | Markers in the new content are swapped for real values before the tool runs. The built-in tool needs the real content, so it is handed over in the tool input, and **Claude Code records that input in its transcript.** | The write is blocked. | | **Grep**, **Glob** | Markers in the pattern and path are swapped for real values (handed over in the tool input, so **recorded in Claude Code's transcript**, like Write); Grep output is tokenized after the tool ran. | See next row. | -| **Grep, WebFetch, WebSearch, MCP tools, subagent results, any other tool** | Output is tokenized after the tool ran. Before the tool runs, the plugin checks that the vault opens, the lock works and the detector finds a test value, and refuses the call if not. | If the plugin breaks *between* that check and the result (hard crash, timeout), **the raw output reaches the model.** Claude Code offers no way to prevent this for output that only exists after a tool ran. | +| **Grep, WebFetch, WebSearch, MCP tools, subagent results, any other tool** | Output is tokenized after the tool ran. Before the tool runs, the plugin checks that the vault opens (its lock can be taken, its key is available, it decrypts) and that the detector finds a test value, and refuses the call if not. | If the plugin breaks *between* that check and the result (hard crash, timeout), **the raw output reaches the model.** Claude Code offers no way to prevent this for output that only exists after a tool ran. | | **Your prompt** | Scanned when you submit it. If it holds values, it is not sent; you are shown the same prompt with markers to submit instead. A plugin cannot rewrite a prompt. | The prompt is blocked. | | **`@file` and `@directory` mentions** | Blocked when a mentioned file, or any file in a mentioned directory, holds values or cannot be checked; you are told to ask Claude to read the files instead. Directories are checked up to 200 files, 8 MiB and 4 levels; beyond that the prompt is blocked with the reason. See [settings](#settings-the-plugin-cannot-set-for-you). | The prompt is blocked. | | **Subagents** | The same hooks run for a subagent's tool calls. | As above. | @@ -93,6 +140,15 @@ where the scanner alone would miss it (for example an account number without its Markers sent to WebFetch, WebSearch, subagents and third-party MCP tools are **not** swapped back: that input leaves your machine or goes to another model. +### Names and street addresses + +Adding these is worthwhile: names and ordinary mailing addresses are a large gap in +free-text documents. The decision for this release is to keep the current rule scanner +and make a future local name/address model an explicit opt-in. Name-shaped regular +expressions would also hide code identifiers and ordinary prose; a model needs its own +coverage, false-positive and hook-latency checks before it becomes a default. Enabling +`STREET_ADDRESS` today only adds the labelled formats core already recognises. + ### How Bash commands run Each Bash command runs in its own child shell, started by the filter, in its own session. @@ -117,9 +173,8 @@ Consequences you will notice: - `NO_COLOR=1` and `CLICOLOR=0` are set for commands. Colour codes that still appear are handled (see below), this only reduces noise. - Each command costs about 70 ms extra for the runner, and the PreToolUse hook takes about - 45 ms (10 ms of it inside the engine, the rest is starting Python). Measured on a Linux - container; reading your permission rules and the late swap added about 2 ms to the hook - and nothing measurable to the runner. + 50 ms (most of it is starting Python). Measured on a Linux container; see + [Speed](#speed) for the numbers with the encrypted vault. Values split or hidden by terminal control sequences are still found. Detection also runs on the text with escape sequences and invisible characters removed, and on the text as a @@ -373,8 +428,10 @@ definition is the grammar in [Markers in Bash commands](#markers-in-bash-command 1 and 2, with these differences for commands without markers: the builtins `echo`, `printf`, `true`, `false`, `:`, `pwd`, `test`, `kill`, `wait`, `type`, `which` and `exit` may be used (this says the command can be read with certainty, not that those builtins are harmless: -`test -v` and `printf -v` evaluate an operand under bash, so a wildcard allow rule does not -approve those forms), other programs are not restricted (the short program list applies +`test -v` and `printf -v` can evaluate an operand under bash; numeric `printf` formats, +dynamic format widths and non-numeric `exit` arguments can do so under zsh. These forms +require an exact allow rule when no restrictive rule exists, and force a prompt whenever +a deny, ask or path rule applies (`dontAsk` denies)), other programs are not restricted (the short program list applies to marker restoration only), a descriptor in a redirection is one digit, and `cd`, `pushd` or `popd` is plain only as the single command of a call (`cd sub` is plain; `cd sub && make` is not, because after it relative paths mean something else). Commands longer than 20,000 characters are not plain. @@ -508,11 +565,17 @@ Ways a real value can still reach the model or leave a trace. output before the plugin replaces it. 10. **Claude Code's own records hold real values for file tools, not for Bash.** See [Traces left in Claude Code's records](#traces-left-in-claude-codes-records). -11. **The vault is not encrypted at rest in this version.** It is protected by owner-only - file permissions (directory `0700`, files `0600`). Anyone who can read your files can - read it. The plugin refuses Read, Write, Edit and Grep on the vault directory and Bash - commands that name it; a command that reaches it indirectly is only covered by the - output filter. +11. **The vault is encrypted at rest, and that protects against less than it may sound.** + The file on disk is ciphertext and its key is in your operating system's key store, so + a copy of the file (a backup, a synced folder, a stolen disk image without your login) + reveals no value. It does **not** protect against a program running as you while you + are logged in: such a program can ask the key store for the key the same way the plugin + does, or start the plugin's own Python. The plugin refuses Read, Write, Edit and Grep on + the vault directory and Bash commands that name it; a command that reaches it indirectly + is only covered by the output filter. With `vault_key: file` the key lies beside the + data and a copy of the directory reveals everything. What is **not** encrypted: the + marker index (the markers issued, no values), the number of values, the vault's ids and + revision, and the key that signs restore tickets for Bash commands. 12. **Bash, Read and Edit permission rules that the plugin cannot read are not enforced for Bash commands**, commands that are not simple always ask, and a `Read` deny rule does not stop a command that reads the file without naming it. See [Bash permissions](#bash-permissions). @@ -527,6 +590,25 @@ Ways a real value can still reach the model or leave a trace. 17. **A value restored into a Bash command is visible in the process list** for as long as a program the command started holds it as an argument, and a value that starts with `-` may be read as an option. See [Markers in Bash commands](#markers-in-bash-commands). +18. **KNOWN ISSUE: an e-mail domain can reach the model when a non-ASCII letter touches the + address** ([datafog-core #272](https://github.com/DataFog/datafog-core/issues/272), + present in core 1.5.0 to 1.7.0). A letter or digit outside ASCII written directly against + an address, with no space or punctuation between, is read as part of the address. For a + single address that only makes the marker cover a little more (`連絡先ada@example.com` + becomes one marker). **Between two addresses it leaks:** `alice@example.comとbob@example.net` + is read as one value, `alice@example.comとbob`, and the model sees + `[[EMAIL_…]]@example.net`: the second person's real domain. This happens in text written + without spaces (Japanese, Chinese, Thai, also `…@a.example.orgßname@…`). A space, a + full-width space or punctuation such as `。` or `:` between the letter and the address + avoids it. The plugin does not work around this; it is fixed in core after 1.7.0 and + goes away with the next core release the plugin moves to. +19. **Phone numbers core 1.7 does not report, which core 1.4 did.** They pass to the model + unchanged: a dotted number directly after a digit and a dot (`2.415.555.0134`, read as a + decimal); after a digit and a comma, a number whose only separator is one dot + (`2,415.5550134`); and a number wrapped across a line break (`(415)` at the end of one + line and `555-0134` on the next). A `+` number wrapped across a line break is replaced + only up to the break (`+44 20 7946` / `0958` leaves `0958`). `3.415-555-0134` and CSV + rows such as `2,415-555-0134` are found. Behaviour worth knowing that is not a leak: @@ -538,11 +620,12 @@ Behaviour worth knowing that is not a leak: - **Markers the vault does not know** (wrong label, changed code, from a purged vault) are left exactly as written and reported to Claude as a count. Lower-cased markers are accepted, as core defines them. One unknown marker never fails a whole write. -- **Limits.** Core allows 20,000 values in a vault, and its known-value matching stops - working when the stored values pass roughly 256 KiB in total, which can come first. - At either limit the plugin stops (new values cannot be protected) and says so; the - remedy today is `/datafog:purge`. `recall_required: false` trades the second limit - for detector-only matching. +- **Limits.** Core allows 20,000 values in a vault, and about 100,000 changes to it (each + batch of *new* values is one change; values the vault already holds cost none). At the + limit the plugin stops (new values cannot be protected) and says so; values it already + holds keep working. The remedy today is `/datafog:purge`. +- **Each process that replaces values holds the vault's values in its memory** while it + runs (to recognise them), as core's own code did before. ## Traces left in Claude Code's records @@ -596,6 +679,21 @@ Design decisions that were considered and settled, so they are not reopened by a be checked asks.** Denying everything that might touch a covered path (every glob, every directory) was rejected: it would make such rules unusable. Allowing it was rejected too: it would let a rule be bypassed with `cat s*.env`. +- **One encrypted vault, no unencrypted fallback.** Values are kept only in core's + application vault. A machine without the vault library or without a usable key store is + not supported: the plugin fails closed there instead of storing values in the clear. The + unencrypted file store of earlier development builds is gone and is not migrated. +- **The key store is the default; a key file is an explicit, documented downgrade** + (`vault_key: file`) for machines that have no key store, never chosen automatically. +- **Known values are matched by the plugin, from a marker index.** Core's application vault + has no way to look a value up without writing, and no known-value matching. The plugin + keeps the list of markers it issued (not secret, not authoritative) and restores them in + memory to recognise values. Asking core to store every detected value again was rejected: + it rewrites the whole vault each time and uses up core's limit of about 100,000 changes. +- **The Bash restore-ticket key stays a small file in the vault directory**, not an entry in + the vault. It guards against a command starting the runner by itself, not against a + program that can read your files, and such a program could equally open the vault through + the key store. Putting it in the vault would add a marker that must never be restored. - **The test-only switch `DATAFOG_TEST_ALLOW_WRAPPED_BASH` was removed.** Tests and the live driver use settings files, like a user would. @@ -650,7 +748,10 @@ also apply to Bash commands, in every permission mode (see ## The vault -One vault serves all your projects, so a value has the same marker everywhere. +The vault is the table that maps markers to real values. There is **one vault for this +plugin, shared by all your projects**, so a value has the same marker everywhere. + +**Where it lives** | | Location | | :- | :- | @@ -658,20 +759,133 @@ One vault serves all your projects, so a value has the same marker everywhere. | "Keep the vault when the plugin is uninstalled" is on (default) | macOS `~/Library/Application Support/DataFog/vaults/claude-code`; Linux `$XDG_DATA_HOME/datafog/vaults/claude-code` or `~/.local/share/datafog/vaults/claude-code` | | the option is off | `${CLAUDE_PLUGIN_DATA}/vault`, which Claude Code deletes when the plugin is uninstalled | -It holds `datafog-core`'s workspace snapshot unmodified, a pointer file and a small -metadata file. **It is not encrypted at rest.** Writes are atomic, and concurrent -sessions are coordinated with a file lock and a compare-and-save on the vault's head. +**How it is stored.** The plugin uses the application vault of the DataFog core project +(`ApplicationVault` in the `datafog-fogvault` package) and adds two small files of its own: + +| File | Mode | What it is | +| :- | :- | :- | +| `workspace.enc` | 0600 | Core's vault: every value, encrypted (XChaCha20-Poly1305, a 256-bit random key). The application id, a random vault id, the revision and the key mode are readable in its header; the values are not. | +| `workspace.lock` | 0600 | Core's lock file. Every change holds it from reading the vault to the finished, flushed write. | +| `workspace.key` | 0600 | **Only with `vault_key: file`.** The key itself. | +| `markers.index` | 0600 | The plugin's list of markers issued so far (such as `[[EMAIL_7KQ4ZM]]`). No values. It lets the plugin recognise known values and count them without changing the vault; if it is lost or damaged, nothing breaks and it fills up again. | +| `bash-restore.key` | 0600 | The plugin's key for signing restore tickets ([Markers in Bash commands](#markers-in-bash-commands)). Not the vault key, and it decrypts nothing. | + +The directory is 0700. The plugin makes a new or still empty directory private itself. If +the directory or a file of an existing vault is open to other users, is not yours, or the +vault directory is a symbolic link, the vault is refused and nothing is repaired silently: +`/datafog:doctor` says which. + +**Where the key is.** By default (`vault_key: keystore`) the key is created once, stored in +your operating system's key store, and read from there by every plugin process: + +- macOS: the login Keychain, one entry with service `DataFog.ApplicationVault.v1` and + account `claude-code/`. +- Linux: the Secret Service (GNOME Keyring, KWallet), same service and account. + +Each vault directory has its own vault id and its own key, so two different +`DATAFOG_VAULT_DIR`s never share one. The key is never written to a file, a log, an +environment variable or a command line by the plugin; it is handled inside core's compiled +code only. + +If the key store is locked, not running or refuses access, the plugin stops with +`keystore_unavailable` and blocks tool calls. It never creates a second key for an existing +vault and never switches to a key file on its own. If the entry was deleted from the key +store, the vault cannot be opened again by anyone: delete it with `/datafog:purge`. + +**`vault_key: file` (opt-in, weaker).** For machines without a key store (a Linux server, +a container, CI) you can set `vault_key` to `file` in `config.json`, or +`DATAFOG_VAULT_KEY=file`, **before the vault is first created**. The key is then a file, +`workspace.key`, in the vault directory. The vault file is still ciphertext, but anyone who +can copy the directory has both, so this protects only against someone who gets +`workspace.enc` alone. A vault keeps the mode it was created with: opening it with the other +setting fails with `vault_key_mismatch` (purge it to change). + +**Several sessions at once.** Hooks are separate short processes and may run in parallel, +next to the long-lived Bash runner and the plugin's MCP server. Changes are serialised by +core's lock and each one is written completely and flushed before a marker is handed out, so +a crash leaves the old vault or the new one, never half of one. A value that is already known +is recognised without writing. + +**Uninstalling: keep or delete.** This is the plugin option "Keep the vault when the plugin +is uninstalled": + +- **On (default): keep.** The vault stays in your user data folder and its key stays in + your key store. Markers that are still in your files can be restored after you install + the plugin again. To remove everything later, run `/datafog:purge` before uninstalling, or + delete the folder above and the key store entry by hand. +- **Off: delete.** The vault is in the plugin's data folder and Claude Code deletes it on + uninstall. The key store entry is left behind (Claude Code does not know about it); it is + 32 random bytes that open nothing once the vault file is gone. Run `/datafog:purge` before + uninstalling to remove it too, or delete it in Keychain Access (search for `DataFog`). + +`/datafog:purge` deletes the vault file, the marker index, the ticket key, the key file if +there is one, and the entry in the key store (on macOS with `security +delete-generic-password`, on Linux with `secret-tool`, because core has no call for it; if +that fails, purge exits with failure and tells you the service and account to delete by hand). +Local deletion errors also return failure; purge never reports a complete deletion after an +error, and it never follows a vault or legacy snapshot symlink into another folder. If the vault is deleted, every marker issued from it is meaningless. Text that still holds markers (a file Claude wrote through another tool, notes, old transcripts) can then never be turned back into real values. +**Coming from a development build.** Builds before this one kept the vault unencrypted in +the same directory (`HEAD`, `meta.json`, `snapshots/`). This version never reads those +files. `/datafog:status` and `/datafog:doctor` say so when they are still there, and +`/datafog:purge` deletes them; nothing is migrated. + +**Limits of the vault library (core 1.7.0) worth knowing:** + +[Core issue #275](https://github.com/DataFog/datafog-core/issues/275) tracks lookup, +counts, deletion with key removal, read performance, lock timeout and parent-folder support. + +- **Every directory above the vault must be listable by you**, not only passable. On a + shared Linux machine where `/home` has mode 0711 the vault cannot be opened + (`vault_unreadable`). Put the vault elsewhere with `DATAFOG_VAULT_DIR`. +- Core waits at most 5 seconds for the vault's lock; the plugin retries up to + `DATAFOG_LOCK_TIMEOUT` (default 10) seconds in total and then stops with `vault_locked`. +- Restoring an older copy of the vault directory rolls the vault back; markers issued since + are then unknown. The encryption does not detect that. +- 20,000 values and about 100,000 changes per vault; see [Known gaps](#known-gaps). + +### Speed + +Wall time of one whole process (starting Python, opening the vault, the work), median and +95th percentile of 40 runs, on a Linux x86_64 container (4 KiB-scale inputs, small vault). +"Before" is the unencrypted file store of the development build with the same core 1.7.0. + +| Process | Before | Encrypted, key in a file | Encrypted, key in the Secret Service | +| :- | -: | -: | -: | +| PreToolUse hook for a Bash command | 45 / 61 ms | 50 / 63 ms | 56 / 59 ms | +| PostToolUse rewrite, 1 known value | 47 / 49 ms | 51 / 65 ms | 58 / 75 ms | +| PostToolUse rewrite, 10 known values | 46 / 49 ms | 52 / 72 ms | 58 / 96 ms | +| PostToolUse rewrite, 200 known values | 55 / 66 ms | 55 / 60 ms | 60 / 78 ms | +| PreToolUse Write, one marker restored | 44 / 55 ms | 47 / 52 ms | 57 / 78 ms | +| Runner, command without markers | 69 / 83 ms | 72 / 76 ms | 80 / 97 ms | +| Runner, one marker restored | 73 / 86 ms | 77 / 88 ms | 86 / 116 ms | + +Starting Python alone is 11 ms of each. With 19,000 values in the vault a rewrite takes +about 220 ms (150 ms before) and a Bash command with a marker about 320 ms (185 ms before), +because core reads and decrypts the whole vault for each operation. The optional macOS +Keychain case below measures full-process hook time and checks key creation and removal. +Release notes record the results of the release run. + ## Commands -- `/datafog:status` shows whether protection is on, where the vault is, and entity types - and counts. Never values. -- `/datafog:doctor` checks the installation and says what to fix. -- `/datafog:purge` deletes the vault after an explicit confirmation step. +- `/datafog:status` shows whether protection is on, where the vault is, how it is + encrypted and where its key is, and entity types and counts. Never values. +- `/datafog:doctor` checks the installation and says what to fix: supported machine, both + libraries, the vault (permissions, lock, key, decryption), leftovers of a development + build, the Bash filter, your permission rules. +- `/datafog:purge` deletes the vault and its key after an explicit confirmation step. + +### Distribution + +Version 0.2.0 is distributed directly from this repository. A public plugin-directory +submission is deferred until the interactive approval and permission-prompt paths listed +below have been checked; the automated live run uses headless Claude Code. Anthropic now +accepts submissions through its [directory portal](https://claude.ai/directory/manage), +not pull requests to its [official plugin repository](https://github.com/anthropics/claude-plugins-official). ## Configuration @@ -698,27 +912,25 @@ More settings go in `config.json` in the plugin's data directory | `egress_policy` | `DATAFOG_EGRESS_POLICY` | `ask` | For commands with markers (and restoring not `off`) that look like they send data away: `ask`, `deny`, `allow`. | | `restore_programs_extra` | `DATAFOG_RESTORE_PROGRAMS_EXTRA` | none | Program names, in addition to the built-in list, that may receive real values in a Bash command. You vouch that each treats its arguments as data. Read from `config.json` and the environment only. See [Markers in Bash commands](#markers-in-bash-commands). | | `restore_in_mcp_input` | | `false` | Swap markers back in input to third-party MCP tools. Real values then leave this process. | -| `recall_required` | `DATAFOG_RECALL_REQUIRED` | `true` | Stop when known-value matching is unavailable (see Limits). | +| `vault_key` | `DATAFOG_VAULT_KEY` | `keystore` | Where the vault's key is kept: `keystore` (macOS Keychain, Linux Secret Service) or `file` (beside the vault; weaker, for machines without a key store). Fixed when the vault is created. See [The vault](#the-vault). | | `max_scan_bytes` | `DATAFOG_MAX_SCAN_BYTES` | 5 MiB | Larger files count as "cannot be checked". | -| | `DATAFOG_VAULT_DIR` | | Vault directory. | +| | `DATAFOG_VAULT_DIR` | | Vault directory. Must be an absolute path whose parent directories you can list. | +| | `DATAFOG_LOCK_TIMEOUT` | 10 | Seconds to wait for the vault's lock before stopping. | A setting the plugin cannot understand makes it stop and say so; it does not fall back to a default in silence. ## Not verified yet -The mechanisms below were shown to work in the spike with a stand-in implementation, or -are new in this build. None has been run in a live session with this engine. -`tests/live/` settles them. +The release uses the full automated suite and `tests/live/` against real headless Claude +Code, including the optional macOS Keychain check. Release notes record the results. +The live driver loads only its project/local fixture settings so unrelated user hooks and +plugins do not interfere; it keeps the real login and DataFog MCP tools. Headless checks +cannot settle every interactive or operating-system behavior below. -- Read redirect, Write restore and Grep/MCP output replacement with the real engine. - The Bash runner inside Claude Code: that `cd` carries over between calls, that Claude Code collects all output, and that a cancelled or timed-out command is stopped. -- The Bash runner on macOS. It was tested on Linux with bash 5 and zsh 5.9 only: process - re-parenting, the `/dev/fd` and `/dev/tty` behaviour and bash 3.2 are untested there - (including `read -d ''`, which the child shell uses to receive the command). -- **Bash permissions, all of it against live Claude Code.** The decision logic is tested - against the documentation, not against Claude Code: +- **Interactive Bash permissions and modes beyond the headless cases:** - that a hook `allow` runs a rewritten command without a prompt, in an interactive session and in `claude -p`; - what the permission prompt for a hook `ask` looks like, that it shows the command with @@ -740,8 +952,11 @@ are new in this build. None has been run in a live session with this engine. documented examples, and which Bash commands it applies those rules to itself; - managed settings: whether a server-managed or MDM policy is in force (invisible to the plugin), in which case Claude Code ignores the managed settings *file* the plugin reads. -- Whether Claude Code lets Write or Edit change a file that was read through a redirected - copy (its read-before-write check may not count that read). +- **Other macOS Keychain states.** The optional live case checks creation, repeated reads, + full-process timing and purge. It does not test a locked Keychain, SSH access, access + immediately after login, or whether prompts return after updating Python or rebuilding + the private environment. The Keychain ties access to the program using the entry. +- The Secret Service with KWallet, and with a keyring that is locked when a session starts. - What the built-in Edit tool's result shows the model after the plugin replaced it. - That the plugin's MCP server receives the project directory and starts on first install. - How a blocked prompt and an `ask` decision look to you. @@ -749,27 +964,40 @@ are new in this build. None has been run in a live session with this engine. - Anything on Windows. To run the live check on your machine (about 29 short headless `claude -p` runs in a -throwaway temp project with a temporary vault; your real vault is not touched; hard caps -of 30 runs, 180 seconds each, 30 minutes in total): +throwaway temp project with a temporary vault whose key is a file in the temp directory; +your real vault and your Keychain are not touched; hard caps of 30 runs, 180 seconds each, +30 minutes in total): ```sh tests/live/run-live.command # or double-click it in Finder ``` +Because of that, the standard run does not exercise the Keychain. One optional, clearly +separate case does: `LIVE_KEYCHAIN=1 tests/live/run-live.command` adds `L28-keychain`, +which makes a second throwaway vault with its key in your real key store (one new entry), +uses it from several processes, measures it, and deletes the vault and that entry again. + Results land in `.live/results/results.md`. ## Development ```sh -uv venv && uv pip install "datafog-core>=1.4.0,<1.5" pytest ruff mypy +uv venv && uv pip install "datafog-core>=1.7.0,<1.8" "datafog-fogvault>=1.7.0,<1.8" pytest ruff mypy DATAFOG_TEST_NETWORK=1 .venv/bin/python -m pytest # the flag enables tests that build the private environment .venv/bin/ruff check . && .venv/bin/mypy ``` +Tests never use your key store: every test vault keeps its key in a file in the test's +temp directory. `tests/test_keystore.py` runs the key-store mode against a private Secret +Service (its own D-Bus session and GNOME Keyring in a temp directory) and needs Linux with +`dbus-run-session`, `gnome-keyring-daemon` and `secret-tool`; elsewhere it is skipped. + Layout: `engine/datafog_guard/` (the engine; entry `python -m datafog_guard `), `scripts/` (launcher, environment bootstrap, shell wrapper), `hooks/hooks.json`, -`.mcp.json`, `commands/`, `tests/`, `tests/live/`. For Bash: `plain.py` (the one recogniser -of plain commands), `shellsub.py` (puts values into a plain command as data, with its threat note), `ccperms.py` (reading and applying +`.mcp.json`, `commands/`, `tests/`, `tests/live/`. For the vault: `store.py` (core’s encrypted +application vault, the marker index, purge) and `vault.py` (finding values, assigning markers, +restoring). For Bash: `plain.py` (the recogniser of plain commands), `shellsub.py` (puts values +into a plain command as data), `ccperms.py` (reading and applying your Claude Code permission rules), `filtercmd.py` (the runner), `bashwrap.py` (the rewrite and the restore ticket). diff --git a/commands/doctor.md b/commands/doctor.md index f99f4b7..f1f9fb4 100644 --- a/commands/doctor.md +++ b/commands/doctor.md @@ -8,7 +8,14 @@ Run exactly this command with the Bash tool, then show its output to the user un sh "${CLAUDE_PLUGIN_ROOT}/scripts/datafog-guard" --data-dir "${CLAUDE_PLUGIN_DATA}" doctor ``` -If a line starts with `[FAIL]`, explain in one or two sentences what the user should do. If the detector library is missing, the fix is to run this in a terminal and then start a new session: +If a line starts with `[FAIL]`, explain in one or two sentences what the user should do: + +- "supported machine": the plugin cannot run on this computer (it needs macOS on Apple Silicon, or Linux on x86_64 with glibc 2.38 or later). The only remedy is to disable or uninstall the plugin. +- `keystore_unavailable`: the operating system's key store (macOS Keychain, or the Secret Service on Linux) is locked, not running or refused access. The user should unlock it or allow access. On a machine without a key store, the README describes the weaker `vault_key: file` setting. +- `vault_key_mismatch`, `vault_corrupt`, `vault_insecure`: say what the line says. Do not suggest deleting anything except through `/datafog:purge`, and say that purging makes existing markers unrestorable. +- "no unencrypted vault left over": an old development build left an unencrypted vault; `/datafog:purge` deletes it. + +If the detector library or the vault library is missing, the fix is to run this in a terminal and then start a new session: ``` sh "${CLAUDE_PLUGIN_ROOT}/scripts/datafog-guard" --data-dir "${CLAUDE_PLUGIN_DATA}" bootstrap diff --git a/commands/purge.md b/commands/purge.md index def35c7..f55a361 100644 --- a/commands/purge.md +++ b/commands/purge.md @@ -11,7 +11,7 @@ The user wants to delete the DataFog vault. This cannot be undone. Follow these sh "${CLAUDE_PLUGIN_ROOT}/scripts/datafog-guard" --data-dir "${CLAUDE_PLUGIN_DATA}" purge ``` -2. Tell the user plainly: the vault is the only thing that can turn markers such as `[[EMAIL_ABC123]]` back into real values. After deletion, any file, note or transcript that still contains markers can never be restored. Files that already contain the real values are not affected. +2. Tell the user plainly: this deletes the encrypted vault and removes its key from the operating system's key store (macOS Keychain or the Linux Secret Service). The vault is the only thing that can turn markers such as `[[EMAIL_ABC123]]` back into real values. After deletion, any file, note or transcript that still contains markers can never be restored. Files that already contain the real values are not affected. 3. Ask the user to reply with the exact words `delete the vault`. Stop and wait for their reply. Anything else means cancel. diff --git a/engine/datafog_guard/__init__.py b/engine/datafog_guard/__init__.py index 332502a..c655568 100644 --- a/engine/datafog_guard/__init__.py +++ b/engine/datafog_guard/__init__.py @@ -5,8 +5,11 @@ to the real values locally when the agent writes. """ -__version__ = "0.2.0.dev0" +__version__ = "0.2.0" -# The only runtime dependency. 1.5.0 has a known email-detection regression. -CORE_REQUIREMENT = "datafog-core>=1.4.0,<1.5" +# The detector. 1.5.0 and 1.6.0 have an email-detection regression (core #266); 1.7.0 fixed it. +CORE_REQUIREMENT = "datafog-core>=1.7.0,<1.8" +# The encrypted vault (datafog_fogvault.ApplicationVault). Released together with core; compiled +# wheels exist for macOS arm64, Linux x86_64 (glibc 2.38+) and Windows x64 only. +VAULT_REQUIREMENT = "datafog-fogvault>=1.7.0,<1.8" APP_ID = "claude-code" diff --git a/engine/datafog_guard/ccperms.py b/engine/datafog_guard/ccperms.py index 2f3758a..768ee74 100644 --- a/engine/datafog_guard/ccperms.py +++ b/engine/datafog_guard/ccperms.py @@ -398,7 +398,7 @@ def managed_dirs() -> list[str]: def config_home(env=None) -> str: env = os.environ if env is None else env - return env.get("CLAUDE_CONFIG_DIR") or os.path.join(os.path.expanduser("~"), ".claude") + return env.get("CLAUDE_CONFIG_DIR") or os.path.join(env.get("HOME") or os.path.expanduser("~"), ".claude") def _salvage(text: str, rules: RuleSet, source: str, source_dirs: list[str] | None = None) -> None: @@ -949,6 +949,33 @@ def is_simple(command: str, markers=()) -> bool: _TEST_EVALUATES = frozenset({"-v", "-R", "-eq", "-ne", "-lt", "-le", "-gt", "-ge", "-o", "-a"}) +_PRINTF_TEXT_FORMAT = re.compile(r"(?:[^%]|%%|%[-+ #0]*[0-9]*(?:\.[0-9]+)?[sbq])*") +_NUMBER = re.compile(r"[+-]?(?:[0-9]+(?:\.[0-9]*)?|\.[0-9]+)(?:[eE][+-]?[0-9]+)?") + + +def builtin_evaluates(words: list[str]) -> bool: + """Whether a nominally literal builtin can interpret an operand as shell arithmetic. + + In zsh, `printf %d 'path[$(cmd)]'` and `exit 'path[$(cmd)]'` execute cmd even though + the shell parser sees a single-quoted argument. Plain grammar alone cannot clear them + against deny/ask rules. Numeric literals and printf text conversions do not evaluate code. + """ + if not words: + return False + name, arguments = os.path.basename(words[0]), words[1:] + if name == "test": + return any(word in _TEST_EVALUATES for word in arguments) + if name == "exit": + return any(not _NUMBER.fullmatch(word) for word in arguments) + if name != "printf": + return False + if any(word.startswith("-v") for word in arguments): + return True + if arguments[:1] == ["--"]: + arguments = arguments[1:] + if not arguments or _PRINTF_TEXT_FORMAT.fullmatch(arguments[0]): + return False + return any(not _NUMBER.fullmatch(word) for word in arguments[1:]) def allow_rule_for(rules: RuleSet, command: str, exact_only: bool = False) -> Rule | None: @@ -961,10 +988,9 @@ def allow_rule_for(rules: RuleSet, command: str, exact_only: bool = False) -> Ru # an exact-match rule for the full command string". STRICTER: the same for every wrapper, including # the ones Claude Code strips (the docs do not say whether the unstripped text is matched as well), # for shells and eval, and for a command name that is quoted or escaped. - # `test -v 'x[$(cmd)]'`, an arithmetic operand of test, and `printf -v 'x[$(cmd)]'` make bash evaluate - # the operand. Claude Code's own wildcard rule would approve them; STRICTER: only an exact rule does here. - evaluates = (name == "test" and any(plain in _TEST_EVALUATES for _, plain in words[1:])) or \ - (name == "printf" and any(plain.startswith("-v") for _, plain in words[1:])) + # Some builtins evaluate even single-quoted operands as arithmetic. STRICTER: without a + # restrictive rule only an exact allow rule can approve them; with one the caller asks firmly. + evaluates = builtin_evaluates([plain for _, plain in words]) needs_exact = exact_only or evaluates or not unquoted or name in WRAPPERS or name in SHELLS or name == "eval" or \ name in ("watch", "setsid", "ionice", "flock") or \ (name == "find" and any(plain in _FIND_ACTIONS for _, plain in words[1:])) @@ -1304,6 +1330,12 @@ def ask(step: int, reason: str, found: Rule | None = None, firm: bool = False) - if markers and egress: return ask(5, f"DataFog: this command would run with real values ({markers}) and looks like it sends data " "to another machine.") + if parsed is not None and any(builtin_evaluates([word.text for word in simple.words]) + for simple in parsed.commands) \ + and (rules.deny or rules.ask or rules.paths or rules.block_outside_reads): + return ask(6, "DataFog: a shell builtin can evaluate an operand as arithmetic, including commands " + "inside a quoted argument, so the plugin cannot clear it against your deny or ask " + "rules. It is not approved without a prompt in any permission mode.", firm=True) unsupported = [rule for rule in rules.paths if rule.unsupported] if parsed is None: # Never allow, never "no decision" while a rule exists the plugin could be misreading the command diff --git a/engine/datafog_guard/cli.py b/engine/datafog_guard/cli.py index ca212ab..9a324d5 100644 --- a/engine/datafog_guard/cli.py +++ b/engine/datafog_guard/cli.py @@ -19,14 +19,26 @@ def _problem(error: BaseException) -> str: return f"{error.code}: {error.user_message}" if isinstance(error, GuardError) else safe_code(error) +PROTECTION_TEXT = { + "credential_store": "encrypted; the key is in the operating system's key store (macOS Keychain, or the " + "Secret Service on Linux)", + "file_key": "encrypted, but the key is a file beside the data (vault_key: file): anyone who can read the " + "vault directory can read the vault", +} +LEGACY_TEXT = ("an UNENCRYPTED vault from a development build is still in the vault directory. This version " + "cannot read it; delete it with /datafog:purge") + + def status_report(for_model: bool = False) -> str: settings = config.load() lines = [f"DataFog guard {__version__}"] + protection = None try: from .engine import open_vault vault, _ = open_vault(settings) health = vault.health() entries = vault.entry_counts() + protection = health["protection"] lines.append("Protection: ON") lines.append(f"Values held in the vault: {sum(entries.values())} ({describe_counts(entries)})") lines.append(f"Vault revision: {health['revision']}") @@ -37,7 +49,11 @@ def status_report(for_model: bool = False) -> str: lines.append(f"Vault location: {place}") if not for_model: lines.append(f"Vault path: {settings.vault_dir}") - lines.append("Vault encryption at rest: NONE in this version (owner-only file permissions)") + lines.append("Vault encryption at rest: " + (PROTECTION_TEXT.get(protection, str(protection)) if protection + else "the vault could not be opened")) + from .store import legacy_plain_store, vault_path + if legacy_plain_store(vault_path(settings.vault_dir)): + lines.append("WARNING: " + LEGACY_TEXT) lines.append(f"Detected types: {', '.join(settings.entities)}") lines.append("Not detected: names of people, addresses without a label, anything in images or PDFs") lines.append(f"Allowlisted exact values: {len(settings.allowlist)}") @@ -60,13 +76,18 @@ def status_report(for_model: bool = False) -> str: def purge(argv: list[str]) -> int: settings = config.load() - from .store import FileVaultStore - store = FileVaultStore(settings.vault_dir) + from .engine import open_store + from .store import KEYSTORE_SERVICE + store = open_store(settings) info = store.describe() if "--confirm" not in argv: print("This deletes the DataFog vault at:") print(f" {settings.vault_dir}") print(f"Current state: {info.get('state')}, revision {info.get('revision', 0)}.") + if info.get("protection") == "credential_store": + print("Its key is removed from the operating system's key store as well.") + if info.get("legacy_plain_store"): + print("The unencrypted vault of a development build in the same directory is deleted too.") print("After that, every marker issued so far is meaningless: text that still holds markers") print("(files Claude wrote with markers, old transcripts, notes) can NEVER be turned back into") print("the real values. Files on disk that already hold real values are not affected.") @@ -77,14 +98,28 @@ def purge(argv: list[str]) -> int: print(f"Not confirmed; nothing was deleted. The confirmation word is {PURGE_WORD}.") return 1 try: - existed = store.purge() - shutil.rmtree(settings.shadow_dir, ignore_errors=True) + result = store.purge() + if os.path.islink(settings.shadow_dir): + os.unlink(settings.shadow_dir) + else: + try: + shutil.rmtree(settings.shadow_dir) + except FileNotFoundError: + pass except Exception as error: print(f"The vault could not be deleted ({_problem(error)}).") return 1 - print("The vault was deleted." if existed else "There was no vault to delete.") + print("The vault was deleted." if result["existed"] or result["legacy"] else "There was no vault to delete.") + if result["legacy"]: + print("The unencrypted vault of a development build was deleted.") + if result["keystore"] == "removed": + print("Its key was removed from the operating system's key store.") + elif result["keystore"] == "left": + print("Its key could not be removed from the operating system's key store. It opens nothing now that the") + print(f"vault file is gone. To remove it by hand, delete the entry with service \"{KEYSTORE_SERVICE}\"") + print(f"and account \"{result['account']}\" (macOS: Keychain Access; Linux: Seahorse or secret-tool).") print("Markers issued before now can no longer be restored. A new, empty vault is created on next use.") - return 0 + return 1 if result["keystore"] == "left" else 0 def _claude_version() -> tuple[int, ...] | None: @@ -112,6 +147,11 @@ def check(name: str, ok, detail: str = "") -> None: print(f"DataFog guard {__version__} doctor") check("Python 3.10 or later", sys.version_info >= (3, 10), sys.version.split()[0]) + from . import VAULT_REQUIREMENT + from .support import UNSUPPORTED, platform_problem + problem = platform_problem() + check("supported machine (macOS on Apple Silicon, or Linux x86_64 with glibc 2.38 or later)", not problem, + f"{problem}. {UNSUPPORTED}" if problem else "") try: started = time.perf_counter() from importlib.metadata import version @@ -123,22 +163,46 @@ def check(name: str, ok, detail: str = "") -> None: check("configured entity types are supported", not missing, ", ".join(missing)) except Exception as error: check("detector library", False, safe_code(error) + "; run the bootstrap command shown at session start") + try: + started = time.perf_counter() + from importlib.metadata import version + + import datafog_fogvault # noqa: F401 + check(f"vault library ({VAULT_REQUIREMENT})", True, f"datafog-fogvault {version('datafog-fogvault')}, " + f"import {1000 * (time.perf_counter() - started):.1f} ms") + except Exception as error: + check("vault library", False, safe_code(error) + ("" if problem else + "; run the bootstrap command shown at session start")) check("configuration files", not settings.problems, "; ".join(settings.problems)) + from .store import legacy_plain_store, vault_path + protection = None try: from .engine import open_vault vault, _ = open_vault(settings) started = time.perf_counter() - vault.health() - check("vault opens, lock works, detector finds a test value", True, + protection = vault.health()["protection"] + check("vault opens (private files, lock, key, decryption) and the detector finds a test value", True, f"{1000 * (time.perf_counter() - started):.1f} ms") text, counts = vault.tokenize("doctor probe.synthetic@example.com") check("tokenize and restore round trip", vault.restore(text).text == "doctor probe.synthetic@example.com") except Exception as error: check("vault and detector", False, _problem(error)) - if os.name != "nt" and os.path.isdir(settings.vault_dir): - mode = os.stat(settings.vault_dir).st_mode & 0o777 + directory = vault_path(settings.vault_dir) + if os.name != "nt" and os.path.isdir(directory): + mode = os.stat(directory).st_mode & 0o777 check("vault directory is owner-only", mode == 0o700, oct(mode)) - check("vault encryption at rest", None, "none in this version") + loose = sorted(name for name in os.listdir(directory) + if os.path.isfile(os.path.join(directory, name)) + and os.stat(os.path.join(directory, name)).st_mode & 0o077) + check("vault files are owner-only", not loose, ", ".join(loose)) + if protection == "credential_store": + check("vault encryption at rest", True, PROTECTION_TEXT[protection]) + elif protection == "file_key": + check("vault encryption at rest", None, PROTECTION_TEXT[protection]) + else: + check("vault encryption at rest", False, "the vault could not be opened, so nothing can be said") + if legacy_plain_store(directory): + check("no unencrypted vault left over", False, LEGACY_TEXT) check("vault location", None, f"{settings.vault_location}: {settings.vault_dir}") for name in ("launcher", "wrap_script"): check(f"plugin file {os.path.basename(getattr(settings, name))}", os.path.exists(getattr(settings, name))) diff --git a/engine/datafog_guard/config.py b/engine/datafog_guard/config.py index 156f433..48dd858 100644 --- a/engine/datafog_guard/config.py +++ b/engine/datafog_guard/config.py @@ -51,6 +51,7 @@ def __init__(self, data_dir: str, vault_dir: str, vault_location: str, plugin_ro self.background_bash = "deny" # "deny" | "allow" self.egress_policy = "ask" # "ask" | "deny" | "allow" self.restore_in_mcp_input = False + self.vault_key = "keystore" # "keystore" | "file" (weaker: the key lies beside the data) # Programs the USER vouches for: "this program treats its arguments as data". Read from # config.json in the plugin data dir and from DATAFOG_RESTORE_PROGRAMS_EXTRA only. self.restore_programs_extra: frozenset[str] = frozenset() @@ -159,7 +160,7 @@ def _read_json(path: str, problems: list[str], label: str) -> dict: "DATAFOG_RESTORE_IN_BASH": "restore_in_bash", "DATAFOG_BACKGROUND_BASH": "background_bash", "DATAFOG_EGRESS_POLICY": "egress_policy", - "DATAFOG_RECALL_REQUIRED": "recall_required", + "DATAFOG_VAULT_KEY": "vault_key", "DATAFOG_MAX_SCAN_BYTES": "max_scan_bytes", "DATAFOG_KEEP_VAULT_ON_UNINSTALL": "keep_vault_on_uninstall", } @@ -247,6 +248,11 @@ def load() -> Settings: value = "off" if key == "restore_in_bash" else "deny" setattr(settings, key, value) settings.restore_in_mcp_input = _truthy(merged.get("restore_in_mcp_input"), False) + vault_key = str(merged.get("vault_key", "keystore")).strip().lower() + if vault_key not in ("keystore", "file"): + problems.append("vault_key must be keystore or file") + vault_key = "keystore" + settings.vault_key = vault_key # Not taken from runtime.json or plugin options: only the user's own config file and environment. extra = os.environ.get("DATAFOG_RESTORE_PROGRAMS_EXTRA") or own_config.get("restore_programs_extra") if extra is not None: diff --git a/engine/datafog_guard/engine.py b/engine/datafog_guard/engine.py index 37d5ded..2b9b471 100644 --- a/engine/datafog_guard/engine.py +++ b/engine/datafog_guard/engine.py @@ -5,18 +5,20 @@ from . import config from .errors import ConfigError -from .store import FileVaultStore +from .store import EncryptedStore from .vault import Detector, Vault -def open_vault(settings: config.Settings | None = None) -> tuple[Vault, config.Settings]: - settings = settings or config.load() - if settings.problems: - raise ConfigError("configuration problem: " + "; ".join(settings.problems)) +def open_store(settings: config.Settings) -> EncryptedStore: try: lock_timeout = float(os.environ.get("DATAFOG_LOCK_TIMEOUT", "10")) except ValueError: lock_timeout = 10.0 - store = FileVaultStore(settings.vault_dir, lock_timeout=lock_timeout) - detector = Detector(settings.entities, settings.allowlist) - return Vault(store, detector, recall_required=settings.recall_required), settings + return EncryptedStore(settings.vault_dir, key_mode=settings.vault_key, lock_timeout=lock_timeout) + + +def open_vault(settings: config.Settings | None = None) -> tuple[Vault, config.Settings]: + settings = settings or config.load() + if settings.problems: + raise ConfigError("configuration problem: " + "; ".join(settings.problems)) + return Vault(open_store(settings), Detector(settings.entities, settings.allowlist)), settings diff --git a/engine/datafog_guard/errors.py b/engine/datafog_guard/errors.py index 003e690..0ebafe9 100644 --- a/engine/datafog_guard/errors.py +++ b/engine/datafog_guard/errors.py @@ -47,8 +47,9 @@ class VaultFull(VaultError): code = "vault_full" -class RecallUnavailable(VaultError): - code = "recall_unavailable" +class KeyStoreUnavailable(VaultError): + """The operating system's key store is locked, missing or refused access.""" + code = "keystore_unavailable" class TokenizeError(GuardError): diff --git a/engine/datafog_guard/hook.py b/engine/datafog_guard/hook.py index dcc62f1..2512f88 100644 --- a/engine/datafog_guard/hook.py +++ b/engine/datafog_guard/hook.py @@ -559,7 +559,9 @@ def status_line(session: Session, healthy: bool, problem: str = "") -> str: if not healthy: return f"DataFog guard: NOT PROTECTING ({problem}). Tool calls are blocked. " + DOCTOR_HINT bash = "filtered" if settings.bash_wrap == "runner" else "NOT FILTERED" - return (f"DataFog guard: on. Vault: {place}, not encrypted at rest. Bash output: {bash}. " + kept = ("encrypted, key in the system key store" if settings.vault_key == "keystore" + else "encrypted, key in a file beside it (weaker)") + return (f"DataFog guard: on. Vault: {place}, {kept}. Bash output: {bash}. " f"Markers in Bash commands: {settings.restore_in_bash}. " f"Detecting: {', '.join(settings.entities)}. Names and free-text addresses are not detected.") diff --git a/engine/datafog_guard/mcp_server.py b/engine/datafog_guard/mcp_server.py index 2f1c05d..605353b 100644 --- a/engine/datafog_guard/mcp_server.py +++ b/engine/datafog_guard/mcp_server.py @@ -64,7 +64,7 @@ def __init__(self): def session(self): from .engine import open_vault settings = config.load() - key = (settings.vault_dir, settings.entities, settings.allowlist, settings.recall_required) + key = (settings.vault_dir, settings.entities, settings.allowlist, settings.vault_key) if self._vault is None or key != self._vault_key: self._vault, _ = open_vault(settings) self._vault_key = key diff --git a/engine/datafog_guard/plain.py b/engine/datafog_guard/plain.py index 1f65a76..3800f5d 100644 --- a/engine/datafog_guard/plain.py +++ b/engine/datafog_guard/plain.py @@ -64,9 +64,10 @@ # directory (cd and friends are handled separately, see name_problem). This is about reading the # command with certainty, NOT a claim that their arguments are inert: `test -v 'x[$(cmd)]'` and # `printf -v 'x[$(cmd)]'`, typed by the model, run cmd under bash, exactly as they would with a -# plain `Bash` allow rule in Claude Code. Marker restoration has its own, far shorter list -# (shellsub.RESTORE_PROGRAMS), and ccperms does not let a wildcard allow rule approve `test` with -# -v or an arithmetic operator, or `printf -v`. +# plain `Bash` allow rule in Claude Code. zsh also evaluates numeric printf operands and exit +# arguments as arithmetic. Marker restoration has its own, far shorter list (shellsub.RESTORE_PROGRAMS). +# ccperms requires exact allow rules for evaluating builtin forms, and a firm prompt while deny +# or ask rules exist because execution inside those operands cannot be cleared by the grammar. PLAIN_BUILTINS = frozenset({"echo", "printf", "true", "false", ":", "pwd", "test", "kill", "wait", "type", "which", "exit"}) MOVES = frozenset({"cd", "chdir", "pushd", "popd"}) diff --git a/engine/datafog_guard/store.py b/engine/datafog_guard/store.py index 322ffe3..0905eb1 100644 --- a/engine/datafog_guard/store.py +++ b/engine/datafog_guard/store.py @@ -1,68 +1,66 @@ -"""Vault storage. +"""Vault storage: datafog-core's encrypted application vault, plus a small marker index. -The engine talks to storage through :class:`VaultStore`, whose only write is -compare-and-save on the workspace head. That is all a backend has to offer, -so core's own vault helper or a remote store can replace the file store later. - -The v1 backend is :class:`FileVaultStore`: a directory holding core's snapshot -bytes unmodified, a pointer file naming the current snapshot, and a small -metadata file. It is NOT encrypted at rest; it relies on owner-only file -permissions. +The values live in ``datafog_fogvault.ApplicationVault`` (a separate package of the core +project). It keeps one encrypted file per application, takes an OS file lock around every +change, and holds the 256-bit key in the operating system's key store (macOS Keychain, Secret +Service on Linux). This module is the only place that talks to it. / 0700 - meta.json 0600 vault id, app id, contract version, created - HEAD 0600 {revision, commit_id, snapshot, sha256, annotations} - snapshots/-.dfv 0600 core's bundle bytes, unmodified - lock 0600 cross-process lock for compare-and-save - -A save writes the new snapshot (temp file, fsync, rename) and then replaces -HEAD the same way. HEAD is the commit point: a crash before it leaves an -unreferenced snapshot file and the old vault intact. + workspace.enc 0600 ApplicationVault: XChaCha20-Poly1305 ciphertext of core's snapshot + workspace.lock 0600 ApplicationVault: cross-process lock + workspace.key 0600 ONLY with vault_key=file: the key, in the clear, beside the data + markers.index 0600 ours: the markers issued so far (no values; see below) + bash-restore.key 0600 ours: signs restore tickets for Bash commands (bashwrap.py) + +What ApplicationVault 1.7 offers is: open, prepare_and_commit, restore, restore_report, forget, +head, operations, close. What it does not offer, and how this module fills the gap: + +* No way to ask "is this value known, and what is its marker" without writing: every + ``prepare_and_commit``, also for values it already holds, rewrites the whole encrypted + file and uses one of roughly 100,000 operation records. So the engine must find known + values itself. ``markers.index`` lists the markers issued (a marker is what the model + sees; it is not a secret). Restoring all of them in one call gives the known values in + memory, and only values that are really new are sent to ``prepare_and_commit``. + The same list gives the entry counts for ``status`` and the known-value matching that + core's ``Workspace.recall`` used to do (ApplicationVault has no recall). + The index is a cache of facts the vault itself is the authority for: a marker missing from + it (a crash between commit and append) is added again the next time its value is detected, + because core gives a repeated value its old marker; a marker the vault does not know is + ignored. +* No delete. ``purge`` removes the files under the vault's own lock and removes the key + from the key store with the operating system's own tool, best effort. +* Every restore re-reads and decrypts the file. Callers batch markers into one call. + +There is no unencrypted mode and no fallback to one. A plain-file vault written by a +development build (``HEAD``, ``meta.json``, ``snapshots/``) is never read; ``doctor`` reports it +and ``purge`` deletes it. """ from __future__ import annotations -import hashlib -import json import os +import re +import stat import time -from collections import namedtuple from . import APP_ID -from .errors import VaultCorrupt, VaultError, VaultLocked - - -class Head(namedtuple("Head", "revision commit_id")): - """A workspace head: revision number and commit id (hex).""" - __slots__ = () - - def name(self) -> str: - return f"{self.revision:012d}-{self.commit_id}" - - -class Snapshot: - def __init__(self, head: Head, bundle: bytes, annotations: dict | None = None): - self.head = head - self.bundle = bundle # core's snapshot bytes, unmodified - self.annotations = annotations or {} # small non-secret counters (types and counts) - - -class VaultStore: - """The storage interface. Its only write is compare-and-save on the workspace head.""" - - def peek_head(self) -> Head | None: - """The current head without the snapshot bytes (cheap), or None for an empty vault.""" - raise NotImplementedError - - def load(self) -> Snapshot | None: - """The current snapshot, or None for an empty vault.""" - raise NotImplementedError - - def compare_and_save(self, expected: Head | None, new: Head, bundle: bytes, annotations: dict) -> bool: - """Save ``bundle`` as head ``new`` only if the stored head is still ``expected``. - - Returns False, changing nothing, when the head moved (the caller reloads and retries). - """ - raise NotImplementedError +from .errors import ( + EngineUnavailable, + KeyStoreUnavailable, + VaultBusy, + VaultCorrupt, + VaultError, + VaultFull, + VaultLocked, +) + +MARKER_RE = re.compile(r"\[\[([A-Z][A-Z0-9_]*)_([0-9A-Z]{6})\]\]") +KEY_MODES = ("keystore", "file") +ENVELOPE, LOCK_FILE, KEY_FILE, INDEX_FILE = "workspace.enc", "workspace.lock", "workspace.key", "markers.index" +LEGACY_NAMES = ("HEAD", "meta.json", "snapshots", "lock") # the unencrypted store of development builds +KEYSTORE_SERVICE = "DataFog.ApplicationVault.v1" # the name core stores the key under +RESTORE_CHUNK_BYTES = 512 * 1024 # core takes 1 MiB of text per call +_PROTECTION = {1: "credential_store", 2: "file_key", 3: "external_key"} +_INDEX_HEADER = "# datafog marker index v1 " def atomic_write(path: str, data: bytes) -> None: @@ -171,148 +169,495 @@ def __exit__(self, *exc) -> None: os.close(fd) -class FileVaultStore(VaultStore): - def __init__(self, directory: str, lock_timeout: float = 10.0): - self.directory = directory +def _fogvault(): + try: + import datafog_fogvault + except Exception as error: # no wheel for this machine, or a broken install + from .support import UNSUPPORTED, platform_problem + if platform_problem(): + raise EngineUnavailable(UNSUPPORTED, "unsupported_platform") from error + raise EngineUnavailable("the datafog-fogvault library cannot be loaded; run the bootstrap command " + "shown at session start", "vault_library_unavailable") from error + return datafog_fogvault + + +def vault_path(directory: str) -> str: + """The directory as ApplicationVault must be given it: absolute, with symbolic links in the + directories above it resolved (``/tmp`` and ``/var`` are links on macOS). The vault directory + itself is not resolved: core refuses a vault directory that is a symbolic link, and so do we. + """ + directory = os.path.abspath(directory) + parent, name = os.path.split(directory.rstrip(os.sep) or os.sep) + return os.path.join(os.path.realpath(parent), name) if name else directory + + +def read_envelope_header(directory: str) -> dict | None: + """What the encrypted file says about itself in the clear: ids, revision, key mode. No key needed.""" + fd = None + try: + fd = os.open(os.path.join(directory, ENVELOPE), os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK) + if not stat.S_ISREG(os.fstat(fd).st_mode): + return {"state": "vault_insecure"} + head = os.read(fd, 512) + except OSError: + return None + finally: + if fd is not None: + os.close(fd) + return _parse_envelope_header(head) + + +def _parse_envelope_header(head: bytes) -> dict: + try: + if head[:8] != b"DFAPP001": + return {"state": "vault_unsupported"} + size = head[12] + end = 13 + size + return {"state": "ok", "app_id": head[13:end].decode("ascii"), "vault_id": head[end:end + 16].hex(), + "revision": int.from_bytes(head[end + 32:end + 40], "little"), + "protection": _PROTECTION.get(head[end + 56], "unknown")} + except (IndexError, UnicodeError): + return {"state": "vault_corrupt"} + + +def legacy_plain_store(directory: str) -> bool: + """True when the directory holds the unencrypted file store of a development build.""" + return os.path.isfile(os.path.join(directory, "HEAD")) or os.path.isdir(os.path.join(directory, "snapshots")) + + +_MESSAGES = { + "credential_store_unavailable": ( + KeyStoreUnavailable, + "the operating system's key store, where the vault's key is kept, is locked, not available or refused " + "access (macOS: the login Keychain; Linux: a Secret Service such as GNOME Keyring). Unlock it or allow " + "access and try again. On a machine without one, see vault_key in the README"), + "key_required": ( + VaultError, + "the vault's key is missing or the vault was created with a different vault_key setting (keystore or " + "file) than the one in use now. Use the setting it was created with, or delete the vault with " + "/datafog:purge"), + "vault_integrity": ( + VaultCorrupt, + "the encrypted vault file is damaged, or the key in the key store is not the key it was written with"), + "unsupported_envelope": (VaultError, "the vault file was written by a version this plugin cannot read"), + "unsafe_permissions": ( + VaultError, + "the vault directory or a file in it is open to other users, is not yours or is not a regular file; " + "the plugin does not repair this by itself (expected: directory 0700, files 0600)"), + "unsafe_path": (VaultError, "the vault directory is not a safe path (it must be absolute and not a symbolic link)"), + "storage_error": ( + VaultError, + "the vault cannot be read or written (the disk, or a directory above the vault that this user cannot list)"), + "vault_busy": (VaultLocked, "another process holds the vault lock"), + "workspace_conflict": (VaultBusy, "the vault changed while it was being updated"), + "invalid_app_id": (VaultError, "internal: the application id was refused"), + "invalid_key": (VaultError, "internal: the key was refused"), +} +_CODES = {"credential_store_unavailable": "keystore_unavailable", "key_required": "vault_key_mismatch", + "unsafe_permissions": "vault_insecure", "unsafe_path": "vault_insecure", + "storage_error": "vault_unreadable", "unsupported_envelope": "vault_unsupported"} +# After these the handle is dead or stale (closed by core, or the vault was replaced under it). +_REOPEN = ("owner_closed", "outcome_unknown", "saved_but_not_activated", "vault_integrity", "storage_error", + "key_required") + + +class StoreError(Exception): + """A core error by its controlled code. Core's messages are codes only; nothing else is kept.""" + + def __init__(self, code: str): + super().__init__(code) + self.code = code + + +def _translate(error: BaseException) -> VaultError: + code = str(getattr(error, "code", "") or "unknown") + if code not in _MESSAGES: + return VaultError("the vault reported an error", "vault_" + re.sub(r"[^a-z0-9_]", "", code)[:40]) + kind, message = _MESSAGES[code] + return kind(message, _CODES.get(code)) + + +def _flock(fd: int, timeout: float) -> None: + """Exclusive lock on an open file, released when the descriptor is closed.""" + import fcntl + deadline = time.monotonic() + timeout + delay = 0.001 + while True: + try: + fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB) + return + except OSError: + if time.monotonic() >= deadline: + raise VaultLocked("another process holds the vault lock") from None + time.sleep(delay) + delay = min(delay * 2, 0.05) + + +class EncryptedStore: + """One process's handle on the application vault and its marker index. + + Not safe for concurrent use from several threads; :class:`~datafog_guard.vault.Vault` serialises. + """ + + def __init__(self, directory: str, key_mode: str = "keystore", lock_timeout: float = 10.0): + if key_mode not in KEY_MODES: + raise VaultError("vault_key must be keystore or file", "config_error") + self.directory = vault_path(directory) + self.key_mode = key_mode self.lock_timeout = lock_timeout - self._head_path = os.path.join(directory, "HEAD") - self._meta_path = os.path.join(directory, "meta.json") - self._snapshots = os.path.join(directory, "snapshots") - self._lock_path = os.path.join(directory, "lock") + self._owner = None + self._index_path = os.path.join(self.directory, INDEX_FILE) + + # -- opening ----------------------------------------------------------- + def exists(self) -> bool: + return os.path.isfile(os.path.join(self.directory, ENVELOPE)) - # -- reading --------------------------------------------------------- - def _read_pointer(self) -> dict | None: + def _prepare_directory(self) -> None: + """Create the directory private, or tighten one that does not hold a vault yet. + + A directory the user made with plain ``mkdir`` is 0755. Core refuses it and repairs + nothing; before any vault exists there is nothing to protect yet, so it is made private + here. A loose directory that already holds a vault is left for core to refuse. + """ + if os.name == "nt" or os.path.islink(self.directory): + return try: - with open(self._head_path, "rb") as handle: - raw = handle.read() + info = os.stat(self.directory) except FileNotFoundError: - return None - except OSError as error: - raise VaultError("the vault cannot be read", "vault_unreadable") from error - try: - pointer = json.loads(raw) - Head(int(pointer["revision"]), str(pointer["commit_id"])) - str(pointer["snapshot"]), str(pointer["sha256"]) - except (ValueError, KeyError, TypeError) as error: - raise VaultCorrupt("the vault pointer file is damaged") from error - return pointer - - def peek_head(self) -> Head | None: - pointer = self._read_pointer() - return Head(int(pointer["revision"]), str(pointer["commit_id"])) if pointer else None - - def load(self) -> Snapshot | None: - for _ in range(8): - pointer = self._read_pointer() - if pointer is None: - return None - name = os.path.basename(pointer["snapshot"]) try: - with open(os.path.join(self._snapshots, name), "rb") as handle: - bundle = handle.read() - except FileNotFoundError: - # A writer replaced HEAD and removed the snapshot we were about to read. - if self._read_pointer() == pointer: - raise VaultCorrupt("the vault snapshot file is missing") - continue + os.makedirs(self.directory, mode=0o700, exist_ok=True) except OSError as error: - raise VaultError("the vault cannot be read", "vault_unreadable") from error - if hashlib.sha256(bundle).hexdigest() != pointer["sha256"]: - raise VaultCorrupt("the vault snapshot does not match its checksum") - annotations = pointer.get("annotations") - return Snapshot(Head(int(pointer["revision"]), str(pointer["commit_id"])), bundle, - annotations if isinstance(annotations, dict) else {}) - raise VaultError("the vault kept changing while it was read", "vault_busy") - - def metadata(self) -> dict: - try: - with open(self._meta_path, encoding="utf-8") as handle: - data = json.load(handle) - return data if isinstance(data, dict) else {} - except (OSError, ValueError): - return {} - - # -- writing --------------------------------------------------------- - def _prepare_dirs(self) -> None: - secure_dir(self.directory) - secure_dir(self._snapshots) - - def lock(self) -> FileLock: - self._prepare_dirs() - return FileLock(self._lock_path, self.lock_timeout) - - def compare_and_save(self, expected: Head | None, new: Head, bundle: bytes, annotations: dict) -> bool: - with self.lock(): - pointer = self._read_pointer() - current = Head(int(pointer["revision"]), str(pointer["commit_id"])) if pointer else None - if current != expected: - return False - if not os.path.exists(self._meta_path): - from datafog_core import workspace_contract_version - meta = {"vault_id": os.urandom(16).hex(), "app_id": APP_ID, - "contract_version": workspace_contract_version(), - "created": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()), - "format": "datafog-file-vault-1", "encrypted_at_rest": False} - atomic_write(self._meta_path, json.dumps(meta, indent=2).encode("utf-8")) - name = new.name() + ".dfv" - atomic_write(os.path.join(self._snapshots, name), bundle) - new_pointer = {"revision": new.revision, "commit_id": new.commit_id, "snapshot": name, - "sha256": hashlib.sha256(bundle).hexdigest(), "annotations": annotations} - atomic_write(self._head_path, json.dumps(new_pointer, sort_keys=True).encode("utf-8")) # commit point - self._collect_garbage(keep={name, os.path.basename(pointer["snapshot"]) if pointer else name}) - return True - - def _collect_garbage(self, keep: set[str]) -> None: - """Remove old snapshots. The previous one stays so a reader that just read HEAD still finds it.""" - try: - names = os.listdir(self._snapshots) - except OSError: + raise VaultError("the vault directory cannot be created", "vault_unreadable") from error return - now = time.time() - for name in names: - if name in keep: - continue - path = os.path.join(self._snapshots, name) + if info.st_uid == os.geteuid() and info.st_mode & 0o077 and not self.exists(): + os.chmod(self.directory, 0o700) + + def open(self, create: bool): + """The open vault, or None when there is none and ``create`` is false. + + Opening is the health check: the directory and files are private, the lock can be taken, + the key is available from where the vault says it is, and the file decrypts. + """ + if self._owner is not None: + # A long-lived process: another process may have purged the vault, or replaced it. + header = read_envelope_header(self.directory) + if header is not None and header.get("vault_id") == self.vault_id(): + return self._owner + self.close() + if not create and not self.exists(): + return None + fogvault = _fogvault() + self._prepare_directory() + deadline = time.monotonic() + self.lock_timeout + while True: try: - if name.endswith(".tmp") and now - os.stat(path).st_mtime < 300: - continue # possibly another writer's file in progress - os.unlink(path) - except OSError: + owner = fogvault.ApplicationVault.open(APP_ID, directory=self.directory, + allow_file_key=self.key_mode == "file") + break + except fogvault.FogVaultWorkspaceError as error: + if error.code == "vault_busy" and time.monotonic() < deadline: + continue + raise _translate(error) from None + mode = owner.protection_mode + if mode != {"keystore": "credential_store", "file": "file_key"}[self.key_mode]: + owner.close() # never reached with core 1.7, which refuses first; kept as a guard + raise VaultError(_MESSAGES["key_required"][1], "vault_key_mismatch") + self._owner = owner + return owner + + def close(self) -> None: + owner, self._owner = self._owner, None + if owner is not None: + try: + owner.close() + except Exception: pass - def purge(self) -> bool: - """Delete the vault. Markers issued from it can never be restored afterwards.""" - if not os.path.isdir(self.directory): - return False - with self.lock(): - existed = os.path.exists(self._head_path) - for path in (self._head_path, self._meta_path): # HEAD first: the vault is gone from here on - try: - os.unlink(path) - except FileNotFoundError: - pass + @property + def protection(self) -> str | None: + """"credential_store" or "file_key" for an open vault.""" + return self._owner.protection_mode if self._owner is not None else None + + def vault_id(self) -> str | None: + return self._owner.vault_id.hex() if self._owner is not None else None + + def _call(self, create: bool, action, retry_busy: bool = True): + """Run ``action(owner)``. Reopens once when the handle went stale, waits out a busy lock.""" + fogvault = _fogvault() + deadline = time.monotonic() + self.lock_timeout + reopened = False + conflicts = 0 + while True: + owner = self.open(create) + if owner is None: + raise StoreError("no_vault") try: - for name in os.listdir(self._snapshots): - os.unlink(os.path.join(self._snapshots, name)) - except OSError: - pass - return existed + return action(owner) + except fogvault.FogVaultWorkspaceError as error: + code = str(error.code) + if code in _REOPEN: + self.close() + if not reopened: + reopened = True + continue + raise _translate(error) from None + if code == "vault_busy" and retry_busy and time.monotonic() < deadline: + continue + if code == "workspace_conflict" and conflicts < 20 and time.monotonic() < deadline: + conflicts += 1 + continue + if code in _MESSAGES: + raise _translate(error) from None + raise StoreError(code) from None + + # -- the three things the engine needs ------------------------------------- + def commit(self, pairs: list[tuple[str, str]]) -> list[str]: + """Store (entity, value) pairs; returns their markers in order. Durable before it returns. + + A value core already holds (compared loosely: case and white space) gets its old marker. + Raises StoreError with core's code when core refuses the values. + """ + separator = "\x1e%s\x1e" % os.urandom(8).hex() + findings, offset, step = [], 0, len(separator) + for entity, value in pairs: + size = len(value.encode("utf-8")) + findings.append({"entityType": entity, "matchedText": value, + "range": {"unit": "utf8_bytes", "start": offset, "end": offset + size}}) + offset += size + step + text = separator.join(value for _, value in pairs) + try: + output = self._call(True, lambda owner: owner.prepare_and_commit(text, findings, os.urandom(16), True)) + except StoreError as error: + if error.code == "resource_limit": + raise VaultFull( + "the vault is full (core allows 20,000 values and about 100,000 changes per vault); new " + "values cannot be protected until it is emptied with /datafog:purge") from None + raise + markers = output.split(separator) + if len(markers) != len(pairs) or not all(MARKER_RE.fullmatch(marker) for marker in markers): + raise StoreError("unexpected_markers") + return markers - def describe(self) -> dict: - info: dict = {"backend": "file", "directory": self.directory, "encrypted_at_rest": False} + def restore_report(self, text: str) -> dict: + """Core's restore report: ``text`` (None when there are issues) and ``issues`` with byte ranges.""" + return self._call(False, lambda owner: owner.restore_report(text)) + + def values_for(self, markers: list[str]) -> dict[str, str]: + """marker -> real value, for the markers the vault knows. Unknown ones are left out. + + One call to core per chunk (two when a chunk holds unknown markers), because every + call re-reads and decrypts the vault file. + """ + found: dict[str, str] = {} + chunk: list[str] = [] + size = 0 + for marker in list(dict.fromkeys(markers)) + [None]: # type: ignore[list-item] + if marker is None or size + len(marker) + 20 > RESTORE_CHUNK_BYTES: + if chunk: + self._restore_chunk(chunk, found) + chunk, size = [], 0 + if marker is not None: + chunk.append(marker) + size += len(marker) + 20 + return found + + def _restore_chunk(self, markers: list[str], found: dict[str, str]) -> None: + for _ in range(4): + if not markers: + return + separator = "\x1e%s\x1e" % os.urandom(8).hex() + starts, offset = [], 0 + for marker in markers: + starts.append(offset) + offset += len(marker) + len(separator) # markers and the separator are ASCII + report = self.restore_report(separator.join(markers)) + issues = report["issues"] + if not issues and report["text"] is not None: + values = report["text"].split(separator) + if len(values) != len(markers): + continue # a value held the separator: draw another + found.update(zip(markers, values)) + return + from bisect import bisect_right + bad = {bisect_right(starts, issue["byteRange"]["start"]) - 1 for issue in issues} + if not bad: + raise StoreError("restore_failed") + markers = [marker for index, marker in enumerate(markers) if index not in bad] + raise StoreError("restore_failed") + + # -- the marker index -------------------------------------------------------- + def index_stamp(self): + """Changes whenever the index file does. Cheap: one stat.""" try: - pointer = self._read_pointer() - except VaultError as error: - info["state"] = error.code - return info - if pointer is None: + info = os.stat(self._index_path) + except OSError: + return None + return (info.st_ino, info.st_size, info.st_mtime_ns) + + def read_index(self) -> list[str]: + """The markers issued from the open vault, oldest first. Empty when the index is another vault's.""" + fd = None + try: + fd = os.open(self._index_path, os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK) + if not stat.S_ISREG(os.fstat(fd).st_mode): + raise VaultError("the marker index is not a regular file", "vault_insecure") + with os.fdopen(fd, "rb") as handle: + fd = None + lines = handle.read().decode("ascii", "replace").split("\n") + except OSError: + return [] + finally: + if fd is not None: + os.close(fd) + if lines[0] != _INDEX_HEADER + str(self.vault_id()): + return [] + return list(dict.fromkeys(line for line in lines[1:] if MARKER_RE.fullmatch(line))) + + def add_to_index(self, markers: list[str]): + """Append markers under an exclusive lock on the index file; an index of another vault is replaced. + + Returns (stamp before, stamp after), so a caller whose copy matched "before" knows its + copy plus these markers matches "after". + """ + if not markers or self._owner is None: + return None, None + header = (_INDEX_HEADER + str(self.vault_id()) + "\n").encode("ascii") + fd = os.open(self._index_path, os.O_RDWR | os.O_CREAT | os.O_APPEND | getattr(os, "O_NOFOLLOW", 0), 0o600) + try: + _flock(fd, self.lock_timeout) + info = os.fstat(fd) + before = (info.st_ino, info.st_size, info.st_mtime_ns) + payload = b"" + if os.pread(fd, len(header), 0) != header: + os.ftruncate(fd, 0) + payload = header + elif os.pread(fd, 1, info.st_size - 1) != b"\n": + payload = b"\n" # a torn last line from a crash: end it + payload += "".join(marker + "\n" for marker in markers).encode("ascii") + os.write(fd, payload) + os.fsync(fd) + info = os.fstat(fd) + return before, (info.st_ino, info.st_size, info.st_mtime_ns) + finally: + os.close(fd) # also releases the lock + + # -- describing and deleting --------------------------------------------------- + def describe(self) -> dict: + """State without opening the vault (no key needed): safe to call when it is broken.""" + info: dict = {"backend": "application-vault", "directory": self.directory, "encrypted_at_rest": True, + "legacy_plain_store": legacy_plain_store(self.directory)} + header = read_envelope_header(self.directory) + if header is None: info["state"] = "empty" return info - info["state"] = "ok" - info["revision"] = pointer["revision"] + info.update(header) try: - info["bytes"] = os.stat(os.path.join(self._snapshots, os.path.basename(pointer["snapshot"]))).st_size + info["bytes"] = os.stat(os.path.join(self.directory, ENVELOPE)).st_size except OSError: - info["state"] = "vault_corrupt" - info.update({key: value for key, value in self.metadata().items() if key in ("vault_id", "created", "app_id")}) + pass return info + + def purge(self) -> dict: + """Delete the vault, its marker index, its key and any plain store of a development build. + + Returns {"existed", "legacy", "keystore"}; ``keystore`` is "none" (no key there), "removed", + or "left" (the key store entry could not be removed; it is 32 random bytes that open + nothing once the vault file is gone). + """ + result: dict = {"existed": False, "legacy": False, "keystore": "none", "account": ""} + self.close() + directory_fd = None + lock_fd = None + try: + try: + directory_fd = os.open(self.directory, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW) + except FileNotFoundError: + return result + info = os.fstat(directory_fd) + if info.st_uid != os.geteuid(): + raise VaultError("the vault directory belongs to another user", "vault_insecure") + lock_fd = os.open(LOCK_FILE, os.O_RDWR | os.O_CREAT | os.O_NOFOLLOW | os.O_NONBLOCK, + 0o600, dir_fd=directory_fd) + info = os.fstat(lock_fd) + if not stat.S_ISREG(info.st_mode) or info.st_uid != os.geteuid() or info.st_nlink != 1: + raise VaultError("the vault lock is not a safe regular file", "vault_insecure") + _flock(lock_fd, self.lock_timeout) + header = None + try: + info = os.stat(ENVELOPE, dir_fd=directory_fd, follow_symlinks=False) + result["existed"] = True + if stat.S_ISREG(info.st_mode): + fd = os.open(ENVELOPE, os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK, dir_fd=directory_fd) + try: + if not stat.S_ISREG(os.fstat(fd).st_mode): + raise VaultError("the vault file is not a regular file", "vault_insecure") + header = _parse_envelope_header(os.read(fd, 512)) + finally: + os.close(fd) + except FileNotFoundError: + pass + + def remove_file(name: str, parent: int = directory_fd) -> None: + try: + os.unlink(name, dir_fd=parent) + except FileNotFoundError: + pass + + for name in (ENVELOPE, KEY_FILE, INDEX_FILE, "bash-restore.key"): # the data first + remove_file(name) + try: + info = os.stat("snapshots", dir_fd=directory_fd, follow_symlinks=False) + result["legacy"] = True + if stat.S_ISDIR(info.st_mode): + snapshots_fd = os.open("snapshots", os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW, + dir_fd=directory_fd) + try: + for name in os.listdir(snapshots_fd): + remove_file(name, snapshots_fd) + os.fsync(snapshots_fd) + finally: + os.close(snapshots_fd) + os.rmdir("snapshots", dir_fd=directory_fd) + else: + remove_file("snapshots") + except FileNotFoundError: + pass + for name in ("HEAD", "meta.json", "lock"): + try: + os.stat(name, dir_fd=directory_fd, follow_symlinks=False) + result["legacy"] = True + except FileNotFoundError: + pass + remove_file(name) + os.fsync(directory_fd) + if header and header.get("protection") == "credential_store" and header.get("app_id") == APP_ID \ + and header.get("vault_id"): + result["account"] = f"{APP_ID}/{header['vault_id']}" + result["keystore"] = "removed" if remove_keystore_entry(result["account"]) else "left" + return result + except OSError as error: + raise VaultError("the vault could not be fully deleted; check its directory and file permissions", + "purge_failed") from error + finally: + if lock_fd is not None: + os.close(lock_fd) + if directory_fd is not None: + os.close(directory_fd) + + +def remove_keystore_entry(account: str) -> bool: + """Remove the vault key from the OS key store. ApplicationVault 1.7 has no call for this, so the + system's own tool is used. The account is ``/``: not a secret.""" + import shutil + import subprocess + import sys + if sys.platform == "darwin": + argv = ["/usr/bin/security", "delete-generic-password", "-s", KEYSTORE_SERVICE, "-a", account] + elif shutil.which("secret-tool"): + argv = ["secret-tool", "clear", "service", KEYSTORE_SERVICE, "username", account] + else: + return False + try: + return subprocess.run(argv, capture_output=True, timeout=20).returncode == 0 + except (OSError, subprocess.SubprocessError): + return False diff --git a/engine/datafog_guard/support.py b/engine/datafog_guard/support.py new file mode 100644 index 0000000..ac331c3 --- /dev/null +++ b/engine/datafog_guard/support.py @@ -0,0 +1,36 @@ +"""Which machines the plugin runs on, and the one message shown everywhere else. + +The vault is ``datafog-fogvault``, which ships compiled wheels for macOS on Apple Silicon, +Linux x86_64 with glibc 2.38 or later, and Windows x64 (the plugin itself does not support +Windows yet). There is no other storage and no fallback: on any other machine the plugin does +not protect, says so with this message, and blocks tool calls. +""" +from __future__ import annotations + +# Also in scripts/bootstrap.sh (tests/test_cli_and_plugin.py checks that the two are the same). +UNSUPPORTED = ( + "DataFog does not support this machine. It needs macOS on Apple Silicon, or Linux on x86_64 with " + "glibc 2.38 or later. Nothing is protected and tool calls are blocked; disable or uninstall the " + "plugin to work without it." +) + + +def platform_problem() -> str | None: + """None on a supported machine, else a short reason (no paths, no content).""" + import platform + import sys + machine = platform.machine().lower() + if sys.platform == "darwin": + return None if machine in ("arm64", "aarch64") else "macOS on Intel" + if sys.platform.startswith("linux"): + if machine not in ("x86_64", "amd64"): + return f"Linux on {machine or 'an unknown processor'}" + name, version = platform.libc_ver() + if name != "glibc": + return "Linux without glibc" + try: + parts = tuple(int(part) for part in version.split(".")[:2]) + except ValueError: + return "Linux with an unknown glibc" + return None if parts >= (2, 38) else f"glibc {version}" + return "this operating system" diff --git a/engine/datafog_guard/vault.py b/engine/datafog_guard/vault.py index 9e23c04..2554a36 100644 --- a/engine/datafog_guard/vault.py +++ b/engine/datafog_guard/vault.py @@ -1,49 +1,53 @@ -"""Detection, tokenization and restoration on top of datafog-core's Workspace. +"""Detection, tokenization and restoration on top of datafog-core's encrypted application vault. Order of a tokenization, which must not change: - find values (detector + recall of values the vault already knows) - -> Workspace.prepare assign markers, nothing is durable yet - -> store.compare_and_save persist core's candidate bundle - -> Workspace.activate_saved only now are the markers valid - -> check each marker restores to exactly its value + find values (detector + values the vault already knows) + -> known values take the marker they already have nothing is written + -> new values: store.commit core assigns markers and saves them, + encrypted and flushed, before it returns + -> check each new marker restores to exactly its value + -> note the new markers in the marker index -> release the tokenized text If any step fails, an exception is raised and no text is released. -Facts about core 1.4 this module is built around (all checked against the real library): - -* ``prepare`` and ``recall`` reject text holding marker-like strings the vault does not - know, so markers are obtained by preparing a small text made of the distinct values - only, and are spliced into the original text here. -* ``prepare`` rejects partially overlapping findings, so overlaps are merged first. -* Core folds case and trims white space when it compares values: ``Ada@Example.com`` and - ``ada@example.com`` share one marker, which restores to whichever was seen first. - A value whose marker would restore to different bytes is stored under a variant - label (``EMAIL_V2``) instead, so that restoration is always exact. -* Limits: 1 MiB of text and 10,000 findings per call, 20,000 live entries, and ``recall`` - stops working once the stored values pass roughly 256 KiB in total. +Facts about core 1.7 and its ApplicationVault this module is built around (all checked against +the real libraries): + +* ``prepare_and_commit`` rejects text holding marker-like strings the vault does not know, so + markers are obtained by committing a small text made of the distinct new values only, and + are spliced into the original text here. +* It rejects partially overlapping findings, so overlaps are merged first. +* Core folds case and white space when it compares values: ``Ada@Example.com`` and + ``ada@example.com`` share one marker, which restores to whichever was seen first; ``a\tb``, + ``a\r\nb`` and ``a b`` likewise. A value whose marker would restore to different bytes is + stored under a variant label (``EMAIL_V2``) instead, so that restoration is always exact. + A value that is only white space is refused by core; spans are trimmed, so none is ever sent. +* ApplicationVault has no ``recall`` and no lookup. Known values are matched here, against the + values of the markers in the store's marker index, with the rules core's recall had: the + whole value, ignoring case and the amount of white space, and not inside a longer word or + number. +* Limits: 1 MiB of text and 10,000 findings per call, 20,000 live entries. """ from __future__ import annotations -import os import re -import time from collections import Counter, namedtuple -from .errors import EngineUnavailable, RecallUnavailable, TokenizeError, VaultBusy, VaultCorrupt, VaultError, VaultFull -from .store import Head, VaultStore +from .errors import EngineUnavailable, TokenizeError, VaultError +from .store import MARKER_RE, EncryptedStore, StoreError -MARKER_RE = re.compile(r"\[\[([A-Z][A-Z0-9_]*)_([0-9A-Z]{6})\]\]") ANY_CASE_MARKER_RE = re.compile(MARKER_RE.pattern, re.IGNORECASE) # core restores markers in any case MAX_VALUE_BYTES = 32 * 1024 # larger findings are refused, which bounds every stored value -RECALL_WINDOW = 512 * 1024 -RECALL_OVERLAP = 2 * MAX_VALUE_BYTES # a stored value always fits whole inside one window VALUES_PER_COMMIT = 1000 BYTES_PER_COMMIT = 256 * 1024 -SAVE_RETRIES = 60 MAX_VARIANTS = 9 ENTRY_LIMIT = 20_000 +# Known-value matching looks for every known value in the text. Past this many (values x text +# characters) the values are first narrowed to those whose first characters occur in the text. +PREFILTER_WORK = 50_000_000 +GRAM = 4 # Characters a terminal does not show, or that move the cursor. A value split by one of them @@ -234,141 +238,150 @@ def merge_spans(spans: list[Span], data: bytes) -> list[Span]: return merged +class _Known: + """The values the vault holds, as this process last read them. Lives in memory only.""" + + __slots__ = ("stamp", "vault_id", "marker_of", "markers", "folded") + + def __init__(self, stamp, vault_id, values: dict[str, str]): + self.stamp = stamp + self.vault_id = vault_id + self.markers = list(values) # every known marker + self.marker_of: dict[str, str] = {} # exact value -> its first marker + self.folded: dict[str, list[str]] = {} # value with case and white space folded -> values + for marker, value in values.items(): + self.add(marker, value, count=False) + + def add(self, marker: str, value: str, count: bool = True) -> None: + if count: + self.markers.append(marker) + if value not in self.marker_of: + self.marker_of[value] = marker + self.folded.setdefault(_fold(value), []).append(value) + + +def _fold(value: str) -> str: + return " ".join(value.split()).casefold() + + +def _is_word(char: str) -> bool: + return char == "_" or char.isalnum() + + +def _value_pattern(value: str): + """A value as core's recall matched it: any white space between its parts, any case, and not + directly against a letter, digit or underscore where the value itself begins or ends with one.""" + parts = value.split() + body = r"\s+".join(re.escape(part) for part in parts) + before = r"(? Head: - return Head(int(core_head.revision), bytes(core_head.commit_id).hex()) - - def _load(self, create: bool): - """Return a workspace at the stored head, reloading when another process moved it.""" - core = _core() - stored = self.store.peek_head() - if self._workspace is not None and stored == self._head: - return self._workspace - self._workspace, self._head, self._recall_ok = None, None, None - snapshot = self.store.load() - if snapshot is None: - if not create: - return None - workspace = core.Workspace.create(os.urandom(16), os.urandom(16)) - head = self._head_of(workspace.head()) - self.store.compare_and_save(None, head, workspace.export_bundle(), {"entries": {}}) - snapshot = self.store.load() # ours, or the one a concurrent creator won with - if snapshot is None: - raise VaultError("the vault could not be created", "vault_create_failed") - try: - workspace = core.Workspace.open_bundle(snapshot.bundle) - except Exception as error: - raise VaultCorrupt("the vault snapshot cannot be opened") from error - if self._head_of(workspace.head()) != snapshot.head: - raise VaultCorrupt("the vault snapshot does not match its pointer") - self._workspace, self._head, self._annotations = workspace, snapshot.head, snapshot.annotations - return workspace - def ensure_exists(self) -> None: with self._mutex: - self._load(create=True) + self.store.open(create=True) def health(self) -> dict: - """Open the vault, take and release its lock, and run the detector. Raises when unhealthy.""" + """Run the detector's self-test and open the vault (creating it when there is none), which + checks its permissions, takes its lock, fetches its key and decrypts it. Raises when unhealthy.""" with self._mutex: self.detector.self_test() - self._load(create=True) - lock = getattr(self.store, "lock", None) - if lock is not None: - with lock(): - pass - if self.recall_required: - self._check_recall(self._workspace) - return {"revision": self._head.revision if self._head else 0, "entries": self.entry_counts()} + self.store.open(create=True) + info = self.store.describe() + return {"revision": info.get("revision", 0), "protection": self.store.protection} + + def _load_known(self) -> _Known | None: + """The known values, re-read when another process added to the vault. None without a vault.""" + if self.store.open(create=False) is None: + self._known = None + return None + stamp, vault_id = self.store.index_stamp(), self.store.vault_id() + known = self._known + if known is not None and known.stamp == stamp and known.vault_id == vault_id: + return known + try: + values = self.store.values_for(self.store.read_index()) + except StoreError as error: + raise VaultError("the vault could not be read", "vault_" + error.code) from None + if self.store.vault_id() != vault_id: # the vault was replaced while it was read + values = self.store.values_for(self.store.read_index()) + vault_id = self.store.vault_id() + self._known = _Known(stamp, vault_id, values) + return self._known def entry_counts(self) -> dict: + """Values held, by marker label. Counts what the vault confirms, not what the index claims.""" with self._mutex: - if self._workspace is None: - self._load(create=False) - entries = self._annotations.get("entries") if isinstance(self._annotations, dict) else None - return dict(entries) if isinstance(entries, dict) else {} + known = self._load_known() + return dict(Counter(marker_label(marker) for marker in known.markers)) if known else {} # -- finding values ---------------------------------------------------- - def _check_recall(self, workspace) -> bool: - if self._recall_ok is None: - try: - workspace.recall("probe") - self._recall_ok = True - except Exception: - self._recall_ok = False - if not self._recall_ok and self.recall_required: - raise RecallUnavailable( - "the vault holds too many values for known-value matching to work; " - "run /datafog:purge, or set recall_required to false to rely on the detector alone") - return self._recall_ok - - def _marker_issues(self, workspace, text: str) -> list[tuple[int, int]]: - """Byte ranges of marker-like strings the vault does not accept (they break recall).""" - if "[[" not in text and "_" not in text: - return [] - report = workspace.restore_report(text) - return sorted((issue["byteRange"]["start"], issue["byteRange"]["end"]) for issue in report["issues"]) - - def _recall_window(self, workspace, data: bytes, offset: int, out: list[Span]) -> None: - core = _core() - try: - findings = workspace.recall(data.decode("utf-8"))["findings"] - except core.DataFogWorkspaceError as error: - if error.code != "resource_limit": - raise TokenizeError("known-value matching failed", "recall_failed") from error - if not self._check_recall(workspace): - return - if len(data) <= 4096: - raise TokenizeError("the text holds too many values to process", "too_many_values") from error - self._recall_range(workspace, data, offset, out, window=max(4096, len(data) // 2)) + def _known_spans(self, known: _Known, text: str, out: list[Span]) -> None: + """Byte spans of known values in ``text``. Text that is itself a marker is never matched.""" + if not known.folded: return - for item in findings: - start, end = item["byteRange"]["start"], item["byteRange"]["end"] - if item["finding"]["matchedText"] in self.detector.allowlist: + folded_text = _fold(text) + candidates = known.folded + if len(candidates) * len(folded_text) > PREFILTER_WORK: + grams = {folded_text[index:index + GRAM] for index in range(len(folded_text) - GRAM + 1)} + candidates = {key: values for key, values in candidates.items() if len(key) < GRAM or key[:GRAM] in grams} + hits = [key for key in candidates if key in folded_text] + if not hits: + return + markers = [(match.start(), match.end()) for match in ANY_CASE_MARKER_RE.finditer(text)] + ascii_only = text.isascii() + for key in hits: + values = known.folded[key] + entity = marker_label(known.marker_of[values[0]]) + if any(value in self.detector.allowlist for value in values): continue - out.append(Span(offset + start, offset + end, item["finding"]["entityType"], True)) + for start, end in self._occurrences(values[0], key, text, folded_text): + if any(left < end and start < right for left, right in markers): + continue + if not ascii_only: + size = len(text[start:end].encode("utf-8", "surrogatepass")) + start = len(text[:start].encode("utf-8", "surrogatepass")) + end = start + size + out.append(Span(start, end, entity, True)) - def _recall_range(self, workspace, data: bytes, offset: int, out: list[Span], window: int) -> None: - if len(data) <= window: - self._recall_window(workspace, data, offset, out) - return - overlap = min(RECALL_OVERLAP, window // 2) - position = 0 - while position < len(data): - end = min(len(data), position + window) - while end < len(data) and (data[end] & 0xC0) == 0x80: - end += 1 - self._recall_window(workspace, data[position:end], offset + position, out) - if end >= len(data): - break - position = end - overlap - while (data[position] & 0xC0) == 0x80: - position -= 1 + @staticmethod + def _occurrences(value: str, key: str, text: str, folded_text: str): + """Character ranges where ``value`` stands in ``text`` (see :func:`_value_pattern`). + + The usual case, every occurrence spelled exactly as stored, is a plain search; a regular + expression is only built when case or white space differ somewhere.""" + if text.count(value) != folded_text.count(key): + return [match.span() for match in _value_pattern(value).finditer(text)] + found = [] + size, edge_left, edge_right = len(value), _is_word(value[0]), _is_word(value[-1]) + position = text.find(value) + while position >= 0: + end = position + size + if not (edge_left and position and _is_word(text[position - 1])) and \ + not (edge_right and end < len(text) and _is_word(text[end])): + found.append((position, end)) + position = text.find(value, end) + else: + position = text.find(value, position + 1) + return found - def _raw_spans(self, workspace, text: str, data: bytes) -> list[Span]: - """Detector findings plus recall hits for one text, as byte spans into that text.""" + def _raw_spans(self, known: _Known | None, text: str) -> list[Span]: + """Detector findings plus known values for one text, as byte spans into that text.""" spans = self.detector.spans(text) - if workspace is not None and self._check_recall(workspace): - position = 0 - for start, end in self._marker_issues(workspace, text) + [(len(data), len(data))]: - if start > position: - self._recall_range(workspace, data[position:start], position, spans, RECALL_WINDOW) - position = max(position, end) + if known is not None: + self._known_spans(known, text, spans) return spans def find_spans(self, text: str, data: bytes | None = None) -> list[Span]: @@ -384,8 +397,8 @@ def find_spans(self, text: str, data: bytes | None = None) -> list[Span]: data = text.encode("utf-8") except UnicodeError as error: raise TokenizeError("the text is not valid Unicode", "undecodable_text") from error - workspace = self._load(create=False) - spans = self._raw_spans(workspace, text, data) + known = self._load_known() + spans = self._raw_spans(known, text) if _NEEDS_VIEWS.search(text): from bisect import bisect_left, bisect_right seen = {text} @@ -400,7 +413,7 @@ def find_spans(self, text: str, data: bytes | None = None) -> list[Span]: starts.append(total) code = ord(char) total += 1 if code < 0x80 else 2 if code < 0x800 else 3 if code < 0x10000 else 4 - for span in self._raw_spans(workspace, view, view.encode("utf-8")): + for span in self._raw_spans(known, view): first = bisect_right(starts, span.start) - 1 last = bisect_left(starts, span.end) - 1 cells = origin[first:last + 1] @@ -423,78 +436,37 @@ def find_spans(self, text: str, data: bytes | None = None) -> list[Span]: # -- assigning markers --------------------------------------------------- def _commit(self, pairs: list[tuple[str, str]]) -> dict[str, str]: - """prepare -> save -> activate for (entity, value) pairs. Returns value -> marker.""" - core = _core() - text = "\n".join(value for _, value in pairs) - last_error: Exception | None = None - for attempt in range(SAVE_RETRIES): - if attempt: - self._workspace = None - import random - time.sleep(min(0.2, 0.002 * (2 ** min(attempt, 6))) * random.random()) - workspace = self._load(create=True) - findings, offset = [], 0 - for entity, value in pairs: - size = len(value.encode("utf-8")) - findings.append(core.WorkspaceFinding(entity, value, core.TextRange(offset, offset + size), - source="scanner", needs_review=False)) - offset += size + 1 - try: - change = workspace.prepare(text, findings, os.urandom(16)) - except core.DataFogWorkspaceError as error: - if error.code == "resource_limit": - raise VaultFull( - f"the vault is full (core allows {ENTRY_LIMIT:,} live entries); new values cannot be " - "protected until it is emptied with /datafog:purge") from error - raise TokenizeError("the vault refused the values", "prepare_" + str(error.code)) from error - try: - preview = change.preview() - output = preview["text"].encode("utf-8") - transformations = sorted(preview["transformations"], key=lambda t: t["sourceByteRange"]["start"]) - if len(transformations) != len(pairs): - raise TokenizeError("the vault did not assign a marker to every value", "prepare_incomplete") - markers: dict[str, str] = {} - for (_, value), item in zip(pairs, transformations): - marker = output[item["outputByteRange"]["start"]:item["outputByteRange"]["end"]].decode("utf-8") - if not MARKER_RE.fullmatch(marker): - raise TokenizeError("the vault returned an unexpected marker", "prepare_bad_marker") - markers[value] = marker - expected, candidate = change.expected_head(), change.candidate_head() - if expected != candidate: - # Markers the workspace cannot restore yet are the new entries: count them by type. - entries = Counter(self.entry_counts()) - distinct = sorted(set(markers.values())) - joined = "\n".join(distinct).encode("utf-8") - for issue in workspace.restore_report(joined.decode("utf-8"))["issues"]: - marker = joined[issue["byteRange"]["start"]:issue["byteRange"]["end"]].decode("utf-8") - entries[marker_label(marker)] += 1 - saved = self.store.compare_and_save(self._head_of(expected), self._head_of(candidate), - change.export_candidate_bundle(), {"entries": dict(entries)}) - if not saved: - change.discard() - last_error = VaultBusy("the vault changed while it was being updated") - continue - self._annotations = {"entries": dict(entries)} - workspace.activate_saved(change, expected, candidate) - self._head = self._head_of(candidate) - self._recall_ok = None - return markers - except BaseException: - try: - change.discard() - except Exception: - pass - raise - raise last_error or VaultBusy("the vault changed while it was being updated") + """Store (entity, value) pairs in the vault. Returns value -> marker. + + Core gives a value it already holds (compared loosely) the marker it has; the caller + checks exactness. The markers are durable when this returns. + """ + try: + markers = self.store.commit(pairs) + except StoreError as error: + raise TokenizeError("the vault refused the values", "prepare_" + error.code) from None + return {value: marker for (_, value), marker in zip(pairs, markers)} def _markers_for(self, wanted: dict[str, list[str]]) -> dict[str, str]: """value -> marker, for values with their candidate entity types (most trusted first).""" + known = self._load_known() markers: dict[str, str] = {} - attempt = {value: 0 for value in wanted} - pending = list(wanted) + pending = [] + for value in wanted: + if not value.strip(): + raise TokenizeError("a value of only white space cannot be stored", "empty_value") + marker = known.marker_of.get(value) if known is not None else None + if marker is not None: + markers[value] = marker # byte-exact: it was read back from the vault + else: + pending.append(value) + if not pending: + return markers + attempt = {value: 0 for value in pending} + fresh: dict[str, str] = {} # marker -> value, to note in the index for _ in range(MAX_VARIANTS + 8): if not pending: - return markers + break pairs = [] for value in pending: candidates, index = wanted[value], attempt[value] @@ -518,22 +490,37 @@ def _markers_for(self, wanted: dict[str, list[str]]) -> dict[str, str]: batch.append(pair) size += len(pair[1].encode("utf-8")) + 1 # Exactness check: core compares values loosely, a write-back must be byte-exact. - separator = f"\n<{os.urandom(8).hex()}>\n" - workspace = self._load(create=False) - if workspace is None: - raise VaultError("the vault disappeared while it was being updated", "vault_missing") - restored = workspace.restore(separator.join(assigned[value] for value in pending)).split(separator) - if len(restored) != len(pending): - raise TokenizeError("the vault did not restore the values it was given", "restore_check_failed") + try: + restored = self.store.values_for([assigned[value] for value in pending]) + except StoreError as error: + raise TokenizeError("the vault did not restore the values it was given", + "restore_check_" + error.code) from None still = [] - for value, back in zip(pending, restored): - if back == value: - markers[value] = assigned[value] + for value in pending: + marker = assigned[value] + if marker not in restored: + raise TokenizeError("the vault did not restore the values it was given", "restore_check_failed") + if restored[marker] == value: + markers[value] = marker + fresh[marker] = value else: attempt[value] += 1 still.append(value) pending = still - raise TokenizeError("a value cannot be stored so that it restores exactly", "no_exact_marker") + if pending: + raise TokenizeError("a value cannot be stored so that it restores exactly", "no_exact_marker") + if known is None or known.vault_id != self.store.vault_id(): + self._known = None # the vault was created or replaced just now: read it afresh + known = self._load_known() + have = set(known.markers) if known is not None else set() + missing = [marker for marker in fresh if marker not in have] + before, after = self.store.add_to_index(missing) + if known is not None: + for marker in missing: + known.add(marker, fresh[marker]) + # Ours was the only change since the index was read: keep what is in memory. + known.stamp = after if before == known.stamp else None + return markers def tokenize_many(self, texts: list[str]) -> tuple[list[str], Counter]: """Replace every value in each text by its marker. Returns the texts and counts by entity type.""" @@ -614,16 +601,17 @@ def restore(self, text: str) -> RestoreResult: if "[[" not in text: # Bare codes without brackets are never restored, so there is nothing to do. return RestoreResult(text, Counter(), 0) - workspace = self._load(create=False) - if workspace is None: - return RestoreResult(text, Counter(), len(ANY_CASE_MARKER_RE.findall(text))) try: - return self._restore(workspace, text, depth=0) + return self._restore(text, depth=0) + except StoreError as error: + if error.code == "no_vault": + return RestoreResult(text, Counter(), len(ANY_CASE_MARKER_RE.findall(text))) + raise VaultError("the vault could not restore the text", "restore_" + error.code) from None except UnicodeError as error: raise TokenizeError("the text is not valid Unicode", "undecodable_text") from error - def _restore(self, workspace, text: str, depth: int) -> RestoreResult: - report = workspace.restore_report(text) + def _restore(self, text: str, depth: int) -> RestoreResult: + report = self.store.restore_report(text) issues = sorted((issue["byteRange"]["start"], issue["byteRange"]["end"]) for issue in report["issues"]) data = text.encode("utf-8") skip = bytearray(len(data) + 1) @@ -644,7 +632,7 @@ def _restore(self, workspace, text: str, depth: int) -> RestoreResult: total: Counter = Counter() for start, end in issues + [(len(data), len(data))]: if start > position: - piece = self._restore(workspace, data[position:start].decode("utf-8"), depth + 1) + piece = self._restore(data[position:start].decode("utf-8"), depth + 1) parts.append(piece.text) total.update(piece.restored) unknown += piece.unknown @@ -662,20 +650,21 @@ def restore_spans(self, text: str) -> tuple[list[tuple[int, int, str, str]], int if "[[" not in text: return [], 0 matches = list(ANY_CASE_MARKER_RE.finditer(text)) - workspace = self._load(create=False) - if workspace is None: - return [], len(matches) try: - unknown = self._restore(workspace, text, depth=0).unknown - spans = [] - for match in matches: - report = workspace.restore_report(match.group(0)) - if report["issues"] or report["text"] is None: - continue - spans.append((match.start(), match.end(), base_entity(match.group(1).upper()), report["text"])) - return spans, unknown + # One call to core for all markers (each call re-reads and decrypts the vault). + values = self.store.values_for([match.group(0) for match in matches]) + unknown = sum(1 for match in matches if match.group(0) not in values) + if len(values) < len({match.group(0) for match in matches}) or not matches: + unknown = self._restore(text, depth=0).unknown # the exact count core would report + except StoreError as error: + if error.code == "no_vault": + return [], len(matches) + raise VaultError("the vault could not restore the text", "restore_" + error.code) from None except UnicodeError as error: raise TokenizeError("the text is not valid Unicode", "undecodable_text") from error + spans = [(match.start(), match.end(), base_entity(match.group(1).upper()), values[match.group(0)]) + for match in matches if match.group(0) in values] + return spans, unknown def marker_counts(self, text: str) -> tuple[Counter, int]: """(known markers by type, unknown marker-like strings) in ``text``; changes nothing.""" diff --git a/pyproject.toml b/pyproject.toml index 3f00b96..a2b3bdb 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,10 +1,10 @@ [project] name = "datafog-guard" -version = "0.2.0.dev0" +version = "0.2.0" description = "Engine of the DataFog Claude Code plugin" requires-python = ">=3.10" license = "Apache-2.0" -dependencies = ["datafog-core>=1.4.0,<1.5"] +dependencies = ["datafog-core>=1.7.0,<1.8", "datafog-fogvault>=1.7.0,<1.8"] [dependency-groups] dev = ["pytest>=8", "ruff>=0.6", "mypy>=1.10"] diff --git a/scripts/bootstrap.sh b/scripts/bootstrap.sh index 07af699..dd31c5b 100755 --- a/scripts/bootstrap.sh +++ b/scripts/bootstrap.sh @@ -2,14 +2,42 @@ # Create or verify the plugin's private Python environment. # # bootstrap.sh [--force] +# bootstrap.sh --platform only check that this machine is supported # -# Idempotent. Fast path: when venv/.datafog-installed names the current requirement, +# Idempotent. Fast path: when venv/.datafog-installed names the current requirements, # nothing is done. Uses uv when it is installed, otherwise python -m venv and pip. -# Exit status 0 means the environment is ready. +# Exit status 0 means the environment is ready; 3 means this machine is not supported. + +# The detector and the encrypted vault. datafog-fogvault has compiled wheels for macOS on +# Apple Silicon and Linux x86_64 with glibc 2.38 or later only; there is no other storage. +CORE_REQUIREMENT='datafog-core>=1.7.0,<1.8' +VAULT_REQUIREMENT='datafog-fogvault>=1.7.0,<1.8' +REQUIREMENT="$CORE_REQUIREMENT $VAULT_REQUIREMENT" +UNSUPPORTED='DataFog does not support this machine. It needs macOS on Apple Silicon, or Linux on x86_64 with glibc 2.38 or later. Nothing is protected and tool calls are blocked; disable or uninstall the plugin to work without it.' + +supported_platform() { + case "$(uname -s 2>/dev/null)/$(uname -m 2>/dev/null)" in + Darwin/arm64) return 0 ;; + Linux/x86_64|Linux/amd64) + libc=$(getconf GNU_LIBC_VERSION 2>/dev/null) || return 1 + version=${libc#glibc } + major=${version%%.*} + minor=${version#*.}; minor=${minor%%.*} + case "$major$minor" in *[!0-9]*|'') return 1 ;; esac + [ "$major" -gt 2 ] || { [ "$major" -eq 2 ] && [ "$minor" -ge 38 ]; } + return $? ;; + esac + return 1 +} + +if ! supported_platform; then + echo "$UNSUPPORTED" + exit 3 +fi +[ "$1" = "--platform" ] && exit 0 DATA=$1 FORCE=$2 -REQUIREMENT='datafog-core>=1.4.0,<1.5' STAMP="$DATA/venv/.datafog-installed" venv_python() { @@ -61,7 +89,7 @@ if command -v uv >/dev/null 2>&1; then SYSTEM_PYTHON=$(find_python) || SYSTEM_PYTHON='>=3.10' uv venv --quiet --allow-existing --python "$SYSTEM_PYTHON" "$DATA/venv" || ok=0 fi - [ "$ok" = 1 ] && { uv pip install --quiet --python "$(venv_python)" "$REQUIREMENT" || ok=0; } + [ "$ok" = 1 ] && { uv pip install --quiet --python "$(venv_python)" "$CORE_REQUIREMENT" "$VAULT_REQUIREMENT" || ok=0; } else if [ -z "$(venv_python)" ] || [ "$FORCE" = "--force" ]; then SYSTEM_PYTHON=$(find_python) || { @@ -70,13 +98,13 @@ else } "$SYSTEM_PYTHON" -m venv "$DATA/venv" || ok=0 fi - [ "$ok" = 1 ] && { "$(venv_python)" -m pip install --quiet --disable-pip-version-check "$REQUIREMENT" || ok=0; } + [ "$ok" = 1 ] && { "$(venv_python)" -m pip install --quiet --disable-pip-version-check "$CORE_REQUIREMENT" "$VAULT_REQUIREMENT" || ok=0; } fi -if [ "$ok" = 1 ] && "$(venv_python)" -c 'import datafog_core; datafog_core.scan("probe")' 2>/dev/null; then +if [ "$ok" = 1 ] && "$(venv_python)" -c 'import datafog_core, datafog_fogvault; datafog_core.scan("probe"); datafog_fogvault.ApplicationVault' 2>/dev/null; then printf '%s' "$REQUIREMENT" > "$STAMP" echo "datafog bootstrap: ready" exit 0 fi -echo "datafog bootstrap: FAILED. To install by hand: create a Python 3.10+ virtual environment at $DATA/venv and run its pip: pip install '$REQUIREMENT'" +echo "datafog bootstrap: FAILED. To install by hand: create a Python 3.10+ virtual environment at $DATA/venv and run its pip: pip install '$CORE_REQUIREMENT' '$VAULT_REQUIREMENT'" exit 1 diff --git a/scripts/datafog-guard b/scripts/datafog-guard index 1ec4482..b21b41a 100755 --- a/scripts/datafog-guard +++ b/scripts/datafog-guard @@ -20,6 +20,7 @@ done # A value that still looks like an unexpanded "${NAME}" placeholder counts as not set. case "${DATAFOG_DATA_DIR:-}" in '${'*) unset DATAFOG_DATA_DIR ;; esac case "${DATAFOG_VAULT_DIR:-}" in '${'*|'') unset DATAFOG_VAULT_DIR ;; esac +case "${DATAFOG_VAULT_KEY:-}" in '${'*|'') unset DATAFOG_VAULT_KEY ;; esac case "${CLAUDE_PLUGIN_DATA:-}" in '${'*) unset CLAUDE_PLUGIN_DATA ;; esac ROOT=$(CDPATH= cd -- "$(dirname -- "$0")/.." && pwd) || exit 2 @@ -42,6 +43,10 @@ case "$1" in [ -x "$PY" ] || PY="$DATA/venv/Scripts/python.exe" if [ ! -x "$PY" ]; then cat >/dev/null + if UNSUPPORTED=$(sh "$ROOT/scripts/bootstrap.sh" --platform 2>/dev/null); then :; else + printf '{"systemMessage": "%s"}\n' "$UNSUPPORTED" + exit 0 + fi MESSAGE="DataFog guard is NOT protecting this session: its Python environment could not be installed. Tool calls are blocked until it is. To fix it, run this in a terminal: sh '$ROOT/scripts/datafog-guard' --data-dir '$DATA' bootstrap (details: $DATA/log/bootstrap.log)" printf '{"systemMessage": "%s"}\n' "$(printf '%s' "$MESSAGE" | sed 's/\\/\\\\/g; s/"/\\"/g')" exit 0 @@ -59,6 +64,8 @@ if [ ! -x "$PY" ] && [ "$1" = "mcp" ]; then fi if [ ! -x "$PY" ]; then + # One message on a machine the plugin does not support; the call is blocked either way. + sh "$ROOT/scripts/bootstrap.sh" --platform >&2 || exit 2 echo "DataFog guard is not installed yet, so this was blocked to keep data protected. Run: sh '$ROOT/scripts/datafog-guard' --data-dir '$DATA' bootstrap" >&2 exit 2 fi diff --git a/tests/conftest.py b/tests/conftest.py index 71fed11..1d7953d 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -32,6 +32,14 @@ ) +def open_test_vault(directory, entities=None, allowlist=frozenset()): + """A Vault on a throwaway directory, with the key in a file there (never the OS key store).""" + from datafog_guard.config import DEFAULT_ENTITIES + from datafog_guard.store import EncryptedStore + from datafog_guard.vault import Detector, Vault + return Vault(EncryptedStore(str(directory), key_mode="file"), Detector(entities or DEFAULT_ENTITIES, allowlist)) + + def assert_no_sentinel(text: str, where: str = "") -> None: for value in SENTINELS: assert value not in text, f"real value leaked {where}" @@ -50,6 +58,10 @@ def __init__(self, tmp: Path): self.project.mkdir() self.home.mkdir() self.extra_env: dict[str, str] = {} + # The vault key of every test vault is a file in the throwaway vault directory, never the + # operating system's key store. Set the way a user would: in the plugin's config file, + # which the hooks, the Bash runner and the MCP server all read (env() sets it as well). + (self.data / "config.json").write_text(json.dumps({"vault_key": "file"}), encoding="utf-8") def env(self, **extra) -> dict: env = {key: value for key, value in os.environ.items() @@ -57,6 +69,9 @@ def env(self, **extra) -> dict: env.update({ "PYTHONPATH": str(ENGINE), "PYTHONDONTWRITEBYTECODE": "1", "DATAFOG_DATA_DIR": str(self.data), "DATAFOG_VAULT_DIR": str(self.vault), + # Tests never touch the operating system's key store: the vault key is a file in the + # throwaway vault directory. test_keystore.py covers what happens without this. + "DATAFOG_VAULT_KEY": "file", "CLAUDE_PLUGIN_ROOT": str(ROOT), "CLAUDE_PROJECT_DIR": str(self.project), # The hook reads the user's Claude Code settings (~/.claude/settings.json, ~/.claude.json): # tests must never see the real ones. @@ -103,7 +118,7 @@ def trust_project(self) -> None: def seed(self, value: str, entity: str = "ACCOUNT_NUMBER") -> str: """Store one value in the vault as it is and return its marker.""" - return self.open_vault()._commit([(entity, value)])[value] + return seed_values(self.open_vault(), [(entity, value)])[value] def post(self, tool: str, tool_input: dict, tool_response, **env_extra): return self.hook({"hook_event_name": "PostToolUse", "tool_name": tool, "tool_input": tool_input, @@ -113,11 +128,8 @@ def prompt(self, text: str, **env_extra): return self.hook({"hook_event_name": "UserPromptSubmit", "prompt": text, "cwd": str(self.project)}, **env_extra) - def open_vault(self): - from datafog_guard.config import DEFAULT_ENTITIES - from datafog_guard.store import FileVaultStore - from datafog_guard.vault import Detector, Vault - return Vault(FileVaultStore(str(self.vault)), Detector(DEFAULT_ENTITIES)) + def open_vault(self, entities=None, allowlist=frozenset()): + return open_test_vault(self.vault, entities, allowlist) def write(self, name: str, content: str | bytes) -> Path: path = self.project / name @@ -153,8 +165,10 @@ def standin_plugin(box: "Sandbox"): " *) break ;; esac; done\n" f'exec "{sys.executable}" -I "{ENGINE}/run.py" "$@"\n') launcher.chmod(0o755) - saved = {name: os.environ.get(name) for name in ("DATAFOG_DATA_DIR", "DATAFOG_VAULT_DIR", "CLAUDE_PLUGIN_ROOT")} - os.environ.update(DATAFOG_DATA_DIR=str(box.data), DATAFOG_VAULT_DIR=str(box.vault), CLAUDE_PLUGIN_ROOT=str(plugin)) + names = ("DATAFOG_DATA_DIR", "DATAFOG_VAULT_DIR", "DATAFOG_VAULT_KEY", "CLAUDE_PLUGIN_ROOT") + saved = {name: os.environ.get(name) for name in names} + os.environ.update(DATAFOG_DATA_DIR=str(box.data), DATAFOG_VAULT_DIR=str(box.vault), DATAFOG_VAULT_KEY="file", + CLAUDE_PLUGIN_ROOT=str(plugin)) try: settings = config.load() finally: @@ -174,16 +188,29 @@ def box(tmp_path) -> Sandbox: @pytest.fixture(scope="session") def full_vault_dir(tmp_path_factory) -> Path: """A vault filled to core's limit of 20,000 live entries (built once).""" - from datafog_guard.config import DEFAULT_ENTITIES - from datafog_guard.store import FileVaultStore - from datafog_guard.vault import Detector, Vault directory = tmp_path_factory.mktemp("fullvault") / "vault" - vault = Vault(FileVaultStore(str(directory)), Detector(DEFAULT_ENTITIES), recall_required=False) + vault = open_test_vault(directory) for start in range(0, 20_000, 1000): - vault._commit([("ACCOUNT_NUMBER", f"v{number:07d}") for number in range(start, start + 1000)]) + seed_values(vault, [("ACCOUNT_NUMBER", f"v{number:07d}") for number in range(start, start + 1000)]) return directory +def seed_values(vault, pairs) -> dict: + """Store (entity, value) pairs as they are, as a tokenization would. Returns value -> marker.""" + markers = vault._commit(pairs) + vault.store.add_to_index(list(markers.values())) + return markers + + +def corrupt_vault(directory, content: bytes = b"corrupt") -> None: + """Replace the encrypted vault file by something that is not one.""" + directory = Path(directory) + directory.mkdir(mode=0o700, exist_ok=True) + path = directory / "workspace.enc" + path.write_bytes(content) + os.chmod(path, 0o600) + + def copy_vault(source: Path, target: Path) -> None: shutil.copytree(source, target) os.chmod(target, 0o700) diff --git a/tests/live/fake_claude.py b/tests/live/fake_claude.py index 479e448..6cf65fb 100755 --- a/tests/live/fake_claude.py +++ b/tests/live/fake_claude.py @@ -365,6 +365,13 @@ def main(argv): if "--plugin-dir" not in argv: print("LIVE_OK" if "LIVE_OK" in prompt else "ok") return 0 + if "--setting-sources" not in argv or argv[argv.index("--setting-sources") + 1:][:1] != ["project,local"]: + print("fake_claude: live runs must isolate fixture settings with --setting-sources project,local", + file=sys.stderr) + return 2 + if "--strict-mcp-config" in argv: + print("fake_claude: strict MCP config would hide the plugin's own MCP tools", file=sys.stderr) + return 2 return Session(argv[argv.index("--plugin-dir") + 1], prompt).run() diff --git a/tests/live/run-live.command b/tests/live/run-live.command index d376f5c..c5cff49 100755 --- a/tests/live/run-live.command +++ b/tests/live/run-live.command @@ -4,8 +4,14 @@ # # It runs tests/live/run_live.py from this checkout in a fresh temp dir: about 29 short # headless `claude -p` runs against a throwaway project of synthetic files, with a -# temporary vault. Your real vault and plugin data are not touched. Hard caps: 30 runs, -# 180 s each, 30 minutes in total. It uses your Claude Code login and usage. +# temporary vault. Your real vault, your Keychain and your plugin data are not touched: the +# temporary vault keeps its key in a file. Hard caps: 30 runs, 180 s each, 30 minutes in +# total. It uses your Claude Code login and usage. +# +# Optional: LIVE_KEYCHAIN=1 adds one case that stores the key of a second throwaway vault in +# your real Keychain (one new entry, removed again at the end). This is the only way to see +# the Keychain prompts and timing a real user gets. Run it from a terminal: +# LIVE_KEYCHAIN=1 tests/live/run-live.command # # Results are copied to /.live/results/ (results.md first; DONE or ABORTED is the # last file written). Needs: python3, Claude Code 2.1.295+, and uv or Python 3.10+ with diff --git a/tests/live/run_live.py b/tests/live/run_live.py index 8392873..c2c469c 100755 --- a/tests/live/run_live.py +++ b/tests/live/run_live.py @@ -8,11 +8,24 @@ /project throwaway project of synthetic files (claude's working directory) /data the plugin's data dir for this run (private Python env, logs, shadow copies) - /vault a temporary vault, pre-seeded with the fixture values (DATAFOG_VAULT_DIR) + /vault a temporary vault, pre-seeded with the fixture values (DATAFOG_VAULT_DIR). + Its key is a file in that directory (vault_key=file), so the run never + reads or writes your Keychain or any other key store. /log one stream-json transcript per run, results.md, results.json, status.txt -Your real vault and your real plugin data dir are not touched. The plugin is loaded -with --plugin-dir from this checkout; it does not have to be installed. +Your real vault, its key in your key store, and your real plugin data dir are not touched. +The plugin is loaded with --plugin-dir from this checkout; it does not have to be installed. + +Because of that, the default run does NOT cover the path real users take: the vault key in +the macOS Keychain (or the Secret Service on Linux). That is a separate, optional case: + + LIVE_KEYCHAIN=1 tests/live/run-live.command + +It adds case L28-keychain, which creates a second throwaway vault whose key IS stored in your +real key store (one new entry, service "DataFog.ApplicationVault.v1", account +"claude-code/"), uses it from several processes, times it, deletes the vault and +removes that one entry again. It never reads your real vault's entry. macOS may show a +Keychain prompt during this case; that prompt is one of the things the case is there to find. Needs: Python 3.8+ for this script, a logged-in Claude Code 2.1.295 or later, and either uv or Python 3.10+ with network access to PyPI (to build the private environment once). @@ -65,6 +78,20 @@ STATUS_TOOL = "mcp__plugin_datafog_guard__protection_status" TOL = " If a tool is unavailable or a call is denied, say so plainly and continue with the rest." + +def key_store_entry_state(account): + """Check only whether this entry exists; send any secret output straight to /dev/null.""" + if sys.platform == "darwin": + argv = ["/usr/bin/security", "find-generic-password", "-s", "DataFog.ApplicationVault.v1", "-a", account] + missing_code = 44 + elif sys.platform.startswith("linux") and shutil.which("secret-tool"): + argv = ["secret-tool", "lookup", "service", "DataFog.ApplicationVault.v1", "username", account] + missing_code = 1 + else: + return "unavailable" + result = subprocess.run(argv, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, timeout=20) + return "present" if result.returncode == 0 else "absent" if result.returncode == missing_code else "unavailable" + # The synthetic values planted in the fixtures. None may ever reach the model. SENTINELS = { "EMAIL ada": "ada.synthetic@example.com", "EMAIL user02": "user02.synthetic@example.com", @@ -218,7 +245,7 @@ def __init__(self, work, claude): def env(self, **extra): env = {key: value for key, value in os.environ.items() if not key.startswith("DATAFOG_") and key != "CLAUDE_CODE_DISABLE_FILE_MENTIONS"} - env.update({"DATAFOG_DATA_DIR": self.data, "DATAFOG_VAULT_DIR": self.vault}) + env.update({"DATAFOG_DATA_DIR": self.data, "DATAFOG_VAULT_DIR": self.vault, "DATAFOG_VAULT_KEY": "file"}) env.update(extra) return env @@ -298,9 +325,16 @@ def prepare_engine(self): code, _, _ = self.timed(["sh", self.launcher, "--data-dir", self.data, "bootstrap"], 600, stdout=out, stderr=subprocess.STDOUT) python = self.engine_python() + if code == 3: + return "this machine is not supported by the plugin (see log/bootstrap.txt): it needs macOS on " \ + "Apple Silicon, or Linux x86_64 with glibc 2.38 or later" if code != 0 or not python: return "the plugin's Python environment could not be built (see log/bootstrap.txt); " \ "it needs uv or Python 3.10+ and access to PyPI" + # The key of every vault of this run is a file beside it. The config file says so for the + # processes that may not inherit this script's environment (the MCP server). + with open(os.path.join(self.data, "config.json"), "w") as handle: + json.dump({"vault_key": "file"}, handle) seed = ( "import json, os, sys\n" f"sys.path.insert(0, {os.path.join(REPO, 'engine')!r})\n" @@ -309,8 +343,9 @@ def prepare_engine(self): "vault.health()\n" "texts = json.load(sys.stdin)\n" "out, counts = vault.tokenize_many(texts[:-1])\n" - "nasty = vault._commit([('API_KEY', texts[-1])])[texts[-1]]\n" + "nasty = vault._markers_for({texts[-1]: ['API_KEY']})[texts[-1]]\n" "back = vault.restore_spans(nasty)[0][0][3]\n" + "assert vault.health()['protection'] == 'file_key', 'the live run must not use the key store'\n" "print(json.dumps({'tokenized': out, 'counts': counts, 'entries': vault.entry_counts(),\n" " 'entities': list(settings.entities), 'nasty': nasty, 'nasty_ok': back == texts[-1]}))\n") texts = [] @@ -333,7 +368,7 @@ def prepare_engine(self): with open(os.path.join(self.log, "seed.json"), "w") as handle: json.dump({"entries": seeded["entries"], "entities": seeded["entities"]}, handle, indent=2) shutil.copytree(self.vault, self.broken_vault) - with open(os.path.join(self.broken_vault, "HEAD"), "w") as handle: + with open(os.path.join(self.broken_vault, "workspace.enc"), "w") as handle: handle.write("{ deliberately corrupted for the fail-closed case") return None @@ -353,10 +388,13 @@ def run(self, case, prompt, env=None, flags=None, mode="acceptEdits"): safe = re.sub(r"[^A-Za-z0-9._-]", "_", case) path = os.path.join(self.log, "runs", "%s-%s.jsonl" % (number, safe)) env = dict(env or {}) + # Keep real auth/Home, but load only the fixture settings: unrelated user hooks can fail + # or interfere with DataFog startup. Plugin MCP still loads normally. argv = [self.claude, "-p", prompt + " [case:%s]" % case, "--plugin-dir", REPO, "--debug-file", os.path.join(self.log, "debug", number + ".log"), "--output-format", "stream-json", "--verbose", "--max-turns", "12", - "--permission-mode", mode] + (self.extra_flags if flags is None else flags) + \ + "--permission-mode", mode, "--setting-sources", "project,local"] + \ + (self.extra_flags if flags is None else flags) + \ ["--tools", "Read,Write,Edit,Bash,Grep,Glob,Agent", "--allowedTools"] + self.allowed_tools() if os.environ.get("LIVE_MODEL"): argv += ["--model", os.environ["LIVE_MODEL"]] @@ -851,7 +889,7 @@ def broken_mid_session(run, events): if result["name"] == "Bash" and not after: after = True denied = [e for e in events if e.get("event") == "PreToolUse" and e.get("decision") == "deny"] - with open(os.path.join(self.mid_vault, "HEAD")) as handle: + with open(os.path.join(self.mid_vault, "workspace.enc"), errors="replace") as handle: corrupted = handle.read().startswith("corrupt") return [ ("the vault was corrupted during the session", "PASS" if corrupted else "FAIL", @@ -865,13 +903,104 @@ def broken_mid_session(run, events): self.mid_vault = os.path.join(self.work, "vault-mid") shutil.rmtree(self.mid_vault, ignore_errors=True) shutil.copytree(self.vault, self.mid_vault) - self.break_script = "printf 'corrupt' > %s\n" % shlex.quote(os.path.join(self.mid_vault, "HEAD")) + self.break_script = "printf 'corrupt' > %s\n" % shlex.quote(os.path.join(self.mid_vault, "workspace.enc")) self.case("L17-engine-breaks-mid-session", "When the vault breaks mid-session, later tool calls are refused", "Make three tool calls in this order, and make each one even if an earlier one fails. First run " "`sh break-step.sh` with Bash. Then use the Read tool on notes.txt. Then run `cat config.env` " "with Bash. Finally tell me exactly what each call returned.", broken_mid_session, env={"DATAFOG_VAULT_DIR": self.mid_vault}) + # -- the optional key store case --------------------------------------------------- + def keychain_case(self): + """L28, only with LIVE_KEYCHAIN=1. The one case that uses the real OS key store. + + A second throwaway vault, key mode "keystore". No `claude -p` run: the engine is driven + directly, as hooks would. Whatever happens, the vault is purged at the end, which removes + the single key store entry this case created.""" + title = "OPTIONAL: the vault key in the real OS key store (Keychain / Secret Service)" + vault = os.path.join(self.work, "vault-keychain") + env = self.env(DATAFOG_VAULT_DIR=vault, DATAFOG_VAULT_KEY="keystore") + python = self.engine_python() + engine = os.path.join(REPO, "engine", "run.py") + checks = [] + account = None + + def engine_run(*argv, stdin=b""): + started = time.time() + result = subprocess.run([python, "-I", engine, *argv], input=stdin, capture_output=True, env=env, + cwd=self.project, timeout=180) + return result, time.time() - started + + def hook(payload): + result, seconds = engine_run("hook", stdin=json.dumps(payload).encode()) + if result.returncode: + raise RuntimeError("hook exited with code %d" % result.returncode) + try: + return json.loads(result.stdout or b"null"), seconds + except ValueError: + return None, seconds + try: + first, seconds = hook({"hook_event_name": "SessionStart", "source": "startup"}) + line = (first or {}).get("systemMessage", "") + checks.append(("first start creates the vault and its key store entry without failing", + "PASS" if "DataFog guard: on" in line and "system key store" in line else "FAIL", + "%.1f s (includes any Keychain prompt you had to answer); %s" % (seconds, line[:160]))) + with open(os.path.join(vault, "workspace.enc"), "rb") as handle: + header = handle.read(512) + end = 13 + header[12] + if header[:8] != b"DFAPP001" or header[13:end] != b"claude-code" or len(header) < end + 57 \ + or header[end + 56] != 1: + raise RuntimeError("the vault has no credential-store envelope") + account = "claude-code/" + header[end:end + 16].hex() + checks.append(("the new vault's key store entry exists", "PASS" if + key_store_entry_state(account) == "present" else "FAIL", "")) + status, _ = engine_run("status") + text = status.stdout.decode(errors="replace") + checks.append(("status reports the key store as the key's home", "PASS" if "key is in the operating " + "system's key store" in text else "FAIL", "")) + checks.append(("no key file lies beside the vault", "PASS" if not os.path.exists( + os.path.join(vault, "workspace.key")) else "FAIL", ", ".join(sorted(os.listdir(vault))))) + email = "keychain.synthetic@example.com" + post = {"hook_event_name": "PostToolUse", "tool_name": "Bash", "tool_input": {"command": "x"}, + "tool_response": {"stdout": "contact %s\n" % email, "stderr": "", "interrupted": False, + "isImage": False, "noOutputExpected": False}, "cwd": self.project} + out, _ = hook(post) + stdout = ((out or {}).get("hookSpecificOutput") or {}).get("updatedToolOutput", {}).get("stdout", "") + checks.append(("a second process opens the vault with the stored key and tokenizes", + "PASS" if "[[EMAIL_" in stdout and email not in stdout else "FAIL", "")) + timings = [] + same = bool(MARKER.search(stdout)) + for _ in range(15): + again, seconds = hook(post) + timings.append(seconds) + same = same and (((again or {}).get("hookSpecificOutput") or {}).get( + "updatedToolOutput", {}).get("stdout") == stdout) + timings.sort() + checks.append(("fifteen more hook processes get the same marker (no prompt each time?)", + "PASS" if same else "FAIL", "")) + checks.append(("wall time of one PostToolUse hook process with the key from the key store", "INFO", + "p50 %.0f ms, max %.0f ms over 15 runs" % (1000 * timings[7], 1000 * timings[-1]))) + raw = b"".join(open(os.path.join(vault, name), "rb").read() for name in os.listdir(vault)) + checks.append(("the address is not readable anywhere in the vault directory", + "PASS" if email.encode() not in raw else "FAIL", "")) + except Exception as error: + checks.append(("the key store case ran to the end", "FAIL", "%r" % (error,))) + finally: + try: + purge, _ = engine_run("purge", "--confirm", "DELETE-VAULT") + text = purge.stdout.decode(errors="replace") + removed = purge.returncode == 0 and not os.path.lexists(os.path.join(vault, "workspace.enc")) \ + and not os.path.lexists(os.path.join(vault, "workspace.key")) + checks.append(("purge removed the vault and its key store entry", "PASS" if removed and account + and key_store_entry_state(account) == "absent" else "FAIL", + text.strip().replace("\n", " ")[:300])) + except Exception as error: + checks.append(("purge removed the vault and its key store entry", "FAIL", "%r" % (error,))) + self.report.append(("L28-keychain", title, checks, None)) + for name, status, detail in checks: + if status == "FAIL": + say(" FAIL: %s%s" % (name, " (%s)" % detail if detail else "")) + # -- reporting ----------------------------------------------------------------- def latency(self): buckets = {} @@ -965,7 +1094,8 @@ def main(self): say("[probe] is claude authenticated?") path = os.path.join(self.log, "runs", "00-probe-auth.txt") with open(path, "wb") as out_file: - code, _, _ = self.timed([self.claude, "-p", "Reply with exactly: LIVE_OK", "--max-turns", "1"], 90, + code, _, _ = self.timed([self.claude, "-p", "Reply with exactly: LIVE_OK", "--max-turns", "1", + "--setting-sources", "project,local"], 90, cwd=self.project, env=self.env(DATAFOG_VAULT_DIR=self.vault), stdout=out_file, stderr=subprocess.STDOUT) with open(path, encoding="utf-8", errors="replace") as handle: @@ -998,6 +1128,9 @@ def main(self): try: self.cases() + if os.environ.get("LIVE_KEYCHAIN") == "1": + say("[L28-keychain] optional: using the real OS key store for a second throwaway vault") + self.keychain_case() except Exception as error: # keep whatever was collected and say why it stopped import traceback frame = traceback.extract_tb(error.__traceback__)[-1] diff --git a/tests/test_bash_boundary.py b/tests/test_bash_boundary.py index 8afb3ef..00bf3b9 100644 --- a/tests/test_bash_boundary.py +++ b/tests/test_bash_boundary.py @@ -16,7 +16,7 @@ import time import pytest -from conftest import EMAIL, ENGINE, NOTES, ROOT, SSN, assert_no_sentinel +from conftest import EMAIL, ENGINE, NOTES, ROOT, SSN, assert_no_sentinel, corrupt_vault SHELLS = [shell for shell in ("bash", "zsh") if shutil.which(shell)] LINUX_PROC = os.path.isdir("/proc/self/fd") @@ -185,7 +185,9 @@ def run_as_unprivileged_user(box, command: str) -> str: path = box.tmp while path.parent != path: try: - os.chmod(path, os.stat(path).st_mode | 0o011) + # Search AND read: core's ApplicationVault opens every directory above the vault to flush + # it, and fails where the user may not list one (test_store.py pins that limit). + os.chmod(path, os.stat(path).st_mode | 0o055) except OSError: pass path = path.parent @@ -307,7 +309,7 @@ def test_variables_and_functions_do_not_persist(hooked): def test_command_does_not_run_unless_the_filter_is_healthy(hooked): command = hooked.command(f"touch {hooked.box.tmp}/ran; echo {EMAIL}") - (hooked.box.vault / "HEAD").write_text("corrupt") + corrupt_vault(hooked.box.vault) result = subprocess.run([hooked.shell, "-c", command], capture_output=True, cwd=hooked.box.project, env={"PATH": os.environ["PATH"], "HOME": str(hooked.box.tmp)}) assert result.returncode == 125 and not (hooked.box.tmp / "ran").exists() diff --git a/tests/test_bash_permissions.py b/tests/test_bash_permissions.py index 141e9f6..0fd0899 100644 --- a/tests/test_bash_permissions.py +++ b/tests/test_bash_permissions.py @@ -1201,6 +1201,40 @@ def test_wildcard_allow_rules_do_not_approve_test_or_printf_forms_that_evaluate_ assert decide(command, broad, cwd="/work/p").outcome == "allow", command +@pytest.mark.parametrize("prefix,suffix", [("printf %d", ""), ("printf %f", ""), + ("printf '%*s'", " x"), ("exit", ""), ("test -v", "")]) +def test_quoted_arithmetic_cannot_bypass_restrictive_rules(tmp_path, prefix, suffix): + command = f"{prefix} 'path[$(touch {tmp_path / 'executed'})]'{suffix}" + for restrictive in (rules(allow=["Bash"], deny=["Bash(touch *)"]), + rules(allow=[f"Bash({command})"], ask=["Bash(touch *)"])): + got = [decide(command, restrictive, mode=mode, cwd=str(tmp_path)) for mode in MODES] + assert [verdict.outcome for verdict in got] == ["ask", "ask", "ask", "ask", "deny", "ask"] + for mode in ("default", "acceptEdits"): + assert decide(command, rules(allow=["Bash"]), mode=mode, cwd=str(tmp_path)).outcome == "ask" + expected = "ask" if "*" in command else "allow" # a literal * cannot make an exact permission rule + assert decide(command, rules(allow=[f"Bash({command})"]), mode=mode, cwd=str(tmp_path)).outcome == expected + + +def test_zsh_executes_quoted_printf_and_exit_arithmetic(tmp_path): + """Exercise the shell behavior behind the deny-rule regression with its existing `path` array.""" + zsh = shutil.which("zsh") + if not zsh: + pytest.skip("zsh is not installed") + sentinel = tmp_path / "executed" + for prefix in ("printf %d", "exit"): + command = f"{prefix} 'path[$(touch {sentinel})]'" + subprocess.run([zsh, "-f", "-c", command], capture_output=True, text=True, check=False) + assert sentinel.exists(), prefix + sentinel.unlink() + + +def test_printf_text_formats_and_numeric_literals_still_follow_allow_rules(): + found = rules(allow=["Bash"], deny=["Bash(touch *)"]) + for command in ("printf '%s' 'path[$(touch PWNED)]'", "printf '%%d%s' text", + "printf '%10.4s' text", "printf %d 7", "printf %f -1.25", "exit 0"): + assert decide(command, found, cwd="/work/p").outcome == "allow", command + + def test_many_directories_and_suffix_words_stay_fast_and_ask(tmp_path): """Review: `ls <7 directories> <19 KB of colon-suffix words>` took 2-5 s (words x suffixes x bases x rules x realpath). The product is bounded; past the bound the command is not cleared: firm ask.""" diff --git a/tests/test_bash_wrap.py b/tests/test_bash_wrap.py index 1c69a6a..7e1147e 100644 --- a/tests/test_bash_wrap.py +++ b/tests/test_bash_wrap.py @@ -7,7 +7,7 @@ import sys import pytest -from conftest import API_KEY, CARD, EMAIL, ENGINE, NOTES, PHONE, ROOT, SSN, assert_no_sentinel +from conftest import API_KEY, CARD, EMAIL, ENGINE, NOTES, PHONE, ROOT, SSN, assert_no_sentinel, corrupt_vault from datafog_guard import bashwrap, config SHELLS = [shell for shell in ("bash", "zsh") if shutil.which(shell)] @@ -198,7 +198,7 @@ def test_exit_inside_the_command(same): def test_filter_that_cannot_start_means_the_command_does_not_run(same): marker = same.box.tmp / "ran" same.box.vault.mkdir() - (same.box.vault / "HEAD").write_text("corrupt") + corrupt_vault(same.box.vault) result = same.run(f"touch {marker}; echo {EMAIL}") assert result.returncode == 125 and not marker.exists(), "fail closed: the command must not have run" assert result.stdout == b"" and b"command was not run" in result.stderr diff --git a/tests/test_cli_and_plugin.py b/tests/test_cli_and_plugin.py index 6c90ad0..c5d69bb 100644 --- a/tests/test_cli_and_plugin.py +++ b/tests/test_cli_and_plugin.py @@ -7,19 +7,20 @@ import subprocess import pytest -from conftest import EMAIL, NOTES, ROOT, assert_no_sentinel -from datafog_guard import CORE_REQUIREMENT, config +from conftest import EMAIL, NOTES, ROOT, assert_no_sentinel, corrupt_vault +from datafog_guard import CORE_REQUIREMENT, VAULT_REQUIREMENT, config def text_of(result) -> str: return result.stdout.decode() + result.stderr.decode() -def test_status_names_types_counts_and_the_missing_encryption(box): +def test_status_names_types_counts_and_how_the_vault_is_encrypted(box): box.open_vault().tokenize(NOTES) out = text_of(box.run("status")) assert "Protection: ON" in out and "Values held in the vault: 5" in out and "1 EMAIL" in out - assert "encryption at rest: NONE" in out and str(box.vault) in out and "set by DATAFOG_VAULT_DIR" in out + assert "encryption at rest: encrypted, but the key is a file beside the data" in out + assert str(box.vault) in out and "set by DATAFOG_VAULT_DIR" in out and "WARNING" not in out assert "Not detected: names of people" in out assert_no_sentinel(out) @@ -48,13 +49,49 @@ def test_purge_needs_the_confirmation_word(box): assert_no_sentinel(text_of(first) + text_of(done)) +@pytest.mark.skipif(os.geteuid() == 0, reason="root can unlink files in a read-only directory") +def test_purge_command_fails_when_the_vault_cannot_be_deleted(box): + marker = box.open_vault().tokenize(EMAIL)[0] + box.vault.chmod(0o500) + try: + result = box.run("purge", "--confirm", "DELETE-VAULT") + assert result.returncode == 1 and "could not be deleted" in text_of(result) + assert "The vault was deleted." not in text_of(result) + assert (box.vault / "workspace.enc").exists() and (box.vault / "workspace.key").exists() + finally: + box.vault.chmod(0o700) + assert box.open_vault().restore(marker).text == EMAIL + + +def test_purge_command_fails_when_the_key_store_entry_remains(box, monkeypatch, capsys): + from datafog_guard import cli, engine + from datafog_guard.store import EncryptedStore + settings = load(monkeypatch, box.tmp, DATAFOG_DATA_DIR=str(box.data), DATAFOG_VAULT_DIR=str(box.vault)) + monkeypatch.setattr(config, "load", lambda: settings) + store = EncryptedStore(str(box.vault), key_mode="file") + monkeypatch.setattr(engine, "open_store", lambda settings: store) + monkeypatch.setattr(store, "purge", lambda: {"existed": True, "legacy": False, "keystore": "left", + "account": "claude-code/synthetic-test-account"}) + assert cli.purge(["--confirm", "DELETE-VAULT"]) == 1 + assert "key could not be removed" in capsys.readouterr().out + + +def test_purge_command_can_remove_a_fifo_in_place_of_the_vault(box): + box.vault.mkdir(mode=0o700) + os.mkfifo(box.vault / "workspace.enc", mode=0o600) + result = box.run("purge", "--confirm", "DELETE-VAULT") + assert result.returncode == 0 and "The vault was deleted" in text_of(result) + assert not (box.vault / "workspace.enc").exists() + + def test_doctor_reports_each_check_and_fails_on_a_broken_vault(box): out = text_of(box.run("doctor")) for line in ("[ok ] Python 3.10 or later", "[ok ] detector library", "[ok ] tokenize and restore round trip", - "[ok ] vault directory is owner-only", "[note] vault encryption at rest: none"): + "[ok ] vault directory is owner-only", "[ok ] vault files are owner-only", "[ok ] vault library", + "[ok ] supported machine", "[note] vault encryption at rest: encrypted, but the key is a file"): assert line in out, out assert_no_sentinel(out) - (box.vault / "HEAD").write_text("corrupt") + corrupt_vault(box.vault) broken = box.run("doctor") assert broken.returncode == 1 and "[FAIL] vault and detector: vault_corrupt" in text_of(broken) @@ -148,7 +185,7 @@ def test_every_hook_entry_blocks_on_failure_and_uses_the_launcher(): def test_manifests(): plugin = json.loads((ROOT / ".claude-plugin" / "plugin.json").read_text()) - assert plugin["name"] == "datafog" and plugin["version"] == "0.2.0-dev" + assert plugin["name"] == "datafog" and plugin["version"] == "0.2.0" options = plugin["userConfig"] assert options["keep_vault_on_uninstall"]["type"] == "boolean" and options["keep_vault_on_uninstall"]["default"] is True assert options["unscannable_file_policy"]["options"] == ["ask", "deny", "allow"] @@ -170,9 +207,14 @@ def test_commands_exist_and_purge_cannot_be_invoked_by_the_model(): def test_dependency_pin_is_the_same_everywhere(): - assert CORE_REQUIREMENT == "datafog-core>=1.4.0,<1.5" - assert f"REQUIREMENT='{CORE_REQUIREMENT}'" in (ROOT / "scripts" / "bootstrap.sh").read_text() - assert f'"{CORE_REQUIREMENT}"' in (ROOT / "pyproject.toml").read_text() + assert CORE_REQUIREMENT == "datafog-core>=1.7.0,<1.8" + assert VAULT_REQUIREMENT == "datafog-fogvault>=1.7.0,<1.8" + bootstrap = (ROOT / "scripts" / "bootstrap.sh").read_text() + assert f"CORE_REQUIREMENT='{CORE_REQUIREMENT}'" in bootstrap and f"VAULT_REQUIREMENT='{VAULT_REQUIREMENT}'" in bootstrap + project = (ROOT / "pyproject.toml").read_text() + assert f'"{CORE_REQUIREMENT}"' in project and f'"{VAULT_REQUIREMENT}"' in project + workflow = (ROOT / ".github" / "workflows" / "ci.yml").read_text() + assert f'"{CORE_REQUIREMENT}" "{VAULT_REQUIREMENT}"' in workflow def test_launcher_ignores_modules_in_the_working_directory(): @@ -201,10 +243,10 @@ def test_shell_scripts_parse(): assert subprocess.run([shell, "-n", str(ROOT / "scripts" / "wrap.sh")]).returncode == 0 -def test_engine_has_no_third_party_imports_besides_core(): +def test_engine_has_no_third_party_imports_besides_core_and_its_vault(): import ast import sys - allowed = set(sys.stdlib_module_names) | {"datafog_core", "datafog_guard"} + allowed = set(sys.stdlib_module_names) | {"datafog_core", "datafog_fogvault", "datafog_guard"} for path in (ROOT / "engine" / "datafog_guard").glob("*.py"): for node in ast.walk(ast.parse(path.read_text())): names = [] @@ -233,7 +275,7 @@ def test_hook_start_up_does_not_import_heavy_modules(box): @pytest.mark.skipif(os.environ.get("DATAFOG_TEST_NETWORK") != "1", reason="set DATAFOG_TEST_NETWORK=1 to run") def test_bootstrap_installs_once_and_the_launcher_then_works(box): launcher = ["sh", str(ROOT / "scripts" / "datafog-guard"), "--data-dir", str(box.data), "--vault-dir", str(box.vault)] - env = {"PATH": os.environ["PATH"], "HOME": str(box.tmp)} + env = {"PATH": os.environ["PATH"], "HOME": str(box.tmp), "DATAFOG_VAULT_KEY": "file"} # no OS key store in tests for name in ("HTTPS_PROXY", "https_proxy", "SSL_CERT_FILE", "UV_NATIVE_TLS", "REQUESTS_CA_BUNDLE", "PIP_CERT", "UV_SYSTEM_CERTS"): if name in os.environ: @@ -243,7 +285,7 @@ def test_bootstrap_installs_once_and_the_launcher_then_works(box): out = json.loads(first.stdout) assert "DataFog guard: on" in out["systemMessage"], (box.data / "log" / "bootstrap.log").read_text() stamp = box.data / "venv" / ".datafog-installed" - assert stamp.read_text() == CORE_REQUIREMENT + assert stamp.read_text() == f"{CORE_REQUIREMENT} {VAULT_REQUIREMENT}" before = stamp.stat().st_mtime_ns import time started = time.time() @@ -262,7 +304,8 @@ def test_session_start_without_any_way_to_install_says_what_to_run(box): payload = json.dumps({"hook_event_name": "SessionStart", "source": "startup"}).encode() empty = box.tmp / "emptybin" empty.mkdir() - for tool in ("sh", "cat", "mkdir", "chmod", "find", "rmdir", "rm", "date", "sed", "printf", "dirname", "sleep"): + for tool in ("sh", "cat", "mkdir", "chmod", "find", "rmdir", "rm", "date", "sed", "printf", "dirname", "sleep", + "uname", "getconf"): found = shutil.which(tool) if found: (empty / tool).symlink_to(found) diff --git a/tests/test_concurrency.py b/tests/test_concurrency.py index d33c80e..7aaef7b 100644 --- a/tests/test_concurrency.py +++ b/tests/test_concurrency.py @@ -1,54 +1,60 @@ -"""Many short-lived processes plus a long-lived one on the same vault, and crashes mid-commit.""" +"""Many short-lived processes plus a long-lived one on the same vault, and processes killed mid-way. + +Hooks are separate short processes that may run in parallel; the MCP server and the Bash runner +live longer. All of them share one encrypted vault file and one marker index.""" from __future__ import annotations import json +import os +import random +import signal import subprocess import sys import textwrap +import time + +from conftest import EMAIL, ENGINE, ROOT -from conftest import EMAIL, ENGINE +OPEN = textwrap.dedent(""" + import json, os, sys, time + sys.path.insert(0, sys.argv.pop(1)) + from conftest import open_test_vault +""") -WORKER = textwrap.dedent(""" - import json, sys - from datafog_guard.config import DEFAULT_ENTITIES - from datafog_guard.store import FileVaultStore - from datafog_guard.vault import Detector, Vault +WORKER = OPEN + textwrap.dedent(""" vault_dir, worker, rounds = sys.argv[1], int(sys.argv[2]), int(sys.argv[3]) pairs = [] for number in range(rounds): - # a new Vault object each round, like a new hook process - vault = Vault(FileVaultStore(vault_dir), Detector(DEFAULT_ENTITIES)) + vault = open_test_vault(vault_dir) # a new Vault object each round, like a new hook process unique = f"w{worker}n{number}.synthetic@example.com" shared = f"shared{number % 10}.synthetic@example.com" text = f"{unique} {shared}" out, counts = vault.tokenize(text) assert "@" not in out + assert vault.restore(out).text == text pairs.append([out, text]) + vault.store.close() print(json.dumps(pairs)) """) -RESTORER = textwrap.dedent(""" - import json, sys, time - from datafog_guard.config import DEFAULT_ENTITIES - from datafog_guard.store import FileVaultStore - from datafog_guard.vault import Detector, Vault - vault = Vault(FileVaultStore(sys.argv[1]), Detector(DEFAULT_ENTITIES)) # long-lived, like the MCP server +RESTORER = OPEN + textwrap.dedent(""" + vault = open_test_vault(sys.argv[1]) # long-lived, like the MCP server marker = vault.tokenize("seed.synthetic@example.com")[0] - reloads, seen, checks = 0, None, 0 + sizes, checks = set(), 0 deadline = time.time() + float(sys.argv[2]) while time.time() < deadline: assert vault.restore(marker).text == "seed.synthetic@example.com" + assert vault.tokenize("seed.synthetic@example.com")[0] == marker + sizes.add(sum(vault.entry_counts().values())) checks += 1 - if vault._head != seen: - reloads += 1 - seen = vault._head - print(json.dumps({"checks": checks, "reloads": reloads})) + print(json.dumps({"checks": checks, "sizes": len(sizes)})) """) def spawn(script: str, *args) -> subprocess.Popen: - return subprocess.Popen([sys.executable, "-c", script, *map(str, args)], stdout=subprocess.PIPE, - stderr=subprocess.PIPE, text=True, env={"PYTHONPATH": str(ENGINE), "PATH": "/usr/bin:/bin"}) + return subprocess.Popen([sys.executable, "-c", script, str(ROOT / "tests"), *map(str, args)], + stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, + env={"PYTHONPATH": str(ENGINE), "PATH": "/usr/bin:/bin", "PYTHONDONTWRITEBYTECODE": "1"}) def test_eight_processes_times_one_hundred_prepares_with_a_concurrent_restorer(box): @@ -57,13 +63,13 @@ def test_eight_processes_times_one_hundred_prepares_with_a_concurrent_restorer(b processes = [spawn(WORKER, box.vault, worker, rounds) for worker in range(workers)] results = [] for process in processes: - out, err = process.communicate(timeout=300) + out, err = process.communicate(timeout=600) assert process.returncode == 0, err[-2000:] results.extend(json.loads(out)) - out, err = restorer.communicate(timeout=60) + out, err = restorer.communicate(timeout=120) assert restorer.returncode == 0, err[-2000:] observed = json.loads(out) - assert observed["checks"] > 0 and observed["reloads"] > 1, "the long-lived process must notice new heads" + assert observed["checks"] > 0 and observed["sizes"] > 1, "the long-lived process must see other processes' values" assert len(results) == workers * rounds vault = box.open_vault() # a fresh process sees every marker: nothing was lost @@ -75,70 +81,107 @@ def test_eight_processes_times_one_hundred_prepares_with_a_concurrent_restorer(b assert len(set(marker_of.values())) == len(marker_of) == workers * rounds + 10 + 0 assert vault.entry_counts() == {"EMAIL": workers * rounds + 10 + 1} # + the restorer's seed value vault.health() - - -CRASH_AFTER_SAVE = textwrap.dedent(""" - import os, sys - from datafog_guard.config import DEFAULT_ENTITIES - from datafog_guard.store import FileVaultStore - from datafog_guard.vault import Detector, Vault - - class DiesAfterSave(FileVaultStore): - def compare_and_save(self, expected, new, bundle, annotations): - saved = super().compare_and_save(expected, new, bundle, annotations) - if expected is not None: - os._exit(137) # killed after the save, before activate and before any text is released - return saved - - vault = Vault(DiesAfterSave(sys.argv[1]), Detector(DEFAULT_ENTITIES)) - out, _ = vault.tokenize(sys.argv[2]) - print(out) # never reached + # every value is known without asking core to write again: tokenizing them all changes nothing + from datafog_guard.store import read_envelope_header + before = read_envelope_header(str(box.vault))["revision"] + out, _ = vault.tokenize(" ".join(marker_of)) + assert out.split() == list(marker_of.values()) + assert read_envelope_header(str(box.vault))["revision"] == before + + +def test_parallel_hook_processes_through_the_real_entry_point(box): + """Twelve PostToolUse hooks at once, as Claude Code starts them for parallel tool calls.""" + import shapes_recorded as recorded + payloads = [] + for number in range(12): + text = f"row {number} user{number}.synthetic@example.com and {EMAIL}\n" + payloads.append(json.dumps({"hook_event_name": "PostToolUse", "tool_name": "Bash", "tool_input": {"command": "x"}, + "tool_response": recorded.bash(stdout=text), "cwd": str(box.project)})) + running = [subprocess.Popen([sys.executable, "-m", "datafog_guard", "hook"], stdin=subprocess.PIPE, + stdout=subprocess.PIPE, stderr=subprocess.PIPE, env=box.env(), cwd=box.project) + for _ in payloads] + outputs = [process.communicate(payload.encode(), timeout=120) for process, payload in zip(running, payloads)] + shared = set() + vault = box.open_vault() + for number, (out, err) in enumerate(outputs): + stdout = json.loads(out)["hookSpecificOutput"]["updatedToolOutput"]["stdout"] + assert "@" not in stdout, err + assert vault.restore(stdout).text == f"row {number} user{number}.synthetic@example.com and {EMAIL}\n" + shared.add(stdout.split()[-1]) + assert len(shared) == 1, "the shared value has one marker in all twelve processes" + assert vault.entry_counts() == {"EMAIL": 13} + + +DIES_AFTER_COMMIT = OPEN + textwrap.dedent(""" + vault = open_test_vault(sys.argv[1]) + real = vault.store.commit + def commit(pairs): + real(pairs) + os._exit(137) # killed after core saved the markers: before the index is written and before any text is released + vault.store.commit = commit + print(vault.tokenize(sys.argv[2])[0]) # never reached """) -CRASH_BEFORE_COMMIT_POINT = textwrap.dedent(""" - import os, sys - import datafog_guard.store as store_module - from datafog_guard.config import DEFAULT_ENTITIES - from datafog_guard.vault import Detector, Vault - - real_replace = os.replace - def replace(source, target): - if os.path.basename(target) == "HEAD" and os.path.exists(target): - os._exit(137) # snapshot file written, pointer not yet switched - return real_replace(source, target) - store_module.os.replace = replace - - vault = Vault(store_module.FileVaultStore(sys.argv[1]), Detector(DEFAULT_ENTITIES)) - print(vault.tokenize(sys.argv[2])[0]) +DIES_BEFORE_INDEX = OPEN + textwrap.dedent(""" + vault = open_test_vault(sys.argv[1]) + vault.store.add_to_index = lambda markers: os._exit(137) # markers saved and checked, index not written + print(vault.tokenize(sys.argv[2])[0]) # never reached """) -def test_kill_between_save_and_activate(box): +def test_kill_between_commit_and_release(box): vault = box.open_vault() before, _ = vault.tokenize(f"first {EMAIL}") - crashed = spawn(CRASH_AFTER_SAVE, box.vault, "second bob.synthetic@example.com") - out, err = crashed.communicate(timeout=60) - assert crashed.returncode == 137 and out == "", "no text may be released by the crashed process" - + for script in (DIES_AFTER_COMMIT, DIES_BEFORE_INDEX): + crashed = spawn(script, box.vault, "second bob.synthetic@example.com") + out, err = crashed.communicate(timeout=60) + assert crashed.returncode == 137 and out == "", "no text may be released by the crashed process" survivor = box.open_vault() survivor.health() # the vault is intact assert survivor.restore(before).text == f"first {EMAIL}" + assert survivor.entry_counts() == {"EMAIL": 1}, "the index does not know the value the dead process stored" again, _ = survivor.tokenize("second bob.synthetic@example.com") assert survivor.restore(again).text == "second bob.synthetic@example.com" - assert survivor.entry_counts() == {"EMAIL": 2}, "the saved entry is reused, not duplicated" + assert box.open_vault().entry_counts() == {"EMAIL": 2}, "the saved entry is reused and noted, not duplicated" + assert box.open_vault().tokenize("second bob.synthetic@example.com")[0] == again + + +LOOP = OPEN + textwrap.dedent(""" + number = 0 + while True: + vault = open_test_vault(sys.argv[1]) + text = f"k{sys.argv[2]}n{number}.synthetic@example.com" + out, _ = vault.tokenize(text) + print(json.dumps([out, text]), flush=True) # released: from here on it must restore forever + number += 1 +""") -def test_kill_before_the_commit_point(box): +def test_sigkill_at_random_moments_never_damages_the_vault(box): + """Writers are killed with SIGKILL while they commit. Whatever they released still restores, + the vault still opens, and no temporary file with a value is left behind.""" + rng = random.Random(7) + released = [] + box.open_vault().tokenize(f"first {EMAIL}") + for round_number in range(12): + writers = [spawn(LOOP, box.vault, f"{round_number}x{index}") for index in range(3)] + first = [writer.stdout.readline() for writer in writers] # every writer is past start-up and committing + time.sleep(rng.uniform(0.0, 0.12)) + for writer in writers: + os.kill(writer.pid, signal.SIGKILL) + for line, writer in zip(first, writers): + out, _ = writer.communicate(timeout=30) + released.extend(json.loads(text) for text in (line + out).splitlines() if text.endswith("]")) + assert len(released) > 30 vault = box.open_vault() - before, _ = vault.tokenize(f"first {EMAIL}") - head = json.loads((box.vault / "HEAD").read_text()) - crashed = spawn(CRASH_BEFORE_COMMIT_POINT, box.vault, "second bob.synthetic@example.com") - out, _ = crashed.communicate(timeout=60) - assert crashed.returncode == 137 and out == "" - assert json.loads((box.vault / "HEAD").read_text()) == head, "the old vault is still the vault" - survivor = box.open_vault() - assert survivor.restore(before).text == f"first {EMAIL}" - after, _ = survivor.tokenize("third carl.synthetic@example.com") - assert box.open_vault().restore(after).text == "third carl.synthetic@example.com" - leftovers = [path.name for path in (box.vault / "snapshots").iterdir()] - assert len(leftovers) <= 3, "the orphaned snapshot is cleaned up by later saves" + vault.health() + for tokenized, original in released: + assert vault.restore(tokenized).text == original + assert vault.tokenize(f"first {EMAIL}")[0] == f"first {box.open_vault().tokenize(EMAIL)[0]}" + for path in box.vault.iterdir(): + assert b"synthetic@example.com" not in path.read_bytes(), path.name + leftovers = [path.name for path in box.vault.iterdir() + if path.name not in ("workspace.enc", "workspace.key", "workspace.lock", "markers.index")] + assert len(leftovers) <= 12 * 3, "at most one unfinished temporary file per killed writer" + later, _ = box.open_vault().tokenize("after.synthetic@example.com") + assert box.open_vault().restore(later).text == "after.synthetic@example.com" diff --git a/tests/test_core_behaviour.py b/tests/test_core_behaviour.py new file mode 100644 index 0000000..3a3e341 --- /dev/null +++ b/tests/test_core_behaviour.py @@ -0,0 +1,138 @@ +"""What datafog-core 1.7 finds, seen through the plugin's tokenize path. + +Core 1.5 to 1.7 changed where an e-mail address and a phone number begin and end. These tests +pin the differences from 1.4.0 that matter to the plugin: the ones where less text is replaced +(good: the marker stands for the address only) and the ones where a value that 1.4.0 hid is now +left visible to the model (documented in the README under "Known gaps"). + +Tests named ``..._today`` describe a known limit of core 1.7.0 exactly as it is; they only run +on that version, so an upgrade does not fail on them. Each has a sibling marked ``xfail`` that +states the correct outcome and starts passing when core fixes it. +""" +from __future__ import annotations + +from importlib.metadata import version + +import pytest +from conftest import EMAIL +from datafog_guard.vault import MARKER_RE + +CORE_VERSION = version("datafog-core") +only_core_1_7_0 = pytest.mark.skipif(CORE_VERSION != "1.7.0", + reason="pins the behaviour of datafog-core 1.7.0 exactly") + + +def tokenize(box, text: str) -> tuple[str, list[str]]: + """(tokenized text, the real values the markers stand for, in order).""" + vault = box.open_vault() + out, _ = vault.tokenize(text) + assert vault.restore(out).text == text, "whatever was replaced must restore exactly" + spans, unknown = vault.restore_spans(out) + assert unknown == 0 + return out, [value for _, _, _, value in spans] + + +# -- (a) text joined in front of an address is no longer part of the match ------------------- +@pytest.mark.parametrize("text, before, after", [ + (f"user=ada&email={EMAIL}", "user=ada&email=", ""), + (f"1042|Ada Synthetic|{EMAIL}|active", "1042|Ada Synthetic|", "|active"), + (f"GET /lookup?user=ada&contact={EMAIL}&page=2 HTTP/1.1", "GET /lookup?user=ada&contact=", "&page=2 HTTP/1.1"), + (f"a={EMAIL}&b=1", "a=", "&b=1"), + (f"*{EMAIL}*", "*", "*"), + (f"10.0.0.7:{EMAIL}", "10.0.0.7:", ""), + (f"2026-11-17,{EMAIL}", "2026-11-17,", ""), + (f"see [1].{EMAIL}", "see [1].", ""), +]) +def test_only_the_address_is_replaced_after_a_separator_or_label(box, text, before, after): + out, values = tokenize(box, text) + assert values == [EMAIL] + assert out.startswith(before) and out.endswith(after) + assert MARKER_RE.fullmatch(out[len(before):len(out) - len(after)]) + + +def test_a_phone_in_front_of_an_address_is_its_own_value(box): + out, values = tokenize(box, f"415-555-0134,{EMAIL}") + assert values == ["415-555-0134", EMAIL] + assert out.count("[[PHONE_") == 1 and out.count("[[EMAIL_") == 1 + + +@pytest.mark.parametrize("prefix", ["12345", "415-555-0134", "10.0.0.7", "2026-11-17"]) +def test_digits_written_directly_onto_an_address_stay_hidden_with_it(box, prefix): + """No separator at all: core reads the digits as part of the local part. Nothing is visible.""" + out, values = tokenize(box, f"{prefix}{EMAIL}") + assert EMAIL not in out and "example.com" not in out and "ada.synthetic" not in out + assert len(values) == 1 and values[0].endswith(EMAIL) + + +# -- (b) known issue: https://github.com/DataFog/datafog-core/issues/272 ---------------------- +ISSUE_272 = "alice@example.comとbob@example.net" + + +@only_core_1_7_0 +def test_issue_272_a_non_ascii_letter_between_two_addresses_leaves_a_domain_visible_today(box): + """KNOWN ISSUE (core #272), accepted by the owner and documented in the README. + + A non-ASCII letter that touches an address is absorbed into the match. Between two addresses + this gives ONE value, ``alice@example.comとbob``, and the second address's domain, + ``@example.net``, reaches the model. + """ + out, values = tokenize(box, ISSUE_272) + assert values == ["alice@example.comとbob"] + assert MARKER_RE.fullmatch(out[:-len("@example.net")]) and out.endswith("@example.net") + + +@pytest.mark.xfail(strict=False, reason="datafog-core #272: fixed in core after 1.7.0") +def test_issue_272_both_addresses_are_hidden(box): + out, values = tokenize(box, ISSUE_272) + assert "example.net" not in out and "example.com" not in out and "bob" not in out + assert len(values) == 2 + + +@only_core_1_7_0 +@pytest.mark.parametrize("text, value", [ + (f"連絡先{EMAIL}", f"連絡先{EMAIL}"), + (f"{EMAIL}に送信", f"{EMAIL}に送信"), + (f"é{EMAIL}", f"é{EMAIL}"), +]) +def test_issue_272_a_single_address_stays_hidden_but_takes_the_neighbouring_letters_today(box, text, value): + """Same cause, no leak: the marker covers the address and the non-ASCII letters touching it.""" + out, values = tokenize(box, text) + assert values == [value] and MARKER_RE.fullmatch(out) + + +@pytest.mark.parametrize("text", [f"連絡先 {EMAIL} に送信", f"{EMAIL}。bob.synthetic@example.net", + f"{EMAIL} bob.synthetic@example.net", f"メール:{EMAIL}"]) +def test_addresses_separated_from_other_scripts_by_space_or_punctuation_are_found(box, text): + out, values = tokenize(box, text) + assert "example" not in out and values[0] == EMAIL + + +# -- phone numbers 1.4.0 found and 1.7 does not (documented limits) --------------------------- +@only_core_1_7_0 +@pytest.mark.parametrize("text", [ + "2.415.555.0134", # a dotted number directly after "." reads as a decimal + "ver 10.415.555.0134", + "2,415.5550134", # after "," an unsigned number with exactly one dot + "(415)\n555-0134", # a number wrapped across a line break + "415 555\n0134", +]) +def test_phone_shapes_core_1_7_does_not_report_today(box, text): + """Documented limit: core 1.7 does not report these, core 1.4.0 did. The text passes unchanged.""" + out, values = tokenize(box, text) + assert out == text and values == [] + + +@only_core_1_7_0 +def test_a_plus_number_wrapped_across_a_line_is_hidden_up_to_the_break_today(box): + out, values = tokenize(box, "+44 20 7946\n0958") + assert values == ["+44 20 7946"] and out.endswith("\n0958") + + +@pytest.mark.parametrize("text, value", [ + ("3.415-555-0134", "415-555-0134"), + ("row 2,415-555-0134,ok", "415-555-0134"), + ("1,+1.4155550134", "+1.4155550134"), +]) +def test_phone_shapes_next_to_a_number_that_are_reported(box, text, value): + _, values = tokenize(box, text) + assert values == [value] diff --git a/tests/test_fail_closed.py b/tests/test_fail_closed.py index 5c91763..89cab8d 100644 --- a/tests/test_fail_closed.py +++ b/tests/test_fail_closed.py @@ -11,32 +11,85 @@ import json import os +import sys import pytest import shapes_recorded as recorded -from conftest import EMAIL, NOTES, SENTINELS, assert_no_sentinel, copy_vault +from conftest import EMAIL, NOTES, SENTINELS, assert_no_sentinel, copy_vault, corrupt_vault, open_test_vault from datafog_guard.shapes import WITHHELD -from datafog_guard.store import FileVaultStore +from datafog_guard.store import FileLock from test_hook_protocol import same_shape -def break_corrupt_pointer(box): +def break_corrupt_vault_file(box): box.open_vault().tokenize(EMAIL) - (box.vault / "HEAD").write_text("{ this is not json") + path = box.vault / "workspace.enc" + raw = bytearray(path.read_bytes()) + raw[-20] ^= 0xFF + path.write_bytes(bytes(raw)) -def break_corrupt_snapshot(box): +def break_garbage_vault_file(box): box.open_vault().tokenize(EMAIL) - pointer = json.loads((box.vault / "HEAD").read_text()) - snapshot = box.vault / "snapshots" / pointer["snapshot"] - raw = bytearray(snapshot.read_bytes()) - raw[len(raw) // 2] ^= 0xFF - snapshot.write_bytes(bytes(raw)) + corrupt_vault(box.vault, b"{ this is not a vault " + EMAIL.encode()) + + +def break_wrong_key(box): + box.open_vault().tokenize(EMAIL) + (box.vault / "workspace.key").write_bytes(bytes(range(32))) + + +def break_missing_key(box): + box.open_vault().tokenize(EMAIL) + (box.vault / "workspace.key").unlink() + + +def break_key_store_unavailable(box): + """The default: the key is kept in the OS key store, and there is none to reach. + + Linux only: the Secret Service is looked for on a D-Bus address that does not exist. On macOS + this would talk to the real Keychain, which tests never do.""" + if sys.platform != "linux": + pytest.skip("would use the real Keychain") + box.extra_env.update(DATAFOG_VAULT_KEY="keystore", DBUS_SESSION_BUS_ADDRESS="unix:path=/nonexistent/datafog-test", + XDG_RUNTIME_DIR=str(box.tmp / "no-runtime")) + + +def break_key_setting_does_not_match_the_vault(box): + """A vault made with vault_key=file, opened with the default: refused before any key store is asked.""" + box.open_vault().tokenize(EMAIL) + box.extra_env["DATAFOG_VAULT_KEY"] = "keystore" + + +def break_vault_open_to_others(box): + box.open_vault().tokenize(EMAIL) + os.chmod(box.vault / "workspace.enc", 0o644) + + +def break_vault_directory_is_a_link(box): + real = box.tmp / "elsewhere" + open_test_vault(real).tokenize(EMAIL) + box.vault.symlink_to(real) + + +def break_vault_library_import(box): + fake = box.tmp / "fake" / "datafog_fogvault" + fake.mkdir(parents=True) + (fake / "__init__.py").write_text("raise ImportError('synthetic import failure')\n") + from conftest import ENGINE + box.extra_env["PYTHONPATH"] = f"{box.tmp / 'fake'}{os.pathsep}{ENGINE}" + + +def break_unsupported_machine(box): + """No wheel for this machine: the vault library is not there, and the platform says why.""" + break_vault_library_import(box) + (box.tmp / "fake" / "sitecustomize.py").write_text( + "import platform\nplatform.machine = lambda: 'riscv64'\n") def break_locked(box): box.open_vault().tokenize(EMAIL) - box._lock = FileVaultStore(str(box.vault)).lock() + box._lock = FileLock(str(box.vault / "workspace.lock")) box._lock.__enter__() box.extra_env["DATAFOG_LOCK_TIMEOUT"] = "0.2" @@ -77,23 +130,23 @@ def break_config_not_json(box): (box.data / "config.json").write_text("allowlist: noreply@example.com") -def break_recall_capacity(box): - from datafog_guard.vault import Detector, Vault - filler = Vault(FileVaultStore(str(box.vault)), Detector(("EMAIL",)), recall_required=False) - for start in range(0, 3500, 500): - filler._commit([("API_KEY", f"k{number:07d}" * 12) for number in range(start, start + 500)]) - - BREAKS = { - "corrupt_pointer": break_corrupt_pointer, - "corrupt_snapshot": break_corrupt_snapshot, + "corrupt_vault_file": break_corrupt_vault_file, + "garbage_vault_file": break_garbage_vault_file, + "wrong_key": break_wrong_key, + "missing_key": break_missing_key, + "key_store_unavailable": break_key_store_unavailable, + "key_setting_does_not_match_the_vault": break_key_setting_does_not_match_the_vault, + "vault_open_to_others": break_vault_open_to_others, + "vault_directory_is_a_link": break_vault_directory_is_a_link, + "vault_library_import_failure": break_vault_library_import, + "unsupported_machine": break_unsupported_machine, "locked_vault": break_locked, "detector_import_failure": break_detector_import, "detector_finds_nothing": break_detector_blind, "unwritable_vault": break_unwritable_vault, "unsupported_entity_in_config": break_bad_config, "config_not_json": break_config_not_json, - "vault_past_recall_capacity": break_recall_capacity, } @@ -104,7 +157,7 @@ def broken(box, request): lock = getattr(box, "_lock", None) if lock is not None: lock.__exit__(None, None, None) - if box.vault.is_dir(): + if box.vault.is_dir() and not box.vault.is_symlink(): os.chmod(box.vault, 0o700) diff --git a/tests/test_hook_protocol.py b/tests/test_hook_protocol.py index 192c08f..efc8e1f 100644 --- a/tests/test_hook_protocol.py +++ b/tests/test_hook_protocol.py @@ -183,7 +183,7 @@ def test_pre_read_of_a_clean_file_passes_untouched(box): assert not (box.data / "shadow").exists() -def test_pre_read_uses_recall_for_values_the_detector_misses(box): +def test_pre_read_hides_known_values_the_detector_misses(box): box.open_vault().tokenize("account number 000123456789") path = box.write("bare.txt", "ref 000123456789\n") new = pre_updated(box.pre("Read", {"file_path": str(path)})[0]) @@ -228,7 +228,7 @@ def test_pre_read_unscannable_policy_is_configurable(box, policy, expected): def test_pre_read_of_the_vault_is_denied(box): box.open_vault().tokenize(EMAIL) - out, _ = box.pre("Read", {"file_path": str(box.vault / "HEAD")}) + out, _ = box.pre("Read", {"file_path": str(box.vault / "workspace.enc")}) assert out["hookSpecificOutput"]["permissionDecision"] == "deny" @@ -562,13 +562,16 @@ def test_pre_bash_own_status_command_is_not_wrapped(box): def test_pre_calls_that_reach_into_the_vault_are_denied(box): box.open_vault().tokenize(EMAIL) - for tool, tool_input in [("Bash", {"command": f"cat {box.vault}/snapshots/*"}), - ("Bash", {"command": f"strings '{box.vault}/HEAD' | head"}), + for tool, tool_input in [("Bash", {"command": f"cat {box.vault}/*"}), + ("Bash", {"command": f"strings '{box.vault}/workspace.key' | head"}), + ("Read", {"file_path": str(box.vault / "workspace.key")}), + ("Read", {"file_path": str(box.vault / "markers.index")}), + ("Read", {"file_path": str(box.vault / "bash-restore.key")}), ("Grep", {"pattern": "example", "path": str(box.vault)}), ("Grep", {"pattern": "example", "path": str(box.tmp)}), - ("Glob", {"pattern": "**/*", "path": str(box.vault / "snapshots")}), - ("Write", {"file_path": str(box.vault / "HEAD"), "content": "x"}), - ("Edit", {"file_path": str(box.vault / "meta.json"), "old_string": "a", "new_string": "b"})]: + ("Glob", {"pattern": "**/*", "path": str(box.vault)}), + ("Write", {"file_path": str(box.vault / "workspace.enc"), "content": "x"}), + ("Edit", {"file_path": str(box.vault / "markers.index"), "old_string": "a", "new_string": "b"})]: out, _ = box.pre(tool, tool_input) assert out["hookSpecificOutput"]["permissionDecision"] == "deny", (tool, tool_input) out, _ = box.pre("Grep", {"pattern": "example", "path": str(box.project)}) @@ -706,9 +709,9 @@ def test_session_start_explains_markers_and_reports_status(box): assert needle in context assert len(context) < 10_000 line = out["systemMessage"] - assert "DataFog guard: on" in line and "not encrypted" in line and "EMAIL" in line + assert "DataFog guard: on" in line and "encrypted, key in a file beside it (weaker)" in line and "EMAIL" in line assert "Bash output: filtered" in line and "Markers in Bash commands: ask" in line - assert (box.vault / "HEAD").exists(), "the vault is created at session start" + assert (box.vault / "workspace.enc").exists(), "the vault is created at session start" assert json.loads((box.data / "runtime.json").read_text()) == {"keep_vault_on_uninstall": "true"} diff --git a/tests/test_keystore.py b/tests/test_keystore.py new file mode 100644 index 0000000..003916b --- /dev/null +++ b/tests/test_keystore.py @@ -0,0 +1,160 @@ +"""The default key mode: the vault key in the operating system's key store. + +No test here touches the developer's real key store. On Linux, where the tools are installed, the +cases run against a PRIVATE Secret Service: a throwaway D-Bus session with its own GNOME Keyring +daemon and its own HOME and XDG directories, all inside the test's temp dir. On macOS these cases +are skipped (they would write to the real login Keychain); the Keychain is covered only by the +optional live case L28 (tests/live/run_live.py, LIVE_KEYCHAIN=1). +""" +from __future__ import annotations + +import json +import os +import shutil +import subprocess +import sys +import textwrap + +import pytest +from conftest import EMAIL, ENGINE + +pytestmark = pytest.mark.skipif( + sys.platform != "linux" or not all(shutil.which(tool) for tool in ("dbus-run-session", "gnome-keyring-daemon", + "secret-tool")), + reason="needs Linux with dbus-run-session, gnome-keyring-daemon and secret-tool (a private Secret Service)") + +SESSION = textwrap.dedent(""" + printf 'synthetic-test-password\\n' | gnome-keyring-daemon --unlock --components=secrets >/dev/null 2>&1 + sleep 0.3 + "$@" +""") +PRELUDE = textwrap.dedent(""" + import json, os, subprocess, sys + from datafog_guard.config import DEFAULT_ENTITIES + from datafog_guard.errors import GuardError + from datafog_guard.store import KEYSTORE_SERVICE, EncryptedStore, read_envelope_header + from datafog_guard.vault import Detector, Vault + def vault(directory, mode="keystore"): + return Vault(EncryptedStore(directory, key_mode=mode), Detector(DEFAULT_ENTITIES)) + def entries(): + found = subprocess.run(["secret-tool", "search", "--all", "service", KEYSTORE_SERVICE], capture_output=True) + return sorted(line.split(b" = ")[1].decode() for line in found.stderr.splitlines() + if line.startswith(b"attribute.username")) + def code_of(action): + try: + action() + return "ok" + except GuardError as error: + return error.code + EMAIL = "ada.synthetic@example.com" + base = sys.argv[1] +""") + + +def in_private_key_store(tmp_path, script: str, timeout: int = 120) -> dict: + """Run a Python script inside a throwaway D-Bus session with its own unlocked keyring.""" + root = tmp_path / "keystore-session" + env = {"PATH": os.environ["PATH"], "PYTHONPATH": str(ENGINE), "PYTHONDONTWRITEBYTECODE": "1", + "HOME": str(root / "home")} + for name in ("data", "config", "cache", "run"): + (root / name).mkdir(parents=True, exist_ok=True) + env["XDG_%s_%s" % (name.upper(), "DIR" if name == "run" else "HOME")] = str(root / name) + (root / "home").mkdir(exist_ok=True) + os.chmod(root / "run", 0o700) + result = subprocess.run(["dbus-run-session", "--", "sh", "-c", SESSION, "sh", sys.executable, "-c", + PRELUDE + textwrap.dedent(script), str(tmp_path)], + capture_output=True, text=True, env=env, timeout=timeout) + assert result.returncode == 0, result.stderr[-2000:] + return json.loads(result.stdout.strip().splitlines()[-1]) + + +def test_key_lives_in_the_key_store_and_other_processes_find_it(tmp_path): + seen = in_private_key_store(tmp_path, """ + d = os.path.join(base, "vault") + first = vault(d) + health = first.health() + out, _ = first.tokenize(f"mail {EMAIL}") + code = "import sys\\n" + "from datafog_guard.config import DEFAULT_ENTITIES\\nfrom datafog_guard.store import EncryptedStore\\n" \\ + "from datafog_guard.vault import Detector, Vault\\n" \\ + "v = Vault(EncryptedStore(sys.argv[1]), Detector(DEFAULT_ENTITIES))\\nprint(v.restore(sys.argv[2]).text, v.health()['protection'])" + other = subprocess.run([sys.executable, "-c", code, d, out], capture_output=True, text=True) + header = read_envelope_header(d) + raw = b"".join(open(os.path.join(d, name), "rb").read() for name in os.listdir(d)) + print(json.dumps({"protection": health["protection"], "files": sorted(os.listdir(d)), "other": other.stdout.strip(), + "entries": entries(), "account": header["app_id"] + "/" + header["vault_id"], + "value_on_disk": EMAIL.encode() in raw, + "file_mode": code_of(lambda: vault(d, "file").health())})) + """) + assert seen["protection"] == "credential_store" + assert seen["files"] == ["markers.index", "workspace.enc", "workspace.lock"], "no key file beside the data" + assert seen["other"] == f"mail {EMAIL} credential_store", "a second process gets the key from the key store" + assert seen["entries"] == [seen["account"]] and seen["account"].startswith("claude-code/") + assert seen["value_on_disk"] is False + assert seen["file_mode"] == "vault_key_mismatch", "a key-store vault is never opened or re-keyed with a file key" + + +def test_two_vault_directories_have_two_keys_and_purge_removes_only_its_own(tmp_path): + seen = in_private_key_store(tmp_path, """ + one, two = os.path.join(base, "one"), os.path.join(base, "two") + a, _ = vault(one).tokenize(EMAIL) + b, _ = vault(two).tokenize(EMAIL) + before = entries() + ids = [read_envelope_header(d)["vault_id"] for d in (one, two)] + result = EncryptedStore(one).purge() + print(json.dumps({"before": before, "ids": ids, "purge": result, "after": entries(), + "two_still_restores": vault(two).restore(b).text == EMAIL, + "one_is_gone": vault(one).restore(a).unknown})) + """) + assert len(seen["before"]) == 2 and seen["ids"][0] != seen["ids"][1] + assert seen["purge"]["keystore"] == "removed" and seen["purge"]["account"] == "claude-code/" + seen["ids"][0] + assert seen["after"] == ["claude-code/" + seen["ids"][1]], "the other vault's key is untouched" + assert seen["two_still_restores"] is True and seen["one_is_gone"] == 1 + + +def test_a_key_removed_from_the_key_store_fails_closed_and_is_never_replaced(tmp_path): + seen = in_private_key_store(tmp_path, """ + d = os.path.join(base, "vault") + out, _ = vault(d).tokenize(EMAIL) + header = read_envelope_header(d) + account = header["app_id"] + "/" + header["vault_id"] + subprocess.run(["secret-tool", "clear", "service", KEYSTORE_SERVICE, "username", account], check=True) + codes = [code_of(lambda: vault(d).health()), code_of(lambda: vault(d).restore(out)), + code_of(lambda: vault(d).tokenize("x " + EMAIL))] + print(json.dumps({"codes": codes, "entries": entries(), "files": sorted(os.listdir(d))})) + """) + assert seen["codes"] == ["keystore_unavailable"] * 3 + assert seen["entries"] == [], "no replacement key is created for an existing vault" + assert "workspace.key" not in seen["files"], "and no silent downgrade to a key file" + + +def test_a_wrong_key_in_the_key_store_fails_closed(tmp_path): + seen = in_private_key_store(tmp_path, """ + d = os.path.join(base, "vault") + out, _ = vault(d).tokenize(EMAIL) + header = read_envelope_header(d) + account = header["app_id"] + "/" + header["vault_id"] + subprocess.run(["secret-tool", "store", "--label=x", "service", KEYSTORE_SERVICE, "username", account, + "application", "rust-keyring", "target", "default"], input=b"0" * 32, check=True) + print(json.dumps({"codes": [code_of(lambda: vault(d).health()), code_of(lambda: vault(d).restore(out))]})) + """) + assert seen["codes"] == ["vault_corrupt"] * 2 + + +def test_without_a_reachable_key_store_nothing_is_created_and_the_message_is_clear(box): + """The default mode on a machine without a Secret Service (a server, a container, SSH).""" + env = box.env(DATAFOG_VAULT_KEY="keystore", DBUS_SESSION_BUS_ADDRESS="unix:path=/nonexistent/datafog-test", + XDG_RUNTIME_DIR=str(box.tmp / "no-runtime")) + (box.data / "config.json").unlink() + out, result = box.hook({"hook_event_name": "PreToolUse", "tool_name": "Read", "tool_input": {"file_path": "/x"}, + "cwd": str(box.project)}, DATAFOG_VAULT_KEY="keystore", + DBUS_SESSION_BUS_ADDRESS=env["DBUS_SESSION_BUS_ADDRESS"], XDG_RUNTIME_DIR=env["XDG_RUNTIME_DIR"]) + reason = out["hookSpecificOutput"]["permissionDecisionReason"] + assert out["hookSpecificOutput"]["permissionDecision"] == "deny" + assert "keystore_unavailable" in reason and "key store" in reason and "vault_key" in reason + status = box.run("status", env=env).stdout.decode() + doctor = box.run("doctor", env=env).stdout.decode() + start = json.loads(box.run("hook", stdin=json.dumps({"hook_event_name": "SessionStart"}), env=env).stdout) + for text in (status, doctor, start["systemMessage"]): + assert "keystore_unavailable: the operating system's key store" in text + assert "Protection: NOT WORKING" in status and "NOT PROTECTING" in start["systemMessage"] + assert not (box.vault / "workspace.enc").exists() and not (box.vault / "workspace.key").exists() diff --git a/tests/test_late_swap.py b/tests/test_late_swap.py index 227cac2..2b64d6e 100644 --- a/tests/test_late_swap.py +++ b/tests/test_late_swap.py @@ -599,7 +599,7 @@ class Runner: def __init__(self, box, receivers: Bin, shell: str): self.box, self.receivers, self.shell = box, receivers, shell - (box.data / "config.json").write_text('{"restore_programs_extra": ["dump", "sdump", "rc", "psprobe"]}') + (box.data / "config.json").write_text('{"vault_key": "file", "restore_programs_extra": ["dump", "sdump", "rc", "psprobe"]}') self.plugin, self.settings = standin_plugin(box) def run(self, command: str, *, ticket: object = True, env: dict | None = None, timeout: int = 600): @@ -621,9 +621,9 @@ def runner(box, receivers, request) -> Runner: def seeded(box): """marker -> value for every nasty value a real vault accepts. - The vault stores what it gives back on restore: core refuses a value that is only whitespace - and normalises a tab or carriage return inside a value to a blank. The runner is checked - against the value the vault returns.""" + Every value is stored so that it comes back byte for byte (core compares values loosely, so a + value that differs from an earlier one only in white space or case gets a variant label). Core + refuses a value that is only white space. The runner is checked against what the vault returns.""" from datafog_guard.errors import GuardError vault = box.open_vault() stored = {} @@ -631,7 +631,7 @@ def seeded(box): if not value: continue try: - marker = vault._commit([("ACCOUNT_NUMBER", value)])[value] + marker = vault._markers_for({value: ["ACCOUNT_NUMBER"]})[value] except GuardError: continue stored[marker] = vault.restore_spans(marker)[0][0][3] @@ -730,7 +730,7 @@ def test_a_command_cannot_get_values_by_starting_the_runner_itself(runner, seede def test_restore_off_never_restores_even_with_a_ticket(runner, seeded): marker = next(m for m, value in seeded.items() if value == "a b") - (runner.box.data / "config.json").write_text('{"restore_in_bash": "off", "restore_programs_extra": ["dump"]}') + (runner.box.data / "config.json").write_text('{"restore_in_bash": "off", "vault_key": "file", "restore_programs_extra": ["dump"]}') result, _ = runner.run(f"dump 0 '{marker}'") assert result.returncode == 0 and runner.receivers.got(0) == marker.encode() + b"\0" diff --git a/tests/test_live_driver.py b/tests/test_live_driver.py index a300bee..f9c8c46 100644 --- a/tests/test_live_driver.py +++ b/tests/test_live_driver.py @@ -5,6 +5,7 @@ """ from __future__ import annotations +import importlib.util import json import os import subprocess @@ -59,6 +60,17 @@ def test_aborts_on_an_old_claude(tmp_path): assert open(os.path.join(work, "log", "status.txt")).read().startswith("ABORTED") +@pytest.mark.parametrize("flags", [None, []]) +def test_driver_isolates_fixture_settings_even_without_optional_flags(tmp_path, flags): + spec = importlib.util.spec_from_file_location("datafog_live_driver", DRIVER) + live = importlib.util.module_from_spec(spec) + spec.loader.exec_module(live) + driver = live.Driver(str(tmp_path), str(FAKE)) + run = driver.run("probe-settings", "Reply with exactly: LIVE_OK", env={"SIM_NO_HOOKS": "1"}, flags=flags) + assert run.exit_code == 0 and run.final == "LIVE_OK" + assert run.init["plugins"] == [{"name": "datafog", "path": str(ROOT)}] + + @needs_network def test_full_run_against_the_simulator(): with tempfile.TemporaryDirectory(prefix="datafog-live.") as work: diff --git a/tests/test_mcp.py b/tests/test_mcp.py index 5b8b15b..48ea89c 100644 --- a/tests/test_mcp.py +++ b/tests/test_mcp.py @@ -8,7 +8,7 @@ import sys import pytest -from conftest import CARD, EMAIL, NOTES, PHONE, assert_no_sentinel +from conftest import CARD, EMAIL, NOTES, PHONE, assert_no_sentinel, corrupt_vault EDIT = "edit_with_markers" @@ -121,7 +121,7 @@ def test_edit_refuses_paths_outside_the_project_and_inside_storage(box, client): link = box.project / "link.txt" link.symlink_to(outside) box.open_vault().tokenize(EMAIL) - for target in (outside, link, box.vault / "HEAD", box.data / "runtime.json", "/etc/hosts", + for target in (outside, link, box.vault / "workspace.enc", box.vault / "markers.index", box.data / "runtime.json", "/etc/hosts", box.project / ".." / "outside.txt"): text, error = client.call(EDIT, file_path=str(target), old_string="a", new_string="b") assert error and "Refused" in text, target @@ -160,14 +160,13 @@ def test_long_lived_server_sees_markers_created_after_it_started(box, client): def test_protection_status_has_types_and_counts_only(box, client): box.open_vault().tokenize(NOTES) text, error = client.call("protection_status") - assert not error and "Protection: ON" in text and "1 EMAIL" in text and "NONE in this version" in text + assert not error and "Protection: ON" in text and "1 EMAIL" in text and "encryption at rest: encrypted" in text assert str(box.vault) not in text, "the model does not need the vault path" def test_server_with_a_broken_vault_reports_without_details(box): box.write("notes.txt", NOTES) - box.vault.mkdir() - (box.vault / "HEAD").write_text("corrupt " + EMAIL) + corrupt_vault(box.vault, b"corrupt " + EMAIL.encode()) client = Client(box) text, error = client.call(EDIT, file_path=str(box.project / "notes.txt"), old_string="End", new_string="Fin") assert error and "vault_corrupt" in text and "Nothing was changed" in text diff --git a/tests/test_store.py b/tests/test_store.py index 0c1a17f..b71e8d5 100644 --- a/tests/test_store.py +++ b/tests/test_store.py @@ -1,119 +1,370 @@ -"""File vault store: permissions, atomic compare-and-save, corruption handling, purge.""" +"""The encrypted store: layout, permissions, ciphertext on disk, key modes, corruption, purge.""" from __future__ import annotations -import json import os import stat import pytest -from conftest import EMAIL -from datafog_guard.errors import VaultCorrupt, VaultLocked -from datafog_guard.store import FileVaultStore, Head +from conftest import API_KEY, EMAIL, NOTES, SENTINELS, open_test_vault +from datafog_guard.errors import VaultCorrupt, VaultError, VaultLocked +from datafog_guard.store import EncryptedStore, FileLock, legacy_plain_store, read_envelope_header, vault_path + +OURS = {"markers.index", "bash-restore.key"} +CORES = {"workspace.enc", "workspace.lock", "workspace.key"} def mode(path) -> int: return stat.S_IMODE(os.stat(path).st_mode) -def test_empty_store(tmp_path): - store = FileVaultStore(str(tmp_path / "v")) - assert store.load() is None and store.peek_head() is None - assert not (tmp_path / "v").exists(), "reading must not create anything" +def test_reading_creates_nothing(box): + vault = box.open_vault() + assert vault.restore("x [[EMAIL_ABC123]]").unknown == 1 and vault.tokenize("plain text")[0] == "plain text" + assert vault.entry_counts() == {} + assert not box.vault.exists(), "reading must not create a vault (or a key)" -def test_compare_and_save_is_the_only_write(tmp_path): - store = FileVaultStore(str(tmp_path / "v")) - first, second = Head(0, "aa"), Head(1, "bb") - assert store.compare_and_save(None, first, b"bundle-0", {"entries": {}}) - assert not store.compare_and_save(None, first, b"other", {}), "creating twice must fail" - assert not store.compare_and_save(second, Head(2, "cc"), b"x", {}), "stale head must fail" - assert store.load().bundle == b"bundle-0" - assert store.compare_and_save(first, second, b"bundle-1", {"entries": {"EMAIL": 1}}) - snapshot = store.load() - assert snapshot.head == second and snapshot.bundle == b"bundle-1" - assert snapshot.annotations == {"entries": {"EMAIL": 1}} +def test_layout_and_permissions(box): + box.open_vault().tokenize(NOTES) + names = {path.name for path in box.vault.iterdir()} + assert names == {"workspace.enc", "workspace.lock", "workspace.key", "markers.index"} + assert mode(box.vault) == 0o700 + for path in box.vault.iterdir(): + assert path.is_file() and mode(path) == 0o600, path.name -def test_permissions_and_layout(box): +def test_our_files_do_not_collide_with_cores(box): + """The restore-ticket key and the marker index live beside core's files and do not disturb them.""" + from datafog_guard import bashwrap + assert not OURS & CORES vault = box.open_vault() - vault.tokenize(f"x {EMAIL}") - assert mode(box.vault) == 0o700 and mode(box.vault / "snapshots") == 0o700 - for path in box.vault.rglob("*"): - if path.is_file(): - assert mode(path) == 0o600, path.name - meta = json.loads((box.vault / "meta.json").read_text()) - assert meta["app_id"] == "claude-code" and meta["contract_version"] == 1 - assert meta["encrypted_at_rest"] is False and len(meta["vault_id"]) == 32 and meta["created"] - - -def test_snapshot_bytes_are_cores_unmodified(box): - import datafog_core + out, _ = vault.tokenize(NOTES) + ticket = bashwrap.restore_ticket("echo x", str(box.vault)) + assert ticket and mode(box.vault / "bash-restore.key") == 0o600 + again = box.open_vault() + again.health() + assert again.restore(out).text == NOTES + assert bashwrap.ticket_is_valid(ticket, "echo x", str(box.vault)) + + +def test_nothing_on_disk_holds_a_value(box): + """What is on disk is ciphertext: no planted value, whole or in a recognisable part.""" vault = box.open_vault() - vault.tokenize(f"x {EMAIL}") - pointer = json.loads((box.vault / "HEAD").read_text()) - raw = (box.vault / "snapshots" / pointer["snapshot"]).read_bytes() - workspace = datafog_core.Workspace.open_bundle(raw) - assert workspace.export_bundle() == raw - assert workspace.head().revision == pointer["revision"] + hostile = "it's \"q\" $(touch x) `y`\nline two\\" + vault.tokenize(NOTES + f"\nkey {API_KEY}\n") + from conftest import seed_values + seed_values(vault, [("ACCOUNT_NUMBER", hostile)]) + vault.restore(vault.tokenize(NOTES)[0]) + needles = [value.encode() for value in SENTINELS] + [b"ada.synthetic", b"4242", b"078-05", b"555-0134", + b"4eC39HqLyjWDarjtT1zdp7dc", b"touch x", b"line two"] + for path in box.tmp.rglob("*"): + if path.is_file() and box.vault in path.parents: + raw = path.read_bytes() + for needle in needles: + assert needle not in raw, f"a value is readable in {path.name}" + index = (box.vault / "markers.index").read_text() + assert index.startswith("# datafog marker index v1 ") and "[[EMAIL_" in index -def test_loose_directory_permissions_are_tightened(tmp_path): +def test_the_envelope_names_the_app_and_the_key_mode_in_the_clear(box): + box.open_vault().tokenize(EMAIL) + header = read_envelope_header(str(box.vault)) + assert header["state"] == "ok" and header["app_id"] == "claude-code" and header["protection"] == "file_key" + assert len(header["vault_id"]) == 32 and header["revision"] == 1 + + +def test_a_directory_made_with_mkdir_is_made_private_before_the_vault_is_created(tmp_path): directory = tmp_path / "v" directory.mkdir(mode=0o755) os.chmod(directory, 0o755) - FileVaultStore(str(directory)).compare_and_save(None, Head(0, "aa"), b"b", {}) + open_test_vault(directory).tokenize(EMAIL) assert mode(directory) == 0o700 -def test_old_snapshots_are_removed(box): - vault = box.open_vault() - for number in range(6): - vault.tokenize(f"user{number}.synthetic@example.com") - assert len(list((box.vault / "snapshots").iterdir())) <= 2 +@pytest.mark.parametrize("target", ["directory", "workspace.enc", "workspace.key"]) +def test_loose_permissions_on_an_existing_vault_are_refused_not_repaired(box, target): + out, _ = box.open_vault().tokenize(EMAIL) + path = box.vault if target == "directory" else box.vault / target + os.chmod(path, 0o755 if target == "directory" else 0o644) + for action in (lambda: box.open_vault().tokenize(f"y {EMAIL}"), lambda: box.open_vault().restore(out), + lambda: box.open_vault().health()): + with pytest.raises(VaultError) as caught: + action() + assert caught.value.code == "vault_insecure" and EMAIL not in caught.value.user_message + assert mode(path) == (0o755 if target == "directory" else 0o644), "nothing is repaired silently" -@pytest.mark.parametrize("damage", ["pointer_garbage", "pointer_truncated", "snapshot_flipped", "snapshot_missing", - "snapshot_truncated"]) +def test_a_vault_directory_that_is_a_symbolic_link_is_refused(box): + out, _ = box.open_vault().tokenize(EMAIL) + link = box.tmp / "link" + link.symlink_to(box.vault) + with pytest.raises(VaultError) as caught: + open_test_vault(link).restore(out) + assert caught.value.code == "vault_insecure" + + +def test_symbolic_links_above_the_vault_directory_are_followed(box): + """/tmp and /var are links on macOS; only the vault directory itself must not be one.""" + real = box.tmp / "real" + real.mkdir() + (box.tmp / "alias").symlink_to(real) + out, _ = open_test_vault(box.tmp / "alias" / "vault").tokenize(EMAIL) + assert open_test_vault(real / "vault").restore(out).text == EMAIL + assert vault_path(str(box.tmp / "alias" / "vault")) == str(real.resolve() / "vault") + + +@pytest.mark.parametrize("damage", ["flipped", "truncated", "garbage", "empty", "wrong_key", "short_key", "missing_key"]) def test_corruption_is_detected_not_ignored(box, damage): - vault = box.open_vault() - vault.tokenize(f"x {EMAIL}") - pointer_path = box.vault / "HEAD" - pointer = json.loads(pointer_path.read_text()) - snapshot = box.vault / "snapshots" / pointer["snapshot"] - if damage == "pointer_garbage": - pointer_path.write_text("not json") - elif damage == "pointer_truncated": - pointer_path.write_text(pointer_path.read_text()[:20]) - elif damage == "snapshot_flipped": - raw = bytearray(snapshot.read_bytes()) - raw[len(raw) // 2] ^= 0xFF - snapshot.write_bytes(bytes(raw)) - elif damage == "snapshot_missing": - snapshot.unlink() + box.open_vault().tokenize(f"x {EMAIL}") + envelope, key = box.vault / "workspace.enc", box.vault / "workspace.key" + if damage == "flipped": + raw = bytearray(envelope.read_bytes()) + raw[-20] ^= 0xFF + envelope.write_bytes(bytes(raw)) + elif damage == "truncated": + envelope.write_bytes(envelope.read_bytes()[:-9]) + elif damage == "garbage": + envelope.write_bytes(b"not a vault at all " * 20) + elif damage == "empty": + envelope.write_bytes(b"") + elif damage == "wrong_key": + key.write_bytes(bytes(32)) + elif damage == "short_key": + key.write_bytes(b"short") else: - snapshot.write_bytes(snapshot.read_bytes()[:-9]) - with pytest.raises(VaultCorrupt): - box.open_vault().tokenize(f"y {EMAIL}") - with pytest.raises(VaultCorrupt): - box.open_vault().restore("[[EMAIL_ABC123]]") + key.unlink() + for action in (lambda: box.open_vault().tokenize(f"y {EMAIL}"), lambda: box.open_vault().restore("[[EMAIL_ABC123]]"), + lambda: box.open_vault().health()): + with pytest.raises(VaultError) as caught: + action() + assert caught.value.code in ("vault_corrupt", "vault_unsupported", "vault_unreadable"), caught.value.code + assert EMAIL not in str(caught.value) + caught.value.user_message + if damage in ("flipped", "truncated", "wrong_key"): + with pytest.raises(VaultCorrupt): + box.open_vault().health() + + +def test_no_new_key_is_made_for_an_existing_vault(box): + """A missing key must fail closed: core never replaces it, and neither does the plugin.""" + box.open_vault().tokenize(EMAIL) + (box.vault / "workspace.key").unlink() + with pytest.raises(VaultError): + box.open_vault().health() + assert not (box.vault / "workspace.key").exists() def test_lock_times_out_instead_of_hanging(box): - box.open_vault().tokenize(f"x {EMAIL}") - holder = FileVaultStore(str(box.vault)) - with holder.lock(): - blocked = FileVaultStore(str(box.vault), lock_timeout=0.2) + out, _ = box.open_vault().tokenize(f"x {EMAIL}") + import time + with FileLock(str(box.vault / "workspace.lock")): + blocked = open_test_vault(box.vault) + blocked.store.lock_timeout = 0.2 + started = time.monotonic() with pytest.raises(VaultLocked): - blocked.compare_and_save(blocked.peek_head(), Head(99, "zz"), b"x", {}) - assert holder.load().head.revision == 1 + blocked.restore(out) + assert time.monotonic() - started < 15, "core waits five seconds for the lock; the plugin does not add much" + assert box.open_vault().restore(out).text == f"x {EMAIL}" + + +@pytest.mark.skipif(os.name == "nt" or os.geteuid() != 0 or not __import__("shutil").which("setpriv"), + reason="needs root and setpriv to run as another user") +def test_core_limit_a_directory_above_the_vault_that_the_user_cannot_list(tmp_path): + """LIMIT OF CORE 1.7.0, pinned so a change is noticed: ApplicationVault opens every directory + above the vault (to flush it), so a parent the user may pass through but not list, such as a + /home with mode 0711, makes the vault unusable. The plugin then fails closed.""" + import subprocess + import sys + + from conftest import ENGINE, ROOT + switch = ["setpriv", "--reuid=65534", "--regid=65534", "--clear-groups"] + if subprocess.run([*switch, sys.executable, "-I", "-c", "import datafog_fogvault"], capture_output=True).returncode: + pytest.skip("this Python installation is not readable by the unprivileged test user") + base = __import__("pathlib").Path(__import__("tempfile").mkdtemp(prefix="datafog-anc-", dir="/tmp")) + try: + home = base / "closed" / "home" + home.mkdir(parents=True) + subprocess.run(["chown", "65534:65534", str(home)], check=True) + os.chmod(base, 0o755) + code = ("import sys; sys.path[:0] = [%r, %r]\n" + "from conftest import open_test_vault\n" + "from datafog_guard.errors import GuardError\n" + "try:\n open_test_vault(sys.argv[1]).health(); print('ok')\n" + "except GuardError as error:\n print(error.code)\n" % (str(ENGINE), str(ROOT / "tests"))) + outcomes = [] + for mode_bits in (0o711, 0o755): + os.chmod(base / "closed", mode_bits) + result = subprocess.run([*switch, sys.executable, "-c", code, str(home / f"vault{mode_bits}")], + capture_output=True, text=True, env={"PATH": os.environ["PATH"], "PYTHONDONTWRITEBYTECODE": "1"}) + outcomes.append(result.stdout.strip() or result.stderr[-300:]) + assert outcomes == ["vault_unreadable", "ok"] + finally: + subprocess.run(["rm", "-rf", str(base)]) + + +def test_two_vault_directories_do_not_share_a_key(box): + first, second = box.tmp / "one", box.tmp / "two" + a, _ = open_test_vault(first).tokenize(EMAIL) + b, _ = open_test_vault(second).tokenize(EMAIL) + assert (first / "workspace.key").read_bytes() != (second / "workspace.key").read_bytes() + assert read_envelope_header(str(first))["vault_id"] != read_envelope_header(str(second))["vault_id"] + assert open_test_vault(second).restore(a).unknown == (0 if a == b else 1) + # one vault's key does not open the other + (second / "workspace.key").write_bytes((first / "workspace.key").read_bytes()) + with pytest.raises(VaultCorrupt): + open_test_vault(second).health() + + +def test_the_marker_index_of_another_vault_is_ignored_and_replaced(box): + vault = box.open_vault() + vault.tokenize(EMAIL) + index = box.vault / "markers.index" + index.write_text("# datafog marker index v1 " + "0" * 32 + "\n[[EMAIL_ZZZZZZ]]\n") + fresh = box.open_vault() + assert fresh.entry_counts() == {} + out, _ = fresh.tokenize(f"again {EMAIL} and 415-555-0134") + assert box.open_vault().entry_counts() == {"EMAIL": 1, "PHONE": 1} + assert "[[EMAIL_ZZZZZZ]]" not in index.read_text() + + +def test_a_damaged_or_lost_marker_index_heals_and_never_blocks(box): + vault = box.open_vault() + first, _ = vault.tokenize(f"{EMAIL} 415-555-0134") + index = box.vault / "markers.index" + index.write_bytes(index.read_bytes()[:-5] + b"\xff\x00 junk") # a torn last line + assert box.open_vault().entry_counts() == {"EMAIL": 1} + again, _ = box.open_vault().tokenize(f"{EMAIL} 415-555-0134") + assert again == first, "the value gets the marker it always had" + assert box.open_vault().entry_counts() == {"EMAIL": 1, "PHONE": 1} + index.unlink() + assert box.open_vault().restore(first).text == f"{EMAIL} 415-555-0134", "restoring never needs the index" + assert box.open_vault().tokenize(f"{EMAIL} 415-555-0134")[0] == first + index.write_text(index.read_text() + "[[EMAIL_ZZZZZZ]]\nnot a marker\n") # entries the vault does not know + assert box.open_vault().entry_counts() == {"EMAIL": 1, "PHONE": 1} + + +def test_a_fifo_marker_index_is_refused_without_waiting_for_a_writer(box): + box.open_vault().tokenize(EMAIL) + index = box.vault / "markers.index" + index.unlink() + os.mkfifo(index, mode=0o600) + with pytest.raises(VaultError) as caught: + box.open_vault().tokenize(EMAIL) + assert caught.value.code == "vault_insecure" def test_purge(box): + from datafog_guard import bashwrap vault = box.open_vault() out, _ = vault.tokenize(f"x {EMAIL}") - store = FileVaultStore(str(box.vault)) - assert store.purge() is True - assert store.load() is None and not list((box.vault / "snapshots").iterdir()) - result = box.open_vault().restore(out) - assert result.text == out and result.unknown == 1, "markers from a purged vault can never be restored" - assert store.purge() is False + bashwrap.restore_ticket("echo", str(box.vault)) + store = EncryptedStore(str(box.vault), key_mode="file") + result = store.purge() + assert result["existed"] is True and result["keystore"] == "none" + assert {path.name for path in box.vault.iterdir()} <= {"workspace.lock"} + restored = box.open_vault().restore(out) + assert restored.text == out and restored.unknown == 1, "markers from a purged vault can never be restored" + assert store.purge()["existed"] is False + box.open_vault().tokenize(EMAIL) + assert box.open_vault().entry_counts() == {"EMAIL": 1}, "a new vault starts empty" + + +def test_purge_does_not_follow_a_symlinked_vault_directory(box): + box.open_vault().tokenize(EMAIL) + alias = box.tmp / "alias" + alias.symlink_to(box.vault, target_is_directory=True) + with pytest.raises(VaultError): + EncryptedStore(str(alias), key_mode="file").purge() + assert (box.vault / "workspace.enc").exists() and (box.vault / "workspace.key").exists() + + +def test_purge_unlinks_a_symlinked_legacy_directory_without_deleting_its_target(box): + box.open_vault().tokenize(EMAIL) + outside = box.tmp / "outside" + outside.mkdir() + document = outside / "important.txt" + document.write_text("synthetic data outside the vault") + (box.vault / "snapshots").symlink_to(outside, target_is_directory=True) + result = EncryptedStore(str(box.vault), key_mode="file").purge() + assert result["legacy"] is True + assert document.read_text() == "synthetic data outside the vault" + assert not (box.vault / "snapshots").is_symlink() + + +@pytest.mark.parametrize("link_kind", ["symlink", "hardlink"]) +def test_purge_refuses_a_linked_lock_file(box, link_kind): + box.open_vault().tokenize(EMAIL) + outside = box.tmp / "outside.txt" + outside.write_text("synthetic outside data") + lock = box.vault / "workspace.lock" + lock.unlink() + if link_kind == "symlink": + lock.symlink_to(outside) + else: + os.link(outside, lock) + with pytest.raises(VaultError): + EncryptedStore(str(box.vault), key_mode="file").purge() + assert outside.read_text() == "synthetic outside data" + assert (box.vault / "workspace.enc").exists() + + +@pytest.mark.skipif(os.geteuid() == 0, reason="root can unlink files in a read-only directory") +def test_purge_reports_a_deletion_failure_and_preserves_the_key(box): + out, _ = box.open_vault().tokenize(EMAIL) + box.vault.chmod(0o500) + try: + with pytest.raises(VaultError) as caught: + EncryptedStore(str(box.vault), key_mode="file").purge() + assert caught.value.code == "purge_failed" + assert (box.vault / "workspace.enc").exists() and (box.vault / "workspace.key").exists() + finally: + box.vault.chmod(0o700) + assert box.open_vault().restore(out).text == EMAIL + + +def test_purge_holds_the_vault_lock_until_key_removal_finishes(box, monkeypatch): + from datafog_guard import store + box.open_vault().tokenize(EMAIL) + envelope = box.vault / "workspace.enc" + raw = bytearray(envelope.read_bytes()) + raw[13 + raw[12] + 56] = 1 # a credential-store envelope; purge needs no working key + envelope.write_bytes(raw) + calls = [] + + def remove_key(account): + assert not envelope.exists() + with pytest.raises(VaultLocked): + with FileLock(str(box.vault / "workspace.lock"), timeout=0.01): + pass + calls.append(account) + return True + + monkeypatch.setattr(store, "remove_keystore_entry", remove_key) + result = EncryptedStore(str(box.vault), key_mode="file").purge() + assert result["keystore"] == "removed" and calls == [result["account"]] + + +def test_purge_under_a_long_lived_process(box): + """The MCP server keeps its vault object: after a purge by another process it sees the new vault.""" + server = box.open_vault() + old, _ = server.tokenize(f"x {EMAIL}") + EncryptedStore(str(box.vault), key_mode="file").purge() + assert server.restore(old).unknown == 1 and server.entry_counts() == {} + new, _ = box.open_vault().tokenize(f"x {EMAIL}") + assert server.restore(new).text == f"x {EMAIL}" and server.entry_counts() == {"EMAIL": 1} + assert server.restore(old).unknown == (0 if old == new else 1) + + +def test_an_unencrypted_vault_of_a_development_build_is_never_read_and_purge_removes_it(box): + box.vault.mkdir(mode=0o700) + (box.vault / "snapshots").mkdir() + (box.vault / "snapshots" / "000000000001-aa.dfv").write_bytes(b"plain " + EMAIL.encode()) + (box.vault / "HEAD").write_text('{"revision": 1}') + (box.vault / "meta.json").write_text("{}") + assert legacy_plain_store(str(box.vault)) + vault = box.open_vault() + assert vault.restore("[[EMAIL_ABC123]]").unknown == 1 + out, _ = vault.tokenize(EMAIL) # the encrypted vault works beside it + assert box.open_vault().restore(out).text == EMAIL + result = EncryptedStore(str(box.vault), key_mode="file").purge() + assert result["legacy"] is True and not legacy_plain_store(str(box.vault)) + assert {path.name for path in box.vault.iterdir()} <= {"workspace.lock"} diff --git a/tests/test_vault.py b/tests/test_vault.py index 1cd7cf6..b29a41e 100644 --- a/tests/test_vault.py +++ b/tests/test_vault.py @@ -5,10 +5,9 @@ from collections import Counter import pytest -from conftest import CARD, EMAIL, NOTES, PHONE, SENTINELS, copy_vault -from datafog_guard.errors import ConfigError, RecallUnavailable, TokenizeError, VaultFull -from datafog_guard.store import FileVaultStore -from datafog_guard.vault import MARKER_RE, Detector, Span, Vault, merge_spans +from conftest import CARD, EMAIL, NOTES, PHONE, SENTINELS, copy_vault, seed_values +from datafog_guard.errors import ConfigError, TokenizeError, VaultFull +from datafog_guard.vault import MARKER_RE, Span, merge_spans MARKER = re.compile(r"\[\[[A-Z0-9_]+_[0-9A-Z]{6}\]\]") @@ -41,7 +40,7 @@ def test_text_without_values_does_not_touch_the_vault(box): vault = box.open_vault() out, counts = vault.tokenize("nothing to see here\n") assert out == "nothing to see here\n" and not counts - assert not box.vault.exists() or FileVaultStore(str(box.vault)).peek_head() is None + assert not box.vault.exists() def test_tokenizing_twice_is_stable(box): @@ -61,6 +60,91 @@ def test_recall_catches_a_value_the_detector_misses(box): assert vault.restore(out).text == bare +@pytest.mark.parametrize("text, hidden", [ + ("ref 000123456789 again", True), + ("ref (000123456789), again", True), + ("REF-000123456789.", True), + ("x000123456789y", False), # inside a longer word or number: not the value + ("0001234567890", False), + ("_000123456789", False), +]) +def test_known_values_match_whole_not_inside_a_longer_word(box, text, hidden): + box.open_vault().tokenize("account number 000123456789") + out, counts = box.open_vault().tokenize(text) + assert ("000123456789" not in out) is hidden and bool(counts) is hidden + + +def test_known_values_match_whatever_the_case_and_white_space(box): + """As core's recall did: a known card number is found with other spacing, and restores exactly.""" + vault = box.open_vault() + seed_values(vault, [("ACCOUNT_NUMBER", "Policy AB 77 31")]) + for text in ("see policy ab 77 31 here", "POLICY AB\t77\n31", "Policy AB 77 31"): + fresh = box.open_vault() + out, counts = fresh.tokenize(text) + assert "77" not in out and counts == Counter({"ACCOUNT_NUMBER": 1}), text + assert box.open_vault().restore(out).text == text + assert box.open_vault().tokenize("Policy AB 77 31")[0] == seed_values(vault, [("ACCOUNT_NUMBER", "Policy AB 77 31")])["Policy AB 77 31"] + + +def test_known_value_matching_never_touches_marker_text(box): + vault = box.open_vault() + marker = vault.tokenize(EMAIL)[0] + seed_values(vault, [("ACCOUNT_NUMBER", marker[2:-2].split("_")[1])]) # a value equal to a marker's code + out, counts = box.open_vault().tokenize(f"keep {marker} as it is") + assert out == f"keep {marker} as it is" and not counts + + +def test_known_values_in_a_large_text_with_a_large_vault(box): + """The narrowing step for big inputs finds the same values as the plain search.""" + import datafog_guard.vault as module + vault = box.open_vault() + seed_values(vault, [("ACCOUNT_NUMBER", f"acct-{number:05d}-zz") for number in range(800)]) + text = "\n".join(f"line {number} filler filler" for number in range(3000)) + "\nsee ACCT-00777-ZZ and acct-00003-zz\n" + plain, _ = box.open_vault().tokenize(text) + saved, module.PREFILTER_WORK = module.PREFILTER_WORK, 1 + try: + narrowed, counts = box.open_vault().tokenize(text) + finally: + module.PREFILTER_WORK = saved + assert counts == Counter({"ACCOUNT_NUMBER": 2}) and "00777" not in narrowed and "00003" not in narrowed + assert box.open_vault().restore(narrowed).text == text and plain.count("[[") == 2 + + +HOSTILE = ["a\tb", "a\r\nb", "a\rb", "a\nb", "a b", "A\u00a0B", " lead", "trail ", "it's \"q\" $(x) `y` \\", "x\x00y", + "é\u200bz", "AB", "tab\tin\tside", "-rf --", "'; rm -rf ~; '", "line1\nline2\n\nline4", "\x1b[31mred\x1b[0m", + "名前 太郎", "a" * 30_000] + + +def test_hostile_values_round_trip_exactly(box): + """Core treats values that differ only in case or white space as one; every one must still come + back byte for byte, in this process and in a new one. (White space around a value is trimmed + before it is stored: the marker replaces the trimmed part and the rest stays in the text.)""" + vault = box.open_vault() + markers = {} + for value in HOSTILE: + markers[value] = seed_one_exact(vault, value) + assert len(set(markers.values())) == len(HOSTILE), "one marker per distinct byte string" + fresh = box.open_vault() + for value, marker in markers.items(): + assert fresh.restore(f"<{marker}>").text == f"<{value}>", repr(value[:20]) + spans, unknown = fresh.restore_spans(f"<{marker}>") + assert spans == [(1, 1 + len(marker), "ACCOUNT_NUMBER", value)] and unknown == 0 + again = box.open_vault() + assert {value: again._markers_for({value: ["ACCOUNT_NUMBER"]})[value] for value in HOSTILE} == markers + + +def seed_one_exact(vault, value: str) -> str: + return vault._markers_for({value: ["ACCOUNT_NUMBER"]})[value] + + +@pytest.mark.parametrize("value", [" ", "\t", "\n", ""]) +def test_a_value_of_only_white_space_is_refused(box, value): + """Core refuses it. It cannot come from detection: spans are trimmed first.""" + with pytest.raises(TokenizeError): + box.open_vault()._markers_for({value: ["ACCOUNT_NUMBER"]}) + assert merge_spans([Span(0, max(1, len(value)), "EMAIL")], value.encode() or b" ") == [] + + def test_case_variants_restore_exactly(box): """Core folds case when comparing values; a write-back must still be byte-exact.""" vault = box.open_vault() @@ -93,7 +177,7 @@ def test_multibyte_text(box): def test_marker_lookalikes_do_not_break_tokenizing(box): - """prepare() and recall() in core reject unknown marker-like text; the engine must cope.""" + """Core's prepare rejects unknown marker-like text; the engine must cope.""" vault = box.open_vault() known, _ = vault.tokenize(EMAIL) text = f"[[SECTION_HEADER]] [[EMAIL_ZZZZZZ]] [[FOO_BAR_BAZ12]] {known[2:-2]} arr[[0]] {PHONE} {known}" @@ -191,17 +275,15 @@ def test_full_vault_fails_closed_with_a_clear_message(box, full_vault_dir): assert "v0000007" not in out and counts == Counter({"ACCOUNT_NUMBER": 1}) -def test_vault_too_large_for_recall_fails_closed(box): - """Core's recall stops working once stored values pass roughly 256 KiB in total.""" - filler = Vault(FileVaultStore(str(box.vault)), Detector(("EMAIL",)), recall_required=False) +def test_known_values_are_matched_however_much_the_vault_holds(box): + """Core's own recall stopped at roughly 256 KiB of stored values; the plugin's matching does not.""" + vault = box.open_vault() for start in range(0, 3500, 500): - filler._commit([("API_KEY", f"k{number:07d}" * 12) for number in range(start, start + 500)]) - with pytest.raises(RecallUnavailable): - box.open_vault().tokenize(f"new {EMAIL}") - with pytest.raises(RecallUnavailable): - box.open_vault().health() - out, counts = filler.tokenize(f"new {EMAIL}") # opt-out: detector only - assert EMAIL not in out + seed_values(vault, [("API_KEY", f"k{number:07d}" * 12) for number in range(start, start + 500)]) + fresh = box.open_vault() + fresh.health() + out, counts = fresh.tokenize(f"new {EMAIL} and {'k0003499' * 12} again") + assert EMAIL not in out and "k0003499" not in out and counts == Counter({"EMAIL": 1, "API_KEY": 1}) # -- configuration ----------------------------------------------------------- @@ -211,20 +293,20 @@ def test_default_entities_exclude_noisy_types(box): def test_noisy_types_can_be_enabled(box): - vault = Vault(FileVaultStore(str(box.vault)), Detector(("IP_ADDRESS", "UUID"))) + vault = box.open_vault(("IP_ADDRESS", "UUID")) out, counts = vault.tokenize("ip 10.1.2.3 id 123e4567-e89b-12d3-a456-426614174000") assert counts == Counter({"IP_ADDRESS": 1, "UUID": 1}) def test_allowlist_is_exact_and_never_stored(box): - vault = Vault(FileVaultStore(str(box.vault)), Detector(("EMAIL",), allowlist=frozenset({"noreply@example.com"}))) + vault = box.open_vault(("EMAIL",), allowlist=frozenset({"noreply@example.com"})) out, counts = vault.tokenize(f"from noreply@example.com to {EMAIL}") assert "noreply@example.com" in out and EMAIL not in out and counts == Counter({"EMAIL": 1}) assert vault.entry_counts() == {"EMAIL": 1} def test_unknown_entity_is_a_config_error(box): - vault = Vault(FileVaultStore(str(box.vault)), Detector(("EMAIL", "NOT_A_TYPE"))) + vault = box.open_vault(("EMAIL", "NOT_A_TYPE")) with pytest.raises(ConfigError): vault.tokenize("x") diff --git a/tests/test_vault_security.py b/tests/test_vault_security.py new file mode 100644 index 0000000..ded56ee --- /dev/null +++ b/tests/test_vault_security.py @@ -0,0 +1,181 @@ +"""Where values and keys must never be, and the single message of an unsupported machine.""" +from __future__ import annotations + +import base64 +import json +import os +import shutil +import subprocess +import sys + +import pytest +import shapes_recorded as recorded +from conftest import EMAIL, NOTES, ROOT, SENTINELS, assert_no_sentinel +from datafog_guard.support import UNSUPPORTED, platform_problem + + +def key_forms(box) -> list[bytes]: + key = (box.vault / "workspace.key").read_bytes() + assert len(key) == 32 + return [key, key.hex().encode(), key.hex().upper().encode(), base64.b64encode(key), base64.urlsafe_b64encode(key)] + + +def test_the_vault_key_appears_in_no_output_log_or_file_outside_the_vault(box): + path = box.write("notes.txt", NOTES) + outputs = [] + for call in (lambda: box.hook({"hook_event_name": "SessionStart", "source": "startup"}), + lambda: box.pre("Read", {"file_path": str(path)}), + lambda: box.post("Bash", {"command": "x"}, recorded.bash(stdout=NOTES)), + lambda: box.pre("Bash", {"command": "echo [[EMAIL_ABC123]]"}), + lambda: box.prompt(f"mail {EMAIL}")): + _, result = call() + outputs.append(result.stdout + result.stderr) + for name in ("status", "doctor"): + result = box.run(name) + outputs.append(result.stdout + result.stderr) + everything = b"\n".join(outputs) + for path in list(box.data.rglob("*")) + list(box.project.rglob("*")) + list(box.home.rglob("*")): + if path.is_file(): + everything += path.read_bytes() + for form in key_forms(box): + assert form not in everything + assert_no_sentinel(box.visible_files(), "in a file outside the vault") + + +def test_the_engine_never_handles_the_key_itself(): + """The key goes from the key store (or the key file) into core's native code. The Python engine + never passes one in, so it cannot end up in a Python traceback, an argument list or the environment.""" + import re + source = (ROOT / "engine" / "datafog_guard" / "store.py").read_text() + calls = re.findall(r"ApplicationVault\.open\(([^)]*)\)", source) + assert len(calls) == 1 and "key=" not in calls[0].replace("allow_file_key=", "") + uses = [line.strip() for line in source.splitlines() if "KEY_FILE" in line] + assert len(uses) == 2 and uses[0].startswith("ENVELOPE, LOCK_FILE, KEY_FILE, INDEX_FILE =") \ + and uses[1].startswith("for name in (ENVELOPE, KEY_FILE, INDEX_FILE"), "the key file is only ever deleted (purge)" + + +def test_no_value_or_key_in_argument_lists_or_environments_of_engine_processes(box): + """While a hook process works on text full of values, its command line and environment hold none.""" + if not os.path.isdir("/proc/self"): + pytest.skip("needs /proc") + box.open_vault().tokenize(NOTES) + code = ("import json, os, sys\n" + "from datafog_guard import hook\n" + "import datafog_guard.vault as vault\n" + "real = vault.Vault._tokenize\n" + "def spy(self, texts, limits):\n" + " out = real(self, texts, limits)\n" + " seen = open('/proc/self/cmdline', 'rb').read() + open('/proc/self/environ', 'rb').read()\n" + " open(os.environ['SPY_OUT'], 'wb').write(seen)\n" + " return out\n" + "vault.Vault._tokenize = spy\n" + "sys.exit(hook.main())\n") + spy = box.tmp / "spy.bin" + payload = json.dumps({"hook_event_name": "PostToolUse", "tool_name": "Bash", "tool_input": {"command": "x"}, + "tool_response": recorded.bash(stdout=NOTES + "new.synthetic@example.com\n")}) + result = subprocess.run([sys.executable, "-c", code], input=payload.encode(), capture_output=True, + env=box.env(SPY_OUT=str(spy)), cwd=box.project) + assert result.returncode == 0 and b"[[EMAIL_" in result.stdout + seen = spy.read_bytes() + for value in (*SENTINELS, "new.synthetic@example.com"): + assert value.encode() not in seen + for form in key_forms(box): + assert form not in seen + + +def test_no_temporary_file_outside_the_vault_and_data_directories(box): + scratch = box.tmp / "scratch" + scratch.mkdir() + path = box.write("notes.txt", NOTES) + for call in (lambda: box.pre("Read", {"file_path": str(path)}, TMPDIR=str(scratch)), + lambda: box.post("Bash", {"command": "x"}, recorded.bash(stdout=NOTES), TMPDIR=str(scratch)), + lambda: box.pre("Write", {"file_path": str(box.project / "o.txt"), "content": "x"}, TMPDIR=str(scratch))): + call() + assert list(scratch.iterdir()) == [], "the engine and core's vault write nothing to the temp dir" + for item in box.vault.iterdir(): + assert item.name in ("workspace.enc", "workspace.key", "workspace.lock", "markers.index", "bash-restore.key") + + +def test_error_messages_and_codes_never_carry_a_value_a_key_or_cores_own_text(box): + from datafog_guard import store + for code, (kind, message) in store._MESSAGES.items(): + error = store._translate(type("E", (Exception,), {"code": code})()) + assert isinstance(error, kind) and error.user_message == message + assert error.code.replace("_", "").isalnum() + odd = store._translate(type("E", (Exception,), {"code": f"weird {EMAIL} "})(f"detail {EMAIL}")) + assert EMAIL not in odd.code + odd.user_message and "@" not in odd.code + + +# -- an unsupported machine: one message, everywhere, and nothing runs unprotected ------------ +def test_the_message_is_the_same_in_the_shell_and_in_the_engine(): + bootstrap = (ROOT / "scripts" / "bootstrap.sh").read_text() + assert f"UNSUPPORTED='{UNSUPPORTED}'" in bootstrap + assert "'" not in UNSUPPORTED and '"' not in UNSUPPORTED and "\\" not in UNSUPPORTED, "safe inside the shell's JSON line" + assert platform_problem() is None, "the suite runs on a supported machine" + readme = (ROOT / "README.md").read_text() + assert "macOS on Apple Silicon" in readme and "glibc 2.38" in readme + + +@pytest.fixture +def other_machine(box): + """A PATH in which `uname` reports a processor the plugin has no vault library for.""" + fake = box.tmp / "fakebin" + fake.mkdir() + (fake / "uname").write_text('#!/bin/sh\ncase "$1" in -s) echo Linux ;; -m) echo riscv64 ;; *) echo Linux ;; esac\n') + (fake / "uname").chmod(0o755) + return {"PATH": f"{fake}{os.pathsep}{os.environ['PATH']}", "HOME": str(box.tmp)} + + +def test_bootstrap_stops_before_installing_anything(box, other_machine): + launcher = ["sh", str(ROOT / "scripts" / "datafog-guard"), "--data-dir", str(box.data)] + result = subprocess.run([*launcher, "bootstrap"], capture_output=True, text=True, env=other_machine, timeout=60) + assert result.returncode == 3 and result.stdout.strip() == UNSUPPORTED + assert not (box.data / "venv").exists() + + +def test_session_start_and_every_hook_say_so_and_block(box, other_machine): + launcher = ["sh", str(ROOT / "scripts" / "datafog-guard"), "--data-dir", str(box.data)] + start = subprocess.run([*launcher, "session-start"], input='{"hook_event_name": "SessionStart"}', + capture_output=True, text=True, env=other_machine, timeout=60) + assert json.loads(start.stdout) == {"systemMessage": UNSUPPORTED} + for event in ("PreToolUse", "PostToolUse", "UserPromptSubmit"): + payload = json.dumps({"hook_event_name": event, "tool_name": "Read", "tool_input": {"file_path": "/x"}}) + result = subprocess.run([*launcher, "hook"], input=payload, capture_output=True, text=True, + env=other_machine, timeout=60) + assert result.returncode == 2 and result.stdout == "", "exit 2: Claude Code blocks the call" + assert result.stderr.strip() == UNSUPPORTED + for name in ("status", "doctor", "run"): + result = subprocess.run([*launcher, name, "echo hi"], capture_output=True, text=True, env=other_machine, timeout=60) + assert result.returncode == 2 and result.stderr.strip() == UNSUPPORTED and result.stdout == "" + + +@pytest.mark.parametrize("glibc, supported", [("glibc 2.38", True), ("glibc 2.39", True), ("glibc 3.0", True), + ("glibc 2.37", False), ("glibc 2.28", False), ("", False), + ("musl 1.2", False)]) +def test_bootstrap_checks_the_c_library_on_linux(box, glibc, supported): + fake = box.tmp / "fakebin" + fake.mkdir() + (fake / "uname").write_text('#!/bin/sh\ncase "$1" in -m) echo x86_64 ;; *) echo Linux ;; esac\n') + (fake / "getconf").write_text(f'#!/bin/sh\n[ -n "{glibc}" ] || exit 1\necho "{glibc}"\n') + for name in ("uname", "getconf"): + (fake / name).chmod(0o755) + sh = shutil.which("sh") + result = subprocess.run([sh, str(ROOT / "scripts" / "bootstrap.sh"), "--platform"], capture_output=True, text=True, + env={"PATH": f"{fake}{os.pathsep}/usr/bin:/bin"}) + assert (result.returncode == 0) is supported + assert result.stdout.strip() == ("" if supported else UNSUPPORTED) + + +def test_engine_on_a_machine_without_the_vault_library_gives_the_same_message(box): + """The environment exists but the vault library does not load and the platform is not supported + (for example a data directory copied from another machine).""" + from test_fail_closed import break_unsupported_machine + break_unsupported_machine(box) + out, _ = box.pre("Read", {"file_path": "/x"}) + reason = out["hookSpecificOutput"]["permissionDecisionReason"] + assert out["hookSpecificOutput"]["permissionDecision"] == "deny" and UNSUPPORTED in reason + start, _ = box.hook({"hook_event_name": "SessionStart", "source": "startup"}) + assert UNSUPPORTED in start["systemMessage"] and "NOT PROTECTING" in start["systemMessage"] + assert UNSUPPORTED in box.run("status").stdout.decode() + doctor = box.run("doctor") + assert doctor.returncode == 1 and UNSUPPORTED in doctor.stdout.decode() and "[FAIL] supported machine" in doctor.stdout.decode()